CombinedText stringlengths 4 3.42M |
|---|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkPlotParallelCoordinates.cxx
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.
=========================================================================*/
#include "vtkPlotParallelCoordinates.h"
#include "vtkChartParallelCoordinates.h"
#include "vtkContext2D.h"
#include "vtkAxis.h"
#include "vtkPen.h"
#include "vtkFloatArray.h"
#include "vtkDoubleArray.h"
#include "vtkVector.h"
#include "vtkTransform2D.h"
#include "vtkContextDevice2D.h"
#include "vtkContextMapper2D.h"
#include "vtkPoints2D.h"
#include "vtkTable.h"
#include "vtkDataArray.h"
#include "vtkIdTypeArray.h"
#include "vtkStringArray.h"
#include "vtkTimeStamp.h"
#include "vtkInformation.h"
#include "vtkSmartPointer.h"
// Need to turn some arrays of strings into categories
#include "vtkStringToCategory.h"
#include "vtkObjectFactory.h"
#include "vtkstd/vector"
#include "vtkstd/algorithm"
class vtkPlotParallelCoordinates::Private :
public vtkstd::vector< vtkstd::vector<float> >
{
public:
Private()
{
this->SelectionInitialized = false;
}
vtkstd::vector<float> AxisPos;
bool SelectionInitialized;
};
//-----------------------------------------------------------------------------
vtkStandardNewMacro(vtkPlotParallelCoordinates);
//-----------------------------------------------------------------------------
vtkPlotParallelCoordinates::vtkPlotParallelCoordinates()
{
this->Points = NULL;
this->Storage = new vtkPlotParallelCoordinates::Private;
this->Pen->SetColor(0, 0, 0, 25);
}
//-----------------------------------------------------------------------------
vtkPlotParallelCoordinates::~vtkPlotParallelCoordinates()
{
if (this->Points)
{
this->Points->Delete();
this->Points = NULL;
}
delete this->Storage;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::Update()
{
if (!this->Visible)
{
return;
}
// Check if we have an input
vtkTable *table = this->Data->GetInput();
if (!table)
{
vtkDebugMacro(<< "Update event called with no input table set.");
return;
}
this->UpdateTableCache(table);
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::Paint(vtkContext2D *painter)
{
// This is where everything should be drawn, or dispatched to other methods.
vtkDebugMacro(<< "Paint event called in vtkPlotParallelCoordinates.");
if (!this->Visible)
{
return false;
}
// Now to plot the points
if (this->Points)
{
painter->ApplyPen(this->Pen);
painter->DrawPoly(this->Points);
painter->GetPen()->SetLineType(vtkPen::SOLID_LINE);
}
painter->ApplyPen(this->Pen);
if (this->Storage->size() == 0)
{
return false;
}
size_t cols = this->Storage->size();
size_t rows = this->Storage->at(0).size();
vtkVector2f* line = new vtkVector2f[cols];
// Update the axis positions
vtkChartParallelCoordinates *parent =
vtkChartParallelCoordinates::SafeDownCast(this->Parent);
for (size_t i = 0; i < cols; ++i)
{
this->Storage->AxisPos[i] = parent->GetAxis(int(i)) ?
parent->GetAxis(int(i))->GetPoint1()[0] :
0;
}
vtkIdType selection = 0;
vtkIdType id = 0;
vtkIdType selectionSize = 0;
if (this->Selection)
{
selectionSize = this->Selection->GetNumberOfTuples();
if (selectionSize)
{
this->Selection->GetTupleValue(selection, &id);
}
}
// Draw all of the lines
painter->ApplyPen(this->Pen);
for (size_t i = 0; i < rows; ++i)
{
for (size_t j = 0; j < cols; ++j)
{
line[j].Set(this->Storage->AxisPos[j], (*this->Storage)[j][i]);
}
painter->DrawPoly(line[0].GetData(), static_cast<int>(cols));
}
// Now draw the selected lines
if (this->Selection)
{
painter->GetPen()->SetColor(255, 0, 0, 100);
for (vtkIdType i = 0; i < this->Selection->GetNumberOfTuples(); ++i)
{
for (size_t j = 0; j < cols; ++j)
{
this->Selection->GetTupleValue(i, &id);
line[j].Set(this->Storage->AxisPos[j], (*this->Storage)[j][id]);
}
painter->DrawPoly(line[0].GetData(), static_cast<int>(cols));
}
}
delete[] line;
return true;
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::PaintLegend(vtkContext2D *painter, float rect[4], int )
{
painter->ApplyPen(this->Pen);
painter->DrawLine(rect[0], rect[1]+0.5*rect[3],
rect[0]+rect[2], rect[1]+0.5*rect[3]);
return true;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::GetBounds(double *)
{
}
//-----------------------------------------------------------------------------
int vtkPlotParallelCoordinates::GetNearestPoint(const vtkVector2f& ,
const vtkVector2f& ,
vtkVector2f* )
{
return -1;
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::SetSelectionRange(int axis, float low,
float high)
{
if (!this->Selection)
{
return false;
}
if (this->Storage->SelectionInitialized)
{
// Further refine the selection that has already been made
vtkIdTypeArray *array = vtkIdTypeArray::New();
vtkstd::vector<float>& col = this->Storage->at(axis);
for (vtkIdType i = 0; i < this->Selection->GetNumberOfTuples(); ++i)
{
vtkIdType id = 0;
this->Selection->GetTupleValue(i, &id);
if (col[id] >= low && col[id] <= high)
{
// Remove this point - no longer selected
array->InsertNextValue(id);
}
}
this->Selection->DeepCopy(array);
array->Delete();
}
else
{
// First run - ensure the selection list is empty and build it up
vtkstd::vector<float>& col = this->Storage->at(axis);
for (size_t i = 0; i < col.size(); ++i)
{
if (col[i] >= low && col[i] <= high)
{
// Remove this point - no longer selected
this->Selection->InsertNextValue(i);
}
}
this->Storage->SelectionInitialized = true;
}
return true;
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::ResetSelectionRange()
{
this->Storage->SelectionInitialized = false;
if (this->Selection)
{
this->Selection->SetNumberOfTuples(0);
}
return true;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::SetInput(vtkTable* table)
{
if (table == this->Data->GetInput() && (!table ||
table->GetMTime() < this->BuildTime))
{
return;
}
this->vtkPlot::SetInput(table);
vtkChartParallelCoordinates *parent =
vtkChartParallelCoordinates::SafeDownCast(this->Parent);
if (parent && table)
{
// By default make the first 10 columns visible in a plot.
for (vtkIdType i = 0; i < table->GetNumberOfColumns() && i < 10; ++i)
{
parent->SetColumnVisibility(table->GetColumnName(i), true);
}
}
else if (parent)
{
// No table, therefore no visible columns
parent->GetVisibleColumns()->SetNumberOfTuples(0);
}
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::UpdateTableCache(vtkTable *table)
{
// Each axis is a column in our storage array, they are scaled from 0.0 to 1.0
vtkChartParallelCoordinates *parent =
vtkChartParallelCoordinates::SafeDownCast(this->Parent);
if (!parent || !table || table->GetNumberOfColumns() == 0)
{
return false;
}
vtkStringArray* cols = parent->GetVisibleColumns();
this->Storage->resize(cols->GetNumberOfTuples());
this->Storage->AxisPos.resize(cols->GetNumberOfTuples());
vtkIdType rows = table->GetNumberOfRows();
for (vtkIdType i = 0; i < cols->GetNumberOfTuples(); ++i)
{
vtkstd::vector<float>& col = this->Storage->at(i);
vtkAxis* axis = parent->GetAxis(i);
col.resize(rows);
vtkSmartPointer<vtkDataArray> data =
vtkDataArray::SafeDownCast(table->GetColumnByName(cols->GetValue(i)));
if (!data)
{
if (table->GetColumnByName(cols->GetValue(i))->IsA("vtkStringArray"))
{
// We have a different kind of column - attempt to make it into an enum
vtkStringToCategory* stoc = vtkStringToCategory::New();
stoc->SetInput(table);
stoc->SetInputArrayToProcess(0, 0, 0,
vtkDataObject::FIELD_ASSOCIATION_ROWS,
cols->GetValue(i));
stoc->SetCategoryArrayName("enumPC");
stoc->Update();
vtkTable* table2 = vtkTable::SafeDownCast(stoc->GetOutput());
vtkTable* stringTable = vtkTable::SafeDownCast(stoc->GetOutput(1));
if (table2)
{
data = vtkDataArray::SafeDownCast(table2->GetColumnByName("enumPC"));
}
if (stringTable && stringTable->GetColumnByName("Strings"))
{
vtkStringArray* strings =
vtkStringArray::SafeDownCast(stringTable->GetColumnByName("Strings"));
vtkSmartPointer<vtkDoubleArray> arr =
vtkSmartPointer<vtkDoubleArray>::New();
for (vtkIdType j = 0; j < strings->GetNumberOfTuples(); ++j)
{
arr->InsertNextValue(j);
}
// Now we need to set the range on the string axis
axis->SetTickLabels(strings);
axis->SetTickPositions(arr);
if (strings->GetNumberOfTuples() > 1)
{
axis->SetRange(0.0, strings->GetNumberOfTuples()-1);
}
else
{
axis->SetRange(-0.1, 0.1);
}
axis->Update();
}
stoc->Delete();
}
// If we still don't have a valid data array then skip this column.
if (!data)
{
continue;
}
}
// Also need the range from the appropriate axis, to normalize points
float min = axis->GetMinimum();
float max = axis->GetMaximum();
float scale = 1.0f / (max - min);
for (vtkIdType j = 0; j < rows; ++j)
{
col[j] = (data->GetTuple1(j)-min) * scale;
}
}
this->BuildTime.Modified();
return true;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
COMP: Include STL headers directly.
VTK policy has changed - migrate to use STL classes directly.
/*=========================================================================
Program: Visualization Toolkit
Module: vtkPlotParallelCoordinates.cxx
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.
=========================================================================*/
#include "vtkPlotParallelCoordinates.h"
#include "vtkChartParallelCoordinates.h"
#include "vtkContext2D.h"
#include "vtkAxis.h"
#include "vtkPen.h"
#include "vtkFloatArray.h"
#include "vtkDoubleArray.h"
#include "vtkVector.h"
#include "vtkTransform2D.h"
#include "vtkContextDevice2D.h"
#include "vtkContextMapper2D.h"
#include "vtkPoints2D.h"
#include "vtkTable.h"
#include "vtkDataArray.h"
#include "vtkIdTypeArray.h"
#include "vtkStringArray.h"
#include "vtkTimeStamp.h"
#include "vtkInformation.h"
#include "vtkSmartPointer.h"
// Need to turn some arrays of strings into categories
#include "vtkStringToCategory.h"
#include "vtkObjectFactory.h"
#include <vector>
#include <algorithm>
class vtkPlotParallelCoordinates::Private :
public std::vector< std::vector<float> >
{
public:
Private()
{
this->SelectionInitialized = false;
}
std::vector<float> AxisPos;
bool SelectionInitialized;
};
//-----------------------------------------------------------------------------
vtkStandardNewMacro(vtkPlotParallelCoordinates);
//-----------------------------------------------------------------------------
vtkPlotParallelCoordinates::vtkPlotParallelCoordinates()
{
this->Points = NULL;
this->Storage = new vtkPlotParallelCoordinates::Private;
this->Pen->SetColor(0, 0, 0, 25);
}
//-----------------------------------------------------------------------------
vtkPlotParallelCoordinates::~vtkPlotParallelCoordinates()
{
if (this->Points)
{
this->Points->Delete();
this->Points = NULL;
}
delete this->Storage;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::Update()
{
if (!this->Visible)
{
return;
}
// Check if we have an input
vtkTable *table = this->Data->GetInput();
if (!table)
{
vtkDebugMacro(<< "Update event called with no input table set.");
return;
}
this->UpdateTableCache(table);
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::Paint(vtkContext2D *painter)
{
// This is where everything should be drawn, or dispatched to other methods.
vtkDebugMacro(<< "Paint event called in vtkPlotParallelCoordinates.");
if (!this->Visible)
{
return false;
}
// Now to plot the points
if (this->Points)
{
painter->ApplyPen(this->Pen);
painter->DrawPoly(this->Points);
painter->GetPen()->SetLineType(vtkPen::SOLID_LINE);
}
painter->ApplyPen(this->Pen);
if (this->Storage->size() == 0)
{
return false;
}
size_t cols = this->Storage->size();
size_t rows = this->Storage->at(0).size();
vtkVector2f* line = new vtkVector2f[cols];
// Update the axis positions
vtkChartParallelCoordinates *parent =
vtkChartParallelCoordinates::SafeDownCast(this->Parent);
for (size_t i = 0; i < cols; ++i)
{
this->Storage->AxisPos[i] = parent->GetAxis(int(i)) ?
parent->GetAxis(int(i))->GetPoint1()[0] :
0;
}
vtkIdType selection = 0;
vtkIdType id = 0;
vtkIdType selectionSize = 0;
if (this->Selection)
{
selectionSize = this->Selection->GetNumberOfTuples();
if (selectionSize)
{
this->Selection->GetTupleValue(selection, &id);
}
}
// Draw all of the lines
painter->ApplyPen(this->Pen);
for (size_t i = 0; i < rows; ++i)
{
for (size_t j = 0; j < cols; ++j)
{
line[j].Set(this->Storage->AxisPos[j], (*this->Storage)[j][i]);
}
painter->DrawPoly(line[0].GetData(), static_cast<int>(cols));
}
// Now draw the selected lines
if (this->Selection)
{
painter->GetPen()->SetColor(255, 0, 0, 100);
for (vtkIdType i = 0; i < this->Selection->GetNumberOfTuples(); ++i)
{
for (size_t j = 0; j < cols; ++j)
{
this->Selection->GetTupleValue(i, &id);
line[j].Set(this->Storage->AxisPos[j], (*this->Storage)[j][id]);
}
painter->DrawPoly(line[0].GetData(), static_cast<int>(cols));
}
}
delete[] line;
return true;
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::PaintLegend(vtkContext2D *painter, float rect[4], int )
{
painter->ApplyPen(this->Pen);
painter->DrawLine(rect[0], rect[1]+0.5*rect[3],
rect[0]+rect[2], rect[1]+0.5*rect[3]);
return true;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::GetBounds(double *)
{
}
//-----------------------------------------------------------------------------
int vtkPlotParallelCoordinates::GetNearestPoint(const vtkVector2f& ,
const vtkVector2f& ,
vtkVector2f* )
{
return -1;
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::SetSelectionRange(int axis, float low,
float high)
{
if (!this->Selection)
{
return false;
}
if (this->Storage->SelectionInitialized)
{
// Further refine the selection that has already been made
vtkIdTypeArray *array = vtkIdTypeArray::New();
std::vector<float>& col = this->Storage->at(axis);
for (vtkIdType i = 0; i < this->Selection->GetNumberOfTuples(); ++i)
{
vtkIdType id = 0;
this->Selection->GetTupleValue(i, &id);
if (col[id] >= low && col[id] <= high)
{
// Remove this point - no longer selected
array->InsertNextValue(id);
}
}
this->Selection->DeepCopy(array);
array->Delete();
}
else
{
// First run - ensure the selection list is empty and build it up
std::vector<float>& col = this->Storage->at(axis);
for (size_t i = 0; i < col.size(); ++i)
{
if (col[i] >= low && col[i] <= high)
{
// Remove this point - no longer selected
this->Selection->InsertNextValue(i);
}
}
this->Storage->SelectionInitialized = true;
}
return true;
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::ResetSelectionRange()
{
this->Storage->SelectionInitialized = false;
if (this->Selection)
{
this->Selection->SetNumberOfTuples(0);
}
return true;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::SetInput(vtkTable* table)
{
if (table == this->Data->GetInput() && (!table ||
table->GetMTime() < this->BuildTime))
{
return;
}
this->vtkPlot::SetInput(table);
vtkChartParallelCoordinates *parent =
vtkChartParallelCoordinates::SafeDownCast(this->Parent);
if (parent && table)
{
// By default make the first 10 columns visible in a plot.
for (vtkIdType i = 0; i < table->GetNumberOfColumns() && i < 10; ++i)
{
parent->SetColumnVisibility(table->GetColumnName(i), true);
}
}
else if (parent)
{
// No table, therefore no visible columns
parent->GetVisibleColumns()->SetNumberOfTuples(0);
}
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::UpdateTableCache(vtkTable *table)
{
// Each axis is a column in our storage array, they are scaled from 0.0 to 1.0
vtkChartParallelCoordinates *parent =
vtkChartParallelCoordinates::SafeDownCast(this->Parent);
if (!parent || !table || table->GetNumberOfColumns() == 0)
{
return false;
}
vtkStringArray* cols = parent->GetVisibleColumns();
this->Storage->resize(cols->GetNumberOfTuples());
this->Storage->AxisPos.resize(cols->GetNumberOfTuples());
vtkIdType rows = table->GetNumberOfRows();
for (vtkIdType i = 0; i < cols->GetNumberOfTuples(); ++i)
{
std::vector<float>& col = this->Storage->at(i);
vtkAxis* axis = parent->GetAxis(i);
col.resize(rows);
vtkSmartPointer<vtkDataArray> data =
vtkDataArray::SafeDownCast(table->GetColumnByName(cols->GetValue(i)));
if (!data)
{
if (table->GetColumnByName(cols->GetValue(i))->IsA("vtkStringArray"))
{
// We have a different kind of column - attempt to make it into an enum
vtkStringToCategory* stoc = vtkStringToCategory::New();
stoc->SetInput(table);
stoc->SetInputArrayToProcess(0, 0, 0,
vtkDataObject::FIELD_ASSOCIATION_ROWS,
cols->GetValue(i));
stoc->SetCategoryArrayName("enumPC");
stoc->Update();
vtkTable* table2 = vtkTable::SafeDownCast(stoc->GetOutput());
vtkTable* stringTable = vtkTable::SafeDownCast(stoc->GetOutput(1));
if (table2)
{
data = vtkDataArray::SafeDownCast(table2->GetColumnByName("enumPC"));
}
if (stringTable && stringTable->GetColumnByName("Strings"))
{
vtkStringArray* strings =
vtkStringArray::SafeDownCast(stringTable->GetColumnByName("Strings"));
vtkSmartPointer<vtkDoubleArray> arr =
vtkSmartPointer<vtkDoubleArray>::New();
for (vtkIdType j = 0; j < strings->GetNumberOfTuples(); ++j)
{
arr->InsertNextValue(j);
}
// Now we need to set the range on the string axis
axis->SetTickLabels(strings);
axis->SetTickPositions(arr);
if (strings->GetNumberOfTuples() > 1)
{
axis->SetRange(0.0, strings->GetNumberOfTuples()-1);
}
else
{
axis->SetRange(-0.1, 0.1);
}
axis->Update();
}
stoc->Delete();
}
// If we still don't have a valid data array then skip this column.
if (!data)
{
continue;
}
}
// Also need the range from the appropriate axis, to normalize points
float min = axis->GetMinimum();
float max = axis->GetMaximum();
float scale = 1.0f / (max - min);
for (vtkIdType j = 0; j < rows; ++j)
{
col[j] = (data->GetTuple1(j)-min) * scale;
}
}
this->BuildTime.Modified();
return true;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
|
// Network.cpp
// Implements the classes used for the Network API
#include "Globals.h"
#include "Network.h"
#include <event2/event.h>
#include <event2/thread.h>
#include <event2/bufferevent.h>
#include <event2/dns.h>
#include <event2/listener.h>
#include <thread>
#include "Event.h"
#include "CriticalSection.h"
// fwd:
class cServerHandleImpl;
class cTCPLinkImpl;
typedef SharedPtr<cTCPLinkImpl> cTCPLinkImplPtr;
typedef std::vector<cTCPLinkImplPtr> cTCPLinkImplPtrs;
typedef SharedPtr<cServerHandleImpl> cServerHandleImplPtr;
typedef std::vector<cServerHandleImplPtr> cServerHandleImplPtrs;
////////////////////////////////////////////////////////////////////////////////
// Class definitions:
/** Holds information about an in-progress Hostname-to-IP lookup. */
class cHostnameLookup
{
/** The callbacks to call for resolved names / errors. */
cNetwork::cResolveNameCallbacksPtr m_Callbacks;
/** The hostname that was queried (needed for the callbacks). */
AString m_Hostname;
static void Callback(int a_ErrCode, struct evutil_addrinfo * a_Addr, void * a_Self);
public:
cHostnameLookup(const AString & a_Hostname, cNetwork::cResolveNameCallbacksPtr a_Callbacks);
};
typedef SharedPtr<cHostnameLookup> cHostnameLookupPtr;
typedef std::vector<cHostnameLookupPtr> cHostnameLookupPtrs;
/** Holds information about an in-progress IP-to-Hostname lookup. */
class cIPLookup
{
/** The callbacks to call for resolved names / errors. */
cNetwork::cResolveNameCallbacksPtr m_Callbacks;
/** The IP that was queried (needed for the callbacks). */
AString m_IP;
static void Callback(int a_Result, char a_Type, int a_Count, int a_Ttl, void * a_Addresses, void * a_Self);
public:
cIPLookup(const AString & a_IP, cNetwork::cResolveNameCallbacksPtr a_Callbacks);
};
typedef SharedPtr<cIPLookup> cIPLookupPtr;
typedef std::vector<cIPLookupPtr> cIPLookupPtrs;
/** Implements the cTCPLink details so that it can represent the single connection between two endpoints. */
class cTCPLinkImpl:
public cTCPLink
{
typedef cTCPLink super;
public:
/** Creates a new link based on the given socket.
Used for connections accepted in a server using cNetwork::Listen().
a_Address and a_AddrLen describe the remote peer that has connected. */
cTCPLinkImpl(evutil_socket_t a_Socket, cCallbacksPtr a_LinkCallbacks, cServerHandleImpl * a_Server, const sockaddr * a_Address, int a_AddrLen);
/** Destroys the LibEvent handle representing the link. */
~cTCPLinkImpl();
/** Queues a connection request to the specified host.
a_ConnectCallbacks must be valid.
Returns a link that has the connection request queued, or NULL for failure. */
static cTCPLinkImplPtr Connect(const AString & a_Host, UInt16 a_Port, cTCPLink::cCallbacksPtr a_LinkCallbacks, cNetwork::cConnectCallbacksPtr a_ConnectCallbacks);
// cTCPLink overrides:
virtual bool Send(const void * a_Data, size_t a_Length) override;
virtual AString GetLocalIP(void) const override { return m_LocalIP; }
virtual UInt16 GetLocalPort(void) const override { return m_LocalPort; }
virtual AString GetRemoteIP(void) const override { return m_RemoteIP; }
virtual UInt16 GetRemotePort(void) const override { return m_RemotePort; }
virtual void Shutdown(void) override;
virtual void Close(void) override;
protected:
/** Callbacks to call when the connection is established.
May be NULL if not used. Only used for outgoing connections (cNetwork::Connect()). */
cNetwork::cConnectCallbacksPtr m_ConnectCallbacks;
/** The LibEvent handle representing this connection. */
bufferevent * m_BufferEvent;
/** The server handle that has created this link.
Only valid for incoming connections, NULL for outgoing connections. */
cServerHandleImpl * m_Server;
/** The IP address of the local endpoint. Valid only after the socket has been connected. */
AString m_LocalIP;
/** The port of the local endpoint. Valid only after the socket has been connected. */
UInt16 m_LocalPort;
/** The IP address of the remote endpoint. Valid only after the socket has been connected. */
AString m_RemoteIP;
/** The port of the remote endpoint. Valid only after the socket has been connected. */
UInt16 m_RemotePort;
/** Creates a new link to be queued to connect to a specified host:port.
Used for outgoing connections created using cNetwork::Connect().
To be used only by the Connect() factory function. */
cTCPLinkImpl(const cCallbacksPtr a_LinkCallbacks);
/** Callback that LibEvent calls when there's data available from the remote peer. */
static void ReadCallback(bufferevent * a_BufferEvent, void * a_Self);
/** Callback that LibEvent calls when there's a non-data-related event on the socket. */
static void EventCallback(bufferevent * a_BufferEvent, short a_What, void * a_Self);
/** Sets a_IP and a_Port to values read from a_Address, based on the correct address family. */
static void UpdateAddress(const sockaddr * a_Address, int a_AddrLen, AString & a_IP, UInt16 & a_Port);
/** Updates m_LocalIP and m_LocalPort based on the metadata read from the socket. */
void UpdateLocalAddress(void);
/** Updates m_RemoteIP and m_RemotePort based on the metadata read from the socket. */
void UpdateRemoteAddress(void);
};
/** Implements the cServerHandle details so that it can represent a real server socket, with a list of clients. */
class cServerHandleImpl:
public cServerHandle
{
typedef cServerHandle super;
friend class cTCPLinkImpl;
public:
/** Closes the server, dropping all the connections. */
~cServerHandleImpl();
/** Creates a new server instance listening on the specified port.
Both IPv4 and IPv6 interfaces are used, if possible.
Always returns a server instance; in the event of a failure, the instance holds the error details. Use IsListening() to query success. */
static cServerHandleImplPtr Listen(
UInt16 a_Port,
cNetwork::cListenCallbacksPtr a_ListenCallbacks,
cTCPLink::cCallbacksPtr a_LinkCallbacks
);
// cServerHandle overrides:
virtual void Close(void) override;
virtual bool IsListening(void) const override { return m_IsListening; }
protected:
/** The callbacks used to notify about incoming connections. */
cNetwork::cListenCallbacksPtr m_ListenCallbacks;
/** The callbacks used to create new cTCPLink instances for incoming connections. */
cTCPLink::cCallbacksPtr m_LinkCallbacks;
/** The LibEvent handle representing the main listening socket. */
evconnlistener * m_ConnListener;
/** The LibEvent handle representing the secondary listening socket (only when side-by-side listening is needed, such as WinXP). */
evconnlistener * m_SecondaryConnListener;
/** Set to true when the server is initialized successfully and is listening for incoming connections. */
bool m_IsListening;
/** Container for all currently active connections on this server. */
cTCPLinkImplPtrs m_Connections;
/** Mutex protecting m_Connections againt multithreaded access. */
cCriticalSection m_CS;
/** Contains the error code for the failure to listen. Only valid for non-listening instances. */
int m_ErrorCode;
/** Contains the error message for the failure to listen. Only valid for non-listening instances. */
AString m_ErrorMsg;
/** Creates a new instance with the specified callbacks.
Initializes the internals, but doesn't start listening yet. */
cServerHandleImpl(
cNetwork::cListenCallbacksPtr a_ListenCallbacks,
cTCPLink::cCallbacksPtr a_LinkCallbacks
);
/** Starts listening on the specified port.
Returns true if successful, false on failure. On failure, sets m_ErrorCode and m_ErrorMsg. */
bool Listen(UInt16 a_Port);
/** The callback called by LibEvent upon incoming connection. */
static void Callback(evconnlistener * a_Listener, evutil_socket_t a_Socket, sockaddr * a_Addr, int a_Len, void * a_Self);
/** Removes the specified link from m_Connections.
Called by cTCPLinkImpl when the link is terminated. */
void RemoveLink(const cTCPLinkImpl * a_Link);
};
class cNetworkSingleton
{
friend class cHostnameLookup; // Needs access to m_DNSBase
friend class cIPLookup; // Needs access to m_DNSBase
friend class cTCPLinkImpl; // Needs access to m_EventBase and m_DNSBase
friend class cServerHandleImpl; // Needs access to m_EventBase
public:
/** Returns the singleton instance of this class */
static cNetworkSingleton & Get(void);
// The following functions are implementations for the cNetwork class
/** Queues a DNS query to resolve the specified hostname to IP address.
Calls one of the callbacks when the resolving succeeds, or when it fails.
Returns true if queueing was successful, false if not.
Note that the return value doesn't report the success of the actual lookup; the lookup happens asynchronously on the background. */
bool HostnameToIP(
const AString & a_Hostname,
cNetwork::cResolveNameCallbacksPtr a_Callbacks
);
/** Queues a DNS query to resolve the specified IP address to a hostname.
Calls one of the callbacks when the resolving succeeds, or when it fails.
Returns true if queueing was successful, false if not.
Note that the return value doesn't report the success of the actual lookup; the lookup happens asynchronously on the background. */
bool IPToHostName(
const AString & a_IP,
cNetwork::cResolveNameCallbacksPtr a_Callbacks
);
protected:
/** The main LibEvent container for driving the event loop. */
event_base * m_EventBase;
/** The LibEvent handle for doing DNS lookups. */
evdns_base * m_DNSBase;
/** Container for all client connections, including ones with pending-connect. */
cTCPLinkImplPtrs m_Connections;
/** Container for all servers that are currently active. */
cServerHandleImplPtrs m_Servers;
/** Container for all pending hostname lookups. */
cHostnameLookupPtrs m_HostnameLookups;
/** Container for all pending IP lookups. */
cIPLookupPtrs m_IPLookups;
/** Mutex protecting all containers against multithreaded access. */
cCriticalSection m_CS;
/** Initializes the LibEvent internals. */
cNetworkSingleton(void);
/** Converts LibEvent-generated log events into log messages in MCS log. */
static void LogCallback(int a_Severity, const char * a_Msg);
/** Implements the thread that runs LibEvent's event dispatcher loop. */
static void RunEventLoop(cNetworkSingleton * a_Self);
/** Removes the specified hostname lookup from m_HostnameLookups.
Used by the underlying lookup implementation when the lookup is finished. */
void RemoveHostnameLookup(const cHostnameLookup * a_HostnameLookup);
/** Removes the specified IP lookup from m_IPLookups.
Used by the underlying lookup implementation when the lookup is finished. */
void RemoveIPLookup(const cIPLookup * a_IPLookup);
/** Adds the specified link to m_Connections.
Used by the underlying link implementation when a new link is created. */
void AddLink(cTCPLinkImplPtr a_Link);
/** Removes the specified link from m_Connections.
Used by the underlying link implementation when the link is closed / errored. */
void RemoveLink(const cTCPLinkImpl * a_Link);
/** Adds the specified link to m_Servers.
Used by the underlying server handle implementation when a new listening server is created.
Only servers that succeed in listening are added. */
void AddServer(cServerHandleImplPtr a_Server);
/** Removes the specified server from m_Servers.
Used by the underlying server handle implementation when the server is closed. */
void RemoveServer(const cServerHandleImpl * a_Server);
};
////////////////////////////////////////////////////////////////////////////////
// Globals:
bool IsValidSocket(evutil_socket_t a_Socket)
{
#ifdef _WIN32
return (a_Socket != INVALID_SOCKET);
#else // _WIN32
return (a_Socket >= 0);
#endif // else _WIN32
}
////////////////////////////////////////////////////////////////////////////////
// cHostnameLookup:
cHostnameLookup::cHostnameLookup(const AString & a_Hostname, cNetwork::cResolveNameCallbacksPtr a_Callbacks):
m_Callbacks(a_Callbacks),
m_Hostname(a_Hostname)
{
evutil_addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_protocol = IPPROTO_TCP;
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_UNSPEC;
hints.ai_flags = EVUTIL_AI_CANONNAME;
evdns_getaddrinfo(cNetworkSingleton::Get().m_DNSBase, a_Hostname.c_str(), nullptr, &hints, Callback, this);
}
void cHostnameLookup::Callback(int a_ErrCode, evutil_addrinfo * a_Addr, void * a_Self)
{
// Get the Self class:
cHostnameLookup * Self = reinterpret_cast<cHostnameLookup *>(a_Self);
ASSERT(Self != nullptr);
// If an error has occurred, notify the error callback:
if (a_ErrCode != 0)
{
Self->m_Callbacks->OnError(a_ErrCode);
cNetworkSingleton::Get().RemoveHostnameLookup(Self);
return;
}
// Call the success handler for each entry received:
bool HasResolved = false;
evutil_addrinfo * OrigAddr = a_Addr;
for (;a_Addr != nullptr; a_Addr = a_Addr->ai_next)
{
char IP[128];
switch (a_Addr->ai_family)
{
case AF_INET: // IPv4
{
sockaddr_in * sin = reinterpret_cast<sockaddr_in *>(a_Addr->ai_addr);
evutil_inet_ntop(AF_INET, &(sin->sin_addr), IP, sizeof(IP));
break;
}
case AF_INET6: // IPv6
{
sockaddr_in6 * sin = reinterpret_cast<sockaddr_in6 *>(a_Addr->ai_addr);
evutil_inet_ntop(AF_INET6, &(sin->sin6_addr), IP, sizeof(IP));
break;
}
default:
{
// Unknown address family, handle as if this entry wasn't received
continue; // for (a_Addr)
}
}
Self->m_Callbacks->OnNameResolved(Self->m_Hostname, IP);
HasResolved = true;
} // for (a_Addr)
// If only unsupported families were reported, call the Error handler:
if (!HasResolved)
{
Self->m_Callbacks->OnError(1);
}
else
{
Self->m_Callbacks->OnFinished();
}
evutil_freeaddrinfo(OrigAddr);
cNetworkSingleton::Get().RemoveHostnameLookup(Self);
}
////////////////////////////////////////////////////////////////////////////////
// cIPLookup:
cIPLookup::cIPLookup(const AString & a_IP, cNetwork::cResolveNameCallbacksPtr a_Callbacks):
m_Callbacks(a_Callbacks),
m_IP(a_IP)
{
sockaddr_storage sa;
int salen = static_cast<int>(sizeof(sa));
evutil_parse_sockaddr_port(a_IP.c_str(), reinterpret_cast<sockaddr *>(&sa), &salen);
switch (sa.ss_family)
{
case AF_INET:
{
sockaddr_in * sa4 = reinterpret_cast<sockaddr_in *>(&sa);
evdns_base_resolve_reverse(cNetworkSingleton::Get().m_DNSBase, &(sa4->sin_addr), 0, Callback, this);
break;
}
case AF_INET6:
{
sockaddr_in6 * sa6 = reinterpret_cast<sockaddr_in6 *>(&sa);
evdns_base_resolve_reverse_ipv6(cNetworkSingleton::Get().m_DNSBase, &(sa6->sin6_addr), 0, Callback, this);
break;
}
default:
{
LOGWARNING("%s: Unknown address family: %d", __FUNCTION__, sa.ss_family);
ASSERT(!"Unknown address family");
break;
}
} // switch (address family)
}
void cIPLookup::Callback(int a_Result, char a_Type, int a_Count, int a_Ttl, void * a_Addresses, void * a_Self)
{
// Get the Self class:
cIPLookup * Self = reinterpret_cast<cIPLookup *>(a_Self);
ASSERT(Self != nullptr);
// Call the proper callback based on the event received:
if ((a_Result != 0) || (a_Addresses == nullptr))
{
// An error has occurred, notify the error callback:
Self->m_Callbacks->OnError(a_Result);
}
else
{
// Call the success handler:
Self->m_Callbacks->OnNameResolved(*(reinterpret_cast<char **>(a_Addresses)), Self->m_IP);
Self->m_Callbacks->OnFinished();
}
cNetworkSingleton::Get().RemoveIPLookup(Self);
}
////////////////////////////////////////////////////////////////////////////////
// cTCPLinkImpl:
cTCPLinkImpl::cTCPLinkImpl(cTCPLink::cCallbacksPtr a_LinkCallbacks):
super(a_LinkCallbacks),
m_BufferEvent(bufferevent_socket_new(cNetworkSingleton::Get().m_EventBase, -1, BEV_OPT_CLOSE_ON_FREE)),
m_Server(nullptr)
{
// Create the LibEvent handle, but don't assign a socket to it yet (will be assigned within Connect() method):
bufferevent_setcb(m_BufferEvent, ReadCallback, nullptr, EventCallback, this);
bufferevent_enable(m_BufferEvent, EV_READ | EV_WRITE);
}
cTCPLinkImpl::cTCPLinkImpl(evutil_socket_t a_Socket, cTCPLink::cCallbacksPtr a_LinkCallbacks, cServerHandleImpl * a_Server, const sockaddr * a_Address, int a_AddrLen):
super(a_LinkCallbacks),
m_BufferEvent(bufferevent_socket_new(cNetworkSingleton::Get().m_EventBase, a_Socket, BEV_OPT_CLOSE_ON_FREE)),
m_Server(a_Server)
{
// Update the endpoint addresses:
UpdateLocalAddress();
UpdateAddress(a_Address, a_AddrLen, m_RemoteIP, m_RemotePort);
// Create the LibEvent handle:
bufferevent_setcb(m_BufferEvent, ReadCallback, nullptr, EventCallback, this);
bufferevent_enable(m_BufferEvent, EV_READ | EV_WRITE);
}
cTCPLinkImpl::~cTCPLinkImpl()
{
bufferevent_free(m_BufferEvent);
}
cTCPLinkImplPtr cTCPLinkImpl::Connect(const AString & a_Host, UInt16 a_Port, cTCPLink::cCallbacksPtr a_LinkCallbacks, cNetwork::cConnectCallbacksPtr a_ConnectCallbacks)
{
ASSERT(a_LinkCallbacks != nullptr);
ASSERT(a_ConnectCallbacks != nullptr);
// Create a new link:
cTCPLinkImplPtr res{new cTCPLinkImpl(a_LinkCallbacks)}; // Cannot use std::make_shared here, constructor is not accessible
res->m_ConnectCallbacks = a_ConnectCallbacks;
cNetworkSingleton::Get().AddLink(res);
// If a_Host is an IP address, schedule a connection immediately:
sockaddr_storage sa;
int salen = static_cast<int>(sizeof(sa));
if (evutil_parse_sockaddr_port(a_Host.c_str(), reinterpret_cast<sockaddr *>(&sa), &salen) == 0)
{
// Insert the correct port:
if (sa.ss_family == AF_INET6)
{
reinterpret_cast<sockaddr_in6 *>(&sa)->sin6_port = htons(a_Port);
}
else
{
reinterpret_cast<sockaddr_in *>(&sa)->sin_port = htons(a_Port);
}
// Queue the connect request:
if (bufferevent_socket_connect(res->m_BufferEvent, reinterpret_cast<sockaddr *>(&sa), salen) == 0)
{
// Success
return res;
}
// Failure
cNetworkSingleton::Get().RemoveLink(res.get());
return nullptr;
}
// a_Host is a hostname, connect after a lookup:
if (bufferevent_socket_connect_hostname(res->m_BufferEvent, cNetworkSingleton::Get().m_DNSBase, AF_UNSPEC, a_Host.c_str(), a_Port) == 0)
{
// Success
return res;
}
// Failure
cNetworkSingleton::Get().RemoveLink(res.get());
return nullptr;
}
bool cTCPLinkImpl::Send(const void * a_Data, size_t a_Length)
{
return (bufferevent_write(m_BufferEvent, a_Data, a_Length) == 0);
}
void cTCPLinkImpl::Shutdown(void)
{
#ifdef _WIN32
shutdown(bufferevent_getfd(m_BufferEvent), SD_SEND);
#else
shutdown(bufferevent_getfd(m_BufferEvent), SHUT_WR);
#endif
bufferevent_disable(m_BufferEvent, EV_WRITE);
}
void cTCPLinkImpl::Close(void)
{
// Disable all events on the socket, but keep it alive:
bufferevent_disable(m_BufferEvent, EV_READ | EV_WRITE);
if (m_Server == nullptr)
{
cNetworkSingleton::Get().RemoveLink(this);
}
else
{
m_Server->RemoveLink(this);
}
}
void cTCPLinkImpl::ReadCallback(bufferevent * a_BufferEvent, void * a_Self)
{
ASSERT(a_Self != nullptr);
cTCPLinkImpl * Self = static_cast<cTCPLinkImpl *>(a_Self);
ASSERT(Self->m_Callbacks != nullptr);
// Read all the incoming data, in 1024-byte chunks:
char data[1024];
size_t length;
while ((length = bufferevent_read(a_BufferEvent, data, sizeof(data))) > 0)
{
Self->m_Callbacks->OnReceivedData(*Self, data, length);
}
}
void cTCPLinkImpl::EventCallback(bufferevent * a_BufferEvent, short a_What, void * a_Self)
{
ASSERT(a_Self != nullptr);
cTCPLinkImpl * Self = static_cast<cTCPLinkImpl *>(a_Self);
// If an error is reported, call the error callback:
if (a_What & BEV_EVENT_ERROR)
{
// Choose the proper callback to call based on whether we were waiting for connection or not:
if (Self->m_ConnectCallbacks != nullptr)
{
Self->m_ConnectCallbacks->OnError(EVUTIL_SOCKET_ERROR());
}
else
{
Self->m_Callbacks->OnError(*Self, EVUTIL_SOCKET_ERROR());
if (Self->m_Server == nullptr)
{
cNetworkSingleton::Get().RemoveLink(Self);
}
else
{
Self->m_Server->RemoveLink(Self);
}
}
return;
}
// Pending connection succeeded, call the connection callback:
if (a_What & BEV_EVENT_CONNECTED)
{
if (Self->m_ConnectCallbacks != nullptr)
{
Self->m_ConnectCallbacks->OnSuccess(*Self);
// Reset the connect callbacks so that later errors get reported through the link callbacks:
Self->m_ConnectCallbacks.reset();
return;
}
Self->UpdateLocalAddress();
Self->UpdateRemoteAddress();
}
// If the connection has been closed, call the link callback and remove the connection:
if (a_What & BEV_EVENT_EOF)
{
Self->m_Callbacks->OnRemoteClosed(*Self);
if (Self->m_Server != nullptr)
{
Self->m_Server->RemoveLink(Self);
}
else
{
cNetworkSingleton::Get().RemoveLink(Self);
}
return;
}
// Unknown event, report it:
LOGWARNING("cTCPLinkImpl: Unhandled LibEvent event %d (0x%x)", a_What, a_What);
ASSERT(!"cTCPLinkImpl: Unhandled LibEvent event");
}
void cTCPLinkImpl::UpdateAddress(const sockaddr * a_Address, int a_AddrLen, AString & a_IP, UInt16 & a_Port)
{
// Based on the family specified in the address, use the correct datastructure to convert to IP string:
char IP[128];
switch (a_Address->sa_family)
{
case AF_INET: // IPv4:
{
const sockaddr_in * sin = reinterpret_cast<const sockaddr_in *>(a_Address);
evutil_inet_ntop(AF_INET, &(sin->sin_addr), IP, sizeof(IP));
a_Port = ntohs(sin->sin_port);
break;
}
case AF_INET6: // IPv6
{
const sockaddr_in6 * sin = reinterpret_cast<const sockaddr_in6 *>(a_Address);
evutil_inet_ntop(AF_INET6, &(sin->sin6_addr), IP, sizeof(IP));
a_Port = ntohs(sin->sin6_port);
break;
}
default:
{
LOGWARNING("%s: Unknown socket address family: %d", __FUNCTION__, a_Address->sa_family);
ASSERT(!"Unknown socket address family");
break;
}
}
a_IP.assign(IP);
}
void cTCPLinkImpl::UpdateLocalAddress(void)
{
sockaddr_storage sa;
socklen_t salen = static_cast<socklen_t>(sizeof(sa));
getsockname(bufferevent_getfd(m_BufferEvent), reinterpret_cast<sockaddr *>(&sa), &salen);
UpdateAddress(reinterpret_cast<const sockaddr *>(&sa), salen, m_LocalIP, m_LocalPort);
}
void cTCPLinkImpl::UpdateRemoteAddress(void)
{
sockaddr_storage sa;
socklen_t salen = static_cast<socklen_t>(sizeof(sa));
getpeername(bufferevent_getfd(m_BufferEvent), reinterpret_cast<sockaddr *>(&sa), &salen);
UpdateAddress(reinterpret_cast<const sockaddr *>(&sa), salen, m_RemoteIP, m_RemotePort);
}
////////////////////////////////////////////////////////////////////////////////
// cServerHandleImpl:
cServerHandleImpl::cServerHandleImpl(
cNetwork::cListenCallbacksPtr a_ListenCallbacks,
cTCPLink::cCallbacksPtr a_LinkCallbacks
):
m_ListenCallbacks(a_ListenCallbacks),
m_LinkCallbacks(a_LinkCallbacks),
m_ConnListener(nullptr),
m_SecondaryConnListener(nullptr),
m_IsListening(false),
m_ErrorCode(0)
{
}
cServerHandleImpl::~cServerHandleImpl()
{
if (m_ConnListener != nullptr)
{
evconnlistener_free(m_ConnListener);
}
if (m_SecondaryConnListener != nullptr)
{
evconnlistener_free(m_SecondaryConnListener);
}
}
void cServerHandleImpl::Close(void)
{
// Stop the listener sockets:
evconnlistener_disable(m_ConnListener);
if (m_SecondaryConnListener != nullptr)
{
evconnlistener_disable(m_SecondaryConnListener);
}
m_IsListening = false;
// Shutdown all connections:
cTCPLinkImplPtrs Conns;
{
cCSLock Lock(m_CS);
std::swap(Conns, m_Connections);
}
for (auto conn: Conns)
{
conn->Shutdown();
}
}
cServerHandleImplPtr cServerHandleImpl::Listen(
UInt16 a_Port,
cNetwork::cListenCallbacksPtr a_ListenCallbacks,
cTCPLink::cCallbacksPtr a_LinkCallbacks
)
{
cServerHandleImplPtr res = cServerHandleImplPtr{new cServerHandleImpl(a_ListenCallbacks, a_LinkCallbacks)};
if (res->Listen(a_Port))
{
cNetworkSingleton::Get().AddServer(res);
}
else
{
a_ListenCallbacks->OnError(res->m_ErrorCode, res->m_ErrorMsg);
}
return res;
}
bool cServerHandleImpl::Listen(UInt16 a_Port)
{
// Set up the main socket:
// It should listen on IPv6 with IPv4 fallback, when available; IPv4 when IPv6 is not available.
bool NeedsTwoSockets = false;
int err;
evutil_socket_t MainSock = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
if (!IsValidSocket(MainSock))
{
// Failed to create IPv6 socket, create an IPv4 one instead:
err = EVUTIL_SOCKET_ERROR();
LOGD("Failed to create IPv6 MainSock: %d (%s)", err, evutil_socket_error_to_string(err));
MainSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (!IsValidSocket(MainSock))
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
Printf(m_ErrorMsg, "Cannot create socket for port %d: %s", a_Port, evutil_socket_error_to_string(m_ErrorCode));
return false;
}
// Bind to all interfaces:
sockaddr_in name;
memset(&name, 0, sizeof(name));
name.sin_family = AF_INET;
name.sin_port = ntohs(a_Port);
if (bind(MainSock, reinterpret_cast<const sockaddr *>(&name), sizeof(name)) != 0)
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
Printf(m_ErrorMsg, "Cannot bind IPv4 socket to port %d: %s", a_Port, evutil_socket_error_to_string(m_ErrorCode));
evutil_closesocket(MainSock);
return false;
}
}
else
{
// IPv6 socket created, switch it into "dualstack" mode:
UInt32 Zero = 0;
#ifdef _WIN32
// WinXP doesn't support this feature, so if the setting fails, create another socket later on:
int res = setsockopt(MainSock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char *>(&Zero), sizeof(Zero));
err = EVUTIL_SOCKET_ERROR();
NeedsTwoSockets = ((res == SOCKET_ERROR) && (err == WSAENOPROTOOPT));
LOGD("setsockopt(IPV6_V6ONLY) returned %d, err is %d (%s). %s",
res, err, evutil_socket_error_to_string(err),
NeedsTwoSockets ? "Second socket will be created" : "Second socket not needed"
);
#else
setsockopt(MainSock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char *>(&Zero), sizeof(Zero));
#endif
// Bind to all interfaces:
sockaddr_in6 name;
memset(&name, 0, sizeof(name));
name.sin6_family = AF_INET6;
name.sin6_port = ntohs(a_Port);
if (bind(MainSock, reinterpret_cast<const sockaddr *>(&name), sizeof(name)) != 0)
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
Printf(m_ErrorMsg, "Cannot bind IPv6 socket to port %d: %s", a_Port, evutil_socket_error_to_string(m_ErrorCode));
evutil_closesocket(MainSock);
return false;
}
}
if (evutil_make_socket_nonblocking(MainSock) != 0)
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
Printf(m_ErrorMsg, "Cannot make socket on port %d non-blocking: %s", a_Port, evutil_socket_error_to_string(m_ErrorCode));
evutil_closesocket(MainSock);
return false;
}
if (listen(MainSock, 0) != 0)
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
Printf(m_ErrorMsg, "Cannot listen on port %d: %s", a_Port, evutil_socket_error_to_string(m_ErrorCode));
evutil_closesocket(MainSock);
return false;
}
m_ConnListener = evconnlistener_new(cNetworkSingleton::Get().m_EventBase, Callback, this, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, 0, MainSock);
// If a secondary socket is required (WinXP dual-stack), create it here:
if (NeedsTwoSockets)
{
LOGD("Creating a second socket for IPv4");
evutil_socket_t SecondSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (IsValidSocket(SecondSock))
{
if (evutil_make_socket_nonblocking(SecondSock) == 0)
{
m_SecondaryConnListener = evconnlistener_new(cNetworkSingleton::Get().m_EventBase, Callback, this, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, 0, SecondSock);
}
else
{
err = EVUTIL_SOCKET_ERROR();
LOGD("evutil_make_socket_nonblocking() failed: %d, %s", err, evutil_socket_error_to_string(err));
}
}
else
{
err = EVUTIL_SOCKET_ERROR();
LOGD("socket(AF_INET, ...) failed: %d, %s", err, evutil_socket_error_to_string(err));
}
}
m_IsListening = true;
return true;
}
void cServerHandleImpl::Callback(evconnlistener * a_Listener, evutil_socket_t a_Socket, sockaddr * a_Addr, int a_Len, void * a_Self)
{
// Cast to true self:
cServerHandleImpl * Self = reinterpret_cast<cServerHandleImpl *>(a_Self);
ASSERT(Self != nullptr);
// Create a new cTCPLink for the incoming connection:
cTCPLinkImplPtr Link = std::make_shared<cTCPLinkImpl>(a_Socket, Self->m_LinkCallbacks, Self, a_Addr, a_Len);
{
cCSLock Lock(Self->m_CS);
Self->m_Connections.push_back(Link);
} // Lock(m_CS)
// Call the OnAccepted callback:
Self->m_ListenCallbacks->OnAccepted(*Link);
}
void cServerHandleImpl::RemoveLink(const cTCPLinkImpl * a_Link)
{
cCSLock Lock(m_CS);
for (auto itr = m_Connections.begin(), end = m_Connections.end(); itr != end; ++itr)
{
if (itr->get() == a_Link)
{
m_Connections.erase(itr);
return;
}
} // for itr - m_Connections[]
}
////////////////////////////////////////////////////////////////////////////////
// cNetwork:
bool cNetwork::Connect(
const AString & a_Host,
const UInt16 a_Port,
cNetwork::cConnectCallbacksPtr a_ConnectCallbacks,
cTCPLink::cCallbacksPtr a_LinkCallbacks
)
{
// Add a connection request to the queue:
cTCPLinkImplPtr Conn = cTCPLinkImpl::Connect(a_Host, a_Port, a_LinkCallbacks, a_ConnectCallbacks);
return (Conn != nullptr);
}
cServerHandlePtr cNetwork::Listen(
const UInt16 a_Port,
cNetwork::cListenCallbacksPtr a_ListenCallbacks,
cTCPLink::cCallbacksPtr a_LinkCallbacks
)
{
return cServerHandleImpl::Listen(a_Port, a_ListenCallbacks, a_LinkCallbacks);
}
bool cNetwork::HostnameToIP(
const AString & a_Hostname,
cNetwork::cResolveNameCallbacksPtr a_Callbacks
)
{
return cNetworkSingleton::Get().HostnameToIP(a_Hostname, a_Callbacks);
}
bool cNetwork::IPToHostName(
const AString & a_IP,
cNetwork::cResolveNameCallbacksPtr a_Callbacks
)
{
return cNetworkSingleton::Get().IPToHostName(a_IP, a_Callbacks);
}
////////////////////////////////////////////////////////////////////////////////
// cTCPLink:
cTCPLink::cTCPLink(cCallbacksPtr a_Callbacks):
m_Callbacks(a_Callbacks)
{
}
////////////////////////////////////////////////////////////////////////////////
// cNetworkSingleton:
cNetworkSingleton::cNetworkSingleton(void)
{
// Windows: initialize networking:
#ifdef _WIN32
WSADATA wsaData;
memset(&wsaData, 0, sizeof(wsaData));
WSAStartup (MAKEWORD(2, 2), &wsaData);
#endif // _WIN32
// Initialize LibEvent logging:
event_set_log_callback(LogCallback);
// Initialize threading:
#if defined(EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED)
evthread_use_windows_threads();
#elif defined(EVTHREAD_USE_PTHREADS_IMPLEMENTED)
evthread_use_pthreads();
#else
#error No threading implemented for EVTHREAD
#endif
// Create the main event_base:
m_EventBase = event_base_new();
if (m_EventBase == nullptr)
{
LOGERROR("Failed to initialize LibEvent. The server will now terminate.");
abort();
}
// Create the DNS lookup helper:
m_DNSBase = evdns_base_new(m_EventBase, 1);
if (m_DNSBase == nullptr)
{
LOGERROR("Failed to initialize LibEvent's DNS subsystem. The server will now terminate.");
abort();
}
// Create the event loop thread:
std::thread EventLoopThread(RunEventLoop, this);
EventLoopThread.detach();
}
cNetworkSingleton & cNetworkSingleton::Get(void)
{
static cNetworkSingleton Instance;
return Instance;
}
bool cNetworkSingleton::HostnameToIP(
const AString & a_Hostname,
cNetwork::cResolveNameCallbacksPtr a_Callbacks
)
{
try
{
cCSLock Lock(m_CS);
m_HostnameLookups.push_back(std::make_shared<cHostnameLookup>(a_Hostname, a_Callbacks));
}
catch (...)
{
return false;
}
return true;
}
bool cNetworkSingleton::IPToHostName(
const AString & a_IP,
cNetwork::cResolveNameCallbacksPtr a_Callbacks
)
{
try
{
cCSLock Lock(m_CS);
m_IPLookups.push_back(std::make_shared<cIPLookup>(a_IP, a_Callbacks));
}
catch (...)
{
return false;
}
return true;
}
void cNetworkSingleton::LogCallback(int a_Severity, const char * a_Msg)
{
switch (a_Severity)
{
case _EVENT_LOG_DEBUG: LOGD ("LibEvent: %s", a_Msg); break;
case _EVENT_LOG_MSG: LOG ("LibEvent: %s", a_Msg); break;
case _EVENT_LOG_WARN: LOGWARNING("LibEvent: %s", a_Msg); break;
case _EVENT_LOG_ERR: LOGERROR ("LibEvent: %s", a_Msg); break;
default:
{
LOGWARNING("LibEvent: Unknown log severity (%d): %s", a_Severity, a_Msg);
break;
}
}
}
void cNetworkSingleton::RunEventLoop(cNetworkSingleton * a_Self)
{
event_base_loop(a_Self->m_EventBase, EVLOOP_NO_EXIT_ON_EMPTY);
}
void cNetworkSingleton::RemoveHostnameLookup(const cHostnameLookup * a_HostnameLookup)
{
cCSLock Lock(m_CS);
for (auto itr = m_HostnameLookups.begin(), end = m_HostnameLookups.end(); itr != end; ++itr)
{
if (itr->get() == a_HostnameLookup)
{
m_HostnameLookups.erase(itr);
return;
}
} // for itr - m_HostnameLookups[]
}
void cNetworkSingleton::RemoveIPLookup(const cIPLookup * a_IPLookup)
{
cCSLock Lock(m_CS);
for (auto itr = m_IPLookups.begin(), end = m_IPLookups.end(); itr != end; ++itr)
{
if (itr->get() == a_IPLookup)
{
m_IPLookups.erase(itr);
return;
}
} // for itr - m_IPLookups[]
}
void cNetworkSingleton::AddLink(cTCPLinkImplPtr a_Link)
{
cCSLock Lock(m_CS);
m_Connections.push_back(a_Link);
}
void cNetworkSingleton::RemoveLink(const cTCPLinkImpl * a_Link)
{
cCSLock Lock(m_CS);
for (auto itr = m_Connections.begin(), end = m_Connections.end(); itr != end; ++itr)
{
if (itr->get() == a_Link)
{
m_Connections.erase(itr);
return;
}
} // for itr - m_Connections[]
}
void cNetworkSingleton::AddServer(cServerHandleImplPtr a_Server)
{
cCSLock Lock(m_CS);
m_Servers.push_back(a_Server);
}
void cNetworkSingleton::RemoveServer(const cServerHandleImpl * a_Server)
{
cCSLock Lock(m_CS);
for (auto itr = m_Servers.begin(), end = m_Servers.end(); itr != end; ++itr)
{
if (itr->get() == a_Server)
{
m_Servers.erase(itr);
return;
}
} // for itr - m_Servers[]
}
cNetwork: Handle WSA initialization failures.
// Network.cpp
// Implements the classes used for the Network API
#include "Globals.h"
#include "Network.h"
#include <event2/event.h>
#include <event2/thread.h>
#include <event2/bufferevent.h>
#include <event2/dns.h>
#include <event2/listener.h>
#include <thread>
#include "Event.h"
#include "CriticalSection.h"
// fwd:
class cServerHandleImpl;
class cTCPLinkImpl;
typedef SharedPtr<cTCPLinkImpl> cTCPLinkImplPtr;
typedef std::vector<cTCPLinkImplPtr> cTCPLinkImplPtrs;
typedef SharedPtr<cServerHandleImpl> cServerHandleImplPtr;
typedef std::vector<cServerHandleImplPtr> cServerHandleImplPtrs;
////////////////////////////////////////////////////////////////////////////////
// Class definitions:
/** Holds information about an in-progress Hostname-to-IP lookup. */
class cHostnameLookup
{
/** The callbacks to call for resolved names / errors. */
cNetwork::cResolveNameCallbacksPtr m_Callbacks;
/** The hostname that was queried (needed for the callbacks). */
AString m_Hostname;
static void Callback(int a_ErrCode, struct evutil_addrinfo * a_Addr, void * a_Self);
public:
cHostnameLookup(const AString & a_Hostname, cNetwork::cResolveNameCallbacksPtr a_Callbacks);
};
typedef SharedPtr<cHostnameLookup> cHostnameLookupPtr;
typedef std::vector<cHostnameLookupPtr> cHostnameLookupPtrs;
/** Holds information about an in-progress IP-to-Hostname lookup. */
class cIPLookup
{
/** The callbacks to call for resolved names / errors. */
cNetwork::cResolveNameCallbacksPtr m_Callbacks;
/** The IP that was queried (needed for the callbacks). */
AString m_IP;
static void Callback(int a_Result, char a_Type, int a_Count, int a_Ttl, void * a_Addresses, void * a_Self);
public:
cIPLookup(const AString & a_IP, cNetwork::cResolveNameCallbacksPtr a_Callbacks);
};
typedef SharedPtr<cIPLookup> cIPLookupPtr;
typedef std::vector<cIPLookupPtr> cIPLookupPtrs;
/** Implements the cTCPLink details so that it can represent the single connection between two endpoints. */
class cTCPLinkImpl:
public cTCPLink
{
typedef cTCPLink super;
public:
/** Creates a new link based on the given socket.
Used for connections accepted in a server using cNetwork::Listen().
a_Address and a_AddrLen describe the remote peer that has connected. */
cTCPLinkImpl(evutil_socket_t a_Socket, cCallbacksPtr a_LinkCallbacks, cServerHandleImpl * a_Server, const sockaddr * a_Address, int a_AddrLen);
/** Destroys the LibEvent handle representing the link. */
~cTCPLinkImpl();
/** Queues a connection request to the specified host.
a_ConnectCallbacks must be valid.
Returns a link that has the connection request queued, or NULL for failure. */
static cTCPLinkImplPtr Connect(const AString & a_Host, UInt16 a_Port, cTCPLink::cCallbacksPtr a_LinkCallbacks, cNetwork::cConnectCallbacksPtr a_ConnectCallbacks);
// cTCPLink overrides:
virtual bool Send(const void * a_Data, size_t a_Length) override;
virtual AString GetLocalIP(void) const override { return m_LocalIP; }
virtual UInt16 GetLocalPort(void) const override { return m_LocalPort; }
virtual AString GetRemoteIP(void) const override { return m_RemoteIP; }
virtual UInt16 GetRemotePort(void) const override { return m_RemotePort; }
virtual void Shutdown(void) override;
virtual void Close(void) override;
protected:
/** Callbacks to call when the connection is established.
May be NULL if not used. Only used for outgoing connections (cNetwork::Connect()). */
cNetwork::cConnectCallbacksPtr m_ConnectCallbacks;
/** The LibEvent handle representing this connection. */
bufferevent * m_BufferEvent;
/** The server handle that has created this link.
Only valid for incoming connections, NULL for outgoing connections. */
cServerHandleImpl * m_Server;
/** The IP address of the local endpoint. Valid only after the socket has been connected. */
AString m_LocalIP;
/** The port of the local endpoint. Valid only after the socket has been connected. */
UInt16 m_LocalPort;
/** The IP address of the remote endpoint. Valid only after the socket has been connected. */
AString m_RemoteIP;
/** The port of the remote endpoint. Valid only after the socket has been connected. */
UInt16 m_RemotePort;
/** Creates a new link to be queued to connect to a specified host:port.
Used for outgoing connections created using cNetwork::Connect().
To be used only by the Connect() factory function. */
cTCPLinkImpl(const cCallbacksPtr a_LinkCallbacks);
/** Callback that LibEvent calls when there's data available from the remote peer. */
static void ReadCallback(bufferevent * a_BufferEvent, void * a_Self);
/** Callback that LibEvent calls when there's a non-data-related event on the socket. */
static void EventCallback(bufferevent * a_BufferEvent, short a_What, void * a_Self);
/** Sets a_IP and a_Port to values read from a_Address, based on the correct address family. */
static void UpdateAddress(const sockaddr * a_Address, int a_AddrLen, AString & a_IP, UInt16 & a_Port);
/** Updates m_LocalIP and m_LocalPort based on the metadata read from the socket. */
void UpdateLocalAddress(void);
/** Updates m_RemoteIP and m_RemotePort based on the metadata read from the socket. */
void UpdateRemoteAddress(void);
};
/** Implements the cServerHandle details so that it can represent a real server socket, with a list of clients. */
class cServerHandleImpl:
public cServerHandle
{
typedef cServerHandle super;
friend class cTCPLinkImpl;
public:
/** Closes the server, dropping all the connections. */
~cServerHandleImpl();
/** Creates a new server instance listening on the specified port.
Both IPv4 and IPv6 interfaces are used, if possible.
Always returns a server instance; in the event of a failure, the instance holds the error details. Use IsListening() to query success. */
static cServerHandleImplPtr Listen(
UInt16 a_Port,
cNetwork::cListenCallbacksPtr a_ListenCallbacks,
cTCPLink::cCallbacksPtr a_LinkCallbacks
);
// cServerHandle overrides:
virtual void Close(void) override;
virtual bool IsListening(void) const override { return m_IsListening; }
protected:
/** The callbacks used to notify about incoming connections. */
cNetwork::cListenCallbacksPtr m_ListenCallbacks;
/** The callbacks used to create new cTCPLink instances for incoming connections. */
cTCPLink::cCallbacksPtr m_LinkCallbacks;
/** The LibEvent handle representing the main listening socket. */
evconnlistener * m_ConnListener;
/** The LibEvent handle representing the secondary listening socket (only when side-by-side listening is needed, such as WinXP). */
evconnlistener * m_SecondaryConnListener;
/** Set to true when the server is initialized successfully and is listening for incoming connections. */
bool m_IsListening;
/** Container for all currently active connections on this server. */
cTCPLinkImplPtrs m_Connections;
/** Mutex protecting m_Connections againt multithreaded access. */
cCriticalSection m_CS;
/** Contains the error code for the failure to listen. Only valid for non-listening instances. */
int m_ErrorCode;
/** Contains the error message for the failure to listen. Only valid for non-listening instances. */
AString m_ErrorMsg;
/** Creates a new instance with the specified callbacks.
Initializes the internals, but doesn't start listening yet. */
cServerHandleImpl(
cNetwork::cListenCallbacksPtr a_ListenCallbacks,
cTCPLink::cCallbacksPtr a_LinkCallbacks
);
/** Starts listening on the specified port.
Returns true if successful, false on failure. On failure, sets m_ErrorCode and m_ErrorMsg. */
bool Listen(UInt16 a_Port);
/** The callback called by LibEvent upon incoming connection. */
static void Callback(evconnlistener * a_Listener, evutil_socket_t a_Socket, sockaddr * a_Addr, int a_Len, void * a_Self);
/** Removes the specified link from m_Connections.
Called by cTCPLinkImpl when the link is terminated. */
void RemoveLink(const cTCPLinkImpl * a_Link);
};
class cNetworkSingleton
{
friend class cHostnameLookup; // Needs access to m_DNSBase
friend class cIPLookup; // Needs access to m_DNSBase
friend class cTCPLinkImpl; // Needs access to m_EventBase and m_DNSBase
friend class cServerHandleImpl; // Needs access to m_EventBase
public:
/** Returns the singleton instance of this class */
static cNetworkSingleton & Get(void);
// The following functions are implementations for the cNetwork class
/** Queues a DNS query to resolve the specified hostname to IP address.
Calls one of the callbacks when the resolving succeeds, or when it fails.
Returns true if queueing was successful, false if not.
Note that the return value doesn't report the success of the actual lookup; the lookup happens asynchronously on the background. */
bool HostnameToIP(
const AString & a_Hostname,
cNetwork::cResolveNameCallbacksPtr a_Callbacks
);
/** Queues a DNS query to resolve the specified IP address to a hostname.
Calls one of the callbacks when the resolving succeeds, or when it fails.
Returns true if queueing was successful, false if not.
Note that the return value doesn't report the success of the actual lookup; the lookup happens asynchronously on the background. */
bool IPToHostName(
const AString & a_IP,
cNetwork::cResolveNameCallbacksPtr a_Callbacks
);
protected:
/** The main LibEvent container for driving the event loop. */
event_base * m_EventBase;
/** The LibEvent handle for doing DNS lookups. */
evdns_base * m_DNSBase;
/** Container for all client connections, including ones with pending-connect. */
cTCPLinkImplPtrs m_Connections;
/** Container for all servers that are currently active. */
cServerHandleImplPtrs m_Servers;
/** Container for all pending hostname lookups. */
cHostnameLookupPtrs m_HostnameLookups;
/** Container for all pending IP lookups. */
cIPLookupPtrs m_IPLookups;
/** Mutex protecting all containers against multithreaded access. */
cCriticalSection m_CS;
/** Initializes the LibEvent internals. */
cNetworkSingleton(void);
/** Converts LibEvent-generated log events into log messages in MCS log. */
static void LogCallback(int a_Severity, const char * a_Msg);
/** Implements the thread that runs LibEvent's event dispatcher loop. */
static void RunEventLoop(cNetworkSingleton * a_Self);
/** Removes the specified hostname lookup from m_HostnameLookups.
Used by the underlying lookup implementation when the lookup is finished. */
void RemoveHostnameLookup(const cHostnameLookup * a_HostnameLookup);
/** Removes the specified IP lookup from m_IPLookups.
Used by the underlying lookup implementation when the lookup is finished. */
void RemoveIPLookup(const cIPLookup * a_IPLookup);
/** Adds the specified link to m_Connections.
Used by the underlying link implementation when a new link is created. */
void AddLink(cTCPLinkImplPtr a_Link);
/** Removes the specified link from m_Connections.
Used by the underlying link implementation when the link is closed / errored. */
void RemoveLink(const cTCPLinkImpl * a_Link);
/** Adds the specified link to m_Servers.
Used by the underlying server handle implementation when a new listening server is created.
Only servers that succeed in listening are added. */
void AddServer(cServerHandleImplPtr a_Server);
/** Removes the specified server from m_Servers.
Used by the underlying server handle implementation when the server is closed. */
void RemoveServer(const cServerHandleImpl * a_Server);
};
////////////////////////////////////////////////////////////////////////////////
// Globals:
bool IsValidSocket(evutil_socket_t a_Socket)
{
#ifdef _WIN32
return (a_Socket != INVALID_SOCKET);
#else // _WIN32
return (a_Socket >= 0);
#endif // else _WIN32
}
////////////////////////////////////////////////////////////////////////////////
// cHostnameLookup:
cHostnameLookup::cHostnameLookup(const AString & a_Hostname, cNetwork::cResolveNameCallbacksPtr a_Callbacks):
m_Callbacks(a_Callbacks),
m_Hostname(a_Hostname)
{
evutil_addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_protocol = IPPROTO_TCP;
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_UNSPEC;
hints.ai_flags = EVUTIL_AI_CANONNAME;
evdns_getaddrinfo(cNetworkSingleton::Get().m_DNSBase, a_Hostname.c_str(), nullptr, &hints, Callback, this);
}
void cHostnameLookup::Callback(int a_ErrCode, evutil_addrinfo * a_Addr, void * a_Self)
{
// Get the Self class:
cHostnameLookup * Self = reinterpret_cast<cHostnameLookup *>(a_Self);
ASSERT(Self != nullptr);
// If an error has occurred, notify the error callback:
if (a_ErrCode != 0)
{
Self->m_Callbacks->OnError(a_ErrCode);
cNetworkSingleton::Get().RemoveHostnameLookup(Self);
return;
}
// Call the success handler for each entry received:
bool HasResolved = false;
evutil_addrinfo * OrigAddr = a_Addr;
for (;a_Addr != nullptr; a_Addr = a_Addr->ai_next)
{
char IP[128];
switch (a_Addr->ai_family)
{
case AF_INET: // IPv4
{
sockaddr_in * sin = reinterpret_cast<sockaddr_in *>(a_Addr->ai_addr);
evutil_inet_ntop(AF_INET, &(sin->sin_addr), IP, sizeof(IP));
break;
}
case AF_INET6: // IPv6
{
sockaddr_in6 * sin = reinterpret_cast<sockaddr_in6 *>(a_Addr->ai_addr);
evutil_inet_ntop(AF_INET6, &(sin->sin6_addr), IP, sizeof(IP));
break;
}
default:
{
// Unknown address family, handle as if this entry wasn't received
continue; // for (a_Addr)
}
}
Self->m_Callbacks->OnNameResolved(Self->m_Hostname, IP);
HasResolved = true;
} // for (a_Addr)
// If only unsupported families were reported, call the Error handler:
if (!HasResolved)
{
Self->m_Callbacks->OnError(1);
}
else
{
Self->m_Callbacks->OnFinished();
}
evutil_freeaddrinfo(OrigAddr);
cNetworkSingleton::Get().RemoveHostnameLookup(Self);
}
////////////////////////////////////////////////////////////////////////////////
// cIPLookup:
cIPLookup::cIPLookup(const AString & a_IP, cNetwork::cResolveNameCallbacksPtr a_Callbacks):
m_Callbacks(a_Callbacks),
m_IP(a_IP)
{
sockaddr_storage sa;
int salen = static_cast<int>(sizeof(sa));
evutil_parse_sockaddr_port(a_IP.c_str(), reinterpret_cast<sockaddr *>(&sa), &salen);
switch (sa.ss_family)
{
case AF_INET:
{
sockaddr_in * sa4 = reinterpret_cast<sockaddr_in *>(&sa);
evdns_base_resolve_reverse(cNetworkSingleton::Get().m_DNSBase, &(sa4->sin_addr), 0, Callback, this);
break;
}
case AF_INET6:
{
sockaddr_in6 * sa6 = reinterpret_cast<sockaddr_in6 *>(&sa);
evdns_base_resolve_reverse_ipv6(cNetworkSingleton::Get().m_DNSBase, &(sa6->sin6_addr), 0, Callback, this);
break;
}
default:
{
LOGWARNING("%s: Unknown address family: %d", __FUNCTION__, sa.ss_family);
ASSERT(!"Unknown address family");
break;
}
} // switch (address family)
}
void cIPLookup::Callback(int a_Result, char a_Type, int a_Count, int a_Ttl, void * a_Addresses, void * a_Self)
{
// Get the Self class:
cIPLookup * Self = reinterpret_cast<cIPLookup *>(a_Self);
ASSERT(Self != nullptr);
// Call the proper callback based on the event received:
if ((a_Result != 0) || (a_Addresses == nullptr))
{
// An error has occurred, notify the error callback:
Self->m_Callbacks->OnError(a_Result);
}
else
{
// Call the success handler:
Self->m_Callbacks->OnNameResolved(*(reinterpret_cast<char **>(a_Addresses)), Self->m_IP);
Self->m_Callbacks->OnFinished();
}
cNetworkSingleton::Get().RemoveIPLookup(Self);
}
////////////////////////////////////////////////////////////////////////////////
// cTCPLinkImpl:
cTCPLinkImpl::cTCPLinkImpl(cTCPLink::cCallbacksPtr a_LinkCallbacks):
super(a_LinkCallbacks),
m_BufferEvent(bufferevent_socket_new(cNetworkSingleton::Get().m_EventBase, -1, BEV_OPT_CLOSE_ON_FREE)),
m_Server(nullptr)
{
// Create the LibEvent handle, but don't assign a socket to it yet (will be assigned within Connect() method):
bufferevent_setcb(m_BufferEvent, ReadCallback, nullptr, EventCallback, this);
bufferevent_enable(m_BufferEvent, EV_READ | EV_WRITE);
}
cTCPLinkImpl::cTCPLinkImpl(evutil_socket_t a_Socket, cTCPLink::cCallbacksPtr a_LinkCallbacks, cServerHandleImpl * a_Server, const sockaddr * a_Address, int a_AddrLen):
super(a_LinkCallbacks),
m_BufferEvent(bufferevent_socket_new(cNetworkSingleton::Get().m_EventBase, a_Socket, BEV_OPT_CLOSE_ON_FREE)),
m_Server(a_Server)
{
// Update the endpoint addresses:
UpdateLocalAddress();
UpdateAddress(a_Address, a_AddrLen, m_RemoteIP, m_RemotePort);
// Create the LibEvent handle:
bufferevent_setcb(m_BufferEvent, ReadCallback, nullptr, EventCallback, this);
bufferevent_enable(m_BufferEvent, EV_READ | EV_WRITE);
}
cTCPLinkImpl::~cTCPLinkImpl()
{
bufferevent_free(m_BufferEvent);
}
cTCPLinkImplPtr cTCPLinkImpl::Connect(const AString & a_Host, UInt16 a_Port, cTCPLink::cCallbacksPtr a_LinkCallbacks, cNetwork::cConnectCallbacksPtr a_ConnectCallbacks)
{
ASSERT(a_LinkCallbacks != nullptr);
ASSERT(a_ConnectCallbacks != nullptr);
// Create a new link:
cTCPLinkImplPtr res{new cTCPLinkImpl(a_LinkCallbacks)}; // Cannot use std::make_shared here, constructor is not accessible
res->m_ConnectCallbacks = a_ConnectCallbacks;
cNetworkSingleton::Get().AddLink(res);
// If a_Host is an IP address, schedule a connection immediately:
sockaddr_storage sa;
int salen = static_cast<int>(sizeof(sa));
if (evutil_parse_sockaddr_port(a_Host.c_str(), reinterpret_cast<sockaddr *>(&sa), &salen) == 0)
{
// Insert the correct port:
if (sa.ss_family == AF_INET6)
{
reinterpret_cast<sockaddr_in6 *>(&sa)->sin6_port = htons(a_Port);
}
else
{
reinterpret_cast<sockaddr_in *>(&sa)->sin_port = htons(a_Port);
}
// Queue the connect request:
if (bufferevent_socket_connect(res->m_BufferEvent, reinterpret_cast<sockaddr *>(&sa), salen) == 0)
{
// Success
return res;
}
// Failure
cNetworkSingleton::Get().RemoveLink(res.get());
return nullptr;
}
// a_Host is a hostname, connect after a lookup:
if (bufferevent_socket_connect_hostname(res->m_BufferEvent, cNetworkSingleton::Get().m_DNSBase, AF_UNSPEC, a_Host.c_str(), a_Port) == 0)
{
// Success
return res;
}
// Failure
cNetworkSingleton::Get().RemoveLink(res.get());
return nullptr;
}
bool cTCPLinkImpl::Send(const void * a_Data, size_t a_Length)
{
return (bufferevent_write(m_BufferEvent, a_Data, a_Length) == 0);
}
void cTCPLinkImpl::Shutdown(void)
{
#ifdef _WIN32
shutdown(bufferevent_getfd(m_BufferEvent), SD_SEND);
#else
shutdown(bufferevent_getfd(m_BufferEvent), SHUT_WR);
#endif
bufferevent_disable(m_BufferEvent, EV_WRITE);
}
void cTCPLinkImpl::Close(void)
{
// Disable all events on the socket, but keep it alive:
bufferevent_disable(m_BufferEvent, EV_READ | EV_WRITE);
if (m_Server == nullptr)
{
cNetworkSingleton::Get().RemoveLink(this);
}
else
{
m_Server->RemoveLink(this);
}
}
void cTCPLinkImpl::ReadCallback(bufferevent * a_BufferEvent, void * a_Self)
{
ASSERT(a_Self != nullptr);
cTCPLinkImpl * Self = static_cast<cTCPLinkImpl *>(a_Self);
ASSERT(Self->m_Callbacks != nullptr);
// Read all the incoming data, in 1024-byte chunks:
char data[1024];
size_t length;
while ((length = bufferevent_read(a_BufferEvent, data, sizeof(data))) > 0)
{
Self->m_Callbacks->OnReceivedData(*Self, data, length);
}
}
void cTCPLinkImpl::EventCallback(bufferevent * a_BufferEvent, short a_What, void * a_Self)
{
ASSERT(a_Self != nullptr);
cTCPLinkImpl * Self = static_cast<cTCPLinkImpl *>(a_Self);
// If an error is reported, call the error callback:
if (a_What & BEV_EVENT_ERROR)
{
// Choose the proper callback to call based on whether we were waiting for connection or not:
if (Self->m_ConnectCallbacks != nullptr)
{
Self->m_ConnectCallbacks->OnError(EVUTIL_SOCKET_ERROR());
}
else
{
Self->m_Callbacks->OnError(*Self, EVUTIL_SOCKET_ERROR());
if (Self->m_Server == nullptr)
{
cNetworkSingleton::Get().RemoveLink(Self);
}
else
{
Self->m_Server->RemoveLink(Self);
}
}
return;
}
// Pending connection succeeded, call the connection callback:
if (a_What & BEV_EVENT_CONNECTED)
{
if (Self->m_ConnectCallbacks != nullptr)
{
Self->m_ConnectCallbacks->OnSuccess(*Self);
// Reset the connect callbacks so that later errors get reported through the link callbacks:
Self->m_ConnectCallbacks.reset();
return;
}
Self->UpdateLocalAddress();
Self->UpdateRemoteAddress();
}
// If the connection has been closed, call the link callback and remove the connection:
if (a_What & BEV_EVENT_EOF)
{
Self->m_Callbacks->OnRemoteClosed(*Self);
if (Self->m_Server != nullptr)
{
Self->m_Server->RemoveLink(Self);
}
else
{
cNetworkSingleton::Get().RemoveLink(Self);
}
return;
}
// Unknown event, report it:
LOGWARNING("cTCPLinkImpl: Unhandled LibEvent event %d (0x%x)", a_What, a_What);
ASSERT(!"cTCPLinkImpl: Unhandled LibEvent event");
}
void cTCPLinkImpl::UpdateAddress(const sockaddr * a_Address, int a_AddrLen, AString & a_IP, UInt16 & a_Port)
{
// Based on the family specified in the address, use the correct datastructure to convert to IP string:
char IP[128];
switch (a_Address->sa_family)
{
case AF_INET: // IPv4:
{
const sockaddr_in * sin = reinterpret_cast<const sockaddr_in *>(a_Address);
evutil_inet_ntop(AF_INET, &(sin->sin_addr), IP, sizeof(IP));
a_Port = ntohs(sin->sin_port);
break;
}
case AF_INET6: // IPv6
{
const sockaddr_in6 * sin = reinterpret_cast<const sockaddr_in6 *>(a_Address);
evutil_inet_ntop(AF_INET6, &(sin->sin6_addr), IP, sizeof(IP));
a_Port = ntohs(sin->sin6_port);
break;
}
default:
{
LOGWARNING("%s: Unknown socket address family: %d", __FUNCTION__, a_Address->sa_family);
ASSERT(!"Unknown socket address family");
break;
}
}
a_IP.assign(IP);
}
void cTCPLinkImpl::UpdateLocalAddress(void)
{
sockaddr_storage sa;
socklen_t salen = static_cast<socklen_t>(sizeof(sa));
getsockname(bufferevent_getfd(m_BufferEvent), reinterpret_cast<sockaddr *>(&sa), &salen);
UpdateAddress(reinterpret_cast<const sockaddr *>(&sa), salen, m_LocalIP, m_LocalPort);
}
void cTCPLinkImpl::UpdateRemoteAddress(void)
{
sockaddr_storage sa;
socklen_t salen = static_cast<socklen_t>(sizeof(sa));
getpeername(bufferevent_getfd(m_BufferEvent), reinterpret_cast<sockaddr *>(&sa), &salen);
UpdateAddress(reinterpret_cast<const sockaddr *>(&sa), salen, m_RemoteIP, m_RemotePort);
}
////////////////////////////////////////////////////////////////////////////////
// cServerHandleImpl:
cServerHandleImpl::cServerHandleImpl(
cNetwork::cListenCallbacksPtr a_ListenCallbacks,
cTCPLink::cCallbacksPtr a_LinkCallbacks
):
m_ListenCallbacks(a_ListenCallbacks),
m_LinkCallbacks(a_LinkCallbacks),
m_ConnListener(nullptr),
m_SecondaryConnListener(nullptr),
m_IsListening(false),
m_ErrorCode(0)
{
}
cServerHandleImpl::~cServerHandleImpl()
{
if (m_ConnListener != nullptr)
{
evconnlistener_free(m_ConnListener);
}
if (m_SecondaryConnListener != nullptr)
{
evconnlistener_free(m_SecondaryConnListener);
}
}
void cServerHandleImpl::Close(void)
{
// Stop the listener sockets:
evconnlistener_disable(m_ConnListener);
if (m_SecondaryConnListener != nullptr)
{
evconnlistener_disable(m_SecondaryConnListener);
}
m_IsListening = false;
// Shutdown all connections:
cTCPLinkImplPtrs Conns;
{
cCSLock Lock(m_CS);
std::swap(Conns, m_Connections);
}
for (auto conn: Conns)
{
conn->Shutdown();
}
}
cServerHandleImplPtr cServerHandleImpl::Listen(
UInt16 a_Port,
cNetwork::cListenCallbacksPtr a_ListenCallbacks,
cTCPLink::cCallbacksPtr a_LinkCallbacks
)
{
cServerHandleImplPtr res = cServerHandleImplPtr{new cServerHandleImpl(a_ListenCallbacks, a_LinkCallbacks)};
if (res->Listen(a_Port))
{
cNetworkSingleton::Get().AddServer(res);
}
else
{
a_ListenCallbacks->OnError(res->m_ErrorCode, res->m_ErrorMsg);
}
return res;
}
bool cServerHandleImpl::Listen(UInt16 a_Port)
{
// Set up the main socket:
// It should listen on IPv6 with IPv4 fallback, when available; IPv4 when IPv6 is not available.
bool NeedsTwoSockets = false;
int err;
evutil_socket_t MainSock = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
if (!IsValidSocket(MainSock))
{
// Failed to create IPv6 socket, create an IPv4 one instead:
err = EVUTIL_SOCKET_ERROR();
LOGD("Failed to create IPv6 MainSock: %d (%s)", err, evutil_socket_error_to_string(err));
MainSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (!IsValidSocket(MainSock))
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
Printf(m_ErrorMsg, "Cannot create socket for port %d: %s", a_Port, evutil_socket_error_to_string(m_ErrorCode));
return false;
}
// Bind to all interfaces:
sockaddr_in name;
memset(&name, 0, sizeof(name));
name.sin_family = AF_INET;
name.sin_port = ntohs(a_Port);
if (bind(MainSock, reinterpret_cast<const sockaddr *>(&name), sizeof(name)) != 0)
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
Printf(m_ErrorMsg, "Cannot bind IPv4 socket to port %d: %s", a_Port, evutil_socket_error_to_string(m_ErrorCode));
evutil_closesocket(MainSock);
return false;
}
}
else
{
// IPv6 socket created, switch it into "dualstack" mode:
UInt32 Zero = 0;
#ifdef _WIN32
// WinXP doesn't support this feature, so if the setting fails, create another socket later on:
int res = setsockopt(MainSock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char *>(&Zero), sizeof(Zero));
err = EVUTIL_SOCKET_ERROR();
NeedsTwoSockets = ((res == SOCKET_ERROR) && (err == WSAENOPROTOOPT));
LOGD("setsockopt(IPV6_V6ONLY) returned %d, err is %d (%s). %s",
res, err, evutil_socket_error_to_string(err),
NeedsTwoSockets ? "Second socket will be created" : "Second socket not needed"
);
#else
setsockopt(MainSock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char *>(&Zero), sizeof(Zero));
#endif
// Bind to all interfaces:
sockaddr_in6 name;
memset(&name, 0, sizeof(name));
name.sin6_family = AF_INET6;
name.sin6_port = ntohs(a_Port);
if (bind(MainSock, reinterpret_cast<const sockaddr *>(&name), sizeof(name)) != 0)
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
Printf(m_ErrorMsg, "Cannot bind IPv6 socket to port %d: %s", a_Port, evutil_socket_error_to_string(m_ErrorCode));
evutil_closesocket(MainSock);
return false;
}
}
if (evutil_make_socket_nonblocking(MainSock) != 0)
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
Printf(m_ErrorMsg, "Cannot make socket on port %d non-blocking: %s", a_Port, evutil_socket_error_to_string(m_ErrorCode));
evutil_closesocket(MainSock);
return false;
}
if (listen(MainSock, 0) != 0)
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
Printf(m_ErrorMsg, "Cannot listen on port %d: %s", a_Port, evutil_socket_error_to_string(m_ErrorCode));
evutil_closesocket(MainSock);
return false;
}
m_ConnListener = evconnlistener_new(cNetworkSingleton::Get().m_EventBase, Callback, this, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, 0, MainSock);
// If a secondary socket is required (WinXP dual-stack), create it here:
if (NeedsTwoSockets)
{
LOGD("Creating a second socket for IPv4");
evutil_socket_t SecondSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (IsValidSocket(SecondSock))
{
if (evutil_make_socket_nonblocking(SecondSock) == 0)
{
m_SecondaryConnListener = evconnlistener_new(cNetworkSingleton::Get().m_EventBase, Callback, this, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, 0, SecondSock);
}
else
{
err = EVUTIL_SOCKET_ERROR();
LOGD("evutil_make_socket_nonblocking() failed: %d, %s", err, evutil_socket_error_to_string(err));
}
}
else
{
err = EVUTIL_SOCKET_ERROR();
LOGD("socket(AF_INET, ...) failed: %d, %s", err, evutil_socket_error_to_string(err));
}
}
m_IsListening = true;
return true;
}
void cServerHandleImpl::Callback(evconnlistener * a_Listener, evutil_socket_t a_Socket, sockaddr * a_Addr, int a_Len, void * a_Self)
{
// Cast to true self:
cServerHandleImpl * Self = reinterpret_cast<cServerHandleImpl *>(a_Self);
ASSERT(Self != nullptr);
// Create a new cTCPLink for the incoming connection:
cTCPLinkImplPtr Link = std::make_shared<cTCPLinkImpl>(a_Socket, Self->m_LinkCallbacks, Self, a_Addr, a_Len);
{
cCSLock Lock(Self->m_CS);
Self->m_Connections.push_back(Link);
} // Lock(m_CS)
// Call the OnAccepted callback:
Self->m_ListenCallbacks->OnAccepted(*Link);
}
void cServerHandleImpl::RemoveLink(const cTCPLinkImpl * a_Link)
{
cCSLock Lock(m_CS);
for (auto itr = m_Connections.begin(), end = m_Connections.end(); itr != end; ++itr)
{
if (itr->get() == a_Link)
{
m_Connections.erase(itr);
return;
}
} // for itr - m_Connections[]
}
////////////////////////////////////////////////////////////////////////////////
// cNetwork:
bool cNetwork::Connect(
const AString & a_Host,
const UInt16 a_Port,
cNetwork::cConnectCallbacksPtr a_ConnectCallbacks,
cTCPLink::cCallbacksPtr a_LinkCallbacks
)
{
// Add a connection request to the queue:
cTCPLinkImplPtr Conn = cTCPLinkImpl::Connect(a_Host, a_Port, a_LinkCallbacks, a_ConnectCallbacks);
return (Conn != nullptr);
}
cServerHandlePtr cNetwork::Listen(
const UInt16 a_Port,
cNetwork::cListenCallbacksPtr a_ListenCallbacks,
cTCPLink::cCallbacksPtr a_LinkCallbacks
)
{
return cServerHandleImpl::Listen(a_Port, a_ListenCallbacks, a_LinkCallbacks);
}
bool cNetwork::HostnameToIP(
const AString & a_Hostname,
cNetwork::cResolveNameCallbacksPtr a_Callbacks
)
{
return cNetworkSingleton::Get().HostnameToIP(a_Hostname, a_Callbacks);
}
bool cNetwork::IPToHostName(
const AString & a_IP,
cNetwork::cResolveNameCallbacksPtr a_Callbacks
)
{
return cNetworkSingleton::Get().IPToHostName(a_IP, a_Callbacks);
}
////////////////////////////////////////////////////////////////////////////////
// cTCPLink:
cTCPLink::cTCPLink(cCallbacksPtr a_Callbacks):
m_Callbacks(a_Callbacks)
{
}
////////////////////////////////////////////////////////////////////////////////
// cNetworkSingleton:
cNetworkSingleton::cNetworkSingleton(void)
{
// Windows: initialize networking:
#ifdef _WIN32
WSADATA wsaData;
memset(&wsaData, 0, sizeof(wsaData));
int res = WSAStartup (MAKEWORD(2, 2), &wsaData);
if (res != 0)
{
int err = WSAGetLastError();
LOGWARNING("WSAStartup failed: %d, WSAGLE = %d (%s)", res, err, evutil_socket_error_to_string(err));
exit(1);
}
#endif // _WIN32
// Initialize LibEvent logging:
event_set_log_callback(LogCallback);
// Initialize threading:
#if defined(EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED)
evthread_use_windows_threads();
#elif defined(EVTHREAD_USE_PTHREADS_IMPLEMENTED)
evthread_use_pthreads();
#else
#error No threading implemented for EVTHREAD
#endif
// Create the main event_base:
m_EventBase = event_base_new();
if (m_EventBase == nullptr)
{
LOGERROR("Failed to initialize LibEvent. The server will now terminate.");
abort();
}
// Create the DNS lookup helper:
m_DNSBase = evdns_base_new(m_EventBase, 1);
if (m_DNSBase == nullptr)
{
LOGERROR("Failed to initialize LibEvent's DNS subsystem. The server will now terminate.");
abort();
}
// Create the event loop thread:
std::thread EventLoopThread(RunEventLoop, this);
EventLoopThread.detach();
}
cNetworkSingleton & cNetworkSingleton::Get(void)
{
static cNetworkSingleton Instance;
return Instance;
}
bool cNetworkSingleton::HostnameToIP(
const AString & a_Hostname,
cNetwork::cResolveNameCallbacksPtr a_Callbacks
)
{
try
{
cCSLock Lock(m_CS);
m_HostnameLookups.push_back(std::make_shared<cHostnameLookup>(a_Hostname, a_Callbacks));
}
catch (...)
{
return false;
}
return true;
}
bool cNetworkSingleton::IPToHostName(
const AString & a_IP,
cNetwork::cResolveNameCallbacksPtr a_Callbacks
)
{
try
{
cCSLock Lock(m_CS);
m_IPLookups.push_back(std::make_shared<cIPLookup>(a_IP, a_Callbacks));
}
catch (...)
{
return false;
}
return true;
}
void cNetworkSingleton::LogCallback(int a_Severity, const char * a_Msg)
{
switch (a_Severity)
{
case _EVENT_LOG_DEBUG: LOGD ("LibEvent: %s", a_Msg); break;
case _EVENT_LOG_MSG: LOG ("LibEvent: %s", a_Msg); break;
case _EVENT_LOG_WARN: LOGWARNING("LibEvent: %s", a_Msg); break;
case _EVENT_LOG_ERR: LOGERROR ("LibEvent: %s", a_Msg); break;
default:
{
LOGWARNING("LibEvent: Unknown log severity (%d): %s", a_Severity, a_Msg);
break;
}
}
}
void cNetworkSingleton::RunEventLoop(cNetworkSingleton * a_Self)
{
event_base_loop(a_Self->m_EventBase, EVLOOP_NO_EXIT_ON_EMPTY);
}
void cNetworkSingleton::RemoveHostnameLookup(const cHostnameLookup * a_HostnameLookup)
{
cCSLock Lock(m_CS);
for (auto itr = m_HostnameLookups.begin(), end = m_HostnameLookups.end(); itr != end; ++itr)
{
if (itr->get() == a_HostnameLookup)
{
m_HostnameLookups.erase(itr);
return;
}
} // for itr - m_HostnameLookups[]
}
void cNetworkSingleton::RemoveIPLookup(const cIPLookup * a_IPLookup)
{
cCSLock Lock(m_CS);
for (auto itr = m_IPLookups.begin(), end = m_IPLookups.end(); itr != end; ++itr)
{
if (itr->get() == a_IPLookup)
{
m_IPLookups.erase(itr);
return;
}
} // for itr - m_IPLookups[]
}
void cNetworkSingleton::AddLink(cTCPLinkImplPtr a_Link)
{
cCSLock Lock(m_CS);
m_Connections.push_back(a_Link);
}
void cNetworkSingleton::RemoveLink(const cTCPLinkImpl * a_Link)
{
cCSLock Lock(m_CS);
for (auto itr = m_Connections.begin(), end = m_Connections.end(); itr != end; ++itr)
{
if (itr->get() == a_Link)
{
m_Connections.erase(itr);
return;
}
} // for itr - m_Connections[]
}
void cNetworkSingleton::AddServer(cServerHandleImplPtr a_Server)
{
cCSLock Lock(m_CS);
m_Servers.push_back(a_Server);
}
void cNetworkSingleton::RemoveServer(const cServerHandleImpl * a_Server)
{
cCSLock Lock(m_CS);
for (auto itr = m_Servers.begin(), end = m_Servers.end(); itr != end; ++itr)
{
if (itr->get() == a_Server)
{
m_Servers.erase(itr);
return;
}
} // for itr - m_Servers[]
}
|
// Copyright (c) 2010 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 <sstream>
#include <string>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
namespace {
class ResourceDispatcherTest : public UITest {
public:
void CheckTitleTest(const std::wstring& file,
const std::wstring& expected_title,
int expected_navigations) {
NavigateToURLBlockUntilNavigationsComplete(
URLRequestMockHTTPJob::GetMockUrl(FilePath::FromWStringHack(file)),
expected_navigations);
EXPECT_EQ(expected_title, GetActiveTabTitle());
}
protected:
ResourceDispatcherTest() : UITest() {
dom_automation_enabled_ = true;
}
};
TEST_F(ResourceDispatcherTest, SniffHTMLWithNoContentType) {
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0", 1);
}
TEST_F(ResourceDispatcherTest, RespectNoSniffDirective) {
CheckTitleTest(L"nosniff-test.html", L"", 1);
}
TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromTextPlain) {
CheckTitleTest(L"content-sniffer-test1.html", L"", 1);
}
TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromImageGIF) {
CheckTitleTest(L"content-sniffer-test2.html", L"", 1);
}
TEST_F(ResourceDispatcherTest, SniffNoContentTypeNoData) {
CheckTitleTest(L"content-sniffer-test3.html",
L"Content Sniffer Test 3", 1);
EXPECT_EQ(1, GetTabCount());
// Make sure the download shelf is not showing.
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
bool visible = false;
ASSERT_TRUE(browser->IsShelfVisible(&visible));
EXPECT_FALSE(visible);
}
TEST_F(ResourceDispatcherTest, ContentDispositionEmpty) {
CheckTitleTest(L"content-disposition-empty.html", L"success", 1);
}
TEST_F(ResourceDispatcherTest, ContentDispositionInline) {
CheckTitleTest(L"content-disposition-inline.html", L"success", 1);
}
// Test for bug #1091358.
// Flaky: http://crbug.com/62595
TEST_F(ResourceDispatcherTest, FLAKY_SyncXMLHttpRequest) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL(
"files/sync_xmlhttprequest.html")));
// Let's check the XMLHttpRequest ran successfully.
bool success = false;
EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send(DidSyncRequestSucceed());",
&success));
EXPECT_TRUE(success);
}
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_Disallowed) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL(
"files/sync_xmlhttprequest_disallowed.html")));
// Let's check the XMLHttpRequest ran successfully.
bool success = false;
EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send(DidSucceed());",
&success));
EXPECT_TRUE(success);
}
// Test for bug #1159553 -- A synchronous xhr (whose content-type is
// downloadable) would trigger download and hang the renderer process,
// if executed while navigating to a new page.
// Disabled -- http://code.google.com/p/chromium/issues/detail?id=56264
TEST_F(ResourceDispatcherTest, DISABLED_SyncXMLHttpRequest_DuringUnload) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL(
"files/sync_xmlhttprequest_during_unload.html")));
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"sync xhr on unload", tab_title);
// Navigate to a new page, to dispatch unload event and trigger xhr.
// (the bug would make this step hang the renderer).
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL("files/title2.html")));
// Check that the new page got loaded, and that no download was triggered.
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"Title Of Awesomeness", tab_title);
bool shelf_is_visible = false;
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
EXPECT_TRUE(browser->IsShelfVisible(&shelf_is_visible));
EXPECT_FALSE(shelf_is_visible);
}
// Tests that onunload is run for cross-site requests. (Bug 1114994)
TEST_F(ResourceDispatcherTest, CrossSiteOnunloadCookie) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url(test_server.GetURL("files/onunload_cookie.html"));
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"set cookie on unload", tab_title);
// Navigate to a new cross-site page, to dispatch unload event and set the
// cookie.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0", 1);
// Check that the cookie was set.
std::string value_result;
ASSERT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
ASSERT_FALSE(value_result.empty());
ASSERT_STREQ("foo", value_result.c_str());
}
#if !defined(OS_MACOSX)
// Tests that the onbeforeunload and onunload logic is shortcutted if the old
// renderer is gone. In that case, we don't want to wait for the old renderer
// to run the handlers.
// We need to disable this on Mac because the crash causes the OS CrashReporter
// process to kick in to analyze the poor dead renderer. Unfortunately, if the
// app isn't stripped of debug symbols, this takes about five minutes to
// complete and isn't conducive to quick turnarounds. As we don't currently
// strip the app on the build bots, this is bad times.
TEST_F(ResourceDispatcherTest, CrossSiteAfterCrash) {
// This test only works in multi-process mode
if (in_process_renderer())
return;
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
// Cause the renderer to crash.
#if defined(OS_WIN) || defined(USE_LINUX_BREAKPAD)
expected_crashes_ = 1;
#endif
ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutCrashURL)));
// Wait for browser to notice the renderer crash.
PlatformThread::Sleep(sleep_timeout_ms());
// Navigate to a new cross-site page. The browser should not wait around for
// the old renderer's on{before}unload handlers to run.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0", 1);
}
#endif // !defined(OS_MACOSX)
// Tests that cross-site navigations work when the new page does not go through
// the BufferedEventHandler (e.g., non-http{s} URLs). (Bug 1225872)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationNonBuffered) {
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
// Start with an HTTP page.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0", 1);
// Now load a file:// page, which does not use the BufferedEventHandler.
// Make sure that the page loads and displays a title, and doesn't get stuck.
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("title2.html");
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(net::FilePathToFileURL(test_file)));
EXPECT_EQ(L"Title Of Awesomeness", GetActiveTabTitle());
}
// Tests that a cross-site navigation to an error page (resulting in the link
// doctor page) still runs the onunload handler and can support navigations
// away from the link doctor page. (Bug 1235537)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationErrorPage) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url(test_server.GetURL("files/onunload_cookie.html"));
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"set cookie on unload", tab_title);
// Navigate to a new cross-site URL that results in an error page.
// TODO(creis): If this causes crashes or hangs, it might be for the same
// reason as ErrorPageTest::DNSError. See bug 1199491 and
// http://crbug.com/22877.
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURLBlockUntilNavigationsComplete(
GURL(URLRequestFailedDnsJob::kTestUrl), 2));
EXPECT_NE(L"set cookie on unload", GetActiveTabTitle());
// Check that the cookie was set, meaning that the onunload handler ran.
std::string value_result;
EXPECT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
EXPECT_FALSE(value_result.empty());
EXPECT_STREQ("foo", value_result.c_str());
// Check that renderer-initiated navigations still work. In a previous bug,
// the ResourceDispatcherHost would think that such navigations were
// cross-site, because we didn't clean up from the previous request. Since
// TabContents was in the NORMAL state, it would ignore the attempt to run
// the onunload handler, and the navigation would fail.
// (Test by redirecting to javascript:window.location='someURL'.)
GURL test_url(test_server.GetURL("files/title2.html"));
std::string redirect_url = "javascript:window.location='" +
test_url.possibly_invalid_spec() + "'";
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(GURL(redirect_url)));
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"Title Of Awesomeness", tab_title);
}
TEST_F(ResourceDispatcherTest, CrossOriginRedirectBlocked) {
// We expect the following URL requests from this test:
// 1- http://mock.http/cross-origin-redirect-blocked.html
// 2- http://mock.http/redirect-to-title2.html
// 3- http://mock.http/title2.html
//
// If the redirect in #2 were not blocked, we'd also see a request
// for http://mock.http:4000/title2.html, and the title would be different.
CheckTitleTest(L"cross-origin-redirect-blocked.html",
L"Title Of More Awesomeness", 2);
}
// Tests that ResourceDispatcherHostRequestInfo is updated correctly on failed
// requests, to prevent calling Read on a request that has already failed.
// See bug 40250.
TEST_F(ResourceDispatcherTest, CrossSiteFailedRequest) {
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
// Visit another URL first to trigger a cross-site navigation.
GURL url(chrome::kChromeUINewTabURL);
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));
// Visit a URL that fails without calling ResourceDispatcherHost::Read.
GURL broken_url("chrome://theme");
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(broken_url));
// Make sure the navigation finishes.
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"chrome://theme/ is not available", tab_title);
}
} // namespace
Marking the ResourceDispatcherTest.SyncXMLHttpRequest_Disallowed as flaky
Bug=62776
TBR=jcivelli
Review URL: http://codereview.chromium.org/4646008
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@65763 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
// Copyright (c) 2010 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 <sstream>
#include <string>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
namespace {
class ResourceDispatcherTest : public UITest {
public:
void CheckTitleTest(const std::wstring& file,
const std::wstring& expected_title,
int expected_navigations) {
NavigateToURLBlockUntilNavigationsComplete(
URLRequestMockHTTPJob::GetMockUrl(FilePath::FromWStringHack(file)),
expected_navigations);
EXPECT_EQ(expected_title, GetActiveTabTitle());
}
protected:
ResourceDispatcherTest() : UITest() {
dom_automation_enabled_ = true;
}
};
TEST_F(ResourceDispatcherTest, SniffHTMLWithNoContentType) {
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0", 1);
}
TEST_F(ResourceDispatcherTest, RespectNoSniffDirective) {
CheckTitleTest(L"nosniff-test.html", L"", 1);
}
TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromTextPlain) {
CheckTitleTest(L"content-sniffer-test1.html", L"", 1);
}
TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromImageGIF) {
CheckTitleTest(L"content-sniffer-test2.html", L"", 1);
}
TEST_F(ResourceDispatcherTest, SniffNoContentTypeNoData) {
CheckTitleTest(L"content-sniffer-test3.html",
L"Content Sniffer Test 3", 1);
EXPECT_EQ(1, GetTabCount());
// Make sure the download shelf is not showing.
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
bool visible = false;
ASSERT_TRUE(browser->IsShelfVisible(&visible));
EXPECT_FALSE(visible);
}
TEST_F(ResourceDispatcherTest, ContentDispositionEmpty) {
CheckTitleTest(L"content-disposition-empty.html", L"success", 1);
}
TEST_F(ResourceDispatcherTest, ContentDispositionInline) {
CheckTitleTest(L"content-disposition-inline.html", L"success", 1);
}
// Test for bug #1091358.
// Flaky: http://crbug.com/62595
TEST_F(ResourceDispatcherTest, FLAKY_SyncXMLHttpRequest) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL(
"files/sync_xmlhttprequest.html")));
// Let's check the XMLHttpRequest ran successfully.
bool success = false;
EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send(DidSyncRequestSucceed());",
&success));
EXPECT_TRUE(success);
}
// http://code.google.com/p/chromium/issues/detail?id=62776
TEST_F(ResourceDispatcherTest, FLAKY_SyncXMLHttpRequest_Disallowed) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL(
"files/sync_xmlhttprequest_disallowed.html")));
// Let's check the XMLHttpRequest ran successfully.
bool success = false;
EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send(DidSucceed());",
&success));
EXPECT_TRUE(success);
}
// Test for bug #1159553 -- A synchronous xhr (whose content-type is
// downloadable) would trigger download and hang the renderer process,
// if executed while navigating to a new page.
// Disabled -- http://code.google.com/p/chromium/issues/detail?id=56264
TEST_F(ResourceDispatcherTest, DISABLED_SyncXMLHttpRequest_DuringUnload) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL(
"files/sync_xmlhttprequest_during_unload.html")));
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"sync xhr on unload", tab_title);
// Navigate to a new page, to dispatch unload event and trigger xhr.
// (the bug would make this step hang the renderer).
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL("files/title2.html")));
// Check that the new page got loaded, and that no download was triggered.
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"Title Of Awesomeness", tab_title);
bool shelf_is_visible = false;
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
EXPECT_TRUE(browser->IsShelfVisible(&shelf_is_visible));
EXPECT_FALSE(shelf_is_visible);
}
// Tests that onunload is run for cross-site requests. (Bug 1114994)
TEST_F(ResourceDispatcherTest, CrossSiteOnunloadCookie) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url(test_server.GetURL("files/onunload_cookie.html"));
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"set cookie on unload", tab_title);
// Navigate to a new cross-site page, to dispatch unload event and set the
// cookie.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0", 1);
// Check that the cookie was set.
std::string value_result;
ASSERT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
ASSERT_FALSE(value_result.empty());
ASSERT_STREQ("foo", value_result.c_str());
}
#if !defined(OS_MACOSX)
// Tests that the onbeforeunload and onunload logic is shortcutted if the old
// renderer is gone. In that case, we don't want to wait for the old renderer
// to run the handlers.
// We need to disable this on Mac because the crash causes the OS CrashReporter
// process to kick in to analyze the poor dead renderer. Unfortunately, if the
// app isn't stripped of debug symbols, this takes about five minutes to
// complete and isn't conducive to quick turnarounds. As we don't currently
// strip the app on the build bots, this is bad times.
TEST_F(ResourceDispatcherTest, CrossSiteAfterCrash) {
// This test only works in multi-process mode
if (in_process_renderer())
return;
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
// Cause the renderer to crash.
#if defined(OS_WIN) || defined(USE_LINUX_BREAKPAD)
expected_crashes_ = 1;
#endif
ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutCrashURL)));
// Wait for browser to notice the renderer crash.
PlatformThread::Sleep(sleep_timeout_ms());
// Navigate to a new cross-site page. The browser should not wait around for
// the old renderer's on{before}unload handlers to run.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0", 1);
}
#endif // !defined(OS_MACOSX)
// Tests that cross-site navigations work when the new page does not go through
// the BufferedEventHandler (e.g., non-http{s} URLs). (Bug 1225872)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationNonBuffered) {
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
// Start with an HTTP page.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0", 1);
// Now load a file:// page, which does not use the BufferedEventHandler.
// Make sure that the page loads and displays a title, and doesn't get stuck.
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("title2.html");
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(net::FilePathToFileURL(test_file)));
EXPECT_EQ(L"Title Of Awesomeness", GetActiveTabTitle());
}
// Tests that a cross-site navigation to an error page (resulting in the link
// doctor page) still runs the onunload handler and can support navigations
// away from the link doctor page. (Bug 1235537)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationErrorPage) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url(test_server.GetURL("files/onunload_cookie.html"));
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"set cookie on unload", tab_title);
// Navigate to a new cross-site URL that results in an error page.
// TODO(creis): If this causes crashes or hangs, it might be for the same
// reason as ErrorPageTest::DNSError. See bug 1199491 and
// http://crbug.com/22877.
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURLBlockUntilNavigationsComplete(
GURL(URLRequestFailedDnsJob::kTestUrl), 2));
EXPECT_NE(L"set cookie on unload", GetActiveTabTitle());
// Check that the cookie was set, meaning that the onunload handler ran.
std::string value_result;
EXPECT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
EXPECT_FALSE(value_result.empty());
EXPECT_STREQ("foo", value_result.c_str());
// Check that renderer-initiated navigations still work. In a previous bug,
// the ResourceDispatcherHost would think that such navigations were
// cross-site, because we didn't clean up from the previous request. Since
// TabContents was in the NORMAL state, it would ignore the attempt to run
// the onunload handler, and the navigation would fail.
// (Test by redirecting to javascript:window.location='someURL'.)
GURL test_url(test_server.GetURL("files/title2.html"));
std::string redirect_url = "javascript:window.location='" +
test_url.possibly_invalid_spec() + "'";
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(GURL(redirect_url)));
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"Title Of Awesomeness", tab_title);
}
TEST_F(ResourceDispatcherTest, CrossOriginRedirectBlocked) {
// We expect the following URL requests from this test:
// 1- http://mock.http/cross-origin-redirect-blocked.html
// 2- http://mock.http/redirect-to-title2.html
// 3- http://mock.http/title2.html
//
// If the redirect in #2 were not blocked, we'd also see a request
// for http://mock.http:4000/title2.html, and the title would be different.
CheckTitleTest(L"cross-origin-redirect-blocked.html",
L"Title Of More Awesomeness", 2);
}
// Tests that ResourceDispatcherHostRequestInfo is updated correctly on failed
// requests, to prevent calling Read on a request that has already failed.
// See bug 40250.
TEST_F(ResourceDispatcherTest, CrossSiteFailedRequest) {
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
ASSERT_TRUE(tab.get());
// Visit another URL first to trigger a cross-site navigation.
GURL url(chrome::kChromeUINewTabURL);
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));
// Visit a URL that fails without calling ResourceDispatcherHost::Read.
GURL broken_url("chrome://theme");
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(broken_url));
// Make sure the navigation finishes.
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"chrome://theme/ is not available", tab_title);
}
} // namespace
|
#include "ex14_16_String.h"
#include <algorithm>
#include <cstring>
std::allocator<char> String::alloc;
std::pair<char*, char*> String::alloc_n_copy(const char *a, const char *b) {
auto newdata = alloc.allocate(b - a + 1);
alloc.construct(newdata + (b - a), '\0');
return{ newdata, std::uninitialized_copy(a, b, newdata) };
}
void String::free() {
if (elements) {
std::for_each(elements, end, [](char& c) { alloc.destroy(&c); });
alloc.deallocate(elements, end - elements);
}
}
String::String(const char *c) {
const char *ce = c;
while (*ce)
++ce;
auto newdata = alloc_n_copy(c, ce);
elements = newdata.first;
end = newdata.second;
}
String::String(const String& s) {
auto newdata = alloc_n_copy(s.elements, s.end);
elements = newdata.first;
end = newdata.second;
}
String& String::operator=(const String &s) {
auto newdata = alloc_n_copy(s.elements, s.end);
free();
elements = newdata.first;
end = newdata.second;
return *this;
}
String::~String() {
free();
}
bool operator==(const String& lhs, const String& rhs) {
return !strcmp(lhs.elements, rhs.elements);
}
bool operator!=(const String& lhs, const String& rhs) {
return !(lhs == rhs);
}
Delete ex14_16_String.cpp
|
// $Id: logStream.C,v 1.15 2000/05/29 23:27:03 amoll Exp $
#include <BALL/COMMON/logStream.h>
#include <BALL/CONCEPT/notification.h>
#include <sys/time.h>
#include <stdio.h>
#define BUFFER_LENGTH 32768
using std::endl;
using std::ostream;
using std::streambuf;
using std::cout;
using std::cerr;
#ifdef BALL_HAS_ANSI_IOSTREAM
# define BALL_IOS std::basic_ios<char>
# define BALL_OSTREAM std::ostream
#else
# define BALL_IOS std::ios
# define BALL_OSTREAM std::ostream
#endif
namespace BALL
{
LogStreamBuf::LogStreamBuf()
: streambuf(),
level_(0),
tmp_level_(0),
incomplete_line_()
{
pbuf_ = new char [BUFFER_LENGTH];
streambuf::setp(pbuf_, pbuf_ + BUFFER_LENGTH - 1);
}
LogStreamBuf::~LogStreamBuf()
{
sync();
delete [] pbuf_;
}
void LogStreamBuf::dump(ostream& stream)
{
char buf[BUFFER_LENGTH];
Size line;
for (line = loglines_.size(); line > 0; --line)
{
strftime(&(buf[0]), BUFFER_LENGTH - 1, "%d.%m.%Y %T ", localtime(&(loglines_[line - 1].time)));
stream << buf << "[" << loglines_[line - 1].level
<< "]:" << loglines_[line - 1].text.c_str() << endl;
}
}
int LogStreamBuf::sync()
{
static char buf[BUFFER_LENGTH];
// sync our streambuffer...
if (pptr() != pbase())
{
char* line_start = pbase();
char* line_end = pbase();
while (line_end <= pptr())
{
// search for the first end of line
for (; line_end < pptr() && *line_end != '\n'; line_end++);
if (line_end >= pptr())
{
// copy the incomplete line to the incomplete_line_ buffer
strncpy(&(buf[0]), line_start, line_end - line_start + 1);
buf[line_end - line_start] = '\0';
incomplete_line_ += &(buf[0]);
// mark everything as read
line_end = pptr() + 1;
} else {
memcpy(&(buf[0]), line_start, line_end - line_start + 1);
buf[line_end - line_start] = '\0';
// assemble the string to be written
// (consider leftovers of the last buffer from incomplete_line_)
string outstring = incomplete_line_;
incomplete_line_ = "";
outstring += &(buf[0]);
// if there are any streams in our list, we
// copy the line into that streams, too and flush them
using ::std::list;
list<StreamStruct>::iterator list_it = stream_list_.begin();
for (; list_it != stream_list_.end(); ++list_it)
{
// if the stream is open for that level, write to it...
if ((list_it->min_level <= tmp_level_) && (list_it->max_level >= tmp_level_))
{
*(list_it->stream) << expandPrefix_(list_it->prefix, tmp_level_, time(0)).c_str()
<< outstring.c_str() << endl;
if (list_it->target != 0)
{
list_it->target->notify();
}
}
}
// update the line pointers (increment both)
line_start = ++line_end;
// remove cr/lf from the end of the line
while (outstring[outstring.size() - 1] == 10 || outstring[outstring.size() - 1] == 13)
{
outstring.erase(outstring.end());
}
// store the line
Logline logline;
logline.text = outstring;
logline.level = tmp_level_;
logline.time = time(0);
// store the new line
loglines_.push_back(logline);
// reset tmp_level_ to the previous level
// (needed for LogStream::level() only)
tmp_level_ = level_;
}
}
// remove all processed lines from the buffer
pbump((int)(pbase() - pptr()));
}
return 0;
}
string LogStreamBuf::expandPrefix_(const string& prefix, const int& level, const time_t& time) const
{
Size index = 0;
Size copied_index = 0;
string result("");
while ((index = prefix.find("%", index)) != string::npos)
{
// append any constant parts of the string to the result
if (copied_index < index)
{
result.append(prefix.substr(copied_index, index - copied_index));
copied_index = index;
}
if (index < prefix.size())
{
char buffer[64];
char* buf = &(buffer[0]);
switch (prefix[index + 1])
{
case '%': // append a '%' (escape sequence)
result.append("%");
break;
case 'l': // append the loglevel
sprintf(buf, "%d", level);
result.append(buf);
break;
case 'y': // append the message type (error/warning/information)
if (level >= LogStream::ERROR)
{
result.append("ERROR");
} else if (level >= LogStream::WARNING) {
result.append("WARNING");
} else if (level >= LogStream::INFORMATION) {
result.append("INFORMATION");
} else {
result.append("LOG"); }
break;
case 'T': // time: HH:MM:SS
strftime(buf, BUFFER_LENGTH - 1, "%T", localtime(&time));
result.append(buf);
break;
case 't': // time: HH:MM
strftime(buf, BUFFER_LENGTH - 1, "%R", localtime(&time));
result.append(buf);
break;
case 'D': // date: DD.MM.YYYY
strftime(buf, BUFFER_LENGTH - 1, "%d.%m.%Y", localtime(&time));
result.append(buf);
break;
case 'd': // date: DD.MM.
strftime(buf, BUFFER_LENGTH - 1, "%d.%m.", localtime(&time));
result.append(buf);
break;
case 'S': // time+date: DD.MM.YYYY, HH:MM:SS
strftime(buf, BUFFER_LENGTH - 1, "%d.%m.%Y, %R", localtime(&time));
result.append(buf);
break;
case 's': // time+date: DD.MM., HH:MM
strftime(buf, BUFFER_LENGTH - 1, "%d.%m., %T", localtime(&time));
result.append(buf);
break;
default:
break;
}
index += 2;
copied_index += 2;
}
}
if (copied_index < prefix.size()) {
result.append(prefix.substr(copied_index, prefix.size() - copied_index));
}
return result;
}
LogStreamNotifier::LogStreamNotifier()
{
}
LogStreamNotifier::LogStreamNotifier(const LogStream::Target& target)
{
NotificationRegister(*this, const_cast<LogStream::Target &>(target));
}
LogStreamNotifier::~LogStreamNotifier()
{
NotificationUnregister(*this);
}
void LogStreamNotifier::notify() const
{
Notify(const_cast<LogStreamNotifier&>(*this));
}
// keep the given buffer
LogStream::LogStream(LogStreamBuf* buf)
: BALL_IOS(buf),
BALL_OSTREAM(buf),
delete_buffer_(false)
{
}
// create a new buffer
LogStream::LogStream(const bool& associate_stdio)
: BALL_IOS(new LogStreamBuf),
BALL_OSTREAM(new LogStreamBuf),
delete_buffer_(true)
{
if (associate_stdio == true)
{
// associate cout to informations and warnings,
// cerr to errors by default
insert(std::cout, INFORMATION, ERROR - 1);
insert(std::cerr, ERROR);
}
}
// remove the streambuffer
LogStream::~LogStream()
{
if (delete_buffer_)
{
delete rdbuf();
}
}
void LogStream::clear()
{
rdbuf()->loglines_.clear();
}
void LogStream::insert(ostream& stream, const int& min_level, const int& max_level)
{
// return if no LogStreamBuf is defined!
if (rdbuf() == 0)
{
return;
}
// first, check whether the stream is already associated (avoid
// multiple insertions)
using std::list;
list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin();
for (; list_it != rdbuf()->stream_list_.end(); ++list_it)
{
if ((*list_it).stream == &stream)
{
return;
}
}
// we didn`t find it - create a new entry in the list
LogStreamBuf::StreamStruct s_struct;
s_struct.min_level = min_level;
s_struct.max_level = max_level;
s_struct.stream = &stream;
rdbuf()->stream_list_.push_back(s_struct);
}
void LogStream::remove(ostream& stream)
{
// return if no LogStreamBuf is defined!
if (rdbuf() == 0)
{
return;
}
// find the stream in the LogStreamBuf's list
using std::list;
list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin();
for (; list_it != rdbuf()->stream_list_.end(); ++list_it)
{
if ((*list_it).stream == &stream)
{
// remove the stream - iterator becomes invalid, so exit
rdbuf()->stream_list_.erase(list_it);
break;
}
}
// if the stream is not found nothing happens!
}
void LogStream::insertNotification(const ostream& s, const LogStream::Target& target)
{
// return if no LogStreamBuf is defined!
if (rdbuf() == 0)
{
return;
}
// find the stream in the LogStreamBuf's list
using std::list;
list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin();
for (; list_it != rdbuf()->stream_list_.end(); ++list_it)
{
if (list_it->stream == &s)
{
// set the notification target
list_it->target = new LogStreamNotifier(const_cast<LogStream::Target&>(target));
break;
}
}
// if the stream is not found nothing happens!
}
void LogStream::removeNotification(const ostream& s)
{
// return if no LogStreamBuf is defined!
if (rdbuf() == 0)
{
return;
}
// find the stream in the LogStreamBuf's list
using std::list;
list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin();
for (; list_it != rdbuf()->stream_list_.end(); ++list_it)
{
if (list_it->stream == &s)
{
// destroy and remove the notification target
delete list_it->target;
list_it->target = 0;
break;
}
}
// if the stream is not found nothing happens!
}
void LogStream::setMinLevel(const ostream& stream, const int& level)
{
// return if no LogStreamBuf is defined!
if (rdbuf() == 0)
{
return;
}
// find the stream in the LogStreamBuf's list
using std::list;
list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin();
for (; list_it != rdbuf()->stream_list_.end(); ++list_it)
{
if ((*list_it).stream == &stream)
{
// change the streams min_level and exit the loop
(*list_it).min_level = level;
break;
}
}
}
void LogStream::setMaxLevel(const ostream& stream, const int& level)
{
// return if no LogStreamBuf is defined!
if (rdbuf() == 0)
{
return;
}
// find the stream in the LogStreamBuf's list:
// iterate over the list until you find the stream`s pointer
using std::list;
list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin();
for (; list_it != rdbuf()->stream_list_.end(); ++list_it)
{
if ((*list_it).stream == &stream)
{
// change the streams max_level and exit the loop
(*list_it).max_level = level;
break;
}
}
}
void LogStream::setPrefix(const ostream& s, const string& prefix)
{
// return if no LogStreamBuf is defined!
if (rdbuf() == 0)
{
return;
}
// find the stream in the LogStreamBuf's list:
// iterate over the list until you find the stream`s pointer
using std::list;
list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin();
for (; list_it != rdbuf()->stream_list_.end(); ++list_it)
{
if ((*list_it).stream == &s)
{
// change the streams max_level and exit the loop
(*list_it).prefix = prefix;
return;
}
}
}
Size LogStream::getNumberOfLines(const int& min_level, const int& max_level) const
{
// cast this to const, to access non const method rdbuf() which
// is usually const, but declared non const
LogStream* non_const_this = const_cast<LogStream*>(this);
// if rdbuf() is NULL, return
if (non_const_this->rdbuf() == 0)
{
return 0;
}
// iterate over all loglines and count the lines of interest
vector<LogStreamBuf::Logline>::iterator it = non_const_this->rdbuf()->loglines_.begin();
Size count = 0;
for (; it != non_const_this->rdbuf()->loglines_.end(); ++it)
{
if ((*it).level >= min_level && (*it).level <= max_level)
{
count++;
}
}
return count;
}
string LogStream::getLineText(const Index& index) const
{
if ((signed)getNumberOfLines() < index)
{
return "";
}
LogStream* non_const_this = const_cast<LogStream*>(this);
if (non_const_this->rdbuf() == 0)
{
return "";
}
return non_const_this->rdbuf()->loglines_[index].text;
}
int LogStream::getLineLevel(const Index& index) const
{
if ((signed)getNumberOfLines() < index)
{
return -1;
}
LogStream* non_const_this = const_cast<LogStream*>(this);
if (non_const_this->rdbuf() == 0)
{
return -1;
}
return non_const_this->rdbuf()->loglines_[index].level;
}
time_t LogStream::getLineTime(const Index& index) const
{
if ((signed)getNumberOfLines() < index)
{
return 0;
}
LogStream* non_const_this = const_cast<LogStream*>(this);
if (non_const_this->rdbuf() == 0)
{
return 0;
}
return non_const_this->rdbuf()->loglines_[index].time;
}
list<int> LogStream::filterLines(const int& min_level = INT_MIN, const int& max_level = INT_MAX,
const time_t& earliest = 0, const time_t& latest = LONG_MAX, const string& s = "") const
{
using std::list;
list<int> list_indices;
Position pos = 0;
LogStreamBuf* log = const_cast<LogStream*>(this)->rdbuf();
while (pos < log->loglines_.size() &&
log->loglines_[pos].time < earliest)
{
pos++;
}
while (pos < log->loglines_.size() &&
log->loglines_[pos].time <= latest)
{
if (log->loglines_[pos].level >= min_level &&
log->loglines_[pos].level <= max_level)
{
if (s.length() > 0)
{
if (log->loglines_[pos].text.find(s, 0) != string::npos )
{
list_indices.push_back(pos);
}
}
else
{
list_indices.push_back(pos);
}
}
pos++;
}
return list_indices;
}
// global default logstream
LogStream Log(true);
# ifdef BALL_NO_INLINE_FUNCTIONS
# include <BALL/COMMON/logStream.iC>
# endif
} // namespace BALL
fixed: repeting default arguments is not allowed in the function definition
// $Id: logStream.C,v 1.16 2000/05/30 18:27:08 oliver Exp $
#include <BALL/COMMON/logStream.h>
#include <BALL/CONCEPT/notification.h>
#include <sys/time.h>
#include <stdio.h>
#define BUFFER_LENGTH 32768
using std::endl;
using std::ostream;
using std::streambuf;
using std::cout;
using std::cerr;
#ifdef BALL_HAS_ANSI_IOSTREAM
# define BALL_IOS std::basic_ios<char>
# define BALL_OSTREAM std::ostream
#else
# define BALL_IOS std::ios
# define BALL_OSTREAM std::ostream
#endif
namespace BALL
{
LogStreamBuf::LogStreamBuf()
: streambuf(),
level_(0),
tmp_level_(0),
incomplete_line_()
{
pbuf_ = new char [BUFFER_LENGTH];
streambuf::setp(pbuf_, pbuf_ + BUFFER_LENGTH - 1);
}
LogStreamBuf::~LogStreamBuf()
{
sync();
delete [] pbuf_;
}
void LogStreamBuf::dump(ostream& stream)
{
char buf[BUFFER_LENGTH];
Size line;
for (line = loglines_.size(); line > 0; --line)
{
strftime(&(buf[0]), BUFFER_LENGTH - 1, "%d.%m.%Y %T ", localtime(&(loglines_[line - 1].time)));
stream << buf << "[" << loglines_[line - 1].level
<< "]:" << loglines_[line - 1].text.c_str() << endl;
}
}
int LogStreamBuf::sync()
{
static char buf[BUFFER_LENGTH];
// sync our streambuffer...
if (pptr() != pbase())
{
char* line_start = pbase();
char* line_end = pbase();
while (line_end <= pptr())
{
// search for the first end of line
for (; line_end < pptr() && *line_end != '\n'; line_end++);
if (line_end >= pptr())
{
// copy the incomplete line to the incomplete_line_ buffer
strncpy(&(buf[0]), line_start, line_end - line_start + 1);
buf[line_end - line_start] = '\0';
incomplete_line_ += &(buf[0]);
// mark everything as read
line_end = pptr() + 1;
} else {
memcpy(&(buf[0]), line_start, line_end - line_start + 1);
buf[line_end - line_start] = '\0';
// assemble the string to be written
// (consider leftovers of the last buffer from incomplete_line_)
string outstring = incomplete_line_;
incomplete_line_ = "";
outstring += &(buf[0]);
// if there are any streams in our list, we
// copy the line into that streams, too and flush them
using ::std::list;
list<StreamStruct>::iterator list_it = stream_list_.begin();
for (; list_it != stream_list_.end(); ++list_it)
{
// if the stream is open for that level, write to it...
if ((list_it->min_level <= tmp_level_) && (list_it->max_level >= tmp_level_))
{
*(list_it->stream) << expandPrefix_(list_it->prefix, tmp_level_, time(0)).c_str()
<< outstring.c_str() << endl;
if (list_it->target != 0)
{
list_it->target->notify();
}
}
}
// update the line pointers (increment both)
line_start = ++line_end;
// remove cr/lf from the end of the line
while (outstring[outstring.size() - 1] == 10 || outstring[outstring.size() - 1] == 13)
{
outstring.erase(outstring.end());
}
// store the line
Logline logline;
logline.text = outstring;
logline.level = tmp_level_;
logline.time = time(0);
// store the new line
loglines_.push_back(logline);
// reset tmp_level_ to the previous level
// (needed for LogStream::level() only)
tmp_level_ = level_;
}
}
// remove all processed lines from the buffer
pbump((int)(pbase() - pptr()));
}
return 0;
}
string LogStreamBuf::expandPrefix_(const string& prefix, const int& level, const time_t& time) const
{
Size index = 0;
Size copied_index = 0;
string result("");
while ((index = prefix.find("%", index)) != string::npos)
{
// append any constant parts of the string to the result
if (copied_index < index)
{
result.append(prefix.substr(copied_index, index - copied_index));
copied_index = index;
}
if (index < prefix.size())
{
char buffer[64];
char* buf = &(buffer[0]);
switch (prefix[index + 1])
{
case '%': // append a '%' (escape sequence)
result.append("%");
break;
case 'l': // append the loglevel
sprintf(buf, "%d", level);
result.append(buf);
break;
case 'y': // append the message type (error/warning/information)
if (level >= LogStream::ERROR)
{
result.append("ERROR");
} else if (level >= LogStream::WARNING) {
result.append("WARNING");
} else if (level >= LogStream::INFORMATION) {
result.append("INFORMATION");
} else {
result.append("LOG"); }
break;
case 'T': // time: HH:MM:SS
strftime(buf, BUFFER_LENGTH - 1, "%T", localtime(&time));
result.append(buf);
break;
case 't': // time: HH:MM
strftime(buf, BUFFER_LENGTH - 1, "%R", localtime(&time));
result.append(buf);
break;
case 'D': // date: DD.MM.YYYY
strftime(buf, BUFFER_LENGTH - 1, "%d.%m.%Y", localtime(&time));
result.append(buf);
break;
case 'd': // date: DD.MM.
strftime(buf, BUFFER_LENGTH - 1, "%d.%m.", localtime(&time));
result.append(buf);
break;
case 'S': // time+date: DD.MM.YYYY, HH:MM:SS
strftime(buf, BUFFER_LENGTH - 1, "%d.%m.%Y, %R", localtime(&time));
result.append(buf);
break;
case 's': // time+date: DD.MM., HH:MM
strftime(buf, BUFFER_LENGTH - 1, "%d.%m., %T", localtime(&time));
result.append(buf);
break;
default:
break;
}
index += 2;
copied_index += 2;
}
}
if (copied_index < prefix.size()) {
result.append(prefix.substr(copied_index, prefix.size() - copied_index));
}
return result;
}
LogStreamNotifier::LogStreamNotifier()
{
}
LogStreamNotifier::LogStreamNotifier(const LogStream::Target& target)
{
NotificationRegister(*this, const_cast<LogStream::Target &>(target));
}
LogStreamNotifier::~LogStreamNotifier()
{
NotificationUnregister(*this);
}
void LogStreamNotifier::notify() const
{
Notify(const_cast<LogStreamNotifier&>(*this));
}
// keep the given buffer
LogStream::LogStream(LogStreamBuf* buf)
: BALL_IOS(buf),
BALL_OSTREAM(buf),
delete_buffer_(false)
{
}
// create a new buffer
LogStream::LogStream(const bool& associate_stdio)
: BALL_IOS(new LogStreamBuf),
BALL_OSTREAM(new LogStreamBuf),
delete_buffer_(true)
{
if (associate_stdio == true)
{
// associate cout to informations and warnings,
// cerr to errors by default
insert(std::cout, INFORMATION, ERROR - 1);
insert(std::cerr, ERROR);
}
}
// remove the streambuffer
LogStream::~LogStream()
{
if (delete_buffer_)
{
delete rdbuf();
}
}
void LogStream::clear()
{
rdbuf()->loglines_.clear();
}
void LogStream::insert(ostream& stream, const int& min_level, const int& max_level)
{
// return if no LogStreamBuf is defined!
if (rdbuf() == 0)
{
return;
}
// first, check whether the stream is already associated (avoid
// multiple insertions)
using std::list;
list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin();
for (; list_it != rdbuf()->stream_list_.end(); ++list_it)
{
if ((*list_it).stream == &stream)
{
return;
}
}
// we didn`t find it - create a new entry in the list
LogStreamBuf::StreamStruct s_struct;
s_struct.min_level = min_level;
s_struct.max_level = max_level;
s_struct.stream = &stream;
rdbuf()->stream_list_.push_back(s_struct);
}
void LogStream::remove(ostream& stream)
{
// return if no LogStreamBuf is defined!
if (rdbuf() == 0)
{
return;
}
// find the stream in the LogStreamBuf's list
using std::list;
list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin();
for (; list_it != rdbuf()->stream_list_.end(); ++list_it)
{
if ((*list_it).stream == &stream)
{
// remove the stream - iterator becomes invalid, so exit
rdbuf()->stream_list_.erase(list_it);
break;
}
}
// if the stream is not found nothing happens!
}
void LogStream::insertNotification(const ostream& s, const LogStream::Target& target)
{
// return if no LogStreamBuf is defined!
if (rdbuf() == 0)
{
return;
}
// find the stream in the LogStreamBuf's list
using std::list;
list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin();
for (; list_it != rdbuf()->stream_list_.end(); ++list_it)
{
if (list_it->stream == &s)
{
// set the notification target
list_it->target = new LogStreamNotifier(const_cast<LogStream::Target&>(target));
break;
}
}
// if the stream is not found nothing happens!
}
void LogStream::removeNotification(const ostream& s)
{
// return if no LogStreamBuf is defined!
if (rdbuf() == 0)
{
return;
}
// find the stream in the LogStreamBuf's list
using std::list;
list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin();
for (; list_it != rdbuf()->stream_list_.end(); ++list_it)
{
if (list_it->stream == &s)
{
// destroy and remove the notification target
delete list_it->target;
list_it->target = 0;
break;
}
}
// if the stream is not found nothing happens!
}
void LogStream::setMinLevel(const ostream& stream, const int& level)
{
// return if no LogStreamBuf is defined!
if (rdbuf() == 0)
{
return;
}
// find the stream in the LogStreamBuf's list
using std::list;
list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin();
for (; list_it != rdbuf()->stream_list_.end(); ++list_it)
{
if ((*list_it).stream == &stream)
{
// change the streams min_level and exit the loop
(*list_it).min_level = level;
break;
}
}
}
void LogStream::setMaxLevel(const ostream& stream, const int& level)
{
// return if no LogStreamBuf is defined!
if (rdbuf() == 0)
{
return;
}
// find the stream in the LogStreamBuf's list:
// iterate over the list until you find the stream`s pointer
using std::list;
list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin();
for (; list_it != rdbuf()->stream_list_.end(); ++list_it)
{
if ((*list_it).stream == &stream)
{
// change the streams max_level and exit the loop
(*list_it).max_level = level;
break;
}
}
}
void LogStream::setPrefix(const ostream& s, const string& prefix)
{
// return if no LogStreamBuf is defined!
if (rdbuf() == 0)
{
return;
}
// find the stream in the LogStreamBuf's list:
// iterate over the list until you find the stream`s pointer
using std::list;
list<LogStreamBuf::StreamStruct>::iterator list_it = rdbuf()->stream_list_.begin();
for (; list_it != rdbuf()->stream_list_.end(); ++list_it)
{
if ((*list_it).stream == &s)
{
// change the streams max_level and exit the loop
(*list_it).prefix = prefix;
return;
}
}
}
Size LogStream::getNumberOfLines(const int& min_level, const int& max_level) const
{
// cast this to const, to access non const method rdbuf() which
// is usually const, but declared non const
LogStream* non_const_this = const_cast<LogStream*>(this);
// if rdbuf() is NULL, return
if (non_const_this->rdbuf() == 0)
{
return 0;
}
// iterate over all loglines and count the lines of interest
vector<LogStreamBuf::Logline>::iterator it = non_const_this->rdbuf()->loglines_.begin();
Size count = 0;
for (; it != non_const_this->rdbuf()->loglines_.end(); ++it)
{
if ((*it).level >= min_level && (*it).level <= max_level)
{
count++;
}
}
return count;
}
string LogStream::getLineText(const Index& index) const
{
if ((signed)getNumberOfLines() < index)
{
return "";
}
LogStream* non_const_this = const_cast<LogStream*>(this);
if (non_const_this->rdbuf() == 0)
{
return "";
}
return non_const_this->rdbuf()->loglines_[index].text;
}
int LogStream::getLineLevel(const Index& index) const
{
if ((signed)getNumberOfLines() < index)
{
return -1;
}
LogStream* non_const_this = const_cast<LogStream*>(this);
if (non_const_this->rdbuf() == 0)
{
return -1;
}
return non_const_this->rdbuf()->loglines_[index].level;
}
time_t LogStream::getLineTime(const Index& index) const
{
if ((signed)getNumberOfLines() < index)
{
return 0;
}
LogStream* non_const_this = const_cast<LogStream*>(this);
if (non_const_this->rdbuf() == 0)
{
return 0;
}
return non_const_this->rdbuf()->loglines_[index].time;
}
list<int> LogStream::filterLines
(const int& min_level, const int& max_level,
const time_t& earliest, const time_t& latest, const string& s) const
{
using std::list;
list<int> list_indices;
Position pos = 0;
LogStreamBuf* log = const_cast<LogStream*>(this)->rdbuf();
while (pos < log->loglines_.size() &&
log->loglines_[pos].time < earliest)
{
pos++;
}
while (pos < log->loglines_.size() &&
log->loglines_[pos].time <= latest)
{
if (log->loglines_[pos].level >= min_level &&
log->loglines_[pos].level <= max_level)
{
if (s.length() > 0)
{
if (log->loglines_[pos].text.find(s, 0) != string::npos )
{
list_indices.push_back(pos);
}
}
else
{
list_indices.push_back(pos);
}
}
pos++;
}
return list_indices;
}
// global default logstream
LogStream Log(true);
# ifdef BALL_NO_INLINE_FUNCTIONS
# include <BALL/COMMON/logStream.iC>
# endif
} // namespace BALL
|
/* vim: set ai et ts=4 sw=4: */
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "defer.h"
#include <PersistentStorage.h>
#include <rapidjson/writer.h>
#include <stdexcept>
#include <string>
using namespace rapidjson;
using namespace rocksdb;
PersistentStorage::PersistentStorage() {
_db = nullptr;
Options options;
options.IncreaseParallelism();
options.OptimizeLevelStyleCompaction();
options.create_if_missing = true;
Status s = rocksdb::DB::Open(options, "hurma_data", &_db);
if(!s.ok())
throw std::runtime_error("PersistentStorage::PersistentStorage() - DB::Open failed");
}
PersistentStorage::~PersistentStorage() {
if(_db != nullptr)
delete _db;
}
void PersistentStorage::set(const std::string& key, const std::string& value) {
Document val;
if(val.Parse(value.c_str()).HasParseError())
throw std::runtime_error("PersistentStore::set() - validation failed");
Status s = _db->Put(WriteOptions(), key, value);
if(!s.ok())
throw std::runtime_error("PersistentStore::set() - _db->Put failed");
}
std::string PersistentStorage::get(const std::string& key, bool* found) {
std::string value = "";
Status s = _db->Get(ReadOptions(), key, &value);
*found = s.ok();
return value;
}
// TODO: impelemt more efficient interation for wide ranges
std::string PersistentStorage::getRange(const std::string& key_from, const std::string& key_to) {
rocksdb::Iterator* it = _db->NewIterator(rocksdb::ReadOptions());
defer(delete it);
Document result;
result.SetObject();
for(it->Seek(key_from); it->Valid() && it->key().ToString() <= key_to; it->Next()) {
std::string key = it->key().ToString();
std::string value = it->value().ToString();
// Add "key": { ... value object ... } to the resulting document
Value k(key.c_str(), result.GetAllocator());
Document val_doc;
val_doc.Parse(value.c_str());
Value v(val_doc, result.GetAllocator());
result.AddMember(k, v, result.GetAllocator());
}
// Check for any errors found during the scan
if(!it->status().ok())
throw std::runtime_error("PersistentStore::getRange() - error during the scan");
StringBuffer sb;
Writer<StringBuffer> writer(sb);
result.Accept(writer);
return sb.GetString();
}
void PersistentStorage::del(const std::string& key, bool* found) {
std::string value = "";
Status check = _db->Get(ReadOptions(), key, &value);
*found = check.ok();
if(!check.ok())
return;
Status s = _db->Delete(WriteOptions(), key);
*found = s.ok();
}
clang-format
/* vim: set ai et ts=4 sw=4: */
#include "defer.h"
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include <PersistentStorage.h>
#include <rapidjson/writer.h>
#include <stdexcept>
#include <string>
using namespace rapidjson;
using namespace rocksdb;
PersistentStorage::PersistentStorage() {
_db = nullptr;
Options options;
options.IncreaseParallelism();
options.OptimizeLevelStyleCompaction();
options.create_if_missing = true;
Status s = rocksdb::DB::Open(options, "hurma_data", &_db);
if(!s.ok())
throw std::runtime_error("PersistentStorage::PersistentStorage() - DB::Open failed");
}
PersistentStorage::~PersistentStorage() {
if(_db != nullptr)
delete _db;
}
void PersistentStorage::set(const std::string& key, const std::string& value) {
Document val;
if(val.Parse(value.c_str()).HasParseError())
throw std::runtime_error("PersistentStore::set() - validation failed");
Status s = _db->Put(WriteOptions(), key, value);
if(!s.ok())
throw std::runtime_error("PersistentStore::set() - _db->Put failed");
}
std::string PersistentStorage::get(const std::string& key, bool* found) {
std::string value = "";
Status s = _db->Get(ReadOptions(), key, &value);
*found = s.ok();
return value;
}
// TODO: impelemt more efficient interation for wide ranges
std::string PersistentStorage::getRange(const std::string& key_from, const std::string& key_to) {
rocksdb::Iterator* it = _db->NewIterator(rocksdb::ReadOptions());
defer(delete it);
Document result;
result.SetObject();
for(it->Seek(key_from); it->Valid() && it->key().ToString() <= key_to; it->Next()) {
std::string key = it->key().ToString();
std::string value = it->value().ToString();
// Add "key": { ... value object ... } to the resulting document
Value k(key.c_str(), result.GetAllocator());
Document val_doc;
val_doc.Parse(value.c_str());
Value v(val_doc, result.GetAllocator());
result.AddMember(k, v, result.GetAllocator());
}
// Check for any errors found during the scan
if(!it->status().ok())
throw std::runtime_error("PersistentStore::getRange() - error during the scan");
StringBuffer sb;
Writer<StringBuffer> writer(sb);
result.Accept(writer);
return sb.GetString();
}
void PersistentStorage::del(const std::string& key, bool* found) {
std::string value = "";
Status check = _db->Get(ReadOptions(), key, &value);
*found = check.ok();
if(!check.ok())
return;
Status s = _db->Delete(WriteOptions(), key);
*found = s.ok();
}
|
// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: Socket_test.C,v 1.9 2003/05/08 13:55:26 anhi Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/SYSTEM/socket.h>
#include <unistd.h>
#ifdef BALL_COMPILER_MSVC
# include<windows.h>
# include<process.h>
#endif
///////////////////////////
using namespace BALL;
SockInetBuf sock_inet_buf(SocketBuf::sock_stream);
char c;
void socket_listener(void*)
{
sock_inet_buf.listen();
IOStreamSocket s(sock_inet_buf.accept());
s.get(c);
}
START_TEST(Socket, "$Id: Socket_test.C,v 1.9 2003/05/08 13:55:26 anhi Exp $")
using namespace BALL;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
CHECK(simple socket transmission)
sock_inet_buf.bind();
int port = sock_inet_buf.localport();
STATUS("localport = " << sock_inet_buf.localport())
STATUS("localhost = " << sock_inet_buf.localhost())
#ifdef BALL_COMPILER_MSVC
_beginthread(socket_listener,0,NULL);
Sleep(1);
IOStreamSocket sio(SocketBuf::sock_stream);
int result = sio->connect(sock_inet_buf.localhost(), port);
STATUS("B:connect = " << result)
sio.put((char)123);
sio.flush();
STATUS("B:done.")
#else
if (fork())
{
socket_listener(0);
}
else
{
sleep(1);
IOStreamSocket sio(SocketBuf::sock_stream);
int result = sio->connect(sock_inet_buf.localhost(), port);
STATUS("B:connect = " << result)
sio.put((char)123);
STATUS("B:done.")
return 0;
}
#endif
TEST_EQUAL((int)c, (int)123);
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
no message
// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: Socket_test.C,v 1.10 2003/07/03 11:55:05 amoll Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/SYSTEM/socket.h>
#include <unistd.h>
#ifdef BALL_COMPILER_MSVC
# include<windows.h>
# include<process.h>
#endif
///////////////////////////
using namespace BALL;
SockInetBuf sock_inet_buf(SocketBuf::sock_stream);
char c;
void socket_listener(void*)
{
sock_inet_buf.listen();
IOStreamSocket s(sock_inet_buf.accept());
s.get(c);
}
START_TEST(Socket, "$Id: Socket_test.C,v 1.10 2003/07/03 11:55:05 amoll Exp $")
using namespace BALL;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
CHECK([EXTRA]simple socket transmission)
sock_inet_buf.bind();
int port = sock_inet_buf.localport();
STATUS("localport = " << sock_inet_buf.localport())
STATUS("localhost = " << sock_inet_buf.localhost())
#ifdef BALL_COMPILER_MSVC
_beginthread(socket_listener,0,NULL);
Sleep(1);
IOStreamSocket sio(SocketBuf::sock_stream);
int result = sio->connect(sock_inet_buf.localhost(), port);
STATUS("B:connect = " << result)
sio.put((char)123);
sio.flush();
STATUS("B:done.")
#else
if (fork())
{
socket_listener(0);
}
else
{
sleep(1);
IOStreamSocket sio(SocketBuf::sock_stream);
int result = sio->connect(sock_inet_buf.localhost(), port);
STATUS("B:connect = " << result)
sio.put((char)123);
STATUS("B:done.")
return 0;
}
#endif
TEST_EQUAL((int)c, (int)123);
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
|
/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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 notices for more information.
=========================================================================*/
#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif
#include <typeinfo>
#include <cassert>
#include "otbMacro.h"
#include "itkMetaDataObject.h"
#include "otbImageMetadataInterface.h"
#include "otbImageKeywordlist.h"
#include "otbVectorDataKeywordlist.h"
namespace otb
{
ImageMetadataInterface::ImageMetadataInterface()
{
}
std::string ImageMetadataInterface::GetProjectionRef( const MetaDataDictionaryType & dict ) const
{
std::string metadata;
if (dict.HasKey(MetaDataKey::ProjectionRefKey))
{
itk::ExposeMetaData<std::string>(dict, static_cast<std::string>(MetaDataKey::ProjectionRefKey), metadata);
return ( metadata );
}
else
return ("");
}
std::string ImageMetadataInterface::GetGCPProjection( const MetaDataDictionaryType & dict ) const
{
std::string metadata;
if (dict.HasKey(MetaDataKey::GCPProjectionKey))
{
itk::ExposeMetaData<std::string>(dict, static_cast<std::string>(MetaDataKey::GCPProjectionKey), metadata);
return ( metadata );
}
else
return ("");
}
unsigned int ImageMetadataInterface::GetGCPCount( const MetaDataDictionaryType & dict) const
{
unsigned int GCPCount = 0;
if (dict.HasKey(MetaDataKey::GCPCountKey))
{
itk::ExposeMetaData<unsigned int>(dict, MetaDataKey::GCPCountKey, GCPCount);
}
return (GCPCount);
}
OTB_GCP & ImageMetadataInterface::GetGCPs( MetaDataDictionaryType & dict, unsigned int GCPnum )
{
std::string key;
::itk::OStringStream lStream;
lStream << MetaDataKey::GCPParametersKey << GCPnum;
key = lStream.str();
if (dict.HasKey(key))
{
itk::ExposeMetaData<OTB_GCP>(dict, key, m_GCP);
}
return ( m_GCP );
}
std::string ImageMetadataInterface::GetGCPId( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const
{
std::string key;
::itk::OStringStream lStream;
lStream << MetaDataKey::GCPParametersKey << GCPnum;
key = lStream.str();
if (dict.HasKey(key))
{
OTB_GCP gcp;
itk::ExposeMetaData<OTB_GCP>(dict, key, gcp);
return ( gcp.m_Id );
}
else
return ("");
}
std::string ImageMetadataInterface::GetGCPInfo( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const
{
std::string key;
::itk::OStringStream lStream;
lStream << MetaDataKey::GCPParametersKey << GCPnum;
key = lStream.str();
if (dict.HasKey(key))
{
OTB_GCP gcp;
itk::ExposeMetaData<OTB_GCP>(dict, key, gcp);
return ( gcp.m_Info );
}
else
return ("");
}
double ImageMetadataInterface::GetGCPRow( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const
{
std::string key;
::itk::OStringStream lStream;
lStream << MetaDataKey::GCPParametersKey << GCPnum;
key = lStream.str();
if (dict.HasKey(key))
{
OTB_GCP gcp;
itk::ExposeMetaData<OTB_GCP>(dict, key, gcp);
return ( gcp.m_GCPRow );
}
else
return (0);
}
double ImageMetadataInterface::GetGCPCol( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const
{
std::string key;
::itk::OStringStream lStream;
lStream << MetaDataKey::GCPParametersKey << GCPnum;
key = lStream.str();
if (dict.HasKey(key))
{
OTB_GCP gcp;
itk::ExposeMetaData<OTB_GCP>(dict, key, gcp);
return ( gcp.m_GCPCol );
}
else
return (0);
}
double ImageMetadataInterface::GetGCPX( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const
{
std::string key;
::itk::OStringStream lStream;
lStream << MetaDataKey::GCPParametersKey << GCPnum;
key = lStream.str();
if (dict.HasKey(key))
{
OTB_GCP gcp;
itk::ExposeMetaData<OTB_GCP>(dict, key, gcp);
return ( gcp.m_GCPX );
}
else
return (0);
}
double ImageMetadataInterface::GetGCPY( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const
{
std::string key;
::itk::OStringStream lStream;
lStream << MetaDataKey::GCPParametersKey << GCPnum;
key = lStream.str();
if (dict.HasKey(key))
{
OTB_GCP gcp;
itk::ExposeMetaData<OTB_GCP>(dict, key, gcp);
return ( gcp.m_GCPY );
}
else
return (0);
}
double ImageMetadataInterface::GetGCPZ( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const
{
std::string key;
::itk::OStringStream lStream;
lStream << MetaDataKey::GCPParametersKey << GCPnum;
key = lStream.str();
if (dict.HasKey(key))
{
OTB_GCP gcp;
itk::ExposeMetaData<OTB_GCP>(dict, key, gcp);
return ( gcp.m_GCPZ );
}
else
return (0);
}
ImageMetadataInterface::VectorType ImageMetadataInterface::GetGeoTransform( const MetaDataDictionaryType & dict ) const
{
VectorType adfGeoTransform;
if (dict.HasKey(MetaDataKey::GeoTransformKey))
{
itk::ExposeMetaData<VectorType>(dict, MetaDataKey::GeoTransformKey, adfGeoTransform);
}
return ( adfGeoTransform );
}
ImageMetadataInterface::VectorType ImageMetadataInterface::GetUpperLeftCorner( const MetaDataDictionaryType & dict ) const
{
VectorType UpperLeftCorner;
if (dict.HasKey(MetaDataKey::UpperLeftCornerKey))
{
itk::ExposeMetaData<VectorType>(dict, MetaDataKey::UpperLeftCornerKey, UpperLeftCorner);
}
return ( UpperLeftCorner );
}
ImageMetadataInterface::VectorType ImageMetadataInterface::GetUpperRightCorner( const MetaDataDictionaryType & dict ) const
{
VectorType UpperRightCorner;
if (dict.HasKey(MetaDataKey::UpperRightCornerKey))
{
itk::ExposeMetaData<VectorType>(dict, MetaDataKey::UpperRightCornerKey, UpperRightCorner);
}
return ( UpperRightCorner );
}
ImageMetadataInterface::VectorType ImageMetadataInterface::GetLowerLeftCorner( const MetaDataDictionaryType & dict ) const
{
VectorType LowerLeftCorner;
if (dict.HasKey(MetaDataKey::LowerLeftCornerKey))
{
itk::ExposeMetaData<VectorType>(dict, MetaDataKey::LowerLeftCornerKey, LowerLeftCorner);
}
return ( LowerLeftCorner );
}
ImageMetadataInterface::VectorType ImageMetadataInterface::GetLowerRightCorner( const MetaDataDictionaryType & dict ) const
{
VectorType LowerRightCorner;
if (dict.HasKey(MetaDataKey::LowerRightCornerKey))
{
itk::ExposeMetaData<VectorType>(dict, MetaDataKey::LowerRightCornerKey, LowerRightCorner);
}
return ( LowerRightCorner );
}
ImageMetadataInterface::ImageKeywordlistType ImageMetadataInterface::GetImageKeywordlist( MetaDataDictionaryType & dict )
{
ImageKeywordlistType ImageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist);
}
return ( ImageKeywordlist );
}
const ImageMetadataInterface::ImageKeywordlistType ImageMetadataInterface::GetImageKeywordlist(const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType ImageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist);
}
return ( ImageKeywordlist );
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetPhysicalBias( const MetaDataDictionaryType & dict ) const
{
if(IsSpot(dict))
{
return GetSpotPhysicalBias(dict);
}
if(IsIkonos(dict))
{
return GetIkonosPhysicalBias(dict);
}
if(IsQuickbird(dict))
{
return GetQuickbirdPhysicalBias(dict);
}
VariableLengthVectorType output(1);
output.Fill(0);
return output;
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetPhysicalGain( const MetaDataDictionaryType & dict ) const
{
if(IsSpot(dict))
{
return GetSpotPhysicalGain(dict);
}
if(IsIkonos(dict))
{
return GetIkonosPhysicalGain(dict);
}
if(IsQuickbird(dict))
{
return GetQuickbirdPhysicalGain(dict);
}
VariableLengthVectorType output(1);
output.Fill(1);
return output;
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetSolarIrradiance( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType imageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist);
}
VariableLengthVectorType outputValuesVariableLengthVector;
ossimKeywordlist kwl;
imageKeywordlist.convertToOSSIMKeywordlist(kwl);
if(IsSpot(dict)) // and QB?
{
std::string key= "support_data.solar_irradiance";
ossimString keywordString = kwl.find(key.c_str());
ossimString separatorList = " ";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
std::vector<double> outputValues;
for (unsigned int i=0; i < keywordStrings.size(); ++i)
{
if (!keywordStrings[i].empty())
{
outputValues.push_back(keywordStrings[i].toDouble());
}
}
outputValuesVariableLengthVector.SetSize(outputValues.size());
outputValuesVariableLengthVector.Fill(0);
//In the case of SPOT, the bands are in a different order:
// XS3, XS2. XS1, SWIR in the tif file.
if(IsSpot(dict))
{
//assert(outputValues.size() == 4);//Valid for Spot 4 and 5
if(outputValues.size() != 4)
itkGenericExceptionMacro(<<"Invalid Solar Irradiance");
outputValuesVariableLengthVector[0]=outputValues[2];
outputValuesVariableLengthVector[1]=outputValues[1];
outputValuesVariableLengthVector[2]=outputValues[0];
outputValuesVariableLengthVector[3]=outputValues[3];
}
else
{
for(unsigned int i=0; i<outputValues.size(); ++i)
{
outputValuesVariableLengthVector[i]=outputValues[i];
}
}
}
else if(IsIkonos(dict))
{
outputValuesVariableLengthVector.SetSize(1);
// values from geoeye
std::string key= "support_data.band_name";
ossimString keywordString = kwl.find(key.c_str());
if(keywordString=="Pan")
{
outputValuesVariableLengthVector[0] = 1375.8;
}
else if(keywordString=="Blue")
{
outputValuesVariableLengthVector[0] = 1930.9;
}
else if(keywordString=="Green")
{
outputValuesVariableLengthVector[0] = 1854.8;
}
else if(keywordString=="Red")
{
outputValuesVariableLengthVector[0] = 1556.5;
}
else if(keywordString=="NIR")
{
outputValuesVariableLengthVector[0] = 1156.9;
}
}
else if(IsQuickbird(dict))
{
std::string keyBId= "support_data.band_id";
ossimString keywordStringBId = kwl.find(keyBId.c_str());
if( keywordStringBId == ossimString("P") )
{
outputValuesVariableLengthVector.SetSize(1);
outputValuesVariableLengthVector.Fill(1381.79);
}
else if(keywordStringBId == ossimString("Multi") )
{
outputValuesVariableLengthVector.SetSize(4);
outputValuesVariableLengthVector[0]=1924.59;
outputValuesVariableLengthVector[1]=1843.08;
outputValuesVariableLengthVector[2]=1574.77;
outputValuesVariableLengthVector[3]=1113.71;
}
else
{
itkExceptionMacro(<<"Invalid bandID "<<keywordStringBId);
}
}
return outputValuesVariableLengthVector;
}
double ImageMetadataInterface::GetSunElevation( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType imageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist);
}
ossimKeywordlist kwl;
imageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key= "support_data.elevation_angle";
ossimString keywordString = kwl.find(key.c_str());
return keywordString.toDouble();
}
double ImageMetadataInterface::GetSunAzimuth( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType imageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist);
}
ossimKeywordlist kwl;
imageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key= "support_data.azimuth_angle";
ossimString keywordString = kwl.find(key.c_str());
return keywordString.toDouble();
}
int ImageMetadataInterface::GetDay( const MetaDataDictionaryType & dict ) const
{
//The image date in the ossim metadata has the form: 2007-10-03T03:17:16.973000
ImageKeywordlistType imageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist);
}
ossimKeywordlist kwl;
imageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key;
ossimString separatorList;
if(IsSpot(dict))
{
key = "support_data.image_date";
separatorList = "-T";
}
if(IsIkonos(dict))
{
key = "support_data.production_date";
separatorList = "/";
}
if(IsQuickbird(dict))
{
key = "support_data.tlc_date";
separatorList = "-T";
}
ossimString keywordString = kwl.find(key.c_str());
//ossimString separatorList = "-T";
//std::string key= "support_data.image_date";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
//assert(keywordStrings.size() > 2);
if(keywordStrings.size() <= 2)
itkExceptionMacro(<<"Invalid Day");
ossimString day = keywordStrings[2];
if(IsIkonos(dict))
{
// MM/DD/YY
day = keywordStrings[1];
}
return day.toInt();
}
int ImageMetadataInterface::GetMonth( const MetaDataDictionaryType & dict ) const
{
//The image date in the ossim metadata has the form: 2007-10-03T03:17:16.973000
ImageKeywordlistType imageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist);
}
ossimKeywordlist kwl;
imageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key;
ossimString separatorList;
if(IsSpot(dict))
{
key = "support_data.image_date";
separatorList = "-T";
}
if(IsIkonos(dict))
{
key = "support_data.production_date";
separatorList = "/";
}
if(IsQuickbird(dict))
{
key = "support_data.tlc_date";
separatorList = "-T";
}
ossimString keywordString = kwl.find(key.c_str());
//ossimString separatorList = "-T";
//std::string key= "support_data.image_date";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
//assert(keywordStrings.size() > 2);
if(keywordStrings.size() <= 2)
itkExceptionMacro(<<"Invalid Month");
ossimString month = keywordStrings[1];
if(IsIkonos(dict))
{
month = keywordStrings[0];
}
return month.toInt();
}
int ImageMetadataInterface::GetYear( const MetaDataDictionaryType & dict ) const
{
//The image date in the ossim metadata has the form: 2007-10-03T03:17:16.973000
ImageKeywordlistType imageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist);
}
ossimKeywordlist kwl;
imageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key;
ossimString separatorList;
if(IsSpot(dict))
{
key = "support_data.image_date";
separatorList = "-T";
}
if(IsIkonos(dict))
{
key = "support_data.production_date";
separatorList = "/";
}
if(IsQuickbird(dict))
{
key = "support_data.tlc_date";
separatorList = "-T";
}
ossimString keywordString = kwl.find(key.c_str());
//ossimString separatorList = "-T";
//std::string key= "support_data.image_date";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
//assert(keywordStrings.size() > 2);
if( keywordStrings.size() <= 2 )
itkExceptionMacro("Invalid Year");
ossimString year = keywordStrings[0];
// For Ikonos 2002 is 02
if(IsIkonos(dict))
{
year = keywordStrings[2];
year = "20"+year;
}
return year.toInt();
//return keywordStrings[0].toInt();
}
std::string ImageMetadataInterface::GetSensorID( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType ImageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist);
}
ossimKeywordlist kwl;
ImageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key= "sensor";
ossimString keywordString = kwl.find(key.c_str());
std::string output(keywordString.chars());
return output;
}
unsigned int ImageMetadataInterface::GetNumberOfBands( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType ImageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist);
}
ossimKeywordlist kwl;
ImageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key= "support_data.number_bands";
ossimString keywordString = kwl.find(key.c_str());
return keywordString.toUInt32();
}
std::vector<std::string> ImageMetadataInterface::GetBandName( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType ImageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist);
}
ossimKeywordlist kwl;
ImageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key= "support_data.band_name";
ossimString keywordString = kwl.find(key.c_str());
ossimString separatorList = " ";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
std::vector<std::string> outputValues;
for (unsigned int i=0; i < keywordStrings.size(); ++i)
{
if (!keywordStrings[i].empty())
{
outputValues.push_back(keywordStrings[i].chars());
}
}
return outputValues;
}
bool ImageMetadataInterface::IsSpot( const MetaDataDictionaryType & dict ) const
{
std::string sensorID = GetSensorID(dict);
if (sensorID.find("Spot") != std::string::npos)
return true;
else
return false;
}
bool ImageMetadataInterface::IsIkonos( const MetaDataDictionaryType & dict ) const
{
std::string sensorID = GetSensorID(dict);
if (sensorID.find("IKONOS-2") != std::string::npos)
return true;
else
return false;
}
bool ImageMetadataInterface::IsQuickbird( const MetaDataDictionaryType & dict ) const
{
std::string sensorID = GetSensorID(dict);
if (sensorID.find("QB02") != std::string::npos)
return true;
else
return false;
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetSpotPhysicalBias( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType imageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist);
}
ossimKeywordlist kwl;
imageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key= "support_data.physical_bias";
ossimString keywordString = kwl.find(key.c_str());
ossimString separatorList = " ";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
std::vector<double> outputValues;
for (unsigned int i=0; i < keywordStrings.size(); ++i)
{
if (!keywordStrings[i].empty())
{
outputValues.push_back(keywordStrings[i].toDouble());
}
}
VariableLengthVectorType outputValuesVariableLengthVector;
outputValuesVariableLengthVector.SetSize(outputValues.size());
outputValuesVariableLengthVector.Fill(0);
//In the case of SPOT, the bands are in a different order:
// XS3, XS2. XS1, SWIR in the tif file.
//assert(outputValues.size() == 4);//Valid for Spot 4 and 5
if( outputValues.size() != 4 )
itkExceptionMacro("Invalid Physical Bias");
outputValuesVariableLengthVector[0]=outputValues[2];
outputValuesVariableLengthVector[1]=outputValues[1];
outputValuesVariableLengthVector[2]=outputValues[0];
outputValuesVariableLengthVector[3]=outputValues[3];
return outputValuesVariableLengthVector;
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetSpotPhysicalGain( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType imageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist);
}
// otbMsgDevMacro( << " --- ImageKeywordlist: " << imageKeywordlist);
ossimKeywordlist kwl;
imageKeywordlist.convertToOSSIMKeywordlist(kwl);
// otbMsgDevMaquitcro( << " --- ossimKeywordlist: " << kwl);
std::string key= "support_data.physical_gain";
ossimString keywordString = kwl.find(key.c_str());
ossimString separatorList = " ";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
std::vector<double> outputValues;
for (unsigned int i=0; i < keywordStrings.size(); ++i)
{
if (!keywordStrings[i].empty())
{
outputValues.push_back(keywordStrings[i].toDouble());
}
}
VariableLengthVectorType outputValuesVariableLengthVector;
outputValuesVariableLengthVector.SetSize(outputValues.size());
outputValuesVariableLengthVector.Fill(0);
//In the case of SPOT, the bands are in a different order:
// XS3, XS2. XS1, SWIR in the tif file.
//assert(outputValues.size() == 4);//Valid for Spot 4 and 5
if( outputValues.size() != 4 )
itkExceptionMacro("Invalid Physical Gain");
outputValuesVariableLengthVector[0]=outputValues[2];
outputValuesVariableLengthVector[1]=outputValues[1];
outputValuesVariableLengthVector[2]=outputValues[0];
outputValuesVariableLengthVector[3]=outputValues[3];
return outputValuesVariableLengthVector;
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetQuickbirdPhysicalBias( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType ImageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist);
}
ossimKeywordlist kwl;
ImageKeywordlist.convertToOSSIMKeywordlist(kwl);
VariableLengthVectorType outputValuesVariableLengthVector;
std::string keyBId= "support_data.band_id";
ossimString keywordStringBId = kwl.find(keyBId.c_str());
if( keywordStringBId == ossimString("P") )
{
outputValuesVariableLengthVector.SetSize(1);
outputValuesVariableLengthVector.Fill(0.0);
}
else if(keywordStringBId == ossimString("Multi") )
{
outputValuesVariableLengthVector.SetSize(4);
outputValuesVariableLengthVector.Fill(0.0);
}
else
{
itkExceptionMacro(<<"Invalid bandID "<<keywordStringBId);
}
return outputValuesVariableLengthVector;
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetQuickbirdPhysicalGain( const MetaDataDictionaryType & dict ) const
{
//Values are different pre/post 2003-06-06 production date, find out where we are
ImageKeywordlistType ImageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist);
}
ossimKeywordlist kwl;
ImageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key= "support_data.generation_date";
ossimString keywordString = kwl.find(key.c_str());
std::string output(keywordString.chars());
//The Ikonos production date has the format MM/DD/YY
ossimString separatorList = "-";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
if (keywordStrings.size() < 3)
{
itkGenericExceptionMacro(<<"Could not retrieve the production date for Ikonos");
}
int productionYear = keywordStrings[0].toInt();
int productionMonth = keywordStrings[1].toInt();
int productionDay = keywordStrings[2].toInt();
bool isPost20030606 = false;
if(productionYear > 2003)
isPost20030606 = true;
else
{
if(productionYear == 2003)
{
if(productionMonth > 6)
isPost20030606 = true;
else
if(productionDay >= 6)
isPost20030606 = true;
}
}
//Value computed from
// http://www.geoeye.com/CorpSite/assets/docs/technical-papers/2009/IKONOS_Esun_Calculations.pdf
// to get the equivalent of the SPOT alpha
VariableLengthVectorType gain;
gain.SetSize(5);
if (isPost20030606)
{
gain[0] = 0.16200;//Pan
gain[1] = 0.23590;//Blue
gain[2] = 0.14530;//Green
gain[3] = 0.17850;//Red
gain[4] = 0.13530;//NIR
}
else
{
gain[0] = 1;//Pan
gain[1] = 1;//Blue
gain[2] = 1;//Green
gain[3] = 1;//Red
gain[4] = 1;//NIR
}
VariableLengthVectorType outputValuesVariableLengthVector;
std::string keyBId= "support_data.band_id";
ossimString keywordStringBId = kwl.find(keyBId.c_str());
if (keywordStringBId == ossimString("P") )
{
outputValuesVariableLengthVector.SetSize(1);
outputValuesVariableLengthVector[0]=gain[0];
}
// Multi spectral
else if(keywordStringBId == ossimString("Multi") )
{
outputValuesVariableLengthVector.SetSize(4);
outputValuesVariableLengthVector[0]=gain[1];
outputValuesVariableLengthVector[1]=gain[2];
outputValuesVariableLengthVector[2]=gain[3];
outputValuesVariableLengthVector[3]=gain[4];
}
else
{
itkExceptionMacro(<<"Invalid bandID "<<keywordStringBId);
}
return outputValuesVariableLengthVector;
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetIkonosPhysicalBias( const MetaDataDictionaryType & dict ) const
{
VariableLengthVectorType outputValuesVariableLengthVector;
outputValuesVariableLengthVector.SetSize(GetNumberOfBands(dict));
outputValuesVariableLengthVector.Fill(0.0);
return outputValuesVariableLengthVector;
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetIkonosPhysicalGain( const MetaDataDictionaryType & dict ) const
{
//Values are different pre/post 2001-01-22 production date, find out where we are
ImageKeywordlistType ImageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist);
}
ossimKeywordlist kwl;
ImageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key= "support_data.production_date";
ossimString keywordString = kwl.find(key.c_str());
std::string output(keywordString.chars());
//The Ikonos production date has the format MM/DD/YY
ossimString separatorList = "/";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
if (keywordStrings.size() < 3)
{
itkGenericExceptionMacro(<<"Could not retrieve the production date for Ikonos");
}
int productionYear = keywordStrings[2].toInt();
int productionMonth = keywordStrings[0].toInt();
int productionDay = keywordStrings[1].toInt();
bool isPost20010122 = false;
if ((productionYear > 2) || (productionYear < 99)) isPost20010122 = true;
else
{
if (productionYear == 2)
{
if (productionMonth > 1) isPost20010122 = true;
else
if (productionDay >= 22) isPost20010122 = true;
}
}
//Value computed from
// http://www.geoeye.com/CorpSite/assets/docs/technical-papers/2009/IKONOS_Esun_Calculations.pdf
// to get the equivalent of the SPOT alpha
VariableLengthVectorType gain;
gain.SetSize(5);
if (isPost20010122)
{
gain[0] = 6.48830;//Pan
gain[1] = 5.19064;//Blue
gain[2] = 6.44122;//Green
gain[3] = 6.24442;//Red
gain[4] = 8.04222;//NIR
}
else
{
gain[0] = 6.48830;//Pan
gain[1] = 4.51329;//Blue
gain[2] = 5.75014;//Green
gain[3] = 5.52720;//Red
gain[4] = 7.11684;//NIR
}
std::vector<std::string> bandName = GetBandName(dict);
VariableLengthVectorType outputValuesVariableLengthVector;
unsigned int numBands = GetNumberOfBands(dict);
outputValuesVariableLengthVector.SetSize(numBands);
for(unsigned int i=0; i<numBands; ++i)
{
if (bandName[i].find("Pan") != std::string::npos)
outputValuesVariableLengthVector[i]=gain[0];
if (bandName[i].find("Blue") != std::string::npos)
outputValuesVariableLengthVector[i]=gain[1];
if (bandName[i].find("Green") != std::string::npos)
outputValuesVariableLengthVector[i]=gain[2];
if (bandName[i].find("Red") != std::string::npos)
outputValuesVariableLengthVector[i]=gain[3];
if (bandName[i].find("NIR") != std::string::npos)
outputValuesVariableLengthVector[i]=gain[4];
}
return outputValuesVariableLengthVector;
}
void
ImageMetadataInterface::PrintSelf(std::ostream& os, itk::Indent indent, const MetaDataDictionaryType & dict) const
{
std::vector<std::string> keys = dict.GetKeys();
std::string svalue;
unsigned int ivalue(0);
VectorType vvalue;
double dvalue = 0.;
OTB_GCP gcpvalue;
ImageKeywordlist ossimvalue;
VectorDataKeywordlist vectorDataKeywordlistValue;
unsigned int i(0);
// Copy of the const metadata dictionary in a metadata dictionary to be used
// by the ExposeMetaData method
MetaDataDictionaryType dict2 = dict;
MetaDataKey key;
for (unsigned int itkey=0; itkey<keys.size(); ++itkey)
{
switch ( key.GetKeyType(keys[itkey]) )
{
case MetaDataKey::TSTRING:
itk::ExposeMetaData<std::string>(dict2, keys[itkey], svalue);
os << indent << "---> " << keys[itkey] << " = " << svalue << std::endl;
break;
case MetaDataKey::TENTIER:
itk::ExposeMetaData<unsigned int>(dict2, keys[itkey], ivalue);
os << indent << "---> " << keys[itkey] << " = " << ivalue << std::endl;
break;
case MetaDataKey::TVECTOR:
itk::ExposeMetaData<VectorType>(dict2, keys[itkey], vvalue);
for (i = 0; i < vvalue.size(); ++i )
{
os << indent << "---> " << keys[itkey] << "[" << i <<"] = "<< vvalue[i]<< std::endl;
}
vvalue.clear();
break;
case MetaDataKey::TDOUBLE:
itk::ExposeMetaData<double>(dict2, keys[itkey], dvalue);
os << indent << "---> " << keys[itkey] << " = " << dvalue << std::endl;
break;
case MetaDataKey::TOTB_GCP:
itk::ExposeMetaData<OTB_GCP>(dict2, keys[itkey], gcpvalue);
os << indent << "---> " << keys[itkey] << std::endl;
gcpvalue.Print(os);
break;
case MetaDataKey::TOSSIMKEYWORDLIST:
itk::ExposeMetaData<ImageKeywordlist>(dict2, keys[itkey], ossimvalue);
os << indent << "---> " << keys[itkey] << std::endl;
ossimvalue.Print(os);
// ossimvalue.Print(os);
break;
case MetaDataKey::TVECTORDATAKEYWORDLIST:
itk::ExposeMetaData<VectorDataKeywordlist>(dict2, keys[itkey], vectorDataKeywordlistValue);
os << indent << "---> " << keys[itkey] << std::endl;
vectorDataKeywordlistValue.Print(os);
break;
default:
break;
}
}
}
} // end namespace otb
ENH : inversve gain coef for QB
/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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 notices for more information.
=========================================================================*/
#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif
#include <typeinfo>
#include <cassert>
#include "otbMacro.h"
#include "itkMetaDataObject.h"
#include "otbImageMetadataInterface.h"
#include "otbImageKeywordlist.h"
#include "otbVectorDataKeywordlist.h"
namespace otb
{
ImageMetadataInterface::ImageMetadataInterface()
{
}
std::string ImageMetadataInterface::GetProjectionRef( const MetaDataDictionaryType & dict ) const
{
std::string metadata;
if (dict.HasKey(MetaDataKey::ProjectionRefKey))
{
itk::ExposeMetaData<std::string>(dict, static_cast<std::string>(MetaDataKey::ProjectionRefKey), metadata);
return ( metadata );
}
else
return ("");
}
std::string ImageMetadataInterface::GetGCPProjection( const MetaDataDictionaryType & dict ) const
{
std::string metadata;
if (dict.HasKey(MetaDataKey::GCPProjectionKey))
{
itk::ExposeMetaData<std::string>(dict, static_cast<std::string>(MetaDataKey::GCPProjectionKey), metadata);
return ( metadata );
}
else
return ("");
}
unsigned int ImageMetadataInterface::GetGCPCount( const MetaDataDictionaryType & dict) const
{
unsigned int GCPCount = 0;
if (dict.HasKey(MetaDataKey::GCPCountKey))
{
itk::ExposeMetaData<unsigned int>(dict, MetaDataKey::GCPCountKey, GCPCount);
}
return (GCPCount);
}
OTB_GCP & ImageMetadataInterface::GetGCPs( MetaDataDictionaryType & dict, unsigned int GCPnum )
{
std::string key;
::itk::OStringStream lStream;
lStream << MetaDataKey::GCPParametersKey << GCPnum;
key = lStream.str();
if (dict.HasKey(key))
{
itk::ExposeMetaData<OTB_GCP>(dict, key, m_GCP);
}
return ( m_GCP );
}
std::string ImageMetadataInterface::GetGCPId( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const
{
std::string key;
::itk::OStringStream lStream;
lStream << MetaDataKey::GCPParametersKey << GCPnum;
key = lStream.str();
if (dict.HasKey(key))
{
OTB_GCP gcp;
itk::ExposeMetaData<OTB_GCP>(dict, key, gcp);
return ( gcp.m_Id );
}
else
return ("");
}
std::string ImageMetadataInterface::GetGCPInfo( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const
{
std::string key;
::itk::OStringStream lStream;
lStream << MetaDataKey::GCPParametersKey << GCPnum;
key = lStream.str();
if (dict.HasKey(key))
{
OTB_GCP gcp;
itk::ExposeMetaData<OTB_GCP>(dict, key, gcp);
return ( gcp.m_Info );
}
else
return ("");
}
double ImageMetadataInterface::GetGCPRow( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const
{
std::string key;
::itk::OStringStream lStream;
lStream << MetaDataKey::GCPParametersKey << GCPnum;
key = lStream.str();
if (dict.HasKey(key))
{
OTB_GCP gcp;
itk::ExposeMetaData<OTB_GCP>(dict, key, gcp);
return ( gcp.m_GCPRow );
}
else
return (0);
}
double ImageMetadataInterface::GetGCPCol( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const
{
std::string key;
::itk::OStringStream lStream;
lStream << MetaDataKey::GCPParametersKey << GCPnum;
key = lStream.str();
if (dict.HasKey(key))
{
OTB_GCP gcp;
itk::ExposeMetaData<OTB_GCP>(dict, key, gcp);
return ( gcp.m_GCPCol );
}
else
return (0);
}
double ImageMetadataInterface::GetGCPX( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const
{
std::string key;
::itk::OStringStream lStream;
lStream << MetaDataKey::GCPParametersKey << GCPnum;
key = lStream.str();
if (dict.HasKey(key))
{
OTB_GCP gcp;
itk::ExposeMetaData<OTB_GCP>(dict, key, gcp);
return ( gcp.m_GCPX );
}
else
return (0);
}
double ImageMetadataInterface::GetGCPY( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const
{
std::string key;
::itk::OStringStream lStream;
lStream << MetaDataKey::GCPParametersKey << GCPnum;
key = lStream.str();
if (dict.HasKey(key))
{
OTB_GCP gcp;
itk::ExposeMetaData<OTB_GCP>(dict, key, gcp);
return ( gcp.m_GCPY );
}
else
return (0);
}
double ImageMetadataInterface::GetGCPZ( const MetaDataDictionaryType & dict, unsigned int GCPnum ) const
{
std::string key;
::itk::OStringStream lStream;
lStream << MetaDataKey::GCPParametersKey << GCPnum;
key = lStream.str();
if (dict.HasKey(key))
{
OTB_GCP gcp;
itk::ExposeMetaData<OTB_GCP>(dict, key, gcp);
return ( gcp.m_GCPZ );
}
else
return (0);
}
ImageMetadataInterface::VectorType ImageMetadataInterface::GetGeoTransform( const MetaDataDictionaryType & dict ) const
{
VectorType adfGeoTransform;
if (dict.HasKey(MetaDataKey::GeoTransformKey))
{
itk::ExposeMetaData<VectorType>(dict, MetaDataKey::GeoTransformKey, adfGeoTransform);
}
return ( adfGeoTransform );
}
ImageMetadataInterface::VectorType ImageMetadataInterface::GetUpperLeftCorner( const MetaDataDictionaryType & dict ) const
{
VectorType UpperLeftCorner;
if (dict.HasKey(MetaDataKey::UpperLeftCornerKey))
{
itk::ExposeMetaData<VectorType>(dict, MetaDataKey::UpperLeftCornerKey, UpperLeftCorner);
}
return ( UpperLeftCorner );
}
ImageMetadataInterface::VectorType ImageMetadataInterface::GetUpperRightCorner( const MetaDataDictionaryType & dict ) const
{
VectorType UpperRightCorner;
if (dict.HasKey(MetaDataKey::UpperRightCornerKey))
{
itk::ExposeMetaData<VectorType>(dict, MetaDataKey::UpperRightCornerKey, UpperRightCorner);
}
return ( UpperRightCorner );
}
ImageMetadataInterface::VectorType ImageMetadataInterface::GetLowerLeftCorner( const MetaDataDictionaryType & dict ) const
{
VectorType LowerLeftCorner;
if (dict.HasKey(MetaDataKey::LowerLeftCornerKey))
{
itk::ExposeMetaData<VectorType>(dict, MetaDataKey::LowerLeftCornerKey, LowerLeftCorner);
}
return ( LowerLeftCorner );
}
ImageMetadataInterface::VectorType ImageMetadataInterface::GetLowerRightCorner( const MetaDataDictionaryType & dict ) const
{
VectorType LowerRightCorner;
if (dict.HasKey(MetaDataKey::LowerRightCornerKey))
{
itk::ExposeMetaData<VectorType>(dict, MetaDataKey::LowerRightCornerKey, LowerRightCorner);
}
return ( LowerRightCorner );
}
ImageMetadataInterface::ImageKeywordlistType ImageMetadataInterface::GetImageKeywordlist( MetaDataDictionaryType & dict )
{
ImageKeywordlistType ImageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist);
}
return ( ImageKeywordlist );
}
const ImageMetadataInterface::ImageKeywordlistType ImageMetadataInterface::GetImageKeywordlist(const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType ImageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist);
}
return ( ImageKeywordlist );
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetPhysicalBias( const MetaDataDictionaryType & dict ) const
{
if(IsSpot(dict))
{
return GetSpotPhysicalBias(dict);
}
if(IsIkonos(dict))
{
return GetIkonosPhysicalBias(dict);
}
if(IsQuickbird(dict))
{
return GetQuickbirdPhysicalBias(dict);
}
VariableLengthVectorType output(1);
output.Fill(0);
return output;
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetPhysicalGain( const MetaDataDictionaryType & dict ) const
{
if(IsSpot(dict))
{
return GetSpotPhysicalGain(dict);
}
if(IsIkonos(dict))
{
return GetIkonosPhysicalGain(dict);
}
if(IsQuickbird(dict))
{
return GetQuickbirdPhysicalGain(dict);
}
VariableLengthVectorType output(1);
output.Fill(1);
return output;
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetSolarIrradiance( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType imageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist);
}
VariableLengthVectorType outputValuesVariableLengthVector;
ossimKeywordlist kwl;
imageKeywordlist.convertToOSSIMKeywordlist(kwl);
if(IsSpot(dict)) // and QB?
{
std::string key= "support_data.solar_irradiance";
ossimString keywordString = kwl.find(key.c_str());
ossimString separatorList = " ";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
std::vector<double> outputValues;
for (unsigned int i=0; i < keywordStrings.size(); ++i)
{
if (!keywordStrings[i].empty())
{
outputValues.push_back(keywordStrings[i].toDouble());
}
}
outputValuesVariableLengthVector.SetSize(outputValues.size());
outputValuesVariableLengthVector.Fill(0);
//In the case of SPOT, the bands are in a different order:
// XS3, XS2. XS1, SWIR in the tif file.
if(IsSpot(dict))
{
//assert(outputValues.size() == 4);//Valid for Spot 4 and 5
if(outputValues.size() != 4)
itkGenericExceptionMacro(<<"Invalid Solar Irradiance");
outputValuesVariableLengthVector[0]=outputValues[2];
outputValuesVariableLengthVector[1]=outputValues[1];
outputValuesVariableLengthVector[2]=outputValues[0];
outputValuesVariableLengthVector[3]=outputValues[3];
}
else
{
for(unsigned int i=0; i<outputValues.size(); ++i)
{
outputValuesVariableLengthVector[i]=outputValues[i];
}
}
}
else if(IsIkonos(dict))
{
outputValuesVariableLengthVector.SetSize(1);
// values from geoeye
std::string key= "support_data.band_name";
ossimString keywordString = kwl.find(key.c_str());
if(keywordString=="Pan")
{
outputValuesVariableLengthVector[0] = 1375.8;
}
else if(keywordString=="Blue")
{
outputValuesVariableLengthVector[0] = 1930.9;
}
else if(keywordString=="Green")
{
outputValuesVariableLengthVector[0] = 1854.8;
}
else if(keywordString=="Red")
{
outputValuesVariableLengthVector[0] = 1556.5;
}
else if(keywordString=="NIR")
{
outputValuesVariableLengthVector[0] = 1156.9;
}
}
else if(IsQuickbird(dict))
{
std::string keyBId= "support_data.band_id";
ossimString keywordStringBId = kwl.find(keyBId.c_str());
if( keywordStringBId == ossimString("P") )
{
outputValuesVariableLengthVector.SetSize(1);
outputValuesVariableLengthVector.Fill(1381.79);
}
else if(keywordStringBId == ossimString("Multi") )
{
outputValuesVariableLengthVector.SetSize(4);
outputValuesVariableLengthVector[0]=1924.59;
outputValuesVariableLengthVector[1]=1843.08;
outputValuesVariableLengthVector[2]=1574.77;
outputValuesVariableLengthVector[3]=1113.71;
}
else
{
itkExceptionMacro(<<"Invalid bandID "<<keywordStringBId);
}
}
return outputValuesVariableLengthVector;
}
double ImageMetadataInterface::GetSunElevation( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType imageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist);
}
ossimKeywordlist kwl;
imageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key= "support_data.elevation_angle";
ossimString keywordString = kwl.find(key.c_str());
return keywordString.toDouble();
}
double ImageMetadataInterface::GetSunAzimuth( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType imageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist);
}
ossimKeywordlist kwl;
imageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key= "support_data.azimuth_angle";
ossimString keywordString = kwl.find(key.c_str());
return keywordString.toDouble();
}
int ImageMetadataInterface::GetDay( const MetaDataDictionaryType & dict ) const
{
//The image date in the ossim metadata has the form: 2007-10-03T03:17:16.973000
ImageKeywordlistType imageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist);
}
ossimKeywordlist kwl;
imageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key;
ossimString separatorList;
if(IsSpot(dict))
{
key = "support_data.image_date";
separatorList = "-T";
}
if(IsIkonos(dict))
{
key = "support_data.production_date";
separatorList = "/";
}
if(IsQuickbird(dict))
{
key = "support_data.tlc_date";
separatorList = "-T";
}
ossimString keywordString = kwl.find(key.c_str());
//ossimString separatorList = "-T";
//std::string key= "support_data.image_date";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
//assert(keywordStrings.size() > 2);
if(keywordStrings.size() <= 2)
itkExceptionMacro(<<"Invalid Day");
ossimString day = keywordStrings[2];
if(IsIkonos(dict))
{
// MM/DD/YY
day = keywordStrings[1];
}
return day.toInt();
}
int ImageMetadataInterface::GetMonth( const MetaDataDictionaryType & dict ) const
{
//The image date in the ossim metadata has the form: 2007-10-03T03:17:16.973000
ImageKeywordlistType imageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist);
}
ossimKeywordlist kwl;
imageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key;
ossimString separatorList;
if(IsSpot(dict))
{
key = "support_data.image_date";
separatorList = "-T";
}
if(IsIkonos(dict))
{
key = "support_data.production_date";
separatorList = "/";
}
if(IsQuickbird(dict))
{
key = "support_data.tlc_date";
separatorList = "-T";
}
ossimString keywordString = kwl.find(key.c_str());
//ossimString separatorList = "-T";
//std::string key= "support_data.image_date";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
//assert(keywordStrings.size() > 2);
if(keywordStrings.size() <= 2)
itkExceptionMacro(<<"Invalid Month");
ossimString month = keywordStrings[1];
if(IsIkonos(dict))
{
month = keywordStrings[0];
}
return month.toInt();
}
int ImageMetadataInterface::GetYear( const MetaDataDictionaryType & dict ) const
{
//The image date in the ossim metadata has the form: 2007-10-03T03:17:16.973000
ImageKeywordlistType imageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist);
}
ossimKeywordlist kwl;
imageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key;
ossimString separatorList;
if(IsSpot(dict))
{
key = "support_data.image_date";
separatorList = "-T";
}
if(IsIkonos(dict))
{
key = "support_data.production_date";
separatorList = "/";
}
if(IsQuickbird(dict))
{
key = "support_data.tlc_date";
separatorList = "-T";
}
ossimString keywordString = kwl.find(key.c_str());
//ossimString separatorList = "-T";
//std::string key= "support_data.image_date";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
//assert(keywordStrings.size() > 2);
if( keywordStrings.size() <= 2 )
itkExceptionMacro("Invalid Year");
ossimString year = keywordStrings[0];
// For Ikonos 2002 is 02
if(IsIkonos(dict))
{
year = keywordStrings[2];
year = "20"+year;
}
return year.toInt();
//return keywordStrings[0].toInt();
}
std::string ImageMetadataInterface::GetSensorID( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType ImageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist);
}
ossimKeywordlist kwl;
ImageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key= "sensor";
ossimString keywordString = kwl.find(key.c_str());
std::string output(keywordString.chars());
return output;
}
unsigned int ImageMetadataInterface::GetNumberOfBands( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType ImageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist);
}
ossimKeywordlist kwl;
ImageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key= "support_data.number_bands";
ossimString keywordString = kwl.find(key.c_str());
return keywordString.toUInt32();
}
std::vector<std::string> ImageMetadataInterface::GetBandName( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType ImageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist);
}
ossimKeywordlist kwl;
ImageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key= "support_data.band_name";
ossimString keywordString = kwl.find(key.c_str());
ossimString separatorList = " ";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
std::vector<std::string> outputValues;
for (unsigned int i=0; i < keywordStrings.size(); ++i)
{
if (!keywordStrings[i].empty())
{
outputValues.push_back(keywordStrings[i].chars());
}
}
return outputValues;
}
bool ImageMetadataInterface::IsSpot( const MetaDataDictionaryType & dict ) const
{
std::string sensorID = GetSensorID(dict);
if (sensorID.find("Spot") != std::string::npos)
return true;
else
return false;
}
bool ImageMetadataInterface::IsIkonos( const MetaDataDictionaryType & dict ) const
{
std::string sensorID = GetSensorID(dict);
if (sensorID.find("IKONOS-2") != std::string::npos)
return true;
else
return false;
}
bool ImageMetadataInterface::IsQuickbird( const MetaDataDictionaryType & dict ) const
{
std::string sensorID = GetSensorID(dict);
if (sensorID.find("QB02") != std::string::npos)
return true;
else
return false;
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetSpotPhysicalBias( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType imageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist);
}
ossimKeywordlist kwl;
imageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key= "support_data.physical_bias";
ossimString keywordString = kwl.find(key.c_str());
ossimString separatorList = " ";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
std::vector<double> outputValues;
for (unsigned int i=0; i < keywordStrings.size(); ++i)
{
if (!keywordStrings[i].empty())
{
outputValues.push_back(keywordStrings[i].toDouble());
}
}
VariableLengthVectorType outputValuesVariableLengthVector;
outputValuesVariableLengthVector.SetSize(outputValues.size());
outputValuesVariableLengthVector.Fill(0);
//In the case of SPOT, the bands are in a different order:
// XS3, XS2. XS1, SWIR in the tif file.
//assert(outputValues.size() == 4);//Valid for Spot 4 and 5
if( outputValues.size() != 4 )
itkExceptionMacro("Invalid Physical Bias");
outputValuesVariableLengthVector[0]=outputValues[2];
outputValuesVariableLengthVector[1]=outputValues[1];
outputValuesVariableLengthVector[2]=outputValues[0];
outputValuesVariableLengthVector[3]=outputValues[3];
return outputValuesVariableLengthVector;
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetSpotPhysicalGain( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType imageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist);
}
// otbMsgDevMacro( << " --- ImageKeywordlist: " << imageKeywordlist);
ossimKeywordlist kwl;
imageKeywordlist.convertToOSSIMKeywordlist(kwl);
// otbMsgDevMaquitcro( << " --- ossimKeywordlist: " << kwl);
std::string key= "support_data.physical_gain";
ossimString keywordString = kwl.find(key.c_str());
ossimString separatorList = " ";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
std::vector<double> outputValues;
for (unsigned int i=0; i < keywordStrings.size(); ++i)
{
if (!keywordStrings[i].empty())
{
outputValues.push_back(keywordStrings[i].toDouble());
}
}
VariableLengthVectorType outputValuesVariableLengthVector;
outputValuesVariableLengthVector.SetSize(outputValues.size());
outputValuesVariableLengthVector.Fill(0);
//In the case of SPOT, the bands are in a different order:
// XS3, XS2. XS1, SWIR in the tif file.
//assert(outputValues.size() == 4);//Valid for Spot 4 and 5
if( outputValues.size() != 4 )
itkExceptionMacro("Invalid Physical Gain");
outputValuesVariableLengthVector[0]=outputValues[2];
outputValuesVariableLengthVector[1]=outputValues[1];
outputValuesVariableLengthVector[2]=outputValues[0];
outputValuesVariableLengthVector[3]=outputValues[3];
return outputValuesVariableLengthVector;
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetQuickbirdPhysicalBias( const MetaDataDictionaryType & dict ) const
{
ImageKeywordlistType ImageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist);
}
ossimKeywordlist kwl;
ImageKeywordlist.convertToOSSIMKeywordlist(kwl);
VariableLengthVectorType outputValuesVariableLengthVector;
std::string keyBId= "support_data.band_id";
ossimString keywordStringBId = kwl.find(keyBId.c_str());
if( keywordStringBId == ossimString("P") )
{
outputValuesVariableLengthVector.SetSize(1);
outputValuesVariableLengthVector.Fill(0.0);
}
else if(keywordStringBId == ossimString("Multi") )
{
outputValuesVariableLengthVector.SetSize(4);
outputValuesVariableLengthVector.Fill(0.0);
}
else
{
itkExceptionMacro(<<"Invalid bandID "<<keywordStringBId);
}
return outputValuesVariableLengthVector;
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetQuickbirdPhysicalGain( const MetaDataDictionaryType & dict ) const
{
//Values are different pre/post 2003-06-06 production date, find out where we are
ImageKeywordlistType ImageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist);
}
ossimKeywordlist kwl;
ImageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key= "support_data.generation_date";
ossimString keywordString = kwl.find(key.c_str());
std::string output(keywordString.chars());
//The Ikonos production date has the format MM/DD/YY
ossimString separatorList = "-";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
if (keywordStrings.size() < 3)
{
itkGenericExceptionMacro(<<"Could not retrieve the production date for Ikonos");
}
int productionYear = keywordStrings[0].toInt();
int productionMonth = keywordStrings[1].toInt();
int productionDay = keywordStrings[2].toInt();
bool isPost20030606 = false;
if(productionYear > 2003)
isPost20030606 = true;
else
{
if(productionYear == 2003)
{
if(productionMonth > 6)
isPost20030606 = true;
else
if(productionDay >= 6)
isPost20030606 = true;
}
}
//Value computed from
// http://www.geoeye.com/CorpSite/assets/docs/technical-papers/2009/IKONOS_Esun_Calculations.pdf
// to get the equivalent of the SPOT alpha
VariableLengthVectorType gain;
gain.SetSize(5);
if (isPost20030606)
{
gain[0] = 1. / 0.16200;//Pan
gain[1] = 1. / 0.23590;//Blue
gain[2] = 1. / 0.14530;//Green
gain[3] = 1. / 0.17850;//Red
gain[4] = 1. / 0.13530;//NIR
}
else
{
gain[0] = 1;//Pan
gain[1] = 1;//Blue
gain[2] = 1;//Green
gain[3] = 1;//Red
gain[4] = 1;//NIR
}
VariableLengthVectorType outputValuesVariableLengthVector;
std::string keyBId= "support_data.band_id";
ossimString keywordStringBId = kwl.find(keyBId.c_str());
if (keywordStringBId == ossimString("P") )
{
outputValuesVariableLengthVector.SetSize(1);
outputValuesVariableLengthVector[0]=gain[0];
}
// Multi spectral
else if(keywordStringBId == ossimString("Multi") )
{
outputValuesVariableLengthVector.SetSize(4);
outputValuesVariableLengthVector[0]=gain[1];
outputValuesVariableLengthVector[1]=gain[2];
outputValuesVariableLengthVector[2]=gain[3];
outputValuesVariableLengthVector[3]=gain[4];
}
else
{
itkExceptionMacro(<<"Invalid bandID "<<keywordStringBId);
}
return outputValuesVariableLengthVector;
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetIkonosPhysicalBias( const MetaDataDictionaryType & dict ) const
{
VariableLengthVectorType outputValuesVariableLengthVector;
outputValuesVariableLengthVector.SetSize(GetNumberOfBands(dict));
outputValuesVariableLengthVector.Fill(0.0);
return outputValuesVariableLengthVector;
}
ImageMetadataInterface::VariableLengthVectorType
ImageMetadataInterface::GetIkonosPhysicalGain( const MetaDataDictionaryType & dict ) const
{
//Values are different pre/post 2001-01-22 production date, find out where we are
ImageKeywordlistType ImageKeywordlist;
if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey))
{
itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, ImageKeywordlist);
}
ossimKeywordlist kwl;
ImageKeywordlist.convertToOSSIMKeywordlist(kwl);
std::string key= "support_data.production_date";
ossimString keywordString = kwl.find(key.c_str());
std::string output(keywordString.chars());
//The Ikonos production date has the format MM/DD/YY
ossimString separatorList = "/";
std::vector<ossimString> keywordStrings = keywordString.split(separatorList);
if (keywordStrings.size() < 3)
{
itkGenericExceptionMacro(<<"Could not retrieve the production date for Ikonos");
}
int productionYear = keywordStrings[2].toInt();
int productionMonth = keywordStrings[0].toInt();
int productionDay = keywordStrings[1].toInt();
bool isPost20010122 = false;
if ((productionYear > 2) || (productionYear < 99)) isPost20010122 = true;
else
{
if (productionYear == 2)
{
if (productionMonth > 1) isPost20010122 = true;
else
if (productionDay >= 22) isPost20010122 = true;
}
}
//Value computed from
// http://www.geoeye.com/CorpSite/assets/docs/technical-papers/2009/IKONOS_Esun_Calculations.pdf
// to get the equivalent of the SPOT alpha
VariableLengthVectorType gain;
gain.SetSize(5);
if (isPost20010122)
{
gain[0] = 6.48830;//Pan
gain[1] = 5.19064;//Blue
gain[2] = 6.44122;//Green
gain[3] = 6.24442;//Red
gain[4] = 8.04222;//NIR
}
else
{
gain[0] = 6.48830;//Pan
gain[1] = 4.51329;//Blue
gain[2] = 5.75014;//Green
gain[3] = 5.52720;//Red
gain[4] = 7.11684;//NIR
}
std::vector<std::string> bandName = GetBandName(dict);
VariableLengthVectorType outputValuesVariableLengthVector;
unsigned int numBands = GetNumberOfBands(dict);
outputValuesVariableLengthVector.SetSize(numBands);
for(unsigned int i=0; i<numBands; ++i)
{
if (bandName[i].find("Pan") != std::string::npos)
outputValuesVariableLengthVector[i]=gain[0];
if (bandName[i].find("Blue") != std::string::npos)
outputValuesVariableLengthVector[i]=gain[1];
if (bandName[i].find("Green") != std::string::npos)
outputValuesVariableLengthVector[i]=gain[2];
if (bandName[i].find("Red") != std::string::npos)
outputValuesVariableLengthVector[i]=gain[3];
if (bandName[i].find("NIR") != std::string::npos)
outputValuesVariableLengthVector[i]=gain[4];
}
return outputValuesVariableLengthVector;
}
void
ImageMetadataInterface::PrintSelf(std::ostream& os, itk::Indent indent, const MetaDataDictionaryType & dict) const
{
std::vector<std::string> keys = dict.GetKeys();
std::string svalue;
unsigned int ivalue(0);
VectorType vvalue;
double dvalue = 0.;
OTB_GCP gcpvalue;
ImageKeywordlist ossimvalue;
VectorDataKeywordlist vectorDataKeywordlistValue;
unsigned int i(0);
// Copy of the const metadata dictionary in a metadata dictionary to be used
// by the ExposeMetaData method
MetaDataDictionaryType dict2 = dict;
MetaDataKey key;
for (unsigned int itkey=0; itkey<keys.size(); ++itkey)
{
switch ( key.GetKeyType(keys[itkey]) )
{
case MetaDataKey::TSTRING:
itk::ExposeMetaData<std::string>(dict2, keys[itkey], svalue);
os << indent << "---> " << keys[itkey] << " = " << svalue << std::endl;
break;
case MetaDataKey::TENTIER:
itk::ExposeMetaData<unsigned int>(dict2, keys[itkey], ivalue);
os << indent << "---> " << keys[itkey] << " = " << ivalue << std::endl;
break;
case MetaDataKey::TVECTOR:
itk::ExposeMetaData<VectorType>(dict2, keys[itkey], vvalue);
for (i = 0; i < vvalue.size(); ++i )
{
os << indent << "---> " << keys[itkey] << "[" << i <<"] = "<< vvalue[i]<< std::endl;
}
vvalue.clear();
break;
case MetaDataKey::TDOUBLE:
itk::ExposeMetaData<double>(dict2, keys[itkey], dvalue);
os << indent << "---> " << keys[itkey] << " = " << dvalue << std::endl;
break;
case MetaDataKey::TOTB_GCP:
itk::ExposeMetaData<OTB_GCP>(dict2, keys[itkey], gcpvalue);
os << indent << "---> " << keys[itkey] << std::endl;
gcpvalue.Print(os);
break;
case MetaDataKey::TOSSIMKEYWORDLIST:
itk::ExposeMetaData<ImageKeywordlist>(dict2, keys[itkey], ossimvalue);
os << indent << "---> " << keys[itkey] << std::endl;
ossimvalue.Print(os);
// ossimvalue.Print(os);
break;
case MetaDataKey::TVECTORDATAKEYWORDLIST:
itk::ExposeMetaData<VectorDataKeywordlist>(dict2, keys[itkey], vectorDataKeywordlistValue);
os << indent << "---> " << keys[itkey] << std::endl;
vectorDataKeywordlistValue.Print(os);
break;
default:
break;
}
}
}
} // end namespace otb
|
// Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#include "../Math/Vector.h"
#include "../Utility/Streams/XmlStreamFormatter.h"
#include "../Utility/Streams/StreamDom.h"
#include "../Utility/UTFUtils.h"
#include "../Utility/Conversion.h"
#include "../Utility/ParameterBox.h"
#include "../ConsoleRig/Log.h"
namespace std
{
inline MAKE_LOGGABLE(StreamLocation, loc, os)
{
os << "Line: " << loc._lineIndex << ", Char: " << loc._charIndex;
return os;
}
inline MAKE_LOGGABLE(XmlInputStreamFormatter<utf8>::InteriorSection, section, os)
{
os << Conversion::Convert<std::basic_string<char>>(
std::basic_string<utf8>(section._start, section._end));
return os;
}
}
namespace ColladaConversion
{
using Formatter = XmlInputStreamFormatter<utf8>;
using Section = Formatter::InteriorSection;
using SubDoc = Utility::Document<Formatter>;
using String = std::basic_string<Formatter::value_type>;
template <typename Type, int Count>
cml::vector<Type, cml::fixed<Count>> ParseValueType(
Formatter& formatter, const cml::vector<Type, cml::fixed<Count>>& def);
template <typename Type>
Type ParseValueType(Formatter& formatter, Type& def);
template<typename Section>
static std::string AsString(const Section& section)
{
using CharType = std::remove_const<std::remove_reference<decltype(*section._start)>::type>::type;
return Conversion::Convert<std::string>(
std::basic_string<CharType>(section._start, section._end));
}
class AssetDesc
{
public:
float _metersPerUnit;
enum class UpAxis { X, Y, Z };
UpAxis _upAxis;
AssetDesc();
AssetDesc(XmlInputStreamFormatter<utf8>& formatter);
};
class Effect;
class ColladaDocument
{
public:
void Parse(XmlInputStreamFormatter<utf8>& formatter);
void Parse_LibraryEffects(XmlInputStreamFormatter<utf8>& formatter);
void Parse_LibraryGeometries(XmlInputStreamFormatter<utf8>& formatter);
ColladaDocument();
~ColladaDocument();
protected:
AssetDesc _rootAsset;
std::vector<Effect> _effects;
};
bool Is(XmlInputStreamFormatter<utf8>::InteriorSection& section, const utf8 match[])
{
return !XlComparePrefix(match, section._start, section._end - section._start);
}
bool StartsWith(XmlInputStreamFormatter<utf8>::InteriorSection& section, const utf8 match[])
{
auto matchLen = XlStringLen(match);
if ((section._end - section._start) < ptrdiff_t(matchLen)) return false;
return !XlComparePrefix(section._start, match, matchLen);
}
using RootElementParser = void (ColladaDocument::*)(XmlInputStreamFormatter<utf8>&);
static std::pair<const utf8*, RootElementParser> s_rootElements[] =
{
std::make_pair(u("library_effects"), &ColladaDocument::Parse_LibraryEffects),
std::make_pair(u("library_geometries"), &ColladaDocument::Parse_LibraryGeometries)
};
AssetDesc::AssetDesc()
{
_metersPerUnit = 1.f;
_upAxis = UpAxis::Z;
}
AssetDesc::AssetDesc(XmlInputStreamFormatter<utf8>& formatter)
: AssetDesc()
{
using Formatter = XmlInputStreamFormatter<utf8>;
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
continue;
}
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
if (Is(eleName, u("unit"))) {
Utility::Document<Formatter> doc(formatter);
_metersPerUnit = doc(u("meter"), _metersPerUnit);
} else if (Is(eleName, u("up_axis"))) {
if (formatter.TryCharacterData(eleName)) {
if ((eleName._end - eleName._start) >= 1) {
switch (std::tolower(*eleName._start)) {
case 'x': _upAxis = UpAxis::X; break;
case 'y': _upAxis = UpAxis::Y; break;
case 'z': _upAxis = UpAxis::Z; break;
}
}
}
} else
formatter.SkipElement();
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
default:
break;
}
break;
}
}
void ColladaDocument::Parse(XmlInputStreamFormatter<utf8>& formatter)
{
using Formatter = XmlInputStreamFormatter<utf8>;
Formatter::InteriorSection rootEle;
if (!formatter.TryBeginElement(rootEle) || !Is(rootEle, u("COLLADA")))
Throw(FormatException("Expecting root COLLADA element", formatter.GetLocation()));
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection ele;
formatter.TryBeginElement(ele);
if (Is(ele, u("asset"))) {
_rootAsset = AssetDesc(formatter);
} else {
bool found = false;
for (unsigned c=0; c<dimof(s_rootElements); ++c)
if (Is(ele, s_rootElements[c].first)) {
(this->*(s_rootElements[c].second))(formatter);
found = true;
break;
}
if (!found) {
LogWarning << "Skipping element " << AsString(ele);
formatter.SkipElement();
}
}
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::EndElement:
break; // hit the end of file
case Formatter::Blob::AttributeName:
{
// we should scan for collada version here
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
continue;
}
default:
Throw(FormatException("Unexpected blob", formatter.GetLocation()));
}
break;
}
}
enum class SamplerAddress
{
Wrap, Mirror, Clamp, Border, MirrorOnce
};
enum class SamplerFilter { Point, Linear, Anisotropic };
enum class SamplerDimensionality { T2D, T3D, Cube };
class ParameterSet
{
public:
class BasicParameter
{
public:
Section _sid;
Section _type;
Section _value;
};
std::vector<BasicParameter> _parameters;
class SamplerParameter
{
public:
Section _sid;
Section _type;
Section _image;
SamplerDimensionality _dimensionality;
SamplerAddress _addressS;
SamplerAddress _addressT;
SamplerAddress _addressQ;
SamplerFilter _minFilter;
SamplerFilter _maxFilter;
SamplerFilter _mipFilter;
Float4 _borderColor;
unsigned _minMipLevel;
unsigned _maxMipLevel;
float _mipMapBias;
unsigned _maxAnisotrophy;
SubDoc _extra;
SamplerParameter();
SamplerParameter(Formatter& formatter);
~SamplerParameter();
};
std::vector<SamplerParameter> _samplerParameters;
void ParseParam(Formatter& formatter);
ParameterSet();
~ParameterSet();
ParameterSet(ParameterSet&& moveFrom);
ParameterSet& operator=(ParameterSet&&);
};
ParameterSet::SamplerParameter::SamplerParameter()
{
_dimensionality = SamplerDimensionality::T2D;
_addressS = _addressT = _addressQ = SamplerAddress::Wrap;
_minFilter = _maxFilter = _mipFilter = SamplerFilter::Point;
_borderColor = Float4(1.f, 1.f, 1.f, 1.f);
_minMipLevel = 0;
_maxMipLevel = 255;
_mipMapBias = 0.f;
_maxAnisotrophy = 1;
}
static Section ExtractSingleAttribute(Formatter& formatter, const Formatter::value_type attribName[])
{
Section result;
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
formatter.SkipElement();
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
if (Is(name, attribName)) result = value;
continue;
}
}
break;
}
return result;
}
std::pair<SamplerAddress, const utf8*> s_SamplerAddressNames[] =
{
std::make_pair(SamplerAddress::Wrap, u("WRAP")),
std::make_pair(SamplerAddress::Mirror, u("MIRROR")),
std::make_pair(SamplerAddress::Clamp, u("CLAMP")),
std::make_pair(SamplerAddress::Border, u("BORDER")),
std::make_pair(SamplerAddress::MirrorOnce, u("MIRROR_ONE")),
std::make_pair(SamplerAddress::Wrap, u("REPEAT")),
std::make_pair(SamplerAddress::Mirror, u("MIRROR_REPEAT"))
// CLAMP_TO_EDGE not supported
};
std::pair<SamplerFilter, const utf8*> s_SamplerFilterNames[] =
{
std::make_pair(SamplerFilter::Point, u("NONE")),
std::make_pair(SamplerFilter::Point, u("NEAREST")),
std::make_pair(SamplerFilter::Linear, u("LINEAR")),
std::make_pair(SamplerFilter::Anisotropic, u("ANISOTROPIC"))
};
template <typename Enum, unsigned Count>
static Enum ParseEnum(Formatter& formatter, const std::pair<Enum, const utf8*> (&table)[Count])
{
Formatter::InteriorSection section;
if (!formatter.TryCharacterData(section)) return table[0].first;
for (unsigned c=0; c<Count; ++c)
if (!Is(section, table[c].second))
return table[c].first;
return table[0].first; // first one is the default
}
ParameterSet::SamplerParameter::SamplerParameter(Formatter& formatter)
: SamplerParameter()
{
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
if (Is(eleName, u("instance_image"))) {
// collada 1.5 uses "instance_image" (Collada 1.4 equivalent is <source>)
_image = ExtractSingleAttribute(formatter, u("url"));
} else if (Is(eleName, u("source"))) {
// collada 1.4 uses "source" (which cannot have extra data attached)
formatter.TryCharacterData(_image);
} else if (Is(eleName, u("wrap_s"))) {
_addressS = ParseEnum(formatter, s_SamplerAddressNames);
} else if (Is(eleName, u("wrap_t"))) {
_addressT = ParseEnum(formatter, s_SamplerAddressNames);
} else if (Is(eleName, u("wrap_p"))) {
_addressQ = ParseEnum(formatter, s_SamplerAddressNames);
} else if (Is(eleName, u("minfilter"))) {
_minFilter = ParseEnum(formatter, s_SamplerFilterNames);
} else if (Is(eleName, u("magfilter"))) {
_maxFilter = ParseEnum(formatter, s_SamplerFilterNames);
} else if (Is(eleName, u("mipfilter"))) {
_mipFilter = ParseEnum(formatter, s_SamplerFilterNames);
} else if (Is(eleName, u("border_color"))) {
_borderColor = ParseValueType(formatter, _borderColor);
} else if (Is(eleName, u("mip_max_level"))) {
_maxMipLevel = ParseValueType(formatter, _maxMipLevel);
} else if (Is(eleName, u("mip_min_level"))) {
_minMipLevel = ParseValueType(formatter, _minMipLevel);
} else if (Is(eleName, u("mip_bias"))) {
_mipMapBias = ParseValueType(formatter, _mipMapBias);
} else if (Is(eleName, u("max_anisotropy"))) {
_maxAnisotrophy = ParseValueType(formatter, _maxAnisotrophy);
} else if (Is(eleName, u("extra"))) {
_extra = SubDoc(formatter);
} else {
formatter.SkipElement();
}
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
LogWarning << "Sampler objects should not have any attributes. At " << formatter.GetLocation();
continue;
}
}
break;
}
}
ParameterSet::SamplerParameter::~SamplerParameter() {}
void ParameterSet::ParseParam(Formatter& formatter)
{
Formatter::InteriorSection sid;
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
if (Is(eleName, u("annotate")) || Is(eleName, u("semantic")) || Is(eleName, u("modifier"))) {
formatter.SkipElement();
} else {
if (!Is(eleName, u("sampler"))) {
_samplerParameters.push_back(SamplerParameter(formatter));
} else {
// this is a basic parameter, typically a scalar, vector or matrix
// we don't need to parse it fully now; just get the location of the
// data and store it as a new parameter
Formatter::InteriorSection cdata;
if (formatter.TryCharacterData(cdata)) {
_parameters.push_back(BasicParameter{sid, eleName, cdata});
} else
LogWarning << "Expecting element with parameter data " << formatter.GetLocation();
}
}
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
if (Is(name, u("sid"))) sid = value;
continue;
}
}
break;
}
}
ParameterSet::ParameterSet() {}
ParameterSet::~ParameterSet() {}
ParameterSet::ParameterSet(ParameterSet&& moveFrom)
: _parameters(std::move(moveFrom._parameters))
, _samplerParameters(std::move(moveFrom._samplerParameters))
{
}
ParameterSet& ParameterSet::operator=(ParameterSet&& moveFrom)
{
_parameters = std::move(moveFrom._parameters);
_samplerParameters = std::move(moveFrom._samplerParameters);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
class TechniqueValue
{
public:
enum class Type { Color, Texture, Float, Param, None };
Type _type;
Section _reference; // texture or parameter reference
Section _texCoord;
Float4 _value;
TechniqueValue(Formatter& formatter);
};
class Effect
{
public:
Section _name;
Section _id;
ParameterSet _params;
class Profile
{
public:
ParameterSet _params;
String _profileType;
String _shaderName; // (phong, blinn, etc)
std::vector<std::pair<String, TechniqueValue>> _values;
SubDoc _extra;
SubDoc _techniqueExtra;
Profile(Formatter& formatter, String profileType);
Profile(Profile&& moveFrom);
Profile& operator=(Profile&& moveFrom);
protected:
void ParseTechnique(Formatter& formatter);
void ParseShaderType(Formatter& formatter);
};
std::vector<Profile> _profiles;
SubDoc _extra;
Effect(Formatter& formatter);
Effect(Effect&& moveFrom);
Effect& operator=(Effect&& moveFrom);
};
Effect::Profile::Profile(Formatter& formatter, String profileType)
: _profileType(profileType)
{
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
if (Is(eleName, u("newparam"))) {
_params.ParseParam(formatter);
} else if (Is(eleName, u("extra"))) {
_extra = SubDoc(formatter);
} else if (Is(eleName, u("technique"))) {
ParseTechnique(formatter);
} else {
// asset
formatter.SkipElement();
}
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
continue;
}
}
break;
}
}
Effect::Profile::Profile(Profile&& moveFrom)
: _params(std::move(moveFrom._params))
, _profileType(std::move(moveFrom._profileType))
, _shaderName(std::move(moveFrom._shaderName))
, _values(std::move(moveFrom._values))
, _extra(std::move(moveFrom._extra))
, _techniqueExtra(std::move(moveFrom._techniqueExtra))
{
}
auto Effect::Profile::operator=(Profile&& moveFrom) -> Profile&
{
_params = std::move(moveFrom._params);
_profileType = std::move(moveFrom._profileType);
_shaderName = std::move(moveFrom._shaderName);
_values = std::move(moveFrom._values);
_extra = std::move(moveFrom._extra);
_techniqueExtra = std::move(moveFrom._techniqueExtra);
return *this;
}
void Effect::Profile::ParseTechnique(Formatter& formatter)
{
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
// Note that we skip a lot of the content in techniques
// importantly, we skip "pass" elements. "pass" is too tightly
// bound to the structure of Collada FX. It makes it difficult
// to extract the particular properties we want, and transform
// them into something practical.
if (Is(eleName, u("extra"))) {
_extra = SubDoc(formatter);
} else if (Is(eleName, u("asset")) || Is(eleName, u("annotate")) || Is(eleName, u("pass"))) {
formatter.SkipElement();
} else {
// Any other elements are seen as a shader definition
// There should be exactly 1.
_shaderName = String(eleName._start, eleName._end);
ParseShaderType(formatter);
}
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
continue;
}
}
break;
}
}
template<typename CharType>
bool IsWhitespace(CharType chr)
{
return chr == 0x20 || chr == 0x9 || chr == 0xD || chr == 0xA;
}
template<typename CharType>
static const CharType* FastParseElement(int64& dst, const CharType* start, const CharType* end)
{
bool positive = true;
dst = 0;
if (start >= end) return start;
if (*start == '-') { positive = false; ++start; }
else if (*start == '+') ++start;
uint64 result = 0;
for (;;) {
if (start >= end) break;
if (*start < '0' || *start > '9') break;
result = (result * 10ull) + uint64((*start) - '0');
}
return positive ? result : -result;
}
template<typename CharType>
static const CharType* FastParseElement(uint64& dst, const CharType* start, const CharType* end)
{
uint64 result = 0;
for (;;) {
if (start >= end) break;
if (*start < '0' || *start > '9') break;
result = (result * 10ull) + uint64((*start) - '0');
}
return result;
}
template<typename CharType>
static const CharType* FastParseElement(float& dst, const CharType* start, const CharType* end)
{
// this code found on stack exchange...
// (http://stackoverflow.com/questions/98586/where-can-i-find-the-worlds-fastest-atof-implementation)
// But there are some problems!
// Most importantly:
// Sub-normal numbers are not handled properly. Subnormal numbers happen when the exponent
// is the smallest is can be. In this case, values in the mantissa are evenly spaced around
// zero.
//
// It does other things right. But I don't think it's reliable enough to use. It's a pity because
// the standard library functions require null terminated strings, and seems that it may be possible
// to get a big performance improvement loss of few features.
// to avoid making a copy, we're going do a hack and
// We're assuming that "end" is writable memory. This will be the case when parsing
// values from XML. But in other cases, it may not be reliable.
// Also, consider that there might be threading implications in some cases!
CharType replaced = *end;
*const_cast<CharType*>(end) = '\0';
char* newEnd = nullptr;
dst = std::strtof((const char*)start, &newEnd);
*const_cast<CharType*>(end) = replaced;
return (const CharType*)newEnd;
}
template<typename Type>
static unsigned ParseXMLList(Type dest[], unsigned destCount, Section section)
{
assert(destCount > 0);
// in xml, lists are deliminated by white space
unsigned elementCount = 0;
auto* eleStart = section._start;
for (;;) {
while (eleStart < section._end && IsWhitespace(*eleStart)) ++eleStart;
auto* eleEnd = FastParseElement(dest[elementCount], eleStart, section._end);
if (eleStart == eleEnd) return elementCount;
++elementCount;
if (elementCount >= destCount) return elementCount;
eleStart = eleEnd;
}
}
template <typename Type, int Count>
cml::vector<Type, cml::fixed<Count>> ParseValueType(
Formatter& formatter, // Formatter::InteriorSection storedType,
const cml::vector<Type, cml::fixed<Count>>& def)
{
Formatter::InteriorSection cdata;
// auto type = HLSLTypeNameAsTypeDesc(
// Conversion::Convert<std::string>(String(storedType._start, storedType._end)).c_str());
// if (type._type == ImpliedTyping::TypeCat::Void) {
// type._type = ImpliedTyping::TypeCat::Float;
// type._arrayCount = 1;
// }
if (formatter.TryCharacterData(cdata)) {
cml::vector<Type, cml::fixed<Count>> result;
unsigned elementsRead = ParseXMLList(&result[0], Count, cdata);
for (unsigned c=elementsRead; c<Count; ++c)
result[c] = def[c];
return result;
} else {
LogWarning << "Expecting vector data at " << formatter.GetLocation();
return def;
}
}
template <typename Type>
Type ParseValueType(Formatter& formatter, Type& def)
{
Formatter::InteriorSection cdata;
if (formatter.TryCharacterData(cdata)) {
auto p = ImpliedTyping::Parse<Type>(cdata._start, cdata._end);
if (!p.first) return def;
return p.second;
} else {
LogWarning << "Expecting scalar data at " << formatter.GetLocation();
return def;
}
}
TechniqueValue::TechniqueValue(Formatter& formatter)
{
_type = Type::None;
// there can be attributes in the containing element -- which should should skip now
{
Formatter::InteriorSection name, value;
while (formatter.TryAttribute(name, value)) {}
}
// We should find exactly one element, which should be
// of "color", "param", "texture" or "float" type
Formatter::InteriorSection eleName;
if (!formatter.TryBeginElement(eleName))
Throw(FormatException("Expecting element for technique value", formatter.GetLocation()));
{
// skip all attributes (sometimes get "sid" tags)
while (formatter.PeekNext(true) == Formatter::Blob::AttributeName) {
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
}
}
if (Is(eleName, u("float"))) {
_value = ParseValueType(formatter, _value);
_type = Type::Float;
} else if (Is(eleName, u("color"))) {
Formatter::InteriorSection cdata;
if (formatter.TryCharacterData(cdata)) {
ParseXMLList(&_value[0], 4, cdata);
_type = Type::Color;
} else
LogWarning << "no data in color value at " << formatter.GetLocation();
} else if (Is(eleName, u("texture"))) {
for (;;) {
Formatter::InteriorSection name, value;
if (!formatter.TryAttribute(name, value)) break;
if (Is(name, u("texture"))) _reference = value;
else if (Is(name, u("texcoord"))) _texCoord = value;
else LogWarning << "Unknown attribute for texture (" << name << ") at " << formatter.GetLocation();
}
_type = Type::Texture;
} else if (Is(eleName, u("param"))) {
Formatter::InteriorSection name, value;
if (!formatter.TryAttribute(name, value) || !Is(name, u("ref"))) {
LogWarning << "Expecting ref attribute in param technique value at " << formatter.GetLocation();
} else {
_reference = value;
_type = Type::Param;
}
} else
Throw(FormatException("Expect either float, color, param or texture element", formatter.GetLocation()));
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
}
void Effect::Profile::ParseShaderType(Formatter& formatter)
{
// This is one of several types of shading equations defined
// by Collada (eg, blinn, phong, lambert)
//
// "shader type" elements just contain a list of parameters,
// each of which can have a value of any of these types:
// <color> <float> <texture> or <param>
//
// Also, there's are special cases for <transparent> and <transparency>
// -- they seem a little strange, actually
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
_values.push_back(
std::make_pair(
String(eleName._start, eleName._end),
TechniqueValue(formatter)));
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
continue;
}
}
break;
}
}
Effect::Effect(Formatter& formatter)
{
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
if (Is(eleName, u("newparam"))) {
_params.ParseParam(formatter);
} else if (StartsWith(eleName, u("profile_"))) {
_profiles.push_back(Profile(formatter, String(eleName._start+8, eleName._end)));
} else if (Is(eleName, u("extra"))) {
_extra = SubDoc(formatter);
} else {
// asset, annotate
formatter.SkipElement();
}
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
if (Is(name, u("name"))) _name = value;
else if (Is(name, u("id"))) _id = value;
continue;
}
}
break;
}
}
Effect::Effect(Effect&& moveFrom)
: _name(moveFrom._name)
, _id(moveFrom._id)
, _params(std::move(moveFrom._params))
, _profiles(std::move(moveFrom._profiles))
, _extra(std::move(moveFrom._extra))
{}
Effect& Effect::operator=(Effect&& moveFrom)
{
_name = moveFrom._name;
_id = moveFrom._id;
_params = std::move(moveFrom._params);
_profiles = std::move(moveFrom._profiles);
_extra = std::move(moveFrom._extra);
return *this;
}
void ColladaDocument::Parse_LibraryEffects(XmlInputStreamFormatter<utf8>& formatter)
{
using Formatter = XmlInputStreamFormatter<utf8>;
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
if (Is(eleName, u("effect"))) {
_effects.push_back(Effect(formatter));
} else {
// "annotate", "asset" and "extra" are also valid
formatter.SkipElement();
}
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
continue;
}
}
break;
}
}
void ColladaDocument::Parse_LibraryGeometries(XmlInputStreamFormatter<utf8>& formatter)
{
formatter.SkipElement();
}
ColladaDocument::ColladaDocument() {}
ColladaDocument::~ColladaDocument() {}
}
#include "../Utility/Streams/FileUtils.h"
#include "NascentModel.h"
void TestParser()
{
size_t size;
auto block = LoadFileAsMemoryBlock("game/testmodels/nyra/Nyra_pose.dae", &size);
using Formatter = XmlInputStreamFormatter<utf8>;
Formatter formatter(MemoryMappedInputStream(block.get(), PtrAdd(block.get(), size)));
ColladaConversion::ColladaDocument doc;
doc.Parse(formatter);
int t = 0;
(void)t;
}
Working on parsing library_geometries
- not compiling currently
// Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#include "../Math/Vector.h"
#include "../Utility/Streams/XmlStreamFormatter.h"
#include "../Utility/Streams/StreamDom.h"
#include "../Utility/UTFUtils.h"
#include "../Utility/Conversion.h"
#include "../Utility/ParameterBox.h"
#include "../ConsoleRig/Log.h"
namespace std // adding these to std is awkward, but it's the only way to make sure easylogging++ can see them
{
inline MAKE_LOGGABLE(StreamLocation, loc, os)
{
os << "Line: " << loc._lineIndex << ", Char: " << loc._charIndex;
return os;
}
// inline MAKE_LOGGABLE(XmlInputStreamFormatter<utf8>::InteriorSection, section, os)
inline std::ostream& operator<<(std::ostream& os, XmlInputStreamFormatter<utf8>::InteriorSection section)
{
os << Conversion::Convert<std::basic_string<char>>(
std::basic_string<utf8>(section._start, section._end));
return os;
}
}
namespace ColladaConversion
{
using Formatter = XmlInputStreamFormatter<utf8>;
using Section = Formatter::InteriorSection;
using SubDoc = Utility::Document<Formatter>;
using String = std::basic_string<Formatter::value_type>;
template <typename Type, int Count>
cml::vector<Type, cml::fixed<Count>> ParseValueType(
Formatter& formatter, const cml::vector<Type, cml::fixed<Count>>& def);
template <typename Type>
Type ParseValueType(Formatter& formatter, Type& def);
template<typename Section>
static std::string AsString(const Section& section)
{
using CharType = std::remove_const<std::remove_reference<decltype(*section._start)>::type>::type;
return Conversion::Convert<std::string>(
std::basic_string<CharType>(section._start, section._end));
}
class AssetDesc
{
public:
float _metersPerUnit;
enum class UpAxis { X, Y, Z };
UpAxis _upAxis;
AssetDesc();
AssetDesc(XmlInputStreamFormatter<utf8>& formatter);
};
class Effect;
class ColladaDocument
{
public:
void Parse(XmlInputStreamFormatter<utf8>& formatter);
void Parse_LibraryEffects(XmlInputStreamFormatter<utf8>& formatter);
void Parse_LibraryGeometries(XmlInputStreamFormatter<utf8>& formatter);
ColladaDocument();
~ColladaDocument();
protected:
AssetDesc _rootAsset;
std::vector<Effect> _effects;
};
bool Is(XmlInputStreamFormatter<utf8>::InteriorSection& section, const utf8 match[])
{
return !XlComparePrefix(match, section._start, section._end - section._start);
}
bool StartsWith(XmlInputStreamFormatter<utf8>::InteriorSection& section, const utf8 match[])
{
auto matchLen = XlStringLen(match);
if ((section._end - section._start) < ptrdiff_t(matchLen)) return false;
return !XlComparePrefix(section._start, match, matchLen);
}
using RootElementParser = void (ColladaDocument::*)(XmlInputStreamFormatter<utf8>&);
static std::pair<const utf8*, RootElementParser> s_rootElements[] =
{
std::make_pair(u("library_effects"), &ColladaDocument::Parse_LibraryEffects),
std::make_pair(u("library_geometries"), &ColladaDocument::Parse_LibraryGeometries)
};
AssetDesc::AssetDesc()
{
_metersPerUnit = 1.f;
_upAxis = UpAxis::Z;
}
AssetDesc::AssetDesc(XmlInputStreamFormatter<utf8>& formatter)
: AssetDesc()
{
using Formatter = XmlInputStreamFormatter<utf8>;
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
continue;
}
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
if (Is(eleName, u("unit"))) {
// Utility::Document<Formatter> doc(formatter);
// _metersPerUnit = doc(u("meter"), _metersPerUnit);
auto meter = ExtractSingleAttribute(formatter, u("meter"));
_metersPerUnit = Parse(meter, _metersPerUnit);
} else if (Is(eleName, u("up_axis"))) {
if (formatter.TryCharacterData(eleName)) {
if ((eleName._end - eleName._start) >= 1) {
switch (std::tolower(*eleName._start)) {
case 'x': _upAxis = UpAxis::X; break;
case 'y': _upAxis = UpAxis::Y; break;
case 'z': _upAxis = UpAxis::Z; break;
}
}
}
} else
formatter.SkipElement();
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
default:
break;
}
break;
}
}
void ColladaDocument::Parse(XmlInputStreamFormatter<utf8>& formatter)
{
using Formatter = XmlInputStreamFormatter<utf8>;
Formatter::InteriorSection rootEle;
if (!formatter.TryBeginElement(rootEle) || !Is(rootEle, u("COLLADA")))
Throw(FormatException("Expecting root COLLADA element", formatter.GetLocation()));
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection ele;
formatter.TryBeginElement(ele);
if (Is(ele, u("asset"))) {
_rootAsset = AssetDesc(formatter);
} else {
bool found = false;
for (unsigned c=0; c<dimof(s_rootElements); ++c)
if (Is(ele, s_rootElements[c].first)) {
(this->*(s_rootElements[c].second))(formatter);
found = true;
break;
}
if (!found) {
LogWarning << "Skipping element " << AsString(ele);
formatter.SkipElement();
}
}
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::EndElement:
break; // hit the end of file
case Formatter::Blob::AttributeName:
{
// we should scan for collada version here
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
continue;
}
default:
Throw(FormatException("Unexpected blob", formatter.GetLocation()));
}
break;
}
}
enum class SamplerAddress
{
Wrap, Mirror, Clamp, Border, MirrorOnce
};
enum class SamplerFilter { Point, Linear, Anisotropic };
enum class SamplerDimensionality { T2D, T3D, Cube };
class ParameterSet
{
public:
class BasicParameter
{
public:
Section _sid;
Section _type;
Section _value;
};
std::vector<BasicParameter> _parameters;
class SamplerParameter
{
public:
Section _sid;
Section _type;
Section _image;
SamplerDimensionality _dimensionality;
SamplerAddress _addressS;
SamplerAddress _addressT;
SamplerAddress _addressQ;
SamplerFilter _minFilter;
SamplerFilter _maxFilter;
SamplerFilter _mipFilter;
Float4 _borderColor;
unsigned _minMipLevel;
unsigned _maxMipLevel;
float _mipMapBias;
unsigned _maxAnisotrophy;
SubDoc _extra;
SamplerParameter();
SamplerParameter(Formatter& formatter);
~SamplerParameter();
};
std::vector<SamplerParameter> _samplerParameters;
void ParseParam(Formatter& formatter);
ParameterSet();
~ParameterSet();
ParameterSet(ParameterSet&& moveFrom) never_throws;
ParameterSet& operator=(ParameterSet&&) never_throws;
};
ParameterSet::SamplerParameter::SamplerParameter()
{
_dimensionality = SamplerDimensionality::T2D;
_addressS = _addressT = _addressQ = SamplerAddress::Wrap;
_minFilter = _maxFilter = _mipFilter = SamplerFilter::Point;
_borderColor = Float4(1.f, 1.f, 1.f, 1.f);
_minMipLevel = 0;
_maxMipLevel = 255;
_mipMapBias = 0.f;
_maxAnisotrophy = 1;
}
static Section ExtractSingleAttribute(Formatter& formatter, const Formatter::value_type attribName[])
{
Section result;
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
formatter.SkipElement();
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
if (Is(name, attribName)) result = value;
continue;
}
}
break;
}
return result;
}
std::pair<SamplerAddress, const utf8*> s_SamplerAddressNames[] =
{
std::make_pair(SamplerAddress::Wrap, u("WRAP")),
std::make_pair(SamplerAddress::Mirror, u("MIRROR")),
std::make_pair(SamplerAddress::Clamp, u("CLAMP")),
std::make_pair(SamplerAddress::Border, u("BORDER")),
std::make_pair(SamplerAddress::MirrorOnce, u("MIRROR_ONE")),
std::make_pair(SamplerAddress::Wrap, u("REPEAT")),
std::make_pair(SamplerAddress::Mirror, u("MIRROR_REPEAT"))
// CLAMP_TO_EDGE not supported
};
std::pair<SamplerFilter, const utf8*> s_SamplerFilterNames[] =
{
std::make_pair(SamplerFilter::Point, u("NONE")),
std::make_pair(SamplerFilter::Point, u("NEAREST")),
std::make_pair(SamplerFilter::Linear, u("LINEAR")),
std::make_pair(SamplerFilter::Anisotropic, u("ANISOTROPIC"))
};
template <typename Enum, unsigned Count>
static Enum ParseEnum(Formatter& formatter, const std::pair<Enum, const utf8*> (&table)[Count])
{
Formatter::InteriorSection section;
if (!formatter.TryCharacterData(section)) return table[0].first;
for (unsigned c=0; c<Count; ++c)
if (!Is(section, table[c].second))
return table[c].first;
return table[0].first; // first one is the default
}
ParameterSet::SamplerParameter::SamplerParameter(Formatter& formatter)
: SamplerParameter()
{
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
if (Is(eleName, u("instance_image"))) {
// collada 1.5 uses "instance_image" (Collada 1.4 equivalent is <source>)
_image = ExtractSingleAttribute(formatter, u("url"));
} else if (Is(eleName, u("source"))) {
// collada 1.4 uses "source" (which cannot have extra data attached)
formatter.TryCharacterData(_image);
} else if (Is(eleName, u("wrap_s"))) {
_addressS = ParseEnum(formatter, s_SamplerAddressNames);
} else if (Is(eleName, u("wrap_t"))) {
_addressT = ParseEnum(formatter, s_SamplerAddressNames);
} else if (Is(eleName, u("wrap_p"))) {
_addressQ = ParseEnum(formatter, s_SamplerAddressNames);
} else if (Is(eleName, u("minfilter"))) {
_minFilter = ParseEnum(formatter, s_SamplerFilterNames);
} else if (Is(eleName, u("magfilter"))) {
_maxFilter = ParseEnum(formatter, s_SamplerFilterNames);
} else if (Is(eleName, u("mipfilter"))) {
_mipFilter = ParseEnum(formatter, s_SamplerFilterNames);
} else if (Is(eleName, u("border_color"))) {
_borderColor = ParseValueType(formatter, _borderColor);
} else if (Is(eleName, u("mip_max_level"))) {
_maxMipLevel = ParseValueType(formatter, _maxMipLevel);
} else if (Is(eleName, u("mip_min_level"))) {
_minMipLevel = ParseValueType(formatter, _minMipLevel);
} else if (Is(eleName, u("mip_bias"))) {
_mipMapBias = ParseValueType(formatter, _mipMapBias);
} else if (Is(eleName, u("max_anisotropy"))) {
_maxAnisotrophy = ParseValueType(formatter, _maxAnisotrophy);
} else if (Is(eleName, u("extra"))) {
_extra = SubDoc(formatter);
} else {
formatter.SkipElement();
}
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
LogWarning << "Sampler objects should not have any attributes. At " << formatter.GetLocation();
continue;
}
}
break;
}
}
ParameterSet::SamplerParameter::~SamplerParameter() {}
void ParameterSet::ParseParam(Formatter& formatter)
{
Formatter::InteriorSection sid;
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
if (Is(eleName, u("annotate")) || Is(eleName, u("semantic")) || Is(eleName, u("modifier"))) {
formatter.SkipElement();
} else {
if (!Is(eleName, u("sampler"))) {
_samplerParameters.push_back(SamplerParameter(formatter));
} else {
// this is a basic parameter, typically a scalar, vector or matrix
// we don't need to parse it fully now; just get the location of the
// data and store it as a new parameter
Formatter::InteriorSection cdata;
if (formatter.TryCharacterData(cdata)) {
_parameters.push_back(BasicParameter{sid, eleName, cdata});
} else
LogWarning << "Expecting element with parameter data " << formatter.GetLocation();
}
}
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
if (Is(name, u("sid"))) sid = value;
continue;
}
}
break;
}
}
ParameterSet::ParameterSet() {}
ParameterSet::~ParameterSet() {}
ParameterSet::ParameterSet(ParameterSet&& moveFrom)
: _parameters(std::move(moveFrom._parameters))
, _samplerParameters(std::move(moveFrom._samplerParameters))
{
}
ParameterSet& ParameterSet::operator=(ParameterSet&& moveFrom)
{
_parameters = std::move(moveFrom._parameters);
_samplerParameters = std::move(moveFrom._samplerParameters);
return *this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
class TechniqueValue
{
public:
enum class Type { Color, Texture, Float, Param, None };
Type _type;
Section _reference; // texture or parameter reference
Section _texCoord;
Float4 _value;
TechniqueValue(Formatter& formatter);
};
class Effect
{
public:
Section _name;
Section _id;
ParameterSet _params;
class Profile
{
public:
ParameterSet _params;
String _profileType;
String _shaderName; // (phong, blinn, etc)
std::vector<std::pair<String, TechniqueValue>> _values;
SubDoc _extra;
SubDoc _techniqueExtra;
Profile(Formatter& formatter, String profileType);
Profile(Profile&& moveFrom) never_throws;
Profile& operator=(Profile&& moveFrom) never_throws;
protected:
void ParseTechnique(Formatter& formatter);
void ParseShaderType(Formatter& formatter);
};
std::vector<Profile> _profiles;
SubDoc _extra;
Effect(Formatter& formatter);
Effect(Effect&& moveFrom) never_throws;
Effect& operator=(Effect&& moveFrom) never_throws;
};
Effect::Profile::Profile(Formatter& formatter, String profileType)
: _profileType(profileType)
{
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
if (Is(eleName, u("newparam"))) {
_params.ParseParam(formatter);
} else if (Is(eleName, u("extra"))) {
_extra = SubDoc(formatter);
} else if (Is(eleName, u("technique"))) {
ParseTechnique(formatter);
} else {
// asset
formatter.SkipElement();
}
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
continue;
}
}
break;
}
}
Effect::Profile::Profile(Profile&& moveFrom)
: _params(std::move(moveFrom._params))
, _profileType(std::move(moveFrom._profileType))
, _shaderName(std::move(moveFrom._shaderName))
, _values(std::move(moveFrom._values))
, _extra(std::move(moveFrom._extra))
, _techniqueExtra(std::move(moveFrom._techniqueExtra))
{
}
auto Effect::Profile::operator=(Profile&& moveFrom) -> Profile&
{
_params = std::move(moveFrom._params);
_profileType = std::move(moveFrom._profileType);
_shaderName = std::move(moveFrom._shaderName);
_values = std::move(moveFrom._values);
_extra = std::move(moveFrom._extra);
_techniqueExtra = std::move(moveFrom._techniqueExtra);
return *this;
}
void Effect::Profile::ParseTechnique(Formatter& formatter)
{
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
// Note that we skip a lot of the content in techniques
// importantly, we skip "pass" elements. "pass" is too tightly
// bound to the structure of Collada FX. It makes it difficult
// to extract the particular properties we want, and transform
// them into something practical.
if (Is(eleName, u("extra"))) {
_extra = SubDoc(formatter);
} else if (Is(eleName, u("asset")) || Is(eleName, u("annotate")) || Is(eleName, u("pass"))) {
formatter.SkipElement();
} else {
// Any other elements are seen as a shader definition
// There should be exactly 1.
_shaderName = String(eleName._start, eleName._end);
ParseShaderType(formatter);
}
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
continue;
}
}
break;
}
}
template<typename CharType>
bool IsWhitespace(CharType chr)
{
return chr == 0x20 || chr == 0x9 || chr == 0xD || chr == 0xA;
}
template<typename CharType>
static const CharType* FastParseElement(int64& dst, const CharType* start, const CharType* end)
{
bool positive = true;
dst = 0;
if (start >= end) return start;
if (*start == '-') { positive = false; ++start; }
else if (*start == '+') ++start;
uint64 result = 0;
for (;;) {
if (start >= end) break;
if (*start < '0' || *start > '9') break;
result = (result * 10ull) + uint64((*start) - '0');
}
return positive ? result : -result;
}
template<typename CharType>
static const CharType* FastParseElement(uint64& dst, const CharType* start, const CharType* end)
{
uint64 result = 0;
for (;;) {
if (start >= end) break;
if (*start < '0' || *start > '9') break;
result = (result * 10ull) + uint64((*start) - '0');
}
return result;
}
template<typename CharType>
static const CharType* FastParseElement(float& dst, const CharType* start, const CharType* end)
{
// this code found on stack exchange...
// (http://stackoverflow.com/questions/98586/where-can-i-find-the-worlds-fastest-atof-implementation)
// But there are some problems!
// Most importantly:
// Sub-normal numbers are not handled properly. Subnormal numbers happen when the exponent
// is the smallest is can be. In this case, values in the mantissa are evenly spaced around
// zero.
//
// It does other things right. But I don't think it's reliable enough to use. It's a pity because
// the standard library functions require null terminated strings, and seems that it may be possible
// to get a big performance improvement loss of few features.
// to avoid making a copy, we're going do a hack and
// We're assuming that "end" is writable memory. This will be the case when parsing
// values from XML. But in other cases, it may not be reliable.
// Also, consider that there might be threading implications in some cases!
CharType replaced = *end;
*const_cast<CharType*>(end) = '\0';
char* newEnd = nullptr;
dst = std::strtof((const char*)start, &newEnd);
*const_cast<CharType*>(end) = replaced;
return (const CharType*)newEnd;
}
template<typename Type>
static unsigned ParseXMLList(Type dest[], unsigned destCount, Section section)
{
assert(destCount > 0);
// in xml, lists are deliminated by white space
unsigned elementCount = 0;
auto* eleStart = section._start;
for (;;) {
while (eleStart < section._end && IsWhitespace(*eleStart)) ++eleStart;
auto* eleEnd = FastParseElement(dest[elementCount], eleStart, section._end);
if (eleStart == eleEnd) return elementCount;
++elementCount;
if (elementCount >= destCount) return elementCount;
eleStart = eleEnd;
}
}
template <typename Type, int Count>
cml::vector<Type, cml::fixed<Count>> ParseValueType(
Formatter& formatter, // Formatter::InteriorSection storedType,
const cml::vector<Type, cml::fixed<Count>>& def)
{
Formatter::InteriorSection cdata;
// auto type = HLSLTypeNameAsTypeDesc(
// Conversion::Convert<std::string>(String(storedType._start, storedType._end)).c_str());
// if (type._type == ImpliedTyping::TypeCat::Void) {
// type._type = ImpliedTyping::TypeCat::Float;
// type._arrayCount = 1;
// }
if (formatter.TryCharacterData(cdata)) {
cml::vector<Type, cml::fixed<Count>> result;
unsigned elementsRead = ParseXMLList(&result[0], Count, cdata);
for (unsigned c=elementsRead; c<Count; ++c)
result[c] = def[c];
return result;
} else {
LogWarning << "Expecting vector data at " << formatter.GetLocation();
return def;
}
}
template <typename Type>
Type ParseValueType(Formatter& formatter, Type& def)
{
Formatter::InteriorSection cdata;
if (formatter.TryCharacterData(cdata)) {
auto p = ImpliedTyping::Parse<Type>(cdata._start, cdata._end);
if (!p.first) return def;
return p.second;
} else {
LogWarning << "Expecting scalar data at " << formatter.GetLocation();
return def;
}
}
TechniqueValue::TechniqueValue(Formatter& formatter)
{
_type = Type::None;
// there can be attributes in the containing element -- which should should skip now
{
Formatter::InteriorSection name, value;
while (formatter.TryAttribute(name, value)) {}
}
// We should find exactly one element, which should be
// of "color", "param", "texture" or "float" type
Formatter::InteriorSection eleName;
if (!formatter.TryBeginElement(eleName))
Throw(FormatException("Expecting element for technique value", formatter.GetLocation()));
{
// skip all attributes (sometimes get "sid" tags)
while (formatter.PeekNext(true) == Formatter::Blob::AttributeName) {
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
}
}
if (Is(eleName, u("float"))) {
_value = ParseValueType(formatter, _value);
_type = Type::Float;
} else if (Is(eleName, u("color"))) {
Formatter::InteriorSection cdata;
if (formatter.TryCharacterData(cdata)) {
ParseXMLList(&_value[0], 4, cdata);
_type = Type::Color;
} else
LogWarning << "no data in color value at " << formatter.GetLocation();
} else if (Is(eleName, u("texture"))) {
for (;;) {
Formatter::InteriorSection name, value;
if (!formatter.TryAttribute(name, value)) break;
if (Is(name, u("texture"))) _reference = value;
else if (Is(name, u("texcoord"))) _texCoord = value;
else LogWarning << "Unknown attribute for texture (" << name << ") at " << formatter.GetLocation();
}
_type = Type::Texture;
} else if (Is(eleName, u("param"))) {
Formatter::InteriorSection name, value;
if (!formatter.TryAttribute(name, value) || !Is(name, u("ref"))) {
LogWarning << "Expecting ref attribute in param technique value at " << formatter.GetLocation();
} else {
_reference = value;
_type = Type::Param;
}
} else
Throw(FormatException("Expect either float, color, param or texture element", formatter.GetLocation()));
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
}
void Effect::Profile::ParseShaderType(Formatter& formatter)
{
// This is one of several types of shading equations defined
// by Collada (eg, blinn, phong, lambert)
//
// "shader type" elements just contain a list of parameters,
// each of which can have a value of any of these types:
// <color> <float> <texture> or <param>
//
// Also, there's are special cases for <transparent> and <transparency>
// -- they seem a little strange, actually
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
_values.push_back(
std::make_pair(
String(eleName._start, eleName._end),
TechniqueValue(formatter)));
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
continue;
}
}
break;
}
}
Effect::Effect(Formatter& formatter)
{
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
if (Is(eleName, u("newparam"))) {
_params.ParseParam(formatter);
} else if (StartsWith(eleName, u("profile_"))) {
_profiles.push_back(Profile(formatter, String(eleName._start+8, eleName._end)));
} else if (Is(eleName, u("extra"))) {
_extra = SubDoc(formatter);
} else {
// asset, annotate
formatter.SkipElement();
}
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
if (Is(name, u("name"))) _name = value;
else if (Is(name, u("id"))) _id = value;
continue;
}
}
break;
}
}
Effect::Effect(Effect&& moveFrom)
: _name(moveFrom._name)
, _id(moveFrom._id)
, _params(std::move(moveFrom._params))
, _profiles(std::move(moveFrom._profiles))
, _extra(std::move(moveFrom._extra))
{}
Effect& Effect::operator=(Effect&& moveFrom)
{
_name = moveFrom._name;
_id = moveFrom._id;
_params = std::move(moveFrom._params);
_profiles = std::move(moveFrom._profiles);
_extra = std::move(moveFrom._extra);
return *this;
}
void ColladaDocument::Parse_LibraryEffects(XmlInputStreamFormatter<utf8>& formatter)
{
using Formatter = XmlInputStreamFormatter<utf8>;
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
if (Is(eleName, u("effect"))) {
_effects.push_back(Effect(formatter));
} else {
// "annotate", "asset" and "extra" are also valid
formatter.SkipElement();
}
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
continue;
}
}
break;
}
}
class Source
{
public:
Section _id;
Section _arrayData;
Section _arrayType;
Section _arrayId;
unsigned _arrayCount;
Source(Formatter& formatter);
};
class Geometry
{
public:
std::vector<Source> _sources;
Geometry(Formatter& formatter);
Geometry();
Geometry(Geometry&& moveFrom) never_throws;
Geometry& operator=(Geometry&& moveFrom) never_throws;
protected:
void ParseMesh(Formatter& formatter);
};
#define ON_ELEMENT \
for (;;) { \
switch (formatter.PeekNext()) { \
case Formatter::Blob::BeginElement: \
{ \
Formatter::InteriorSection eleName; \
formatter.TryBeginElement(eleName); \
/**/
#define ON_ATTRIBUTE \
if (!formatter.TryEndElement()) \
Throw(FormatException("Expecting end element", formatter.GetLocation())); \
continue; \
} \
\
case Formatter::Blob::AttributeName: \
{ \
Formatter::InteriorSection name, value; \
formatter.TryAttribute(name, value); \
/**/
#define PARSE_END \
continue; \
} \
} \
\
break; \
} \
/**/
Source::Source(Formatter& formatter)
{
ON_ELEMENT
if (EndsWith(eleName, "_array")) {
// This is an array of elements, typically with an id and count
// we should have only a single array in each source. But it can
// be one of many different types.
// Most large data in Collada should appear in blocks like this.
// We don't attempt to parse it here, just record it's location in
// the file for later;
_arrayType = Section(eleName._start, eleName._end-6);
// this element should have no sub-elements. But it has important
// attributes. Given that the source is XML, the attributes
// will always come first.
{
while (formatter.PeekNext(true) == Formatter::Blob::AttributeName) {
Section name, value;
formatter.TryAttribute(name, value);
if (Is(name, u("count"))) {
_arrayCount = Parse(value, 0u);
} else if (Is(name, u("id"))) {
_arrayId = value;
} // "name also valid
}
}
Section cdata;
if (formatter.TryCharacterData(cdata)) {
_arrayData = cdata;
} else {
LogWarning << "Data source contains no data! At: " << formatter.GetLocation();
}
} else if (Is(eleName, "technique")) {
// this can contain special case non-standard information
// But it's not clear what this would be used for
formatter.SkipElement();
} else if (Is(eleName, "technique_common")) {
// This specifies the way we interpret the information in the array.
// It should occur after the array object. So we can resolve the reference
// in the accessor -- but only assuming that the reference in the accessor
// refers to an array in this document. That would be logical and typical.
// But the standard suggests the accessor can actually refer to a data array
// anywhere (including in other files)
// Anyway, it looks like we should have only a single accessor per technique
} else {
// "asset" also valid
formatter.SkipElement();
}
ON_ATTRIBUTE
if (Is(name, u("id"))) {
_id = value;
} // "name" is also valid
PARSE_END
}
void Geometry::ParseMesh(Formatter& formatter)
{
ON_ELEMENT
if (Is(eleName, u("source"))) {
_sources.push_back(Source(formatter));
}
ON_ATTRIBUTE
PARSE_END
}
Geometry::Geometry(Formatter& formatter)
{
ON_ELEMENT
if (Is(eleName, u("mesh"))) {
ParseMesh(formatter);
} else if (Is(eleName, u("convex_mesh")) || Is(eleName, u("spline")) || Is(eleName, u("brep"))) {
LogWarning << "convex_mesh, spline and brep geometries are not supported. At: " << formatter.GetLocation();
formatter.SkipElement();
} else {
// "asset" and "extra" are also valid, but it's unlikely that they would be present here
formatter.SkipElement();
}
ON_ATTRIBUTE
PARSE_END
}
void ColladaDocument::Parse_LibraryGeometries(XmlInputStreamFormatter<utf8>& formatter)
{
for (;;) {
switch (formatter.PeekNext()) {
case Formatter::Blob::BeginElement:
{
Formatter::InteriorSection eleName;
formatter.TryBeginElement(eleName);
if (Is(eleName, u("geometry"))) {
_geometries.push_back(Geometry(formatter));
} else {
// "asset" and "extra" are also valid, but uninteresting
formatter.SkipElement();
}
if (!formatter.TryEndElement())
Throw(FormatException("Expecting end element", formatter.GetLocation()));
continue;
}
case Formatter::Blob::AttributeName:
{
Formatter::InteriorSection name, value;
formatter.TryAttribute(name, value);
// name and id. Not interesting if we have only a single library
continue;
}
}
break;
}
}
ColladaDocument::ColladaDocument() {}
ColladaDocument::~ColladaDocument() {}
}
#include "../Utility/Streams/FileUtils.h"
#include "NascentModel.h"
void TestParser()
{
size_t size;
auto block = LoadFileAsMemoryBlock("game/testmodels/nyra/Nyra_pose.dae", &size);
using Formatter = XmlInputStreamFormatter<utf8>;
Formatter formatter(MemoryMappedInputStream(block.get(), PtrAdd(block.get(), size)));
ColladaConversion::ColladaDocument doc;
doc.Parse(formatter);
int t = 0;
(void)t;
}
|
/*
* Copyright 2015 Cloudius Systems
*/
#include "server.hh"
#include <boost/bimap/unordered_set_of.hpp>
#include <boost/range/irange.hpp>
#include <boost/bimap.hpp>
#include <boost/assign.hpp>
#include <boost/locale/encoding_utf.hpp>
#include <boost/range/adaptor/sliced.hpp>
#include "service/migration_manager.hh"
#include "service/storage_service.hh"
#include "db/consistency_level.hh"
#include "core/future-util.hh"
#include "core/reactor.hh"
#include "utils/UUID.hh"
#include "database.hh"
#include "net/byteorder.hh"
#include <seastar/core/scollectd.hh>
#include "enum_set.hh"
#include "service/query_state.hh"
#include "service/client_state.hh"
#include "exceptions/exceptions.hh"
#include <cassert>
#include <string>
static logging::logger logger("cql_server");
struct cql_frame_error : std::exception {
const char* what() const throw () override {
return "bad cql binary frame";
}
};
struct [[gnu::packed]] cql_binary_frame_v1 {
uint8_t version;
uint8_t flags;
uint8_t stream;
uint8_t opcode;
net::packed<uint32_t> length;
template <typename Adjuster>
void adjust_endianness(Adjuster a) {
return a(length);
}
};
struct [[gnu::packed]] cql_binary_frame_v3 {
uint8_t version;
uint8_t flags;
net::packed<uint16_t> stream;
uint8_t opcode;
net::packed<uint32_t> length;
template <typename Adjuster>
void adjust_endianness(Adjuster a) {
return a(stream, length);
}
};
enum class cql_binary_opcode : uint8_t {
ERROR = 0,
STARTUP = 1,
READY = 2,
AUTHENTICATE = 3,
CREDENTIALS = 4,
OPTIONS = 5,
SUPPORTED = 6,
QUERY = 7,
RESULT = 8,
PREPARE = 9,
EXECUTE = 10,
REGISTER = 11,
EVENT = 12,
BATCH = 13,
AUTH_CHALLENGE = 14,
AUTH_RESPONSE = 15,
AUTH_SUCCESS = 16,
};
inline db::consistency_level wire_to_consistency(int16_t v)
{
switch (v) {
case 0x0000: return db::consistency_level::ANY;
case 0x0001: return db::consistency_level::ONE;
case 0x0002: return db::consistency_level::TWO;
case 0x0003: return db::consistency_level::THREE;
case 0x0004: return db::consistency_level::QUORUM;
case 0x0005: return db::consistency_level::ALL;
case 0x0006: return db::consistency_level::LOCAL_QUORUM;
case 0x0007: return db::consistency_level::EACH_QUORUM;
case 0x0008: return db::consistency_level::SERIAL;
case 0x0009: return db::consistency_level::LOCAL_SERIAL;
case 0x000A: return db::consistency_level::LOCAL_ONE;
default: throw exceptions::protocol_exception(sprint("Unknown code %d for a consistency level", v));
}
}
inline int16_t consistency_to_wire(db::consistency_level c)
{
switch (c) {
case db::consistency_level::ANY: return 0x0000;
case db::consistency_level::ONE: return 0x0001;
case db::consistency_level::TWO: return 0x0002;
case db::consistency_level::THREE: return 0x0003;
case db::consistency_level::QUORUM: return 0x0004;
case db::consistency_level::ALL: return 0x0005;
case db::consistency_level::LOCAL_QUORUM: return 0x0006;
case db::consistency_level::EACH_QUORUM: return 0x0007;
case db::consistency_level::SERIAL: return 0x0008;
case db::consistency_level::LOCAL_SERIAL: return 0x0009;
case db::consistency_level::LOCAL_ONE: return 0x000A;
default: throw std::runtime_error("Invalid consistency level");
}
}
sstring to_string(const transport::event::topology_change::change_type t) {
using type = transport::event::topology_change::change_type;
switch (t) {
case type::NEW_NODE: return "NEW_NODE";
case type::REMOVED_NODE: return "REMOVED_NODE";
case type::MOVED_NODE: return "MOVED_NODE";
}
throw std::invalid_argument("unknown change type");
}
sstring to_string(const transport::event::status_change::status_type t) {
using type = transport::event::status_change::status_type;
switch (t) {
case type::UP: return "NEW_NODE";
case type::DOWN: return "REMOVED_NODE";
}
throw std::invalid_argument("unknown change type");
}
sstring to_string(const transport::event::schema_change::change_type t) {
switch (t) {
case transport::event::schema_change::change_type::CREATED: return "CREATED";
case transport::event::schema_change::change_type::UPDATED: return "UPDATED";
case transport::event::schema_change::change_type::DROPPED: return "DROPPED";
}
throw std::invalid_argument("unknown change type");
}
sstring to_string(const transport::event::schema_change::target_type t) {
switch (t) {
case transport::event::schema_change::target_type::KEYSPACE: return "KEYSPACE";
case transport::event::schema_change::target_type::TABLE: return "TABLE";
case transport::event::schema_change::target_type::TYPE: return "TYPE";
}
throw std::invalid_argument("unknown target type");
}
transport::event::event_type parse_event_type(const sstring& value)
{
if (value == "TOPOLOGY_CHANGE") {
return transport::event::event_type::TOPOLOGY_CHANGE;
} else if (value == "STATUS_CHANGE") {
return transport::event::event_type::STATUS_CHANGE;
} else if (value == "SCHEMA_CHANGE") {
return transport::event::event_type::SCHEMA_CHANGE;
} else {
throw exceptions::protocol_exception(sprint("Invalid value '%s' for Event.Type", value));
}
}
struct cql_query_state {
service::query_state query_state;
std::unique_ptr<cql3::query_options> options;
cql_query_state(service::client_state& client_state)
: query_state(client_state)
{ }
};
class cql_server::connection {
cql_server& _server;
connected_socket _fd;
input_stream<char> _read_buf;
output_stream<char> _write_buf;
seastar::gate _pending_requests_gate;
future<> _ready_to_respond = make_ready_future<>();
uint8_t _version = 0;
serialization_format _serialization_format = serialization_format::use_16_bit();
service::client_state _client_state;
std::unordered_map<uint16_t, cql_query_state> _query_states;
public:
connection(cql_server& server, connected_socket&& fd, socket_address addr)
: _server(server)
, _fd(std::move(fd))
, _read_buf(_fd.input())
, _write_buf(_fd.output())
, _client_state(service::client_state::for_external_calls())
{ }
~connection() {
_server._notifier->unregister_connection(this);
}
future<> process() {
return do_until([this] {
return _read_buf.eof();
}, [this] {
return process_request();
}).then_wrapped([this] (future<> f) {
try {
f.get();
return make_ready_future<>();
} catch (const exceptions::cassandra_exception& ex) {
return write_error(0, ex.code(), ex.what());
} catch (std::exception& ex) {
return write_error(0, exceptions::exception_code::SERVER_ERROR, ex.what());
} catch (...) {
return write_error(0, exceptions::exception_code::SERVER_ERROR, "unknown error");
}
}).finally([this] {
return _pending_requests_gate.close().then([this] {
return std::move(_ready_to_respond);
});
});
}
future<> process_request();
private:
future<> process_request_one(temporary_buffer<char> buf,
uint8_t op,
uint16_t stream);
unsigned frame_size() const;
cql_binary_frame_v3 parse_frame(temporary_buffer<char> buf);
future<std::experimental::optional<cql_binary_frame_v3>> read_frame();
future<> process_startup(uint16_t stream, temporary_buffer<char> buf);
future<> process_auth_response(uint16_t stream, temporary_buffer<char> buf);
future<> process_options(uint16_t stream, temporary_buffer<char> buf);
future<> process_query(uint16_t stream, temporary_buffer<char> buf);
future<> process_prepare(uint16_t stream, temporary_buffer<char> buf);
future<> process_execute(uint16_t stream, temporary_buffer<char> buf);
future<> process_batch(uint16_t stream, temporary_buffer<char> buf);
future<> process_register(uint16_t stream, temporary_buffer<char> buf);
future<> write_unavailable_error(int16_t stream, exceptions::exception_code err, sstring msg, db::consistency_level cl, int32_t required, int32_t alive);
future<> write_read_timeout_error(int16_t stream, exceptions::exception_code err, sstring msg, db::consistency_level cl, int32_t received, int32_t blockfor, bool data_present);
future<> write_already_exists_error(int16_t stream, exceptions::exception_code err, sstring msg, sstring ks_name, sstring cf_name);
future<> write_unprepared_error(int16_t stream, exceptions::exception_code err, sstring msg, bytes id);
future<> write_error(int16_t stream, exceptions::exception_code err, sstring msg);
future<> write_ready(int16_t stream);
future<> write_supported(int16_t stream);
future<> write_result(int16_t stream, shared_ptr<transport::messages::result_message> msg);
future<> write_topology_change_event(const transport::event::topology_change& event);
future<> write_status_change_event(const transport::event::status_change& event);
future<> write_schema_change_event(const transport::event::schema_change& event);
future<> write_response(shared_ptr<cql_server::response> response);
void check_room(temporary_buffer<char>& buf, size_t n) {
if (buf.size() < n) {
throw exceptions::protocol_exception("truncated frame");
}
}
void validate_utf8(sstring_view s) {
try {
boost::locale::conv::utf_to_utf<char>(s.begin(), s.end(), boost::locale::conv::stop);
} catch (const boost::locale::conv::conversion_error& ex) {
throw exceptions::protocol_exception("Cannot decode string as UTF8");
}
}
int8_t read_byte(temporary_buffer<char>& buf);
int32_t read_int(temporary_buffer<char>& buf);
int64_t read_long(temporary_buffer<char>& buf);
int16_t read_short(temporary_buffer<char>& buf);
uint16_t read_unsigned_short(temporary_buffer<char>& buf);
sstring read_string(temporary_buffer<char>& buf);
bytes read_short_bytes(temporary_buffer<char>& buf);
bytes_opt read_value(temporary_buffer<char>& buf);
sstring_view read_long_string_view(temporary_buffer<char>& buf);
void read_name_and_value_list(temporary_buffer<char>& buf, std::vector<sstring>& names, std::vector<bytes_opt>& values);
void read_string_list(temporary_buffer<char>& buf, std::vector<sstring>& strings);
void read_value_list(temporary_buffer<char>& buf, std::vector<bytes_opt>& values);
db::consistency_level read_consistency(temporary_buffer<char>& buf);
std::unordered_map<sstring, sstring> read_string_map(temporary_buffer<char>& buf);
std::unique_ptr<cql3::query_options> read_options(temporary_buffer<char>& buf);
cql_query_state& get_query_state(uint16_t stream);
void init_serialization_format();
friend event_notifier;
};
cql_server::event_notifier::event_notifier(uint16_t port)
: _port{port}
{
}
void cql_server::event_notifier::register_event(transport::event::event_type et, cql_server::connection* conn)
{
switch (et) {
case transport::event::event_type::TOPOLOGY_CHANGE:
_topology_change_listeners.emplace(conn);
break;
case transport::event::event_type::STATUS_CHANGE:
_status_change_listeners.emplace(conn);
break;
case transport::event::event_type::SCHEMA_CHANGE:
_schema_change_listeners.emplace(conn);
break;
}
}
void cql_server::event_notifier::unregister_connection(cql_server::connection* conn)
{
_topology_change_listeners.erase(conn);
_status_change_listeners.erase(conn);
_schema_change_listeners.erase(conn);
}
void cql_server::event_notifier::on_create_keyspace(const sstring& ks_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::CREATED,
ks_name
});
}
}
void cql_server::event_notifier::on_create_column_family(const sstring& ks_name, const sstring& cf_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::CREATED,
event::schema_change::target_type::TABLE,
ks_name,
cf_name
});
}
}
void cql_server::event_notifier::on_create_user_type(const sstring& ks_name, const sstring& type_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::CREATED,
event::schema_change::target_type::TYPE,
ks_name,
type_name
});
}
}
void cql_server::event_notifier::on_create_function(const sstring& ks_name, const sstring& function_name)
{
logger.warn("{} event ignored", __func__);
}
void cql_server::event_notifier::on_create_aggregate(const sstring& ks_name, const sstring& aggregate_name)
{
logger.warn("{} event ignored", __func__);
}
void cql_server::event_notifier::on_update_keyspace(const sstring& ks_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::UPDATED,
ks_name
});
}
}
void cql_server::event_notifier::on_update_column_family(const sstring& ks_name, const sstring& cf_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::UPDATED,
event::schema_change::target_type::TABLE,
ks_name,
cf_name
});
}
}
void cql_server::event_notifier::on_update_user_type(const sstring& ks_name, const sstring& type_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::UPDATED,
event::schema_change::target_type::TYPE,
ks_name,
type_name
});
}
}
void cql_server::event_notifier::on_update_function(const sstring& ks_name, const sstring& function_name)
{
logger.warn("%s event ignored", __func__);
}
void cql_server::event_notifier::on_update_aggregate(const sstring& ks_name, const sstring& aggregate_name)
{
logger.warn("%s event ignored", __func__);
}
void cql_server::event_notifier::on_drop_keyspace(const sstring& ks_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::DROPPED,
ks_name
});
}
}
void cql_server::event_notifier::on_drop_column_family(const sstring& ks_name, const sstring& cf_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::DROPPED,
event::schema_change::target_type::TABLE,
ks_name,
cf_name
});
}
}
void cql_server::event_notifier::on_drop_user_type(const sstring& ks_name, const sstring& type_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::DROPPED,
event::schema_change::target_type::TYPE,
ks_name,
type_name
});
}
}
void cql_server::event_notifier::on_drop_function(const sstring& ks_name, const sstring& function_name)
{
logger.warn("%s event ignored", __func__);
}
void cql_server::event_notifier::on_drop_aggregate(const sstring& ks_name, const sstring& aggregate_name)
{
logger.warn("%s event ignored", __func__);
}
void cql_server::event_notifier::on_join_cluster(const gms::inet_address& endpoint)
{
for (auto&& conn : _topology_change_listeners) {
using namespace transport;
conn->write_topology_change_event(event::topology_change::new_node(endpoint, _port));
}
}
void cql_server::event_notifier::on_leave_cluster(const gms::inet_address& endpoint)
{
for (auto&& conn : _topology_change_listeners) {
using namespace transport;
conn->write_topology_change_event(event::topology_change::removed_node(endpoint, _port));
}
}
void cql_server::event_notifier::on_move(const gms::inet_address& endpoint)
{
for (auto&& conn : _topology_change_listeners) {
using namespace transport;
conn->write_topology_change_event(event::topology_change::moved_node(endpoint, _port));
}
}
void cql_server::event_notifier::on_up(const gms::inet_address& endpoint)
{
for (auto&& conn : _status_change_listeners) {
using namespace transport;
conn->write_status_change_event(event::status_change::node_up(endpoint, _port));
}
}
void cql_server::event_notifier::on_down(const gms::inet_address& endpoint)
{
for (auto&& conn : _status_change_listeners) {
using namespace transport;
conn->write_status_change_event(event::status_change::node_down(endpoint, _port));
}
}
class cql_server::response {
int16_t _stream;
cql_binary_opcode _opcode;
std::vector<char> _body;
public:
response(int16_t stream, cql_binary_opcode opcode)
: _stream{stream}
, _opcode{opcode}
{ }
scattered_message<char> make_message(uint8_t version);
void write_byte(uint8_t b);
void write_int(int32_t n);
void write_long(int64_t n);
void write_short(int16_t n);
void write_string(const sstring& s);
void write_long_string(const sstring& s);
void write_uuid(utils::UUID uuid);
void write_string_list(std::vector<sstring> string_list);
void write_bytes(bytes b);
void write_short_bytes(bytes b);
void write_option(std::pair<int16_t, boost::any> opt);
void write_option_list(std::vector<std::pair<int16_t, boost::any>> opt_list);
void write_inet(ipv4_addr inet);
void write_consistency(db::consistency_level c);
void write_string_map(std::map<sstring, sstring> string_map);
void write_string_multimap(std::multimap<sstring, sstring> string_map);
void write_value(bytes_opt value);
void write(const cql3::metadata& m);
private:
sstring make_frame(uint8_t version, size_t length);
};
cql_server::cql_server(distributed<service::storage_proxy>& proxy, distributed<cql3::query_processor>& qp)
: _proxy(proxy)
, _query_processor(qp)
, _collectd_registrations(std::make_unique<scollectd::registrations>(setup_collectd()))
{
}
scollectd::registrations
cql_server::setup_collectd() {
return {
scollectd::add_polled_metric(
scollectd::type_instance_id("transport", scollectd::per_cpu_plugin_instance,
"connections", "cql-connections"),
scollectd::make_typed(scollectd::data_type::DERIVE, _connects)),
scollectd::add_polled_metric(
scollectd::type_instance_id("transport", scollectd::per_cpu_plugin_instance,
"current_connections", "current"),
scollectd::make_typed(scollectd::data_type::GAUGE, _connects)),
scollectd::add_polled_metric(
scollectd::type_instance_id("transport", scollectd::per_cpu_plugin_instance,
"total_requests", "requests_served"),
scollectd::make_typed(scollectd::data_type::DERIVE, _requests_served)),
scollectd::add_polled_metric(
scollectd::type_instance_id("transport", scollectd::per_cpu_plugin_instance,
"queue_length", "requests_serving"),
scollectd::make_typed(scollectd::data_type::GAUGE, _requests_serving)),
};
}
future<> cql_server::stop() {
service::get_local_storage_service().unregister_subscriber(_notifier.get());
service::get_local_migration_manager().unregister_listener(_notifier.get());
return make_ready_future<>();
}
future<>
cql_server::listen(ipv4_addr addr) {
_notifier = std::make_unique<event_notifier>(addr.port);
service::get_local_migration_manager().register_listener(_notifier.get());
service::get_local_storage_service().register_subscriber(_notifier.get());
listen_options lo;
lo.reuse_address = true;
_listeners.push_back(engine().listen(make_ipv4_address(addr), lo));
do_accepts(_listeners.size() - 1);
return make_ready_future<>();
}
void
cql_server::do_accepts(int which) {
_listeners[which].accept().then([this, which] (connected_socket fd, socket_address addr) mutable {
auto conn = make_shared<connection>(*this, std::move(fd), addr);
++_connects;
++_connections;
conn->process().then_wrapped([this, conn] (future<> f) {
--_connections;
try {
f.get();
} catch (std::exception& ex) {
logger.debug("connection error: {}", ex.what());
}
});
do_accepts(which);
}).then_wrapped([] (future<> f) {
try {
f.get();
} catch (std::exception& ex) {
logger.debug("accept failed: {}", ex.what());
}
});
}
unsigned
cql_server::connection::frame_size() const {
if (_version < 3) {
return 8;
} else {
return 9;
}
}
cql_binary_frame_v3
cql_server::connection::parse_frame(temporary_buffer<char> buf) {
if (buf.size() != frame_size()) {
throw cql_frame_error();
}
cql_binary_frame_v3 v3;
switch (_version) {
case 1:
case 2: {
auto raw = reinterpret_cast<const cql_binary_frame_v1*>(buf.get());
auto cooked = net::ntoh(*raw);
v3.version = cooked.version;
v3.flags = cooked.flags;
v3.opcode = cooked.opcode;
v3.stream = cooked.stream;
v3.length = cooked.length;
break;
}
case 3:
case 4: {
v3 = net::ntoh(*reinterpret_cast<const cql_binary_frame_v3*>(buf.get()));
break;
}
default:
throw exceptions::protocol_exception(sprint("Invalid or unsupported protocol version: %d", _version));
}
if (v3.version != _version) {
throw exceptions::protocol_exception(sprint("Invalid message version. Got %d but previous messages on this connection had version %d", v3.version, _version));
}
return v3;
}
future<std::experimental::optional<cql_binary_frame_v3>>
cql_server::connection::read_frame() {
using ret_type = std::experimental::optional<cql_binary_frame_v3>;
if (!_version) {
// We don't know the frame size before reading the first frame,
// so read just one byte, and then read the rest of the frame.
return _read_buf.read_exactly(1).then([this] (temporary_buffer<char> buf) {
if (buf.empty()) {
return make_ready_future<ret_type>();
}
_version = buf[0];
init_serialization_format();
if (_version < 1 || _version > current_version) {
throw exceptions::protocol_exception(sprint("Invalid or unsupported protocol version: %d", _version));
}
return _read_buf.read_exactly(frame_size() - 1).then([this] (temporary_buffer<char> tail) {
temporary_buffer<char> full(frame_size());
full.get_write()[0] = _version;
std::copy(tail.get(), tail.get() + tail.size(), full.get_write() + 1);
return make_ready_future<ret_type>(parse_frame(std::move(full)));
});
});
} else {
// Not the first frame, so we know the size.
return _read_buf.read_exactly(frame_size()).then([this] (temporary_buffer<char> buf) {
if (buf.empty()) {
return make_ready_future<ret_type>();
}
return make_ready_future<ret_type>(parse_frame(std::move(buf)));
});
}
}
future<> cql_server::connection::process_request_one(temporary_buffer<char> buf,
uint8_t op,
uint16_t stream) {
return make_ready_future<>().then([this, op, stream, buf = std::move(buf)] () mutable {
switch (static_cast<cql_binary_opcode>(op)) {
case cql_binary_opcode::STARTUP: return process_startup(stream, std::move(buf));
case cql_binary_opcode::AUTH_RESPONSE: return process_auth_response(stream, std::move(buf));
case cql_binary_opcode::OPTIONS: return process_options(stream, std::move(buf));
case cql_binary_opcode::QUERY: return process_query(stream, std::move(buf));
case cql_binary_opcode::PREPARE: return process_prepare(stream, std::move(buf));
case cql_binary_opcode::EXECUTE: return process_execute(stream, std::move(buf));
case cql_binary_opcode::BATCH: return process_batch(stream, std::move(buf));
case cql_binary_opcode::REGISTER: return process_register(stream, std::move(buf));
default: throw exceptions::protocol_exception(sprint("Unknown opcode %d", op));
}
}).then_wrapped([stream, this] (future<> f) {
--_server._requests_serving;
try {
f.get();
return make_ready_future<>();
} catch (const exceptions::unavailable_exception& ex) {
return write_unavailable_error(stream, ex.code(), ex.what(), ex.consistency, ex.required, ex.alive);
} catch (const exceptions::read_timeout_exception& ex) {
return write_read_timeout_error(stream, ex.code(), ex.what(), ex.consistency, ex.received, ex.block_for, ex.data_present);
} catch (const exceptions::already_exists_exception& ex) {
return write_already_exists_error(stream, ex.code(), ex.what(), ex.ks_name, ex.cf_name);
} catch (const exceptions::prepared_query_not_found_exception& ex) {
return write_unprepared_error(stream, ex.code(), ex.what(), ex.id);
} catch (const exceptions::cassandra_exception& ex) {
return write_error(stream, ex.code(), ex.what());
} catch (std::exception& ex) {
return write_error(stream, exceptions::exception_code::SERVER_ERROR, ex.what());
} catch (...) {
return write_error(stream, exceptions::exception_code::SERVER_ERROR, "unknown error");
}
});
}
future<> cql_server::connection::process_request() {
return read_frame().then_wrapped([this] (future<std::experimental::optional<cql_binary_frame_v3>>&& v) {
auto maybe_frame = std::get<0>(v.get());
if (!maybe_frame) {
// eof
return make_ready_future<>();
}
auto& f = *maybe_frame;
// FIXME: compression
if (f.flags & 0x01) {
throw std::runtime_error("CQL frame compression is not supported");
}
auto op = f.opcode;
auto stream = f.stream;
return _read_buf.read_exactly(f.length).then([this, op, stream] (temporary_buffer<char> buf) {
++_server._requests_served;
++_server._requests_serving;
with_gate(
_pending_requests_gate,
[this, op, stream, buf = std::move(buf)] () mutable {
return process_request_one(std::move(buf), op, stream);
}
);
return make_ready_future<>();
});
});
}
future<> cql_server::connection::process_startup(uint16_t stream, temporary_buffer<char> buf)
{
/*auto string_map =*/ read_string_map(buf);
return write_ready(stream);
}
future<> cql_server::connection::process_auth_response(uint16_t stream, temporary_buffer<char> buf)
{
assert(0);
return make_ready_future<>();
}
future<> cql_server::connection::process_options(uint16_t stream, temporary_buffer<char> buf)
{
return write_supported(stream);
}
cql_query_state& cql_server::connection::get_query_state(uint16_t stream)
{
auto i = _query_states.find(stream);
if (i == _query_states.end()) {
i = _query_states.emplace(stream, _client_state).first;
}
return i->second;
}
void
cql_server::connection::init_serialization_format() {
if (_version < 3) {
_serialization_format = serialization_format::use_16_bit();
} else {
_serialization_format = serialization_format::use_32_bit();
}
}
future<> cql_server::connection::process_query(uint16_t stream, temporary_buffer<char> buf)
{
auto query = read_long_string_view(buf);
auto& q_state = get_query_state(stream);
q_state.options = read_options(buf);
return _server._query_processor.local().process(query, q_state.query_state, *q_state.options).then([this, stream] (auto msg) {
return this->write_result(stream, msg);
});
}
future<> cql_server::connection::process_prepare(uint16_t stream, temporary_buffer<char> buf)
{
auto query = read_long_string_view(buf).to_string();
auto cpu_id = engine().cpu_id();
auto cpus = boost::irange(0u, smp::count);
return parallel_for_each(cpus.begin(), cpus.end(), [this, query, cpu_id, stream] (unsigned int c) mutable {
if (c != cpu_id) {
return smp::submit_to(c, [this, query, stream] () mutable {
auto& q_state = get_query_state(stream); // FIXME: is this safe?
_server._query_processor.local().prepare(query, q_state.query_state);
// FIXME: error handling
});
} else {
return make_ready_future<>();
}
}).then([this, query, stream] {
auto& q_state = get_query_state(stream);
return _server._query_processor.local().prepare(query, q_state.query_state).then([this, stream] (auto msg) {
return this->write_result(stream, msg);
});
});
}
future<> cql_server::connection::process_execute(uint16_t stream, temporary_buffer<char> buf)
{
auto id = read_short_bytes(buf);
auto prepared = _server._query_processor.local().get_prepared(id);
if (!prepared) {
throw exceptions::prepared_query_not_found_exception(id);
}
auto& q_state = get_query_state(stream);
auto& query_state = q_state.query_state;
q_state.options = read_options(buf);
auto& options = *q_state.options;
options.prepare(prepared->bound_names);
auto stmt = prepared->statement;
if (stmt->get_bound_terms() != options.get_values().size()) {
throw exceptions::invalid_request_exception("Invalid amount of bind variables");
}
return _server._query_processor.local().process_statement(stmt, query_state, options).then([this, stream] (auto msg) {
return this->write_result(stream, msg);
});
}
future<> cql_server::connection::process_batch(uint16_t stream, temporary_buffer<char> buf)
{
assert(0);
return make_ready_future<>();
}
future<> cql_server::connection::process_register(uint16_t stream, temporary_buffer<char> buf)
{
std::vector<sstring> event_types;
read_string_list(buf, event_types);
for (auto&& event_type : event_types) {
auto et = parse_event_type(event_type);
_server._notifier->register_event(et, this);
}
return write_ready(stream);
}
future<> cql_server::connection::write_unavailable_error(int16_t stream, exceptions::exception_code err, sstring msg, db::consistency_level cl, int32_t required, int32_t alive)
{
auto response = make_shared<cql_server::response>(stream, cql_binary_opcode::ERROR);
response->write_int(static_cast<int32_t>(err));
response->write_string(msg);
response->write_consistency(cl);
response->write_int(required);
response->write_int(alive);
return write_response(response);
}
future<> cql_server::connection::write_read_timeout_error(int16_t stream, exceptions::exception_code err, sstring msg, db::consistency_level cl, int32_t received, int32_t blockfor, bool data_present)
{
auto response = make_shared<cql_server::response>(stream, cql_binary_opcode::ERROR);
response->write_int(static_cast<int32_t>(err));
response->write_string(msg);
response->write_consistency(cl);
response->write_int(received);
response->write_int(blockfor);
response->write_byte(data_present);
return write_response(response);
}
future<> cql_server::connection::write_already_exists_error(int16_t stream, exceptions::exception_code err, sstring msg, sstring ks_name, sstring cf_name)
{
auto response = make_shared<cql_server::response>(stream, cql_binary_opcode::ERROR);
response->write_int(static_cast<int32_t>(err));
response->write_string(msg);
response->write_string(ks_name);
response->write_string(cf_name);
return write_response(response);
}
future<> cql_server::connection::write_unprepared_error(int16_t stream, exceptions::exception_code err, sstring msg, bytes id)
{
auto response = make_shared<cql_server::response>(stream, cql_binary_opcode::ERROR);
response->write_int(static_cast<int32_t>(err));
response->write_string(msg);
response->write_short_bytes(id);
return write_response(response);
}
future<> cql_server::connection::write_error(int16_t stream, exceptions::exception_code err, sstring msg)
{
auto response = make_shared<cql_server::response>(stream, cql_binary_opcode::ERROR);
response->write_int(static_cast<int32_t>(err));
response->write_string(msg);
return write_response(response);
}
future<> cql_server::connection::write_ready(int16_t stream)
{
auto response = make_shared<cql_server::response>(stream, cql_binary_opcode::READY);
return write_response(response);
}
future<> cql_server::connection::write_supported(int16_t stream)
{
std::multimap<sstring, sstring> opts;
opts.insert({"CQL_VERSION", cql3::query_processor::CQL_VERSION});
opts.insert({"COMPRESSION", "snappy"});
auto response = make_shared<cql_server::response>(stream, cql_binary_opcode::SUPPORTED);
response->write_string_multimap(opts);
return write_response(response);
}
class cql_server::fmt_visitor : public transport::messages::result_message::visitor {
private:
uint8_t _version;
shared_ptr<cql_server::response> _response;
public:
fmt_visitor(uint8_t version, shared_ptr<cql_server::response> response)
: _version{version}
, _response{response}
{ }
virtual void visit(const transport::messages::result_message::void_message&) override {
_response->write_int(0x0001);
}
virtual void visit(const transport::messages::result_message::set_keyspace& m) override {
_response->write_int(0x0003);
_response->write_string(m.get_keyspace());
}
virtual void visit(const transport::messages::result_message::prepared& m) override {
auto prepared = m.get_prepared();
_response->write_int(0x0004);
_response->write_short_bytes(m.get_id());
// FIXME: not compatible with v4
assert(_version < 4);
cql3::metadata metadata{prepared->bound_names};
_response->write(metadata);
if (_version > 1) {
cql3::metadata result_metadata{std::vector<::shared_ptr<cql3::column_specification>>{}};
result_metadata.set_skip_metadata();
_response->write(result_metadata);
}
}
virtual void visit(const transport::messages::result_message::schema_change& m) override {
auto change = m.get_change();
switch (change->type) {
case transport::event::event_type::SCHEMA_CHANGE: {
auto sc = static_pointer_cast<transport::event::schema_change>(change);
_response->write_int(0x0005);
_response->write_string(to_string(sc->change));
_response->write_string(to_string(sc->target));
_response->write_string(sc->keyspace);
if (sc->target != transport::event::schema_change::target_type::KEYSPACE) {
_response->write_string(sc->table_or_type_or_function.value());
}
break;
}
default:
assert(0);
}
}
virtual void visit(const transport::messages::result_message::rows& m) override {
_response->write_int(0x0002);
auto& rs = m.rs();
_response->write(rs.get_metadata());
_response->write_int(rs.size());
for (auto&& row : rs.rows()) {
for (auto&& cell : row | boost::adaptors::sliced(0, rs.get_metadata().column_count())) {
_response->write_value(cell);
}
}
}
};
future<> cql_server::connection::write_result(int16_t stream, shared_ptr<transport::messages::result_message> msg)
{
auto response = make_shared<cql_server::response>(stream, cql_binary_opcode::RESULT);
fmt_visitor fmt{_version, response};
msg->accept(fmt);
return write_response(response);
}
future<> cql_server::connection::write_topology_change_event(const transport::event::topology_change& event)
{
auto response = make_shared<cql_server::response>(-1, cql_binary_opcode::EVENT);
response->write_string("TOPOLOGY_CHANGE");
response->write_string(to_string(event.change));
response->write_inet(event.node);
return write_response(response);
}
future<> cql_server::connection::write_status_change_event(const transport::event::status_change& event)
{
auto response = make_shared<cql_server::response>(-1, cql_binary_opcode::EVENT);
response->write_string("STATUS_CHANGE");
response->write_string(to_string(event.status));
response->write_inet(event.node);
return write_response(response);
}
future<> cql_server::connection::write_schema_change_event(const transport::event::schema_change& event)
{
auto response = make_shared<cql_server::response>(-1, cql_binary_opcode::EVENT);
response->write_string("SCHEMA_CHANGE");
response->write_string(to_string(event.change));
response->write_string(to_string(event.target));
response->write_string(event.keyspace);
if (event.target != transport::event::schema_change::target_type::KEYSPACE) {
response->write_string(*(event.table_or_type_or_function));
}
return write_response(response);
}
future<> cql_server::connection::write_response(shared_ptr<cql_server::response> response)
{
auto msg = response->make_message(_version);
_ready_to_respond = _ready_to_respond.then([this, msg = std::move(msg)] () mutable {
return _write_buf.write(std::move(msg)).then([this] {
return _write_buf.flush();
});
});
return make_ready_future<>();
}
int8_t cql_server::connection::read_byte(temporary_buffer<char>& buf)
{
check_room(buf, 1);
int8_t n = buf[0];
buf.trim_front(1);
return n;
}
int32_t cql_server::connection::read_int(temporary_buffer<char>& buf)
{
check_room(buf, sizeof(int32_t));
auto p = reinterpret_cast<const uint8_t*>(buf.begin());
uint32_t n = (static_cast<uint32_t>(p[0]) << 24)
| (static_cast<uint32_t>(p[1]) << 16)
| (static_cast<uint32_t>(p[2]) << 8)
| (static_cast<uint32_t>(p[3]));
buf.trim_front(4);
return n;
}
int64_t cql_server::connection::read_long(temporary_buffer<char>& buf)
{
check_room(buf, sizeof(int64_t));
auto p = reinterpret_cast<const uint8_t*>(buf.begin());
uint64_t n = (static_cast<uint64_t>(p[0]) << 56)
| (static_cast<uint64_t>(p[1]) << 48)
| (static_cast<uint64_t>(p[2]) << 40)
| (static_cast<uint64_t>(p[3]) << 32)
| (static_cast<uint64_t>(p[4]) << 24)
| (static_cast<uint64_t>(p[5]) << 16)
| (static_cast<uint64_t>(p[6]) << 8)
| (static_cast<uint64_t>(p[7]));
buf.trim_front(8);
return n;
}
int16_t cql_server::connection::read_short(temporary_buffer<char>& buf)
{
return static_cast<int16_t>(read_unsigned_short(buf));
}
uint16_t cql_server::connection::read_unsigned_short(temporary_buffer<char>& buf)
{
check_room(buf, sizeof(uint16_t));
auto p = reinterpret_cast<const uint8_t*>(buf.begin());
uint16_t n = (static_cast<uint16_t>(p[0]) << 8)
| (static_cast<uint16_t>(p[1]));
buf.trim_front(2);
return n;
}
bytes cql_server::connection::read_short_bytes(temporary_buffer<char>& buf)
{
auto n = read_short(buf);
check_room(buf, n);
bytes s{reinterpret_cast<const int8_t*>(buf.begin()), static_cast<size_t>(n)};
assert(n >= 0);
buf.trim_front(n);
return s;
}
sstring cql_server::connection::read_string(temporary_buffer<char>& buf)
{
auto n = read_short(buf);
check_room(buf, n);
sstring s{buf.begin(), static_cast<size_t>(n)};
assert(n >= 0);
buf.trim_front(n);
validate_utf8(s);
return s;
}
sstring_view cql_server::connection::read_long_string_view(temporary_buffer<char>& buf)
{
auto n = read_int(buf);
check_room(buf, n);
sstring_view s{buf.begin(), static_cast<size_t>(n)};
buf.trim_front(n);
validate_utf8(s);
return s;
}
db::consistency_level cql_server::connection::read_consistency(temporary_buffer<char>& buf)
{
return wire_to_consistency(read_short(buf));
}
std::unordered_map<sstring, sstring> cql_server::connection::read_string_map(temporary_buffer<char>& buf)
{
std::unordered_map<sstring, sstring> string_map;
auto n = read_short(buf);
for (auto i = 0; i < n; i++) {
auto key = read_string(buf);
auto val = read_string(buf);
string_map.emplace(std::piecewise_construct,
std::forward_as_tuple(std::move(key)),
std::forward_as_tuple(std::move(val)));
}
return string_map;
}
enum class options_flag {
VALUES,
SKIP_METADATA,
PAGE_SIZE,
PAGING_STATE,
SERIAL_CONSISTENCY,
TIMESTAMP,
NAMES_FOR_VALUES
};
using options_flag_enum = super_enum<options_flag,
options_flag::VALUES,
options_flag::SKIP_METADATA,
options_flag::PAGE_SIZE,
options_flag::PAGING_STATE,
options_flag::SERIAL_CONSISTENCY,
options_flag::TIMESTAMP,
options_flag::NAMES_FOR_VALUES
>;
std::unique_ptr<cql3::query_options> cql_server::connection::read_options(temporary_buffer<char>& buf)
{
auto consistency = read_consistency(buf);
if (_version == 1) {
return std::make_unique<cql3::query_options>(consistency, std::experimental::nullopt, std::vector<bytes_opt>{},
false, cql3::query_options::specific_options::DEFAULT, 1, _serialization_format);
}
assert(_version >= 2);
auto flags = enum_set<options_flag_enum>::from_mask(read_byte(buf));
std::vector<bytes_opt> values;
std::vector<sstring> names;
if (flags.contains<options_flag::VALUES>()) {
if (flags.contains<options_flag::NAMES_FOR_VALUES>()) {
read_name_and_value_list(buf, names, values);
} else {
read_value_list(buf, values);
}
}
bool skip_metadata = flags.contains<options_flag::SKIP_METADATA>();
flags.remove<options_flag::VALUES>();
flags.remove<options_flag::SKIP_METADATA>();
std::unique_ptr<cql3::query_options> options;
if (flags) {
::shared_ptr<service::pager::paging_state> paging_state;
int32_t page_size = flags.contains<options_flag::PAGE_SIZE>() ? read_int(buf) : -1;
if (flags.contains<options_flag::PAGING_STATE>()) {
fail(unimplemented::cause::PAGING);
#if 0
paging_state = PagingState.deserialize(CBUtil.readValue(body))
#endif
}
db::consistency_level serial_consistency = db::consistency_level::SERIAL;
if (flags.contains<options_flag::SERIAL_CONSISTENCY>()) {
serial_consistency = read_consistency(buf);
}
api::timestamp_type ts = api::missing_timestamp;
if (flags.contains<options_flag::TIMESTAMP>()) {
ts = read_long(buf);
if (ts < api::min_timestamp || ts > api::max_timestamp) {
throw exceptions::protocol_exception(sprint("Out of bound timestamp, must be in [%d, %d] (got %d)",
api::min_timestamp, api::max_timestamp, ts));
}
}
std::experimental::optional<std::vector<sstring>> onames;
if (!names.empty()) {
onames = std::move(names);
}
options = std::make_unique<cql3::query_options>(consistency, std::move(onames), std::move(values), skip_metadata,
cql3::query_options::specific_options{page_size, std::move(paging_state), serial_consistency, ts}, _version,
_serialization_format);
} else {
options = std::make_unique<cql3::query_options>(consistency, std::experimental::nullopt, std::move(values), skip_metadata,
cql3::query_options::specific_options::DEFAULT, _version, _serialization_format);
}
return std::move(options);
}
void cql_server::connection::read_name_and_value_list(temporary_buffer<char>& buf, std::vector<sstring>& names, std::vector<bytes_opt>& values) {
uint16_t size = read_unsigned_short(buf);
names.reserve(size);
values.reserve(size);
for (uint16_t i = 0; i < size; i++) {
names.emplace_back(read_string(buf));
values.emplace_back(read_value(buf));
}
}
void cql_server::connection::read_string_list(temporary_buffer<char>& buf, std::vector<sstring>& strings) {
uint16_t size = read_unsigned_short(buf);
strings.reserve(size);
for (uint16_t i = 0; i < size; i++) {
strings.emplace_back(read_string(buf));
}
}
void cql_server::connection::read_value_list(temporary_buffer<char>& buf, std::vector<bytes_opt>& values) {
uint16_t size = read_unsigned_short(buf);
values.reserve(size);
for (uint16_t i = 0; i < size; i++) {
values.emplace_back(read_value(buf));
}
}
bytes_opt cql_server::connection::read_value(temporary_buffer<char>& buf) {
auto len = read_int(buf);
if (len < 0) {
return {};
}
check_room(buf, len);
bytes b(reinterpret_cast<const int8_t*>(buf.begin()), len);
buf.trim_front(len);
return {std::move(b)};
}
scattered_message<char> cql_server::response::make_message(uint8_t version) {
scattered_message<char> msg;
sstring body{_body.data(), _body.size()};
sstring frame = make_frame(version, body.size());
msg.append(std::move(frame));
msg.append(std::move(body));
return msg;
}
sstring cql_server::response::make_frame(uint8_t version, size_t length)
{
switch (version) {
case 0x01:
case 0x02: {
sstring frame_buf(sstring::initialized_later(), sizeof(cql_binary_frame_v1));
auto* frame = reinterpret_cast<cql_binary_frame_v1*>(frame_buf.begin());
frame->version = version | 0x80;
frame->flags = 0x00;
frame->stream = _stream;
frame->opcode = static_cast<uint8_t>(_opcode);
frame->length = htonl(length);
return frame_buf;
}
case 0x03:
case 0x04: {
sstring frame_buf(sstring::initialized_later(), sizeof(cql_binary_frame_v3));
auto* frame = reinterpret_cast<cql_binary_frame_v3*>(frame_buf.begin());
frame->version = version | 0x80;
frame->flags = 0x00;
frame->stream = htons(_stream);
frame->opcode = static_cast<uint8_t>(_opcode);
frame->length = htonl(length);
return frame_buf;
}
default:
throw exceptions::protocol_exception(sprint("Invalid or unsupported protocol version: %d", version));
}
}
void cql_server::response::write_byte(uint8_t b)
{
_body.insert(_body.end(), b);
}
void cql_server::response::write_int(int32_t n)
{
auto u = htonl(n);
auto *s = reinterpret_cast<const char*>(&u);
_body.insert(_body.end(), s, s+sizeof(u));
}
void cql_server::response::write_long(int64_t n)
{
auto u = htonq(n);
auto *s = reinterpret_cast<const char*>(&u);
_body.insert(_body.end(), s, s+sizeof(u));
}
void cql_server::response::write_short(int16_t n)
{
auto u = htons(n);
auto *s = reinterpret_cast<const char*>(&u);
_body.insert(_body.end(), s, s+sizeof(u));
}
void cql_server::response::write_string(const sstring& s)
{
assert(s.size() < std::numeric_limits<int16_t>::max());
write_short(s.size());
_body.insert(_body.end(), s.begin(), s.end());
}
void cql_server::response::write_long_string(const sstring& s)
{
assert(s.size() < std::numeric_limits<int32_t>::max());
write_int(s.size());
_body.insert(_body.end(), s.begin(), s.end());
}
void cql_server::response::write_uuid(utils::UUID uuid)
{
// FIXME
assert(0);
}
void cql_server::response::write_string_list(std::vector<sstring> string_list)
{
assert(string_list.size() < std::numeric_limits<int16_t>::max());
write_short(string_list.size());
for (auto&& s : string_list) {
write_string(s);
}
}
void cql_server::response::write_bytes(bytes b)
{
assert(b.size() < std::numeric_limits<int32_t>::max());
write_int(b.size());
_body.insert(_body.end(), b.begin(), b.end());
}
void cql_server::response::write_short_bytes(bytes b)
{
assert(b.size() < std::numeric_limits<int16_t>::max());
write_short(b.size());
_body.insert(_body.end(), b.begin(), b.end());
}
void cql_server::response::write_option(std::pair<int16_t, boost::any> opt)
{
// FIXME
assert(0);
}
void cql_server::response::write_option_list(std::vector<std::pair<int16_t, boost::any>> opt_list)
{
// FIXME
assert(0);
}
void cql_server::response::write_inet(ipv4_addr inet)
{
write_byte(4);
write_byte(((inet.ip & 0xff000000) >> 24));
write_byte(((inet.ip & 0x00ff0000) >> 16));
write_byte(((inet.ip & 0x0000ff00) >> 8 ));
write_byte(((inet.ip & 0x000000ff) ));
write_int(inet.port);
}
void cql_server::response::write_consistency(db::consistency_level c)
{
write_short(consistency_to_wire(c));
}
void cql_server::response::write_string_map(std::map<sstring, sstring> string_map)
{
assert(string_map.size() < std::numeric_limits<int16_t>::max());
write_short(string_map.size());
for (auto&& s : string_map) {
write_string(s.first);
write_string(s.second);
}
}
void cql_server::response::write_string_multimap(std::multimap<sstring, sstring> string_map)
{
std::vector<sstring> keys;
for (auto it = string_map.begin(), end = string_map.end(); it != end; it = string_map.upper_bound(it->first)) {
keys.push_back(it->first);
}
assert(keys.size() < std::numeric_limits<int16_t>::max());
write_short(keys.size());
for (auto&& key : keys) {
std::vector<sstring> values;
auto range = string_map.equal_range(key);
for (auto it = range.first; it != range.second; ++it) {
values.push_back(it->second);
}
write_string(key);
write_string_list(values);
}
}
void cql_server::response::write_value(bytes_opt value)
{
if (!value) {
write_int(-1);
return;
}
write_int(value->size());
_body.insert(_body.end(), value->begin(), value->end());
}
class type_codec {
private:
enum class type_id : int16_t {
CUSTOM = 0,
ASCII,
BIGINT,
BLOB,
BOOLEAN,
COUNTER,
DECIMAL,
DOUBLE,
FLOAT,
INT,
TEXT,
TIMESTAMP,
UUID,
VARCHAR,
VARINT,
TIMEUUID,
INET,
LIST = 32,
MAP,
SET,
UDT = 48,
TUPLE
};
using type_id_to_type_type = boost::bimap<
boost::bimaps::unordered_set_of<type_id>,
boost::bimaps::unordered_set_of<data_type>>;
static thread_local const type_id_to_type_type type_id_to_type;
public:
static void encode(cql_server::response& r, data_type type) {
type = type->underlying_type();
// For compatibility sake, we still return DateType as the timestamp type in resultSet metadata (#5723)
if (type == date_type) {
type = timestamp_type;
}
auto i = type_id_to_type.right.find(type);
if (i != type_id_to_type.right.end()) {
r.write_short(static_cast<std::underlying_type<type_id>::type>(i->second));
return;
}
if (type->is_reversed()) {
fail(unimplemented::cause::REVERSED);
}
if (type->is_collection()) {
auto&& ctype = static_cast<const collection_type_impl*>(type.get());
if (&ctype->_kind == &collection_type_impl::kind::map) {
r.write_short(uint16_t(type_id::MAP));
auto&& mtype = static_cast<const map_type_impl*>(ctype);
encode(r, mtype->get_keys_type());
encode(r, mtype->get_values_type());
} else if (&ctype->_kind == &collection_type_impl::kind::set) {
r.write_short(uint16_t(type_id::SET));
auto&& stype = static_cast<const set_type_impl*>(ctype);
encode(r, stype->get_elements_type());
} else if (&ctype->_kind == &collection_type_impl::kind::list) {
r.write_short(uint16_t(type_id::LIST));
auto&& ltype = static_cast<const list_type_impl*>(ctype);
encode(r, ltype->get_elements_type());
} else {
abort();
}
return;
}
abort();
}
};
thread_local const type_codec::type_id_to_type_type type_codec::type_id_to_type = boost::assign::list_of<type_id_to_type_type::relation>
(type_id::ASCII , ascii_type)
(type_id::BIGINT , long_type)
(type_id::BLOB , bytes_type)
(type_id::BOOLEAN , boolean_type)
//(type_id::COUNTER , CounterColumn_type)
//(type_id::DECIMAL , Decimal_type)
(type_id::DOUBLE , double_type)
(type_id::FLOAT , float_type)
(type_id::INT , int32_type)
(type_id::TEXT , utf8_type)
(type_id::TIMESTAMP , timestamp_type)
(type_id::UUID , uuid_type)
(type_id::VARCHAR , utf8_type)
(type_id::VARINT , varint_type)
(type_id::TIMEUUID , timeuuid_type)
(type_id::INET , inet_addr_type);
void cql_server::response::write(const cql3::metadata& m) {
bool no_metadata = m.flags().contains<cql3::metadata::flag::NO_METADATA>();
bool global_tables_spec = m.flags().contains<cql3::metadata::flag::GLOBAL_TABLES_SPEC>();
bool has_more_pages = m.flags().contains<cql3::metadata::flag::HAS_MORE_PAGES>();
write_int(m.flags().mask());
write_int(m.column_count());
if (has_more_pages) {
write_value(m.paging_state()->serialize());
}
if (no_metadata) {
return;
}
auto names_i = m.get_names().begin();
if (global_tables_spec) {
auto first_spec = *names_i;
write_string(first_spec->ks_name);
write_string(first_spec->cf_name);
}
for (uint32_t i = 0; i < m.column_count(); ++i, ++names_i) {
::shared_ptr<cql3::column_specification> name = *names_i;
if (!global_tables_spec) {
write_string(name->ks_name);
write_string(name->cf_name);
}
write_string(name->name->text());
type_codec::encode(*this, name->type);
};
}
transport/server: Clean up connection class definition
Move member function definitions outside of the class definition in
preparation for moving the latter to a header file.
Signed-off-by: Pekka Enberg <add4fcd06328a394f0ad91feda7ee057316dc5ed@cloudius-systems.com>
/*
* Copyright 2015 Cloudius Systems
*/
#include "server.hh"
#include <boost/bimap/unordered_set_of.hpp>
#include <boost/range/irange.hpp>
#include <boost/bimap.hpp>
#include <boost/assign.hpp>
#include <boost/locale/encoding_utf.hpp>
#include <boost/range/adaptor/sliced.hpp>
#include "service/migration_manager.hh"
#include "service/storage_service.hh"
#include "db/consistency_level.hh"
#include "core/future-util.hh"
#include "core/reactor.hh"
#include "utils/UUID.hh"
#include "database.hh"
#include "net/byteorder.hh"
#include <seastar/core/scollectd.hh>
#include "enum_set.hh"
#include "service/query_state.hh"
#include "service/client_state.hh"
#include "exceptions/exceptions.hh"
#include <cassert>
#include <string>
static logging::logger logger("cql_server");
struct cql_frame_error : std::exception {
const char* what() const throw () override {
return "bad cql binary frame";
}
};
struct [[gnu::packed]] cql_binary_frame_v1 {
uint8_t version;
uint8_t flags;
uint8_t stream;
uint8_t opcode;
net::packed<uint32_t> length;
template <typename Adjuster>
void adjust_endianness(Adjuster a) {
return a(length);
}
};
struct [[gnu::packed]] cql_binary_frame_v3 {
uint8_t version;
uint8_t flags;
net::packed<uint16_t> stream;
uint8_t opcode;
net::packed<uint32_t> length;
template <typename Adjuster>
void adjust_endianness(Adjuster a) {
return a(stream, length);
}
};
enum class cql_binary_opcode : uint8_t {
ERROR = 0,
STARTUP = 1,
READY = 2,
AUTHENTICATE = 3,
CREDENTIALS = 4,
OPTIONS = 5,
SUPPORTED = 6,
QUERY = 7,
RESULT = 8,
PREPARE = 9,
EXECUTE = 10,
REGISTER = 11,
EVENT = 12,
BATCH = 13,
AUTH_CHALLENGE = 14,
AUTH_RESPONSE = 15,
AUTH_SUCCESS = 16,
};
inline db::consistency_level wire_to_consistency(int16_t v)
{
switch (v) {
case 0x0000: return db::consistency_level::ANY;
case 0x0001: return db::consistency_level::ONE;
case 0x0002: return db::consistency_level::TWO;
case 0x0003: return db::consistency_level::THREE;
case 0x0004: return db::consistency_level::QUORUM;
case 0x0005: return db::consistency_level::ALL;
case 0x0006: return db::consistency_level::LOCAL_QUORUM;
case 0x0007: return db::consistency_level::EACH_QUORUM;
case 0x0008: return db::consistency_level::SERIAL;
case 0x0009: return db::consistency_level::LOCAL_SERIAL;
case 0x000A: return db::consistency_level::LOCAL_ONE;
default: throw exceptions::protocol_exception(sprint("Unknown code %d for a consistency level", v));
}
}
inline int16_t consistency_to_wire(db::consistency_level c)
{
switch (c) {
case db::consistency_level::ANY: return 0x0000;
case db::consistency_level::ONE: return 0x0001;
case db::consistency_level::TWO: return 0x0002;
case db::consistency_level::THREE: return 0x0003;
case db::consistency_level::QUORUM: return 0x0004;
case db::consistency_level::ALL: return 0x0005;
case db::consistency_level::LOCAL_QUORUM: return 0x0006;
case db::consistency_level::EACH_QUORUM: return 0x0007;
case db::consistency_level::SERIAL: return 0x0008;
case db::consistency_level::LOCAL_SERIAL: return 0x0009;
case db::consistency_level::LOCAL_ONE: return 0x000A;
default: throw std::runtime_error("Invalid consistency level");
}
}
sstring to_string(const transport::event::topology_change::change_type t) {
using type = transport::event::topology_change::change_type;
switch (t) {
case type::NEW_NODE: return "NEW_NODE";
case type::REMOVED_NODE: return "REMOVED_NODE";
case type::MOVED_NODE: return "MOVED_NODE";
}
throw std::invalid_argument("unknown change type");
}
sstring to_string(const transport::event::status_change::status_type t) {
using type = transport::event::status_change::status_type;
switch (t) {
case type::UP: return "NEW_NODE";
case type::DOWN: return "REMOVED_NODE";
}
throw std::invalid_argument("unknown change type");
}
sstring to_string(const transport::event::schema_change::change_type t) {
switch (t) {
case transport::event::schema_change::change_type::CREATED: return "CREATED";
case transport::event::schema_change::change_type::UPDATED: return "UPDATED";
case transport::event::schema_change::change_type::DROPPED: return "DROPPED";
}
throw std::invalid_argument("unknown change type");
}
sstring to_string(const transport::event::schema_change::target_type t) {
switch (t) {
case transport::event::schema_change::target_type::KEYSPACE: return "KEYSPACE";
case transport::event::schema_change::target_type::TABLE: return "TABLE";
case transport::event::schema_change::target_type::TYPE: return "TYPE";
}
throw std::invalid_argument("unknown target type");
}
transport::event::event_type parse_event_type(const sstring& value)
{
if (value == "TOPOLOGY_CHANGE") {
return transport::event::event_type::TOPOLOGY_CHANGE;
} else if (value == "STATUS_CHANGE") {
return transport::event::event_type::STATUS_CHANGE;
} else if (value == "SCHEMA_CHANGE") {
return transport::event::event_type::SCHEMA_CHANGE;
} else {
throw exceptions::protocol_exception(sprint("Invalid value '%s' for Event.Type", value));
}
}
struct cql_query_state {
service::query_state query_state;
std::unique_ptr<cql3::query_options> options;
cql_query_state(service::client_state& client_state)
: query_state(client_state)
{ }
};
class cql_server::connection {
cql_server& _server;
connected_socket _fd;
input_stream<char> _read_buf;
output_stream<char> _write_buf;
seastar::gate _pending_requests_gate;
future<> _ready_to_respond = make_ready_future<>();
uint8_t _version = 0;
serialization_format _serialization_format = serialization_format::use_16_bit();
service::client_state _client_state;
std::unordered_map<uint16_t, cql_query_state> _query_states;
public:
connection(cql_server& server, connected_socket&& fd, socket_address addr);
~connection();
future<> process();
future<> process_request();
private:
future<> process_request_one(temporary_buffer<char> buf,
uint8_t op,
uint16_t stream);
unsigned frame_size() const;
cql_binary_frame_v3 parse_frame(temporary_buffer<char> buf);
future<std::experimental::optional<cql_binary_frame_v3>> read_frame();
future<> process_startup(uint16_t stream, temporary_buffer<char> buf);
future<> process_auth_response(uint16_t stream, temporary_buffer<char> buf);
future<> process_options(uint16_t stream, temporary_buffer<char> buf);
future<> process_query(uint16_t stream, temporary_buffer<char> buf);
future<> process_prepare(uint16_t stream, temporary_buffer<char> buf);
future<> process_execute(uint16_t stream, temporary_buffer<char> buf);
future<> process_batch(uint16_t stream, temporary_buffer<char> buf);
future<> process_register(uint16_t stream, temporary_buffer<char> buf);
future<> write_unavailable_error(int16_t stream, exceptions::exception_code err, sstring msg, db::consistency_level cl, int32_t required, int32_t alive);
future<> write_read_timeout_error(int16_t stream, exceptions::exception_code err, sstring msg, db::consistency_level cl, int32_t received, int32_t blockfor, bool data_present);
future<> write_already_exists_error(int16_t stream, exceptions::exception_code err, sstring msg, sstring ks_name, sstring cf_name);
future<> write_unprepared_error(int16_t stream, exceptions::exception_code err, sstring msg, bytes id);
future<> write_error(int16_t stream, exceptions::exception_code err, sstring msg);
future<> write_ready(int16_t stream);
future<> write_supported(int16_t stream);
future<> write_result(int16_t stream, shared_ptr<transport::messages::result_message> msg);
future<> write_topology_change_event(const transport::event::topology_change& event);
future<> write_status_change_event(const transport::event::status_change& event);
future<> write_schema_change_event(const transport::event::schema_change& event);
future<> write_response(shared_ptr<cql_server::response> response);
void check_room(temporary_buffer<char>& buf, size_t n);
void validate_utf8(sstring_view s);
int8_t read_byte(temporary_buffer<char>& buf);
int32_t read_int(temporary_buffer<char>& buf);
int64_t read_long(temporary_buffer<char>& buf);
int16_t read_short(temporary_buffer<char>& buf);
uint16_t read_unsigned_short(temporary_buffer<char>& buf);
sstring read_string(temporary_buffer<char>& buf);
bytes read_short_bytes(temporary_buffer<char>& buf);
bytes_opt read_value(temporary_buffer<char>& buf);
sstring_view read_long_string_view(temporary_buffer<char>& buf);
void read_name_and_value_list(temporary_buffer<char>& buf, std::vector<sstring>& names, std::vector<bytes_opt>& values);
void read_string_list(temporary_buffer<char>& buf, std::vector<sstring>& strings);
void read_value_list(temporary_buffer<char>& buf, std::vector<bytes_opt>& values);
db::consistency_level read_consistency(temporary_buffer<char>& buf);
std::unordered_map<sstring, sstring> read_string_map(temporary_buffer<char>& buf);
std::unique_ptr<cql3::query_options> read_options(temporary_buffer<char>& buf);
cql_query_state& get_query_state(uint16_t stream);
void init_serialization_format();
friend event_notifier;
};
cql_server::event_notifier::event_notifier(uint16_t port)
: _port{port}
{
}
void cql_server::event_notifier::register_event(transport::event::event_type et, cql_server::connection* conn)
{
switch (et) {
case transport::event::event_type::TOPOLOGY_CHANGE:
_topology_change_listeners.emplace(conn);
break;
case transport::event::event_type::STATUS_CHANGE:
_status_change_listeners.emplace(conn);
break;
case transport::event::event_type::SCHEMA_CHANGE:
_schema_change_listeners.emplace(conn);
break;
}
}
void cql_server::event_notifier::unregister_connection(cql_server::connection* conn)
{
_topology_change_listeners.erase(conn);
_status_change_listeners.erase(conn);
_schema_change_listeners.erase(conn);
}
void cql_server::event_notifier::on_create_keyspace(const sstring& ks_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::CREATED,
ks_name
});
}
}
void cql_server::event_notifier::on_create_column_family(const sstring& ks_name, const sstring& cf_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::CREATED,
event::schema_change::target_type::TABLE,
ks_name,
cf_name
});
}
}
void cql_server::event_notifier::on_create_user_type(const sstring& ks_name, const sstring& type_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::CREATED,
event::schema_change::target_type::TYPE,
ks_name,
type_name
});
}
}
void cql_server::event_notifier::on_create_function(const sstring& ks_name, const sstring& function_name)
{
logger.warn("{} event ignored", __func__);
}
void cql_server::event_notifier::on_create_aggregate(const sstring& ks_name, const sstring& aggregate_name)
{
logger.warn("{} event ignored", __func__);
}
void cql_server::event_notifier::on_update_keyspace(const sstring& ks_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::UPDATED,
ks_name
});
}
}
void cql_server::event_notifier::on_update_column_family(const sstring& ks_name, const sstring& cf_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::UPDATED,
event::schema_change::target_type::TABLE,
ks_name,
cf_name
});
}
}
void cql_server::event_notifier::on_update_user_type(const sstring& ks_name, const sstring& type_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::UPDATED,
event::schema_change::target_type::TYPE,
ks_name,
type_name
});
}
}
void cql_server::event_notifier::on_update_function(const sstring& ks_name, const sstring& function_name)
{
logger.warn("%s event ignored", __func__);
}
void cql_server::event_notifier::on_update_aggregate(const sstring& ks_name, const sstring& aggregate_name)
{
logger.warn("%s event ignored", __func__);
}
void cql_server::event_notifier::on_drop_keyspace(const sstring& ks_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::DROPPED,
ks_name
});
}
}
void cql_server::event_notifier::on_drop_column_family(const sstring& ks_name, const sstring& cf_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::DROPPED,
event::schema_change::target_type::TABLE,
ks_name,
cf_name
});
}
}
void cql_server::event_notifier::on_drop_user_type(const sstring& ks_name, const sstring& type_name)
{
for (auto&& conn : _schema_change_listeners) {
using namespace transport;
conn->write_schema_change_event(event::schema_change{
event::schema_change::change_type::DROPPED,
event::schema_change::target_type::TYPE,
ks_name,
type_name
});
}
}
void cql_server::event_notifier::on_drop_function(const sstring& ks_name, const sstring& function_name)
{
logger.warn("%s event ignored", __func__);
}
void cql_server::event_notifier::on_drop_aggregate(const sstring& ks_name, const sstring& aggregate_name)
{
logger.warn("%s event ignored", __func__);
}
void cql_server::event_notifier::on_join_cluster(const gms::inet_address& endpoint)
{
for (auto&& conn : _topology_change_listeners) {
using namespace transport;
conn->write_topology_change_event(event::topology_change::new_node(endpoint, _port));
}
}
void cql_server::event_notifier::on_leave_cluster(const gms::inet_address& endpoint)
{
for (auto&& conn : _topology_change_listeners) {
using namespace transport;
conn->write_topology_change_event(event::topology_change::removed_node(endpoint, _port));
}
}
void cql_server::event_notifier::on_move(const gms::inet_address& endpoint)
{
for (auto&& conn : _topology_change_listeners) {
using namespace transport;
conn->write_topology_change_event(event::topology_change::moved_node(endpoint, _port));
}
}
void cql_server::event_notifier::on_up(const gms::inet_address& endpoint)
{
for (auto&& conn : _status_change_listeners) {
using namespace transport;
conn->write_status_change_event(event::status_change::node_up(endpoint, _port));
}
}
void cql_server::event_notifier::on_down(const gms::inet_address& endpoint)
{
for (auto&& conn : _status_change_listeners) {
using namespace transport;
conn->write_status_change_event(event::status_change::node_down(endpoint, _port));
}
}
class cql_server::response {
int16_t _stream;
cql_binary_opcode _opcode;
std::vector<char> _body;
public:
response(int16_t stream, cql_binary_opcode opcode)
: _stream{stream}
, _opcode{opcode}
{ }
scattered_message<char> make_message(uint8_t version);
void write_byte(uint8_t b);
void write_int(int32_t n);
void write_long(int64_t n);
void write_short(int16_t n);
void write_string(const sstring& s);
void write_long_string(const sstring& s);
void write_uuid(utils::UUID uuid);
void write_string_list(std::vector<sstring> string_list);
void write_bytes(bytes b);
void write_short_bytes(bytes b);
void write_option(std::pair<int16_t, boost::any> opt);
void write_option_list(std::vector<std::pair<int16_t, boost::any>> opt_list);
void write_inet(ipv4_addr inet);
void write_consistency(db::consistency_level c);
void write_string_map(std::map<sstring, sstring> string_map);
void write_string_multimap(std::multimap<sstring, sstring> string_map);
void write_value(bytes_opt value);
void write(const cql3::metadata& m);
private:
sstring make_frame(uint8_t version, size_t length);
};
cql_server::cql_server(distributed<service::storage_proxy>& proxy, distributed<cql3::query_processor>& qp)
: _proxy(proxy)
, _query_processor(qp)
, _collectd_registrations(std::make_unique<scollectd::registrations>(setup_collectd()))
{
}
scollectd::registrations
cql_server::setup_collectd() {
return {
scollectd::add_polled_metric(
scollectd::type_instance_id("transport", scollectd::per_cpu_plugin_instance,
"connections", "cql-connections"),
scollectd::make_typed(scollectd::data_type::DERIVE, _connects)),
scollectd::add_polled_metric(
scollectd::type_instance_id("transport", scollectd::per_cpu_plugin_instance,
"current_connections", "current"),
scollectd::make_typed(scollectd::data_type::GAUGE, _connects)),
scollectd::add_polled_metric(
scollectd::type_instance_id("transport", scollectd::per_cpu_plugin_instance,
"total_requests", "requests_served"),
scollectd::make_typed(scollectd::data_type::DERIVE, _requests_served)),
scollectd::add_polled_metric(
scollectd::type_instance_id("transport", scollectd::per_cpu_plugin_instance,
"queue_length", "requests_serving"),
scollectd::make_typed(scollectd::data_type::GAUGE, _requests_serving)),
};
}
future<> cql_server::stop() {
service::get_local_storage_service().unregister_subscriber(_notifier.get());
service::get_local_migration_manager().unregister_listener(_notifier.get());
return make_ready_future<>();
}
future<>
cql_server::listen(ipv4_addr addr) {
_notifier = std::make_unique<event_notifier>(addr.port);
service::get_local_migration_manager().register_listener(_notifier.get());
service::get_local_storage_service().register_subscriber(_notifier.get());
listen_options lo;
lo.reuse_address = true;
_listeners.push_back(engine().listen(make_ipv4_address(addr), lo));
do_accepts(_listeners.size() - 1);
return make_ready_future<>();
}
void
cql_server::do_accepts(int which) {
_listeners[which].accept().then([this, which] (connected_socket fd, socket_address addr) mutable {
auto conn = make_shared<connection>(*this, std::move(fd), addr);
++_connects;
++_connections;
conn->process().then_wrapped([this, conn] (future<> f) {
--_connections;
try {
f.get();
} catch (std::exception& ex) {
logger.debug("connection error: {}", ex.what());
}
});
do_accepts(which);
}).then_wrapped([] (future<> f) {
try {
f.get();
} catch (std::exception& ex) {
logger.debug("accept failed: {}", ex.what());
}
});
}
unsigned
cql_server::connection::frame_size() const {
if (_version < 3) {
return 8;
} else {
return 9;
}
}
cql_binary_frame_v3
cql_server::connection::parse_frame(temporary_buffer<char> buf) {
if (buf.size() != frame_size()) {
throw cql_frame_error();
}
cql_binary_frame_v3 v3;
switch (_version) {
case 1:
case 2: {
auto raw = reinterpret_cast<const cql_binary_frame_v1*>(buf.get());
auto cooked = net::ntoh(*raw);
v3.version = cooked.version;
v3.flags = cooked.flags;
v3.opcode = cooked.opcode;
v3.stream = cooked.stream;
v3.length = cooked.length;
break;
}
case 3:
case 4: {
v3 = net::ntoh(*reinterpret_cast<const cql_binary_frame_v3*>(buf.get()));
break;
}
default:
throw exceptions::protocol_exception(sprint("Invalid or unsupported protocol version: %d", _version));
}
if (v3.version != _version) {
throw exceptions::protocol_exception(sprint("Invalid message version. Got %d but previous messages on this connection had version %d", v3.version, _version));
}
return v3;
}
future<std::experimental::optional<cql_binary_frame_v3>>
cql_server::connection::read_frame() {
using ret_type = std::experimental::optional<cql_binary_frame_v3>;
if (!_version) {
// We don't know the frame size before reading the first frame,
// so read just one byte, and then read the rest of the frame.
return _read_buf.read_exactly(1).then([this] (temporary_buffer<char> buf) {
if (buf.empty()) {
return make_ready_future<ret_type>();
}
_version = buf[0];
init_serialization_format();
if (_version < 1 || _version > current_version) {
throw exceptions::protocol_exception(sprint("Invalid or unsupported protocol version: %d", _version));
}
return _read_buf.read_exactly(frame_size() - 1).then([this] (temporary_buffer<char> tail) {
temporary_buffer<char> full(frame_size());
full.get_write()[0] = _version;
std::copy(tail.get(), tail.get() + tail.size(), full.get_write() + 1);
return make_ready_future<ret_type>(parse_frame(std::move(full)));
});
});
} else {
// Not the first frame, so we know the size.
return _read_buf.read_exactly(frame_size()).then([this] (temporary_buffer<char> buf) {
if (buf.empty()) {
return make_ready_future<ret_type>();
}
return make_ready_future<ret_type>(parse_frame(std::move(buf)));
});
}
}
future<> cql_server::connection::process_request_one(temporary_buffer<char> buf,
uint8_t op,
uint16_t stream) {
return make_ready_future<>().then([this, op, stream, buf = std::move(buf)] () mutable {
switch (static_cast<cql_binary_opcode>(op)) {
case cql_binary_opcode::STARTUP: return process_startup(stream, std::move(buf));
case cql_binary_opcode::AUTH_RESPONSE: return process_auth_response(stream, std::move(buf));
case cql_binary_opcode::OPTIONS: return process_options(stream, std::move(buf));
case cql_binary_opcode::QUERY: return process_query(stream, std::move(buf));
case cql_binary_opcode::PREPARE: return process_prepare(stream, std::move(buf));
case cql_binary_opcode::EXECUTE: return process_execute(stream, std::move(buf));
case cql_binary_opcode::BATCH: return process_batch(stream, std::move(buf));
case cql_binary_opcode::REGISTER: return process_register(stream, std::move(buf));
default: throw exceptions::protocol_exception(sprint("Unknown opcode %d", op));
}
}).then_wrapped([stream, this] (future<> f) {
--_server._requests_serving;
try {
f.get();
return make_ready_future<>();
} catch (const exceptions::unavailable_exception& ex) {
return write_unavailable_error(stream, ex.code(), ex.what(), ex.consistency, ex.required, ex.alive);
} catch (const exceptions::read_timeout_exception& ex) {
return write_read_timeout_error(stream, ex.code(), ex.what(), ex.consistency, ex.received, ex.block_for, ex.data_present);
} catch (const exceptions::already_exists_exception& ex) {
return write_already_exists_error(stream, ex.code(), ex.what(), ex.ks_name, ex.cf_name);
} catch (const exceptions::prepared_query_not_found_exception& ex) {
return write_unprepared_error(stream, ex.code(), ex.what(), ex.id);
} catch (const exceptions::cassandra_exception& ex) {
return write_error(stream, ex.code(), ex.what());
} catch (std::exception& ex) {
return write_error(stream, exceptions::exception_code::SERVER_ERROR, ex.what());
} catch (...) {
return write_error(stream, exceptions::exception_code::SERVER_ERROR, "unknown error");
}
});
}
cql_server::connection::connection(cql_server& server, connected_socket&& fd, socket_address addr)
: _server(server)
, _fd(std::move(fd))
, _read_buf(_fd.input())
, _write_buf(_fd.output())
, _client_state(service::client_state::for_external_calls())
{ }
cql_server::connection::~connection()
{
_server._notifier->unregister_connection(this);
}
future<> cql_server::connection::process()
{
return do_until([this] {
return _read_buf.eof();
}, [this] {
return process_request();
}).then_wrapped([this] (future<> f) {
try {
f.get();
return make_ready_future<>();
} catch (const exceptions::cassandra_exception& ex) {
return write_error(0, ex.code(), ex.what());
} catch (std::exception& ex) {
return write_error(0, exceptions::exception_code::SERVER_ERROR, ex.what());
} catch (...) {
return write_error(0, exceptions::exception_code::SERVER_ERROR, "unknown error");
}
}).finally([this] {
return _pending_requests_gate.close().then([this] {
return std::move(_ready_to_respond);
});
});
}
future<> cql_server::connection::process_request() {
return read_frame().then_wrapped([this] (future<std::experimental::optional<cql_binary_frame_v3>>&& v) {
auto maybe_frame = std::get<0>(v.get());
if (!maybe_frame) {
// eof
return make_ready_future<>();
}
auto& f = *maybe_frame;
// FIXME: compression
if (f.flags & 0x01) {
throw std::runtime_error("CQL frame compression is not supported");
}
auto op = f.opcode;
auto stream = f.stream;
return _read_buf.read_exactly(f.length).then([this, op, stream] (temporary_buffer<char> buf) {
++_server._requests_served;
++_server._requests_serving;
with_gate(
_pending_requests_gate,
[this, op, stream, buf = std::move(buf)] () mutable {
return process_request_one(std::move(buf), op, stream);
}
);
return make_ready_future<>();
});
});
}
future<> cql_server::connection::process_startup(uint16_t stream, temporary_buffer<char> buf)
{
/*auto string_map =*/ read_string_map(buf);
return write_ready(stream);
}
future<> cql_server::connection::process_auth_response(uint16_t stream, temporary_buffer<char> buf)
{
assert(0);
return make_ready_future<>();
}
future<> cql_server::connection::process_options(uint16_t stream, temporary_buffer<char> buf)
{
return write_supported(stream);
}
cql_query_state& cql_server::connection::get_query_state(uint16_t stream)
{
auto i = _query_states.find(stream);
if (i == _query_states.end()) {
i = _query_states.emplace(stream, _client_state).first;
}
return i->second;
}
void
cql_server::connection::init_serialization_format() {
if (_version < 3) {
_serialization_format = serialization_format::use_16_bit();
} else {
_serialization_format = serialization_format::use_32_bit();
}
}
future<> cql_server::connection::process_query(uint16_t stream, temporary_buffer<char> buf)
{
auto query = read_long_string_view(buf);
auto& q_state = get_query_state(stream);
q_state.options = read_options(buf);
return _server._query_processor.local().process(query, q_state.query_state, *q_state.options).then([this, stream] (auto msg) {
return this->write_result(stream, msg);
});
}
future<> cql_server::connection::process_prepare(uint16_t stream, temporary_buffer<char> buf)
{
auto query = read_long_string_view(buf).to_string();
auto cpu_id = engine().cpu_id();
auto cpus = boost::irange(0u, smp::count);
return parallel_for_each(cpus.begin(), cpus.end(), [this, query, cpu_id, stream] (unsigned int c) mutable {
if (c != cpu_id) {
return smp::submit_to(c, [this, query, stream] () mutable {
auto& q_state = get_query_state(stream); // FIXME: is this safe?
_server._query_processor.local().prepare(query, q_state.query_state);
// FIXME: error handling
});
} else {
return make_ready_future<>();
}
}).then([this, query, stream] {
auto& q_state = get_query_state(stream);
return _server._query_processor.local().prepare(query, q_state.query_state).then([this, stream] (auto msg) {
return this->write_result(stream, msg);
});
});
}
future<> cql_server::connection::process_execute(uint16_t stream, temporary_buffer<char> buf)
{
auto id = read_short_bytes(buf);
auto prepared = _server._query_processor.local().get_prepared(id);
if (!prepared) {
throw exceptions::prepared_query_not_found_exception(id);
}
auto& q_state = get_query_state(stream);
auto& query_state = q_state.query_state;
q_state.options = read_options(buf);
auto& options = *q_state.options;
options.prepare(prepared->bound_names);
auto stmt = prepared->statement;
if (stmt->get_bound_terms() != options.get_values().size()) {
throw exceptions::invalid_request_exception("Invalid amount of bind variables");
}
return _server._query_processor.local().process_statement(stmt, query_state, options).then([this, stream] (auto msg) {
return this->write_result(stream, msg);
});
}
future<> cql_server::connection::process_batch(uint16_t stream, temporary_buffer<char> buf)
{
assert(0);
return make_ready_future<>();
}
future<> cql_server::connection::process_register(uint16_t stream, temporary_buffer<char> buf)
{
std::vector<sstring> event_types;
read_string_list(buf, event_types);
for (auto&& event_type : event_types) {
auto et = parse_event_type(event_type);
_server._notifier->register_event(et, this);
}
return write_ready(stream);
}
future<> cql_server::connection::write_unavailable_error(int16_t stream, exceptions::exception_code err, sstring msg, db::consistency_level cl, int32_t required, int32_t alive)
{
auto response = make_shared<cql_server::response>(stream, cql_binary_opcode::ERROR);
response->write_int(static_cast<int32_t>(err));
response->write_string(msg);
response->write_consistency(cl);
response->write_int(required);
response->write_int(alive);
return write_response(response);
}
future<> cql_server::connection::write_read_timeout_error(int16_t stream, exceptions::exception_code err, sstring msg, db::consistency_level cl, int32_t received, int32_t blockfor, bool data_present)
{
auto response = make_shared<cql_server::response>(stream, cql_binary_opcode::ERROR);
response->write_int(static_cast<int32_t>(err));
response->write_string(msg);
response->write_consistency(cl);
response->write_int(received);
response->write_int(blockfor);
response->write_byte(data_present);
return write_response(response);
}
future<> cql_server::connection::write_already_exists_error(int16_t stream, exceptions::exception_code err, sstring msg, sstring ks_name, sstring cf_name)
{
auto response = make_shared<cql_server::response>(stream, cql_binary_opcode::ERROR);
response->write_int(static_cast<int32_t>(err));
response->write_string(msg);
response->write_string(ks_name);
response->write_string(cf_name);
return write_response(response);
}
future<> cql_server::connection::write_unprepared_error(int16_t stream, exceptions::exception_code err, sstring msg, bytes id)
{
auto response = make_shared<cql_server::response>(stream, cql_binary_opcode::ERROR);
response->write_int(static_cast<int32_t>(err));
response->write_string(msg);
response->write_short_bytes(id);
return write_response(response);
}
future<> cql_server::connection::write_error(int16_t stream, exceptions::exception_code err, sstring msg)
{
auto response = make_shared<cql_server::response>(stream, cql_binary_opcode::ERROR);
response->write_int(static_cast<int32_t>(err));
response->write_string(msg);
return write_response(response);
}
future<> cql_server::connection::write_ready(int16_t stream)
{
auto response = make_shared<cql_server::response>(stream, cql_binary_opcode::READY);
return write_response(response);
}
future<> cql_server::connection::write_supported(int16_t stream)
{
std::multimap<sstring, sstring> opts;
opts.insert({"CQL_VERSION", cql3::query_processor::CQL_VERSION});
opts.insert({"COMPRESSION", "snappy"});
auto response = make_shared<cql_server::response>(stream, cql_binary_opcode::SUPPORTED);
response->write_string_multimap(opts);
return write_response(response);
}
class cql_server::fmt_visitor : public transport::messages::result_message::visitor {
private:
uint8_t _version;
shared_ptr<cql_server::response> _response;
public:
fmt_visitor(uint8_t version, shared_ptr<cql_server::response> response)
: _version{version}
, _response{response}
{ }
virtual void visit(const transport::messages::result_message::void_message&) override {
_response->write_int(0x0001);
}
virtual void visit(const transport::messages::result_message::set_keyspace& m) override {
_response->write_int(0x0003);
_response->write_string(m.get_keyspace());
}
virtual void visit(const transport::messages::result_message::prepared& m) override {
auto prepared = m.get_prepared();
_response->write_int(0x0004);
_response->write_short_bytes(m.get_id());
// FIXME: not compatible with v4
assert(_version < 4);
cql3::metadata metadata{prepared->bound_names};
_response->write(metadata);
if (_version > 1) {
cql3::metadata result_metadata{std::vector<::shared_ptr<cql3::column_specification>>{}};
result_metadata.set_skip_metadata();
_response->write(result_metadata);
}
}
virtual void visit(const transport::messages::result_message::schema_change& m) override {
auto change = m.get_change();
switch (change->type) {
case transport::event::event_type::SCHEMA_CHANGE: {
auto sc = static_pointer_cast<transport::event::schema_change>(change);
_response->write_int(0x0005);
_response->write_string(to_string(sc->change));
_response->write_string(to_string(sc->target));
_response->write_string(sc->keyspace);
if (sc->target != transport::event::schema_change::target_type::KEYSPACE) {
_response->write_string(sc->table_or_type_or_function.value());
}
break;
}
default:
assert(0);
}
}
virtual void visit(const transport::messages::result_message::rows& m) override {
_response->write_int(0x0002);
auto& rs = m.rs();
_response->write(rs.get_metadata());
_response->write_int(rs.size());
for (auto&& row : rs.rows()) {
for (auto&& cell : row | boost::adaptors::sliced(0, rs.get_metadata().column_count())) {
_response->write_value(cell);
}
}
}
};
future<> cql_server::connection::write_result(int16_t stream, shared_ptr<transport::messages::result_message> msg)
{
auto response = make_shared<cql_server::response>(stream, cql_binary_opcode::RESULT);
fmt_visitor fmt{_version, response};
msg->accept(fmt);
return write_response(response);
}
future<> cql_server::connection::write_topology_change_event(const transport::event::topology_change& event)
{
auto response = make_shared<cql_server::response>(-1, cql_binary_opcode::EVENT);
response->write_string("TOPOLOGY_CHANGE");
response->write_string(to_string(event.change));
response->write_inet(event.node);
return write_response(response);
}
future<> cql_server::connection::write_status_change_event(const transport::event::status_change& event)
{
auto response = make_shared<cql_server::response>(-1, cql_binary_opcode::EVENT);
response->write_string("STATUS_CHANGE");
response->write_string(to_string(event.status));
response->write_inet(event.node);
return write_response(response);
}
future<> cql_server::connection::write_schema_change_event(const transport::event::schema_change& event)
{
auto response = make_shared<cql_server::response>(-1, cql_binary_opcode::EVENT);
response->write_string("SCHEMA_CHANGE");
response->write_string(to_string(event.change));
response->write_string(to_string(event.target));
response->write_string(event.keyspace);
if (event.target != transport::event::schema_change::target_type::KEYSPACE) {
response->write_string(*(event.table_or_type_or_function));
}
return write_response(response);
}
future<> cql_server::connection::write_response(shared_ptr<cql_server::response> response)
{
auto msg = response->make_message(_version);
_ready_to_respond = _ready_to_respond.then([this, msg = std::move(msg)] () mutable {
return _write_buf.write(std::move(msg)).then([this] {
return _write_buf.flush();
});
});
return make_ready_future<>();
}
void cql_server::connection::check_room(temporary_buffer<char>& buf, size_t n)
{
if (buf.size() < n) {
throw exceptions::protocol_exception("truncated frame");
}
}
void cql_server::connection::validate_utf8(sstring_view s)
{
try {
boost::locale::conv::utf_to_utf<char>(s.begin(), s.end(), boost::locale::conv::stop);
} catch (const boost::locale::conv::conversion_error& ex) {
throw exceptions::protocol_exception("Cannot decode string as UTF8");
}
}
int8_t cql_server::connection::read_byte(temporary_buffer<char>& buf)
{
check_room(buf, 1);
int8_t n = buf[0];
buf.trim_front(1);
return n;
}
int32_t cql_server::connection::read_int(temporary_buffer<char>& buf)
{
check_room(buf, sizeof(int32_t));
auto p = reinterpret_cast<const uint8_t*>(buf.begin());
uint32_t n = (static_cast<uint32_t>(p[0]) << 24)
| (static_cast<uint32_t>(p[1]) << 16)
| (static_cast<uint32_t>(p[2]) << 8)
| (static_cast<uint32_t>(p[3]));
buf.trim_front(4);
return n;
}
int64_t cql_server::connection::read_long(temporary_buffer<char>& buf)
{
check_room(buf, sizeof(int64_t));
auto p = reinterpret_cast<const uint8_t*>(buf.begin());
uint64_t n = (static_cast<uint64_t>(p[0]) << 56)
| (static_cast<uint64_t>(p[1]) << 48)
| (static_cast<uint64_t>(p[2]) << 40)
| (static_cast<uint64_t>(p[3]) << 32)
| (static_cast<uint64_t>(p[4]) << 24)
| (static_cast<uint64_t>(p[5]) << 16)
| (static_cast<uint64_t>(p[6]) << 8)
| (static_cast<uint64_t>(p[7]));
buf.trim_front(8);
return n;
}
int16_t cql_server::connection::read_short(temporary_buffer<char>& buf)
{
return static_cast<int16_t>(read_unsigned_short(buf));
}
uint16_t cql_server::connection::read_unsigned_short(temporary_buffer<char>& buf)
{
check_room(buf, sizeof(uint16_t));
auto p = reinterpret_cast<const uint8_t*>(buf.begin());
uint16_t n = (static_cast<uint16_t>(p[0]) << 8)
| (static_cast<uint16_t>(p[1]));
buf.trim_front(2);
return n;
}
bytes cql_server::connection::read_short_bytes(temporary_buffer<char>& buf)
{
auto n = read_short(buf);
check_room(buf, n);
bytes s{reinterpret_cast<const int8_t*>(buf.begin()), static_cast<size_t>(n)};
assert(n >= 0);
buf.trim_front(n);
return s;
}
sstring cql_server::connection::read_string(temporary_buffer<char>& buf)
{
auto n = read_short(buf);
check_room(buf, n);
sstring s{buf.begin(), static_cast<size_t>(n)};
assert(n >= 0);
buf.trim_front(n);
validate_utf8(s);
return s;
}
sstring_view cql_server::connection::read_long_string_view(temporary_buffer<char>& buf)
{
auto n = read_int(buf);
check_room(buf, n);
sstring_view s{buf.begin(), static_cast<size_t>(n)};
buf.trim_front(n);
validate_utf8(s);
return s;
}
db::consistency_level cql_server::connection::read_consistency(temporary_buffer<char>& buf)
{
return wire_to_consistency(read_short(buf));
}
std::unordered_map<sstring, sstring> cql_server::connection::read_string_map(temporary_buffer<char>& buf)
{
std::unordered_map<sstring, sstring> string_map;
auto n = read_short(buf);
for (auto i = 0; i < n; i++) {
auto key = read_string(buf);
auto val = read_string(buf);
string_map.emplace(std::piecewise_construct,
std::forward_as_tuple(std::move(key)),
std::forward_as_tuple(std::move(val)));
}
return string_map;
}
enum class options_flag {
VALUES,
SKIP_METADATA,
PAGE_SIZE,
PAGING_STATE,
SERIAL_CONSISTENCY,
TIMESTAMP,
NAMES_FOR_VALUES
};
using options_flag_enum = super_enum<options_flag,
options_flag::VALUES,
options_flag::SKIP_METADATA,
options_flag::PAGE_SIZE,
options_flag::PAGING_STATE,
options_flag::SERIAL_CONSISTENCY,
options_flag::TIMESTAMP,
options_flag::NAMES_FOR_VALUES
>;
std::unique_ptr<cql3::query_options> cql_server::connection::read_options(temporary_buffer<char>& buf)
{
auto consistency = read_consistency(buf);
if (_version == 1) {
return std::make_unique<cql3::query_options>(consistency, std::experimental::nullopt, std::vector<bytes_opt>{},
false, cql3::query_options::specific_options::DEFAULT, 1, _serialization_format);
}
assert(_version >= 2);
auto flags = enum_set<options_flag_enum>::from_mask(read_byte(buf));
std::vector<bytes_opt> values;
std::vector<sstring> names;
if (flags.contains<options_flag::VALUES>()) {
if (flags.contains<options_flag::NAMES_FOR_VALUES>()) {
read_name_and_value_list(buf, names, values);
} else {
read_value_list(buf, values);
}
}
bool skip_metadata = flags.contains<options_flag::SKIP_METADATA>();
flags.remove<options_flag::VALUES>();
flags.remove<options_flag::SKIP_METADATA>();
std::unique_ptr<cql3::query_options> options;
if (flags) {
::shared_ptr<service::pager::paging_state> paging_state;
int32_t page_size = flags.contains<options_flag::PAGE_SIZE>() ? read_int(buf) : -1;
if (flags.contains<options_flag::PAGING_STATE>()) {
fail(unimplemented::cause::PAGING);
#if 0
paging_state = PagingState.deserialize(CBUtil.readValue(body))
#endif
}
db::consistency_level serial_consistency = db::consistency_level::SERIAL;
if (flags.contains<options_flag::SERIAL_CONSISTENCY>()) {
serial_consistency = read_consistency(buf);
}
api::timestamp_type ts = api::missing_timestamp;
if (flags.contains<options_flag::TIMESTAMP>()) {
ts = read_long(buf);
if (ts < api::min_timestamp || ts > api::max_timestamp) {
throw exceptions::protocol_exception(sprint("Out of bound timestamp, must be in [%d, %d] (got %d)",
api::min_timestamp, api::max_timestamp, ts));
}
}
std::experimental::optional<std::vector<sstring>> onames;
if (!names.empty()) {
onames = std::move(names);
}
options = std::make_unique<cql3::query_options>(consistency, std::move(onames), std::move(values), skip_metadata,
cql3::query_options::specific_options{page_size, std::move(paging_state), serial_consistency, ts}, _version,
_serialization_format);
} else {
options = std::make_unique<cql3::query_options>(consistency, std::experimental::nullopt, std::move(values), skip_metadata,
cql3::query_options::specific_options::DEFAULT, _version, _serialization_format);
}
return std::move(options);
}
void cql_server::connection::read_name_and_value_list(temporary_buffer<char>& buf, std::vector<sstring>& names, std::vector<bytes_opt>& values) {
uint16_t size = read_unsigned_short(buf);
names.reserve(size);
values.reserve(size);
for (uint16_t i = 0; i < size; i++) {
names.emplace_back(read_string(buf));
values.emplace_back(read_value(buf));
}
}
void cql_server::connection::read_string_list(temporary_buffer<char>& buf, std::vector<sstring>& strings) {
uint16_t size = read_unsigned_short(buf);
strings.reserve(size);
for (uint16_t i = 0; i < size; i++) {
strings.emplace_back(read_string(buf));
}
}
void cql_server::connection::read_value_list(temporary_buffer<char>& buf, std::vector<bytes_opt>& values) {
uint16_t size = read_unsigned_short(buf);
values.reserve(size);
for (uint16_t i = 0; i < size; i++) {
values.emplace_back(read_value(buf));
}
}
bytes_opt cql_server::connection::read_value(temporary_buffer<char>& buf) {
auto len = read_int(buf);
if (len < 0) {
return {};
}
check_room(buf, len);
bytes b(reinterpret_cast<const int8_t*>(buf.begin()), len);
buf.trim_front(len);
return {std::move(b)};
}
scattered_message<char> cql_server::response::make_message(uint8_t version) {
scattered_message<char> msg;
sstring body{_body.data(), _body.size()};
sstring frame = make_frame(version, body.size());
msg.append(std::move(frame));
msg.append(std::move(body));
return msg;
}
sstring cql_server::response::make_frame(uint8_t version, size_t length)
{
switch (version) {
case 0x01:
case 0x02: {
sstring frame_buf(sstring::initialized_later(), sizeof(cql_binary_frame_v1));
auto* frame = reinterpret_cast<cql_binary_frame_v1*>(frame_buf.begin());
frame->version = version | 0x80;
frame->flags = 0x00;
frame->stream = _stream;
frame->opcode = static_cast<uint8_t>(_opcode);
frame->length = htonl(length);
return frame_buf;
}
case 0x03:
case 0x04: {
sstring frame_buf(sstring::initialized_later(), sizeof(cql_binary_frame_v3));
auto* frame = reinterpret_cast<cql_binary_frame_v3*>(frame_buf.begin());
frame->version = version | 0x80;
frame->flags = 0x00;
frame->stream = htons(_stream);
frame->opcode = static_cast<uint8_t>(_opcode);
frame->length = htonl(length);
return frame_buf;
}
default:
throw exceptions::protocol_exception(sprint("Invalid or unsupported protocol version: %d", version));
}
}
void cql_server::response::write_byte(uint8_t b)
{
_body.insert(_body.end(), b);
}
void cql_server::response::write_int(int32_t n)
{
auto u = htonl(n);
auto *s = reinterpret_cast<const char*>(&u);
_body.insert(_body.end(), s, s+sizeof(u));
}
void cql_server::response::write_long(int64_t n)
{
auto u = htonq(n);
auto *s = reinterpret_cast<const char*>(&u);
_body.insert(_body.end(), s, s+sizeof(u));
}
void cql_server::response::write_short(int16_t n)
{
auto u = htons(n);
auto *s = reinterpret_cast<const char*>(&u);
_body.insert(_body.end(), s, s+sizeof(u));
}
void cql_server::response::write_string(const sstring& s)
{
assert(s.size() < std::numeric_limits<int16_t>::max());
write_short(s.size());
_body.insert(_body.end(), s.begin(), s.end());
}
void cql_server::response::write_long_string(const sstring& s)
{
assert(s.size() < std::numeric_limits<int32_t>::max());
write_int(s.size());
_body.insert(_body.end(), s.begin(), s.end());
}
void cql_server::response::write_uuid(utils::UUID uuid)
{
// FIXME
assert(0);
}
void cql_server::response::write_string_list(std::vector<sstring> string_list)
{
assert(string_list.size() < std::numeric_limits<int16_t>::max());
write_short(string_list.size());
for (auto&& s : string_list) {
write_string(s);
}
}
void cql_server::response::write_bytes(bytes b)
{
assert(b.size() < std::numeric_limits<int32_t>::max());
write_int(b.size());
_body.insert(_body.end(), b.begin(), b.end());
}
void cql_server::response::write_short_bytes(bytes b)
{
assert(b.size() < std::numeric_limits<int16_t>::max());
write_short(b.size());
_body.insert(_body.end(), b.begin(), b.end());
}
void cql_server::response::write_option(std::pair<int16_t, boost::any> opt)
{
// FIXME
assert(0);
}
void cql_server::response::write_option_list(std::vector<std::pair<int16_t, boost::any>> opt_list)
{
// FIXME
assert(0);
}
void cql_server::response::write_inet(ipv4_addr inet)
{
write_byte(4);
write_byte(((inet.ip & 0xff000000) >> 24));
write_byte(((inet.ip & 0x00ff0000) >> 16));
write_byte(((inet.ip & 0x0000ff00) >> 8 ));
write_byte(((inet.ip & 0x000000ff) ));
write_int(inet.port);
}
void cql_server::response::write_consistency(db::consistency_level c)
{
write_short(consistency_to_wire(c));
}
void cql_server::response::write_string_map(std::map<sstring, sstring> string_map)
{
assert(string_map.size() < std::numeric_limits<int16_t>::max());
write_short(string_map.size());
for (auto&& s : string_map) {
write_string(s.first);
write_string(s.second);
}
}
void cql_server::response::write_string_multimap(std::multimap<sstring, sstring> string_map)
{
std::vector<sstring> keys;
for (auto it = string_map.begin(), end = string_map.end(); it != end; it = string_map.upper_bound(it->first)) {
keys.push_back(it->first);
}
assert(keys.size() < std::numeric_limits<int16_t>::max());
write_short(keys.size());
for (auto&& key : keys) {
std::vector<sstring> values;
auto range = string_map.equal_range(key);
for (auto it = range.first; it != range.second; ++it) {
values.push_back(it->second);
}
write_string(key);
write_string_list(values);
}
}
void cql_server::response::write_value(bytes_opt value)
{
if (!value) {
write_int(-1);
return;
}
write_int(value->size());
_body.insert(_body.end(), value->begin(), value->end());
}
class type_codec {
private:
enum class type_id : int16_t {
CUSTOM = 0,
ASCII,
BIGINT,
BLOB,
BOOLEAN,
COUNTER,
DECIMAL,
DOUBLE,
FLOAT,
INT,
TEXT,
TIMESTAMP,
UUID,
VARCHAR,
VARINT,
TIMEUUID,
INET,
LIST = 32,
MAP,
SET,
UDT = 48,
TUPLE
};
using type_id_to_type_type = boost::bimap<
boost::bimaps::unordered_set_of<type_id>,
boost::bimaps::unordered_set_of<data_type>>;
static thread_local const type_id_to_type_type type_id_to_type;
public:
static void encode(cql_server::response& r, data_type type) {
type = type->underlying_type();
// For compatibility sake, we still return DateType as the timestamp type in resultSet metadata (#5723)
if (type == date_type) {
type = timestamp_type;
}
auto i = type_id_to_type.right.find(type);
if (i != type_id_to_type.right.end()) {
r.write_short(static_cast<std::underlying_type<type_id>::type>(i->second));
return;
}
if (type->is_reversed()) {
fail(unimplemented::cause::REVERSED);
}
if (type->is_collection()) {
auto&& ctype = static_cast<const collection_type_impl*>(type.get());
if (&ctype->_kind == &collection_type_impl::kind::map) {
r.write_short(uint16_t(type_id::MAP));
auto&& mtype = static_cast<const map_type_impl*>(ctype);
encode(r, mtype->get_keys_type());
encode(r, mtype->get_values_type());
} else if (&ctype->_kind == &collection_type_impl::kind::set) {
r.write_short(uint16_t(type_id::SET));
auto&& stype = static_cast<const set_type_impl*>(ctype);
encode(r, stype->get_elements_type());
} else if (&ctype->_kind == &collection_type_impl::kind::list) {
r.write_short(uint16_t(type_id::LIST));
auto&& ltype = static_cast<const list_type_impl*>(ctype);
encode(r, ltype->get_elements_type());
} else {
abort();
}
return;
}
abort();
}
};
thread_local const type_codec::type_id_to_type_type type_codec::type_id_to_type = boost::assign::list_of<type_id_to_type_type::relation>
(type_id::ASCII , ascii_type)
(type_id::BIGINT , long_type)
(type_id::BLOB , bytes_type)
(type_id::BOOLEAN , boolean_type)
//(type_id::COUNTER , CounterColumn_type)
//(type_id::DECIMAL , Decimal_type)
(type_id::DOUBLE , double_type)
(type_id::FLOAT , float_type)
(type_id::INT , int32_type)
(type_id::TEXT , utf8_type)
(type_id::TIMESTAMP , timestamp_type)
(type_id::UUID , uuid_type)
(type_id::VARCHAR , utf8_type)
(type_id::VARINT , varint_type)
(type_id::TIMEUUID , timeuuid_type)
(type_id::INET , inet_addr_type);
void cql_server::response::write(const cql3::metadata& m) {
bool no_metadata = m.flags().contains<cql3::metadata::flag::NO_METADATA>();
bool global_tables_spec = m.flags().contains<cql3::metadata::flag::GLOBAL_TABLES_SPEC>();
bool has_more_pages = m.flags().contains<cql3::metadata::flag::HAS_MORE_PAGES>();
write_int(m.flags().mask());
write_int(m.column_count());
if (has_more_pages) {
write_value(m.paging_state()->serialize());
}
if (no_metadata) {
return;
}
auto names_i = m.get_names().begin();
if (global_tables_spec) {
auto first_spec = *names_i;
write_string(first_spec->ks_name);
write_string(first_spec->cf_name);
}
for (uint32_t i = 0; i < m.column_count(); ++i, ++names_i) {
::shared_ptr<cql3::column_specification> name = *names_i;
if (!global_tables_spec) {
write_string(name->ks_name);
write_string(name->cf_name);
}
write_string(name->name->text());
type_codec::encode(*this, name->type);
};
}
|
#include "mitkOpenGLRenderer.h"
#include "Mapper.h"
#include "mitkImageMapper2D.h"
#include "BaseVtkMapper2D.h"
#include "BaseVtkMapper3D.h"
#include "LevelWindow.h"
#include "mitkVtkInteractorCameraController.h"
#include "mitkVtkRenderWindow.h"
#include "mitkRenderWindow.h"
#include <vtkRenderer.h>
#include <vtkLight.h>
#include <vtkLightKit.h>
#include <vtkRenderWindow.h>
#include <vtkTransform.h>
#include <vtkCamera.h>
#include "PlaneGeometry.h"
#include "mitkProperties.h"
#include <queue>
#include <utility>
//##ModelId=3E33ECF301AD
mitk::OpenGLRenderer::OpenGLRenderer() : m_VtkMapperPresent(false),
m_VtkRenderer(NULL), m_MitkVtkRenderWindow(NULL)
{
m_CameraController=NULL;
m_CameraController = VtkInteractorCameraController::New();
m_CameraController->AddRenderer(this);
m_DataChangedCommand = itk::MemberCommand<mitk::OpenGLRenderer>::New();
#ifdef WIN32
m_DataChangedCommand->SetCallbackFunction(this, mitk::OpenGLRenderer::DataChangedEvent);
#else
m_DataChangedCommand->SetCallbackFunction(this, &mitk::OpenGLRenderer::DataChangedEvent);
#endif
}
//##ModelId=3E3D28AB0018
void mitk::OpenGLRenderer::SetData(mitk::DataTreeIterator* iterator)
{
if(iterator!=GetData())
{
bool geometry_is_set=false;
if(m_DataTreeIterator!=NULL)
{
//remove old connections
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
BaseData::Pointer data=it->get()->GetData();
}
delete it;
}
BaseRenderer::SetData(iterator);
if (iterator != NULL)
{
//initialize world geometry: use first slice of first node containing an image
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
BaseData::Pointer data=it->get()->GetData();
if(data.IsNotNull())
{
if(geometry_is_set==false)
{
Image::Pointer image = dynamic_cast<Image*>(data.GetPointer());
if(image.IsNotNull())
{
SetWorldGeometry(image->GetGeometry2D(0, 0));
geometry_is_set=true;
}
}
//@todo add connections
//data->AddObserver(itk::EndEvent(), m_DataChangedCommand);
}
}
delete it;
}
//update the vtk-based mappers
Update(); //this is only called to check, whether we have vtk-based mappers!
UpdateVtkActors();
Modified();
}
}
//##ModelId=3ED91D060305
void mitk::OpenGLRenderer::UpdateVtkActors()
{
VtkInteractorCameraController* vicc=dynamic_cast<VtkInteractorCameraController*>(m_CameraController.GetPointer());
if (m_VtkMapperPresent == false)
{
if(vicc!=NULL)
vicc->GetVtkInteractor()->Disable();
return;
}
if(vicc!=NULL)
vicc->GetVtkInteractor()->Enable();
// m_LightKit->RemoveLightsFromRenderer(this->m_VtkRenderer);
// m_MitkVtkRenderWindow->RemoveRenderer(m_VtkRenderer);
// m_VtkRenderer->Delete();
bool newRenderer = false;
if(m_VtkRenderer==NULL)
{
m_VtkRenderer = vtkRenderer::New();
m_VtkRenderer->SetLayer(0);
m_MitkVtkRenderWindow->AddRenderer( this->m_VtkRenderer );
newRenderer = true;
//strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers)
//m_Light = vtkLight::New();
//m_VtkRenderer->AddLight( m_Light );
m_LightKit = vtkLightKit::New();
m_LightKit->AddLightsToRenderer(m_VtkRenderer);
}
m_VtkRenderer->RemoveAllProps();
//strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers)
//m_Light->Delete();
//m_Light = vtkLight::New();
//m_VtkRenderer->AddLight( m_Light );
if(m_LightKit!=NULL)
{
m_LightKit = vtkLightKit::New();
m_LightKit->AddLightsToRenderer(m_VtkRenderer);
}
// try
if (m_DataTreeIterator != NULL)
{
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
BaseVtkMapper2D* anVtkMapper2D;
anVtkMapper2D=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer());
if(anVtkMapper2D != NULL)
{
anVtkMapper2D->Update(this);
m_VtkRenderer->AddProp(anVtkMapper2D->GetProp());
}
else
{
BaseVtkMapper3D* anVtkMapper3D;
anVtkMapper3D=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer());
if(anVtkMapper3D != NULL)
{
anVtkMapper3D->Update(this);
m_VtkRenderer->AddProp(anVtkMapper3D->GetProp());
}
}
}
}
delete it;
}
if(newRenderer)
m_VtkRenderer->GetActiveCamera()->Elevation(-90);
// catch( ::itk::ExceptionObject ee)
// {
// printf("%s\n",ee.what());
//// itkGenericOutputMacro(ee->what());
// }
// catch( ...)
// {
// printf("test\n");
// }
}
//##ModelId=3E330D260255
void mitk::OpenGLRenderer::Update()
{
if(m_DataTreeIterator == NULL) return;
m_VtkMapperPresent=false;
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
// mitk::LevelWindow lw;
//unsigned int dummy[] = {10,10,10};
//Geometry3D geometry(3,dummy);
mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
Mapper2D* mapper2d=dynamic_cast<Mapper2D*>(mapper.GetPointer());
if(mapper2d != NULL)
{
BaseVtkMapper2D* vtkmapper2d=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer());
if(vtkmapper2d != NULL)
{
vtkmapper2d->Update(this);
m_VtkMapperPresent=true;
}
else
mapper2d->Update();
//ImageMapper2D* imagemapper2d=dynamic_cast<ImageMapper2D*>(mapper.GetPointer());
}
else
{
BaseVtkMapper3D* vtkmapper3d=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer());
if(vtkmapper3d != NULL)
{
vtkmapper3d->Update(this);
m_VtkMapperPresent=true;
}
}
}
}
delete it;
Modified();
m_LastUpdateTime=GetMTime();
}
//##ModelId=3E330D2903CC
void mitk::OpenGLRenderer::Render()
{
//if we do not have any data, we do nothing else but clearing our window
if(GetData() == NULL)
{
glClear(GL_COLOR_BUFFER_BIT);
if(m_VtkMapperPresent) {
// m_MitkVtkRenderWindow->MitkRender();
} else
m_RenderWindow->swapBuffers();
return;
}
//has someone transformed our worldgeometry-node? if so, incorporate this transform into
//the worldgeometry itself and reset the transform of the node to identity
/* if(m_WorldGeometryTransformTime<m_WorldGeometryNode->GetVtkTransform()->GetMTime())
{
vtkTransform *i;
m_WorldGeometry->TransformGeometry(m_WorldGeometryNode->GetVtkTransform());
m_WorldGeometryNode->GetVtkTransform()->Identity();
m_WorldGeometryTransformTime=GetWorldGeometryNode()->GetVtkTransform()->GetMTime();
}
*/
//has the data tree been changed?
if(dynamic_cast<mitk::DataTree*>(GetData()->getTree()) == NULL ) return;
// if(m_LastUpdateTime<((mitk::DataTree*)GetData()->getTree())->GetMTime())
if(m_LastUpdateTime < dynamic_cast<mitk::DataTree*>(GetData()->getTree())->GetMTime() )
{
//yes: update vtk-actors
Update();
UpdateVtkActors();
}
else
//has anything else changed (geometry to display, etc.)?
if (m_LastUpdateTime<GetMTime() ||
m_LastUpdateTime<GetDisplayGeometry()->GetMTime() ||
m_LastUpdateTime<GetDisplayGeometry()->GetWorldGeometry()->GetMTime())
{
//std::cout << "OpenGLRenderer calling its update..." << std::endl;
Update();
}
else
if(m_MapperID==2)
{ //@todo in 3D mode wird sonst nix geupdated, da z.Z. weder camera noch nderung des Baums beachtet wird!!!
Update();
}
glClear(GL_COLOR_BUFFER_BIT);
//PlaneGeometry* myPlaneGeom =
// dynamic_cast<PlaneGeometry *>((mitk::Geometry2D*)(GetWorldGeometry()));
glViewport (0, 0, m_Size[0], m_Size[1]);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0.0, m_Size[0], 0.0, m_Size[1] );
glMatrixMode( GL_MODELVIEW );
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
mitk::DataTree::Pointer tree = dynamic_cast <mitk::DataTree *> (it->getTree());
// std::cout << "Render:: tree: " << *tree << std::endl;
typedef std::pair<int, GLMapper2D*> LayerMapperPair;
std::priority_queue<LayerMapperPair> layers;
int mapperNo = 0;
while(it->hasNext())
{
it->next();
mitk::DataTreeNode::Pointer node = it->get();
mitk::Mapper::Pointer mapper = node->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
GLMapper2D* mapper2d=dynamic_cast<GLMapper2D*>(mapper.GetPointer());
if(mapper2d!=NULL)
{
// mapper without a layer property are painted first
int layer=-1;
node->GetIntProperty("layer", layer, this);
// pushing negative layer value, since default sort for
// priority_queue is lessthan
layers.push(LayerMapperPair(- (layer<<16) - mapperNo ,mapper2d));
mapperNo++;
}
}
}
delete it;
while (!layers.empty()) {
layers.top().second->Paint(this);
layers.pop();
}
if(m_VtkMapperPresent) {
m_MitkVtkRenderWindow->MitkRender();
}
else
m_RenderWindow->swapBuffers();
}
/*!
\brief Initialize the OpenGLRenderer
This method is called from the two Constructors
*/
void mitk::OpenGLRenderer::InitRenderer(mitk::RenderWindow* renderwindow)
{
BaseRenderer::InitRenderer(renderwindow);
m_InitNeeded = true;
m_ResizeNeeded = true;
m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();
m_MitkVtkRenderWindow->SetMitkRenderer(this);
/**@todo SetNumberOfLayers commented out, because otherwise the backface of the planes are not shown (only, when a light is added).
* But we need SetNumberOfLayers(2) later, when we want to prevent vtk to clear the widget before it renders (i.e., when we render something in the scene before vtk).
*/
//m_MitkVtkRenderWindow->SetNumberOfLayers(2);
if(m_CameraController.IsNotNull())
((VtkInteractorCameraController*)m_CameraController.GetPointer())->SetRenderWindow(m_MitkVtkRenderWindow);
//we should disable vtk doublebuffering, but then it doesn't work
//m_MitkVtkRenderWindow->SwapBuffersOff();
}
/*!
\brief Destructs the OpenGLRenderer.
*/
//##ModelId=3E33ECF301B7
mitk::OpenGLRenderer::~OpenGLRenderer() {
m_VtkRenderer->Delete();
m_MitkVtkRenderWindow->Delete();
}
/*!
\brief Initialize the OpenGL Window
*/
//##ModelId=3E33145B0096
void mitk::OpenGLRenderer::Initialize( ) {
glClearColor(0.0, 0.0, 0.0, 1.0);
glColor3f(1.0, 0.0, 0.0);
}
/*!
\brief Resize the OpenGL Window
*/
//##ModelId=3E33145B00D2
void mitk::OpenGLRenderer::Resize(int w, int h)
{
glViewport (0, 0, w, h);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0.0, w, 0.0, h );
glMatrixMode( GL_MODELVIEW );
BaseRenderer::Resize(w, h);
Update();
// m_MitkVtkRenderWindow->SetSize(w,h); //@FIXME?
}
/*!
\brief Render the scene
*/
//##ModelId=3E33145B005A
void mitk::OpenGLRenderer::Paint( )
{
// glFlush();
// m_RenderWindow->swapBuffers();
Render();
}
//##ModelId=3E3314B0005C
void mitk::OpenGLRenderer::SetWindowId(void * id)
{
m_MitkVtkRenderWindow->SetWindowId( id );
}
//##ModelId=3E3799420227
void mitk::OpenGLRenderer::InitSize(int w, int h)
{
m_MitkVtkRenderWindow->SetSize(w,h);
GetDisplayGeometry()->SetSizeInDisplayUnits(w, h);
GetDisplayGeometry()->Fit();
Modified();
Update();
}
//##ModelId=3EF59AD20235
void mitk::OpenGLRenderer::SetMapperID(const MapperSlotId mapperId)
{
Superclass::SetMapperID(mapperId);
Update();
UpdateVtkActors();
}
//##ModelId=3EF162760271
void mitk::OpenGLRenderer::MakeCurrent()
{
if(m_RenderWindow!=NULL)
{
m_RenderWindow->MakeCurrent();
}
}
void mitk::OpenGLRenderer::DataChangedEvent(const itk::Object *caller, const itk::EventObject &event)
{
if(m_RenderWindow!=NULL)
{
m_RenderWindow->Update();
}
}
ivo removed bug: starting without data and clicking in a non vtk window lead into seg.-fault
#include "mitkOpenGLRenderer.h"
#include "Mapper.h"
#include "mitkImageMapper2D.h"
#include "BaseVtkMapper2D.h"
#include "BaseVtkMapper3D.h"
#include "LevelWindow.h"
#include "mitkVtkInteractorCameraController.h"
#include "mitkVtkRenderWindow.h"
#include "mitkRenderWindow.h"
#include <vtkRenderer.h>
#include <vtkLight.h>
#include <vtkLightKit.h>
#include <vtkRenderWindow.h>
#include <vtkTransform.h>
#include <vtkCamera.h>
#include "PlaneGeometry.h"
#include "mitkProperties.h"
#include <queue>
#include <utility>
//##ModelId=3E33ECF301AD
mitk::OpenGLRenderer::OpenGLRenderer() : m_VtkMapperPresent(false),
m_VtkRenderer(NULL), m_MitkVtkRenderWindow(NULL)
{
m_CameraController=NULL;
m_CameraController = VtkInteractorCameraController::New();
m_CameraController->AddRenderer(this);
m_DataChangedCommand = itk::MemberCommand<mitk::OpenGLRenderer>::New();
#ifdef WIN32
m_DataChangedCommand->SetCallbackFunction(this, mitk::OpenGLRenderer::DataChangedEvent);
#else
m_DataChangedCommand->SetCallbackFunction(this, &mitk::OpenGLRenderer::DataChangedEvent);
#endif
}
//##ModelId=3E3D28AB0018
void mitk::OpenGLRenderer::SetData(mitk::DataTreeIterator* iterator)
{
if(iterator!=GetData())
{
bool geometry_is_set=false;
if(m_DataTreeIterator!=NULL)
{
//remove old connections
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
BaseData::Pointer data=it->get()->GetData();
}
delete it;
}
BaseRenderer::SetData(iterator);
if (iterator != NULL)
{
//initialize world geometry: use first slice of first node containing an image
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
BaseData::Pointer data=it->get()->GetData();
if(data.IsNotNull())
{
if(geometry_is_set==false)
{
Image::Pointer image = dynamic_cast<Image*>(data.GetPointer());
if(image.IsNotNull())
{
SetWorldGeometry(image->GetGeometry2D(0, 0));
geometry_is_set=true;
}
}
//@todo add connections
//data->AddObserver(itk::EndEvent(), m_DataChangedCommand);
}
}
delete it;
}
//update the vtk-based mappers
Update(); //this is only called to check, whether we have vtk-based mappers!
UpdateVtkActors();
Modified();
}
}
//##ModelId=3ED91D060305
void mitk::OpenGLRenderer::UpdateVtkActors()
{
VtkInteractorCameraController* vicc=dynamic_cast<VtkInteractorCameraController*>(m_CameraController.GetPointer());
if (m_VtkMapperPresent == false)
{
if(vicc!=NULL)
vicc->GetVtkInteractor()->Disable();
return;
}
if(vicc!=NULL)
vicc->GetVtkInteractor()->Enable();
// m_LightKit->RemoveLightsFromRenderer(this->m_VtkRenderer);
// m_MitkVtkRenderWindow->RemoveRenderer(m_VtkRenderer);
// m_VtkRenderer->Delete();
bool newRenderer = false;
if(m_VtkRenderer==NULL)
{
m_VtkRenderer = vtkRenderer::New();
m_VtkRenderer->SetLayer(0);
m_MitkVtkRenderWindow->AddRenderer( this->m_VtkRenderer );
newRenderer = true;
//strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers)
//m_Light = vtkLight::New();
//m_VtkRenderer->AddLight( m_Light );
m_LightKit = vtkLightKit::New();
m_LightKit->AddLightsToRenderer(m_VtkRenderer);
}
m_VtkRenderer->RemoveAllProps();
//strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers)
//m_Light->Delete();
//m_Light = vtkLight::New();
//m_VtkRenderer->AddLight( m_Light );
if(m_LightKit!=NULL)
{
m_LightKit = vtkLightKit::New();
m_LightKit->AddLightsToRenderer(m_VtkRenderer);
}
// try
if (m_DataTreeIterator != NULL)
{
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
BaseVtkMapper2D* anVtkMapper2D;
anVtkMapper2D=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer());
if(anVtkMapper2D != NULL)
{
anVtkMapper2D->Update(this);
m_VtkRenderer->AddProp(anVtkMapper2D->GetProp());
}
else
{
BaseVtkMapper3D* anVtkMapper3D;
anVtkMapper3D=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer());
if(anVtkMapper3D != NULL)
{
anVtkMapper3D->Update(this);
m_VtkRenderer->AddProp(anVtkMapper3D->GetProp());
}
}
}
}
delete it;
}
if(newRenderer)
m_VtkRenderer->GetActiveCamera()->Elevation(-90);
// catch( ::itk::ExceptionObject ee)
// {
// printf("%s\n",ee.what());
//// itkGenericOutputMacro(ee->what());
// }
// catch( ...)
// {
// printf("test\n");
// }
}
//##ModelId=3E330D260255
void mitk::OpenGLRenderer::Update()
{
if(m_DataTreeIterator == NULL) return;
m_VtkMapperPresent=false;
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
// mitk::LevelWindow lw;
//unsigned int dummy[] = {10,10,10};
//Geometry3D geometry(3,dummy);
mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
Mapper2D* mapper2d=dynamic_cast<Mapper2D*>(mapper.GetPointer());
if(mapper2d != NULL)
{
BaseVtkMapper2D* vtkmapper2d=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer());
if(vtkmapper2d != NULL)
{
vtkmapper2d->Update(this);
m_VtkMapperPresent=true;
}
else
mapper2d->Update();
//ImageMapper2D* imagemapper2d=dynamic_cast<ImageMapper2D*>(mapper.GetPointer());
}
else
{
BaseVtkMapper3D* vtkmapper3d=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer());
if(vtkmapper3d != NULL)
{
vtkmapper3d->Update(this);
m_VtkMapperPresent=true;
}
}
}
}
delete it;
Modified();
m_LastUpdateTime=GetMTime();
}
//##ModelId=3E330D2903CC
void mitk::OpenGLRenderer::Render()
{
//if we do not have any data, we do nothing else but clearing our window
if(GetData() == NULL)
{
glClear(GL_COLOR_BUFFER_BIT);
if(m_VtkMapperPresent) {
// m_MitkVtkRenderWindow->MitkRender();
} else
m_RenderWindow->swapBuffers();
return;
}
//has someone transformed our worldgeometry-node? if so, incorporate this transform into
//the worldgeometry itself and reset the transform of the node to identity
/* if(m_WorldGeometryTransformTime<m_WorldGeometryNode->GetVtkTransform()->GetMTime())
{
vtkTransform *i;
m_WorldGeometry->TransformGeometry(m_WorldGeometryNode->GetVtkTransform());
m_WorldGeometryNode->GetVtkTransform()->Identity();
m_WorldGeometryTransformTime=GetWorldGeometryNode()->GetVtkTransform()->GetMTime();
}
*/
//has the data tree been changed?
if(dynamic_cast<mitk::DataTree*>(GetData()->getTree()) == NULL ) return;
// if(m_LastUpdateTime<((mitk::DataTree*)GetData()->getTree())->GetMTime())
if(m_LastUpdateTime < dynamic_cast<mitk::DataTree*>(GetData()->getTree())->GetMTime() )
{
//yes: update vtk-actors
Update();
UpdateVtkActors();
}
else
//has anything else changed (geometry to display, etc.)?
if (m_LastUpdateTime<GetMTime() ||
m_LastUpdateTime<GetDisplayGeometry()->GetMTime() ||
m_LastUpdateTime<GetDisplayGeometry()->GetWorldGeometry()->GetMTime())
{
//std::cout << "OpenGLRenderer calling its update..." << std::endl;
Update();
}
else
if(m_MapperID==2)
{ //@todo in 3D mode wird sonst nix geupdated, da z.Z. weder camera noch nderung des Baums beachtet wird!!!
Update();
}
glClear(GL_COLOR_BUFFER_BIT);
//PlaneGeometry* myPlaneGeom =
// dynamic_cast<PlaneGeometry *>((mitk::Geometry2D*)(GetWorldGeometry()));
glViewport (0, 0, m_Size[0], m_Size[1]);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0.0, m_Size[0], 0.0, m_Size[1] );
glMatrixMode( GL_MODELVIEW );
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
mitk::DataTree::Pointer tree = dynamic_cast <mitk::DataTree *> (it->getTree());
// std::cout << "Render:: tree: " << *tree << std::endl;
typedef std::pair<int, GLMapper2D*> LayerMapperPair;
std::priority_queue<LayerMapperPair> layers;
int mapperNo = 0;
while(it->hasNext())
{
it->next();
mitk::DataTreeNode::Pointer node = it->get();
mitk::Mapper::Pointer mapper = node->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
GLMapper2D* mapper2d=dynamic_cast<GLMapper2D*>(mapper.GetPointer());
if(mapper2d!=NULL)
{
// mapper without a layer property are painted first
int layer=-1;
node->GetIntProperty("layer", layer, this);
// pushing negative layer value, since default sort for
// priority_queue is lessthan
layers.push(LayerMapperPair(- (layer<<16) - mapperNo ,mapper2d));
mapperNo++;
}
}
}
delete it;
while (!layers.empty()) {
layers.top().second->Paint(this);
layers.pop();
}
if(m_VtkMapperPresent) {
m_MitkVtkRenderWindow->MitkRender();
}
else
m_RenderWindow->swapBuffers();
}
/*!
\brief Initialize the OpenGLRenderer
This method is called from the two Constructors
*/
void mitk::OpenGLRenderer::InitRenderer(mitk::RenderWindow* renderwindow)
{
BaseRenderer::InitRenderer(renderwindow);
m_InitNeeded = true;
m_ResizeNeeded = true;
m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();
m_MitkVtkRenderWindow->SetMitkRenderer(this);
/**@todo SetNumberOfLayers commented out, because otherwise the backface of the planes are not shown (only, when a light is added).
* But we need SetNumberOfLayers(2) later, when we want to prevent vtk to clear the widget before it renders (i.e., when we render something in the scene before vtk).
*/
//m_MitkVtkRenderWindow->SetNumberOfLayers(2);
if(m_CameraController.IsNotNull())
{
VtkInteractorCameraController* vicc=dynamic_cast<VtkInteractorCameraController*>(m_CameraController.GetPointer());
if(vicc!=NULL)
{
vicc->SetRenderWindow(m_MitkVtkRenderWindow);
vicc->GetVtkInteractor()->Disable();
}
}
//we should disable vtk doublebuffering, but then it doesn't work
//m_MitkVtkRenderWindow->SwapBuffersOff();
}
/*!
\brief Destructs the OpenGLRenderer.
*/
//##ModelId=3E33ECF301B7
mitk::OpenGLRenderer::~OpenGLRenderer() {
m_VtkRenderer->Delete();
m_MitkVtkRenderWindow->Delete();
}
/*!
\brief Initialize the OpenGL Window
*/
//##ModelId=3E33145B0096
void mitk::OpenGLRenderer::Initialize( ) {
glClearColor(0.0, 0.0, 0.0, 1.0);
glColor3f(1.0, 0.0, 0.0);
}
/*!
\brief Resize the OpenGL Window
*/
//##ModelId=3E33145B00D2
void mitk::OpenGLRenderer::Resize(int w, int h)
{
glViewport (0, 0, w, h);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0.0, w, 0.0, h );
glMatrixMode( GL_MODELVIEW );
BaseRenderer::Resize(w, h);
Update();
// m_MitkVtkRenderWindow->SetSize(w,h); //@FIXME?
}
/*!
\brief Render the scene
*/
//##ModelId=3E33145B005A
void mitk::OpenGLRenderer::Paint( )
{
// glFlush();
// m_RenderWindow->swapBuffers();
Render();
}
//##ModelId=3E3314B0005C
void mitk::OpenGLRenderer::SetWindowId(void * id)
{
m_MitkVtkRenderWindow->SetWindowId( id );
}
//##ModelId=3E3799420227
void mitk::OpenGLRenderer::InitSize(int w, int h)
{
m_MitkVtkRenderWindow->SetSize(w,h);
GetDisplayGeometry()->SetSizeInDisplayUnits(w, h);
GetDisplayGeometry()->Fit();
Modified();
Update();
}
//##ModelId=3EF59AD20235
void mitk::OpenGLRenderer::SetMapperID(const MapperSlotId mapperId)
{
Superclass::SetMapperID(mapperId);
Update();
UpdateVtkActors();
}
//##ModelId=3EF162760271
void mitk::OpenGLRenderer::MakeCurrent()
{
if(m_RenderWindow!=NULL)
{
m_RenderWindow->MakeCurrent();
}
}
void mitk::OpenGLRenderer::DataChangedEvent(const itk::Object *caller, const itk::EventObject &event)
{
if(m_RenderWindow!=NULL)
{
m_RenderWindow->Update();
}
}
|
/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile: mitkPropertyManager.cpp,v $
Language: C++
Date: $Date$
Version: $Revision: 1.12 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information.
=========================================================================*/
#include "QmitkPointListWidget.h"
#include "mitkGlobalInteraction.h"
#include "mitkPointSetReader.h"
#include "mitkPointSetWriter.h"
#include <QGridLayout>
#include <QPushButton>
#include <QMessageBox>
#include <QFileDialog>
#include "btnSetPoints.xpm"
#include "btnClear.xpm"
#include "btnLoad.xpm"
#include "btnSave.xpm"
QmitkPointListWidget::QmitkPointListWidget( QWidget* parent, Qt::WindowFlags f )
:QWidget( parent, f ),
m_PointSetNode(NULL),
m_NodeObserverTag(0)
{
QGridLayout* layout = new QGridLayout;
layout->setContentsMargins( 0, 0, 0, 0 );
this->setLayout( layout );
this->setContentsMargins( 0, 0, 0, 0 );
m_ListView = new QmitkPointListView( this );
layout->addWidget( m_ListView, 0, 0, 1, 4 ); // span 4 cols
const QIcon iconEdit( btnSetPoints_xpm );
m_BtnEdit = new QPushButton( iconEdit, "", this );
m_BtnEdit->setToolTip("Toggle point editing (use CTRL+left mouse button)");
connect( m_BtnEdit, SIGNAL(toggled(bool)), this, SLOT(OnEditPointSetButtonToggled(bool)) );
m_BtnEdit->setCheckable( true ); // installs/removes pointset interactor
layout->addWidget( m_BtnEdit, 1, 0 );
const QIcon iconClear( btnClear_xpm ); // clears whole point set
m_BtnClear = new QPushButton( iconClear, "", this );
m_BtnClear->setToolTip("Erase all points from list");
connect( m_BtnClear, SIGNAL(clicked()), this, SLOT(OnClearPointSetButtonClicked()) );
layout->addWidget( m_BtnClear, 1, 1 );
const QIcon iconLoad( btnLoad_xpm ); // loads a point set from file
m_BtnLoad = new QPushButton( iconLoad, "", this );
m_BtnLoad->setToolTip("Load list of points from file (REPLACES current content)");
connect( m_BtnLoad, SIGNAL(clicked()), this, SLOT(OnLoadPointSetButtonClicked()) );
layout->addWidget( m_BtnLoad, 1, 2 );
const QIcon iconSave( btnSave_xpm ); // saves point set to file
m_BtnSave = new QPushButton( iconSave, "", this );
m_BtnSave->setToolTip("Save points to file");
connect( m_BtnSave, SIGNAL(clicked()), this, SLOT(OnSavePointSetButtonClicked()) );
layout->addWidget( m_BtnSave, 1, 3 );
ObserveNewNode(NULL);
}
QmitkPointListWidget::~QmitkPointListWidget()
{
}
void QmitkPointListWidget::SetPointSetNode( mitk::DataTreeNode* node )
{
ObserveNewNode(node);
if (node)
{
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( node->GetData() );
m_ListView->SetPointSet( pointSet );
}
else
{
m_ListView->SetPointSet( NULL );
}
}
void QmitkPointListWidget::SetMultiWidget( QmitkStdMultiWidget* multiWidget )
{
m_ListView->SetMultiWidget( multiWidget );
}
void QmitkPointListWidget::DeactivateInteractor(bool deactivate)
{
if (deactivate)
{
if (m_Interactor)
{
mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
m_Interactor = NULL;
m_BtnEdit->setChecked( false );
}
}
}
void QmitkPointListWidget::ObserveNewNode( mitk::DataTreeNode* node )
{
// remove old observer
if ( m_PointSetNode != NULL )
{
if (m_Interactor)
{
mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
m_Interactor = NULL;
m_BtnEdit->setChecked( false );
}
m_PointSetNode->RemoveObserver( m_NodeObserverTag );
}
m_PointSetNode = node;
// add new observer if neccessary
if ( m_PointSetNode != NULL )
{
itk::ReceptorMemberCommand<QmitkPointListWidget>::Pointer command = itk::ReceptorMemberCommand<QmitkPointListWidget>::New();
command->SetCallbackFunction( this, &QmitkPointListWidget::OnNodeDeleted );
m_NodeObserverTag = m_PointSetNode->AddObserver( itk::DeleteEvent(), command );
}
else
{
m_NodeObserverTag = 0;
}
m_BtnEdit->setEnabled( m_PointSetNode != NULL );
m_BtnClear->setEnabled( m_PointSetNode != NULL );
m_BtnLoad->setEnabled( m_PointSetNode != NULL );
m_BtnSave->setEnabled( m_PointSetNode != NULL );
}
void QmitkPointListWidget::OnNodeDeleted( const itk::EventObject & e )
{
m_PointSetNode = NULL;
m_NodeObserverTag = 0;
m_ListView->SetPointSet( NULL );
}
void QmitkPointListWidget::OnEditPointSetButtonToggled(bool checked)
{
if (m_PointSetNode)
{
if (checked)
{
m_Interactor = mitk::PointSetInteractor::New("pointsetinteractor", m_PointSetNode);
mitk::GlobalInteraction::GetInstance()->AddInteractor( m_Interactor );
}
else if ( m_Interactor )
{
mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
m_Interactor = NULL;
}
emit EditPointSets(checked);
}
}
void QmitkPointListWidget::OnClearPointSetButtonClicked()
{
if (!m_PointSetNode) return;
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
if (!pointSet) return;
if (pointSet->GetSize() == 0) return; // we don't have to disturb by asking silly questions
switch( QMessageBox::question( this, tr("Clear Points"),
tr("Remove all points from the displayed list?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No))
{
case QMessageBox::Yes:
if (pointSet)
{
mitk::PointSet::DataType::PointsContainer::Pointer pointsContainer = pointSet->GetPointSet()->GetPoints();
pointsContainer->Initialize(); // a call to initialize results in clearing the points container
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
break;
case QMessageBox::No:
default:
break;
}
emit PointListChanged();
}
void QmitkPointListWidget::OnLoadPointSetButtonClicked()
{
if (!m_PointSetNode) return;
// get the name of the file to load
QString filename = QFileDialog::getOpenFileName( NULL, QString::null, "MITK Point Sets (*.mps)", NULL );
if ( filename.isEmpty() ) return;
// attempt to load file
try
{
mitk::PointSetReader::Pointer reader = mitk::PointSetReader::New();
reader->SetFileName( filename.latin1() );
reader->Update();
mitk::PointSet::Pointer pointSet = reader->GetOutput();
if ( pointSet.IsNull() )
{
QMessageBox::warning( this, "Load point set", QString("File reader could not read %1").arg(filename) );
return;
}
// loading successful
bool interactionOn( m_Interactor.IsNotNull() );
if (interactionOn)
{
OnEditPointSetButtonToggled(false);
}
m_PointSetNode->SetData( pointSet );
m_ListView->SetPointSet( pointSet );
if (interactionOn)
{
OnEditPointSetButtonToggled(true);
}
}
catch(...)
{
QMessageBox::warning( this, "Load point set", QString("File reader collapsed while reading %1").arg(filename) );
}
emit PointListChanged();
}
void QmitkPointListWidget::OnSavePointSetButtonClicked()
{
if (!m_PointSetNode) return;
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
if (!pointSet) return; // don't write empty point sets. If application logic requires something else then do something else.
if (pointSet->GetSize() == 0) return;
// let the user choose a file
std::string name("");
QString fileNameProposal = "PointSet.mps";
QString aFilename = QFileDialog::getSaveFileName( fileNameProposal.latin1() );
if ( aFilename.isEmpty() ) return;
try
{
// instantiate the writer and add the point-sets to write
mitk::PointSetWriter::Pointer writer = mitk::PointSetWriter::New();
writer->SetInput( pointSet );
writer->SetFileName( aFilename.latin1() );
writer->Update();
}
catch(...)
{
QMessageBox::warning( this, "Save point set",
QString("File writer reported problems writing %1\n\n"
"PLEASE CHECK output file!").arg(aFilename) );
}
}
COMP: restructuring
/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile: mitkPropertyManager.cpp,v $
Language: C++
Date: $Date$
Version: $Revision: 1.12 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information.
=========================================================================*/
#include "QmitkPointListWidget.h"
#include "mitkGlobalInteraction.h"
#include "mitkPointSetReader.h"
#include "mitkPointSetWriter.h"
#include <QGridLayout>
#include <QPushButton>
#include <QMessageBox>
#include <QFileDialog>
#include "btnSetPoints.xpm"
#include "btnClear.xpm"
#include "btnLoad.xpm"
#include "btnSave.xpm"
QmitkPointListWidget::QmitkPointListWidget( QWidget* parent, Qt::WindowFlags f )
:QWidget( parent, f ),
m_PointSetNode(NULL),
m_NodeObserverTag(0)
{
QGridLayout* layout = new QGridLayout;
layout->setContentsMargins( 0, 0, 0, 0 );
this->setLayout( layout );
this->setContentsMargins( 0, 0, 0, 0 );
m_ListView = new QmitkPointListView( this );
layout->addWidget( m_ListView, 0, 0, 1, 4 ); // span 4 cols
const QIcon iconEdit( btnSetPoints_xpm );
m_BtnEdit = new QPushButton( iconEdit, "", this );
m_BtnEdit->setToolTip("Toggle point editing (use CTRL+left mouse button)");
connect( m_BtnEdit, SIGNAL(toggled(bool)), this, SLOT(OnEditPointSetButtonToggled(bool)) );
m_BtnEdit->setCheckable( true ); // installs/removes pointset interactor
layout->addWidget( m_BtnEdit, 1, 0 );
const QIcon iconClear( btnClear_xpm ); // clears whole point set
m_BtnClear = new QPushButton( iconClear, "", this );
m_BtnClear->setToolTip("Erase all points from list");
connect( m_BtnClear, SIGNAL(clicked()), this, SLOT(OnClearPointSetButtonClicked()) );
layout->addWidget( m_BtnClear, 1, 1 );
const QIcon iconLoad( btnLoad_xpm ); // loads a point set from file
m_BtnLoad = new QPushButton( iconLoad, "", this );
m_BtnLoad->setToolTip("Load list of points from file (REPLACES current content)");
connect( m_BtnLoad, SIGNAL(clicked()), this, SLOT(OnLoadPointSetButtonClicked()) );
layout->addWidget( m_BtnLoad, 1, 2 );
const QIcon iconSave( btnSave_xpm ); // saves point set to file
m_BtnSave = new QPushButton( iconSave, "", this );
m_BtnSave->setToolTip("Save points to file");
connect( m_BtnSave, SIGNAL(clicked()), this, SLOT(OnSavePointSetButtonClicked()) );
layout->addWidget( m_BtnSave, 1, 3 );
ObserveNewNode(NULL);
}
QmitkPointListWidget::~QmitkPointListWidget()
{
}
void QmitkPointListWidget::SetPointSetNode( mitk::DataTreeNode* node )
{
ObserveNewNode(node);
if (node)
{
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( node->GetData() );
m_ListView->SetPointSet( pointSet );
}
else
{
m_ListView->SetPointSet( NULL );
}
}
void QmitkPointListWidget::SetMultiWidget( QmitkStdMultiWidget* multiWidget )
{
m_ListView->SetMultiWidget( multiWidget );
}
void QmitkPointListWidget::DeactivateInteractor(bool deactivate)
{
if (deactivate)
{
if (m_Interactor)
{
mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
m_Interactor = NULL;
m_BtnEdit->setChecked( false );
}
}
}
void QmitkPointListWidget::ObserveNewNode( mitk::DataTreeNode* node )
{
// remove old observer
if ( m_PointSetNode != NULL )
{
if (m_Interactor)
{
mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
m_Interactor = NULL;
m_BtnEdit->setChecked( false );
}
m_PointSetNode->RemoveObserver( m_NodeObserverTag );
}
m_PointSetNode = node;
// add new observer if neccessary
if ( m_PointSetNode != NULL )
{
itk::ReceptorMemberCommand<QmitkPointListWidget>::Pointer command = itk::ReceptorMemberCommand<QmitkPointListWidget>::New();
command->SetCallbackFunction( this, &QmitkPointListWidget::OnNodeDeleted );
m_NodeObserverTag = m_PointSetNode->AddObserver( itk::DeleteEvent(), command );
}
else
{
m_NodeObserverTag = 0;
}
m_BtnEdit->setEnabled( m_PointSetNode != NULL );
m_BtnClear->setEnabled( m_PointSetNode != NULL );
m_BtnLoad->setEnabled( m_PointSetNode != NULL );
m_BtnSave->setEnabled( m_PointSetNode != NULL );
}
void QmitkPointListWidget::OnNodeDeleted( const itk::EventObject & e )
{
m_PointSetNode = NULL;
m_NodeObserverTag = 0;
m_ListView->SetPointSet( NULL );
}
void QmitkPointListWidget::OnEditPointSetButtonToggled(bool checked)
{
if (m_PointSetNode)
{
if (checked)
{
m_Interactor = mitk::PointSetInteractor::New("pointsetinteractor", m_PointSetNode);
mitk::GlobalInteraction::GetInstance()->AddInteractor( m_Interactor );
}
else if ( m_Interactor )
{
mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
m_Interactor = NULL;
}
emit EditPointSets(checked);
}
}
void QmitkPointListWidget::OnClearPointSetButtonClicked()
{
if (!m_PointSetNode) return;
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
if (!pointSet) return;
if (pointSet->GetSize() == 0) return; // we don't have to disturb by asking silly questions
switch( QMessageBox::question( this, tr("Clear Points"),
tr("Remove all points from the displayed list?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No))
{
case QMessageBox::Yes:
if (pointSet)
{
mitk::PointSet::DataType::PointsContainer::Pointer pointsContainer = pointSet->GetPointSet()->GetPoints();
pointsContainer->Initialize(); // a call to initialize results in clearing the points container
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
break;
case QMessageBox::No:
default:
break;
}
emit PointListChanged();
}
void QmitkPointListWidget::OnLoadPointSetButtonClicked()
{
if (!m_PointSetNode) return;
// get the name of the file to load
QString filename = QFileDialog::getOpenFileName( NULL, QString::null, "MITK Point Sets (*.mps)", NULL );
if ( filename.isEmpty() ) return;
// attempt to load file
try
{
mitk::PointSetReader::Pointer reader = mitk::PointSetReader::New();
reader->SetFileName( filename.toLatin1() );
reader->Update();
mitk::PointSet::Pointer pointSet = reader->GetOutput();
if ( pointSet.IsNull() )
{
QMessageBox::warning( this, "Load point set", QString("File reader could not read %1").arg(filename) );
return;
}
// loading successful
bool interactionOn( m_Interactor.IsNotNull() );
if (interactionOn)
{
OnEditPointSetButtonToggled(false);
}
m_PointSetNode->SetData( pointSet );
m_ListView->SetPointSet( pointSet );
if (interactionOn)
{
OnEditPointSetButtonToggled(true);
}
}
catch(...)
{
QMessageBox::warning( this, "Load point set", QString("File reader collapsed while reading %1").arg(filename) );
}
emit PointListChanged();
}
void QmitkPointListWidget::OnSavePointSetButtonClicked()
{
if (!m_PointSetNode) return;
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
if (!pointSet) return; // don't write empty point sets. If application logic requires something else then do something else.
if (pointSet->GetSize() == 0) return;
// let the user choose a file
std::string name("");
QString fileNameProposal = "PointSet.mps";
QString aFilename = QFileDialog::getSaveFileName( fileNameProposal.toLatin1() );
if ( aFilename.isEmpty() ) return;
try
{
// instantiate the writer and add the point-sets to write
mitk::PointSetWriter::Pointer writer = mitk::PointSetWriter::New();
writer->SetInput( pointSet );
writer->SetFileName( aFilename.toLatin1() );
writer->Update();
}
catch(...)
{
QMessageBox::warning( this, "Save point set",
QString("File writer reported problems writing %1\n\n"
"PLEASE CHECK output file!").arg(aFilename) );
}
}
|
// @(#)root/tree:$Name: $:$Id: TChain.cxx,v 1.33 2001/12/14 13:29:44 brun Exp $
// Author: Rene Brun 03/02/97
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TChain //
// //
// A chain is a collection of files containg TTree objects. //
// When the chain is created, the first parameter is the default name //
// for the Tree to be processed later on. //
// //
// Enter a new element in the chain via the TChain::Add function. //
// Once a chain is defined, one can use the normal TTree functions //
// to Draw,Scan,etc. //
// //
// Use TChain::SetBranchStatus to activate one or more branches for all //
// the trees in the chain. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TROOT.h"
#include "TChain.h"
#include "TTree.h"
#include "TFile.h"
#include "TSelector.h"
#include "TBranch.h"
#include "TLeaf.h"
#include "TBrowser.h"
#include "TChainElement.h"
#include "TFriendElement.h"
#include "TSystem.h"
#include "TRegexp.h"
Int_t TChain::fgMaxMergeSize = 1900000000;
ClassImp(TChain)
//______________________________________________________________________________
TChain::TChain(): TTree()
{
//*-*-*-*-*-*Default constructor for Chain*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* ==============================
fTreeOffsetLen = 100;
fNtrees = 0;
fTreeNumber = -1;
fTreeOffset = 0;
fTree = 0;
fFile = 0;
fFiles = new TObjArray(fTreeOffsetLen );
fStatus = new TList();
fNotify = 0;
}
//______________________________________________________________________________
TChain::TChain(const char *name, const char *title)
:TTree(name,title)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*Create a Chain*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* ==============
//
// A TChain is a collection of TFile objects.
// the first parameter "name" is the name of the TTree object
// in the files added with Add.
// Use TChain::Add to add a new element to this chain.
//
// In case the Tree is in a subdirectory, do, eg:
// TChain ch("subdir/treename");
//
// Example:
// Suppose we have 3 files f1.root, f2.root and f3.root. Each file
// contains a TTree object named "T".
// TChain ch("T"); creates a chain to process a Tree called "T"
// ch.Add("f1.root");
// ch.Add("f2.root");
// ch.Add("f3.root");
// ch.Draw("x");
// The Draw function above will process the variable "x" in Tree "T"
// reading sequentially the 3 files in the chain ch.
//
//*-*
fTreeOffsetLen = 100;
fNtrees = 0;
fTreeNumber = -1;
fTreeOffset = new Int_t[fTreeOffsetLen];
fTree = 0;
fFile = 0;
fFiles = new TObjArray(fTreeOffsetLen );
fStatus = new TList();
fTreeOffset[0] = 0;
TChainElement *element = new TChainElement("*","");
fStatus->Add(element);
gDirectory->GetList()->Remove(this);
gROOT->GetListOfSpecials()->Add(this);
fDirectory = 0;
fNotify = 0;
}
//______________________________________________________________________________
TChain::~TChain()
{
//*-*-*-*-*-*Default destructor for a Chain*-*-*-*-*-*-*-*-*-*-*-*
//*-* ==============================
fDirectory = 0;
fFile = 0;
gROOT->GetListOfSpecials()->Remove(this);
delete [] fTreeOffset;
fFiles->Delete();
delete fFiles;
fStatus->Delete();
delete fStatus;
}
//______________________________________________________________________________
Int_t TChain::Add(TChain *chain)
{
// Add all files referenced by the TChain chain to this chain.
//Check enough space in fTreeOffset
if (fNtrees+chain->GetNtrees() >= fTreeOffsetLen) {
fTreeOffsetLen += 2*chain->GetNtrees();
Int_t *trees = new Int_t[fTreeOffsetLen];
for (Int_t i=0;i<=fNtrees;i++) trees[i] = fTreeOffset[i];
delete [] fTreeOffset;
fTreeOffset = trees;
}
TIter next(chain->GetListOfFiles());
TChainElement *element, *newelement;
Int_t nf = 0;
while ((element = (TChainElement*)next())) {
Int_t nentries = element->GetEntries();
fTreeOffset[fNtrees+1] = fTreeOffset[fNtrees] + nentries;
fNtrees++;
fEntries += nentries;
newelement = new TChainElement(element->GetName(),element->GetTitle());
newelement->SetPacketSize(element->GetPacketSize());
newelement->SetNumberEntries(nentries);
fFiles->Add(newelement);
nf++;
}
return nf;
}
//______________________________________________________________________________
Int_t TChain::Add(const char *name, Int_t nentries)
{
// Add a new file to this chain.
// Argument name may have the following format:
// //machine/file_name.root/subdir/tree_name
// machine, subdir and tree_name are optional. If tree_name is missing,
// the chain name will be assumed.
// Name may use the wildcarding notation, eg "xxx*.root" means all files
// starting with xxx in the current file system directory.
//
// If nentries <= 0, the file is connected and the tree header read in memory
// to get the number of entries.
// If (nentries > 0, the file is not connected, nentries is assumed to be
// the number of entries in the file. In this case, no check is made that
// the file exists and the Tree existing in the file. This second mode
// is interesting in case the number of entries in the file is already stored
// in a run data base for example.
// NB. To add all the files of a TChain to a chain, use Add(TChain *chain).
// case with one single file
if (strchr(name,'*') == 0) {
return AddFile(name,nentries);
}
// wildcarding used in name
Int_t nf = 0;
char aname[2048]; //files may have very long names, eg AFS
strcpy(aname,name);
char *dot = (char*)strstr(aname,".root");
const char *behind_dot_root = 0;
if (dot) {
if (dot[5] == '/') behind_dot_root = dot + 6;
*dot = 0;
}
char *slash = strrchr(aname,'/');
if (slash) {
*slash = 0;
slash++;
strcat(slash,".root");
} else {
strcpy(aname,gSystem->WorkingDirectory());
slash = (char*)name;
}
const char *file;
void *dir = gSystem->OpenDirectory(gSystem->ExpandPathName(aname));
if (dir) {
TRegexp re(slash,kTRUE);
while ((file = gSystem->GetDirEntry(dir))) {
if (!strcmp(file,".") || !strcmp(file,"..")) continue;
//if (IsDirectory(file)) continue;
TString s = file;
if (strcmp(slash,file) && s.Index(re) == kNPOS) continue;
if (behind_dot_root != 0 && *behind_dot_root != 0)
nf += AddFile(Form("%s/%s/%s",aname,file,behind_dot_root),-1);
else
nf += AddFile(Form("%s/%s",aname,file),-1);
}
gSystem->FreeDirectory(dir);
}
return nf;
}
//______________________________________________________________________________
Int_t TChain::AddFile(const char *name, Int_t nentries)
{
// Add a new file to this chain.
//
// if nentries <= 0, the file is connected and the tree header read in memory
// to get the number of entries.
// if (nentries > 0, the file is not connected, nentries is assumed to be
// the number of entries in the file. In this case, no check is made that
// the file exists and the Tree existing in the file. This second mode
// is interesting in case the number of entries in the file is already stored
// in a run data base for example.
TDirectory *cursav = gDirectory;
char *treename = (char*)GetName();
char *dot = (char*)strstr(name,".root");
//the ".root" is mandatory only if one wants to specify a treename
//if (!dot) {
// Error("AddFile","a chain element name must contain the string .root");
// return 0;
//}
//Check enough space in fTreeOffset
if (fNtrees+1 >= fTreeOffsetLen) {
fTreeOffsetLen *= 2;
Int_t *trees = new Int_t[fTreeOffsetLen];
for (Int_t i=0;i<=fNtrees;i++) trees[i] = fTreeOffset[i];
delete [] fTreeOffset;
fTreeOffset = trees;
}
//Search for a a slash between the .root and the end
Int_t nch = strlen(name) + strlen(treename);
char *filename = new char[nch+1];
strcpy(filename,name);
if (dot) {
char *pos = (char*)strstr(filename,".root") + 5;
while (*pos) {
if (*pos == '/') {
treename = pos+1;
*pos = 0;
break;
}
pos++;
}
}
//Connect the file to get the number of entries
Int_t pksize = 0;
if (nentries <= 0) {
TFile *file = TFile::Open(filename);
if (file->IsZombie()) {
delete file;
delete [] filename;
return 0;
}
//Check that tree with the right name exists in the file
TObject *obj = file->Get(treename);
if (!obj || !obj->InheritsFrom("TTree") ) {
Error("AddFile","cannot find tree with name %s in file %s", treename,filename);
delete file;
delete [] filename;
return 0;
}
TTree *tree = (TTree*)obj;
nentries = (Int_t)tree->GetEntries();
pksize = tree->GetPacketSize();
delete tree;
delete file;
}
if (nentries > 0) {
fTreeOffset[fNtrees+1] = fTreeOffset[fNtrees] + nentries;
fNtrees++;
fEntries += nentries;
TChainElement *element = new TChainElement(treename,filename);
element->SetPacketSize(pksize);
element->SetNumberEntries(nentries);
fFiles->Add(element);
} else {
Warning("Add","Adding Tree with no entries from file: %s",filename);
}
delete [] filename;
if (cursav) cursav->cd();
return 1;
}
//______________________________________________________________________________
TFriendElement *TChain::AddFriend(const char *chain, const char *dummy)
{
// Add a TFriendElement to the list of friends of this chain.
//
// A TChain has a list of friends similar to a tree (see TTree::AddFriend).
// You can add a friend to a chain with the TChain::AddFriend method, and you
// can retrieve the list of friends with TChain::GetListOfFriends.
// This example has four chains each has 20 ROOT trees from 20 ROOT files.
//
// TChain ch("t"); // a chain with 20 trees from 20 files
// TChain ch1("t1");
// TChain ch2("t2");
// TChain ch3("t3");
// Now we can add the friends to the first chain.
//
// ch.AddFriend("t1")
// ch.AddFriend("t2")
// ch.AddFriend("t3")
//
//Begin_Html
/*
<img src="gif/chain_friend.gif">
*/
//End_Html
//
// The parameter is the name of friend chain (the name of a chain is always
// the name of the tree from which it was created).
// The original chain has access to all variable in its friends.
// We can use the TChain::Draw method as if the values in the friends were
// in the original chain.
// To specify the chain to use in the Draw method, use the syntax:
//
// <chainname>.<branchname>.<varname>
// If the variable name is enough to uniquely identify the variable, you can
// leave out the chain and/or branch name.
// For example, this generates a 3-d scatter plot of variable "var" in the
// TChain ch versus variable v1 in TChain t1 versus variable v2 in TChain t2.
//
// ch.Draw("var:t1.v1:t2.v2");
// When a TChain::Draw is executed, an automatic call to TTree::AddFriend
// connects the trees in the chain. When a chain is deleted, its friend
// elements are also deleted.
//
// The number of entries in the friend must be equal or greater to the number
// of entries of the original chain. If the friend has fewer entries a warning
// is given and the resulting histogram will have missing entries.
// For additional information see TTree::AddFriend.
if (!fFriends) fFriends = new TList();
TFriendElement *fe = new TFriendElement(this,chain,dummy);
if (fe) {
fFriends->Add(fe);
TTree *t = fe->GetTree();
if (t) {
if (t->GetEntries() < fEntries) {
//Warning("AddFriend","FriendElement %s in file %s has less entries %g than its parent Tree: %g",
// chain,filename,t->GetEntries(),fEntries);
}
} else {
Warning("AddFriend","Unknown TChain %s",chain);
}
} else {
Warning("AddFriend","Cannot add FriendElement %s",chain);
}
return fe;
}
//______________________________________________________________________________
TFriendElement *TChain::AddFriend(const char *chain, TFile *dummy)
{
if (!fFriends) fFriends = new TList();
TFriendElement *fe = new TFriendElement(this,chain,dummy);
if (fe) {
fFriends->Add(fe);
TTree *t = fe->GetTree();
if (t) {
if (t->GetEntries() < fEntries) {
//Warning("AddFriend","FriendElement %s in file %s has less entries %g than its parent Tree: %g",
// chain,filename,t->GetEntries(),fEntries);
}
} else {
Warning("AddFriend","Unknown TChain %s",chain);
}
} else {
Warning("AddFriend","Cannot add FriendElement %s",chain);
}
return fe;
}
//______________________________________________________________________________
void TChain::Browse(TBrowser *)
{
}
//_______________________________________________________________________
void TChain::CreatePackets()
{
//*-*-*-*-*-*-*-*-*Initialize the packet descriptor string*-*-*-*-*-*-*-*-*-*
//*-* =======================================
TIter next(fFiles);
TChainElement *element;
while ((element = (TChainElement*)next())) {
element->CreatePackets();
}
}
//______________________________________________________________________________
Int_t TChain::Draw(const char *varexp, TCut selection, Option_t *option, Int_t nentries, Int_t firstentry)
{
// Draw expression varexp for selected entries.
//
// This function accepts TCut objects as arguments.
// Useful to use the string operator +, example:
// ntuple.Draw("x",cut1+cut2+cut3);
//
return TChain::Draw(varexp, selection.GetTitle(), option, nentries, firstentry);
}
//______________________________________________________________________________
Int_t TChain::Draw(const char *varexp, const char *selection, Option_t *option,Int_t nentries, Int_t firstentry)
{
// Process all entries in this chain and draw histogram
// corresponding to expression varexp.
if (LoadTree(firstentry) < 0) return 0;
return TTree::Draw(varexp,selection,option,nentries,firstentry);
}
//______________________________________________________________________________
TBranch *TChain::GetBranch(const char *name)
{
//*-*-*-*-*-*-*-*-*Return pointer to the branch name*-*-*-*-*
//*-* ==========================================
if (fTree) return fTree->GetBranch(name);
LoadTree(0);
if (fTree) return fTree->GetBranch(name);
return 0;
}
//______________________________________________________________________________
Int_t TChain::GetChainEntryNumber(Int_t entry) const
{
// return absolute entry number in the chain
// the input parameter entry is the entry number in the current Tree of this chain
return entry + fTreeOffset[fTreeNumber];
}
//______________________________________________________________________________
Int_t TChain::GetEntry(Int_t entry, Int_t getall)
{
//*-*-*-*-*-*-*-*-*Return entry in memory*-*-*-*-*-*-*-*-*-*
//*-* ======================
// getall = 0 : get only active branches
// getall = 1 : get all branches
if (LoadTree(entry) < 0) return 0;
return fTree->GetEntry(fReadEntry,getall);
}
//______________________________________________________________________________
TLeaf *TChain::GetLeaf(const char *name)
{
//*-*-*-*-*-*-*-*-*Return pointer to the leaf name*-*-*-*-*
//*-* ==========================================
if (fTree) return fTree->GetLeaf(name);
LoadTree(0);
if (fTree) return fTree->GetLeaf(name);
return 0;
}
//______________________________________________________________________________
TObjArray *TChain::GetListOfBranches()
{
//*-*-*-*-*-*-*-*-*Return pointer to list of branches of current tree*-*-*-*-*
//*-* ================================================
if (fTree) return fTree->GetListOfBranches();
LoadTree(0);
if (fTree) return fTree->GetListOfBranches();
return 0;
}
//______________________________________________________________________________
TObjArray *TChain::GetListOfLeaves()
{
//*-*-*-*-*-*-*-*-*Return pointer to list of leaves of current tree*-*-*-*-*
//*-* ================================================
if (fTree) return fTree->GetListOfLeaves();
LoadTree(0);
if (fTree) return fTree->GetListOfLeaves();
return 0;
}
//______________________________________________________________________________
Int_t TChain::GetMaxMergeSize()
{
// static function
// return maximum size of a merged file
return fgMaxMergeSize;
}
//______________________________________________________________________________
Double_t TChain::GetMaximum(const char *columname)
{
//*-*-*-*-*-*-*-*-*Return maximum of column with name columname*-*-*-*-*-*-*
//*-* ============================================
Double_t theMax = -FLT_MAX; //in float.h
for (Int_t file=0;file<fNtrees;file++) {
Int_t first = fTreeOffset[file];
LoadTree(first);
Double_t curmax = fTree->GetMaximum(columname);;
if (curmax > theMax) theMax = curmax;
}
return theMax;
}
//______________________________________________________________________________
Double_t TChain::GetMinimum(const char *columname)
{
//*-*-*-*-*-*-*-*-*Return minimum of column with name columname*-*-*-*-*-*-*
//*-* ============================================
Double_t theMin = FLT_MAX; //in float.h
for (Int_t file=0;file<fNtrees;file++) {
Int_t first = fTreeOffset[file];
LoadTree(first);
Double_t curmin = fTree->GetMinimum(columname);;
if (curmin < theMin) theMin = curmin;
}
return theMin;
}
//______________________________________________________________________________
Int_t TChain::GetNbranches()
{
//*-*-*-*-*-*-*-*-*Return number of branches of current tree*-*-*-*-*
//*-* =========================================
if (fTree) return fTree->GetNbranches();
LoadTree(0);
if (fTree) return fTree->GetNbranches();
return 0;
}
//______________________________________________________________________________
Int_t TChain::LoadTree(Int_t entry)
{
// The input argument entry is the entry serial number in the whole chain.
// The function finds the corresponding Tree and returns the entry number
// in this tree.
if (!fNtrees) return 1;
if (entry < 0 || entry >= fEntries) return -2;
//Find in which tree this entry belongs to
Int_t t;
if (entry >= fTreeOffset[fTreeNumber] && entry < fTreeOffset[fTreeNumber+1]){
t = fTreeNumber;
}
else {
for (t=0;t<fNtrees;t++) {
if (entry < fTreeOffset[t+1]) break;
}
}
fReadEntry = entry - fTreeOffset[t];
// If entry belongs to the current tree return entry
if (t == fTreeNumber) {
return fReadEntry;
}
//Delete current tree and connect new tree
TDirectory *cursav = gDirectory;
delete fFile; fFile = 0;
TChainElement *element = (TChainElement*)fFiles->At(t);
if (!element) return -4;
fFile = TFile::Open(element->GetTitle());
if (fFile->IsZombie()) {
delete fFile; fFile = 0;
return -3;
}
fTree = (TTree*)fFile->Get(element->GetName());
fTreeNumber = t;
fDirectory = fFile;
//Set the branches status and address for the newly connected file
fTree->SetMakeClass(fMakeClass);
fTree->SetMaxVirtualSize(fMaxVirtualSize);
SetChainOffset(fTreeOffset[t]);
TIter next(fStatus);
Int_t status;
while ((element = (TChainElement*)next())) {
status = element->GetStatus();
if (status >=0) fTree->SetBranchStatus(element->GetName(),status);
void *add = element->GetBaddress();
if (add) fTree->SetBranchAddress(element->GetName(),add);
}
if (cursav) cursav->cd();
//update list of leaves in all TTreeFormula of the TTreePlayer (if any)
if (fPlayer) fPlayer->UpdateFormulaLeaves();
//Notify user if requested
if (fNotify) fNotify->Notify();
return fReadEntry;
}
//______________________________________________________________________________
void TChain::Loop(Option_t *option, Int_t nentries, Int_t firstentry)
{
//*-*-*-*-*-*-*-*-*Loop on nentries of this chain starting at firstentry
//*-* ===================================================
Error("Loop","Function not yet implemented");
if (option || nentries || firstentry) { } // keep warnings away
#ifdef NEVER
if (LoadTree(firstentry) < 0) return;
if (firstentry < 0) firstentry = 0;
Int_t lastentry = firstentry + nentries -1;
if (lastentry > fEntries-1) {
lastentry = (Int_t)fEntries -1;
}
GetPlayer();
GetSelector();
fSelector->Start(option);
Int_t entry = firstentry;
Int_t tree,e0,en;
for (tree=0;tree<fNtrees;tree++) {
e0 = fTreeOffset[tree];
en = fTreeOffset[tree+1] - 1;
if (en > lastentry) en = lastentry;
if (entry > en) continue;
LoadTree(entry);
fSelector->BeginFile();
while (entry <= en) {
fSelector->Execute(fTree, entry - e0);
entry++;
}
fSelector->EndFile();
}
fSelector->Finish(option);
#endif
}
//______________________________________________________________________________
void TChain::ls(Option_t *option) const
{
TIter next(fFiles);
TChainElement *file;
while ((file = (TChainElement*)next())) {
file->ls();
}
}
//______________________________________________________________________________
Int_t TChain::Merge(const char *name)
{
// Merge all files in this chain into a new file
// see important note in the following function Merge
TFile *file = TFile::Open(name,"recreate","chain files",1);
Int_t nFiles = Merge(file,0,"");
if (nFiles <= 1) {
file->Close();
delete file;
}
return nFiles;
}
//______________________________________________________________________________
Int_t TChain::Merge(TFile *file, Int_t basketsize, Option_t *option)
{
// Merge all files in this chain into a new file
// if option ="C" is given, the compression level for all branches
// in the new Tree is set to the file compression level.
// By default, the compression level of all branches is the
// original compression level in the old Trees.
//
// if (basketsize > 1000, the basket size for all branches of the
// new Tree will be set to basketsize.
//
// IMPORTANT: Before invoking this function, the branch addresses
// of the TTree must have been set.
// example using the file generated in $ROOTSYS/test/Event
// merge two copies of Event.root
//
// gSystem.Load("libEvent");
// Event *event = new Event();
// TChain ch("T");
// ch.SetBranchAddress("event",&event);
// ch.Add("Event1.root");
// ch.Add("Event2.root");
// ch.Merge("all.root");
//
// The SetBranchAddress statement is not necessary if the Tree
// contains only basic types (case of files converted from hbook)
//
// NOTE that the merged Tree contains only the active branches.
//
// AUTOMATIC FILE OVERFLOW
// -----------------------
// When merging many files, it may happen that the resulting file
// reaches a size > fgMaxMergeSize (default = 1.9 GBytes). In this case
// the current file is automatically closed and a new file started.
// If the name of the merged file was "merged.root", the subsequent files
// will be named "merged_1.root", "merged_2.root", etc.
// fgMaxMergeSize may be modified via the static function SetMaxMergeSize.
//
// The function returns the total number of files produced.
if (!file) return 0;
TObjArray *lbranches = GetListOfBranches();
if (!lbranches) return 0;
if (!fTree) return 0;
// Clone Chain tree
//file->cd(); //in case a user wants to write in a file/subdir
TTree *hnew = (TTree*)fTree->CloneTree(0);
hnew->SetAutoSave(2000000000);
// May be reset branches compression level?
TBranch *branch;
TIter nextb(hnew->GetListOfBranches());
if (strstr(option,"c") || strstr(option,"C")) {
while ((branch = (TBranch*)nextb())) {
branch->SetCompressionLevel(file->GetCompressionLevel());
}
nextb.Reset();
}
// May be reset branches basket size?
if (basketsize > 1000) {
while ((branch = (TBranch*)nextb())) {
branch->SetBasketSize(basketsize);
}
nextb.Reset();
}
char *firstname = new char[1000];
firstname[0] = 0;
strcpy(firstname,gFile->GetName());
Int_t nFiles = 0;
Int_t treeNumber = -1;
Int_t nentries = Int_t(GetEntries());
for (Int_t i=0;i<nentries;i++) {
GetEntry(i);
if (treeNumber != fTreeNumber) {
treeNumber = fTreeNumber;
TIter next(fTree->GetListOfBranches());
Bool_t failed = kFALSE;
while ((branch = (TBranch*)next())) {
TBranch *new_branch = hnew->GetBranch( branch->GetName() );
if (!new_branch) continue;
void *add = branch->GetAddress();
// in case branch addresses have not been set, give a last chance
// for simple Trees (h2root converted for example)
if (!add) {
TLeaf *leaf, *new_leaf;
TIter next_l(branch->GetListOfLeaves());
while ((leaf = (TLeaf*) next_l())) {
add = leaf->GetValuePointer();
if (add) {
new_leaf = new_branch->GetLeaf(leaf->GetName());
if(new_leaf) new_leaf->SetAddress(add);
} else {
failed = kTRUE;
}
}
} else {
new_branch->SetAddress(add);
}
if (failed) Warning("Merge","Tree branch addresses not defined");
}
}
hnew->Fill();
//check that output file is still below the maximum size.
//If above, close the current file and continue on a new file.
if (gFile->GetBytesWritten() > (Double_t)fgMaxMergeSize) {
hnew->Write();
hnew->SetDirectory(0);
hnew->Reset();
nFiles++;
char *fname = new char[1000];
fname[0] = 0;
strcpy(fname,firstname);
char *cdot = strrchr(fname,'.');
if (cdot) {
sprintf(cdot,"_%d",nFiles);
strcat(fname,strrchr(firstname,'.'));
} else {
char fcount[10];
sprintf(fcount,"_%d",nFiles);
strcat(fname,fcount);
}
delete file;
file = TFile::Open(fname,"recreate","chain files",1);
Printf("Merge: Switching to new file: %s at entry: %d",fname,i);
hnew->SetDirectory(file);
nextb.Reset();
while ((branch = (TBranch*)nextb())) {
branch->SetFile(file);
}
delete [] fname;
}
}
// Write new tree header
hnew->Write();
delete [] firstname;
if (nFiles) {
delete file;
}
return nFiles+1;
}
//______________________________________________________________________________
void TChain::Print(Option_t *option) const
{
TIter next(fFiles);
TChainElement *element;
while ((element = (TChainElement*)next())) {
TFile *file = TFile::Open(element->GetTitle());
if (!file->IsZombie()) {
TTree *tree = (TTree*)file->Get(element->GetName());
tree->Print(option);
}
delete file;
}
}
//______________________________________________________________________________
Int_t TChain::Process(const char *filename,Option_t *option, Int_t nentries, Int_t firstentry)
{
// Process all entries in this chain, calling functions in filename
// see TTree::Process
if (LoadTree(firstentry) < 0) return 0;
return TTree::Process(filename,option,nentries,firstentry);
}
//______________________________________________________________________________
Int_t TChain::Process(TSelector *selector,Option_t *option, Int_t nentries, Int_t firstentry)
{
//*-*-*-*-*-*-*-*-*Process this chain executing the code in selector*-*-*-*-*
//*-* ================================================
return TTree::Process(selector,option,nentries,firstentry);
}
//______________________________________________________________________________
void TChain::Reset(Option_t *)
{
// Resets the definition of this chain
delete fFile;
fNtrees = 0;
fTreeNumber = -1;
fTree = 0;
fFile = 0;
fFiles->Delete();
fStatus->Delete();
fTreeOffset[0] = 0;
TChainElement *element = new TChainElement("*","");
fStatus->Add(element);
fDirectory = 0;
fNotify = 0;
TTree::Reset();
}
//_______________________________________________________________________
void TChain::SetBranchAddress(const char *bname, void *add)
{
//*-*-*-*-*-*-*-*-*Set branch address*-*-*-*-*-*-*-*
//*-* ==================
//
// bname is the name of a branch.
// add is the address of the branch.
//Check if bname is already in the Status list
//Otherwise create a TChainElement object and set its address
TChainElement *element = (TChainElement*)fStatus->FindObject(bname);
if (!element) {
element = new TChainElement(bname,"");
fStatus->Add(element);
}
element->SetBaddress(add);
// invalidate current Tree
fTreeNumber = -1;
}
//_______________________________________________________________________
void TChain::SetBranchStatus(const char *bname, Bool_t status)
{
//*-*-*-*-*-*-*-*-*Set branch status Process or DoNotProcess*-*-*-*-*-*-*-*
//*-* =========================================
//
// bname is the name of a branch. if bname="*", apply to all branches.
// status = 1 branch will be processed
// = 0 branch will not be processed
//Check if bname is already in the Status list
//Otherwise create a TChainElement object and set its status
TChainElement *element = (TChainElement*)fStatus->FindObject(bname);
if (!element) {
element = new TChainElement(bname,"");
fStatus->Add(element);
}
element->SetStatus(status);
// invalidate current Tree
fTreeNumber = -1;
}
//______________________________________________________________________________
void TChain::SetMaxMergeSize(Int_t maxsize)
{
// static function
// Set the maximum size of a merged file.
// In TChain::Merge, when the merged file has a size > fgMaxMergeSize,
// the function closes the current merged file and starts writing into
// a new file with a name of the style "merged_1.root" if the original
// requested file name was "merged.root"
fgMaxMergeSize = maxsize;
}
//_______________________________________________________________________
void TChain::SetPacketSize(Int_t size)
{
//*-*-*-*-*-*-*-*-*Set number of entries per packet for parallel root*-*-*-*-*
//*-* =================================================
fPacketSize = size;
TIter next(fFiles);
TChainElement *element;
while ((element = (TChainElement*)next())) {
element->SetPacketSize(size);
}
}
//_______________________________________________________________________
void TChain::Streamer(TBuffer &b)
{
//*-*-*-*-*-*-*-*-*Stream a class object*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* =========================================
if (b.IsReading()) {
UInt_t R__s, R__c;
Version_t R__v = b.ReadVersion(&R__s, &R__c);
if (R__v > 2) {
TChain::Class()->ReadBuffer(b, this, R__v, R__s, R__c);
return;
}
//====process old versions before automatic schema evolution
TTree::Streamer(b);
b >> fTreeOffsetLen;
b >> fNtrees;
fFiles->Streamer(b);
if (R__v > 1) {
fStatus->Streamer(b);
fTreeOffset = new Int_t[fTreeOffsetLen];
b.ReadFastArray(fTreeOffset,fTreeOffsetLen);
}
b.CheckByteCount(R__s, R__c, TChain::IsA());
//====end of old versions
} else {
TChain::Class()->WriteBuffer(b,this);
}
}
Patch by Philippe to prevent reads before the start of the
fTreeOffset array.
git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@3664 27541ba8-7e3a-0410-8455-c3a389f83636
// @(#)root/tree:$Name: $:$Id: TChain.cxx,v 1.34 2002/01/07 09:10:20 rdm Exp $
// Author: Rene Brun 03/02/97
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TChain //
// //
// A chain is a collection of files containg TTree objects. //
// When the chain is created, the first parameter is the default name //
// for the Tree to be processed later on. //
// //
// Enter a new element in the chain via the TChain::Add function. //
// Once a chain is defined, one can use the normal TTree functions //
// to Draw,Scan,etc. //
// //
// Use TChain::SetBranchStatus to activate one or more branches for all //
// the trees in the chain. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TROOT.h"
#include "TChain.h"
#include "TTree.h"
#include "TFile.h"
#include "TSelector.h"
#include "TBranch.h"
#include "TLeaf.h"
#include "TBrowser.h"
#include "TChainElement.h"
#include "TFriendElement.h"
#include "TSystem.h"
#include "TRegexp.h"
Int_t TChain::fgMaxMergeSize = 1900000000;
ClassImp(TChain)
//______________________________________________________________________________
TChain::TChain(): TTree()
{
//*-*-*-*-*-*Default constructor for Chain*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* ==============================
fTreeOffsetLen = 100;
fNtrees = 0;
fTreeNumber = -1;
fTreeOffset = 0;
fTree = 0;
fFile = 0;
fFiles = new TObjArray(fTreeOffsetLen );
fStatus = new TList();
fNotify = 0;
}
//______________________________________________________________________________
TChain::TChain(const char *name, const char *title)
:TTree(name,title)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*Create a Chain*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* ==============
//
// A TChain is a collection of TFile objects.
// the first parameter "name" is the name of the TTree object
// in the files added with Add.
// Use TChain::Add to add a new element to this chain.
//
// In case the Tree is in a subdirectory, do, eg:
// TChain ch("subdir/treename");
//
// Example:
// Suppose we have 3 files f1.root, f2.root and f3.root. Each file
// contains a TTree object named "T".
// TChain ch("T"); creates a chain to process a Tree called "T"
// ch.Add("f1.root");
// ch.Add("f2.root");
// ch.Add("f3.root");
// ch.Draw("x");
// The Draw function above will process the variable "x" in Tree "T"
// reading sequentially the 3 files in the chain ch.
//
//*-*
fTreeOffsetLen = 100;
fNtrees = 0;
fTreeNumber = -1;
fTreeOffset = new Int_t[fTreeOffsetLen];
fTree = 0;
fFile = 0;
fFiles = new TObjArray(fTreeOffsetLen );
fStatus = new TList();
fTreeOffset[0] = 0;
TChainElement *element = new TChainElement("*","");
fStatus->Add(element);
gDirectory->GetList()->Remove(this);
gROOT->GetListOfSpecials()->Add(this);
fDirectory = 0;
fNotify = 0;
}
//______________________________________________________________________________
TChain::~TChain()
{
//*-*-*-*-*-*Default destructor for a Chain*-*-*-*-*-*-*-*-*-*-*-*
//*-* ==============================
fDirectory = 0;
fFile = 0;
gROOT->GetListOfSpecials()->Remove(this);
delete [] fTreeOffset;
fFiles->Delete();
delete fFiles;
fStatus->Delete();
delete fStatus;
}
//______________________________________________________________________________
Int_t TChain::Add(TChain *chain)
{
// Add all files referenced by the TChain chain to this chain.
//Check enough space in fTreeOffset
if (fNtrees+chain->GetNtrees() >= fTreeOffsetLen) {
fTreeOffsetLen += 2*chain->GetNtrees();
Int_t *trees = new Int_t[fTreeOffsetLen];
for (Int_t i=0;i<=fNtrees;i++) trees[i] = fTreeOffset[i];
delete [] fTreeOffset;
fTreeOffset = trees;
}
TIter next(chain->GetListOfFiles());
TChainElement *element, *newelement;
Int_t nf = 0;
while ((element = (TChainElement*)next())) {
Int_t nentries = element->GetEntries();
fTreeOffset[fNtrees+1] = fTreeOffset[fNtrees] + nentries;
fNtrees++;
fEntries += nentries;
newelement = new TChainElement(element->GetName(),element->GetTitle());
newelement->SetPacketSize(element->GetPacketSize());
newelement->SetNumberEntries(nentries);
fFiles->Add(newelement);
nf++;
}
return nf;
}
//______________________________________________________________________________
Int_t TChain::Add(const char *name, Int_t nentries)
{
// Add a new file to this chain.
// Argument name may have the following format:
// //machine/file_name.root/subdir/tree_name
// machine, subdir and tree_name are optional. If tree_name is missing,
// the chain name will be assumed.
// Name may use the wildcarding notation, eg "xxx*.root" means all files
// starting with xxx in the current file system directory.
//
// If nentries <= 0, the file is connected and the tree header read in memory
// to get the number of entries.
// If (nentries > 0, the file is not connected, nentries is assumed to be
// the number of entries in the file. In this case, no check is made that
// the file exists and the Tree existing in the file. This second mode
// is interesting in case the number of entries in the file is already stored
// in a run data base for example.
// NB. To add all the files of a TChain to a chain, use Add(TChain *chain).
// case with one single file
if (strchr(name,'*') == 0) {
return AddFile(name,nentries);
}
// wildcarding used in name
Int_t nf = 0;
char aname[2048]; //files may have very long names, eg AFS
strcpy(aname,name);
char *dot = (char*)strstr(aname,".root");
const char *behind_dot_root = 0;
if (dot) {
if (dot[5] == '/') behind_dot_root = dot + 6;
*dot = 0;
}
char *slash = strrchr(aname,'/');
if (slash) {
*slash = 0;
slash++;
strcat(slash,".root");
} else {
strcpy(aname,gSystem->WorkingDirectory());
slash = (char*)name;
}
const char *file;
void *dir = gSystem->OpenDirectory(gSystem->ExpandPathName(aname));
if (dir) {
TRegexp re(slash,kTRUE);
while ((file = gSystem->GetDirEntry(dir))) {
if (!strcmp(file,".") || !strcmp(file,"..")) continue;
//if (IsDirectory(file)) continue;
TString s = file;
if (strcmp(slash,file) && s.Index(re) == kNPOS) continue;
if (behind_dot_root != 0 && *behind_dot_root != 0)
nf += AddFile(Form("%s/%s/%s",aname,file,behind_dot_root),-1);
else
nf += AddFile(Form("%s/%s",aname,file),-1);
}
gSystem->FreeDirectory(dir);
}
return nf;
}
//______________________________________________________________________________
Int_t TChain::AddFile(const char *name, Int_t nentries)
{
// Add a new file to this chain.
//
// if nentries <= 0, the file is connected and the tree header read in memory
// to get the number of entries.
// if (nentries > 0, the file is not connected, nentries is assumed to be
// the number of entries in the file. In this case, no check is made that
// the file exists and the Tree existing in the file. This second mode
// is interesting in case the number of entries in the file is already stored
// in a run data base for example.
TDirectory *cursav = gDirectory;
char *treename = (char*)GetName();
char *dot = (char*)strstr(name,".root");
//the ".root" is mandatory only if one wants to specify a treename
//if (!dot) {
// Error("AddFile","a chain element name must contain the string .root");
// return 0;
//}
//Check enough space in fTreeOffset
if (fNtrees+1 >= fTreeOffsetLen) {
fTreeOffsetLen *= 2;
Int_t *trees = new Int_t[fTreeOffsetLen];
for (Int_t i=0;i<=fNtrees;i++) trees[i] = fTreeOffset[i];
delete [] fTreeOffset;
fTreeOffset = trees;
}
//Search for a a slash between the .root and the end
Int_t nch = strlen(name) + strlen(treename);
char *filename = new char[nch+1];
strcpy(filename,name);
if (dot) {
char *pos = (char*)strstr(filename,".root") + 5;
while (*pos) {
if (*pos == '/') {
treename = pos+1;
*pos = 0;
break;
}
pos++;
}
}
//Connect the file to get the number of entries
Int_t pksize = 0;
if (nentries <= 0) {
TFile *file = TFile::Open(filename);
if (file->IsZombie()) {
delete file;
delete [] filename;
return 0;
}
//Check that tree with the right name exists in the file
TObject *obj = file->Get(treename);
if (!obj || !obj->InheritsFrom("TTree") ) {
Error("AddFile","cannot find tree with name %s in file %s", treename,filename);
delete file;
delete [] filename;
return 0;
}
TTree *tree = (TTree*)obj;
nentries = (Int_t)tree->GetEntries();
pksize = tree->GetPacketSize();
delete tree;
delete file;
}
if (nentries > 0) {
fTreeOffset[fNtrees+1] = fTreeOffset[fNtrees] + nentries;
fNtrees++;
fEntries += nentries;
TChainElement *element = new TChainElement(treename,filename);
element->SetPacketSize(pksize);
element->SetNumberEntries(nentries);
fFiles->Add(element);
} else {
Warning("Add","Adding Tree with no entries from file: %s",filename);
}
delete [] filename;
if (cursav) cursav->cd();
return 1;
}
//______________________________________________________________________________
TFriendElement *TChain::AddFriend(const char *chain, const char *dummy)
{
// Add a TFriendElement to the list of friends of this chain.
//
// A TChain has a list of friends similar to a tree (see TTree::AddFriend).
// You can add a friend to a chain with the TChain::AddFriend method, and you
// can retrieve the list of friends with TChain::GetListOfFriends.
// This example has four chains each has 20 ROOT trees from 20 ROOT files.
//
// TChain ch("t"); // a chain with 20 trees from 20 files
// TChain ch1("t1");
// TChain ch2("t2");
// TChain ch3("t3");
// Now we can add the friends to the first chain.
//
// ch.AddFriend("t1")
// ch.AddFriend("t2")
// ch.AddFriend("t3")
//
//Begin_Html
/*
<img src="gif/chain_friend.gif">
*/
//End_Html
//
// The parameter is the name of friend chain (the name of a chain is always
// the name of the tree from which it was created).
// The original chain has access to all variable in its friends.
// We can use the TChain::Draw method as if the values in the friends were
// in the original chain.
// To specify the chain to use in the Draw method, use the syntax:
//
// <chainname>.<branchname>.<varname>
// If the variable name is enough to uniquely identify the variable, you can
// leave out the chain and/or branch name.
// For example, this generates a 3-d scatter plot of variable "var" in the
// TChain ch versus variable v1 in TChain t1 versus variable v2 in TChain t2.
//
// ch.Draw("var:t1.v1:t2.v2");
// When a TChain::Draw is executed, an automatic call to TTree::AddFriend
// connects the trees in the chain. When a chain is deleted, its friend
// elements are also deleted.
//
// The number of entries in the friend must be equal or greater to the number
// of entries of the original chain. If the friend has fewer entries a warning
// is given and the resulting histogram will have missing entries.
// For additional information see TTree::AddFriend.
if (!fFriends) fFriends = new TList();
TFriendElement *fe = new TFriendElement(this,chain,dummy);
if (fe) {
fFriends->Add(fe);
TTree *t = fe->GetTree();
if (t) {
if (t->GetEntries() < fEntries) {
//Warning("AddFriend","FriendElement %s in file %s has less entries %g than its parent Tree: %g",
// chain,filename,t->GetEntries(),fEntries);
}
} else {
Warning("AddFriend","Unknown TChain %s",chain);
}
} else {
Warning("AddFriend","Cannot add FriendElement %s",chain);
}
return fe;
}
//______________________________________________________________________________
TFriendElement *TChain::AddFriend(const char *chain, TFile *dummy)
{
if (!fFriends) fFriends = new TList();
TFriendElement *fe = new TFriendElement(this,chain,dummy);
if (fe) {
fFriends->Add(fe);
TTree *t = fe->GetTree();
if (t) {
if (t->GetEntries() < fEntries) {
//Warning("AddFriend","FriendElement %s in file %s has less entries %g than its parent Tree: %g",
// chain,filename,t->GetEntries(),fEntries);
}
} else {
Warning("AddFriend","Unknown TChain %s",chain);
}
} else {
Warning("AddFriend","Cannot add FriendElement %s",chain);
}
return fe;
}
//______________________________________________________________________________
void TChain::Browse(TBrowser *)
{
}
//_______________________________________________________________________
void TChain::CreatePackets()
{
//*-*-*-*-*-*-*-*-*Initialize the packet descriptor string*-*-*-*-*-*-*-*-*-*
//*-* =======================================
TIter next(fFiles);
TChainElement *element;
while ((element = (TChainElement*)next())) {
element->CreatePackets();
}
}
//______________________________________________________________________________
Int_t TChain::Draw(const char *varexp, TCut selection, Option_t *option, Int_t nentries, Int_t firstentry)
{
// Draw expression varexp for selected entries.
//
// This function accepts TCut objects as arguments.
// Useful to use the string operator +, example:
// ntuple.Draw("x",cut1+cut2+cut3);
//
return TChain::Draw(varexp, selection.GetTitle(), option, nentries, firstentry);
}
//______________________________________________________________________________
Int_t TChain::Draw(const char *varexp, const char *selection, Option_t *option,Int_t nentries, Int_t firstentry)
{
// Process all entries in this chain and draw histogram
// corresponding to expression varexp.
if (LoadTree(firstentry) < 0) return 0;
return TTree::Draw(varexp,selection,option,nentries,firstentry);
}
//______________________________________________________________________________
TBranch *TChain::GetBranch(const char *name)
{
//*-*-*-*-*-*-*-*-*Return pointer to the branch name*-*-*-*-*
//*-* ==========================================
if (fTree) return fTree->GetBranch(name);
LoadTree(0);
if (fTree) return fTree->GetBranch(name);
return 0;
}
//______________________________________________________________________________
Int_t TChain::GetChainEntryNumber(Int_t entry) const
{
// return absolute entry number in the chain
// the input parameter entry is the entry number in the current Tree of this chain
return entry + fTreeOffset[fTreeNumber];
}
//______________________________________________________________________________
Int_t TChain::GetEntry(Int_t entry, Int_t getall)
{
//*-*-*-*-*-*-*-*-*Return entry in memory*-*-*-*-*-*-*-*-*-*
//*-* ======================
// getall = 0 : get only active branches
// getall = 1 : get all branches
if (LoadTree(entry) < 0) return 0;
return fTree->GetEntry(fReadEntry,getall);
}
//______________________________________________________________________________
TLeaf *TChain::GetLeaf(const char *name)
{
//*-*-*-*-*-*-*-*-*Return pointer to the leaf name*-*-*-*-*
//*-* ==========================================
if (fTree) return fTree->GetLeaf(name);
LoadTree(0);
if (fTree) return fTree->GetLeaf(name);
return 0;
}
//______________________________________________________________________________
TObjArray *TChain::GetListOfBranches()
{
//*-*-*-*-*-*-*-*-*Return pointer to list of branches of current tree*-*-*-*-*
//*-* ================================================
if (fTree) return fTree->GetListOfBranches();
LoadTree(0);
if (fTree) return fTree->GetListOfBranches();
return 0;
}
//______________________________________________________________________________
TObjArray *TChain::GetListOfLeaves()
{
//*-*-*-*-*-*-*-*-*Return pointer to list of leaves of current tree*-*-*-*-*
//*-* ================================================
if (fTree) return fTree->GetListOfLeaves();
LoadTree(0);
if (fTree) return fTree->GetListOfLeaves();
return 0;
}
//______________________________________________________________________________
Int_t TChain::GetMaxMergeSize()
{
// static function
// return maximum size of a merged file
return fgMaxMergeSize;
}
//______________________________________________________________________________
Double_t TChain::GetMaximum(const char *columname)
{
//*-*-*-*-*-*-*-*-*Return maximum of column with name columname*-*-*-*-*-*-*
//*-* ============================================
Double_t theMax = -FLT_MAX; //in float.h
for (Int_t file=0;file<fNtrees;file++) {
Int_t first = fTreeOffset[file];
LoadTree(first);
Double_t curmax = fTree->GetMaximum(columname);;
if (curmax > theMax) theMax = curmax;
}
return theMax;
}
//______________________________________________________________________________
Double_t TChain::GetMinimum(const char *columname)
{
//*-*-*-*-*-*-*-*-*Return minimum of column with name columname*-*-*-*-*-*-*
//*-* ============================================
Double_t theMin = FLT_MAX; //in float.h
for (Int_t file=0;file<fNtrees;file++) {
Int_t first = fTreeOffset[file];
LoadTree(first);
Double_t curmin = fTree->GetMinimum(columname);;
if (curmin < theMin) theMin = curmin;
}
return theMin;
}
//______________________________________________________________________________
Int_t TChain::GetNbranches()
{
//*-*-*-*-*-*-*-*-*Return number of branches of current tree*-*-*-*-*
//*-* =========================================
if (fTree) return fTree->GetNbranches();
LoadTree(0);
if (fTree) return fTree->GetNbranches();
return 0;
}
//______________________________________________________________________________
Int_t TChain::LoadTree(Int_t entry)
{
// The input argument entry is the entry serial number in the whole chain.
// The function finds the corresponding Tree and returns the entry number
// in this tree.
if (!fNtrees) return 1;
if (entry < 0 || entry >= fEntries) return -2;
//Find in which tree this entry belongs to
Int_t t;
if (fTreeNumber!=-1 &&
(entry >= fTreeOffset[fTreeNumber] && entry < fTreeOffset[fTreeNumber+1])){
t = fTreeNumber;
}
else {
for (t=0;t<fNtrees;t++) {
if (entry < fTreeOffset[t+1]) break;
}
}
fReadEntry = entry - fTreeOffset[t];
// If entry belongs to the current tree return entry
if (t == fTreeNumber) {
return fReadEntry;
}
//Delete current tree and connect new tree
TDirectory *cursav = gDirectory;
delete fFile; fFile = 0;
TChainElement *element = (TChainElement*)fFiles->At(t);
if (!element) return -4;
fFile = TFile::Open(element->GetTitle());
if (fFile->IsZombie()) {
delete fFile; fFile = 0;
return -3;
}
fTree = (TTree*)fFile->Get(element->GetName());
fTreeNumber = t;
fDirectory = fFile;
//Set the branches status and address for the newly connected file
fTree->SetMakeClass(fMakeClass);
fTree->SetMaxVirtualSize(fMaxVirtualSize);
SetChainOffset(fTreeOffset[t]);
TIter next(fStatus);
Int_t status;
while ((element = (TChainElement*)next())) {
status = element->GetStatus();
if (status >=0) fTree->SetBranchStatus(element->GetName(),status);
void *add = element->GetBaddress();
if (add) fTree->SetBranchAddress(element->GetName(),add);
}
if (cursav) cursav->cd();
//update list of leaves in all TTreeFormula of the TTreePlayer (if any)
if (fPlayer) fPlayer->UpdateFormulaLeaves();
//Notify user if requested
if (fNotify) fNotify->Notify();
return fReadEntry;
}
//______________________________________________________________________________
void TChain::Loop(Option_t *option, Int_t nentries, Int_t firstentry)
{
//*-*-*-*-*-*-*-*-*Loop on nentries of this chain starting at firstentry
//*-* ===================================================
Error("Loop","Function not yet implemented");
if (option || nentries || firstentry) { } // keep warnings away
#ifdef NEVER
if (LoadTree(firstentry) < 0) return;
if (firstentry < 0) firstentry = 0;
Int_t lastentry = firstentry + nentries -1;
if (lastentry > fEntries-1) {
lastentry = (Int_t)fEntries -1;
}
GetPlayer();
GetSelector();
fSelector->Start(option);
Int_t entry = firstentry;
Int_t tree,e0,en;
for (tree=0;tree<fNtrees;tree++) {
e0 = fTreeOffset[tree];
en = fTreeOffset[tree+1] - 1;
if (en > lastentry) en = lastentry;
if (entry > en) continue;
LoadTree(entry);
fSelector->BeginFile();
while (entry <= en) {
fSelector->Execute(fTree, entry - e0);
entry++;
}
fSelector->EndFile();
}
fSelector->Finish(option);
#endif
}
//______________________________________________________________________________
void TChain::ls(Option_t *option) const
{
TIter next(fFiles);
TChainElement *file;
while ((file = (TChainElement*)next())) {
file->ls();
}
}
//______________________________________________________________________________
Int_t TChain::Merge(const char *name)
{
// Merge all files in this chain into a new file
// see important note in the following function Merge
TFile *file = TFile::Open(name,"recreate","chain files",1);
Int_t nFiles = Merge(file,0,"");
if (nFiles <= 1) {
file->Close();
delete file;
}
return nFiles;
}
//______________________________________________________________________________
Int_t TChain::Merge(TFile *file, Int_t basketsize, Option_t *option)
{
// Merge all files in this chain into a new file
// if option ="C" is given, the compression level for all branches
// in the new Tree is set to the file compression level.
// By default, the compression level of all branches is the
// original compression level in the old Trees.
//
// if (basketsize > 1000, the basket size for all branches of the
// new Tree will be set to basketsize.
//
// IMPORTANT: Before invoking this function, the branch addresses
// of the TTree must have been set.
// example using the file generated in $ROOTSYS/test/Event
// merge two copies of Event.root
//
// gSystem.Load("libEvent");
// Event *event = new Event();
// TChain ch("T");
// ch.SetBranchAddress("event",&event);
// ch.Add("Event1.root");
// ch.Add("Event2.root");
// ch.Merge("all.root");
//
// The SetBranchAddress statement is not necessary if the Tree
// contains only basic types (case of files converted from hbook)
//
// NOTE that the merged Tree contains only the active branches.
//
// AUTOMATIC FILE OVERFLOW
// -----------------------
// When merging many files, it may happen that the resulting file
// reaches a size > fgMaxMergeSize (default = 1.9 GBytes). In this case
// the current file is automatically closed and a new file started.
// If the name of the merged file was "merged.root", the subsequent files
// will be named "merged_1.root", "merged_2.root", etc.
// fgMaxMergeSize may be modified via the static function SetMaxMergeSize.
//
// The function returns the total number of files produced.
if (!file) return 0;
TObjArray *lbranches = GetListOfBranches();
if (!lbranches) return 0;
if (!fTree) return 0;
// Clone Chain tree
//file->cd(); //in case a user wants to write in a file/subdir
TTree *hnew = (TTree*)fTree->CloneTree(0);
hnew->SetAutoSave(2000000000);
// May be reset branches compression level?
TBranch *branch;
TIter nextb(hnew->GetListOfBranches());
if (strstr(option,"c") || strstr(option,"C")) {
while ((branch = (TBranch*)nextb())) {
branch->SetCompressionLevel(file->GetCompressionLevel());
}
nextb.Reset();
}
// May be reset branches basket size?
if (basketsize > 1000) {
while ((branch = (TBranch*)nextb())) {
branch->SetBasketSize(basketsize);
}
nextb.Reset();
}
char *firstname = new char[1000];
firstname[0] = 0;
strcpy(firstname,gFile->GetName());
Int_t nFiles = 0;
Int_t treeNumber = -1;
Int_t nentries = Int_t(GetEntries());
for (Int_t i=0;i<nentries;i++) {
GetEntry(i);
if (treeNumber != fTreeNumber) {
treeNumber = fTreeNumber;
TIter next(fTree->GetListOfBranches());
Bool_t failed = kFALSE;
while ((branch = (TBranch*)next())) {
TBranch *new_branch = hnew->GetBranch( branch->GetName() );
if (!new_branch) continue;
void *add = branch->GetAddress();
// in case branch addresses have not been set, give a last chance
// for simple Trees (h2root converted for example)
if (!add) {
TLeaf *leaf, *new_leaf;
TIter next_l(branch->GetListOfLeaves());
while ((leaf = (TLeaf*) next_l())) {
add = leaf->GetValuePointer();
if (add) {
new_leaf = new_branch->GetLeaf(leaf->GetName());
if(new_leaf) new_leaf->SetAddress(add);
} else {
failed = kTRUE;
}
}
} else {
new_branch->SetAddress(add);
}
if (failed) Warning("Merge","Tree branch addresses not defined");
}
}
hnew->Fill();
//check that output file is still below the maximum size.
//If above, close the current file and continue on a new file.
if (gFile->GetBytesWritten() > (Double_t)fgMaxMergeSize) {
hnew->Write();
hnew->SetDirectory(0);
hnew->Reset();
nFiles++;
char *fname = new char[1000];
fname[0] = 0;
strcpy(fname,firstname);
char *cdot = strrchr(fname,'.');
if (cdot) {
sprintf(cdot,"_%d",nFiles);
strcat(fname,strrchr(firstname,'.'));
} else {
char fcount[10];
sprintf(fcount,"_%d",nFiles);
strcat(fname,fcount);
}
delete file;
file = TFile::Open(fname,"recreate","chain files",1);
Printf("Merge: Switching to new file: %s at entry: %d",fname,i);
hnew->SetDirectory(file);
nextb.Reset();
while ((branch = (TBranch*)nextb())) {
branch->SetFile(file);
}
delete [] fname;
}
}
// Write new tree header
hnew->Write();
delete [] firstname;
if (nFiles) {
delete file;
}
return nFiles+1;
}
//______________________________________________________________________________
void TChain::Print(Option_t *option) const
{
TIter next(fFiles);
TChainElement *element;
while ((element = (TChainElement*)next())) {
TFile *file = TFile::Open(element->GetTitle());
if (!file->IsZombie()) {
TTree *tree = (TTree*)file->Get(element->GetName());
tree->Print(option);
}
delete file;
}
}
//______________________________________________________________________________
Int_t TChain::Process(const char *filename,Option_t *option, Int_t nentries, Int_t firstentry)
{
// Process all entries in this chain, calling functions in filename
// see TTree::Process
if (LoadTree(firstentry) < 0) return 0;
return TTree::Process(filename,option,nentries,firstentry);
}
//______________________________________________________________________________
Int_t TChain::Process(TSelector *selector,Option_t *option, Int_t nentries, Int_t firstentry)
{
//*-*-*-*-*-*-*-*-*Process this chain executing the code in selector*-*-*-*-*
//*-* ================================================
return TTree::Process(selector,option,nentries,firstentry);
}
//______________________________________________________________________________
void TChain::Reset(Option_t *)
{
// Resets the definition of this chain
delete fFile;
fNtrees = 0;
fTreeNumber = -1;
fTree = 0;
fFile = 0;
fFiles->Delete();
fStatus->Delete();
fTreeOffset[0] = 0;
TChainElement *element = new TChainElement("*","");
fStatus->Add(element);
fDirectory = 0;
fNotify = 0;
TTree::Reset();
}
//_______________________________________________________________________
void TChain::SetBranchAddress(const char *bname, void *add)
{
//*-*-*-*-*-*-*-*-*Set branch address*-*-*-*-*-*-*-*
//*-* ==================
//
// bname is the name of a branch.
// add is the address of the branch.
//Check if bname is already in the Status list
//Otherwise create a TChainElement object and set its address
TChainElement *element = (TChainElement*)fStatus->FindObject(bname);
if (!element) {
element = new TChainElement(bname,"");
fStatus->Add(element);
}
element->SetBaddress(add);
// invalidate current Tree
fTreeNumber = -1;
}
//_______________________________________________________________________
void TChain::SetBranchStatus(const char *bname, Bool_t status)
{
//*-*-*-*-*-*-*-*-*Set branch status Process or DoNotProcess*-*-*-*-*-*-*-*
//*-* =========================================
//
// bname is the name of a branch. if bname="*", apply to all branches.
// status = 1 branch will be processed
// = 0 branch will not be processed
//Check if bname is already in the Status list
//Otherwise create a TChainElement object and set its status
TChainElement *element = (TChainElement*)fStatus->FindObject(bname);
if (!element) {
element = new TChainElement(bname,"");
fStatus->Add(element);
}
element->SetStatus(status);
// invalidate current Tree
fTreeNumber = -1;
}
//______________________________________________________________________________
void TChain::SetMaxMergeSize(Int_t maxsize)
{
// static function
// Set the maximum size of a merged file.
// In TChain::Merge, when the merged file has a size > fgMaxMergeSize,
// the function closes the current merged file and starts writing into
// a new file with a name of the style "merged_1.root" if the original
// requested file name was "merged.root"
fgMaxMergeSize = maxsize;
}
//_______________________________________________________________________
void TChain::SetPacketSize(Int_t size)
{
//*-*-*-*-*-*-*-*-*Set number of entries per packet for parallel root*-*-*-*-*
//*-* =================================================
fPacketSize = size;
TIter next(fFiles);
TChainElement *element;
while ((element = (TChainElement*)next())) {
element->SetPacketSize(size);
}
}
//_______________________________________________________________________
void TChain::Streamer(TBuffer &b)
{
//*-*-*-*-*-*-*-*-*Stream a class object*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* =========================================
if (b.IsReading()) {
UInt_t R__s, R__c;
Version_t R__v = b.ReadVersion(&R__s, &R__c);
if (R__v > 2) {
TChain::Class()->ReadBuffer(b, this, R__v, R__s, R__c);
return;
}
//====process old versions before automatic schema evolution
TTree::Streamer(b);
b >> fTreeOffsetLen;
b >> fNtrees;
fFiles->Streamer(b);
if (R__v > 1) {
fStatus->Streamer(b);
fTreeOffset = new Int_t[fTreeOffsetLen];
b.ReadFastArray(fTreeOffset,fTreeOffsetLen);
}
b.CheckByteCount(R__s, R__c, TChain::IsA());
//====end of old versions
} else {
TChain::Class()->WriteBuffer(b,this);
}
}
|
#include "TerrainRenderer.h"
#include <Render/RenderNode.h>
#include <Render/GPUDriver.h>
#include <Render/Terrain.h>
#include <Render/Light.h>
#include <Render/Material.h>
#include <Render/Effect.h>
#include <Render/ShaderConstant.h>
#include <Render/ConstantBufferSet.h>
#include <Math/Sphere.h>
#include <Core/Factory.h>
namespace Render
{
__ImplementClass(Render::CTerrainRenderer, 'TRNR', Render::IRenderer);
CTerrainRenderer::~CTerrainRenderer()
{
if (pInstances) n_free_aligned(pInstances);
}
//---------------------------------------------------------------------
bool CTerrainRenderer::Init(bool LightingEnabled)
{
// Setup dynamic enumeration
InputSet_CDLOD = RegisterShaderInputSetID(CStrID("CDLOD"));
HMSamplerDesc.SetDefaults();
HMSamplerDesc.AddressU = TexAddr_Clamp;
HMSamplerDesc.AddressV = TexAddr_Clamp;
HMSamplerDesc.Filter = TexFilter_MinMag_Linear_Mip_Point;
//!!!DBG TMP! //???where to define?
MaxInstanceCount = 128;
if (LightingEnabled)
{
// With stream instancing we add light indices to a vertex declaration, maximum light count is
// determined by DEM_LIGHT_COUNT of a tech, lighting stops at the first light index == -1.
// Clamp to maximum free VS input/output register count of 10, other 6 are used for other values.
const UPTR LightIdxVectorCount = (INSTANCE_MAX_LIGHT_COUNT + 3) / 4;
InstanceDataDecl.SetSize(n_min(2 + LightIdxVectorCount, 10));
}
else
{
// Only vertex shader data will be added
InstanceDataDecl.SetSize(2);
}
// Patch offset and scale in XZ
CVertexComponent* pCmp = &InstanceDataDecl[0];
pCmp->Semantic = VCSem_TexCoord;
pCmp->UserDefinedName = NULL;
pCmp->Index = 0;
pCmp->Format = VCFmt_Float32_4;
pCmp->Stream = INSTANCE_BUFFER_STREAM_INDEX;
pCmp->OffsetInVertex = DEM_VERTEX_COMPONENT_OFFSET_DEFAULT;
pCmp->PerInstanceData = true;
// Morph constants
pCmp = &InstanceDataDecl[1];
pCmp->Semantic = VCSem_TexCoord;
pCmp->UserDefinedName = NULL;
pCmp->Index = 1;
pCmp->Format = VCFmt_Float32_2;
pCmp->Stream = INSTANCE_BUFFER_STREAM_INDEX;
pCmp->OffsetInVertex = DEM_VERTEX_COMPONENT_OFFSET_DEFAULT;
pCmp->PerInstanceData = true;
// Light indices
UPTR ElementIdx = 2;
while (ElementIdx < InstanceDataDecl.GetCount())
{
pCmp = &InstanceDataDecl[ElementIdx];
pCmp->Semantic = VCSem_TexCoord;
pCmp->UserDefinedName = NULL;
pCmp->Index = ElementIdx;
pCmp->Format = VCFmt_SInt16_4;
pCmp->Stream = INSTANCE_BUFFER_STREAM_INDEX;
pCmp->OffsetInVertex = DEM_VERTEX_COMPONENT_OFFSET_DEFAULT;
pCmp->PerInstanceData = true;
++ElementIdx;
}
OK;
}
//---------------------------------------------------------------------
bool CTerrainRenderer::CheckNodeSphereIntersection(const CLightTestArgs& Args, const sphere& Sphere, U32 X, U32 Z, U32 LOD, UPTR& AABBTestCounter)
{
I16 MinY, MaxY;
Args.pCDLOD->GetMinMaxHeight(X, Z, LOD, MinY, MaxY);
// Node has no data, can't intersect with it
if (MaxY < MinY) FAIL;
U32 NodeSize = Args.pCDLOD->GetPatchSize() << LOD;
float ScaleX = NodeSize * Args.ScaleBaseX;
float ScaleZ = NodeSize * Args.ScaleBaseZ;
float NodeMinX = Args.AABBMinX + X * ScaleX;
float NodeMinZ = Args.AABBMinZ + Z * ScaleZ;
CAABB NodeAABB;
NodeAABB.Min.x = NodeMinX;
NodeAABB.Min.y = MinY * Args.pCDLOD->GetVerticalScale();
NodeAABB.Min.z = NodeMinZ;
NodeAABB.Max.x = NodeMinX + ScaleX;
NodeAABB.Max.y = MaxY * Args.pCDLOD->GetVerticalScale();
NodeAABB.Max.z = NodeMinZ + ScaleZ;
if (Sphere.GetClipStatus(NodeAABB) == Outside) FAIL;
// Leaf node reached
if (LOD == 0) OK;
++AABBTestCounter;
if (AABBTestCounter >= LIGHT_INTERSECTION_COARSE_TEST_MAX_AABBS) OK;
const U32 XNext = X << 1, ZNext = Z << 1, NextLOD = LOD - 1;
if (CheckNodeSphereIntersection(Args, Sphere, XNext, ZNext, NextLOD, AABBTestCounter)) OK;
if (Args.pCDLOD->HasNode(XNext + 1, ZNext, NextLOD) && CheckNodeSphereIntersection(Args, Sphere, XNext + 1, ZNext, NextLOD, AABBTestCounter)) OK;
if (Args.pCDLOD->HasNode(XNext, ZNext + 1, NextLOD) && CheckNodeSphereIntersection(Args, Sphere, XNext, ZNext + 1, NextLOD, AABBTestCounter)) OK;
if (Args.pCDLOD->HasNode(XNext + 1, ZNext + 1, NextLOD) && CheckNodeSphereIntersection(Args, Sphere, XNext + 1, ZNext + 1, NextLOD, AABBTestCounter)) OK;
// No child node touches the volume
FAIL;
}
//---------------------------------------------------------------------
bool CTerrainRenderer::CheckNodeFrustumIntersection(const CLightTestArgs& Args, const matrix44& Frustum, U32 X, U32 Z, U32 LOD, UPTR& AABBTestCounter)
{
I16 MinY, MaxY;
Args.pCDLOD->GetMinMaxHeight(X, Z, LOD, MinY, MaxY);
// Node has no data, can't intersect with it
if (MaxY < MinY) FAIL;
U32 NodeSize = Args.pCDLOD->GetPatchSize() << LOD;
float ScaleX = NodeSize * Args.ScaleBaseX;
float ScaleZ = NodeSize * Args.ScaleBaseZ;
float NodeMinX = Args.AABBMinX + X * ScaleX;
float NodeMinZ = Args.AABBMinZ + Z * ScaleZ;
CAABB NodeAABB;
NodeAABB.Min.x = NodeMinX;
NodeAABB.Min.y = MinY * Args.pCDLOD->GetVerticalScale();
NodeAABB.Min.z = NodeMinZ;
NodeAABB.Max.x = NodeMinX + ScaleX;
NodeAABB.Max.y = MaxY * Args.pCDLOD->GetVerticalScale();
NodeAABB.Max.z = NodeMinZ + ScaleZ;
if (NodeAABB.GetClipStatus(Frustum) == Outside) FAIL;
// Leaf node reached
if (LOD == 0) OK;
++AABBTestCounter;
if (AABBTestCounter >= LIGHT_INTERSECTION_COARSE_TEST_MAX_AABBS) OK;
const U32 XNext = X << 1, ZNext = Z << 1, NextLOD = LOD - 1;
if (CheckNodeFrustumIntersection(Args, Frustum, XNext, ZNext, NextLOD, AABBTestCounter)) OK;
if (Args.pCDLOD->HasNode(XNext + 1, ZNext, NextLOD) && CheckNodeFrustumIntersection(Args, Frustum, XNext + 1, ZNext, NextLOD, AABBTestCounter)) OK;
if (Args.pCDLOD->HasNode(XNext, ZNext + 1, NextLOD) && CheckNodeFrustumIntersection(Args, Frustum, XNext, ZNext + 1, NextLOD, AABBTestCounter)) OK;
if (Args.pCDLOD->HasNode(XNext + 1, ZNext + 1, NextLOD) && CheckNodeFrustumIntersection(Args, Frustum, XNext + 1, ZNext + 1, NextLOD, AABBTestCounter)) OK;
// No child node touches the volume
FAIL;
}
//---------------------------------------------------------------------
bool CTerrainRenderer::PrepareNode(CRenderNode& Node, const CRenderNodeContext& Context)
{
CTerrain* pTerrain = Node.pRenderable->As<CTerrain>();
n_assert_dbg(pTerrain);
CMaterial* pMaterial = pTerrain->GetMaterial(); //!!!Get by MaterialLOD!
if (!pMaterial) FAIL;
CEffect* pEffect = pMaterial->GetEffect();
EEffectType EffType = pEffect->GetType();
if (Context.pEffectOverrides)
for (UPTR i = 0; i < Context.pEffectOverrides->GetCount(); ++i)
if (Context.pEffectOverrides->KeyAt(i) == EffType)
{
pEffect = Context.pEffectOverrides->ValueAt(i).GetUnsafe();
break;
}
if (!pEffect) FAIL;
Node.pMaterial = pMaterial;
Node.pEffect = pEffect;
Node.pTech = pEffect->GetTechByInputSet(InputSet_CDLOD);
if (!Node.pTech) FAIL;
Node.pMesh = pTerrain->GetPatchMesh();
Node.pGroup = pTerrain->GetPatchMesh()->GetGroup(0, 0); // For sorting, different terrain objects with the same mesh will be rendered sequentially
U8 LightCount = 0;
// Collect all lights that potentially touch the terrain, no limit here, limit is
// applied to the light count of a terrain patch instance.
if (Context.pLights)
{
n_assert_dbg(Context.pLightIndices);
const CCDLODData& CDLOD = *pTerrain->GetCDLODData();
const U32 TopPatchesW = CDLOD.GetTopPatchCountW();
const U32 TopPatchesH = CDLOD.GetTopPatchCountH();
const U32 TopLOD = CDLOD.GetLODCount() - 1;
float AABBMinX = Context.AABB.Min.x;
float AABBMinZ = Context.AABB.Min.z;
float AABBSizeX = Context.AABB.Max.x - AABBMinX;
float AABBSizeZ = Context.AABB.Max.z - AABBMinZ;
CLightTestArgs Args;
Args.pCDLOD = pTerrain->GetCDLODData();
Args.AABBMinX = AABBMinX;
Args.AABBMinZ = AABBMinZ;
Args.ScaleBaseX = AABBSizeX / (float)(pTerrain->GetCDLODData()->GetHeightMapWidth() - 1);
Args.ScaleBaseZ = AABBSizeZ / (float)(pTerrain->GetCDLODData()->GetHeightMapHeight() - 1);
CArray<U16>& LightIndices = *Context.pLightIndices;
Node.LightIndexBase = LightIndices.GetCount();
const CArray<CLightRecord>& Lights = *Context.pLights;
for (UPTR i = 0; i < Lights.GetCount(); ++i)
{
CLightRecord& LightRec = Lights[i];
const CLight* pLight = LightRec.pLight;
switch (pLight->Type)
{
case Light_Point:
{
//!!!???avoid object creation, rewrite functions so that testing against vector + float is possible!?
sphere LightBounds(LightRec.Transform.Translation(), pLight->GetRange());
if (LightBounds.GetClipStatus(Context.AABB) == Outside) continue;
// Perform coarse test on quadtree
if (LIGHT_INTERSECTION_COARSE_TEST_MAX_AABBS > 1)
{
bool Intersects = false;
UPTR AABBTestCounter = 1;
for (U32 Z = 0; Z < TopPatchesH; ++Z)
{
for (U32 X = 0; X < TopPatchesW; ++X)
if (CheckNodeSphereIntersection(Args, LightBounds, X, Z, TopLOD, AABBTestCounter))
{
Intersects = true;
break;
}
if (Intersects) break;
}
if (!Intersects) continue;
}
break;
}
case Light_Spot:
{
//!!!???PERF: test against sphere before?!
//???cache GlobalFrustum in a light record?
matrix44 LocalFrustum;
pLight->CalcLocalFrustum(LocalFrustum);
matrix44 GlobalFrustum;
LightRec.Transform.invert_simple(GlobalFrustum);
GlobalFrustum *= LocalFrustum;
if (Context.AABB.GetClipStatus(GlobalFrustum) == Outside) continue;
// Perform coarse test on quadtree
if (LIGHT_INTERSECTION_COARSE_TEST_MAX_AABBS > 1)
{
bool Intersects = false;
UPTR AABBTestCounter = 1;
for (U32 Z = 0; Z < TopPatchesH; ++Z)
{
for (U32 X = 0; X < TopPatchesW; ++X)
if (CheckNodeFrustumIntersection(Args, GlobalFrustum, X, Z, TopLOD, AABBTestCounter))
{
Intersects = true;
break;
}
if (Intersects) break;
}
if (!Intersects) continue;
}
break;
}
}
LightIndices.Add(i);
++LightCount;
++LightRec.UseCount;
}
}
Node.LightCount = LightCount;
OK;
}
//---------------------------------------------------------------------
void CTerrainRenderer::FillNodeLightIndices(const CProcessTerrainNodeArgs& Args, CPatchInstance& Patch, const CAABB& NodeAABB, U8& MaxLightCount)
{
n_assert_dbg(Args.pRenderContext->pLightIndices);
const CArray<U16>& LightIndices = *Args.pRenderContext->pLightIndices;
UPTR LightCount = 0;
const CArray<CLightRecord>& Lights = *Args.pRenderContext->pLights;
for (UPTR i = 0; i < Args.LightCount; ++i)
{
CLightRecord& LightRec = Lights[i];
const CLight* pLight = LightRec.pLight;
switch (pLight->Type)
{
case Light_Point:
{
//!!!???avoid object creation, rewrite functions so that testing against vector + float is possible!?
sphere LightBounds(LightRec.Transform.Translation(), pLight->GetRange());
if (LightBounds.GetClipStatus(NodeAABB) == Outside) continue;
break;
}
case Light_Spot:
{
//!!!???PERF: test against sphere before?!
//???cache GlobalFrustum in a light record?
matrix44 LocalFrustum;
pLight->CalcLocalFrustum(LocalFrustum);
matrix44 GlobalFrustum;
LightRec.Transform.invert_simple(GlobalFrustum);
GlobalFrustum *= LocalFrustum;
if (NodeAABB.GetClipStatus(GlobalFrustum) == Outside) continue;
break;
}
}
// Don't want to calculate priorities, just skip all remaining lights (for simplicity, may rework later)
if (LightCount >= INSTANCE_MAX_LIGHT_COUNT) break;
Patch.LightIndex[LightCount] = LightRec.GPULightIndex;
++LightCount;
}
if (LightCount < INSTANCE_MAX_LIGHT_COUNT)
Patch.LightIndex[LightCount] = -1;
if (MaxLightCount < LightCount)
MaxLightCount = LightCount;
}
//---------------------------------------------------------------------
//!!!recalculation required only on viewer's position / look vector change!
CTerrainRenderer::ENodeStatus CTerrainRenderer::ProcessTerrainNode(const CProcessTerrainNodeArgs& Args,
U32 X, U32 Z, U32 LOD, float LODRange,
U32& PatchCount, U32& QPatchCount,
U8& MaxLightCount, EClipStatus Clip)
{
const CCDLODData* pCDLOD = Args.pCDLOD;
I16 MinY, MaxY;
pCDLOD->GetMinMaxHeight(X, Z, LOD, MinY, MaxY);
// Node has no data, skip it completely
if (MaxY < MinY) return Node_Invisible;
U32 NodeSize = pCDLOD->GetPatchSize() << LOD;
float ScaleX = NodeSize * Args.ScaleBaseX;
float ScaleZ = NodeSize * Args.ScaleBaseZ;
float NodeMinX = Args.AABBMinX + X * ScaleX;
float NodeMinZ = Args.AABBMinZ + Z * ScaleZ;
CAABB NodeAABB;
NodeAABB.Min.x = NodeMinX;
NodeAABB.Min.y = MinY * pCDLOD->GetVerticalScale();
NodeAABB.Min.z = NodeMinZ;
NodeAABB.Max.x = NodeMinX + ScaleX;
NodeAABB.Max.y = MaxY * pCDLOD->GetVerticalScale();
NodeAABB.Max.z = NodeMinZ + ScaleZ;
if (Clip == Clipped)
{
// NB: Visibility is tested for the current camera, NOT always for the main
Clip = NodeAABB.GetClipStatus(Args.pRenderContext->ViewProjection);
if (Clip == Outside) return Node_Invisible;
}
// NB: Always must check the main frame camera, even if some special camera is used for intermediate rendering
sphere LODSphere(Args.pRenderContext->CameraPosition, LODRange);
if (LODSphere.GetClipStatus(NodeAABB) == Outside) return Node_NotInLOD;
// Bits 0 to 3 - if set, add quarterpatch for child[0 .. 3]
U8 ChildFlags = 0;
enum
{
Child_TopLeft = 0x01,
Child_TopRight = 0x02,
Child_BottomLeft = 0x04,
Child_BottomRight = 0x08,
Child_All = (Child_TopLeft | Child_TopRight | Child_BottomLeft | Child_BottomRight)
};
bool IsVisible;
if (LOD > 0)
{
// Hack, see original CDLOD code. LOD 0 range is 0.9 of what is expected.
float NextLODRange = LODRange * ((LOD == 1) ? 0.45f : 0.5f);
IsVisible = false;
// NB: Always must check the main frame camera, even if some special camera is used for intermediate rendering
LODSphere.r = NextLODRange;
if (LODSphere.GetClipStatus(NodeAABB) == Outside)
{
// Add the whole node to the current LOD
ChildFlags = Child_All;
}
else
{
const U32 XNext = X << 1, ZNext = Z << 1, NextLOD = LOD - 1;
ENodeStatus Status = ProcessTerrainNode(Args, XNext, ZNext, NextLOD, NextLODRange, PatchCount, QPatchCount, MaxLightCount, Clip);
if (Status != Node_Invisible)
{
IsVisible = true;
if (Status == Node_NotInLOD) ChildFlags |= Child_TopLeft;
}
if (pCDLOD->HasNode(XNext + 1, ZNext, NextLOD))
{
Status = ProcessTerrainNode(Args, XNext + 1, ZNext, NextLOD, NextLODRange, PatchCount, QPatchCount, MaxLightCount, Clip);
if (Status != Node_Invisible)
{
IsVisible = true;
if (Status == Node_NotInLOD) ChildFlags |= Child_TopRight;
}
}
if (pCDLOD->HasNode(XNext, ZNext + 1, NextLOD))
{
Status = ProcessTerrainNode(Args, XNext, ZNext + 1, NextLOD, NextLODRange, PatchCount, QPatchCount, MaxLightCount, Clip);
if (Status != Node_Invisible)
{
IsVisible = true;
if (Status == Node_NotInLOD) ChildFlags |= Child_BottomLeft;
}
}
if (pCDLOD->HasNode(XNext + 1, ZNext + 1, NextLOD))
{
Status = ProcessTerrainNode(Args, XNext + 1, ZNext + 1, NextLOD, NextLODRange, PatchCount, QPatchCount, MaxLightCount, Clip);
if (Status != Node_Invisible)
{
IsVisible = true;
if (Status == Node_NotInLOD) ChildFlags |= Child_BottomRight;
}
}
}
if (!ChildFlags) return IsVisible ? Node_Processed : Node_Invisible;
}
else
{
ChildFlags = Child_All;
IsVisible = true;
}
const bool LightingEnabled = (Args.pRenderContext->pLights != NULL);
float* pLODMorphConsts = Args.pMorphConsts + 2 * LOD;
if (ChildFlags == Child_All)
{
// Add whole patch
n_assert(PatchCount + QPatchCount < Args.MaxInstanceCount);
CPatchInstance& Patch = Args.pInstances[PatchCount];
Patch.ScaleOffset[0] = NodeAABB.Max.x - NodeAABB.Min.x;
Patch.ScaleOffset[1] = NodeAABB.Max.z - NodeAABB.Min.z;
Patch.ScaleOffset[2] = NodeAABB.Min.x;
Patch.ScaleOffset[3] = NodeAABB.Min.z;
Patch.MorphConsts[0] = pLODMorphConsts[0];
Patch.MorphConsts[1] = pLODMorphConsts[1];
if (LightingEnabled && INSTANCE_MAX_LIGHT_COUNT)
FillNodeLightIndices(Args, Patch, NodeAABB, MaxLightCount);
++PatchCount;
}
else
{
// Add quarterpatches
float NodeMinX = NodeAABB.Min.x;
float NodeMinZ = NodeAABB.Min.z;
float ScaleX = (NodeAABB.Max.x - NodeAABB.Min.x);
float ScaleZ = (NodeAABB.Max.z - NodeAABB.Min.z);
float HalfScaleX = ScaleX * 0.5f;
float HalfScaleZ = ScaleZ * 0.5f;
// For lighting. We don't request minmax Y for quarterpatches, but we could.
CAABB QuarterNodeAABB;
QuarterNodeAABB.Min.y = NodeAABB.Min.y;
QuarterNodeAABB.Max.y = NodeAABB.Max.y;
if (ChildFlags & Child_TopLeft)
{
n_assert(PatchCount + QPatchCount < Args.MaxInstanceCount);
CPatchInstance& Patch = Args.pInstances[Args.MaxInstanceCount - QPatchCount - 1];
Patch.ScaleOffset[0] = HalfScaleX;
Patch.ScaleOffset[1] = HalfScaleZ;
Patch.ScaleOffset[2] = NodeMinX;
Patch.ScaleOffset[3] = NodeMinZ;
Patch.MorphConsts[0] = pLODMorphConsts[0];
Patch.MorphConsts[1] = pLODMorphConsts[1];
if (LightingEnabled && INSTANCE_MAX_LIGHT_COUNT)
{
QuarterNodeAABB.Min.x = NodeMinX;
QuarterNodeAABB.Min.z = NodeMinZ;
QuarterNodeAABB.Max.x = NodeMinX + HalfScaleX;
QuarterNodeAABB.Max.z = NodeMinZ + HalfScaleZ;
FillNodeLightIndices(Args, Patch, QuarterNodeAABB, MaxLightCount);
}
++QPatchCount;
}
if (ChildFlags & Child_TopRight)
{
n_assert(PatchCount + QPatchCount < Args.MaxInstanceCount);
CPatchInstance& Patch = Args.pInstances[Args.MaxInstanceCount - QPatchCount - 1];
Patch.ScaleOffset[0] = HalfScaleX;
Patch.ScaleOffset[1] = HalfScaleZ;
Patch.ScaleOffset[2] = NodeMinX + HalfScaleX;
Patch.ScaleOffset[3] = NodeMinZ;
Patch.MorphConsts[0] = pLODMorphConsts[0];
Patch.MorphConsts[1] = pLODMorphConsts[1];
if (LightingEnabled && INSTANCE_MAX_LIGHT_COUNT)
{
QuarterNodeAABB.Min.x = NodeMinX + HalfScaleX;
QuarterNodeAABB.Min.z = NodeMinZ;
QuarterNodeAABB.Max.x = NodeMinX + ScaleX;
QuarterNodeAABB.Max.z = NodeMinZ + HalfScaleZ;
FillNodeLightIndices(Args, Patch, QuarterNodeAABB, MaxLightCount);
}
++QPatchCount;
}
if (ChildFlags & Child_BottomLeft)
{
n_assert(PatchCount + QPatchCount < Args.MaxInstanceCount);
CPatchInstance& Patch = Args.pInstances[Args.MaxInstanceCount - QPatchCount - 1];
Patch.ScaleOffset[0] = HalfScaleX;
Patch.ScaleOffset[1] = HalfScaleZ;
Patch.ScaleOffset[2] = NodeMinX;
Patch.ScaleOffset[3] = NodeMinZ + HalfScaleZ;
Patch.MorphConsts[0] = pLODMorphConsts[0];
Patch.MorphConsts[1] = pLODMorphConsts[1];
if (LightingEnabled && INSTANCE_MAX_LIGHT_COUNT)
{
QuarterNodeAABB.Min.x = NodeMinX;
QuarterNodeAABB.Min.z = NodeMinZ + HalfScaleZ;
QuarterNodeAABB.Max.x = NodeMinX + HalfScaleX;
QuarterNodeAABB.Max.z = NodeMinZ + ScaleZ;
FillNodeLightIndices(Args, Patch, QuarterNodeAABB, MaxLightCount);
}
++QPatchCount;
}
if (ChildFlags & Child_BottomRight)
{
n_assert(PatchCount + QPatchCount < Args.MaxInstanceCount);
CPatchInstance& Patch = Args.pInstances[Args.MaxInstanceCount - QPatchCount - 1];
Patch.ScaleOffset[0] = HalfScaleX;
Patch.ScaleOffset[1] = HalfScaleZ;
Patch.ScaleOffset[2] = NodeMinX + HalfScaleX;
Patch.ScaleOffset[3] = NodeMinZ + HalfScaleZ;
Patch.MorphConsts[0] = pLODMorphConsts[0];
Patch.MorphConsts[1] = pLODMorphConsts[1];
if (LightingEnabled && INSTANCE_MAX_LIGHT_COUNT)
{
QuarterNodeAABB.Min.x = NodeMinX + HalfScaleX;
QuarterNodeAABB.Min.z = NodeMinZ + HalfScaleZ;
QuarterNodeAABB.Max.x = NodeMinX + ScaleX;
QuarterNodeAABB.Max.z = NodeMinZ + ScaleZ;
FillNodeLightIndices(Args, Patch, QuarterNodeAABB, MaxLightCount);
}
++QPatchCount;
}
}
// Morphing artifacts test (from the original CDLOD code)
/*
#ifdef _DEBUG
if (LOD < Terrain.GetLODCount() - 1)
{
//!!!Always must check the Main camera!
float MaxDistToCameraSq = NodeAABB.MaxDistFromPointSq(RenderSrv->GetCameraPosition());
float MorphStart = MorphConsts[LOD + 1].Start;
if (MaxDistToCameraSq > MorphStart * MorphStart)
Sys::Error("Visibility distance is too small!");
}
#endif
*/
return Node_Processed;
}
//---------------------------------------------------------------------
CArray<CRenderNode*>::CIterator CTerrainRenderer::Render(const CRenderContext& Context, CArray<CRenderNode*>& RenderQueue, CArray<CRenderNode*>::CIterator ItCurr)
{
CGPUDriver& GPU = *Context.pGPU;
CArray<CRenderNode*>::CIterator ItEnd = RenderQueue.End();
if (!GPU.CheckCaps(Caps_VSTexFiltering_Linear))
{
// Skip terrain rendering. Can fall back to manual 4-sample filtering in a shader instead.
while (ItCurr != ItEnd)
{
if ((*ItCurr)->pRenderer != this) return ItCurr;
++ItCurr;
}
return ItEnd;
}
const CMaterial* pCurrMaterial = NULL;
const CTechnique* pCurrTech = NULL;
const CEffectConstant* pConstVSCDLODParams = NULL;
const CEffectConstant* pConstPSCDLODParams = NULL;
const CEffectConstant* pConstGridConsts = NULL;
const CEffectConstant* pConstInstanceDataVS = NULL;
const CEffectConstant* pConstInstanceDataPS = NULL;
const CEffectResource* pResourceHeightMap = NULL;
const bool LightingEnabled = (Context.pLights != NULL);
if (HMSampler.IsNullPtr()) HMSampler = GPU.CreateSampler(HMSamplerDesc);
while (ItCurr != ItEnd)
{
CRenderNode* pRenderNode = *ItCurr;
if (pRenderNode->pRenderer != this) return ItCurr;
CTerrain* pTerrain = pRenderNode->pRenderable->As<CTerrain>();
const float VisibilityRange = 1000.f;
const float MorphStartRatio = 0.7f;
const CCDLODData* pCDLOD = pTerrain->GetCDLODData();
U32 LODCount = pCDLOD->GetLODCount();
// Calculate morph constants
//!!!PERF: may recalculate only when LODCount / VisibilityRange changes!
float MorphStart = 0.f;
float CurrVisRange = VisibilityRange / (float)(1 << (LODCount - 1));
float* pMorphConsts = (float*)_malloca(sizeof(float) * 2 * LODCount);
float* pCurrMorphConst = pMorphConsts;
for (U32 j = 0; j < LODCount; ++j)
{
float MorphEnd = j ? CurrVisRange : CurrVisRange * 0.9f;
MorphStart = MorphStart + (MorphEnd - MorphStart) * MorphStartRatio;
MorphEnd = n_lerp(MorphEnd, MorphStart, 0.01f);
float MorphConst2 = 1.0f / (MorphEnd - MorphStart);
*pCurrMorphConst++ = MorphEnd * MorphConst2;
*pCurrMorphConst++ = MorphConst2;
CurrVisRange *= 2.f;
}
// Fill instance data with patches and quarter-patches to render
U32 PatchCount = 0, QuarterPatchCount = 0;
//!!!PERF: for D3D11 const instancing can create CB without a RAM copy and update whole!
if (!pInstances)
{
pInstances = (CPatchInstance*)n_malloc_aligned(sizeof(CPatchInstance) * MaxInstanceCount, 16);
n_assert_dbg(pInstances);
}
CAABB AABB;
n_verify_dbg(pTerrain->GetLocalAABB(AABB, 0));
AABB.Transform(pRenderNode->Transform);
float AABBMinX = AABB.Min.x;
float AABBMinZ = AABB.Min.z;
float AABBSizeX = AABB.Max.x - AABBMinX;
float AABBSizeZ = AABB.Max.z - AABBMinZ;
CProcessTerrainNodeArgs Args;
Args.pCDLOD = pTerrain->GetCDLODData();
Args.pInstances = pInstances;
Args.pMorphConsts = pMorphConsts;
Args.pRenderContext = &Context;
Args.MaxInstanceCount = MaxInstanceCount;
Args.AABBMinX = AABBMinX;
Args.AABBMinZ = AABBMinZ;
Args.ScaleBaseX = AABBSizeX / (float)(pCDLOD->GetHeightMapWidth() - 1);
Args.ScaleBaseZ = AABBSizeZ / (float)(pCDLOD->GetHeightMapHeight() - 1);
Args.LightIndexBase = pRenderNode->LightIndexBase;
Args.LightCount = pRenderNode->LightCount;
U8 MaxLightCount = 0;
const U32 TopPatchesW = pCDLOD->GetTopPatchCountW();
const U32 TopPatchesH = pCDLOD->GetTopPatchCountH();
const U32 TopLOD = LODCount - 1;
for (U32 Z = 0; Z < TopPatchesH; ++Z)
for (U32 X = 0; X < TopPatchesW; ++X)
ProcessTerrainNode(Args, X, Z, TopLOD, VisibilityRange, PatchCount, QuarterPatchCount, MaxLightCount);
// Since we allocate instance stream based on maximum light count, we never reallocate it when frame max light count
// drops compared to the previous frame, to avoid per-frame VB recreation. Instead we remember the biggest light
// count ever requested, allocate VB for it, and live without VB reallocations until more lights are required.
// The first unused light index is always equal -1 so no matter how much lights are, all unused ones are ignored.
// For constant instancing this value never gets used, tech with LightCount = 0 is always selected.
if (CurrMaxLightCount > MaxLightCount) MaxLightCount = CurrMaxLightCount;
_freea(pMorphConsts);
if (!PatchCount && !QuarterPatchCount)
{
++ItCurr;
continue;
}
// Sort patches
// We sort by LOD (the more is scale, the coarser is LOD), and therefore we
// almost sort by distance to the camera, as LOD depends solely on it.
struct CPatchInstanceCmp
{
inline bool operator()(const CPatchInstance& a, const CPatchInstance& b) const
{
return a.ScaleOffset[0] < b.ScaleOffset[0];
}
};
if (PatchCount)
std::sort(pInstances, pInstances + PatchCount, CPatchInstanceCmp());
if (QuarterPatchCount)
std::sort(pInstances + MaxInstanceCount - QuarterPatchCount, pInstances + MaxInstanceCount, CPatchInstanceCmp());
// Select tech for the maximal light count used per-patch
UPTR LightCount = MaxLightCount;
const CTechnique* pTech = pRenderNode->pTech;
const CPassList* pPasses = pTech->GetPasses(LightCount);
n_assert_dbg(pPasses); // To test if it could happen at all
if (!pPasses)
{
++ItCurr;
continue;
}
if (LightingEnabled)
{
if (CurrMaxLightCount < LightCount) CurrMaxLightCount = LightCount;
if (!Context.UsesGlobalLightBuffer)
{
NOT_IMPLEMENTED;
}
}
// Apply material, if changed
const CMaterial* pMaterial = pRenderNode->pMaterial;
if (pMaterial != pCurrMaterial)
{
n_assert_dbg(pMaterial);
n_verify_dbg(pMaterial->Apply(GPU));
pCurrMaterial = pMaterial;
}
// Pass tech params to GPU
if (pTech != pCurrTech)
{
pCurrTech = pTech;
pConstVSCDLODParams = pTech->GetConstant(CStrID("VSCDLODParams"));
pConstPSCDLODParams = pTech->GetConstant(CStrID("PSCDLODParams"));
pConstGridConsts = pTech->GetConstant(CStrID("GridConsts"));
pConstInstanceDataVS = pTech->GetConstant(CStrID("InstanceDataVS"));
pConstInstanceDataPS = pTech->GetConstant(CStrID("InstanceDataPS"));
pResourceHeightMap = pTech->GetResource(CStrID("HeightMapVS"));
const CEffectSampler* pVSHeightSampler = pTech->GetSampler(CStrID("VSHeightSampler"));
if (pVSHeightSampler)
GPU.BindSampler(pVSHeightSampler->ShaderType, pVSHeightSampler->Handle, HMSampler.GetUnsafe());
}
if (pResourceHeightMap)
GPU.BindResource(pResourceHeightMap->ShaderType, pResourceHeightMap->Handle, pCDLOD->GetHeightMap());
CConstantBufferSet PerInstanceBuffers;
PerInstanceBuffers.SetGPU(&GPU);
if (pConstVSCDLODParams)
{
struct
{
float WorldToHM[4];
float TerrainYScale;
float TerrainYOffset;
float InvSplatSizeX;
float InvSplatSizeZ;
float TexelSize[2];
//float TextureSize[2]; // For manual bilinear filtering in VS
} CDLODParams;
CDLODParams.WorldToHM[0] = 1.f / AABBSizeX;
CDLODParams.WorldToHM[1] = 1.f / AABBSizeZ;
CDLODParams.WorldToHM[2] = -AABBMinX * CDLODParams.WorldToHM[0];
CDLODParams.WorldToHM[3] = -AABBMinZ * CDLODParams.WorldToHM[1];
CDLODParams.TerrainYScale = 65535.f * pCDLOD->GetVerticalScale();
CDLODParams.TerrainYOffset = -32767.f * pCDLOD->GetVerticalScale() + pRenderNode->Transform.m[3][1]; // [3][1] = Translation.y
CDLODParams.InvSplatSizeX = pTerrain->GetInvSplatSizeX();
CDLODParams.InvSplatSizeZ = pTerrain->GetInvSplatSizeZ();
CDLODParams.TexelSize[0] = 1.f / (float)pCDLOD->GetHeightMapWidth();
CDLODParams.TexelSize[1] = 1.f / (float)pCDLOD->GetHeightMapHeight();
CConstantBuffer* pCB = PerInstanceBuffers.RequestBuffer(pConstVSCDLODParams->Const->GetConstantBufferHandle(), pConstVSCDLODParams->ShaderType);
pConstVSCDLODParams->Const->SetRawValue(*pCB, &CDLODParams, sizeof(CDLODParams));
if (pConstPSCDLODParams)
{
CConstantBuffer* pCB = PerInstanceBuffers.RequestBuffer(pConstPSCDLODParams->Const->GetConstantBufferHandle(), pConstPSCDLODParams->ShaderType);
pConstPSCDLODParams->Const->SetRawValue(*pCB, CDLODParams.WorldToHM, sizeof(float) * 4);
}
}
//!!!implement looping if instance buffer is too small!
if (pConstInstanceDataVS)
{
// For D3D11 constant instancing
NOT_IMPLEMENTED;
}
else
{
// Calculate int4 light index vector count supported by both tech and vertex declaration.
// Vertex declaration size will be 2 elements for VS data + one element per vector.
const UPTR LightVectorCount = (LightCount + 3) / 4;
const UPTR DeclSize = 2 + LightVectorCount;
n_assert_dbg(DeclSize <= InstanceDataDecl.GetCount());
// If current buffer doesn't suit the tech, recreate it. Since we only grow tech LightCount and never
// shrink it, buffer reallocation will be requested only if can't handle desired light count.
if (InstanceVB.IsNullPtr() || InstanceVB->GetVertexLayout()->GetComponentCount() != DeclSize)
{
PVertexLayout VLInstanceData = GPU.CreateVertexLayout(InstanceDataDecl.GetPtr(), DeclSize);
InstanceVB = NULL; // Drop before allocating new buffer
InstanceVB = GPU.CreateVertexBuffer(*VLInstanceData, MaxInstanceCount, Access_CPU_Write | Access_GPU_Read);
//!!!DBG TMP!
Sys::DbgOut("New terrain instance buffer allocated, %d vertex decl elements\n", DeclSize);
}
// Upload instance data to IA stream
//???what about D3D11_APPEND_ALIGNED_ELEMENT in D3D11 and float2?
const UPTR InstanceElementSize = InstanceVB->GetVertexLayout()->GetVertexSizeInBytes();
void* pInstData;
n_verify(GPU.MapResource(&pInstData, *InstanceVB, Map_WriteDiscard));
if (PatchCount)
{
UPTR InstDataSize = InstanceElementSize * PatchCount;
if (sizeof(CPatchInstance) == InstanceElementSize)
{
memcpy(pInstData, pInstances, InstDataSize);
}
else
{
char* pCurrInstData = (char*)pInstData;
for (UPTR PatchIdx = 0; PatchIdx < PatchCount; ++PatchIdx)
{
memcpy(pCurrInstData, pInstances + PatchIdx, InstanceElementSize);
pCurrInstData += InstanceElementSize;
}
}
pInstData = (char*)pInstData + InstDataSize;
}
if (QuarterPatchCount)
{
const CPatchInstance* pQInstances = pInstances + MaxInstanceCount - QuarterPatchCount;
if (sizeof(CPatchInstance) == InstanceElementSize)
{
memcpy(pInstData, pQInstances, InstanceElementSize * QuarterPatchCount);
}
else
{
char* pCurrInstData = (char*)pInstData;
for (UPTR PatchIdx = 0; PatchIdx < QuarterPatchCount; ++PatchIdx)
{
memcpy(pCurrInstData, pQInstances + PatchIdx, InstanceElementSize);
pCurrInstData += InstanceElementSize;
}
}
}
GPU.UnmapResource(*InstanceVB);
}
// Set vertex layout
// In the real world we don't want to use differently laid out meshes
n_assert_dbg(pTerrain->GetPatchMesh()->GetVertexBuffer()->GetVertexLayout() == pTerrain->GetQuarterPatchMesh()->GetVertexBuffer()->GetVertexLayout());
const CMesh* pMesh = pTerrain->GetPatchMesh();
n_assert_dbg(pMesh);
CVertexBuffer* pVB = pMesh->GetVertexBuffer().GetUnsafe();
n_assert_dbg(pVB);
CVertexLayout* pVL = pVB->GetVertexLayout();
//!!!implement looping if instance buffer is too small!
if (pConstInstanceDataVS) GPU.SetVertexLayout(pVL);
else
{
IPTR VLIdx = InstancedLayouts.FindIndex(pVL);
if (VLIdx == INVALID_INDEX)
{
UPTR BaseComponentCount = pVL->GetComponentCount();
UPTR InstComponentCount = InstanceVB->GetVertexLayout()->GetComponentCount();
UPTR DescComponentCount = BaseComponentCount + InstComponentCount;
CVertexComponent* pInstancedDecl = (CVertexComponent*)_malloca(DescComponentCount * sizeof(CVertexComponent));
memcpy(pInstancedDecl, pVL->GetComponent(0), BaseComponentCount * sizeof(CVertexComponent));
memcpy(pInstancedDecl + BaseComponentCount, InstanceDataDecl.GetPtr(), InstComponentCount * sizeof(CVertexComponent));
PVertexLayout VLInstanced = GPU.CreateVertexLayout(pInstancedDecl, DescComponentCount);
_freea(pInstancedDecl);
n_assert_dbg(VLInstanced.IsValidPtr());
InstancedLayouts.Add(pVL, VLInstanced);
GPU.SetVertexLayout(VLInstanced.GetUnsafe());
}
else GPU.SetVertexLayout(InstancedLayouts.ValueAt(VLIdx).GetUnsafe());
}
// Render patches //!!!may collect patches of different CTerrains if material is the same and instance buffer is big enough!
if (PatchCount)
{
if (pConstGridConsts)
{
float GridConsts[2];
GridConsts[0] = pCDLOD->GetPatchSize() * 0.5f;
GridConsts[1] = 1.f / GridConsts[0];
CConstantBuffer* pCB = PerInstanceBuffers.RequestBuffer(pConstGridConsts->Const->GetConstantBufferHandle(), pConstGridConsts->ShaderType);
pConstGridConsts->Const->SetRawValue(*pCB, &GridConsts, sizeof(GridConsts));
}
PerInstanceBuffers.CommitChanges();
GPU.SetVertexBuffer(0, pVB);
GPU.SetIndexBuffer(pMesh->GetIndexBuffer().GetUnsafe());
if (!pConstInstanceDataVS)
GPU.SetVertexBuffer(INSTANCE_BUFFER_STREAM_INDEX, InstanceVB.GetUnsafe(), 0);
const CPrimitiveGroup* pGroup = pMesh->GetGroup(0);
for (UPTR PassIdx = 0; PassIdx < pPasses->GetCount(); ++PassIdx)
{
GPU.SetRenderState((*pPasses)[PassIdx]);
GPU.DrawInstanced(*pGroup, PatchCount);
}
}
if (QuarterPatchCount)
{
if (pConstGridConsts)
{
float GridConsts[2];
GridConsts[0] = pCDLOD->GetPatchSize() * 0.25f;
GridConsts[1] = 1.f / GridConsts[0];
CConstantBuffer* pCB = PerInstanceBuffers.RequestBuffer(pConstGridConsts->Const->GetConstantBufferHandle(), pConstGridConsts->ShaderType);
pConstGridConsts->Const->SetRawValue(*pCB, &GridConsts, sizeof(GridConsts));
}
PerInstanceBuffers.CommitChanges();
pMesh = pTerrain->GetQuarterPatchMesh();
n_assert_dbg(pMesh);
pVB = pMesh->GetVertexBuffer().GetUnsafe();
n_assert_dbg(pVB);
GPU.SetVertexBuffer(0, pVB);
GPU.SetIndexBuffer(pMesh->GetIndexBuffer().GetUnsafe());
if (!pConstInstanceDataVS)
GPU.SetVertexBuffer(INSTANCE_BUFFER_STREAM_INDEX, InstanceVB.GetUnsafe(), PatchCount);
const CPrimitiveGroup* pGroup = pMesh->GetGroup(0);
for (UPTR PassIdx = 0; PassIdx < pPasses->GetCount(); ++PassIdx)
{
GPU.SetRenderState((*pPasses)[PassIdx]);
GPU.DrawInstanced(*pGroup, QuarterPatchCount);
}
}
++ItCurr;
};
return ItEnd;
}
//---------------------------------------------------------------------
}
Terrain VS sampler renamed
#include "TerrainRenderer.h"
#include <Render/RenderNode.h>
#include <Render/GPUDriver.h>
#include <Render/Terrain.h>
#include <Render/Light.h>
#include <Render/Material.h>
#include <Render/Effect.h>
#include <Render/ShaderConstant.h>
#include <Render/ConstantBufferSet.h>
#include <Math/Sphere.h>
#include <Core/Factory.h>
namespace Render
{
__ImplementClass(Render::CTerrainRenderer, 'TRNR', Render::IRenderer);
CTerrainRenderer::~CTerrainRenderer()
{
if (pInstances) n_free_aligned(pInstances);
}
//---------------------------------------------------------------------
bool CTerrainRenderer::Init(bool LightingEnabled)
{
// Setup dynamic enumeration
InputSet_CDLOD = RegisterShaderInputSetID(CStrID("CDLOD"));
HMSamplerDesc.SetDefaults();
HMSamplerDesc.AddressU = TexAddr_Clamp;
HMSamplerDesc.AddressV = TexAddr_Clamp;
HMSamplerDesc.Filter = TexFilter_MinMag_Linear_Mip_Point;
//!!!DBG TMP! //???where to define?
MaxInstanceCount = 128;
if (LightingEnabled)
{
// With stream instancing we add light indices to a vertex declaration, maximum light count is
// determined by DEM_LIGHT_COUNT of a tech, lighting stops at the first light index == -1.
// Clamp to maximum free VS input/output register count of 10, other 6 are used for other values.
const UPTR LightIdxVectorCount = (INSTANCE_MAX_LIGHT_COUNT + 3) / 4;
InstanceDataDecl.SetSize(n_min(2 + LightIdxVectorCount, 10));
}
else
{
// Only vertex shader data will be added
InstanceDataDecl.SetSize(2);
}
// Patch offset and scale in XZ
CVertexComponent* pCmp = &InstanceDataDecl[0];
pCmp->Semantic = VCSem_TexCoord;
pCmp->UserDefinedName = NULL;
pCmp->Index = 0;
pCmp->Format = VCFmt_Float32_4;
pCmp->Stream = INSTANCE_BUFFER_STREAM_INDEX;
pCmp->OffsetInVertex = DEM_VERTEX_COMPONENT_OFFSET_DEFAULT;
pCmp->PerInstanceData = true;
// Morph constants
pCmp = &InstanceDataDecl[1];
pCmp->Semantic = VCSem_TexCoord;
pCmp->UserDefinedName = NULL;
pCmp->Index = 1;
pCmp->Format = VCFmt_Float32_2;
pCmp->Stream = INSTANCE_BUFFER_STREAM_INDEX;
pCmp->OffsetInVertex = DEM_VERTEX_COMPONENT_OFFSET_DEFAULT;
pCmp->PerInstanceData = true;
// Light indices
UPTR ElementIdx = 2;
while (ElementIdx < InstanceDataDecl.GetCount())
{
pCmp = &InstanceDataDecl[ElementIdx];
pCmp->Semantic = VCSem_TexCoord;
pCmp->UserDefinedName = NULL;
pCmp->Index = ElementIdx;
pCmp->Format = VCFmt_SInt16_4;
pCmp->Stream = INSTANCE_BUFFER_STREAM_INDEX;
pCmp->OffsetInVertex = DEM_VERTEX_COMPONENT_OFFSET_DEFAULT;
pCmp->PerInstanceData = true;
++ElementIdx;
}
OK;
}
//---------------------------------------------------------------------
bool CTerrainRenderer::CheckNodeSphereIntersection(const CLightTestArgs& Args, const sphere& Sphere, U32 X, U32 Z, U32 LOD, UPTR& AABBTestCounter)
{
I16 MinY, MaxY;
Args.pCDLOD->GetMinMaxHeight(X, Z, LOD, MinY, MaxY);
// Node has no data, can't intersect with it
if (MaxY < MinY) FAIL;
U32 NodeSize = Args.pCDLOD->GetPatchSize() << LOD;
float ScaleX = NodeSize * Args.ScaleBaseX;
float ScaleZ = NodeSize * Args.ScaleBaseZ;
float NodeMinX = Args.AABBMinX + X * ScaleX;
float NodeMinZ = Args.AABBMinZ + Z * ScaleZ;
CAABB NodeAABB;
NodeAABB.Min.x = NodeMinX;
NodeAABB.Min.y = MinY * Args.pCDLOD->GetVerticalScale();
NodeAABB.Min.z = NodeMinZ;
NodeAABB.Max.x = NodeMinX + ScaleX;
NodeAABB.Max.y = MaxY * Args.pCDLOD->GetVerticalScale();
NodeAABB.Max.z = NodeMinZ + ScaleZ;
if (Sphere.GetClipStatus(NodeAABB) == Outside) FAIL;
// Leaf node reached
if (LOD == 0) OK;
++AABBTestCounter;
if (AABBTestCounter >= LIGHT_INTERSECTION_COARSE_TEST_MAX_AABBS) OK;
const U32 XNext = X << 1, ZNext = Z << 1, NextLOD = LOD - 1;
if (CheckNodeSphereIntersection(Args, Sphere, XNext, ZNext, NextLOD, AABBTestCounter)) OK;
if (Args.pCDLOD->HasNode(XNext + 1, ZNext, NextLOD) && CheckNodeSphereIntersection(Args, Sphere, XNext + 1, ZNext, NextLOD, AABBTestCounter)) OK;
if (Args.pCDLOD->HasNode(XNext, ZNext + 1, NextLOD) && CheckNodeSphereIntersection(Args, Sphere, XNext, ZNext + 1, NextLOD, AABBTestCounter)) OK;
if (Args.pCDLOD->HasNode(XNext + 1, ZNext + 1, NextLOD) && CheckNodeSphereIntersection(Args, Sphere, XNext + 1, ZNext + 1, NextLOD, AABBTestCounter)) OK;
// No child node touches the volume
FAIL;
}
//---------------------------------------------------------------------
bool CTerrainRenderer::CheckNodeFrustumIntersection(const CLightTestArgs& Args, const matrix44& Frustum, U32 X, U32 Z, U32 LOD, UPTR& AABBTestCounter)
{
I16 MinY, MaxY;
Args.pCDLOD->GetMinMaxHeight(X, Z, LOD, MinY, MaxY);
// Node has no data, can't intersect with it
if (MaxY < MinY) FAIL;
U32 NodeSize = Args.pCDLOD->GetPatchSize() << LOD;
float ScaleX = NodeSize * Args.ScaleBaseX;
float ScaleZ = NodeSize * Args.ScaleBaseZ;
float NodeMinX = Args.AABBMinX + X * ScaleX;
float NodeMinZ = Args.AABBMinZ + Z * ScaleZ;
CAABB NodeAABB;
NodeAABB.Min.x = NodeMinX;
NodeAABB.Min.y = MinY * Args.pCDLOD->GetVerticalScale();
NodeAABB.Min.z = NodeMinZ;
NodeAABB.Max.x = NodeMinX + ScaleX;
NodeAABB.Max.y = MaxY * Args.pCDLOD->GetVerticalScale();
NodeAABB.Max.z = NodeMinZ + ScaleZ;
if (NodeAABB.GetClipStatus(Frustum) == Outside) FAIL;
// Leaf node reached
if (LOD == 0) OK;
++AABBTestCounter;
if (AABBTestCounter >= LIGHT_INTERSECTION_COARSE_TEST_MAX_AABBS) OK;
const U32 XNext = X << 1, ZNext = Z << 1, NextLOD = LOD - 1;
if (CheckNodeFrustumIntersection(Args, Frustum, XNext, ZNext, NextLOD, AABBTestCounter)) OK;
if (Args.pCDLOD->HasNode(XNext + 1, ZNext, NextLOD) && CheckNodeFrustumIntersection(Args, Frustum, XNext + 1, ZNext, NextLOD, AABBTestCounter)) OK;
if (Args.pCDLOD->HasNode(XNext, ZNext + 1, NextLOD) && CheckNodeFrustumIntersection(Args, Frustum, XNext, ZNext + 1, NextLOD, AABBTestCounter)) OK;
if (Args.pCDLOD->HasNode(XNext + 1, ZNext + 1, NextLOD) && CheckNodeFrustumIntersection(Args, Frustum, XNext + 1, ZNext + 1, NextLOD, AABBTestCounter)) OK;
// No child node touches the volume
FAIL;
}
//---------------------------------------------------------------------
bool CTerrainRenderer::PrepareNode(CRenderNode& Node, const CRenderNodeContext& Context)
{
CTerrain* pTerrain = Node.pRenderable->As<CTerrain>();
n_assert_dbg(pTerrain);
CMaterial* pMaterial = pTerrain->GetMaterial(); //!!!Get by MaterialLOD!
if (!pMaterial) FAIL;
CEffect* pEffect = pMaterial->GetEffect();
EEffectType EffType = pEffect->GetType();
if (Context.pEffectOverrides)
for (UPTR i = 0; i < Context.pEffectOverrides->GetCount(); ++i)
if (Context.pEffectOverrides->KeyAt(i) == EffType)
{
pEffect = Context.pEffectOverrides->ValueAt(i).GetUnsafe();
break;
}
if (!pEffect) FAIL;
Node.pMaterial = pMaterial;
Node.pEffect = pEffect;
Node.pTech = pEffect->GetTechByInputSet(InputSet_CDLOD);
if (!Node.pTech) FAIL;
Node.pMesh = pTerrain->GetPatchMesh();
Node.pGroup = pTerrain->GetPatchMesh()->GetGroup(0, 0); // For sorting, different terrain objects with the same mesh will be rendered sequentially
U8 LightCount = 0;
// Collect all lights that potentially touch the terrain, no limit here, limit is
// applied to the light count of a terrain patch instance.
if (Context.pLights)
{
n_assert_dbg(Context.pLightIndices);
const CCDLODData& CDLOD = *pTerrain->GetCDLODData();
const U32 TopPatchesW = CDLOD.GetTopPatchCountW();
const U32 TopPatchesH = CDLOD.GetTopPatchCountH();
const U32 TopLOD = CDLOD.GetLODCount() - 1;
float AABBMinX = Context.AABB.Min.x;
float AABBMinZ = Context.AABB.Min.z;
float AABBSizeX = Context.AABB.Max.x - AABBMinX;
float AABBSizeZ = Context.AABB.Max.z - AABBMinZ;
CLightTestArgs Args;
Args.pCDLOD = pTerrain->GetCDLODData();
Args.AABBMinX = AABBMinX;
Args.AABBMinZ = AABBMinZ;
Args.ScaleBaseX = AABBSizeX / (float)(pTerrain->GetCDLODData()->GetHeightMapWidth() - 1);
Args.ScaleBaseZ = AABBSizeZ / (float)(pTerrain->GetCDLODData()->GetHeightMapHeight() - 1);
CArray<U16>& LightIndices = *Context.pLightIndices;
Node.LightIndexBase = LightIndices.GetCount();
const CArray<CLightRecord>& Lights = *Context.pLights;
for (UPTR i = 0; i < Lights.GetCount(); ++i)
{
CLightRecord& LightRec = Lights[i];
const CLight* pLight = LightRec.pLight;
switch (pLight->Type)
{
case Light_Point:
{
//!!!???avoid object creation, rewrite functions so that testing against vector + float is possible!?
sphere LightBounds(LightRec.Transform.Translation(), pLight->GetRange());
if (LightBounds.GetClipStatus(Context.AABB) == Outside) continue;
// Perform coarse test on quadtree
if (LIGHT_INTERSECTION_COARSE_TEST_MAX_AABBS > 1)
{
bool Intersects = false;
UPTR AABBTestCounter = 1;
for (U32 Z = 0; Z < TopPatchesH; ++Z)
{
for (U32 X = 0; X < TopPatchesW; ++X)
if (CheckNodeSphereIntersection(Args, LightBounds, X, Z, TopLOD, AABBTestCounter))
{
Intersects = true;
break;
}
if (Intersects) break;
}
if (!Intersects) continue;
}
break;
}
case Light_Spot:
{
//!!!???PERF: test against sphere before?!
//???cache GlobalFrustum in a light record?
matrix44 LocalFrustum;
pLight->CalcLocalFrustum(LocalFrustum);
matrix44 GlobalFrustum;
LightRec.Transform.invert_simple(GlobalFrustum);
GlobalFrustum *= LocalFrustum;
if (Context.AABB.GetClipStatus(GlobalFrustum) == Outside) continue;
// Perform coarse test on quadtree
if (LIGHT_INTERSECTION_COARSE_TEST_MAX_AABBS > 1)
{
bool Intersects = false;
UPTR AABBTestCounter = 1;
for (U32 Z = 0; Z < TopPatchesH; ++Z)
{
for (U32 X = 0; X < TopPatchesW; ++X)
if (CheckNodeFrustumIntersection(Args, GlobalFrustum, X, Z, TopLOD, AABBTestCounter))
{
Intersects = true;
break;
}
if (Intersects) break;
}
if (!Intersects) continue;
}
break;
}
}
LightIndices.Add(i);
++LightCount;
++LightRec.UseCount;
}
}
Node.LightCount = LightCount;
OK;
}
//---------------------------------------------------------------------
void CTerrainRenderer::FillNodeLightIndices(const CProcessTerrainNodeArgs& Args, CPatchInstance& Patch, const CAABB& NodeAABB, U8& MaxLightCount)
{
n_assert_dbg(Args.pRenderContext->pLightIndices);
const CArray<U16>& LightIndices = *Args.pRenderContext->pLightIndices;
UPTR LightCount = 0;
const CArray<CLightRecord>& Lights = *Args.pRenderContext->pLights;
for (UPTR i = 0; i < Args.LightCount; ++i)
{
CLightRecord& LightRec = Lights[i];
const CLight* pLight = LightRec.pLight;
switch (pLight->Type)
{
case Light_Point:
{
//!!!???avoid object creation, rewrite functions so that testing against vector + float is possible!?
sphere LightBounds(LightRec.Transform.Translation(), pLight->GetRange());
if (LightBounds.GetClipStatus(NodeAABB) == Outside) continue;
break;
}
case Light_Spot:
{
//!!!???PERF: test against sphere before?!
//???cache GlobalFrustum in a light record?
matrix44 LocalFrustum;
pLight->CalcLocalFrustum(LocalFrustum);
matrix44 GlobalFrustum;
LightRec.Transform.invert_simple(GlobalFrustum);
GlobalFrustum *= LocalFrustum;
if (NodeAABB.GetClipStatus(GlobalFrustum) == Outside) continue;
break;
}
}
// Don't want to calculate priorities, just skip all remaining lights (for simplicity, may rework later)
if (LightCount >= INSTANCE_MAX_LIGHT_COUNT) break;
Patch.LightIndex[LightCount] = LightRec.GPULightIndex;
++LightCount;
}
if (LightCount < INSTANCE_MAX_LIGHT_COUNT)
Patch.LightIndex[LightCount] = -1;
if (MaxLightCount < LightCount)
MaxLightCount = LightCount;
}
//---------------------------------------------------------------------
//!!!recalculation required only on viewer's position / look vector change!
CTerrainRenderer::ENodeStatus CTerrainRenderer::ProcessTerrainNode(const CProcessTerrainNodeArgs& Args,
U32 X, U32 Z, U32 LOD, float LODRange,
U32& PatchCount, U32& QPatchCount,
U8& MaxLightCount, EClipStatus Clip)
{
const CCDLODData* pCDLOD = Args.pCDLOD;
I16 MinY, MaxY;
pCDLOD->GetMinMaxHeight(X, Z, LOD, MinY, MaxY);
// Node has no data, skip it completely
if (MaxY < MinY) return Node_Invisible;
U32 NodeSize = pCDLOD->GetPatchSize() << LOD;
float ScaleX = NodeSize * Args.ScaleBaseX;
float ScaleZ = NodeSize * Args.ScaleBaseZ;
float NodeMinX = Args.AABBMinX + X * ScaleX;
float NodeMinZ = Args.AABBMinZ + Z * ScaleZ;
CAABB NodeAABB;
NodeAABB.Min.x = NodeMinX;
NodeAABB.Min.y = MinY * pCDLOD->GetVerticalScale();
NodeAABB.Min.z = NodeMinZ;
NodeAABB.Max.x = NodeMinX + ScaleX;
NodeAABB.Max.y = MaxY * pCDLOD->GetVerticalScale();
NodeAABB.Max.z = NodeMinZ + ScaleZ;
if (Clip == Clipped)
{
// NB: Visibility is tested for the current camera, NOT always for the main
Clip = NodeAABB.GetClipStatus(Args.pRenderContext->ViewProjection);
if (Clip == Outside) return Node_Invisible;
}
// NB: Always must check the main frame camera, even if some special camera is used for intermediate rendering
sphere LODSphere(Args.pRenderContext->CameraPosition, LODRange);
if (LODSphere.GetClipStatus(NodeAABB) == Outside) return Node_NotInLOD;
// Bits 0 to 3 - if set, add quarterpatch for child[0 .. 3]
U8 ChildFlags = 0;
enum
{
Child_TopLeft = 0x01,
Child_TopRight = 0x02,
Child_BottomLeft = 0x04,
Child_BottomRight = 0x08,
Child_All = (Child_TopLeft | Child_TopRight | Child_BottomLeft | Child_BottomRight)
};
bool IsVisible;
if (LOD > 0)
{
// Hack, see original CDLOD code. LOD 0 range is 0.9 of what is expected.
float NextLODRange = LODRange * ((LOD == 1) ? 0.45f : 0.5f);
IsVisible = false;
// NB: Always must check the main frame camera, even if some special camera is used for intermediate rendering
LODSphere.r = NextLODRange;
if (LODSphere.GetClipStatus(NodeAABB) == Outside)
{
// Add the whole node to the current LOD
ChildFlags = Child_All;
}
else
{
const U32 XNext = X << 1, ZNext = Z << 1, NextLOD = LOD - 1;
ENodeStatus Status = ProcessTerrainNode(Args, XNext, ZNext, NextLOD, NextLODRange, PatchCount, QPatchCount, MaxLightCount, Clip);
if (Status != Node_Invisible)
{
IsVisible = true;
if (Status == Node_NotInLOD) ChildFlags |= Child_TopLeft;
}
if (pCDLOD->HasNode(XNext + 1, ZNext, NextLOD))
{
Status = ProcessTerrainNode(Args, XNext + 1, ZNext, NextLOD, NextLODRange, PatchCount, QPatchCount, MaxLightCount, Clip);
if (Status != Node_Invisible)
{
IsVisible = true;
if (Status == Node_NotInLOD) ChildFlags |= Child_TopRight;
}
}
if (pCDLOD->HasNode(XNext, ZNext + 1, NextLOD))
{
Status = ProcessTerrainNode(Args, XNext, ZNext + 1, NextLOD, NextLODRange, PatchCount, QPatchCount, MaxLightCount, Clip);
if (Status != Node_Invisible)
{
IsVisible = true;
if (Status == Node_NotInLOD) ChildFlags |= Child_BottomLeft;
}
}
if (pCDLOD->HasNode(XNext + 1, ZNext + 1, NextLOD))
{
Status = ProcessTerrainNode(Args, XNext + 1, ZNext + 1, NextLOD, NextLODRange, PatchCount, QPatchCount, MaxLightCount, Clip);
if (Status != Node_Invisible)
{
IsVisible = true;
if (Status == Node_NotInLOD) ChildFlags |= Child_BottomRight;
}
}
}
if (!ChildFlags) return IsVisible ? Node_Processed : Node_Invisible;
}
else
{
ChildFlags = Child_All;
IsVisible = true;
}
const bool LightingEnabled = (Args.pRenderContext->pLights != NULL);
float* pLODMorphConsts = Args.pMorphConsts + 2 * LOD;
if (ChildFlags == Child_All)
{
// Add whole patch
n_assert(PatchCount + QPatchCount < Args.MaxInstanceCount);
CPatchInstance& Patch = Args.pInstances[PatchCount];
Patch.ScaleOffset[0] = NodeAABB.Max.x - NodeAABB.Min.x;
Patch.ScaleOffset[1] = NodeAABB.Max.z - NodeAABB.Min.z;
Patch.ScaleOffset[2] = NodeAABB.Min.x;
Patch.ScaleOffset[3] = NodeAABB.Min.z;
Patch.MorphConsts[0] = pLODMorphConsts[0];
Patch.MorphConsts[1] = pLODMorphConsts[1];
if (LightingEnabled && INSTANCE_MAX_LIGHT_COUNT)
FillNodeLightIndices(Args, Patch, NodeAABB, MaxLightCount);
++PatchCount;
}
else
{
// Add quarterpatches
float NodeMinX = NodeAABB.Min.x;
float NodeMinZ = NodeAABB.Min.z;
float ScaleX = (NodeAABB.Max.x - NodeAABB.Min.x);
float ScaleZ = (NodeAABB.Max.z - NodeAABB.Min.z);
float HalfScaleX = ScaleX * 0.5f;
float HalfScaleZ = ScaleZ * 0.5f;
// For lighting. We don't request minmax Y for quarterpatches, but we could.
CAABB QuarterNodeAABB;
QuarterNodeAABB.Min.y = NodeAABB.Min.y;
QuarterNodeAABB.Max.y = NodeAABB.Max.y;
if (ChildFlags & Child_TopLeft)
{
n_assert(PatchCount + QPatchCount < Args.MaxInstanceCount);
CPatchInstance& Patch = Args.pInstances[Args.MaxInstanceCount - QPatchCount - 1];
Patch.ScaleOffset[0] = HalfScaleX;
Patch.ScaleOffset[1] = HalfScaleZ;
Patch.ScaleOffset[2] = NodeMinX;
Patch.ScaleOffset[3] = NodeMinZ;
Patch.MorphConsts[0] = pLODMorphConsts[0];
Patch.MorphConsts[1] = pLODMorphConsts[1];
if (LightingEnabled && INSTANCE_MAX_LIGHT_COUNT)
{
QuarterNodeAABB.Min.x = NodeMinX;
QuarterNodeAABB.Min.z = NodeMinZ;
QuarterNodeAABB.Max.x = NodeMinX + HalfScaleX;
QuarterNodeAABB.Max.z = NodeMinZ + HalfScaleZ;
FillNodeLightIndices(Args, Patch, QuarterNodeAABB, MaxLightCount);
}
++QPatchCount;
}
if (ChildFlags & Child_TopRight)
{
n_assert(PatchCount + QPatchCount < Args.MaxInstanceCount);
CPatchInstance& Patch = Args.pInstances[Args.MaxInstanceCount - QPatchCount - 1];
Patch.ScaleOffset[0] = HalfScaleX;
Patch.ScaleOffset[1] = HalfScaleZ;
Patch.ScaleOffset[2] = NodeMinX + HalfScaleX;
Patch.ScaleOffset[3] = NodeMinZ;
Patch.MorphConsts[0] = pLODMorphConsts[0];
Patch.MorphConsts[1] = pLODMorphConsts[1];
if (LightingEnabled && INSTANCE_MAX_LIGHT_COUNT)
{
QuarterNodeAABB.Min.x = NodeMinX + HalfScaleX;
QuarterNodeAABB.Min.z = NodeMinZ;
QuarterNodeAABB.Max.x = NodeMinX + ScaleX;
QuarterNodeAABB.Max.z = NodeMinZ + HalfScaleZ;
FillNodeLightIndices(Args, Patch, QuarterNodeAABB, MaxLightCount);
}
++QPatchCount;
}
if (ChildFlags & Child_BottomLeft)
{
n_assert(PatchCount + QPatchCount < Args.MaxInstanceCount);
CPatchInstance& Patch = Args.pInstances[Args.MaxInstanceCount - QPatchCount - 1];
Patch.ScaleOffset[0] = HalfScaleX;
Patch.ScaleOffset[1] = HalfScaleZ;
Patch.ScaleOffset[2] = NodeMinX;
Patch.ScaleOffset[3] = NodeMinZ + HalfScaleZ;
Patch.MorphConsts[0] = pLODMorphConsts[0];
Patch.MorphConsts[1] = pLODMorphConsts[1];
if (LightingEnabled && INSTANCE_MAX_LIGHT_COUNT)
{
QuarterNodeAABB.Min.x = NodeMinX;
QuarterNodeAABB.Min.z = NodeMinZ + HalfScaleZ;
QuarterNodeAABB.Max.x = NodeMinX + HalfScaleX;
QuarterNodeAABB.Max.z = NodeMinZ + ScaleZ;
FillNodeLightIndices(Args, Patch, QuarterNodeAABB, MaxLightCount);
}
++QPatchCount;
}
if (ChildFlags & Child_BottomRight)
{
n_assert(PatchCount + QPatchCount < Args.MaxInstanceCount);
CPatchInstance& Patch = Args.pInstances[Args.MaxInstanceCount - QPatchCount - 1];
Patch.ScaleOffset[0] = HalfScaleX;
Patch.ScaleOffset[1] = HalfScaleZ;
Patch.ScaleOffset[2] = NodeMinX + HalfScaleX;
Patch.ScaleOffset[3] = NodeMinZ + HalfScaleZ;
Patch.MorphConsts[0] = pLODMorphConsts[0];
Patch.MorphConsts[1] = pLODMorphConsts[1];
if (LightingEnabled && INSTANCE_MAX_LIGHT_COUNT)
{
QuarterNodeAABB.Min.x = NodeMinX + HalfScaleX;
QuarterNodeAABB.Min.z = NodeMinZ + HalfScaleZ;
QuarterNodeAABB.Max.x = NodeMinX + ScaleX;
QuarterNodeAABB.Max.z = NodeMinZ + ScaleZ;
FillNodeLightIndices(Args, Patch, QuarterNodeAABB, MaxLightCount);
}
++QPatchCount;
}
}
// Morphing artifacts test (from the original CDLOD code)
/*
#ifdef _DEBUG
if (LOD < Terrain.GetLODCount() - 1)
{
//!!!Always must check the Main camera!
float MaxDistToCameraSq = NodeAABB.MaxDistFromPointSq(RenderSrv->GetCameraPosition());
float MorphStart = MorphConsts[LOD + 1].Start;
if (MaxDistToCameraSq > MorphStart * MorphStart)
Sys::Error("Visibility distance is too small!");
}
#endif
*/
return Node_Processed;
}
//---------------------------------------------------------------------
CArray<CRenderNode*>::CIterator CTerrainRenderer::Render(const CRenderContext& Context, CArray<CRenderNode*>& RenderQueue, CArray<CRenderNode*>::CIterator ItCurr)
{
CGPUDriver& GPU = *Context.pGPU;
CArray<CRenderNode*>::CIterator ItEnd = RenderQueue.End();
if (!GPU.CheckCaps(Caps_VSTexFiltering_Linear))
{
// Skip terrain rendering. Can fall back to manual 4-sample filtering in a shader instead.
while (ItCurr != ItEnd)
{
if ((*ItCurr)->pRenderer != this) return ItCurr;
++ItCurr;
}
return ItEnd;
}
const CMaterial* pCurrMaterial = NULL;
const CTechnique* pCurrTech = NULL;
const CEffectConstant* pConstVSCDLODParams = NULL;
const CEffectConstant* pConstPSCDLODParams = NULL;
const CEffectConstant* pConstGridConsts = NULL;
const CEffectConstant* pConstInstanceDataVS = NULL;
const CEffectConstant* pConstInstanceDataPS = NULL;
const CEffectResource* pResourceHeightMap = NULL;
const bool LightingEnabled = (Context.pLights != NULL);
if (HMSampler.IsNullPtr()) HMSampler = GPU.CreateSampler(HMSamplerDesc);
while (ItCurr != ItEnd)
{
CRenderNode* pRenderNode = *ItCurr;
if (pRenderNode->pRenderer != this) return ItCurr;
CTerrain* pTerrain = pRenderNode->pRenderable->As<CTerrain>();
const float VisibilityRange = 1000.f;
const float MorphStartRatio = 0.7f;
const CCDLODData* pCDLOD = pTerrain->GetCDLODData();
U32 LODCount = pCDLOD->GetLODCount();
// Calculate morph constants
//!!!PERF: may recalculate only when LODCount / VisibilityRange changes!
float MorphStart = 0.f;
float CurrVisRange = VisibilityRange / (float)(1 << (LODCount - 1));
float* pMorphConsts = (float*)_malloca(sizeof(float) * 2 * LODCount);
float* pCurrMorphConst = pMorphConsts;
for (U32 j = 0; j < LODCount; ++j)
{
float MorphEnd = j ? CurrVisRange : CurrVisRange * 0.9f;
MorphStart = MorphStart + (MorphEnd - MorphStart) * MorphStartRatio;
MorphEnd = n_lerp(MorphEnd, MorphStart, 0.01f);
float MorphConst2 = 1.0f / (MorphEnd - MorphStart);
*pCurrMorphConst++ = MorphEnd * MorphConst2;
*pCurrMorphConst++ = MorphConst2;
CurrVisRange *= 2.f;
}
// Fill instance data with patches and quarter-patches to render
U32 PatchCount = 0, QuarterPatchCount = 0;
//!!!PERF: for D3D11 const instancing can create CB without a RAM copy and update whole!
if (!pInstances)
{
pInstances = (CPatchInstance*)n_malloc_aligned(sizeof(CPatchInstance) * MaxInstanceCount, 16);
n_assert_dbg(pInstances);
}
CAABB AABB;
n_verify_dbg(pTerrain->GetLocalAABB(AABB, 0));
AABB.Transform(pRenderNode->Transform);
float AABBMinX = AABB.Min.x;
float AABBMinZ = AABB.Min.z;
float AABBSizeX = AABB.Max.x - AABBMinX;
float AABBSizeZ = AABB.Max.z - AABBMinZ;
CProcessTerrainNodeArgs Args;
Args.pCDLOD = pTerrain->GetCDLODData();
Args.pInstances = pInstances;
Args.pMorphConsts = pMorphConsts;
Args.pRenderContext = &Context;
Args.MaxInstanceCount = MaxInstanceCount;
Args.AABBMinX = AABBMinX;
Args.AABBMinZ = AABBMinZ;
Args.ScaleBaseX = AABBSizeX / (float)(pCDLOD->GetHeightMapWidth() - 1);
Args.ScaleBaseZ = AABBSizeZ / (float)(pCDLOD->GetHeightMapHeight() - 1);
Args.LightIndexBase = pRenderNode->LightIndexBase;
Args.LightCount = pRenderNode->LightCount;
U8 MaxLightCount = 0;
const U32 TopPatchesW = pCDLOD->GetTopPatchCountW();
const U32 TopPatchesH = pCDLOD->GetTopPatchCountH();
const U32 TopLOD = LODCount - 1;
for (U32 Z = 0; Z < TopPatchesH; ++Z)
for (U32 X = 0; X < TopPatchesW; ++X)
ProcessTerrainNode(Args, X, Z, TopLOD, VisibilityRange, PatchCount, QuarterPatchCount, MaxLightCount);
// Since we allocate instance stream based on maximum light count, we never reallocate it when frame max light count
// drops compared to the previous frame, to avoid per-frame VB recreation. Instead we remember the biggest light
// count ever requested, allocate VB for it, and live without VB reallocations until more lights are required.
// The first unused light index is always equal -1 so no matter how much lights are, all unused ones are ignored.
// For constant instancing this value never gets used, tech with LightCount = 0 is always selected.
if (CurrMaxLightCount > MaxLightCount) MaxLightCount = CurrMaxLightCount;
_freea(pMorphConsts);
if (!PatchCount && !QuarterPatchCount)
{
++ItCurr;
continue;
}
// Sort patches
// We sort by LOD (the more is scale, the coarser is LOD), and therefore we
// almost sort by distance to the camera, as LOD depends solely on it.
struct CPatchInstanceCmp
{
inline bool operator()(const CPatchInstance& a, const CPatchInstance& b) const
{
return a.ScaleOffset[0] < b.ScaleOffset[0];
}
};
if (PatchCount)
std::sort(pInstances, pInstances + PatchCount, CPatchInstanceCmp());
if (QuarterPatchCount)
std::sort(pInstances + MaxInstanceCount - QuarterPatchCount, pInstances + MaxInstanceCount, CPatchInstanceCmp());
// Select tech for the maximal light count used per-patch
UPTR LightCount = MaxLightCount;
const CTechnique* pTech = pRenderNode->pTech;
const CPassList* pPasses = pTech->GetPasses(LightCount);
n_assert_dbg(pPasses); // To test if it could happen at all
if (!pPasses)
{
++ItCurr;
continue;
}
if (LightingEnabled)
{
if (CurrMaxLightCount < LightCount) CurrMaxLightCount = LightCount;
if (!Context.UsesGlobalLightBuffer)
{
NOT_IMPLEMENTED;
}
}
// Apply material, if changed
const CMaterial* pMaterial = pRenderNode->pMaterial;
if (pMaterial != pCurrMaterial)
{
n_assert_dbg(pMaterial);
n_verify_dbg(pMaterial->Apply(GPU));
pCurrMaterial = pMaterial;
}
// Pass tech params to GPU
if (pTech != pCurrTech)
{
pCurrTech = pTech;
pConstVSCDLODParams = pTech->GetConstant(CStrID("VSCDLODParams"));
pConstPSCDLODParams = pTech->GetConstant(CStrID("PSCDLODParams"));
pConstGridConsts = pTech->GetConstant(CStrID("GridConsts"));
pConstInstanceDataVS = pTech->GetConstant(CStrID("InstanceDataVS"));
pConstInstanceDataPS = pTech->GetConstant(CStrID("InstanceDataPS"));
pResourceHeightMap = pTech->GetResource(CStrID("HeightMapVS"));
//???normal map?! now in material, must not be there!
const CEffectSampler* pVSLinearSampler = pTech->GetSampler(CStrID("VSLinearSampler"));
if (pVSLinearSampler)
GPU.BindSampler(pVSLinearSampler->ShaderType, pVSLinearSampler->Handle, HMSampler.GetUnsafe());
}
if (pResourceHeightMap)
GPU.BindResource(pResourceHeightMap->ShaderType, pResourceHeightMap->Handle, pCDLOD->GetHeightMap());
CConstantBufferSet PerInstanceBuffers;
PerInstanceBuffers.SetGPU(&GPU);
if (pConstVSCDLODParams)
{
struct
{
float WorldToHM[4];
float TerrainYScale;
float TerrainYOffset;
float InvSplatSizeX;
float InvSplatSizeZ;
float TexelSize[2];
//float TextureSize[2]; // For manual bilinear filtering in VS
} CDLODParams;
CDLODParams.WorldToHM[0] = 1.f / AABBSizeX;
CDLODParams.WorldToHM[1] = 1.f / AABBSizeZ;
CDLODParams.WorldToHM[2] = -AABBMinX * CDLODParams.WorldToHM[0];
CDLODParams.WorldToHM[3] = -AABBMinZ * CDLODParams.WorldToHM[1];
CDLODParams.TerrainYScale = 65535.f * pCDLOD->GetVerticalScale();
CDLODParams.TerrainYOffset = -32767.f * pCDLOD->GetVerticalScale() + pRenderNode->Transform.m[3][1]; // [3][1] = Translation.y
CDLODParams.InvSplatSizeX = pTerrain->GetInvSplatSizeX();
CDLODParams.InvSplatSizeZ = pTerrain->GetInvSplatSizeZ();
CDLODParams.TexelSize[0] = 1.f / (float)pCDLOD->GetHeightMapWidth();
CDLODParams.TexelSize[1] = 1.f / (float)pCDLOD->GetHeightMapHeight();
CConstantBuffer* pCB = PerInstanceBuffers.RequestBuffer(pConstVSCDLODParams->Const->GetConstantBufferHandle(), pConstVSCDLODParams->ShaderType);
pConstVSCDLODParams->Const->SetRawValue(*pCB, &CDLODParams, sizeof(CDLODParams));
if (pConstPSCDLODParams)
{
CConstantBuffer* pCB = PerInstanceBuffers.RequestBuffer(pConstPSCDLODParams->Const->GetConstantBufferHandle(), pConstPSCDLODParams->ShaderType);
pConstPSCDLODParams->Const->SetRawValue(*pCB, CDLODParams.WorldToHM, sizeof(float) * 4);
}
}
//!!!implement looping if instance buffer is too small!
if (pConstInstanceDataVS)
{
// For D3D11 constant instancing
NOT_IMPLEMENTED;
}
else
{
// Calculate int4 light index vector count supported by both tech and vertex declaration.
// Vertex declaration size will be 2 elements for VS data + one element per vector.
const UPTR LightVectorCount = (LightCount + 3) / 4;
const UPTR DeclSize = 2 + LightVectorCount;
n_assert_dbg(DeclSize <= InstanceDataDecl.GetCount());
// If current buffer doesn't suit the tech, recreate it. Since we only grow tech LightCount and never
// shrink it, buffer reallocation will be requested only if can't handle desired light count.
if (InstanceVB.IsNullPtr() || InstanceVB->GetVertexLayout()->GetComponentCount() != DeclSize)
{
PVertexLayout VLInstanceData = GPU.CreateVertexLayout(InstanceDataDecl.GetPtr(), DeclSize);
InstanceVB = NULL; // Drop before allocating new buffer
InstanceVB = GPU.CreateVertexBuffer(*VLInstanceData, MaxInstanceCount, Access_CPU_Write | Access_GPU_Read);
//!!!DBG TMP!
Sys::DbgOut("New terrain instance buffer allocated, %d vertex decl elements\n", DeclSize);
}
// Upload instance data to IA stream
//???what about D3D11_APPEND_ALIGNED_ELEMENT in D3D11 and float2?
const UPTR InstanceElementSize = InstanceVB->GetVertexLayout()->GetVertexSizeInBytes();
void* pInstData;
n_verify(GPU.MapResource(&pInstData, *InstanceVB, Map_WriteDiscard));
if (PatchCount)
{
UPTR InstDataSize = InstanceElementSize * PatchCount;
if (sizeof(CPatchInstance) == InstanceElementSize)
{
memcpy(pInstData, pInstances, InstDataSize);
}
else
{
char* pCurrInstData = (char*)pInstData;
for (UPTR PatchIdx = 0; PatchIdx < PatchCount; ++PatchIdx)
{
memcpy(pCurrInstData, pInstances + PatchIdx, InstanceElementSize);
pCurrInstData += InstanceElementSize;
}
}
pInstData = (char*)pInstData + InstDataSize;
}
if (QuarterPatchCount)
{
const CPatchInstance* pQInstances = pInstances + MaxInstanceCount - QuarterPatchCount;
if (sizeof(CPatchInstance) == InstanceElementSize)
{
memcpy(pInstData, pQInstances, InstanceElementSize * QuarterPatchCount);
}
else
{
char* pCurrInstData = (char*)pInstData;
for (UPTR PatchIdx = 0; PatchIdx < QuarterPatchCount; ++PatchIdx)
{
memcpy(pCurrInstData, pQInstances + PatchIdx, InstanceElementSize);
pCurrInstData += InstanceElementSize;
}
}
}
GPU.UnmapResource(*InstanceVB);
}
// Set vertex layout
// In the real world we don't want to use differently laid out meshes
n_assert_dbg(pTerrain->GetPatchMesh()->GetVertexBuffer()->GetVertexLayout() == pTerrain->GetQuarterPatchMesh()->GetVertexBuffer()->GetVertexLayout());
const CMesh* pMesh = pTerrain->GetPatchMesh();
n_assert_dbg(pMesh);
CVertexBuffer* pVB = pMesh->GetVertexBuffer().GetUnsafe();
n_assert_dbg(pVB);
CVertexLayout* pVL = pVB->GetVertexLayout();
//!!!implement looping if instance buffer is too small!
if (pConstInstanceDataVS) GPU.SetVertexLayout(pVL);
else
{
IPTR VLIdx = InstancedLayouts.FindIndex(pVL);
if (VLIdx == INVALID_INDEX)
{
UPTR BaseComponentCount = pVL->GetComponentCount();
UPTR InstComponentCount = InstanceVB->GetVertexLayout()->GetComponentCount();
UPTR DescComponentCount = BaseComponentCount + InstComponentCount;
CVertexComponent* pInstancedDecl = (CVertexComponent*)_malloca(DescComponentCount * sizeof(CVertexComponent));
memcpy(pInstancedDecl, pVL->GetComponent(0), BaseComponentCount * sizeof(CVertexComponent));
memcpy(pInstancedDecl + BaseComponentCount, InstanceDataDecl.GetPtr(), InstComponentCount * sizeof(CVertexComponent));
PVertexLayout VLInstanced = GPU.CreateVertexLayout(pInstancedDecl, DescComponentCount);
_freea(pInstancedDecl);
n_assert_dbg(VLInstanced.IsValidPtr());
InstancedLayouts.Add(pVL, VLInstanced);
GPU.SetVertexLayout(VLInstanced.GetUnsafe());
}
else GPU.SetVertexLayout(InstancedLayouts.ValueAt(VLIdx).GetUnsafe());
}
// Render patches //!!!may collect patches of different CTerrains if material is the same and instance buffer is big enough!
if (PatchCount)
{
if (pConstGridConsts)
{
float GridConsts[2];
GridConsts[0] = pCDLOD->GetPatchSize() * 0.5f;
GridConsts[1] = 1.f / GridConsts[0];
CConstantBuffer* pCB = PerInstanceBuffers.RequestBuffer(pConstGridConsts->Const->GetConstantBufferHandle(), pConstGridConsts->ShaderType);
pConstGridConsts->Const->SetRawValue(*pCB, &GridConsts, sizeof(GridConsts));
}
PerInstanceBuffers.CommitChanges();
GPU.SetVertexBuffer(0, pVB);
GPU.SetIndexBuffer(pMesh->GetIndexBuffer().GetUnsafe());
if (!pConstInstanceDataVS)
GPU.SetVertexBuffer(INSTANCE_BUFFER_STREAM_INDEX, InstanceVB.GetUnsafe(), 0);
const CPrimitiveGroup* pGroup = pMesh->GetGroup(0);
for (UPTR PassIdx = 0; PassIdx < pPasses->GetCount(); ++PassIdx)
{
GPU.SetRenderState((*pPasses)[PassIdx]);
GPU.DrawInstanced(*pGroup, PatchCount);
}
}
if (QuarterPatchCount)
{
if (pConstGridConsts)
{
float GridConsts[2];
GridConsts[0] = pCDLOD->GetPatchSize() * 0.25f;
GridConsts[1] = 1.f / GridConsts[0];
CConstantBuffer* pCB = PerInstanceBuffers.RequestBuffer(pConstGridConsts->Const->GetConstantBufferHandle(), pConstGridConsts->ShaderType);
pConstGridConsts->Const->SetRawValue(*pCB, &GridConsts, sizeof(GridConsts));
}
PerInstanceBuffers.CommitChanges();
pMesh = pTerrain->GetQuarterPatchMesh();
n_assert_dbg(pMesh);
pVB = pMesh->GetVertexBuffer().GetUnsafe();
n_assert_dbg(pVB);
GPU.SetVertexBuffer(0, pVB);
GPU.SetIndexBuffer(pMesh->GetIndexBuffer().GetUnsafe());
if (!pConstInstanceDataVS)
GPU.SetVertexBuffer(INSTANCE_BUFFER_STREAM_INDEX, InstanceVB.GetUnsafe(), PatchCount);
const CPrimitiveGroup* pGroup = pMesh->GetGroup(0);
for (UPTR PassIdx = 0; PassIdx < pPasses->GetCount(); ++PassIdx)
{
GPU.SetRenderState((*pPasses)[PassIdx]);
GPU.DrawInstanced(*pGroup, QuarterPatchCount);
}
}
++ItCurr;
};
return ItEnd;
}
//---------------------------------------------------------------------
} |
#include "net.h"
#include "masternodeconfig.h"
#include "util.h"
#include "ui_interface.h"
#include "chainparams.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
CMasternodeConfig masternodeConfig;
void CMasternodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex) {
CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex);
entries.push_back(cme);
}
bool CMasternodeConfig::read(std::string& strErr) {
int linenumber = 1;
boost::filesystem::path pathMasternodeConfigFile = GetMasternodeConfigFile();
boost::filesystem::ifstream streamConfig(pathMasternodeConfigFile);
LogPrintf("loading masternode file at %s\n", pathMasternodeConfigFile.c_str());
if (!streamConfig.good()) {
FILE* configFile = fopen(pathMasternodeConfigFile.string().c_str(), "a");
if (configFile != NULL) {
std::string strHeader = "# Masternode config file\n"
"# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n"
"# Example: mn1 127.0.0.2:19999 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n";
fwrite(strHeader.c_str(), std::strlen(strHeader.c_str()), 1, configFile);
fclose(configFile);
}
return true; // Nothing to read, so just return
}
for(std::string line; std::getline(streamConfig, line); linenumber++)
{
if(line.empty()) continue;
std::istringstream iss(line);
std::string comment, alias, ip, privKey, txHash, outputIndex;
if (iss >> comment) {
if(comment.at(0) == '#') continue;
iss.str(line);
iss.clear();
}
if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
iss.str(line);
iss.clear();
if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
strErr = _("Could not parse masternode.conf") + "\n" +
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"";
streamConfig.close();
return false;
}
}
int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort();
if(Params().NetworkIDString() == CBaseChainParams::MAIN) {
if(CService(ip).GetPort() != mainnetDefaultPort) {
strErr = _("Invalid port detected in masternode.conf") + "\n" +
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" +
strprintf(_("(must be %d for mainnet)"), mainnetDefaultPort);
streamConfig.close();
return false;
}
} else if(CService(ip).GetPort() == mainnetDefaultPort) {
strErr = _("Invalid port detected in masternode.conf") + "\n" +
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" +
strprintf(_("(%d could be used only on mainnet)"), mainnetDefaultPort);
streamConfig.close();
return false;
}
add(alias, ip, privKey, txHash, outputIndex);
}
streamConfig.close();
return true;
}
fix CMasternodeConfig::read()
#include "net.h"
#include "masternodeconfig.h"
#include "util.h"
#include "ui_interface.h"
#include "chainparams.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
CMasternodeConfig masternodeConfig;
void CMasternodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex) {
CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex);
entries.push_back(cme);
}
bool CMasternodeConfig::read(std::string& strErr) {
int linenumber = 1;
boost::filesystem::path pathMasternodeConfigFile = GetMasternodeConfigFile();
boost::filesystem::ifstream streamConfig(pathMasternodeConfigFile);
LogPrintf("loading masternode file at %s\n", pathMasternodeConfigFile.string());
if (!streamConfig.good()) {
FILE* configFile = fopen(pathMasternodeConfigFile.string().c_str(), "a");
if (configFile != NULL) {
std::string strHeader = "# Masternode config file\n"
"# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n"
"# Example: mn1 127.0.0.2:19999 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n";
fwrite(strHeader.c_str(), std::strlen(strHeader.c_str()), 1, configFile);
fclose(configFile);
}
return true; // Nothing to read, so just return
}
for(std::string line; std::getline(streamConfig, line); linenumber++)
{
if(line.empty()) continue;
std::istringstream iss(line);
std::string comment, alias, ip, privKey, txHash, outputIndex;
if (iss >> comment) {
if(comment.at(0) == '#') continue;
iss.str(line);
iss.clear();
}
if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
iss.str(line);
iss.clear();
if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
strErr = _("Could not parse masternode.conf") + "\n" +
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"";
streamConfig.close();
return false;
}
}
int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort();
if(Params().NetworkIDString() == CBaseChainParams::MAIN) {
if(CService(ip).GetPort() != mainnetDefaultPort) {
strErr = _("Invalid port detected in masternode.conf") + "\n" +
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" +
strprintf(_("(must be %d for mainnet)"), mainnetDefaultPort);
streamConfig.close();
return false;
}
} else if(CService(ip).GetPort() == mainnetDefaultPort) {
strErr = _("Invalid port detected in masternode.conf") + "\n" +
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" +
strprintf(_("(%d could be used only on mainnet)"), mainnetDefaultPort);
streamConfig.close();
return false;
}
add(alias, ip, privKey, txHash, outputIndex);
}
streamConfig.close();
return true;
}
|
/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of mcompositor.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mcompositewindow.h"
#include "mcompwindowanimator.h"
#include "mcompositemanager.h"
#include "mcompositemanager_p.h"
#include "mtexturepixmapitem.h"
#include "mdecoratorframe.h"
#include "mcompositemanagerextension.h"
#include "mcompositewindowgroup.h"
#include <QX11Info>
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
#include <X11/Xatom.h>
int MCompositeWindow::window_transitioning = 0;
static QRectF fadeRect = QRectF();
MCompositeWindow::MCompositeWindow(Qt::HANDLE window,
MWindowPropertyCache *mpc,
QGraphicsItem *p)
: QGraphicsItem(p),
pc(mpc),
scalefrom(1),
scaleto(1),
scaled(false),
zval(1),
sent_ping_timestamp(0),
received_ping_timestamp(0),
blur(false),
iconified(false),
iconified_final(false),
iconify_state(NoIconifyState),
destroyed(false),
window_status(Normal),
need_decor(false),
window_obscured(-1),
is_transitioning(false),
pinging_enabled(false),
dimmed_effect(false),
waiting_for_damage(0),
win_id(window)
{
thumb_mode = false;
if (!mpc || (mpc && !mpc->is_valid)) {
is_valid = false;
anim = 0;
newly_mapped = false;
t_ping = 0;
window_visible = false;
return;
} else
is_valid = true;
anim = new MCompWindowAnimator(this);
connect(anim, SIGNAL(transitionDone()), SLOT(finalizeState()));
connect(anim, SIGNAL(transitionStart()), SLOT(beginAnimation()));
connect(mpc, SIGNAL(iconGeometryUpdated()), SLOT(updateIconGeometry()));
setAcceptHoverEvents(true);
t_ping = new QTimer(this);
connect(t_ping, SIGNAL(timeout()), SLOT(pingTimeout()));
t_reappear = new QTimer(this);
connect(t_reappear, SIGNAL(timeout()), SLOT(reappearTimeout()));
damage_timer = new QTimer(this);
damage_timer->setSingleShot(true);
connect(damage_timer, SIGNAL(timeout()), SLOT(damageTimeout()));
MCompAtoms* atoms = MCompAtoms::instance();
if (pc->windowType() == MCompAtoms::NORMAL)
pc->setWindowTypeAtom(ATOM(_NET_WM_WINDOW_TYPE_NORMAL));
else
pc->setWindowTypeAtom(atoms->getType(window));
// needed before calling isAppWindow()
QVector<Atom> states = atoms->getAtomArray(window, ATOM(_NET_WM_STATE));
pc->setNetWmState(states.toList());
// Newly-mapped non-decorated application windows are not initially
// visible to prevent flickering when animation is started.
// We initially prevent item visibility from compositor itself
// or it's corresponding thumbnail rendered by the switcher
bool is_app = isAppWindow();
newly_mapped = is_app;
if (!pc->isInputOnly()) {
// never paint InputOnly windows
window_visible = !is_app;
setVisible(window_visible); // newly_mapped used here
}
origPosition = QPointF(pc->realGeometry().x(), pc->realGeometry().y());
if (fadeRect.isEmpty()) {
QRectF d = QApplication::desktop()->availableGeometry();
fadeRect.setWidth(d.width()/2);
fadeRect.setHeight(d.height()/2);
fadeRect.moveTo(fadeRect.width()/2, fadeRect.height()/2);
}
}
MCompositeWindow::~MCompositeWindow()
{
MCompositeManager *p = (MCompositeManager *) qApp;
if (window() && (t_ping || t_reappear)) {
stopPing();
delete t_ping;
delete t_reappear;
t_ping = t_reappear = 0;
}
endAnimation();
anim = 0;
delete damage_timer;
if (pc) {
pc->damageTracking(false);
p->d->prop_caches.remove(window());
pc->deleteLater();
}
}
void MCompositeWindow::setBlurred(bool b)
{
blur = b;
update();
}
bool MCompositeWindow::blurred()
{
return blur;
}
void MCompositeWindow::saveState()
{
anim->saveState();
}
void MCompositeWindow::localSaveState()
{
anim->localSaveState();
}
// set the scale point to actual values
void MCompositeWindow::setScalePoint(qreal from, qreal to)
{
scalefrom = from;
scaleto = to;
}
void MCompositeWindow::setThumbMode(bool mode)
{
thumb_mode = mode;
}
/* This is a delayed animation. Actual animation is triggered
* when startTransition() is called
*/
void MCompositeWindow::iconify(const QRectF &icongeometry, bool defer)
{
if (iconify_state == ManualIconifyState) {
setIconified(true);
window_status = Normal;
return;
}
if (window_status != MCompositeWindow::Closing)
window_status = MCompositeWindow::Minimizing;
// Custom iconify handler
MCompositeManager *p = (MCompositeManager *) qApp;
QList<MCompositeManagerExtension*> evlist = p->d->m_extensions.values(MapNotify);
for (int i = 0; i < evlist.size(); ++i) {
if (evlist[i]->windowIconified(this, defer)) {
iconified = true;
window_status = Normal;
return;
}
}
this->iconGeometry = icongeometry;
if (!iconified)
origPosition = pos();
// horizontal and vert. scaling factors
qreal sx = iconGeometry.width() / boundingRect().width();
qreal sy = iconGeometry.height() / boundingRect().height();
anim->deferAnimation(defer);
anim->translateScale(qreal(1.0), qreal(1.0), sx, sy,
iconGeometry.topLeft());
iconified = true;
// do this to avoid stacking code disturbing Z values
beginAnimation();
}
void MCompositeWindow::setUntransformed()
{
endAnimation();
if (anim)
anim->stopAnimation(); // stop and restore the matrix
newly_mapped = false;
setVisible(true);
setOpacity(1.0);
setScale(1.0);
setScaled(false);
iconified = false;
}
void MCompositeWindow::setIconified(bool iconified)
{
iconified_final = iconified;
iconify_state = ManualIconifyState;
if (iconified && !anim->pendingAnimation())
emit itemIconified(this);
else if (!iconified && !anim->pendingAnimation())
iconify_state = NoIconifyState;
}
MCompositeWindow::IconifyState MCompositeWindow::iconifyState() const
{
return iconify_state;
}
void MCompositeWindow::setIconifyState(MCompositeWindow::IconifyState state)
{
iconify_state = state;
}
void MCompositeWindow::setWindowObscured(bool obscured, bool no_notify)
{
MCompositeManager *p = (MCompositeManager *) qApp;
short new_value = obscured ? 1 : 0;
if ((new_value == window_obscured && !newly_mapped)
|| (!obscured && p->displayOff()))
return;
window_obscured = new_value;
if (!no_notify) {
XVisibilityEvent c;
c.type = VisibilityNotify;
c.send_event = True;
c.window = window();
c.state = obscured ? VisibilityFullyObscured :
VisibilityUnobscured;
XSendEvent(QX11Info::display(), window(), true,
VisibilityChangeMask, (XEvent *)&c);
}
}
/*
* We ensure that ensure there are ALWAYS updated thumbnails in the
* switcher by letting switcher know in advance of the presence of this window.
* Delay the minimize animation until we receive an iconGeometry update from
* the switcher
*/
void MCompositeWindow::startTransition()
{
if (iconified) {
if (iconGeometry.isNull())
return;
setWindowObscured(true);
}
if (anim->pendingAnimation()) {
MCompositeWindow::setVisible(true);
anim->startAnimation();
anim->deferAnimation(false);
}
}
void MCompositeWindow::updateIconGeometry()
{
if (!pc)
return;
iconGeometry = pc->iconGeometry();
if (iconGeometry.isNull())
return;
// trigger transition the second time around and update animation values
if (iconified) {
qreal sx = iconGeometry.width() / boundingRect().width();
qreal sy = iconGeometry.height() / boundingRect().height();
anim->translateScale(qreal(1.0), qreal(1.0), sx, sy,
iconGeometry.topLeft());
startTransition();
}
}
// TODO: have an option of disabling the animation
void MCompositeWindow::restore(const QRectF &icongeometry, bool defer)
{
// Custom restore handler
MCompositeManager *p = (MCompositeManager *) qApp;
QList<MCompositeManagerExtension*> evlist = p->d->m_extensions.values(MapNotify);
for (int i = 0; i < evlist.size(); ++i) {
if (evlist[i]->windowRestored(this, defer)) {
iconified = false;
return;
}
}
if (icongeometry.isEmpty())
this->iconGeometry = fadeRect;
else
this->iconGeometry = icongeometry;
setPos(iconGeometry.topLeft());
// horizontal and vert. scaling factors
qreal sx = iconGeometry.width() / boundingRect().width();
qreal sy = iconGeometry.height() / boundingRect().height();
setVisible(true);
anim->deferAnimation(defer);
anim->translateScale(qreal(1.0), qreal(1.0), sx, sy, origPosition, true);
iconified = false;
// do this to avoid stacking code disturbing Z values
beginAnimation();
}
bool MCompositeWindow::showWindow()
{
// defer putting this window in the _NET_CLIENT_LIST
// only after animation is done to prevent the switcher from rendering it
if (!isAppWindow() || !pc || !pc->is_valid
// isAppWindow() returns true for system dialogs
|| pc->windowTypeAtom() == ATOM(_NET_WM_WINDOW_TYPE_DIALOG))
return false;
findBehindWindow();
beginAnimation();
if (newly_mapped) {
// NB#180628 - some stupid apps are listening for visibilitynotifies.
// Well, all of the toolkit anyways
setWindowObscured(false);
// waiting for two damage events seems to work for Meegotouch apps
// at least, for the rest, there is a timeout
waiting_for_damage = 2;
damage_timer->start(500);
} else
q_fadeIn();
return true;
}
void MCompositeWindow::damageTimeout()
{
damageReceived(true);
}
void MCompositeWindow::damageReceived(bool timeout)
{
if (timeout || (waiting_for_damage > 0 && !--waiting_for_damage)) {
damage_timer->stop();
waiting_for_damage = 0;
q_fadeIn();
}
}
void MCompositeWindow::q_fadeIn()
{
endAnimation();
newly_mapped = false;
setVisible(true);
setOpacity(0.0);
updateWindowPixmap();
origPosition = pos();
newly_mapped = true;
// Custom fade-in handler
MCompositeManager *p = (MCompositeManager *) qApp;
QList<MCompositeManagerExtension*> evlist = p->d->m_extensions.values(MapNotify);
for (int i = 0; i < evlist.size(); ++i) {
if (evlist[i]->windowShown(this))
return;
}
setPos(fadeRect.topLeft());
restore(fadeRect, false);
}
void MCompositeWindow::closeWindowRequest()
{
if (!pc || !pc->is_valid || (!isMapped() && !pc->beingMapped()))
return;
if (!windowPixmap() && !pc->isInputOnly()) {
// get a Pixmap for the possible unmap animation
MCompositeManager *p = (MCompositeManager *) qApp;
if (!p->isCompositing())
p->d->enableCompositing(true);
updateWindowPixmap();
}
emit closeWindowRequest(this);
}
void MCompositeWindow::closeWindowAnimation()
{
if (!pc || !pc->is_valid || window_status == Closing
|| pc->isInputOnly() || pc->isOverrideRedirect()
|| !windowPixmap() || !isAppWindow()
// isAppWindow() returns true for system dialogs
|| pc->windowTypeAtom() == ATOM(_NET_WM_WINDOW_TYPE_DIALOG)
|| propertyCache()->windowState() == IconicState
|| window_status == MCompositeWindow::Hung) {
return;
}
window_status = Closing; // animating, do not disturb
MCompositeManager *p = (MCompositeManager *) qApp;
bool defer = false;
setVisible(true);
if (!p->isCompositing()) {
p->d->enableCompositing(true);
defer = true;
}
origPosition = pos();
// Custom close window animation handler
QList<MCompositeManagerExtension*> evlist = p->d->m_extensions.values(MapNotify);
for (int i = 0; i < evlist.size(); ++i) {
if (evlist[i]->windowClosed(this)) {
window_status = Normal; // can't guarantee that Closing is cleared
return;
}
}
iconify(fadeRect, defer);
}
bool MCompositeWindow::event(QEvent *e)
{
if (e->type() == QEvent::DeferredDelete && is_transitioning) {
// Can't delete the object yet, try again in the next iteration.
deleteLater();
return true;
} else
return QObject::event(e);
}
void MCompositeWindow::prettyDestroy()
{
setVisible(true);
destroyed = true;
iconify();
}
void MCompositeWindow::finalizeState()
{
endAnimation();
// as far as this window is concerned, it's OK to direct render
window_status = Normal;
if (pc && pc->windowTypeAtom() == ATOM(_NET_WM_WINDOW_TYPE_DESKTOP))
emit desktopActivated(this);
// iconification status
if (iconified) {
iconified = false;
iconified_final = true;
hide();
iconify_state = TransitionIconifyState;
emit itemIconified(this);
} else {
iconify_state = NoIconifyState;
iconified_final = false;
show();
// no delay: window does not need to be repainted when restoring
// from the switcher (even then the animation should take long enough
// to allow it)
q_itemRestored();
}
// item lifetime
if (destroyed)
deleteLater();
}
void MCompositeWindow::q_itemRestored()
{
emit itemRestored(this);
}
void MCompositeWindow::requestZValue(int zvalue)
{
// when animating, Z-value is set again after finishing the animation
// (setting it later in finalizeState() caused flickering)
if (anim && !anim->isActive() && !anim->pendingAnimation())
setZValue(zvalue);
}
bool MCompositeWindow::isIconified() const
{
if (anim->isActive())
return false;
return iconified_final;
}
bool MCompositeWindow::isScaled() const
{
return scaled;
}
void MCompositeWindow::setScaled(bool s)
{
scaled = s;
}
void MCompositeWindow::setVisible(bool visible)
{
if ((pc && pc->isInputOnly())
|| (visible && newly_mapped && isAppWindow())
|| (!visible && is_transitioning))
return;
// Set the iconification status as well
iconified_final = !visible;
if (visible != window_visible)
emit visualized(visible);
window_visible = visible;
QGraphicsItem::setVisible(visible);
MCompositeManager *p = (MCompositeManager *) qApp;
p->d->setWindowDebugProperties(window());
QGraphicsScene* sc = scene();
if (sc && !visible && sc->items().count() == 1)
clearTexture();
}
void MCompositeWindow::startPing()
{
if (pinging_enabled || !t_ping)
// this function can be called repeatedly without extending the timeout
return;
// startup: send ping now, otherwise it is sent after timeout
pinging_enabled = true;
pingWindow();
if (t_ping->isActive())
t_ping->stop();
// this could be configurable. But will do for now. Most WMs use 5s delay
t_ping->setSingleShot(false);
t_ping->setInterval(5000);
t_ping->start();
}
void MCompositeWindow::stopPing()
{
pinging_enabled = false;
if (t_ping)
t_ping->stop();
if (t_reappear)
t_reappear->stop();
}
void MCompositeWindow::startDialogReappearTimer()
{
if (!t_reappear || window_status != Hung)
return;
if (t_reappear->isActive())
t_reappear->stop();
t_reappear->setSingleShot(true);
t_reappear->setInterval(30 * 1000);
t_reappear->start();
}
void MCompositeWindow::reappearTimeout()
{
if (window_status == Hung)
// show "application not responding" UI again
emit windowHung(this);
}
void MCompositeWindow::receivedPing(ulong serverTimeStamp)
{
received_ping_timestamp = serverTimeStamp;
if (window_status != Minimizing && window_status != Closing)
window_status = Normal;
if (blurred())
setBlurred(false);
if (t_reappear->isActive())
t_reappear->stop();
}
void MCompositeWindow::pingTimeout()
{
if (pinging_enabled && received_ping_timestamp < sent_ping_timestamp
&& pc && pc->isMapped() && window_status != Hung
&& window_status != Minimizing && window_status != Closing) {
window_status = Hung;
emit windowHung(this);
}
if (pinging_enabled)
// interval timer is still active
pingWindow();
}
void MCompositeWindow::pingWindow()
{
if (window_status == Hung)
// don't send a new ping before the window responds, otherwise we may
// queue up too many of them
return;
ulong t = QDateTime::currentDateTime().toTime_t();
sent_ping_timestamp = t;
Window w = window();
XEvent ev;
memset(&ev, 0, sizeof(ev));
ev.xclient.type = ClientMessage;
ev.xclient.window = w;
ev.xclient.message_type = ATOM(WM_PROTOCOLS);
ev.xclient.format = 32;
ev.xclient.data.l[0] = ATOM(_NET_WM_PING);
ev.xclient.data.l[1] = t;
ev.xclient.data.l[2] = w;
XSendEvent(QX11Info::display(), w, False, NoEventMask, &ev);
}
MCompositeWindow::WindowStatus MCompositeWindow::status() const
{
return window_status;
}
bool MCompositeWindow::needDecoration() const
{
return need_decor;
}
void MCompositeWindow::setDecorated(bool decorated)
{
need_decor = decorated;
}
MCompositeWindow *MCompositeWindow::compositeWindow(Qt::HANDLE window)
{
MCompositeManager *p = (MCompositeManager *) qApp;
return p->d->windows.value(window, 0);
}
void MCompositeWindow::beginAnimation()
{
if (!isMapped() && window_status != Closing)
return;
if (!is_transitioning) {
++window_transitioning;
is_transitioning = true;
}
}
void MCompositeWindow::endAnimation()
{
if (is_transitioning) {
--window_transitioning;
is_transitioning = false;
}
}
bool MCompositeWindow::hasTransitioningWindow()
{
return window_transitioning > 0;
}
QVariant MCompositeWindow::itemChange(GraphicsItemChange change, const QVariant &value)
{
MCompositeManager *p = (MCompositeManager *) qApp;
bool zvalChanged = (change == ItemZValueHasChanged);
if (zvalChanged) {
findBehindWindow();
p->d->setWindowDebugProperties(window());
}
// Be careful that there is a changed visible item, to not reopen NB#189519.
// Update is needed if visibility changes for a visible item
// (other visible items get redrawn also)
QList<QGraphicsItem*> l;
if (scene())
l = scene()->items();
int highest_visible_z = -1000;
for (QList<QGraphicsItem*>::const_iterator i = l.begin(); i != l.end(); ++i)
if ((*i)->isVisible()) {
highest_visible_z = (*i)->zValue();
break;
}
// case requiring this: status menu closed on top of decorated FieldTest app
if (zValue() >= highest_visible_z && change == ItemVisibleHasChanged)
p->d->glwidget->update();
return QGraphicsItem::itemChange(change, value);
}
void MCompositeWindow::findBehindWindow()
{
MCompositeManager *p = (MCompositeManager *) qApp;
int behind_i = indexInStack() - 1;
if (behind_i >= 0 && behind_i < p->d->stacking_list.size()) {
MCompositeWindow* w = MCompositeWindow::compositeWindow(p->d->stacking_list.at(behind_i));
if (w->propertyCache()->windowState() == NormalState
&& w->propertyCache()->isMapped()
&& !w->propertyCache()->isDecorator())
behind_window = w;
else if (w->propertyCache()->isDecorator() && MDecoratorFrame::instance()->managedClient())
behind_window = MDecoratorFrame::instance()->managedClient();
else
behind_window = MCompositeWindow::compositeWindow(p->d->stack[DESKTOP_LAYER]);
}
}
void MCompositeWindow::update()
{
MCompositeManager *p = (MCompositeManager *) qApp;
p->d->glwidget->update();
}
bool MCompositeWindow::windowVisible() const
{
return window_visible;
}
bool MCompositeWindow::isAppWindow(bool include_transients)
{
MCompositeManager *p = (MCompositeManager *) qApp;
if (!include_transients && p->d->getLastVisibleParent(pc))
return false;
if (pc && !pc->isOverrideRedirect() &&
(pc->windowTypeAtom() == ATOM(_NET_WM_WINDOW_TYPE_NORMAL) ||
pc->windowTypeAtom() == ATOM(_KDE_NET_WM_WINDOW_TYPE_OVERRIDE) ||
/* non-modal, non-transient dialogs behave like applications */
(pc->windowTypeAtom() == ATOM(_NET_WM_WINDOW_TYPE_DIALOG) &&
(pc->netWmState().indexOf(ATOM(_NET_WM_STATE_MODAL)) == -1)))
&& !pc->isDecorator())
return true;
return false;
}
QPainterPath MCompositeWindow::shape() const
{
QPainterPath path;
const QRegion &shape = propertyCache()->shapeRegion();
if (QRegion(boundingRect().toRect()).subtracted(shape).isEmpty())
path.addRect(boundingRect());
else
path.addRegion(shape);
return path;
}
Window MCompositeWindow::lastVisibleParent() const
{
MCompositeManager *p = (MCompositeManager *) qApp;
if (pc && pc->is_valid)
return p->d->getLastVisibleParent(pc);
else
return None;
}
int MCompositeWindow::indexInStack() const
{
MCompositeManager *p = (MCompositeManager *) qApp;
return p->d->stacking_list.indexOf(window());
}
void MCompositeWindow::setIsMapped(bool mapped)
{
if (mapped)
window_status = Normal; // make sure Closing -> Normal when remapped
if (pc) pc->setIsMapped(mapped);
}
bool MCompositeWindow::isMapped() const
{
return pc ? pc->isMapped() : false;
}
MCompositeWindowGroup* MCompositeWindow::group() const
{
#ifdef GLES2_VERSION
return renderer()->current_window_group;
#else
return 0;
#endif
}
simplify MCompositeWindow::itemChange()
* src/mcompositewindow.cpp (MCompositeWindow::itemChange):
Use a flag rather than highest_visible_z == -1000.
/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of mcompositor.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mcompositewindow.h"
#include "mcompwindowanimator.h"
#include "mcompositemanager.h"
#include "mcompositemanager_p.h"
#include "mtexturepixmapitem.h"
#include "mdecoratorframe.h"
#include "mcompositemanagerextension.h"
#include "mcompositewindowgroup.h"
#include <QX11Info>
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
#include <X11/Xatom.h>
int MCompositeWindow::window_transitioning = 0;
static QRectF fadeRect = QRectF();
MCompositeWindow::MCompositeWindow(Qt::HANDLE window,
MWindowPropertyCache *mpc,
QGraphicsItem *p)
: QGraphicsItem(p),
pc(mpc),
scalefrom(1),
scaleto(1),
scaled(false),
zval(1),
sent_ping_timestamp(0),
received_ping_timestamp(0),
blur(false),
iconified(false),
iconified_final(false),
iconify_state(NoIconifyState),
destroyed(false),
window_status(Normal),
need_decor(false),
window_obscured(-1),
is_transitioning(false),
pinging_enabled(false),
dimmed_effect(false),
waiting_for_damage(0),
win_id(window)
{
thumb_mode = false;
if (!mpc || (mpc && !mpc->is_valid)) {
is_valid = false;
anim = 0;
newly_mapped = false;
t_ping = 0;
window_visible = false;
return;
} else
is_valid = true;
anim = new MCompWindowAnimator(this);
connect(anim, SIGNAL(transitionDone()), SLOT(finalizeState()));
connect(anim, SIGNAL(transitionStart()), SLOT(beginAnimation()));
connect(mpc, SIGNAL(iconGeometryUpdated()), SLOT(updateIconGeometry()));
setAcceptHoverEvents(true);
t_ping = new QTimer(this);
connect(t_ping, SIGNAL(timeout()), SLOT(pingTimeout()));
t_reappear = new QTimer(this);
connect(t_reappear, SIGNAL(timeout()), SLOT(reappearTimeout()));
damage_timer = new QTimer(this);
damage_timer->setSingleShot(true);
connect(damage_timer, SIGNAL(timeout()), SLOT(damageTimeout()));
MCompAtoms* atoms = MCompAtoms::instance();
if (pc->windowType() == MCompAtoms::NORMAL)
pc->setWindowTypeAtom(ATOM(_NET_WM_WINDOW_TYPE_NORMAL));
else
pc->setWindowTypeAtom(atoms->getType(window));
// needed before calling isAppWindow()
QVector<Atom> states = atoms->getAtomArray(window, ATOM(_NET_WM_STATE));
pc->setNetWmState(states.toList());
// Newly-mapped non-decorated application windows are not initially
// visible to prevent flickering when animation is started.
// We initially prevent item visibility from compositor itself
// or it's corresponding thumbnail rendered by the switcher
bool is_app = isAppWindow();
newly_mapped = is_app;
if (!pc->isInputOnly()) {
// never paint InputOnly windows
window_visible = !is_app;
setVisible(window_visible); // newly_mapped used here
}
origPosition = QPointF(pc->realGeometry().x(), pc->realGeometry().y());
if (fadeRect.isEmpty()) {
QRectF d = QApplication::desktop()->availableGeometry();
fadeRect.setWidth(d.width()/2);
fadeRect.setHeight(d.height()/2);
fadeRect.moveTo(fadeRect.width()/2, fadeRect.height()/2);
}
}
MCompositeWindow::~MCompositeWindow()
{
MCompositeManager *p = (MCompositeManager *) qApp;
if (window() && (t_ping || t_reappear)) {
stopPing();
delete t_ping;
delete t_reappear;
t_ping = t_reappear = 0;
}
endAnimation();
anim = 0;
delete damage_timer;
if (pc) {
pc->damageTracking(false);
p->d->prop_caches.remove(window());
pc->deleteLater();
}
}
void MCompositeWindow::setBlurred(bool b)
{
blur = b;
update();
}
bool MCompositeWindow::blurred()
{
return blur;
}
void MCompositeWindow::saveState()
{
anim->saveState();
}
void MCompositeWindow::localSaveState()
{
anim->localSaveState();
}
// set the scale point to actual values
void MCompositeWindow::setScalePoint(qreal from, qreal to)
{
scalefrom = from;
scaleto = to;
}
void MCompositeWindow::setThumbMode(bool mode)
{
thumb_mode = mode;
}
/* This is a delayed animation. Actual animation is triggered
* when startTransition() is called
*/
void MCompositeWindow::iconify(const QRectF &icongeometry, bool defer)
{
if (iconify_state == ManualIconifyState) {
setIconified(true);
window_status = Normal;
return;
}
if (window_status != MCompositeWindow::Closing)
window_status = MCompositeWindow::Minimizing;
// Custom iconify handler
MCompositeManager *p = (MCompositeManager *) qApp;
QList<MCompositeManagerExtension*> evlist = p->d->m_extensions.values(MapNotify);
for (int i = 0; i < evlist.size(); ++i) {
if (evlist[i]->windowIconified(this, defer)) {
iconified = true;
window_status = Normal;
return;
}
}
this->iconGeometry = icongeometry;
if (!iconified)
origPosition = pos();
// horizontal and vert. scaling factors
qreal sx = iconGeometry.width() / boundingRect().width();
qreal sy = iconGeometry.height() / boundingRect().height();
anim->deferAnimation(defer);
anim->translateScale(qreal(1.0), qreal(1.0), sx, sy,
iconGeometry.topLeft());
iconified = true;
// do this to avoid stacking code disturbing Z values
beginAnimation();
}
void MCompositeWindow::setUntransformed()
{
endAnimation();
if (anim)
anim->stopAnimation(); // stop and restore the matrix
newly_mapped = false;
setVisible(true);
setOpacity(1.0);
setScale(1.0);
setScaled(false);
iconified = false;
}
void MCompositeWindow::setIconified(bool iconified)
{
iconified_final = iconified;
iconify_state = ManualIconifyState;
if (iconified && !anim->pendingAnimation())
emit itemIconified(this);
else if (!iconified && !anim->pendingAnimation())
iconify_state = NoIconifyState;
}
MCompositeWindow::IconifyState MCompositeWindow::iconifyState() const
{
return iconify_state;
}
void MCompositeWindow::setIconifyState(MCompositeWindow::IconifyState state)
{
iconify_state = state;
}
void MCompositeWindow::setWindowObscured(bool obscured, bool no_notify)
{
MCompositeManager *p = (MCompositeManager *) qApp;
short new_value = obscured ? 1 : 0;
if ((new_value == window_obscured && !newly_mapped)
|| (!obscured && p->displayOff()))
return;
window_obscured = new_value;
if (!no_notify) {
XVisibilityEvent c;
c.type = VisibilityNotify;
c.send_event = True;
c.window = window();
c.state = obscured ? VisibilityFullyObscured :
VisibilityUnobscured;
XSendEvent(QX11Info::display(), window(), true,
VisibilityChangeMask, (XEvent *)&c);
}
}
/*
* We ensure that ensure there are ALWAYS updated thumbnails in the
* switcher by letting switcher know in advance of the presence of this window.
* Delay the minimize animation until we receive an iconGeometry update from
* the switcher
*/
void MCompositeWindow::startTransition()
{
if (iconified) {
if (iconGeometry.isNull())
return;
setWindowObscured(true);
}
if (anim->pendingAnimation()) {
MCompositeWindow::setVisible(true);
anim->startAnimation();
anim->deferAnimation(false);
}
}
void MCompositeWindow::updateIconGeometry()
{
if (!pc)
return;
iconGeometry = pc->iconGeometry();
if (iconGeometry.isNull())
return;
// trigger transition the second time around and update animation values
if (iconified) {
qreal sx = iconGeometry.width() / boundingRect().width();
qreal sy = iconGeometry.height() / boundingRect().height();
anim->translateScale(qreal(1.0), qreal(1.0), sx, sy,
iconGeometry.topLeft());
startTransition();
}
}
// TODO: have an option of disabling the animation
void MCompositeWindow::restore(const QRectF &icongeometry, bool defer)
{
// Custom restore handler
MCompositeManager *p = (MCompositeManager *) qApp;
QList<MCompositeManagerExtension*> evlist = p->d->m_extensions.values(MapNotify);
for (int i = 0; i < evlist.size(); ++i) {
if (evlist[i]->windowRestored(this, defer)) {
iconified = false;
return;
}
}
if (icongeometry.isEmpty())
this->iconGeometry = fadeRect;
else
this->iconGeometry = icongeometry;
setPos(iconGeometry.topLeft());
// horizontal and vert. scaling factors
qreal sx = iconGeometry.width() / boundingRect().width();
qreal sy = iconGeometry.height() / boundingRect().height();
setVisible(true);
anim->deferAnimation(defer);
anim->translateScale(qreal(1.0), qreal(1.0), sx, sy, origPosition, true);
iconified = false;
// do this to avoid stacking code disturbing Z values
beginAnimation();
}
bool MCompositeWindow::showWindow()
{
// defer putting this window in the _NET_CLIENT_LIST
// only after animation is done to prevent the switcher from rendering it
if (!isAppWindow() || !pc || !pc->is_valid
// isAppWindow() returns true for system dialogs
|| pc->windowTypeAtom() == ATOM(_NET_WM_WINDOW_TYPE_DIALOG))
return false;
findBehindWindow();
beginAnimation();
if (newly_mapped) {
// NB#180628 - some stupid apps are listening for visibilitynotifies.
// Well, all of the toolkit anyways
setWindowObscured(false);
// waiting for two damage events seems to work for Meegotouch apps
// at least, for the rest, there is a timeout
waiting_for_damage = 2;
damage_timer->start(500);
} else
q_fadeIn();
return true;
}
void MCompositeWindow::damageTimeout()
{
damageReceived(true);
}
void MCompositeWindow::damageReceived(bool timeout)
{
if (timeout || (waiting_for_damage > 0 && !--waiting_for_damage)) {
damage_timer->stop();
waiting_for_damage = 0;
q_fadeIn();
}
}
void MCompositeWindow::q_fadeIn()
{
endAnimation();
newly_mapped = false;
setVisible(true);
setOpacity(0.0);
updateWindowPixmap();
origPosition = pos();
newly_mapped = true;
// Custom fade-in handler
MCompositeManager *p = (MCompositeManager *) qApp;
QList<MCompositeManagerExtension*> evlist = p->d->m_extensions.values(MapNotify);
for (int i = 0; i < evlist.size(); ++i) {
if (evlist[i]->windowShown(this))
return;
}
setPos(fadeRect.topLeft());
restore(fadeRect, false);
}
void MCompositeWindow::closeWindowRequest()
{
if (!pc || !pc->is_valid || (!isMapped() && !pc->beingMapped()))
return;
if (!windowPixmap() && !pc->isInputOnly()) {
// get a Pixmap for the possible unmap animation
MCompositeManager *p = (MCompositeManager *) qApp;
if (!p->isCompositing())
p->d->enableCompositing(true);
updateWindowPixmap();
}
emit closeWindowRequest(this);
}
void MCompositeWindow::closeWindowAnimation()
{
if (!pc || !pc->is_valid || window_status == Closing
|| pc->isInputOnly() || pc->isOverrideRedirect()
|| !windowPixmap() || !isAppWindow()
// isAppWindow() returns true for system dialogs
|| pc->windowTypeAtom() == ATOM(_NET_WM_WINDOW_TYPE_DIALOG)
|| propertyCache()->windowState() == IconicState
|| window_status == MCompositeWindow::Hung) {
return;
}
window_status = Closing; // animating, do not disturb
MCompositeManager *p = (MCompositeManager *) qApp;
bool defer = false;
setVisible(true);
if (!p->isCompositing()) {
p->d->enableCompositing(true);
defer = true;
}
origPosition = pos();
// Custom close window animation handler
QList<MCompositeManagerExtension*> evlist = p->d->m_extensions.values(MapNotify);
for (int i = 0; i < evlist.size(); ++i) {
if (evlist[i]->windowClosed(this)) {
window_status = Normal; // can't guarantee that Closing is cleared
return;
}
}
iconify(fadeRect, defer);
}
bool MCompositeWindow::event(QEvent *e)
{
if (e->type() == QEvent::DeferredDelete && is_transitioning) {
// Can't delete the object yet, try again in the next iteration.
deleteLater();
return true;
} else
return QObject::event(e);
}
void MCompositeWindow::prettyDestroy()
{
setVisible(true);
destroyed = true;
iconify();
}
void MCompositeWindow::finalizeState()
{
endAnimation();
// as far as this window is concerned, it's OK to direct render
window_status = Normal;
if (pc && pc->windowTypeAtom() == ATOM(_NET_WM_WINDOW_TYPE_DESKTOP))
emit desktopActivated(this);
// iconification status
if (iconified) {
iconified = false;
iconified_final = true;
hide();
iconify_state = TransitionIconifyState;
emit itemIconified(this);
} else {
iconify_state = NoIconifyState;
iconified_final = false;
show();
// no delay: window does not need to be repainted when restoring
// from the switcher (even then the animation should take long enough
// to allow it)
q_itemRestored();
}
// item lifetime
if (destroyed)
deleteLater();
}
void MCompositeWindow::q_itemRestored()
{
emit itemRestored(this);
}
void MCompositeWindow::requestZValue(int zvalue)
{
// when animating, Z-value is set again after finishing the animation
// (setting it later in finalizeState() caused flickering)
if (anim && !anim->isActive() && !anim->pendingAnimation())
setZValue(zvalue);
}
bool MCompositeWindow::isIconified() const
{
if (anim->isActive())
return false;
return iconified_final;
}
bool MCompositeWindow::isScaled() const
{
return scaled;
}
void MCompositeWindow::setScaled(bool s)
{
scaled = s;
}
void MCompositeWindow::setVisible(bool visible)
{
if ((pc && pc->isInputOnly())
|| (visible && newly_mapped && isAppWindow())
|| (!visible && is_transitioning))
return;
// Set the iconification status as well
iconified_final = !visible;
if (visible != window_visible)
emit visualized(visible);
window_visible = visible;
QGraphicsItem::setVisible(visible);
MCompositeManager *p = (MCompositeManager *) qApp;
p->d->setWindowDebugProperties(window());
QGraphicsScene* sc = scene();
if (sc && !visible && sc->items().count() == 1)
clearTexture();
}
void MCompositeWindow::startPing()
{
if (pinging_enabled || !t_ping)
// this function can be called repeatedly without extending the timeout
return;
// startup: send ping now, otherwise it is sent after timeout
pinging_enabled = true;
pingWindow();
if (t_ping->isActive())
t_ping->stop();
// this could be configurable. But will do for now. Most WMs use 5s delay
t_ping->setSingleShot(false);
t_ping->setInterval(5000);
t_ping->start();
}
void MCompositeWindow::stopPing()
{
pinging_enabled = false;
if (t_ping)
t_ping->stop();
if (t_reappear)
t_reappear->stop();
}
void MCompositeWindow::startDialogReappearTimer()
{
if (!t_reappear || window_status != Hung)
return;
if (t_reappear->isActive())
t_reappear->stop();
t_reappear->setSingleShot(true);
t_reappear->setInterval(30 * 1000);
t_reappear->start();
}
void MCompositeWindow::reappearTimeout()
{
if (window_status == Hung)
// show "application not responding" UI again
emit windowHung(this);
}
void MCompositeWindow::receivedPing(ulong serverTimeStamp)
{
received_ping_timestamp = serverTimeStamp;
if (window_status != Minimizing && window_status != Closing)
window_status = Normal;
if (blurred())
setBlurred(false);
if (t_reappear->isActive())
t_reappear->stop();
}
void MCompositeWindow::pingTimeout()
{
if (pinging_enabled && received_ping_timestamp < sent_ping_timestamp
&& pc && pc->isMapped() && window_status != Hung
&& window_status != Minimizing && window_status != Closing) {
window_status = Hung;
emit windowHung(this);
}
if (pinging_enabled)
// interval timer is still active
pingWindow();
}
void MCompositeWindow::pingWindow()
{
if (window_status == Hung)
// don't send a new ping before the window responds, otherwise we may
// queue up too many of them
return;
ulong t = QDateTime::currentDateTime().toTime_t();
sent_ping_timestamp = t;
Window w = window();
XEvent ev;
memset(&ev, 0, sizeof(ev));
ev.xclient.type = ClientMessage;
ev.xclient.window = w;
ev.xclient.message_type = ATOM(WM_PROTOCOLS);
ev.xclient.format = 32;
ev.xclient.data.l[0] = ATOM(_NET_WM_PING);
ev.xclient.data.l[1] = t;
ev.xclient.data.l[2] = w;
XSendEvent(QX11Info::display(), w, False, NoEventMask, &ev);
}
MCompositeWindow::WindowStatus MCompositeWindow::status() const
{
return window_status;
}
bool MCompositeWindow::needDecoration() const
{
return need_decor;
}
void MCompositeWindow::setDecorated(bool decorated)
{
need_decor = decorated;
}
MCompositeWindow *MCompositeWindow::compositeWindow(Qt::HANDLE window)
{
MCompositeManager *p = (MCompositeManager *) qApp;
return p->d->windows.value(window, 0);
}
void MCompositeWindow::beginAnimation()
{
if (!isMapped() && window_status != Closing)
return;
if (!is_transitioning) {
++window_transitioning;
is_transitioning = true;
}
}
void MCompositeWindow::endAnimation()
{
if (is_transitioning) {
--window_transitioning;
is_transitioning = false;
}
}
bool MCompositeWindow::hasTransitioningWindow()
{
return window_transitioning > 0;
}
QVariant MCompositeWindow::itemChange(GraphicsItemChange change, const QVariant &value)
{
MCompositeManager *p = (MCompositeManager *) qApp;
if (change == ItemZValueHasChanged) {
findBehindWindow();
p->d->setWindowDebugProperties(window());
// Be careful not to update if this item whose visibility is about
// to change is behind a visible item, to not reopen NB#189519.
// Update is needed if visibility changes for a visible item
// (other visible items get redrawn also). Case requiring this:
// status menu closed on top of an mdecorated window.
bool ok_to_update = true;
if (scene()) {
QList<QGraphicsItem*> l = scene()->items();
for (QList<QGraphicsItem*>::const_iterator i = l.begin();
i != l.end(); ++i)
if ((*i)->isVisible()) {
ok_to_update = zValue() >= (*i)->zValue();
break;
}
}
if (ok_to_update)
// Nothing is visible or the topmost visible item is lower than us.
p->d->glwidget->update();
}
return QGraphicsItem::itemChange(change, value);
}
void MCompositeWindow::findBehindWindow()
{
MCompositeManager *p = (MCompositeManager *) qApp;
int behind_i = indexInStack() - 1;
if (behind_i >= 0 && behind_i < p->d->stacking_list.size()) {
MCompositeWindow* w = MCompositeWindow::compositeWindow(p->d->stacking_list.at(behind_i));
if (w->propertyCache()->windowState() == NormalState
&& w->propertyCache()->isMapped()
&& !w->propertyCache()->isDecorator())
behind_window = w;
else if (w->propertyCache()->isDecorator() && MDecoratorFrame::instance()->managedClient())
behind_window = MDecoratorFrame::instance()->managedClient();
else
behind_window = MCompositeWindow::compositeWindow(p->d->stack[DESKTOP_LAYER]);
}
}
void MCompositeWindow::update()
{
MCompositeManager *p = (MCompositeManager *) qApp;
p->d->glwidget->update();
}
bool MCompositeWindow::windowVisible() const
{
return window_visible;
}
bool MCompositeWindow::isAppWindow(bool include_transients)
{
MCompositeManager *p = (MCompositeManager *) qApp;
if (!include_transients && p->d->getLastVisibleParent(pc))
return false;
if (pc && !pc->isOverrideRedirect() &&
(pc->windowTypeAtom() == ATOM(_NET_WM_WINDOW_TYPE_NORMAL) ||
pc->windowTypeAtom() == ATOM(_KDE_NET_WM_WINDOW_TYPE_OVERRIDE) ||
/* non-modal, non-transient dialogs behave like applications */
(pc->windowTypeAtom() == ATOM(_NET_WM_WINDOW_TYPE_DIALOG) &&
(pc->netWmState().indexOf(ATOM(_NET_WM_STATE_MODAL)) == -1)))
&& !pc->isDecorator())
return true;
return false;
}
QPainterPath MCompositeWindow::shape() const
{
QPainterPath path;
const QRegion &shape = propertyCache()->shapeRegion();
if (QRegion(boundingRect().toRect()).subtracted(shape).isEmpty())
path.addRect(boundingRect());
else
path.addRegion(shape);
return path;
}
Window MCompositeWindow::lastVisibleParent() const
{
MCompositeManager *p = (MCompositeManager *) qApp;
if (pc && pc->is_valid)
return p->d->getLastVisibleParent(pc);
else
return None;
}
int MCompositeWindow::indexInStack() const
{
MCompositeManager *p = (MCompositeManager *) qApp;
return p->d->stacking_list.indexOf(window());
}
void MCompositeWindow::setIsMapped(bool mapped)
{
if (mapped)
window_status = Normal; // make sure Closing -> Normal when remapped
if (pc) pc->setIsMapped(mapped);
}
bool MCompositeWindow::isMapped() const
{
return pc ? pc->isMapped() : false;
}
MCompositeWindowGroup* MCompositeWindow::group() const
{
#ifdef GLES2_VERSION
return renderer()->current_window_group;
#else
return 0;
#endif
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/*
* This pass identifies tracable object allocations that don't escape, and then
* attempts to inline all code interacting with the local object, turning all
* instance fields into registers. The changes are only applied when the
* estimated savings are not negative. This helps reduce...
* - object allocations at runtime, and
* - code size by eliminating a many of the involved classes, fields and
* methods.
*
* At the core is an interprocedural escape analysis with method-level summaries
* that...
* - may include results of method invocations as allocations, and
* - follows arguments to non-true-virtual method invocations.
*
* This pass is conservative: Any use of an object allocation that isn't fully
* understood, e.g. an external method invocation, causes that allocation to
* become ineligable for optimization. In any case, this pass will not transform
* a root method with the no_optimizations annotation.
*
* The pass computes...
* - method summaries, indicating whether a method allocates and returns an
* object that doesn't otherwise escape, and which method arguments don't
* escape
* - "inline anchors", which are particular instructions (in particular methods)
* which produce a new unescaped object, either by directly allocating it or
* invoking a method that directly or indirect allocates and returns an object
* that doesn't otherwise escape, and then possibly use that object in ways
* where it doesn't escape
* - "root methods", which are all the methods which contain "inline anchors" of
* types whose allocation instructions are all ultimately inlinably anchored.
* - "reduced methods", which are root methods where all inlinable anchors got
* fully inlined, and the fields of allocated objects got turned into
* registers (and the transformation does not produce estimated negative net
* savings)
*
* Notes:
* - The transformation doesn't directly eliminate the object allocation, as the
* object might be involved in some identity comparisons, e.g. for
* null-checks. Instead, the object allocation gets rewritten to create an
* object of type java.lang.Object, and other optimizations such as
* constant-propagation and local-dead-code-elimination should be able to
* remove that remaining code in most cases.
*
* Ideas for future work:
* - Support check-cast instructions for singleton-allocations
* - Support conditional branches over either zero or single allocations
* - Refine the tracing of object allocations in root methods to ignore
* unanchored object allocations
* - Instead of inlining all invoked methods, consider transforming those which
* do not mutate or compare the allocated object as follows: instead of
* passing in the allocated object via an argument, pass in all read fields
* are passed in as separate arguments. This could reduce the size increase
* due to multiple inlined method body copies. We already do something similar
* for constructors.
*/
#include "ObjectEscapeAnalysis.h"
#include <algorithm>
#include <optional>
#include "ApiLevelChecker.h"
#include "BaseIRAnalyzer.h"
#include "CFGMutation.h"
#include "ConfigFiles.h"
#include "ConstantAbstractDomain.h"
#include "ControlFlow.h"
#include "DexClass.h"
#include "ExpandableMethodParams.h"
#include "HierarchyUtil.h"
#include "IRCode.h"
#include "IRInstruction.h"
#include "IROpcode.h"
#include "Inliner.h"
#include "Lazy.h"
#include "LiveRange.h"
#include "MethodOverrideGraph.h"
#include "PassManager.h"
#include "PatriciaTreeMap.h"
#include "PatriciaTreeMapAbstractEnvironment.h"
#include "PatriciaTreeSet.h"
#include "PatriciaTreeSetAbstractDomain.h"
#include "Resolver.h"
#include "Show.h"
#include "StringBuilder.h"
#include "Walkers.h"
using namespace sparta;
namespace mog = method_override_graph;
namespace hier = hierarchy_util;
namespace {
// How deep callee chains will be considered.
constexpr int MAX_INLINE_INVOKES_ITERATIONS = 8;
constexpr size_t MAX_INLINE_SIZE = 48;
// Don't even try to inline an incompletely inlinable type if a very rough
// estimate predicts an increase exceeding this threshold in code units.
constexpr float INCOMPLETE_ESTIMATED_DELTA_THRESHOLD = 0;
// Overhead of having a method and its metadata.
constexpr size_t COST_METHOD = 16;
// Overhead of having a class and its metadata.
constexpr size_t COST_CLASS = 48;
// Overhead of having a field and its metadata.
constexpr size_t COST_FIELD = 8;
// Typical overhead of calling a method, without move-result overhead.
constexpr float COST_INVOKE = 4.7f;
// Typical overhead of having move-result instruction.
constexpr float COST_MOVE_RESULT = 3.0f;
// Overhead of a new-instance instruction.
constexpr float COST_NEW_INSTANCE = 2.0f;
using Locations = std::vector<std::pair<DexMethod*, const IRInstruction*>>;
// Collect all allocation and invoke instructions, as well as non-virtual
// invocation dependencies.
void analyze_scope(
const Scope& scope,
const std::unordered_set<const DexMethod*>& non_overridden_virtuals,
std::unordered_map<DexType*, Locations>* new_instances,
std::unordered_map<DexMethod*, Locations>* invokes,
std::unordered_map<DexMethod*, std::unordered_set<DexMethod*>>*
dependencies) {
Timer t("analyze_scope");
ConcurrentMap<DexType*, Locations> concurrent_new_instances;
ConcurrentMap<DexMethod*, Locations> concurrent_invokes;
ConcurrentMap<DexMethod*, std::unordered_set<DexMethod*>>
concurrent_dependencies;
walk::parallel::code(scope, [&](DexMethod* method, IRCode& code) {
code.build_cfg(/* editable */ true);
for (auto& mie : InstructionIterable(code.cfg())) {
auto insn = mie.insn;
if (insn->opcode() == OPCODE_NEW_INSTANCE) {
auto cls = type_class(insn->get_type());
if (cls && !cls->is_external()) {
concurrent_new_instances.update(
insn->get_type(),
[&](auto*, auto& vec, bool) { vec.emplace_back(method, insn); });
}
} else if (opcode::is_an_invoke(insn->opcode())) {
auto callee =
resolve_method(insn->get_method(), opcode_to_search(insn));
if (callee &&
(!callee->is_virtual() || non_overridden_virtuals.count(callee))) {
concurrent_invokes.update(callee, [&](auto*, auto& vec, bool) {
vec.emplace_back(method, insn);
});
if (!method->is_virtual() || non_overridden_virtuals.count(method)) {
concurrent_dependencies.update(
callee,
[method](auto, auto& set, auto) { set.insert(method); });
}
}
}
}
});
*new_instances = concurrent_new_instances.move_to_container();
*invokes = concurrent_invokes.move_to_container();
*dependencies = concurrent_dependencies.move_to_container();
}
// A benign method invocation can be ignored during the escape analysis.
bool is_benign(const DexMethodRef* method_ref) {
static const std::unordered_set<std::string> methods = {
// clang-format off
"Ljava/lang/Object;.<init>:()V",
// clang-format on
};
return method_ref->is_def() &&
methods.count(
method_ref->as_def()->get_deobfuscated_name_or_empty_copy());
}
constexpr const IRInstruction* NO_ALLOCATION = nullptr;
using namespace ir_analyzer;
// For each allocating instruction that escapes (not including returns), all
// uses by which it escapes.
using Escapes = std::unordered_map<const IRInstruction*,
std::unordered_set<live_range::Use>>;
// For each object, we track which instruction might have allocated it:
// - new-instance, invoke-, and load-param-object instructions might represent
// allocation points
// - NO_ALLOCATION is a value for which the allocation instruction is not known,
// or it is not an object
using Domain = sparta::PatriciaTreeSetAbstractDomain<const IRInstruction*>;
// For each register that holds a relevant value, keep track of it.
using Environment = sparta::PatriciaTreeMapAbstractEnvironment<reg_t, Domain>;
struct MethodSummary {
// A parameter is "benign" if a provided argument does not escape
std::unordered_set<src_index_t> benign_params;
// A method might contain a unique instruction which allocates an object that
// is eventually unconditionally returned.
const IRInstruction* allocation_insn{nullptr};
};
using MethodSummaries = std::unordered_map<DexMethod*, MethodSummary>;
// The analyzer computes...
// - which instructions allocate (new-instance, invoke-)
// - which allocations escape (and how)
// - which allocations return
class Analyzer final : public BaseIRAnalyzer<Environment> {
public:
explicit Analyzer(const MethodSummaries& method_summaries,
DexMethodRef* incomplete_marker_method,
cfg::ControlFlowGraph& cfg)
: BaseIRAnalyzer(cfg),
m_method_summaries(method_summaries),
m_incomplete_marker_method(incomplete_marker_method) {
MonotonicFixpointIterator::run(Environment::top());
}
static const IRInstruction* get_singleton_allocation(const Domain& domain) {
always_assert(domain.kind() == AbstractValueKind::Value);
auto& elements = domain.elements();
if (elements.size() != 1) {
return nullptr;
}
return *elements.begin();
}
void analyze_instruction(const IRInstruction* insn,
Environment* current_state) const override {
const auto escape = [&](src_index_t src_idx) {
auto reg = insn->src(src_idx);
const auto& domain = current_state->get(reg);
always_assert(domain.kind() == AbstractValueKind::Value);
for (auto allocation_insn : domain.elements()) {
if (allocation_insn != NO_ALLOCATION) {
m_escapes[allocation_insn].insert(
{const_cast<IRInstruction*>(insn), src_idx});
}
}
};
if (insn->opcode() == OPCODE_NEW_INSTANCE) {
auto type = insn->get_type();
auto cls = type_class(type);
if (cls && !cls->is_external()) {
m_escapes[insn];
current_state->set(RESULT_REGISTER, Domain(insn));
return;
}
} else if (insn->opcode() == IOPCODE_LOAD_PARAM_OBJECT) {
m_escapes[insn];
current_state->set(insn->dest(), Domain(insn));
return;
} else if (insn->opcode() == OPCODE_RETURN_OBJECT) {
const auto& domain = current_state->get(insn->src(0));
always_assert(domain.kind() == AbstractValueKind::Value);
m_returns.insert(domain.elements().begin(), domain.elements().end());
return;
} else if (insn->opcode() == OPCODE_MOVE_RESULT_OBJECT ||
insn->opcode() == IOPCODE_MOVE_RESULT_PSEUDO_OBJECT) {
const auto& domain = current_state->get(RESULT_REGISTER);
current_state->set(insn->dest(), domain);
return;
} else if (insn->opcode() == OPCODE_MOVE_OBJECT) {
const auto& domain = current_state->get(insn->src(0));
current_state->set(insn->dest(), domain);
return;
} else if (insn->opcode() == OPCODE_INSTANCE_OF ||
opcode::is_an_iget(insn->opcode())) {
if (get_singleton_allocation(current_state->get(insn->src(0)))) {
current_state->set(RESULT_REGISTER, Domain(NO_ALLOCATION));
return;
}
} else if (opcode::is_a_monitor(insn->opcode()) ||
insn->opcode() == OPCODE_IF_EQZ ||
insn->opcode() == OPCODE_IF_NEZ) {
if (get_singleton_allocation(current_state->get(insn->src(0)))) {
return;
}
} else if (opcode::is_an_iput(insn->opcode())) {
if (get_singleton_allocation(current_state->get(insn->src(1)))) {
escape(0);
return;
}
} else if (opcode::is_an_invoke(insn->opcode())) {
if (is_benign(insn->get_method()) || is_incomplete_marker(insn)) {
current_state->set(RESULT_REGISTER, Domain(NO_ALLOCATION));
return;
}
auto callee = resolve_method(insn->get_method(), opcode_to_search(insn));
auto it = m_method_summaries.find(callee);
auto benign_params =
it == m_method_summaries.end() ? nullptr : &it->second.benign_params;
for (src_index_t i = 0; i < insn->srcs_size(); i++) {
if (!benign_params || !benign_params->count(i) ||
!get_singleton_allocation(current_state->get(insn->src(i)))) {
escape(i);
}
}
Domain domain(NO_ALLOCATION);
if (it != m_method_summaries.end() && it->second.allocation_insn) {
m_escapes[insn];
domain = Domain(insn);
}
current_state->set(RESULT_REGISTER, domain);
return;
}
for (src_index_t i = 0; i < insn->srcs_size(); i++) {
escape(i);
}
if (insn->has_dest()) {
current_state->set(insn->dest(), Domain(NO_ALLOCATION));
if (insn->dest_is_wide()) {
current_state->set(insn->dest() + 1, Domain::top());
}
} else if (insn->has_move_result_any()) {
current_state->set(RESULT_REGISTER, Domain(NO_ALLOCATION));
}
}
const Escapes& get_escapes() { return m_escapes; }
const std::unordered_set<const IRInstruction*>& get_returns() {
return m_returns;
}
// Returns set of new-instance and invoke- allocating instructions that do not
// escape (or return).
std::unordered_set<IRInstruction*> get_inlinables() {
std::unordered_set<IRInstruction*> inlinables;
for (auto&& [insn, uses] : m_escapes) {
if (uses.empty() && insn->opcode() != IOPCODE_LOAD_PARAM_OBJECT &&
!m_returns.count(insn)) {
inlinables.insert(const_cast<IRInstruction*>(insn));
}
}
return inlinables;
}
private:
const MethodSummaries& m_method_summaries;
DexMethodRef* m_incomplete_marker_method;
mutable Escapes m_escapes;
mutable std::unordered_set<const IRInstruction*> m_returns;
bool is_incomplete_marker(const IRInstruction* insn) const {
return insn->opcode() == OPCODE_INVOKE_STATIC &&
insn->get_method() == m_incomplete_marker_method;
}
};
MethodSummaries compute_method_summaries(
PassManager& mgr,
const Scope& scope,
const std::unordered_map<DexMethod*, std::unordered_set<DexMethod*>>&
dependencies,
const std::unordered_set<const DexMethod*>& non_overridden_virtuals) {
Timer t("compute_method_summaries");
std::unordered_set<DexMethod*> impacted_methods;
walk::code(scope, [&](DexMethod* method, IRCode&) {
if (!method->is_virtual() || non_overridden_virtuals.count(method)) {
impacted_methods.insert(method);
}
});
MethodSummaries method_summaries;
size_t analysis_iterations = 0;
while (!impacted_methods.empty()) {
Timer t2("analysis iteration");
analysis_iterations++;
TRACE(OEA, 2, "[object escape analysis] analysis_iteration %zu",
analysis_iterations);
ConcurrentMap<DexMethod*, MethodSummary> recomputed_method_summaries;
workqueue_run<DexMethod*>(
[&](DexMethod* method) {
auto& cfg = method->get_code()->cfg();
Analyzer analyzer(method_summaries,
/* incomplete_marker_method */ nullptr, cfg);
const auto& escapes = analyzer.get_escapes();
const auto& returns = analyzer.get_returns();
src_index_t src_index = 0;
for (auto& mie : InstructionIterable(cfg.get_param_instructions())) {
if (mie.insn->opcode() == IOPCODE_LOAD_PARAM_OBJECT &&
escapes.at(mie.insn).empty() && !returns.count(mie.insn)) {
recomputed_method_summaries.update(
method, [src_index](DexMethod*, auto& ms, bool) {
ms.benign_params.insert(src_index);
});
}
src_index++;
}
const IRInstruction* allocation_insn;
if (returns.size() == 1 &&
(allocation_insn = *returns.begin()) != NO_ALLOCATION &&
escapes.at(allocation_insn).empty() &&
allocation_insn->opcode() != IOPCODE_LOAD_PARAM_OBJECT) {
recomputed_method_summaries.update(
method, [allocation_insn](DexMethod*, auto& ms, bool) {
ms.allocation_insn = allocation_insn;
});
}
},
impacted_methods);
std::unordered_set<DexMethod*> changed_methods;
// (Recomputed) summaries can only grow; assert that, update summaries when
// necessary, and remember for which methods the summaries actually changed.
for (auto&& [method, recomputed_summary] : recomputed_method_summaries) {
auto& summary = method_summaries[method];
for (auto src_index : summary.benign_params) {
always_assert(recomputed_summary.benign_params.count(src_index));
}
if (recomputed_summary.benign_params.size() >
summary.benign_params.size()) {
summary.benign_params = std::move(recomputed_summary.benign_params);
changed_methods.insert(method);
}
if (recomputed_summary.allocation_insn) {
if (summary.allocation_insn) {
always_assert(summary.allocation_insn ==
recomputed_summary.allocation_insn);
} else {
summary.allocation_insn = recomputed_summary.allocation_insn;
changed_methods.insert(method);
}
} else {
always_assert(summary.allocation_insn == nullptr);
}
}
impacted_methods.clear();
for (auto method : changed_methods) {
auto it = dependencies.find(method);
if (it != dependencies.end()) {
impacted_methods.insert(it->second.begin(), it->second.end());
}
}
}
mgr.incr_metric("analysis_iterations", analysis_iterations);
return method_summaries;
}
// For an inlinable new-instance or invoke- instruction, determine first
// resolved callee (if any), and (eventually) allocated type
std::pair<DexMethod*, DexType*> resolve_inlinable(
const MethodSummaries& method_summaries, const IRInstruction* insn) {
always_assert(insn->opcode() == OPCODE_NEW_INSTANCE ||
opcode::is_an_invoke(insn->opcode()));
DexMethod* first_callee{nullptr};
while (insn->opcode() != OPCODE_NEW_INSTANCE) {
always_assert(opcode::is_an_invoke(insn->opcode()));
auto callee = resolve_method(insn->get_method(), opcode_to_search(insn));
if (!first_callee) {
first_callee = callee;
}
insn = method_summaries.at(callee).allocation_insn;
}
return std::make_pair(first_callee, insn->get_type());
}
using InlineAnchorsOfType =
std::unordered_map<DexMethod*, std::unordered_set<IRInstruction*>>;
std::unordered_map<DexType*, InlineAnchorsOfType> compute_inline_anchors(
const Scope& scope, const MethodSummaries& method_summaries) {
Timer t("compute_inline_anchors");
ConcurrentMap<DexType*, InlineAnchorsOfType> concurrent_inline_anchors;
walk::parallel::code(scope, [&](DexMethod* method, IRCode& code) {
Analyzer analyzer(method_summaries, /* incomplete_marker_method */ nullptr,
code.cfg());
auto inlinables = analyzer.get_inlinables();
for (auto insn : inlinables) {
auto [callee, type] = resolve_inlinable(method_summaries, insn);
TRACE(OEA, 3, "[object escape analysis] inline anchor [%s] %s",
SHOW(method), SHOW(insn));
concurrent_inline_anchors.update(
type, [&](auto*, auto& map, bool) { map[method].insert(insn); });
}
});
return concurrent_inline_anchors.move_to_container();
}
class InlinedCodeSizeEstimator {
private:
using DeltaKey = std::pair<DexMethod*, const IRInstruction*>;
LazyUnorderedMap<DexMethod*, size_t> m_inlined_code_sizes;
LazyUnorderedMap<DexMethod*, live_range::DefUseChains> m_du_chains;
LazyUnorderedMap<DeltaKey, float, boost::hash<DeltaKey>> m_deltas;
public:
explicit InlinedCodeSizeEstimator(const MethodSummaries& method_summaries)
: m_inlined_code_sizes([](DexMethod* method) {
size_t code_size{0};
auto& cfg = method->get_code()->cfg();
for (auto& mie : InstructionIterable(cfg)) {
auto* insn = mie.insn;
// We do the cost estimation before shrinking, so we discount moves.
// Returns will go away after inlining.
if (opcode::is_a_move(insn->opcode()) ||
opcode::is_a_return(insn->opcode())) {
continue;
}
code_size += mie.insn->size();
}
return code_size;
}),
m_du_chains([](DexMethod* method) {
live_range::MoveAwareChains chains(method->get_code()->cfg());
return chains.get_def_use_chains();
}),
m_deltas([&](DeltaKey key) {
auto [method, allocation_insn] = key;
float delta = 0;
auto& du_chains = m_du_chains[method];
if (opcode::is_an_invoke(allocation_insn->opcode())) {
auto callee = resolve_method(allocation_insn->get_method(),
opcode_to_search(allocation_insn));
always_assert(callee);
auto* callee_allocation_insn =
method_summaries.at(callee).allocation_insn;
always_assert(callee_allocation_insn);
delta += m_inlined_code_sizes[callee] +
get_delta(callee, callee_allocation_insn) - COST_INVOKE -
COST_MOVE_RESULT;
} else if (allocation_insn->opcode() == OPCODE_NEW_INSTANCE) {
delta -= COST_NEW_INSTANCE;
}
for (auto& use :
du_chains[const_cast<IRInstruction*>(allocation_insn)]) {
if (opcode::is_an_invoke(use.insn->opcode())) {
delta -= COST_INVOKE;
auto callee = resolve_method(use.insn->get_method(),
opcode_to_search(use.insn));
always_assert(callee);
if (is_benign(callee)) {
continue;
}
auto load_param_insns = InstructionIterable(
callee->get_code()->cfg().get_param_instructions());
auto* load_param_insn =
std::next(load_param_insns.begin(), use.src_index)->insn;
always_assert(load_param_insn);
always_assert(opcode::is_a_load_param(load_param_insn->opcode()));
delta += m_inlined_code_sizes[callee] +
get_delta(callee, load_param_insn);
if (!callee->get_proto()->is_void()) {
delta -= COST_MOVE_RESULT;
}
} else if (opcode::is_an_iget(use.insn->opcode()) ||
opcode::is_an_iput(use.insn->opcode())) {
delta -= use.insn->size();
}
}
return delta;
}) {}
float get_delta(DexMethod* method, const IRInstruction* allocation_insn) {
return m_deltas[std::make_pair(method, allocation_insn)];
}
};
enum class InlinableTypeKind {
// All uses of this type have inline anchors in identified root methods. It is
// safe to inline all resolved inlinables.
CompleteSingleRoot,
// Same as CompleteSingleRoot, except that inlinable anchors are spread over
// multiple root methods.
CompleteMultipleRoots,
// Not all uses of this type have inlinable anchors. Only attempt to inline
// anchors present in original identified root methods.
Incomplete,
Last = Incomplete
};
using InlinableTypes = std::unordered_map<DexType*, InlinableTypeKind>;
std::unordered_map<DexMethod*, InlinableTypes> compute_root_methods(
PassManager& mgr,
const std::unordered_map<DexType*, Locations>& new_instances,
const std::unordered_map<DexMethod*, Locations>& invokes,
const MethodSummaries& method_summaries,
const std::unordered_map<DexType*, InlineAnchorsOfType>& inline_anchors) {
Timer t("compute_root_methods");
std::array<size_t, (size_t)(InlinableTypeKind::Last) + 1> candidate_types{
0, 0, 0};
std::unordered_map<DexMethod*, InlinableTypes> root_methods;
std::unordered_set<DexType*> inline_anchor_types;
std::mutex mutex; // protects candidate_types and root_methods
std::atomic<size_t> incomplete_estimated_delta_threshold_exceeded{0};
auto concurrent_add_root_methods = [&](DexType* type, bool complete) {
const auto& inline_anchors_of_type = inline_anchors.at(type);
InlinedCodeSizeEstimator inlined_code_size_estimator(method_summaries);
std::vector<DexMethod*> methods;
for (auto& [method, allocation_insns] : inline_anchors_of_type) {
auto it2 = method_summaries.find(method);
if (it2 != method_summaries.end() && it2->second.allocation_insn &&
resolve_inlinable(method_summaries, it2->second.allocation_insn)
.second == type) {
continue;
}
if (!complete) {
float delta = 0;
for (auto allocation_insn : allocation_insns) {
delta +=
inlined_code_size_estimator.get_delta(method, allocation_insn);
}
if (delta > INCOMPLETE_ESTIMATED_DELTA_THRESHOLD) {
// Skipping, as it's highly unlikely to results in an overall size
// win, while taking a very long time to compute exactly.
incomplete_estimated_delta_threshold_exceeded++;
continue;
}
}
methods.push_back(method);
}
if (methods.empty()) {
return;
}
bool multiple_roots = methods.size() > 1;
auto kind = complete ? multiple_roots
? InlinableTypeKind::CompleteMultipleRoots
: InlinableTypeKind::CompleteSingleRoot
: InlinableTypeKind::Incomplete;
std::lock_guard<std::mutex> lock_guard(mutex);
candidate_types[(size_t)kind]++;
for (auto method : methods) {
TRACE(OEA, 3, "[object escape analysis] root method %s with %s%s",
SHOW(method), SHOW(type),
kind == InlinableTypeKind::CompleteMultipleRoots
? " complete multiple-roots"
: kind == InlinableTypeKind::CompleteSingleRoot
? " complete single-root"
: " incomplete");
root_methods[method].emplace(type, kind);
}
};
for (auto& [type, method_insn_pairs] : new_instances) {
auto it = inline_anchors.find(type);
if (it == inline_anchors.end()) {
continue;
}
inline_anchor_types.insert(type);
}
workqueue_run<DexType*>(
[&](DexType* type) {
const auto& method_insn_pairs = new_instances.at(type);
const auto& inline_anchors_of_type = inline_anchors.at(type);
std::function<bool(const std::pair<DexMethod*, const IRInstruction*>&)>
is_anchored;
is_anchored = [&](const auto& p) {
auto [method, insn] = p;
auto it2 = inline_anchors_of_type.find(method);
if (it2 != inline_anchors_of_type.end() &&
it2->second.count(const_cast<IRInstruction*>(insn))) {
return true;
}
auto it3 = method_summaries.find(method);
if (it3 == method_summaries.end() ||
it3->second.allocation_insn != insn) {
return false;
}
auto it4 = invokes.find(method);
if (it4 == invokes.end()) {
return false;
}
for (auto q : it4->second) {
if (!is_anchored(q)) {
return false;
}
}
return true;
};
// Check whether all uses of this type have inline anchors optimizable
// root methods.
bool complete =
std::all_of(method_insn_pairs.begin(), method_insn_pairs.end(),
is_anchored) &&
std::all_of(
inline_anchors_of_type.begin(), inline_anchors_of_type.end(),
[](auto& p) { return !p.first->rstate.no_optimizations(); });
concurrent_add_root_methods(type, complete);
},
inline_anchor_types);
TRACE(OEA,
1,
"[object escape analysis] candidate types: %zu",
candidate_types.size());
mgr.incr_metric(
"candidate types CompleteSingleRoot",
candidate_types[(size_t)InlinableTypeKind::CompleteSingleRoot]);
mgr.incr_metric(
"candidate types CompleteMultipleRoots",
candidate_types[(size_t)InlinableTypeKind::CompleteMultipleRoots]);
mgr.incr_metric("candidate types Incomplete",
candidate_types[(size_t)InlinableTypeKind::Incomplete]);
mgr.incr_metric("incomplete_estimated_delta_threshold_exceeded",
(size_t)incomplete_estimated_delta_threshold_exceeded);
return root_methods;
}
size_t get_code_size(DexMethod* method) {
return method->get_code()->cfg().sum_opcode_sizes();
}
struct Stats {
std::atomic<size_t> total_savings{0};
std::atomic<size_t> reduced_methods{0};
std::atomic<size_t> reduced_methods_variants{0};
std::atomic<size_t> selected_reduced_methods{0};
std::atomic<size_t> invokes_not_inlinable_callee_unexpandable{0};
std::atomic<size_t> invokes_not_inlinable_callee_inconcrete{0};
std::atomic<size_t> invokes_not_inlinable_callee_too_many_params_to_expand{0};
std::atomic<size_t> invokes_not_inlinable_inlining{0};
std::atomic<size_t> invokes_not_inlinable_too_many_iterations{0};
std::atomic<size_t> anchors_not_inlinable_inlining{0};
std::atomic<size_t> stackify_returns_objects{0};
std::atomic<size_t> too_costly_multiple_conditional_classes{0};
std::atomic<size_t> too_costly_irreducible_classes{0};
std::atomic<size_t> too_costly_globally{0};
std::atomic<size_t> expanded_methods{0};
std::atomic<size_t> calls_inlined{0};
std::atomic<size_t> new_instances_eliminated{0};
};
// Data structure to derive local or accumulated global net savings
struct NetSavings {
int local{0};
std::unordered_set<DexType*> classes;
std::unordered_set<DexMethod*> methods;
NetSavings& operator+=(const NetSavings& other) {
local += other.local;
classes.insert(other.classes.begin(), other.classes.end());
methods.insert(other.methods.begin(), other.methods.end());
return *this;
}
// Estimate how many code units will be saved.
int get_value() const {
int net_savings{local};
// A class will only eventually get deleted if all static methods are
// inlined.
std::unordered_map<DexType*, std::unordered_set<DexMethod*>> smethods;
for (auto type : classes) {
auto cls = type_class(type);
always_assert(cls);
auto& type_smethods = smethods[type];
for (auto method : cls->get_dmethods()) {
if (is_static(method)) {
type_smethods.insert(method);
}
}
}
for (auto method : methods) {
if (can_delete(method)) {
auto code_size = get_code_size(method);
net_savings += COST_METHOD + code_size;
if (is_static(method)) {
smethods[method->get_class()].erase(method);
}
}
}
for (auto type : classes) {
auto cls = type_class(type);
always_assert(cls);
if (can_delete(cls) && cls->get_sfields().empty() && !cls->get_clinit()) {
auto& type_smethods = smethods[type];
if (type_smethods.empty()) {
net_savings += COST_CLASS;
}
}
for (auto field : cls->get_ifields()) {
if (can_delete(field)) {
net_savings += COST_FIELD;
}
}
}
return net_savings;
}
};
// Data structure that represents a (cloned) reduced method, together with some
// auxiliary information that allows to derive net savings.
struct ReducedMethod {
DexMethod* method;
size_t initial_code_size;
std::unordered_map<DexMethod*, std::unordered_set<DexType*>> inlined_methods;
InlinableTypes types;
size_t calls_inlined;
size_t new_instances_eliminated;
NetSavings get_net_savings(
const std::unordered_set<DexType*>& irreducible_types,
NetSavings* conditional_net_savings = nullptr) const {
auto final_code_size = get_code_size(method);
NetSavings net_savings;
net_savings.local = (int)initial_code_size - (int)final_code_size;
std::unordered_set<DexType*> remaining;
for (auto& [inlined_method, inlined_types] : inlined_methods) {
bool any_remaining = false;
bool any_incomplete = false;
for (auto type : inlined_types) {
auto kind = types.at(type);
if (kind != InlinableTypeKind::CompleteSingleRoot ||
irreducible_types.count(type)) {
remaining.insert(type);
any_remaining = true;
if (kind == InlinableTypeKind::Incomplete) {
any_incomplete = true;
}
}
}
if (any_remaining) {
if (conditional_net_savings && !any_incomplete) {
conditional_net_savings->methods.insert(inlined_method);
}
continue;
}
net_savings.methods.insert(inlined_method);
}
for (auto [type, kind] : types) {
if (remaining.count(type) ||
kind != InlinableTypeKind::CompleteSingleRoot ||
irreducible_types.count(type)) {
if (conditional_net_savings && kind != InlinableTypeKind::Incomplete) {
conditional_net_savings->classes.insert(type);
}
continue;
}
net_savings.classes.insert(type);
}
return net_savings;
}
};
class RootMethodReducer {
private:
const ExpandableMethodParams& m_expandable_method_params;
DexMethodRef* m_incomplete_marker_method;
MultiMethodInliner& m_inliner;
const MethodSummaries& m_method_summaries;
Stats* m_stats;
bool m_is_init_or_clinit;
DexMethod* m_method;
const InlinableTypes& m_types;
size_t m_calls_inlined{0};
size_t m_new_instances_eliminated{0};
size_t m_max_inline_size;
public:
RootMethodReducer(const ExpandableMethodParams& expandable_method_params,
DexMethodRef* incomplete_marker_method,
MultiMethodInliner& inliner,
const MethodSummaries& method_summaries,
Stats* stats,
bool is_init_or_clinit,
DexMethod* method,
const InlinableTypes& types,
size_t max_inline_size)
: m_expandable_method_params(expandable_method_params),
m_incomplete_marker_method(incomplete_marker_method),
m_inliner(inliner),
m_method_summaries(method_summaries),
m_stats(stats),
m_is_init_or_clinit(is_init_or_clinit),
m_method(method),
m_types(types),
m_max_inline_size(max_inline_size) {}
std::optional<ReducedMethod> reduce() {
auto initial_code_size{get_code_size(m_method)};
if (!inline_anchors() || !expand_or_inline_invokes()) {
return std::nullopt;
}
while (auto opt_p = find_inlinable_new_instance()) {
if (!stackify(opt_p->first, opt_p->second)) {
return std::nullopt;
}
}
auto* insn = find_incomplete_marker_methods();
always_assert_log(!insn,
"Incomplete marker {%s} present after reduction in\n%s",
SHOW(insn), SHOW(m_method->get_code()->cfg()));
shrink();
return (ReducedMethod){
m_method, initial_code_size, std::move(m_inlined_methods),
m_types, m_calls_inlined, m_new_instances_eliminated};
}
private:
void shrink() {
m_inliner.get_shrinker().shrink_code(m_method->get_code(),
is_static(m_method),
m_is_init_or_clinit,
m_method->get_class(),
m_method->get_proto(),
[this]() { return show(m_method); });
}
bool inline_insns(const std::unordered_set<IRInstruction*>& insns) {
auto inlined = m_inliner.inline_callees(m_method, insns);
m_calls_inlined += inlined;
return inlined == insns.size();
}
// Given a method invocation, replace a particular argument with the
// sequence of the argument's field values to flow into an expanded
// method.
DexMethodRef* expand_invoke(cfg::CFGMutation& mutation,
const cfg::InstructionIterator& it,
param_index_t param_index) {
auto insn = it->insn;
auto callee = resolve_method(insn->get_method(), opcode_to_search(insn));
always_assert(callee);
always_assert(callee->is_concrete());
std::vector<DexField*>* fields;
auto expanded_method_ref =
m_expandable_method_params.get_expanded_method_ref(callee, param_index,
&fields);
if (!expanded_method_ref) {
return nullptr;
}
insn->set_method(expanded_method_ref);
if (!method::is_init(expanded_method_ref)) {
insn->set_opcode(OPCODE_INVOKE_STATIC);
}
auto obj_reg = insn->src(param_index);
auto srcs_range = insn->srcs();
std::vector<reg_t> srcs_copy(srcs_range.begin(), srcs_range.end());
insn->set_srcs_size(srcs_copy.size() - 1 + fields->size());
for (param_index_t i = param_index; i < srcs_copy.size() - 1; i++) {
insn->set_src(i + fields->size(), srcs_copy.at(i + 1));
}
std::vector<IRInstruction*> instructions_to_insert;
auto& cfg = m_method->get_code()->cfg();
for (auto field : *fields) {
auto reg = type::is_wide_type(field->get_type())
? cfg.allocate_wide_temp()
: cfg.allocate_temp();
insn->set_src(param_index++, reg);
auto iget_opcode = opcode::iget_opcode_for_field(field);
instructions_to_insert.push_back((new IRInstruction(iget_opcode))
->set_src(0, obj_reg)
->set_field(field));
auto move_result_pseudo_opcode =
opcode::move_result_pseudo_for_iget(iget_opcode);
instructions_to_insert.push_back(
(new IRInstruction(move_result_pseudo_opcode))->set_dest(reg));
}
mutation.insert_before(it, std::move(instructions_to_insert));
return expanded_method_ref;
}
bool expand_invokes(const std::unordered_map<IRInstruction*, param_index_t>&
invokes_to_expand,
std::unordered_set<DexMethodRef*>* expanded_method_refs) {
if (invokes_to_expand.empty()) {
return true;
}
auto& cfg = m_method->get_code()->cfg();
cfg::CFGMutation mutation(cfg);
auto ii = InstructionIterable(cfg);
for (auto it = ii.begin(); it != ii.end(); it++) {
auto insn = it->insn;
auto it2 = invokes_to_expand.find(insn);
if (it2 == invokes_to_expand.end()) {
continue;
}
auto param_index = it2->second;
auto expanded_method_ref = expand_invoke(mutation, it, param_index);
if (!expanded_method_ref) {
return false;
}
expanded_method_refs->insert(expanded_method_ref);
}
mutation.flush();
return true;
}
// Inline all "anchors" until all relevant allocations are new-instance
// instructions in the (root) method.
bool inline_anchors() {
auto& cfg = m_method->get_code()->cfg();
for (int iteration = 0; true; iteration++) {
Analyzer analyzer(m_method_summaries, m_incomplete_marker_method, cfg);
std::unordered_set<IRInstruction*> invokes_to_inline;
auto inlinables = analyzer.get_inlinables();
Lazy<live_range::DefUseChains> du_chains([&]() {
live_range::MoveAwareChains chains(cfg);
return chains.get_def_use_chains();
});
cfg::CFGMutation mutation(cfg);
for (auto insn : inlinables) {
auto [callee, type] = resolve_inlinable(m_method_summaries, insn);
auto it = m_types.find(type);
if (it == m_types.end()) {
continue;
}
if (it->second == InlinableTypeKind::Incomplete) {
// We are only going to consider incompletely inlinable types when we
// find them in the first iteration, i.e. in the original method,
// and not coming from any inlined method. We are then going insert
// a special marker invocation instruction so that we can later find
// the originally matched anchors again. This instruction will get
// removed later.
if (!has_incomplete_marker((*du_chains)[insn])) {
if (iteration > 0) {
continue;
}
auto insn_it = cfg.find_insn(insn);
always_assert(!insn_it.is_end());
auto move_result_it = cfg.move_result_of(insn_it);
if (move_result_it.is_end()) {
continue;
}
auto invoke_insn = (new IRInstruction(OPCODE_INVOKE_STATIC))
->set_method(m_incomplete_marker_method)
->set_srcs_size(1)
->set_src(0, move_result_it->insn->dest());
mutation.insert_after(move_result_it, {invoke_insn});
}
}
if (!callee) {
continue;
}
invokes_to_inline.insert(insn);
m_inlined_methods[callee].insert(type);
}
mutation.flush();
if (invokes_to_inline.empty()) {
return true;
}
if (!inline_insns(invokes_to_inline)) {
m_stats->anchors_not_inlinable_inlining++;
return false;
}
// simplify to prune now unreachable code, e.g. from removed exception
// handlers
cfg.simplify();
}
}
bool is_inlinable_new_instance(IRInstruction* insn) const {
return insn->opcode() == OPCODE_NEW_INSTANCE &&
m_types.count(insn->get_type());
}
bool is_incomplete_marker(IRInstruction* insn) const {
return insn->opcode() == OPCODE_INVOKE_STATIC &&
insn->get_method() == m_incomplete_marker_method;
}
bool has_incomplete_marker(
const std::unordered_set<live_range::Use>& uses) const {
return std::any_of(uses.begin(), uses.end(), [&](auto& use) {
return is_incomplete_marker(use.insn);
});
}
IRInstruction* find_incomplete_marker_methods() {
auto& cfg = m_method->get_code()->cfg();
for (auto& mie : InstructionIterable(cfg)) {
if (is_incomplete_marker(mie.insn)) {
return mie.insn;
}
}
return nullptr;
}
std::optional<std::pair<live_range::DefUseChains, IRInstruction*>>
find_inlinable_new_instance() const {
auto& cfg = m_method->get_code()->cfg();
Lazy<live_range::DefUseChains> du_chains([&]() {
live_range::MoveAwareChains chains(cfg);
return chains.get_def_use_chains();
});
for (auto& mie : InstructionIterable(cfg)) {
auto insn = mie.insn;
if (!is_inlinable_new_instance(insn)) {
continue;
}
auto type = insn->get_type();
if (m_types.at(type) == InlinableTypeKind::Incomplete &&
!has_incomplete_marker((*du_chains)[insn])) {
continue;
}
return std::make_optional(std::pair(std::move(*du_chains), insn));
}
return std::nullopt;
}
bool should_expand(
DexMethod* callee,
const std::unordered_map<src_index_t, DexType*>& src_indices) {
always_assert(!src_indices.empty());
if (method::is_init(callee) && !src_indices.count(0)) {
return true;
}
if (src_indices.size() > 1) {
return false;
}
auto [param_index, type] = *src_indices.begin();
bool multiples =
m_types.at(type) == InlinableTypeKind::CompleteMultipleRoots;
if (multiples && get_code_size(callee) > m_max_inline_size &&
m_expandable_method_params.get_expanded_method_ref(callee,
param_index)) {
return true;
}
return false;
}
// Expand or inline all uses of all relevant new-instance instructions that
// involve invoke- instructions, until there are no more such uses.
bool expand_or_inline_invokes() {
auto& cfg = m_method->get_code()->cfg();
std::unordered_set<DexMethodRef*> expanded_method_refs;
for (int iteration = 0; iteration < MAX_INLINE_INVOKES_ITERATIONS;
iteration++) {
std::unordered_set<IRInstruction*> invokes_to_inline;
std::unordered_map<IRInstruction*, param_index_t> invokes_to_expand;
live_range::MoveAwareChains chains(cfg);
auto du_chains = chains.get_def_use_chains();
std::unordered_map<IRInstruction*,
std::unordered_map<src_index_t, DexType*>>
aggregated_uses;
for (auto& [insn, uses] : du_chains) {
if (!is_inlinable_new_instance(insn)) {
continue;
}
auto type = insn->get_type();
if (m_types.at(type) == InlinableTypeKind::Incomplete &&
!has_incomplete_marker(uses)) {
continue;
}
for (auto& use : uses) {
auto emplaced =
aggregated_uses[use.insn].emplace(use.src_index, type).second;
always_assert(emplaced);
}
}
for (auto&& [uses_insn, src_indices] : aggregated_uses) {
if (!opcode::is_an_invoke(uses_insn->opcode()) ||
is_benign(uses_insn->get_method()) ||
is_incomplete_marker(uses_insn)) {
continue;
}
if (expanded_method_refs.count(uses_insn->get_method())) {
m_stats->invokes_not_inlinable_callee_inconcrete++;
return false;
}
auto callee = resolve_method(uses_insn->get_method(),
opcode_to_search(uses_insn));
always_assert(callee);
always_assert(callee->is_concrete());
if (should_expand(callee, src_indices)) {
if (src_indices.size() > 1) {
m_stats->invokes_not_inlinable_callee_too_many_params_to_expand++;
return false;
}
always_assert(src_indices.size() == 1);
auto src_index = src_indices.begin()->first;
invokes_to_expand.emplace(uses_insn, src_index);
continue;
}
invokes_to_inline.insert(uses_insn);
for (auto [src_index, type] : src_indices) {
m_inlined_methods[callee].insert(type);
}
}
if (!expand_invokes(invokes_to_expand, &expanded_method_refs)) {
m_stats->invokes_not_inlinable_callee_unexpandable++;
return false;
}
if (invokes_to_inline.empty()) {
// Nothing else to do
return true;
}
if (!inline_insns(invokes_to_inline)) {
m_stats->invokes_not_inlinable_inlining++;
return false;
}
// simplify to prune now unreachable code, e.g. from removed exception
// handlers
cfg.simplify();
}
m_stats->invokes_not_inlinable_too_many_iterations++;
return false;
}
// Given a new-instance instruction whose (main) uses are as the receiver in
// iget- and iput- instruction, transform all such field accesses into
// accesses to registers, one per field.
bool stackify(live_range::DefUseChains& du_chains,
IRInstruction* new_instance_insn) {
auto& cfg = m_method->get_code()->cfg();
std::unordered_map<DexField*, reg_t> field_regs;
std::vector<DexField*> ordered_fields;
auto get_field_reg = [&](DexFieldRef* ref) {
always_assert(ref->is_def());
auto field = ref->as_def();
auto it = field_regs.find(field);
if (it == field_regs.end()) {
auto wide = type::is_wide_type(field->get_type());
auto reg = wide ? cfg.allocate_wide_temp() : cfg.allocate_temp();
it = field_regs.emplace(field, reg).first;
ordered_fields.push_back(field);
}
return it->second;
};
auto& uses = du_chains[new_instance_insn];
std::unordered_set<IRInstruction*> instructions_to_replace;
bool identity_matters{false};
for (auto& use : uses) {
auto opcode = use.insn->opcode();
if (opcode::is_an_iput(opcode)) {
always_assert(use.src_index == 1);
} else if (opcode::is_an_invoke(opcode) || opcode::is_a_monitor(opcode)) {
always_assert(use.src_index == 0);
} else if (opcode == OPCODE_IF_EQZ || opcode == OPCODE_IF_NEZ) {
identity_matters = true;
continue;
} else if (opcode::is_move_object(opcode)) {
continue;
} else if (opcode::is_return_object(opcode)) {
// Can happen if the root method is also an allocator
m_stats->stackify_returns_objects++;
return false;
} else {
always_assert_log(
opcode::is_an_iget(opcode) || opcode::is_instance_of(opcode),
"Unexpected use: %s at %u", SHOW(use.insn), use.src_index);
}
instructions_to_replace.insert(use.insn);
}
cfg::CFGMutation mutation(cfg);
auto ii = InstructionIterable(cfg);
auto new_instance_insn_it = ii.end();
for (auto it = ii.begin(); it != ii.end(); it++) {
auto insn = it->insn;
if (!instructions_to_replace.count(insn)) {
if (insn == new_instance_insn) {
new_instance_insn_it = it;
}
continue;
}
auto opcode = insn->opcode();
if (opcode::is_an_iget(opcode)) {
auto move_result_it = cfg.move_result_of(it);
auto new_insn = (new IRInstruction(opcode::iget_to_move(opcode)))
->set_src(0, get_field_reg(insn->get_field()))
->set_dest(move_result_it->insn->dest());
mutation.replace(it, {new_insn});
} else if (opcode::is_an_iput(opcode)) {
auto new_insn = (new IRInstruction(opcode::iput_to_move(opcode)))
->set_src(0, insn->src(0))
->set_dest(get_field_reg(insn->get_field()));
mutation.replace(it, {new_insn});
} else if (opcode::is_an_invoke(opcode)) {
always_assert(is_benign(insn->get_method()) ||
is_incomplete_marker(insn));
if (is_incomplete_marker(insn) || !identity_matters) {
mutation.remove(it);
}
} else if (opcode::is_instance_of(opcode)) {
auto move_result_it = cfg.move_result_of(it);
auto new_insn =
(new IRInstruction(OPCODE_CONST))
->set_literal(type::is_subclass(insn->get_type(),
new_instance_insn->get_type()))
->set_dest(move_result_it->insn->dest());
mutation.replace(it, {new_insn});
} else if (opcode::is_a_monitor(opcode)) {
mutation.remove(it);
} else {
not_reached();
}
}
always_assert(!new_instance_insn_it.is_end());
auto init_class_insn =
m_inliner.get_shrinker()
.get_init_classes_with_side_effects()
.create_init_class_insn(new_instance_insn->get_type());
if (init_class_insn) {
mutation.insert_before(new_instance_insn_it, {init_class_insn});
}
if (identity_matters) {
new_instance_insn_it->insn->set_type(type::java_lang_Object());
} else {
auto move_result_it = cfg.move_result_of(new_instance_insn_it);
auto new_insn = (new IRInstruction(OPCODE_CONST))
->set_literal(0)
->set_dest(move_result_it->insn->dest());
mutation.replace(new_instance_insn_it, {new_insn});
}
// Insert zero-initialization code for field registers.
std::sort(ordered_fields.begin(), ordered_fields.end(), compare_dexfields);
std::vector<IRInstruction*> field_inits;
field_inits.reserve(ordered_fields.size());
for (auto field : ordered_fields) {
auto wide = type::is_wide_type(field->get_type());
auto opcode = wide ? OPCODE_CONST_WIDE : OPCODE_CONST;
auto reg = field_regs.at(field);
auto new_insn =
(new IRInstruction(opcode))->set_literal(0)->set_dest(reg);
field_inits.push_back(new_insn);
}
mutation.insert_before(new_instance_insn_it, field_inits);
mutation.flush();
// simplify to prune now unreachable code, e.g. from removed exception
// handlers
cfg.simplify();
m_new_instances_eliminated++;
return true;
}
std::unordered_map<DexMethod*, std::unordered_set<DexType*>>
m_inlined_methods;
};
// Reduce all root methods to a set of variants. The reduced methods are ordered
// by how many types where inlined, with the largest number of inlined types
// going first.
std::unordered_map<DexMethod*, std::vector<ReducedMethod>>
compute_reduced_methods(
ExpandableMethodParams& expandable_method_params,
MultiMethodInliner& inliner,
const MethodSummaries& method_summaries,
const std::unordered_map<DexMethod*, InlinableTypes>& root_methods,
std::unordered_set<DexType*>* irreducible_types,
Stats* stats,
size_t max_inline_size) {
Timer t("compute_reduced_methods");
// We are not exploring all possible subsets of types, but only single chain
// of subsets, guided by the inlinable kind, and by how often
// they appear as inlinable types in root methods.
// TODO: Explore all possible subsets of types.
std::unordered_map<DexType*, size_t> occurrences;
for (auto&& [method, types] : root_methods) {
for (auto [type, kind] : types) {
occurrences[type]++;
}
}
workqueue_run<std::pair<DexMethod*, InlinableTypes>>(
[&](const std::pair<DexMethod*, InlinableTypes>& p) {
const auto& [method, types] = p;
inliner.get_shrinker().shrink_method(method);
},
root_methods);
// This comparison function implies the sequence of inlinable type subsets
// we'll consider. We'll structure the sequence such that often occurring
// types with multiple uses will be chopped off the type set first.
auto less = [&occurrences](auto& p, auto& q) {
// We sort types with incomplete anchors to the front.
if (p.second != q.second) {
return p.second > q.second;
}
// We sort types with more frequent occurrences to the front.
auto p_count = occurrences.at(p.first);
auto q_count = occurrences.at(q.first);
if (p_count != q_count) {
return p_count > q_count;
}
// Tie breaker.
return compare_dextypes(p.first, q.first);
};
// We'll now compute the set of variants we'll consider. For each root method
// with N inlinable types, there will be N variants.
std::vector<std::pair<DexMethod*, InlinableTypes>>
ordered_root_methods_variants;
for (auto&& [method, types] : root_methods) {
std::vector<std::pair<DexType*, InlinableTypeKind>> ordered_types(
types.begin(), types.end());
std::sort(ordered_types.begin(), ordered_types.end(), less);
for (auto it = ordered_types.begin(); it != ordered_types.end(); it++) {
ordered_root_methods_variants.emplace_back(
method, InlinableTypes(it, ordered_types.end()));
}
}
// Order such that items with many types to process go first, which improves
// workqueue efficiency.
std::stable_sort(ordered_root_methods_variants.begin(),
ordered_root_methods_variants.end(), [](auto& a, auto& b) {
return a.second.size() > b.second.size();
});
// Special marker method, used to identify which newly created objects of only
// incompletely inlinable types should get inlined.
DexMethodRef* incomplete_marker_method = DexMethod::make_method(
"Lredex/$ObjectEscapeAnalysis;.markIncomplete:(Ljava/lang/Object;)V");
// We make a copy before we start reducing a root method, in case we run
// into issues, or negative net savings.
ConcurrentMap<DexMethod*, std::vector<ReducedMethod>>
concurrent_reduced_methods;
workqueue_run<std::pair<DexMethod*, InlinableTypes>>(
[&](const std::pair<DexMethod*, InlinableTypes>& p) {
auto* method = p.first;
const auto& types = p.second;
auto copy_name_str =
method->get_name()->str() + "$oea$" + std::to_string(types.size());
auto copy = DexMethod::make_method_from(
method, method->get_class(), DexString::make_string(copy_name_str));
RootMethodReducer root_method_reducer{expandable_method_params,
incomplete_marker_method,
inliner,
method_summaries,
stats,
method::is_init(method) ||
method::is_clinit(method),
copy,
types,
max_inline_size};
auto reduced_method = root_method_reducer.reduce();
if (reduced_method) {
concurrent_reduced_methods.update(
method, [&](auto*, auto& reduced_methods_variants, bool) {
reduced_methods_variants.emplace_back(
std::move(*reduced_method));
});
return;
}
DexMethod::erase_method(copy);
DexMethod::delete_method_DO_NOT_USE(copy);
},
ordered_root_methods_variants);
// For each root method, we order the reduced methods (if any) by how many
// types where inlined, with the largest number of inlined types going first.
std::unordered_map<DexMethod*, std::vector<ReducedMethod>> reduced_methods;
for (auto& [method, reduced_methods_variants] : concurrent_reduced_methods) {
std::sort(
reduced_methods_variants.begin(), reduced_methods_variants.end(),
[&](auto& a, auto& b) { return a.types.size() > b.types.size(); });
reduced_methods.emplace(method, std::move(reduced_methods_variants));
}
// All types which could not be accomodated by any reduced method variants are
// marked as "irreducible", which is later used when doing a global cost
// analysis.
static const InlinableTypes no_types;
for (auto&& [method, types] : root_methods) {
auto it = reduced_methods.find(method);
const auto& largest_types =
it == reduced_methods.end() ? no_types : it->second.front().types;
for (auto&& [type, kind] : types) {
if (!largest_types.count(type)) {
irreducible_types->insert(type);
}
}
}
return reduced_methods;
}
// Select all those reduced methods which will result in overall size savings,
// either by looking at local net savings for just a single reduced method, or
// by considering families of reduced methods that affect the same classes.
std::unordered_map<DexMethod*, size_t> select_reduced_methods(
const std::unordered_map<DexMethod*, std::vector<ReducedMethod>>&
reduced_methods,
std::unordered_set<DexType*>* irreducible_types,
Stats* stats) {
Timer t("select_reduced_methods");
// First, we are going to identify all reduced methods which will result in
// local net savings, considering just a single reduced method at a time.
// We'll also build up families of reduced methods for which we can later do a
// global net savings analysis.
ConcurrentSet<DexType*> concurrent_irreducible_types;
ConcurrentMap<DexMethod*, size_t> concurrent_selected_reduced_methods;
// A family of reduced methods for which we'll look at the combined global net
// savings
struct Family {
// Maps root methods to an index into the reduced method variants list.
std::unordered_map<DexMethod*, size_t> reduced_methods;
NetSavings global_net_savings;
};
ConcurrentMap<DexType*, Family> concurrent_families;
workqueue_run<std::pair<DexMethod*, std::vector<ReducedMethod>>>(
[&](const std::pair<DexMethod*, std::vector<ReducedMethod>>& p) {
auto method = p.first;
const auto& reduced_methods_variants = p.second;
always_assert(!reduced_methods_variants.empty());
auto update_irreducible_types = [&](size_t i) {
const auto& reduced_method = reduced_methods_variants.at(i);
const auto& reduced_types = reduced_method.types;
for (auto&& [type, kind] : reduced_methods_variants.at(0).types) {
if (!reduced_types.count(type) &&
kind != InlinableTypeKind::Incomplete) {
concurrent_irreducible_types.insert(type);
}
}
};
// We'll try to find the maximal (involving most inlined non-incomplete
// types) reduced method variant for which we can make the largest
// non-negative local cost determination.
boost::optional<std::pair<size_t, int>> best_candidate;
for (size_t i = 0; i < reduced_methods_variants.size(); i++) {
// If we couldn't accommodate any types, we'll need to add them to the
// irreducible types set. Except for the last variant with the least
// inlined types, for which might below try to make a global cost
// determination.
const auto& reduced_method = reduced_methods_variants.at(i);
auto savings =
reduced_method.get_net_savings(*irreducible_types).get_value();
if (!best_candidate || savings > best_candidate->second) {
best_candidate = std::make_pair(i, savings);
}
// If there are no incomplete types left, we can stop here
const auto& reduced_types = reduced_method.types;
if (best_candidate && best_candidate->second >= 0 &&
!std::any_of(reduced_types.begin(), reduced_types.end(),
[](auto& p) {
return p.second == InlinableTypeKind::Incomplete;
})) {
break;
}
}
if (best_candidate && best_candidate->second >= 0) {
auto [i, savings] = *best_candidate;
stats->total_savings += savings;
concurrent_selected_reduced_methods.emplace(method, i);
update_irreducible_types(i);
return;
}
update_irreducible_types(reduced_methods_variants.size() - 1);
const auto& smallest_reduced_method = reduced_methods_variants.back();
NetSavings conditional_net_savings;
auto local_net_savings = smallest_reduced_method.get_net_savings(
*irreducible_types, &conditional_net_savings);
const auto& classes = conditional_net_savings.classes;
if (std::any_of(classes.begin(), classes.end(), [&](DexType* type) {
return irreducible_types->count(type);
})) {
stats->too_costly_irreducible_classes++;
} else if (classes.size() > 1) {
stats->too_costly_multiple_conditional_classes++;
} else if (classes.empty()) {
stats->too_costly_globally++;
} else {
always_assert(classes.size() == 1);
// For a reduced method variant with only a single involved class,
// we'll do a global cost analysis below.
auto conditional_type = *classes.begin();
concurrent_families.update(
conditional_type, [&](auto*, Family& family, bool) {
family.global_net_savings += local_net_savings;
family.global_net_savings += conditional_net_savings;
family.reduced_methods.emplace(
method, reduced_methods_variants.size() - 1);
});
return;
}
for (auto [type, kind] : smallest_reduced_method.types) {
concurrent_irreducible_types.insert(type);
}
},
reduced_methods);
irreducible_types->insert(concurrent_irreducible_types.begin(),
concurrent_irreducible_types.end());
// Second, perform global net savings analysis
workqueue_run<std::pair<DexType*, Family>>(
[&](const std::pair<DexType*, Family>& p) {
auto& [type, family] = p;
if (irreducible_types->count(type) ||
family.global_net_savings.get_value() < 0) {
stats->too_costly_globally += family.reduced_methods.size();
return;
}
stats->total_savings += family.global_net_savings.get_value();
for (auto& [method, i] : family.reduced_methods) {
concurrent_selected_reduced_methods.emplace(method, i);
}
},
concurrent_families);
return std::unordered_map<DexMethod*, size_t>(
concurrent_selected_reduced_methods.begin(),
concurrent_selected_reduced_methods.end());
}
void reduce(DexStoresVector& stores,
const Scope& scope,
ConfigFiles& conf,
const init_classes::InitClassesWithSideEffects&
init_classes_with_side_effects,
const MethodSummaries& method_summaries,
const std::unordered_map<DexMethod*, InlinableTypes>& root_methods,
Stats* stats,
size_t max_inline_size) {
Timer t("reduce");
ConcurrentMethodRefCache concurrent_resolved_refs;
auto concurrent_resolver = [&](DexMethodRef* method, MethodSearch search) {
return resolve_method(method, search, concurrent_resolved_refs);
};
std::unordered_set<DexMethod*> no_default_inlinables;
// customize shrinking options
auto inliner_config = conf.get_inliner_config();
inliner_config.shrinker = shrinker::ShrinkerConfig();
inliner_config.shrinker.run_const_prop = true;
inliner_config.shrinker.run_cse = true;
inliner_config.shrinker.run_copy_prop = true;
inliner_config.shrinker.run_local_dce = true;
inliner_config.shrinker.compute_pure_methods = false;
int min_sdk = 0;
MultiMethodInliner inliner(scope, init_classes_with_side_effects, stores,
no_default_inlinables, concurrent_resolver,
inliner_config, min_sdk,
MultiMethodInlinerMode::None);
// First, we compute all reduced methods
ExpandableMethodParams expandable_method_params(scope);
std::unordered_set<DexType*> irreducible_types;
auto reduced_methods = compute_reduced_methods(
expandable_method_params, inliner, method_summaries, root_methods,
&irreducible_types, stats, max_inline_size);
stats->reduced_methods = reduced_methods.size();
// Second, we select reduced methods that will result in net savings
auto selected_reduced_methods =
select_reduced_methods(reduced_methods, &irreducible_types, stats);
stats->selected_reduced_methods = selected_reduced_methods.size();
// Finally, we are going to apply those selected methods, and clean up all
// reduced method clones
workqueue_run<std::pair<DexMethod*, std::vector<ReducedMethod>>>(
[&](const std::pair<DexMethod*, std::vector<ReducedMethod>>& p) {
auto& [method, reduced_methods_variants] = p;
auto it = selected_reduced_methods.find(method);
if (it != selected_reduced_methods.end()) {
auto& reduced_method = reduced_methods_variants.at(it->second);
method->set_code(reduced_method.method->release_code());
stats->calls_inlined += reduced_method.calls_inlined;
stats->new_instances_eliminated +=
reduced_method.new_instances_eliminated;
}
stats->reduced_methods_variants += reduced_methods_variants.size();
for (auto& reduced_method : reduced_methods_variants) {
DexMethod::erase_method(reduced_method.method);
DexMethod::delete_method_DO_NOT_USE(reduced_method.method);
}
},
reduced_methods);
size_t expanded_methods = expandable_method_params.flush(scope);
stats->expanded_methods += expanded_methods;
}
} // namespace
void ObjectEscapeAnalysisPass::bind_config() {
bind("max_inline_size", MAX_INLINE_SIZE, m_max_inline_size);
}
void ObjectEscapeAnalysisPass::run_pass(DexStoresVector& stores,
ConfigFiles& conf,
PassManager& mgr) {
const auto scope = build_class_scope(stores);
auto method_override_graph = mog::build_graph(scope);
init_classes::InitClassesWithSideEffects init_classes_with_side_effects(
scope, conf.create_init_class_insns(), method_override_graph.get());
auto non_overridden_virtuals =
hier::find_non_overridden_virtuals(*method_override_graph);
std::unordered_map<DexType*, Locations> new_instances;
std::unordered_map<DexMethod*, Locations> invokes;
std::unordered_map<DexMethod*, std::unordered_set<DexMethod*>> dependencies;
analyze_scope(scope, non_overridden_virtuals, &new_instances, &invokes,
&dependencies);
auto method_summaries = compute_method_summaries(mgr, scope, dependencies,
non_overridden_virtuals);
auto inline_anchors = compute_inline_anchors(scope, method_summaries);
auto root_methods = compute_root_methods(mgr, new_instances, invokes,
method_summaries, inline_anchors);
Stats stats;
reduce(stores, scope, conf, init_classes_with_side_effects, method_summaries,
root_methods, &stats, m_max_inline_size);
walk::parallel::code(scope,
[&](DexMethod*, IRCode& code) { code.clear_cfg(); });
TRACE(OEA, 1, "[object escape analysis] total savings: %zu",
(size_t)stats.total_savings);
TRACE(
OEA, 1,
"[object escape analysis] %zu root methods lead to %zu reduced root "
"methods with %zu variants "
"of which %zu were selected and %zu anchors not inlinable because "
"inlining failed, %zu/%zu invokes not inlinable because callee is "
"init, %zu invokes not inlinable because callee is not concrete,"
"%zu invokes not inlinable because inlining failed, %zu invokes not "
"inlinable after too many iterations, %zu stackify returned objects, "
"%zu too costly with irreducible classes, %zu too costly with multiple "
"conditional classes, %zu too costly globally; %zu expanded methods; %zu "
"calls inlined; %zu new-instances eliminated",
root_methods.size(), (size_t)stats.reduced_methods,
(size_t)stats.reduced_methods_variants,
(size_t)stats.selected_reduced_methods,
(size_t)stats.anchors_not_inlinable_inlining,
(size_t)stats.invokes_not_inlinable_callee_unexpandable,
(size_t)stats.invokes_not_inlinable_callee_too_many_params_to_expand,
(size_t)stats.invokes_not_inlinable_callee_inconcrete,
(size_t)stats.invokes_not_inlinable_inlining,
(size_t)stats.invokes_not_inlinable_too_many_iterations,
(size_t)stats.stackify_returns_objects,
(size_t)stats.too_costly_irreducible_classes,
(size_t)stats.too_costly_multiple_conditional_classes,
(size_t)stats.too_costly_globally, (size_t)stats.expanded_methods,
(size_t)stats.calls_inlined, (size_t)stats.new_instances_eliminated);
mgr.incr_metric("total_savings", stats.total_savings);
mgr.incr_metric("root_methods", root_methods.size());
mgr.incr_metric("reduced_methods", (size_t)stats.reduced_methods);
mgr.incr_metric("reduced_methods_variants",
(size_t)stats.reduced_methods_variants);
mgr.incr_metric("selected_reduced_methods",
(size_t)stats.selected_reduced_methods);
mgr.incr_metric("root_method_anchors_not_inlinable_inlining",
(size_t)stats.anchors_not_inlinable_inlining);
mgr.incr_metric("root_method_invokes_not_inlinable_callee_unexpandable",
(size_t)stats.invokes_not_inlinable_callee_unexpandable);
mgr.incr_metric(
"root_method_invokes_not_inlinable_callee_is_init_too_many_params_to_"
"expand",
(size_t)stats.invokes_not_inlinable_callee_too_many_params_to_expand);
mgr.incr_metric("root_method_invokes_not_inlinable_callee_inconcrete",
(size_t)stats.invokes_not_inlinable_callee_inconcrete);
mgr.incr_metric("root_method_invokes_not_inlinable_inlining",
(size_t)stats.invokes_not_inlinable_inlining);
mgr.incr_metric("root_method_invokes_not_inlinable_too_many_iterations",
(size_t)stats.invokes_not_inlinable_too_many_iterations);
mgr.incr_metric("root_method_stackify_returns_objects",
(size_t)stats.stackify_returns_objects);
mgr.incr_metric("root_method_too_costly_globally",
(size_t)stats.too_costly_globally);
mgr.incr_metric("root_method_too_costly_multiple_conditional_classes",
(size_t)stats.too_costly_multiple_conditional_classes);
mgr.incr_metric("root_method_too_costly_irreducible_classes",
(size_t)stats.too_costly_irreducible_classes);
mgr.incr_metric("expanded_methods", (size_t)stats.expanded_methods);
mgr.incr_metric("calls_inlined", (size_t)stats.calls_inlined);
mgr.incr_metric("new_instances_eliminated",
(size_t)stats.new_instances_eliminated);
}
static ObjectEscapeAnalysisPass s_pass;
Remove outdated TODOs
Summary: The removed items have already been addressed.
Reviewed By: NicholasGorski
Differential Revision: D40739825
fbshipit-source-id: 2024d56bdc2ee856f75e2c957f1c22f6710c2247
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/*
* This pass identifies tracable object allocations that don't escape, and then
* attempts to inline all code interacting with the local object, turning all
* instance fields into registers. The changes are only applied when the
* estimated savings are not negative. This helps reduce...
* - object allocations at runtime, and
* - code size by eliminating a many of the involved classes, fields and
* methods.
*
* At the core is an interprocedural escape analysis with method-level summaries
* that...
* - may include results of method invocations as allocations, and
* - follows arguments to non-true-virtual method invocations.
*
* This pass is conservative: Any use of an object allocation that isn't fully
* understood, e.g. an external method invocation, causes that allocation to
* become ineligable for optimization. In any case, this pass will not transform
* a root method with the no_optimizations annotation.
*
* The pass computes...
* - method summaries, indicating whether a method allocates and returns an
* object that doesn't otherwise escape, and which method arguments don't
* escape
* - "inline anchors", which are particular instructions (in particular methods)
* which produce a new unescaped object, either by directly allocating it or
* invoking a method that directly or indirect allocates and returns an object
* that doesn't otherwise escape, and then possibly use that object in ways
* where it doesn't escape
* - "root methods", which are all the methods which contain "inline anchors" of
* types whose allocation instructions are all ultimately inlinably anchored.
* - "reduced methods", which are root methods where all inlinable anchors got
* fully inlined, and the fields of allocated objects got turned into
* registers (and the transformation does not produce estimated negative net
* savings)
*
* Notes:
* - The transformation doesn't directly eliminate the object allocation, as the
* object might be involved in some identity comparisons, e.g. for
* null-checks. Instead, the object allocation gets rewritten to create an
* object of type java.lang.Object, and other optimizations such as
* constant-propagation and local-dead-code-elimination should be able to
* remove that remaining code in most cases.
*
* Ideas for future work:
* - Support check-cast instructions for singleton-allocations
* - Support conditional branches over either zero or single allocations
*/
#include "ObjectEscapeAnalysis.h"
#include <algorithm>
#include <optional>
#include "ApiLevelChecker.h"
#include "BaseIRAnalyzer.h"
#include "CFGMutation.h"
#include "ConfigFiles.h"
#include "ConstantAbstractDomain.h"
#include "ControlFlow.h"
#include "DexClass.h"
#include "ExpandableMethodParams.h"
#include "HierarchyUtil.h"
#include "IRCode.h"
#include "IRInstruction.h"
#include "IROpcode.h"
#include "Inliner.h"
#include "Lazy.h"
#include "LiveRange.h"
#include "MethodOverrideGraph.h"
#include "PassManager.h"
#include "PatriciaTreeMap.h"
#include "PatriciaTreeMapAbstractEnvironment.h"
#include "PatriciaTreeSet.h"
#include "PatriciaTreeSetAbstractDomain.h"
#include "Resolver.h"
#include "Show.h"
#include "StringBuilder.h"
#include "Walkers.h"
using namespace sparta;
namespace mog = method_override_graph;
namespace hier = hierarchy_util;
namespace {
// How deep callee chains will be considered.
constexpr int MAX_INLINE_INVOKES_ITERATIONS = 8;
constexpr size_t MAX_INLINE_SIZE = 48;
// Don't even try to inline an incompletely inlinable type if a very rough
// estimate predicts an increase exceeding this threshold in code units.
constexpr float INCOMPLETE_ESTIMATED_DELTA_THRESHOLD = 0;
// Overhead of having a method and its metadata.
constexpr size_t COST_METHOD = 16;
// Overhead of having a class and its metadata.
constexpr size_t COST_CLASS = 48;
// Overhead of having a field and its metadata.
constexpr size_t COST_FIELD = 8;
// Typical overhead of calling a method, without move-result overhead.
constexpr float COST_INVOKE = 4.7f;
// Typical overhead of having move-result instruction.
constexpr float COST_MOVE_RESULT = 3.0f;
// Overhead of a new-instance instruction.
constexpr float COST_NEW_INSTANCE = 2.0f;
using Locations = std::vector<std::pair<DexMethod*, const IRInstruction*>>;
// Collect all allocation and invoke instructions, as well as non-virtual
// invocation dependencies.
void analyze_scope(
const Scope& scope,
const std::unordered_set<const DexMethod*>& non_overridden_virtuals,
std::unordered_map<DexType*, Locations>* new_instances,
std::unordered_map<DexMethod*, Locations>* invokes,
std::unordered_map<DexMethod*, std::unordered_set<DexMethod*>>*
dependencies) {
Timer t("analyze_scope");
ConcurrentMap<DexType*, Locations> concurrent_new_instances;
ConcurrentMap<DexMethod*, Locations> concurrent_invokes;
ConcurrentMap<DexMethod*, std::unordered_set<DexMethod*>>
concurrent_dependencies;
walk::parallel::code(scope, [&](DexMethod* method, IRCode& code) {
code.build_cfg(/* editable */ true);
for (auto& mie : InstructionIterable(code.cfg())) {
auto insn = mie.insn;
if (insn->opcode() == OPCODE_NEW_INSTANCE) {
auto cls = type_class(insn->get_type());
if (cls && !cls->is_external()) {
concurrent_new_instances.update(
insn->get_type(),
[&](auto*, auto& vec, bool) { vec.emplace_back(method, insn); });
}
} else if (opcode::is_an_invoke(insn->opcode())) {
auto callee =
resolve_method(insn->get_method(), opcode_to_search(insn));
if (callee &&
(!callee->is_virtual() || non_overridden_virtuals.count(callee))) {
concurrent_invokes.update(callee, [&](auto*, auto& vec, bool) {
vec.emplace_back(method, insn);
});
if (!method->is_virtual() || non_overridden_virtuals.count(method)) {
concurrent_dependencies.update(
callee,
[method](auto, auto& set, auto) { set.insert(method); });
}
}
}
}
});
*new_instances = concurrent_new_instances.move_to_container();
*invokes = concurrent_invokes.move_to_container();
*dependencies = concurrent_dependencies.move_to_container();
}
// A benign method invocation can be ignored during the escape analysis.
bool is_benign(const DexMethodRef* method_ref) {
static const std::unordered_set<std::string> methods = {
// clang-format off
"Ljava/lang/Object;.<init>:()V",
// clang-format on
};
return method_ref->is_def() &&
methods.count(
method_ref->as_def()->get_deobfuscated_name_or_empty_copy());
}
constexpr const IRInstruction* NO_ALLOCATION = nullptr;
using namespace ir_analyzer;
// For each allocating instruction that escapes (not including returns), all
// uses by which it escapes.
using Escapes = std::unordered_map<const IRInstruction*,
std::unordered_set<live_range::Use>>;
// For each object, we track which instruction might have allocated it:
// - new-instance, invoke-, and load-param-object instructions might represent
// allocation points
// - NO_ALLOCATION is a value for which the allocation instruction is not known,
// or it is not an object
using Domain = sparta::PatriciaTreeSetAbstractDomain<const IRInstruction*>;
// For each register that holds a relevant value, keep track of it.
using Environment = sparta::PatriciaTreeMapAbstractEnvironment<reg_t, Domain>;
struct MethodSummary {
// A parameter is "benign" if a provided argument does not escape
std::unordered_set<src_index_t> benign_params;
// A method might contain a unique instruction which allocates an object that
// is eventually unconditionally returned.
const IRInstruction* allocation_insn{nullptr};
};
using MethodSummaries = std::unordered_map<DexMethod*, MethodSummary>;
// The analyzer computes...
// - which instructions allocate (new-instance, invoke-)
// - which allocations escape (and how)
// - which allocations return
class Analyzer final : public BaseIRAnalyzer<Environment> {
public:
explicit Analyzer(const MethodSummaries& method_summaries,
DexMethodRef* incomplete_marker_method,
cfg::ControlFlowGraph& cfg)
: BaseIRAnalyzer(cfg),
m_method_summaries(method_summaries),
m_incomplete_marker_method(incomplete_marker_method) {
MonotonicFixpointIterator::run(Environment::top());
}
static const IRInstruction* get_singleton_allocation(const Domain& domain) {
always_assert(domain.kind() == AbstractValueKind::Value);
auto& elements = domain.elements();
if (elements.size() != 1) {
return nullptr;
}
return *elements.begin();
}
void analyze_instruction(const IRInstruction* insn,
Environment* current_state) const override {
const auto escape = [&](src_index_t src_idx) {
auto reg = insn->src(src_idx);
const auto& domain = current_state->get(reg);
always_assert(domain.kind() == AbstractValueKind::Value);
for (auto allocation_insn : domain.elements()) {
if (allocation_insn != NO_ALLOCATION) {
m_escapes[allocation_insn].insert(
{const_cast<IRInstruction*>(insn), src_idx});
}
}
};
if (insn->opcode() == OPCODE_NEW_INSTANCE) {
auto type = insn->get_type();
auto cls = type_class(type);
if (cls && !cls->is_external()) {
m_escapes[insn];
current_state->set(RESULT_REGISTER, Domain(insn));
return;
}
} else if (insn->opcode() == IOPCODE_LOAD_PARAM_OBJECT) {
m_escapes[insn];
current_state->set(insn->dest(), Domain(insn));
return;
} else if (insn->opcode() == OPCODE_RETURN_OBJECT) {
const auto& domain = current_state->get(insn->src(0));
always_assert(domain.kind() == AbstractValueKind::Value);
m_returns.insert(domain.elements().begin(), domain.elements().end());
return;
} else if (insn->opcode() == OPCODE_MOVE_RESULT_OBJECT ||
insn->opcode() == IOPCODE_MOVE_RESULT_PSEUDO_OBJECT) {
const auto& domain = current_state->get(RESULT_REGISTER);
current_state->set(insn->dest(), domain);
return;
} else if (insn->opcode() == OPCODE_MOVE_OBJECT) {
const auto& domain = current_state->get(insn->src(0));
current_state->set(insn->dest(), domain);
return;
} else if (insn->opcode() == OPCODE_INSTANCE_OF ||
opcode::is_an_iget(insn->opcode())) {
if (get_singleton_allocation(current_state->get(insn->src(0)))) {
current_state->set(RESULT_REGISTER, Domain(NO_ALLOCATION));
return;
}
} else if (opcode::is_a_monitor(insn->opcode()) ||
insn->opcode() == OPCODE_IF_EQZ ||
insn->opcode() == OPCODE_IF_NEZ) {
if (get_singleton_allocation(current_state->get(insn->src(0)))) {
return;
}
} else if (opcode::is_an_iput(insn->opcode())) {
if (get_singleton_allocation(current_state->get(insn->src(1)))) {
escape(0);
return;
}
} else if (opcode::is_an_invoke(insn->opcode())) {
if (is_benign(insn->get_method()) || is_incomplete_marker(insn)) {
current_state->set(RESULT_REGISTER, Domain(NO_ALLOCATION));
return;
}
auto callee = resolve_method(insn->get_method(), opcode_to_search(insn));
auto it = m_method_summaries.find(callee);
auto benign_params =
it == m_method_summaries.end() ? nullptr : &it->second.benign_params;
for (src_index_t i = 0; i < insn->srcs_size(); i++) {
if (!benign_params || !benign_params->count(i) ||
!get_singleton_allocation(current_state->get(insn->src(i)))) {
escape(i);
}
}
Domain domain(NO_ALLOCATION);
if (it != m_method_summaries.end() && it->second.allocation_insn) {
m_escapes[insn];
domain = Domain(insn);
}
current_state->set(RESULT_REGISTER, domain);
return;
}
for (src_index_t i = 0; i < insn->srcs_size(); i++) {
escape(i);
}
if (insn->has_dest()) {
current_state->set(insn->dest(), Domain(NO_ALLOCATION));
if (insn->dest_is_wide()) {
current_state->set(insn->dest() + 1, Domain::top());
}
} else if (insn->has_move_result_any()) {
current_state->set(RESULT_REGISTER, Domain(NO_ALLOCATION));
}
}
const Escapes& get_escapes() { return m_escapes; }
const std::unordered_set<const IRInstruction*>& get_returns() {
return m_returns;
}
// Returns set of new-instance and invoke- allocating instructions that do not
// escape (or return).
std::unordered_set<IRInstruction*> get_inlinables() {
std::unordered_set<IRInstruction*> inlinables;
for (auto&& [insn, uses] : m_escapes) {
if (uses.empty() && insn->opcode() != IOPCODE_LOAD_PARAM_OBJECT &&
!m_returns.count(insn)) {
inlinables.insert(const_cast<IRInstruction*>(insn));
}
}
return inlinables;
}
private:
const MethodSummaries& m_method_summaries;
DexMethodRef* m_incomplete_marker_method;
mutable Escapes m_escapes;
mutable std::unordered_set<const IRInstruction*> m_returns;
bool is_incomplete_marker(const IRInstruction* insn) const {
return insn->opcode() == OPCODE_INVOKE_STATIC &&
insn->get_method() == m_incomplete_marker_method;
}
};
MethodSummaries compute_method_summaries(
PassManager& mgr,
const Scope& scope,
const std::unordered_map<DexMethod*, std::unordered_set<DexMethod*>>&
dependencies,
const std::unordered_set<const DexMethod*>& non_overridden_virtuals) {
Timer t("compute_method_summaries");
std::unordered_set<DexMethod*> impacted_methods;
walk::code(scope, [&](DexMethod* method, IRCode&) {
if (!method->is_virtual() || non_overridden_virtuals.count(method)) {
impacted_methods.insert(method);
}
});
MethodSummaries method_summaries;
size_t analysis_iterations = 0;
while (!impacted_methods.empty()) {
Timer t2("analysis iteration");
analysis_iterations++;
TRACE(OEA, 2, "[object escape analysis] analysis_iteration %zu",
analysis_iterations);
ConcurrentMap<DexMethod*, MethodSummary> recomputed_method_summaries;
workqueue_run<DexMethod*>(
[&](DexMethod* method) {
auto& cfg = method->get_code()->cfg();
Analyzer analyzer(method_summaries,
/* incomplete_marker_method */ nullptr, cfg);
const auto& escapes = analyzer.get_escapes();
const auto& returns = analyzer.get_returns();
src_index_t src_index = 0;
for (auto& mie : InstructionIterable(cfg.get_param_instructions())) {
if (mie.insn->opcode() == IOPCODE_LOAD_PARAM_OBJECT &&
escapes.at(mie.insn).empty() && !returns.count(mie.insn)) {
recomputed_method_summaries.update(
method, [src_index](DexMethod*, auto& ms, bool) {
ms.benign_params.insert(src_index);
});
}
src_index++;
}
const IRInstruction* allocation_insn;
if (returns.size() == 1 &&
(allocation_insn = *returns.begin()) != NO_ALLOCATION &&
escapes.at(allocation_insn).empty() &&
allocation_insn->opcode() != IOPCODE_LOAD_PARAM_OBJECT) {
recomputed_method_summaries.update(
method, [allocation_insn](DexMethod*, auto& ms, bool) {
ms.allocation_insn = allocation_insn;
});
}
},
impacted_methods);
std::unordered_set<DexMethod*> changed_methods;
// (Recomputed) summaries can only grow; assert that, update summaries when
// necessary, and remember for which methods the summaries actually changed.
for (auto&& [method, recomputed_summary] : recomputed_method_summaries) {
auto& summary = method_summaries[method];
for (auto src_index : summary.benign_params) {
always_assert(recomputed_summary.benign_params.count(src_index));
}
if (recomputed_summary.benign_params.size() >
summary.benign_params.size()) {
summary.benign_params = std::move(recomputed_summary.benign_params);
changed_methods.insert(method);
}
if (recomputed_summary.allocation_insn) {
if (summary.allocation_insn) {
always_assert(summary.allocation_insn ==
recomputed_summary.allocation_insn);
} else {
summary.allocation_insn = recomputed_summary.allocation_insn;
changed_methods.insert(method);
}
} else {
always_assert(summary.allocation_insn == nullptr);
}
}
impacted_methods.clear();
for (auto method : changed_methods) {
auto it = dependencies.find(method);
if (it != dependencies.end()) {
impacted_methods.insert(it->second.begin(), it->second.end());
}
}
}
mgr.incr_metric("analysis_iterations", analysis_iterations);
return method_summaries;
}
// For an inlinable new-instance or invoke- instruction, determine first
// resolved callee (if any), and (eventually) allocated type
std::pair<DexMethod*, DexType*> resolve_inlinable(
const MethodSummaries& method_summaries, const IRInstruction* insn) {
always_assert(insn->opcode() == OPCODE_NEW_INSTANCE ||
opcode::is_an_invoke(insn->opcode()));
DexMethod* first_callee{nullptr};
while (insn->opcode() != OPCODE_NEW_INSTANCE) {
always_assert(opcode::is_an_invoke(insn->opcode()));
auto callee = resolve_method(insn->get_method(), opcode_to_search(insn));
if (!first_callee) {
first_callee = callee;
}
insn = method_summaries.at(callee).allocation_insn;
}
return std::make_pair(first_callee, insn->get_type());
}
using InlineAnchorsOfType =
std::unordered_map<DexMethod*, std::unordered_set<IRInstruction*>>;
std::unordered_map<DexType*, InlineAnchorsOfType> compute_inline_anchors(
const Scope& scope, const MethodSummaries& method_summaries) {
Timer t("compute_inline_anchors");
ConcurrentMap<DexType*, InlineAnchorsOfType> concurrent_inline_anchors;
walk::parallel::code(scope, [&](DexMethod* method, IRCode& code) {
Analyzer analyzer(method_summaries, /* incomplete_marker_method */ nullptr,
code.cfg());
auto inlinables = analyzer.get_inlinables();
for (auto insn : inlinables) {
auto [callee, type] = resolve_inlinable(method_summaries, insn);
TRACE(OEA, 3, "[object escape analysis] inline anchor [%s] %s",
SHOW(method), SHOW(insn));
concurrent_inline_anchors.update(
type, [&](auto*, auto& map, bool) { map[method].insert(insn); });
}
});
return concurrent_inline_anchors.move_to_container();
}
class InlinedCodeSizeEstimator {
private:
using DeltaKey = std::pair<DexMethod*, const IRInstruction*>;
LazyUnorderedMap<DexMethod*, size_t> m_inlined_code_sizes;
LazyUnorderedMap<DexMethod*, live_range::DefUseChains> m_du_chains;
LazyUnorderedMap<DeltaKey, float, boost::hash<DeltaKey>> m_deltas;
public:
explicit InlinedCodeSizeEstimator(const MethodSummaries& method_summaries)
: m_inlined_code_sizes([](DexMethod* method) {
size_t code_size{0};
auto& cfg = method->get_code()->cfg();
for (auto& mie : InstructionIterable(cfg)) {
auto* insn = mie.insn;
// We do the cost estimation before shrinking, so we discount moves.
// Returns will go away after inlining.
if (opcode::is_a_move(insn->opcode()) ||
opcode::is_a_return(insn->opcode())) {
continue;
}
code_size += mie.insn->size();
}
return code_size;
}),
m_du_chains([](DexMethod* method) {
live_range::MoveAwareChains chains(method->get_code()->cfg());
return chains.get_def_use_chains();
}),
m_deltas([&](DeltaKey key) {
auto [method, allocation_insn] = key;
float delta = 0;
auto& du_chains = m_du_chains[method];
if (opcode::is_an_invoke(allocation_insn->opcode())) {
auto callee = resolve_method(allocation_insn->get_method(),
opcode_to_search(allocation_insn));
always_assert(callee);
auto* callee_allocation_insn =
method_summaries.at(callee).allocation_insn;
always_assert(callee_allocation_insn);
delta += m_inlined_code_sizes[callee] +
get_delta(callee, callee_allocation_insn) - COST_INVOKE -
COST_MOVE_RESULT;
} else if (allocation_insn->opcode() == OPCODE_NEW_INSTANCE) {
delta -= COST_NEW_INSTANCE;
}
for (auto& use :
du_chains[const_cast<IRInstruction*>(allocation_insn)]) {
if (opcode::is_an_invoke(use.insn->opcode())) {
delta -= COST_INVOKE;
auto callee = resolve_method(use.insn->get_method(),
opcode_to_search(use.insn));
always_assert(callee);
if (is_benign(callee)) {
continue;
}
auto load_param_insns = InstructionIterable(
callee->get_code()->cfg().get_param_instructions());
auto* load_param_insn =
std::next(load_param_insns.begin(), use.src_index)->insn;
always_assert(load_param_insn);
always_assert(opcode::is_a_load_param(load_param_insn->opcode()));
delta += m_inlined_code_sizes[callee] +
get_delta(callee, load_param_insn);
if (!callee->get_proto()->is_void()) {
delta -= COST_MOVE_RESULT;
}
} else if (opcode::is_an_iget(use.insn->opcode()) ||
opcode::is_an_iput(use.insn->opcode())) {
delta -= use.insn->size();
}
}
return delta;
}) {}
float get_delta(DexMethod* method, const IRInstruction* allocation_insn) {
return m_deltas[std::make_pair(method, allocation_insn)];
}
};
enum class InlinableTypeKind {
// All uses of this type have inline anchors in identified root methods. It is
// safe to inline all resolved inlinables.
CompleteSingleRoot,
// Same as CompleteSingleRoot, except that inlinable anchors are spread over
// multiple root methods.
CompleteMultipleRoots,
// Not all uses of this type have inlinable anchors. Only attempt to inline
// anchors present in original identified root methods.
Incomplete,
Last = Incomplete
};
using InlinableTypes = std::unordered_map<DexType*, InlinableTypeKind>;
std::unordered_map<DexMethod*, InlinableTypes> compute_root_methods(
PassManager& mgr,
const std::unordered_map<DexType*, Locations>& new_instances,
const std::unordered_map<DexMethod*, Locations>& invokes,
const MethodSummaries& method_summaries,
const std::unordered_map<DexType*, InlineAnchorsOfType>& inline_anchors) {
Timer t("compute_root_methods");
std::array<size_t, (size_t)(InlinableTypeKind::Last) + 1> candidate_types{
0, 0, 0};
std::unordered_map<DexMethod*, InlinableTypes> root_methods;
std::unordered_set<DexType*> inline_anchor_types;
std::mutex mutex; // protects candidate_types and root_methods
std::atomic<size_t> incomplete_estimated_delta_threshold_exceeded{0};
auto concurrent_add_root_methods = [&](DexType* type, bool complete) {
const auto& inline_anchors_of_type = inline_anchors.at(type);
InlinedCodeSizeEstimator inlined_code_size_estimator(method_summaries);
std::vector<DexMethod*> methods;
for (auto& [method, allocation_insns] : inline_anchors_of_type) {
auto it2 = method_summaries.find(method);
if (it2 != method_summaries.end() && it2->second.allocation_insn &&
resolve_inlinable(method_summaries, it2->second.allocation_insn)
.second == type) {
continue;
}
if (!complete) {
float delta = 0;
for (auto allocation_insn : allocation_insns) {
delta +=
inlined_code_size_estimator.get_delta(method, allocation_insn);
}
if (delta > INCOMPLETE_ESTIMATED_DELTA_THRESHOLD) {
// Skipping, as it's highly unlikely to results in an overall size
// win, while taking a very long time to compute exactly.
incomplete_estimated_delta_threshold_exceeded++;
continue;
}
}
methods.push_back(method);
}
if (methods.empty()) {
return;
}
bool multiple_roots = methods.size() > 1;
auto kind = complete ? multiple_roots
? InlinableTypeKind::CompleteMultipleRoots
: InlinableTypeKind::CompleteSingleRoot
: InlinableTypeKind::Incomplete;
std::lock_guard<std::mutex> lock_guard(mutex);
candidate_types[(size_t)kind]++;
for (auto method : methods) {
TRACE(OEA, 3, "[object escape analysis] root method %s with %s%s",
SHOW(method), SHOW(type),
kind == InlinableTypeKind::CompleteMultipleRoots
? " complete multiple-roots"
: kind == InlinableTypeKind::CompleteSingleRoot
? " complete single-root"
: " incomplete");
root_methods[method].emplace(type, kind);
}
};
for (auto& [type, method_insn_pairs] : new_instances) {
auto it = inline_anchors.find(type);
if (it == inline_anchors.end()) {
continue;
}
inline_anchor_types.insert(type);
}
workqueue_run<DexType*>(
[&](DexType* type) {
const auto& method_insn_pairs = new_instances.at(type);
const auto& inline_anchors_of_type = inline_anchors.at(type);
std::function<bool(const std::pair<DexMethod*, const IRInstruction*>&)>
is_anchored;
is_anchored = [&](const auto& p) {
auto [method, insn] = p;
auto it2 = inline_anchors_of_type.find(method);
if (it2 != inline_anchors_of_type.end() &&
it2->second.count(const_cast<IRInstruction*>(insn))) {
return true;
}
auto it3 = method_summaries.find(method);
if (it3 == method_summaries.end() ||
it3->second.allocation_insn != insn) {
return false;
}
auto it4 = invokes.find(method);
if (it4 == invokes.end()) {
return false;
}
for (auto q : it4->second) {
if (!is_anchored(q)) {
return false;
}
}
return true;
};
// Check whether all uses of this type have inline anchors optimizable
// root methods.
bool complete =
std::all_of(method_insn_pairs.begin(), method_insn_pairs.end(),
is_anchored) &&
std::all_of(
inline_anchors_of_type.begin(), inline_anchors_of_type.end(),
[](auto& p) { return !p.first->rstate.no_optimizations(); });
concurrent_add_root_methods(type, complete);
},
inline_anchor_types);
TRACE(OEA,
1,
"[object escape analysis] candidate types: %zu",
candidate_types.size());
mgr.incr_metric(
"candidate types CompleteSingleRoot",
candidate_types[(size_t)InlinableTypeKind::CompleteSingleRoot]);
mgr.incr_metric(
"candidate types CompleteMultipleRoots",
candidate_types[(size_t)InlinableTypeKind::CompleteMultipleRoots]);
mgr.incr_metric("candidate types Incomplete",
candidate_types[(size_t)InlinableTypeKind::Incomplete]);
mgr.incr_metric("incomplete_estimated_delta_threshold_exceeded",
(size_t)incomplete_estimated_delta_threshold_exceeded);
return root_methods;
}
size_t get_code_size(DexMethod* method) {
return method->get_code()->cfg().sum_opcode_sizes();
}
struct Stats {
std::atomic<size_t> total_savings{0};
std::atomic<size_t> reduced_methods{0};
std::atomic<size_t> reduced_methods_variants{0};
std::atomic<size_t> selected_reduced_methods{0};
std::atomic<size_t> invokes_not_inlinable_callee_unexpandable{0};
std::atomic<size_t> invokes_not_inlinable_callee_inconcrete{0};
std::atomic<size_t> invokes_not_inlinable_callee_too_many_params_to_expand{0};
std::atomic<size_t> invokes_not_inlinable_inlining{0};
std::atomic<size_t> invokes_not_inlinable_too_many_iterations{0};
std::atomic<size_t> anchors_not_inlinable_inlining{0};
std::atomic<size_t> stackify_returns_objects{0};
std::atomic<size_t> too_costly_multiple_conditional_classes{0};
std::atomic<size_t> too_costly_irreducible_classes{0};
std::atomic<size_t> too_costly_globally{0};
std::atomic<size_t> expanded_methods{0};
std::atomic<size_t> calls_inlined{0};
std::atomic<size_t> new_instances_eliminated{0};
};
// Data structure to derive local or accumulated global net savings
struct NetSavings {
int local{0};
std::unordered_set<DexType*> classes;
std::unordered_set<DexMethod*> methods;
NetSavings& operator+=(const NetSavings& other) {
local += other.local;
classes.insert(other.classes.begin(), other.classes.end());
methods.insert(other.methods.begin(), other.methods.end());
return *this;
}
// Estimate how many code units will be saved.
int get_value() const {
int net_savings{local};
// A class will only eventually get deleted if all static methods are
// inlined.
std::unordered_map<DexType*, std::unordered_set<DexMethod*>> smethods;
for (auto type : classes) {
auto cls = type_class(type);
always_assert(cls);
auto& type_smethods = smethods[type];
for (auto method : cls->get_dmethods()) {
if (is_static(method)) {
type_smethods.insert(method);
}
}
}
for (auto method : methods) {
if (can_delete(method)) {
auto code_size = get_code_size(method);
net_savings += COST_METHOD + code_size;
if (is_static(method)) {
smethods[method->get_class()].erase(method);
}
}
}
for (auto type : classes) {
auto cls = type_class(type);
always_assert(cls);
if (can_delete(cls) && cls->get_sfields().empty() && !cls->get_clinit()) {
auto& type_smethods = smethods[type];
if (type_smethods.empty()) {
net_savings += COST_CLASS;
}
}
for (auto field : cls->get_ifields()) {
if (can_delete(field)) {
net_savings += COST_FIELD;
}
}
}
return net_savings;
}
};
// Data structure that represents a (cloned) reduced method, together with some
// auxiliary information that allows to derive net savings.
struct ReducedMethod {
DexMethod* method;
size_t initial_code_size;
std::unordered_map<DexMethod*, std::unordered_set<DexType*>> inlined_methods;
InlinableTypes types;
size_t calls_inlined;
size_t new_instances_eliminated;
NetSavings get_net_savings(
const std::unordered_set<DexType*>& irreducible_types,
NetSavings* conditional_net_savings = nullptr) const {
auto final_code_size = get_code_size(method);
NetSavings net_savings;
net_savings.local = (int)initial_code_size - (int)final_code_size;
std::unordered_set<DexType*> remaining;
for (auto& [inlined_method, inlined_types] : inlined_methods) {
bool any_remaining = false;
bool any_incomplete = false;
for (auto type : inlined_types) {
auto kind = types.at(type);
if (kind != InlinableTypeKind::CompleteSingleRoot ||
irreducible_types.count(type)) {
remaining.insert(type);
any_remaining = true;
if (kind == InlinableTypeKind::Incomplete) {
any_incomplete = true;
}
}
}
if (any_remaining) {
if (conditional_net_savings && !any_incomplete) {
conditional_net_savings->methods.insert(inlined_method);
}
continue;
}
net_savings.methods.insert(inlined_method);
}
for (auto [type, kind] : types) {
if (remaining.count(type) ||
kind != InlinableTypeKind::CompleteSingleRoot ||
irreducible_types.count(type)) {
if (conditional_net_savings && kind != InlinableTypeKind::Incomplete) {
conditional_net_savings->classes.insert(type);
}
continue;
}
net_savings.classes.insert(type);
}
return net_savings;
}
};
class RootMethodReducer {
private:
const ExpandableMethodParams& m_expandable_method_params;
DexMethodRef* m_incomplete_marker_method;
MultiMethodInliner& m_inliner;
const MethodSummaries& m_method_summaries;
Stats* m_stats;
bool m_is_init_or_clinit;
DexMethod* m_method;
const InlinableTypes& m_types;
size_t m_calls_inlined{0};
size_t m_new_instances_eliminated{0};
size_t m_max_inline_size;
public:
RootMethodReducer(const ExpandableMethodParams& expandable_method_params,
DexMethodRef* incomplete_marker_method,
MultiMethodInliner& inliner,
const MethodSummaries& method_summaries,
Stats* stats,
bool is_init_or_clinit,
DexMethod* method,
const InlinableTypes& types,
size_t max_inline_size)
: m_expandable_method_params(expandable_method_params),
m_incomplete_marker_method(incomplete_marker_method),
m_inliner(inliner),
m_method_summaries(method_summaries),
m_stats(stats),
m_is_init_or_clinit(is_init_or_clinit),
m_method(method),
m_types(types),
m_max_inline_size(max_inline_size) {}
std::optional<ReducedMethod> reduce() {
auto initial_code_size{get_code_size(m_method)};
if (!inline_anchors() || !expand_or_inline_invokes()) {
return std::nullopt;
}
while (auto opt_p = find_inlinable_new_instance()) {
if (!stackify(opt_p->first, opt_p->second)) {
return std::nullopt;
}
}
auto* insn = find_incomplete_marker_methods();
always_assert_log(!insn,
"Incomplete marker {%s} present after reduction in\n%s",
SHOW(insn), SHOW(m_method->get_code()->cfg()));
shrink();
return (ReducedMethod){
m_method, initial_code_size, std::move(m_inlined_methods),
m_types, m_calls_inlined, m_new_instances_eliminated};
}
private:
void shrink() {
m_inliner.get_shrinker().shrink_code(m_method->get_code(),
is_static(m_method),
m_is_init_or_clinit,
m_method->get_class(),
m_method->get_proto(),
[this]() { return show(m_method); });
}
bool inline_insns(const std::unordered_set<IRInstruction*>& insns) {
auto inlined = m_inliner.inline_callees(m_method, insns);
m_calls_inlined += inlined;
return inlined == insns.size();
}
// Given a method invocation, replace a particular argument with the
// sequence of the argument's field values to flow into an expanded
// method.
DexMethodRef* expand_invoke(cfg::CFGMutation& mutation,
const cfg::InstructionIterator& it,
param_index_t param_index) {
auto insn = it->insn;
auto callee = resolve_method(insn->get_method(), opcode_to_search(insn));
always_assert(callee);
always_assert(callee->is_concrete());
std::vector<DexField*>* fields;
auto expanded_method_ref =
m_expandable_method_params.get_expanded_method_ref(callee, param_index,
&fields);
if (!expanded_method_ref) {
return nullptr;
}
insn->set_method(expanded_method_ref);
if (!method::is_init(expanded_method_ref)) {
insn->set_opcode(OPCODE_INVOKE_STATIC);
}
auto obj_reg = insn->src(param_index);
auto srcs_range = insn->srcs();
std::vector<reg_t> srcs_copy(srcs_range.begin(), srcs_range.end());
insn->set_srcs_size(srcs_copy.size() - 1 + fields->size());
for (param_index_t i = param_index; i < srcs_copy.size() - 1; i++) {
insn->set_src(i + fields->size(), srcs_copy.at(i + 1));
}
std::vector<IRInstruction*> instructions_to_insert;
auto& cfg = m_method->get_code()->cfg();
for (auto field : *fields) {
auto reg = type::is_wide_type(field->get_type())
? cfg.allocate_wide_temp()
: cfg.allocate_temp();
insn->set_src(param_index++, reg);
auto iget_opcode = opcode::iget_opcode_for_field(field);
instructions_to_insert.push_back((new IRInstruction(iget_opcode))
->set_src(0, obj_reg)
->set_field(field));
auto move_result_pseudo_opcode =
opcode::move_result_pseudo_for_iget(iget_opcode);
instructions_to_insert.push_back(
(new IRInstruction(move_result_pseudo_opcode))->set_dest(reg));
}
mutation.insert_before(it, std::move(instructions_to_insert));
return expanded_method_ref;
}
bool expand_invokes(const std::unordered_map<IRInstruction*, param_index_t>&
invokes_to_expand,
std::unordered_set<DexMethodRef*>* expanded_method_refs) {
if (invokes_to_expand.empty()) {
return true;
}
auto& cfg = m_method->get_code()->cfg();
cfg::CFGMutation mutation(cfg);
auto ii = InstructionIterable(cfg);
for (auto it = ii.begin(); it != ii.end(); it++) {
auto insn = it->insn;
auto it2 = invokes_to_expand.find(insn);
if (it2 == invokes_to_expand.end()) {
continue;
}
auto param_index = it2->second;
auto expanded_method_ref = expand_invoke(mutation, it, param_index);
if (!expanded_method_ref) {
return false;
}
expanded_method_refs->insert(expanded_method_ref);
}
mutation.flush();
return true;
}
// Inline all "anchors" until all relevant allocations are new-instance
// instructions in the (root) method.
bool inline_anchors() {
auto& cfg = m_method->get_code()->cfg();
for (int iteration = 0; true; iteration++) {
Analyzer analyzer(m_method_summaries, m_incomplete_marker_method, cfg);
std::unordered_set<IRInstruction*> invokes_to_inline;
auto inlinables = analyzer.get_inlinables();
Lazy<live_range::DefUseChains> du_chains([&]() {
live_range::MoveAwareChains chains(cfg);
return chains.get_def_use_chains();
});
cfg::CFGMutation mutation(cfg);
for (auto insn : inlinables) {
auto [callee, type] = resolve_inlinable(m_method_summaries, insn);
auto it = m_types.find(type);
if (it == m_types.end()) {
continue;
}
if (it->second == InlinableTypeKind::Incomplete) {
// We are only going to consider incompletely inlinable types when we
// find them in the first iteration, i.e. in the original method,
// and not coming from any inlined method. We are then going insert
// a special marker invocation instruction so that we can later find
// the originally matched anchors again. This instruction will get
// removed later.
if (!has_incomplete_marker((*du_chains)[insn])) {
if (iteration > 0) {
continue;
}
auto insn_it = cfg.find_insn(insn);
always_assert(!insn_it.is_end());
auto move_result_it = cfg.move_result_of(insn_it);
if (move_result_it.is_end()) {
continue;
}
auto invoke_insn = (new IRInstruction(OPCODE_INVOKE_STATIC))
->set_method(m_incomplete_marker_method)
->set_srcs_size(1)
->set_src(0, move_result_it->insn->dest());
mutation.insert_after(move_result_it, {invoke_insn});
}
}
if (!callee) {
continue;
}
invokes_to_inline.insert(insn);
m_inlined_methods[callee].insert(type);
}
mutation.flush();
if (invokes_to_inline.empty()) {
return true;
}
if (!inline_insns(invokes_to_inline)) {
m_stats->anchors_not_inlinable_inlining++;
return false;
}
// simplify to prune now unreachable code, e.g. from removed exception
// handlers
cfg.simplify();
}
}
bool is_inlinable_new_instance(IRInstruction* insn) const {
return insn->opcode() == OPCODE_NEW_INSTANCE &&
m_types.count(insn->get_type());
}
bool is_incomplete_marker(IRInstruction* insn) const {
return insn->opcode() == OPCODE_INVOKE_STATIC &&
insn->get_method() == m_incomplete_marker_method;
}
bool has_incomplete_marker(
const std::unordered_set<live_range::Use>& uses) const {
return std::any_of(uses.begin(), uses.end(), [&](auto& use) {
return is_incomplete_marker(use.insn);
});
}
IRInstruction* find_incomplete_marker_methods() {
auto& cfg = m_method->get_code()->cfg();
for (auto& mie : InstructionIterable(cfg)) {
if (is_incomplete_marker(mie.insn)) {
return mie.insn;
}
}
return nullptr;
}
std::optional<std::pair<live_range::DefUseChains, IRInstruction*>>
find_inlinable_new_instance() const {
auto& cfg = m_method->get_code()->cfg();
Lazy<live_range::DefUseChains> du_chains([&]() {
live_range::MoveAwareChains chains(cfg);
return chains.get_def_use_chains();
});
for (auto& mie : InstructionIterable(cfg)) {
auto insn = mie.insn;
if (!is_inlinable_new_instance(insn)) {
continue;
}
auto type = insn->get_type();
if (m_types.at(type) == InlinableTypeKind::Incomplete &&
!has_incomplete_marker((*du_chains)[insn])) {
continue;
}
return std::make_optional(std::pair(std::move(*du_chains), insn));
}
return std::nullopt;
}
bool should_expand(
DexMethod* callee,
const std::unordered_map<src_index_t, DexType*>& src_indices) {
always_assert(!src_indices.empty());
if (method::is_init(callee) && !src_indices.count(0)) {
return true;
}
if (src_indices.size() > 1) {
return false;
}
auto [param_index, type] = *src_indices.begin();
bool multiples =
m_types.at(type) == InlinableTypeKind::CompleteMultipleRoots;
if (multiples && get_code_size(callee) > m_max_inline_size &&
m_expandable_method_params.get_expanded_method_ref(callee,
param_index)) {
return true;
}
return false;
}
// Expand or inline all uses of all relevant new-instance instructions that
// involve invoke- instructions, until there are no more such uses.
bool expand_or_inline_invokes() {
auto& cfg = m_method->get_code()->cfg();
std::unordered_set<DexMethodRef*> expanded_method_refs;
for (int iteration = 0; iteration < MAX_INLINE_INVOKES_ITERATIONS;
iteration++) {
std::unordered_set<IRInstruction*> invokes_to_inline;
std::unordered_map<IRInstruction*, param_index_t> invokes_to_expand;
live_range::MoveAwareChains chains(cfg);
auto du_chains = chains.get_def_use_chains();
std::unordered_map<IRInstruction*,
std::unordered_map<src_index_t, DexType*>>
aggregated_uses;
for (auto& [insn, uses] : du_chains) {
if (!is_inlinable_new_instance(insn)) {
continue;
}
auto type = insn->get_type();
if (m_types.at(type) == InlinableTypeKind::Incomplete &&
!has_incomplete_marker(uses)) {
continue;
}
for (auto& use : uses) {
auto emplaced =
aggregated_uses[use.insn].emplace(use.src_index, type).second;
always_assert(emplaced);
}
}
for (auto&& [uses_insn, src_indices] : aggregated_uses) {
if (!opcode::is_an_invoke(uses_insn->opcode()) ||
is_benign(uses_insn->get_method()) ||
is_incomplete_marker(uses_insn)) {
continue;
}
if (expanded_method_refs.count(uses_insn->get_method())) {
m_stats->invokes_not_inlinable_callee_inconcrete++;
return false;
}
auto callee = resolve_method(uses_insn->get_method(),
opcode_to_search(uses_insn));
always_assert(callee);
always_assert(callee->is_concrete());
if (should_expand(callee, src_indices)) {
if (src_indices.size() > 1) {
m_stats->invokes_not_inlinable_callee_too_many_params_to_expand++;
return false;
}
always_assert(src_indices.size() == 1);
auto src_index = src_indices.begin()->first;
invokes_to_expand.emplace(uses_insn, src_index);
continue;
}
invokes_to_inline.insert(uses_insn);
for (auto [src_index, type] : src_indices) {
m_inlined_methods[callee].insert(type);
}
}
if (!expand_invokes(invokes_to_expand, &expanded_method_refs)) {
m_stats->invokes_not_inlinable_callee_unexpandable++;
return false;
}
if (invokes_to_inline.empty()) {
// Nothing else to do
return true;
}
if (!inline_insns(invokes_to_inline)) {
m_stats->invokes_not_inlinable_inlining++;
return false;
}
// simplify to prune now unreachable code, e.g. from removed exception
// handlers
cfg.simplify();
}
m_stats->invokes_not_inlinable_too_many_iterations++;
return false;
}
// Given a new-instance instruction whose (main) uses are as the receiver in
// iget- and iput- instruction, transform all such field accesses into
// accesses to registers, one per field.
bool stackify(live_range::DefUseChains& du_chains,
IRInstruction* new_instance_insn) {
auto& cfg = m_method->get_code()->cfg();
std::unordered_map<DexField*, reg_t> field_regs;
std::vector<DexField*> ordered_fields;
auto get_field_reg = [&](DexFieldRef* ref) {
always_assert(ref->is_def());
auto field = ref->as_def();
auto it = field_regs.find(field);
if (it == field_regs.end()) {
auto wide = type::is_wide_type(field->get_type());
auto reg = wide ? cfg.allocate_wide_temp() : cfg.allocate_temp();
it = field_regs.emplace(field, reg).first;
ordered_fields.push_back(field);
}
return it->second;
};
auto& uses = du_chains[new_instance_insn];
std::unordered_set<IRInstruction*> instructions_to_replace;
bool identity_matters{false};
for (auto& use : uses) {
auto opcode = use.insn->opcode();
if (opcode::is_an_iput(opcode)) {
always_assert(use.src_index == 1);
} else if (opcode::is_an_invoke(opcode) || opcode::is_a_monitor(opcode)) {
always_assert(use.src_index == 0);
} else if (opcode == OPCODE_IF_EQZ || opcode == OPCODE_IF_NEZ) {
identity_matters = true;
continue;
} else if (opcode::is_move_object(opcode)) {
continue;
} else if (opcode::is_return_object(opcode)) {
// Can happen if the root method is also an allocator
m_stats->stackify_returns_objects++;
return false;
} else {
always_assert_log(
opcode::is_an_iget(opcode) || opcode::is_instance_of(opcode),
"Unexpected use: %s at %u", SHOW(use.insn), use.src_index);
}
instructions_to_replace.insert(use.insn);
}
cfg::CFGMutation mutation(cfg);
auto ii = InstructionIterable(cfg);
auto new_instance_insn_it = ii.end();
for (auto it = ii.begin(); it != ii.end(); it++) {
auto insn = it->insn;
if (!instructions_to_replace.count(insn)) {
if (insn == new_instance_insn) {
new_instance_insn_it = it;
}
continue;
}
auto opcode = insn->opcode();
if (opcode::is_an_iget(opcode)) {
auto move_result_it = cfg.move_result_of(it);
auto new_insn = (new IRInstruction(opcode::iget_to_move(opcode)))
->set_src(0, get_field_reg(insn->get_field()))
->set_dest(move_result_it->insn->dest());
mutation.replace(it, {new_insn});
} else if (opcode::is_an_iput(opcode)) {
auto new_insn = (new IRInstruction(opcode::iput_to_move(opcode)))
->set_src(0, insn->src(0))
->set_dest(get_field_reg(insn->get_field()));
mutation.replace(it, {new_insn});
} else if (opcode::is_an_invoke(opcode)) {
always_assert(is_benign(insn->get_method()) ||
is_incomplete_marker(insn));
if (is_incomplete_marker(insn) || !identity_matters) {
mutation.remove(it);
}
} else if (opcode::is_instance_of(opcode)) {
auto move_result_it = cfg.move_result_of(it);
auto new_insn =
(new IRInstruction(OPCODE_CONST))
->set_literal(type::is_subclass(insn->get_type(),
new_instance_insn->get_type()))
->set_dest(move_result_it->insn->dest());
mutation.replace(it, {new_insn});
} else if (opcode::is_a_monitor(opcode)) {
mutation.remove(it);
} else {
not_reached();
}
}
always_assert(!new_instance_insn_it.is_end());
auto init_class_insn =
m_inliner.get_shrinker()
.get_init_classes_with_side_effects()
.create_init_class_insn(new_instance_insn->get_type());
if (init_class_insn) {
mutation.insert_before(new_instance_insn_it, {init_class_insn});
}
if (identity_matters) {
new_instance_insn_it->insn->set_type(type::java_lang_Object());
} else {
auto move_result_it = cfg.move_result_of(new_instance_insn_it);
auto new_insn = (new IRInstruction(OPCODE_CONST))
->set_literal(0)
->set_dest(move_result_it->insn->dest());
mutation.replace(new_instance_insn_it, {new_insn});
}
// Insert zero-initialization code for field registers.
std::sort(ordered_fields.begin(), ordered_fields.end(), compare_dexfields);
std::vector<IRInstruction*> field_inits;
field_inits.reserve(ordered_fields.size());
for (auto field : ordered_fields) {
auto wide = type::is_wide_type(field->get_type());
auto opcode = wide ? OPCODE_CONST_WIDE : OPCODE_CONST;
auto reg = field_regs.at(field);
auto new_insn =
(new IRInstruction(opcode))->set_literal(0)->set_dest(reg);
field_inits.push_back(new_insn);
}
mutation.insert_before(new_instance_insn_it, field_inits);
mutation.flush();
// simplify to prune now unreachable code, e.g. from removed exception
// handlers
cfg.simplify();
m_new_instances_eliminated++;
return true;
}
std::unordered_map<DexMethod*, std::unordered_set<DexType*>>
m_inlined_methods;
};
// Reduce all root methods to a set of variants. The reduced methods are ordered
// by how many types where inlined, with the largest number of inlined types
// going first.
std::unordered_map<DexMethod*, std::vector<ReducedMethod>>
compute_reduced_methods(
ExpandableMethodParams& expandable_method_params,
MultiMethodInliner& inliner,
const MethodSummaries& method_summaries,
const std::unordered_map<DexMethod*, InlinableTypes>& root_methods,
std::unordered_set<DexType*>* irreducible_types,
Stats* stats,
size_t max_inline_size) {
Timer t("compute_reduced_methods");
// We are not exploring all possible subsets of types, but only single chain
// of subsets, guided by the inlinable kind, and by how often
// they appear as inlinable types in root methods.
// TODO: Explore all possible subsets of types.
std::unordered_map<DexType*, size_t> occurrences;
for (auto&& [method, types] : root_methods) {
for (auto [type, kind] : types) {
occurrences[type]++;
}
}
workqueue_run<std::pair<DexMethod*, InlinableTypes>>(
[&](const std::pair<DexMethod*, InlinableTypes>& p) {
const auto& [method, types] = p;
inliner.get_shrinker().shrink_method(method);
},
root_methods);
// This comparison function implies the sequence of inlinable type subsets
// we'll consider. We'll structure the sequence such that often occurring
// types with multiple uses will be chopped off the type set first.
auto less = [&occurrences](auto& p, auto& q) {
// We sort types with incomplete anchors to the front.
if (p.second != q.second) {
return p.second > q.second;
}
// We sort types with more frequent occurrences to the front.
auto p_count = occurrences.at(p.first);
auto q_count = occurrences.at(q.first);
if (p_count != q_count) {
return p_count > q_count;
}
// Tie breaker.
return compare_dextypes(p.first, q.first);
};
// We'll now compute the set of variants we'll consider. For each root method
// with N inlinable types, there will be N variants.
std::vector<std::pair<DexMethod*, InlinableTypes>>
ordered_root_methods_variants;
for (auto&& [method, types] : root_methods) {
std::vector<std::pair<DexType*, InlinableTypeKind>> ordered_types(
types.begin(), types.end());
std::sort(ordered_types.begin(), ordered_types.end(), less);
for (auto it = ordered_types.begin(); it != ordered_types.end(); it++) {
ordered_root_methods_variants.emplace_back(
method, InlinableTypes(it, ordered_types.end()));
}
}
// Order such that items with many types to process go first, which improves
// workqueue efficiency.
std::stable_sort(ordered_root_methods_variants.begin(),
ordered_root_methods_variants.end(), [](auto& a, auto& b) {
return a.second.size() > b.second.size();
});
// Special marker method, used to identify which newly created objects of only
// incompletely inlinable types should get inlined.
DexMethodRef* incomplete_marker_method = DexMethod::make_method(
"Lredex/$ObjectEscapeAnalysis;.markIncomplete:(Ljava/lang/Object;)V");
// We make a copy before we start reducing a root method, in case we run
// into issues, or negative net savings.
ConcurrentMap<DexMethod*, std::vector<ReducedMethod>>
concurrent_reduced_methods;
workqueue_run<std::pair<DexMethod*, InlinableTypes>>(
[&](const std::pair<DexMethod*, InlinableTypes>& p) {
auto* method = p.first;
const auto& types = p.second;
auto copy_name_str =
method->get_name()->str() + "$oea$" + std::to_string(types.size());
auto copy = DexMethod::make_method_from(
method, method->get_class(), DexString::make_string(copy_name_str));
RootMethodReducer root_method_reducer{expandable_method_params,
incomplete_marker_method,
inliner,
method_summaries,
stats,
method::is_init(method) ||
method::is_clinit(method),
copy,
types,
max_inline_size};
auto reduced_method = root_method_reducer.reduce();
if (reduced_method) {
concurrent_reduced_methods.update(
method, [&](auto*, auto& reduced_methods_variants, bool) {
reduced_methods_variants.emplace_back(
std::move(*reduced_method));
});
return;
}
DexMethod::erase_method(copy);
DexMethod::delete_method_DO_NOT_USE(copy);
},
ordered_root_methods_variants);
// For each root method, we order the reduced methods (if any) by how many
// types where inlined, with the largest number of inlined types going first.
std::unordered_map<DexMethod*, std::vector<ReducedMethod>> reduced_methods;
for (auto& [method, reduced_methods_variants] : concurrent_reduced_methods) {
std::sort(
reduced_methods_variants.begin(), reduced_methods_variants.end(),
[&](auto& a, auto& b) { return a.types.size() > b.types.size(); });
reduced_methods.emplace(method, std::move(reduced_methods_variants));
}
// All types which could not be accomodated by any reduced method variants are
// marked as "irreducible", which is later used when doing a global cost
// analysis.
static const InlinableTypes no_types;
for (auto&& [method, types] : root_methods) {
auto it = reduced_methods.find(method);
const auto& largest_types =
it == reduced_methods.end() ? no_types : it->second.front().types;
for (auto&& [type, kind] : types) {
if (!largest_types.count(type)) {
irreducible_types->insert(type);
}
}
}
return reduced_methods;
}
// Select all those reduced methods which will result in overall size savings,
// either by looking at local net savings for just a single reduced method, or
// by considering families of reduced methods that affect the same classes.
std::unordered_map<DexMethod*, size_t> select_reduced_methods(
const std::unordered_map<DexMethod*, std::vector<ReducedMethod>>&
reduced_methods,
std::unordered_set<DexType*>* irreducible_types,
Stats* stats) {
Timer t("select_reduced_methods");
// First, we are going to identify all reduced methods which will result in
// local net savings, considering just a single reduced method at a time.
// We'll also build up families of reduced methods for which we can later do a
// global net savings analysis.
ConcurrentSet<DexType*> concurrent_irreducible_types;
ConcurrentMap<DexMethod*, size_t> concurrent_selected_reduced_methods;
// A family of reduced methods for which we'll look at the combined global net
// savings
struct Family {
// Maps root methods to an index into the reduced method variants list.
std::unordered_map<DexMethod*, size_t> reduced_methods;
NetSavings global_net_savings;
};
ConcurrentMap<DexType*, Family> concurrent_families;
workqueue_run<std::pair<DexMethod*, std::vector<ReducedMethod>>>(
[&](const std::pair<DexMethod*, std::vector<ReducedMethod>>& p) {
auto method = p.first;
const auto& reduced_methods_variants = p.second;
always_assert(!reduced_methods_variants.empty());
auto update_irreducible_types = [&](size_t i) {
const auto& reduced_method = reduced_methods_variants.at(i);
const auto& reduced_types = reduced_method.types;
for (auto&& [type, kind] : reduced_methods_variants.at(0).types) {
if (!reduced_types.count(type) &&
kind != InlinableTypeKind::Incomplete) {
concurrent_irreducible_types.insert(type);
}
}
};
// We'll try to find the maximal (involving most inlined non-incomplete
// types) reduced method variant for which we can make the largest
// non-negative local cost determination.
boost::optional<std::pair<size_t, int>> best_candidate;
for (size_t i = 0; i < reduced_methods_variants.size(); i++) {
// If we couldn't accommodate any types, we'll need to add them to the
// irreducible types set. Except for the last variant with the least
// inlined types, for which might below try to make a global cost
// determination.
const auto& reduced_method = reduced_methods_variants.at(i);
auto savings =
reduced_method.get_net_savings(*irreducible_types).get_value();
if (!best_candidate || savings > best_candidate->second) {
best_candidate = std::make_pair(i, savings);
}
// If there are no incomplete types left, we can stop here
const auto& reduced_types = reduced_method.types;
if (best_candidate && best_candidate->second >= 0 &&
!std::any_of(reduced_types.begin(), reduced_types.end(),
[](auto& p) {
return p.second == InlinableTypeKind::Incomplete;
})) {
break;
}
}
if (best_candidate && best_candidate->second >= 0) {
auto [i, savings] = *best_candidate;
stats->total_savings += savings;
concurrent_selected_reduced_methods.emplace(method, i);
update_irreducible_types(i);
return;
}
update_irreducible_types(reduced_methods_variants.size() - 1);
const auto& smallest_reduced_method = reduced_methods_variants.back();
NetSavings conditional_net_savings;
auto local_net_savings = smallest_reduced_method.get_net_savings(
*irreducible_types, &conditional_net_savings);
const auto& classes = conditional_net_savings.classes;
if (std::any_of(classes.begin(), classes.end(), [&](DexType* type) {
return irreducible_types->count(type);
})) {
stats->too_costly_irreducible_classes++;
} else if (classes.size() > 1) {
stats->too_costly_multiple_conditional_classes++;
} else if (classes.empty()) {
stats->too_costly_globally++;
} else {
always_assert(classes.size() == 1);
// For a reduced method variant with only a single involved class,
// we'll do a global cost analysis below.
auto conditional_type = *classes.begin();
concurrent_families.update(
conditional_type, [&](auto*, Family& family, bool) {
family.global_net_savings += local_net_savings;
family.global_net_savings += conditional_net_savings;
family.reduced_methods.emplace(
method, reduced_methods_variants.size() - 1);
});
return;
}
for (auto [type, kind] : smallest_reduced_method.types) {
concurrent_irreducible_types.insert(type);
}
},
reduced_methods);
irreducible_types->insert(concurrent_irreducible_types.begin(),
concurrent_irreducible_types.end());
// Second, perform global net savings analysis
workqueue_run<std::pair<DexType*, Family>>(
[&](const std::pair<DexType*, Family>& p) {
auto& [type, family] = p;
if (irreducible_types->count(type) ||
family.global_net_savings.get_value() < 0) {
stats->too_costly_globally += family.reduced_methods.size();
return;
}
stats->total_savings += family.global_net_savings.get_value();
for (auto& [method, i] : family.reduced_methods) {
concurrent_selected_reduced_methods.emplace(method, i);
}
},
concurrent_families);
return std::unordered_map<DexMethod*, size_t>(
concurrent_selected_reduced_methods.begin(),
concurrent_selected_reduced_methods.end());
}
void reduce(DexStoresVector& stores,
const Scope& scope,
ConfigFiles& conf,
const init_classes::InitClassesWithSideEffects&
init_classes_with_side_effects,
const MethodSummaries& method_summaries,
const std::unordered_map<DexMethod*, InlinableTypes>& root_methods,
Stats* stats,
size_t max_inline_size) {
Timer t("reduce");
ConcurrentMethodRefCache concurrent_resolved_refs;
auto concurrent_resolver = [&](DexMethodRef* method, MethodSearch search) {
return resolve_method(method, search, concurrent_resolved_refs);
};
std::unordered_set<DexMethod*> no_default_inlinables;
// customize shrinking options
auto inliner_config = conf.get_inliner_config();
inliner_config.shrinker = shrinker::ShrinkerConfig();
inliner_config.shrinker.run_const_prop = true;
inliner_config.shrinker.run_cse = true;
inliner_config.shrinker.run_copy_prop = true;
inliner_config.shrinker.run_local_dce = true;
inliner_config.shrinker.compute_pure_methods = false;
int min_sdk = 0;
MultiMethodInliner inliner(scope, init_classes_with_side_effects, stores,
no_default_inlinables, concurrent_resolver,
inliner_config, min_sdk,
MultiMethodInlinerMode::None);
// First, we compute all reduced methods
ExpandableMethodParams expandable_method_params(scope);
std::unordered_set<DexType*> irreducible_types;
auto reduced_methods = compute_reduced_methods(
expandable_method_params, inliner, method_summaries, root_methods,
&irreducible_types, stats, max_inline_size);
stats->reduced_methods = reduced_methods.size();
// Second, we select reduced methods that will result in net savings
auto selected_reduced_methods =
select_reduced_methods(reduced_methods, &irreducible_types, stats);
stats->selected_reduced_methods = selected_reduced_methods.size();
// Finally, we are going to apply those selected methods, and clean up all
// reduced method clones
workqueue_run<std::pair<DexMethod*, std::vector<ReducedMethod>>>(
[&](const std::pair<DexMethod*, std::vector<ReducedMethod>>& p) {
auto& [method, reduced_methods_variants] = p;
auto it = selected_reduced_methods.find(method);
if (it != selected_reduced_methods.end()) {
auto& reduced_method = reduced_methods_variants.at(it->second);
method->set_code(reduced_method.method->release_code());
stats->calls_inlined += reduced_method.calls_inlined;
stats->new_instances_eliminated +=
reduced_method.new_instances_eliminated;
}
stats->reduced_methods_variants += reduced_methods_variants.size();
for (auto& reduced_method : reduced_methods_variants) {
DexMethod::erase_method(reduced_method.method);
DexMethod::delete_method_DO_NOT_USE(reduced_method.method);
}
},
reduced_methods);
size_t expanded_methods = expandable_method_params.flush(scope);
stats->expanded_methods += expanded_methods;
}
} // namespace
void ObjectEscapeAnalysisPass::bind_config() {
bind("max_inline_size", MAX_INLINE_SIZE, m_max_inline_size);
}
void ObjectEscapeAnalysisPass::run_pass(DexStoresVector& stores,
ConfigFiles& conf,
PassManager& mgr) {
const auto scope = build_class_scope(stores);
auto method_override_graph = mog::build_graph(scope);
init_classes::InitClassesWithSideEffects init_classes_with_side_effects(
scope, conf.create_init_class_insns(), method_override_graph.get());
auto non_overridden_virtuals =
hier::find_non_overridden_virtuals(*method_override_graph);
std::unordered_map<DexType*, Locations> new_instances;
std::unordered_map<DexMethod*, Locations> invokes;
std::unordered_map<DexMethod*, std::unordered_set<DexMethod*>> dependencies;
analyze_scope(scope, non_overridden_virtuals, &new_instances, &invokes,
&dependencies);
auto method_summaries = compute_method_summaries(mgr, scope, dependencies,
non_overridden_virtuals);
auto inline_anchors = compute_inline_anchors(scope, method_summaries);
auto root_methods = compute_root_methods(mgr, new_instances, invokes,
method_summaries, inline_anchors);
Stats stats;
reduce(stores, scope, conf, init_classes_with_side_effects, method_summaries,
root_methods, &stats, m_max_inline_size);
walk::parallel::code(scope,
[&](DexMethod*, IRCode& code) { code.clear_cfg(); });
TRACE(OEA, 1, "[object escape analysis] total savings: %zu",
(size_t)stats.total_savings);
TRACE(
OEA, 1,
"[object escape analysis] %zu root methods lead to %zu reduced root "
"methods with %zu variants "
"of which %zu were selected and %zu anchors not inlinable because "
"inlining failed, %zu/%zu invokes not inlinable because callee is "
"init, %zu invokes not inlinable because callee is not concrete,"
"%zu invokes not inlinable because inlining failed, %zu invokes not "
"inlinable after too many iterations, %zu stackify returned objects, "
"%zu too costly with irreducible classes, %zu too costly with multiple "
"conditional classes, %zu too costly globally; %zu expanded methods; %zu "
"calls inlined; %zu new-instances eliminated",
root_methods.size(), (size_t)stats.reduced_methods,
(size_t)stats.reduced_methods_variants,
(size_t)stats.selected_reduced_methods,
(size_t)stats.anchors_not_inlinable_inlining,
(size_t)stats.invokes_not_inlinable_callee_unexpandable,
(size_t)stats.invokes_not_inlinable_callee_too_many_params_to_expand,
(size_t)stats.invokes_not_inlinable_callee_inconcrete,
(size_t)stats.invokes_not_inlinable_inlining,
(size_t)stats.invokes_not_inlinable_too_many_iterations,
(size_t)stats.stackify_returns_objects,
(size_t)stats.too_costly_irreducible_classes,
(size_t)stats.too_costly_multiple_conditional_classes,
(size_t)stats.too_costly_globally, (size_t)stats.expanded_methods,
(size_t)stats.calls_inlined, (size_t)stats.new_instances_eliminated);
mgr.incr_metric("total_savings", stats.total_savings);
mgr.incr_metric("root_methods", root_methods.size());
mgr.incr_metric("reduced_methods", (size_t)stats.reduced_methods);
mgr.incr_metric("reduced_methods_variants",
(size_t)stats.reduced_methods_variants);
mgr.incr_metric("selected_reduced_methods",
(size_t)stats.selected_reduced_methods);
mgr.incr_metric("root_method_anchors_not_inlinable_inlining",
(size_t)stats.anchors_not_inlinable_inlining);
mgr.incr_metric("root_method_invokes_not_inlinable_callee_unexpandable",
(size_t)stats.invokes_not_inlinable_callee_unexpandable);
mgr.incr_metric(
"root_method_invokes_not_inlinable_callee_is_init_too_many_params_to_"
"expand",
(size_t)stats.invokes_not_inlinable_callee_too_many_params_to_expand);
mgr.incr_metric("root_method_invokes_not_inlinable_callee_inconcrete",
(size_t)stats.invokes_not_inlinable_callee_inconcrete);
mgr.incr_metric("root_method_invokes_not_inlinable_inlining",
(size_t)stats.invokes_not_inlinable_inlining);
mgr.incr_metric("root_method_invokes_not_inlinable_too_many_iterations",
(size_t)stats.invokes_not_inlinable_too_many_iterations);
mgr.incr_metric("root_method_stackify_returns_objects",
(size_t)stats.stackify_returns_objects);
mgr.incr_metric("root_method_too_costly_globally",
(size_t)stats.too_costly_globally);
mgr.incr_metric("root_method_too_costly_multiple_conditional_classes",
(size_t)stats.too_costly_multiple_conditional_classes);
mgr.incr_metric("root_method_too_costly_irreducible_classes",
(size_t)stats.too_costly_irreducible_classes);
mgr.incr_metric("expanded_methods", (size_t)stats.expanded_methods);
mgr.incr_metric("calls_inlined", (size_t)stats.calls_inlined);
mgr.incr_metric("new_instances_eliminated",
(size_t)stats.new_instances_eliminated);
}
static ObjectEscapeAnalysisPass s_pass;
|
#define NOMINMAX
#ifdef _WIN32
#define GLEW_STATIC 1
#include <GL/glew.h>
#endif
#include "../EffekseerTool/EffekseerTool.Renderer.h"
#include "efk.GUIManager.h"
#include "Platform/efk.Language.h"
#include "efk.JapaneseFont.h"
#include "../3rdParty/imgui_addon/fcurve/fcurve.h"
#include "../3rdParty/Boxer/boxer.h"
#include "../dll.h"
namespace ImGui
{
static ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs)
{
return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y);
}
static ImVec2 operator * (const ImVec2& lhs, const float& rhs)
{
return ImVec2(lhs.x * rhs, lhs.y * rhs);
}
bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, bool* v, ImTextureID user_texture, const char* label, const char* label_end)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0;
const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f);
if (!label_end)
label_end = FindRenderedTextEnd(label);
const ImVec2 label_size = CalcTextSize(label, label_end, false);
// We vertically grow up to current line height up the typical widget height.
const float text_base_offset_y = ImMax(padding.y, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it
const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y * 2), label_size.y + padding.y * 2);
const float icon_size = frame_height;
ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height));
if (display_frame)
{
// Framed header expand a little outside the default padding
frame_bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1;
frame_bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1;
}
const float text_offset_x = (g.FontSize + icon_size + (display_frame ? padding.x * 3 : padding.x * 2)); // Collapser arrow width + Spacing
const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x * 2 : 0.0f); // Include collapser
ItemSize(ImVec2(text_width + icon_size, frame_height), text_base_offset_y);
// For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
// (Ideally we'd want to add a flag for the user to specify if we want the hit test to be done up to the right side of the content or not)
const ImRect interact_bb = display_frame ? frame_bb : ImRect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + text_width + style.ItemSpacing.x * 2, frame_bb.Max.y);
bool is_open = TreeNodeBehaviorIsOpen(id, flags);
// Store a flag for the current depth to tell if we will allow closing this node when navigating one of its child.
// For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop().
// This is currently only support 32 level deep and we are fine with (1 << Depth) overflowing into a zero.
if (is_open && !g.NavIdIsAlive && (flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
window->DC.TreeDepthMayJumpToParentOnPop |= (1 << window->DC.TreeDepth);
bool item_add = ItemAdd(interact_bb, id);
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDisplayRect;
window->DC.LastItemDisplayRect = frame_bb;
if (!item_add)
{
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushRawID(id);
return is_open;
}
// Flags that affects opening behavior:
// - 0(default) ..................... single-click anywhere to open
// - OpenOnDoubleClick .............. double-click anywhere to open
// - OpenOnArrow .................... single-click on arrow to open
// - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open
ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowItemOverlap) ? ImGuiButtonFlags_AllowItemOverlap : 0);
if (!(flags & ImGuiTreeNodeFlags_Leaf))
button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0);
bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);
if (!(flags & ImGuiTreeNodeFlags_Leaf))
{
bool toggled = false;
if (pressed)
{
toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) || (g.NavActivateId == id);
if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y)) && (!g.NavDisableMouseHover);
if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
toggled |= g.IO.MouseDoubleClicked[0];
if (g.DragDropActive && is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again.
toggled = false;
}
if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Left && is_open)
{
toggled = true;
NavMoveRequestCancel();
}
if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?
{
toggled = true;
NavMoveRequestCancel();
}
if (toggled)
{
is_open = !is_open;
window->DC.StateStorage->SetInt(id, is_open);
}
}
if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)
SetItemAllowOverlap();
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
const ImVec2 text_pos = frame_bb.Min + ImVec2(text_offset_x, text_base_offset_y);
if (display_frame)
{
// Framed type
RenderFrame(frame_bb.Min, frame_bb.Max, col, true, style.FrameRounding);
RenderNavHighlight(frame_bb, id, ImGuiNavHighlightFlags_TypeThin);
RenderArrow(frame_bb.Min + ImVec2(padding.x, text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f);
window->DrawList->AddImage(user_texture,
frame_bb.Min + ImVec2(padding.x + g.FontSize, text_base_offset_y),
frame_bb.Min + ImVec2(padding.x + g.FontSize, text_base_offset_y) + ImVec2(icon_size,icon_size), ImVec2(0, 0), ImVec2(1, 1));
if (g.LogEnabled)
{
// NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here.
const char log_prefix[] = "\n##";
const char log_suffix[] = "##";
//LogRenderedText(&text_pos, log_prefix, log_prefix + 3);
RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
//LogRenderedText(&text_pos, log_suffix + 1, log_suffix + 3);
}
else
{
RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
}
}
else
{
// Unframed typed for tree nodes
if (hovered || (flags & ImGuiTreeNodeFlags_Selected))
{
RenderFrame(frame_bb.Min, frame_bb.Max, col, false);
RenderNavHighlight(frame_bb, id, ImGuiNavHighlightFlags_TypeThin);
}
if (flags & ImGuiTreeNodeFlags_Bullet)
RenderBullet(frame_bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y));
else if (!(flags & ImGuiTreeNodeFlags_Leaf))
RenderArrow(frame_bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f);
//if (g.LogEnabled)
// LogRenderedText(&text_pos, ">");
window->DrawList->AddImage(user_texture,
frame_bb.Min + ImVec2(padding.x + g.FontSize, text_base_offset_y),
frame_bb.Min + ImVec2(padding.x + g.FontSize, text_base_offset_y) + ImVec2(icon_size, icon_size), ImVec2(0, 0), ImVec2(1, 1));
RenderText(text_pos, label, label_end, false);
}
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushRawID(id);
return is_open;
}
bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags, bool* v, ImTextureID user_texture)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
return TreeNodeBehavior(window->GetID(label), flags, v, user_texture, label, NULL);
}
bool ImageButton_(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
// Default to using texture ID as ID. User can still push string/integer prefixes.
// We could hash the size/uv to create a unique ID but that would prevent the user from animating UV.
PushID((void *)user_texture_id);
const ImGuiID id = window->GetID("#image");
PopID();
const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding * 2);
const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size);
ItemSize(bb);
if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_PressedOnClick);
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding));
if (bg_col.w > 0.0f)
window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col));
window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col));
return pressed;
}
}
namespace efk
{
template <size_t size_>
struct utf8str {
enum {size = size_};
char data[size];
utf8str(const char16_t* u16str) {
Effekseer::ConvertUtf16ToUtf8((int8_t*)data, size, (const int16_t*)u16str);
}
operator const char*() const {
return data;
}
};
// http://hasenpfote36.blogspot.jp/2016/09/stdcodecvt.html
static constexpr std::codecvt_mode mode = std::codecvt_mode::little_endian;
static std::string utf16_to_utf8(const std::u16string& s)
{
#if defined(_MSC_VER)
std::wstring_convert<std::codecvt_utf8_utf16<std::uint16_t, 0x10ffff, mode>, std::uint16_t> conv;
auto p = reinterpret_cast<const std::uint16_t*>(s.c_str());
return conv.to_bytes(p, p + s.length());
#else
std::wstring_convert<std::codecvt_utf8_utf16<char16_t, 0x10ffff, mode>, char16_t> conv;
return conv.to_bytes(s);
#endif
}
static std::u16string utf8_to_utf16(const std::string& s)
{
#if defined(_MSC_VER)
std::wstring_convert<std::codecvt_utf8_utf16<std::uint16_t, 0x10ffff, mode>, std::uint16_t> conv;
auto p = reinterpret_cast<const std::uint16_t*>(s.c_str());
return std::u16string((const char16_t*)conv.from_bytes(s).c_str());
#else
std::wstring_convert<std::codecvt_utf8_utf16<char16_t, 0x10ffff, mode>, char16_t> conv;
return conv.from_bytes(s);
#endif
}
static ImTextureID ToImTextureID(ImageResource* image)
{
if (image != nullptr)
{
Effekseer::TextureData* texture = image->GetTextureData();
if (texture != nullptr)
{
if (texture->UserPtr != nullptr)
{
return (ImTextureID)texture->UserPtr;
}
else
{
return (ImTextureID)texture->UserID;
}
}
}
return nullptr;
}
bool DragFloatN(const char* label, float* v, int components, float v_speed, float* v_min, float* v_max,
const char* display_format1,
const char* display_format2,
const char* display_format3,
float power)
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
ImGui::BeginGroup();
ImGui::PushID(label);
ImGui::PushMultiItemsWidths(components);
const char* display_formats[] = {
display_format1,
display_format2,
display_format3
};
for (int i = 0; i < components; i++)
{
ImGui::PushID(i);
value_changed |= ImGui::DragFloat("##v", &v[i], v_speed, v_min[i], v_max[i], display_formats[i], power);
ImGui::SameLine(0, g.Style.ItemInnerSpacing.x);
ImGui::PopID();
ImGui::PopItemWidth();
}
ImGui::PopID();
ImGui::TextUnformatted(label, ImGui::FindRenderedTextEnd(label));
ImGui::EndGroup();
return value_changed;
}
bool DragIntN(const char* label, int* v, int components, int v_speed, int* v_min, int* v_max,
const char* display_format1,
const char* display_format2,
const char* display_format3)
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
ImGui::BeginGroup();
ImGui::PushID(label);
ImGui::PushMultiItemsWidths(components);
const char* display_formats[] = {
display_format1,
display_format2,
display_format3
};
for (int i = 0; i < components; i++)
{
ImGui::PushID(i);
value_changed |= ImGui::DragInt("##v", &v[i], v_speed, v_min[i], v_max[i], display_formats[i]);
ImGui::SameLine(0, g.Style.ItemInnerSpacing.x);
ImGui::PopID();
ImGui::PopItemWidth();
}
ImGui::PopID();
ImGui::TextUnformatted(label, ImGui::FindRenderedTextEnd(label));
ImGui::EndGroup();
return value_changed;
}
GUIManager::GUIManager()
{}
GUIManager::~GUIManager()
{}
bool GUIManager::Initialize(const char16_t* title, int32_t width, int32_t height, efk::DeviceType deviceType, bool isSRGBMode)
{
window = new efk::Window();
this->deviceType = deviceType;
if (!window->Initialize(title, width, height, isSRGBMode, deviceType))
{
ES_SAFE_DELETE(window);
return false;
}
window->Resized = [this](int x, int y) -> void
{
if (this->callback != nullptr)
{
this->callback->Resized(x, y);
}
};
window->Focused = [this]() -> void
{
if (this->callback != nullptr)
{
this->callback->Focused();
}
};
window->Droped = [this](const char* path) -> void
{
if (this->callback != nullptr)
{
this->callback->SetPath(utf8_to_utf16(path).c_str());
this->callback->Droped();
}
};
window->Closing = [this]() -> bool
{
if (this->callback != nullptr)
{
return this->callback->Closing();
}
return true;
};
window->Iconify = [this](float f) -> void
{
if (this->callback != nullptr)
{
this->callback->Iconify(f);
}
};
if (deviceType == DeviceType::OpenGL)
{
window->MakeCurrent();
#ifdef _WIN32
glewInit();
#endif
}
#ifdef _WIN32
// Calculate font scale from DPI
HDC screen = GetDC(0);
int dpiX = GetDeviceCaps(screen, LOGPIXELSX);
fontScale = (float)dpiX / 96.0f;
#endif
return true;
}
void GUIManager::InitializeGUI(Native* native)
{
ImGui::CreateContext();
if (deviceType == DeviceType::OpenGL)
{
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
#if __APPLE__
// GL 3.2 + GLSL 150
const char* glsl_version = "#version 150";
#else
// GL 3.0 + GLSL 130
const char* glsl_version = "#version 130";
#endif
ImGui_ImplGlfw_InitForOpenGL(window->GetGLFWWindows(), true);
ImGui_ImplOpenGL3_Init(glsl_version);
}
#ifdef _WIN32
else if (deviceType == DeviceType::DirectX11)
{
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
ImGui_ImplGlfw_InitForVulkan(window->GetGLFWWindows(), true);
auto r = (EffekseerRendererDX11::Renderer*)native->GetRenderer();
ImGui_ImplDX11_Init(r->GetDevice(), r->GetContext());
}
else
{
ImGui_ImplGlfw_InitForOpenGL(window->GetGLFWWindows(), true);
auto r = (EffekseerRendererDX9::Renderer*)native->GetRenderer();
ImGui_ImplDX9_Init(r->GetDevice());
}
#endif
ImGui::StyleColorsDark();
ImGuiStyle& style = ImGui::GetStyle();
style.ChildRounding = 3.f;
style.GrabRounding = 3.f;
style.WindowRounding = 3.f;
style.ScrollbarRounding = 3.f;
style.FrameRounding = 3.f;
style.WindowTitleAlign = ImVec2(0.5f, 0.5f);
// mono tone
for (int32_t i = 0; i < ImGuiCol_COUNT; i++)
{
auto v = (style.Colors[i].x + style.Colors[i].y + style.Colors[i].z) / 3.0f;
style.Colors[i].x = v;
style.Colors[i].y = v;
style.Colors[i].z = v;
}
style.Colors[ImGuiCol_Text] = ImVec4(0.80f, 0.80f, 0.80f, 1.00f);
style.Colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
style.Colors[ImGuiCol_WindowBg] = ImVec4(0.1f, 0.1f, 0.1f, 0.9f);
}
void GUIManager::SetTitle(const char16_t* title)
{
window->SetTitle(title);
}
void GUIManager::SetWindowIcon(const char16_t * iconPath)
{
window->SetWindowIcon(iconPath);
}
Vec2 GUIManager::GetSize() const
{
return window->GetSize();
}
void GUIManager::SetSize(int32_t width, int32_t height)
{
window->SetSize(width, height);
}
void GUIManager::Terminate()
{
if (deviceType == DeviceType::OpenGL)
{
ImGui_ImplOpenGL3_Shutdown();
}
#ifdef _WIN32
else if (deviceType == DeviceType::DirectX11)
{
ImGui_ImplDX11_Shutdown();
}
else
{
ImGui_ImplDX9_Shutdown();
}
#endif
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
window->MakeNone();
window->Terminate();
ES_SAFE_DELETE(window);
}
bool GUIManager::DoEvents()
{
return window->DoEvents();
}
void GUIManager::Present()
{
window->Present();
}
void GUIManager::Close()
{
window->Close();
}
Vec2 GUIManager::GetMousePosition()
{
return window->GetMousePosition();
}
int GUIManager::GetMouseButton(int32_t mouseButton)
{
return window->GetMouseButton(mouseButton);
}
int GUIManager::GetMouseWheel()
{
return ImGui::GetIO().MouseWheel;
}
void GUIManager::SetCallback(GUIManagerCallback* callback)
{
this->callback = callback;
}
void GUIManager::ResetGUI()
{
if (deviceType == DeviceType::OpenGL)
{
ImGui_ImplOpenGL3_NewFrame();
}
#if _WIN32
else if (deviceType == DeviceType::DirectX11)
{
ImGui_ImplDX11_NewFrame();
}
else
{
ImGui_ImplDX9_NewFrame();
}
#endif
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
}
void GUIManager::RenderGUI(bool isValid)
{
ImGui::EndFrame();
ImGui::Render();
if (isValid)
{
if (deviceType == DeviceType::OpenGL)
{
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
#if _WIN32
else if (deviceType == DeviceType::DirectX11)
{
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
}
else
{
ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData());
}
#endif
}
else
{
if (ImGui::GetDrawData() != nullptr)
{
ImGui::GetDrawData()->Clear();
}
}
{
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
}
if (deviceType == DeviceType::OpenGL)
{
glfwMakeContextCurrent(window->GetGLFWWindows());
}
}
}
void* GUIManager::GetNativeHandle()
{
return window->GetNativeHandle();
}
const char16_t* GUIManager::GetClipboardText()
{
auto ret = glfwGetClipboardString(window->GetGLFWWindows());
clipboard = utf8_to_utf16(ret);
return clipboard.c_str();
}
void GUIManager::SetClipboardText(const char16_t* text)
{
glfwSetClipboardString(window->GetGLFWWindows(), utf16_to_utf8(text).c_str());
}
bool GUIManager::Begin(const char16_t* name, bool* p_open)
{
return ImGui::Begin(utf8str<256>(name), p_open);
}
void GUIManager::End()
{
ImGui::End();
}
bool GUIManager::BeginChild(const char* str_id, const Vec2& size_arg, bool border, WindowFlags extra_flags)
{
return ImGui::BeginChild(str_id, ImVec2(size_arg.X, size_arg.Y), border, (ImGuiWindowFlags)extra_flags);
}
void GUIManager::EndChild()
{
ImGui::EndChild();
}
Vec2 GUIManager::GetWindowSize()
{
auto v = ImGui::GetWindowSize();
return Vec2(v.x, v.y);
}
Vec2 GUIManager::GetContentRegionAvail()
{
auto v = ImGui::GetContentRegionAvail();
return Vec2(v.x, v.y);
}
void GUIManager::SetNextWindowSize(float size_x, float size_y, Cond cond)
{
ImVec2 size;
size.x = size_x;
size.y = size_y;
ImGui::SetNextWindowSize(size, (int)cond);
}
void GUIManager::PushItemWidth(float item_width)
{
ImGui::PushItemWidth(item_width);
}
void GUIManager::PopItemWidth()
{
ImGui::PopItemWidth();
}
void GUIManager::Separator()
{
ImGui::Separator();
}
void GUIManager::HiddenSeparator()
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
ImGuiSeparatorFlags flags = 0;
if ((flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)) == 0)
flags |= (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal;
IM_ASSERT(ImIsPowerOfTwo((int)(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)))); // Check that only 1 option is selected
if (flags & ImGuiSeparatorFlags_Vertical)
{
ImGui::VerticalSeparator();
return;
}
// Horizontal Separator
if (window->DC.ColumnsSet)
ImGui::PopClipRect();
float x1 = window->Pos.x;
float x2 = window->Pos.x + window->Size.x;
if (!window->DC.GroupStack.empty())
x1 += window->DC.IndentX;
const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y + 4.0f));
ImGui::ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit, we don't provide height to not alter layout.
if (!ImGui::ItemAdd(bb, 0))
{
if (window->DC.ColumnsSet)
ImGui::PushColumnClipRect();
return;
}
window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x, bb.Min.y), 0);
if (window->DC.ColumnsSet)
{
ImGui::PushColumnClipRect();
window->DC.ColumnsSet->LineMinY = window->DC.CursorPos.y;
}
}
void GUIManager::SameLine()
{
ImGui::SameLine();
}
void GUIManager::BeginGroup()
{
ImGui::BeginGroup();
}
void GUIManager::EndGroup()
{
ImGui::EndGroup();
}
void GUIManager::SetCursorPosX(float x)
{
ImGui::SetCursorPosX(x);
}
void GUIManager::SetCursorPosY(float y)
{
ImGui::SetCursorPosY(y);
}
float GUIManager::GetCursorPosX()
{
return ImGui::GetCursorPosX();
}
float GUIManager::GetCursorPosY()
{
return ImGui::GetCursorPosY();
}
float GUIManager::GetTextLineHeight()
{
return ImGui::GetTextLineHeight();
}
float GUIManager::GetTextLineHeightWithSpacing()
{
return ImGui::GetTextLineHeightWithSpacing();
}
float GUIManager::GetFrameHeight()
{
return ImGui::GetFrameHeight();
}
float GUIManager::GetFrameHeightWithSpacing()
{
return ImGui::GetFrameHeightWithSpacing();
}
void GUIManager::Columns(int count, const char* id, bool border)
{
ImGui::Columns(count, id, border);
}
void GUIManager::NextColumn()
{
ImGui::NextColumn();
}
float GUIManager::GetColumnWidth(int column_index)
{
return ImGui::GetColumnWidth(column_index);
}
void GUIManager::SetColumnWidth(int column_index, float width)
{
ImGui::SetColumnWidth(column_index, width);
}
float GUIManager::GetColumnOffset(int column_index)
{
return ImGui::GetColumnOffset(column_index);
}
void GUIManager::SetColumnOffset(int column_index, float offset_x)
{
ImGui::SetColumnOffset(column_index, offset_x);
}
void GUIManager::Text(const char16_t* text)
{
if (std::char_traits<char16_t>::length(text) < 1024)
{
ImGui::Text(utf8str<1024>(text));
}
else
{
ImGui::Text(utf16_to_utf8(text).c_str());
}
}
void GUIManager::TextWrapped(const char16_t* text)
{
if (std::char_traits<char16_t>::length(text) < 1024)
{
ImGui::TextWrapped(utf8str<1024>(text));
}
else
{
ImGui::TextWrapped(utf16_to_utf8(text).c_str());
}
}
bool GUIManager::Button(const char16_t* label, float size_x, float size_y)
{
return ImGui::Button(utf8str<256>(label), ImVec2(size_x, size_y));
}
void GUIManager::Image(ImageResource* user_texture_id, float x, float y)
{
ImGui::Image(ToImTextureID(user_texture_id), ImVec2(x, y));
}
void GUIManager::Image(void* user_texture_id, float x, float y)
{
if (deviceType != DeviceType::OpenGL)
{
ImGui::Image((ImTextureID)user_texture_id, ImVec2(x, y), ImVec2(0, 0), ImVec2(1, 1));
}
else
{
ImGui::Image((ImTextureID)user_texture_id, ImVec2(x, y), ImVec2(0, 1), ImVec2(1, 0));
}
}
bool GUIManager::ImageButton(ImageResource* user_texture_id, float x, float y)
{
return ImGui::ImageButton_(ToImTextureID(user_texture_id), ImVec2(x, y), ImVec2(0, 0), ImVec2(1, 1), 0, ImVec4(0, 0, 0, 0), ImVec4(1, 1, 1, 1));
}
bool GUIManager::Checkbox(const char16_t* label, bool* v)
{
return ImGui::Checkbox(utf8str<256>(label), v);
}
bool GUIManager::RadioButton(const char16_t* label, bool active)
{
return ImGui::RadioButton(utf8str<256>(label), active);
}
bool GUIManager::InputInt(const char16_t* label, int* v, int step, int step_fast)
{
return ImGui::InputInt(utf8str<256>(label), v, step, step_fast);
}
bool GUIManager::SliderInt(const char16_t* label, int* v, int v_min, int v_max)
{
return ImGui::SliderInt(utf8str<256>(label), v, v_min, v_max);
}
bool GUIManager::BeginCombo(const char16_t* label, const char16_t* preview_value, ComboFlags flags, ImageResource* user_texture_id)
{
return ImGui::BeginCombo(
utf8str<256>(label),
utf8str<256>(preview_value),
(int)flags, ToImTextureID(user_texture_id));
}
void GUIManager::EndCombo()
{
ImGui::EndCombo();
}
bool GUIManager::DragFloat(const char16_t* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power)
{
return ImGui::DragFloat(utf8str<256>(label), v, v_speed, v_min, v_max, display_format);
}
bool GUIManager::DragFloat2(const char16_t* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power)
{
return ImGui::DragFloat2(utf8str<256>(label), v, v_speed, v_min, v_max, display_format);
}
bool GUIManager::DragFloat3(const char16_t* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power)
{
return ImGui::DragFloat3(utf8str<256>(label), v, v_speed, v_min, v_max, display_format);
}
bool GUIManager::DragFloat4(const char16_t* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power)
{
return ImGui::DragFloat4(utf8str<256>(label), v, v_speed, v_min, v_max, display_format);
}
bool GUIManager::DragFloatRange2(const char16_t* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* display_format, const char* display_format_max, float power)
{
return ImGui::DragFloatRange2(utf8str<256>(label), v_current_min, v_current_max, v_speed, v_min, v_max, display_format, display_format_max);
}
bool GUIManager::DragInt(const char16_t* label, int* v, float v_speed, int v_min, int v_max, const char* display_format)
{
return ImGui::DragInt(utf8str<256>(label), v, v_speed, v_min, v_max, display_format);
}
bool GUIManager::DragInt2(const char16_t* label, int* v, float v_speed, int v_min, int v_max, const char* display_format)
{
return ImGui::DragInt2(utf8str<256>(label), v, v_speed, v_min, v_max, display_format);
}
bool GUIManager::DragInt3(const char16_t* label, int* v, float v_speed, int v_min, int v_max, const char* display_format)
{
return ImGui::DragInt3(utf8str<256>(label), v, v_speed, v_min, v_max, display_format);
}
bool GUIManager::DragInt4(const char16_t* label, int* v, float v_speed, int v_min, int v_max, const char* display_format)
{
return ImGui::DragInt4(utf8str<256>(label), v, v_speed, v_min, v_max, display_format);
}
bool GUIManager::DragIntRange2(const char16_t* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* display_format, const char* display_format_max)
{
return ImGui::DragIntRange2(utf8str<256>(label), v_current_min, v_current_max, v_speed, v_min, v_max, display_format, display_format_max);
}
bool GUIManager::DragFloat1EfkEx(const char16_t* label, float* v, float v_speed, float v_min, float v_max, const char16_t* display_format1, float power)
{
float v_min_[3];
float v_max_[3];
v_min_[0] = v_min;
v_max_[0] = v_max;
return DragFloatN(
utf8str<256>(label), v, 1, v_speed, v_min_, v_max_,
utf8str<256>(display_format1),
nullptr,
nullptr,
power);
}
bool GUIManager::DragFloat2EfkEx(const char16_t* label, float* v, float v_speed, float v_min1, float v_max1, float v_min2, float v_max2, const char16_t* display_format1, const char16_t* display_format2, float power)
{
float v_min_[3];
float v_max_[3];
v_min_[0] = v_min1;
v_max_[0] = v_max1;
v_min_[1] = v_min2;
v_max_[1] = v_max2;
return DragFloatN(
utf8str<256>(label), v, 2, v_speed, v_min_, v_max_,
utf8str<256>(display_format1),
utf8str<256>(display_format2),
nullptr,
power);
}
bool GUIManager::DragFloat3EfkEx(const char16_t* label, float* v, float v_speed, float v_min1, float v_max1, float v_min2, float v_max2, float v_min3, float v_max3, const char16_t* display_format1, const char16_t* display_format2, const char16_t* display_format3, float power)
{
float v_min_[3];
float v_max_[3];
v_min_[0] = v_min1;
v_max_[0] = v_max1;
v_min_[1] = v_min2;
v_max_[1] = v_max2;
v_min_[2] = v_min3;
v_max_[2] = v_max3;
return DragFloatN(
utf8str<256>(label), v, 3, v_speed, v_min_, v_max_,
utf8str<256>(display_format1),
utf8str<256>(display_format2),
utf8str<256>(display_format3),
power);
}
bool GUIManager::DragInt2EfkEx(const char16_t* label, int* v, int v_speed, int v_min1, int v_max1, int v_min2, int v_max2, const char16_t* display_format1, const char16_t* display_format2)
{
int v_min_[3];
int v_max_[3];
v_min_[0] = v_min1;
v_max_[0] = v_max1;
v_min_[1] = v_min2;
v_max_[1] = v_max2;
return DragIntN(
utf8str<256>(label), v, 2, v_speed, v_min_, v_max_,
utf8str<256>(display_format1),
utf8str<256>(display_format2),
nullptr);
}
static std::u16string inputTextResult;
bool GUIManager::InputText(const char16_t* label, const char16_t* text, InputTextFlags flags)
{
auto text_ = utf8str<1024>(text);
char buf[260];
memcpy(buf, text_.data, std::min((int32_t)text_.size, 250));
buf[std::min((int32_t)text_.size, 250)] = 0;
auto ret = ImGui::InputText(utf8str<256>(label), buf, 260, (ImGuiWindowFlags)flags);
inputTextResult = utf8_to_utf16(buf);
return ret;
}
const char16_t* GUIManager::GetInputTextResult()
{
return inputTextResult.c_str();
}
bool GUIManager::ColorEdit4(const char16_t* label, float* col, ColorEditFlags flags)
{
return ImGui::ColorEdit4(utf8str<256>(label), col, (int)flags);
}
bool GUIManager::TreeNode(const char16_t* label)
{
return ImGui::TreeNode(utf8str<256>(label));
}
bool GUIManager::TreeNodeEx(const char16_t* label, TreeNodeFlags flags)
{
return ImGui::TreeNodeEx(utf8str<256>(label), (int)flags);
}
void GUIManager::TreePop()
{
ImGui::TreePop();
}
void GUIManager::SetNextTreeNodeOpen(bool is_open, Cond cond)
{
ImGui::SetNextTreeNodeOpen(is_open, (ImGuiCond)cond);
}
bool GUIManager::TreeNodeEx(const char16_t* label, bool* v, ImageResource* user_texture_id, TreeNodeFlags flags)
{
return ImGui::TreeNodeEx(utf8str<256>(label), (ImGuiTreeNodeFlags)flags, v, ToImTextureID(user_texture_id));
}
bool GUIManager::Selectable(const char16_t* label, bool selected, SelectableFlags flags, ImageResource* user_texture_id)
{
return ImGui::Selectable(utf8str<256>(label), selected, (int)flags, ImVec2(0, 0), ToImTextureID(user_texture_id));
}
void GUIManager::SetTooltip(const char16_t* text)
{
ImGui::SetTooltip(utf8str<256>(text));
}
void GUIManager::BeginTooltip()
{
ImGui::BeginTooltip();
}
void GUIManager::EndTooltip()
{
ImGui::EndTooltip();
}
bool GUIManager::BeginMainMenuBar()
{
return ImGui::BeginMainMenuBar();
}
void GUIManager::EndMainMenuBar()
{
ImGui::EndMainMenuBar();
}
bool GUIManager::BeginMenuBar()
{
return ImGui::BeginMenuBar();
}
void GUIManager::EndMenuBar()
{
return ImGui::EndMenuBar();
}
bool GUIManager::BeginMenu(const char16_t* label, bool enabled)
{
return ImGui::BeginMenu(utf8str<256>(label), enabled);
}
void GUIManager::EndMenu()
{
ImGui::EndMenu();
}
bool GUIManager::MenuItem(const char16_t* label, const char* shortcut, bool selected, bool enabled, ImageResource* icon)
{
return ImGui::MenuItem(utf8str<256>(label), shortcut, selected, enabled, ToImTextureID(icon));
}
bool GUIManager::MenuItem(const char16_t* label, const char* shortcut, bool* p_selected, bool enabled, ImageResource* icon)
{
return ImGui::MenuItem(utf8str<256>(label), shortcut, p_selected, enabled, ToImTextureID(icon));
}
void GUIManager::OpenPopup(const char* str_id)
{
ImGui::OpenPopup(str_id);
}
bool GUIManager::BeginPopup(const char* str_id, WindowFlags extra_flags)
{
return ImGui::BeginPopup(str_id, (int)extra_flags);
}
bool GUIManager::BeginPopupModal(const char16_t* name, bool* p_open, WindowFlags extra_flags)
{
return ImGui::BeginPopupModal(utf8str<256>(name), p_open, (int)extra_flags);
}
bool GUIManager::BeginPopupContextItem(const char* str_id, int mouse_button)
{
return ImGui::BeginPopupContextItem(str_id, mouse_button);
}
void GUIManager::EndPopup()
{
ImGui::EndPopup();
}
bool GUIManager::IsPopupOpen(const char* str_id)
{
return ImGui::IsPopupOpen(str_id);
}
void GUIManager::CloseCurrentPopup()
{
ImGui::CloseCurrentPopup();
}
void GUIManager::SetItemDefaultFocus()
{
ImGui::SetItemDefaultFocus();
}
void GUIManager::AddFontFromFileTTF(const char* filename, float size_pixels)
{
ImGuiIO& io = ImGui::GetIO();
size_pixels = roundf(size_pixels * fontScale);
io.Fonts->AddFontFromFileTTF(filename, size_pixels, nullptr, glyphRangesJapanese);
}
bool GUIManager::BeginChildFrame(uint32_t id, const Vec2& size, WindowFlags flags)
{
return ImGui::BeginChildFrame(id, ImVec2(size.X, size.Y), (int32_t)flags);
}
void GUIManager::EndChildFrame()
{
ImGui::EndChildFrame();
}
bool GUIManager::IsKeyDown(int user_key_index)
{
return ImGui::IsKeyDown(user_key_index);
}
bool GUIManager::IsMouseDown(int button)
{
return ImGui::IsMouseDown(button);
}
bool GUIManager::IsMouseDoubleClicked(int button)
{
return ImGui::IsMouseDoubleClicked(button);
}
bool GUIManager::IsItemHovered()
{
return ImGui::IsItemHovered();
}
bool GUIManager::IsItemActive()
{
return ImGui::IsItemActive();
}
bool GUIManager::IsItemFocused()
{
return ImGui::IsItemFocused();
}
bool GUIManager::IsItemClicked(int mouse_button)
{
return ImGui::IsItemClicked(mouse_button);
}
bool GUIManager::IsWindowHovered()
{
return ImGui::IsWindowHovered();
}
bool GUIManager::IsAnyWindowHovered()
{
return ImGui::IsAnyWindowHovered();
}
MouseCursor GUIManager::GetMouseCursor()
{
return (MouseCursor)ImGui::GetMouseCursor();
}
void GUIManager::DrawLineBackground(float height, uint32_t col)
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
auto cursorPos = ImGui::GetCursorPos();
cursorPos.x = window->Pos.x;
cursorPos.y = window->DC.CursorPos.y;
ImVec2 size;
size.x = window->Size.x;
size.y = height;
window->DrawList->AddRectFilled(cursorPos, ImVec2(cursorPos.x + size.x, cursorPos.y + size.y), col);
}
bool GUIManager::BeginFullscreen(const char16_t* label)
{
ImVec2 windowSize;
windowSize.x = ImGui::GetIO().DisplaySize.x;
windowSize.y = ImGui::GetIO().DisplaySize.y - 25;
ImGui::SetNextWindowSize(windowSize);
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
auto pos = ImGui::GetMainViewport()->Pos;
pos.y += 25;
ImGui::SetNextWindowPos(pos);
}
else
{
ImGui::SetNextWindowPos(ImVec2(0, 25));
}
const ImGuiWindowFlags flags = (ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoTitleBar);
const float oldWindowRounding = ImGui::GetStyle().WindowRounding; ImGui::GetStyle().WindowRounding = 0;
const bool visible = ImGui::Begin(utf8str<256>(label), NULL, ImVec2(0, 0), 1.0f, flags);
ImGui::GetStyle().WindowRounding = oldWindowRounding;
return visible;
}
void GUIManager::SetNextDock(DockSlot slot)
{
ImGui::SetNextDock((ImGuiDockSlot)slot);
}
void GUIManager::BeginDockspace()
{
ImGui::BeginDockspace();
}
void GUIManager::EndDockspace()
{
ImGui::EndDockspace();
}
bool GUIManager::BeginDock(const char16_t* label, bool* p_open, WindowFlags extra_flags, Vec2 default_size)
{
return ImGui::BeginDock(utf8str<256>(label), p_open, (int32_t)extra_flags, ImVec2(default_size.X, default_size.Y));
}
void GUIManager::EndDock()
{
ImGui::EndDock();
}
void GUIManager::SetNextDockRate(float rate)
{
ImGui::SetNextDockRate(rate);
}
void GUIManager::ResetNextParentDock()
{
ImGui::ResetNextParentDock();
}
void GUIManager::SaveDock(const char* path)
{
ImGui::SaveDock(path);
}
void GUIManager::LoadDock(const char* path)
{
ImGui::LoadDock(path);
}
void GUIManager::ShutdownDock()
{
ImGui::ShutdownDock();
}
void GUIManager::SetNextDockIcon(ImageResource* icon, Vec2 iconSize)
{
ImGui::SetNextDockIcon(ToImTextureID(icon), ImVec2(iconSize.X, iconSize.Y));
}
void GUIManager::SetNextDockTabToolTip(const char16_t* popup)
{
ImGui::SetNextDockTabToolTip(utf8str<256>(popup));
}
bool GUIManager::GetDockActive()
{
return ImGui::GetDockActive();
}
void GUIManager::SetDockActive()
{
ImGui::SetDockActive();
}
bool GUIManager::BeginFCurve(int id, const Vec2& size, float current, const Vec2& scale, float min_value, float max_value)
{
return ImGui::BeginFCurve(id, ImVec2(size.X, size.Y), current, ImVec2(scale.X, scale.Y), min_value, max_value);
}
void GUIManager::EndFCurve()
{
ImGui::EndFCurve();
}
bool GUIManager::FCurve(
int fcurve_id,
float* keys, float* values,
float* leftHandleKeys, float* leftHandleValues,
float* rightHandleKeys, float* rightHandleValues,
int* interporations,
FCurveEdgeType startEdge,
FCurveEdgeType endEdge,
uint8_t* kv_selected,
int count,
float defaultValue,
bool isLocked,
bool canControl,
uint32_t col,
bool selected,
float v_min,
float v_max,
int* newCount,
bool* newSelected,
float* movedX,
float* movedY,
int* changedType)
{
return ImGui::FCurve(
fcurve_id,
keys,
values,
leftHandleKeys,
leftHandleValues,
rightHandleKeys,
rightHandleValues,
(ImGui::ImFCurveInterporationType*)interporations,
(ImGui::ImFCurveEdgeType)startEdge,
(ImGui::ImFCurveEdgeType)endEdge,
(bool*)kv_selected,
count,
defaultValue,
isLocked,
canControl,
col,
selected,
v_min,
v_max,
newCount,
newSelected,
movedX,
movedY,
changedType);
}
bool GUIManager::BeginDragDropSource()
{
return ImGui::BeginDragDropSource();
}
bool GUIManager::SetDragDropPayload(const char* type, uint8_t* data, int size)
{
return ImGui::SetDragDropPayload(type, data, size);
}
void GUIManager::EndDragDropSource()
{
ImGui::EndDragDropSource();
}
bool GUIManager::BeginDragDropTarget()
{
return ImGui::BeginDragDropTarget();
}
bool GUIManager::AcceptDragDropPayload(const char* type, uint8_t* data_output, int data_output_size, int* size)
{
auto pyload = ImGui::AcceptDragDropPayload(type);
if (pyload == nullptr)
{
*size = 0;
return false;
}
auto max_size = std::min(data_output_size, pyload->DataSize);
memcpy(data_output, pyload->Data, max_size);
*size = max_size;
return true;
}
void GUIManager::EndDragDropTarget()
{
ImGui::EndDragDropTarget();
}
DialogSelection GUIManager::show(const char16_t* message, const char16_t* title, DialogStyle style, DialogButtons buttons)
{
return (DialogSelection)boxer::show(
utf8str<256>(message),
utf8str<256>(title),
(boxer::Style)style,
(boxer::Buttons)buttons);
}
bool GUIManager::IsMacOSX()
{
#if __APPLE__
return true;
#else
return false;
#endif
}
void GUIManager::SetIniFilename(const char16_t* filename)
{
static std::string filename_ = utf8str<256>(filename);
ImGui::GetIO().IniFilename = filename_.c_str();
}
int GUIManager::GetLanguage()
{
return (int32_t)GetEfkLanguage();
}
}
Fixed for mac
#define NOMINMAX
#ifdef _WIN32
#define GLEW_STATIC 1
#include <GL/glew.h>
#endif
#include "../EffekseerTool/EffekseerTool.Renderer.h"
#include "efk.GUIManager.h"
#include "Platform/efk.Language.h"
#include "efk.JapaneseFont.h"
#include "../3rdParty/imgui_addon/fcurve/fcurve.h"
#include "../3rdParty/Boxer/boxer.h"
#include "../dll.h"
namespace ImGui
{
static ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs)
{
return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y);
}
static ImVec2 operator * (const ImVec2& lhs, const float& rhs)
{
return ImVec2(lhs.x * rhs, lhs.y * rhs);
}
bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, bool* v, ImTextureID user_texture, const char* label, const char* label_end)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0;
const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f);
if (!label_end)
label_end = FindRenderedTextEnd(label);
const ImVec2 label_size = CalcTextSize(label, label_end, false);
// We vertically grow up to current line height up the typical widget height.
const float text_base_offset_y = ImMax(padding.y, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it
const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y * 2), label_size.y + padding.y * 2);
const float icon_size = frame_height;
ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height));
if (display_frame)
{
// Framed header expand a little outside the default padding
frame_bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1;
frame_bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1;
}
const float text_offset_x = (g.FontSize + icon_size + (display_frame ? padding.x * 3 : padding.x * 2)); // Collapser arrow width + Spacing
const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x * 2 : 0.0f); // Include collapser
ItemSize(ImVec2(text_width + icon_size, frame_height), text_base_offset_y);
// For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
// (Ideally we'd want to add a flag for the user to specify if we want the hit test to be done up to the right side of the content or not)
const ImRect interact_bb = display_frame ? frame_bb : ImRect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + text_width + style.ItemSpacing.x * 2, frame_bb.Max.y);
bool is_open = TreeNodeBehaviorIsOpen(id, flags);
// Store a flag for the current depth to tell if we will allow closing this node when navigating one of its child.
// For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop().
// This is currently only support 32 level deep and we are fine with (1 << Depth) overflowing into a zero.
if (is_open && !g.NavIdIsAlive && (flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
window->DC.TreeDepthMayJumpToParentOnPop |= (1 << window->DC.TreeDepth);
bool item_add = ItemAdd(interact_bb, id);
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDisplayRect;
window->DC.LastItemDisplayRect = frame_bb;
if (!item_add)
{
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushRawID(id);
return is_open;
}
// Flags that affects opening behavior:
// - 0(default) ..................... single-click anywhere to open
// - OpenOnDoubleClick .............. double-click anywhere to open
// - OpenOnArrow .................... single-click on arrow to open
// - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open
ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowItemOverlap) ? ImGuiButtonFlags_AllowItemOverlap : 0);
if (!(flags & ImGuiTreeNodeFlags_Leaf))
button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0);
bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);
if (!(flags & ImGuiTreeNodeFlags_Leaf))
{
bool toggled = false;
if (pressed)
{
toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) || (g.NavActivateId == id);
if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y)) && (!g.NavDisableMouseHover);
if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
toggled |= g.IO.MouseDoubleClicked[0];
if (g.DragDropActive && is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again.
toggled = false;
}
if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Left && is_open)
{
toggled = true;
NavMoveRequestCancel();
}
if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?
{
toggled = true;
NavMoveRequestCancel();
}
if (toggled)
{
is_open = !is_open;
window->DC.StateStorage->SetInt(id, is_open);
}
}
if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)
SetItemAllowOverlap();
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
const ImVec2 text_pos = frame_bb.Min + ImVec2(text_offset_x, text_base_offset_y);
if (display_frame)
{
// Framed type
RenderFrame(frame_bb.Min, frame_bb.Max, col, true, style.FrameRounding);
RenderNavHighlight(frame_bb, id, ImGuiNavHighlightFlags_TypeThin);
RenderArrow(frame_bb.Min + ImVec2(padding.x, text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f);
window->DrawList->AddImage(user_texture,
frame_bb.Min + ImVec2(padding.x + g.FontSize, text_base_offset_y),
frame_bb.Min + ImVec2(padding.x + g.FontSize, text_base_offset_y) + ImVec2(icon_size,icon_size), ImVec2(0, 0), ImVec2(1, 1));
if (g.LogEnabled)
{
// NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here.
const char log_prefix[] = "\n##";
const char log_suffix[] = "##";
//LogRenderedText(&text_pos, log_prefix, log_prefix + 3);
RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
//LogRenderedText(&text_pos, log_suffix + 1, log_suffix + 3);
}
else
{
RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
}
}
else
{
// Unframed typed for tree nodes
if (hovered || (flags & ImGuiTreeNodeFlags_Selected))
{
RenderFrame(frame_bb.Min, frame_bb.Max, col, false);
RenderNavHighlight(frame_bb, id, ImGuiNavHighlightFlags_TypeThin);
}
if (flags & ImGuiTreeNodeFlags_Bullet)
RenderBullet(frame_bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y));
else if (!(flags & ImGuiTreeNodeFlags_Leaf))
RenderArrow(frame_bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f);
//if (g.LogEnabled)
// LogRenderedText(&text_pos, ">");
window->DrawList->AddImage(user_texture,
frame_bb.Min + ImVec2(padding.x + g.FontSize, text_base_offset_y),
frame_bb.Min + ImVec2(padding.x + g.FontSize, text_base_offset_y) + ImVec2(icon_size, icon_size), ImVec2(0, 0), ImVec2(1, 1));
RenderText(text_pos, label, label_end, false);
}
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushRawID(id);
return is_open;
}
bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags, bool* v, ImTextureID user_texture)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
return TreeNodeBehavior(window->GetID(label), flags, v, user_texture, label, NULL);
}
bool ImageButton_(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
// Default to using texture ID as ID. User can still push string/integer prefixes.
// We could hash the size/uv to create a unique ID but that would prevent the user from animating UV.
PushID((void *)user_texture_id);
const ImGuiID id = window->GetID("#image");
PopID();
const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding * 2);
const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size);
ItemSize(bb);
if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_PressedOnClick);
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding));
if (bg_col.w > 0.0f)
window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col));
window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col));
return pressed;
}
}
namespace efk
{
template <size_t size_>
struct utf8str {
enum {size = size_};
char data[size];
utf8str(const char16_t* u16str) {
Effekseer::ConvertUtf16ToUtf8((int8_t*)data, size, (const int16_t*)u16str);
}
operator const char*() const {
return data;
}
};
// http://hasenpfote36.blogspot.jp/2016/09/stdcodecvt.html
static constexpr std::codecvt_mode mode = std::codecvt_mode::little_endian;
static std::string utf16_to_utf8(const std::u16string& s)
{
#if defined(_MSC_VER)
std::wstring_convert<std::codecvt_utf8_utf16<std::uint16_t, 0x10ffff, mode>, std::uint16_t> conv;
auto p = reinterpret_cast<const std::uint16_t*>(s.c_str());
return conv.to_bytes(p, p + s.length());
#else
std::wstring_convert<std::codecvt_utf8_utf16<char16_t, 0x10ffff, mode>, char16_t> conv;
return conv.to_bytes(s);
#endif
}
static std::u16string utf8_to_utf16(const std::string& s)
{
#if defined(_MSC_VER)
std::wstring_convert<std::codecvt_utf8_utf16<std::uint16_t, 0x10ffff, mode>, std::uint16_t> conv;
auto p = reinterpret_cast<const std::uint16_t*>(s.c_str());
return std::u16string((const char16_t*)conv.from_bytes(s).c_str());
#else
std::wstring_convert<std::codecvt_utf8_utf16<char16_t, 0x10ffff, mode>, char16_t> conv;
return conv.from_bytes(s);
#endif
}
static ImTextureID ToImTextureID(ImageResource* image)
{
if (image != nullptr)
{
Effekseer::TextureData* texture = image->GetTextureData();
if (texture != nullptr)
{
if (texture->UserPtr != nullptr)
{
return (ImTextureID)texture->UserPtr;
}
else
{
return (ImTextureID)texture->UserID;
}
}
}
return nullptr;
}
bool DragFloatN(const char* label, float* v, int components, float v_speed, float* v_min, float* v_max,
const char* display_format1,
const char* display_format2,
const char* display_format3,
float power)
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
ImGui::BeginGroup();
ImGui::PushID(label);
ImGui::PushMultiItemsWidths(components);
const char* display_formats[] = {
display_format1,
display_format2,
display_format3
};
for (int i = 0; i < components; i++)
{
ImGui::PushID(i);
value_changed |= ImGui::DragFloat("##v", &v[i], v_speed, v_min[i], v_max[i], display_formats[i], power);
ImGui::SameLine(0, g.Style.ItemInnerSpacing.x);
ImGui::PopID();
ImGui::PopItemWidth();
}
ImGui::PopID();
ImGui::TextUnformatted(label, ImGui::FindRenderedTextEnd(label));
ImGui::EndGroup();
return value_changed;
}
bool DragIntN(const char* label, int* v, int components, int v_speed, int* v_min, int* v_max,
const char* display_format1,
const char* display_format2,
const char* display_format3)
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
ImGui::BeginGroup();
ImGui::PushID(label);
ImGui::PushMultiItemsWidths(components);
const char* display_formats[] = {
display_format1,
display_format2,
display_format3
};
for (int i = 0; i < components; i++)
{
ImGui::PushID(i);
value_changed |= ImGui::DragInt("##v", &v[i], v_speed, v_min[i], v_max[i], display_formats[i]);
ImGui::SameLine(0, g.Style.ItemInnerSpacing.x);
ImGui::PopID();
ImGui::PopItemWidth();
}
ImGui::PopID();
ImGui::TextUnformatted(label, ImGui::FindRenderedTextEnd(label));
ImGui::EndGroup();
return value_changed;
}
GUIManager::GUIManager()
{}
GUIManager::~GUIManager()
{}
bool GUIManager::Initialize(const char16_t* title, int32_t width, int32_t height, efk::DeviceType deviceType, bool isSRGBMode)
{
window = new efk::Window();
this->deviceType = deviceType;
if (!window->Initialize(title, width, height, isSRGBMode, deviceType))
{
ES_SAFE_DELETE(window);
return false;
}
window->Resized = [this](int x, int y) -> void
{
if (this->callback != nullptr)
{
this->callback->Resized(x, y);
}
};
window->Focused = [this]() -> void
{
if (this->callback != nullptr)
{
this->callback->Focused();
}
};
window->Droped = [this](const char* path) -> void
{
if (this->callback != nullptr)
{
this->callback->SetPath(utf8_to_utf16(path).c_str());
this->callback->Droped();
}
};
window->Closing = [this]() -> bool
{
if (this->callback != nullptr)
{
return this->callback->Closing();
}
return true;
};
window->Iconify = [this](float f) -> void
{
if (this->callback != nullptr)
{
this->callback->Iconify(f);
}
};
if (deviceType == DeviceType::OpenGL)
{
window->MakeCurrent();
#ifdef _WIN32
glewInit();
#endif
}
#ifdef _WIN32
// Calculate font scale from DPI
HDC screen = GetDC(0);
int dpiX = GetDeviceCaps(screen, LOGPIXELSX);
fontScale = (float)dpiX / 96.0f;
#endif
return true;
}
void GUIManager::InitializeGUI(Native* native)
{
ImGui::CreateContext();
if (deviceType == DeviceType::OpenGL)
{
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
#if __APPLE__
// GL 3.2 + GLSL 150
const char* glsl_version = "#version 150";
#else
// GL 3.0 + GLSL 130
const char* glsl_version = "#version 130";
#endif
ImGui_ImplGlfw_InitForOpenGL(window->GetGLFWWindows(), true);
ImGui_ImplOpenGL3_Init(glsl_version);
}
#ifdef _WIN32
else if (deviceType == DeviceType::DirectX11)
{
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
ImGui_ImplGlfw_InitForVulkan(window->GetGLFWWindows(), true);
auto r = (EffekseerRendererDX11::Renderer*)native->GetRenderer();
ImGui_ImplDX11_Init(r->GetDevice(), r->GetContext());
}
else
{
ImGui_ImplGlfw_InitForOpenGL(window->GetGLFWWindows(), true);
auto r = (EffekseerRendererDX9::Renderer*)native->GetRenderer();
ImGui_ImplDX9_Init(r->GetDevice());
}
#endif
ImGui::StyleColorsDark();
ImGuiStyle& style = ImGui::GetStyle();
style.ChildRounding = 3.f;
style.GrabRounding = 3.f;
style.WindowRounding = 3.f;
style.ScrollbarRounding = 3.f;
style.FrameRounding = 3.f;
style.WindowTitleAlign = ImVec2(0.5f, 0.5f);
// mono tone
for (int32_t i = 0; i < ImGuiCol_COUNT; i++)
{
auto v = (style.Colors[i].x + style.Colors[i].y + style.Colors[i].z) / 3.0f;
style.Colors[i].x = v;
style.Colors[i].y = v;
style.Colors[i].z = v;
}
style.Colors[ImGuiCol_Text] = ImVec4(0.80f, 0.80f, 0.80f, 1.00f);
style.Colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
style.Colors[ImGuiCol_WindowBg] = ImVec4(0.1f, 0.1f, 0.1f, 0.9f);
}
void GUIManager::SetTitle(const char16_t* title)
{
window->SetTitle(title);
}
void GUIManager::SetWindowIcon(const char16_t * iconPath)
{
window->SetWindowIcon(iconPath);
}
Vec2 GUIManager::GetSize() const
{
return window->GetSize();
}
void GUIManager::SetSize(int32_t width, int32_t height)
{
window->SetSize(width, height);
}
void GUIManager::Terminate()
{
if (deviceType == DeviceType::OpenGL)
{
ImGui_ImplOpenGL3_Shutdown();
}
#ifdef _WIN32
else if (deviceType == DeviceType::DirectX11)
{
ImGui_ImplDX11_Shutdown();
}
else
{
ImGui_ImplDX9_Shutdown();
}
#endif
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
window->MakeNone();
window->Terminate();
ES_SAFE_DELETE(window);
}
bool GUIManager::DoEvents()
{
return window->DoEvents();
}
void GUIManager::Present()
{
window->Present();
}
void GUIManager::Close()
{
window->Close();
}
Vec2 GUIManager::GetMousePosition()
{
return window->GetMousePosition();
}
int GUIManager::GetMouseButton(int32_t mouseButton)
{
return window->GetMouseButton(mouseButton);
}
int GUIManager::GetMouseWheel()
{
return ImGui::GetIO().MouseWheel;
}
void GUIManager::SetCallback(GUIManagerCallback* callback)
{
this->callback = callback;
}
void GUIManager::ResetGUI()
{
if (deviceType == DeviceType::OpenGL)
{
ImGui_ImplOpenGL3_NewFrame();
}
#if _WIN32
else if (deviceType == DeviceType::DirectX11)
{
ImGui_ImplDX11_NewFrame();
}
else
{
ImGui_ImplDX9_NewFrame();
}
#endif
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
}
void GUIManager::RenderGUI(bool isValid)
{
ImGui::EndFrame();
ImGui::Render();
if (isValid)
{
if (deviceType == DeviceType::OpenGL)
{
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
#if _WIN32
else if (deviceType == DeviceType::DirectX11)
{
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
}
else
{
ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData());
}
#endif
}
else
{
if (ImGui::GetDrawData() != nullptr)
{
ImGui::GetDrawData()->Clear();
}
}
{
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
}
if (deviceType == DeviceType::OpenGL)
{
glfwMakeContextCurrent(window->GetGLFWWindows());
}
}
}
void* GUIManager::GetNativeHandle()
{
return window->GetNativeHandle();
}
const char16_t* GUIManager::GetClipboardText()
{
auto ret = glfwGetClipboardString(window->GetGLFWWindows());
clipboard = utf8_to_utf16(ret);
return clipboard.c_str();
}
void GUIManager::SetClipboardText(const char16_t* text)
{
glfwSetClipboardString(window->GetGLFWWindows(), utf16_to_utf8(text).c_str());
}
bool GUIManager::Begin(const char16_t* name, bool* p_open)
{
return ImGui::Begin(utf8str<256>(name), p_open);
}
void GUIManager::End()
{
ImGui::End();
}
bool GUIManager::BeginChild(const char* str_id, const Vec2& size_arg, bool border, WindowFlags extra_flags)
{
return ImGui::BeginChild(str_id, ImVec2(size_arg.X, size_arg.Y), border, (ImGuiWindowFlags)extra_flags);
}
void GUIManager::EndChild()
{
ImGui::EndChild();
}
Vec2 GUIManager::GetWindowSize()
{
auto v = ImGui::GetWindowSize();
return Vec2(v.x, v.y);
}
Vec2 GUIManager::GetContentRegionAvail()
{
auto v = ImGui::GetContentRegionAvail();
return Vec2(v.x, v.y);
}
void GUIManager::SetNextWindowSize(float size_x, float size_y, Cond cond)
{
ImVec2 size;
size.x = size_x;
size.y = size_y;
ImGui::SetNextWindowSize(size, (int)cond);
}
void GUIManager::PushItemWidth(float item_width)
{
ImGui::PushItemWidth(item_width);
}
void GUIManager::PopItemWidth()
{
ImGui::PopItemWidth();
}
void GUIManager::Separator()
{
ImGui::Separator();
}
void GUIManager::HiddenSeparator()
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
ImGuiSeparatorFlags flags = 0;
if ((flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)) == 0)
flags |= (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal;
IM_ASSERT(ImIsPowerOfTwo((int)(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)))); // Check that only 1 option is selected
if (flags & ImGuiSeparatorFlags_Vertical)
{
ImGui::VerticalSeparator();
return;
}
// Horizontal Separator
if (window->DC.ColumnsSet)
ImGui::PopClipRect();
float x1 = window->Pos.x;
float x2 = window->Pos.x + window->Size.x;
if (!window->DC.GroupStack.empty())
x1 += window->DC.IndentX;
const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y + 4.0f));
ImGui::ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit, we don't provide height to not alter layout.
if (!ImGui::ItemAdd(bb, 0))
{
if (window->DC.ColumnsSet)
ImGui::PushColumnClipRect();
return;
}
window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x, bb.Min.y), 0);
if (window->DC.ColumnsSet)
{
ImGui::PushColumnClipRect();
window->DC.ColumnsSet->LineMinY = window->DC.CursorPos.y;
}
}
void GUIManager::SameLine()
{
ImGui::SameLine();
}
void GUIManager::BeginGroup()
{
ImGui::BeginGroup();
}
void GUIManager::EndGroup()
{
ImGui::EndGroup();
}
void GUIManager::SetCursorPosX(float x)
{
ImGui::SetCursorPosX(x);
}
void GUIManager::SetCursorPosY(float y)
{
ImGui::SetCursorPosY(y);
}
float GUIManager::GetCursorPosX()
{
return ImGui::GetCursorPosX();
}
float GUIManager::GetCursorPosY()
{
return ImGui::GetCursorPosY();
}
float GUIManager::GetTextLineHeight()
{
return ImGui::GetTextLineHeight();
}
float GUIManager::GetTextLineHeightWithSpacing()
{
return ImGui::GetTextLineHeightWithSpacing();
}
float GUIManager::GetFrameHeight()
{
return ImGui::GetFrameHeight();
}
float GUIManager::GetFrameHeightWithSpacing()
{
return ImGui::GetFrameHeightWithSpacing();
}
void GUIManager::Columns(int count, const char* id, bool border)
{
ImGui::Columns(count, id, border);
}
void GUIManager::NextColumn()
{
ImGui::NextColumn();
}
float GUIManager::GetColumnWidth(int column_index)
{
return ImGui::GetColumnWidth(column_index);
}
void GUIManager::SetColumnWidth(int column_index, float width)
{
ImGui::SetColumnWidth(column_index, width);
}
float GUIManager::GetColumnOffset(int column_index)
{
return ImGui::GetColumnOffset(column_index);
}
void GUIManager::SetColumnOffset(int column_index, float offset_x)
{
ImGui::SetColumnOffset(column_index, offset_x);
}
void GUIManager::Text(const char16_t* text)
{
if (std::char_traits<char16_t>::length(text) < 1024)
{
ImGui::Text(utf8str<1024>(text));
}
else
{
ImGui::Text(utf16_to_utf8(text).c_str());
}
}
void GUIManager::TextWrapped(const char16_t* text)
{
if (std::char_traits<char16_t>::length(text) < 1024)
{
ImGui::TextWrapped(utf8str<1024>(text));
}
else
{
ImGui::TextWrapped(utf16_to_utf8(text).c_str());
}
}
bool GUIManager::Button(const char16_t* label, float size_x, float size_y)
{
return ImGui::Button(utf8str<256>(label), ImVec2(size_x, size_y));
}
void GUIManager::Image(ImageResource* user_texture_id, float x, float y)
{
ImGui::Image(ToImTextureID(user_texture_id), ImVec2(x, y));
}
void GUIManager::Image(void* user_texture_id, float x, float y)
{
if (deviceType != DeviceType::OpenGL)
{
ImGui::Image((ImTextureID)user_texture_id, ImVec2(x, y), ImVec2(0, 0), ImVec2(1, 1));
}
else
{
ImGui::Image((ImTextureID)user_texture_id, ImVec2(x, y), ImVec2(0, 1), ImVec2(1, 0));
}
}
bool GUIManager::ImageButton(ImageResource* user_texture_id, float x, float y)
{
return ImGui::ImageButton_(ToImTextureID(user_texture_id), ImVec2(x, y), ImVec2(0, 0), ImVec2(1, 1), 0, ImVec4(0, 0, 0, 0), ImVec4(1, 1, 1, 1));
}
bool GUIManager::Checkbox(const char16_t* label, bool* v)
{
return ImGui::Checkbox(utf8str<256>(label), v);
}
bool GUIManager::RadioButton(const char16_t* label, bool active)
{
return ImGui::RadioButton(utf8str<256>(label), active);
}
bool GUIManager::InputInt(const char16_t* label, int* v, int step, int step_fast)
{
return ImGui::InputInt(utf8str<256>(label), v, step, step_fast);
}
bool GUIManager::SliderInt(const char16_t* label, int* v, int v_min, int v_max)
{
return ImGui::SliderInt(utf8str<256>(label), v, v_min, v_max);
}
bool GUIManager::BeginCombo(const char16_t* label, const char16_t* preview_value, ComboFlags flags, ImageResource* user_texture_id)
{
return ImGui::BeginCombo(
utf8str<256>(label),
utf8str<256>(preview_value),
(int)flags, ToImTextureID(user_texture_id));
}
void GUIManager::EndCombo()
{
ImGui::EndCombo();
}
bool GUIManager::DragFloat(const char16_t* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power)
{
return ImGui::DragFloat(utf8str<256>(label), v, v_speed, v_min, v_max, display_format);
}
bool GUIManager::DragFloat2(const char16_t* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power)
{
return ImGui::DragFloat2(utf8str<256>(label), v, v_speed, v_min, v_max, display_format);
}
bool GUIManager::DragFloat3(const char16_t* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power)
{
return ImGui::DragFloat3(utf8str<256>(label), v, v_speed, v_min, v_max, display_format);
}
bool GUIManager::DragFloat4(const char16_t* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power)
{
return ImGui::DragFloat4(utf8str<256>(label), v, v_speed, v_min, v_max, display_format);
}
bool GUIManager::DragFloatRange2(const char16_t* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* display_format, const char* display_format_max, float power)
{
return ImGui::DragFloatRange2(utf8str<256>(label), v_current_min, v_current_max, v_speed, v_min, v_max, display_format, display_format_max);
}
bool GUIManager::DragInt(const char16_t* label, int* v, float v_speed, int v_min, int v_max, const char* display_format)
{
return ImGui::DragInt(utf8str<256>(label), v, v_speed, v_min, v_max, display_format);
}
bool GUIManager::DragInt2(const char16_t* label, int* v, float v_speed, int v_min, int v_max, const char* display_format)
{
return ImGui::DragInt2(utf8str<256>(label), v, v_speed, v_min, v_max, display_format);
}
bool GUIManager::DragInt3(const char16_t* label, int* v, float v_speed, int v_min, int v_max, const char* display_format)
{
return ImGui::DragInt3(utf8str<256>(label), v, v_speed, v_min, v_max, display_format);
}
bool GUIManager::DragInt4(const char16_t* label, int* v, float v_speed, int v_min, int v_max, const char* display_format)
{
return ImGui::DragInt4(utf8str<256>(label), v, v_speed, v_min, v_max, display_format);
}
bool GUIManager::DragIntRange2(const char16_t* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* display_format, const char* display_format_max)
{
return ImGui::DragIntRange2(utf8str<256>(label), v_current_min, v_current_max, v_speed, v_min, v_max, display_format, display_format_max);
}
bool GUIManager::DragFloat1EfkEx(const char16_t* label, float* v, float v_speed, float v_min, float v_max, const char16_t* display_format1, float power)
{
float v_min_[3];
float v_max_[3];
v_min_[0] = v_min;
v_max_[0] = v_max;
return DragFloatN(
utf8str<256>(label), v, 1, v_speed, v_min_, v_max_,
utf8str<256>(display_format1),
nullptr,
nullptr,
power);
}
bool GUIManager::DragFloat2EfkEx(const char16_t* label, float* v, float v_speed, float v_min1, float v_max1, float v_min2, float v_max2, const char16_t* display_format1, const char16_t* display_format2, float power)
{
float v_min_[3];
float v_max_[3];
v_min_[0] = v_min1;
v_max_[0] = v_max1;
v_min_[1] = v_min2;
v_max_[1] = v_max2;
return DragFloatN(
utf8str<256>(label), v, 2, v_speed, v_min_, v_max_,
utf8str<256>(display_format1),
utf8str<256>(display_format2),
nullptr,
power);
}
bool GUIManager::DragFloat3EfkEx(const char16_t* label, float* v, float v_speed, float v_min1, float v_max1, float v_min2, float v_max2, float v_min3, float v_max3, const char16_t* display_format1, const char16_t* display_format2, const char16_t* display_format3, float power)
{
float v_min_[3];
float v_max_[3];
v_min_[0] = v_min1;
v_max_[0] = v_max1;
v_min_[1] = v_min2;
v_max_[1] = v_max2;
v_min_[2] = v_min3;
v_max_[2] = v_max3;
return DragFloatN(
utf8str<256>(label), v, 3, v_speed, v_min_, v_max_,
utf8str<256>(display_format1),
utf8str<256>(display_format2),
utf8str<256>(display_format3),
power);
}
bool GUIManager::DragInt2EfkEx(const char16_t* label, int* v, int v_speed, int v_min1, int v_max1, int v_min2, int v_max2, const char16_t* display_format1, const char16_t* display_format2)
{
int v_min_[3];
int v_max_[3];
v_min_[0] = v_min1;
v_max_[0] = v_max1;
v_min_[1] = v_min2;
v_max_[1] = v_max2;
return DragIntN(
utf8str<256>(label), v, 2, v_speed, v_min_, v_max_,
utf8str<256>(display_format1),
utf8str<256>(display_format2),
nullptr);
}
static std::u16string inputTextResult;
bool GUIManager::InputText(const char16_t* label, const char16_t* text, InputTextFlags flags)
{
auto text_ = utf8str<1024>(text);
char buf[260];
memcpy(buf, text_.data, std::min((int32_t)text_.size, 250));
buf[std::min((int32_t)text_.size, 250)] = 0;
auto ret = ImGui::InputText(utf8str<256>(label), buf, 260, (ImGuiWindowFlags)flags);
inputTextResult = utf8_to_utf16(buf);
return ret;
}
const char16_t* GUIManager::GetInputTextResult()
{
return inputTextResult.c_str();
}
bool GUIManager::ColorEdit4(const char16_t* label, float* col, ColorEditFlags flags)
{
return ImGui::ColorEdit4(utf8str<256>(label), col, (int)flags);
}
bool GUIManager::TreeNode(const char16_t* label)
{
return ImGui::TreeNode(utf8str<256>(label));
}
bool GUIManager::TreeNodeEx(const char16_t* label, TreeNodeFlags flags)
{
return ImGui::TreeNodeEx(utf8str<256>(label), (int)flags);
}
void GUIManager::TreePop()
{
ImGui::TreePop();
}
void GUIManager::SetNextTreeNodeOpen(bool is_open, Cond cond)
{
ImGui::SetNextTreeNodeOpen(is_open, (ImGuiCond)cond);
}
bool GUIManager::TreeNodeEx(const char16_t* label, bool* v, ImageResource* user_texture_id, TreeNodeFlags flags)
{
return ImGui::TreeNodeEx(utf8str<256>(label), (ImGuiTreeNodeFlags)flags, v, ToImTextureID(user_texture_id));
}
bool GUIManager::Selectable(const char16_t* label, bool selected, SelectableFlags flags, ImageResource* user_texture_id)
{
return ImGui::Selectable(utf8str<256>(label), selected, (int)flags, ImVec2(0, 0), ToImTextureID(user_texture_id));
}
void GUIManager::SetTooltip(const char16_t* text)
{
ImGui::SetTooltip(utf8str<256>(text));
}
void GUIManager::BeginTooltip()
{
ImGui::BeginTooltip();
}
void GUIManager::EndTooltip()
{
ImGui::EndTooltip();
}
bool GUIManager::BeginMainMenuBar()
{
return ImGui::BeginMainMenuBar();
}
void GUIManager::EndMainMenuBar()
{
ImGui::EndMainMenuBar();
}
bool GUIManager::BeginMenuBar()
{
return ImGui::BeginMenuBar();
}
void GUIManager::EndMenuBar()
{
return ImGui::EndMenuBar();
}
bool GUIManager::BeginMenu(const char16_t* label, bool enabled)
{
return ImGui::BeginMenu(utf8str<256>(label), enabled);
}
void GUIManager::EndMenu()
{
ImGui::EndMenu();
}
bool GUIManager::MenuItem(const char16_t* label, const char* shortcut, bool selected, bool enabled, ImageResource* icon)
{
return ImGui::MenuItem(utf8str<256>(label), shortcut, selected, enabled, ToImTextureID(icon));
}
bool GUIManager::MenuItem(const char16_t* label, const char* shortcut, bool* p_selected, bool enabled, ImageResource* icon)
{
return ImGui::MenuItem(utf8str<256>(label), shortcut, p_selected, enabled, ToImTextureID(icon));
}
void GUIManager::OpenPopup(const char* str_id)
{
ImGui::OpenPopup(str_id);
}
bool GUIManager::BeginPopup(const char* str_id, WindowFlags extra_flags)
{
return ImGui::BeginPopup(str_id, (int)extra_flags);
}
bool GUIManager::BeginPopupModal(const char16_t* name, bool* p_open, WindowFlags extra_flags)
{
return ImGui::BeginPopupModal(utf8str<256>(name), p_open, (int)extra_flags);
}
bool GUIManager::BeginPopupContextItem(const char* str_id, int mouse_button)
{
return ImGui::BeginPopupContextItem(str_id, mouse_button);
}
void GUIManager::EndPopup()
{
ImGui::EndPopup();
}
bool GUIManager::IsPopupOpen(const char* str_id)
{
return ImGui::IsPopupOpen(str_id);
}
void GUIManager::CloseCurrentPopup()
{
ImGui::CloseCurrentPopup();
}
void GUIManager::SetItemDefaultFocus()
{
ImGui::SetItemDefaultFocus();
}
void GUIManager::AddFontFromFileTTF(const char* filename, float size_pixels)
{
ImGuiIO& io = ImGui::GetIO();
size_pixels = roundf(size_pixels * fontScale);
io.Fonts->AddFontFromFileTTF(filename, size_pixels, nullptr, glyphRangesJapanese);
}
bool GUIManager::BeginChildFrame(uint32_t id, const Vec2& size, WindowFlags flags)
{
return ImGui::BeginChildFrame(id, ImVec2(size.X, size.Y), (int32_t)flags);
}
void GUIManager::EndChildFrame()
{
ImGui::EndChildFrame();
}
bool GUIManager::IsKeyDown(int user_key_index)
{
return ImGui::IsKeyDown(user_key_index);
}
bool GUIManager::IsMouseDown(int button)
{
return ImGui::IsMouseDown(button);
}
bool GUIManager::IsMouseDoubleClicked(int button)
{
return ImGui::IsMouseDoubleClicked(button);
}
bool GUIManager::IsItemHovered()
{
return ImGui::IsItemHovered();
}
bool GUIManager::IsItemActive()
{
return ImGui::IsItemActive();
}
bool GUIManager::IsItemFocused()
{
return ImGui::IsItemFocused();
}
bool GUIManager::IsItemClicked(int mouse_button)
{
return ImGui::IsItemClicked(mouse_button);
}
bool GUIManager::IsWindowHovered()
{
return ImGui::IsWindowHovered();
}
bool GUIManager::IsAnyWindowHovered()
{
return ImGui::IsAnyWindowHovered();
}
MouseCursor GUIManager::GetMouseCursor()
{
return (MouseCursor)ImGui::GetMouseCursor();
}
void GUIManager::DrawLineBackground(float height, uint32_t col)
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
auto cursorPos = ImGui::GetCursorPos();
cursorPos.x = window->Pos.x;
cursorPos.y = window->DC.CursorPos.y;
ImVec2 size;
size.x = window->Size.x;
size.y = height;
window->DrawList->AddRectFilled(cursorPos, ImVec2(cursorPos.x + size.x, cursorPos.y + size.y), col);
}
bool GUIManager::BeginFullscreen(const char16_t* label)
{
ImVec2 windowSize;
windowSize.x = ImGui::GetIO().DisplaySize.x;
windowSize.y = ImGui::GetIO().DisplaySize.y - 25;
ImGui::SetNextWindowSize(windowSize);
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
auto pos = ImGui::GetMainViewport()->Pos;
pos.y += 25;
ImGui::SetNextWindowPos(pos);
}
else
{
ImGui::SetNextWindowPos(ImVec2(0, 25));
}
const ImGuiWindowFlags flags = (ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoTitleBar);
const float oldWindowRounding = ImGui::GetStyle().WindowRounding; ImGui::GetStyle().WindowRounding = 0;
const bool visible = ImGui::Begin(utf8str<256>(label), NULL, ImVec2(0, 0), 1.0f, flags);
ImGui::GetStyle().WindowRounding = oldWindowRounding;
return visible;
}
void GUIManager::SetNextDock(DockSlot slot)
{
ImGui::SetNextDock((ImGuiDockSlot)slot);
}
void GUIManager::BeginDockspace()
{
ImGui::BeginDockspace();
}
void GUIManager::EndDockspace()
{
ImGui::EndDockspace();
}
bool GUIManager::BeginDock(const char16_t* label, bool* p_open, WindowFlags extra_flags, Vec2 default_size)
{
return ImGui::BeginDock(utf8str<256>(label), p_open, (int32_t)extra_flags, ImVec2(default_size.X, default_size.Y));
}
void GUIManager::EndDock()
{
ImGui::EndDock();
}
void GUIManager::SetNextDockRate(float rate)
{
ImGui::SetNextDockRate(rate);
}
void GUIManager::ResetNextParentDock()
{
ImGui::ResetNextParentDock();
}
void GUIManager::SaveDock(const char* path)
{
ImGui::SaveDock(path);
}
void GUIManager::LoadDock(const char* path)
{
ImGui::LoadDock(path);
}
void GUIManager::ShutdownDock()
{
ImGui::ShutdownDock();
}
void GUIManager::SetNextDockIcon(ImageResource* icon, Vec2 iconSize)
{
ImGui::SetNextDockIcon(ToImTextureID(icon), ImVec2(iconSize.X, iconSize.Y));
}
void GUIManager::SetNextDockTabToolTip(const char16_t* popup)
{
ImGui::SetNextDockTabToolTip(utf8str<256>(popup));
}
bool GUIManager::GetDockActive()
{
return ImGui::GetDockActive();
}
void GUIManager::SetDockActive()
{
ImGui::SetDockActive();
}
bool GUIManager::BeginFCurve(int id, const Vec2& size, float current, const Vec2& scale, float min_value, float max_value)
{
return ImGui::BeginFCurve(id, ImVec2(size.X, size.Y), current, ImVec2(scale.X, scale.Y), min_value, max_value);
}
void GUIManager::EndFCurve()
{
ImGui::EndFCurve();
}
bool GUIManager::FCurve(
int fcurve_id,
float* keys, float* values,
float* leftHandleKeys, float* leftHandleValues,
float* rightHandleKeys, float* rightHandleValues,
int* interporations,
FCurveEdgeType startEdge,
FCurveEdgeType endEdge,
uint8_t* kv_selected,
int count,
float defaultValue,
bool isLocked,
bool canControl,
uint32_t col,
bool selected,
float v_min,
float v_max,
int* newCount,
bool* newSelected,
float* movedX,
float* movedY,
int* changedType)
{
return ImGui::FCurve(
fcurve_id,
keys,
values,
leftHandleKeys,
leftHandleValues,
rightHandleKeys,
rightHandleValues,
(ImGui::ImFCurveInterporationType*)interporations,
(ImGui::ImFCurveEdgeType)startEdge,
(ImGui::ImFCurveEdgeType)endEdge,
(bool*)kv_selected,
count,
defaultValue,
isLocked,
canControl,
col,
selected,
v_min,
v_max,
newCount,
newSelected,
movedX,
movedY,
changedType);
}
bool GUIManager::BeginDragDropSource()
{
return ImGui::BeginDragDropSource();
}
bool GUIManager::SetDragDropPayload(const char* type, uint8_t* data, int size)
{
return ImGui::SetDragDropPayload(type, data, size);
}
void GUIManager::EndDragDropSource()
{
ImGui::EndDragDropSource();
}
bool GUIManager::BeginDragDropTarget()
{
return ImGui::BeginDragDropTarget();
}
bool GUIManager::AcceptDragDropPayload(const char* type, uint8_t* data_output, int data_output_size, int* size)
{
auto pyload = ImGui::AcceptDragDropPayload(type);
if (pyload == nullptr)
{
*size = 0;
return false;
}
auto max_size = std::min(data_output_size, pyload->DataSize);
memcpy(data_output, pyload->Data, max_size);
*size = max_size;
return true;
}
void GUIManager::EndDragDropTarget()
{
ImGui::EndDragDropTarget();
}
DialogSelection GUIManager::show(const char16_t* message, const char16_t* title, DialogStyle style, DialogButtons buttons)
{
return (DialogSelection)boxer::show(
utf8str<256>(message),
utf8str<256>(title),
(boxer::Style)style,
(boxer::Buttons)buttons);
}
bool GUIManager::IsMacOSX()
{
#if __APPLE__
return true;
#else
return false;
#endif
}
void GUIManager::SetIniFilename(const char16_t* filename)
{
static std::string filename_ = std::string(utf8str<256>(filename));
ImGui::GetIO().IniFilename = filename_.c_str();
}
int GUIManager::GetLanguage()
{
return (int32_t)GetEfkLanguage();
}
}
|
/****************************************************************************
* Copyright (c) 2012-2018 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#ifndef DTK_DETAILS_CONCEPTS_HPP
#define DTK_DETAILS_CONCEPTS_HPP
#include <DTK_DetailsAlgorithms.hpp>
#include <type_traits>
#if !defined( __cpp_lib_void_t )
namespace std
{
template <typename...>
using void_t = void;
}
#endif
namespace DataTransferKit
{
namespace Details
{
// Checks for existence of a free function that expands an object of type
// Geometry using an object of type Other
template <typename Geometry, typename Other, typename = void>
struct is_expandable : std::false_type
{
};
template <typename Geometry, typename Other>
struct is_expandable<
Geometry, Other,
std::void_t<decltype(
expand( std::declval<Geometry &>(), std::declval<Other const &>() ) )>>
: std::true_type
{
};
// Checks for existence of a free function that calculates the centroid of an
// object of type Geometry
template <typename Geometry, typename Point, typename = void>
struct has_centroid : std::false_type
{
};
template <typename Geometry, typename Point>
struct has_centroid<
Geometry, Point,
std::void_t<decltype( centroid( std::declval<Geometry const &>(),
std::declval<Point &>() ) )>>
: std::true_type
{
};
} // namespace Details
} // namespace DataTransferKit
#endif
Use prepocessor directives to hide concepts from Doxygen that had trouble parsing
/****************************************************************************
* Copyright (c) 2012-2018 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#ifndef DTK_DETAILS_CONCEPTS_HPP
#define DTK_DETAILS_CONCEPTS_HPP
#include <DTK_DetailsAlgorithms.hpp>
#include <type_traits>
#if !defined( __cpp_lib_void_t )
namespace std
{
template <typename...>
using void_t = void;
}
#endif
#if !defined( DOXYGEN_SHOULD_SKIP_THIS )
namespace DataTransferKit
{
namespace Details
{
// Checks for existence of a free function that expands an object of type
// Geometry using an object of type Other
template <typename Geometry, typename Other, typename = void>
struct is_expandable : std::false_type
{
};
template <typename Geometry, typename Other>
struct is_expandable<
Geometry, Other,
std::void_t<decltype(
expand( std::declval<Geometry &>(), std::declval<Other const &>() ) )>>
: std::true_type
{
};
// Checks for existence of a free function that calculates the centroid of an
// object of type Geometry
template <typename Geometry, typename Point, typename = void>
struct has_centroid : std::false_type
{
};
template <typename Geometry, typename Point>
struct has_centroid<
Geometry, Point,
std::void_t<decltype( centroid( std::declval<Geometry const &>(),
std::declval<Point &>() ) )>>
: std::true_type
{
};
} // namespace Details
} // namespace DataTransferKit
#endif // DOXYGEN_SHOULD_SKIP_THIS
#endif
|
#include "vec3.h"
namespace fd {
namespace core {
namespace math {
vec3::vec3() : x(0), y(0), z(0) {}
vec3::vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {}
#pragma region vec-vec
//Asss
//float32
vec3& vec3::Add(const vec3& v) {
__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
__m128 xmm = _mm_set_ps(0, z, y, x);
xmm = _mm_add_ps(xmm, vxmm);
x = M128(xmm, 0);
y = M128(xmm, 1);
z = M128(xmm, 2);
return *this;
}
//sub
//float32
vec3& vec3::Sub(const vec3& v) {
__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
__m128 xmm = _mm_set_ps(0, z, y, x);
xmm = _mm_sub_ps(xmm, vxmm);
x = M128(xmm, 0);
y = M128(xmm, 1);
z = M128(xmm, 2);
return *this;
}
//Mul
//float32
vec3& vec3::Mul(const vec3& v) {
__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
__m128 xmm = _mm_set_ps(0, z, y, x);
xmm = _mm_mul_ps(xmm, vxmm);
x = M128(xmm, 0);
y = M128(xmm, 1);
z = M128(xmm, 2);
return *this;
}
//Div
//float32
vec3& vec3::Div(const vec3& v) {
__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
__m128 xmm = _mm_set_ps(0, z, y, x);
xmm = _mm_div_ps(xmm, vxmm);
x = M128(xmm, 0);
y = M128(xmm, 1);
z = M128(xmm, 2);
return *this;
}
#pragma endregion
#pragma region vec-shit
//Add
//float32
vec3& vec3::Add(float32 v) {
__m128 vxmm = _mm_set_ps(0, v, v, v);
__m128 xmm = _mm_set_ps(0, z, y, x);
xmm = _mm_add_ps(xmm, vxmm);
x = M128(xmm, 0);
y = M128(xmm, 1);
z = M128(xmm, 2);
return *this;
}
//Sub
//float32
vec3& vec3::Sub(float32 v) {
__m128 vxmm = _mm_set_ps(0, v, v, v);
__m128 xmm = _mm_set_ps(0, z, y, x);
xmm = _mm_sub_ps(xmm, vxmm);
x = M128(xmm, 0);
y = M128(xmm, 1);
z = M128(xmm, 2);
return *this;
}
//Mul
//float32
vec3& vec3::Mul(float32 v) {
__m128 vxmm = _mm_set_ps(0, v, v, v);
__m128 xmm = _mm_set_ps(0, z, y, x);
xmm = _mm_mul_ps(xmm, vxmm);
x = M128(xmm, 0);
y = M128(xmm, 1);
z = M128(xmm, 2);
return *this;
}
//Div
//float32
vec3& vec3::Div(float32 v) {
__m128 vxmm = _mm_set_ps(0, v, v, v);
__m128 xmm = _mm_set_ps(0, z, y, x);
xmm = _mm_div_ps(xmm, vxmm);
x = M128(xmm, 0);
y = M128(xmm, 1);
z = M128(xmm, 2);
return *this;
}
float32 vec3::Length() const {
return sqrtf(x * x + y * y + z * z);
}
vec3& vec3::Normalize() {
return Mul(1.0f / Length());
}
vec3 vec3::Cross(const vec3& v) const {
__m128 xmm0 = _mm_set_ps(0, x, z, y);
__m128 vxmm0 = _mm_set_ps(0, v.y, v.x, v.z);
__m128 xmm1 = _mm_set_ps(0, y, x, z);
__m128 vxmm1 = _mm_set_ps(0, v.x, v.z, v.y);
xmm0 = _mm_mul_ps(xmm0, vxmm0);
xmm1 = _mm_mul_ps(xmm1, vxmm1);
xmm0 = _mm_sub_ps(xmm0, xmm1);
return vec3(M128(xmm, 0), M128(xmm, 1), M128(xmm, 2));
}
float32 vec3::Dot(const vec3& v) const {
__m128 xmm = _mm_set_ps(0, v.z, v.y, v.x);
xmm = _mm_mul_ps(xmm, _mm_set_ps(0, y, z, x));
return M128(xmm, 0) + M128(xmm, 1) + M128(xmm, 2);
}
#pragma endregion
}
}
}
I'm stupid
#include "vec3.h"
namespace fd {
namespace core {
namespace math {
vec3::vec3() : x(0), y(0), z(0) {}
vec3::vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {}
#pragma region vec-vec
//Asss
//float32
vec3& vec3::Add(const vec3& v) {
__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
__m128 xmm = _mm_set_ps(0, z, y, x);
xmm = _mm_add_ps(xmm, vxmm);
x = M128(xmm, 0);
y = M128(xmm, 1);
z = M128(xmm, 2);
return *this;
}
//sub
//float32
vec3& vec3::Sub(const vec3& v) {
__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
__m128 xmm = _mm_set_ps(0, z, y, x);
xmm = _mm_sub_ps(xmm, vxmm);
x = M128(xmm, 0);
y = M128(xmm, 1);
z = M128(xmm, 2);
return *this;
}
//Mul
//float32
vec3& vec3::Mul(const vec3& v) {
__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
__m128 xmm = _mm_set_ps(0, z, y, x);
xmm = _mm_mul_ps(xmm, vxmm);
x = M128(xmm, 0);
y = M128(xmm, 1);
z = M128(xmm, 2);
return *this;
}
//Div
//float32
vec3& vec3::Div(const vec3& v) {
__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
__m128 xmm = _mm_set_ps(0, z, y, x);
xmm = _mm_div_ps(xmm, vxmm);
x = M128(xmm, 0);
y = M128(xmm, 1);
z = M128(xmm, 2);
return *this;
}
#pragma endregion
#pragma region vec-shit
//Add
//float32
vec3& vec3::Add(float32 v) {
__m128 vxmm = _mm_set_ps(0, v, v, v);
__m128 xmm = _mm_set_ps(0, z, y, x);
xmm = _mm_add_ps(xmm, vxmm);
x = M128(xmm, 0);
y = M128(xmm, 1);
z = M128(xmm, 2);
return *this;
}
//Sub
//float32
vec3& vec3::Sub(float32 v) {
__m128 vxmm = _mm_set_ps(0, v, v, v);
__m128 xmm = _mm_set_ps(0, z, y, x);
xmm = _mm_sub_ps(xmm, vxmm);
x = M128(xmm, 0);
y = M128(xmm, 1);
z = M128(xmm, 2);
return *this;
}
//Mul
//float32
vec3& vec3::Mul(float32 v) {
__m128 vxmm = _mm_set_ps(0, v, v, v);
__m128 xmm = _mm_set_ps(0, z, y, x);
xmm = _mm_mul_ps(xmm, vxmm);
x = M128(xmm, 0);
y = M128(xmm, 1);
z = M128(xmm, 2);
return *this;
}
//Div
//float32
vec3& vec3::Div(float32 v) {
__m128 vxmm = _mm_set_ps(0, v, v, v);
__m128 xmm = _mm_set_ps(0, z, y, x);
xmm = _mm_div_ps(xmm, vxmm);
x = M128(xmm, 0);
y = M128(xmm, 1);
z = M128(xmm, 2);
return *this;
}
float32 vec3::Length() const {
return sqrtf(x * x + y * y + z * z);
}
vec3& vec3::Normalize() {
return Mul(1.0f / Length());
}
vec3 vec3::Cross(const vec3& v) const {
__m128 xmm0 = _mm_set_ps(0, x, z, y);
__m128 vxmm0 = _mm_set_ps(0, v.y, v.x, v.z);
__m128 xmm1 = _mm_set_ps(0, y, x, z);
__m128 vxmm1 = _mm_set_ps(0, v.x, v.z, v.y);
xmm0 = _mm_mul_ps(xmm0, vxmm0);
xmm1 = _mm_mul_ps(xmm1, vxmm1);
xmm0 = _mm_sub_ps(xmm0, xmm1);
return vec3(M128(xmm0, 0), M128(xmm0, 1), M128(xmm0, 2));
}
float32 vec3::Dot(const vec3& v) const {
__m128 xmm = _mm_set_ps(0, v.z, v.y, v.x);
xmm = _mm_mul_ps(xmm, _mm_set_ps(0, y, z, x));
return M128(xmm, 0) + M128(xmm, 1) + M128(xmm, 2);
}
#pragma endregion
}
}
} |
// LiveCoding.cpp : Definiert den Einstiegspunkt fr die Anwendung.
//
#include "stdafx.h"
#include "LiveCoding.h"
#include "Configuration.h"
#include "glext.h"
#include "GLNames.h"
#include "ShaderManager.h"
#include "TextureManager.h"
//#include "FluidSimulation.h"
#include "Editor.h"
#include "Parameter.h"
#include "bass.h"
#define MAX_LOADSTRING 100
#define BLOB_FADE_SPEED 1.0f
// The used effect (will be changeable later on)
#define NUM_USED_PROGRAMS 10
char *usedShader[NUM_USED_PROGRAMS] = {"empty.jlsl", "vp1.jlsl", "vp2.jlsl", "vp3.jlsl", "vp4.jlsl", "vp5.jlsl", "vp6.jlsl", "vp7.jlsl", "vp8.jlsl", "vp9.jlsl"};
char *usedProgram[NUM_USED_PROGRAMS] = {"empty.gprg", "vp1.gprg", "vp2.gprg", "vp3.gprg", "vp4.gprg", "vp5.gprg", "vp6.gprg", "vp7.gprg", "vp8.gprg", "vp9.gprg"};
int usedIndex = 0;
float aspectRatio = (float)XRES / (float)YRES;
float music_start_time_ = -10000.0f;
float otone_start_time_ = 1.0e20f;
float real_otone_start_time_ = 1.0e20f; // triggered by close-to-entrance rotation
float masako_start_time_ = 1.0e20f;
float real_masako_start_time_ = 1.0e20f; // triggered by close-to-entrance rotation
// Time when theatre goes black (end)
float black_start_time_ = 1.0e20f;
// Set to true if the animation stops
bool rotation_stopped_ = false;
// Engawa logo
float ending_start_time_ = 1.0e20f;
long start_time_ = 0;
//FluidSimulation fluid_simulation_;
HSTREAM mp3Str;
// Of the music stuff
const int kNumEdges = 8;
const int kNumSegmentsPerEdge = 16;
const int kNumSegments = kNumEdges * kNumSegmentsPerEdge;
// Created by music, used by floaty stuff
float interpolation_quad_[2][kNumSegments][4][2];
/*************************************************
* GL Core variables
*************************************************/
GenFP glFP[NUM_GL_NAMES]; // pointer to openGL functions
const static char* glnames[NUM_GL_NAMES]={
"glCreateShader", "glCreateProgram", "glShaderSource", "glCompileShader",
"glAttachShader", "glLinkProgram", "glUseProgram",
"glTexImage3D", "glGetShaderiv","glGetShaderInfoLog",
"glDeleteProgram", "glDeleteShader",
"glActiveTexture", "glGetUniformLocation", "glUniform1i", "glUniform1f",
"glMultiTexCoord2f"
};
/*************************************************
* The core managing units that hold the resources
*************************************************/
ShaderManager shaderManager;
TextureManager textureManager;
Editor editor;
/*************************************************
* Window core variables
*************************************************/
HINSTANCE hInst; // Aktuelle Instanz
TCHAR szTitle[MAX_LOADSTRING]; // Titelleistentext
TCHAR szWindowClass[MAX_LOADSTRING]; // Klassenname des Hauptfensters
// The size of the window that we render to...
RECT windowRect;
typedef struct
{
//---------------
HINSTANCE hInstance;
HDC hDC;
HGLRC hRC;
HWND hWnd;
//---------------
int full;
//---------------
char wndclass[4]; // window class and title :)
//---------------
}WININFO;
static const PIXELFORMATDESCRIPTOR pfd =
{
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
24,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, // accum
0, // zbuffer
0, // stencil!
0, // aux
PFD_MAIN_PLANE,
0, 0, 0, 0
};
static WININFO wininfo = { 0,0,0,0,0,
{'l','c','_',0}
};
/**************************************************
* Parameters from the midi stuff
****************************************************/
// ---------------------------------------------------------------
// Parameter interpolation stuff
// ------------------------------------------------------------
// I want to interpolate the new values from the old ones.
const int maxNumParameters = 25;
const static float defaultParameters[maxNumParameters] =
{
-1.0f, -1.0f,
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, // 2-6 ~= 1-5
-1.0f,
0.0f, 0.0f, // 8,9 ~= 6,7
-1.0f, -1.0f,
0.0f, 0.0f, // 12,13 ~= 8-9
0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f, // 14-22 ~= 1b-9b
};
float interpolatedParameters[maxNumParameters];
const int NUM_KEYS = 127;
static int keyPressed[NUM_KEYS] = {0};
// BPM stuff
const int NUM_BEAT_TIMES = 7;
float BPM = 0.0f;
int beatDurations[NUM_BEAT_TIMES] = {900, 1200, 1100, 1000, 1400, 1000, 1000};
int lastBeatTime = 0;
float blob = 0.;
/*************************************************
* OpenGL initialization
*************************************************/
static int initGL(WININFO *winInfo)
{
char errorString[MAX_ERROR_LENGTH + 1];
// Create openGL functions
for (int i=0; i<NUM_GL_NAMES; i++) glFP[i] = (GenFP)wglGetProcAddress(glnames[i]);
// Create and initialize the shader manager
if (shaderManager.init(errorString))
{
MessageBox(winInfo->hWnd, errorString, "Shader Manager Load", MB_OK);
return -1;
}
// Create and initialize everything needed for texture Management
if (textureManager.init(errorString))
{
MessageBox(winInfo->hWnd, errorString, "Texture Manager Load", MB_OK);
return -1;
}
// Create the text editor
if (editor.init(&shaderManager, &textureManager, errorString))
{
MessageBox(winInfo->hWnd, errorString, "Editor init", MB_OK);
return -1;
}
blob = 0.;
// Create the fluid simulation stuff
//fluid_simulation_.Init(false);
return 0;
}
/*************************************************
* Windows callback
*************************************************/
static LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
int time = timeGetTime() - start_time_;
float ftime = 0.001f * time;
// salvapantallas
if( uMsg==WM_SYSCOMMAND && (wParam==SC_SCREENSAVE || wParam==SC_MONITORPOWER) )
return( 0 );
// boton x o pulsacion de escape
//if( uMsg==WM_CLOSE || uMsg==WM_DESTROY || (uMsg==WM_KEYDOWN && wParam==VK_ESCAPE) )
if( uMsg==WM_CLOSE || uMsg==WM_DESTROY )
{
PostQuitMessage(0);
return( 0 );
}
// Reaction to command keys
if( uMsg==WM_KEYDOWN )
{
switch (wParam)
{
#if 0
case VK_ESCAPE:
PostQuitMessage(0);
return 0;
#endif
case VK_LEFT:
case VK_RIGHT:
case VK_UP:
case VK_DOWN:
case VK_PRIOR:
case VK_NEXT:
case VK_END:
case VK_HOME:
break;
case VK_RETURN:
case VK_DELETE:
case VK_BACK:
break;
case 'q':
case 'Q':
music_start_time_ = 0.001f * (timeGetTime() - start_time_);
black_start_time_ = 1.0e20f;
ending_start_time_ = 1.0e20f;
rotation_stopped_ = false;
// start music playback
#ifdef MUSIC
BASS_Init(-1, 44100, 0, hWnd, NULL);
mp3Str = BASS_StreamCreateFile(FALSE, "Goethe_music.mp3", 0, 0, 0);
BASS_ChannelPlay(mp3Str, TRUE);
BASS_Start();
#endif
break;
case 'w':
case 'W':
music_start_time_ = -10000.0f;
black_start_time_ = 1.0e20f;
ending_start_time_ = 1.0e20f;
rotation_stopped_ = false;
#ifdef MUSIC
BASS_Stop();
BASS_ChannelStop(mp3Str);
BASS_StreamFree(mp3Str);
BASS_Free();
#endif
break;
case 'a':
case 'A':
//fluid_simulation_.request_set_points_ = true;
otone_start_time_ = 1.0e20f;
real_otone_start_time_ = otone_start_time_;
masako_start_time_ = 1.0e20f;
real_masako_start_time_ = masako_start_time_;
black_start_time_ = 1.0e20f;
ending_start_time_ = 1.0e20f;
rotation_stopped_ = false;
break;
case 's':
case 'S':
otone_start_time_ = 0.001f * (timeGetTime() - start_time_);
black_start_time_ = 1.0e20f;
ending_start_time_ = 1.0e20f;
rotation_stopped_ = false;
break;
case 'd':
case 'D':
masako_start_time_ = 0.001f * (timeGetTime() - start_time_);
black_start_time_ = 1.0e20f;
ending_start_time_ = 1.0e20f;
rotation_stopped_ = false;
break;
case 'o':
case 'O':
//fluid_simulation_.Init(false);
rotation_stopped_ = false;
break;
case 'p':
case 'P':
//fluid_simulation_.Init(true);
rotation_stopped_ = true;
break;
case 'x':
case 'X':
//fluid_simulation_.PushApart();
black_start_time_ = 0.001f * (timeGetTime() - start_time_);
ending_start_time_ = 1.0e20f;
rotation_stopped_ = true;
break;
case 'c':
case 'C':
//fluid_simulation_.PushApart();
ending_start_time_ = 0.001f * (timeGetTime() - start_time_);
break;
case 'm':
case 'M':
if (GetAsyncKeyState(VK_CONTROL) < 0) {
// TODO: Minimization again.
SetWindowLong(hWnd, GWL_STYLE, WS_POPUP | WS_VISIBLE);
ShowWindow(hWnd, SW_MAXIMIZE);
GetClientRect(hWnd, &windowRect);
glViewport(0, 0, windowRect.right - windowRect.left, abs(windowRect.bottom - windowRect.top)); //NEW
aspectRatio = (float)(windowRect.right - windowRect.left) / (float)(abs(windowRect.bottom - windowRect.top));
ShowCursor(false);
}
break;
default:
break;
}
}
if (uMsg == WM_KEYUP) {
switch(wParam) {
default:
break;
}
}
return( DefWindowProc(hWnd,uMsg,wParam,lParam) );
}
static void window_end( WININFO *info )
{
if( info->hRC )
{
wglMakeCurrent( 0, 0 );
wglDeleteContext( info->hRC );
}
if( info->hDC ) ReleaseDC( info->hWnd, info->hDC );
if( info->hWnd ) DestroyWindow( info->hWnd );
UnregisterClass( info->wndclass, info->hInstance );
if( info->full )
{
ChangeDisplaySettings( 0, 0 );
ShowCursor( 1 );
}
}
static int window_init( WININFO *info )
{
unsigned int PixelFormat;
DWORD dwExStyle, dwStyle;
DEVMODE dmScreenSettings;
RECT rec;
WNDCLASS wc;
ZeroMemory( &wc, sizeof(WNDCLASS) );
wc.style = CS_OWNDC|CS_HREDRAW|CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.hInstance = info->hInstance;
wc.lpszClassName = info->wndclass;
if( !RegisterClass(&wc) )
return( 0 );
if( info->full )
{
dmScreenSettings.dmSize = sizeof(DEVMODE);
dmScreenSettings.dmFields = DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
dmScreenSettings.dmBitsPerPel = 24;
dmScreenSettings.dmPelsWidth = XRES;
dmScreenSettings.dmPelsHeight = YRES;
if( ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
return( 0 );
dwExStyle = WS_EX_APPWINDOW;
dwStyle = WS_VISIBLE | WS_POPUP;// | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
ShowCursor( 0 );
}
else
{
dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
dwStyle = WS_VISIBLE | WS_CAPTION | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_SYSMENU;
}
rec.left = 0;
rec.top = 0;
rec.right = XRES;
rec.bottom = YRES;
AdjustWindowRect( &rec, dwStyle, 0 );
windowRect.left = 0;
windowRect.top = 0;
windowRect.right = XRES;
windowRect.bottom = YRES;
info->hWnd = CreateWindowEx( dwExStyle, wc.lpszClassName, "live coding", dwStyle,
(GetSystemMetrics(SM_CXSCREEN)-rec.right+rec.left)>>1,
(GetSystemMetrics(SM_CYSCREEN)-rec.bottom+rec.top)>>1,
rec.right-rec.left, rec.bottom-rec.top, 0, 0, info->hInstance, 0 );
if( !info->hWnd )
return( 0 );
if( !(info->hDC=GetDC(info->hWnd)) )
return( 0 );
if( !(PixelFormat=ChoosePixelFormat(info->hDC,&pfd)) )
return( 0 );
if( !SetPixelFormat(info->hDC,PixelFormat,&pfd) )
return( 0 );
if( !(info->hRC=wglCreateContext(info->hDC)) )
return( 0 );
if( !wglMakeCurrent(info->hDC,info->hRC) )
return( 0 );
return( 1 );
}
void drawQuad(float startX, float endX, float startY, float endY, float startV, float endV, float alpha)
{
// set up matrices
glEnable(GL_TEXTURE_2D);
glColor4f(1.0f, 1.0f, 1.0f, alpha);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, endV);
glVertex3f(startX, endY * aspectRatio / 4 * 3 - 0.1f, 0.99f);
glTexCoord2f(1.0f, endV);
glVertex3f(endX, endY * aspectRatio / 4 * 3 - 0.1f, 0.99f);
glTexCoord2f(1.0f, startV);
glVertex3f(endX, startY * aspectRatio / 4 * 3 - 0.1f, 0.99f);
glTexCoord2f(0.0, startV);
glVertex3f(startX, startY * aspectRatio / 4 * 3 - 0.1f, 0.99f);
glEnd();
}
// interpolation with the interpolation_quad
void DrawTearCircle(float start_angle, float end_angle, float distance,
float center_x, float center_y,
int person, float interpolation,
float ftime,
float thickness) {
float kTearWidth = 0.04f * thickness;
if (ftime > black_start_time_) {
kTearWidth += (ftime - black_start_time_) * (ftime - black_start_time_) * 0.02f;
start_angle += (ftime - black_start_time_) * (ftime - black_start_time_) * 0.1f;
end_angle -= (ftime - black_start_time_) * (ftime - black_start_time_) * 0.1f;
}
float cur_angle = start_angle;
float delta_angle = (end_angle - start_angle) / kNumSegments;
float tear_delta_position = 1.0f / (kNumSegments + 1);
float tear_position = tear_delta_position / 4.0f;
// Initialize OGL stuff
GLuint programID;
char errorText[MAX_ERROR_LENGTH + 1];
shaderManager.getProgramID("SimpleTexture.gprg", &programID, errorText);
glUseProgram(programID);
glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
glBegin(GL_QUADS);
for (int i = 0; i < kNumSegments; i++) {
float left_angle = cur_angle;
float right_angle = cur_angle + delta_angle;
float tear_left_pos = tear_position; // nothing for 0.
float tear_right_pos = tear_left_pos + tear_delta_position;
float left_width = kTearWidth * sinf(tear_left_pos * 3.1415f) / sqrtf(tear_left_pos);
float right_width = kTearWidth * sinf(tear_right_pos * 3.1415f) / sqrtf(tear_right_pos);
float left_pos[2] = {
distance * sinf(left_angle) + center_x,
distance * cosf(left_angle) + center_y
};
float right_pos[2] = {
distance * sinf(right_angle) + center_x,
distance * cosf(right_angle) + center_y
};
float left_normal[2] = { sinf(left_angle), cosf(left_angle) };
float right_normal[2] = { sinf(right_angle), cosf(right_angle) };
float t = interpolation;
float k = 1.0f - t;
float vertices[4][2] = {
{left_pos[0] - left_width * left_normal[0], (left_pos[1] - left_width * left_normal[1]) * aspectRatio},
{left_pos[0] + left_width * left_normal[0], (left_pos[1] + left_width * left_normal[1]) * aspectRatio},
{right_pos[0] + right_width * right_normal[0], (right_pos[1] + right_width * right_normal[1]) * aspectRatio},
{right_pos[0] - right_width * right_normal[0],(right_pos[1] - right_width * right_normal[1]) * aspectRatio}
};
glVertex2f(t * interpolation_quad_[person][i][0][0] + k * vertices[0][0], t * interpolation_quad_[person][i][0][1] + k * vertices[0][1]);
glVertex2f(t * interpolation_quad_[person][i][1][0] + k * vertices[1][0], t * interpolation_quad_[person][i][1][1] + k * vertices[1][1]);
glVertex2f(t * interpolation_quad_[person][i][2][0] + k * vertices[2][0], t * interpolation_quad_[person][i][2][1] + k * vertices[2][1]);
glVertex2f(t * interpolation_quad_[person][i][3][0] + k * vertices[3][0], t * interpolation_quad_[person][i][3][1] + k * vertices[3][1]);
cur_angle = right_angle;
tear_position = tear_right_pos;
}
glEnd();
}
void DrawMusic(float ftime) {
float delta_angle = 3.141592f * 2.0f / kNumEdges;
const float music_beat = 0.405f;
const float rotation_speed = 0.1f;
// Initialize OGL stuff
GLuint programID;
char errorText[MAX_ERROR_LENGTH + 1];
shaderManager.getProgramID("SimpleTexture.gprg", &programID, errorText);
glUseProgram(programID);
glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
glBegin(GL_QUADS);
// Just a 5-edge thingie
for (int person = 0; person < 2; person++) {
//float divergence = person * -sinf(ftime * 3.1415f / 160.0f * 8.0f);
//if (divergence < 0.0f) divergence = 0.0f;
float divergence = person * sinf(ftime * 3.1415f / 160.0f * 7.5f);
divergence *= divergence;
if (ftime < 20.0f) divergence = 0.0f;
int interpolation_quad_id = 0;
for (int edge = 0; edge < kNumEdges; edge++) {
float start_angle = edge * delta_angle;
int next_edge = edge + 1;
if (edge == kNumEdges - 1) next_edge = 0;
float end_angle = next_edge * delta_angle;
float beat_overdrive = sinf(ftime * 3.1415f / 160.0f) * 2.0f + .5f;
if (ftime > 80.0f) beat_overdrive = 1.0f;
float rotation = rotation_speed * 3.1415f * 2.0f * ftime;
float beat = sinf(ftime * 3.1415f * 2.0f / music_beat);
//beat *= beat * beat;
rotation += rotation_speed * beat * music_beat * beat_overdrive * 0.35f;
start_angle -= rotation;
end_angle -= rotation;
float start_line[2] = { cosf(start_angle), sinf(start_angle) };
float end_line[2] = { cosf(end_angle), sinf(end_angle) };
float star_amount = 0.2f * sinf(ftime * 3.1415f / 160.0f);
if (ftime > 80.0f) star_amount = 0.2f;
float inner_dist_start = 0.27f + star_amount * sinf(0.2f * ftime + 3.1415f * 2.0f * edge / kNumEdges * 10 + divergence*star_amount);
float inner_dist_end = 0.27f + star_amount * sinf(0.2f * ftime + 3.1415f * 2.0f * next_edge / kNumEdges * 10 + divergence*star_amount);
float outer_dist_start = 0.35f + star_amount * sinf(0.2f * ftime + 3.1415f * 2.0f * edge / kNumEdges * 10 + divergence);
float outer_dist_end = 0.35f + star_amount * sinf(0.2f * ftime + 3.1415f * 2.0f * next_edge / kNumEdges * 10 + divergence);
float size_overdrive = sinf(ftime * 3.1415f / 160.0f) * 2.0f + .4f;
float size = 1.0f + 0.2f * size_overdrive +
size_overdrive * (0.25f * sinf(ftime * 0.4f + divergence * 3.14f) + 0.15f * sinf(ftime * 0.25f + divergence * 3.14f));
inner_dist_start *= size;
inner_dist_end *= size;
outer_dist_start *= size;
outer_dist_end *= size;
float vertices[4][2] = {
{start_line[0] * inner_dist_start, start_line[1] * inner_dist_start * aspectRatio},
{start_line[0] * outer_dist_start, start_line[1] * outer_dist_start * aspectRatio},
{end_line[0] * outer_dist_end, end_line[1] * outer_dist_end * aspectRatio},
{end_line[0] * inner_dist_end, end_line[1] * inner_dist_end * aspectRatio}
};
for (int segment = 0; segment < kNumSegmentsPerEdge; segment++) {
float t_start = (float)segment / (float)(kNumSegmentsPerEdge);
float k_start = 1.0f - t_start;
float t_end = (float)(segment + 1) / (float)(kNumSegmentsPerEdge);
float k_end = 1.0f - t_end;
interpolation_quad_[person][interpolation_quad_id][0][0] = k_start * vertices[0][0] + t_start * vertices[3][0];
interpolation_quad_[person][interpolation_quad_id][0][1] = k_start * vertices[0][1] + t_start * vertices[3][1];
interpolation_quad_[person][interpolation_quad_id][1][0] = k_start * vertices[1][0] + t_start * vertices[2][0];
interpolation_quad_[person][interpolation_quad_id][1][1] = k_start * vertices[1][1] + t_start * vertices[2][1];
interpolation_quad_[person][interpolation_quad_id][3][0] = k_end * vertices[0][0] + t_end * vertices[3][0];
interpolation_quad_[person][interpolation_quad_id][3][1] = k_end * vertices[0][1] + t_end * vertices[3][1];
interpolation_quad_[person][interpolation_quad_id][2][0] = k_end * vertices[1][0] + t_end * vertices[2][0];
interpolation_quad_[person][interpolation_quad_id][2][1] = k_end * vertices[1][1] + t_end * vertices[2][1];
glVertex2f(interpolation_quad_[person][interpolation_quad_id][0][0], interpolation_quad_[person][interpolation_quad_id][0][1]);
glVertex2f(interpolation_quad_[person][interpolation_quad_id][1][0], interpolation_quad_[person][interpolation_quad_id][1][1]);
glVertex2f(interpolation_quad_[person][interpolation_quad_id][2][0], interpolation_quad_[person][interpolation_quad_id][2][1]);
glVertex2f(interpolation_quad_[person][interpolation_quad_id][3][0], interpolation_quad_[person][interpolation_quad_id][3][1]);
interpolation_quad_id++;
}
}
}
glEnd();
}
// Anfang langsamer
// Anfang Masako immer synchron, kein berlappen!
// Nach Musik langsamer
// Black aprupt
// Streit kein Kreis - ggf. zwei unterschiedliche Zentren fr die Kreise
// Bei Masako eh voraussichtlich Kreis 70* drehen
// Feste Parameter, dass ich nur noch auf Tasten drcken muss...
// Abstand ruckartig, ca. 3 unterschiedliche Stufen. Geschwindigkeit immer gleich?
// --> Zusammengehen immer langsam.
// --> Problem nach dem Streit: Zusammen <-> Auseinander hin-und-her: Wie mach ich das?
// Mittwoch: 19:00
// Donnerstag: Ab 18:00 Sprichst mit Masako
// Freitag: 9-11
void intro_do(long t, long delta_time)
{
char errorText[MAX_ERROR_LENGTH + 1];
float ftime = 0.001f*(float)t;
float fdelta_time = 0.001f * (float)(delta_time);
GLuint textureID;
glDisable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
// Those are key-Press indicators. I only act on 0-to-1.
for (int i = 0; i < maxNumParameters; i++)
{
interpolatedParameters[i] = expf(-2.0f*fdelta_time) * interpolatedParameters[i] +
(1.0f - expf(-2.0f*fdelta_time)) * params.getParam(i, defaultParameters[i]);
}
// Update key press events.
for (int i = 0; i < NUM_KEYS; i++)
{
if (params.getParam(i, 0.0) > 0.5f) keyPressed[i]++;
else keyPressed[i] = 0;
}
// BPM => spike calculation
float BPS = BPM / 60.0f;
float jumpsPerSecond = BPS / 1.0f; // Jump on every fourth beat.
static float phase = 0.0f;
float jumpTime = (ftime * jumpsPerSecond) + phase;
jumpTime -= (float)floor(jumpTime);
if (keyPressed[41] == 1)
{
phase -= jumpTime;
jumpTime = 0.0f;
if (phase < 0.0f) phase += 1.0;
}
jumpTime = jumpTime * jumpTime;
// spike is between 0.0 and 1.0 depending on the position within whatever.
float spike = 0.5f * cosf(jumpTime * 3.1415926f * 1.5f) + 0.5f;
// blob is growing down from 1. after keypress
static float lastFTime = 0.f;
blob *= (float)exp(-(float)(ftime - lastFTime) * BLOB_FADE_SPEED);
lastFTime = ftime;
// Set the program uniforms
GLuint programID;
shaderManager.getProgramID(usedProgram[usedIndex], &programID, errorText);
glUseProgram(programID);
GLuint loc = glGetUniformLocation(programID, "aspectRatio");
glUniform1f(loc, aspectRatio);
loc = glGetUniformLocation(programID, "time");
glUniform1f(loc, (float)(t * 0.001f));
// For now I am just sending the spike to the shader. I might need something better...
loc = glGetUniformLocation(programID, "spike");
glUniform1f(loc, spike);
loc = glGetUniformLocation(programID, "blob");
glUniform1f(loc, blob);
loc = glGetUniformLocation(programID, "knob1");
glUniform1f(loc, interpolatedParameters[14]);
loc = glGetUniformLocation(programID, "knob2");
glUniform1f(loc, interpolatedParameters[15]);
loc = glGetUniformLocation(programID, "knob3");
glUniform1f(loc, interpolatedParameters[16]);
loc = glGetUniformLocation(programID, "knob4");
glUniform1f(loc, interpolatedParameters[17]);
loc = glGetUniformLocation(programID, "knob5");
glUniform1f(loc, interpolatedParameters[18]);
loc = glGetUniformLocation(programID, "knob6");
glUniform1f(loc, interpolatedParameters[19]);
loc = glGetUniformLocation(programID, "knob7");
glUniform1f(loc, interpolatedParameters[20]);
loc = glGetUniformLocation(programID, "knob8");
glUniform1f(loc, interpolatedParameters[21]);
loc = glGetUniformLocation(programID, "knob9");
glUniform1f(loc, interpolatedParameters[22]);
loc = glGetUniformLocation(programID, "slider1");
glUniform1f(loc, interpolatedParameters[2]);
loc = glGetUniformLocation(programID, "slider2");
glUniform1f(loc, interpolatedParameters[3]);
loc = glGetUniformLocation(programID, "slider3");
glUniform1f(loc, interpolatedParameters[4]);
loc = glGetUniformLocation(programID, "slider4");
glUniform1f(loc, interpolatedParameters[5]);
loc = glGetUniformLocation(programID, "slider5");
glUniform1f(loc, interpolatedParameters[6]);
loc = glGetUniformLocation(programID, "slider6");
glUniform1f(loc, interpolatedParameters[8]);
loc = glGetUniformLocation(programID, "slider7");
glUniform1f(loc, interpolatedParameters[9]);
loc = glGetUniformLocation(programID, "slider8");
glUniform1f(loc, interpolatedParameters[12]);
loc = glGetUniformLocation(programID, "slider9");
glUniform1f(loc, interpolatedParameters[13]);
// Set texture identifiers
GLint texture_location;
texture_location = glGetUniformLocation(programID, "Noise3DTexture");
glUniform1i(texture_location, 0);
texture_location = glGetUniformLocation(programID, "DepthSensorTexture");
glUniform1i(texture_location, 1);
texture_location = glGetUniformLocation(programID, "BGTexture");
glUniform1i(texture_location, 2);
// render to larger offscreen texture
glActiveTexture(GL_TEXTURE2);
textureManager.getTextureID("hermaniak.tga", &textureID, errorText);
glBindTexture(GL_TEXTURE_2D, textureID);
glActiveTexture(GL_TEXTURE1);
//textureManager.getTextureID(TM_DEPTH_SENSOR_NAME, &textureID, errorText);
glBindTexture(GL_TEXTURE_2D, textureID);
glActiveTexture(GL_TEXTURE0);
textureManager.getTextureID(TM_NOISE3D_NAME, &textureID, errorText);
glBindTexture(GL_TEXTURE_3D, textureID);
#if 0
if (usedIndex > 4) {
glViewport(0, 0, X_HIGHLIGHT, Y_HIGHLIGHT);
}
else {
glViewport(0, 0, X_OFFSCREEN, Y_OFFSCREEN);
}
#endif
// TODO: Here is the rendering done!
float red = 1.0f + sinf(ftime * 0.3f) * interpolatedParameters[12];
float green = 1.0f + sinf(ftime * 0.4f) * interpolatedParameters[12];
float blue = 1.0f - sinf(ftime * 0.3f) * interpolatedParameters[12];
glClearColor(red, green, blue, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
shaderManager.getProgramID("DitherTexture.gprg", &programID, errorText);
glUseProgram(programID);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
glDisable(GL_BLEND);
glDisable(GL_CULL_FACE);
//glEnable(GL_BLEND);
//glBlendFunc(GL_DST_COLOR, GL_ZERO);
glDisable(GL_BLEND);
if (ftime - music_start_time_ > 159.0f ||
ftime - music_start_time_ < 0.5f) { // Do the fluid stuff
#if 0
fluid_simulation_.UpdateTime(fdelta_time);
fluid_simulation_.GetTexture();
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex2f(-1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex2f(1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex2f(1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex2f(-1.0f, 1.0f);
glEnd();
#endif
const float line_length = 0.35f;
float rotation_speed = 0.09f + 1.0f * interpolatedParameters[13];
static float rotation = 0.0f;
if (rotation > 2.0f * 3.1415928f) rotation -= 2.0f * 3.1415928f;
float distance1 = interpolatedParameters[2] * 0.5f + 1.0f;
float distance2 = interpolatedParameters[3] * 0.5f + 1.0f;
if (ftime >= otone_start_time_ &&
ftime < real_otone_start_time_) {
// The theatre just started, init the rotation to where it should be
rotation = 2.0f * 3.141529f - 1.5f;
real_otone_start_time_ = ftime;
}
float incoming1 = (real_otone_start_time_ - ftime) * 0.03f + 0.75f;
if (incoming1 < 0.0f) incoming1 = 0.0f;
incoming1 *= incoming1;
distance1 += 1.1f * incoming1 / line_length;
// slow down in the beginning
float inverter = 1.0f;
if (!rotation_stopped_) {
rotation += rotation_speed * fdelta_time * 3.1415f * 2.0f * (1.0f - incoming1);
}
else {
inverter = -1.0f;
//distance1 += 0.1f;
//distance2 -= 0.5f;
rotation += 3.1415f * 0.4f;
}
float center1_move_x = sinf(ftime * 1.7f) * interpolatedParameters[6] * 0.4f;
float center1_move_y = sinf(ftime * 0.57f) * interpolatedParameters[6] * 0.4f;
float center2_move_x = sinf(ftime * 1.97f) * interpolatedParameters[6] * 0.4f;
float center2_move_y = sinf(ftime * 0.3f) * interpolatedParameters[6] * 0.4f;
static float masako_rotation_error = 0.0f;
if (ftime >= masako_start_time_ &&
ftime < real_masako_start_time_) {
// The theatre just started, init the rotation to where it should be
float destination_rotation = 2.0f * 3.141529f - 1.5f;
if (rotation - 1.0f < destination_rotation) {
masako_rotation_error = destination_rotation - rotation;
} else {
masako_rotation_error = destination_rotation - rotation + 2.0f * 3.141529f;
}
// Only start Masako if she is about at the right position
if (fabsf(masako_rotation_error) < 0.5f) {
real_masako_start_time_ = ftime;
}
}
float incoming2 = (real_masako_start_time_ - ftime) * 0.03f + 0.75f;
if (incoming2 < 0.0f) incoming2 = 0.0f;
incoming2 *= incoming2;
distance2 += 1.1f * incoming2 / line_length;
float masako_rotation = rotation + 3.1415f;
float rotation_adaptation = 1.0f - 0.03f * (ftime - real_masako_start_time_);
if (rotation_adaptation < 0.0f) rotation_adaptation = 0.0f;
rotation_adaptation = 1.0f - cosf(rotation_adaptation * 3.1415f / 2.0f);
masako_rotation += rotation_adaptation * masako_rotation_error;
// Interpolation with the music stuff
float interpolation = 1.0f - (ftime - music_start_time_ - 159.0f) * 0.03f;
if (interpolation < 0.0f || ftime - music_start_time_ < 0.5f) interpolation = 0.0f;
interpolation *= interpolation;
float length_difference = 1.2f * interpolatedParameters[4];
if (ftime >= real_otone_start_time_) {
DrawTearCircle(rotation + inverter * (1.6f - length_difference) / distance1,
rotation - inverter * (1.6f - length_difference) / distance1,
0.35f * distance1,
-0.7f * incoming1 - center1_move_x, -0.8f * incoming1 - center1_move_y,
0, interpolation, ftime,
1.0f - length_difference * 0.2f);
}
if (ftime >= real_masako_start_time_) {
DrawTearCircle(masako_rotation + inverter * (1.6f + length_difference) / distance2,
masako_rotation - inverter * (1.6f + length_difference) / distance2,
0.35f * distance2,
0.7f * incoming2 - center2_move_x, 0.8f * incoming2 - center2_move_y,
1, interpolation, ftime,
1.0f + length_difference * 0.2f);
}
if (rotation_stopped_) {
rotation -= 3.1415f * 0.4f;
}
} else { // Do the rigit dance stuff
#if 0
glViewport(0, 0, X_HIGHLIGHT, Y_HIGHLIGHT);
DrawMusic(ftime - music_start_time_);
textureManager.getTextureID(TM_HIGHLIGHT_NAME, &textureID, errorText);
glBindTexture(GL_TEXTURE_2D, textureID);
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, X_HIGHLIGHT, Y_HIGHLIGHT);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, fluid_simulation_.GetBackBuffer());
fluid_simulation_.SetBackBuffer();
#endif
int xres = windowRect.right - windowRect.left;
int yres = windowRect.bottom - windowRect.top;
glViewport(0, 0, xres, yres);
DrawMusic(ftime - music_start_time_);
}
if (ftime > black_start_time_) {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
}
if (ftime > ending_start_time_)
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
shaderManager.getProgramID("SimpleTexture.gprg", &programID, errorText);
glUseProgram(programID);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
// Draw icon
char errorString[MAX_ERROR_LENGTH + 1];
GLuint texID;
textureManager.getTextureID("icon.tga", &texID, errorString);
glBindTexture(GL_TEXTURE_2D, texID);
float alpha;
if (ftime - ending_start_time_ < 0.4f) alpha = 0.0f;
else alpha = 1.0f;
drawQuad(-0.5f, 0.5f, -0.5f, 0.91f, 0.0f, 1.0f, alpha);
// Draw first highlight
textureManager.getTextureID("icon_highlight1.tga", &texID, errorString);
glBindTexture(GL_TEXTURE_2D, texID);
if (ftime - ending_start_time_ < 0.3f) alpha = (ftime - ending_start_time_) / 0.3f;
else alpha = 1.1f - (ftime - ending_start_time_ - 0.3f) * 0.5f;
if (alpha < 0.0f) alpha = 0.0f;
if (alpha > 1.0f) alpha = 1.0f;
alpha = 0.5f - 0.5f * (float)cos(alpha * 3.14159);
drawQuad(-0.5f, 0.5f, -0.5f, 0.91f, 0.0f, 1.0f, alpha*0.75f);
// Draw second highlight
textureManager.getTextureID("icon_highlight2.tga", &texID, errorString);
glBindTexture(GL_TEXTURE_2D, texID);
if (ftime - ending_start_time_ < 0.4f) alpha = (ftime - ending_start_time_ - 0.3f) / 0.1f;
else alpha = 1.2f - (ftime - ending_start_time_ - 0.4f) * 1.2f;
if (alpha < 0.0f) alpha = 0.0f;
if (alpha > 1.0f) alpha = 1.0f;
alpha = 0.5f - 0.5f * (float)cos(alpha * 3.14159);
alpha *= 0.75f;
drawQuad(-0.5f, 0.5f, -0.5f, 0.91f, 0.0f, 1.0f, alpha*0.75f);
// draw some sparkles
textureManager.getTextureID("sparkle.tga", &texID, errorString);
glBindTexture(GL_TEXTURE_2D, texID);
float sparkleTime = (ftime - ending_start_time_ - 0.4f) * 0.4f;
for (int i = 0; i < 16; i++)
{
float sparkleDuration = 1.3f + 0.4f * sinf(i*2.4f + 2.3f);
if (sparkleTime > 0.0f && sparkleTime < sparkleDuration)
{
float amount = sqrtf(sinf((sparkleTime / sparkleDuration * 3.1415f)));
float iconDistance = 0.5f;
float ASPECT_RATIO = 240.0f / 170.0f;
float centerX = -0.3f + iconDistance * (0.55f + 0.35f * sinf(i*2.1f + 7.3f));
centerX += (0.7f + 0.15f*sinf(i*1.4f + 8.3f)) * iconDistance / sparkleDuration * sparkleTime -
0.1f * sparkleTime*sparkleTime / sparkleDuration / sparkleDuration;
float centerY = 0.5f + iconDistance * ASPECT_RATIO * (0.8f + 0.3f * sinf(i*4.6f + 2.9f) - 1.0f);
centerY += (0.5f + 0.2f*sinf(i*6.8f + 3.0f)) * iconDistance / sparkleDuration * sparkleTime * ASPECT_RATIO -
0.2f * sparkleTime*sparkleTime / sparkleDuration / sparkleDuration;
float width = iconDistance * 0.25f;
drawQuad(centerX - width, centerX + width,
centerY - width * ASPECT_RATIO, centerY + width * ASPECT_RATIO,
0.0f, 1.0f, amount);
}
}
glDisable(GL_BLEND);
}
#if 0
glEnable(GL_BLEND);
glBlendFunc(GL_DST_COLOR, GL_ZERO);
shaderManager.getProgramID("SimpleTexture.gprg", &programID, errorText);
glUseProgram(programID);
textureManager.getTextureID("blatt.tga", &textureID, errorText);
glBindTexture(GL_TEXTURE_2D, textureID);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex2f(-1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex2f(1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex2f(1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex2f(-1.0f, 1.0f);
glEnd();
#endif
#if 0
// Copy backbuffer to texture
if (usedIndex > 4) {
textureManager.getTextureID(TM_HIGHLIGHT_NAME, &textureID, errorText);
glBindTexture(GL_TEXTURE_2D, textureID);
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, X_HIGHLIGHT, Y_HIGHLIGHT);
} else {
textureManager.getTextureID(TM_OFFSCREEN_NAME, &textureID, errorText);
glBindTexture(GL_TEXTURE_2D, textureID);
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, X_OFFSCREEN, Y_OFFSCREEN);
}
// Copy backbuffer to front (so far no improvement)
int xres = windowRect.right - windowRect.left;
int yres = windowRect.bottom - windowRect.top;
glViewport(0, 0, xres, yres);
shaderManager.getProgramID("SimpleTexture.gprg", &programID, errorText);
glUseProgram(programID);
loc = glGetUniformLocation(programID, "time");
glUniform1f(loc, (float)(t * 0.001f));
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
glDisable(GL_BLEND);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex2f(-1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex2f(1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex2f(1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex2f(-1.0f, 1.0f);
glEnd();
#endif
}
int WINAPI WinMain( HINSTANCE instance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
MSG msg;
int done=0;
WININFO *info = &wininfo;
info->hInstance = GetModuleHandle( 0 );
//if( MessageBox( 0, "fullscreen?", info->wndclass, MB_YESNO|MB_ICONQUESTION)==IDYES ) info->full++;
if (!window_init(info))
{
window_end(info);
MessageBox(0, "window_init()!", "error", MB_OK|MB_ICONEXCLAMATION);
return 0;
}
if (initGL(info))
{
return 0;
}
//intro_init();
// Initialize COM
HRESULT hr = CoInitialize(NULL);
if (FAILED(hr)) exit(-1);
// Example editor usage
char errorText[MAX_ERROR_LENGTH+1];
char filename[SM_MAX_FILENAME_LENGTH+1];
sprintf_s(filename, SM_MAX_FILENAME_LENGTH, "shaders/%s", usedShader[usedIndex]);
if (editor.loadText(filename, errorText))
{
MessageBox(info->hWnd, errorText, "Editor init", MB_OK);
return -1;
}
start_time_ = timeGetTime();
long last_time = 0;
while( !done )
{
long t = timeGetTime() - start_time_;
while( PeekMessage(&msg,0,0,0,PM_REMOVE) )
{
if( msg.message==WM_QUIT ) done=1;
TranslateMessage( &msg );
DispatchMessage( &msg );
}
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
intro_do(t, t - last_time);
editor.render(t);
last_time = t;
SwapBuffers( info->hDC );
}
window_end( info );
#ifdef MUSIC
// music uninit
BASS_Free();
#endif
// Un-initialize COM
CoUninitialize();
return( 0 );
}
// Note that a key was pressed
void registerParameterChange(int keyID)
{
const int beatKey = 41;
const int blobKey = 40;
const int minBeatTime = 100;
const int maxBeatTime = 5000;
int sortedBeatDurations[NUM_BEAT_TIMES];
// get the blobber
if (params.getParam(blobKey) > 0.5f) blob = 1.f;
// Do nothing on key release!
if (params.getParam(beatKey) < 0.5f) return;
if (keyID == beatKey)
{
int t = timeGetTime();
int timeDiff = t - lastBeatTime;
if (timeDiff > minBeatTime && timeDiff < maxBeatTime)
{
for (int i = 0; i < NUM_BEAT_TIMES-1; i++)
{
beatDurations[i] = beatDurations[i+1];
}
beatDurations[NUM_BEAT_TIMES-1] = timeDiff;
}
lastBeatTime = t;
}
// copy sorted beat durations
for (int i = 0; i < NUM_BEAT_TIMES; i++)
{
sortedBeatDurations[i] = beatDurations[i];
}
// Calculate median of beat durations by bubble sorting.
bool sorted = false;
while (!sorted)
{
sorted = true;
for (int i = 0; i < NUM_BEAT_TIMES-1; i++)
{
if (sortedBeatDurations[i] < sortedBeatDurations[i+1]) {
int tmp = sortedBeatDurations[i+1];
sortedBeatDurations[i+1] = sortedBeatDurations[i];
sortedBeatDurations[i] = tmp;
sorted = false;
}
}
}
BPM = 60.0f * 1000.0f / sortedBeatDurations[NUM_BEAT_TIMES/2];
}
Slightly shorter Beginning
// LiveCoding.cpp : Definiert den Einstiegspunkt fr die Anwendung.
//
#include "stdafx.h"
#include "LiveCoding.h"
#include "Configuration.h"
#include "glext.h"
#include "GLNames.h"
#include "ShaderManager.h"
#include "TextureManager.h"
//#include "FluidSimulation.h"
#include "Editor.h"
#include "Parameter.h"
#include "bass.h"
#define MAX_LOADSTRING 100
#define BLOB_FADE_SPEED 1.0f
// The used effect (will be changeable later on)
#define NUM_USED_PROGRAMS 10
char *usedShader[NUM_USED_PROGRAMS] = {"empty.jlsl", "vp1.jlsl", "vp2.jlsl", "vp3.jlsl", "vp4.jlsl", "vp5.jlsl", "vp6.jlsl", "vp7.jlsl", "vp8.jlsl", "vp9.jlsl"};
char *usedProgram[NUM_USED_PROGRAMS] = {"empty.gprg", "vp1.gprg", "vp2.gprg", "vp3.gprg", "vp4.gprg", "vp5.gprg", "vp6.gprg", "vp7.gprg", "vp8.gprg", "vp9.gprg"};
int usedIndex = 0;
float aspectRatio = (float)XRES / (float)YRES;
float music_start_time_ = -10000.0f;
float otone_start_time_ = 1.0e20f;
float real_otone_start_time_ = 1.0e20f; // triggered by close-to-entrance rotation
float masako_start_time_ = 1.0e20f;
float real_masako_start_time_ = 1.0e20f; // triggered by close-to-entrance rotation
// Time when theatre goes black (end)
float black_start_time_ = 1.0e20f;
// Set to true if the animation stops
bool rotation_stopped_ = false;
// Engawa logo
float ending_start_time_ = 1.0e20f;
long start_time_ = 0;
//FluidSimulation fluid_simulation_;
HSTREAM mp3Str;
// Of the music stuff
const int kNumEdges = 8;
const int kNumSegmentsPerEdge = 16;
const int kNumSegments = kNumEdges * kNumSegmentsPerEdge;
// Created by music, used by floaty stuff
float interpolation_quad_[2][kNumSegments][4][2];
/*************************************************
* GL Core variables
*************************************************/
GenFP glFP[NUM_GL_NAMES]; // pointer to openGL functions
const static char* glnames[NUM_GL_NAMES]={
"glCreateShader", "glCreateProgram", "glShaderSource", "glCompileShader",
"glAttachShader", "glLinkProgram", "glUseProgram",
"glTexImage3D", "glGetShaderiv","glGetShaderInfoLog",
"glDeleteProgram", "glDeleteShader",
"glActiveTexture", "glGetUniformLocation", "glUniform1i", "glUniform1f",
"glMultiTexCoord2f"
};
/*************************************************
* The core managing units that hold the resources
*************************************************/
ShaderManager shaderManager;
TextureManager textureManager;
Editor editor;
/*************************************************
* Window core variables
*************************************************/
HINSTANCE hInst; // Aktuelle Instanz
TCHAR szTitle[MAX_LOADSTRING]; // Titelleistentext
TCHAR szWindowClass[MAX_LOADSTRING]; // Klassenname des Hauptfensters
// The size of the window that we render to...
RECT windowRect;
typedef struct
{
//---------------
HINSTANCE hInstance;
HDC hDC;
HGLRC hRC;
HWND hWnd;
//---------------
int full;
//---------------
char wndclass[4]; // window class and title :)
//---------------
}WININFO;
static const PIXELFORMATDESCRIPTOR pfd =
{
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
24,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, // accum
0, // zbuffer
0, // stencil!
0, // aux
PFD_MAIN_PLANE,
0, 0, 0, 0
};
static WININFO wininfo = { 0,0,0,0,0,
{'l','c','_',0}
};
/**************************************************
* Parameters from the midi stuff
****************************************************/
// ---------------------------------------------------------------
// Parameter interpolation stuff
// ------------------------------------------------------------
// I want to interpolate the new values from the old ones.
const int maxNumParameters = 25;
const static float defaultParameters[maxNumParameters] =
{
-1.0f, -1.0f,
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, // 2-6 ~= 1-5
-1.0f,
0.0f, 0.0f, // 8,9 ~= 6,7
-1.0f, -1.0f,
0.0f, 0.0f, // 12,13 ~= 8-9
0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f, // 14-22 ~= 1b-9b
};
float interpolatedParameters[maxNumParameters];
const int NUM_KEYS = 127;
static int keyPressed[NUM_KEYS] = {0};
// BPM stuff
const int NUM_BEAT_TIMES = 7;
float BPM = 0.0f;
int beatDurations[NUM_BEAT_TIMES] = {900, 1200, 1100, 1000, 1400, 1000, 1000};
int lastBeatTime = 0;
float blob = 0.;
/*************************************************
* OpenGL initialization
*************************************************/
static int initGL(WININFO *winInfo)
{
char errorString[MAX_ERROR_LENGTH + 1];
// Create openGL functions
for (int i=0; i<NUM_GL_NAMES; i++) glFP[i] = (GenFP)wglGetProcAddress(glnames[i]);
// Create and initialize the shader manager
if (shaderManager.init(errorString))
{
MessageBox(winInfo->hWnd, errorString, "Shader Manager Load", MB_OK);
return -1;
}
// Create and initialize everything needed for texture Management
if (textureManager.init(errorString))
{
MessageBox(winInfo->hWnd, errorString, "Texture Manager Load", MB_OK);
return -1;
}
// Create the text editor
if (editor.init(&shaderManager, &textureManager, errorString))
{
MessageBox(winInfo->hWnd, errorString, "Editor init", MB_OK);
return -1;
}
blob = 0.;
// Create the fluid simulation stuff
//fluid_simulation_.Init(false);
return 0;
}
/*************************************************
* Windows callback
*************************************************/
static LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
int time = timeGetTime() - start_time_;
float ftime = 0.001f * time;
// salvapantallas
if( uMsg==WM_SYSCOMMAND && (wParam==SC_SCREENSAVE || wParam==SC_MONITORPOWER) )
return( 0 );
// boton x o pulsacion de escape
//if( uMsg==WM_CLOSE || uMsg==WM_DESTROY || (uMsg==WM_KEYDOWN && wParam==VK_ESCAPE) )
if( uMsg==WM_CLOSE || uMsg==WM_DESTROY )
{
PostQuitMessage(0);
return( 0 );
}
// Reaction to command keys
if( uMsg==WM_KEYDOWN )
{
switch (wParam)
{
#if 0
case VK_ESCAPE:
PostQuitMessage(0);
return 0;
#endif
case VK_LEFT:
case VK_RIGHT:
case VK_UP:
case VK_DOWN:
case VK_PRIOR:
case VK_NEXT:
case VK_END:
case VK_HOME:
break;
case VK_RETURN:
case VK_DELETE:
case VK_BACK:
break;
case 'q':
case 'Q':
music_start_time_ = 0.001f * (timeGetTime() - start_time_);
black_start_time_ = 1.0e20f;
ending_start_time_ = 1.0e20f;
rotation_stopped_ = false;
// start music playback
#ifdef MUSIC
BASS_Init(-1, 44100, 0, hWnd, NULL);
mp3Str = BASS_StreamCreateFile(FALSE, "Goethe_music.mp3", 0, 0, 0);
BASS_ChannelPlay(mp3Str, TRUE);
BASS_Start();
#endif
break;
case 'w':
case 'W':
music_start_time_ = -10000.0f;
black_start_time_ = 1.0e20f;
ending_start_time_ = 1.0e20f;
rotation_stopped_ = false;
#ifdef MUSIC
BASS_Stop();
BASS_ChannelStop(mp3Str);
BASS_StreamFree(mp3Str);
BASS_Free();
#endif
break;
case 'a':
case 'A':
//fluid_simulation_.request_set_points_ = true;
otone_start_time_ = 1.0e20f;
real_otone_start_time_ = otone_start_time_;
masako_start_time_ = 1.0e20f;
real_masako_start_time_ = masako_start_time_;
black_start_time_ = 1.0e20f;
ending_start_time_ = 1.0e20f;
rotation_stopped_ = false;
break;
case 's':
case 'S':
otone_start_time_ = 0.001f * (timeGetTime() - start_time_);
black_start_time_ = 1.0e20f;
ending_start_time_ = 1.0e20f;
rotation_stopped_ = false;
break;
case 'd':
case 'D':
masako_start_time_ = 0.001f * (timeGetTime() - start_time_);
black_start_time_ = 1.0e20f;
ending_start_time_ = 1.0e20f;
rotation_stopped_ = false;
break;
case 'o':
case 'O':
//fluid_simulation_.Init(false);
rotation_stopped_ = false;
break;
case 'p':
case 'P':
//fluid_simulation_.Init(true);
rotation_stopped_ = true;
break;
case 'x':
case 'X':
//fluid_simulation_.PushApart();
black_start_time_ = 0.001f * (timeGetTime() - start_time_);
ending_start_time_ = 1.0e20f;
rotation_stopped_ = true;
break;
case 'c':
case 'C':
//fluid_simulation_.PushApart();
ending_start_time_ = 0.001f * (timeGetTime() - start_time_);
break;
case 'm':
case 'M':
if (GetAsyncKeyState(VK_CONTROL) < 0) {
// TODO: Minimization again.
SetWindowLong(hWnd, GWL_STYLE, WS_POPUP | WS_VISIBLE);
ShowWindow(hWnd, SW_MAXIMIZE);
GetClientRect(hWnd, &windowRect);
glViewport(0, 0, windowRect.right - windowRect.left, abs(windowRect.bottom - windowRect.top)); //NEW
aspectRatio = (float)(windowRect.right - windowRect.left) / (float)(abs(windowRect.bottom - windowRect.top));
ShowCursor(false);
}
break;
default:
break;
}
}
if (uMsg == WM_KEYUP) {
switch(wParam) {
default:
break;
}
}
return( DefWindowProc(hWnd,uMsg,wParam,lParam) );
}
static void window_end( WININFO *info )
{
if( info->hRC )
{
wglMakeCurrent( 0, 0 );
wglDeleteContext( info->hRC );
}
if( info->hDC ) ReleaseDC( info->hWnd, info->hDC );
if( info->hWnd ) DestroyWindow( info->hWnd );
UnregisterClass( info->wndclass, info->hInstance );
if( info->full )
{
ChangeDisplaySettings( 0, 0 );
ShowCursor( 1 );
}
}
static int window_init( WININFO *info )
{
unsigned int PixelFormat;
DWORD dwExStyle, dwStyle;
DEVMODE dmScreenSettings;
RECT rec;
WNDCLASS wc;
ZeroMemory( &wc, sizeof(WNDCLASS) );
wc.style = CS_OWNDC|CS_HREDRAW|CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.hInstance = info->hInstance;
wc.lpszClassName = info->wndclass;
if( !RegisterClass(&wc) )
return( 0 );
if( info->full )
{
dmScreenSettings.dmSize = sizeof(DEVMODE);
dmScreenSettings.dmFields = DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
dmScreenSettings.dmBitsPerPel = 24;
dmScreenSettings.dmPelsWidth = XRES;
dmScreenSettings.dmPelsHeight = YRES;
if( ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
return( 0 );
dwExStyle = WS_EX_APPWINDOW;
dwStyle = WS_VISIBLE | WS_POPUP;// | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
ShowCursor( 0 );
}
else
{
dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
dwStyle = WS_VISIBLE | WS_CAPTION | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_SYSMENU;
}
rec.left = 0;
rec.top = 0;
rec.right = XRES;
rec.bottom = YRES;
AdjustWindowRect( &rec, dwStyle, 0 );
windowRect.left = 0;
windowRect.top = 0;
windowRect.right = XRES;
windowRect.bottom = YRES;
info->hWnd = CreateWindowEx( dwExStyle, wc.lpszClassName, "live coding", dwStyle,
(GetSystemMetrics(SM_CXSCREEN)-rec.right+rec.left)>>1,
(GetSystemMetrics(SM_CYSCREEN)-rec.bottom+rec.top)>>1,
rec.right-rec.left, rec.bottom-rec.top, 0, 0, info->hInstance, 0 );
if( !info->hWnd )
return( 0 );
if( !(info->hDC=GetDC(info->hWnd)) )
return( 0 );
if( !(PixelFormat=ChoosePixelFormat(info->hDC,&pfd)) )
return( 0 );
if( !SetPixelFormat(info->hDC,PixelFormat,&pfd) )
return( 0 );
if( !(info->hRC=wglCreateContext(info->hDC)) )
return( 0 );
if( !wglMakeCurrent(info->hDC,info->hRC) )
return( 0 );
return( 1 );
}
void drawQuad(float startX, float endX, float startY, float endY, float startV, float endV, float alpha)
{
// set up matrices
glEnable(GL_TEXTURE_2D);
glColor4f(1.0f, 1.0f, 1.0f, alpha);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, endV);
glVertex3f(startX, endY * aspectRatio / 4 * 3 - 0.1f, 0.99f);
glTexCoord2f(1.0f, endV);
glVertex3f(endX, endY * aspectRatio / 4 * 3 - 0.1f, 0.99f);
glTexCoord2f(1.0f, startV);
glVertex3f(endX, startY * aspectRatio / 4 * 3 - 0.1f, 0.99f);
glTexCoord2f(0.0, startV);
glVertex3f(startX, startY * aspectRatio / 4 * 3 - 0.1f, 0.99f);
glEnd();
}
// interpolation with the interpolation_quad
void DrawTearCircle(float start_angle, float end_angle, float distance,
float center_x, float center_y,
int person, float interpolation,
float ftime,
float thickness) {
float kTearWidth = 0.04f * thickness;
if (ftime > black_start_time_) {
kTearWidth += (ftime - black_start_time_) * (ftime - black_start_time_) * 0.02f;
start_angle += (ftime - black_start_time_) * (ftime - black_start_time_) * 0.1f;
end_angle -= (ftime - black_start_time_) * (ftime - black_start_time_) * 0.1f;
}
float cur_angle = start_angle;
float delta_angle = (end_angle - start_angle) / kNumSegments;
float tear_delta_position = 1.0f / (kNumSegments + 1);
float tear_position = tear_delta_position / 4.0f;
// Initialize OGL stuff
GLuint programID;
char errorText[MAX_ERROR_LENGTH + 1];
shaderManager.getProgramID("SimpleTexture.gprg", &programID, errorText);
glUseProgram(programID);
glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
glBegin(GL_QUADS);
for (int i = 0; i < kNumSegments; i++) {
float left_angle = cur_angle;
float right_angle = cur_angle + delta_angle;
float tear_left_pos = tear_position; // nothing for 0.
float tear_right_pos = tear_left_pos + tear_delta_position;
float left_width = kTearWidth * sinf(tear_left_pos * 3.1415f) / sqrtf(tear_left_pos);
float right_width = kTearWidth * sinf(tear_right_pos * 3.1415f) / sqrtf(tear_right_pos);
float left_pos[2] = {
distance * sinf(left_angle) + center_x,
distance * cosf(left_angle) + center_y
};
float right_pos[2] = {
distance * sinf(right_angle) + center_x,
distance * cosf(right_angle) + center_y
};
float left_normal[2] = { sinf(left_angle), cosf(left_angle) };
float right_normal[2] = { sinf(right_angle), cosf(right_angle) };
float t = interpolation;
float k = 1.0f - t;
float vertices[4][2] = {
{left_pos[0] - left_width * left_normal[0], (left_pos[1] - left_width * left_normal[1]) * aspectRatio},
{left_pos[0] + left_width * left_normal[0], (left_pos[1] + left_width * left_normal[1]) * aspectRatio},
{right_pos[0] + right_width * right_normal[0], (right_pos[1] + right_width * right_normal[1]) * aspectRatio},
{right_pos[0] - right_width * right_normal[0],(right_pos[1] - right_width * right_normal[1]) * aspectRatio}
};
glVertex2f(t * interpolation_quad_[person][i][0][0] + k * vertices[0][0], t * interpolation_quad_[person][i][0][1] + k * vertices[0][1]);
glVertex2f(t * interpolation_quad_[person][i][1][0] + k * vertices[1][0], t * interpolation_quad_[person][i][1][1] + k * vertices[1][1]);
glVertex2f(t * interpolation_quad_[person][i][2][0] + k * vertices[2][0], t * interpolation_quad_[person][i][2][1] + k * vertices[2][1]);
glVertex2f(t * interpolation_quad_[person][i][3][0] + k * vertices[3][0], t * interpolation_quad_[person][i][3][1] + k * vertices[3][1]);
cur_angle = right_angle;
tear_position = tear_right_pos;
}
glEnd();
}
void DrawMusic(float ftime) {
float delta_angle = 3.141592f * 2.0f / kNumEdges;
const float music_beat = 0.405f;
const float rotation_speed = 0.1f;
// Initialize OGL stuff
GLuint programID;
char errorText[MAX_ERROR_LENGTH + 1];
shaderManager.getProgramID("SimpleTexture.gprg", &programID, errorText);
glUseProgram(programID);
glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
glBegin(GL_QUADS);
// Just a 5-edge thingie
for (int person = 0; person < 2; person++) {
//float divergence = person * -sinf(ftime * 3.1415f / 160.0f * 8.0f);
//if (divergence < 0.0f) divergence = 0.0f;
float divergence = person * sinf(ftime * 3.1415f / 160.0f * 7.5f);
divergence *= divergence;
if (ftime < 20.0f) divergence = 0.0f;
int interpolation_quad_id = 0;
for (int edge = 0; edge < kNumEdges; edge++) {
float start_angle = edge * delta_angle;
int next_edge = edge + 1;
if (edge == kNumEdges - 1) next_edge = 0;
float end_angle = next_edge * delta_angle;
float beat_overdrive = sinf(ftime * 3.1415f / 160.0f) * 2.0f + .5f;
if (ftime > 80.0f) beat_overdrive = 1.0f;
float rotation = rotation_speed * 3.1415f * 2.0f * ftime;
float beat = sinf(ftime * 3.1415f * 2.0f / music_beat);
//beat *= beat * beat;
rotation += rotation_speed * beat * music_beat * beat_overdrive * 0.35f;
start_angle -= rotation;
end_angle -= rotation;
float start_line[2] = { cosf(start_angle), sinf(start_angle) };
float end_line[2] = { cosf(end_angle), sinf(end_angle) };
float star_amount = 0.2f * sinf(ftime * 3.1415f / 160.0f);
if (ftime > 80.0f) star_amount = 0.2f;
float inner_dist_start = 0.27f + star_amount * sinf(0.2f * ftime + 3.1415f * 2.0f * edge / kNumEdges * 10 + divergence*star_amount);
float inner_dist_end = 0.27f + star_amount * sinf(0.2f * ftime + 3.1415f * 2.0f * next_edge / kNumEdges * 10 + divergence*star_amount);
float outer_dist_start = 0.35f + star_amount * sinf(0.2f * ftime + 3.1415f * 2.0f * edge / kNumEdges * 10 + divergence);
float outer_dist_end = 0.35f + star_amount * sinf(0.2f * ftime + 3.1415f * 2.0f * next_edge / kNumEdges * 10 + divergence);
float size_overdrive = sinf(ftime * 3.1415f / 160.0f) * 2.0f + .4f;
float size = 1.0f + 0.2f * size_overdrive +
size_overdrive * (0.25f * sinf(ftime * 0.4f + divergence * 3.14f) + 0.15f * sinf(ftime * 0.25f + divergence * 3.14f));
inner_dist_start *= size;
inner_dist_end *= size;
outer_dist_start *= size;
outer_dist_end *= size;
float vertices[4][2] = {
{start_line[0] * inner_dist_start, start_line[1] * inner_dist_start * aspectRatio},
{start_line[0] * outer_dist_start, start_line[1] * outer_dist_start * aspectRatio},
{end_line[0] * outer_dist_end, end_line[1] * outer_dist_end * aspectRatio},
{end_line[0] * inner_dist_end, end_line[1] * inner_dist_end * aspectRatio}
};
for (int segment = 0; segment < kNumSegmentsPerEdge; segment++) {
float t_start = (float)segment / (float)(kNumSegmentsPerEdge);
float k_start = 1.0f - t_start;
float t_end = (float)(segment + 1) / (float)(kNumSegmentsPerEdge);
float k_end = 1.0f - t_end;
interpolation_quad_[person][interpolation_quad_id][0][0] = k_start * vertices[0][0] + t_start * vertices[3][0];
interpolation_quad_[person][interpolation_quad_id][0][1] = k_start * vertices[0][1] + t_start * vertices[3][1];
interpolation_quad_[person][interpolation_quad_id][1][0] = k_start * vertices[1][0] + t_start * vertices[2][0];
interpolation_quad_[person][interpolation_quad_id][1][1] = k_start * vertices[1][1] + t_start * vertices[2][1];
interpolation_quad_[person][interpolation_quad_id][3][0] = k_end * vertices[0][0] + t_end * vertices[3][0];
interpolation_quad_[person][interpolation_quad_id][3][1] = k_end * vertices[0][1] + t_end * vertices[3][1];
interpolation_quad_[person][interpolation_quad_id][2][0] = k_end * vertices[1][0] + t_end * vertices[2][0];
interpolation_quad_[person][interpolation_quad_id][2][1] = k_end * vertices[1][1] + t_end * vertices[2][1];
glVertex2f(interpolation_quad_[person][interpolation_quad_id][0][0], interpolation_quad_[person][interpolation_quad_id][0][1]);
glVertex2f(interpolation_quad_[person][interpolation_quad_id][1][0], interpolation_quad_[person][interpolation_quad_id][1][1]);
glVertex2f(interpolation_quad_[person][interpolation_quad_id][2][0], interpolation_quad_[person][interpolation_quad_id][2][1]);
glVertex2f(interpolation_quad_[person][interpolation_quad_id][3][0], interpolation_quad_[person][interpolation_quad_id][3][1]);
interpolation_quad_id++;
}
}
}
glEnd();
}
// Anfang langsamer
// Anfang Masako immer synchron, kein berlappen!
// Nach Musik langsamer
// Black aprupt
// Streit kein Kreis - ggf. zwei unterschiedliche Zentren fr die Kreise
// Bei Masako eh voraussichtlich Kreis 70* drehen
// Feste Parameter, dass ich nur noch auf Tasten drcken muss...
// Abstand ruckartig, ca. 3 unterschiedliche Stufen. Geschwindigkeit immer gleich?
// --> Zusammengehen immer langsam.
// --> Problem nach dem Streit: Zusammen <-> Auseinander hin-und-her: Wie mach ich das?
// Mittwoch: 19:00
// Donnerstag: Ab 18:00 Sprichst mit Masako
// Freitag: 9-11
void intro_do(long t, long delta_time)
{
char errorText[MAX_ERROR_LENGTH + 1];
float ftime = 0.001f*(float)t;
float fdelta_time = 0.001f * (float)(delta_time);
GLuint textureID;
glDisable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
// Those are key-Press indicators. I only act on 0-to-1.
for (int i = 0; i < maxNumParameters; i++)
{
interpolatedParameters[i] = expf(-2.0f*fdelta_time) * interpolatedParameters[i] +
(1.0f - expf(-2.0f*fdelta_time)) * params.getParam(i, defaultParameters[i]);
}
// Update key press events.
for (int i = 0; i < NUM_KEYS; i++)
{
if (params.getParam(i, 0.0) > 0.5f) keyPressed[i]++;
else keyPressed[i] = 0;
}
// BPM => spike calculation
float BPS = BPM / 60.0f;
float jumpsPerSecond = BPS / 1.0f; // Jump on every fourth beat.
static float phase = 0.0f;
float jumpTime = (ftime * jumpsPerSecond) + phase;
jumpTime -= (float)floor(jumpTime);
if (keyPressed[41] == 1)
{
phase -= jumpTime;
jumpTime = 0.0f;
if (phase < 0.0f) phase += 1.0;
}
jumpTime = jumpTime * jumpTime;
// spike is between 0.0 and 1.0 depending on the position within whatever.
float spike = 0.5f * cosf(jumpTime * 3.1415926f * 1.5f) + 0.5f;
// blob is growing down from 1. after keypress
static float lastFTime = 0.f;
blob *= (float)exp(-(float)(ftime - lastFTime) * BLOB_FADE_SPEED);
lastFTime = ftime;
// Set the program uniforms
GLuint programID;
shaderManager.getProgramID(usedProgram[usedIndex], &programID, errorText);
glUseProgram(programID);
GLuint loc = glGetUniformLocation(programID, "aspectRatio");
glUniform1f(loc, aspectRatio);
loc = glGetUniformLocation(programID, "time");
glUniform1f(loc, (float)(t * 0.001f));
// For now I am just sending the spike to the shader. I might need something better...
loc = glGetUniformLocation(programID, "spike");
glUniform1f(loc, spike);
loc = glGetUniformLocation(programID, "blob");
glUniform1f(loc, blob);
loc = glGetUniformLocation(programID, "knob1");
glUniform1f(loc, interpolatedParameters[14]);
loc = glGetUniformLocation(programID, "knob2");
glUniform1f(loc, interpolatedParameters[15]);
loc = glGetUniformLocation(programID, "knob3");
glUniform1f(loc, interpolatedParameters[16]);
loc = glGetUniformLocation(programID, "knob4");
glUniform1f(loc, interpolatedParameters[17]);
loc = glGetUniformLocation(programID, "knob5");
glUniform1f(loc, interpolatedParameters[18]);
loc = glGetUniformLocation(programID, "knob6");
glUniform1f(loc, interpolatedParameters[19]);
loc = glGetUniformLocation(programID, "knob7");
glUniform1f(loc, interpolatedParameters[20]);
loc = glGetUniformLocation(programID, "knob8");
glUniform1f(loc, interpolatedParameters[21]);
loc = glGetUniformLocation(programID, "knob9");
glUniform1f(loc, interpolatedParameters[22]);
loc = glGetUniformLocation(programID, "slider1");
glUniform1f(loc, interpolatedParameters[2]);
loc = glGetUniformLocation(programID, "slider2");
glUniform1f(loc, interpolatedParameters[3]);
loc = glGetUniformLocation(programID, "slider3");
glUniform1f(loc, interpolatedParameters[4]);
loc = glGetUniformLocation(programID, "slider4");
glUniform1f(loc, interpolatedParameters[5]);
loc = glGetUniformLocation(programID, "slider5");
glUniform1f(loc, interpolatedParameters[6]);
loc = glGetUniformLocation(programID, "slider6");
glUniform1f(loc, interpolatedParameters[8]);
loc = glGetUniformLocation(programID, "slider7");
glUniform1f(loc, interpolatedParameters[9]);
loc = glGetUniformLocation(programID, "slider8");
glUniform1f(loc, interpolatedParameters[12]);
loc = glGetUniformLocation(programID, "slider9");
glUniform1f(loc, interpolatedParameters[13]);
// Set texture identifiers
GLint texture_location;
texture_location = glGetUniformLocation(programID, "Noise3DTexture");
glUniform1i(texture_location, 0);
texture_location = glGetUniformLocation(programID, "DepthSensorTexture");
glUniform1i(texture_location, 1);
texture_location = glGetUniformLocation(programID, "BGTexture");
glUniform1i(texture_location, 2);
// render to larger offscreen texture
glActiveTexture(GL_TEXTURE2);
textureManager.getTextureID("hermaniak.tga", &textureID, errorText);
glBindTexture(GL_TEXTURE_2D, textureID);
glActiveTexture(GL_TEXTURE1);
//textureManager.getTextureID(TM_DEPTH_SENSOR_NAME, &textureID, errorText);
glBindTexture(GL_TEXTURE_2D, textureID);
glActiveTexture(GL_TEXTURE0);
textureManager.getTextureID(TM_NOISE3D_NAME, &textureID, errorText);
glBindTexture(GL_TEXTURE_3D, textureID);
#if 0
if (usedIndex > 4) {
glViewport(0, 0, X_HIGHLIGHT, Y_HIGHLIGHT);
}
else {
glViewport(0, 0, X_OFFSCREEN, Y_OFFSCREEN);
}
#endif
// TODO: Here is the rendering done!
float red = 1.0f + sinf(ftime * 0.3f) * interpolatedParameters[12];
float green = 1.0f + sinf(ftime * 0.4f) * interpolatedParameters[12];
float blue = 1.0f - sinf(ftime * 0.3f) * interpolatedParameters[12];
glClearColor(red, green, blue, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
shaderManager.getProgramID("DitherTexture.gprg", &programID, errorText);
glUseProgram(programID);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
glDisable(GL_BLEND);
glDisable(GL_CULL_FACE);
//glEnable(GL_BLEND);
//glBlendFunc(GL_DST_COLOR, GL_ZERO);
glDisable(GL_BLEND);
if (ftime - music_start_time_ > 159.0f ||
ftime - music_start_time_ < 0.5f) { // Do the fluid stuff
#if 0
fluid_simulation_.UpdateTime(fdelta_time);
fluid_simulation_.GetTexture();
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex2f(-1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex2f(1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex2f(1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex2f(-1.0f, 1.0f);
glEnd();
#endif
const float line_length = 0.35f;
float rotation_speed = 0.09f + 1.0f * interpolatedParameters[13];
static float rotation = 0.0f;
if (rotation > 2.0f * 3.1415928f) rotation -= 2.0f * 3.1415928f;
float distance1 = interpolatedParameters[2] * 0.5f + 1.0f;
float distance2 = interpolatedParameters[3] * 0.5f + 1.0f;
if (ftime >= otone_start_time_ &&
ftime < real_otone_start_time_) {
// The theatre just started, init the rotation to where it should be
rotation = 2.0f * 3.141529f - 1.5f;
real_otone_start_time_ = ftime;
}
float incoming1 = (real_otone_start_time_ - ftime) * 0.04f + 0.75f;
if (incoming1 < 0.0f) incoming1 = 0.0f;
incoming1 *= incoming1;
distance1 += 1.1f * incoming1 / line_length;
// slow down in the beginning
float inverter = 1.0f;
if (!rotation_stopped_) {
rotation += rotation_speed * fdelta_time * 3.1415f * 2.0f * (1.0f - incoming1);
}
else {
inverter = -1.0f;
//distance1 += 0.1f;
//distance2 -= 0.5f;
rotation += 3.1415f * 0.4f;
}
float center1_move_x = sinf(ftime * 1.7f) * interpolatedParameters[6] * 0.4f;
float center1_move_y = sinf(ftime * 0.57f) * interpolatedParameters[6] * 0.4f;
float center2_move_x = sinf(ftime * 1.97f) * interpolatedParameters[6] * 0.4f;
float center2_move_y = sinf(ftime * 0.3f) * interpolatedParameters[6] * 0.4f;
static float masako_rotation_error = 0.0f;
if (ftime >= masako_start_time_ &&
ftime < real_masako_start_time_) {
// The theatre just started, init the rotation to where it should be
float destination_rotation = 2.0f * 3.141529f - 1.5f;
if (rotation - 1.0f < destination_rotation) {
masako_rotation_error = destination_rotation - rotation;
} else {
masako_rotation_error = destination_rotation - rotation + 2.0f * 3.141529f;
}
// Only start Masako if she is about at the right position
if (fabsf(masako_rotation_error) < 0.5f) {
real_masako_start_time_ = ftime;
}
}
float incoming2 = (real_masako_start_time_ - ftime) * 0.04f + 0.75f;
if (incoming2 < 0.0f) incoming2 = 0.0f;
incoming2 *= incoming2;
distance2 += 1.1f * incoming2 / line_length;
float masako_rotation = rotation + 3.1415f;
float rotation_adaptation = 1.0f - 0.03f * (ftime - real_masako_start_time_);
if (rotation_adaptation < 0.0f) rotation_adaptation = 0.0f;
rotation_adaptation = 1.0f - cosf(rotation_adaptation * 3.1415f / 2.0f);
masako_rotation += rotation_adaptation * masako_rotation_error;
// Interpolation with the music stuff
float interpolation = 1.0f - (ftime - music_start_time_ - 159.0f) * 0.03f;
if (interpolation < 0.0f || ftime - music_start_time_ < 0.5f) interpolation = 0.0f;
interpolation *= interpolation;
float length_difference = 1.2f * interpolatedParameters[4];
if (ftime >= real_otone_start_time_) {
DrawTearCircle(rotation + inverter * (1.6f - length_difference) / distance1,
rotation - inverter * (1.6f - length_difference) / distance1,
0.35f * distance1,
-0.7f * incoming1 - center1_move_x, -0.8f * incoming1 - center1_move_y,
0, interpolation, ftime,
1.0f - length_difference * 0.2f);
}
if (ftime >= real_masako_start_time_) {
DrawTearCircle(masako_rotation + inverter * (1.6f + length_difference) / distance2,
masako_rotation - inverter * (1.6f + length_difference) / distance2,
0.35f * distance2,
0.7f * incoming2 - center2_move_x, 0.8f * incoming2 - center2_move_y,
1, interpolation, ftime,
1.0f + length_difference * 0.2f);
}
if (rotation_stopped_) {
rotation -= 3.1415f * 0.4f;
}
} else { // Do the rigit dance stuff
#if 0
glViewport(0, 0, X_HIGHLIGHT, Y_HIGHLIGHT);
DrawMusic(ftime - music_start_time_);
textureManager.getTextureID(TM_HIGHLIGHT_NAME, &textureID, errorText);
glBindTexture(GL_TEXTURE_2D, textureID);
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, X_HIGHLIGHT, Y_HIGHLIGHT);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, fluid_simulation_.GetBackBuffer());
fluid_simulation_.SetBackBuffer();
#endif
int xres = windowRect.right - windowRect.left;
int yres = windowRect.bottom - windowRect.top;
glViewport(0, 0, xres, yres);
DrawMusic(ftime - music_start_time_);
}
if (ftime > black_start_time_) {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
}
if (ftime > ending_start_time_)
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
shaderManager.getProgramID("SimpleTexture.gprg", &programID, errorText);
glUseProgram(programID);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
// Draw icon
char errorString[MAX_ERROR_LENGTH + 1];
GLuint texID;
textureManager.getTextureID("icon.tga", &texID, errorString);
glBindTexture(GL_TEXTURE_2D, texID);
float alpha;
if (ftime - ending_start_time_ < 0.4f) alpha = 0.0f;
else alpha = 1.0f;
drawQuad(-0.5f, 0.5f, -0.5f, 0.91f, 0.0f, 1.0f, alpha);
// Draw first highlight
textureManager.getTextureID("icon_highlight1.tga", &texID, errorString);
glBindTexture(GL_TEXTURE_2D, texID);
if (ftime - ending_start_time_ < 0.3f) alpha = (ftime - ending_start_time_) / 0.3f;
else alpha = 1.1f - (ftime - ending_start_time_ - 0.3f) * 0.5f;
if (alpha < 0.0f) alpha = 0.0f;
if (alpha > 1.0f) alpha = 1.0f;
alpha = 0.5f - 0.5f * (float)cos(alpha * 3.14159);
drawQuad(-0.5f, 0.5f, -0.5f, 0.91f, 0.0f, 1.0f, alpha*0.75f);
// Draw second highlight
textureManager.getTextureID("icon_highlight2.tga", &texID, errorString);
glBindTexture(GL_TEXTURE_2D, texID);
if (ftime - ending_start_time_ < 0.4f) alpha = (ftime - ending_start_time_ - 0.3f) / 0.1f;
else alpha = 1.2f - (ftime - ending_start_time_ - 0.4f) * 1.2f;
if (alpha < 0.0f) alpha = 0.0f;
if (alpha > 1.0f) alpha = 1.0f;
alpha = 0.5f - 0.5f * (float)cos(alpha * 3.14159);
alpha *= 0.75f;
drawQuad(-0.5f, 0.5f, -0.5f, 0.91f, 0.0f, 1.0f, alpha*0.75f);
// draw some sparkles
textureManager.getTextureID("sparkle.tga", &texID, errorString);
glBindTexture(GL_TEXTURE_2D, texID);
float sparkleTime = (ftime - ending_start_time_ - 0.4f) * 0.4f;
for (int i = 0; i < 16; i++)
{
float sparkleDuration = 1.3f + 0.4f * sinf(i*2.4f + 2.3f);
if (sparkleTime > 0.0f && sparkleTime < sparkleDuration)
{
float amount = sqrtf(sinf((sparkleTime / sparkleDuration * 3.1415f)));
float iconDistance = 0.5f;
float ASPECT_RATIO = 240.0f / 170.0f;
float centerX = -0.3f + iconDistance * (0.55f + 0.35f * sinf(i*2.1f + 7.3f));
centerX += (0.7f + 0.15f*sinf(i*1.4f + 8.3f)) * iconDistance / sparkleDuration * sparkleTime -
0.1f * sparkleTime*sparkleTime / sparkleDuration / sparkleDuration;
float centerY = 0.5f + iconDistance * ASPECT_RATIO * (0.8f + 0.3f * sinf(i*4.6f + 2.9f) - 1.0f);
centerY += (0.5f + 0.2f*sinf(i*6.8f + 3.0f)) * iconDistance / sparkleDuration * sparkleTime * ASPECT_RATIO -
0.2f * sparkleTime*sparkleTime / sparkleDuration / sparkleDuration;
float width = iconDistance * 0.25f;
drawQuad(centerX - width, centerX + width,
centerY - width * ASPECT_RATIO, centerY + width * ASPECT_RATIO,
0.0f, 1.0f, amount);
}
}
glDisable(GL_BLEND);
}
#if 0
glEnable(GL_BLEND);
glBlendFunc(GL_DST_COLOR, GL_ZERO);
shaderManager.getProgramID("SimpleTexture.gprg", &programID, errorText);
glUseProgram(programID);
textureManager.getTextureID("blatt.tga", &textureID, errorText);
glBindTexture(GL_TEXTURE_2D, textureID);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex2f(-1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex2f(1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex2f(1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex2f(-1.0f, 1.0f);
glEnd();
#endif
#if 0
// Copy backbuffer to texture
if (usedIndex > 4) {
textureManager.getTextureID(TM_HIGHLIGHT_NAME, &textureID, errorText);
glBindTexture(GL_TEXTURE_2D, textureID);
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, X_HIGHLIGHT, Y_HIGHLIGHT);
} else {
textureManager.getTextureID(TM_OFFSCREEN_NAME, &textureID, errorText);
glBindTexture(GL_TEXTURE_2D, textureID);
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, X_OFFSCREEN, Y_OFFSCREEN);
}
// Copy backbuffer to front (so far no improvement)
int xres = windowRect.right - windowRect.left;
int yres = windowRect.bottom - windowRect.top;
glViewport(0, 0, xres, yres);
shaderManager.getProgramID("SimpleTexture.gprg", &programID, errorText);
glUseProgram(programID);
loc = glGetUniformLocation(programID, "time");
glUniform1f(loc, (float)(t * 0.001f));
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
glDisable(GL_BLEND);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex2f(-1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex2f(1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex2f(1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex2f(-1.0f, 1.0f);
glEnd();
#endif
}
int WINAPI WinMain( HINSTANCE instance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
MSG msg;
int done=0;
WININFO *info = &wininfo;
info->hInstance = GetModuleHandle( 0 );
//if( MessageBox( 0, "fullscreen?", info->wndclass, MB_YESNO|MB_ICONQUESTION)==IDYES ) info->full++;
if (!window_init(info))
{
window_end(info);
MessageBox(0, "window_init()!", "error", MB_OK|MB_ICONEXCLAMATION);
return 0;
}
if (initGL(info))
{
return 0;
}
//intro_init();
// Initialize COM
HRESULT hr = CoInitialize(NULL);
if (FAILED(hr)) exit(-1);
// Example editor usage
char errorText[MAX_ERROR_LENGTH+1];
char filename[SM_MAX_FILENAME_LENGTH+1];
sprintf_s(filename, SM_MAX_FILENAME_LENGTH, "shaders/%s", usedShader[usedIndex]);
if (editor.loadText(filename, errorText))
{
MessageBox(info->hWnd, errorText, "Editor init", MB_OK);
return -1;
}
start_time_ = timeGetTime();
long last_time = 0;
while( !done )
{
long t = timeGetTime() - start_time_;
while( PeekMessage(&msg,0,0,0,PM_REMOVE) )
{
if( msg.message==WM_QUIT ) done=1;
TranslateMessage( &msg );
DispatchMessage( &msg );
}
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
intro_do(t, t - last_time);
editor.render(t);
last_time = t;
SwapBuffers( info->hDC );
}
window_end( info );
#ifdef MUSIC
// music uninit
BASS_Free();
#endif
// Un-initialize COM
CoUninitialize();
return( 0 );
}
// Note that a key was pressed
void registerParameterChange(int keyID)
{
const int beatKey = 41;
const int blobKey = 40;
const int minBeatTime = 100;
const int maxBeatTime = 5000;
int sortedBeatDurations[NUM_BEAT_TIMES];
// get the blobber
if (params.getParam(blobKey) > 0.5f) blob = 1.f;
// Do nothing on key release!
if (params.getParam(beatKey) < 0.5f) return;
if (keyID == beatKey)
{
int t = timeGetTime();
int timeDiff = t - lastBeatTime;
if (timeDiff > minBeatTime && timeDiff < maxBeatTime)
{
for (int i = 0; i < NUM_BEAT_TIMES-1; i++)
{
beatDurations[i] = beatDurations[i+1];
}
beatDurations[NUM_BEAT_TIMES-1] = timeDiff;
}
lastBeatTime = t;
}
// copy sorted beat durations
for (int i = 0; i < NUM_BEAT_TIMES; i++)
{
sortedBeatDurations[i] = beatDurations[i];
}
// Calculate median of beat durations by bubble sorting.
bool sorted = false;
while (!sorted)
{
sorted = true;
for (int i = 0; i < NUM_BEAT_TIMES-1; i++)
{
if (sortedBeatDurations[i] < sortedBeatDurations[i+1]) {
int tmp = sortedBeatDurations[i+1];
sortedBeatDurations[i+1] = sortedBeatDurations[i];
sortedBeatDurations[i] = tmp;
sorted = false;
}
}
}
BPM = 60.0f * 1000.0f / sortedBeatDurations[NUM_BEAT_TIMES/2];
} |
/*
* File: RTPPackage.cpp
* Author: daniel
*
* Created on May 02, 2015, 13:03 PM
*/
#include "RTPPackageHandler.h"
RTPPackageHandler::RTPPackageHandler(unsigned int sizeOfAudioData, PayloadType payloadType, unsigned int sizeOfRTPHeader)
{
this->sizeOfAudioData = sizeOfAudioData;
this->sizeOfRTPHeader = sizeOfRTPHeader;
this->size = sizeOfAudioData + sizeOfRTPHeader;
this->payloadType = payloadType;
newRTPPackageBuffer = new char[size];
workBuffer = new char[size];
unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count();
std::mt19937 tmp(seed1);
this->randomGenerator = tmp;
sequenceNr = getRandomNumber();
timestamp = getTimestamp();
ssrc = getAudioSourceId();
}
auto RTPPackageHandler::getNewRTPPackage(void* audioData) -> void*
{
RTPHeader RTPHeaderObject;
RTPHeaderObject.version = 2;
RTPHeaderObject.padding = 0;
RTPHeaderObject.extension = 0;
RTPHeaderObject.csrc_count = 0;
RTPHeaderObject.marker = 0;
RTPHeaderObject.payload_type = this->payloadType;
RTPHeaderObject.sequence_number = (this->sequenceNr++) % UINT16_MAX;
//we need steady clock so it will always change monotonically (etc. no change to/from daylight savings time)
//additionally, we need to count with milliseconds precision
RTPHeaderObject.timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
RTPHeaderObject.ssrc = this->ssrc;
// Copy RTPHeader and Audiodata in the buffer
memcpy((char*)newRTPPackageBuffer, &RTPHeaderObject, this->sizeOfRTPHeader);
memcpy((char*)(newRTPPackageBuffer)+sizeOfRTPHeader, audioData, this->sizeOfAudioData);
return newRTPPackageBuffer;
}
auto RTPPackageHandler::getRTPPackageData(void *rtpPackage) -> void*
{
if (rtpPackage == nullptr)
{
return (char*)workBuffer + sizeOfRTPHeader;
}
memcpy((char*)(workBuffer) + sizeOfRTPHeader, (char*)rtpPackage + sizeOfRTPHeader, sizeOfAudioData);
return (char*)(workBuffer)+sizeOfRTPHeader;
}
auto RTPPackageHandler::getRTPPackageHeader(void *rtpPackage) -> RTPHeader*
{
if (rtpPackage == nullptr)
{
return (RTPHeader*)workBuffer;
}
memcpy((char*)(workBuffer), (char*)rtpPackage, sizeOfRTPHeader);
return (RTPHeader*)workBuffer;
}
unsigned int RTPPackageHandler::getRandomNumber()
{
return this->randomGenerator();
}
unsigned int RTPPackageHandler::getTimestamp()
{
//start timestamp should be a random number
return this->randomGenerator();
}
unsigned int RTPPackageHandler::getAudioSourceId()
{
//SSRC should be a random number
return this->randomGenerator();
}
auto RTPPackageHandler::getSize() -> unsigned int const
{
return size;
}
auto RTPPackageHandler::getSizeOfRTPHeader() -> unsigned int const
{
return sizeOfRTPHeader;
}
auto RTPPackageHandler::getSizeOfAudioData() -> unsigned int const
{
return sizeOfAudioData;
}
auto RTPPackageHandler::getWorkBuffer() -> void*
{
return this->workBuffer;
}
Added random starting timestamp to meet RTP standard
Signed-off-by:doe300 <ea171286d560108c4b22a58de6300bfe96efc821@web.de>
/*
* File: RTPPackage.cpp
* Author: daniel
*
* Created on May 02, 2015, 13:03 PM
*/
#include "RTPPackageHandler.h"
RTPPackageHandler::RTPPackageHandler(unsigned int sizeOfAudioData, PayloadType payloadType, unsigned int sizeOfRTPHeader)
{
this->sizeOfAudioData = sizeOfAudioData;
this->sizeOfRTPHeader = sizeOfRTPHeader;
this->size = sizeOfAudioData + sizeOfRTPHeader;
this->payloadType = payloadType;
newRTPPackageBuffer = new char[size];
workBuffer = new char[size];
unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count();
std::mt19937 tmp(seed1);
this->randomGenerator = tmp;
sequenceNr = getRandomNumber();
timestamp = getTimestamp();
ssrc = getAudioSourceId();
}
auto RTPPackageHandler::getNewRTPPackage(void* audioData) -> void*
{
RTPHeader RTPHeaderObject;
RTPHeaderObject.version = 2;
RTPHeaderObject.padding = 0;
RTPHeaderObject.extension = 0;
RTPHeaderObject.csrc_count = 0;
RTPHeaderObject.marker = 0;
RTPHeaderObject.payload_type = this->payloadType;
RTPHeaderObject.sequence_number = (this->sequenceNr++) % UINT16_MAX;
//we need steady clock so it will always change monotonically (etc. no change to/from daylight savings time)
//additionally, we need to count with milliseconds precision
//we add the random starting timestamp to meet the condition specified in the RTP standard
RTPHeaderObject.timestamp = this->timestamp + std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
RTPHeaderObject.ssrc = this->ssrc;
// Copy RTPHeader and Audiodata in the buffer
memcpy((char*)newRTPPackageBuffer, &RTPHeaderObject, this->sizeOfRTPHeader);
memcpy((char*)(newRTPPackageBuffer)+sizeOfRTPHeader, audioData, this->sizeOfAudioData);
return newRTPPackageBuffer;
}
auto RTPPackageHandler::getRTPPackageData(void *rtpPackage) -> void*
{
if (rtpPackage == nullptr)
{
return (char*)workBuffer + sizeOfRTPHeader;
}
memcpy((char*)(workBuffer) + sizeOfRTPHeader, (char*)rtpPackage + sizeOfRTPHeader, sizeOfAudioData);
return (char*)(workBuffer)+sizeOfRTPHeader;
}
auto RTPPackageHandler::getRTPPackageHeader(void *rtpPackage) -> RTPHeader*
{
if (rtpPackage == nullptr)
{
return (RTPHeader*)workBuffer;
}
memcpy((char*)(workBuffer), (char*)rtpPackage, sizeOfRTPHeader);
return (RTPHeader*)workBuffer;
}
unsigned int RTPPackageHandler::getRandomNumber()
{
return this->randomGenerator();
}
unsigned int RTPPackageHandler::getTimestamp()
{
//start timestamp should be a random number
return this->randomGenerator();
}
unsigned int RTPPackageHandler::getAudioSourceId()
{
//SSRC should be a random number
return this->randomGenerator();
}
auto RTPPackageHandler::getSize() -> unsigned int const
{
return size;
}
auto RTPPackageHandler::getSizeOfRTPHeader() -> unsigned int const
{
return sizeOfRTPHeader;
}
auto RTPPackageHandler::getSizeOfAudioData() -> unsigned int const
{
return sizeOfAudioData;
}
auto RTPPackageHandler::getWorkBuffer() -> void*
{
return this->workBuffer;
} |
// Copyright 2016 The SwiftShader 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 "Renderer.hpp"
#include "Clipper.hpp"
#include "Math.hpp"
#include "FrameBuffer.hpp"
#include "Timer.hpp"
#include "Surface.hpp"
#include "Half.hpp"
#include "Primitive.hpp"
#include "Polygon.hpp"
#include "SwiftConfig.hpp"
#include "MutexLock.hpp"
#include "CPUID.hpp"
#include "Memory.hpp"
#include "Resource.hpp"
#include "Constants.hpp"
#include "Debug.hpp"
#include "Reactor/Reactor.hpp"
#undef max
bool disableServer = true;
#ifndef NDEBUG
unsigned int minPrimitives = 1;
unsigned int maxPrimitives = 1 << 21;
#endif
namespace sw
{
extern bool halfIntegerCoordinates; // Pixel centers are not at integer coordinates
extern bool symmetricNormalizedDepth; // [-1, 1] instead of [0, 1]
extern bool booleanFaceRegister;
extern bool fullPixelPositionRegister;
extern bool leadingVertexFirst; // Flat shading uses first vertex, else last
extern bool secondaryColor; // Specular lighting is applied after texturing
extern bool forceWindowed;
extern bool complementaryDepthBuffer;
extern bool postBlendSRGB;
extern bool exactColorRounding;
extern TransparencyAntialiasing transparencyAntialiasing;
extern bool forceClearRegisters;
extern bool precacheVertex;
extern bool precacheSetup;
extern bool precachePixel;
int batchSize = 128;
int threadCount = 1;
int unitCount = 1;
int clusterCount = 1;
TranscendentalPrecision logPrecision = ACCURATE;
TranscendentalPrecision expPrecision = ACCURATE;
TranscendentalPrecision rcpPrecision = ACCURATE;
TranscendentalPrecision rsqPrecision = ACCURATE;
bool perspectiveCorrection = true;
struct Parameters
{
Renderer *renderer;
int threadIndex;
};
DrawCall::DrawCall()
{
queries = 0;
vsDirtyConstF = VERTEX_UNIFORM_VECTORS + 1;
vsDirtyConstI = 16;
vsDirtyConstB = 16;
psDirtyConstF = FRAGMENT_UNIFORM_VECTORS;
psDirtyConstI = 16;
psDirtyConstB = 16;
references = -1;
data = (DrawData*)allocate(sizeof(DrawData));
data->constants = &constants;
}
DrawCall::~DrawCall()
{
delete queries;
deallocate(data);
}
Renderer::Renderer(Context *context, Conventions conventions, bool exactColorRounding) : VertexProcessor(context), PixelProcessor(context), SetupProcessor(context), context(context), viewport()
{
sw::halfIntegerCoordinates = conventions.halfIntegerCoordinates;
sw::symmetricNormalizedDepth = conventions.symmetricNormalizedDepth;
sw::booleanFaceRegister = conventions.booleanFaceRegister;
sw::fullPixelPositionRegister = conventions.fullPixelPositionRegister;
sw::leadingVertexFirst = conventions.leadingVertexFirst;
sw::secondaryColor = conventions.secondaryColor;
sw::exactColorRounding = exactColorRounding;
setRenderTarget(0, 0);
clipper = new Clipper(symmetricNormalizedDepth);
updateViewMatrix = true;
updateBaseMatrix = true;
updateProjectionMatrix = true;
updateClipPlanes = true;
#if PERF_HUD
resetTimers();
#endif
for(int i = 0; i < 16; i++)
{
vertexTask[i] = 0;
worker[i] = 0;
resume[i] = 0;
suspend[i] = 0;
}
threadsAwake = 0;
resumeApp = new Event();
currentDraw = 0;
nextDraw = 0;
qHead = 0;
qSize = 0;
for(int i = 0; i < 16; i++)
{
triangleBatch[i] = 0;
primitiveBatch[i] = 0;
}
for(int draw = 0; draw < DRAW_COUNT; draw++)
{
drawCall[draw] = new DrawCall();
drawList[draw] = drawCall[draw];
}
for(int unit = 0; unit < 16; unit++)
{
primitiveProgress[unit].init();
}
for(int cluster = 0; cluster < 16; cluster++)
{
pixelProgress[cluster].init();
}
clipFlags = 0;
swiftConfig = new SwiftConfig(disableServer);
updateConfiguration(true);
sync = new Resource(0);
}
Renderer::~Renderer()
{
sync->destruct();
delete clipper;
clipper = 0;
terminateThreads();
delete resumeApp;
for(int draw = 0; draw < DRAW_COUNT; draw++)
{
delete drawCall[draw];
}
delete swiftConfig;
}
// This object has to be mem aligned
void* Renderer::operator new(size_t size)
{
ASSERT(size == sizeof(Renderer)); // This operator can't be called from a derived class
return sw::allocate(sizeof(Renderer), 16);
}
void Renderer::operator delete(void * mem)
{
sw::deallocate(mem);
}
void Renderer::clear(void *pixel, Format format, Surface *dest, const SliceRect &dRect, unsigned int rgbaMask)
{
blitter.clear(pixel, format, dest, dRect, rgbaMask);
}
void Renderer::blit(Surface *source, const SliceRect &sRect, Surface *dest, const SliceRect &dRect, bool filter, bool isStencil)
{
blitter.blit(source, sRect, dest, dRect, filter, isStencil);
}
void Renderer::blit3D(Surface *source, Surface *dest)
{
blitter.blit3D(source, dest);
}
void Renderer::draw(DrawType drawType, unsigned int indexOffset, unsigned int count, bool update)
{
#ifndef NDEBUG
if(count < minPrimitives || count > maxPrimitives)
{
return;
}
#endif
context->drawType = drawType;
updateConfiguration();
updateClipper();
int ss = context->getSuperSampleCount();
int ms = context->getMultiSampleCount();
for(int q = 0; q < ss; q++)
{
unsigned int oldMultiSampleMask = context->multiSampleMask;
context->multiSampleMask = (context->sampleMask >> (ms * q)) & ((unsigned)0xFFFFFFFF >> (32 - ms));
if(!context->multiSampleMask)
{
continue;
}
sync->lock(sw::PRIVATE);
if(update || oldMultiSampleMask != context->multiSampleMask)
{
vertexState = VertexProcessor::update(drawType);
setupState = SetupProcessor::update();
pixelState = PixelProcessor::update();
vertexRoutine = VertexProcessor::routine(vertexState);
setupRoutine = SetupProcessor::routine(setupState);
pixelRoutine = PixelProcessor::routine(pixelState);
}
int batch = batchSize / ms;
int (Renderer::*setupPrimitives)(int batch, int count);
if(context->isDrawTriangle())
{
switch(context->fillMode)
{
case FILL_SOLID:
setupPrimitives = &Renderer::setupSolidTriangles;
break;
case FILL_WIREFRAME:
setupPrimitives = &Renderer::setupWireframeTriangle;
batch = 1;
break;
case FILL_VERTEX:
setupPrimitives = &Renderer::setupVertexTriangle;
batch = 1;
break;
default:
ASSERT(false);
return;
}
}
else if(context->isDrawLine())
{
setupPrimitives = &Renderer::setupLines;
}
else // Point draw
{
setupPrimitives = &Renderer::setupPoints;
}
DrawCall *draw = 0;
do
{
for(int i = 0; i < DRAW_COUNT; i++)
{
if(drawCall[i]->references == -1)
{
draw = drawCall[i];
drawList[nextDraw % DRAW_COUNT] = draw;
break;
}
}
if(!draw)
{
resumeApp->wait();
}
}
while(!draw);
DrawData *data = draw->data;
if(queries.size() != 0)
{
draw->queries = new std::list<Query*>();
bool includePrimitivesWrittenQueries = vertexState.transformFeedbackQueryEnabled && vertexState.transformFeedbackEnabled;
for(std::list<Query*>::iterator query = queries.begin(); query != queries.end(); query++)
{
Query* q = *query;
if(includePrimitivesWrittenQueries || (q->type != Query::TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN))
{
atomicIncrement(&(q->reference));
draw->queries->push_back(q);
}
}
}
draw->drawType = drawType;
draw->batchSize = batch;
vertexRoutine->bind();
setupRoutine->bind();
pixelRoutine->bind();
draw->vertexRoutine = vertexRoutine;
draw->setupRoutine = setupRoutine;
draw->pixelRoutine = pixelRoutine;
draw->vertexPointer = (VertexProcessor::RoutinePointer)vertexRoutine->getEntry();
draw->setupPointer = (SetupProcessor::RoutinePointer)setupRoutine->getEntry();
draw->pixelPointer = (PixelProcessor::RoutinePointer)pixelRoutine->getEntry();
draw->setupPrimitives = setupPrimitives;
draw->setupState = setupState;
for(int i = 0; i < MAX_VERTEX_INPUTS; i++)
{
draw->vertexStream[i] = context->input[i].resource;
data->input[i] = context->input[i].buffer;
data->stride[i] = context->input[i].stride;
if(draw->vertexStream[i])
{
draw->vertexStream[i]->lock(PUBLIC, PRIVATE);
}
}
if(context->indexBuffer)
{
data->indices = (unsigned char*)context->indexBuffer->lock(PUBLIC, PRIVATE) + indexOffset;
}
draw->indexBuffer = context->indexBuffer;
for(int sampler = 0; sampler < TOTAL_IMAGE_UNITS; sampler++)
{
draw->texture[sampler] = 0;
}
for(int sampler = 0; sampler < TEXTURE_IMAGE_UNITS; sampler++)
{
if(pixelState.sampler[sampler].textureType != TEXTURE_NULL)
{
draw->texture[sampler] = context->texture[sampler];
draw->texture[sampler]->lock(PUBLIC, isReadWriteTexture(sampler) ? MANAGED : PRIVATE); // If the texure is both read and written, use the same read/write lock as render targets
data->mipmap[sampler] = context->sampler[sampler].getTextureData();
}
}
if(context->pixelShader)
{
if(draw->psDirtyConstF)
{
memcpy(&data->ps.cW, PixelProcessor::cW, sizeof(word4) * 4 * (draw->psDirtyConstF < 8 ? draw->psDirtyConstF : 8));
memcpy(&data->ps.c, PixelProcessor::c, sizeof(float4) * draw->psDirtyConstF);
draw->psDirtyConstF = 0;
}
if(draw->psDirtyConstI)
{
memcpy(&data->ps.i, PixelProcessor::i, sizeof(int4) * draw->psDirtyConstI);
draw->psDirtyConstI = 0;
}
if(draw->psDirtyConstB)
{
memcpy(&data->ps.b, PixelProcessor::b, sizeof(bool) * draw->psDirtyConstB);
draw->psDirtyConstB = 0;
}
PixelProcessor::lockUniformBuffers(data->ps.u, draw->pUniformBuffers);
}
else
{
for(int i = 0; i < MAX_UNIFORM_BUFFER_BINDINGS; i++)
{
draw->pUniformBuffers[i] = nullptr;
}
}
if(context->pixelShaderVersion() <= 0x0104)
{
for(int stage = 0; stage < 8; stage++)
{
if(pixelState.textureStage[stage].stageOperation != TextureStage::STAGE_DISABLE || context->pixelShader)
{
data->textureStage[stage] = context->textureStage[stage].uniforms;
}
else break;
}
}
if(context->vertexShader)
{
if(context->vertexShader->getVersion() >= 0x0300)
{
for(int sampler = 0; sampler < VERTEX_TEXTURE_IMAGE_UNITS; sampler++)
{
if(vertexState.samplerState[sampler].textureType != TEXTURE_NULL)
{
draw->texture[TEXTURE_IMAGE_UNITS + sampler] = context->texture[TEXTURE_IMAGE_UNITS + sampler];
draw->texture[TEXTURE_IMAGE_UNITS + sampler]->lock(PUBLIC, PRIVATE);
data->mipmap[TEXTURE_IMAGE_UNITS + sampler] = context->sampler[TEXTURE_IMAGE_UNITS + sampler].getTextureData();
}
}
}
if(draw->vsDirtyConstF)
{
memcpy(&data->vs.c, VertexProcessor::c, sizeof(float4) * draw->vsDirtyConstF);
draw->vsDirtyConstF = 0;
}
if(draw->vsDirtyConstI)
{
memcpy(&data->vs.i, VertexProcessor::i, sizeof(int4) * draw->vsDirtyConstI);
draw->vsDirtyConstI = 0;
}
if(draw->vsDirtyConstB)
{
memcpy(&data->vs.b, VertexProcessor::b, sizeof(bool) * draw->vsDirtyConstB);
draw->vsDirtyConstB = 0;
}
if(context->vertexShader->isInstanceIdDeclared())
{
data->instanceID = context->instanceID;
}
VertexProcessor::lockUniformBuffers(data->vs.u, draw->vUniformBuffers);
VertexProcessor::lockTransformFeedbackBuffers(data->vs.t, data->vs.reg, data->vs.row, data->vs.col, data->vs.str, draw->transformFeedbackBuffers);
}
else
{
data->ff = ff;
draw->vsDirtyConstF = VERTEX_UNIFORM_VECTORS + 1;
draw->vsDirtyConstI = 16;
draw->vsDirtyConstB = 16;
for(int i = 0; i < MAX_UNIFORM_BUFFER_BINDINGS; i++)
{
draw->vUniformBuffers[i] = nullptr;
}
for(int i = 0; i < MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS; i++)
{
draw->transformFeedbackBuffers[i] = nullptr;
}
}
if(pixelState.stencilActive)
{
data->stencil[0] = stencil;
data->stencil[1] = stencilCCW;
}
if(pixelState.fogActive)
{
data->fog = fog;
}
if(setupState.isDrawPoint)
{
data->point = point;
}
data->lineWidth = context->lineWidth;
data->factor = factor;
if(pixelState.transparencyAntialiasing == TRANSPARENCY_ALPHA_TO_COVERAGE)
{
float ref = context->alphaReference * (1.0f / 255.0f);
float margin = sw::min(ref, 1.0f - ref);
if(ms == 4)
{
data->a2c0 = replicate(ref - margin * 0.6f);
data->a2c1 = replicate(ref - margin * 0.2f);
data->a2c2 = replicate(ref + margin * 0.2f);
data->a2c3 = replicate(ref + margin * 0.6f);
}
else if(ms == 2)
{
data->a2c0 = replicate(ref - margin * 0.3f);
data->a2c1 = replicate(ref + margin * 0.3f);
}
else ASSERT(false);
}
if(pixelState.occlusionEnabled)
{
for(int cluster = 0; cluster < clusterCount; cluster++)
{
data->occlusion[cluster] = 0;
}
}
#if PERF_PROFILE
for(int cluster = 0; cluster < clusterCount; cluster++)
{
for(int i = 0; i < PERF_TIMERS; i++)
{
data->cycles[i][cluster] = 0;
}
}
#endif
// Viewport
{
float W = 0.5f * viewport.width;
float H = 0.5f * viewport.height;
float X0 = viewport.x0 + W;
float Y0 = viewport.y0 + H;
float N = viewport.minZ;
float F = viewport.maxZ;
float Z = F - N;
if(context->isDrawTriangle(false))
{
N += depthBias;
}
if(complementaryDepthBuffer)
{
Z = -Z;
N = 1 - N;
}
static const float X[5][16] = // Fragment offsets
{
{+0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 1 sample
{-0.2500f, +0.2500f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 2 samples
{-0.3000f, +0.1000f, +0.3000f, -0.1000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 4 samples
{+0.1875f, -0.3125f, +0.3125f, -0.4375f, -0.0625f, +0.4375f, +0.0625f, -0.1875f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 8 samples
{+0.2553f, -0.1155f, +0.1661f, -0.1828f, +0.2293f, -0.4132f, -0.1773f, -0.0577f, +0.3891f, -0.4656f, +0.4103f, +0.4248f, -0.2109f, +0.3966f, -0.2664f, -0.3872f} // 16 samples
};
static const float Y[5][16] = // Fragment offsets
{
{+0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 1 sample
{-0.2500f, +0.2500f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 2 samples
{-0.1000f, -0.3000f, +0.1000f, +0.3000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 4 samples
{-0.4375f, -0.3125f, -0.1875f, -0.0625f, +0.0625f, +0.1875f, +0.3125f, +0.4375f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 8 samples
{-0.4503f, +0.1883f, +0.3684f, -0.4668f, -0.0690f, -0.1315f, +0.4999f, +0.0728f, +0.1070f, -0.3086f, +0.3725f, -0.1547f, -0.1102f, -0.3588f, +0.1789f, +0.0269f} // 16 samples
};
int s = sw::log2(ss);
data->Wx16 = replicate(W * 16);
data->Hx16 = replicate(H * 16);
data->X0x16 = replicate(X0 * 16 - 8);
data->Y0x16 = replicate(Y0 * 16 - 8);
data->XXXX = replicate(X[s][q] / W);
data->YYYY = replicate(Y[s][q] / H);
data->halfPixelX = replicate(0.5f / W);
data->halfPixelY = replicate(0.5f / H);
data->viewportHeight = abs(viewport.height);
data->slopeDepthBias = slopeDepthBias;
data->depthRange = Z;
data->depthNear = N;
draw->clipFlags = clipFlags;
if(clipFlags)
{
if(clipFlags & Clipper::CLIP_PLANE0) data->clipPlane[0] = clipPlane[0];
if(clipFlags & Clipper::CLIP_PLANE1) data->clipPlane[1] = clipPlane[1];
if(clipFlags & Clipper::CLIP_PLANE2) data->clipPlane[2] = clipPlane[2];
if(clipFlags & Clipper::CLIP_PLANE3) data->clipPlane[3] = clipPlane[3];
if(clipFlags & Clipper::CLIP_PLANE4) data->clipPlane[4] = clipPlane[4];
if(clipFlags & Clipper::CLIP_PLANE5) data->clipPlane[5] = clipPlane[5];
}
}
// Target
{
for(int index = 0; index < RENDERTARGETS; index++)
{
draw->renderTarget[index] = context->renderTarget[index];
if(draw->renderTarget[index])
{
data->colorBuffer[index] = (unsigned int*)context->renderTarget[index]->lockInternal(0, 0, q * ms, LOCK_READWRITE, MANAGED);
data->colorPitchB[index] = context->renderTarget[index]->getInternalPitchB();
data->colorSliceB[index] = context->renderTarget[index]->getInternalSliceB();
}
}
draw->depthBuffer = context->depthBuffer;
draw->stencilBuffer = context->stencilBuffer;
if(draw->depthBuffer)
{
data->depthBuffer = (float*)context->depthBuffer->lockInternal(0, 0, q * ms, LOCK_READWRITE, MANAGED);
data->depthPitchB = context->depthBuffer->getInternalPitchB();
data->depthSliceB = context->depthBuffer->getInternalSliceB();
}
if(draw->stencilBuffer)
{
data->stencilBuffer = (unsigned char*)context->stencilBuffer->lockStencil(0, 0, q * ms, MANAGED);
data->stencilPitchB = context->stencilBuffer->getStencilPitchB();
data->stencilSliceB = context->stencilBuffer->getStencilSliceB();
}
}
// Scissor
{
data->scissorX0 = scissor.x0;
data->scissorX1 = scissor.x1;
data->scissorY0 = scissor.y0;
data->scissorY1 = scissor.y1;
}
draw->primitive = 0;
draw->count = count;
draw->references = (count + batch - 1) / batch;
schedulerMutex.lock();
nextDraw++;
schedulerMutex.unlock();
if(threadCount > 1)
{
if(!threadsAwake)
{
suspend[0]->wait();
threadsAwake = 1;
task[0].type = Task::RESUME;
resume[0]->signal();
}
}
else // Use main thread for draw execution
{
threadsAwake = 1;
task[0].type = Task::RESUME;
taskLoop(0);
}
}
}
void Renderer::threadFunction(void *parameters)
{
Renderer *renderer = static_cast<Parameters*>(parameters)->renderer;
int threadIndex = static_cast<Parameters*>(parameters)->threadIndex;
if(logPrecision < IEEE)
{
CPUID::setFlushToZero(true);
CPUID::setDenormalsAreZero(true);
}
renderer->threadLoop(threadIndex);
}
void Renderer::threadLoop(int threadIndex)
{
while(!exitThreads)
{
taskLoop(threadIndex);
suspend[threadIndex]->signal();
resume[threadIndex]->wait();
}
}
void Renderer::taskLoop(int threadIndex)
{
while(task[threadIndex].type != Task::SUSPEND)
{
scheduleTask(threadIndex);
executeTask(threadIndex);
}
}
void Renderer::findAvailableTasks()
{
// Find pixel tasks
for(int cluster = 0; cluster < clusterCount; cluster++)
{
if(!pixelProgress[cluster].executing)
{
for(int unit = 0; unit < unitCount; unit++)
{
if(primitiveProgress[unit].references > 0) // Contains processed primitives
{
if(pixelProgress[cluster].drawCall == primitiveProgress[unit].drawCall)
{
if(pixelProgress[cluster].processedPrimitives == primitiveProgress[unit].firstPrimitive) // Previous primitives have been rendered
{
Task &task = taskQueue[qHead];
task.type = Task::PIXELS;
task.primitiveUnit = unit;
task.pixelCluster = cluster;
pixelProgress[cluster].executing = true;
// Commit to the task queue
qHead = (qHead + 1) % 32;
qSize++;
break;
}
}
}
}
}
}
// Find primitive tasks
if(currentDraw == nextDraw)
{
return; // No more primitives to process
}
for(int unit = 0; unit < unitCount; unit++)
{
DrawCall *draw = drawList[currentDraw % DRAW_COUNT];
if(draw->primitive >= draw->count)
{
currentDraw++;
if(currentDraw == nextDraw)
{
return; // No more primitives to process
}
draw = drawList[currentDraw % DRAW_COUNT];
}
if(!primitiveProgress[unit].references) // Task not already being executed and not still in use by a pixel unit
{
int primitive = draw->primitive;
int count = draw->count;
int batch = draw->batchSize;
primitiveProgress[unit].drawCall = currentDraw;
primitiveProgress[unit].firstPrimitive = primitive;
primitiveProgress[unit].primitiveCount = count - primitive >= batch ? batch : count - primitive;
draw->primitive += batch;
Task &task = taskQueue[qHead];
task.type = Task::PRIMITIVES;
task.primitiveUnit = unit;
primitiveProgress[unit].references = -1;
// Commit to the task queue
qHead = (qHead + 1) % 32;
qSize++;
}
}
}
void Renderer::scheduleTask(int threadIndex)
{
schedulerMutex.lock();
if((int)qSize < threadCount - threadsAwake + 1)
{
findAvailableTasks();
}
if(qSize != 0)
{
task[threadIndex] = taskQueue[(qHead - qSize) % 32];
qSize--;
if(threadsAwake != threadCount)
{
int wakeup = qSize - threadsAwake + 1;
for(int i = 0; i < threadCount && wakeup > 0; i++)
{
if(task[i].type == Task::SUSPEND)
{
suspend[i]->wait();
task[i].type = Task::RESUME;
resume[i]->signal();
threadsAwake++;
wakeup--;
}
}
}
}
else
{
task[threadIndex].type = Task::SUSPEND;
threadsAwake--;
}
schedulerMutex.unlock();
}
void Renderer::executeTask(int threadIndex)
{
#if PERF_HUD
int64_t startTick = Timer::ticks();
#endif
switch(task[threadIndex].type)
{
case Task::PRIMITIVES:
{
int unit = task[threadIndex].primitiveUnit;
int input = primitiveProgress[unit].firstPrimitive;
int count = primitiveProgress[unit].primitiveCount;
DrawCall *draw = drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
int (Renderer::*setupPrimitives)(int batch, int count) = draw->setupPrimitives;
processPrimitiveVertices(unit, input, count, draw->count, threadIndex);
#if PERF_HUD
int64_t time = Timer::ticks();
vertexTime[threadIndex] += time - startTick;
startTick = time;
#endif
int visible = 0;
if(!draw->setupState.rasterizerDiscard)
{
visible = (this->*setupPrimitives)(unit, count);
}
primitiveProgress[unit].visible = visible;
primitiveProgress[unit].references = clusterCount;
#if PERF_HUD
setupTime[threadIndex] += Timer::ticks() - startTick;
#endif
}
break;
case Task::PIXELS:
{
int unit = task[threadIndex].primitiveUnit;
int visible = primitiveProgress[unit].visible;
if(visible > 0)
{
int cluster = task[threadIndex].pixelCluster;
Primitive *primitive = primitiveBatch[unit];
DrawCall *draw = drawList[pixelProgress[cluster].drawCall % DRAW_COUNT];
DrawData *data = draw->data;
PixelProcessor::RoutinePointer pixelRoutine = draw->pixelPointer;
pixelRoutine(primitive, visible, cluster, data);
}
finishRendering(task[threadIndex]);
#if PERF_HUD
pixelTime[threadIndex] += Timer::ticks() - startTick;
#endif
}
break;
case Task::RESUME:
break;
case Task::SUSPEND:
break;
default:
ASSERT(false);
}
}
void Renderer::synchronize()
{
sync->lock(sw::PUBLIC);
sync->unlock();
}
void Renderer::finishRendering(Task &pixelTask)
{
int unit = pixelTask.primitiveUnit;
int cluster = pixelTask.pixelCluster;
DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
DrawData &data = *draw.data;
int primitive = primitiveProgress[unit].firstPrimitive;
int count = primitiveProgress[unit].primitiveCount;
int processedPrimitives = primitive + count;
pixelProgress[cluster].processedPrimitives = processedPrimitives;
if(pixelProgress[cluster].processedPrimitives >= draw.count)
{
pixelProgress[cluster].drawCall++;
pixelProgress[cluster].processedPrimitives = 0;
}
int ref = atomicDecrement(&primitiveProgress[unit].references);
if(ref == 0)
{
ref = atomicDecrement(&draw.references);
if(ref == 0)
{
#if PERF_PROFILE
for(int cluster = 0; cluster < clusterCount; cluster++)
{
for(int i = 0; i < PERF_TIMERS; i++)
{
profiler.cycles[i] += data.cycles[i][cluster];
}
}
#endif
if(draw.queries)
{
for(std::list<Query*>::iterator q = draw.queries->begin(); q != draw.queries->end(); q++)
{
Query *query = *q;
switch(query->type)
{
case Query::FRAGMENTS_PASSED:
for(int cluster = 0; cluster < clusterCount; cluster++)
{
atomicAdd((volatile int*)&query->data, data.occlusion[cluster]);
}
break;
case Query::TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
atomicAdd((volatile int*)&query->data, processedPrimitives);
break;
default:
break;
}
atomicDecrement(&query->reference);
}
delete draw.queries;
draw.queries = 0;
}
for(int i = 0; i < RENDERTARGETS; i++)
{
if(draw.renderTarget[i])
{
draw.renderTarget[i]->unlockInternal();
}
}
if(draw.depthBuffer)
{
draw.depthBuffer->unlockInternal();
}
if(draw.stencilBuffer)
{
draw.stencilBuffer->unlockStencil();
}
for(int i = 0; i < TOTAL_IMAGE_UNITS; i++)
{
if(draw.texture[i])
{
draw.texture[i]->unlock();
}
}
for(int i = 0; i < MAX_VERTEX_INPUTS; i++)
{
if(draw.vertexStream[i])
{
draw.vertexStream[i]->unlock();
}
}
if(draw.indexBuffer)
{
draw.indexBuffer->unlock();
}
for(int i = 0; i < MAX_UNIFORM_BUFFER_BINDINGS; i++)
{
if(draw.pUniformBuffers[i])
{
draw.pUniformBuffers[i]->unlock();
}
if(draw.vUniformBuffers[i])
{
draw.vUniformBuffers[i]->unlock();
}
}
for(int i = 0; i < MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS; i++)
{
if(draw.transformFeedbackBuffers[i])
{
draw.transformFeedbackBuffers[i]->unlock();
}
}
draw.vertexRoutine->unbind();
draw.setupRoutine->unbind();
draw.pixelRoutine->unbind();
sync->unlock();
draw.references = -1;
resumeApp->signal();
}
}
pixelProgress[cluster].executing = false;
}
void Renderer::processPrimitiveVertices(int unit, unsigned int start, unsigned int triangleCount, unsigned int loop, int thread)
{
Triangle *triangle = triangleBatch[unit];
DrawCall *draw = drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
DrawData *data = draw->data;
VertexTask *task = vertexTask[thread];
const void *indices = data->indices;
VertexProcessor::RoutinePointer vertexRoutine = draw->vertexPointer;
if(task->vertexCache.drawCall != primitiveProgress[unit].drawCall)
{
task->vertexCache.clear();
task->vertexCache.drawCall = primitiveProgress[unit].drawCall;
}
unsigned int batch[128][3]; // FIXME: Adjust to dynamic batch size
switch(draw->drawType)
{
case DRAW_POINTLIST:
{
unsigned int index = start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index;
batch[i][1] = index;
batch[i][2] = index;
index += 1;
}
}
break;
case DRAW_LINELIST:
{
unsigned int index = 2 * start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index + 0;
batch[i][1] = index + 1;
batch[i][2] = index + 1;
index += 2;
}
}
break;
case DRAW_LINESTRIP:
{
unsigned int index = start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index + 0;
batch[i][1] = index + 1;
batch[i][2] = index + 1;
index += 1;
}
}
break;
case DRAW_LINELOOP:
{
unsigned int index = start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = (index + 0) % loop;
batch[i][1] = (index + 1) % loop;
batch[i][2] = (index + 1) % loop;
index += 1;
}
}
break;
case DRAW_TRIANGLELIST:
{
unsigned int index = 3 * start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index + 0;
batch[i][1] = index + 1;
batch[i][2] = index + 2;
index += 3;
}
}
break;
case DRAW_TRIANGLESTRIP:
{
unsigned int index = start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index + 0;
batch[i][1] = index + (index & 1) + 1;
batch[i][2] = index + (~index & 1) + 1;
index += 1;
}
}
break;
case DRAW_TRIANGLEFAN:
{
unsigned int index = start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index + 1;
batch[i][1] = index + 2;
batch[i][2] = 0;
index += 1;
}
}
break;
case DRAW_INDEXEDPOINTLIST8:
{
const unsigned char *index = (const unsigned char*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = *index;
batch[i][1] = *index;
batch[i][2] = *index;
index += 1;
}
}
break;
case DRAW_INDEXEDPOINTLIST16:
{
const unsigned short *index = (const unsigned short*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = *index;
batch[i][1] = *index;
batch[i][2] = *index;
index += 1;
}
}
break;
case DRAW_INDEXEDPOINTLIST32:
{
const unsigned int *index = (const unsigned int*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = *index;
batch[i][1] = *index;
batch[i][2] = *index;
index += 1;
}
}
break;
case DRAW_INDEXEDLINELIST8:
{
const unsigned char *index = (const unsigned char*)indices + 2 * start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[1];
index += 2;
}
}
break;
case DRAW_INDEXEDLINELIST16:
{
const unsigned short *index = (const unsigned short*)indices + 2 * start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[1];
index += 2;
}
}
break;
case DRAW_INDEXEDLINELIST32:
{
const unsigned int *index = (const unsigned int*)indices + 2 * start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[1];
index += 2;
}
}
break;
case DRAW_INDEXEDLINESTRIP8:
{
const unsigned char *index = (const unsigned char*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[1];
index += 1;
}
}
break;
case DRAW_INDEXEDLINESTRIP16:
{
const unsigned short *index = (const unsigned short*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[1];
index += 1;
}
}
break;
case DRAW_INDEXEDLINESTRIP32:
{
const unsigned int *index = (const unsigned int*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[1];
index += 1;
}
}
break;
case DRAW_INDEXEDLINELOOP8:
{
const unsigned char *index = (const unsigned char*)indices;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[(start + i + 0) % loop];
batch[i][1] = index[(start + i + 1) % loop];
batch[i][2] = index[(start + i + 1) % loop];
}
}
break;
case DRAW_INDEXEDLINELOOP16:
{
const unsigned short *index = (const unsigned short*)indices;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[(start + i + 0) % loop];
batch[i][1] = index[(start + i + 1) % loop];
batch[i][2] = index[(start + i + 1) % loop];
}
}
break;
case DRAW_INDEXEDLINELOOP32:
{
const unsigned int *index = (const unsigned int*)indices;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[(start + i + 0) % loop];
batch[i][1] = index[(start + i + 1) % loop];
batch[i][2] = index[(start + i + 1) % loop];
}
}
break;
case DRAW_INDEXEDTRIANGLELIST8:
{
const unsigned char *index = (const unsigned char*)indices + 3 * start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[2];
index += 3;
}
}
break;
case DRAW_INDEXEDTRIANGLELIST16:
{
const unsigned short *index = (const unsigned short*)indices + 3 * start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[2];
index += 3;
}
}
break;
case DRAW_INDEXEDTRIANGLELIST32:
{
const unsigned int *index = (const unsigned int*)indices + 3 * start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[2];
index += 3;
}
}
break;
case DRAW_INDEXEDTRIANGLESTRIP8:
{
const unsigned char *index = (const unsigned char*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[((start + i) & 1) + 1];
batch[i][2] = index[(~(start + i) & 1) + 1];
index += 1;
}
}
break;
case DRAW_INDEXEDTRIANGLESTRIP16:
{
const unsigned short *index = (const unsigned short*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[((start + i) & 1) + 1];
batch[i][2] = index[(~(start + i) & 1) + 1];
index += 1;
}
}
break;
case DRAW_INDEXEDTRIANGLESTRIP32:
{
const unsigned int *index = (const unsigned int*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[((start + i) & 1) + 1];
batch[i][2] = index[(~(start + i) & 1) + 1];
index += 1;
}
}
break;
case DRAW_INDEXEDTRIANGLEFAN8:
{
const unsigned char *index = (const unsigned char*)indices;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[start + i + 1];
batch[i][1] = index[start + i + 2];
batch[i][2] = index[0];
}
}
break;
case DRAW_INDEXEDTRIANGLEFAN16:
{
const unsigned short *index = (const unsigned short*)indices;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[start + i + 1];
batch[i][1] = index[start + i + 2];
batch[i][2] = index[0];
}
}
break;
case DRAW_INDEXEDTRIANGLEFAN32:
{
const unsigned int *index = (const unsigned int*)indices;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[start + i + 1];
batch[i][1] = index[start + i + 2];
batch[i][2] = index[0];
}
}
break;
case DRAW_QUADLIST:
{
unsigned int index = 4 * start / 2;
for(unsigned int i = 0; i < triangleCount; i += 2)
{
batch[i+0][0] = index + 0;
batch[i+0][1] = index + 1;
batch[i+0][2] = index + 2;
batch[i+1][0] = index + 0;
batch[i+1][1] = index + 2;
batch[i+1][2] = index + 3;
index += 4;
}
}
break;
default:
ASSERT(false);
return;
}
task->primitiveStart = start;
task->vertexCount = triangleCount * 3;
vertexRoutine(&triangle->v0, (unsigned int*)&batch, task, data);
}
int Renderer::setupSolidTriangles(int unit, int count)
{
Triangle *triangle = triangleBatch[unit];
Primitive *primitive = primitiveBatch[unit];
DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
SetupProcessor::State &state = draw.setupState;
const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
int ms = state.multiSample;
int pos = state.positionRegister;
const DrawData *data = draw.data;
int visible = 0;
for(int i = 0; i < count; i++, triangle++)
{
Vertex &v0 = triangle->v0;
Vertex &v1 = triangle->v1;
Vertex &v2 = triangle->v2;
if((v0.clipFlags & v1.clipFlags & v2.clipFlags) == Clipper::CLIP_FINITE)
{
Polygon polygon(&v0.v[pos], &v1.v[pos], &v2.v[pos]);
int clipFlagsOr = v0.clipFlags | v1.clipFlags | v2.clipFlags | draw.clipFlags;
if(clipFlagsOr != Clipper::CLIP_FINITE)
{
if(!clipper->clip(polygon, clipFlagsOr, draw))
{
continue;
}
}
if(setupRoutine(primitive, triangle, &polygon, data))
{
primitive += ms;
visible++;
}
}
}
return visible;
}
int Renderer::setupWireframeTriangle(int unit, int count)
{
Triangle *triangle = triangleBatch[unit];
Primitive *primitive = primitiveBatch[unit];
int visible = 0;
DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
SetupProcessor::State &state = draw.setupState;
const Vertex &v0 = triangle[0].v0;
const Vertex &v1 = triangle[0].v1;
const Vertex &v2 = triangle[0].v2;
float d = (v0.y * v1.x - v0.x * v1.y) * v2.w + (v0.x * v2.y - v0.y * v2.x) * v1.w + (v2.x * v1.y - v1.x * v2.y) * v0.w;
if(state.cullMode == CULL_CLOCKWISE)
{
if(d >= 0) return 0;
}
else if(state.cullMode == CULL_COUNTERCLOCKWISE)
{
if(d <= 0) return 0;
}
// Copy attributes
triangle[1].v0 = v1;
triangle[1].v1 = v2;
triangle[2].v0 = v2;
triangle[2].v1 = v0;
if(state.color[0][0].flat) // FIXME
{
for(int i = 0; i < 2; i++)
{
triangle[1].v0.C[i] = triangle[0].v0.C[i];
triangle[1].v1.C[i] = triangle[0].v0.C[i];
triangle[2].v0.C[i] = triangle[0].v0.C[i];
triangle[2].v1.C[i] = triangle[0].v0.C[i];
}
}
for(int i = 0; i < 3; i++)
{
if(setupLine(*primitive, *triangle, draw))
{
primitive->area = 0.5f * d;
primitive++;
visible++;
}
triangle++;
}
return visible;
}
int Renderer::setupVertexTriangle(int unit, int count)
{
Triangle *triangle = triangleBatch[unit];
Primitive *primitive = primitiveBatch[unit];
int visible = 0;
DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
SetupProcessor::State &state = draw.setupState;
const Vertex &v0 = triangle[0].v0;
const Vertex &v1 = triangle[0].v1;
const Vertex &v2 = triangle[0].v2;
float d = (v0.y * v1.x - v0.x * v1.y) * v2.w + (v0.x * v2.y - v0.y * v2.x) * v1.w + (v2.x * v1.y - v1.x * v2.y) * v0.w;
if(state.cullMode == CULL_CLOCKWISE)
{
if(d >= 0) return 0;
}
else if(state.cullMode == CULL_COUNTERCLOCKWISE)
{
if(d <= 0) return 0;
}
// Copy attributes
triangle[1].v0 = v1;
triangle[2].v0 = v2;
for(int i = 0; i < 3; i++)
{
if(setupPoint(*primitive, *triangle, draw))
{
primitive->area = 0.5f * d;
primitive++;
visible++;
}
triangle++;
}
return visible;
}
int Renderer::setupLines(int unit, int count)
{
Triangle *triangle = triangleBatch[unit];
Primitive *primitive = primitiveBatch[unit];
int visible = 0;
DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
SetupProcessor::State &state = draw.setupState;
int ms = state.multiSample;
for(int i = 0; i < count; i++)
{
if(setupLine(*primitive, *triangle, draw))
{
primitive += ms;
visible++;
}
triangle++;
}
return visible;
}
int Renderer::setupPoints(int unit, int count)
{
Triangle *triangle = triangleBatch[unit];
Primitive *primitive = primitiveBatch[unit];
int visible = 0;
DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
SetupProcessor::State &state = draw.setupState;
int ms = state.multiSample;
for(int i = 0; i < count; i++)
{
if(setupPoint(*primitive, *triangle, draw))
{
primitive += ms;
visible++;
}
triangle++;
}
return visible;
}
bool Renderer::setupLine(Primitive &primitive, Triangle &triangle, const DrawCall &draw)
{
const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
const SetupProcessor::State &state = draw.setupState;
const DrawData &data = *draw.data;
float lineWidth = data.lineWidth;
Vertex &v0 = triangle.v0;
Vertex &v1 = triangle.v1;
int pos = state.positionRegister;
const float4 &P0 = v0.v[pos];
const float4 &P1 = v1.v[pos];
if(P0.w <= 0 && P1.w <= 0)
{
return false;
}
const float W = data.Wx16[0] * (1.0f / 16.0f);
const float H = data.Hx16[0] * (1.0f / 16.0f);
float dx = W * (P1.x / P1.w - P0.x / P0.w);
float dy = H * (P1.y / P1.w - P0.y / P0.w);
if(dx == 0 && dy == 0)
{
return false;
}
if(false) // Rectangle
{
float4 P[4];
int C[4];
P[0] = P0;
P[1] = P1;
P[2] = P1;
P[3] = P0;
float scale = lineWidth * 0.5f / sqrt(dx*dx + dy*dy);
dx *= scale;
dy *= scale;
float dx0w = dx * P0.w / W;
float dy0h = dy * P0.w / H;
float dx0h = dx * P0.w / H;
float dy0w = dy * P0.w / W;
float dx1w = dx * P1.w / W;
float dy1h = dy * P1.w / H;
float dx1h = dx * P1.w / H;
float dy1w = dy * P1.w / W;
P[0].x += -dy0w + -dx0w;
P[0].y += -dx0h + +dy0h;
C[0] = clipper->computeClipFlags(P[0]);
P[1].x += -dy1w + +dx1w;
P[1].y += -dx1h + +dy1h;
C[1] = clipper->computeClipFlags(P[1]);
P[2].x += +dy1w + +dx1w;
P[2].y += +dx1h + -dy1h;
C[2] = clipper->computeClipFlags(P[2]);
P[3].x += +dy0w + -dx0w;
P[3].y += +dx0h + +dy0h;
C[3] = clipper->computeClipFlags(P[3]);
if((C[0] & C[1] & C[2] & C[3]) == Clipper::CLIP_FINITE)
{
Polygon polygon(P, 4);
int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | draw.clipFlags;
if(clipFlagsOr != Clipper::CLIP_FINITE)
{
if(!clipper->clip(polygon, clipFlagsOr, draw))
{
return false;
}
}
return setupRoutine(&primitive, &triangle, &polygon, &data);
}
}
else // Diamond test convention
{
float4 P[8];
int C[8];
P[0] = P0;
P[1] = P0;
P[2] = P0;
P[3] = P0;
P[4] = P1;
P[5] = P1;
P[6] = P1;
P[7] = P1;
float dx0 = lineWidth * 0.5f * P0.w / W;
float dy0 = lineWidth * 0.5f * P0.w / H;
float dx1 = lineWidth * 0.5f * P1.w / W;
float dy1 = lineWidth * 0.5f * P1.w / H;
P[0].x += -dx0;
C[0] = clipper->computeClipFlags(P[0]);
P[1].y += +dy0;
C[1] = clipper->computeClipFlags(P[1]);
P[2].x += +dx0;
C[2] = clipper->computeClipFlags(P[2]);
P[3].y += -dy0;
C[3] = clipper->computeClipFlags(P[3]);
P[4].x += -dx1;
C[4] = clipper->computeClipFlags(P[4]);
P[5].y += +dy1;
C[5] = clipper->computeClipFlags(P[5]);
P[6].x += +dx1;
C[6] = clipper->computeClipFlags(P[6]);
P[7].y += -dy1;
C[7] = clipper->computeClipFlags(P[7]);
if((C[0] & C[1] & C[2] & C[3] & C[4] & C[5] & C[6] & C[7]) == Clipper::CLIP_FINITE)
{
float4 L[6];
if(dx > -dy)
{
if(dx > dy) // Right
{
L[0] = P[0];
L[1] = P[1];
L[2] = P[5];
L[3] = P[6];
L[4] = P[7];
L[5] = P[3];
}
else // Down
{
L[0] = P[0];
L[1] = P[4];
L[2] = P[5];
L[3] = P[6];
L[4] = P[2];
L[5] = P[3];
}
}
else
{
if(dx > dy) // Up
{
L[0] = P[0];
L[1] = P[1];
L[2] = P[2];
L[3] = P[6];
L[4] = P[7];
L[5] = P[4];
}
else // Left
{
L[0] = P[1];
L[1] = P[2];
L[2] = P[3];
L[3] = P[7];
L[4] = P[4];
L[5] = P[5];
}
}
Polygon polygon(L, 6);
int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | C[4] | C[5] | C[6] | C[7] | draw.clipFlags;
if(clipFlagsOr != Clipper::CLIP_FINITE)
{
if(!clipper->clip(polygon, clipFlagsOr, draw))
{
return false;
}
}
return setupRoutine(&primitive, &triangle, &polygon, &data);
}
}
return false;
}
bool Renderer::setupPoint(Primitive &primitive, Triangle &triangle, const DrawCall &draw)
{
const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
const SetupProcessor::State &state = draw.setupState;
const DrawData &data = *draw.data;
Vertex &v = triangle.v0;
float pSize;
int pts = state.pointSizeRegister;
if(state.pointSizeRegister != Unused)
{
pSize = v.v[pts].y;
}
else
{
pSize = data.point.pointSize[0];
}
pSize = clamp(pSize, data.point.pointSizeMin, data.point.pointSizeMax);
float4 P[4];
int C[4];
int pos = state.positionRegister;
P[0] = v.v[pos];
P[1] = v.v[pos];
P[2] = v.v[pos];
P[3] = v.v[pos];
const float X = pSize * P[0].w * data.halfPixelX[0];
const float Y = pSize * P[0].w * data.halfPixelY[0];
P[0].x -= X;
P[0].y += Y;
C[0] = clipper->computeClipFlags(P[0]);
P[1].x += X;
P[1].y += Y;
C[1] = clipper->computeClipFlags(P[1]);
P[2].x += X;
P[2].y -= Y;
C[2] = clipper->computeClipFlags(P[2]);
P[3].x -= X;
P[3].y -= Y;
C[3] = clipper->computeClipFlags(P[3]);
triangle.v1 = triangle.v0;
triangle.v2 = triangle.v0;
triangle.v1.X += iround(16 * 0.5f * pSize);
triangle.v2.Y -= iround(16 * 0.5f * pSize) * (data.Hx16[0] > 0.0f ? 1 : -1); // Both Direct3D and OpenGL expect (0, 0) in the top-left corner
Polygon polygon(P, 4);
if((C[0] & C[1] & C[2] & C[3]) == Clipper::CLIP_FINITE)
{
int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | draw.clipFlags;
if(clipFlagsOr != Clipper::CLIP_FINITE)
{
if(!clipper->clip(polygon, clipFlagsOr, draw))
{
return false;
}
}
return setupRoutine(&primitive, &triangle, &polygon, &data);
}
return false;
}
void Renderer::initializeThreads()
{
unitCount = ceilPow2(threadCount);
clusterCount = ceilPow2(threadCount);
for(int i = 0; i < unitCount; i++)
{
triangleBatch[i] = (Triangle*)allocate(batchSize * sizeof(Triangle));
primitiveBatch[i] = (Primitive*)allocate(batchSize * sizeof(Primitive));
}
for(int i = 0; i < threadCount; i++)
{
vertexTask[i] = (VertexTask*)allocate(sizeof(VertexTask));
vertexTask[i]->vertexCache.drawCall = -1;
task[i].type = Task::SUSPEND;
resume[i] = new Event();
suspend[i] = new Event();
Parameters parameters;
parameters.threadIndex = i;
parameters.renderer = this;
exitThreads = false;
worker[i] = new Thread(threadFunction, ¶meters);
suspend[i]->wait();
suspend[i]->signal();
}
}
void Renderer::terminateThreads()
{
while(threadsAwake != 0)
{
Thread::sleep(1);
}
for(int thread = 0; thread < threadCount; thread++)
{
if(worker[thread])
{
exitThreads = true;
resume[thread]->signal();
worker[thread]->join();
delete worker[thread];
worker[thread] = 0;
delete resume[thread];
resume[thread] = 0;
delete suspend[thread];
suspend[thread] = 0;
}
deallocate(vertexTask[thread]);
vertexTask[thread] = 0;
}
for(int i = 0; i < 16; i++)
{
deallocate(triangleBatch[i]);
triangleBatch[i] = 0;
deallocate(primitiveBatch[i]);
primitiveBatch[i] = 0;
}
}
void Renderer::loadConstants(const VertexShader *vertexShader)
{
if(!vertexShader) return;
size_t count = vertexShader->getLength();
for(size_t i = 0; i < count; i++)
{
const Shader::Instruction *instruction = vertexShader->getInstruction(i);
if(instruction->opcode == Shader::OPCODE_DEF)
{
int index = instruction->dst.index;
float value[4];
value[0] = instruction->src[0].value[0];
value[1] = instruction->src[0].value[1];
value[2] = instruction->src[0].value[2];
value[3] = instruction->src[0].value[3];
setVertexShaderConstantF(index, value);
}
else if(instruction->opcode == Shader::OPCODE_DEFI)
{
int index = instruction->dst.index;
int integer[4];
integer[0] = instruction->src[0].integer[0];
integer[1] = instruction->src[0].integer[1];
integer[2] = instruction->src[0].integer[2];
integer[3] = instruction->src[0].integer[3];
setVertexShaderConstantI(index, integer);
}
else if(instruction->opcode == Shader::OPCODE_DEFB)
{
int index = instruction->dst.index;
int boolean = instruction->src[0].boolean[0];
setVertexShaderConstantB(index, &boolean);
}
}
}
void Renderer::loadConstants(const PixelShader *pixelShader)
{
if(!pixelShader) return;
size_t count = pixelShader->getLength();
for(size_t i = 0; i < count; i++)
{
const Shader::Instruction *instruction = pixelShader->getInstruction(i);
if(instruction->opcode == Shader::OPCODE_DEF)
{
int index = instruction->dst.index;
float value[4];
value[0] = instruction->src[0].value[0];
value[1] = instruction->src[0].value[1];
value[2] = instruction->src[0].value[2];
value[3] = instruction->src[0].value[3];
setPixelShaderConstantF(index, value);
}
else if(instruction->opcode == Shader::OPCODE_DEFI)
{
int index = instruction->dst.index;
int integer[4];
integer[0] = instruction->src[0].integer[0];
integer[1] = instruction->src[0].integer[1];
integer[2] = instruction->src[0].integer[2];
integer[3] = instruction->src[0].integer[3];
setPixelShaderConstantI(index, integer);
}
else if(instruction->opcode == Shader::OPCODE_DEFB)
{
int index = instruction->dst.index;
int boolean = instruction->src[0].boolean[0];
setPixelShaderConstantB(index, &boolean);
}
}
}
void Renderer::setIndexBuffer(Resource *indexBuffer)
{
context->indexBuffer = indexBuffer;
}
void Renderer::setMultiSampleMask(unsigned int mask)
{
context->sampleMask = mask;
}
void Renderer::setTransparencyAntialiasing(TransparencyAntialiasing transparencyAntialiasing)
{
sw::transparencyAntialiasing = transparencyAntialiasing;
}
bool Renderer::isReadWriteTexture(int sampler)
{
for(int index = 0; index < RENDERTARGETS; index++)
{
if(context->renderTarget[index] && context->texture[sampler] == context->renderTarget[index]->getResource())
{
return true;
}
}
if(context->depthBuffer && context->texture[sampler] == context->depthBuffer->getResource())
{
return true;
}
return false;
}
void Renderer::updateClipper()
{
if(updateClipPlanes)
{
if(VertexProcessor::isFixedFunction()) // User plane in world space
{
const Matrix &scissorWorld = getViewTransform();
if(clipFlags & Clipper::CLIP_PLANE0) clipPlane[0] = scissorWorld * userPlane[0];
if(clipFlags & Clipper::CLIP_PLANE1) clipPlane[1] = scissorWorld * userPlane[1];
if(clipFlags & Clipper::CLIP_PLANE2) clipPlane[2] = scissorWorld * userPlane[2];
if(clipFlags & Clipper::CLIP_PLANE3) clipPlane[3] = scissorWorld * userPlane[3];
if(clipFlags & Clipper::CLIP_PLANE4) clipPlane[4] = scissorWorld * userPlane[4];
if(clipFlags & Clipper::CLIP_PLANE5) clipPlane[5] = scissorWorld * userPlane[5];
}
else // User plane in clip space
{
if(clipFlags & Clipper::CLIP_PLANE0) clipPlane[0] = userPlane[0];
if(clipFlags & Clipper::CLIP_PLANE1) clipPlane[1] = userPlane[1];
if(clipFlags & Clipper::CLIP_PLANE2) clipPlane[2] = userPlane[2];
if(clipFlags & Clipper::CLIP_PLANE3) clipPlane[3] = userPlane[3];
if(clipFlags & Clipper::CLIP_PLANE4) clipPlane[4] = userPlane[4];
if(clipFlags & Clipper::CLIP_PLANE5) clipPlane[5] = userPlane[5];
}
updateClipPlanes = false;
}
}
void Renderer::setTextureResource(unsigned int sampler, Resource *resource)
{
ASSERT(sampler < TOTAL_IMAGE_UNITS);
context->texture[sampler] = resource;
}
void Renderer::setTextureLevel(unsigned int sampler, unsigned int face, unsigned int level, Surface *surface, TextureType type)
{
ASSERT(sampler < TOTAL_IMAGE_UNITS && face < 6 && level < MIPMAP_LEVELS);
context->sampler[sampler].setTextureLevel(face, level, surface, type);
}
void Renderer::setTextureFilter(SamplerType type, int sampler, FilterType textureFilter)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setTextureFilter(sampler, textureFilter);
}
else
{
VertexProcessor::setTextureFilter(sampler, textureFilter);
}
}
void Renderer::setMipmapFilter(SamplerType type, int sampler, MipmapType mipmapFilter)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setMipmapFilter(sampler, mipmapFilter);
}
else
{
VertexProcessor::setMipmapFilter(sampler, mipmapFilter);
}
}
void Renderer::setGatherEnable(SamplerType type, int sampler, bool enable)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setGatherEnable(sampler, enable);
}
else
{
VertexProcessor::setGatherEnable(sampler, enable);
}
}
void Renderer::setAddressingModeU(SamplerType type, int sampler, AddressingMode addressMode)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setAddressingModeU(sampler, addressMode);
}
else
{
VertexProcessor::setAddressingModeU(sampler, addressMode);
}
}
void Renderer::setAddressingModeV(SamplerType type, int sampler, AddressingMode addressMode)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setAddressingModeV(sampler, addressMode);
}
else
{
VertexProcessor::setAddressingModeV(sampler, addressMode);
}
}
void Renderer::setAddressingModeW(SamplerType type, int sampler, AddressingMode addressMode)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setAddressingModeW(sampler, addressMode);
}
else
{
VertexProcessor::setAddressingModeW(sampler, addressMode);
}
}
void Renderer::setReadSRGB(SamplerType type, int sampler, bool sRGB)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setReadSRGB(sampler, sRGB);
}
else
{
VertexProcessor::setReadSRGB(sampler, sRGB);
}
}
void Renderer::setMipmapLOD(SamplerType type, int sampler, float bias)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setMipmapLOD(sampler, bias);
}
else
{
VertexProcessor::setMipmapLOD(sampler, bias);
}
}
void Renderer::setBorderColor(SamplerType type, int sampler, const Color<float> &borderColor)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setBorderColor(sampler, borderColor);
}
else
{
VertexProcessor::setBorderColor(sampler, borderColor);
}
}
void Renderer::setMaxAnisotropy(SamplerType type, int sampler, float maxAnisotropy)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setMaxAnisotropy(sampler, maxAnisotropy);
}
else
{
VertexProcessor::setMaxAnisotropy(sampler, maxAnisotropy);
}
}
void Renderer::setSwizzleR(SamplerType type, int sampler, SwizzleType swizzleR)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setSwizzleR(sampler, swizzleR);
}
else
{
VertexProcessor::setSwizzleR(sampler, swizzleR);
}
}
void Renderer::setSwizzleG(SamplerType type, int sampler, SwizzleType swizzleG)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setSwizzleG(sampler, swizzleG);
}
else
{
VertexProcessor::setSwizzleG(sampler, swizzleG);
}
}
void Renderer::setSwizzleB(SamplerType type, int sampler, SwizzleType swizzleB)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setSwizzleB(sampler, swizzleB);
}
else
{
VertexProcessor::setSwizzleB(sampler, swizzleB);
}
}
void Renderer::setSwizzleA(SamplerType type, int sampler, SwizzleType swizzleA)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setSwizzleA(sampler, swizzleA);
}
else
{
VertexProcessor::setSwizzleA(sampler, swizzleA);
}
}
void Renderer::setBaseLevel(SamplerType type, int sampler, int baseLevel)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setBaseLevel(sampler, baseLevel);
}
else
{
VertexProcessor::setBaseLevel(sampler, baseLevel);
}
}
void Renderer::setMaxLevel(SamplerType type, int sampler, int maxLevel)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setMaxLevel(sampler, maxLevel);
}
else
{
VertexProcessor::setMaxLevel(sampler, maxLevel);
}
}
void Renderer::setMinLod(SamplerType type, int sampler, float minLod)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setMinLod(sampler, minLod);
}
else
{
VertexProcessor::setMinLod(sampler, minLod);
}
}
void Renderer::setMaxLod(SamplerType type, int sampler, float maxLod)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setMaxLod(sampler, maxLod);
}
else
{
VertexProcessor::setMaxLod(sampler, maxLod);
}
}
void Renderer::setPointSpriteEnable(bool pointSpriteEnable)
{
context->setPointSpriteEnable(pointSpriteEnable);
}
void Renderer::setPointScaleEnable(bool pointScaleEnable)
{
context->setPointScaleEnable(pointScaleEnable);
}
void Renderer::setLineWidth(float width)
{
context->lineWidth = width;
}
void Renderer::setDepthBias(float bias)
{
depthBias = bias;
}
void Renderer::setSlopeDepthBias(float slopeBias)
{
slopeDepthBias = slopeBias;
}
void Renderer::setRasterizerDiscard(bool rasterizerDiscard)
{
context->rasterizerDiscard = rasterizerDiscard;
}
void Renderer::setPixelShader(const PixelShader *shader)
{
context->pixelShader = shader;
loadConstants(shader);
}
void Renderer::setVertexShader(const VertexShader *shader)
{
context->vertexShader = shader;
loadConstants(shader);
}
void Renderer::setPixelShaderConstantF(int index, const float value[4], int count)
{
for(int i = 0; i < DRAW_COUNT; i++)
{
if(drawCall[i]->psDirtyConstF < index + count)
{
drawCall[i]->psDirtyConstF = index + count;
}
}
for(int i = 0; i < count; i++)
{
PixelProcessor::setFloatConstant(index + i, value);
value += 4;
}
}
void Renderer::setPixelShaderConstantI(int index, const int value[4], int count)
{
for(int i = 0; i < DRAW_COUNT; i++)
{
if(drawCall[i]->psDirtyConstI < index + count)
{
drawCall[i]->psDirtyConstI = index + count;
}
}
for(int i = 0; i < count; i++)
{
PixelProcessor::setIntegerConstant(index + i, value);
value += 4;
}
}
void Renderer::setPixelShaderConstantB(int index, const int *boolean, int count)
{
for(int i = 0; i < DRAW_COUNT; i++)
{
if(drawCall[i]->psDirtyConstB < index + count)
{
drawCall[i]->psDirtyConstB = index + count;
}
}
for(int i = 0; i < count; i++)
{
PixelProcessor::setBooleanConstant(index + i, *boolean);
boolean++;
}
}
void Renderer::setVertexShaderConstantF(int index, const float value[4], int count)
{
for(int i = 0; i < DRAW_COUNT; i++)
{
if(drawCall[i]->vsDirtyConstF < index + count)
{
drawCall[i]->vsDirtyConstF = index + count;
}
}
for(int i = 0; i < count; i++)
{
VertexProcessor::setFloatConstant(index + i, value);
value += 4;
}
}
void Renderer::setVertexShaderConstantI(int index, const int value[4], int count)
{
for(int i = 0; i < DRAW_COUNT; i++)
{
if(drawCall[i]->vsDirtyConstI < index + count)
{
drawCall[i]->vsDirtyConstI = index + count;
}
}
for(int i = 0; i < count; i++)
{
VertexProcessor::setIntegerConstant(index + i, value);
value += 4;
}
}
void Renderer::setVertexShaderConstantB(int index, const int *boolean, int count)
{
for(int i = 0; i < DRAW_COUNT; i++)
{
if(drawCall[i]->vsDirtyConstB < index + count)
{
drawCall[i]->vsDirtyConstB = index + count;
}
}
for(int i = 0; i < count; i++)
{
VertexProcessor::setBooleanConstant(index + i, *boolean);
boolean++;
}
}
void Renderer::setModelMatrix(const Matrix &M, int i)
{
VertexProcessor::setModelMatrix(M, i);
}
void Renderer::setViewMatrix(const Matrix &V)
{
VertexProcessor::setViewMatrix(V);
updateClipPlanes = true;
}
void Renderer::setBaseMatrix(const Matrix &B)
{
VertexProcessor::setBaseMatrix(B);
updateClipPlanes = true;
}
void Renderer::setProjectionMatrix(const Matrix &P)
{
VertexProcessor::setProjectionMatrix(P);
updateClipPlanes = true;
}
void Renderer::addQuery(Query *query)
{
queries.push_back(query);
}
void Renderer::removeQuery(Query *query)
{
queries.remove(query);
}
#if PERF_HUD
int Renderer::getThreadCount()
{
return threadCount;
}
int64_t Renderer::getVertexTime(int thread)
{
return vertexTime[thread];
}
int64_t Renderer::getSetupTime(int thread)
{
return setupTime[thread];
}
int64_t Renderer::getPixelTime(int thread)
{
return pixelTime[thread];
}
void Renderer::resetTimers()
{
for(int thread = 0; thread < threadCount; thread++)
{
vertexTime[thread] = 0;
setupTime[thread] = 0;
pixelTime[thread] = 0;
}
}
#endif
void Renderer::setViewport(const Viewport &viewport)
{
this->viewport = viewport;
}
void Renderer::setScissor(const Rect &scissor)
{
this->scissor = scissor;
}
void Renderer::setClipFlags(int flags)
{
clipFlags = flags << 8; // Bottom 8 bits used by legacy frustum
}
void Renderer::setClipPlane(unsigned int index, const float plane[4])
{
if(index < MAX_CLIP_PLANES)
{
userPlane[index] = plane;
}
else ASSERT(false);
updateClipPlanes = true;
}
void Renderer::updateConfiguration(bool initialUpdate)
{
bool newConfiguration = swiftConfig->hasNewConfiguration();
if(newConfiguration || initialUpdate)
{
terminateThreads();
SwiftConfig::Configuration configuration = {};
swiftConfig->getConfiguration(configuration);
precacheVertex = !newConfiguration && configuration.precache;
precacheSetup = !newConfiguration && configuration.precache;
precachePixel = !newConfiguration && configuration.precache;
VertexProcessor::setRoutineCacheSize(configuration.vertexRoutineCacheSize);
PixelProcessor::setRoutineCacheSize(configuration.pixelRoutineCacheSize);
SetupProcessor::setRoutineCacheSize(configuration.setupRoutineCacheSize);
switch(configuration.textureSampleQuality)
{
case 0: Sampler::setFilterQuality(FILTER_POINT); break;
case 1: Sampler::setFilterQuality(FILTER_LINEAR); break;
case 2: Sampler::setFilterQuality(FILTER_ANISOTROPIC); break;
default: Sampler::setFilterQuality(FILTER_ANISOTROPIC); break;
}
switch(configuration.mipmapQuality)
{
case 0: Sampler::setMipmapQuality(MIPMAP_POINT); break;
case 1: Sampler::setMipmapQuality(MIPMAP_LINEAR); break;
default: Sampler::setMipmapQuality(MIPMAP_LINEAR); break;
}
setPerspectiveCorrection(configuration.perspectiveCorrection);
switch(configuration.transcendentalPrecision)
{
case 0:
logPrecision = APPROXIMATE;
expPrecision = APPROXIMATE;
rcpPrecision = APPROXIMATE;
rsqPrecision = APPROXIMATE;
break;
case 1:
logPrecision = PARTIAL;
expPrecision = PARTIAL;
rcpPrecision = PARTIAL;
rsqPrecision = PARTIAL;
break;
case 2:
logPrecision = ACCURATE;
expPrecision = ACCURATE;
rcpPrecision = ACCURATE;
rsqPrecision = ACCURATE;
break;
case 3:
logPrecision = WHQL;
expPrecision = WHQL;
rcpPrecision = WHQL;
rsqPrecision = WHQL;
break;
case 4:
logPrecision = IEEE;
expPrecision = IEEE;
rcpPrecision = IEEE;
rsqPrecision = IEEE;
break;
default:
logPrecision = ACCURATE;
expPrecision = ACCURATE;
rcpPrecision = ACCURATE;
rsqPrecision = ACCURATE;
break;
}
switch(configuration.transparencyAntialiasing)
{
case 0: transparencyAntialiasing = TRANSPARENCY_NONE; break;
case 1: transparencyAntialiasing = TRANSPARENCY_ALPHA_TO_COVERAGE; break;
default: transparencyAntialiasing = TRANSPARENCY_NONE; break;
}
switch(configuration.threadCount)
{
case -1: threadCount = CPUID::coreCount(); break;
case 0: threadCount = CPUID::processAffinity(); break;
default: threadCount = configuration.threadCount; break;
}
CPUID::setEnableSSE4_1(configuration.enableSSE4_1);
CPUID::setEnableSSSE3(configuration.enableSSSE3);
CPUID::setEnableSSE3(configuration.enableSSE3);
CPUID::setEnableSSE2(configuration.enableSSE2);
CPUID::setEnableSSE(configuration.enableSSE);
for(int pass = 0; pass < 10; pass++)
{
optimization[pass] = configuration.optimization[pass];
}
forceWindowed = configuration.forceWindowed;
complementaryDepthBuffer = configuration.complementaryDepthBuffer;
postBlendSRGB = configuration.postBlendSRGB;
exactColorRounding = configuration.exactColorRounding;
forceClearRegisters = configuration.forceClearRegisters;
#ifndef NDEBUG
minPrimitives = configuration.minPrimitives;
maxPrimitives = configuration.maxPrimitives;
#endif
}
if(!initialUpdate && !worker[0])
{
initializeThreads();
}
}
}
Only support main thread rendering in debug builds.
Rendering on the main thread can cause segmentation faults on Windows
due to uncommitted stack memory, since Subzero does not currently call
__chkstk. In practice this would have mainly been an issue on VMs with
a single virtual CPU.
Bug swiftshader:25
Change-Id: Ic3be7e5a41ef09b7e056d3c3df2983c225101fe4
Reviewed-on: https://swiftshader-review.googlesource.com/8934
Tested-by: Nicolas Capens <0612353e1fcebbfd4b302d9337447ca0cdfa9122@google.com>
Reviewed-by: Alexis Hétu <1c7141772178a7e80858c3db5052b328076f08f4@google.com>
Reviewed-by: Nicolas Capens <0612353e1fcebbfd4b302d9337447ca0cdfa9122@google.com>
// Copyright 2016 The SwiftShader 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 "Renderer.hpp"
#include "Clipper.hpp"
#include "Math.hpp"
#include "FrameBuffer.hpp"
#include "Timer.hpp"
#include "Surface.hpp"
#include "Half.hpp"
#include "Primitive.hpp"
#include "Polygon.hpp"
#include "SwiftConfig.hpp"
#include "MutexLock.hpp"
#include "CPUID.hpp"
#include "Memory.hpp"
#include "Resource.hpp"
#include "Constants.hpp"
#include "Debug.hpp"
#include "Reactor/Reactor.hpp"
#undef max
bool disableServer = true;
#ifndef NDEBUG
unsigned int minPrimitives = 1;
unsigned int maxPrimitives = 1 << 21;
#endif
namespace sw
{
extern bool halfIntegerCoordinates; // Pixel centers are not at integer coordinates
extern bool symmetricNormalizedDepth; // [-1, 1] instead of [0, 1]
extern bool booleanFaceRegister;
extern bool fullPixelPositionRegister;
extern bool leadingVertexFirst; // Flat shading uses first vertex, else last
extern bool secondaryColor; // Specular lighting is applied after texturing
extern bool forceWindowed;
extern bool complementaryDepthBuffer;
extern bool postBlendSRGB;
extern bool exactColorRounding;
extern TransparencyAntialiasing transparencyAntialiasing;
extern bool forceClearRegisters;
extern bool precacheVertex;
extern bool precacheSetup;
extern bool precachePixel;
int batchSize = 128;
int threadCount = 1;
int unitCount = 1;
int clusterCount = 1;
TranscendentalPrecision logPrecision = ACCURATE;
TranscendentalPrecision expPrecision = ACCURATE;
TranscendentalPrecision rcpPrecision = ACCURATE;
TranscendentalPrecision rsqPrecision = ACCURATE;
bool perspectiveCorrection = true;
struct Parameters
{
Renderer *renderer;
int threadIndex;
};
DrawCall::DrawCall()
{
queries = 0;
vsDirtyConstF = VERTEX_UNIFORM_VECTORS + 1;
vsDirtyConstI = 16;
vsDirtyConstB = 16;
psDirtyConstF = FRAGMENT_UNIFORM_VECTORS;
psDirtyConstI = 16;
psDirtyConstB = 16;
references = -1;
data = (DrawData*)allocate(sizeof(DrawData));
data->constants = &constants;
}
DrawCall::~DrawCall()
{
delete queries;
deallocate(data);
}
Renderer::Renderer(Context *context, Conventions conventions, bool exactColorRounding) : VertexProcessor(context), PixelProcessor(context), SetupProcessor(context), context(context), viewport()
{
sw::halfIntegerCoordinates = conventions.halfIntegerCoordinates;
sw::symmetricNormalizedDepth = conventions.symmetricNormalizedDepth;
sw::booleanFaceRegister = conventions.booleanFaceRegister;
sw::fullPixelPositionRegister = conventions.fullPixelPositionRegister;
sw::leadingVertexFirst = conventions.leadingVertexFirst;
sw::secondaryColor = conventions.secondaryColor;
sw::exactColorRounding = exactColorRounding;
setRenderTarget(0, 0);
clipper = new Clipper(symmetricNormalizedDepth);
updateViewMatrix = true;
updateBaseMatrix = true;
updateProjectionMatrix = true;
updateClipPlanes = true;
#if PERF_HUD
resetTimers();
#endif
for(int i = 0; i < 16; i++)
{
vertexTask[i] = 0;
worker[i] = 0;
resume[i] = 0;
suspend[i] = 0;
}
threadsAwake = 0;
resumeApp = new Event();
currentDraw = 0;
nextDraw = 0;
qHead = 0;
qSize = 0;
for(int i = 0; i < 16; i++)
{
triangleBatch[i] = 0;
primitiveBatch[i] = 0;
}
for(int draw = 0; draw < DRAW_COUNT; draw++)
{
drawCall[draw] = new DrawCall();
drawList[draw] = drawCall[draw];
}
for(int unit = 0; unit < 16; unit++)
{
primitiveProgress[unit].init();
}
for(int cluster = 0; cluster < 16; cluster++)
{
pixelProgress[cluster].init();
}
clipFlags = 0;
swiftConfig = new SwiftConfig(disableServer);
updateConfiguration(true);
sync = new Resource(0);
}
Renderer::~Renderer()
{
sync->destruct();
delete clipper;
clipper = 0;
terminateThreads();
delete resumeApp;
for(int draw = 0; draw < DRAW_COUNT; draw++)
{
delete drawCall[draw];
}
delete swiftConfig;
}
// This object has to be mem aligned
void* Renderer::operator new(size_t size)
{
ASSERT(size == sizeof(Renderer)); // This operator can't be called from a derived class
return sw::allocate(sizeof(Renderer), 16);
}
void Renderer::operator delete(void * mem)
{
sw::deallocate(mem);
}
void Renderer::clear(void *pixel, Format format, Surface *dest, const SliceRect &dRect, unsigned int rgbaMask)
{
blitter.clear(pixel, format, dest, dRect, rgbaMask);
}
void Renderer::blit(Surface *source, const SliceRect &sRect, Surface *dest, const SliceRect &dRect, bool filter, bool isStencil)
{
blitter.blit(source, sRect, dest, dRect, filter, isStencil);
}
void Renderer::blit3D(Surface *source, Surface *dest)
{
blitter.blit3D(source, dest);
}
void Renderer::draw(DrawType drawType, unsigned int indexOffset, unsigned int count, bool update)
{
#ifndef NDEBUG
if(count < minPrimitives || count > maxPrimitives)
{
return;
}
#endif
context->drawType = drawType;
updateConfiguration();
updateClipper();
int ss = context->getSuperSampleCount();
int ms = context->getMultiSampleCount();
for(int q = 0; q < ss; q++)
{
unsigned int oldMultiSampleMask = context->multiSampleMask;
context->multiSampleMask = (context->sampleMask >> (ms * q)) & ((unsigned)0xFFFFFFFF >> (32 - ms));
if(!context->multiSampleMask)
{
continue;
}
sync->lock(sw::PRIVATE);
if(update || oldMultiSampleMask != context->multiSampleMask)
{
vertexState = VertexProcessor::update(drawType);
setupState = SetupProcessor::update();
pixelState = PixelProcessor::update();
vertexRoutine = VertexProcessor::routine(vertexState);
setupRoutine = SetupProcessor::routine(setupState);
pixelRoutine = PixelProcessor::routine(pixelState);
}
int batch = batchSize / ms;
int (Renderer::*setupPrimitives)(int batch, int count);
if(context->isDrawTriangle())
{
switch(context->fillMode)
{
case FILL_SOLID:
setupPrimitives = &Renderer::setupSolidTriangles;
break;
case FILL_WIREFRAME:
setupPrimitives = &Renderer::setupWireframeTriangle;
batch = 1;
break;
case FILL_VERTEX:
setupPrimitives = &Renderer::setupVertexTriangle;
batch = 1;
break;
default:
ASSERT(false);
return;
}
}
else if(context->isDrawLine())
{
setupPrimitives = &Renderer::setupLines;
}
else // Point draw
{
setupPrimitives = &Renderer::setupPoints;
}
DrawCall *draw = 0;
do
{
for(int i = 0; i < DRAW_COUNT; i++)
{
if(drawCall[i]->references == -1)
{
draw = drawCall[i];
drawList[nextDraw % DRAW_COUNT] = draw;
break;
}
}
if(!draw)
{
resumeApp->wait();
}
}
while(!draw);
DrawData *data = draw->data;
if(queries.size() != 0)
{
draw->queries = new std::list<Query*>();
bool includePrimitivesWrittenQueries = vertexState.transformFeedbackQueryEnabled && vertexState.transformFeedbackEnabled;
for(std::list<Query*>::iterator query = queries.begin(); query != queries.end(); query++)
{
Query* q = *query;
if(includePrimitivesWrittenQueries || (q->type != Query::TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN))
{
atomicIncrement(&(q->reference));
draw->queries->push_back(q);
}
}
}
draw->drawType = drawType;
draw->batchSize = batch;
vertexRoutine->bind();
setupRoutine->bind();
pixelRoutine->bind();
draw->vertexRoutine = vertexRoutine;
draw->setupRoutine = setupRoutine;
draw->pixelRoutine = pixelRoutine;
draw->vertexPointer = (VertexProcessor::RoutinePointer)vertexRoutine->getEntry();
draw->setupPointer = (SetupProcessor::RoutinePointer)setupRoutine->getEntry();
draw->pixelPointer = (PixelProcessor::RoutinePointer)pixelRoutine->getEntry();
draw->setupPrimitives = setupPrimitives;
draw->setupState = setupState;
for(int i = 0; i < MAX_VERTEX_INPUTS; i++)
{
draw->vertexStream[i] = context->input[i].resource;
data->input[i] = context->input[i].buffer;
data->stride[i] = context->input[i].stride;
if(draw->vertexStream[i])
{
draw->vertexStream[i]->lock(PUBLIC, PRIVATE);
}
}
if(context->indexBuffer)
{
data->indices = (unsigned char*)context->indexBuffer->lock(PUBLIC, PRIVATE) + indexOffset;
}
draw->indexBuffer = context->indexBuffer;
for(int sampler = 0; sampler < TOTAL_IMAGE_UNITS; sampler++)
{
draw->texture[sampler] = 0;
}
for(int sampler = 0; sampler < TEXTURE_IMAGE_UNITS; sampler++)
{
if(pixelState.sampler[sampler].textureType != TEXTURE_NULL)
{
draw->texture[sampler] = context->texture[sampler];
draw->texture[sampler]->lock(PUBLIC, isReadWriteTexture(sampler) ? MANAGED : PRIVATE); // If the texure is both read and written, use the same read/write lock as render targets
data->mipmap[sampler] = context->sampler[sampler].getTextureData();
}
}
if(context->pixelShader)
{
if(draw->psDirtyConstF)
{
memcpy(&data->ps.cW, PixelProcessor::cW, sizeof(word4) * 4 * (draw->psDirtyConstF < 8 ? draw->psDirtyConstF : 8));
memcpy(&data->ps.c, PixelProcessor::c, sizeof(float4) * draw->psDirtyConstF);
draw->psDirtyConstF = 0;
}
if(draw->psDirtyConstI)
{
memcpy(&data->ps.i, PixelProcessor::i, sizeof(int4) * draw->psDirtyConstI);
draw->psDirtyConstI = 0;
}
if(draw->psDirtyConstB)
{
memcpy(&data->ps.b, PixelProcessor::b, sizeof(bool) * draw->psDirtyConstB);
draw->psDirtyConstB = 0;
}
PixelProcessor::lockUniformBuffers(data->ps.u, draw->pUniformBuffers);
}
else
{
for(int i = 0; i < MAX_UNIFORM_BUFFER_BINDINGS; i++)
{
draw->pUniformBuffers[i] = nullptr;
}
}
if(context->pixelShaderVersion() <= 0x0104)
{
for(int stage = 0; stage < 8; stage++)
{
if(pixelState.textureStage[stage].stageOperation != TextureStage::STAGE_DISABLE || context->pixelShader)
{
data->textureStage[stage] = context->textureStage[stage].uniforms;
}
else break;
}
}
if(context->vertexShader)
{
if(context->vertexShader->getVersion() >= 0x0300)
{
for(int sampler = 0; sampler < VERTEX_TEXTURE_IMAGE_UNITS; sampler++)
{
if(vertexState.samplerState[sampler].textureType != TEXTURE_NULL)
{
draw->texture[TEXTURE_IMAGE_UNITS + sampler] = context->texture[TEXTURE_IMAGE_UNITS + sampler];
draw->texture[TEXTURE_IMAGE_UNITS + sampler]->lock(PUBLIC, PRIVATE);
data->mipmap[TEXTURE_IMAGE_UNITS + sampler] = context->sampler[TEXTURE_IMAGE_UNITS + sampler].getTextureData();
}
}
}
if(draw->vsDirtyConstF)
{
memcpy(&data->vs.c, VertexProcessor::c, sizeof(float4) * draw->vsDirtyConstF);
draw->vsDirtyConstF = 0;
}
if(draw->vsDirtyConstI)
{
memcpy(&data->vs.i, VertexProcessor::i, sizeof(int4) * draw->vsDirtyConstI);
draw->vsDirtyConstI = 0;
}
if(draw->vsDirtyConstB)
{
memcpy(&data->vs.b, VertexProcessor::b, sizeof(bool) * draw->vsDirtyConstB);
draw->vsDirtyConstB = 0;
}
if(context->vertexShader->isInstanceIdDeclared())
{
data->instanceID = context->instanceID;
}
VertexProcessor::lockUniformBuffers(data->vs.u, draw->vUniformBuffers);
VertexProcessor::lockTransformFeedbackBuffers(data->vs.t, data->vs.reg, data->vs.row, data->vs.col, data->vs.str, draw->transformFeedbackBuffers);
}
else
{
data->ff = ff;
draw->vsDirtyConstF = VERTEX_UNIFORM_VECTORS + 1;
draw->vsDirtyConstI = 16;
draw->vsDirtyConstB = 16;
for(int i = 0; i < MAX_UNIFORM_BUFFER_BINDINGS; i++)
{
draw->vUniformBuffers[i] = nullptr;
}
for(int i = 0; i < MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS; i++)
{
draw->transformFeedbackBuffers[i] = nullptr;
}
}
if(pixelState.stencilActive)
{
data->stencil[0] = stencil;
data->stencil[1] = stencilCCW;
}
if(pixelState.fogActive)
{
data->fog = fog;
}
if(setupState.isDrawPoint)
{
data->point = point;
}
data->lineWidth = context->lineWidth;
data->factor = factor;
if(pixelState.transparencyAntialiasing == TRANSPARENCY_ALPHA_TO_COVERAGE)
{
float ref = context->alphaReference * (1.0f / 255.0f);
float margin = sw::min(ref, 1.0f - ref);
if(ms == 4)
{
data->a2c0 = replicate(ref - margin * 0.6f);
data->a2c1 = replicate(ref - margin * 0.2f);
data->a2c2 = replicate(ref + margin * 0.2f);
data->a2c3 = replicate(ref + margin * 0.6f);
}
else if(ms == 2)
{
data->a2c0 = replicate(ref - margin * 0.3f);
data->a2c1 = replicate(ref + margin * 0.3f);
}
else ASSERT(false);
}
if(pixelState.occlusionEnabled)
{
for(int cluster = 0; cluster < clusterCount; cluster++)
{
data->occlusion[cluster] = 0;
}
}
#if PERF_PROFILE
for(int cluster = 0; cluster < clusterCount; cluster++)
{
for(int i = 0; i < PERF_TIMERS; i++)
{
data->cycles[i][cluster] = 0;
}
}
#endif
// Viewport
{
float W = 0.5f * viewport.width;
float H = 0.5f * viewport.height;
float X0 = viewport.x0 + W;
float Y0 = viewport.y0 + H;
float N = viewport.minZ;
float F = viewport.maxZ;
float Z = F - N;
if(context->isDrawTriangle(false))
{
N += depthBias;
}
if(complementaryDepthBuffer)
{
Z = -Z;
N = 1 - N;
}
static const float X[5][16] = // Fragment offsets
{
{+0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 1 sample
{-0.2500f, +0.2500f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 2 samples
{-0.3000f, +0.1000f, +0.3000f, -0.1000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 4 samples
{+0.1875f, -0.3125f, +0.3125f, -0.4375f, -0.0625f, +0.4375f, +0.0625f, -0.1875f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 8 samples
{+0.2553f, -0.1155f, +0.1661f, -0.1828f, +0.2293f, -0.4132f, -0.1773f, -0.0577f, +0.3891f, -0.4656f, +0.4103f, +0.4248f, -0.2109f, +0.3966f, -0.2664f, -0.3872f} // 16 samples
};
static const float Y[5][16] = // Fragment offsets
{
{+0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 1 sample
{-0.2500f, +0.2500f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 2 samples
{-0.1000f, -0.3000f, +0.1000f, +0.3000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 4 samples
{-0.4375f, -0.3125f, -0.1875f, -0.0625f, +0.0625f, +0.1875f, +0.3125f, +0.4375f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 8 samples
{-0.4503f, +0.1883f, +0.3684f, -0.4668f, -0.0690f, -0.1315f, +0.4999f, +0.0728f, +0.1070f, -0.3086f, +0.3725f, -0.1547f, -0.1102f, -0.3588f, +0.1789f, +0.0269f} // 16 samples
};
int s = sw::log2(ss);
data->Wx16 = replicate(W * 16);
data->Hx16 = replicate(H * 16);
data->X0x16 = replicate(X0 * 16 - 8);
data->Y0x16 = replicate(Y0 * 16 - 8);
data->XXXX = replicate(X[s][q] / W);
data->YYYY = replicate(Y[s][q] / H);
data->halfPixelX = replicate(0.5f / W);
data->halfPixelY = replicate(0.5f / H);
data->viewportHeight = abs(viewport.height);
data->slopeDepthBias = slopeDepthBias;
data->depthRange = Z;
data->depthNear = N;
draw->clipFlags = clipFlags;
if(clipFlags)
{
if(clipFlags & Clipper::CLIP_PLANE0) data->clipPlane[0] = clipPlane[0];
if(clipFlags & Clipper::CLIP_PLANE1) data->clipPlane[1] = clipPlane[1];
if(clipFlags & Clipper::CLIP_PLANE2) data->clipPlane[2] = clipPlane[2];
if(clipFlags & Clipper::CLIP_PLANE3) data->clipPlane[3] = clipPlane[3];
if(clipFlags & Clipper::CLIP_PLANE4) data->clipPlane[4] = clipPlane[4];
if(clipFlags & Clipper::CLIP_PLANE5) data->clipPlane[5] = clipPlane[5];
}
}
// Target
{
for(int index = 0; index < RENDERTARGETS; index++)
{
draw->renderTarget[index] = context->renderTarget[index];
if(draw->renderTarget[index])
{
data->colorBuffer[index] = (unsigned int*)context->renderTarget[index]->lockInternal(0, 0, q * ms, LOCK_READWRITE, MANAGED);
data->colorPitchB[index] = context->renderTarget[index]->getInternalPitchB();
data->colorSliceB[index] = context->renderTarget[index]->getInternalSliceB();
}
}
draw->depthBuffer = context->depthBuffer;
draw->stencilBuffer = context->stencilBuffer;
if(draw->depthBuffer)
{
data->depthBuffer = (float*)context->depthBuffer->lockInternal(0, 0, q * ms, LOCK_READWRITE, MANAGED);
data->depthPitchB = context->depthBuffer->getInternalPitchB();
data->depthSliceB = context->depthBuffer->getInternalSliceB();
}
if(draw->stencilBuffer)
{
data->stencilBuffer = (unsigned char*)context->stencilBuffer->lockStencil(0, 0, q * ms, MANAGED);
data->stencilPitchB = context->stencilBuffer->getStencilPitchB();
data->stencilSliceB = context->stencilBuffer->getStencilSliceB();
}
}
// Scissor
{
data->scissorX0 = scissor.x0;
data->scissorX1 = scissor.x1;
data->scissorY0 = scissor.y0;
data->scissorY1 = scissor.y1;
}
draw->primitive = 0;
draw->count = count;
draw->references = (count + batch - 1) / batch;
schedulerMutex.lock();
nextDraw++;
schedulerMutex.unlock();
#ifndef NDEBUG
if(threadCount == 1) // Use main thread for draw execution
{
threadsAwake = 1;
task[0].type = Task::RESUME;
taskLoop(0);
}
else
#endif
{
if(!threadsAwake)
{
suspend[0]->wait();
threadsAwake = 1;
task[0].type = Task::RESUME;
resume[0]->signal();
}
}
}
}
void Renderer::threadFunction(void *parameters)
{
Renderer *renderer = static_cast<Parameters*>(parameters)->renderer;
int threadIndex = static_cast<Parameters*>(parameters)->threadIndex;
if(logPrecision < IEEE)
{
CPUID::setFlushToZero(true);
CPUID::setDenormalsAreZero(true);
}
renderer->threadLoop(threadIndex);
}
void Renderer::threadLoop(int threadIndex)
{
while(!exitThreads)
{
taskLoop(threadIndex);
suspend[threadIndex]->signal();
resume[threadIndex]->wait();
}
}
void Renderer::taskLoop(int threadIndex)
{
while(task[threadIndex].type != Task::SUSPEND)
{
scheduleTask(threadIndex);
executeTask(threadIndex);
}
}
void Renderer::findAvailableTasks()
{
// Find pixel tasks
for(int cluster = 0; cluster < clusterCount; cluster++)
{
if(!pixelProgress[cluster].executing)
{
for(int unit = 0; unit < unitCount; unit++)
{
if(primitiveProgress[unit].references > 0) // Contains processed primitives
{
if(pixelProgress[cluster].drawCall == primitiveProgress[unit].drawCall)
{
if(pixelProgress[cluster].processedPrimitives == primitiveProgress[unit].firstPrimitive) // Previous primitives have been rendered
{
Task &task = taskQueue[qHead];
task.type = Task::PIXELS;
task.primitiveUnit = unit;
task.pixelCluster = cluster;
pixelProgress[cluster].executing = true;
// Commit to the task queue
qHead = (qHead + 1) % 32;
qSize++;
break;
}
}
}
}
}
}
// Find primitive tasks
if(currentDraw == nextDraw)
{
return; // No more primitives to process
}
for(int unit = 0; unit < unitCount; unit++)
{
DrawCall *draw = drawList[currentDraw % DRAW_COUNT];
if(draw->primitive >= draw->count)
{
currentDraw++;
if(currentDraw == nextDraw)
{
return; // No more primitives to process
}
draw = drawList[currentDraw % DRAW_COUNT];
}
if(!primitiveProgress[unit].references) // Task not already being executed and not still in use by a pixel unit
{
int primitive = draw->primitive;
int count = draw->count;
int batch = draw->batchSize;
primitiveProgress[unit].drawCall = currentDraw;
primitiveProgress[unit].firstPrimitive = primitive;
primitiveProgress[unit].primitiveCount = count - primitive >= batch ? batch : count - primitive;
draw->primitive += batch;
Task &task = taskQueue[qHead];
task.type = Task::PRIMITIVES;
task.primitiveUnit = unit;
primitiveProgress[unit].references = -1;
// Commit to the task queue
qHead = (qHead + 1) % 32;
qSize++;
}
}
}
void Renderer::scheduleTask(int threadIndex)
{
schedulerMutex.lock();
if((int)qSize < threadCount - threadsAwake + 1)
{
findAvailableTasks();
}
if(qSize != 0)
{
task[threadIndex] = taskQueue[(qHead - qSize) % 32];
qSize--;
if(threadsAwake != threadCount)
{
int wakeup = qSize - threadsAwake + 1;
for(int i = 0; i < threadCount && wakeup > 0; i++)
{
if(task[i].type == Task::SUSPEND)
{
suspend[i]->wait();
task[i].type = Task::RESUME;
resume[i]->signal();
threadsAwake++;
wakeup--;
}
}
}
}
else
{
task[threadIndex].type = Task::SUSPEND;
threadsAwake--;
}
schedulerMutex.unlock();
}
void Renderer::executeTask(int threadIndex)
{
#if PERF_HUD
int64_t startTick = Timer::ticks();
#endif
switch(task[threadIndex].type)
{
case Task::PRIMITIVES:
{
int unit = task[threadIndex].primitiveUnit;
int input = primitiveProgress[unit].firstPrimitive;
int count = primitiveProgress[unit].primitiveCount;
DrawCall *draw = drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
int (Renderer::*setupPrimitives)(int batch, int count) = draw->setupPrimitives;
processPrimitiveVertices(unit, input, count, draw->count, threadIndex);
#if PERF_HUD
int64_t time = Timer::ticks();
vertexTime[threadIndex] += time - startTick;
startTick = time;
#endif
int visible = 0;
if(!draw->setupState.rasterizerDiscard)
{
visible = (this->*setupPrimitives)(unit, count);
}
primitiveProgress[unit].visible = visible;
primitiveProgress[unit].references = clusterCount;
#if PERF_HUD
setupTime[threadIndex] += Timer::ticks() - startTick;
#endif
}
break;
case Task::PIXELS:
{
int unit = task[threadIndex].primitiveUnit;
int visible = primitiveProgress[unit].visible;
if(visible > 0)
{
int cluster = task[threadIndex].pixelCluster;
Primitive *primitive = primitiveBatch[unit];
DrawCall *draw = drawList[pixelProgress[cluster].drawCall % DRAW_COUNT];
DrawData *data = draw->data;
PixelProcessor::RoutinePointer pixelRoutine = draw->pixelPointer;
pixelRoutine(primitive, visible, cluster, data);
}
finishRendering(task[threadIndex]);
#if PERF_HUD
pixelTime[threadIndex] += Timer::ticks() - startTick;
#endif
}
break;
case Task::RESUME:
break;
case Task::SUSPEND:
break;
default:
ASSERT(false);
}
}
void Renderer::synchronize()
{
sync->lock(sw::PUBLIC);
sync->unlock();
}
void Renderer::finishRendering(Task &pixelTask)
{
int unit = pixelTask.primitiveUnit;
int cluster = pixelTask.pixelCluster;
DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
DrawData &data = *draw.data;
int primitive = primitiveProgress[unit].firstPrimitive;
int count = primitiveProgress[unit].primitiveCount;
int processedPrimitives = primitive + count;
pixelProgress[cluster].processedPrimitives = processedPrimitives;
if(pixelProgress[cluster].processedPrimitives >= draw.count)
{
pixelProgress[cluster].drawCall++;
pixelProgress[cluster].processedPrimitives = 0;
}
int ref = atomicDecrement(&primitiveProgress[unit].references);
if(ref == 0)
{
ref = atomicDecrement(&draw.references);
if(ref == 0)
{
#if PERF_PROFILE
for(int cluster = 0; cluster < clusterCount; cluster++)
{
for(int i = 0; i < PERF_TIMERS; i++)
{
profiler.cycles[i] += data.cycles[i][cluster];
}
}
#endif
if(draw.queries)
{
for(std::list<Query*>::iterator q = draw.queries->begin(); q != draw.queries->end(); q++)
{
Query *query = *q;
switch(query->type)
{
case Query::FRAGMENTS_PASSED:
for(int cluster = 0; cluster < clusterCount; cluster++)
{
atomicAdd((volatile int*)&query->data, data.occlusion[cluster]);
}
break;
case Query::TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
atomicAdd((volatile int*)&query->data, processedPrimitives);
break;
default:
break;
}
atomicDecrement(&query->reference);
}
delete draw.queries;
draw.queries = 0;
}
for(int i = 0; i < RENDERTARGETS; i++)
{
if(draw.renderTarget[i])
{
draw.renderTarget[i]->unlockInternal();
}
}
if(draw.depthBuffer)
{
draw.depthBuffer->unlockInternal();
}
if(draw.stencilBuffer)
{
draw.stencilBuffer->unlockStencil();
}
for(int i = 0; i < TOTAL_IMAGE_UNITS; i++)
{
if(draw.texture[i])
{
draw.texture[i]->unlock();
}
}
for(int i = 0; i < MAX_VERTEX_INPUTS; i++)
{
if(draw.vertexStream[i])
{
draw.vertexStream[i]->unlock();
}
}
if(draw.indexBuffer)
{
draw.indexBuffer->unlock();
}
for(int i = 0; i < MAX_UNIFORM_BUFFER_BINDINGS; i++)
{
if(draw.pUniformBuffers[i])
{
draw.pUniformBuffers[i]->unlock();
}
if(draw.vUniformBuffers[i])
{
draw.vUniformBuffers[i]->unlock();
}
}
for(int i = 0; i < MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS; i++)
{
if(draw.transformFeedbackBuffers[i])
{
draw.transformFeedbackBuffers[i]->unlock();
}
}
draw.vertexRoutine->unbind();
draw.setupRoutine->unbind();
draw.pixelRoutine->unbind();
sync->unlock();
draw.references = -1;
resumeApp->signal();
}
}
pixelProgress[cluster].executing = false;
}
void Renderer::processPrimitiveVertices(int unit, unsigned int start, unsigned int triangleCount, unsigned int loop, int thread)
{
Triangle *triangle = triangleBatch[unit];
DrawCall *draw = drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
DrawData *data = draw->data;
VertexTask *task = vertexTask[thread];
const void *indices = data->indices;
VertexProcessor::RoutinePointer vertexRoutine = draw->vertexPointer;
if(task->vertexCache.drawCall != primitiveProgress[unit].drawCall)
{
task->vertexCache.clear();
task->vertexCache.drawCall = primitiveProgress[unit].drawCall;
}
unsigned int batch[128][3]; // FIXME: Adjust to dynamic batch size
switch(draw->drawType)
{
case DRAW_POINTLIST:
{
unsigned int index = start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index;
batch[i][1] = index;
batch[i][2] = index;
index += 1;
}
}
break;
case DRAW_LINELIST:
{
unsigned int index = 2 * start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index + 0;
batch[i][1] = index + 1;
batch[i][2] = index + 1;
index += 2;
}
}
break;
case DRAW_LINESTRIP:
{
unsigned int index = start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index + 0;
batch[i][1] = index + 1;
batch[i][2] = index + 1;
index += 1;
}
}
break;
case DRAW_LINELOOP:
{
unsigned int index = start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = (index + 0) % loop;
batch[i][1] = (index + 1) % loop;
batch[i][2] = (index + 1) % loop;
index += 1;
}
}
break;
case DRAW_TRIANGLELIST:
{
unsigned int index = 3 * start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index + 0;
batch[i][1] = index + 1;
batch[i][2] = index + 2;
index += 3;
}
}
break;
case DRAW_TRIANGLESTRIP:
{
unsigned int index = start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index + 0;
batch[i][1] = index + (index & 1) + 1;
batch[i][2] = index + (~index & 1) + 1;
index += 1;
}
}
break;
case DRAW_TRIANGLEFAN:
{
unsigned int index = start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index + 1;
batch[i][1] = index + 2;
batch[i][2] = 0;
index += 1;
}
}
break;
case DRAW_INDEXEDPOINTLIST8:
{
const unsigned char *index = (const unsigned char*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = *index;
batch[i][1] = *index;
batch[i][2] = *index;
index += 1;
}
}
break;
case DRAW_INDEXEDPOINTLIST16:
{
const unsigned short *index = (const unsigned short*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = *index;
batch[i][1] = *index;
batch[i][2] = *index;
index += 1;
}
}
break;
case DRAW_INDEXEDPOINTLIST32:
{
const unsigned int *index = (const unsigned int*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = *index;
batch[i][1] = *index;
batch[i][2] = *index;
index += 1;
}
}
break;
case DRAW_INDEXEDLINELIST8:
{
const unsigned char *index = (const unsigned char*)indices + 2 * start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[1];
index += 2;
}
}
break;
case DRAW_INDEXEDLINELIST16:
{
const unsigned short *index = (const unsigned short*)indices + 2 * start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[1];
index += 2;
}
}
break;
case DRAW_INDEXEDLINELIST32:
{
const unsigned int *index = (const unsigned int*)indices + 2 * start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[1];
index += 2;
}
}
break;
case DRAW_INDEXEDLINESTRIP8:
{
const unsigned char *index = (const unsigned char*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[1];
index += 1;
}
}
break;
case DRAW_INDEXEDLINESTRIP16:
{
const unsigned short *index = (const unsigned short*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[1];
index += 1;
}
}
break;
case DRAW_INDEXEDLINESTRIP32:
{
const unsigned int *index = (const unsigned int*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[1];
index += 1;
}
}
break;
case DRAW_INDEXEDLINELOOP8:
{
const unsigned char *index = (const unsigned char*)indices;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[(start + i + 0) % loop];
batch[i][1] = index[(start + i + 1) % loop];
batch[i][2] = index[(start + i + 1) % loop];
}
}
break;
case DRAW_INDEXEDLINELOOP16:
{
const unsigned short *index = (const unsigned short*)indices;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[(start + i + 0) % loop];
batch[i][1] = index[(start + i + 1) % loop];
batch[i][2] = index[(start + i + 1) % loop];
}
}
break;
case DRAW_INDEXEDLINELOOP32:
{
const unsigned int *index = (const unsigned int*)indices;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[(start + i + 0) % loop];
batch[i][1] = index[(start + i + 1) % loop];
batch[i][2] = index[(start + i + 1) % loop];
}
}
break;
case DRAW_INDEXEDTRIANGLELIST8:
{
const unsigned char *index = (const unsigned char*)indices + 3 * start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[2];
index += 3;
}
}
break;
case DRAW_INDEXEDTRIANGLELIST16:
{
const unsigned short *index = (const unsigned short*)indices + 3 * start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[2];
index += 3;
}
}
break;
case DRAW_INDEXEDTRIANGLELIST32:
{
const unsigned int *index = (const unsigned int*)indices + 3 * start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[1];
batch[i][2] = index[2];
index += 3;
}
}
break;
case DRAW_INDEXEDTRIANGLESTRIP8:
{
const unsigned char *index = (const unsigned char*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[((start + i) & 1) + 1];
batch[i][2] = index[(~(start + i) & 1) + 1];
index += 1;
}
}
break;
case DRAW_INDEXEDTRIANGLESTRIP16:
{
const unsigned short *index = (const unsigned short*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[((start + i) & 1) + 1];
batch[i][2] = index[(~(start + i) & 1) + 1];
index += 1;
}
}
break;
case DRAW_INDEXEDTRIANGLESTRIP32:
{
const unsigned int *index = (const unsigned int*)indices + start;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[0];
batch[i][1] = index[((start + i) & 1) + 1];
batch[i][2] = index[(~(start + i) & 1) + 1];
index += 1;
}
}
break;
case DRAW_INDEXEDTRIANGLEFAN8:
{
const unsigned char *index = (const unsigned char*)indices;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[start + i + 1];
batch[i][1] = index[start + i + 2];
batch[i][2] = index[0];
}
}
break;
case DRAW_INDEXEDTRIANGLEFAN16:
{
const unsigned short *index = (const unsigned short*)indices;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[start + i + 1];
batch[i][1] = index[start + i + 2];
batch[i][2] = index[0];
}
}
break;
case DRAW_INDEXEDTRIANGLEFAN32:
{
const unsigned int *index = (const unsigned int*)indices;
for(unsigned int i = 0; i < triangleCount; i++)
{
batch[i][0] = index[start + i + 1];
batch[i][1] = index[start + i + 2];
batch[i][2] = index[0];
}
}
break;
case DRAW_QUADLIST:
{
unsigned int index = 4 * start / 2;
for(unsigned int i = 0; i < triangleCount; i += 2)
{
batch[i+0][0] = index + 0;
batch[i+0][1] = index + 1;
batch[i+0][2] = index + 2;
batch[i+1][0] = index + 0;
batch[i+1][1] = index + 2;
batch[i+1][2] = index + 3;
index += 4;
}
}
break;
default:
ASSERT(false);
return;
}
task->primitiveStart = start;
task->vertexCount = triangleCount * 3;
vertexRoutine(&triangle->v0, (unsigned int*)&batch, task, data);
}
int Renderer::setupSolidTriangles(int unit, int count)
{
Triangle *triangle = triangleBatch[unit];
Primitive *primitive = primitiveBatch[unit];
DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
SetupProcessor::State &state = draw.setupState;
const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
int ms = state.multiSample;
int pos = state.positionRegister;
const DrawData *data = draw.data;
int visible = 0;
for(int i = 0; i < count; i++, triangle++)
{
Vertex &v0 = triangle->v0;
Vertex &v1 = triangle->v1;
Vertex &v2 = triangle->v2;
if((v0.clipFlags & v1.clipFlags & v2.clipFlags) == Clipper::CLIP_FINITE)
{
Polygon polygon(&v0.v[pos], &v1.v[pos], &v2.v[pos]);
int clipFlagsOr = v0.clipFlags | v1.clipFlags | v2.clipFlags | draw.clipFlags;
if(clipFlagsOr != Clipper::CLIP_FINITE)
{
if(!clipper->clip(polygon, clipFlagsOr, draw))
{
continue;
}
}
if(setupRoutine(primitive, triangle, &polygon, data))
{
primitive += ms;
visible++;
}
}
}
return visible;
}
int Renderer::setupWireframeTriangle(int unit, int count)
{
Triangle *triangle = triangleBatch[unit];
Primitive *primitive = primitiveBatch[unit];
int visible = 0;
DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
SetupProcessor::State &state = draw.setupState;
const Vertex &v0 = triangle[0].v0;
const Vertex &v1 = triangle[0].v1;
const Vertex &v2 = triangle[0].v2;
float d = (v0.y * v1.x - v0.x * v1.y) * v2.w + (v0.x * v2.y - v0.y * v2.x) * v1.w + (v2.x * v1.y - v1.x * v2.y) * v0.w;
if(state.cullMode == CULL_CLOCKWISE)
{
if(d >= 0) return 0;
}
else if(state.cullMode == CULL_COUNTERCLOCKWISE)
{
if(d <= 0) return 0;
}
// Copy attributes
triangle[1].v0 = v1;
triangle[1].v1 = v2;
triangle[2].v0 = v2;
triangle[2].v1 = v0;
if(state.color[0][0].flat) // FIXME
{
for(int i = 0; i < 2; i++)
{
triangle[1].v0.C[i] = triangle[0].v0.C[i];
triangle[1].v1.C[i] = triangle[0].v0.C[i];
triangle[2].v0.C[i] = triangle[0].v0.C[i];
triangle[2].v1.C[i] = triangle[0].v0.C[i];
}
}
for(int i = 0; i < 3; i++)
{
if(setupLine(*primitive, *triangle, draw))
{
primitive->area = 0.5f * d;
primitive++;
visible++;
}
triangle++;
}
return visible;
}
int Renderer::setupVertexTriangle(int unit, int count)
{
Triangle *triangle = triangleBatch[unit];
Primitive *primitive = primitiveBatch[unit];
int visible = 0;
DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
SetupProcessor::State &state = draw.setupState;
const Vertex &v0 = triangle[0].v0;
const Vertex &v1 = triangle[0].v1;
const Vertex &v2 = triangle[0].v2;
float d = (v0.y * v1.x - v0.x * v1.y) * v2.w + (v0.x * v2.y - v0.y * v2.x) * v1.w + (v2.x * v1.y - v1.x * v2.y) * v0.w;
if(state.cullMode == CULL_CLOCKWISE)
{
if(d >= 0) return 0;
}
else if(state.cullMode == CULL_COUNTERCLOCKWISE)
{
if(d <= 0) return 0;
}
// Copy attributes
triangle[1].v0 = v1;
triangle[2].v0 = v2;
for(int i = 0; i < 3; i++)
{
if(setupPoint(*primitive, *triangle, draw))
{
primitive->area = 0.5f * d;
primitive++;
visible++;
}
triangle++;
}
return visible;
}
int Renderer::setupLines(int unit, int count)
{
Triangle *triangle = triangleBatch[unit];
Primitive *primitive = primitiveBatch[unit];
int visible = 0;
DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
SetupProcessor::State &state = draw.setupState;
int ms = state.multiSample;
for(int i = 0; i < count; i++)
{
if(setupLine(*primitive, *triangle, draw))
{
primitive += ms;
visible++;
}
triangle++;
}
return visible;
}
int Renderer::setupPoints(int unit, int count)
{
Triangle *triangle = triangleBatch[unit];
Primitive *primitive = primitiveBatch[unit];
int visible = 0;
DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
SetupProcessor::State &state = draw.setupState;
int ms = state.multiSample;
for(int i = 0; i < count; i++)
{
if(setupPoint(*primitive, *triangle, draw))
{
primitive += ms;
visible++;
}
triangle++;
}
return visible;
}
bool Renderer::setupLine(Primitive &primitive, Triangle &triangle, const DrawCall &draw)
{
const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
const SetupProcessor::State &state = draw.setupState;
const DrawData &data = *draw.data;
float lineWidth = data.lineWidth;
Vertex &v0 = triangle.v0;
Vertex &v1 = triangle.v1;
int pos = state.positionRegister;
const float4 &P0 = v0.v[pos];
const float4 &P1 = v1.v[pos];
if(P0.w <= 0 && P1.w <= 0)
{
return false;
}
const float W = data.Wx16[0] * (1.0f / 16.0f);
const float H = data.Hx16[0] * (1.0f / 16.0f);
float dx = W * (P1.x / P1.w - P0.x / P0.w);
float dy = H * (P1.y / P1.w - P0.y / P0.w);
if(dx == 0 && dy == 0)
{
return false;
}
if(false) // Rectangle
{
float4 P[4];
int C[4];
P[0] = P0;
P[1] = P1;
P[2] = P1;
P[3] = P0;
float scale = lineWidth * 0.5f / sqrt(dx*dx + dy*dy);
dx *= scale;
dy *= scale;
float dx0w = dx * P0.w / W;
float dy0h = dy * P0.w / H;
float dx0h = dx * P0.w / H;
float dy0w = dy * P0.w / W;
float dx1w = dx * P1.w / W;
float dy1h = dy * P1.w / H;
float dx1h = dx * P1.w / H;
float dy1w = dy * P1.w / W;
P[0].x += -dy0w + -dx0w;
P[0].y += -dx0h + +dy0h;
C[0] = clipper->computeClipFlags(P[0]);
P[1].x += -dy1w + +dx1w;
P[1].y += -dx1h + +dy1h;
C[1] = clipper->computeClipFlags(P[1]);
P[2].x += +dy1w + +dx1w;
P[2].y += +dx1h + -dy1h;
C[2] = clipper->computeClipFlags(P[2]);
P[3].x += +dy0w + -dx0w;
P[3].y += +dx0h + +dy0h;
C[3] = clipper->computeClipFlags(P[3]);
if((C[0] & C[1] & C[2] & C[3]) == Clipper::CLIP_FINITE)
{
Polygon polygon(P, 4);
int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | draw.clipFlags;
if(clipFlagsOr != Clipper::CLIP_FINITE)
{
if(!clipper->clip(polygon, clipFlagsOr, draw))
{
return false;
}
}
return setupRoutine(&primitive, &triangle, &polygon, &data);
}
}
else // Diamond test convention
{
float4 P[8];
int C[8];
P[0] = P0;
P[1] = P0;
P[2] = P0;
P[3] = P0;
P[4] = P1;
P[5] = P1;
P[6] = P1;
P[7] = P1;
float dx0 = lineWidth * 0.5f * P0.w / W;
float dy0 = lineWidth * 0.5f * P0.w / H;
float dx1 = lineWidth * 0.5f * P1.w / W;
float dy1 = lineWidth * 0.5f * P1.w / H;
P[0].x += -dx0;
C[0] = clipper->computeClipFlags(P[0]);
P[1].y += +dy0;
C[1] = clipper->computeClipFlags(P[1]);
P[2].x += +dx0;
C[2] = clipper->computeClipFlags(P[2]);
P[3].y += -dy0;
C[3] = clipper->computeClipFlags(P[3]);
P[4].x += -dx1;
C[4] = clipper->computeClipFlags(P[4]);
P[5].y += +dy1;
C[5] = clipper->computeClipFlags(P[5]);
P[6].x += +dx1;
C[6] = clipper->computeClipFlags(P[6]);
P[7].y += -dy1;
C[7] = clipper->computeClipFlags(P[7]);
if((C[0] & C[1] & C[2] & C[3] & C[4] & C[5] & C[6] & C[7]) == Clipper::CLIP_FINITE)
{
float4 L[6];
if(dx > -dy)
{
if(dx > dy) // Right
{
L[0] = P[0];
L[1] = P[1];
L[2] = P[5];
L[3] = P[6];
L[4] = P[7];
L[5] = P[3];
}
else // Down
{
L[0] = P[0];
L[1] = P[4];
L[2] = P[5];
L[3] = P[6];
L[4] = P[2];
L[5] = P[3];
}
}
else
{
if(dx > dy) // Up
{
L[0] = P[0];
L[1] = P[1];
L[2] = P[2];
L[3] = P[6];
L[4] = P[7];
L[5] = P[4];
}
else // Left
{
L[0] = P[1];
L[1] = P[2];
L[2] = P[3];
L[3] = P[7];
L[4] = P[4];
L[5] = P[5];
}
}
Polygon polygon(L, 6);
int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | C[4] | C[5] | C[6] | C[7] | draw.clipFlags;
if(clipFlagsOr != Clipper::CLIP_FINITE)
{
if(!clipper->clip(polygon, clipFlagsOr, draw))
{
return false;
}
}
return setupRoutine(&primitive, &triangle, &polygon, &data);
}
}
return false;
}
bool Renderer::setupPoint(Primitive &primitive, Triangle &triangle, const DrawCall &draw)
{
const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
const SetupProcessor::State &state = draw.setupState;
const DrawData &data = *draw.data;
Vertex &v = triangle.v0;
float pSize;
int pts = state.pointSizeRegister;
if(state.pointSizeRegister != Unused)
{
pSize = v.v[pts].y;
}
else
{
pSize = data.point.pointSize[0];
}
pSize = clamp(pSize, data.point.pointSizeMin, data.point.pointSizeMax);
float4 P[4];
int C[4];
int pos = state.positionRegister;
P[0] = v.v[pos];
P[1] = v.v[pos];
P[2] = v.v[pos];
P[3] = v.v[pos];
const float X = pSize * P[0].w * data.halfPixelX[0];
const float Y = pSize * P[0].w * data.halfPixelY[0];
P[0].x -= X;
P[0].y += Y;
C[0] = clipper->computeClipFlags(P[0]);
P[1].x += X;
P[1].y += Y;
C[1] = clipper->computeClipFlags(P[1]);
P[2].x += X;
P[2].y -= Y;
C[2] = clipper->computeClipFlags(P[2]);
P[3].x -= X;
P[3].y -= Y;
C[3] = clipper->computeClipFlags(P[3]);
triangle.v1 = triangle.v0;
triangle.v2 = triangle.v0;
triangle.v1.X += iround(16 * 0.5f * pSize);
triangle.v2.Y -= iround(16 * 0.5f * pSize) * (data.Hx16[0] > 0.0f ? 1 : -1); // Both Direct3D and OpenGL expect (0, 0) in the top-left corner
Polygon polygon(P, 4);
if((C[0] & C[1] & C[2] & C[3]) == Clipper::CLIP_FINITE)
{
int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | draw.clipFlags;
if(clipFlagsOr != Clipper::CLIP_FINITE)
{
if(!clipper->clip(polygon, clipFlagsOr, draw))
{
return false;
}
}
return setupRoutine(&primitive, &triangle, &polygon, &data);
}
return false;
}
void Renderer::initializeThreads()
{
unitCount = ceilPow2(threadCount);
clusterCount = ceilPow2(threadCount);
for(int i = 0; i < unitCount; i++)
{
triangleBatch[i] = (Triangle*)allocate(batchSize * sizeof(Triangle));
primitiveBatch[i] = (Primitive*)allocate(batchSize * sizeof(Primitive));
}
for(int i = 0; i < threadCount; i++)
{
vertexTask[i] = (VertexTask*)allocate(sizeof(VertexTask));
vertexTask[i]->vertexCache.drawCall = -1;
task[i].type = Task::SUSPEND;
resume[i] = new Event();
suspend[i] = new Event();
Parameters parameters;
parameters.threadIndex = i;
parameters.renderer = this;
exitThreads = false;
worker[i] = new Thread(threadFunction, ¶meters);
suspend[i]->wait();
suspend[i]->signal();
}
}
void Renderer::terminateThreads()
{
while(threadsAwake != 0)
{
Thread::sleep(1);
}
for(int thread = 0; thread < threadCount; thread++)
{
if(worker[thread])
{
exitThreads = true;
resume[thread]->signal();
worker[thread]->join();
delete worker[thread];
worker[thread] = 0;
delete resume[thread];
resume[thread] = 0;
delete suspend[thread];
suspend[thread] = 0;
}
deallocate(vertexTask[thread]);
vertexTask[thread] = 0;
}
for(int i = 0; i < 16; i++)
{
deallocate(triangleBatch[i]);
triangleBatch[i] = 0;
deallocate(primitiveBatch[i]);
primitiveBatch[i] = 0;
}
}
void Renderer::loadConstants(const VertexShader *vertexShader)
{
if(!vertexShader) return;
size_t count = vertexShader->getLength();
for(size_t i = 0; i < count; i++)
{
const Shader::Instruction *instruction = vertexShader->getInstruction(i);
if(instruction->opcode == Shader::OPCODE_DEF)
{
int index = instruction->dst.index;
float value[4];
value[0] = instruction->src[0].value[0];
value[1] = instruction->src[0].value[1];
value[2] = instruction->src[0].value[2];
value[3] = instruction->src[0].value[3];
setVertexShaderConstantF(index, value);
}
else if(instruction->opcode == Shader::OPCODE_DEFI)
{
int index = instruction->dst.index;
int integer[4];
integer[0] = instruction->src[0].integer[0];
integer[1] = instruction->src[0].integer[1];
integer[2] = instruction->src[0].integer[2];
integer[3] = instruction->src[0].integer[3];
setVertexShaderConstantI(index, integer);
}
else if(instruction->opcode == Shader::OPCODE_DEFB)
{
int index = instruction->dst.index;
int boolean = instruction->src[0].boolean[0];
setVertexShaderConstantB(index, &boolean);
}
}
}
void Renderer::loadConstants(const PixelShader *pixelShader)
{
if(!pixelShader) return;
size_t count = pixelShader->getLength();
for(size_t i = 0; i < count; i++)
{
const Shader::Instruction *instruction = pixelShader->getInstruction(i);
if(instruction->opcode == Shader::OPCODE_DEF)
{
int index = instruction->dst.index;
float value[4];
value[0] = instruction->src[0].value[0];
value[1] = instruction->src[0].value[1];
value[2] = instruction->src[0].value[2];
value[3] = instruction->src[0].value[3];
setPixelShaderConstantF(index, value);
}
else if(instruction->opcode == Shader::OPCODE_DEFI)
{
int index = instruction->dst.index;
int integer[4];
integer[0] = instruction->src[0].integer[0];
integer[1] = instruction->src[0].integer[1];
integer[2] = instruction->src[0].integer[2];
integer[3] = instruction->src[0].integer[3];
setPixelShaderConstantI(index, integer);
}
else if(instruction->opcode == Shader::OPCODE_DEFB)
{
int index = instruction->dst.index;
int boolean = instruction->src[0].boolean[0];
setPixelShaderConstantB(index, &boolean);
}
}
}
void Renderer::setIndexBuffer(Resource *indexBuffer)
{
context->indexBuffer = indexBuffer;
}
void Renderer::setMultiSampleMask(unsigned int mask)
{
context->sampleMask = mask;
}
void Renderer::setTransparencyAntialiasing(TransparencyAntialiasing transparencyAntialiasing)
{
sw::transparencyAntialiasing = transparencyAntialiasing;
}
bool Renderer::isReadWriteTexture(int sampler)
{
for(int index = 0; index < RENDERTARGETS; index++)
{
if(context->renderTarget[index] && context->texture[sampler] == context->renderTarget[index]->getResource())
{
return true;
}
}
if(context->depthBuffer && context->texture[sampler] == context->depthBuffer->getResource())
{
return true;
}
return false;
}
void Renderer::updateClipper()
{
if(updateClipPlanes)
{
if(VertexProcessor::isFixedFunction()) // User plane in world space
{
const Matrix &scissorWorld = getViewTransform();
if(clipFlags & Clipper::CLIP_PLANE0) clipPlane[0] = scissorWorld * userPlane[0];
if(clipFlags & Clipper::CLIP_PLANE1) clipPlane[1] = scissorWorld * userPlane[1];
if(clipFlags & Clipper::CLIP_PLANE2) clipPlane[2] = scissorWorld * userPlane[2];
if(clipFlags & Clipper::CLIP_PLANE3) clipPlane[3] = scissorWorld * userPlane[3];
if(clipFlags & Clipper::CLIP_PLANE4) clipPlane[4] = scissorWorld * userPlane[4];
if(clipFlags & Clipper::CLIP_PLANE5) clipPlane[5] = scissorWorld * userPlane[5];
}
else // User plane in clip space
{
if(clipFlags & Clipper::CLIP_PLANE0) clipPlane[0] = userPlane[0];
if(clipFlags & Clipper::CLIP_PLANE1) clipPlane[1] = userPlane[1];
if(clipFlags & Clipper::CLIP_PLANE2) clipPlane[2] = userPlane[2];
if(clipFlags & Clipper::CLIP_PLANE3) clipPlane[3] = userPlane[3];
if(clipFlags & Clipper::CLIP_PLANE4) clipPlane[4] = userPlane[4];
if(clipFlags & Clipper::CLIP_PLANE5) clipPlane[5] = userPlane[5];
}
updateClipPlanes = false;
}
}
void Renderer::setTextureResource(unsigned int sampler, Resource *resource)
{
ASSERT(sampler < TOTAL_IMAGE_UNITS);
context->texture[sampler] = resource;
}
void Renderer::setTextureLevel(unsigned int sampler, unsigned int face, unsigned int level, Surface *surface, TextureType type)
{
ASSERT(sampler < TOTAL_IMAGE_UNITS && face < 6 && level < MIPMAP_LEVELS);
context->sampler[sampler].setTextureLevel(face, level, surface, type);
}
void Renderer::setTextureFilter(SamplerType type, int sampler, FilterType textureFilter)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setTextureFilter(sampler, textureFilter);
}
else
{
VertexProcessor::setTextureFilter(sampler, textureFilter);
}
}
void Renderer::setMipmapFilter(SamplerType type, int sampler, MipmapType mipmapFilter)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setMipmapFilter(sampler, mipmapFilter);
}
else
{
VertexProcessor::setMipmapFilter(sampler, mipmapFilter);
}
}
void Renderer::setGatherEnable(SamplerType type, int sampler, bool enable)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setGatherEnable(sampler, enable);
}
else
{
VertexProcessor::setGatherEnable(sampler, enable);
}
}
void Renderer::setAddressingModeU(SamplerType type, int sampler, AddressingMode addressMode)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setAddressingModeU(sampler, addressMode);
}
else
{
VertexProcessor::setAddressingModeU(sampler, addressMode);
}
}
void Renderer::setAddressingModeV(SamplerType type, int sampler, AddressingMode addressMode)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setAddressingModeV(sampler, addressMode);
}
else
{
VertexProcessor::setAddressingModeV(sampler, addressMode);
}
}
void Renderer::setAddressingModeW(SamplerType type, int sampler, AddressingMode addressMode)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setAddressingModeW(sampler, addressMode);
}
else
{
VertexProcessor::setAddressingModeW(sampler, addressMode);
}
}
void Renderer::setReadSRGB(SamplerType type, int sampler, bool sRGB)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setReadSRGB(sampler, sRGB);
}
else
{
VertexProcessor::setReadSRGB(sampler, sRGB);
}
}
void Renderer::setMipmapLOD(SamplerType type, int sampler, float bias)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setMipmapLOD(sampler, bias);
}
else
{
VertexProcessor::setMipmapLOD(sampler, bias);
}
}
void Renderer::setBorderColor(SamplerType type, int sampler, const Color<float> &borderColor)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setBorderColor(sampler, borderColor);
}
else
{
VertexProcessor::setBorderColor(sampler, borderColor);
}
}
void Renderer::setMaxAnisotropy(SamplerType type, int sampler, float maxAnisotropy)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setMaxAnisotropy(sampler, maxAnisotropy);
}
else
{
VertexProcessor::setMaxAnisotropy(sampler, maxAnisotropy);
}
}
void Renderer::setSwizzleR(SamplerType type, int sampler, SwizzleType swizzleR)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setSwizzleR(sampler, swizzleR);
}
else
{
VertexProcessor::setSwizzleR(sampler, swizzleR);
}
}
void Renderer::setSwizzleG(SamplerType type, int sampler, SwizzleType swizzleG)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setSwizzleG(sampler, swizzleG);
}
else
{
VertexProcessor::setSwizzleG(sampler, swizzleG);
}
}
void Renderer::setSwizzleB(SamplerType type, int sampler, SwizzleType swizzleB)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setSwizzleB(sampler, swizzleB);
}
else
{
VertexProcessor::setSwizzleB(sampler, swizzleB);
}
}
void Renderer::setSwizzleA(SamplerType type, int sampler, SwizzleType swizzleA)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setSwizzleA(sampler, swizzleA);
}
else
{
VertexProcessor::setSwizzleA(sampler, swizzleA);
}
}
void Renderer::setBaseLevel(SamplerType type, int sampler, int baseLevel)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setBaseLevel(sampler, baseLevel);
}
else
{
VertexProcessor::setBaseLevel(sampler, baseLevel);
}
}
void Renderer::setMaxLevel(SamplerType type, int sampler, int maxLevel)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setMaxLevel(sampler, maxLevel);
}
else
{
VertexProcessor::setMaxLevel(sampler, maxLevel);
}
}
void Renderer::setMinLod(SamplerType type, int sampler, float minLod)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setMinLod(sampler, minLod);
}
else
{
VertexProcessor::setMinLod(sampler, minLod);
}
}
void Renderer::setMaxLod(SamplerType type, int sampler, float maxLod)
{
if(type == SAMPLER_PIXEL)
{
PixelProcessor::setMaxLod(sampler, maxLod);
}
else
{
VertexProcessor::setMaxLod(sampler, maxLod);
}
}
void Renderer::setPointSpriteEnable(bool pointSpriteEnable)
{
context->setPointSpriteEnable(pointSpriteEnable);
}
void Renderer::setPointScaleEnable(bool pointScaleEnable)
{
context->setPointScaleEnable(pointScaleEnable);
}
void Renderer::setLineWidth(float width)
{
context->lineWidth = width;
}
void Renderer::setDepthBias(float bias)
{
depthBias = bias;
}
void Renderer::setSlopeDepthBias(float slopeBias)
{
slopeDepthBias = slopeBias;
}
void Renderer::setRasterizerDiscard(bool rasterizerDiscard)
{
context->rasterizerDiscard = rasterizerDiscard;
}
void Renderer::setPixelShader(const PixelShader *shader)
{
context->pixelShader = shader;
loadConstants(shader);
}
void Renderer::setVertexShader(const VertexShader *shader)
{
context->vertexShader = shader;
loadConstants(shader);
}
void Renderer::setPixelShaderConstantF(int index, const float value[4], int count)
{
for(int i = 0; i < DRAW_COUNT; i++)
{
if(drawCall[i]->psDirtyConstF < index + count)
{
drawCall[i]->psDirtyConstF = index + count;
}
}
for(int i = 0; i < count; i++)
{
PixelProcessor::setFloatConstant(index + i, value);
value += 4;
}
}
void Renderer::setPixelShaderConstantI(int index, const int value[4], int count)
{
for(int i = 0; i < DRAW_COUNT; i++)
{
if(drawCall[i]->psDirtyConstI < index + count)
{
drawCall[i]->psDirtyConstI = index + count;
}
}
for(int i = 0; i < count; i++)
{
PixelProcessor::setIntegerConstant(index + i, value);
value += 4;
}
}
void Renderer::setPixelShaderConstantB(int index, const int *boolean, int count)
{
for(int i = 0; i < DRAW_COUNT; i++)
{
if(drawCall[i]->psDirtyConstB < index + count)
{
drawCall[i]->psDirtyConstB = index + count;
}
}
for(int i = 0; i < count; i++)
{
PixelProcessor::setBooleanConstant(index + i, *boolean);
boolean++;
}
}
void Renderer::setVertexShaderConstantF(int index, const float value[4], int count)
{
for(int i = 0; i < DRAW_COUNT; i++)
{
if(drawCall[i]->vsDirtyConstF < index + count)
{
drawCall[i]->vsDirtyConstF = index + count;
}
}
for(int i = 0; i < count; i++)
{
VertexProcessor::setFloatConstant(index + i, value);
value += 4;
}
}
void Renderer::setVertexShaderConstantI(int index, const int value[4], int count)
{
for(int i = 0; i < DRAW_COUNT; i++)
{
if(drawCall[i]->vsDirtyConstI < index + count)
{
drawCall[i]->vsDirtyConstI = index + count;
}
}
for(int i = 0; i < count; i++)
{
VertexProcessor::setIntegerConstant(index + i, value);
value += 4;
}
}
void Renderer::setVertexShaderConstantB(int index, const int *boolean, int count)
{
for(int i = 0; i < DRAW_COUNT; i++)
{
if(drawCall[i]->vsDirtyConstB < index + count)
{
drawCall[i]->vsDirtyConstB = index + count;
}
}
for(int i = 0; i < count; i++)
{
VertexProcessor::setBooleanConstant(index + i, *boolean);
boolean++;
}
}
void Renderer::setModelMatrix(const Matrix &M, int i)
{
VertexProcessor::setModelMatrix(M, i);
}
void Renderer::setViewMatrix(const Matrix &V)
{
VertexProcessor::setViewMatrix(V);
updateClipPlanes = true;
}
void Renderer::setBaseMatrix(const Matrix &B)
{
VertexProcessor::setBaseMatrix(B);
updateClipPlanes = true;
}
void Renderer::setProjectionMatrix(const Matrix &P)
{
VertexProcessor::setProjectionMatrix(P);
updateClipPlanes = true;
}
void Renderer::addQuery(Query *query)
{
queries.push_back(query);
}
void Renderer::removeQuery(Query *query)
{
queries.remove(query);
}
#if PERF_HUD
int Renderer::getThreadCount()
{
return threadCount;
}
int64_t Renderer::getVertexTime(int thread)
{
return vertexTime[thread];
}
int64_t Renderer::getSetupTime(int thread)
{
return setupTime[thread];
}
int64_t Renderer::getPixelTime(int thread)
{
return pixelTime[thread];
}
void Renderer::resetTimers()
{
for(int thread = 0; thread < threadCount; thread++)
{
vertexTime[thread] = 0;
setupTime[thread] = 0;
pixelTime[thread] = 0;
}
}
#endif
void Renderer::setViewport(const Viewport &viewport)
{
this->viewport = viewport;
}
void Renderer::setScissor(const Rect &scissor)
{
this->scissor = scissor;
}
void Renderer::setClipFlags(int flags)
{
clipFlags = flags << 8; // Bottom 8 bits used by legacy frustum
}
void Renderer::setClipPlane(unsigned int index, const float plane[4])
{
if(index < MAX_CLIP_PLANES)
{
userPlane[index] = plane;
}
else ASSERT(false);
updateClipPlanes = true;
}
void Renderer::updateConfiguration(bool initialUpdate)
{
bool newConfiguration = swiftConfig->hasNewConfiguration();
if(newConfiguration || initialUpdate)
{
terminateThreads();
SwiftConfig::Configuration configuration = {};
swiftConfig->getConfiguration(configuration);
precacheVertex = !newConfiguration && configuration.precache;
precacheSetup = !newConfiguration && configuration.precache;
precachePixel = !newConfiguration && configuration.precache;
VertexProcessor::setRoutineCacheSize(configuration.vertexRoutineCacheSize);
PixelProcessor::setRoutineCacheSize(configuration.pixelRoutineCacheSize);
SetupProcessor::setRoutineCacheSize(configuration.setupRoutineCacheSize);
switch(configuration.textureSampleQuality)
{
case 0: Sampler::setFilterQuality(FILTER_POINT); break;
case 1: Sampler::setFilterQuality(FILTER_LINEAR); break;
case 2: Sampler::setFilterQuality(FILTER_ANISOTROPIC); break;
default: Sampler::setFilterQuality(FILTER_ANISOTROPIC); break;
}
switch(configuration.mipmapQuality)
{
case 0: Sampler::setMipmapQuality(MIPMAP_POINT); break;
case 1: Sampler::setMipmapQuality(MIPMAP_LINEAR); break;
default: Sampler::setMipmapQuality(MIPMAP_LINEAR); break;
}
setPerspectiveCorrection(configuration.perspectiveCorrection);
switch(configuration.transcendentalPrecision)
{
case 0:
logPrecision = APPROXIMATE;
expPrecision = APPROXIMATE;
rcpPrecision = APPROXIMATE;
rsqPrecision = APPROXIMATE;
break;
case 1:
logPrecision = PARTIAL;
expPrecision = PARTIAL;
rcpPrecision = PARTIAL;
rsqPrecision = PARTIAL;
break;
case 2:
logPrecision = ACCURATE;
expPrecision = ACCURATE;
rcpPrecision = ACCURATE;
rsqPrecision = ACCURATE;
break;
case 3:
logPrecision = WHQL;
expPrecision = WHQL;
rcpPrecision = WHQL;
rsqPrecision = WHQL;
break;
case 4:
logPrecision = IEEE;
expPrecision = IEEE;
rcpPrecision = IEEE;
rsqPrecision = IEEE;
break;
default:
logPrecision = ACCURATE;
expPrecision = ACCURATE;
rcpPrecision = ACCURATE;
rsqPrecision = ACCURATE;
break;
}
switch(configuration.transparencyAntialiasing)
{
case 0: transparencyAntialiasing = TRANSPARENCY_NONE; break;
case 1: transparencyAntialiasing = TRANSPARENCY_ALPHA_TO_COVERAGE; break;
default: transparencyAntialiasing = TRANSPARENCY_NONE; break;
}
switch(configuration.threadCount)
{
case -1: threadCount = CPUID::coreCount(); break;
case 0: threadCount = CPUID::processAffinity(); break;
default: threadCount = configuration.threadCount; break;
}
CPUID::setEnableSSE4_1(configuration.enableSSE4_1);
CPUID::setEnableSSSE3(configuration.enableSSSE3);
CPUID::setEnableSSE3(configuration.enableSSE3);
CPUID::setEnableSSE2(configuration.enableSSE2);
CPUID::setEnableSSE(configuration.enableSSE);
for(int pass = 0; pass < 10; pass++)
{
optimization[pass] = configuration.optimization[pass];
}
forceWindowed = configuration.forceWindowed;
complementaryDepthBuffer = configuration.complementaryDepthBuffer;
postBlendSRGB = configuration.postBlendSRGB;
exactColorRounding = configuration.exactColorRounding;
forceClearRegisters = configuration.forceClearRegisters;
#ifndef NDEBUG
minPrimitives = configuration.minPrimitives;
maxPrimitives = configuration.maxPrimitives;
#endif
}
if(!initialUpdate && !worker[0])
{
initializeThreads();
}
}
}
|
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: ImageRegistration1.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
// Software Guide : BeginCommandLineArgs
// INPUTS: {BrainProtonDensitySliceBorder20.png}
// INPUTS: {BrainProtonDensitySliceShifted13x17y.png}
// OUTPUTS: {ImageRegistration1Output.png}
// OUTPUTS: {ImageRegistration1DifferenceAfter.png}
// OUTPUTS: {ImageRegistration1DifferenceBefore.png}
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example illustrates the use of the image registration framework in
// Insight. It should be read as a "Hello World" for ITK
// registration. Which means that for now you don't ask "why?". Instead,
// use the example as an introduction to the typical elements involved in
// solving an image registration problem.
//
// \index{itk::Image!Instantiation}
// \index{itk::Image!Header}
//
// A registration method requires the following set of components: two input
// images, a transform, a metric, an interpolator and an optimizer. Some of
// these components are parametrized by the image type for which the
// registration is intended. The following header files provide declarations
// of common types used for these components.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkImageRegistrationMethod.h"
#include "itkTranslationTransform.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkRegularStepGradientDescentOptimizer.h"
#include "itkImage.h"
// Software Guide : EndCodeSnippet
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkSubtractImageFilter.h"
int main( int argc, char *argv[] )
{
if( argc < 4 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " fixedImageFile movingImageFile ";
std::cerr << "outputImagefile [differenceImageAfter]";
std::cerr << "[differenceImageBefore]" << std::endl;
return 1;
}
// Software Guide : BeginLatex
//
// The types of each one of the components in the registration methods should
// be instantiated. First, we select the image dimension and the type used for
// representing image pixels.
//
// Software Guide : EndLatex
//
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 2;
typedef float PixelType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The types of the input images are instantiated by the following lines.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::Image< PixelType, Dimension > FixedImageType;
typedef itk::Image< PixelType, Dimension > MovingImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The transform that will map one image space into the other is defined
// below.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::TranslationTransform< double, Dimension > TransformType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// An optimizer is required to explore the parameter space of the transform
// in search of optimal values of the metric.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The metric will compare how well the two images match each other. Metric
// types are usually parametrized by the image types as can be seen in the
// following type declaration.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::MeanSquaresImageToImageMetric<
FixedImageType,
MovingImageType > MetricType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally, the type of the interpolator is declared. The interpolator will
// evaluate the moving image at non-grid positions.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk:: LinearInterpolateImageFunction<
MovingImageType,
double > InterpolatorType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The registration method type is instantiated using the types of the
// fixed and moving images. This class is responsible for interconnecting
// all the components we have described so far.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::ImageRegistrationMethod<
FixedImageType,
MovingImageType > RegistrationType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Each one of the registration components is created using its
// \code{New()} method and is assigned to its respective
// \doxygen{SmartPointer}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
MetricType::Pointer metric = MetricType::New();
TransformType::Pointer transform = TransformType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
RegistrationType::Pointer registration = RegistrationType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Each component is now connected to the instance of the registration method.
// \index{itk::RegistrationMethod!SetMetric()}
// \index{itk::RegistrationMethod!SetOptimizer()}
// \index{itk::RegistrationMethod!SetTransform()}
// \index{itk::RegistrationMethod!SetFixedImage()}
// \index{itk::RegistrationMethod!SetMovingImage()}
// \index{itk::RegistrationMethod!SetInterpolator()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
registration->SetMetric( metric );
registration->SetOptimizer( optimizer );
registration->SetTransform( transform );
registration->SetInterpolator( interpolator );
// Software Guide : EndCodeSnippet
typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;
typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;
FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();
MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();
fixedImageReader->SetFileName( argv[1] );
movingImageReader->SetFileName( argv[2] );
// Software Guide : BeginLatex
//
// In this example, the fixed and moving images are read from files. This
// requires the \doxygen{ImageRegistrationMethod} to acquire its inputs from
// the output of the readers.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
registration->SetFixedImage( fixedImageReader->GetOutput() );
registration->SetMovingImage( movingImageReader->GetOutput() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The registration can be restricted to consider only a particular region
// of the fixed image as input to the metric computation. This region is
// defined by the \code{SetFixedImageRegion()} method. You could use this
// feature to reduce the computational time of the registration or to avoid
// unwanted objects present in the image from affecting the registration outcome.
// In this example we use the full available content of the image. This
// region is identified by the \code{BufferedRegion} of the fixed image.
// Note that for this region to be valid the reader must first invoke its
// \code{Update()} method.
//
// \index{itk::ImageRegistrationMethod!SetFixedImageRegion()}
// \index{itk::Image!GetBufferedRegion()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
fixedImageReader->Update();
registration->SetFixedImageRegion(
fixedImageReader->GetOutput()->GetBufferedRegion() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The parameters of the transform are initialized by passing them in an
// array. This can be used to setup an initial known correction of the
// misalignment. In this particular case, a translation transform is
// being used for the registration. The array of parameters for this
// transform is simply composed of the translation values along each
// dimension. Setting the values of the parameters to zero
// initializes the transform as an \emph{identity} transform. Note that the
// array constructor requires the number of elements as an argument.
//
// \index{itk::TranslationTransform!GetNumberOfParameters()}
// \index{itk::RegistrationMethod!SetInitialTransformParameters()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef RegistrationType::ParametersType ParametersType;
ParametersType initialParameters( transform->GetNumberOfParameters() );
initialParameters[0] = 0.0; // Initial offset in mm along X
initialParameters[1] = 0.0; // Initial offset in mm along Y
registration->SetInitialTransformParameters( initialParameters );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// At this point the registration method is ready for execution. The
// optimizer is the component that drives the execution of the
// registration. However, the ImageRegistrationMethod class
// orchestrates the ensemble to make sure that everything is in place
// before control is passed to the optimizer.
//
// It is usually desirable to fine tune the parameters of the optimizer.
// Each optimizer has particular parameters that must be interpreted in the
// context of the optimization strategy it implements. The optimizer used in
// this example is a variant of gradient descent that attempts to prevent it
// from taking steps which are too large. At each iteration, this optimizer
// will take a step along the direction of the \doxygen{ImageToImageMetric}
// derivative. The initial length of the step is defined by the user. Each
// time the direction of the derivative abruptly changes, the optimizer
// assumes that a local extrema has been passed and reacts by reducing the
// step length by a half. After several reductions of the step length, the
// optimizer may be moving in a very restricted area of the transform
// parameter space. The user can define how small the step length should be
// to consider convergence to have been reached. This is equivalent to defining
// the precision with which the final transform should be known.
//
// The initial step length is defined with the method
// \code{SetMaximumStepLength()}, while the tolerance for convergence is
// defined with the method \code{SetMinimumStepLength()}.
//
// \index{itk::Regular\-Setp\-Gradient\-Descent\-Optimizer!SetMaximumStepLength()}
// \index{itk::Regular\-Step\-Gradient\-Descent\-Optimizer!SetMinimumStepLength()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
optimizer->SetMaximumStepLength( 4.00 );
optimizer->SetMinimumStepLength( 0.01 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// In case the optimizer never succeeds reaching the desired
// precision tolerance, it is prudent to establish a limit on the number of
// iterations to be performed. This maximum number is defined with the
// method \code{SetNumberOfIterations()}.
//
// \index{itk::Regular\-Setp\-Gradient\-Descent\-Optimizer!SetNumberOfIterations()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
optimizer->SetNumberOfIterations( 200 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The registration process is triggered by an invocation of the
// \code{Update()} method. If something goes wrong during the
// initialization or execution of the registration an exception will be
// thrown. We should therefore place the \code{Update()} method
// inside a \code{try/catch} block as illustrated in the following lines.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
try
{
registration->Update();
}
catch( itk::ExceptionObject & err )
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// In a real application, you may attempt to recover from the error in the
// catch block. Here we are simply printing out a message and then
// terminating the execution of the program.
//
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// The result of the registration process is an array of parameters that
// defines the spatial transformation in an unique way. This final result is
// obtained using the \code{GetLastTransformParameters()} method.
//
// \index{itk::RegistrationMethod!GetLastTransformParameters()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ParametersType finalParameters = registration->GetLastTransformParameters();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// In the case of the \doxygen{TranslationTransform}, there is a
// straightforward interpretation of the parameters. Each element of the
// array corresponds to a translation along one spatial dimension.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const double TranslationAlongX = finalParameters[0];
const double TranslationAlongY = finalParameters[1];
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The optimizer can be queried for the actual number of iterations
// performed to reach convergence. The \code{GetCurrentIteration()}
// method returns this value. A large number of iterations may be an
// indication that the maximum step length has been set too small, which
// is undesirable since it results in long computational times.
//
// \index{itk::Regular\-Setp\-Gradient\-Descent\-Optimizer!GetCurrentIteration()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int numberOfIterations = optimizer->GetCurrentIteration();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The value of the image metric corresponding to the last set of parameters
// can be obtained with the \code{GetValue()} method of the optimizer.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const double bestValue = optimizer->GetValue();
// Software Guide : EndCodeSnippet
// Print out results
//
std::cout << "Result = " << std::endl;
std::cout << " Translation X = " << TranslationAlongX << std::endl;
std::cout << " Translation Y = " << TranslationAlongY << std::endl;
std::cout << " Iterations = " << numberOfIterations << std::endl;
std::cout << " Metric value = " << bestValue << std::endl;
// Software Guide : BeginLatex
//
// Let's execute this example over two of the images provided in
// \code{Examples/Data}:
//
// \begin{itemize}
// \item \code{BrainProtonDensitySliceBorder20.png}
// \item \code{BrainProtonDensitySliceShifted13x17y.png}
// \end{itemize}
//
// The second image is the result of intentionally translating the first
// image by $(13,17)$ millimeters. Both images have unit-spacing and
// are shown in Figure \ref{fig:FixedMovingImageRegistration1}. The
// registration takes 18 iterations and the resulting transform parameters are:
//
// \begin{verbatim}
// Translation X = 12.9959
// Translation Y = 17.0001
// \end{verbatim}
//
// As expected, these values match quite well the misalignment that we
// intentionally introduced in the moving image.
//
// \begin{figure}
// \center
// \includegraphics[width=0.44\textwidth]{BrainProtonDensitySliceBorder20.eps}
// \includegraphics[width=0.44\textwidth]{BrainProtonDensitySliceShifted13x17y.eps}
// \itkcaption[Fixed and Moving images in registration framework]{Fixed and
// Moving image provided as input to the registration method.}
// \label{fig:FixedMovingImageRegistration1}
// \end{figure}
//
//
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// It is common, as the last step of a registration task, to use the
// resulting transform to map the moving image into the fixed image space.
// This is easily done with the \doxygen{ResampleImageFilter}. Please
// refer to Section~\ref{sec:ResampleImageFilter} for details on the use
// of this filter. First, a ResampleImageFilter type is instantiated
// using the image types. It is convenient to use the fixed image type as
// the output type since it is likely that the transformed moving image
// will be compared with the fixed image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::ResampleImageFilter<
MovingImageType,
FixedImageType > ResampleFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// A resampling filter is created and the moving image is connected as
// its input.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ResampleFilterType::Pointer resampler = ResampleFilterType::New();
resampler->SetInput( movingImageReader->GetOutput() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The Transform that is produced as output of the Registration method is
// also passed as input to the resampling filter. Note the use of the
// methods \code{GetOutput()} and \code{Get()}. This combination is needed
// here because the registration method acts as a filter whose output is a
// transform decorated in the form of a \doxygen{DataObject}. For details in
// this construction you may want to read the documentation of the
// \doxygen{DataObjectDecorator}.
//
// \index{itk::ImageRegistrationMethod!Resampling image}
// \index{itk::DataObjectDecorator!Use in Registration}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
resampler->SetTransform( registration->GetOutput()->Get() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// As described in Section \ref{sec:ResampleImageFilter}, the
// ResampleImageFilter requires additional parameters to be
// specified, in particular, the spacing, origin and size of the output
// image. The default pixel value is also set to a distinct gray level in
// order highlight the regions that are mapped outside of the moving image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();
resampler->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() );
resampler->SetOutputOrigin( fixedImage->GetOrigin() );
resampler->SetOutputSpacing( fixedImage->GetSpacing() );
resampler->SetDefaultPixelValue( 100 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// \begin{figure}
// \center
// \includegraphics[width=0.32\textwidth]{ImageRegistration1Output.eps}
// \includegraphics[width=0.32\textwidth]{ImageRegistration1DifferenceBefore.eps}
// \includegraphics[width=0.32\textwidth]{ImageRegistration1DifferenceAfter.eps}
// \itkcaption[HelloWorld registration output images]{Mapped moving image and its
// difference with the fixed image before and after registration}
// \label{fig:ImageRegistration1Output}
// \end{figure}
//
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// The output of the filter is passed to a writer that will store the
// image in a file. An \doxygen{CastImageFilter} is used to convert the
// pixel type of the resampled image to the final type used by the
// writer. The cast and writer filters are instantiated below.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
// typedef unsigned char OutputPixelType;
typedef float OutputPixelType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
typedef itk::CastImageFilter<
FixedImageType,
OutputImageType > CastFilterType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The filters are created by invoking their \code{New()}
// method.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
WriterType::Pointer writer = WriterType::New();
CastFilterType::Pointer caster = CastFilterType::New();
// Software Guide : EndCodeSnippet
writer->SetFileName( argv[3] );
// Software Guide : BeginLatex
//
// The \code{Update()} method of the writer is invoked in order to trigger
// the execution of the pipeline.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
caster->SetInput( resampler->GetOutput() );
writer->SetInput( caster->GetOutput() );
writer->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// \begin{figure}
// \center
// \includegraphics[width=\textwidth]{ImageRegistration1Pipeline.eps}
// \itkcaption[Pipeline structure of the registration example]{Pipeline
// structure of the registration example.}
// \label{fig:ImageRegistration1Pipeline}
// \end{figure}
//
//
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// The fixed image and the transformed moving image can easily be compared
// using the \doxygen{SubtractImageFilter}. This pixel-wise filter computes
// the difference between homologous pixels of its two input images.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::SubtractImageFilter<
FixedImageType,
FixedImageType,
FixedImageType > DifferenceFilterType;
DifferenceFilterType::Pointer difference = DifferenceFilterType::New();
difference->SetInput1( fixedImageReader->GetOutput() );
difference->SetInput2( resampler->GetOutput() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Since the differences between the two images may correspond to very low
// values of intensity, we rescale those intensities with a
// \doxygen{RescaleIntensityImageFilter} in order to make them more visible.
// This rescaling will also make possible to visualize the negative values
// in standard image file formats. We also reduce the
// \code{DefaultPixelValue} in order to prevent that value from absorving
// the dynamic range of the differences between the two images.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::RescaleIntensityImageFilter<
FixedImageType,
OutputImageType > RescalerType;
RescalerType::Pointer intensityRescaler = RescalerType::New();
intensityRescaler->SetInput( difference->GetOutput() );
intensityRescaler->SetOutputMinimum( 0 );
intensityRescaler->SetOutputMaximum( 255 );
resampler->SetDefaultPixelValue( 1 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Its output can be passed to another writer.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
WriterType::Pointer writer2 = WriterType::New();
writer2->SetInput( intensityRescaler->GetOutput() );
// Software Guide : EndCodeSnippet
if( argc >= 4 )
{
writer2->SetFileName( argv[4] );
writer2->Update();
}
// Software Guide : BeginLatex
//
// For the purpose of comparison, the difference between the fixed image and
// the moving image before registration can also be computed by simply
// setting the transform to an identity transform. Note that the resampling
// is still necessary because the moving image does not necessarily have the
// same spacing, origin and number of pixels as the fixed image. Therefore a
// pixel-by-pixel operation cannot in general be performed. The resampling
// process with an identity transform will ensure that we have a
// representation of the moving image in the grid of the fixed image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
transform->SetIdentity();
resampler->SetTransform( transform );
// Software Guide : EndCodeSnippet
if( argc >= 5 )
{
writer2->SetFileName( argv[5] );
writer2->Update();
}
// Software Guide : BeginLatex
//
// The complete pipeline structure of the current example is presented in
// Figure~\ref{fig:ImageRegistration1Pipeline}. The components of the
// registration method are depicted as well. Figure
// \ref{fig:ImageRegistration1Output} (left) shows the result of resampling
// the moving image in order to map it onto the fixed image space. The top
// and right borders of the image appear in the gray level selected with the
// \code{SetDefaultPixelValue()} in the ResampleImageFilter. The
// center image shows the squared difference between the fixed image and
// the moving image. The right image shows the squared difference between
// the fixed image and the transformed moving image. Both difference images
// are displayed negated in order to accentuate those pixels where differences
// exist.
//
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// \begin{figure}
// \center
// \includegraphics[height=0.44\textwidth]{ImageRegistration1TraceTranslations.eps}
// \includegraphics[height=0.44\textwidth]{ImageRegistration1TraceMetric.eps}
// \itkcaption[Trace of translations and metrics during registration]{The sequence
// of translations and metric values at each iteration of the optimizer.}
// \label{fig:ImageRegistration1Trace}
// \end{figure}
//
// It is always useful to keep in mind that registration is essentially an
// optimization problem. Figure \ref{fig:ImageRegistration1Trace} helps to
// reinforce this notion by showing the trace of translations and values of
// the image metric at each iteration of the optimizer. It can be seen from
// the top figure that the step length is reduced progressively as the
// optimizer gets closer to the metric extrema. The bottom plot clearly
// shows how the metric value decreases as the optimization advances. The
// log plot helps to highlight the normal oscilations of the optimizer
// around the extrema value.
//
// Software Guide : EndLatex
return 0;
}
ENH: Output pixel type set to unsigned char again.
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: ImageRegistration1.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
// Software Guide : BeginCommandLineArgs
// INPUTS: {BrainProtonDensitySliceBorder20.png}
// INPUTS: {BrainProtonDensitySliceShifted13x17y.png}
// OUTPUTS: {ImageRegistration1Output.png}
// OUTPUTS: {ImageRegistration1DifferenceAfter.png}
// OUTPUTS: {ImageRegistration1DifferenceBefore.png}
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example illustrates the use of the image registration framework in
// Insight. It should be read as a "Hello World" for ITK
// registration. Which means that for now you don't ask "why?". Instead,
// use the example as an introduction to the typical elements involved in
// solving an image registration problem.
//
// \index{itk::Image!Instantiation}
// \index{itk::Image!Header}
//
// A registration method requires the following set of components: two input
// images, a transform, a metric, an interpolator and an optimizer. Some of
// these components are parametrized by the image type for which the
// registration is intended. The following header files provide declarations
// of common types used for these components.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkImageRegistrationMethod.h"
#include "itkTranslationTransform.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkRegularStepGradientDescentOptimizer.h"
#include "itkImage.h"
// Software Guide : EndCodeSnippet
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkSubtractImageFilter.h"
int main( int argc, char *argv[] )
{
if( argc < 4 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " fixedImageFile movingImageFile ";
std::cerr << "outputImagefile [differenceImageAfter]";
std::cerr << "[differenceImageBefore]" << std::endl;
return 1;
}
// Software Guide : BeginLatex
//
// The types of each one of the components in the registration methods should
// be instantiated. First, we select the image dimension and the type used for
// representing image pixels.
//
// Software Guide : EndLatex
//
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 2;
typedef float PixelType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The types of the input images are instantiated by the following lines.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::Image< PixelType, Dimension > FixedImageType;
typedef itk::Image< PixelType, Dimension > MovingImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The transform that will map one image space into the other is defined
// below.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::TranslationTransform< double, Dimension > TransformType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// An optimizer is required to explore the parameter space of the transform
// in search of optimal values of the metric.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The metric will compare how well the two images match each other. Metric
// types are usually parametrized by the image types as can be seen in the
// following type declaration.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::MeanSquaresImageToImageMetric<
FixedImageType,
MovingImageType > MetricType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally, the type of the interpolator is declared. The interpolator will
// evaluate the moving image at non-grid positions.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk:: LinearInterpolateImageFunction<
MovingImageType,
double > InterpolatorType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The registration method type is instantiated using the types of the
// fixed and moving images. This class is responsible for interconnecting
// all the components we have described so far.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::ImageRegistrationMethod<
FixedImageType,
MovingImageType > RegistrationType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Each one of the registration components is created using its
// \code{New()} method and is assigned to its respective
// \doxygen{SmartPointer}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
MetricType::Pointer metric = MetricType::New();
TransformType::Pointer transform = TransformType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
RegistrationType::Pointer registration = RegistrationType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Each component is now connected to the instance of the registration method.
// \index{itk::RegistrationMethod!SetMetric()}
// \index{itk::RegistrationMethod!SetOptimizer()}
// \index{itk::RegistrationMethod!SetTransform()}
// \index{itk::RegistrationMethod!SetFixedImage()}
// \index{itk::RegistrationMethod!SetMovingImage()}
// \index{itk::RegistrationMethod!SetInterpolator()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
registration->SetMetric( metric );
registration->SetOptimizer( optimizer );
registration->SetTransform( transform );
registration->SetInterpolator( interpolator );
// Software Guide : EndCodeSnippet
typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;
typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;
FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();
MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();
fixedImageReader->SetFileName( argv[1] );
movingImageReader->SetFileName( argv[2] );
// Software Guide : BeginLatex
//
// In this example, the fixed and moving images are read from files. This
// requires the \doxygen{ImageRegistrationMethod} to acquire its inputs from
// the output of the readers.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
registration->SetFixedImage( fixedImageReader->GetOutput() );
registration->SetMovingImage( movingImageReader->GetOutput() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The registration can be restricted to consider only a particular region
// of the fixed image as input to the metric computation. This region is
// defined by the \code{SetFixedImageRegion()} method. You could use this
// feature to reduce the computational time of the registration or to avoid
// unwanted objects present in the image from affecting the registration outcome.
// In this example we use the full available content of the image. This
// region is identified by the \code{BufferedRegion} of the fixed image.
// Note that for this region to be valid the reader must first invoke its
// \code{Update()} method.
//
// \index{itk::ImageRegistrationMethod!SetFixedImageRegion()}
// \index{itk::Image!GetBufferedRegion()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
fixedImageReader->Update();
registration->SetFixedImageRegion(
fixedImageReader->GetOutput()->GetBufferedRegion() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The parameters of the transform are initialized by passing them in an
// array. This can be used to setup an initial known correction of the
// misalignment. In this particular case, a translation transform is
// being used for the registration. The array of parameters for this
// transform is simply composed of the translation values along each
// dimension. Setting the values of the parameters to zero
// initializes the transform as an \emph{identity} transform. Note that the
// array constructor requires the number of elements as an argument.
//
// \index{itk::TranslationTransform!GetNumberOfParameters()}
// \index{itk::RegistrationMethod!SetInitialTransformParameters()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef RegistrationType::ParametersType ParametersType;
ParametersType initialParameters( transform->GetNumberOfParameters() );
initialParameters[0] = 0.0; // Initial offset in mm along X
initialParameters[1] = 0.0; // Initial offset in mm along Y
registration->SetInitialTransformParameters( initialParameters );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// At this point the registration method is ready for execution. The
// optimizer is the component that drives the execution of the
// registration. However, the ImageRegistrationMethod class
// orchestrates the ensemble to make sure that everything is in place
// before control is passed to the optimizer.
//
// It is usually desirable to fine tune the parameters of the optimizer.
// Each optimizer has particular parameters that must be interpreted in the
// context of the optimization strategy it implements. The optimizer used in
// this example is a variant of gradient descent that attempts to prevent it
// from taking steps which are too large. At each iteration, this optimizer
// will take a step along the direction of the \doxygen{ImageToImageMetric}
// derivative. The initial length of the step is defined by the user. Each
// time the direction of the derivative abruptly changes, the optimizer
// assumes that a local extrema has been passed and reacts by reducing the
// step length by a half. After several reductions of the step length, the
// optimizer may be moving in a very restricted area of the transform
// parameter space. The user can define how small the step length should be
// to consider convergence to have been reached. This is equivalent to defining
// the precision with which the final transform should be known.
//
// The initial step length is defined with the method
// \code{SetMaximumStepLength()}, while the tolerance for convergence is
// defined with the method \code{SetMinimumStepLength()}.
//
// \index{itk::Regular\-Setp\-Gradient\-Descent\-Optimizer!SetMaximumStepLength()}
// \index{itk::Regular\-Step\-Gradient\-Descent\-Optimizer!SetMinimumStepLength()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
optimizer->SetMaximumStepLength( 4.00 );
optimizer->SetMinimumStepLength( 0.01 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// In case the optimizer never succeeds reaching the desired
// precision tolerance, it is prudent to establish a limit on the number of
// iterations to be performed. This maximum number is defined with the
// method \code{SetNumberOfIterations()}.
//
// \index{itk::Regular\-Setp\-Gradient\-Descent\-Optimizer!SetNumberOfIterations()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
optimizer->SetNumberOfIterations( 200 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The registration process is triggered by an invocation of the
// \code{Update()} method. If something goes wrong during the
// initialization or execution of the registration an exception will be
// thrown. We should therefore place the \code{Update()} method
// inside a \code{try/catch} block as illustrated in the following lines.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
try
{
registration->Update();
}
catch( itk::ExceptionObject & err )
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// In a real application, you may attempt to recover from the error in the
// catch block. Here we are simply printing out a message and then
// terminating the execution of the program.
//
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// The result of the registration process is an array of parameters that
// defines the spatial transformation in an unique way. This final result is
// obtained using the \code{GetLastTransformParameters()} method.
//
// \index{itk::RegistrationMethod!GetLastTransformParameters()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ParametersType finalParameters = registration->GetLastTransformParameters();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// In the case of the \doxygen{TranslationTransform}, there is a
// straightforward interpretation of the parameters. Each element of the
// array corresponds to a translation along one spatial dimension.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const double TranslationAlongX = finalParameters[0];
const double TranslationAlongY = finalParameters[1];
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The optimizer can be queried for the actual number of iterations
// performed to reach convergence. The \code{GetCurrentIteration()}
// method returns this value. A large number of iterations may be an
// indication that the maximum step length has been set too small, which
// is undesirable since it results in long computational times.
//
// \index{itk::Regular\-Setp\-Gradient\-Descent\-Optimizer!GetCurrentIteration()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int numberOfIterations = optimizer->GetCurrentIteration();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The value of the image metric corresponding to the last set of parameters
// can be obtained with the \code{GetValue()} method of the optimizer.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const double bestValue = optimizer->GetValue();
// Software Guide : EndCodeSnippet
// Print out results
//
std::cout << "Result = " << std::endl;
std::cout << " Translation X = " << TranslationAlongX << std::endl;
std::cout << " Translation Y = " << TranslationAlongY << std::endl;
std::cout << " Iterations = " << numberOfIterations << std::endl;
std::cout << " Metric value = " << bestValue << std::endl;
// Software Guide : BeginLatex
//
// Let's execute this example over two of the images provided in
// \code{Examples/Data}:
//
// \begin{itemize}
// \item \code{BrainProtonDensitySliceBorder20.png}
// \item \code{BrainProtonDensitySliceShifted13x17y.png}
// \end{itemize}
//
// The second image is the result of intentionally translating the first
// image by $(13,17)$ millimeters. Both images have unit-spacing and
// are shown in Figure \ref{fig:FixedMovingImageRegistration1}. The
// registration takes 18 iterations and the resulting transform parameters are:
//
// \begin{verbatim}
// Translation X = 12.9959
// Translation Y = 17.0001
// \end{verbatim}
//
// As expected, these values match quite well the misalignment that we
// intentionally introduced in the moving image.
//
// \begin{figure}
// \center
// \includegraphics[width=0.44\textwidth]{BrainProtonDensitySliceBorder20.eps}
// \includegraphics[width=0.44\textwidth]{BrainProtonDensitySliceShifted13x17y.eps}
// \itkcaption[Fixed and Moving images in registration framework]{Fixed and
// Moving image provided as input to the registration method.}
// \label{fig:FixedMovingImageRegistration1}
// \end{figure}
//
//
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// It is common, as the last step of a registration task, to use the
// resulting transform to map the moving image into the fixed image space.
// This is easily done with the \doxygen{ResampleImageFilter}. Please
// refer to Section~\ref{sec:ResampleImageFilter} for details on the use
// of this filter. First, a ResampleImageFilter type is instantiated
// using the image types. It is convenient to use the fixed image type as
// the output type since it is likely that the transformed moving image
// will be compared with the fixed image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::ResampleImageFilter<
MovingImageType,
FixedImageType > ResampleFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// A resampling filter is created and the moving image is connected as
// its input.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ResampleFilterType::Pointer resampler = ResampleFilterType::New();
resampler->SetInput( movingImageReader->GetOutput() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The Transform that is produced as output of the Registration method is
// also passed as input to the resampling filter. Note the use of the
// methods \code{GetOutput()} and \code{Get()}. This combination is needed
// here because the registration method acts as a filter whose output is a
// transform decorated in the form of a \doxygen{DataObject}. For details in
// this construction you may want to read the documentation of the
// \doxygen{DataObjectDecorator}.
//
// \index{itk::ImageRegistrationMethod!Resampling image}
// \index{itk::DataObjectDecorator!Use in Registration}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
resampler->SetTransform( registration->GetOutput()->Get() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// As described in Section \ref{sec:ResampleImageFilter}, the
// ResampleImageFilter requires additional parameters to be
// specified, in particular, the spacing, origin and size of the output
// image. The default pixel value is also set to a distinct gray level in
// order highlight the regions that are mapped outside of the moving image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();
resampler->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() );
resampler->SetOutputOrigin( fixedImage->GetOrigin() );
resampler->SetOutputSpacing( fixedImage->GetSpacing() );
resampler->SetDefaultPixelValue( 100 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// \begin{figure}
// \center
// \includegraphics[width=0.32\textwidth]{ImageRegistration1Output.eps}
// \includegraphics[width=0.32\textwidth]{ImageRegistration1DifferenceBefore.eps}
// \includegraphics[width=0.32\textwidth]{ImageRegistration1DifferenceAfter.eps}
// \itkcaption[HelloWorld registration output images]{Mapped moving image and its
// difference with the fixed image before and after registration}
// \label{fig:ImageRegistration1Output}
// \end{figure}
//
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// The output of the filter is passed to a writer that will store the
// image in a file. An \doxygen{CastImageFilter} is used to convert the
// pixel type of the resampled image to the final type used by the
// writer. The cast and writer filters are instantiated below.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
// typedef unsigned char OutputPixelType;
typedef unsigned char OutputPixelType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
typedef itk::CastImageFilter<
FixedImageType,
OutputImageType > CastFilterType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The filters are created by invoking their \code{New()}
// method.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
WriterType::Pointer writer = WriterType::New();
CastFilterType::Pointer caster = CastFilterType::New();
// Software Guide : EndCodeSnippet
writer->SetFileName( argv[3] );
// Software Guide : BeginLatex
//
// The \code{Update()} method of the writer is invoked in order to trigger
// the execution of the pipeline.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
caster->SetInput( resampler->GetOutput() );
writer->SetInput( caster->GetOutput() );
writer->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// \begin{figure}
// \center
// \includegraphics[width=\textwidth]{ImageRegistration1Pipeline.eps}
// \itkcaption[Pipeline structure of the registration example]{Pipeline
// structure of the registration example.}
// \label{fig:ImageRegistration1Pipeline}
// \end{figure}
//
//
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// The fixed image and the transformed moving image can easily be compared
// using the \doxygen{SubtractImageFilter}. This pixel-wise filter computes
// the difference between homologous pixels of its two input images.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::SubtractImageFilter<
FixedImageType,
FixedImageType,
FixedImageType > DifferenceFilterType;
DifferenceFilterType::Pointer difference = DifferenceFilterType::New();
difference->SetInput1( fixedImageReader->GetOutput() );
difference->SetInput2( resampler->GetOutput() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Since the differences between the two images may correspond to very low
// values of intensity, we rescale those intensities with a
// \doxygen{RescaleIntensityImageFilter} in order to make them more visible.
// This rescaling will also make possible to visualize the negative values
// in standard image file formats. We also reduce the
// \code{DefaultPixelValue} in order to prevent that value from absorving
// the dynamic range of the differences between the two images.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::RescaleIntensityImageFilter<
FixedImageType,
OutputImageType > RescalerType;
RescalerType::Pointer intensityRescaler = RescalerType::New();
intensityRescaler->SetInput( difference->GetOutput() );
intensityRescaler->SetOutputMinimum( 0 );
intensityRescaler->SetOutputMaximum( 255 );
resampler->SetDefaultPixelValue( 1 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Its output can be passed to another writer.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
WriterType::Pointer writer2 = WriterType::New();
writer2->SetInput( intensityRescaler->GetOutput() );
// Software Guide : EndCodeSnippet
if( argc >= 4 )
{
writer2->SetFileName( argv[4] );
writer2->Update();
}
// Software Guide : BeginLatex
//
// For the purpose of comparison, the difference between the fixed image and
// the moving image before registration can also be computed by simply
// setting the transform to an identity transform. Note that the resampling
// is still necessary because the moving image does not necessarily have the
// same spacing, origin and number of pixels as the fixed image. Therefore a
// pixel-by-pixel operation cannot in general be performed. The resampling
// process with an identity transform will ensure that we have a
// representation of the moving image in the grid of the fixed image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
transform->SetIdentity();
resampler->SetTransform( transform );
// Software Guide : EndCodeSnippet
if( argc >= 5 )
{
writer2->SetFileName( argv[5] );
writer2->Update();
}
// Software Guide : BeginLatex
//
// The complete pipeline structure of the current example is presented in
// Figure~\ref{fig:ImageRegistration1Pipeline}. The components of the
// registration method are depicted as well. Figure
// \ref{fig:ImageRegistration1Output} (left) shows the result of resampling
// the moving image in order to map it onto the fixed image space. The top
// and right borders of the image appear in the gray level selected with the
// \code{SetDefaultPixelValue()} in the ResampleImageFilter. The
// center image shows the squared difference between the fixed image and
// the moving image. The right image shows the squared difference between
// the fixed image and the transformed moving image. Both difference images
// are displayed negated in order to accentuate those pixels where differences
// exist.
//
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// \begin{figure}
// \center
// \includegraphics[height=0.44\textwidth]{ImageRegistration1TraceTranslations.eps}
// \includegraphics[height=0.44\textwidth]{ImageRegistration1TraceMetric.eps}
// \itkcaption[Trace of translations and metrics during registration]{The sequence
// of translations and metric values at each iteration of the optimizer.}
// \label{fig:ImageRegistration1Trace}
// \end{figure}
//
// It is always useful to keep in mind that registration is essentially an
// optimization problem. Figure \ref{fig:ImageRegistration1Trace} helps to
// reinforce this notion by showing the trace of translations and values of
// the image metric at each iteration of the optimizer. It can be seen from
// the top figure that the step length is reduced progressively as the
// optimizer gets closer to the metric extrema. The bottom plot clearly
// shows how the metric value decreases as the optimization advances. The
// log plot helps to highlight the normal oscilations of the optimizer
// around the extrema value.
//
// Software Guide : EndLatex
return 0;
}
|
// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, 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
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local includes
#include "libmesh_config.h"
#include "boundary_info.h"
#include "boundary_mesh.h"
#include "elem.h"
#include "mesh_data.h"
#include "parallel.h"
//------------------------------------------------------
// BoundaryInfo static member initializations
const short int BoundaryInfo::invalid_id = -1234;
//------------------------------------------------------
// BoundaryInfo functions
BoundaryInfo::BoundaryInfo(const MeshBase& m) :
_mesh (m)
{
}
BoundaryInfo::~BoundaryInfo()
{
this->clear();
}
void BoundaryInfo::clear()
{
_boundary_node_id.clear();
_boundary_side_id.clear();
_boundary_ids.clear();
}
void BoundaryInfo::sync(BoundaryMesh& boundary_mesh,
MeshData* boundary_mesh_data,
MeshData* this_mesh_data)
{
boundary_mesh.clear();
/**
* Re-create the boundary mesh.
*/
boundary_mesh.set_n_subdomains() = this->n_boundary_ids();
boundary_mesh.set_n_partitions() = this->n_boundary_ids();
// Add sides to the structure.
std::map<short int, unsigned int> id_map;
// Original Code
// unsigned int cnt = 0;
// for (std::set<short int>::iterator pos = boundary_ids.begin();
// pos != boundary_ids.end(); ++pos)
// id_map[*pos] = cnt++;
// id_map[invalid_id] = cnt;
// New code
// Here we need to use iota() once it is in the
// Utility namespace.
std::for_each(_boundary_ids.begin(),
_boundary_ids.end(),
Fill(id_map));
boundary_mesh.set_n_subdomains() = id_map.size();
// Make individual copies of all the nodes in the current mesh
// and add them to the boundary mesh. Yes, this is overkill because
// all of the current mesh nodes will not end up in the the boundary
// mesh. These nodes can be trimmed later via a call to prepare_for_use().
{
libmesh_assert (boundary_mesh.n_nodes() == 0);
boundary_mesh.reserve_nodes(_mesh.n_nodes());
MeshBase::const_node_iterator it = _mesh.nodes_begin();
MeshBase::const_node_iterator end = _mesh.nodes_end();
for(; it != end; ++it)
{
const Node* node = *it;
boundary_mesh.add_point(*node); // calls Node::build(Point, id)
}
}
// Add additional sides that aren't flagged with boundary conditions
MeshBase::const_element_iterator el = _mesh.active_elements_begin();
const MeshBase::const_element_iterator end_el = _mesh.active_elements_end();
for ( ; el != end_el; ++el)
{
const Elem* elem = *el;
for (unsigned int s=0; s<elem->n_sides(); s++)
if (elem->neighbor(s) == NULL) // on the boundary
{
// Build the side - do not use a "proxy" element here:
// This will be going into the BoundaryMesh and needs to
// stand on its own.
AutoPtr<Elem> side (elem->build_side(s, false));
// Get the top-level parent for this element
const Elem* top_parent = elem->top_parent();
// A convenient typedef
typedef
std::multimap<const Elem*, std::pair<unsigned short int, short int> >::const_iterator
Iter;
// Find the right id number for that side
std::pair<Iter, Iter> pos = _boundary_side_id.equal_range(top_parent);
while (pos.first != pos.second)
{
if (pos.first->second.first == s) // already flagged with a boundary condition
{
side->subdomain_id() =
id_map[pos.first->second.second];
side->processor_id() =
side->subdomain_id();
break;
}
++pos.first;
}
// either the element wasn't found or side s
// doesn't have a boundary condition
if (pos.first == pos.second)
{
side->subdomain_id() = id_map[invalid_id];
}
// Add the side
Elem* new_elem = boundary_mesh.add_elem(side.release());
// This side's Node pointers still point to the nodes of the original mesh.
// We need to re-point them to the boundary mesh's nodes! Since we copied *ALL* of
// the original mesh's nodes over, we should be guaranteed to have the same ordering.
for (unsigned int nn=0; nn<new_elem->n_nodes(); ++nn)
{
// Get the correct node pointer, based on the id()
Node* new_node = boundary_mesh.node_ptr(new_elem->node(nn));
// sanity check: be sure that the new Nodes global id really matches
libmesh_assert (new_node->id() == new_elem->node(nn));
// Assign the new node pointer
new_elem->set_node(nn) = new_node;
}
}
} // end loop over active elements
// When desired, copy the MeshData
// to the boundary_mesh
if ((boundary_mesh_data != NULL) && (this_mesh_data != NULL))
boundary_mesh_data->assign(*this_mesh_data);
// Don't repartition this mesh; we're using the processor_id values
// as a hack to display bcids for now.
boundary_mesh.partitioner().reset(NULL);
// Trim any un-used nodes from the Mesh
boundary_mesh.prepare_for_use();
}
void BoundaryInfo::add_node(const unsigned int node,
const short int id)
{
this->add_node (_mesh.node_ptr(node), id);
}
void BoundaryInfo::add_node(const Node* node,
const short int id)
{
if (id == invalid_id)
{
std::cerr << "ERROR: You may not set a boundary ID of "
<< invalid_id << std::endl
<< " That is reserved for internal use.\n"
<< std::endl;
libmesh_error();
}
_boundary_node_id[node] = id;
_boundary_ids.insert(id);
}
void BoundaryInfo::add_side(const unsigned int e,
const unsigned short int side,
const short int id)
{
this->add_side (_mesh.elem(e), side, id);
}
void BoundaryInfo::add_side(const Elem* elem,
const unsigned short int side,
const short int id)
{
libmesh_assert (elem != NULL);
// Only add BCs for level-0 elements.
libmesh_assert (elem->level() == 0);
if (id == invalid_id)
{
std::cerr << "ERROR: You may not set a boundary ID of "
<< invalid_id << std::endl
<< " That is reserved for internal use.\n"
<< std::endl;
libmesh_error();
}
std::pair<unsigned short int, short int> p(side,id);
std::pair<const Elem*, std::pair<unsigned short int, short int> >
kv (elem, p);
_boundary_side_id.insert(kv);
_boundary_ids.insert(id);
}
short int BoundaryInfo::boundary_id(const Node* node) const
{
std::map<const Node*, short int>::const_iterator
n = _boundary_node_id.find(node);
// node not in the data structure
if (n == _boundary_node_id.end())
return invalid_id;
return n->second;
}
short int BoundaryInfo::boundary_id(const Elem* const elem,
const unsigned short int side) const
{
libmesh_assert (elem != NULL);
// Only level-0 elements store BCs. If this is not a level-0
// element get its level-0 parent and infer the BCs.
const Elem* searched_elem = elem;
if (elem->level() != 0)
searched_elem = elem->top_parent ();
std::pair<std::multimap<const Elem*,
std::pair<unsigned short int, short int> >::const_iterator,
std::multimap<const Elem*,
std::pair<unsigned short int, short int> >::const_iterator >
e = _boundary_side_id.equal_range(searched_elem);
// elem not in the data structure
if (e.first == e.second)
return invalid_id;
// elem is there, maybe multiple occurances
while (e.first != e.second)
{
// if this is true we found the requested side
// of the element and want to return the id
if (e.first->second.first == side)
return e.first->second.second;
++e.first;
}
// if we get here, we found elem in the data structure but not
// the requested side, so return the default value
return invalid_id;
}
unsigned int BoundaryInfo::side_with_boundary_id(const Elem* const elem,
const unsigned short int boundary_id) const
{
const Elem* searched_elem = elem;
if (elem->level() != 0)
searched_elem = elem->top_parent();
std::pair<std::multimap<const Elem*,
std::pair<unsigned short int, short int> >::const_iterator,
std::multimap<const Elem*,
std::pair<unsigned short int, short int> >::const_iterator >
e = _boundary_side_id.equal_range(searched_elem);
// elem not in the data structure
if (e.first == e.second)
return libMesh::invalid_uint;
// elem is there, maybe multiple occurances
while (e.first != e.second)
{
// if this is true we found the requested boundary_id
// of the element and want to return the side
if (e.first->second.second == boundary_id)
return e.first->second.first;
++e.first;
}
// if we get here, we found elem in the data structure but not
// the requested boundary id, so return the default value
return libMesh::invalid_uint;
}
unsigned int BoundaryInfo::n_boundary_conds () const
{
// in serial we know the number of bcs from the
// size of the container
if (_mesh.is_serial())
return _boundary_side_id.size();
// in parallel we need to sum the number of local bcs
parallel_only();
unsigned int nbcs=0;
std::multimap<const Elem*,
std::pair<unsigned short int,
short int> >::const_iterator pos;
for (pos=_boundary_side_id.begin(); pos != _boundary_side_id.end(); ++pos)
if (pos->first->processor_id() == libMesh::processor_id())
nbcs++;
Parallel::sum (nbcs);
return nbcs;
}
void BoundaryInfo::build_node_list (std::vector<unsigned int>& nl,
std::vector<short int>& il) const
{
// Reserve the size, then use push_back
nl.reserve (_boundary_node_id.size());
il.reserve (_boundary_node_id.size());
std::map<const Node*, short int>::const_iterator pos
= _boundary_node_id.begin();
for (; pos != _boundary_node_id.end(); ++pos)
{
nl.push_back (pos->first->id());
il.push_back (pos->second);
}
}
void BoundaryInfo::build_side_list (std::vector<unsigned int>& el,
std::vector<unsigned short int>& sl,
std::vector<short int>& il) const
{
// Reserve the size, then use push_back
el.reserve (_boundary_side_id.size());
sl.reserve (_boundary_side_id.size());
il.reserve (_boundary_side_id.size());
std::multimap<const Elem*,
std::pair<unsigned short int,
short int> >::const_iterator pos;
for (pos=_boundary_side_id.begin(); pos != _boundary_side_id.end();
++pos)
{
el.push_back (pos->first->id());
sl.push_back (pos->second.first);
il.push_back (pos->second.second);
}
}
void BoundaryInfo::print_info() const
{
// Print out the nodal BCs
if (!_boundary_node_id.empty())
{
std::cout << "Nodal Boundary conditions:" << std::endl
<< "--------------------------" << std::endl
<< " (Node No., ID) " << std::endl;
// std::for_each(_boundary_node_id.begin(),
// _boundary_node_id.end(),
// PrintNodeInfo());
std::map<const Node*, short int>::const_iterator it = _boundary_node_id.begin();
const std::map<const Node*, short int>::const_iterator end = _boundary_node_id.end();
for (; it != end; ++it)
std::cout << " (" << (*it).first->id()
<< ", " << (*it).second
<< ")" << std::endl;
}
// Print out the element BCs
if (!_boundary_side_id.empty())
{
std::cout << std::endl
<< "Side Boundary conditions:" << std::endl
<< "-------------------------" << std::endl
<< " (Elem No., Side No., ID) " << std::endl;
// std::for_each(_boundary_side_id.begin(),
// _boundary_side_id.end(),
// PrintSideInfo());
std::multimap<const Elem*,
std::pair<unsigned short int, short int> >::const_iterator it = _boundary_side_id.begin();
const std::multimap<const Elem*,
std::pair<unsigned short int, short int> >::const_iterator end = _boundary_side_id.end();
for (; it != end; ++it)
std::cout << " (" << (*it).first->id()
<< ", " << (*it).second.first
<< ", " << (*it).second.second
<< ")" << std::endl;
}
}
Don't accidentally add duplicate side boundary condition ids
git-svn-id: ffc1bc5b3feaf8644044862cc38c386ade156493@3183 434f946d-2f3d-0410-ba4c-cb9f52fb0dbf
// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, 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
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local includes
#include "libmesh_config.h"
#include "boundary_info.h"
#include "boundary_mesh.h"
#include "elem.h"
#include "mesh_data.h"
#include "parallel.h"
//------------------------------------------------------
// BoundaryInfo static member initializations
const short int BoundaryInfo::invalid_id = -1234;
//------------------------------------------------------
// BoundaryInfo functions
BoundaryInfo::BoundaryInfo(const MeshBase& m) :
_mesh (m)
{
}
BoundaryInfo::~BoundaryInfo()
{
this->clear();
}
void BoundaryInfo::clear()
{
_boundary_node_id.clear();
_boundary_side_id.clear();
_boundary_ids.clear();
}
void BoundaryInfo::sync(BoundaryMesh& boundary_mesh,
MeshData* boundary_mesh_data,
MeshData* this_mesh_data)
{
boundary_mesh.clear();
/**
* Re-create the boundary mesh.
*/
boundary_mesh.set_n_subdomains() = this->n_boundary_ids();
boundary_mesh.set_n_partitions() = this->n_boundary_ids();
// Add sides to the structure.
std::map<short int, unsigned int> id_map;
// Original Code
// unsigned int cnt = 0;
// for (std::set<short int>::iterator pos = boundary_ids.begin();
// pos != boundary_ids.end(); ++pos)
// id_map[*pos] = cnt++;
// id_map[invalid_id] = cnt;
// New code
// Here we need to use iota() once it is in the
// Utility namespace.
std::for_each(_boundary_ids.begin(),
_boundary_ids.end(),
Fill(id_map));
boundary_mesh.set_n_subdomains() = id_map.size();
// Make individual copies of all the nodes in the current mesh
// and add them to the boundary mesh. Yes, this is overkill because
// all of the current mesh nodes will not end up in the the boundary
// mesh. These nodes can be trimmed later via a call to prepare_for_use().
{
libmesh_assert (boundary_mesh.n_nodes() == 0);
boundary_mesh.reserve_nodes(_mesh.n_nodes());
MeshBase::const_node_iterator it = _mesh.nodes_begin();
MeshBase::const_node_iterator end = _mesh.nodes_end();
for(; it != end; ++it)
{
const Node* node = *it;
boundary_mesh.add_point(*node); // calls Node::build(Point, id)
}
}
// Add additional sides that aren't flagged with boundary conditions
MeshBase::const_element_iterator el = _mesh.active_elements_begin();
const MeshBase::const_element_iterator end_el = _mesh.active_elements_end();
for ( ; el != end_el; ++el)
{
const Elem* elem = *el;
for (unsigned int s=0; s<elem->n_sides(); s++)
if (elem->neighbor(s) == NULL) // on the boundary
{
// Build the side - do not use a "proxy" element here:
// This will be going into the BoundaryMesh and needs to
// stand on its own.
AutoPtr<Elem> side (elem->build_side(s, false));
// Get the top-level parent for this element
const Elem* top_parent = elem->top_parent();
// A convenient typedef
typedef
std::multimap<const Elem*, std::pair<unsigned short int, short int> >::const_iterator
Iter;
// Find the right id number for that side
std::pair<Iter, Iter> pos = _boundary_side_id.equal_range(top_parent);
while (pos.first != pos.second)
{
if (pos.first->second.first == s) // already flagged with a boundary condition
{
side->subdomain_id() =
id_map[pos.first->second.second];
side->processor_id() =
side->subdomain_id();
break;
}
++pos.first;
}
// either the element wasn't found or side s
// doesn't have a boundary condition
if (pos.first == pos.second)
{
side->subdomain_id() = id_map[invalid_id];
}
// Add the side
Elem* new_elem = boundary_mesh.add_elem(side.release());
// This side's Node pointers still point to the nodes of the original mesh.
// We need to re-point them to the boundary mesh's nodes! Since we copied *ALL* of
// the original mesh's nodes over, we should be guaranteed to have the same ordering.
for (unsigned int nn=0; nn<new_elem->n_nodes(); ++nn)
{
// Get the correct node pointer, based on the id()
Node* new_node = boundary_mesh.node_ptr(new_elem->node(nn));
// sanity check: be sure that the new Nodes global id really matches
libmesh_assert (new_node->id() == new_elem->node(nn));
// Assign the new node pointer
new_elem->set_node(nn) = new_node;
}
}
} // end loop over active elements
// When desired, copy the MeshData
// to the boundary_mesh
if ((boundary_mesh_data != NULL) && (this_mesh_data != NULL))
boundary_mesh_data->assign(*this_mesh_data);
// Don't repartition this mesh; we're using the processor_id values
// as a hack to display bcids for now.
boundary_mesh.partitioner().reset(NULL);
// Trim any un-used nodes from the Mesh
boundary_mesh.prepare_for_use();
}
void BoundaryInfo::add_node(const unsigned int node,
const short int id)
{
this->add_node (_mesh.node_ptr(node), id);
}
void BoundaryInfo::add_node(const Node* node,
const short int id)
{
if (id == invalid_id)
{
std::cerr << "ERROR: You may not set a boundary ID of "
<< invalid_id << std::endl
<< " That is reserved for internal use.\n"
<< std::endl;
libmesh_error();
}
_boundary_node_id[node] = id;
_boundary_ids.insert(id);
}
void BoundaryInfo::add_side(const unsigned int e,
const unsigned short int side,
const short int id)
{
this->add_side (_mesh.elem(e), side, id);
}
void BoundaryInfo::add_side(const Elem* elem,
const unsigned short int side,
const short int id)
{
libmesh_assert (elem != NULL);
// Only add BCs for level-0 elements.
libmesh_assert (elem->level() == 0);
if (id == invalid_id)
{
std::cerr << "ERROR: You may not set a boundary ID of "
<< invalid_id << std::endl
<< " That is reserved for internal use.\n"
<< std::endl;
libmesh_error();
}
// A convenient typedef
typedef std::multimap<const Elem*, std::pair<unsigned short int, short int> >::const_iterator Iter;
// Don't add the same ID twice
std::pair<Iter, Iter> pos = _boundary_side_id.equal_range(elem);
for (;pos.first != pos.second; ++pos.first)
if (pos.first->second.first == side &&
pos.first->second.second == id)
return;
std::pair<unsigned short int, short int> p(side,id);
std::pair<const Elem*, std::pair<unsigned short int, short int> >
kv (elem, p);
_boundary_side_id.insert(kv);
_boundary_ids.insert(id);
}
short int BoundaryInfo::boundary_id(const Node* node) const
{
std::map<const Node*, short int>::const_iterator
n = _boundary_node_id.find(node);
// node not in the data structure
if (n == _boundary_node_id.end())
return invalid_id;
return n->second;
}
short int BoundaryInfo::boundary_id(const Elem* const elem,
const unsigned short int side) const
{
libmesh_assert (elem != NULL);
// Only level-0 elements store BCs. If this is not a level-0
// element get its level-0 parent and infer the BCs.
const Elem* searched_elem = elem;
if (elem->level() != 0)
searched_elem = elem->top_parent ();
std::pair<std::multimap<const Elem*,
std::pair<unsigned short int, short int> >::const_iterator,
std::multimap<const Elem*,
std::pair<unsigned short int, short int> >::const_iterator >
e = _boundary_side_id.equal_range(searched_elem);
// elem not in the data structure
if (e.first == e.second)
return invalid_id;
// elem is there, maybe multiple occurances
while (e.first != e.second)
{
// if this is true we found the requested side
// of the element and want to return the id
if (e.first->second.first == side)
return e.first->second.second;
++e.first;
}
// if we get here, we found elem in the data structure but not
// the requested side, so return the default value
return invalid_id;
}
unsigned int BoundaryInfo::side_with_boundary_id(const Elem* const elem,
const unsigned short int boundary_id) const
{
const Elem* searched_elem = elem;
if (elem->level() != 0)
searched_elem = elem->top_parent();
std::pair<std::multimap<const Elem*,
std::pair<unsigned short int, short int> >::const_iterator,
std::multimap<const Elem*,
std::pair<unsigned short int, short int> >::const_iterator >
e = _boundary_side_id.equal_range(searched_elem);
// elem not in the data structure
if (e.first == e.second)
return libMesh::invalid_uint;
// elem is there, maybe multiple occurances
while (e.first != e.second)
{
// if this is true we found the requested boundary_id
// of the element and want to return the side
if (e.first->second.second == boundary_id)
return e.first->second.first;
++e.first;
}
// if we get here, we found elem in the data structure but not
// the requested boundary id, so return the default value
return libMesh::invalid_uint;
}
unsigned int BoundaryInfo::n_boundary_conds () const
{
// in serial we know the number of bcs from the
// size of the container
if (_mesh.is_serial())
return _boundary_side_id.size();
// in parallel we need to sum the number of local bcs
parallel_only();
unsigned int nbcs=0;
std::multimap<const Elem*,
std::pair<unsigned short int,
short int> >::const_iterator pos;
for (pos=_boundary_side_id.begin(); pos != _boundary_side_id.end(); ++pos)
if (pos->first->processor_id() == libMesh::processor_id())
nbcs++;
Parallel::sum (nbcs);
return nbcs;
}
void BoundaryInfo::build_node_list (std::vector<unsigned int>& nl,
std::vector<short int>& il) const
{
// Reserve the size, then use push_back
nl.reserve (_boundary_node_id.size());
il.reserve (_boundary_node_id.size());
std::map<const Node*, short int>::const_iterator pos
= _boundary_node_id.begin();
for (; pos != _boundary_node_id.end(); ++pos)
{
nl.push_back (pos->first->id());
il.push_back (pos->second);
}
}
void BoundaryInfo::build_side_list (std::vector<unsigned int>& el,
std::vector<unsigned short int>& sl,
std::vector<short int>& il) const
{
// Reserve the size, then use push_back
el.reserve (_boundary_side_id.size());
sl.reserve (_boundary_side_id.size());
il.reserve (_boundary_side_id.size());
std::multimap<const Elem*,
std::pair<unsigned short int,
short int> >::const_iterator pos;
for (pos=_boundary_side_id.begin(); pos != _boundary_side_id.end();
++pos)
{
el.push_back (pos->first->id());
sl.push_back (pos->second.first);
il.push_back (pos->second.second);
}
}
void BoundaryInfo::print_info() const
{
// Print out the nodal BCs
if (!_boundary_node_id.empty())
{
std::cout << "Nodal Boundary conditions:" << std::endl
<< "--------------------------" << std::endl
<< " (Node No., ID) " << std::endl;
// std::for_each(_boundary_node_id.begin(),
// _boundary_node_id.end(),
// PrintNodeInfo());
std::map<const Node*, short int>::const_iterator it = _boundary_node_id.begin();
const std::map<const Node*, short int>::const_iterator end = _boundary_node_id.end();
for (; it != end; ++it)
std::cout << " (" << (*it).first->id()
<< ", " << (*it).second
<< ")" << std::endl;
}
// Print out the element BCs
if (!_boundary_side_id.empty())
{
std::cout << std::endl
<< "Side Boundary conditions:" << std::endl
<< "-------------------------" << std::endl
<< " (Elem No., Side No., ID) " << std::endl;
// std::for_each(_boundary_side_id.begin(),
// _boundary_side_id.end(),
// PrintSideInfo());
std::multimap<const Elem*,
std::pair<unsigned short int, short int> >::const_iterator it = _boundary_side_id.begin();
const std::multimap<const Elem*,
std::pair<unsigned short int, short int> >::const_iterator end = _boundary_side_id.end();
for (; it != end; ++it)
std::cout << " (" << (*it).first->id()
<< ", " << (*it).second.first
<< ", " << (*it).second.second
<< ")" << std::endl;
}
}
|
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include <sol.hpp>
std::string free_function() {
std::cout << "free_function()" << std::endl;
return "test";
}
struct object {
std::string operator() () {
std::cout << "member_test()" << std::endl;
return "test";
}
};
int plop_xyz(int x, int y, std::string z) {
std::cout << x << " " << y << " " << z << std::endl;
return 11;
}
void run_script(sol::state& lua) {
lua.script("assert(os.fun() == \"test\")\n"
"assert(os.name == \"windows\")");
}
TEST_CASE("simple/set_global", "Check if the set_global works properly.") {
sol::state lua;
lua.set("a", 9);
REQUIRE_NOTHROW(lua.script("if a ~= 9 then error('wrong value') end"));
lua.set("d", "hello");
REQUIRE_NOTHROW(lua.script("if d ~= 'hello' then error('expected \\'hello\\', got '.. tostring(d)) end"));
lua.set("e", std::string("hello"));
REQUIRE_NOTHROW(lua.script("if d ~= 'hello' then error('expected \\'hello\\', got '.. tostring(d)) end"));
lua.set("f", true);
REQUIRE_NOTHROW(lua.script("if f ~= true then error('wrong value') end"));
}
TEST_CASE("simple/get", "Tests if the get function works properly.") {
sol::state lua;
lua.script("a = 9");
auto a = lua.get<int>("a");
REQUIRE(a == 9.0);
lua.script("b = nil");
REQUIRE_NOTHROW(lua.get<sol::nil_t>("b"));
lua.script("d = 'hello'");
auto d = lua.get<std::string>("d");
REQUIRE(d == "hello");
lua.script("e = true");
auto e = lua.get<bool>("e");
REQUIRE(e == true);
}
TEST_CASE("simple/addition", "") {
sol::state lua;
lua.set("b", 0.2);
lua.script("c = 9 + b");
auto c = lua.get<double>("c");
REQUIRE(c == 9.2);
}
TEST_CASE("simple/if", "") {
sol::state lua;
std::string program = "if true then f = 0.1 else f = 'test' end";
lua.script(program);
auto f = lua.get<double>("f");
REQUIRE(f == 0.1);
}
TEST_CASE("simple/evalStream", "The VM evaluates a stream's contents using a reader") {
sol::state lua;
std::stringstream sscript;
int g = 9;
sscript << "g = " << g << ";";
REQUIRE_NOTHROW(lua.script(sscript.str()));
REQUIRE(lua.get<double>("g") == 9.0);
}
TEST_CASE("simple/callWithParameters", "Lua function is called with a few parameters from C++") {
sol::state lua;
REQUIRE_NOTHROW(lua.script("function my_add(i, j, k) return i + j + k end"));
auto f = lua.get<sol::function>("my_add");
int a;
REQUIRE_NOTHROW(a = f.call<int>(1, 2, 3));
REQUIRE(a == 6);
REQUIRE_THROWS(a = f.call<int>(1, 2, "arf"));
}
TEST_CASE("simple/callCppFunction", "C++ function is called from lua") {
sol::state lua;
lua.set_function("plop_xyz", plop_xyz);
lua.script("x = plop_xyz(2, 6, 'hello')");
REQUIRE(lua.get<int>("x") == 11);
}
TEST_CASE("simple/callLambda", "A C++ lambda is exposed to lua and called") {
sol::state lua;
int x = 0;
lua.set_function("foo", [ &x ] { x = 1; });
lua.script("foo()");
REQUIRE(x == 1);
}
TEST_CASE("advanced/callLambdaReturns", "Checks for lambdas returning values") {
sol::state lua;
lua.set_function("a", [ ] { return 42; });
lua.set_function("b", [ ] { return 42u; });
lua.set_function("c", [ ] { return 3.14; });
lua.set_function("d", [ ] { return 6.28f; });
lua.set_function("e", [ ] { return "lol"; });
lua.set_function("f", [ ] { return true; });
lua.set_function("g", [ ] { return std::string("str"); });
lua.set_function("h", [ ] { });
lua.set_function("i", [ ] { return sol::nil; });
}
TEST_CASE("advanced/callLambda2", "A C++ lambda is exposed to lua and called") {
sol::state lua;
int x = 0;
lua.set_function("set_x", [ &] (int new_x) {
x = new_x;
return 0;
});
lua.script("set_x(9)");
REQUIRE(x == 9);
}
TEST_CASE("negative/basicError", "Check if error handling works correctly") {
sol::state lua;
REQUIRE_THROWS(lua.script("nil[5]"));
}
/*
lua.get<sol::table>("os").set("name", "windows");
SECTION("")
lua.get<sol::table>("os").set_function("fun",
[ ] () {
std::cout << "stateless lambda()" << std::endl;
return "test";
}
);
run_script(lua);
lua.get<sol::table>("os").set_function("fun", &free_function);
run_script(lua);
// l-value, can optomize
auto lval = object();
lua.get<sol::table>("os").set_function("fun", &object::operator(), lval);
run_script(lua);
// Tests will begin failing here
// stateful lambda: non-convertible, unoptomizable
int breakit = 50;
lua.get<sol::table>("os").set_function("fun",
[ &breakit ] () {
std::cout << "stateless lambda()" << std::endl;
return "test";
}
);
run_script(lua);
// r-value, cannot optomize
lua.get<sol::table>("os").set_function("fun", &object::operator(), object());
run_script(lua);
// r-value, cannot optomize
auto rval = object();
lua.get<sol::table>("os").set_function("fun", &object::operator(), std::move(rval));
run_script(lua);
}
*/
Test cases for tables and the opening of libraries.
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include <sol.hpp>
std::string free_function() {
std::cout << "free_function()" << std::endl;
return "test";
}
struct object {
std::string operator() () {
std::cout << "member_test()" << std::endl;
return "test";
}
};
int plop_xyz(int x, int y, std::string z) {
std::cout << x << " " << y << " " << z << std::endl;
return 11;
}
TEST_CASE("simple/set_global", "Check if the set_global works properly.") {
sol::state lua;
lua.set("a", 9);
REQUIRE_NOTHROW(lua.script("if a ~= 9 then error('wrong value') end"));
lua.set("d", "hello");
REQUIRE_NOTHROW(lua.script("if d ~= 'hello' then error('expected \\'hello\\', got '.. tostring(d)) end"));
lua.set("e", std::string("hello"));
REQUIRE_NOTHROW(lua.script("if d ~= 'hello' then error('expected \\'hello\\', got '.. tostring(d)) end"));
lua.set("f", true);
REQUIRE_NOTHROW(lua.script("if f ~= true then error('wrong value') end"));
}
TEST_CASE("simple/get", "Tests if the get function works properly.") {
sol::state lua;
lua.script("a = 9");
auto a = lua.get<int>("a");
REQUIRE(a == 9.0);
lua.script("b = nil");
REQUIRE_NOTHROW(lua.get<sol::nil_t>("b"));
lua.script("d = 'hello'");
auto d = lua.get<std::string>("d");
REQUIRE(d == "hello");
lua.script("e = true");
auto e = lua.get<bool>("e");
REQUIRE(e == true);
}
TEST_CASE("simple/addition", "") {
sol::state lua;
lua.set("b", 0.2);
lua.script("c = 9 + b");
auto c = lua.get<double>("c");
REQUIRE(c == 9.2);
}
TEST_CASE("simple/if", "") {
sol::state lua;
std::string program = "if true then f = 0.1 else f = 'test' end";
lua.script(program);
auto f = lua.get<double>("f");
REQUIRE(f == 0.1);
}
TEST_CASE("simple/callWithParameters", "Lua function is called with a few parameters from C++") {
sol::state lua;
REQUIRE_NOTHROW(lua.script("function my_add(i, j, k) return i + j + k end"));
auto f = lua.get<sol::function>("my_add");
int a;
REQUIRE_NOTHROW(a = f.call<int>(1, 2, 3));
REQUIRE(a == 6);
REQUIRE_THROWS(a = f.call<int>(1, 2, "arf"));
}
TEST_CASE("simple/callCppFunction", "C++ function is called from lua") {
sol::state lua;
lua.set_function("plop_xyz", plop_xyz);
lua.script("x = plop_xyz(2, 6, 'hello')");
REQUIRE(lua.get<int>("x") == 11);
}
TEST_CASE("simple/callLambda", "A C++ lambda is exposed to lua and called") {
sol::state lua;
int x = 0;
lua.set_function("foo", [ &x ] { x = 1; });
lua.script("foo()");
REQUIRE(x == 1);
}
TEST_CASE("advanced/callLambdaReturns", "Checks for lambdas returning values") {
sol::state lua;
lua.set_function("a", [ ] { return 42; });
lua.set_function("b", [ ] { return 42u; });
lua.set_function("c", [ ] { return 3.14; });
lua.set_function("d", [ ] { return 6.28f; });
lua.set_function("e", [ ] { return "lol"; });
lua.set_function("f", [ ] { return true; });
lua.set_function("g", [ ] { return std::string("str"); });
lua.set_function("h", [ ] { });
lua.set_function("i", [ ] { return sol::nil; });
}
TEST_CASE("advanced/callLambda2", "A C++ lambda is exposed to lua and called") {
sol::state lua;
int x = 0;
lua.set_function("set_x", [ &] (int new_x) {
x = new_x;
return 0;
});
lua.script("set_x(9)");
REQUIRE(x == 9);
}
TEST_CASE("negative/basicError", "Check if error handling works correctly") {
sol::state lua;
REQUIRE_THROWS(lua.script("nil[5]"));
}
TEST_CASE("libraries", "Check if we can open libraries through sol") {
sol::state lua;
REQUIRE_NOTHROW(lua.open_libraries(sol::lib::base, sol::lib::os));
}
TEST_CASE("tables/variables", "Check if tables and variables work as intended") {
sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::os);
lua.get<sol::table>("os").set("name", "windows");
REQUIRE_NOTHROW(lua.script("assert(os.name == \"windows\")"));
}
TEST_CASE("tables/functions_variables", "Check if tables and function calls work as intended") {
sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::os);
auto run_script = [ ] (sol::state& lua) -> void {
lua.script("assert(os.fun() == \"test\")");
};
lua.get<sol::table>("os").set_function("fun",
[ ] () {
std::cout << "stateless lambda()" << std::endl;
return "test";
}
);
REQUIRE_NOTHROW(run_script(lua));
lua.get<sol::table>("os").set_function("fun", &free_function);
REQUIRE_NOTHROW(run_script(lua));
// l-value, can optomize
auto lval = object();
lua.get<sol::table>("os").set_function("fun", &object::operator(), lval);
REQUIRE_NOTHROW((lua));
// stateful lambda: non-convertible, unoptomizable
int breakit = 50;
lua.get<sol::table>("os").set_function("fun",
[ &breakit ] () {
std::cout << "stateless lambda()" << std::endl;
return "test";
}
);
REQUIRE_NOTHROW(run_script(lua));
// r-value, cannot optomize
lua.get<sol::table>("os").set_function("fun", &object::operator(), object());
REQUIRE_NOTHROW(run_script(lua));
// r-value, cannot optomize
auto rval = object();
lua.get<sol::table>("os").set_function("fun", &object::operator(), std::move(rval));
REQUIRE_NOTHROW(run_script(lua));
} |
#include "SUIT_FileDlg.h"
#include "SUIT_Tools.h"
#include "SUIT_Session.h"
#include "SUIT_Desktop.h"
#include "SUIT_MessageBox.h"
#include "SUIT_ResourceMgr.h"
#include "SUIT_FileValidator.h"
#include <qdir.h>
#include <qlabel.h>
#include <qregexp.h>
#include <qpalette.h>
#include <qobjectlist.h>
#include <qcombobox.h>
#include <qpushbutton.h>
#include <qapplication.h>
#define MIN_COMBO_SIZE 100
QString SUIT_FileDlg::myLastVisitedPath;
/*!
Constructor
*/
SUIT_FileDlg::SUIT_FileDlg( QWidget* parent, bool open, bool showQuickDir, bool modal ) :
QFileDialog( parent, 0, modal ),
myValidator( 0 ),
myQuickCombo( 0 ), myQuickButton( 0 ), myQuickLab( 0 ),
myOpen( open )
{
if ( parent->icon() )
setIcon( *parent->icon() );
setSizeGripEnabled( true );
if ( showQuickDir ) {
// inserting quick dir combo box
myQuickLab = new QLabel(tr("LAB_QUICK_PATH"), this);
myQuickCombo = new QComboBox(false, this);
myQuickCombo->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
myQuickCombo->setMinimumSize(MIN_COMBO_SIZE, 0);
myQuickButton = new QPushButton(tr("BUT_ADD_PATH"), this);
connect(myQuickCombo, SIGNAL(activated(const QString&)), this, SLOT(quickDir(const QString&)));
connect(myQuickButton, SIGNAL(clicked()), this, SLOT(addQuickDir()));
addWidgets(myQuickLab, myQuickCombo, myQuickButton);
// getting dir list from settings
QString dirs;
SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
if ( resMgr )
dirs = resMgr->stringValue( "FileDlg", QString( "QuickDirList" ) );
QStringList dirList = QStringList::split(';', dirs, false);
if (dirList.count() > 0) {
for (unsigned i = 0; i < dirList.count(); i++)
myQuickCombo->insertItem(dirList[i]);
}
else {
myQuickCombo->insertItem(QDir::homeDirPath());
}
}
setMode( myOpen ? ExistingFile : AnyFile );
setCaption( myOpen ? tr( "INF_DESK_DOC_OPEN" ) : tr( "INF_DESK_DOC_SAVE" ) );
// If last visited path doesn't exist -> switch to the first preferred path
if ( !myLastVisitedPath.isEmpty() ) {
if ( !processPath( myLastVisitedPath ) && showQuickDir )
processPath( myQuickCombo->text( 0 ) );
}
else {
if ( showQuickDir )
processPath(myQuickCombo->text( 0 ) );
}
// set default file validator
myValidator = new SUIT_FileValidator(this);
}
/*!
Destructor
*/
SUIT_FileDlg::~SUIT_FileDlg()
{
setValidator( 0 );
}
/*!
Redefined from QFileDialog.
*/
void SUIT_FileDlg::polish()
{
QFileDialog::polish();
if ( myQuickButton && myQuickLab ) {
// the following is a workaround for proper layouting of custom widgets
QValueList<QPushButton*> buttonList;
QValueList<QLabel*> labelList;
const QObjectList *list = children();
QObjectListIt it(*list);
int maxButWidth = myQuickLab->sizeHint().width();
int maxLabWidth = myQuickButton->sizeHint().width();
for (; it.current() ; ++it) {
if ( it.current()->isA( "QLabel" ) ) {
int tempW = ((QLabel*)it.current())->minimumWidth();
if ( maxLabWidth < tempW ) maxLabWidth = tempW;
labelList.append( (QLabel*)it.current() );
}
else if( it.current()->isA("QPushButton") ) {
int tempW = ((QPushButton*)it.current())->minimumWidth();
if ( maxButWidth < tempW ) maxButWidth = tempW;
buttonList.append( (QPushButton*)it.current() );
}
}
if (maxButWidth > 0) {
QValueList<QPushButton*>::Iterator bListIt;
for ( bListIt = buttonList.begin(); bListIt != buttonList.end(); ++bListIt )
(*bListIt)->setFixedWidth( maxButWidth );
}
if (maxLabWidth > 0) {
QValueList<QLabel*>::Iterator lListIt;
for ( lListIt = labelList.begin(); lListIt != labelList.end(); ++lListIt )
(*lListIt)->setFixedWidth( maxLabWidth );
}
}
}
/*!
Sets validator for file names to open/save
Deletes previous validator if the dialog owns it.
*/
void SUIT_FileDlg::setValidator( SUIT_FileValidator* v )
{
if ( myValidator && myValidator->parent() == this )
delete myValidator;
myValidator = v;
}
/*!
Returns the selected file
*/
QString SUIT_FileDlg::selectedFile() const
{
return mySelectedFile;
}
/*!
Returns 'true' if this is 'Open File' dialog
and 'false' if 'Save File' dialog
*/
bool SUIT_FileDlg::isOpenDlg() const
{
return myOpen;
}
/*!
Closes this dialog and sets the return code to 'Accepted'
if the selected name is valid ( see 'acceptData()' )
*/
void SUIT_FileDlg::accept()
{
// mySelectedFile = QFileDialog::selectedFile().simplifyWhiteSpace(); //VSR- 06/12/02
if ( mode() != ExistingFiles ) {
mySelectedFile = QFileDialog::selectedFile(); //VSR+ 06/12/02
addExtension();
}
// mySelectedFile = mySelectedFile.simplifyWhiteSpace(); //VSR- 06/12/02
/* Qt 2.2.2 BUG: accept() is called twice if you validate
the selected file name by pressing 'Return' key in file
name editor but this name is not acceptable for acceptData()
*/
if ( acceptData() ) {
myLastVisitedPath = dirPath();
QFileDialog::accept();
}
}
/*!
Closes this dialog and sets the return code to 'Rejected'
*/
void SUIT_FileDlg::reject()
{
mySelectedFile = QString::null;
QFileDialog::reject();
}
/*!
Returns 'true' if selected file is valid.
The validity is checked by a file validator,
if there is no validator the file is always
considered as valid
*/
bool SUIT_FileDlg::acceptData()
{
if ( myValidator )
{
if ( isOpenDlg() )
if ( mode() == ExistingFiles ) {
QStringList fileNames = selectedFiles();
for ( int i = 0; i < fileNames.count(); i++ ) {
if ( !myValidator->canOpen( fileNames[i] ) )
return false;
}
return true;
}
else {
return myValidator->canOpen( selectedFile() );
}
else
return myValidator->canSave( selectedFile() );
}
return true;
}
/*!
Adds an extension to the selected file name
if the file has not it.
The extension is extracted from the active filter.
*/
void SUIT_FileDlg::addExtension()
{
// mySelectedFile.stripWhiteSpace();//VSR- 06/12/02
// if ( mySelectedFile.isEmpty() )//VSR- 06/12/02
if ( mySelectedFile.stripWhiteSpace().isEmpty() )//VSR+ 06/12/02
return;
// if ( SUIT_Tools::getFileExtensionFromPath( mySelectedFile ).isEmpty() ) //VSR- 06/12/02
//ota : 16/12/03 if ( SUIT_Tools::getFileExtensionFromPath( mySelectedFile ).isEmpty() ) //VSR+ 06/12/02
// {
#if QT_VERSION < 0x030000
QRegExp r( QString::fromLatin1("([a-zA-Z0-9.*? +;#]*)$") );
int len, index = r.match( selectedFilter(), 0, &len );
#else
QRegExp r( QString::fromLatin1("\\([a-zA-Z0-9.*? +;#]*\\)$") );
int index = r.search(selectedFilter());
#endif
if ( index >= 0 )
{
#if QT_VERSION < 0x030000
// QString wildcard = selectedFilter().mid( index + 1, len-2 ); //VSR- 06/12/02
QString wildcard = selectedFilter().mid( index + 1, len-2 ).stripWhiteSpace(); //VSR+ 06/12/02
#else
// QString wildcard = selectedFilter().mid( index + 1, r.matchedLength()-2 ); //VSR- 06/12/02
QString wildcard = selectedFilter().mid( index + 1, r.matchedLength()-2 ).stripWhiteSpace(); //VSR+ 06/12/02
#endif
int aLen = mySelectedFile.length();
if ( mySelectedFile[aLen - 1] == '.')
//if the file name ends with the point remove it
mySelectedFile.truncate(aLen - 1);
QString anExt = "." + SUIT_Tools::extension( mySelectedFile ).stripWhiteSpace();
// From the filters list make a pattern to validate a file extension
// Due to transformations from the filter list (*.txt *.*xx *.c++ SUIT*.* ) we
// will have the pattern (\.txt|\..*xx|\.c\+\+|\..*) (as we validate extension only we remove
// stay extension mask only in the pattern
QString aPattern(wildcard);
QRegExp anExtRExp("("+aPattern.replace(QRegExp("(^| )[0-9a-zA-Z*_?]*\\."), " \\.").
stripWhiteSpace().replace(QRegExp("\\s+"), "|").
replace(QRegExp("[*]"),".*").replace(QRegExp("[+]"),"\\+") + ")");
if ( anExtRExp.match(anExt) == -1 ) //if a selected file extension does not match to filter's list
{ //remove a point if it is at the word end
int aExtLen = anExt.length();
if (anExt[ aExtLen - 1 ] == '.') anExt.truncate( aExtLen - 1 );
index = wildcard.findRev( '.' );
if ( index >= 0 )
mySelectedFile += wildcard.mid( index ); //add the extension
}
}
// }
}
/*!
Processes selection : tries to set given path or filename as selection
*/
bool SUIT_FileDlg::processPath( const QString& path )
{
if ( !path.isNull() ) {
QFileInfo fi( path );
if ( fi.exists() ) {
if ( fi.isFile() )
setSelection( path );
else if ( fi.isDir() )
setDir( path );
return true;
}
else {
if ( QFileInfo( fi.dirPath() ).exists() ) {
setDir( fi.dirPath() );
setSelection( path );
return true;
}
}
}
return false;
}
/*!
Called when user selects item from "Quick Dir" combo box
*/
void SUIT_FileDlg::quickDir(const QString& dirPath)
{
if ( !QDir(dirPath).exists() ) {
SUIT_MessageBox::error1(this,
tr("ERR_ERROR"),
tr("ERR_DIR_NOT_EXIST").arg(dirPath),
tr("BUT_OK"));
}
else {
processPath(dirPath);
}
}
/*!
Called when user presses "Add" button - adds current directory to quick directory
list and to the preferences
*/
void SUIT_FileDlg::addQuickDir()
{
QString dp = dirPath();
if ( !dp.isEmpty() ) {
QDir dir( dp );
// getting dir list from settings
QString dirs;
SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
if ( resMgr )
dirs = resMgr->stringValue( "FileDlg", QString( "QuickDirList" ) );
QStringList dirList = QStringList::split(';', dirs, false);
bool found = false;
bool emptyAndHome = false;
if ( dirList.count() > 0 ) {
for ( unsigned i = 0; i < dirList.count(); i++ ) {
QDir aDir( dirList[i] );
if ( aDir.canonicalPath().isNull() && dirList[i] == dir.absPath() ||
!aDir.canonicalPath().isNull() && aDir.exists() && aDir.canonicalPath() == dir.canonicalPath() ) {
found = true;
break;
}
}
}
else {
emptyAndHome = dir.canonicalPath() == QDir(QDir::homeDirPath()).canonicalPath();
}
if ( !found ) {
dirList.append( dp );
resMgr->setValue( "FileDlg", QString( "QuickDirList" ), dirList.join(";") );
if ( !emptyAndHome )
myQuickCombo->insertItem( dp );
}
}
}
/*!
Returns the file name for Open/Save [ static ]
*/
QString SUIT_FileDlg::getFileName( QWidget* parent,
const QString& initial,
const QStringList& filters,
const QString& caption,
bool open,
bool showQuickDir,
SUIT_FileValidator* validator )
{
SUIT_FileDlg* fd = new SUIT_FileDlg( parent, open, showQuickDir, true );
if ( !caption.isEmpty() )
fd->setCaption( caption );
if ( !initial.isEmpty() ) {
fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
}
fd->setFilters( filters );
if ( validator )
fd->setValidator( validator );
fd->exec();
QString filename = fd->selectedFile();
delete fd;
qApp->processEvents();
return filename;
}
/*!
Returns the list of files to be opened [ static ]
*/
QStringList SUIT_FileDlg::getOpenFileNames( QWidget* parent,
const QString& initial,
const QStringList& filters,
const QString& caption,
bool showQuickDir,
SUIT_FileValidator* validator )
{
SUIT_FileDlg* fd = new SUIT_FileDlg( parent, true, showQuickDir, true );
fd->setMode( ExistingFiles );
if ( !caption.isEmpty() )
fd->setCaption( caption );
if ( !initial.isEmpty() ) {
fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
}
fd->setFilters( filters );
if ( validator )
fd->setValidator( validator );
fd->exec();
QStringList filenames = fd->selectedFiles();
delete fd;
qApp->processEvents();
return filenames;
}
/*!
Existing directory selection dialog [ static ]
*/
QString SUIT_FileDlg::getExistingDirectory( QWidget* parent,
const QString& initial,
const QString& caption,
bool showQuickDir )
{
SUIT_FileDlg* fd = new SUIT_FileDlg( parent, true, showQuickDir, true);
if ( !caption.isEmpty() )
fd->setCaption( caption );
if ( !initial.isEmpty() ) {
fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
}
fd->setMode( DirectoryOnly );
fd->setFilters(tr("INF_DIRECTORIES_FILTER"));
fd->exec();
QString dirname = fd->selectedFile();
delete fd;
qApp->processEvents();
return dirname;
}
BUG 8990: Use HOME directory if selected one doesn't exist
#include "SUIT_FileDlg.h"
#include "SUIT_Tools.h"
#include "SUIT_Session.h"
#include "SUIT_Desktop.h"
#include "SUIT_MessageBox.h"
#include "SUIT_ResourceMgr.h"
#include "SUIT_FileValidator.h"
#include <qdir.h>
#include <qlabel.h>
#include <qregexp.h>
#include <qpalette.h>
#include <qobjectlist.h>
#include <qcombobox.h>
#include <qpushbutton.h>
#include <qapplication.h>
#define MIN_COMBO_SIZE 100
QString SUIT_FileDlg::myLastVisitedPath;
/*!
Constructor
*/
SUIT_FileDlg::SUIT_FileDlg( QWidget* parent, bool open, bool showQuickDir, bool modal ) :
QFileDialog( parent, 0, modal ),
myValidator( 0 ),
myQuickCombo( 0 ), myQuickButton( 0 ), myQuickLab( 0 ),
myOpen( open )
{
if ( parent->icon() )
setIcon( *parent->icon() );
setSizeGripEnabled( true );
if ( showQuickDir ) {
// inserting quick dir combo box
myQuickLab = new QLabel(tr("LAB_QUICK_PATH"), this);
myQuickCombo = new QComboBox(false, this);
myQuickCombo->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
myQuickCombo->setMinimumSize(MIN_COMBO_SIZE, 0);
myQuickButton = new QPushButton(tr("BUT_ADD_PATH"), this);
connect(myQuickCombo, SIGNAL(activated(const QString&)), this, SLOT(quickDir(const QString&)));
connect(myQuickButton, SIGNAL(clicked()), this, SLOT(addQuickDir()));
addWidgets(myQuickLab, myQuickCombo, myQuickButton);
// getting dir list from settings
QString dirs;
SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
if ( resMgr )
dirs = resMgr->stringValue( "FileDlg", QString( "QuickDirList" ) );
QStringList dirList = QStringList::split(';', dirs, false);
if (dirList.count() > 0) {
for (unsigned i = 0; i < dirList.count(); i++)
myQuickCombo->insertItem(dirList[i]);
}
else {
myQuickCombo->insertItem(QDir::homeDirPath());
}
}
setMode( myOpen ? ExistingFile : AnyFile );
setCaption( myOpen ? tr( "INF_DESK_DOC_OPEN" ) : tr( "INF_DESK_DOC_SAVE" ) );
// If last visited path doesn't exist -> switch to the first preferred path
if ( !myLastVisitedPath.isEmpty() ) {
if ( !processPath( myLastVisitedPath ) && showQuickDir )
processPath( myQuickCombo->text( 0 ) );
}
else {
if ( showQuickDir )
processPath(myQuickCombo->text( 0 ) );
}
// set default file validator
myValidator = new SUIT_FileValidator(this);
}
/*!
Destructor
*/
SUIT_FileDlg::~SUIT_FileDlg()
{
setValidator( 0 );
}
/*!
Redefined from QFileDialog.
*/
void SUIT_FileDlg::polish()
{
QFileDialog::polish();
if ( myQuickButton && myQuickLab ) {
// the following is a workaround for proper layouting of custom widgets
QValueList<QPushButton*> buttonList;
QValueList<QLabel*> labelList;
const QObjectList *list = children();
QObjectListIt it(*list);
int maxButWidth = myQuickLab->sizeHint().width();
int maxLabWidth = myQuickButton->sizeHint().width();
for (; it.current() ; ++it) {
if ( it.current()->isA( "QLabel" ) ) {
int tempW = ((QLabel*)it.current())->minimumWidth();
if ( maxLabWidth < tempW ) maxLabWidth = tempW;
labelList.append( (QLabel*)it.current() );
}
else if( it.current()->isA("QPushButton") ) {
int tempW = ((QPushButton*)it.current())->minimumWidth();
if ( maxButWidth < tempW ) maxButWidth = tempW;
buttonList.append( (QPushButton*)it.current() );
}
}
if (maxButWidth > 0) {
QValueList<QPushButton*>::Iterator bListIt;
for ( bListIt = buttonList.begin(); bListIt != buttonList.end(); ++bListIt )
(*bListIt)->setFixedWidth( maxButWidth );
}
if (maxLabWidth > 0) {
QValueList<QLabel*>::Iterator lListIt;
for ( lListIt = labelList.begin(); lListIt != labelList.end(); ++lListIt )
(*lListIt)->setFixedWidth( maxLabWidth );
}
}
}
/*!
Sets validator for file names to open/save
Deletes previous validator if the dialog owns it.
*/
void SUIT_FileDlg::setValidator( SUIT_FileValidator* v )
{
if ( myValidator && myValidator->parent() == this )
delete myValidator;
myValidator = v;
}
/*!
Returns the selected file
*/
QString SUIT_FileDlg::selectedFile() const
{
return mySelectedFile;
}
/*!
Returns 'true' if this is 'Open File' dialog
and 'false' if 'Save File' dialog
*/
bool SUIT_FileDlg::isOpenDlg() const
{
return myOpen;
}
/*!
Closes this dialog and sets the return code to 'Accepted'
if the selected name is valid ( see 'acceptData()' )
*/
void SUIT_FileDlg::accept()
{
// mySelectedFile = QFileDialog::selectedFile().simplifyWhiteSpace(); //VSR- 06/12/02
if ( mode() != ExistingFiles ) {
mySelectedFile = QFileDialog::selectedFile(); //VSR+ 06/12/02
addExtension();
}
// mySelectedFile = mySelectedFile.simplifyWhiteSpace(); //VSR- 06/12/02
/* Qt 2.2.2 BUG: accept() is called twice if you validate
the selected file name by pressing 'Return' key in file
name editor but this name is not acceptable for acceptData()
*/
if ( acceptData() ) {
myLastVisitedPath = dirPath();
QFileDialog::accept();
}
}
/*!
Closes this dialog and sets the return code to 'Rejected'
*/
void SUIT_FileDlg::reject()
{
mySelectedFile = QString::null;
QFileDialog::reject();
}
/*!
Returns 'true' if selected file is valid.
The validity is checked by a file validator,
if there is no validator the file is always
considered as valid
*/
bool SUIT_FileDlg::acceptData()
{
if ( myValidator )
{
if ( isOpenDlg() )
if ( mode() == ExistingFiles ) {
QStringList fileNames = selectedFiles();
for ( int i = 0; i < fileNames.count(); i++ ) {
if ( !myValidator->canOpen( fileNames[i] ) )
return false;
}
return true;
}
else {
return myValidator->canOpen( selectedFile() );
}
else
return myValidator->canSave( selectedFile() );
}
return true;
}
/*!
Adds an extension to the selected file name
if the file has not it.
The extension is extracted from the active filter.
*/
void SUIT_FileDlg::addExtension()
{
// mySelectedFile.stripWhiteSpace();//VSR- 06/12/02
// if ( mySelectedFile.isEmpty() )//VSR- 06/12/02
if ( mySelectedFile.stripWhiteSpace().isEmpty() )//VSR+ 06/12/02
return;
// if ( SUIT_Tools::getFileExtensionFromPath( mySelectedFile ).isEmpty() ) //VSR- 06/12/02
//ota : 16/12/03 if ( SUIT_Tools::getFileExtensionFromPath( mySelectedFile ).isEmpty() ) //VSR+ 06/12/02
// {
#if QT_VERSION < 0x030000
QRegExp r( QString::fromLatin1("([a-zA-Z0-9.*? +;#]*)$") );
int len, index = r.match( selectedFilter(), 0, &len );
#else
QRegExp r( QString::fromLatin1("\\([a-zA-Z0-9.*? +;#]*\\)$") );
int index = r.search(selectedFilter());
#endif
if ( index >= 0 )
{
#if QT_VERSION < 0x030000
// QString wildcard = selectedFilter().mid( index + 1, len-2 ); //VSR- 06/12/02
QString wildcard = selectedFilter().mid( index + 1, len-2 ).stripWhiteSpace(); //VSR+ 06/12/02
#else
// QString wildcard = selectedFilter().mid( index + 1, r.matchedLength()-2 ); //VSR- 06/12/02
QString wildcard = selectedFilter().mid( index + 1, r.matchedLength()-2 ).stripWhiteSpace(); //VSR+ 06/12/02
#endif
int aLen = mySelectedFile.length();
if ( mySelectedFile[aLen - 1] == '.')
//if the file name ends with the point remove it
mySelectedFile.truncate(aLen - 1);
QString anExt = "." + SUIT_Tools::extension( mySelectedFile ).stripWhiteSpace();
// From the filters list make a pattern to validate a file extension
// Due to transformations from the filter list (*.txt *.*xx *.c++ SUIT*.* ) we
// will have the pattern (\.txt|\..*xx|\.c\+\+|\..*) (as we validate extension only we remove
// stay extension mask only in the pattern
QString aPattern(wildcard);
QRegExp anExtRExp("("+aPattern.replace(QRegExp("(^| )[0-9a-zA-Z*_?]*\\."), " \\.").
stripWhiteSpace().replace(QRegExp("\\s+"), "|").
replace(QRegExp("[*]"),".*").replace(QRegExp("[+]"),"\\+") + ")");
if ( anExtRExp.match(anExt) == -1 ) //if a selected file extension does not match to filter's list
{ //remove a point if it is at the word end
int aExtLen = anExt.length();
if (anExt[ aExtLen - 1 ] == '.') anExt.truncate( aExtLen - 1 );
index = wildcard.findRev( '.' );
if ( index >= 0 )
mySelectedFile += wildcard.mid( index ); //add the extension
}
}
// }
}
/*!
Processes selection : tries to set given path or filename as selection
*/
bool SUIT_FileDlg::processPath( const QString& path )
{
if ( !path.isNull() ) {
QFileInfo fi( path );
if ( fi.exists() ) {
if ( fi.isFile() )
setSelection( path );
else if ( fi.isDir() )
setDir( path );
return true;
}
else {
if ( QFileInfo( fi.dirPath() ).exists() ) {
setDir( fi.dirPath() );
setSelection( path );
return true;
}
}
}
return false;
}
/*!
Called when user selects item from "Quick Dir" combo box
*/
void SUIT_FileDlg::quickDir(const QString& dirPath)
{
QString aPath = dirPath;
if ( !QDir(aPath).exists() ) {
aPath = QDir::homeDirPath();
/* SUIT_MessageBox::error1(this,
tr("ERR_ERROR"),
tr("ERR_DIR_NOT_EXIST").arg(dirPath),
tr("BUT_OK"));*/
}
// else {
processPath(aPath);
// }
}
/*!
Called when user presses "Add" button - adds current directory to quick directory
list and to the preferences
*/
void SUIT_FileDlg::addQuickDir()
{
QString dp = dirPath();
if ( !dp.isEmpty() ) {
QDir dir( dp );
// getting dir list from settings
QString dirs;
SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
if ( resMgr )
dirs = resMgr->stringValue( "FileDlg", QString( "QuickDirList" ) );
QStringList dirList = QStringList::split(';', dirs, false);
bool found = false;
bool emptyAndHome = false;
if ( dirList.count() > 0 ) {
for ( unsigned i = 0; i < dirList.count(); i++ ) {
QDir aDir( dirList[i] );
if ( aDir.canonicalPath().isNull() && dirList[i] == dir.absPath() ||
!aDir.canonicalPath().isNull() && aDir.exists() && aDir.canonicalPath() == dir.canonicalPath() ) {
found = true;
break;
}
}
}
else {
emptyAndHome = dir.canonicalPath() == QDir(QDir::homeDirPath()).canonicalPath();
}
if ( !found ) {
dirList.append( dp );
resMgr->setValue( "FileDlg", QString( "QuickDirList" ), dirList.join(";") );
if ( !emptyAndHome )
myQuickCombo->insertItem( dp );
}
}
}
/*!
Returns the file name for Open/Save [ static ]
*/
QString SUIT_FileDlg::getFileName( QWidget* parent,
const QString& initial,
const QStringList& filters,
const QString& caption,
bool open,
bool showQuickDir,
SUIT_FileValidator* validator )
{
SUIT_FileDlg* fd = new SUIT_FileDlg( parent, open, showQuickDir, true );
if ( !caption.isEmpty() )
fd->setCaption( caption );
if ( !initial.isEmpty() ) {
fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
}
fd->setFilters( filters );
if ( validator )
fd->setValidator( validator );
fd->exec();
QString filename = fd->selectedFile();
delete fd;
qApp->processEvents();
return filename;
}
/*!
Returns the list of files to be opened [ static ]
*/
QStringList SUIT_FileDlg::getOpenFileNames( QWidget* parent,
const QString& initial,
const QStringList& filters,
const QString& caption,
bool showQuickDir,
SUIT_FileValidator* validator )
{
SUIT_FileDlg* fd = new SUIT_FileDlg( parent, true, showQuickDir, true );
fd->setMode( ExistingFiles );
if ( !caption.isEmpty() )
fd->setCaption( caption );
if ( !initial.isEmpty() ) {
fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
}
fd->setFilters( filters );
if ( validator )
fd->setValidator( validator );
fd->exec();
QStringList filenames = fd->selectedFiles();
delete fd;
qApp->processEvents();
return filenames;
}
/*!
Existing directory selection dialog [ static ]
*/
QString SUIT_FileDlg::getExistingDirectory( QWidget* parent,
const QString& initial,
const QString& caption,
bool showQuickDir )
{
SUIT_FileDlg* fd = new SUIT_FileDlg( parent, true, showQuickDir, true);
if ( !caption.isEmpty() )
fd->setCaption( caption );
if ( !initial.isEmpty() ) {
fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
}
fd->setMode( DirectoryOnly );
fd->setFilters(tr("INF_DIRECTORIES_FILTER"));
fd->exec();
QString dirname = fd->selectedFile();
delete fd;
qApp->processEvents();
return dirname;
}
|
#include "Scene/SceneLoader.hpp"
#include "rapidjson/document.h"
#include "Engine/Engine.hpp"
#include "Rendering/Renderer.hpp"
#include "Resources/MeshManager.hpp"
#include "Entity/EntityManager.hpp"
#include "Resources/ResourceManager.hpp"
#include "Resources/MaterialManager.hpp"
#include "Resources/ValueSerialization.hpp"
SceneLoader::SceneLoader(Engine* engine, Scene* scene):
scene(scene),
renderer(engine->GetRenderer()),
meshManager(engine->GetMeshManager()),
materialManager(engine->GetMaterialManager()),
entityManager(engine->GetEntityManager()),
resourceManager(engine->GetResourceManager())
{
}
void SceneLoader::Load(BufferRef<char> sceneConfig)
{
rapidjson::Document doc;
doc.Parse(sceneConfig.data, sceneConfig.count);
if (doc.IsObject() == false)
return;
MemberItr objectsItr = doc.FindMember("objects");
if (objectsItr != doc.MemberEnd() && objectsItr->value.IsArray())
{
ValueItr itr = objectsItr->value.Begin();
ValueItr end = objectsItr->value.End();
CreateObjects(itr, end);
}
MemberItr colorItr = doc.FindMember("background-color");
if (colorItr != doc.MemberEnd())
{
scene->backgroundColor = ValueSerialization::Deserialize_Color(colorItr->value);
}
MemberItr skyboxItr = doc.FindMember("skybox-material");
if (skyboxItr != doc.MemberEnd() && skyboxItr->value.IsString())
{
StringRef materialPath(skyboxItr->value.GetString(), skyboxItr->value.GetStringLength());
MaterialId matId = materialManager->GetIdByPath(materialPath);
if (matId.IsNull() == false)
{
scene->SetSkyboxMaterial(matId);
}
}
}
void SceneLoader::CreateObjects(ValueItr itr, ValueItr end)
{
for (; itr != end; ++itr)
{
if (itr->IsObject())
{
Entity entity = entityManager->Create();
SceneObjectId sceneObj = scene->AddSceneObject(entity);
CreateSceneObject(itr, sceneObj);
CreateRenderObject(itr, entity);
}
}
}
void SceneLoader::CreateChildObjects(ValueItr itr, ValueItr end, SceneObjectId parent)
{
for (; itr != end; ++itr)
{
if (itr->IsObject())
{
Entity entity = entityManager->Create();
SceneObjectId sceneObj = scene->AddSceneObject(entity);
scene->SetParent(sceneObj, parent);
CreateSceneObject(itr, sceneObj);
CreateRenderObject(itr, entity);
}
}
}
void SceneLoader::CreateSceneObject(ValueItr itr, SceneObjectId sceneObject)
{
Mat4x4f transform;
rapidjson::Value::ConstMemberIterator rotItr = itr->FindMember("rotation");
if (rotItr != itr->MemberEnd())
{
Vec3f rot = ValueSerialization::Deserialize_Vec3f(rotItr->value);
transform = Mat4x4f::RotateEuler(Math::DegreesToRadians(rot)) * transform;
}
rapidjson::Value::ConstMemberIterator positionItr = itr->FindMember("position");
if (positionItr != itr->MemberEnd())
{
Vec3f pos = ValueSerialization::Deserialize_Vec3f(positionItr->value);
transform = Mat4x4f::Translate(pos) * transform;
}
scene->SetLocalTransform(sceneObject, transform);
rapidjson::Value::ConstMemberIterator childrenItr = itr->FindMember("children");
if (childrenItr != itr->MemberEnd() && childrenItr->value.IsArray())
{
rapidjson::Value::ConstValueIterator itr = childrenItr->value.Begin();
rapidjson::Value::ConstValueIterator end = childrenItr->value.End();
CreateChildObjects(itr, end, sceneObject);
}
}
void SceneLoader::CreateRenderObject(ValueItr itr, Entity entity)
{
MemberItr meshItr = itr->FindMember("mesh");
MemberItr materialItr = itr->FindMember("material");
if (meshItr != itr->MemberEnd() && meshItr->value.IsString() &&
materialItr != itr->MemberEnd() && materialItr->value.IsString())
{
RenderObjectId renderObj = renderer->AddRenderObject(entity);
StringRef meshPath(meshItr->value.GetString(), meshItr->value.GetStringLength());
MeshId meshId = meshManager->GetIdByPath(meshPath);
if (meshId.IsValid())
renderer->SetMeshId(renderObj, meshId);
StringRef matPath(materialItr->value.GetString(), materialItr->value.GetStringLength());
MaterialId matId = materialManager->GetIdByPath(matPath);
if (matId.IsNull() == false)
{
RenderOrderData data;
data.material = matId;
data.transparency = materialManager->GetTransparency(matId);
renderer->SetOrderData(renderObj, data);
}
}
}
Add an assertion so scene objects load valid materials
#include "Scene/SceneLoader.hpp"
#include "rapidjson/document.h"
#include "Engine/Engine.hpp"
#include "Rendering/Renderer.hpp"
#include "Resources/MeshManager.hpp"
#include "Entity/EntityManager.hpp"
#include "Resources/ResourceManager.hpp"
#include "Resources/MaterialManager.hpp"
#include "Resources/ValueSerialization.hpp"
SceneLoader::SceneLoader(Engine* engine, Scene* scene):
scene(scene),
renderer(engine->GetRenderer()),
meshManager(engine->GetMeshManager()),
materialManager(engine->GetMaterialManager()),
entityManager(engine->GetEntityManager()),
resourceManager(engine->GetResourceManager())
{
}
void SceneLoader::Load(BufferRef<char> sceneConfig)
{
rapidjson::Document doc;
doc.Parse(sceneConfig.data, sceneConfig.count);
if (doc.IsObject() == false)
return;
MemberItr objectsItr = doc.FindMember("objects");
if (objectsItr != doc.MemberEnd() && objectsItr->value.IsArray())
{
ValueItr itr = objectsItr->value.Begin();
ValueItr end = objectsItr->value.End();
CreateObjects(itr, end);
}
MemberItr colorItr = doc.FindMember("background-color");
if (colorItr != doc.MemberEnd())
{
scene->backgroundColor = ValueSerialization::Deserialize_Color(colorItr->value);
}
MemberItr skyboxItr = doc.FindMember("skybox-material");
if (skyboxItr != doc.MemberEnd() && skyboxItr->value.IsString())
{
StringRef materialPath(skyboxItr->value.GetString(), skyboxItr->value.GetStringLength());
MaterialId matId = materialManager->GetIdByPath(materialPath);
if (matId.IsNull() == false)
{
scene->SetSkyboxMaterial(matId);
}
}
}
void SceneLoader::CreateObjects(ValueItr itr, ValueItr end)
{
for (; itr != end; ++itr)
{
if (itr->IsObject())
{
Entity entity = entityManager->Create();
SceneObjectId sceneObj = scene->AddSceneObject(entity);
CreateSceneObject(itr, sceneObj);
CreateRenderObject(itr, entity);
}
}
}
void SceneLoader::CreateChildObjects(ValueItr itr, ValueItr end, SceneObjectId parent)
{
for (; itr != end; ++itr)
{
if (itr->IsObject())
{
Entity entity = entityManager->Create();
SceneObjectId sceneObj = scene->AddSceneObject(entity);
scene->SetParent(sceneObj, parent);
CreateSceneObject(itr, sceneObj);
CreateRenderObject(itr, entity);
}
}
}
void SceneLoader::CreateSceneObject(ValueItr itr, SceneObjectId sceneObject)
{
Mat4x4f transform;
rapidjson::Value::ConstMemberIterator rotItr = itr->FindMember("rotation");
if (rotItr != itr->MemberEnd())
{
Vec3f rot = ValueSerialization::Deserialize_Vec3f(rotItr->value);
transform = Mat4x4f::RotateEuler(Math::DegreesToRadians(rot)) * transform;
}
rapidjson::Value::ConstMemberIterator positionItr = itr->FindMember("position");
if (positionItr != itr->MemberEnd())
{
Vec3f pos = ValueSerialization::Deserialize_Vec3f(positionItr->value);
transform = Mat4x4f::Translate(pos) * transform;
}
scene->SetLocalTransform(sceneObject, transform);
rapidjson::Value::ConstMemberIterator childrenItr = itr->FindMember("children");
if (childrenItr != itr->MemberEnd() && childrenItr->value.IsArray())
{
rapidjson::Value::ConstValueIterator itr = childrenItr->value.Begin();
rapidjson::Value::ConstValueIterator end = childrenItr->value.End();
CreateChildObjects(itr, end, sceneObject);
}
}
void SceneLoader::CreateRenderObject(ValueItr itr, Entity entity)
{
MemberItr meshItr = itr->FindMember("mesh");
MemberItr materialItr = itr->FindMember("material");
if (meshItr != itr->MemberEnd() && meshItr->value.IsString() &&
materialItr != itr->MemberEnd() && materialItr->value.IsString())
{
RenderObjectId renderObj = renderer->AddRenderObject(entity);
StringRef meshPath(meshItr->value.GetString(), meshItr->value.GetStringLength());
MeshId meshId = meshManager->GetIdByPath(meshPath);
if (meshId.IsValid())
renderer->SetMeshId(renderObj, meshId);
StringRef matPath(materialItr->value.GetString(), materialItr->value.GetStringLength());
MaterialId matId = materialManager->GetIdByPath(matPath);
assert(matId.IsNull() == false);
RenderOrderData data;
data.material = matId;
data.transparency = materialManager->GetTransparency(matId);
renderer->SetOrderData(renderObj, data);
}
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/compression/Zstd.h>
#if FOLLY_HAVE_LIBZSTD
#include <stdexcept>
#include <string>
#include <zstd.h>
#include <folly/Conv.h>
#include <folly/Range.h>
#include <folly/ScopeGuard.h>
#include <folly/compression/CompressionContextPoolSingletons.h>
#include <folly/compression/Utils.h>
static_assert(
ZSTD_VERSION_NUMBER >= 10302,
"zstd-1.3.2 is the minimum supported zstd version.");
using folly::io::compression::detail::dataStartsWithLE;
using folly::io::compression::detail::prefixToStringLE;
using namespace folly::compression::contexts;
namespace folly {
namespace io {
namespace zstd {
namespace {
// Compatibility helpers for zstd versions < 1.4.0
#if ZSTD_VERSION_NUMBER < 10400
#define ZSTD_CCtxParams_setParameter ZSTD_CCtxParam_setParameter
#endif
// Compatibility helpers for zstd versions < 1.3.8.
#if ZSTD_VERSION_NUMBER < 10308
#define ZSTD_compressStream2 ZSTD_compress_generic
#define ZSTD_c_compressionLevel ZSTD_p_compressionLevel
#define ZSTD_c_contentSizeFlag ZSTD_p_contentSizeFlag
void resetCCtxSessionAndParameters(ZSTD_CCtx* cctx) {
ZSTD_CCtx_reset(cctx);
}
void resetDCtxSessionAndParameters(ZSTD_DCtx* dctx) {
ZSTD_DCtx_reset(dctx);
}
#else
void resetCCtxSessionAndParameters(ZSTD_CCtx* cctx) {
ZSTD_CCtx_reset(cctx, ZSTD_reset_session_and_parameters);
}
void resetDCtxSessionAndParameters(ZSTD_DCtx* dctx) {
ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters);
}
#endif
size_t zstdThrowIfError(size_t rc) {
if (!ZSTD_isError(rc)) {
return rc;
}
throw std::runtime_error(
to<std::string>("ZSTD returned an error: ", ZSTD_getErrorName(rc)));
}
ZSTD_EndDirective zstdTranslateFlush(StreamCodec::FlushOp flush) {
switch (flush) {
case StreamCodec::FlushOp::NONE:
return ZSTD_e_continue;
case StreamCodec::FlushOp::FLUSH:
return ZSTD_e_flush;
case StreamCodec::FlushOp::END:
return ZSTD_e_end;
default:
throw std::invalid_argument("ZSTDStreamCodec: Invalid flush");
}
}
class ZSTDStreamCodec final : public StreamCodec {
public:
explicit ZSTDStreamCodec(Options options);
std::vector<std::string> validPrefixes() const override;
bool canUncompress(
const IOBuf* data, Optional<uint64_t> uncompressedLength) const override;
private:
bool doNeedsUncompressedLength() const override;
uint64_t doMaxCompressedLength(uint64_t uncompressedLength) const override;
Optional<uint64_t> doGetUncompressedLength(
IOBuf const* data, Optional<uint64_t> uncompressedLength) const override;
void doResetStream() override;
bool doCompressStream(
ByteRange& input,
MutableByteRange& output,
StreamCodec::FlushOp flushOp) override;
bool doUncompressStream(
ByteRange& input,
MutableByteRange& output,
StreamCodec::FlushOp flushOp) override;
void resetCCtx();
void resetDCtx();
Options options_;
bool needReset_{true};
ZSTD_CCtx_Pool::Ref cctx_{getNULL_ZSTD_CCtx()};
ZSTD_DCtx_Pool::Ref dctx_{getNULL_ZSTD_DCtx()};
};
constexpr uint32_t kZSTDMagicLE = 0xFD2FB528;
std::vector<std::string> ZSTDStreamCodec::validPrefixes() const {
return {prefixToStringLE(kZSTDMagicLE)};
}
bool ZSTDStreamCodec::canUncompress(
const IOBuf* data, Optional<uint64_t>) const {
return dataStartsWithLE(data, kZSTDMagicLE);
}
CodecType codecType(Options const& options) {
int const level = options.level();
DCHECK_NE(level, 0);
return level > 0 ? CodecType::ZSTD : CodecType::ZSTD_FAST;
}
ZSTDStreamCodec::ZSTDStreamCodec(Options options)
: StreamCodec(codecType(options), options.level()),
options_(std::move(options)) {}
bool ZSTDStreamCodec::doNeedsUncompressedLength() const {
return false;
}
uint64_t ZSTDStreamCodec::doMaxCompressedLength(
uint64_t uncompressedLength) const {
return ZSTD_compressBound(uncompressedLength);
}
Optional<uint64_t> ZSTDStreamCodec::doGetUncompressedLength(
IOBuf const* data, Optional<uint64_t> uncompressedLength) const {
// Read decompressed size from frame if available in first IOBuf.
auto const decompressedSize =
ZSTD_getFrameContentSize(data->data(), data->length());
if (decompressedSize == ZSTD_CONTENTSIZE_UNKNOWN ||
decompressedSize == ZSTD_CONTENTSIZE_ERROR) {
return uncompressedLength;
}
if (uncompressedLength && *uncompressedLength != decompressedSize) {
throw std::runtime_error("ZSTD: invalid uncompressed length");
}
return decompressedSize;
}
void ZSTDStreamCodec::doResetStream() {
needReset_ = true;
}
void ZSTDStreamCodec::resetCCtx() {
if (!cctx_) {
cctx_ = getZSTD_CCtx();
if (!cctx_) {
throw std::bad_alloc{};
}
}
resetCCtxSessionAndParameters(cctx_.get());
zstdThrowIfError(
ZSTD_CCtx_setParametersUsingCCtxParams(cctx_.get(), options_.params()));
zstdThrowIfError(ZSTD_CCtx_setPledgedSrcSize(
cctx_.get(), uncompressedLength().value_or(ZSTD_CONTENTSIZE_UNKNOWN)));
}
bool ZSTDStreamCodec::doCompressStream(
ByteRange& input, MutableByteRange& output, StreamCodec::FlushOp flushOp) {
if (needReset_) {
resetCCtx();
needReset_ = false;
}
ZSTD_inBuffer in = {input.data(), input.size(), 0};
ZSTD_outBuffer out = {output.data(), output.size(), 0};
SCOPE_EXIT {
input.uncheckedAdvance(in.pos);
output.uncheckedAdvance(out.pos);
};
size_t const rc = zstdThrowIfError(ZSTD_compressStream2(
cctx_.get(), &out, &in, zstdTranslateFlush(flushOp)));
switch (flushOp) {
case StreamCodec::FlushOp::NONE:
return false;
case StreamCodec::FlushOp::FLUSH:
case StreamCodec::FlushOp::END:
return rc == 0;
default:
throw std::invalid_argument("ZSTD: invalid FlushOp");
}
}
void ZSTDStreamCodec::resetDCtx() {
if (!dctx_) {
dctx_ = getZSTD_DCtx();
if (!dctx_) {
throw std::bad_alloc{};
}
}
resetDCtxSessionAndParameters(dctx_.get());
if (options_.maxWindowSize() != 0) {
zstdThrowIfError(
ZSTD_DCtx_setMaxWindowSize(dctx_.get(), options_.maxWindowSize()));
}
}
bool ZSTDStreamCodec::doUncompressStream(
ByteRange& input, MutableByteRange& output, StreamCodec::FlushOp) {
if (needReset_) {
resetDCtx();
needReset_ = false;
}
ZSTD_inBuffer in = {input.data(), input.size(), 0};
ZSTD_outBuffer out = {output.data(), output.size(), 0};
SCOPE_EXIT {
input.uncheckedAdvance(in.pos);
output.uncheckedAdvance(out.pos);
};
size_t const rc =
zstdThrowIfError(ZSTD_decompressStream(dctx_.get(), &out, &in));
return rc == 0;
}
} // namespace
Options::Options(int level) : params_(ZSTD_createCCtxParams()), level_(level) {
if (params_ == nullptr) {
throw std::bad_alloc{};
}
#if ZSTD_VERSION_NUMBER >= 10304
zstdThrowIfError(ZSTD_CCtxParams_init(params_.get(), level));
#else
zstdThrowIfError(ZSTD_initCCtxParams(params_.get(), level));
set(ZSTD_c_contentSizeFlag, 1);
#endif
// zstd-1.3.4 is buggy and only disables Huffman decompression for negative
// compression levels if this call is present. This call is begign in other
// versions.
set(ZSTD_c_compressionLevel, level);
}
void Options::set(ZSTD_cParameter param, unsigned value) {
zstdThrowIfError(ZSTD_CCtxParams_setParameter(params_.get(), param, value));
if (param == ZSTD_c_compressionLevel) {
level_ = static_cast<int>(value);
}
}
/* static */ void Options::freeCCtxParams(ZSTD_CCtx_params* params) {
ZSTD_freeCCtxParams(params);
}
std::unique_ptr<Codec> getCodec(Options options) {
return std::make_unique<ZSTDStreamCodec>(std::move(options));
}
std::unique_ptr<StreamCodec> getStreamCodec(Options options) {
return std::make_unique<ZSTDStreamCodec>(std::move(options));
}
} // namespace zstd
} // namespace io
} // namespace folly
#endif
Surrender the ZSTD_{C,D}Ctx on (de)compression end
Summary: We already cache the contexts in the context pool. We don't also need to cache the contexts in the `Codec` when the user keeps the codec around. This will allow us to better utilize the contexts, and potentially reduce memory usage.
Reviewed By: felixhandte
Differential Revision: D26356275
fbshipit-source-id: 6d80326f469de61094478c73b6fe557eebcd7a22
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/compression/Zstd.h>
#if FOLLY_HAVE_LIBZSTD
#include <stdexcept>
#include <string>
#include <zstd.h>
#include <folly/Conv.h>
#include <folly/Range.h>
#include <folly/ScopeGuard.h>
#include <folly/compression/CompressionContextPoolSingletons.h>
#include <folly/compression/Utils.h>
static_assert(
ZSTD_VERSION_NUMBER >= 10302,
"zstd-1.3.2 is the minimum supported zstd version.");
using folly::io::compression::detail::dataStartsWithLE;
using folly::io::compression::detail::prefixToStringLE;
using namespace folly::compression::contexts;
namespace folly {
namespace io {
namespace zstd {
namespace {
// Compatibility helpers for zstd versions < 1.4.0
#if ZSTD_VERSION_NUMBER < 10400
#define ZSTD_CCtxParams_setParameter ZSTD_CCtxParam_setParameter
#endif
// Compatibility helpers for zstd versions < 1.3.8.
#if ZSTD_VERSION_NUMBER < 10308
#define ZSTD_compressStream2 ZSTD_compress_generic
#define ZSTD_c_compressionLevel ZSTD_p_compressionLevel
#define ZSTD_c_contentSizeFlag ZSTD_p_contentSizeFlag
void resetCCtxSessionAndParameters(ZSTD_CCtx* cctx) {
ZSTD_CCtx_reset(cctx);
}
void resetDCtxSessionAndParameters(ZSTD_DCtx* dctx) {
ZSTD_DCtx_reset(dctx);
}
#else
void resetCCtxSessionAndParameters(ZSTD_CCtx* cctx) {
ZSTD_CCtx_reset(cctx, ZSTD_reset_session_and_parameters);
}
void resetDCtxSessionAndParameters(ZSTD_DCtx* dctx) {
ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters);
}
#endif
size_t zstdThrowIfError(size_t rc) {
if (!ZSTD_isError(rc)) {
return rc;
}
throw std::runtime_error(
to<std::string>("ZSTD returned an error: ", ZSTD_getErrorName(rc)));
}
ZSTD_EndDirective zstdTranslateFlush(StreamCodec::FlushOp flush) {
switch (flush) {
case StreamCodec::FlushOp::NONE:
return ZSTD_e_continue;
case StreamCodec::FlushOp::FLUSH:
return ZSTD_e_flush;
case StreamCodec::FlushOp::END:
return ZSTD_e_end;
default:
throw std::invalid_argument("ZSTDStreamCodec: Invalid flush");
}
}
class ZSTDStreamCodec final : public StreamCodec {
public:
explicit ZSTDStreamCodec(Options options);
std::vector<std::string> validPrefixes() const override;
bool canUncompress(
const IOBuf* data, Optional<uint64_t> uncompressedLength) const override;
private:
bool doNeedsUncompressedLength() const override;
uint64_t doMaxCompressedLength(uint64_t uncompressedLength) const override;
Optional<uint64_t> doGetUncompressedLength(
IOBuf const* data, Optional<uint64_t> uncompressedLength) const override;
void doResetStream() override;
bool doCompressStream(
ByteRange& input,
MutableByteRange& output,
StreamCodec::FlushOp flushOp) override;
bool doUncompressStream(
ByteRange& input,
MutableByteRange& output,
StreamCodec::FlushOp flushOp) override;
void resetCCtx();
void resetDCtx();
Options options_;
ZSTD_CCtx_Pool::Ref cctx_{getNULL_ZSTD_CCtx()};
ZSTD_DCtx_Pool::Ref dctx_{getNULL_ZSTD_DCtx()};
};
constexpr uint32_t kZSTDMagicLE = 0xFD2FB528;
std::vector<std::string> ZSTDStreamCodec::validPrefixes() const {
return {prefixToStringLE(kZSTDMagicLE)};
}
bool ZSTDStreamCodec::canUncompress(
const IOBuf* data, Optional<uint64_t>) const {
return dataStartsWithLE(data, kZSTDMagicLE);
}
CodecType codecType(Options const& options) {
int const level = options.level();
DCHECK_NE(level, 0);
return level > 0 ? CodecType::ZSTD : CodecType::ZSTD_FAST;
}
ZSTDStreamCodec::ZSTDStreamCodec(Options options)
: StreamCodec(codecType(options), options.level()),
options_(std::move(options)) {}
bool ZSTDStreamCodec::doNeedsUncompressedLength() const {
return false;
}
uint64_t ZSTDStreamCodec::doMaxCompressedLength(
uint64_t uncompressedLength) const {
return ZSTD_compressBound(uncompressedLength);
}
Optional<uint64_t> ZSTDStreamCodec::doGetUncompressedLength(
IOBuf const* data, Optional<uint64_t> uncompressedLength) const {
// Read decompressed size from frame if available in first IOBuf.
auto const decompressedSize =
ZSTD_getFrameContentSize(data->data(), data->length());
if (decompressedSize == ZSTD_CONTENTSIZE_UNKNOWN ||
decompressedSize == ZSTD_CONTENTSIZE_ERROR) {
return uncompressedLength;
}
if (uncompressedLength && *uncompressedLength != decompressedSize) {
throw std::runtime_error("ZSTD: invalid uncompressed length");
}
return decompressedSize;
}
void ZSTDStreamCodec::doResetStream() {
cctx_.reset(nullptr);
dctx_.reset(nullptr);
}
void ZSTDStreamCodec::resetCCtx() {
DCHECK(cctx_ == nullptr);
cctx_ = getZSTD_CCtx();
DCHECK(cctx_ != nullptr);
resetCCtxSessionAndParameters(cctx_.get());
zstdThrowIfError(
ZSTD_CCtx_setParametersUsingCCtxParams(cctx_.get(), options_.params()));
zstdThrowIfError(ZSTD_CCtx_setPledgedSrcSize(
cctx_.get(), uncompressedLength().value_or(ZSTD_CONTENTSIZE_UNKNOWN)));
}
bool ZSTDStreamCodec::doCompressStream(
ByteRange& input, MutableByteRange& output, StreamCodec::FlushOp flushOp) {
if (cctx_ == nullptr) {
resetCCtx();
}
ZSTD_inBuffer in = {input.data(), input.size(), 0};
ZSTD_outBuffer out = {output.data(), output.size(), 0};
SCOPE_EXIT {
input.uncheckedAdvance(in.pos);
output.uncheckedAdvance(out.pos);
};
size_t const rc = zstdThrowIfError(ZSTD_compressStream2(
cctx_.get(), &out, &in, zstdTranslateFlush(flushOp)));
switch (flushOp) {
case StreamCodec::FlushOp::NONE:
return false;
case StreamCodec::FlushOp::FLUSH:
return rc == 0;
case StreamCodec::FlushOp::END:
if (rc == 0) {
// Surrender our cctx_
doResetStream();
}
return rc == 0;
default:
throw std::invalid_argument("ZSTD: invalid FlushOp");
}
}
void ZSTDStreamCodec::resetDCtx() {
DCHECK(dctx_ == nullptr);
dctx_ = getZSTD_DCtx();
DCHECK(dctx_ != nullptr);
resetDCtxSessionAndParameters(dctx_.get());
if (options_.maxWindowSize() != 0) {
zstdThrowIfError(
ZSTD_DCtx_setMaxWindowSize(dctx_.get(), options_.maxWindowSize()));
}
}
bool ZSTDStreamCodec::doUncompressStream(
ByteRange& input, MutableByteRange& output, StreamCodec::FlushOp) {
if (dctx_ == nullptr) {
resetDCtx();
}
ZSTD_inBuffer in = {input.data(), input.size(), 0};
ZSTD_outBuffer out = {output.data(), output.size(), 0};
SCOPE_EXIT {
input.uncheckedAdvance(in.pos);
output.uncheckedAdvance(out.pos);
};
size_t const rc =
zstdThrowIfError(ZSTD_decompressStream(dctx_.get(), &out, &in));
if (rc == 0) {
// Surrender our dctx_
doResetStream();
}
return rc == 0;
}
} // namespace
Options::Options(int level) : params_(ZSTD_createCCtxParams()), level_(level) {
if (params_ == nullptr) {
throw std::bad_alloc{};
}
#if ZSTD_VERSION_NUMBER >= 10304
zstdThrowIfError(ZSTD_CCtxParams_init(params_.get(), level));
#else
zstdThrowIfError(ZSTD_initCCtxParams(params_.get(), level));
set(ZSTD_c_contentSizeFlag, 1);
#endif
// zstd-1.3.4 is buggy and only disables Huffman decompression for negative
// compression levels if this call is present. This call is begign in other
// versions.
set(ZSTD_c_compressionLevel, level);
}
void Options::set(ZSTD_cParameter param, unsigned value) {
zstdThrowIfError(ZSTD_CCtxParams_setParameter(params_.get(), param, value));
if (param == ZSTD_c_compressionLevel) {
level_ = static_cast<int>(value);
}
}
/* static */ void Options::freeCCtxParams(ZSTD_CCtx_params* params) {
ZSTD_freeCCtxParams(params);
}
std::unique_ptr<Codec> getCodec(Options options) {
return std::make_unique<ZSTDStreamCodec>(std::move(options));
}
std::unique_ptr<StreamCodec> getStreamCodec(Options options) {
return std::make_unique<ZSTDStreamCodec>(std::move(options));
}
} // namespace zstd
} // namespace io
} // namespace folly
#endif
|
/*
* Copyright 2014 Facebook, Inc.
*
* 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 <folly/Foreach.h>
#include <folly/Benchmark.h>
#include <gtest/gtest.h>
#include <map>
#include <string>
#include <vector>
#include <list>
using namespace folly;
using namespace folly::detail;
TEST(Foreach, ForEachRvalue) {
const char* const hello = "hello";
int n = 0;
FOR_EACH(it, std::string(hello)) {
++n;
}
EXPECT_EQ(strlen(hello), n);
FOR_EACH_R(it, std::string(hello)) {
--n;
EXPECT_EQ(hello[n], *it);
}
EXPECT_EQ(0, n);
}
TEST(Foreach, ForEachKV) {
std::map<std::string, int> testMap;
testMap["abc"] = 1;
testMap["def"] = 2;
std::string keys = "";
int values = 0;
int numEntries = 0;
FOR_EACH_KV (key, value, testMap) {
keys += key;
values += value;
++numEntries;
}
EXPECT_EQ("abcdef", keys);
EXPECT_EQ(3, values);
EXPECT_EQ(2, numEntries);
}
TEST(Foreach, ForEachKVBreak) {
std::map<std::string, int> testMap;
testMap["abc"] = 1;
testMap["def"] = 2;
std::string keys = "";
int values = 0;
int numEntries = 0;
FOR_EACH_KV (key, value, testMap) {
keys += key;
values += value;
++numEntries;
break;
}
EXPECT_EQ("abc", keys);
EXPECT_EQ(1, values);
EXPECT_EQ(1, numEntries);
}
TEST(Foreach, ForEachKvWithMultiMap) {
std::multimap<std::string, int> testMap;
testMap.insert(std::make_pair("abc", 1));
testMap.insert(std::make_pair("abc", 2));
testMap.insert(std::make_pair("def", 3));
std::string keys = "";
int values = 0;
int numEntries = 0;
FOR_EACH_KV (key, value, testMap) {
keys += key;
values += value;
++numEntries;
}
EXPECT_EQ("abcabcdef", keys);
EXPECT_EQ(6, values);
EXPECT_EQ(3, numEntries);
}
TEST(Foreach, ForEachEnumerate) {
std::vector<int> vv;
int sumAA = 0;
int sumIter = 0;
int numIterations = 0;
FOR_EACH_ENUMERATE(aa, iter, vv) {
sumAA += aa;
sumIter += *iter;
++numIterations;
}
EXPECT_EQ(sumAA, 0);
EXPECT_EQ(sumIter, 0);
EXPECT_EQ(numIterations, 0);
vv.push_back(1);
vv.push_back(3);
vv.push_back(5);
FOR_EACH_ENUMERATE(aa, iter, vv) {
sumAA += aa;
sumIter += *iter;
++numIterations;
}
EXPECT_EQ(sumAA, 3); // 0 + 1 + 2
EXPECT_EQ(sumIter, 9); // 1 + 3 + 5
EXPECT_EQ(numIterations, 3);
}
TEST(Foreach, ForEachEnumerateBreak) {
std::vector<int> vv;
int sumAA = 0;
int sumIter = 0;
int numIterations = 0;
vv.push_back(1);
vv.push_back(2);
vv.push_back(4);
vv.push_back(8);
FOR_EACH_ENUMERATE(aa, iter, vv) {
sumAA += aa;
sumIter += *iter;
++numIterations;
if (aa == 1) break;
}
EXPECT_EQ(sumAA, 1); // 0 + 1
EXPECT_EQ(sumIter, 3); // 1 + 2
EXPECT_EQ(numIterations, 2);
}
TEST(Foreach, ForEachRangeR) {
int sum = 0;
FOR_EACH_RANGE_R (i, 0, 0) {
sum += i;
}
EXPECT_EQ(0, sum);
FOR_EACH_RANGE_R (i, 0, -1) {
sum += i;
}
EXPECT_EQ(0, sum);
FOR_EACH_RANGE_R (i, 0, 5) {
sum += i;
}
EXPECT_EQ(10, sum);
std::list<int> lst = { 0, 1, 2, 3, 4 };
sum = 0;
FOR_EACH_RANGE_R (i, lst.begin(), lst.end()) {
sum += *i;
}
EXPECT_EQ(10, sum);
}
// Benchmarks:
// 1. Benchmark iterating through the man with FOR_EACH, and also assign
// iter->first and iter->second to local vars inside the FOR_EACH loop.
// 2. Benchmark iterating through the man with FOR_EACH, but use iter->first and
// iter->second as is, without assigning to local variables.
// 3. Use FOR_EACH_KV loop to iterate through the map.
std::map<int, std::string> bmMap; // For use in benchmarks below.
void setupBenchmark(size_t iters) {
bmMap.clear();
for (size_t i = 0; i < iters; ++i) {
bmMap[i] = "teststring";
}
}
BENCHMARK(ForEachKVNoMacroAssign, iters) {
int sumKeys = 0;
std::string sumValues;
BENCHMARK_SUSPEND {
setupBenchmark(iters);
int sumKeys = 0;
std::string sumValues = "";
}
FOR_EACH (iter, bmMap) {
const int k = iter->first;
const std::string v = iter->second;
sumKeys += k;
sumValues += v;
}
}
BENCHMARK(ForEachKVNoMacroNoAssign, iters) {
int sumKeys = 0;
std::string sumValues;
BENCHMARK_SUSPEND {
setupBenchmark(iters);
}
FOR_EACH (iter, bmMap) {
sumKeys += iter->first;
sumValues += iter->second;
}
}
BENCHMARK(ManualLoopNoAssign, iters) {
BENCHMARK_SUSPEND {
setupBenchmark(iters);
}
int sumKeys = 0;
std::string sumValues;
for (auto iter = bmMap.begin(); iter != bmMap.end(); ++iter) {
sumKeys += iter->first;
sumValues += iter->second;
}
}
BENCHMARK(ForEachKVMacro, iters) {
BENCHMARK_SUSPEND {
setupBenchmark(iters);
}
int sumKeys = 0;
std::string sumValues;
FOR_EACH_KV (k, v, bmMap) {
sumKeys += k;
sumValues += v;
}
}
BENCHMARK(ForEachManual, iters) {
int sum = 1;
for (size_t i = 1; i < iters; ++i) {
sum *= i;
}
doNotOptimizeAway(sum);
}
BENCHMARK(ForEachRange, iters) {
int sum = 1;
FOR_EACH_RANGE (i, 1, iters) {
sum *= i;
}
doNotOptimizeAway(sum);
}
BENCHMARK(ForEachDescendingManual, iters) {
int sum = 1;
for (size_t i = iters; i-- > 1; ) {
sum *= i;
}
doNotOptimizeAway(sum);
}
BENCHMARK(ForEachRangeR, iters) {
int sum = 1;
FOR_EACH_RANGE_R (i, 1, iters) {
sum *= i;
}
doNotOptimizeAway(sum);
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
auto r = RUN_ALL_TESTS();
if (r) {
return r;
}
runBenchmarks();
return 0;
}
folly/test/ForeachTest.cpp: avoid -Wsign-compare error
Summary:
* folly/test/ForeachTest.cpp: Change a "1" to "1U", so it matches
the signedness of the size_t upper bound.
Otherwise, gcc-4.9 fails with e.g.,
folly/Foreach.h:194:16: error: comparison between signed and unsigned integer expressions [-Werror=sign-compare]
Test Plan:
Run this and note there are fewer errors than before:
fbconfig --platform-all=gcc-4.9-glibc-2.20 -r folly && fbmake dbgo
Reviewed By: andrei.alexandrescu@fb.com
Subscribers: folly-diffs@
FB internal diff: D1770603
Tasks: 5941250
Signature: t1:1770603:1420679246:56ef62ac7fa4413a4ad6310c3381a12bdc59e64c
/*
* Copyright 2014 Facebook, Inc.
*
* 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 <folly/Foreach.h>
#include <folly/Benchmark.h>
#include <gtest/gtest.h>
#include <map>
#include <string>
#include <vector>
#include <list>
using namespace folly;
using namespace folly::detail;
TEST(Foreach, ForEachRvalue) {
const char* const hello = "hello";
int n = 0;
FOR_EACH(it, std::string(hello)) {
++n;
}
EXPECT_EQ(strlen(hello), n);
FOR_EACH_R(it, std::string(hello)) {
--n;
EXPECT_EQ(hello[n], *it);
}
EXPECT_EQ(0, n);
}
TEST(Foreach, ForEachKV) {
std::map<std::string, int> testMap;
testMap["abc"] = 1;
testMap["def"] = 2;
std::string keys = "";
int values = 0;
int numEntries = 0;
FOR_EACH_KV (key, value, testMap) {
keys += key;
values += value;
++numEntries;
}
EXPECT_EQ("abcdef", keys);
EXPECT_EQ(3, values);
EXPECT_EQ(2, numEntries);
}
TEST(Foreach, ForEachKVBreak) {
std::map<std::string, int> testMap;
testMap["abc"] = 1;
testMap["def"] = 2;
std::string keys = "";
int values = 0;
int numEntries = 0;
FOR_EACH_KV (key, value, testMap) {
keys += key;
values += value;
++numEntries;
break;
}
EXPECT_EQ("abc", keys);
EXPECT_EQ(1, values);
EXPECT_EQ(1, numEntries);
}
TEST(Foreach, ForEachKvWithMultiMap) {
std::multimap<std::string, int> testMap;
testMap.insert(std::make_pair("abc", 1));
testMap.insert(std::make_pair("abc", 2));
testMap.insert(std::make_pair("def", 3));
std::string keys = "";
int values = 0;
int numEntries = 0;
FOR_EACH_KV (key, value, testMap) {
keys += key;
values += value;
++numEntries;
}
EXPECT_EQ("abcabcdef", keys);
EXPECT_EQ(6, values);
EXPECT_EQ(3, numEntries);
}
TEST(Foreach, ForEachEnumerate) {
std::vector<int> vv;
int sumAA = 0;
int sumIter = 0;
int numIterations = 0;
FOR_EACH_ENUMERATE(aa, iter, vv) {
sumAA += aa;
sumIter += *iter;
++numIterations;
}
EXPECT_EQ(sumAA, 0);
EXPECT_EQ(sumIter, 0);
EXPECT_EQ(numIterations, 0);
vv.push_back(1);
vv.push_back(3);
vv.push_back(5);
FOR_EACH_ENUMERATE(aa, iter, vv) {
sumAA += aa;
sumIter += *iter;
++numIterations;
}
EXPECT_EQ(sumAA, 3); // 0 + 1 + 2
EXPECT_EQ(sumIter, 9); // 1 + 3 + 5
EXPECT_EQ(numIterations, 3);
}
TEST(Foreach, ForEachEnumerateBreak) {
std::vector<int> vv;
int sumAA = 0;
int sumIter = 0;
int numIterations = 0;
vv.push_back(1);
vv.push_back(2);
vv.push_back(4);
vv.push_back(8);
FOR_EACH_ENUMERATE(aa, iter, vv) {
sumAA += aa;
sumIter += *iter;
++numIterations;
if (aa == 1) break;
}
EXPECT_EQ(sumAA, 1); // 0 + 1
EXPECT_EQ(sumIter, 3); // 1 + 2
EXPECT_EQ(numIterations, 2);
}
TEST(Foreach, ForEachRangeR) {
int sum = 0;
FOR_EACH_RANGE_R (i, 0, 0) {
sum += i;
}
EXPECT_EQ(0, sum);
FOR_EACH_RANGE_R (i, 0, -1) {
sum += i;
}
EXPECT_EQ(0, sum);
FOR_EACH_RANGE_R (i, 0, 5) {
sum += i;
}
EXPECT_EQ(10, sum);
std::list<int> lst = { 0, 1, 2, 3, 4 };
sum = 0;
FOR_EACH_RANGE_R (i, lst.begin(), lst.end()) {
sum += *i;
}
EXPECT_EQ(10, sum);
}
// Benchmarks:
// 1. Benchmark iterating through the man with FOR_EACH, and also assign
// iter->first and iter->second to local vars inside the FOR_EACH loop.
// 2. Benchmark iterating through the man with FOR_EACH, but use iter->first and
// iter->second as is, without assigning to local variables.
// 3. Use FOR_EACH_KV loop to iterate through the map.
std::map<int, std::string> bmMap; // For use in benchmarks below.
void setupBenchmark(size_t iters) {
bmMap.clear();
for (size_t i = 0; i < iters; ++i) {
bmMap[i] = "teststring";
}
}
BENCHMARK(ForEachKVNoMacroAssign, iters) {
int sumKeys = 0;
std::string sumValues;
BENCHMARK_SUSPEND {
setupBenchmark(iters);
int sumKeys = 0;
std::string sumValues = "";
}
FOR_EACH (iter, bmMap) {
const int k = iter->first;
const std::string v = iter->second;
sumKeys += k;
sumValues += v;
}
}
BENCHMARK(ForEachKVNoMacroNoAssign, iters) {
int sumKeys = 0;
std::string sumValues;
BENCHMARK_SUSPEND {
setupBenchmark(iters);
}
FOR_EACH (iter, bmMap) {
sumKeys += iter->first;
sumValues += iter->second;
}
}
BENCHMARK(ManualLoopNoAssign, iters) {
BENCHMARK_SUSPEND {
setupBenchmark(iters);
}
int sumKeys = 0;
std::string sumValues;
for (auto iter = bmMap.begin(); iter != bmMap.end(); ++iter) {
sumKeys += iter->first;
sumValues += iter->second;
}
}
BENCHMARK(ForEachKVMacro, iters) {
BENCHMARK_SUSPEND {
setupBenchmark(iters);
}
int sumKeys = 0;
std::string sumValues;
FOR_EACH_KV (k, v, bmMap) {
sumKeys += k;
sumValues += v;
}
}
BENCHMARK(ForEachManual, iters) {
int sum = 1;
for (size_t i = 1; i < iters; ++i) {
sum *= i;
}
doNotOptimizeAway(sum);
}
BENCHMARK(ForEachRange, iters) {
int sum = 1;
FOR_EACH_RANGE (i, 1, iters) {
sum *= i;
}
doNotOptimizeAway(sum);
}
BENCHMARK(ForEachDescendingManual, iters) {
int sum = 1;
for (size_t i = iters; i-- > 1; ) {
sum *= i;
}
doNotOptimizeAway(sum);
}
BENCHMARK(ForEachRangeR, iters) {
int sum = 1;
FOR_EACH_RANGE_R (i, 1U, iters) {
sum *= i;
}
doNotOptimizeAway(sum);
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
auto r = RUN_ALL_TESTS();
if (r) {
return r;
}
runBenchmarks();
return 0;
}
|
#include "Camera.h"
#include "Render.h"
#include "base/basedef.h"
#include "math/mathdef.h"
#include <GL/glew.h>
using fei::Camera;
Camera::Camera()
: width(1.0f),
height(1.0f),
cameraType(Type::ORTHOGRAPHIC),
cameraScale(1.0f),
needDataUpdate(true)
{
}
void Camera::update()
{
updateCameraData();
glMatrixMode(GL_PROJECTION);
if (cameraType == Type::ORTHOGRAPHIC) {
glLoadIdentity();
glOrtho(left, right, bottom, top, near, far);
} else if (cameraType == Type::PERSPECTIVE) {
//TODO: write it when you want to test it
}
glTranslatef(-pos.x, -pos.y, 0);
glMatrixMode(GL_MODELVIEW);
}
void Camera::setCameraType(Type type)
{
if (cameraType != type) {
cameraType = type;
needDataUpdate = true;
}
}
Camera::Type Camera::getCameraType()
{
return cameraType;
}
void Camera::setCameraScale(float scale)
{
if (cameraScale != scale && std::abs(scale) > fei::eps) {
cameraScale = scale;
needDataUpdate = true;
}
}
float Camera::getCameraScale()
{
return cameraScale;
}
void Camera::cameraScaleZoom(float zoom)
{
setCameraScale(cameraScale * zoom);
}
void Camera::cameraScaleCenterZoom(const Vec2& center, float zoom)
{
move((center - pos) * (1.0f - 1.0f / zoom));
setCameraScale(cameraScale * zoom);
}
void Camera::setCameraSize(const fei::Vec2& v)
{
width = v.x;
height = v.y;
needDataUpdate = true;
}
const fei::Vec2 Camera::screenToWorld(const fei::Vec2& scrPos)
{
updateCameraData();
auto camSize = fei::Vec2(right - left, top - bottom);
auto vpSize = fei::Render::getInstance()->getViewport().getSize();
auto ans = camSize.zoomed(scrPos.zoomed(vpSize.reciprocal()) - fei::Vec2(0.5f)) + pos;
return ans;
}
const fei::Vec2 Camera::worldToScreen(const fei::Vec2& wrdPos)
{
updateCameraData();
auto camSize = fei::Vec2(right - left, top - bottom);
auto vpSize = fei::Render::getInstance()->getViewport().getSize();
auto ans = ((wrdPos - pos).zoomed(camSize.reciprocal()) + fei::Vec2(0.5f)).zoomed(vpSize);
return ans;
}
void Camera::updateCameraData()
{
if (needDataUpdate) {
if (cameraType == Type::ORTHOGRAPHIC) {
float ratio = 2.0f * cameraScale;
left = -width / ratio;
right = width / ratio;
bottom = -height / ratio;
top = height / ratio;
near = -99999.0f;
far = 99999.0f;
} else if (cameraType == Type::PERSPECTIVE) {
//TODO: write it when you want to test it
}
needDataUpdate = false;
}
}
fix namespace
#include "Camera.h"
#include "Render.h"
#include "base/basedef.h"
#include "math/mathdef.h"
#include <GL/glew.h>
using fei::Camera;
Camera::Camera()
: width(1.0f),
height(1.0f),
cameraType(Type::ORTHOGRAPHIC),
cameraScale(1.0f),
needDataUpdate(true)
{
}
void Camera::update()
{
updateCameraData();
glMatrixMode(GL_PROJECTION);
if (cameraType == Type::ORTHOGRAPHIC) {
glLoadIdentity();
glOrtho(left, right, bottom, top, near, far);
} else if (cameraType == Type::PERSPECTIVE) {
//TODO: write it when you want to test it
}
glTranslatef(-pos.x, -pos.y, 0);
glMatrixMode(GL_MODELVIEW);
}
void Camera::setCameraType(Type type)
{
if (cameraType != type) {
cameraType = type;
needDataUpdate = true;
}
}
Camera::Type Camera::getCameraType()
{
return cameraType;
}
void Camera::setCameraScale(float scale)
{
if (cameraScale != scale && std::abs(scale) > fei::eps) {
cameraScale = scale;
needDataUpdate = true;
}
}
float Camera::getCameraScale()
{
return cameraScale;
}
void Camera::cameraScaleZoom(float zoom)
{
setCameraScale(cameraScale * zoom);
}
void Camera::cameraScaleCenterZoom(const fei::Vec2& center, float zoom)
{
move((center - pos) * (1.0f - 1.0f / zoom));
setCameraScale(cameraScale * zoom);
}
void Camera::setCameraSize(const fei::Vec2& v)
{
width = v.x;
height = v.y;
needDataUpdate = true;
}
const fei::Vec2 Camera::screenToWorld(const fei::Vec2& scrPos)
{
updateCameraData();
auto camSize = fei::Vec2(right - left, top - bottom);
auto vpSize = fei::Render::getInstance()->getViewport().getSize();
auto ans = camSize.zoomed(scrPos.zoomed(vpSize.reciprocal()) - fei::Vec2(0.5f)) + pos;
return ans;
}
const fei::Vec2 Camera::worldToScreen(const fei::Vec2& wrdPos)
{
updateCameraData();
auto camSize = fei::Vec2(right - left, top - bottom);
auto vpSize = fei::Render::getInstance()->getViewport().getSize();
auto ans = ((wrdPos - pos).zoomed(camSize.reciprocal()) + fei::Vec2(0.5f)).zoomed(vpSize);
return ans;
}
void Camera::updateCameraData()
{
if (needDataUpdate) {
if (cameraType == Type::ORTHOGRAPHIC) {
float ratio = 2.0f * cameraScale;
left = -width / ratio;
right = width / ratio;
bottom = -height / ratio;
top = height / ratio;
near = -99999.0f;
far = 99999.0f;
} else if (cameraType == Type::PERSPECTIVE) {
//TODO: write it when you want to test it
}
needDataUpdate = false;
}
}
|
//=================================================================================================
// Copyright (C) 2017 Olivier Mallet - All Rights Reserved
//=================================================================================================
#ifndef CHROMOSOME_HPP
#define CHROMOSOME_HPP
namespace galgo {
//=================================================================================================
template <typename T, int...N>
class Chromosome
{
static_assert(std::is_same<float,T>::value || std::is_same<double,T>::value, "variable type can only be float or double, please amend.");
public:
// constructor
Chromosome(const GeneticAlgorithm<T,N...>& ga);
// copy constructor
Chromosome(const Chromosome<T,N...>& rhs);
// end of recursion for creating new chromosome
template <int I = 0>
typename std::enable_if<I == sizeof...(N), void>::type create();
// recursion for creating new chromosome
template <int I = 0>
typename std::enable_if<I < sizeof...(N), void>::type create();
// end of recursion for initializing new chromosome
template <int I = 0>
typename std::enable_if<I == sizeof...(N), void>::type initialize();
// recursion for initializing new chromosome
template <int I = 0>
typename std::enable_if<I < sizeof...(N), void>::type initialize();
// end of recursion for converting gene to real value
template <int I = 0>
typename std::enable_if<I == sizeof...(N), void>::type convert();
// recursion for converting gene to real value
template <int I = 0>
typename std::enable_if<I < sizeof...(N), void>::type convert();
// evaluate chromosome
void evaluate();
// reset chromosome
void reset();
// end of recursion for setting or replace kth gene by a new one
template <int I = 0>
inline typename std::enable_if<I == sizeof...(N), void>::type setGene(int k);
// recursion for setting or replace kth gene by a new one
template <int I = 0>
inline typename std::enable_if<I < sizeof...(N), void>::type setGene(int k);
// end of recursion for initializing or replacing kth gene by a know value
template <int I = 0>
typename std::enable_if<I == sizeof...(N), void>::type initGene(int k, T x);
// recursion for initializing or replacing kth gene by a know value
template <int I = 0>
typename std::enable_if<I < sizeof...(N), void>::type initGene(int k, T x);
// add bit to chromosome
void addBit(char bit);
// initialize or replace an existing chromosome bit
void setBit(char bit, int pos);
// flip an existing chromosome bit
void flipBit(int pos);
// get chromosome bit
char getBit(int pos) const;
// initialize or replace a portion of bits with a portion of another chromosome
void setPortion(const Chromosome<T,N...>& x, int start, int end);
// initialize or replace a portion of bits with a portion of another chromosome
void setPortion(const Chromosome<T,N...>& x, int start);
// get parameter value(s) from chromosome
const std::vector<T>& getParam() const;
// get objective function result
const std::vector<T>& getResult() const;
// get the total sum of all objective function(s) result
T getTotal() const;
// get constraint value(s)
const std::vector<T> getConstraint() const;
// return chromosome size in number of bits
int size() const;
// return number of chromosome bits to mutate
T mutrate() const;
// return number of genes in chromosome
int nbgene() const;
// return numero of generation this chromosome belongs to
int nogen() const;
// return lower bound(s)
const std::vector<T>& lowerBound() const;
// return upper bound(s)
const std::vector<T>& upperBound() const;
private:
std::vector<T> param; // estimated parameters parameters
std::vector<T> result; // chromosome objective function(s) result
std::string chr; // string of bits representing chromosome
const GeneticAlgorithm<T,N...>* ptr = nullptr; // pointer to genetic algorithm
public:
T fitness; // chromosome fitness, objective function(s) result that can be modified (adapted to constraint(s), set to positive values, etc...)
private:
T total; // total sum of objective function(s) result
int chrsize; // chromosome size (in number of bits)
int numgen; // numero of generation
int idx; // index for chromosome breakdown
};
/*-------------------------------------------------------------------------------------------------*/
// constructor
template <typename T, int...N>
Chromosome<T,N...>::Chromosome(const GeneticAlgorithm<T,N...>& ga)
{
param.resize(sizeof...(N));
ptr = &ga;
chrsize = ga.nbbit;
numgen = ga.nogen;
}
/*-------------------------------------------------------------------------------------------------*/
// copy constructor
template <typename T, int...N>
Chromosome<T,N...>::Chromosome(const Chromosome<T,N...>& rhs)
{
param = rhs.param;
result = rhs.result;
chr = rhs.chr;
ptr = rhs.ptr;
// re-initializing fitness to its original value
fitness = rhs.total;
total = rhs.total;
chrsize = rhs.chrsize;
numgen = rhs.numgen;
}
/*-------------------------------------------------------------------------------------------------*/
// end of recursion for creating new chromosome
template <typename T, int...N> template <int I>
inline typename std::enable_if<I == sizeof...(N), void>::type
Chromosome<T,N...>::create() {}
// recursion for creating new chromosome
template <typename T, int...N> template <int I>
inline typename std::enable_if<I < sizeof...(N), void>::type
Chromosome<T,N...>::create()
{
std::string str = std::get<I>(ptr->tp).encode();
chr.append(str);
create<I + 1>();
}
/*-------------------------------------------------------------------------------------------------*/
// intialize chromosome from a known value
template <typename T, int...N> template <int I>
inline typename std::enable_if<I == sizeof...(N), void>::type
Chromosome<T,N...>::initialize() {}
// recursion for initializing chromosome from a known value
template <typename T, int...N> template <int I>
inline typename std::enable_if<I < sizeof...(N), void>::type
Chromosome<T,N...>::initialize()
{
std::string str = std::get<I>(ptr->tp).encode(ptr->initialSet[I]);
chr.append(str);
initialize<I + 1>();
}
/*-------------------------------------------------------------------------------------------------*/
// end of recursion for converting gene to real value
template <typename T, int...N> template <int I>
inline typename std::enable_if<I == sizeof...(N), void>::type
Chromosome<T,N...>::convert() {}
// recursion for converting gene to real value
template <typename T, int...N> template <int I>
inline typename std::enable_if<I < sizeof...(N), void>::type
Chromosome<T,N...>::convert()
{
const auto& par = std::get<I>(ptr->tp);
param[I] = par.decode(chr.substr(idx, par.size()));
idx += par.size();
convert<I + 1>();
}
/*-------------------------------------------------------------------------------------------------*/
// evaluate chromosome fitness
template <typename T, int...N>
inline void Chromosome<T,N...>::evaluate() {
// setting index for chromosome breakdown to 0
idx = 0;
// converting chromosome to value(s)
convert();
// computing objective result(s)
result = ptr->Objective(param);
// computing sum of all results (in case there is not only one objective functions)
total = std::accumulate(result.begin(), result.end(), 0.0);
// initializing fitness to this total
fitness = total;
}
/*-------------------------------------------------------------------------------------------------*/
// reset chromosome
template <typename T, int...N>
inline void Chromosome<T,N...>::reset()
{
chr.clear();
result = 0.0;
total = 0.0;
fitness = 0.0;
}
/*-------------------------------------------------------------------------------------------------*/
// end of recursion for setting or replace kth gene by a new one
template <typename T, int...N> template <int I>
inline typename std::enable_if<I == sizeof...(N), void>::type
Chromosome<T,N...>::setGene(int k) {}
// recursion for setting or replace kth gene by a new one
template <typename T, int...N> template <int I>
inline typename std::enable_if<I < sizeof...(N), void>::type
Chromosome<T,N...>::setGene(int k)
{
#ifndef NDEBUG
if (k < 0 || k >= ptr->nbparam) {
throw std::invalid_argument("Error: in galgo::Chromosome<T>::setGene(int), argument cannot be outside interval [0,nbparam-1], please amend.");
}
#endif
// setting index for chromosome breakdown to 0
if (I == 0) idx = 0;
// getting Ith parameter in tuple
const auto& par = std::get<I>(ptr->tp);
// if gene found
if (I == k) {
// generating a new gene
std::string s = par.encode();
// adding or replacing gene in chromosome
chr.replace(idx, par.size(), s, 0, par.size());
// ending recursion
setGene<sizeof...(N)>(k);
} else {
idx += par.size();
setGene<I + 1>(k);
}
}
/*-------------------------------------------------------------------------------------------------*/
// end of recursion for initializing or replacing kth gene by a know value
template <typename T, int...N> template <int I>
inline typename std::enable_if<I == sizeof...(N), void>::type
Chromosome<T,N...>::initGene(int k, T x) {}
// recursion for initializing or replacing kth gene by a know value
template <typename T, int...N> template <int I>
inline typename std::enable_if<I < sizeof...(N), void>::type
Chromosome<T,N...>::initGene(int k, T x)
{
#ifndef NDEBUG
if (k < 0 || k >= ptr->nbparam) {
throw std::invalid_argument("Error: in galgo::Chromosome<T>::initGene(int), first argument cannot be outside interval [0,nbparam-1], please amend.");
}
#endif
// setting index for chromosome breakdown to 0
if (I == 0) idx = 0;
// getting Ith parameter in tuple
const auto& par = std::get<I>(ptr->tp);
// if gene found
if (I == k) {
// generating a new gene
std::string s = par.encode(x);
// adding or replacing gene in chromosome
chr.replace(idx, par.size(), s, 0, par.size());
// ending recursion
initGene<sizeof...(N)>(k, x);
} else {
idx += par.size();
initGene<I + 1>(k, x);
}
}
/*-------------------------------------------------------------------------------------------------*/
// add chromosome bit to chromosome (when constructing a new one)
template <typename T, int...N>
inline void Chromosome<T,N...>::addBit(char bit)
{
chr.push_back(bit);
#ifndef NDEBUG
if (chr.size() > chrsize) {
throw std::invalid_argument("Error: in galgo::Chromosome<T>::setBit(char), exceeding chromosome size.");
}
#endif
}
/*-------------------------------------------------------------------------------------------------*/
// initialize or replace an existing chromosome bit
template <typename T, int...N>
inline void Chromosome<T,N...>::setBit(char bit, int pos)
{
#ifndef NDEBUG
if (pos >= chrsize) {
throw std::invalid_argument("Error: in galgo::Chromosome<T>::replaceBit(char, int), second argument cannot be equal or greater than chromosome size.");
}
#endif
std::stringstream ss;
std::string str;
ss << bit;
ss >> str;
chr.replace(pos, 1, str);
std::cout << chr << "\n";
}
/*-------------------------------------------------------------------------------------------------*/
// flip an existing chromosome bit
template <typename T, int...N>
inline void Chromosome<T,N...>::flipBit(int pos)
{
#ifndef NDEBUG
if (pos >= chrsize) {
throw std::invalid_argument("Error: in galgo::Chromosome<T>::flipBit(int), argument cannot be equal or greater than chromosome size.");
}
#endif
if (chr[pos] == '0') {
chr.replace(pos, 1, "1");
} else {
chr.replace(pos, 1, "0");
}
}
/*-------------------------------------------------------------------------------------------------*/
// get a chromosome bit
template <typename T, int...N>
inline char Chromosome<T,N...>::getBit(int pos) const
{
#ifndef NDEBUG
if (pos >= chrsize) {
throw std::invalid_argument("Error: in galgo::Chromosome<T>::getBit(int), argument cannot be equal or greater than chromosome size.");
}
#endif
return chr[pos];
}
/*-------------------------------------------------------------------------------------------------*/
// initialize or replace a portion of bits with a portion of another chromosome (from position start to position end included)
template <typename T, int...N>
inline void Chromosome<T,N...>::setPortion(const Chromosome<T,N...>& x, int start, int end)
{
#ifndef NDEBUG
if (start > chrsize) {
throw std::invalid_argument("Error: in galgo::Chromosome<T>::setPortion(const Chromosome<T>&, int, int), second argument cannot be greater than chromosome size.");
}
#endif
chr.replace(start, end - start + 1, x.chr, start, end - start + 1);
}
/*-------------------------------------------------------------------------------------------------*/
// initialize or replace a portion of bits with a portion of another chromosome (from position start to the end of he chromosome)
template <typename T, int...N>
inline void Chromosome<T,N...>::setPortion(const Chromosome<T,N...>& x, int start)
{
#ifndef NDEBUG
if (start > chrsize) {
throw std::invalid_argument("Error: in galgo::Chromosome<T>::setPortion(const Chromosome<T>&, int), second argument cannot be greater than chromosome size.");
}
#endif
chr.replace(start, chrsize, x.chr, start, x.chrsize);
}
/*-------------------------------------------------------------------------------------------------*/
// get parameter value(s) from chromosome
template <typename T, int...N>
inline const std::vector<T>& Chromosome<T,N...>::getParam() const
{
return param;
}
/*-------------------------------------------------------------------------------------------------*/
// get objective function result
template <typename T, int...N>
inline const std::vector<T>& Chromosome<T,N...>::getResult() const
{
return result;
}
/*-------------------------------------------------------------------------------------------------*/
// get the total sum of all objective function(s) result
template <typename T, int...N>
inline T Chromosome<T,N...>::getTotal() const
{
return total;
}
/*-------------------------------------------------------------------------------------------------*/
// get constraint value(s) for this chromosome
template <typename T, int...N>
inline const std::vector<T> Chromosome<T,N...>::getConstraint() const
{
return ptr->Constraint(param);
}
/*-------------------------------------------------------------------------------------------------*/
// return chromosome size in number of bits
template <typename T, int...N>
inline int Chromosome<T,N...>::size() const
{
return chrsize;
}
/*-------------------------------------------------------------------------------------------------*/
// return mutation rate
template <typename T, int...N>
inline T Chromosome<T,N...>::mutrate() const
{
return ptr->mutrate;
}
/*-------------------------------------------------------------------------------------------------*/
// return number of genes in chromosome
template <typename T, int...N>
inline int Chromosome<T,N...>::nbgene() const
{
return ptr->nbparam;
}
/*-------------------------------------------------------------------------------------------------*/
// return numero of generation this chromosome belongs to
template <typename T, int...N>
inline int Chromosome<T,N...>::nogen() const
{
return numgen;
}
/*-------------------------------------------------------------------------------------------------*/
// return lower bound(s)
template <typename T, int...N>
inline const std::vector<T>& Chromosome<T,N...>::lowerBound() const
{
return ptr->lowerBound;
}
/*-------------------------------------------------------------------------------------------------*/
// return upper bound(s)
template <typename T, int...N>
inline const std::vector<T>& Chromosome<T,N...>::upperBound() const
{
return ptr->upperBound;
}
//=================================================================================================
}
#endif
Delete Chromosome.hpp
|
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <iostream>
#include <memory>
#include <utility>
#include <map>
#include <functional>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <chrono>
#include <sstream>
#include <sg14/fixed_point>
using sg14::fixed_point;
#include <EASTL/vector.h>
#include <EASTL/array.h>
#include <NativeBitmap.h>
#include <ETextures.h>
#include <unordered_map>
using eastl::vector;
using eastl::array;
using namespace std::chrono;
#include "IFileLoaderDelegate.h"
#include "NativeBitmap.h"
#include "Vec2i.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CItem.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "IRenderer.h"
#include "RasterizerCommon.h"
#include "CRenderer.h"
#include "LoadPNG.h"
namespace odb {
const static bool kShouldDrawOutline = false;
vector<std::shared_ptr<odb::NativeBitmap>> loadBitmapList(std::string filename, std::shared_ptr<Knights::IFileLoaderDelegate> fileLoader ) {
auto data = fileLoader->loadFileFromPath( filename );
std::stringstream dataStream;
dataStream << data;
std::string buffer;
vector<std::shared_ptr<odb::NativeBitmap>> toReturn;
while (dataStream.good()) {
std::getline(dataStream, buffer);
toReturn.push_back(loadPNG(buffer, fileLoader));
}
return toReturn;
}
odb::CTilePropertyMap loadTileProperties( int levelNumber, std::shared_ptr<Knights::IFileLoaderDelegate> fileLoader ) {
std::stringstream roomName("");
roomName << "tiles";
roomName << levelNumber;
roomName << ".prp";
std::string filename = roomName.str();
auto data = fileLoader->loadFileFromPath( filename );
return odb::CTile3DProperties::parsePropertyList( data );
}
vector<vector<std::shared_ptr<odb::NativeBitmap>>>
loadTexturesForLevel(int levelNumber, std::shared_ptr<Knights::IFileLoaderDelegate> fileLoader) {
std::stringstream roomName("");
roomName << "tiles";
roomName << levelNumber;
roomName << ".lst";
std::string tilesFilename = roomName.str();
auto data = fileLoader->loadFileFromPath( tilesFilename );
std::stringstream dataStream;
dataStream << data;
std::string buffer;
vector<vector<std::shared_ptr<odb::NativeBitmap>>> tilesToLoad;
while (dataStream.good()) {
std::getline(dataStream, buffer);
vector<std::shared_ptr<odb::NativeBitmap>> textures;
if (buffer.substr(buffer.length() - 4) == ".lst") {
auto frames = loadBitmapList(buffer, fileLoader );
for ( const auto frame : frames ) {
textures.push_back(frame);
}
} else {
textures.push_back(loadPNG(buffer, fileLoader));
}
tilesToLoad.push_back(textures);
}
return tilesToLoad;
}
void CRenderer::drawMap(Knights::CMap &map, std::shared_ptr<Knights::CActor> current) {
auto mapCamera = current->getPosition();
// mCamera = Vec3{ mapCamera.x, 0, mapCamera.y};
for ( int z = 0; z < 40; ++z ) {
for ( int x = 0; x < 40; ++x ) {
mElementsMap[z][x] = map.getElementAt({ x, z });
}
}
if (!mCached ) {
mCached = true;
mNeedsToRedraw = true;
}
}
Knights::CommandType CRenderer::getInput() {
auto toReturn = mBufferedCommand;
mBufferedCommand = '.';
return toReturn;
}
Vec2 CRenderer::project(const Vec3& p ) {
FixP halfWidth{160};
FixP halfHeight{100};
FixP oneOver = divide( halfHeight, p.mZ );
return {
halfWidth + multiply(p.mX, oneOver),
halfHeight - multiply(p.mY, oneOver)
};
}
void CRenderer::projectAllVertices() {
FixP halfWidth{160};
FixP halfHeight{100};
FixP two{2};
for ( auto& vertex : mVertices ) {
if (vertex.first.mZ == 0 ) {
continue;
}
FixP oneOver = divide( halfHeight, divide(vertex.first.mZ, two) );
vertex.second.mX = halfWidth + multiply(vertex.first.mX, oneOver);
vertex.second.mY = halfHeight - multiply(vertex.first.mY, oneOver);
}
}
void CRenderer::drawCubeAt(const Vec3& center, std::shared_ptr<odb::NativeBitmap> texture) {
if (static_cast<int>(center.mZ) <= 2 ) {
return;
}
FixP one{ 1 };
mVertices[ 0 ].first = ( center + Vec3{ -one, -one, -one });
mVertices[ 1 ].first = ( center + Vec3{ one, -one, -one });
mVertices[ 2 ].first = ( center + Vec3{ -one, one, -one });
mVertices[ 3 ].first = ( center + Vec3{ one, one, -one });
mVertices[ 4 ].first = ( center + Vec3{ -one, -one, one });
mVertices[ 5 ].first = ( center + Vec3{ one, -one, one });
mVertices[ 6 ].first = ( center + Vec3{ -one, one, one });
mVertices[ 7 ].first = ( center + Vec3{ one, one, one });
projectAllVertices();
auto ulz0 = mVertices[0].second;
auto urz0 = mVertices[1].second;
auto llz0 = mVertices[2].second;
auto lrz0 = mVertices[3].second;
auto ulz1 = mVertices[4].second;
auto urz1 = mVertices[5].second;
auto llz1 = mVertices[6].second;
auto lrz1 = mVertices[7].second;
if (static_cast<int>(center.mX) <= 0 ) {
drawWall( urz0.mX, urz1.mX,
urz0.mY, lrz0.mY,
urz1.mY, lrz1.mY,
texture);
}
if (static_cast<int>(center.mY) >= 0 ) {
drawFloor(ulz1.mY, urz0.mY,
ulz1.mX, urz1.mX,
ulz0.mX, urz0.mX,
texture);
}
if (static_cast<int>(center.mY) <= 0 ) {
drawFloor(llz1.mY, lrz0.mY,
llz1.mX, lrz1.mX,
llz0.mX, lrz0.mX,
texture);
}
if (static_cast<int>(center.mX) >= 0 ) {
drawWall(ulz1.mX, ulz0.mX,
ulz1.mY, llz1.mY,
urz0.mY, lrz0.mY,
texture);
}
drawWall( ulz0.mX, urz0.mX,
ulz0.mY, llz0.mY,
urz0.mY, lrz0.mY,
texture );
}
void CRenderer::drawColumnAt(const Vec3 ¢er, const Vec3 &scale, std::shared_ptr<odb::NativeBitmap> texture) {
if (static_cast<int>(center.mZ) <= 2 ) {
return;
}
FixP one{ 1 };
FixP two{ 2 };
auto halfScale = divide(scale.mY, two);
mVertices[ 0 ].first = ( center + Vec3{ -one, halfScale + scale.mY, -one });
mVertices[ 1 ].first = ( center + Vec3{ one, halfScale + scale.mY, -one });
mVertices[ 2 ].first = ( center + Vec3{ -one, -halfScale, -one });
mVertices[ 3 ].first = ( center + Vec3{ one, -halfScale, -one });
mVertices[ 4 ].first = ( center + Vec3{ -one, halfScale + scale.mY, one });
mVertices[ 5 ].first = ( center + Vec3{ one, halfScale + scale.mY, one });
mVertices[ 6 ].first = ( center + Vec3{ -one, -halfScale, one });
mVertices[ 7 ].first = ( center + Vec3{ one, -halfScale, one });
projectAllVertices();
auto ulz0 = mVertices[0].second;
auto urz0 = mVertices[1].second;
auto llz0 = mVertices[2].second;
auto lrz0 = mVertices[3].second;
auto ulz1 = mVertices[4].second;
auto urz1 = mVertices[5].second;
auto llz1 = mVertices[6].second;
auto lrz1 = mVertices[7].second;
if (static_cast<int>(center.mX) <= 0 ) {
drawWall( urz0.mX, urz1.mX,
urz0.mY, lrz0.mY,
urz1.mY, lrz1.mY,
texture);
}
if (static_cast<int>(center.mX) >= 0 ) {
drawWall(ulz1.mX, ulz0.mX,
ulz1.mY, llz1.mY,
urz0.mY, lrz0.mY,
texture);
}
drawWall( ulz0.mX, urz0.mX,
ulz0.mY, llz0.mY,
urz0.mY, lrz0.mY,
texture );
}
void CRenderer::drawFloorAt(const Vec3& center, std::shared_ptr<odb::NativeBitmap> texture) {
if (static_cast<int>(center.mZ) <= 2 ) {
return;
}
FixP one{ 1 };
mVertices[ 0 ].first = ( center + Vec3{ -one, one, -one });
mVertices[ 1 ].first = ( center + Vec3{ one, one, -one });
mVertices[ 2 ].first = ( center + Vec3{ -one, one, one });
mVertices[ 3 ].first = ( center + Vec3{ one, one, one });
projectAllVertices();
auto llz0 = mVertices[0].second;
auto lrz0 = mVertices[1].second;
auto llz1 = mVertices[2].second;
auto lrz1 = mVertices[3].second;
drawFloor(llz1.mY, lrz0.mY,
llz1.mX, lrz1.mX,
llz0.mX, lrz0.mX,
texture);
}
void CRenderer::drawCeilingAt(const Vec3& center, std::shared_ptr<odb::NativeBitmap> texture) {
if (static_cast<int>(center.mZ) <= 2 ) {
return;
}
FixP one{ 1 };
mVertices[ 0 ].first = ( center + Vec3{ -one, one, -one });
mVertices[ 1 ].first = ( center + Vec3{ one, one, -one });
mVertices[ 2 ].first = ( center + Vec3{ -one, one, one });
mVertices[ 3 ].first = ( center + Vec3{ one, one, one });
projectAllVertices();
auto llz0 = mVertices[0].second;
auto lrz0 = mVertices[1].second;
auto llz1 = mVertices[2].second;
auto lrz1 = mVertices[3].second;
drawFloor(llz1.mY, lrz0.mY,
llz1.mX, lrz1.mX,
llz0.mX, lrz0.mX,
texture);
}
void CRenderer::drawLeftNear(const Vec3& center, const Vec3 &scale, std::shared_ptr<odb::NativeBitmap> texture) {
if (static_cast<int>(center.mZ) <= 2 ) {
return;
}
FixP one{ 1 };
FixP two{ 2 };
auto halfScale = divide( scale.mY, two );
mVertices[ 0 ].first = ( center + Vec3{ -one, halfScale + scale.mY, -one });
mVertices[ 1 ].first = ( center + Vec3{ one, halfScale + scale.mY, one });
mVertices[ 2 ].first = ( center + Vec3{ -one, -halfScale, -one });
mVertices[ 3 ].first = ( center + Vec3{ one, -halfScale, one });
projectAllVertices();
auto ulz0 = mVertices[0].second;
auto urz0 = mVertices[1].second;
auto llz0 = mVertices[2].second;
auto lrz0 = mVertices[3].second;
drawWall( ulz0.mX, urz0.mX,
ulz0.mY, llz0.mY,
urz0.mY, lrz0.mY,
texture );
}
void CRenderer:: drawRightNear(const Vec3& center, const Vec3 &scale, std::shared_ptr<odb::NativeBitmap> texture) {
if (static_cast<int>(center.mZ) <= 2 ) {
return;
}
FixP one{ 1 };
FixP two{ 2 };
auto halfScale = divide( scale.mY, two );
mVertices[ 0 ].first = ( center + Vec3{ -one, halfScale + scale.mY, one });
mVertices[ 1 ].first = ( center + Vec3{ one, halfScale + scale.mY, -one });
mVertices[ 2 ].first = ( center + Vec3{ -one, -halfScale, one });
mVertices[ 3 ].first = ( center + Vec3{ one, -halfScale, -one });
projectAllVertices();
auto ulz0 = mVertices[0].second;
auto urz0 = mVertices[1].second;
auto llz0 = mVertices[2].second;
auto lrz0 = mVertices[3].second;
drawWall( ulz0.mX, urz0.mX,
ulz0.mY, llz0.mY,
urz0.mY, lrz0.mY,
texture );
}
/*
* /|x1y0
* x0y0 / |
* | |
* | |
* x0y1 | |
* \ |
* \ |
* \| x1y1
*/
void CRenderer::drawWall( FixP x0, FixP x1, FixP x0y0, FixP x0y1, FixP x1y0, FixP x1y1, std::shared_ptr<odb::NativeBitmap> texture ) {
if ( x0 > x1) {
//switch x0 with x1
x0 = x0 + x1;
x1 = x0 - x1;
x0 = x0 - x1;
//switch x0y0 with x1y0
x0y0 = x0y0 + x1y0;
x1y0 = x0y0 - x1y0;
x0y0 = x0y0 - x1y0;
//switch x0y1 with x1y1
x0y1 = x0y1 + x1y1;
x1y1 = x0y1 - x1y1;
x0y1 = x0y1 - x1y1;
}
auto x = static_cast<int16_t >(x0);
auto limit = static_cast<int16_t >(x1);
if ( x == limit ) {
return;
}
FixP upperY0 = x0y0;
FixP lowerY0 = x0y1;
FixP upperY1 = x1y0;
FixP lowerY1 = x1y1;
if ( x0y0 > x0y1 ) {
upperY0 = x0y1;
lowerY0 = x0y0;
upperY1 = x1y1;
lowerY1 = x1y0;
};
FixP upperDy = upperY1 - upperY0;
FixP lowerDy = lowerY1 - lowerY0;
FixP y0 = upperY0;
FixP y1 = lowerY0;
FixP dX{limit - x};
FixP upperDyDx = upperDy / dX;
FixP lowerDyDx = lowerDy / dX;
uint32_t pixel = 0;
FixP u{0};
//0xFF here acts as a dirty value, indicating there is no last value. But even if we had
//textures this big, it would be only at the end of the run.
uint8_t lastU = 0xFF;
uint8_t lastV = 0xFF;
//we can use this statically, since the textures are already loaded.
//we don't need to fetch that data on every run.
int* data = texture->getPixelData();
int8_t textureWidth = texture->getWidth();
FixP textureSize{ textureWidth };
FixP du = textureSize / (dX);
auto ix = x;
for (; ix < limit; ++ix ) {
auto diffY = ( y1 - y0 );
if ( diffY == 0 ) {
continue;
}
FixP dv = textureSize / diffY;
FixP v{0};
auto iu = static_cast<uint8_t >(u);
auto iY0 = static_cast<int16_t >(y0);
auto iY1 = static_cast<int16_t >(y1);
for ( auto iy = iY0; iy < iY1; ++iy ) {
auto iv = static_cast<uint8_t >(v);
if ( iv != lastV || iu != lastU ) {
pixel = data[ (iv * textureWidth ) + iu];
}
lastU = iu;
lastV = iv;
if ( pixel & 0xFF000000 ) {
putRaw( ix, iy, pixel);
}
v += dv;
}
y0 += upperDyDx;
y1 += lowerDyDx;
u += du;
}
}
/*
* x0y0 ____________ x1y0
* / \
* / \
* x0y1 /______________\ x1y1
*/
void CRenderer::drawFloor(FixP y0, FixP y1, FixP x0y0, FixP x1y0, FixP x0y1, FixP x1y1, std::shared_ptr<odb::NativeBitmap> texture ) {
//if we have a trapezoid in which the base is smaller
if ( y0 > y1) {
//switch y0 with y1
y0 = y0 + y1;
y1 = y0 - y1;
y0 = y0 - y1;
//switch x0y0 with x0y1
x0y0 = x0y0 + x0y1;
x0y1 = x0y0 - x0y1;
x0y0 = x0y0 - x0y1;
//switch x1y0 with x1y1
x1y0 = x1y0 + x1y1;
x1y1 = x1y0 - x1y1;
x1y0 = x1y0 - x1y1;
}
auto y = static_cast<int16_t >(y0);
auto limit = static_cast<int16_t >(y1);
if ( y == limit ) {
return;
}
FixP upperX0 = x0y0;
FixP upperX1 = x1y0;
FixP lowerX0 = x0y1;
FixP lowerX1 = x1y1;
//what if the trapezoid is flipped horizontally?
if ( x0y0 > x1y0 ) {
upperX0 = x1y0;
upperX1 = x0y0;
lowerX0 = x1y1;
lowerX1 = x0y1;
};
FixP leftDX = lowerX0 - upperX0;
FixP rightDX = lowerX1 - upperX1;
FixP dY = y1 - y0;
FixP leftDxDy = leftDX / dY;
FixP rightDxDy = rightDX / dY;
FixP x0 = upperX0;
FixP x1 = upperX1;
uint32_t pixel = 0 ;
FixP v{0};
//0xFF here acts as a dirty value, indicating there is no last value. But even if we had
//textures this big, it would be only at the end of the run.
uint8_t lastU = 0xFF;
uint8_t lastV = 0xFF;
auto iy = static_cast<int16_t >(y);
int* data = texture->getPixelData();
int8_t textureWidth = texture->getWidth();
FixP textureSize{ textureWidth };
FixP dv = textureSize / (dY);
for (; iy < limit; ++iy ) {
auto diffX = ( x1 - x0 );
if ( diffX == 0 ) {
continue;
}
auto iX0 = static_cast<int16_t >(x0);
auto iX1 = static_cast<int16_t >(x1);
FixP du = textureSize / diffX;
FixP u{0};
auto iv = static_cast<uint8_t >(v);
for ( auto ix = iX0; ix < iX1; ++ix ) {
auto iu = static_cast<uint8_t >(u);
//only fetch the next texel if we really changed the u, v coordinates
//(otherwise, would fetch the same thing anyway)
if ( iv != lastV || iu != lastU ) {
pixel = data[ (iv * textureWidth ) + iu];
}
lastU = iu;
lastV = iv;
if ( pixel & 0xFF000000 ) {
putRaw( ix, iy, pixel);
}
u += du;
}
x0 += leftDxDy;
x1 += rightDxDy;
v += dv;
}
}
void CRenderer::drawLine(const Vec2& p0, const Vec2& p1) {
drawLine(static_cast<int16_t >(p0.mX),
static_cast<int16_t >(p0.mY),
static_cast<int16_t >(p1.mX),
static_cast<int16_t >(p1.mY)
);
}
void CRenderer::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1) {
if ( x0 == x1 ) {
int16_t _y0 = y0;
int16_t _y1 = y1;
if ( y0 > y1 ) {
_y0 = y1;
_y1 = y0;
}
for ( int y = _y0; y <= _y1; ++y ) {
putRaw( x0, y, 0xFFFFFFFF);
}
return;
}
if ( y0 == y1 ) {
int16_t _x0 = x0;
int16_t _x1 = x1;
if ( x0 > x1 ) {
_x0 = x1;
_x1 = x0;
}
for ( int x = _x0; x <= _x1; ++x ) {
putRaw( x, y0, 0xFFFFFFFF);
}
return;
}
//switching x0 with x1
if( x0 > x1 ) {
x0 = x0 + x1;
x1 = x0 - x1;
x0 = x0 - x1;
y0 = y0 + y1;
y1 = y0 - y1;
y0 = y0 - y1;
}
FixP fy = FixP{ y0 };
FixP fLimitY = FixP{ y1 };
FixP fDeltatY = FixP{ y1 - y0 } / FixP{ x1 - x0 };
for ( int x = x0; x <= x1; ++x ) {
putRaw( x, static_cast<int16_t >(fy), 0xFFFFFFFF);
fy += fDeltatY;
}
}
void CRenderer::render(long ms) {
const static FixP two{2};
if ( mSpeed.mX ) {
mSpeed.mX /= two;
mNeedsToRedraw = true;
}
if ( mSpeed.mY ) {
mSpeed.mY /= two;
mNeedsToRedraw = true;
}
if ( mSpeed.mZ ) {
mSpeed.mZ /= two;
mNeedsToRedraw = true;
}
mCamera += mSpeed;
if ( mNeedsToRedraw ) {
mNeedsToRedraw = false;
if ( clearScr ) {
clear();
}
for (int z = 0; z <40; ++z ) {
for ( int x = 0; x < 40; ++x ) {
auto element = mElementsMap[z][40 - x];
auto tileProp = mTileProperties[element];
auto heightDiff = tileProp.mCeilingHeight - tileProp.mFloorHeight;
auto halfHeightDiff = divide( heightDiff, two );
Vec3 position = mCamera + Vec3{ FixP{- 2 * x}, FixP{ -2 }, FixP{2 * (40 - z)}};
if ( tileProp.mFloorRepeatedTextureIndex > 0 ) {
drawColumnAt(position + Vec3{ 0, tileProp.mFloorHeight - divide(heightDiff, two), 0}, {1, FixP{tileProp.mFloorRepetitions}, 1}, mTextures[ tileProp.mFloorRepeatedTextureIndex ][ 0 ] );
}
if ( tileProp.mCeilingRepeatedTextureIndex > 0 ) {
drawColumnAt(position + Vec3{ 0, tileProp.mCeilingHeight + divide(heightDiff, two), 0}, {1, FixP{tileProp.mCeilingRepetitions}, 1}, mTextures[ tileProp.mCeilingRepeatedTextureIndex ][ 0 ] );
}
if ( tileProp.mFloorTextureIndex != -1 ) {
drawFloorAt( position + Vec3{ 0, tileProp.mFloorHeight, 0}, mTextures[ tileProp.mFloorTextureIndex ][ 0 ] );
}
if ( tileProp.mCeilingTextureIndex != -1 ) {
drawCeilingAt(position + Vec3{ 0, tileProp.mCeilingHeight, 0}, mTextures[ tileProp.mCeilingTextureIndex ][ 0 ] );
}
if ( tileProp.mMainWallTextureIndex > 0 ) {
auto scale = tileProp.mCeilingHeight - tileProp.mFloorHeight;
switch (tileProp.mGeometryType ) {
case kRightNearWall:
drawRightNear(position + Vec3{ 0, halfHeightDiff, 0}, {1, heightDiff, 1}, mTextures[ tileProp.mMainWallTextureIndex ][ 0 ] );
break;
case kLeftNearWall:
drawLeftNear(position + Vec3{ 0, halfHeightDiff, 0}, {1, heightDiff, 1}, mTextures[ tileProp.mMainWallTextureIndex ][ 0 ] );
break;
case kCube:
default:
drawColumnAt(position + Vec3{ 0, halfHeightDiff, 0}, {1, heightDiff, 1}, mTextures[ tileProp.mMainWallTextureIndex ][ 0 ] );
break;
}
}
}
}
}
flip();
}
void CRenderer::loadTextures(vector<vector<std::shared_ptr<odb::NativeBitmap>>> textureList, CTilePropertyMap &tile3DProperties) {
mTextures = textureList;
mTileProperties = tile3DProperties;
std::unordered_map<std::string, TextureIndex > textureRegistry;
textureRegistry["null"] = -1;
textureRegistry["sky"] = ETextures::Skybox;
textureRegistry["grass"] = ETextures::Grass;
textureRegistry["lava"] = ETextures::Lava;
textureRegistry["floor"] = ETextures::Floor;
textureRegistry["bricks"] = ETextures::Bricks;
textureRegistry["arch"] = ETextures::Arch;
textureRegistry["bars"] = ETextures::Bars;
textureRegistry["begin"] = ETextures::Begin;
textureRegistry["exit"] = ETextures::Exit;
textureRegistry["bricksblood"] = ETextures::BricksBlood;
textureRegistry["brickscandles"] = ETextures::BricksCandles;
textureRegistry["stonegrassfar"] = ETextures::StoneGrassFar;
textureRegistry["grassstonefar"] = ETextures::GrassStoneFar;
textureRegistry["stonegrassnear"] = ETextures::StoneGrassNear;
textureRegistry["grassstonenear"] = ETextures::GrassStoneNear;
textureRegistry["ceiling"] = ETextures::Ceiling;
textureRegistry["ceilingdoor"] = ETextures::CeilingDoor;
textureRegistry["ceilingbegin"] = ETextures::CeilingBegin;
textureRegistry["ceilingend"] = ETextures::CeilingEnd;
textureRegistry["ceilingbars"] = ETextures::CeilingBars;
textureRegistry["rope"] = ETextures::Rope;
textureRegistry["slot"] = ETextures::Slot;
textureRegistry["magicseal"] = ETextures::MagicSeal;
textureRegistry["shutdoor"] = ETextures::ShutDoor;
textureRegistry["cobblestone"] = ETextures::Cobblestone;
textureRegistry["fence"] = ETextures::Fence;
for ( auto& propMap : mTileProperties ) {
auto tileProp = propMap.second;
tileProp.mCeilingTextureIndex = (textureRegistry[tileProp.mCeilingTexture]);
tileProp.mFloorTextureIndex = (textureRegistry[tileProp.mFloorTexture]);
tileProp.mCeilingRepeatedTextureIndex = (textureRegistry[tileProp.mCeilingRepeatedWallTexture]);
tileProp.mFloorRepeatedTextureIndex = (textureRegistry[tileProp.mFloorRepeatedWallTexture]);
tileProp.mMainWallTextureIndex = (textureRegistry[tileProp.mMainWallTexture]);
propMap.second = tileProp;
}
}
}
Better organize the viewport rendering
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <iostream>
#include <memory>
#include <utility>
#include <map>
#include <functional>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <chrono>
#include <sstream>
#include <sg14/fixed_point>
using sg14::fixed_point;
#include <EASTL/vector.h>
#include <EASTL/array.h>
#include <NativeBitmap.h>
#include <ETextures.h>
#include <unordered_map>
using eastl::vector;
using eastl::array;
using namespace std::chrono;
#include "IFileLoaderDelegate.h"
#include "NativeBitmap.h"
#include "Vec2i.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CItem.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "IRenderer.h"
#include "RasterizerCommon.h"
#include "CRenderer.h"
#include "LoadPNG.h"
namespace odb {
const static bool kShouldDrawOutline = false;
const static bool kShouldDrawTextures = true;
vector<std::shared_ptr<odb::NativeBitmap>> loadBitmapList(std::string filename, std::shared_ptr<Knights::IFileLoaderDelegate> fileLoader ) {
auto data = fileLoader->loadFileFromPath( filename );
std::stringstream dataStream;
dataStream << data;
std::string buffer;
vector<std::shared_ptr<odb::NativeBitmap>> toReturn;
while (dataStream.good()) {
std::getline(dataStream, buffer);
toReturn.push_back(loadPNG(buffer, fileLoader));
}
return toReturn;
}
odb::CTilePropertyMap loadTileProperties( int levelNumber, std::shared_ptr<Knights::IFileLoaderDelegate> fileLoader ) {
std::stringstream roomName("");
roomName << "tiles";
roomName << levelNumber;
roomName << ".prp";
std::string filename = roomName.str();
auto data = fileLoader->loadFileFromPath( filename );
return odb::CTile3DProperties::parsePropertyList( data );
}
vector<vector<std::shared_ptr<odb::NativeBitmap>>>
loadTexturesForLevel(int levelNumber, std::shared_ptr<Knights::IFileLoaderDelegate> fileLoader) {
std::stringstream roomName("");
roomName << "tiles";
roomName << levelNumber;
roomName << ".lst";
std::string tilesFilename = roomName.str();
auto data = fileLoader->loadFileFromPath( tilesFilename );
std::stringstream dataStream;
dataStream << data;
std::string buffer;
vector<vector<std::shared_ptr<odb::NativeBitmap>>> tilesToLoad;
while (dataStream.good()) {
std::getline(dataStream, buffer);
vector<std::shared_ptr<odb::NativeBitmap>> textures;
if (buffer.substr(buffer.length() - 4) == ".lst") {
auto frames = loadBitmapList(buffer, fileLoader );
for ( const auto frame : frames ) {
textures.push_back(frame);
}
} else {
textures.push_back(loadPNG(buffer, fileLoader));
}
tilesToLoad.push_back(textures);
}
return tilesToLoad;
}
void CRenderer::drawMap(Knights::CMap &map, std::shared_ptr<Knights::CActor> current) {
auto mapCamera = current->getPosition();
// mCamera = Vec3{ mapCamera.x, 0, mapCamera.y};
for ( int z = 0; z < 40; ++z ) {
for ( int x = 0; x < 40; ++x ) {
mElementsMap[z][x] = map.getElementAt({ x, z });
}
}
if (!mCached ) {
mCached = true;
mNeedsToRedraw = true;
}
}
Knights::CommandType CRenderer::getInput() {
auto toReturn = mBufferedCommand;
mBufferedCommand = '.';
return toReturn;
}
Vec2 CRenderer::project(const Vec3& p ) {
FixP halfWidth{128};
FixP halfHeight{64};
FixP oneOver = divide( halfHeight, p.mZ );
return {
halfWidth + multiply(p.mX, oneOver),
halfHeight - multiply(p.mY, oneOver)
};
}
void CRenderer::projectAllVertices() {
FixP halfWidth{128};
FixP halfHeight{64};
FixP two{2};
for ( auto& vertex : mVertices ) {
if (vertex.first.mZ == 0 ) {
continue;
}
FixP oneOver = divide( halfHeight, divide(vertex.first.mZ, two) );
vertex.second.mX = halfWidth + multiply(vertex.first.mX, oneOver);
vertex.second.mY = halfHeight - multiply(vertex.first.mY, oneOver);
}
}
void CRenderer::drawCubeAt(const Vec3& center, std::shared_ptr<odb::NativeBitmap> texture) {
if (static_cast<int>(center.mZ) <= 2 ) {
return;
}
FixP one{ 1 };
mVertices[ 0 ].first = ( center + Vec3{ -one, -one, -one });
mVertices[ 1 ].first = ( center + Vec3{ one, -one, -one });
mVertices[ 2 ].first = ( center + Vec3{ -one, one, -one });
mVertices[ 3 ].first = ( center + Vec3{ one, one, -one });
mVertices[ 4 ].first = ( center + Vec3{ -one, -one, one });
mVertices[ 5 ].first = ( center + Vec3{ one, -one, one });
mVertices[ 6 ].first = ( center + Vec3{ -one, one, one });
mVertices[ 7 ].first = ( center + Vec3{ one, one, one });
projectAllVertices();
auto ulz0 = mVertices[0].second;
auto urz0 = mVertices[1].second;
auto llz0 = mVertices[2].second;
auto lrz0 = mVertices[3].second;
auto ulz1 = mVertices[4].second;
auto urz1 = mVertices[5].second;
auto llz1 = mVertices[6].second;
auto lrz1 = mVertices[7].second;
if (static_cast<int>(center.mX) <= 0 ) {
drawWall( urz0.mX, urz1.mX,
urz0.mY, lrz0.mY,
urz1.mY, lrz1.mY,
texture);
}
if (static_cast<int>(center.mY) >= 0 ) {
drawFloor(ulz1.mY, urz0.mY,
ulz1.mX, urz1.mX,
ulz0.mX, urz0.mX,
texture);
}
if (static_cast<int>(center.mY) <= 0 ) {
drawFloor(llz1.mY, lrz0.mY,
llz1.mX, lrz1.mX,
llz0.mX, lrz0.mX,
texture);
}
if (static_cast<int>(center.mX) >= 0 ) {
drawWall(ulz1.mX, ulz0.mX,
ulz1.mY, llz1.mY,
urz0.mY, lrz0.mY,
texture);
}
drawWall( ulz0.mX, urz0.mX,
ulz0.mY, llz0.mY,
urz0.mY, lrz0.mY,
texture );
}
void CRenderer::drawColumnAt(const Vec3 ¢er, const Vec3 &scale, std::shared_ptr<odb::NativeBitmap> texture) {
if (static_cast<int>(center.mZ) <= 2 ) {
return;
}
FixP one{ 1 };
FixP two{ 2 };
auto halfScale = divide(scale.mY, two);
mVertices[ 0 ].first = ( center + Vec3{ -one, halfScale + scale.mY, -one });
mVertices[ 1 ].first = ( center + Vec3{ one, halfScale + scale.mY, -one });
mVertices[ 2 ].first = ( center + Vec3{ -one, -halfScale, -one });
mVertices[ 3 ].first = ( center + Vec3{ one, -halfScale, -one });
mVertices[ 4 ].first = ( center + Vec3{ -one, halfScale + scale.mY, one });
mVertices[ 5 ].first = ( center + Vec3{ one, halfScale + scale.mY, one });
mVertices[ 6 ].first = ( center + Vec3{ -one, -halfScale, one });
mVertices[ 7 ].first = ( center + Vec3{ one, -halfScale, one });
projectAllVertices();
auto ulz0 = mVertices[0].second;
auto urz0 = mVertices[1].second;
auto llz0 = mVertices[2].second;
auto lrz0 = mVertices[3].second;
auto ulz1 = mVertices[4].second;
auto urz1 = mVertices[5].second;
auto llz1 = mVertices[6].second;
auto lrz1 = mVertices[7].second;
if (kShouldDrawTextures) {
if (static_cast<int>(center.mX) <= 0 ) {
drawWall( urz0.mX, urz1.mX,
urz0.mY, lrz0.mY,
urz1.mY, lrz1.mY,
texture);
}
if (static_cast<int>(center.mX) >= 0 ) {
drawWall(ulz1.mX, ulz0.mX,
ulz1.mY, llz1.mY,
urz0.mY, lrz0.mY,
texture);
}
drawWall( ulz0.mX, urz0.mX,
ulz0.mY, llz0.mY,
urz0.mY, lrz0.mY,
texture );
}
if (kShouldDrawOutline) {
drawLine( ulz0, urz0 );
drawLine( ulz0, llz0 );
drawLine( urz0, lrz0 );
drawLine( llz0, lrz0 );
drawLine( ulz0, ulz1 );
drawLine( llz0, llz1 );
drawLine( ulz1, llz1 );
drawLine( urz0, urz1 );
drawLine( lrz0, lrz1 );
drawLine( urz1, lrz1 );
}
}
void CRenderer::drawFloorAt(const Vec3& center, std::shared_ptr<odb::NativeBitmap> texture) {
if (static_cast<int>(center.mZ) <= 2 ) {
return;
}
FixP one{ 1 };
mVertices[ 0 ].first = ( center + Vec3{ -one, one, -one });
mVertices[ 1 ].first = ( center + Vec3{ one, one, -one });
mVertices[ 2 ].first = ( center + Vec3{ -one, one, one });
mVertices[ 3 ].first = ( center + Vec3{ one, one, one });
projectAllVertices();
auto llz0 = mVertices[0].second;
auto lrz0 = mVertices[1].second;
auto llz1 = mVertices[2].second;
auto lrz1 = mVertices[3].second;
if ( kShouldDrawTextures ) {
drawFloor(llz1.mY, lrz0.mY,
llz1.mX, lrz1.mX,
llz0.mX, lrz0.mX,
texture);
}
if ( kShouldDrawOutline) {
drawLine( llz0, lrz0 );
drawLine( llz0, llz1 );
drawLine( lrz0, lrz1 );
drawLine( llz1, lrz1 );
}
}
void CRenderer::drawCeilingAt(const Vec3& center, std::shared_ptr<odb::NativeBitmap> texture) {
if (static_cast<int>(center.mZ) <= 2 ) {
return;
}
FixP one{ 1 };
mVertices[ 0 ].first = ( center + Vec3{ -one, one, -one });
mVertices[ 1 ].first = ( center + Vec3{ one, one, -one });
mVertices[ 2 ].first = ( center + Vec3{ -one, one, one });
mVertices[ 3 ].first = ( center + Vec3{ one, one, one });
projectAllVertices();
auto llz0 = mVertices[0].second;
auto lrz0 = mVertices[1].second;
auto llz1 = mVertices[2].second;
auto lrz1 = mVertices[3].second;
if (kShouldDrawTextures){
drawFloor(llz1.mY, lrz0.mY,
llz1.mX, lrz1.mX,
llz0.mX, lrz0.mX,
texture);
}
if (kShouldDrawOutline) {
drawLine( llz0, lrz0 );
drawLine( llz0, llz1 );
drawLine( lrz0, lrz1 );
drawLine( llz1, lrz1 );
}
}
void CRenderer::drawLeftNear(const Vec3& center, const Vec3 &scale, std::shared_ptr<odb::NativeBitmap> texture) {
if (static_cast<int>(center.mZ) <= 2 ) {
return;
}
FixP one{ 1 };
FixP two{ 2 };
auto halfScale = divide( scale.mY, two );
mVertices[ 0 ].first = ( center + Vec3{ -one, halfScale + scale.mY, -one });
mVertices[ 1 ].first = ( center + Vec3{ one, halfScale + scale.mY, one });
mVertices[ 2 ].first = ( center + Vec3{ -one, -halfScale, -one });
mVertices[ 3 ].first = ( center + Vec3{ one, -halfScale, one });
projectAllVertices();
auto ulz0 = mVertices[0].second;
auto urz0 = mVertices[1].second;
auto llz0 = mVertices[2].second;
auto lrz0 = mVertices[3].second;
if (kShouldDrawTextures) {
drawWall( ulz0.mX, urz0.mX,
ulz0.mY, llz0.mY,
urz0.mY, lrz0.mY,
texture );
}
if (kShouldDrawOutline){
drawLine( ulz0, urz0 );
drawLine( llz0, ulz0 );
drawLine( llz0, lrz0 );
drawLine( urz0, lrz0 );
}
}
void CRenderer::drawRightNear(const Vec3& center, const Vec3 &scale, std::shared_ptr<odb::NativeBitmap> texture) {
if (static_cast<int>(center.mZ) <= 2 ) {
return;
}
FixP one{ 1 };
FixP two{ 2 };
auto halfScale = divide( scale.mY, two );
mVertices[ 0 ].first = ( center + Vec3{ -one, halfScale + scale.mY, one });
mVertices[ 1 ].first = ( center + Vec3{ one, halfScale + scale.mY, -one });
mVertices[ 2 ].first = ( center + Vec3{ -one, -halfScale, one });
mVertices[ 3 ].first = ( center + Vec3{ one, -halfScale, -one });
projectAllVertices();
auto ulz0 = mVertices[0].second;
auto urz0 = mVertices[1].second;
auto llz0 = mVertices[2].second;
auto lrz0 = mVertices[3].second;
if (kShouldDrawTextures) {
drawWall( ulz0.mX, urz0.mX,
ulz0.mY, llz0.mY,
urz0.mY, lrz0.mY,
texture );
}
if (kShouldDrawOutline) {
drawLine( ulz0, urz0 );
drawLine( llz0, ulz0 );
drawLine( llz0, lrz0 );
drawLine( urz0, lrz0 );
}
}
/*
* /|x1y0
* x0y0 / |
* | |
* | |
* x0y1 | |
* \ |
* \ |
* \| x1y1
*/
void CRenderer::drawWall( FixP x0, FixP x1, FixP x0y0, FixP x0y1, FixP x1y0, FixP x1y1, std::shared_ptr<odb::NativeBitmap> texture ) {
if ( x0 > x1) {
//switch x0 with x1
x0 = x0 + x1;
x1 = x0 - x1;
x0 = x0 - x1;
//switch x0y0 with x1y0
x0y0 = x0y0 + x1y0;
x1y0 = x0y0 - x1y0;
x0y0 = x0y0 - x1y0;
//switch x0y1 with x1y1
x0y1 = x0y1 + x1y1;
x1y1 = x0y1 - x1y1;
x0y1 = x0y1 - x1y1;
}
auto x = static_cast<int16_t >(x0);
auto limit = static_cast<int16_t >(x1);
if ( x == limit ) {
return;
}
FixP upperY0 = x0y0;
FixP lowerY0 = x0y1;
FixP upperY1 = x1y0;
FixP lowerY1 = x1y1;
if ( x0y0 > x0y1 ) {
upperY0 = x0y1;
lowerY0 = x0y0;
upperY1 = x1y1;
lowerY1 = x1y0;
};
FixP upperDy = upperY1 - upperY0;
FixP lowerDy = lowerY1 - lowerY0;
FixP y0 = upperY0;
FixP y1 = lowerY0;
FixP dX{limit - x};
FixP upperDyDx = upperDy / dX;
FixP lowerDyDx = lowerDy / dX;
uint32_t pixel = 0;
FixP u{0};
//0xFF here acts as a dirty value, indicating there is no last value. But even if we had
//textures this big, it would be only at the end of the run.
uint8_t lastU = 0xFF;
uint8_t lastV = 0xFF;
//we can use this statically, since the textures are already loaded.
//we don't need to fetch that data on every run.
int* data = texture->getPixelData();
int8_t textureWidth = texture->getWidth();
FixP textureSize{ textureWidth };
FixP du = textureSize / (dX);
auto ix = x;
for (; ix < limit; ++ix ) {
auto diffY = ( y1 - y0 );
if ( diffY == 0 ) {
continue;
}
FixP dv = textureSize / diffY;
FixP v{0};
auto iu = static_cast<uint8_t >(u);
auto iY0 = static_cast<int16_t >(y0);
auto iY1 = static_cast<int16_t >(y1);
for ( auto iy = iY0; iy < iY1; ++iy ) {
if ( iy < 128 && ix < 256 ) {
auto iv = static_cast<uint8_t >(v);
if ( iv != lastV || iu != lastU ) {
pixel = data[ (iv * textureWidth ) + iu];
}
lastU = iu;
lastV = iv;
if ( pixel & 0xFF000000 ) {
putRaw( ix, iy, pixel);
}
v += dv;
}
y0 += upperDyDx;
y1 += lowerDyDx;
u += du;
}
}
/*
* x0y0 ____________ x1y0
* / \
* / \
* x0y1 /______________\ x1y1
*/
void CRenderer::drawFloor(FixP y0, FixP y1, FixP x0y0, FixP x1y0, FixP x0y1, FixP x1y1, std::shared_ptr<odb::NativeBitmap> texture ) {
//if we have a trapezoid in which the base is smaller
if ( y0 > y1) {
//switch y0 with y1
y0 = y0 + y1;
y1 = y0 - y1;
y0 = y0 - y1;
//switch x0y0 with x0y1
x0y0 = x0y0 + x0y1;
x0y1 = x0y0 - x0y1;
x0y0 = x0y0 - x0y1;
//switch x1y0 with x1y1
x1y0 = x1y0 + x1y1;
x1y1 = x1y0 - x1y1;
x1y0 = x1y0 - x1y1;
}
auto y = static_cast<int16_t >(y0);
auto limit = static_cast<int16_t >(y1);
if ( y == limit ) {
return;
}
FixP upperX0 = x0y0;
FixP upperX1 = x1y0;
FixP lowerX0 = x0y1;
FixP lowerX1 = x1y1;
//what if the trapezoid is flipped horizontally?
if ( x0y0 > x1y0 ) {
upperX0 = x1y0;
upperX1 = x0y0;
lowerX0 = x1y1;
lowerX1 = x0y1;
};
FixP leftDX = lowerX0 - upperX0;
FixP rightDX = lowerX1 - upperX1;
FixP dY = y1 - y0;
FixP leftDxDy = leftDX / dY;
FixP rightDxDy = rightDX / dY;
FixP x0 = upperX0;
FixP x1 = upperX1;
uint32_t pixel = 0 ;
FixP v{0};
//0xFF here acts as a dirty value, indicating there is no last value. But even if we had
//textures this big, it would be only at the end of the run.
uint8_t lastU = 0xFF;
uint8_t lastV = 0xFF;
auto iy = static_cast<int16_t >(y);
int* data = texture->getPixelData();
int8_t textureWidth = texture->getWidth();
FixP textureSize{ textureWidth };
FixP dv = textureSize / (dY);
for (; iy < limit; ++iy ) {
auto diffX = ( x1 - x0 );
if ( diffX == 0 ) {
continue;
}
auto iX0 = static_cast<int16_t >(x0);
auto iX1 = static_cast<int16_t >(x1);
FixP du = textureSize / diffX;
FixP u{0};
auto iv = static_cast<uint8_t >(v);
for ( auto ix = iX0; ix < iX1; ++ix ) {
if ( iy < 128 && ix < 256 ) {
auto iu = static_cast<uint8_t >(u);
//only fetch the next texel if we really changed the u, v coordinates
//(otherwise, would fetch the same thing anyway)
if ( iv != lastV || iu != lastU ) {
pixel = data[ (iv * textureWidth ) + iu];
}
lastU = iu;
lastV = iv;
if ( pixel & 0xFF000000 ) {
putRaw( ix, iy, pixel);
}
u += du;
}
x0 += leftDxDy;
x1 += rightDxDy;
v += dv;
}
}
void CRenderer::drawLine(const Vec2& p0, const Vec2& p1) {
drawLine(static_cast<int16_t >(p0.mX),
static_cast<int16_t >(p0.mY),
static_cast<int16_t >(p1.mX),
static_cast<int16_t >(p1.mY)
);
}
void CRenderer::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1) {
if ( x0 == x1 ) {
int16_t _y0 = y0;
int16_t _y1 = y1;
if ( y0 > y1 ) {
_y0 = y1;
_y1 = y0;
}
for ( int y = _y0; y <= _y1; ++y ) {
putRaw( x0, y, 0xFFFFFFFF);
}
return;
}
if ( y0 == y1 ) {
int16_t _x0 = x0;
int16_t _x1 = x1;
if ( x0 > x1 ) {
_x0 = x1;
_x1 = x0;
}
for ( int x = _x0; x <= _x1; ++x ) {
putRaw( x, y0, 0xFFFFFFFF);
}
return;
}
//switching x0 with x1
if( x0 > x1 ) {
x0 = x0 + x1;
x1 = x0 - x1;
x0 = x0 - x1;
y0 = y0 + y1;
y1 = y0 - y1;
y0 = y0 - y1;
}
FixP fy = FixP{ y0 };
FixP fLimitY = FixP{ y1 };
FixP fDeltatY = FixP{ y1 - y0 } / FixP{ x1 - x0 };
for ( int x = x0; x <= x1; ++x ) {
putRaw( x, static_cast<int16_t >(fy), 0xFFFFFFFF);
fy += fDeltatY;
}
}
void CRenderer::render(long ms) {
const static FixP two{2};
if ( mSpeed.mX ) {
mSpeed.mX /= two;
mNeedsToRedraw = true;
}
if ( mSpeed.mY ) {
mSpeed.mY /= two;
mNeedsToRedraw = true;
}
if ( mSpeed.mZ ) {
mSpeed.mZ /= two;
mNeedsToRedraw = true;
}
mCamera += mSpeed;
if ( mNeedsToRedraw ) {
mNeedsToRedraw = false;
if ( clearScr ) {
clear();
}
for (int z = 0; z <40; ++z ) {
for ( int x = 0; x < 40; ++x ) {
auto element = mElementsMap[z][40 - x];
auto tileProp = mTileProperties[element];
auto heightDiff = tileProp.mCeilingHeight - tileProp.mFloorHeight;
auto halfHeightDiff = divide( heightDiff, two );
Vec3 position = mCamera + Vec3{ FixP{- 2 * x}, FixP{ -2 }, FixP{2 * (40 - z)}};
if ( tileProp.mFloorRepeatedTextureIndex > 0 ) {
drawColumnAt(position + Vec3{ 0, tileProp.mFloorHeight - divide(heightDiff, two), 0}, {1, FixP{tileProp.mFloorRepetitions}, 1}, mTextures[ tileProp.mFloorRepeatedTextureIndex ][ 0 ] );
}
if ( tileProp.mCeilingRepeatedTextureIndex > 0 ) {
drawColumnAt(position + Vec3{ 0, tileProp.mCeilingHeight + divide(heightDiff, two), 0}, {1, FixP{tileProp.mCeilingRepetitions}, 1}, mTextures[ tileProp.mCeilingRepeatedTextureIndex ][ 0 ] );
}
if ( tileProp.mFloorTextureIndex != -1 ) {
drawFloorAt( position + Vec3{ 0, tileProp.mFloorHeight, 0}, mTextures[ tileProp.mFloorTextureIndex ][ 0 ] );
}
if ( tileProp.mCeilingTextureIndex != -1 ) {
drawCeilingAt(position + Vec3{ 0, tileProp.mCeilingHeight, 0}, mTextures[ tileProp.mCeilingTextureIndex ][ 0 ] );
}
if ( tileProp.mMainWallTextureIndex > 0 ) {
auto scale = tileProp.mCeilingHeight - tileProp.mFloorHeight;
switch (tileProp.mGeometryType ) {
case kRightNearWall:
drawRightNear(position + Vec3{ 0, halfHeightDiff, 0}, {1, heightDiff, 1}, mTextures[ tileProp.mMainWallTextureIndex ][ 0 ] );
break;
case kLeftNearWall:
drawLeftNear(position + Vec3{ 0, halfHeightDiff, 0}, {1, heightDiff, 1}, mTextures[ tileProp.mMainWallTextureIndex ][ 0 ] );
break;
case kCube:
default:
drawColumnAt(position + Vec3{ 0, halfHeightDiff, 0}, {1, heightDiff, 1}, mTextures[ tileProp.mMainWallTextureIndex ][ 0 ] );
break;
}
}
}
}
}
flip();
}
void CRenderer::loadTextures(vector<vector<std::shared_ptr<odb::NativeBitmap>>> textureList, CTilePropertyMap &tile3DProperties) {
mTextures = textureList;
mTileProperties = tile3DProperties;
std::unordered_map<std::string, TextureIndex > textureRegistry;
textureRegistry["null"] = -1;
textureRegistry["sky"] = ETextures::Skybox;
textureRegistry["grass"] = ETextures::Grass;
textureRegistry["lava"] = ETextures::Lava;
textureRegistry["floor"] = ETextures::Floor;
textureRegistry["bricks"] = ETextures::Bricks;
textureRegistry["arch"] = ETextures::Arch;
textureRegistry["bars"] = ETextures::Bars;
textureRegistry["begin"] = ETextures::Begin;
textureRegistry["exit"] = ETextures::Exit;
textureRegistry["bricksblood"] = ETextures::BricksBlood;
textureRegistry["brickscandles"] = ETextures::BricksCandles;
textureRegistry["stonegrassfar"] = ETextures::StoneGrassFar;
textureRegistry["grassstonefar"] = ETextures::GrassStoneFar;
textureRegistry["stonegrassnear"] = ETextures::StoneGrassNear;
textureRegistry["grassstonenear"] = ETextures::GrassStoneNear;
textureRegistry["ceiling"] = ETextures::Ceiling;
textureRegistry["ceilingdoor"] = ETextures::CeilingDoor;
textureRegistry["ceilingbegin"] = ETextures::CeilingBegin;
textureRegistry["ceilingend"] = ETextures::CeilingEnd;
textureRegistry["ceilingbars"] = ETextures::CeilingBars;
textureRegistry["rope"] = ETextures::Rope;
textureRegistry["slot"] = ETextures::Slot;
textureRegistry["magicseal"] = ETextures::MagicSeal;
textureRegistry["shutdoor"] = ETextures::ShutDoor;
textureRegistry["cobblestone"] = ETextures::Cobblestone;
textureRegistry["fence"] = ETextures::Fence;
for ( auto& propMap : mTileProperties ) {
auto tileProp = propMap.second;
tileProp.mCeilingTextureIndex = (textureRegistry[tileProp.mCeilingTexture]);
tileProp.mFloorTextureIndex = (textureRegistry[tileProp.mFloorTexture]);
tileProp.mCeilingRepeatedTextureIndex = (textureRegistry[tileProp.mCeilingRepeatedWallTexture]);
tileProp.mFloorRepeatedTextureIndex = (textureRegistry[tileProp.mFloorRepeatedWallTexture]);
tileProp.mMainWallTextureIndex = (textureRegistry[tileProp.mMainWallTexture]);
propMap.second = tileProp;
}
}
}
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <TGeoBBox.h>
#include "AliEMCALGeometry.h"
#include "AliEveEMCALSModuleData.h"
class TClonesArray;
class TGeoNode;
class TGeoMatrix;
class TVector2;
class AliEveEventManager;
ClassImp(AliEveEMCALSModuleData)
Float_t AliEveEMCALSModuleData::fgSModuleBigBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleBigBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleBigBox2 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallBox2 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleDCalBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleDCalBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleDCalBox2 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox2 = 0.;
//Float_t AliEveEMCALSModuleData::fgSModuleCenter0 = 0.;
//Float_t AliEveEMCALSModuleData::fgSModuleCenter1 = 0.;
//Float_t AliEveEMCALSModuleData::fgSModuleCenter2 = 0.;
//
// Constructor
//
//______________________________________________________________________________
AliEveEMCALSModuleData::AliEveEMCALSModuleData(Int_t sm,AliEMCALGeometry* geom, TGeoNode* node, TGeoHMatrix* m) :
TObject(),
fGeom(geom),
fNode(node),
fSmId(sm),
fNsm(0),
fNDigits(0),
fNClusters(0),
fNHits(0),
fPhiTileSize(0), fEtaTileSize(0),
fHitArray(0),
fDigitArray(0),
fClusterArray(0),
fMatrix(0),
fHMatrix(m)
{
Init(sm);
}
///
/// Copy constructor
///
//______________________________________________________________________________
AliEveEMCALSModuleData::AliEveEMCALSModuleData(const AliEveEMCALSModuleData &esmdata) :
TObject(),
fGeom(esmdata.fGeom),
fNode(esmdata.fNode),
fSmId(esmdata.fSmId),
fNsm(esmdata.fNsm),
fNDigits(esmdata.fNDigits),
fNClusters(esmdata.fNClusters),
fNHits(esmdata.fNHits),
fPhiTileSize(esmdata.fPhiTileSize), fEtaTileSize(esmdata.fEtaTileSize),
fHitArray(esmdata.fHitArray),
fDigitArray(esmdata.fDigitArray),
fClusterArray(esmdata.fClusterArray),
fMatrix(esmdata.fMatrix),
fHMatrix(esmdata.fHMatrix)
{
Init(esmdata.fNsm);
}
///
/// Destructor
///
//______________________________________________________________________________
AliEveEMCALSModuleData::~AliEveEMCALSModuleData()
{
if(!fHitArray.empty())
fHitArray.clear();
if(!fDigitArray.empty())
fDigitArray.clear();
if(!fClusterArray.empty())
fClusterArray.clear();
}
///
/// Release the SM data
///
//______________________________________________________________________________
void AliEveEMCALSModuleData::DropData()
{
fNDigits = 0;
fNClusters = 0;
fNHits = 0;
if(!fHitArray.empty())
fHitArray.clear();
if(!fDigitArray.empty())
fDigitArray.clear();
if(!fClusterArray.empty())
fClusterArray.clear();
return;
}
///
/// Initialize parameters
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::Init(Int_t sm)
{
fNsm = fGeom->GetNumberOfSuperModules();
fPhiTileSize = fGeom->GetPhiTileSize();
fEtaTileSize = fGeom->GetPhiTileSize();
TGeoBBox* bbbox = (TGeoBBox*) fNode->GetDaughter(0) ->GetVolume()->GetShape();
TGeoBBox* sbbox = (TGeoBBox*) fNode->GetDaughter(10)->GetVolume()->GetShape();
TGeoBBox* dbbox = (TGeoBBox*) fNode->GetDaughter(12)->GetVolume()->GetShape();
TGeoBBox* dsbbox = (TGeoBBox*) fNode->GetDaughter(18)->GetVolume()->GetShape();
fMatrix = (TGeoMatrix*) fNode->GetDaughter(sm)->GetMatrix();
if(sm < 10)
{
fgSModuleBigBox0 = bbbox->GetDX();
fgSModuleBigBox1 = bbbox->GetDY();
fgSModuleBigBox2 = bbbox->GetDZ();
}
else if(sm < 12)
{
fgSModuleSmallBox0 = sbbox->GetDX();
fgSModuleSmallBox1 = sbbox->GetDY();
fgSModuleSmallBox2 = sbbox->GetDZ();
}
else if(sm < 18)
{
fgSModuleDCalBox0 = dbbox->GetDX();
fgSModuleDCalBox1 = dbbox->GetDY();
fgSModuleDCalBox2 = dbbox->GetDZ();
}
else if(sm < 20)
{
fgSModuleSmallDBox0 = dsbbox->GetDX();
fgSModuleSmallDBox1 = dsbbox->GetDY();
fgSModuleSmallDBox2 = dsbbox->GetDZ();
}
}
///
/// Add a digit to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterDigit(Int_t AbsId, Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
std::vector<Double_t> bufDig(6);
bufDig[0] = AbsId;
bufDig[1] = isupMod;
bufDig[2] = iamp;
bufDig[3] = ix;
bufDig[4] = iy;
bufDig[5] = iz;
fDigitArray.push_back(bufDig);
fNDigits++;
}
///
/// Add a hit to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterHit(Int_t AbsId, Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
std::vector<Float_t> bufHit(6);
bufHit[0] = AbsId;
bufHit[1] = isupMod;
bufHit[2] = iamp;
bufHit[3] = ix;
bufHit[4] = iy;
bufHit[5] = iz;
fHitArray.push_back(bufHit);
fNHits++;
}
///
/// Add a cluster to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterCluster(Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
std::vector<Double_t> bufClu(5);
bufClu[0] = isupMod;
bufClu[1] = iamp;
bufClu[2] = ix;
bufClu[3] = iy;
bufClu[4] = iz;
fClusterArray.push_back(bufClu);
fNClusters++;
}
forgot ClassImp doxy condition
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <TGeoBBox.h>
#include "AliEMCALGeometry.h"
#include "AliEveEMCALSModuleData.h"
class TClonesArray;
class TGeoNode;
class TGeoMatrix;
class TVector2;
class AliEveEventManager;
/// \cond CLASSIMP
ClassImp(AliEveEMCALSModuleData) ;
/// \endcond
Float_t AliEveEMCALSModuleData::fgSModuleBigBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleBigBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleBigBox2 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallBox2 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleDCalBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleDCalBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleDCalBox2 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox2 = 0.;
//Float_t AliEveEMCALSModuleData::fgSModuleCenter0 = 0.;
//Float_t AliEveEMCALSModuleData::fgSModuleCenter1 = 0.;
//Float_t AliEveEMCALSModuleData::fgSModuleCenter2 = 0.;
//
// Constructor
//
//______________________________________________________________________________
AliEveEMCALSModuleData::AliEveEMCALSModuleData(Int_t sm,AliEMCALGeometry* geom, TGeoNode* node, TGeoHMatrix* m) :
TObject(),
fGeom(geom),
fNode(node),
fSmId(sm),
fNsm(0),
fNDigits(0),
fNClusters(0),
fNHits(0),
fPhiTileSize(0), fEtaTileSize(0),
fHitArray(0),
fDigitArray(0),
fClusterArray(0),
fMatrix(0),
fHMatrix(m)
{
Init(sm);
}
///
/// Copy constructor
///
//______________________________________________________________________________
AliEveEMCALSModuleData::AliEveEMCALSModuleData(const AliEveEMCALSModuleData &esmdata) :
TObject(),
fGeom(esmdata.fGeom),
fNode(esmdata.fNode),
fSmId(esmdata.fSmId),
fNsm(esmdata.fNsm),
fNDigits(esmdata.fNDigits),
fNClusters(esmdata.fNClusters),
fNHits(esmdata.fNHits),
fPhiTileSize(esmdata.fPhiTileSize), fEtaTileSize(esmdata.fEtaTileSize),
fHitArray(esmdata.fHitArray),
fDigitArray(esmdata.fDigitArray),
fClusterArray(esmdata.fClusterArray),
fMatrix(esmdata.fMatrix),
fHMatrix(esmdata.fHMatrix)
{
Init(esmdata.fNsm);
}
///
/// Destructor
///
//______________________________________________________________________________
AliEveEMCALSModuleData::~AliEveEMCALSModuleData()
{
if(!fHitArray.empty())
fHitArray.clear();
if(!fDigitArray.empty())
fDigitArray.clear();
if(!fClusterArray.empty())
fClusterArray.clear();
}
///
/// Release the SM data
///
//______________________________________________________________________________
void AliEveEMCALSModuleData::DropData()
{
fNDigits = 0;
fNClusters = 0;
fNHits = 0;
if(!fHitArray.empty())
fHitArray.clear();
if(!fDigitArray.empty())
fDigitArray.clear();
if(!fClusterArray.empty())
fClusterArray.clear();
return;
}
///
/// Initialize parameters
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::Init(Int_t sm)
{
fNsm = fGeom->GetNumberOfSuperModules();
fPhiTileSize = fGeom->GetPhiTileSize();
fEtaTileSize = fGeom->GetPhiTileSize();
TGeoBBox* bbbox = (TGeoBBox*) fNode->GetDaughter(0) ->GetVolume()->GetShape();
TGeoBBox* sbbox = (TGeoBBox*) fNode->GetDaughter(10)->GetVolume()->GetShape();
TGeoBBox* dbbox = (TGeoBBox*) fNode->GetDaughter(12)->GetVolume()->GetShape();
TGeoBBox* dsbbox = (TGeoBBox*) fNode->GetDaughter(18)->GetVolume()->GetShape();
fMatrix = (TGeoMatrix*) fNode->GetDaughter(sm)->GetMatrix();
if(sm < 10)
{
fgSModuleBigBox0 = bbbox->GetDX();
fgSModuleBigBox1 = bbbox->GetDY();
fgSModuleBigBox2 = bbbox->GetDZ();
}
else if(sm < 12)
{
fgSModuleSmallBox0 = sbbox->GetDX();
fgSModuleSmallBox1 = sbbox->GetDY();
fgSModuleSmallBox2 = sbbox->GetDZ();
}
else if(sm < 18)
{
fgSModuleDCalBox0 = dbbox->GetDX();
fgSModuleDCalBox1 = dbbox->GetDY();
fgSModuleDCalBox2 = dbbox->GetDZ();
}
else if(sm < 20)
{
fgSModuleSmallDBox0 = dsbbox->GetDX();
fgSModuleSmallDBox1 = dsbbox->GetDY();
fgSModuleSmallDBox2 = dsbbox->GetDZ();
}
}
///
/// Add a digit to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterDigit(Int_t AbsId, Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
std::vector<Double_t> bufDig(6);
bufDig[0] = AbsId;
bufDig[1] = isupMod;
bufDig[2] = iamp;
bufDig[3] = ix;
bufDig[4] = iy;
bufDig[5] = iz;
fDigitArray.push_back(bufDig);
fNDigits++;
}
///
/// Add a hit to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterHit(Int_t AbsId, Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
std::vector<Float_t> bufHit(6);
bufHit[0] = AbsId;
bufHit[1] = isupMod;
bufHit[2] = iamp;
bufHit[3] = ix;
bufHit[4] = iy;
bufHit[5] = iz;
fHitArray.push_back(bufHit);
fNHits++;
}
///
/// Add a cluster to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterCluster(Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
std::vector<Double_t> bufClu(5);
bufClu[0] = isupMod;
bufClu[1] = iamp;
bufClu[2] = ix;
bufClu[3] = iy;
bufClu[4] = iz;
fClusterArray.push_back(bufClu);
fNClusters++;
}
|
#if defined(TEMPEST_BUILD_VULKAN)
#include "vcommandbuffer.h"
#include <Tempest/DescriptorSet>
#include <Tempest/Attachment>
#include "vdevice.h"
#include "vcommandpool.h"
#include "vpipeline.h"
#include "vbuffer.h"
#include "vdescriptorarray.h"
#include "vswapchain.h"
#include "vtexture.h"
#include "vframebuffermap.h"
using namespace Tempest;
using namespace Tempest::Detail;
static VkAttachmentLoadOp mkLoadOp(const AccessOp op) {
switch (op) {
case AccessOp::Discard:
return VK_ATTACHMENT_LOAD_OP_DONT_CARE;
case AccessOp::Preserve:
return VK_ATTACHMENT_LOAD_OP_LOAD;
case AccessOp::Clear:
return VK_ATTACHMENT_LOAD_OP_CLEAR;
}
return VK_ATTACHMENT_LOAD_OP_DONT_CARE;
}
static VkAttachmentStoreOp mkStoreOp(const AccessOp op) {
switch (op) {
case AccessOp::Discard:
return VK_ATTACHMENT_STORE_OP_DONT_CARE;
case AccessOp::Preserve:
return VK_ATTACHMENT_STORE_OP_STORE;
case AccessOp::Clear:
return VK_ATTACHMENT_STORE_OP_STORE;
}
return VK_ATTACHMENT_STORE_OP_DONT_CARE;
}
static void toStage(VkPipelineStageFlags2KHR& stage, VkAccessFlagBits2KHR& access, ResourceAccess rs, bool isSrc) {
uint32_t ret = 0;
uint32_t acc = 0;
if((rs&ResourceAccess::TransferSrc)==ResourceAccess::TransferSrc) {
ret |= VK_PIPELINE_STAGE_TRANSFER_BIT;
acc |= VK_ACCESS_TRANSFER_READ_BIT;
}
if((rs&ResourceAccess::TransferDst)==ResourceAccess::TransferDst) {
ret |= VK_PIPELINE_STAGE_TRANSFER_BIT;
acc |= VK_ACCESS_TRANSFER_WRITE_BIT;
}
if((rs&ResourceAccess::Present)==ResourceAccess::Present) {
ret |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
acc |= VK_ACCESS_COLOR_ATTACHMENT_READ_BIT;
}
if((rs&ResourceAccess::Sampler)==ResourceAccess::Sampler) {
ret |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
acc |= VK_ACCESS_SHADER_READ_BIT;
}
if((rs&ResourceAccess::ColorAttach)==ResourceAccess::ColorAttach) {
ret |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
acc |= (VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT);
}
if((rs&ResourceAccess::DepthAttach)==ResourceAccess::DepthAttach) {
ret |= (VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT);
acc |= (VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT);
}
if((rs&ResourceAccess::DepthReadOnly)==ResourceAccess::DepthReadOnly) {
ret |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
acc |= VK_ACCESS_SHADER_READ_BIT;
}
if((rs&ResourceAccess::Index)==ResourceAccess::Index) {
ret |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
acc |= VK_ACCESS_INDEX_READ_BIT;
}
if((rs&ResourceAccess::Vertex)==ResourceAccess::Vertex) {
ret |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
acc |= VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
}
if((rs&ResourceAccess::Vertex)==ResourceAccess::Uniform) {
ret |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
acc |= VK_ACCESS_UNIFORM_READ_BIT;
}
// memory barriers
if((rs&ResourceAccess::UavReadGr)==ResourceAccess::UavReadGr) {
ret |= VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT;
acc |= VK_ACCESS_SHADER_READ_BIT;
}
if((rs&ResourceAccess::UavWriteGr)==ResourceAccess::UavWriteGr) {
ret |= VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT;
acc |= VK_ACCESS_SHADER_WRITE_BIT;
}
if((rs&ResourceAccess::UavReadComp)==ResourceAccess::UavReadComp) {
ret |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
acc |= VK_ACCESS_SHADER_READ_BIT;
}
if((rs&ResourceAccess::UavWriteComp)==ResourceAccess::UavWriteComp) {
ret |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
acc |= VK_ACCESS_SHADER_WRITE_BIT;
}
if(isSrc && ret==0) {
// wait for nothing: asset uploading case
ret = VK_PIPELINE_STAGE_NONE_KHR;
acc = VK_ACCESS_NONE_KHR;
}
stage = VkPipelineStageFlags2KHR(ret);
access = VkAccessFlagBits2KHR(acc);
}
static VkImageLayout toLayout(ResourceAccess rs) {
if(rs==ResourceAccess::None)
return VK_IMAGE_LAYOUT_UNDEFINED;
if((rs&ResourceAccess::TransferSrc)==ResourceAccess::TransferSrc)
return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
if((rs&ResourceAccess::TransferDst)==ResourceAccess::TransferDst)
return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
if((rs&ResourceAccess::Present)==ResourceAccess::Present)
return VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
if((rs&ResourceAccess::Sampler)==ResourceAccess::Sampler)
return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
if((rs&ResourceAccess::ColorAttach)==ResourceAccess::ColorAttach)
return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
if((rs&ResourceAccess::DepthReadOnly)==ResourceAccess::DepthReadOnly)
return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
if((rs&ResourceAccess::DepthAttach)==ResourceAccess::DepthAttach)
return VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL;
return VK_IMAGE_LAYOUT_GENERAL;
}
static VkImage toVkResource(const AbstractGraphicsApi::BarrierDesc& b) {
if(b.texture!=nullptr) {
VTexture& t = *reinterpret_cast<VTexture*>(b.texture);
return t.impl;
}
if(b.buffer!=nullptr) {
VBuffer& buf = *reinterpret_cast<VBuffer*>(b.buffer);
return buf.impl;
}
VSwapchain& s = *reinterpret_cast<VSwapchain*>(b.swapchain);
return s.images[b.swId];
}
VCommandBuffer::VCommandBuffer(VDevice& device, VkCommandPoolCreateFlags flags)
:device(device), pool(device,flags) {
VkCommandBufferAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.commandPool = pool.impl;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = 1;
vkAssert(vkAllocateCommandBuffers(device.device.impl,&allocInfo,&impl));
}
VCommandBuffer::~VCommandBuffer() {
vkFreeCommandBuffers(device.device.impl,pool.impl,1,&impl);
}
void VCommandBuffer::reset() {
vkResetCommandBuffer(impl,VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT);
swapchainSync.reserve(swapchainSync.size());
swapchainSync.clear();
}
void VCommandBuffer::begin() {
begin(0);
}
void VCommandBuffer::begin(VkCommandBufferUsageFlags flg) {
state = Idle;
swapchainSync.reserve(swapchainSync.size());
swapchainSync.clear();
curVbo = VK_NULL_HANDLE;
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = flg;
beginInfo.pInheritanceInfo = nullptr;
vkAssert(vkBeginCommandBuffer(impl,&beginInfo));
}
void VCommandBuffer::end() {
swapchainSync.reserve(swapchainSync.size());
resState.finalize(*this);
vkAssert(vkEndCommandBuffer(impl));
state = NoRecording;
}
bool VCommandBuffer::isRecording() const {
return state!=NoRecording;
}
void VCommandBuffer::beginRendering(const AttachmentDesc* desc, size_t descSize,
uint32_t width, uint32_t height,
const TextureFormat* frm,
AbstractGraphicsApi::Texture** att,
AbstractGraphicsApi::Swapchain** sw, const uint32_t* imgId) {
for(size_t i=0; i<descSize; ++i) {
if(sw[i]!=nullptr)
addDependency(*reinterpret_cast<VSwapchain*>(sw[i]),imgId[i]);
}
resState.joinCompute(PipelineStage::S_Graphics);
resState.setRenderpass(*this,desc,descSize,frm,att,sw,imgId);
if(device.props.hasDynRendering) {
VkRenderingAttachmentInfoKHR colorAtt[MaxFramebufferAttachments] = {};
VkRenderingAttachmentInfoKHR depthAtt = {};
VkRenderingInfoKHR info = {};
info.sType = VK_STRUCTURE_TYPE_RENDERING_INFO_KHR;
info.flags = 0;
info.renderArea.offset = {0, 0};
info.renderArea.extent = {width,height};
info.layerCount = 1;
info.viewMask = 0;
info.colorAttachmentCount = 0;
info.pColorAttachments = colorAtt;
passDyn.sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR;
passDyn.pNext = nullptr;
passDyn.viewMask = info.viewMask;
passDyn.colorAttachmentCount = 0;
passDyn.pColorAttachmentFormats = passDyn.colorFrm;
VkImageView imageView = VK_NULL_HANDLE;
VkFormat imageFormat = VK_FORMAT_UNDEFINED;
for(size_t i = 0; i < descSize; ++i) {
if(sw[i] != nullptr) {
auto& t = *reinterpret_cast<VSwapchain*>(sw[i]);
imageView = t.views[imgId[i]];
imageFormat = t.format();
}
else if (desc[i].attachment != nullptr) {
auto& t = *reinterpret_cast<VTexture*>(att[i]);
imageView = t.imgView;
imageFormat = t.format;
}
else {
auto &t = *reinterpret_cast<VTexture*>(att[i]);
imageView = t.imgView;
imageFormat = t.format;
}
auto& att = isDepthFormat(frm[i]) ? depthAtt : colorAtt[info.colorAttachmentCount];
att.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR;
att.imageView = imageView;
if(isDepthFormat(frm[i])) {
info.pDepthAttachment = &depthAtt;
att.imageLayout = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL;
passDyn.depthAttachmentFormat = imageFormat;
auto& clr = att.clearValue;
clr.depthStencil.depth = desc[i].clear.x;
} else {
passDyn.colorFrm[info.colorAttachmentCount] = imageFormat;
++info.colorAttachmentCount;
att.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
auto& clr = att.clearValue;
clr.color.float32[0] = desc[i].clear.x;
clr.color.float32[1] = desc[i].clear.y;
clr.color.float32[2] = desc[i].clear.z;
clr.color.float32[3] = desc[i].clear.w;
}
att.resolveMode = VK_RESOLVE_MODE_NONE;
att.resolveImageView = VK_NULL_HANDLE;
att.resolveImageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
att.loadOp = mkLoadOp(desc[i].load);
att.storeOp = mkStoreOp(desc[i].store);
}
passDyn.colorAttachmentCount = info.colorAttachmentCount;
device.vkCmdBeginRenderingKHR(impl,&info);
} else {
auto fbo = device.fboMap.find(desc,descSize, att,sw,imgId,width,height);
auto fb = fbo.get();
pass = fbo->pass;
VkClearValue clr[MaxFramebufferAttachments];
for(size_t i=0; i<descSize; ++i) {
if(isDepthFormat(frm[i])) {
clr[i].depthStencil.depth = desc[i].clear.x;
} else {
clr[i].color.float32[0] = desc[i].clear.x;
clr[i].color.float32[1] = desc[i].clear.y;
clr[i].color.float32[2] = desc[i].clear.z;
clr[i].color.float32[3] = desc[i].clear.w;
}
}
VkRenderPassBeginInfo info = {};
info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
info.renderPass = fb->pass->pass;
info.framebuffer = fb->fbo;
info.renderArea.offset = {0, 0};
info.renderArea.extent = {width,height};
info.clearValueCount = uint32_t(descSize);
info.pClearValues = clr;
vkCmdBeginRenderPass(impl, &info, VK_SUBPASS_CONTENTS_INLINE);
}
state = RenderPass;
// setup dynamic state
// https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#pipelines-dynamic-state
setViewport(Rect(0,0,int32_t(width),int32_t(height)));
VkRect2D scissor = {};
scissor.offset = {0, 0};
scissor.extent = {width, height};
vkCmdSetScissor(impl,0,1,&scissor);
}
void VCommandBuffer::endRendering() {
if(device.props.hasDynRendering) {
device.vkCmdEndRenderingKHR(impl);
} else {
vkCmdEndRenderPass(impl);
}
state = Idle;
}
void VCommandBuffer::setPipeline(AbstractGraphicsApi::Pipeline& p) {
VPipeline& px = reinterpret_cast<VPipeline&>(p);
auto& v = device.props.hasDynRendering ? px.instance(passDyn) : px.instance(pass);
vkCmdBindPipeline(impl,VK_PIPELINE_BIND_POINT_GRAPHICS,v.val);
}
void VCommandBuffer::setBytes(AbstractGraphicsApi::Pipeline& p, const void* data, size_t size) {
VPipeline& px=reinterpret_cast<VPipeline&>(p);
assert(size<=px.pushSize);
vkCmdPushConstants(impl, px.pipelineLayout, px.pushStageFlags, 0, uint32_t(size), data);
}
void VCommandBuffer::setUniforms(AbstractGraphicsApi::Pipeline &p, AbstractGraphicsApi::Desc &u) {
VPipeline& px=reinterpret_cast<VPipeline&>(p);
VDescriptorArray& ux=reinterpret_cast<VDescriptorArray&>(u);
curUniforms = &ux;
ux.ssboBarriers(resState,PipelineStage::S_Graphics);
vkCmdBindDescriptorSets(impl,VK_PIPELINE_BIND_POINT_GRAPHICS,
px.pipelineLayout,0,
1,&ux.impl,
0,nullptr);
}
void VCommandBuffer::setComputePipeline(AbstractGraphicsApi::CompPipeline& p) {
state = Compute;
VCompPipeline& px = reinterpret_cast<VCompPipeline&>(p);
vkCmdBindPipeline(impl,VK_PIPELINE_BIND_POINT_COMPUTE,px.impl);
}
void VCommandBuffer::dispatch(size_t x, size_t y, size_t z) {
curUniforms->ssboBarriers(resState,PipelineStage::S_Compute);
resState.flush(*this);
vkCmdDispatch(impl,uint32_t(x),uint32_t(y),uint32_t(z));
}
void VCommandBuffer::setBytes(AbstractGraphicsApi::CompPipeline& p, const void* data, size_t size) {
VCompPipeline& px=reinterpret_cast<VCompPipeline&>(p);
assert(size<=px.pushSize);
vkCmdPushConstants(impl, px.pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, uint32_t(size), data);
}
void VCommandBuffer::setUniforms(AbstractGraphicsApi::CompPipeline& p, AbstractGraphicsApi::Desc& u) {
VCompPipeline& px=reinterpret_cast<VCompPipeline&>(p);
VDescriptorArray& ux=reinterpret_cast<VDescriptorArray&>(u);
curUniforms = &ux;
vkCmdBindDescriptorSets(impl,VK_PIPELINE_BIND_POINT_COMPUTE,
px.pipelineLayout,0,
1,&ux.impl,
0,nullptr);
}
void VCommandBuffer::draw(const AbstractGraphicsApi::Buffer& ivbo, size_t voffset, size_t vsize,
size_t firstInstance, size_t instanceCount) {
const VBuffer& vbo=reinterpret_cast<const VBuffer&>(ivbo);
if(curVbo!=vbo.impl) {
VkBuffer buffers[1] = {vbo.impl};
VkDeviceSize offsets[1] = {0};
vkCmdBindVertexBuffers(impl, 0, 1, buffers, offsets );
curVbo = vbo.impl;
}
vkCmdDraw(impl, uint32_t(vsize), uint32_t(instanceCount), uint32_t(voffset), uint32_t(firstInstance));
}
void VCommandBuffer::drawIndexed(const AbstractGraphicsApi::Buffer& ivbo, size_t voffset,
const AbstractGraphicsApi::Buffer& iibo, Detail::IndexClass cls,
size_t ioffset, size_t isize, size_t firstInstance, size_t instanceCount) {
const VBuffer& vbo = reinterpret_cast<const VBuffer&>(ivbo);
const VBuffer& ibo = reinterpret_cast<const VBuffer&>(iibo);
if(curVbo!=vbo.impl) {
VkBuffer buffers[1] = {vbo.impl};
VkDeviceSize offsets[1] = {0};
vkCmdBindVertexBuffers(impl, 0, 1, buffers, offsets);
curVbo = vbo.impl;
}
vkCmdBindIndexBuffer(impl, ibo.impl, 0, nativeFormat(cls));
vkCmdDrawIndexed (impl, uint32_t(isize), uint32_t(instanceCount), uint32_t(ioffset), int32_t(voffset), uint32_t(firstInstance));
}
void VCommandBuffer::dispatchMesh(size_t firstInstance, size_t instanceCount) {
device.vkCmdDrawMeshTasks(impl, uint32_t(instanceCount), uint32_t(firstInstance));
}
void VCommandBuffer::setViewport(const Tempest::Rect &r) {
VkViewport viewPort = {};
viewPort.x = float(r.x);
viewPort.y = float(r.y);
viewPort.width = float(r.w);
viewPort.height = float(r.h);
viewPort.minDepth = 0;
viewPort.maxDepth = 1;
vkCmdSetViewport(impl,0,1,&viewPort);
}
void VCommandBuffer::setScissor(const Rect& r) {
VkRect2D scissor = {};
scissor.offset = {r.x, r.y};
scissor.extent = {uint32_t(r.w), uint32_t(r.h)};
vkCmdSetScissor(impl,0,1,&scissor);
}
void VCommandBuffer::copy(AbstractGraphicsApi::Buffer& dstBuf, size_t offsetDest, const AbstractGraphicsApi::Buffer &srcBuf, size_t offsetSrc, size_t size) {
auto& src = reinterpret_cast<const VBuffer&>(srcBuf);
auto& dst = reinterpret_cast<VBuffer&>(dstBuf);
VkBufferCopy copyRegion = {};
copyRegion.dstOffset = offsetDest;
copyRegion.srcOffset = offsetSrc;
copyRegion.size = size;
vkCmdCopyBuffer(impl, src.impl, dst.impl, 1, ©Region);
}
void VCommandBuffer::copy(AbstractGraphicsApi::Buffer& dstBuf, size_t offsetDest, const void* src, size_t size) {
auto& dst = reinterpret_cast<VBuffer&>(dstBuf);
auto srcBuf = reinterpret_cast<const uint8_t*>(src);
size_t maxSz = 0x10000;
while(size>maxSz) {
vkCmdUpdateBuffer(impl,dst.impl,offsetDest,maxSz,srcBuf);
offsetDest += maxSz;
srcBuf += maxSz;
size -= maxSz;
}
vkCmdUpdateBuffer(impl,dst.impl,offsetDest,size,srcBuf);
VkBufferMemoryBarrier buf = {};
buf.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
buf.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
buf.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
buf.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
buf.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
buf.buffer = dst.impl;
buf.offset = 0;
buf.size = VK_WHOLE_SIZE;
vkCmdPipelineBarrier(impl, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
0,
0, nullptr,
0, &buf,
0, nullptr);
}
void VCommandBuffer::copy(AbstractGraphicsApi::Texture& dstTex, size_t width, size_t height, size_t mip, const AbstractGraphicsApi::Buffer& srcBuf, size_t offset) {
auto& src = reinterpret_cast<const VBuffer&>(srcBuf);
auto& dst = reinterpret_cast<VTexture&>(dstTex);
VkBufferImageCopy region = {};
region.bufferOffset = offset;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = uint32_t(mip);
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = {0, 0, 0};
region.imageExtent = {
uint32_t(width),
uint32_t(height),
1
};
vkCmdCopyBufferToImage(impl, src.impl, dst.impl, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion);
}
void VCommandBuffer::copyNative(AbstractGraphicsApi::Buffer& dst, size_t offset,
const AbstractGraphicsApi::Texture& src, size_t width, size_t height, size_t mip) {
auto& nSrc = reinterpret_cast<const VTexture&>(src);
auto& nDst = reinterpret_cast<VBuffer&>(dst);
VkBufferImageCopy region={};
region.bufferOffset = offset;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = uint32_t(mip);
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = {0, 0, 0};
region.imageExtent = {
uint32_t(width),
uint32_t(height),
1
};
VkImageLayout layout = nSrc.isStorageImage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
vkCmdCopyImageToBuffer(impl, nSrc.impl, layout, nDst.impl, 1, ®ion);
}
void VCommandBuffer::blit(AbstractGraphicsApi::Texture& srcTex, uint32_t srcW, uint32_t srcH, uint32_t srcMip,
AbstractGraphicsApi::Texture& dstTex, uint32_t dstW, uint32_t dstH, uint32_t dstMip) {
auto& src = reinterpret_cast<VTexture&>(srcTex);
auto& dst = reinterpret_cast<VTexture&>(dstTex);
// Check if image format supports linear blitting
VkFormatProperties formatProperties;
vkGetPhysicalDeviceFormatProperties(device.physicalDevice, src.format, &formatProperties);
VkFilter filter = VK_FILTER_LINEAR;
if(0==(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT)) {
filter = VK_FILTER_NEAREST;
}
VkImageBlit blit = {};
blit.srcOffsets[0] = {0, 0, 0};
blit.srcOffsets[1] = {int32_t(srcW), int32_t(srcH), 1};
blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit.srcSubresource.mipLevel = srcMip;
blit.srcSubresource.baseArrayLayer = 0;
blit.srcSubresource.layerCount = 1;
blit.dstOffsets[0] = {0, 0, 0};
blit.dstOffsets[1] = {int32_t(dstW), int32_t(dstH), 1 };
blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit.dstSubresource.mipLevel = dstMip;
blit.dstSubresource.baseArrayLayer = 0;
blit.dstSubresource.layerCount = 1;
vkCmdBlitImage(impl,
src.impl, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
dst.impl, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1, &blit,
filter);
}
void VCommandBuffer::buildBlas(VkAccelerationStructureKHR dest,
const AbstractGraphicsApi::Buffer& ivbo, size_t vboSz, size_t stride,
const AbstractGraphicsApi::Buffer& iibo, size_t iboSz, size_t ioffset, IndexClass icls,
AbstractGraphicsApi::Buffer& scratch) {
auto& vbo = reinterpret_cast<const VBuffer&>(ivbo);
auto& ibo = reinterpret_cast<const VBuffer&>(iibo);
VkAccelerationStructureGeometryKHR geometry = {};
geometry.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR;
geometry.pNext = nullptr;
geometry.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR;
geometry.geometry.triangles.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR;
geometry.geometry.triangles.vertexFormat = VK_FORMAT_R32G32B32_SFLOAT;
geometry.geometry.triangles.vertexStride = stride;
geometry.geometry.triangles.maxVertex = uint32_t(vboSz);
geometry.geometry.triangles.indexType = nativeFormat(icls);
geometry.geometry.triangles.transformData = VkDeviceOrHostAddressConstKHR{};
geometry.flags = VK_GEOMETRY_OPAQUE_BIT_KHR;
geometry.geometry.triangles.vertexData.deviceAddress = vbo.toDeviceAddress(device);
geometry.geometry.triangles.indexData .deviceAddress = ibo.toDeviceAddress(device) + ioffset*sizeofIndex(icls);
VkAccelerationStructureBuildGeometryInfoKHR buildGeometryInfo = {};
buildGeometryInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR;
buildGeometryInfo.pNext = nullptr;
buildGeometryInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR;
buildGeometryInfo.flags = 0;
buildGeometryInfo.mode = VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR;
buildGeometryInfo.srcAccelerationStructure = VK_NULL_HANDLE;
buildGeometryInfo.dstAccelerationStructure = dest;
buildGeometryInfo.geometryCount = 1;
buildGeometryInfo.pGeometries = &geometry;
buildGeometryInfo.ppGeometries = nullptr;
buildGeometryInfo.scratchData.deviceAddress = reinterpret_cast<const VBuffer&>(scratch).toDeviceAddress(device);
VkAccelerationStructureBuildRangeInfoKHR buildRangeInfo = {};
buildRangeInfo.primitiveCount = uint32_t(iboSz/3);
buildRangeInfo.primitiveOffset = 0;
buildRangeInfo.firstVertex = 0;
buildRangeInfo.transformOffset = 0;
VkAccelerationStructureBuildRangeInfoKHR* pbuildRangeInfo = &buildRangeInfo;
device.vkCmdBuildAccelerationStructures(impl, 1, &buildGeometryInfo, &pbuildRangeInfo);
// make sure BLAS'es are ready
VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
barrier.srcAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_KHR;
barrier.dstAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_KHR;
vkCmdPipelineBarrier(impl,
VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR,
VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR,
0, 1, &barrier, 0, nullptr, 0, nullptr);
}
void VCommandBuffer::buildTlas(VkAccelerationStructureKHR dest,
AbstractGraphicsApi::Buffer& tbo,
const AbstractGraphicsApi::Buffer& instances, uint32_t numInstances,
AbstractGraphicsApi::Buffer& scratch) {
VkAccelerationStructureGeometryInstancesDataKHR geometryInstancesData = {};
geometryInstancesData.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_INSTANCES_DATA_KHR;
geometryInstancesData.pNext = NULL;
geometryInstancesData.arrayOfPointers = VK_FALSE;
geometryInstancesData.data.deviceAddress = reinterpret_cast<const VBuffer&>(instances).toDeviceAddress(device);
VkAccelerationStructureGeometryKHR geometry = {};
geometry.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR;
geometry.pNext = nullptr;
geometry.geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR;
geometry.geometry.instances = geometryInstancesData;
geometry.flags = VK_GEOMETRY_OPAQUE_BIT_KHR;
VkAccelerationStructureBuildGeometryInfoKHR buildGeometryInfo = {};
buildGeometryInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR;
buildGeometryInfo.pNext = nullptr;
buildGeometryInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR;
buildGeometryInfo.flags = VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR | VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR;
buildGeometryInfo.mode = VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR;
buildGeometryInfo.srcAccelerationStructure = VK_NULL_HANDLE;
buildGeometryInfo.dstAccelerationStructure = dest;
buildGeometryInfo.geometryCount = 1;
buildGeometryInfo.pGeometries = &geometry;
buildGeometryInfo.ppGeometries = nullptr;
buildGeometryInfo.scratchData.deviceAddress = reinterpret_cast<const VBuffer&>(scratch).toDeviceAddress(device);
VkAccelerationStructureBuildRangeInfoKHR buildRangeInfo = {};
buildRangeInfo.primitiveCount = numInstances;
buildRangeInfo.primitiveOffset = 0;
buildRangeInfo.firstVertex = 0;
buildRangeInfo.transformOffset = 0;
VkAccelerationStructureBuildRangeInfoKHR* pbuildRangeInfo = &buildRangeInfo;
device.vkCmdBuildAccelerationStructures(impl, 1, &buildGeometryInfo, &pbuildRangeInfo);
// make sure TLAS is ready
VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
barrier.srcAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_KHR;
barrier.dstAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_KHR;
vkCmdPipelineBarrier(impl,
VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR,
VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR,
0, 1, &barrier, 0, nullptr, 0, nullptr);
}
void VCommandBuffer::copy(AbstractGraphicsApi::Buffer& dst, size_t offset,
AbstractGraphicsApi::Texture& src, uint32_t width, uint32_t height, uint32_t mip) {
auto& nDst = reinterpret_cast<VBuffer&>(dst);
auto& nSrc = reinterpret_cast<const VTexture&>(src);
if(!nSrc.isStorageImage)
resState.setLayout(src,ResourceAccess::TransferSrc);
resState.onTranferUsage(nDst.nonUniqId,nSrc.nonUniqId);
resState.flush(*this);
copyNative(dst,offset, src,width,height,mip);
if(!nSrc.isStorageImage)
resState.setLayout(src,ResourceAccess::Sampler);
}
void VCommandBuffer::generateMipmap(AbstractGraphicsApi::Texture& img,
uint32_t texWidth, uint32_t texHeight, uint32_t mipLevels) {
if(mipLevels==1)
return;
auto& image = reinterpret_cast<VTexture&>(img);
// Check if image format supports linear blitting
VkFormatProperties formatProperties;
vkGetPhysicalDeviceFormatProperties(device.physicalDevice, image.format, &formatProperties);
if(!(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT))
throw std::runtime_error("texture image format does not support linear blitting!");
int32_t w = int32_t(texWidth);
int32_t h = int32_t(texHeight);
resState.setLayout(img,ResourceAccess::TransferDst);
resState.flush(*this);
for(uint32_t i=1; i<mipLevels; ++i) {
const int mw = (w==1 ? 1 : w/2);
const int mh = (h==1 ? 1 : h/2);
barrier(img,ResourceAccess::TransferDst, ResourceAccess::TransferSrc,i-1);
blit(img, w, h, i-1,
img, mw,mh, i);
w = mw;
h = mh;
}
barrier(img,ResourceAccess::TransferDst, ResourceAccess::TransferSrc, mipLevels-1);
barrier(img,ResourceAccess::TransferSrc, ResourceAccess::Sampler, uint32_t(-1));
resState.setLayout(img,ResourceAccess::Sampler);
resState.forceLayout(img);
}
void VCommandBuffer::barrier(const AbstractGraphicsApi::BarrierDesc* desc, size_t cnt) {
VkBufferMemoryBarrier2KHR bufBarrier[MaxBarriers] = {};
uint32_t bufCount = 0;
VkImageMemoryBarrier2KHR imgBarrier[MaxBarriers] = {};
uint32_t imgCount = 0;
VkMemoryBarrier2KHR memBarrier = {};
VkDependencyInfoKHR info = {};
info.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO_KHR;
for(size_t i=0; i<cnt; ++i) {
auto& b = desc[i];
if(b.buffer==nullptr && b.texture==nullptr && b.swapchain==nullptr) {
VkPipelineStageFlags2KHR srcStageMask = 0;
VkAccessFlags2KHR srcAccessMask = 0;
VkPipelineStageFlags2KHR dstStageMask = 0;
VkAccessFlags2KHR dstAccessMask = 0;
toStage(srcStageMask, srcAccessMask, b.prev,true);
toStage(dstStageMask, dstAccessMask, b.next,false);
memBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2_KHR;
memBarrier.srcStageMask |= srcStageMask;
memBarrier.srcAccessMask |= srcAccessMask;
memBarrier.dstStageMask |= dstStageMask;
memBarrier.dstAccessMask |= dstAccessMask;
}
else if(b.buffer!=nullptr) {
auto& bx = bufBarrier[bufCount];
++bufCount;
bx.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER_2_KHR;
bx.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
bx.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
bx.buffer = reinterpret_cast<VBuffer&>(*b.buffer).impl;
bx.offset = 0;
bx.size = VK_WHOLE_SIZE;
toStage(bx.srcStageMask, bx.srcAccessMask, b.prev,true);
toStage(bx.dstStageMask, bx.dstAccessMask, b.next,false);
} else {
auto& bx = imgBarrier[imgCount];
++imgCount;
bx.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2_KHR;
bx.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
bx.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
bx.image = toVkResource(b);
toStage(bx.srcStageMask, bx.srcAccessMask, b.prev,true);
toStage(bx.dstStageMask, bx.dstAccessMask, b.next,false);
bx.oldLayout = toLayout(b.prev);
bx.newLayout = toLayout(b.next);
finalizeImageBarrier(bx,b);
}
}
info.pBufferMemoryBarriers = bufBarrier;
info.bufferMemoryBarrierCount = bufCount;
info.pImageMemoryBarriers = imgBarrier;
info.imageMemoryBarrierCount = imgCount;
if(memBarrier.sType==VK_STRUCTURE_TYPE_MEMORY_BARRIER_2_KHR) {
info.pMemoryBarriers = &memBarrier;
info.memoryBarrierCount++;
}
vkCmdPipelineBarrier2(impl,&info);
}
void VCommandBuffer::vkCmdPipelineBarrier2(VkCommandBuffer impl, const VkDependencyInfoKHR* info) {
if(device.vkCmdPipelineBarrier2!=nullptr) {
device.vkCmdPipelineBarrier2(impl,info);
return;
}
VkPipelineStageFlags srcStage = 0;
VkPipelineStageFlags dstStage = 0;
uint32_t memCount = 0;
VkMemoryBarrier memBarrier[MaxBarriers] = {};
uint32_t bufCount = 0;
VkBufferMemoryBarrier bufBarrier[MaxBarriers] = {};
uint32_t imgCount = 0;
VkImageMemoryBarrier imgBarrier[MaxBarriers] = {};
for(size_t i=0; i<info->memoryBarrierCount; ++i) {
auto& b = info->pMemoryBarriers[i];
if(memCount>MaxBarriers || b.srcStageMask!=srcStage || b.dstStageMask!=dstStage) {
if(memCount>0) {
vkCmdPipelineBarrier(impl,srcStage,dstStage,info->dependencyFlags,
memCount,memBarrier,
0,nullptr,
0,nullptr);
}
srcStage = VkPipelineStageFlags(b.srcStageMask);
dstStage = VkPipelineStageFlags(b.dstStageMask);
memCount = 0;
}
auto& bx = memBarrier[memCount];
bx.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
bx.srcAccessMask = VkAccessFlags(b.srcAccessMask);
bx.dstAccessMask = VkAccessFlags(b.dstAccessMask);
++memCount;
}
for(size_t i=0; i<info->bufferMemoryBarrierCount; ++i) {
auto& b = info->pBufferMemoryBarriers[i];
if(bufCount>MaxBarriers || b.srcStageMask!=srcStage || b.dstStageMask!=dstStage) {
if(bufCount>0) {
vkCmdPipelineBarrier(impl,srcStage,dstStage,info->dependencyFlags,
0,nullptr,
bufCount,bufBarrier,
0,nullptr);
}
srcStage = VkPipelineStageFlags(b.srcStageMask);
dstStage = VkPipelineStageFlags(b.dstStageMask);
bufCount = 0;
}
auto& bx = bufBarrier[bufCount];
bx.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
bx.srcAccessMask = VkAccessFlags(b.srcAccessMask);
bx.dstAccessMask = VkAccessFlags(b.dstAccessMask);
bx.srcQueueFamilyIndex = b.srcQueueFamilyIndex;
bx.dstQueueFamilyIndex = b.dstQueueFamilyIndex;
bx.buffer = b.buffer;
bx.offset = b.offset;
bx.size = b.size;
++bufCount;
}
for(size_t i=0; i<info->imageMemoryBarrierCount; ++i) {
auto& b = info->pImageMemoryBarriers[i];
if(imgCount>MaxBarriers || b.srcStageMask!=srcStage || b.dstStageMask!=dstStage) {
if(imgCount>0) {
vkCmdPipelineBarrier(impl,srcStage,dstStage,info->dependencyFlags,
0,nullptr,
0,nullptr,
imgCount,imgBarrier);
}
srcStage = VkPipelineStageFlags(b.srcStageMask);
dstStage = VkPipelineStageFlags(b.dstStageMask);
imgCount = 0;
}
auto& bx = imgBarrier[imgCount];
bx.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
bx.srcAccessMask = VkAccessFlags(b.srcAccessMask);
bx.dstAccessMask = VkAccessFlags(b.dstAccessMask);
bx.oldLayout = b.oldLayout;
bx.newLayout = b.newLayout;
bx.srcQueueFamilyIndex = b.srcQueueFamilyIndex;
bx.dstQueueFamilyIndex = b.dstQueueFamilyIndex;
bx.image = b.image;
bx.subresourceRange = b.subresourceRange;
++imgCount;
}
if(memCount==0 && bufCount==0 && imgCount==0)
return;
vkCmdPipelineBarrier(impl,srcStage,dstStage,info->dependencyFlags,
memCount,memBarrier,
bufCount,bufBarrier,
imgCount,imgBarrier);
}
template<class T>
void VCommandBuffer::finalizeImageBarrier(T& bx, const AbstractGraphicsApi::BarrierDesc& b) {
if(b.prev==ResourceAccess::Present)
bx.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
if(b.next==ResourceAccess::Present)
bx.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkFormat nativeFormat = VK_FORMAT_UNDEFINED;
if(b.texture!=nullptr) {
VTexture& t = *reinterpret_cast<VTexture*> (b.texture);
nativeFormat = t.format;
} else {
VSwapchain& s = *reinterpret_cast<VSwapchain*>(b.swapchain);
nativeFormat = s.format();
}
bx.subresourceRange.baseMipLevel = b.mip==uint32_t(-1) ? 0 : b.mip;
bx.subresourceRange.levelCount = b.mip==uint32_t(-1) ? VK_REMAINING_MIP_LEVELS : 1;
bx.subresourceRange.baseArrayLayer = 0;
bx.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS;
if(nativeFormat==VK_FORMAT_D24_UNORM_S8_UINT || nativeFormat==VK_FORMAT_D16_UNORM_S8_UINT || nativeFormat==VK_FORMAT_D32_SFLOAT_S8_UINT)
bx.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; else
if(Detail::nativeIsDepthFormat(nativeFormat))
bx.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; else
bx.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
if(b.discard)
bx.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
}
void VCommandBuffer::addDependency(VSwapchain& s, size_t imgId) {
VSwapchain::Sync* sc = nullptr;
for(auto& i:s.sync)
if(i.imgId==imgId) {
sc = &i;
break;
}
for(auto i:swapchainSync)
if(i==sc)
return;
assert(sc!=nullptr);
swapchainSync.push_back(sc);
}
#endif
fix pipeline barrier 1.0 srcStage
#if defined(TEMPEST_BUILD_VULKAN)
#include "vcommandbuffer.h"
#include <Tempest/DescriptorSet>
#include <Tempest/Attachment>
#include "vdevice.h"
#include "vcommandpool.h"
#include "vpipeline.h"
#include "vbuffer.h"
#include "vdescriptorarray.h"
#include "vswapchain.h"
#include "vtexture.h"
#include "vframebuffermap.h"
using namespace Tempest;
using namespace Tempest::Detail;
static VkAttachmentLoadOp mkLoadOp(const AccessOp op) {
switch (op) {
case AccessOp::Discard:
return VK_ATTACHMENT_LOAD_OP_DONT_CARE;
case AccessOp::Preserve:
return VK_ATTACHMENT_LOAD_OP_LOAD;
case AccessOp::Clear:
return VK_ATTACHMENT_LOAD_OP_CLEAR;
}
return VK_ATTACHMENT_LOAD_OP_DONT_CARE;
}
static VkAttachmentStoreOp mkStoreOp(const AccessOp op) {
switch (op) {
case AccessOp::Discard:
return VK_ATTACHMENT_STORE_OP_DONT_CARE;
case AccessOp::Preserve:
return VK_ATTACHMENT_STORE_OP_STORE;
case AccessOp::Clear:
return VK_ATTACHMENT_STORE_OP_STORE;
}
return VK_ATTACHMENT_STORE_OP_DONT_CARE;
}
static void toStage(VkPipelineStageFlags2KHR& stage, VkAccessFlagBits2KHR& access, ResourceAccess rs, bool isSrc) {
uint32_t ret = 0;
uint32_t acc = 0;
if((rs&ResourceAccess::TransferSrc)==ResourceAccess::TransferSrc) {
ret |= VK_PIPELINE_STAGE_TRANSFER_BIT;
acc |= VK_ACCESS_TRANSFER_READ_BIT;
}
if((rs&ResourceAccess::TransferDst)==ResourceAccess::TransferDst) {
ret |= VK_PIPELINE_STAGE_TRANSFER_BIT;
acc |= VK_ACCESS_TRANSFER_WRITE_BIT;
}
if((rs&ResourceAccess::Present)==ResourceAccess::Present) {
ret |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
acc |= VK_ACCESS_COLOR_ATTACHMENT_READ_BIT;
}
if((rs&ResourceAccess::Sampler)==ResourceAccess::Sampler) {
ret |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
acc |= VK_ACCESS_SHADER_READ_BIT;
}
if((rs&ResourceAccess::ColorAttach)==ResourceAccess::ColorAttach) {
ret |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
acc |= (VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT);
}
if((rs&ResourceAccess::DepthAttach)==ResourceAccess::DepthAttach) {
ret |= (VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT);
acc |= (VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT);
}
if((rs&ResourceAccess::DepthReadOnly)==ResourceAccess::DepthReadOnly) {
ret |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
acc |= VK_ACCESS_SHADER_READ_BIT;
}
if((rs&ResourceAccess::Index)==ResourceAccess::Index) {
ret |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
acc |= VK_ACCESS_INDEX_READ_BIT;
}
if((rs&ResourceAccess::Vertex)==ResourceAccess::Vertex) {
ret |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
acc |= VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
}
if((rs&ResourceAccess::Vertex)==ResourceAccess::Uniform) {
ret |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
acc |= VK_ACCESS_UNIFORM_READ_BIT;
}
// memory barriers
if((rs&ResourceAccess::UavReadGr)==ResourceAccess::UavReadGr) {
ret |= VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT;
acc |= VK_ACCESS_SHADER_READ_BIT;
}
if((rs&ResourceAccess::UavWriteGr)==ResourceAccess::UavWriteGr) {
ret |= VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT;
acc |= VK_ACCESS_SHADER_WRITE_BIT;
}
if((rs&ResourceAccess::UavReadComp)==ResourceAccess::UavReadComp) {
ret |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
acc |= VK_ACCESS_SHADER_READ_BIT;
}
if((rs&ResourceAccess::UavWriteComp)==ResourceAccess::UavWriteComp) {
ret |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
acc |= VK_ACCESS_SHADER_WRITE_BIT;
}
if(isSrc && ret==0) {
// wait for nothing: asset uploading case
ret = VK_PIPELINE_STAGE_NONE_KHR;
acc = VK_ACCESS_NONE_KHR;
}
stage = VkPipelineStageFlags2KHR(ret);
access = VkAccessFlagBits2KHR(acc);
}
static VkImageLayout toLayout(ResourceAccess rs) {
if(rs==ResourceAccess::None)
return VK_IMAGE_LAYOUT_UNDEFINED;
if((rs&ResourceAccess::TransferSrc)==ResourceAccess::TransferSrc)
return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
if((rs&ResourceAccess::TransferDst)==ResourceAccess::TransferDst)
return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
if((rs&ResourceAccess::Present)==ResourceAccess::Present)
return VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
if((rs&ResourceAccess::Sampler)==ResourceAccess::Sampler)
return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
if((rs&ResourceAccess::ColorAttach)==ResourceAccess::ColorAttach)
return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
if((rs&ResourceAccess::DepthReadOnly)==ResourceAccess::DepthReadOnly)
return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
if((rs&ResourceAccess::DepthAttach)==ResourceAccess::DepthAttach)
return VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL;
return VK_IMAGE_LAYOUT_GENERAL;
}
static VkImage toVkResource(const AbstractGraphicsApi::BarrierDesc& b) {
if(b.texture!=nullptr) {
VTexture& t = *reinterpret_cast<VTexture*>(b.texture);
return t.impl;
}
if(b.buffer!=nullptr) {
VBuffer& buf = *reinterpret_cast<VBuffer*>(b.buffer);
return buf.impl;
}
VSwapchain& s = *reinterpret_cast<VSwapchain*>(b.swapchain);
return s.images[b.swId];
}
VCommandBuffer::VCommandBuffer(VDevice& device, VkCommandPoolCreateFlags flags)
:device(device), pool(device,flags) {
VkCommandBufferAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.commandPool = pool.impl;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = 1;
vkAssert(vkAllocateCommandBuffers(device.device.impl,&allocInfo,&impl));
}
VCommandBuffer::~VCommandBuffer() {
vkFreeCommandBuffers(device.device.impl,pool.impl,1,&impl);
}
void VCommandBuffer::reset() {
vkResetCommandBuffer(impl,VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT);
swapchainSync.reserve(swapchainSync.size());
swapchainSync.clear();
}
void VCommandBuffer::begin() {
begin(0);
}
void VCommandBuffer::begin(VkCommandBufferUsageFlags flg) {
state = Idle;
swapchainSync.reserve(swapchainSync.size());
swapchainSync.clear();
curVbo = VK_NULL_HANDLE;
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = flg;
beginInfo.pInheritanceInfo = nullptr;
vkAssert(vkBeginCommandBuffer(impl,&beginInfo));
}
void VCommandBuffer::end() {
swapchainSync.reserve(swapchainSync.size());
resState.finalize(*this);
vkAssert(vkEndCommandBuffer(impl));
state = NoRecording;
}
bool VCommandBuffer::isRecording() const {
return state!=NoRecording;
}
void VCommandBuffer::beginRendering(const AttachmentDesc* desc, size_t descSize,
uint32_t width, uint32_t height,
const TextureFormat* frm,
AbstractGraphicsApi::Texture** att,
AbstractGraphicsApi::Swapchain** sw, const uint32_t* imgId) {
for(size_t i=0; i<descSize; ++i) {
if(sw[i]!=nullptr)
addDependency(*reinterpret_cast<VSwapchain*>(sw[i]),imgId[i]);
}
resState.joinCompute(PipelineStage::S_Graphics);
resState.setRenderpass(*this,desc,descSize,frm,att,sw,imgId);
if(device.props.hasDynRendering) {
VkRenderingAttachmentInfoKHR colorAtt[MaxFramebufferAttachments] = {};
VkRenderingAttachmentInfoKHR depthAtt = {};
VkRenderingInfoKHR info = {};
info.sType = VK_STRUCTURE_TYPE_RENDERING_INFO_KHR;
info.flags = 0;
info.renderArea.offset = {0, 0};
info.renderArea.extent = {width,height};
info.layerCount = 1;
info.viewMask = 0;
info.colorAttachmentCount = 0;
info.pColorAttachments = colorAtt;
passDyn.sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR;
passDyn.pNext = nullptr;
passDyn.viewMask = info.viewMask;
passDyn.colorAttachmentCount = 0;
passDyn.pColorAttachmentFormats = passDyn.colorFrm;
VkImageView imageView = VK_NULL_HANDLE;
VkFormat imageFormat = VK_FORMAT_UNDEFINED;
for(size_t i = 0; i < descSize; ++i) {
if(sw[i] != nullptr) {
auto& t = *reinterpret_cast<VSwapchain*>(sw[i]);
imageView = t.views[imgId[i]];
imageFormat = t.format();
}
else if (desc[i].attachment != nullptr) {
auto& t = *reinterpret_cast<VTexture*>(att[i]);
imageView = t.imgView;
imageFormat = t.format;
}
else {
auto &t = *reinterpret_cast<VTexture*>(att[i]);
imageView = t.imgView;
imageFormat = t.format;
}
auto& att = isDepthFormat(frm[i]) ? depthAtt : colorAtt[info.colorAttachmentCount];
att.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR;
att.imageView = imageView;
if(isDepthFormat(frm[i])) {
info.pDepthAttachment = &depthAtt;
att.imageLayout = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL;
passDyn.depthAttachmentFormat = imageFormat;
auto& clr = att.clearValue;
clr.depthStencil.depth = desc[i].clear.x;
} else {
passDyn.colorFrm[info.colorAttachmentCount] = imageFormat;
++info.colorAttachmentCount;
att.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
auto& clr = att.clearValue;
clr.color.float32[0] = desc[i].clear.x;
clr.color.float32[1] = desc[i].clear.y;
clr.color.float32[2] = desc[i].clear.z;
clr.color.float32[3] = desc[i].clear.w;
}
att.resolveMode = VK_RESOLVE_MODE_NONE;
att.resolveImageView = VK_NULL_HANDLE;
att.resolveImageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
att.loadOp = mkLoadOp(desc[i].load);
att.storeOp = mkStoreOp(desc[i].store);
}
passDyn.colorAttachmentCount = info.colorAttachmentCount;
device.vkCmdBeginRenderingKHR(impl,&info);
} else {
auto fbo = device.fboMap.find(desc,descSize, att,sw,imgId,width,height);
auto fb = fbo.get();
pass = fbo->pass;
VkClearValue clr[MaxFramebufferAttachments];
for(size_t i=0; i<descSize; ++i) {
if(isDepthFormat(frm[i])) {
clr[i].depthStencil.depth = desc[i].clear.x;
} else {
clr[i].color.float32[0] = desc[i].clear.x;
clr[i].color.float32[1] = desc[i].clear.y;
clr[i].color.float32[2] = desc[i].clear.z;
clr[i].color.float32[3] = desc[i].clear.w;
}
}
VkRenderPassBeginInfo info = {};
info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
info.renderPass = fb->pass->pass;
info.framebuffer = fb->fbo;
info.renderArea.offset = {0, 0};
info.renderArea.extent = {width,height};
info.clearValueCount = uint32_t(descSize);
info.pClearValues = clr;
vkCmdBeginRenderPass(impl, &info, VK_SUBPASS_CONTENTS_INLINE);
}
state = RenderPass;
// setup dynamic state
// https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#pipelines-dynamic-state
setViewport(Rect(0,0,int32_t(width),int32_t(height)));
VkRect2D scissor = {};
scissor.offset = {0, 0};
scissor.extent = {width, height};
vkCmdSetScissor(impl,0,1,&scissor);
}
void VCommandBuffer::endRendering() {
if(device.props.hasDynRendering) {
device.vkCmdEndRenderingKHR(impl);
} else {
vkCmdEndRenderPass(impl);
}
state = Idle;
}
void VCommandBuffer::setPipeline(AbstractGraphicsApi::Pipeline& p) {
VPipeline& px = reinterpret_cast<VPipeline&>(p);
auto& v = device.props.hasDynRendering ? px.instance(passDyn) : px.instance(pass);
vkCmdBindPipeline(impl,VK_PIPELINE_BIND_POINT_GRAPHICS,v.val);
}
void VCommandBuffer::setBytes(AbstractGraphicsApi::Pipeline& p, const void* data, size_t size) {
VPipeline& px=reinterpret_cast<VPipeline&>(p);
assert(size<=px.pushSize);
vkCmdPushConstants(impl, px.pipelineLayout, px.pushStageFlags, 0, uint32_t(size), data);
}
void VCommandBuffer::setUniforms(AbstractGraphicsApi::Pipeline &p, AbstractGraphicsApi::Desc &u) {
VPipeline& px=reinterpret_cast<VPipeline&>(p);
VDescriptorArray& ux=reinterpret_cast<VDescriptorArray&>(u);
curUniforms = &ux;
ux.ssboBarriers(resState,PipelineStage::S_Graphics);
vkCmdBindDescriptorSets(impl,VK_PIPELINE_BIND_POINT_GRAPHICS,
px.pipelineLayout,0,
1,&ux.impl,
0,nullptr);
}
void VCommandBuffer::setComputePipeline(AbstractGraphicsApi::CompPipeline& p) {
state = Compute;
VCompPipeline& px = reinterpret_cast<VCompPipeline&>(p);
vkCmdBindPipeline(impl,VK_PIPELINE_BIND_POINT_COMPUTE,px.impl);
}
void VCommandBuffer::dispatch(size_t x, size_t y, size_t z) {
curUniforms->ssboBarriers(resState,PipelineStage::S_Compute);
resState.flush(*this);
vkCmdDispatch(impl,uint32_t(x),uint32_t(y),uint32_t(z));
}
void VCommandBuffer::setBytes(AbstractGraphicsApi::CompPipeline& p, const void* data, size_t size) {
VCompPipeline& px=reinterpret_cast<VCompPipeline&>(p);
assert(size<=px.pushSize);
vkCmdPushConstants(impl, px.pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, uint32_t(size), data);
}
void VCommandBuffer::setUniforms(AbstractGraphicsApi::CompPipeline& p, AbstractGraphicsApi::Desc& u) {
VCompPipeline& px=reinterpret_cast<VCompPipeline&>(p);
VDescriptorArray& ux=reinterpret_cast<VDescriptorArray&>(u);
curUniforms = &ux;
vkCmdBindDescriptorSets(impl,VK_PIPELINE_BIND_POINT_COMPUTE,
px.pipelineLayout,0,
1,&ux.impl,
0,nullptr);
}
void VCommandBuffer::draw(const AbstractGraphicsApi::Buffer& ivbo, size_t voffset, size_t vsize,
size_t firstInstance, size_t instanceCount) {
const VBuffer& vbo=reinterpret_cast<const VBuffer&>(ivbo);
if(curVbo!=vbo.impl) {
VkBuffer buffers[1] = {vbo.impl};
VkDeviceSize offsets[1] = {0};
vkCmdBindVertexBuffers(impl, 0, 1, buffers, offsets );
curVbo = vbo.impl;
}
vkCmdDraw(impl, uint32_t(vsize), uint32_t(instanceCount), uint32_t(voffset), uint32_t(firstInstance));
}
void VCommandBuffer::drawIndexed(const AbstractGraphicsApi::Buffer& ivbo, size_t voffset,
const AbstractGraphicsApi::Buffer& iibo, Detail::IndexClass cls,
size_t ioffset, size_t isize, size_t firstInstance, size_t instanceCount) {
const VBuffer& vbo = reinterpret_cast<const VBuffer&>(ivbo);
const VBuffer& ibo = reinterpret_cast<const VBuffer&>(iibo);
if(curVbo!=vbo.impl) {
VkBuffer buffers[1] = {vbo.impl};
VkDeviceSize offsets[1] = {0};
vkCmdBindVertexBuffers(impl, 0, 1, buffers, offsets);
curVbo = vbo.impl;
}
vkCmdBindIndexBuffer(impl, ibo.impl, 0, nativeFormat(cls));
vkCmdDrawIndexed (impl, uint32_t(isize), uint32_t(instanceCount), uint32_t(ioffset), int32_t(voffset), uint32_t(firstInstance));
}
void VCommandBuffer::dispatchMesh(size_t firstInstance, size_t instanceCount) {
device.vkCmdDrawMeshTasks(impl, uint32_t(instanceCount), uint32_t(firstInstance));
}
void VCommandBuffer::setViewport(const Tempest::Rect &r) {
VkViewport viewPort = {};
viewPort.x = float(r.x);
viewPort.y = float(r.y);
viewPort.width = float(r.w);
viewPort.height = float(r.h);
viewPort.minDepth = 0;
viewPort.maxDepth = 1;
vkCmdSetViewport(impl,0,1,&viewPort);
}
void VCommandBuffer::setScissor(const Rect& r) {
VkRect2D scissor = {};
scissor.offset = {r.x, r.y};
scissor.extent = {uint32_t(r.w), uint32_t(r.h)};
vkCmdSetScissor(impl,0,1,&scissor);
}
void VCommandBuffer::copy(AbstractGraphicsApi::Buffer& dstBuf, size_t offsetDest, const AbstractGraphicsApi::Buffer &srcBuf, size_t offsetSrc, size_t size) {
auto& src = reinterpret_cast<const VBuffer&>(srcBuf);
auto& dst = reinterpret_cast<VBuffer&>(dstBuf);
VkBufferCopy copyRegion = {};
copyRegion.dstOffset = offsetDest;
copyRegion.srcOffset = offsetSrc;
copyRegion.size = size;
vkCmdCopyBuffer(impl, src.impl, dst.impl, 1, ©Region);
}
void VCommandBuffer::copy(AbstractGraphicsApi::Buffer& dstBuf, size_t offsetDest, const void* src, size_t size) {
auto& dst = reinterpret_cast<VBuffer&>(dstBuf);
auto srcBuf = reinterpret_cast<const uint8_t*>(src);
size_t maxSz = 0x10000;
while(size>maxSz) {
vkCmdUpdateBuffer(impl,dst.impl,offsetDest,maxSz,srcBuf);
offsetDest += maxSz;
srcBuf += maxSz;
size -= maxSz;
}
vkCmdUpdateBuffer(impl,dst.impl,offsetDest,size,srcBuf);
VkBufferMemoryBarrier buf = {};
buf.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
buf.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
buf.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
buf.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
buf.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
buf.buffer = dst.impl;
buf.offset = 0;
buf.size = VK_WHOLE_SIZE;
vkCmdPipelineBarrier(impl, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
0,
0, nullptr,
0, &buf,
0, nullptr);
}
void VCommandBuffer::copy(AbstractGraphicsApi::Texture& dstTex, size_t width, size_t height, size_t mip, const AbstractGraphicsApi::Buffer& srcBuf, size_t offset) {
auto& src = reinterpret_cast<const VBuffer&>(srcBuf);
auto& dst = reinterpret_cast<VTexture&>(dstTex);
VkBufferImageCopy region = {};
region.bufferOffset = offset;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = uint32_t(mip);
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = {0, 0, 0};
region.imageExtent = {
uint32_t(width),
uint32_t(height),
1
};
vkCmdCopyBufferToImage(impl, src.impl, dst.impl, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion);
}
void VCommandBuffer::copyNative(AbstractGraphicsApi::Buffer& dst, size_t offset,
const AbstractGraphicsApi::Texture& src, size_t width, size_t height, size_t mip) {
auto& nSrc = reinterpret_cast<const VTexture&>(src);
auto& nDst = reinterpret_cast<VBuffer&>(dst);
VkBufferImageCopy region={};
region.bufferOffset = offset;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = uint32_t(mip);
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = {0, 0, 0};
region.imageExtent = {
uint32_t(width),
uint32_t(height),
1
};
VkImageLayout layout = nSrc.isStorageImage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
vkCmdCopyImageToBuffer(impl, nSrc.impl, layout, nDst.impl, 1, ®ion);
}
void VCommandBuffer::blit(AbstractGraphicsApi::Texture& srcTex, uint32_t srcW, uint32_t srcH, uint32_t srcMip,
AbstractGraphicsApi::Texture& dstTex, uint32_t dstW, uint32_t dstH, uint32_t dstMip) {
auto& src = reinterpret_cast<VTexture&>(srcTex);
auto& dst = reinterpret_cast<VTexture&>(dstTex);
// Check if image format supports linear blitting
VkFormatProperties formatProperties;
vkGetPhysicalDeviceFormatProperties(device.physicalDevice, src.format, &formatProperties);
VkFilter filter = VK_FILTER_LINEAR;
if(0==(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT)) {
filter = VK_FILTER_NEAREST;
}
VkImageBlit blit = {};
blit.srcOffsets[0] = {0, 0, 0};
blit.srcOffsets[1] = {int32_t(srcW), int32_t(srcH), 1};
blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit.srcSubresource.mipLevel = srcMip;
blit.srcSubresource.baseArrayLayer = 0;
blit.srcSubresource.layerCount = 1;
blit.dstOffsets[0] = {0, 0, 0};
blit.dstOffsets[1] = {int32_t(dstW), int32_t(dstH), 1 };
blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit.dstSubresource.mipLevel = dstMip;
blit.dstSubresource.baseArrayLayer = 0;
blit.dstSubresource.layerCount = 1;
vkCmdBlitImage(impl,
src.impl, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
dst.impl, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1, &blit,
filter);
}
void VCommandBuffer::buildBlas(VkAccelerationStructureKHR dest,
const AbstractGraphicsApi::Buffer& ivbo, size_t vboSz, size_t stride,
const AbstractGraphicsApi::Buffer& iibo, size_t iboSz, size_t ioffset, IndexClass icls,
AbstractGraphicsApi::Buffer& scratch) {
auto& vbo = reinterpret_cast<const VBuffer&>(ivbo);
auto& ibo = reinterpret_cast<const VBuffer&>(iibo);
VkAccelerationStructureGeometryKHR geometry = {};
geometry.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR;
geometry.pNext = nullptr;
geometry.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR;
geometry.geometry.triangles.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR;
geometry.geometry.triangles.vertexFormat = VK_FORMAT_R32G32B32_SFLOAT;
geometry.geometry.triangles.vertexStride = stride;
geometry.geometry.triangles.maxVertex = uint32_t(vboSz);
geometry.geometry.triangles.indexType = nativeFormat(icls);
geometry.geometry.triangles.transformData = VkDeviceOrHostAddressConstKHR{};
geometry.flags = VK_GEOMETRY_OPAQUE_BIT_KHR;
geometry.geometry.triangles.vertexData.deviceAddress = vbo.toDeviceAddress(device);
geometry.geometry.triangles.indexData .deviceAddress = ibo.toDeviceAddress(device) + ioffset*sizeofIndex(icls);
VkAccelerationStructureBuildGeometryInfoKHR buildGeometryInfo = {};
buildGeometryInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR;
buildGeometryInfo.pNext = nullptr;
buildGeometryInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR;
buildGeometryInfo.flags = 0;
buildGeometryInfo.mode = VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR;
buildGeometryInfo.srcAccelerationStructure = VK_NULL_HANDLE;
buildGeometryInfo.dstAccelerationStructure = dest;
buildGeometryInfo.geometryCount = 1;
buildGeometryInfo.pGeometries = &geometry;
buildGeometryInfo.ppGeometries = nullptr;
buildGeometryInfo.scratchData.deviceAddress = reinterpret_cast<const VBuffer&>(scratch).toDeviceAddress(device);
VkAccelerationStructureBuildRangeInfoKHR buildRangeInfo = {};
buildRangeInfo.primitiveCount = uint32_t(iboSz/3);
buildRangeInfo.primitiveOffset = 0;
buildRangeInfo.firstVertex = 0;
buildRangeInfo.transformOffset = 0;
VkAccelerationStructureBuildRangeInfoKHR* pbuildRangeInfo = &buildRangeInfo;
device.vkCmdBuildAccelerationStructures(impl, 1, &buildGeometryInfo, &pbuildRangeInfo);
// make sure BLAS'es are ready
VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
barrier.srcAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_KHR;
barrier.dstAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_KHR;
vkCmdPipelineBarrier(impl,
VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR,
VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR,
0, 1, &barrier, 0, nullptr, 0, nullptr);
}
void VCommandBuffer::buildTlas(VkAccelerationStructureKHR dest,
AbstractGraphicsApi::Buffer& tbo,
const AbstractGraphicsApi::Buffer& instances, uint32_t numInstances,
AbstractGraphicsApi::Buffer& scratch) {
VkAccelerationStructureGeometryInstancesDataKHR geometryInstancesData = {};
geometryInstancesData.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_INSTANCES_DATA_KHR;
geometryInstancesData.pNext = NULL;
geometryInstancesData.arrayOfPointers = VK_FALSE;
geometryInstancesData.data.deviceAddress = reinterpret_cast<const VBuffer&>(instances).toDeviceAddress(device);
VkAccelerationStructureGeometryKHR geometry = {};
geometry.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR;
geometry.pNext = nullptr;
geometry.geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR;
geometry.geometry.instances = geometryInstancesData;
geometry.flags = VK_GEOMETRY_OPAQUE_BIT_KHR;
VkAccelerationStructureBuildGeometryInfoKHR buildGeometryInfo = {};
buildGeometryInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR;
buildGeometryInfo.pNext = nullptr;
buildGeometryInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR;
buildGeometryInfo.flags = VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR | VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR;
buildGeometryInfo.mode = VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR;
buildGeometryInfo.srcAccelerationStructure = VK_NULL_HANDLE;
buildGeometryInfo.dstAccelerationStructure = dest;
buildGeometryInfo.geometryCount = 1;
buildGeometryInfo.pGeometries = &geometry;
buildGeometryInfo.ppGeometries = nullptr;
buildGeometryInfo.scratchData.deviceAddress = reinterpret_cast<const VBuffer&>(scratch).toDeviceAddress(device);
VkAccelerationStructureBuildRangeInfoKHR buildRangeInfo = {};
buildRangeInfo.primitiveCount = numInstances;
buildRangeInfo.primitiveOffset = 0;
buildRangeInfo.firstVertex = 0;
buildRangeInfo.transformOffset = 0;
VkAccelerationStructureBuildRangeInfoKHR* pbuildRangeInfo = &buildRangeInfo;
device.vkCmdBuildAccelerationStructures(impl, 1, &buildGeometryInfo, &pbuildRangeInfo);
// make sure TLAS is ready
VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
barrier.srcAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_KHR;
barrier.dstAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_KHR;
vkCmdPipelineBarrier(impl,
VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR,
VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR,
0, 1, &barrier, 0, nullptr, 0, nullptr);
}
void VCommandBuffer::copy(AbstractGraphicsApi::Buffer& dst, size_t offset,
AbstractGraphicsApi::Texture& src, uint32_t width, uint32_t height, uint32_t mip) {
auto& nDst = reinterpret_cast<VBuffer&>(dst);
auto& nSrc = reinterpret_cast<const VTexture&>(src);
if(!nSrc.isStorageImage)
resState.setLayout(src,ResourceAccess::TransferSrc);
resState.onTranferUsage(nDst.nonUniqId,nSrc.nonUniqId);
resState.flush(*this);
copyNative(dst,offset, src,width,height,mip);
if(!nSrc.isStorageImage)
resState.setLayout(src,ResourceAccess::Sampler);
}
void VCommandBuffer::generateMipmap(AbstractGraphicsApi::Texture& img,
uint32_t texWidth, uint32_t texHeight, uint32_t mipLevels) {
if(mipLevels==1)
return;
auto& image = reinterpret_cast<VTexture&>(img);
// Check if image format supports linear blitting
VkFormatProperties formatProperties;
vkGetPhysicalDeviceFormatProperties(device.physicalDevice, image.format, &formatProperties);
if(!(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT))
throw std::runtime_error("texture image format does not support linear blitting!");
int32_t w = int32_t(texWidth);
int32_t h = int32_t(texHeight);
resState.setLayout(img,ResourceAccess::TransferDst);
resState.flush(*this);
for(uint32_t i=1; i<mipLevels; ++i) {
const int mw = (w==1 ? 1 : w/2);
const int mh = (h==1 ? 1 : h/2);
barrier(img,ResourceAccess::TransferDst, ResourceAccess::TransferSrc,i-1);
blit(img, w, h, i-1,
img, mw,mh, i);
w = mw;
h = mh;
}
barrier(img,ResourceAccess::TransferDst, ResourceAccess::TransferSrc, mipLevels-1);
barrier(img,ResourceAccess::TransferSrc, ResourceAccess::Sampler, uint32_t(-1));
resState.setLayout(img,ResourceAccess::Sampler);
resState.forceLayout(img);
}
void VCommandBuffer::barrier(const AbstractGraphicsApi::BarrierDesc* desc, size_t cnt) {
VkBufferMemoryBarrier2KHR bufBarrier[MaxBarriers] = {};
uint32_t bufCount = 0;
VkImageMemoryBarrier2KHR imgBarrier[MaxBarriers] = {};
uint32_t imgCount = 0;
VkMemoryBarrier2KHR memBarrier = {};
VkDependencyInfoKHR info = {};
info.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO_KHR;
for(size_t i=0; i<cnt; ++i) {
auto& b = desc[i];
if(b.buffer==nullptr && b.texture==nullptr && b.swapchain==nullptr) {
VkPipelineStageFlags2KHR srcStageMask = 0;
VkAccessFlags2KHR srcAccessMask = 0;
VkPipelineStageFlags2KHR dstStageMask = 0;
VkAccessFlags2KHR dstAccessMask = 0;
toStage(srcStageMask, srcAccessMask, b.prev,true);
toStage(dstStageMask, dstAccessMask, b.next,false);
memBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2_KHR;
memBarrier.srcStageMask |= srcStageMask;
memBarrier.srcAccessMask |= srcAccessMask;
memBarrier.dstStageMask |= dstStageMask;
memBarrier.dstAccessMask |= dstAccessMask;
}
else if(b.buffer!=nullptr) {
auto& bx = bufBarrier[bufCount];
++bufCount;
bx.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER_2_KHR;
bx.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
bx.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
bx.buffer = reinterpret_cast<VBuffer&>(*b.buffer).impl;
bx.offset = 0;
bx.size = VK_WHOLE_SIZE;
toStage(bx.srcStageMask, bx.srcAccessMask, b.prev,true);
toStage(bx.dstStageMask, bx.dstAccessMask, b.next,false);
} else {
auto& bx = imgBarrier[imgCount];
++imgCount;
bx.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2_KHR;
bx.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
bx.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
bx.image = toVkResource(b);
toStage(bx.srcStageMask, bx.srcAccessMask, b.prev,true);
toStage(bx.dstStageMask, bx.dstAccessMask, b.next,false);
bx.oldLayout = toLayout(b.prev);
bx.newLayout = toLayout(b.next);
finalizeImageBarrier(bx,b);
}
}
info.pBufferMemoryBarriers = bufBarrier;
info.bufferMemoryBarrierCount = bufCount;
info.pImageMemoryBarriers = imgBarrier;
info.imageMemoryBarrierCount = imgCount;
if(memBarrier.sType==VK_STRUCTURE_TYPE_MEMORY_BARRIER_2_KHR) {
info.pMemoryBarriers = &memBarrier;
info.memoryBarrierCount++;
}
vkCmdPipelineBarrier2(impl,&info);
}
void VCommandBuffer::vkCmdPipelineBarrier2(VkCommandBuffer impl, const VkDependencyInfoKHR* info) {
if(device.vkCmdPipelineBarrier2!=nullptr) {
device.vkCmdPipelineBarrier2(impl,info);
return;
}
VkPipelineStageFlags srcStage = 0;
VkPipelineStageFlags dstStage = 0;
uint32_t memCount = 0;
VkMemoryBarrier memBarrier[MaxBarriers] = {};
uint32_t bufCount = 0;
VkBufferMemoryBarrier bufBarrier[MaxBarriers] = {};
uint32_t imgCount = 0;
VkImageMemoryBarrier imgBarrier[MaxBarriers] = {};
for(size_t i=0; i<info->memoryBarrierCount; ++i) {
auto& b = info->pMemoryBarriers[i];
if(memCount>MaxBarriers || b.srcStageMask!=srcStage || b.dstStageMask!=dstStage) {
if(memCount>0) {
vkCmdPipelineBarrier(impl,srcStage,dstStage,info->dependencyFlags,
memCount,memBarrier,
0,nullptr,
0,nullptr);
}
srcStage = VkPipelineStageFlags(b.srcStageMask);
dstStage = VkPipelineStageFlags(b.dstStageMask);
memCount = 0;
}
auto& bx = memBarrier[memCount];
bx.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
bx.srcAccessMask = VkAccessFlags(b.srcAccessMask);
bx.dstAccessMask = VkAccessFlags(b.dstAccessMask);
++memCount;
}
for(size_t i=0; i<info->bufferMemoryBarrierCount; ++i) {
auto& b = info->pBufferMemoryBarriers[i];
if(bufCount>MaxBarriers || b.srcStageMask!=srcStage || b.dstStageMask!=dstStage) {
if(bufCount>0) {
vkCmdPipelineBarrier(impl,srcStage,dstStage,info->dependencyFlags,
0,nullptr,
bufCount,bufBarrier,
0,nullptr);
}
srcStage = VkPipelineStageFlags(b.srcStageMask);
dstStage = VkPipelineStageFlags(b.dstStageMask);
bufCount = 0;
}
auto& bx = bufBarrier[bufCount];
bx.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
bx.srcAccessMask = VkAccessFlags(b.srcAccessMask);
bx.dstAccessMask = VkAccessFlags(b.dstAccessMask);
bx.srcQueueFamilyIndex = b.srcQueueFamilyIndex;
bx.dstQueueFamilyIndex = b.dstQueueFamilyIndex;
bx.buffer = b.buffer;
bx.offset = b.offset;
bx.size = b.size;
++bufCount;
}
for(size_t i=0; i<info->imageMemoryBarrierCount; ++i) {
auto& b = info->pImageMemoryBarriers[i];
if(imgCount>MaxBarriers || b.srcStageMask!=srcStage || b.dstStageMask!=dstStage) {
if(imgCount>0) {
vkCmdPipelineBarrier(impl,srcStage,dstStage,info->dependencyFlags,
0,nullptr,
0,nullptr,
imgCount,imgBarrier);
}
srcStage = VkPipelineStageFlags(b.srcStageMask);
dstStage = VkPipelineStageFlags(b.dstStageMask);
imgCount = 0;
}
auto& bx = imgBarrier[imgCount];
bx.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
bx.srcAccessMask = VkAccessFlags(b.srcAccessMask);
bx.dstAccessMask = VkAccessFlags(b.dstAccessMask);
bx.oldLayout = b.oldLayout;
bx.newLayout = b.newLayout;
bx.srcQueueFamilyIndex = b.srcQueueFamilyIndex;
bx.dstQueueFamilyIndex = b.dstQueueFamilyIndex;
bx.image = b.image;
bx.subresourceRange = b.subresourceRange;
++imgCount;
}
if(memCount==0 && bufCount==0 && imgCount==0)
return;
if(srcStage==0)
srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
vkCmdPipelineBarrier(impl,srcStage,dstStage,info->dependencyFlags,
memCount,memBarrier,
bufCount,bufBarrier,
imgCount,imgBarrier);
}
template<class T>
void VCommandBuffer::finalizeImageBarrier(T& bx, const AbstractGraphicsApi::BarrierDesc& b) {
if(b.prev==ResourceAccess::Present)
bx.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
if(b.next==ResourceAccess::Present)
bx.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkFormat nativeFormat = VK_FORMAT_UNDEFINED;
if(b.texture!=nullptr) {
VTexture& t = *reinterpret_cast<VTexture*> (b.texture);
nativeFormat = t.format;
} else {
VSwapchain& s = *reinterpret_cast<VSwapchain*>(b.swapchain);
nativeFormat = s.format();
}
bx.subresourceRange.baseMipLevel = b.mip==uint32_t(-1) ? 0 : b.mip;
bx.subresourceRange.levelCount = b.mip==uint32_t(-1) ? VK_REMAINING_MIP_LEVELS : 1;
bx.subresourceRange.baseArrayLayer = 0;
bx.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS;
if(nativeFormat==VK_FORMAT_D24_UNORM_S8_UINT || nativeFormat==VK_FORMAT_D16_UNORM_S8_UINT || nativeFormat==VK_FORMAT_D32_SFLOAT_S8_UINT)
bx.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; else
if(Detail::nativeIsDepthFormat(nativeFormat))
bx.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; else
bx.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
if(b.discard)
bx.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
}
void VCommandBuffer::addDependency(VSwapchain& s, size_t imgId) {
VSwapchain::Sync* sc = nullptr;
for(auto& i:s.sync)
if(i.imgId==imgId) {
sc = &i;
break;
}
for(auto i:swapchainSync)
if(i==sc)
return;
assert(sc!=nullptr);
swapchainSync.push_back(sc);
}
#endif
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "docsumconfig.h"
#include "docsumwriter.h"
#include "idocsumenvironment.h"
#include "rankfeaturesdfw.h"
#include "textextractordfw.h"
#include "geoposdfw.h"
#include "positionsdfw.h"
#include "juniperdfw.h"
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/exceptions.h>
namespace search::docsummary {
using vespalib::IllegalArgumentException;
using vespalib::make_string;
const ResultConfig &
DynamicDocsumConfig::getResultConfig() const {
return *_writer->GetResultConfig();
}
IDocsumFieldWriter::UP
DynamicDocsumConfig::createFieldWriter(const string & fieldName, const string & overrideName, const string & argument, bool & rc)
{
const ResultConfig & resultConfig = getResultConfig();
rc = false;
IDocsumFieldWriter::UP fieldWriter;
if (overrideName == "dynamicteaser") {
if ( ! argument.empty() ) {
const char *langFieldName = "something unused";
DynamicTeaserDFW *fw = new DynamicTeaserDFW(getEnvironment()->getJuniper());
fieldWriter.reset(fw);
rc = fw->Init(fieldName.c_str(), langFieldName, resultConfig, argument.c_str());
} else {
throw IllegalArgumentException("Missing argument");
}
} else if (overrideName == "textextractor") {
if ( ! argument.empty() ) {
TextExtractorDFW * fw = new TextExtractorDFW();
fieldWriter.reset(fw);
rc = fw->init(fieldName, argument, resultConfig);
} else {
throw IllegalArgumentException("Missing argument");
}
} else if (overrideName == "summaryfeatures") {
SummaryFeaturesDFW *fw = new SummaryFeaturesDFW();
fieldWriter.reset(fw);
fw->init(getEnvironment());
rc = true;
} else if (overrideName == "rankfeatures") {
RankFeaturesDFW * fw = new RankFeaturesDFW();
fw->init(getEnvironment());
fieldWriter.reset(fw);
rc = true;
} else if (overrideName == "empty") {
EmptyDFW *fw = new EmptyDFW();
fieldWriter.reset(fw);
rc = true;
} else if (overrideName == "copy") {
if ( ! argument.empty() ) {
CopyDFW *fw = new CopyDFW();
fieldWriter.reset(fw);
rc = fw->Init(resultConfig, argument.c_str());
} else {
throw IllegalArgumentException("Missing argument");
}
} else if (overrideName == "absdist") {
if (getEnvironment()) {
IAttributeManager *am = getEnvironment()->getAttributeManager();
fieldWriter = createAbsDistanceDFW(argument.c_str(), am);
rc = fieldWriter.get();
}
} else if (overrideName == "positions") {
if (getEnvironment()) {
IAttributeManager *am = getEnvironment()->getAttributeManager();
fieldWriter = createPositionsDFW(argument.c_str(), am);
rc = fieldWriter.get();
}
} else if (overrideName == "geopos") {
if (getEnvironment()) {
IAttributeManager *am = getEnvironment()->getAttributeManager();
fieldWriter = GeoPositionDFW::create(argument.c_str(), am);
rc = fieldWriter.get();
}
} else if (overrideName == "attribute") {
const char *vectorName = argument.c_str();
if (getEnvironment() && getEnvironment()->getAttributeManager()) {
IDocsumFieldWriter *fw = AttributeDFWFactory::create(*getEnvironment()->getAttributeManager(), vectorName);
fieldWriter.reset(fw);
rc = fw != NULL;
}
} else {
throw IllegalArgumentException("unknown override operation '" + overrideName + "' for field '" + fieldName + "'.");
}
return fieldWriter;
}
void
DynamicDocsumConfig::configure(const vespa::config::search::SummarymapConfig &cfg)
{
std::vector<string> strCfg;
if ((cfg.defaultoutputclass != -1) && !_writer->SetDefaultOutputClass(cfg.defaultoutputclass)) {
throw IllegalArgumentException(make_string("could not set default output class to %d", cfg.defaultoutputclass));
}
for (size_t i = 0; i < cfg.override.size(); ++i) {
const vespa::config::search::SummarymapConfig::Override & o = cfg.override[i];
if (o.command == "attributecombiner") {
// TODO: Remove this when support has been added
continue;
}
bool rc(false);
IDocsumFieldWriter::UP fieldWriter = createFieldWriter(o.field, o.command, o.arguments, rc);
if (rc && fieldWriter.get() != NULL) {
rc = _writer->Override(o.field.c_str(), fieldWriter.release()); // OBJECT HAND-OVER
}
if (!rc) {
throw IllegalArgumentException(o.command + " override operation failed during initialization");
}
}
}
}
Wire in AttributeCombinerDFW.
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "docsumconfig.h"
#include "docsumwriter.h"
#include "idocsumenvironment.h"
#include "rankfeaturesdfw.h"
#include "textextractordfw.h"
#include "geoposdfw.h"
#include "positionsdfw.h"
#include "juniperdfw.h"
#include "attribute_combiner_dfw.h"
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/exceptions.h>
namespace search::docsummary {
using vespalib::IllegalArgumentException;
using vespalib::make_string;
const ResultConfig &
DynamicDocsumConfig::getResultConfig() const {
return *_writer->GetResultConfig();
}
IDocsumFieldWriter::UP
DynamicDocsumConfig::createFieldWriter(const string & fieldName, const string & overrideName, const string & argument, bool & rc)
{
const ResultConfig & resultConfig = getResultConfig();
rc = false;
IDocsumFieldWriter::UP fieldWriter;
if (overrideName == "dynamicteaser") {
if ( ! argument.empty() ) {
const char *langFieldName = "something unused";
DynamicTeaserDFW *fw = new DynamicTeaserDFW(getEnvironment()->getJuniper());
fieldWriter.reset(fw);
rc = fw->Init(fieldName.c_str(), langFieldName, resultConfig, argument.c_str());
} else {
throw IllegalArgumentException("Missing argument");
}
} else if (overrideName == "textextractor") {
if ( ! argument.empty() ) {
TextExtractorDFW * fw = new TextExtractorDFW();
fieldWriter.reset(fw);
rc = fw->init(fieldName, argument, resultConfig);
} else {
throw IllegalArgumentException("Missing argument");
}
} else if (overrideName == "summaryfeatures") {
SummaryFeaturesDFW *fw = new SummaryFeaturesDFW();
fieldWriter.reset(fw);
fw->init(getEnvironment());
rc = true;
} else if (overrideName == "rankfeatures") {
RankFeaturesDFW * fw = new RankFeaturesDFW();
fw->init(getEnvironment());
fieldWriter.reset(fw);
rc = true;
} else if (overrideName == "empty") {
EmptyDFW *fw = new EmptyDFW();
fieldWriter.reset(fw);
rc = true;
} else if (overrideName == "copy") {
if ( ! argument.empty() ) {
CopyDFW *fw = new CopyDFW();
fieldWriter.reset(fw);
rc = fw->Init(resultConfig, argument.c_str());
} else {
throw IllegalArgumentException("Missing argument");
}
} else if (overrideName == "absdist") {
if (getEnvironment()) {
IAttributeManager *am = getEnvironment()->getAttributeManager();
fieldWriter = createAbsDistanceDFW(argument.c_str(), am);
rc = fieldWriter.get();
}
} else if (overrideName == "positions") {
if (getEnvironment()) {
IAttributeManager *am = getEnvironment()->getAttributeManager();
fieldWriter = createPositionsDFW(argument.c_str(), am);
rc = fieldWriter.get();
}
} else if (overrideName == "geopos") {
if (getEnvironment()) {
IAttributeManager *am = getEnvironment()->getAttributeManager();
fieldWriter = GeoPositionDFW::create(argument.c_str(), am);
rc = fieldWriter.get();
}
} else if (overrideName == "attribute") {
const char *vectorName = argument.c_str();
if (getEnvironment() && getEnvironment()->getAttributeManager()) {
IDocsumFieldWriter *fw = AttributeDFWFactory::create(*getEnvironment()->getAttributeManager(), vectorName);
fieldWriter.reset(fw);
rc = fw != NULL;
}
} else if (overrideName == "attributecombiner") {
if (getEnvironment() && getEnvironment()->getAttributeManager()) {
fieldWriter = AttributeCombinerDFW::create(fieldName, *getEnvironment()->getAttributeManager());
rc = static_cast<bool>(fieldWriter);
}
} else {
throw IllegalArgumentException("unknown override operation '" + overrideName + "' for field '" + fieldName + "'.");
}
return fieldWriter;
}
void
DynamicDocsumConfig::configure(const vespa::config::search::SummarymapConfig &cfg)
{
std::vector<string> strCfg;
if ((cfg.defaultoutputclass != -1) && !_writer->SetDefaultOutputClass(cfg.defaultoutputclass)) {
throw IllegalArgumentException(make_string("could not set default output class to %d", cfg.defaultoutputclass));
}
for (size_t i = 0; i < cfg.override.size(); ++i) {
const vespa::config::search::SummarymapConfig::Override & o = cfg.override[i];
bool rc(false);
IDocsumFieldWriter::UP fieldWriter = createFieldWriter(o.field, o.command, o.arguments, rc);
if (rc && fieldWriter.get() != NULL) {
rc = _writer->Override(o.field.c_str(), fieldWriter.release()); // OBJECT HAND-OVER
}
if (!rc) {
throw IllegalArgumentException(o.command + " override operation failed during initialization");
}
}
}
}
|
// Copyright 2021 Code Intelligence GmbH
//
// 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 "fuzz_target_runner.h"
#include <jni.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <string>
#include <vector>
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/str_split.h"
#include "absl/strings/substitute.h"
#include "coverage_tracker.h"
#include "fuzzed_data_provider.h"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "java_reproducer.h"
#include "java_reproducer_templates.h"
#include "utils.h"
DEFINE_string(
target_class, "",
"The Java class that contains the static fuzzerTestOneInput function");
DEFINE_string(target_args, "",
"Arguments passed to fuzzerInitialize as a String array. "
"Separated by space.");
DEFINE_uint32(keep_going, 0,
"Continue fuzzing until N distinct exception stack traces have"
"been encountered. Defaults to exit after the first finding "
"unless --autofuzz is specified.");
DEFINE_bool(dedup, true,
"Emit a dedup token for every finding. Defaults to true and is "
"required for --keep_going and --ignore.");
DEFINE_string(
ignore, "",
"Comma-separated list of crash dedup tokens to ignore. This is useful to "
"continue fuzzing before a crash is fixed.");
DEFINE_string(reproducer_path, ".",
"Path at which fuzzing reproducers are stored. Defaults to the "
"current directory.");
DEFINE_string(coverage_report, "",
"Path at which a coverage report is stored when the fuzzer "
"exits. If left empty, no report is generated (default)");
DEFINE_string(coverage_dump, "",
"Path at which a coverage dump is stored when the fuzzer "
"exits. If left empty, no dump is generated (default)");
DEFINE_string(autofuzz, "",
"Fully qualified reference to a method on the classpath that "
"should be fuzzed automatically (example: System.out::println). "
"Fuzzing will continue even after a finding; specify "
"--keep_going=N to stop after N findings.");
DEFINE_string(autofuzz_ignore, "",
"Fully qualified class names of exceptions to ignore during "
"autofuzz. Separated by comma.");
DECLARE_bool(hooks);
constexpr auto kManifestUtilsClass =
"com/code_intelligence/jazzer/runtime/ManifestUtils";
constexpr auto kJazzerClass =
"com/code_intelligence/jazzer/runtime/JazzerInternal";
constexpr auto kAutofuzzFuzzTargetClass =
"com/code_intelligence/jazzer/autofuzz/FuzzTarget";
// A constant pool CONSTANT_Utf8_info entry should be able to hold data of size
// uint16, but somehow this does not seem to be the case and leads to invalid
// code crash reproducer code. Reducing the size by one resolves the problem.
constexpr auto dataChunkMaxLength = std::numeric_limits<uint16_t>::max() - 1;
namespace jazzer {
// split a string on unescaped spaces
std::vector<std::string> splitOnSpace(const std::string &s) {
if (s.empty()) {
return {};
}
std::vector<std::string> tokens;
std::size_t token_begin = 0;
for (std::size_t i = 1; i < s.size() - 1; i++) {
// only split if the space is not escaped by a backslash "\"
if (s[i] == ' ' && s[i - 1] != '\\') {
// don't split on multiple spaces
if (i > token_begin + 1)
tokens.push_back(s.substr(token_begin, i - token_begin));
token_begin = i + 1;
}
}
tokens.push_back(s.substr(token_begin));
return tokens;
}
FuzzTargetRunner::FuzzTargetRunner(
JVM &jvm, const std::vector<std::string> &additional_target_args)
: ExceptionPrinter(jvm), jvm_(jvm), ignore_tokens_() {
auto &env = jvm.GetEnv();
if (!FLAGS_target_class.empty() && !FLAGS_autofuzz.empty()) {
std::cerr << "--target_class and --autofuzz cannot be specified together"
<< std::endl;
exit(1);
}
if (!FLAGS_target_args.empty() && !FLAGS_autofuzz.empty()) {
std::cerr << "--target_args and --autofuzz cannot be specified together"
<< std::endl;
exit(1);
}
if (FLAGS_autofuzz.empty() && !FLAGS_autofuzz_ignore.empty()) {
std::cerr << "--autofuzz_ignore requires --autofuzz" << std::endl;
exit(1);
}
if (FLAGS_target_class.empty() && FLAGS_autofuzz.empty()) {
FLAGS_target_class = DetectFuzzTargetClass();
}
// If automatically detecting the fuzz target class failed, we expect it as
// the value of the --target_class argument.
if (FLAGS_target_class.empty() && FLAGS_autofuzz.empty()) {
std::cerr << "Missing argument --target_class=<fuzz_target_class>"
<< std::endl;
exit(1);
}
if (!FLAGS_autofuzz.empty()) {
FLAGS_target_class = kAutofuzzFuzzTargetClass;
if (FLAGS_keep_going == 0) {
FLAGS_keep_going = std::numeric_limits<gflags::uint32>::max();
}
// Pass the method reference string as the first argument to the generic
// autofuzz fuzz target. Subseqeuent arguments are interpreted as exception
// class names that should be ignored.
FLAGS_target_args = FLAGS_autofuzz;
if (!FLAGS_autofuzz_ignore.empty()) {
FLAGS_target_args = absl::StrCat(
FLAGS_target_args, " ",
absl::StrReplaceAll(FLAGS_autofuzz_ignore, {{",", " "}}));
}
}
// Set --keep_going to its real default.
if (FLAGS_keep_going == 0) {
FLAGS_keep_going = 1;
}
if ((!FLAGS_ignore.empty() || FLAGS_keep_going > 1) && !FLAGS_dedup) {
std::cerr << "--nodedup is not supported with --ignore or --keep_going"
<< std::endl;
exit(1);
}
jazzer_ = jvm.FindClass(kJazzerClass);
last_finding_ =
env.GetStaticFieldID(jazzer_, "lastFinding", "Ljava/lang/Throwable;");
// Inform the agent about the fuzz target class.
// Important note: This has to be done *before*
// jvm.FindClass(FLAGS_target_class) so that hooks can enable themselves in
// time for the fuzz target's static initializer.
auto on_fuzz_target_ready = jvm.GetStaticMethodID(
jazzer_, "onFuzzTargetReady", "(Ljava/lang/String;)V", true);
jstring fuzz_target_class = env.NewStringUTF(FLAGS_target_class.c_str());
env.CallStaticObjectMethod(jazzer_, on_fuzz_target_ready, fuzz_target_class);
if (env.ExceptionCheck()) {
env.ExceptionDescribe();
return;
}
env.DeleteLocalRef(fuzz_target_class);
try {
jclass_ = jvm.FindClass(FLAGS_target_class);
} catch (const std::runtime_error &error) {
std::cerr << "ERROR: " << error.what() << std::endl;
exit(1);
}
// one of the following functions is required:
// public static void fuzzerTestOneInput(byte[] input)
// public static void fuzzerTestOneInput(FuzzedDataProvider data)
fuzzer_test_one_input_bytes_ =
jvm.GetStaticMethodID(jclass_, "fuzzerTestOneInput", "([B)V", false);
fuzzer_test_one_input_data_ = jvm.GetStaticMethodID(
jclass_, "fuzzerTestOneInput",
"(Lcom/code_intelligence/jazzer/api/FuzzedDataProvider;)V", false);
bool using_bytes = fuzzer_test_one_input_bytes_ != nullptr;
bool using_data = fuzzer_test_one_input_data_ != nullptr;
// Fail if none ore both of the two possible fuzzerTestOneInput versions is
// defined in the class.
if (using_bytes == using_data) {
LOG(ERROR) << FLAGS_target_class
<< " must define exactly one of the following two functions:";
LOG(ERROR) << "public static void fuzzerTestOneInput(byte[] ...)";
LOG(ERROR)
<< "public static void fuzzerTestOneInput(FuzzedDataProvider ...)";
LOG(ERROR) << "Note: Fuzz targets returning boolean are no longer "
"supported; exceptions should be thrown instead of "
"returning true.";
exit(1);
}
// check existence of optional methods for initialization and destruction
fuzzer_initialize_ =
jvm.GetStaticMethodID(jclass_, "fuzzerInitialize", "()V", false);
fuzzer_tear_down_ =
jvm.GetStaticMethodID(jclass_, "fuzzerTearDown", "()V", false);
fuzzer_initialize_with_args_ = jvm.GetStaticMethodID(
jclass_, "fuzzerInitialize", "([Ljava/lang/String;)V", false);
auto fuzz_target_args_tokens = splitOnSpace(FLAGS_target_args);
fuzz_target_args_tokens.insert(fuzz_target_args_tokens.end(),
additional_target_args.begin(),
additional_target_args.end());
if (fuzzer_initialize_with_args_) {
// fuzzerInitialize with arguments gets priority
jclass string_class = jvm.FindClass("java/lang/String");
jobjectArray arg_array = jvm.GetEnv().NewObjectArray(
fuzz_target_args_tokens.size(), string_class, nullptr);
for (jint i = 0; i < fuzz_target_args_tokens.size(); i++) {
jstring str = env.NewStringUTF(fuzz_target_args_tokens[i].c_str());
env.SetObjectArrayElement(arg_array, i, str);
}
env.CallStaticObjectMethod(jclass_, fuzzer_initialize_with_args_,
arg_array);
} else if (fuzzer_initialize_) {
env.CallStaticVoidMethod(jclass_, fuzzer_initialize_);
} else {
LOG(INFO) << "did not call any fuzz target initialize functions";
}
if (jthrowable exception = env.ExceptionOccurred()) {
LOG(ERROR) << "== Java Exception in fuzzerInitialize: ";
LOG(ERROR) << getStackTrace(exception);
std::exit(1);
}
if (FLAGS_hooks) {
CoverageTracker::RecordInitialCoverage(env);
}
SetUpFuzzedDataProvider(jvm_.GetEnv());
// Parse a comma-separated list of hex dedup tokens.
std::vector<std::string> str_ignore_tokens =
absl::StrSplit(FLAGS_ignore, ',');
for (const std::string &str_token : str_ignore_tokens) {
if (str_token.empty()) continue;
try {
ignore_tokens_.push_back(std::stoull(str_token, nullptr, 16));
} catch (...) {
LOG(ERROR) << "Invalid dedup token (expected up to 16 hex digits): '"
<< str_token << "'";
// Don't let libFuzzer print a crash stack trace.
_Exit(1);
}
}
}
FuzzTargetRunner::~FuzzTargetRunner() {
if (FLAGS_hooks && !FLAGS_coverage_report.empty()) {
CoverageTracker::ReportCoverage(jvm_.GetEnv(), FLAGS_coverage_report);
}
if (FLAGS_hooks && !FLAGS_coverage_dump.empty()) {
CoverageTracker::DumpCoverage(jvm_.GetEnv(), FLAGS_coverage_dump);
}
if (fuzzer_tear_down_ != nullptr) {
std::cerr << "calling fuzzer teardown function" << std::endl;
jvm_.GetEnv().CallStaticVoidMethod(jclass_, fuzzer_tear_down_);
if (jthrowable exception = jvm_.GetEnv().ExceptionOccurred()) {
std::cerr << getStackTrace(exception) << std::endl;
_Exit(1);
}
}
}
RunResult FuzzTargetRunner::Run(const uint8_t *data, const std::size_t size) {
auto &env = jvm_.GetEnv();
static std::size_t run_count = 0;
if (run_count < 2 && FLAGS_hooks) {
run_count++;
// For the first two runs only, replay the coverage recorded from static
// initializers. libFuzzer cleared the coverage map after they ran and could
// fail to see any coverage, triggering an early exit, if we don't replay it
// here.
// https://github.com/llvm/llvm-project/blob/957a5e987444d3193575d6ad8afe6c75da00d794/compiler-rt/lib/fuzzer/FuzzerLoop.cpp#L804-L809
CoverageTracker::ReplayInitialCoverage(env);
}
if (fuzzer_test_one_input_data_ != nullptr) {
FeedFuzzedDataProvider(data, size);
env.CallStaticVoidMethod(jclass_, fuzzer_test_one_input_data_,
GetFuzzedDataProviderJavaObject(jvm_));
} else {
jbyteArray byte_array = env.NewByteArray(size);
if (byte_array == nullptr) {
env.ExceptionDescribe();
throw std::runtime_error(std::string("Cannot create byte array"));
}
env.SetByteArrayRegion(byte_array, 0, size,
reinterpret_cast<const jbyte *>(data));
env.CallStaticVoidMethod(jclass_, fuzzer_test_one_input_bytes_, byte_array);
env.DeleteLocalRef(byte_array);
}
const auto finding = GetFinding();
if (finding != nullptr) {
jlong dedup_token = computeDedupToken(finding);
// Check whether this stack trace has been encountered before if
// `--keep_going` has been supplied.
if (dedup_token != 0 && FLAGS_keep_going > 1 &&
std::find(ignore_tokens_.cbegin(), ignore_tokens_.cend(),
dedup_token) != ignore_tokens_.end()) {
env.DeleteLocalRef(finding);
return RunResult::kOk;
} else {
ignore_tokens_.push_back(dedup_token);
std::cout << std::endl;
std::cerr << "== Java Exception: " << getStackTrace(finding);
env.DeleteLocalRef(finding);
if (FLAGS_dedup) {
std::cout << "DEDUP_TOKEN: " << std::hex << std::setfill('0')
<< std::setw(16) << dedup_token << std::endl;
}
if (ignore_tokens_.size() < static_cast<std::size_t>(FLAGS_keep_going)) {
return RunResult::kDumpAndContinue;
} else {
return RunResult::kException;
}
}
}
return RunResult::kOk;
}
// Returns a fuzzer finding as a Throwable (or nullptr if there is none),
// clearing any JVM exceptions in the process.
jthrowable FuzzTargetRunner::GetFinding() const {
auto &env = jvm_.GetEnv();
jthrowable unprocessed_finding = nullptr;
if (env.ExceptionCheck()) {
unprocessed_finding = env.ExceptionOccurred();
env.ExceptionClear();
}
// Explicitly reported findings take precedence over uncaught exceptions.
if (auto reported_finding =
(jthrowable)env.GetStaticObjectField(jazzer_, last_finding_);
reported_finding != nullptr) {
env.DeleteLocalRef(unprocessed_finding);
unprocessed_finding = reported_finding;
}
jthrowable processed_finding = preprocessException(unprocessed_finding);
env.DeleteLocalRef(unprocessed_finding);
return processed_finding;
}
void FuzzTargetRunner::DumpReproducer(const uint8_t *data, std::size_t size) {
auto &env = jvm_.GetEnv();
std::string data_sha1 = jazzer::Sha1Hash(data, size);
if (!FLAGS_autofuzz.empty()) {
auto autofuzz_fuzz_target_class = env.FindClass(kAutofuzzFuzzTargetClass);
if (env.ExceptionCheck()) {
env.ExceptionDescribe();
return;
}
auto dump_reproducer = env.GetStaticMethodID(
autofuzz_fuzz_target_class, "dumpReproducer",
"(Lcom/code_intelligence/jazzer/api/FuzzedDataProvider;Ljava/lang/"
"String;Ljava/lang/String;)V");
if (env.ExceptionCheck()) {
env.ExceptionDescribe();
return;
}
FeedFuzzedDataProvider(data, size);
auto reproducer_path_jni = env.NewStringUTF(FLAGS_reproducer_path.c_str());
auto data_sha1_jni = env.NewStringUTF(data_sha1.c_str());
env.CallStaticVoidMethod(autofuzz_fuzz_target_class, dump_reproducer,
GetFuzzedDataProviderJavaObject(jvm_),
reproducer_path_jni, data_sha1_jni);
if (env.ExceptionCheck()) {
env.ExceptionDescribe();
return;
}
env.DeleteLocalRef(data_sha1_jni);
env.DeleteLocalRef(reproducer_path_jni);
return;
}
std::string base64_data;
if (fuzzer_test_one_input_data_) {
// Record the data retrieved from the FuzzedDataProvider and supply it to a
// Java-only CannedFuzzedDataProvider in the reproducer.
FeedFuzzedDataProvider(data, size);
jobject recorder = GetRecordingFuzzedDataProviderJavaObject(jvm_);
env.CallStaticVoidMethod(jclass_, fuzzer_test_one_input_data_, recorder);
const auto finding = GetFinding();
if (finding == nullptr) {
LOG(ERROR) << "Failed to reproduce crash when rerunning with recorder";
return;
}
base64_data = SerializeRecordingFuzzedDataProvider(jvm_, recorder);
} else {
absl::string_view data_str(reinterpret_cast<const char *>(data), size);
absl::Base64Escape(data_str, &base64_data);
}
const char *fuzz_target_call = fuzzer_test_one_input_data_
? kTestOneInputWithData
: kTestOneInputWithBytes;
// The serialization of recorded FuzzedDataProvider invocations can get to
// long to be stored in one String variable in the template. This is
// mitigated by chunking the data and concatenating it again in the generated
// code.
absl::ByLength chunk_delimiter = absl::ByLength(dataChunkMaxLength);
std::string chunked_base64_data =
absl::StrJoin(absl::StrSplit(base64_data, chunk_delimiter), "\", \"");
std::string reproducer =
absl::Substitute(kBaseReproducer, data_sha1, chunked_base64_data,
FLAGS_target_class, fuzz_target_call);
std::string reproducer_filename = absl::StrFormat("Crash_%s.java", data_sha1);
std::string reproducer_full_path = absl::StrFormat(
"%s%c%s", FLAGS_reproducer_path, kPathSeparator, reproducer_filename);
std::ofstream reproducer_out(reproducer_full_path);
reproducer_out << reproducer;
std::cout << absl::StrFormat(
"reproducer_path='%s'; Java reproducer written to %s",
FLAGS_reproducer_path, reproducer_full_path)
<< std::endl;
}
std::string FuzzTargetRunner::DetectFuzzTargetClass() const {
jclass manifest_utils = jvm_.FindClass(kManifestUtilsClass);
jmethodID detect_fuzz_target_class = jvm_.GetStaticMethodID(
manifest_utils, "detectFuzzTargetClass", "()Ljava/lang/String;", true);
auto &env = jvm_.GetEnv();
auto jni_fuzz_target_class = (jstring)(env.CallStaticObjectMethod(
manifest_utils, detect_fuzz_target_class));
if (env.ExceptionCheck()) {
env.ExceptionDescribe();
exit(1);
}
if (jni_fuzz_target_class == nullptr) return "";
const char *fuzz_target_class_cstr =
env.GetStringUTFChars(jni_fuzz_target_class, nullptr);
std::string fuzz_target_class = std::string(fuzz_target_class_cstr);
env.ReleaseStringUTFChars(jni_fuzz_target_class, fuzz_target_class_cstr);
env.DeleteLocalRef(jni_fuzz_target_class);
return fuzz_target_class;
}
} // namespace jazzer
Refactor FuzzTargetRunner destructor
// Copyright 2021 Code Intelligence GmbH
//
// 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 "fuzz_target_runner.h"
#include <jni.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <string>
#include <vector>
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/str_split.h"
#include "absl/strings/substitute.h"
#include "coverage_tracker.h"
#include "fuzzed_data_provider.h"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "java_reproducer.h"
#include "java_reproducer_templates.h"
#include "utils.h"
DEFINE_string(
target_class, "",
"The Java class that contains the static fuzzerTestOneInput function");
DEFINE_string(target_args, "",
"Arguments passed to fuzzerInitialize as a String array. "
"Separated by space.");
DEFINE_uint32(keep_going, 0,
"Continue fuzzing until N distinct exception stack traces have"
"been encountered. Defaults to exit after the first finding "
"unless --autofuzz is specified.");
DEFINE_bool(dedup, true,
"Emit a dedup token for every finding. Defaults to true and is "
"required for --keep_going and --ignore.");
DEFINE_string(
ignore, "",
"Comma-separated list of crash dedup tokens to ignore. This is useful to "
"continue fuzzing before a crash is fixed.");
DEFINE_string(reproducer_path, ".",
"Path at which fuzzing reproducers are stored. Defaults to the "
"current directory.");
DEFINE_string(coverage_report, "",
"Path at which a coverage report is stored when the fuzzer "
"exits. If left empty, no report is generated (default)");
DEFINE_string(coverage_dump, "",
"Path at which a coverage dump is stored when the fuzzer "
"exits. If left empty, no dump is generated (default)");
DEFINE_string(autofuzz, "",
"Fully qualified reference to a method on the classpath that "
"should be fuzzed automatically (example: System.out::println). "
"Fuzzing will continue even after a finding; specify "
"--keep_going=N to stop after N findings.");
DEFINE_string(autofuzz_ignore, "",
"Fully qualified class names of exceptions to ignore during "
"autofuzz. Separated by comma.");
DECLARE_bool(hooks);
constexpr auto kManifestUtilsClass =
"com/code_intelligence/jazzer/runtime/ManifestUtils";
constexpr auto kJazzerClass =
"com/code_intelligence/jazzer/runtime/JazzerInternal";
constexpr auto kAutofuzzFuzzTargetClass =
"com/code_intelligence/jazzer/autofuzz/FuzzTarget";
// A constant pool CONSTANT_Utf8_info entry should be able to hold data of size
// uint16, but somehow this does not seem to be the case and leads to invalid
// code crash reproducer code. Reducing the size by one resolves the problem.
constexpr auto dataChunkMaxLength = std::numeric_limits<uint16_t>::max() - 1;
namespace jazzer {
// split a string on unescaped spaces
std::vector<std::string> splitOnSpace(const std::string &s) {
if (s.empty()) {
return {};
}
std::vector<std::string> tokens;
std::size_t token_begin = 0;
for (std::size_t i = 1; i < s.size() - 1; i++) {
// only split if the space is not escaped by a backslash "\"
if (s[i] == ' ' && s[i - 1] != '\\') {
// don't split on multiple spaces
if (i > token_begin + 1)
tokens.push_back(s.substr(token_begin, i - token_begin));
token_begin = i + 1;
}
}
tokens.push_back(s.substr(token_begin));
return tokens;
}
FuzzTargetRunner::FuzzTargetRunner(
JVM &jvm, const std::vector<std::string> &additional_target_args)
: ExceptionPrinter(jvm), jvm_(jvm), ignore_tokens_() {
auto &env = jvm.GetEnv();
if (!FLAGS_target_class.empty() && !FLAGS_autofuzz.empty()) {
std::cerr << "--target_class and --autofuzz cannot be specified together"
<< std::endl;
exit(1);
}
if (!FLAGS_target_args.empty() && !FLAGS_autofuzz.empty()) {
std::cerr << "--target_args and --autofuzz cannot be specified together"
<< std::endl;
exit(1);
}
if (FLAGS_autofuzz.empty() && !FLAGS_autofuzz_ignore.empty()) {
std::cerr << "--autofuzz_ignore requires --autofuzz" << std::endl;
exit(1);
}
if (FLAGS_target_class.empty() && FLAGS_autofuzz.empty()) {
FLAGS_target_class = DetectFuzzTargetClass();
}
// If automatically detecting the fuzz target class failed, we expect it as
// the value of the --target_class argument.
if (FLAGS_target_class.empty() && FLAGS_autofuzz.empty()) {
std::cerr << "Missing argument --target_class=<fuzz_target_class>"
<< std::endl;
exit(1);
}
if (!FLAGS_autofuzz.empty()) {
FLAGS_target_class = kAutofuzzFuzzTargetClass;
if (FLAGS_keep_going == 0) {
FLAGS_keep_going = std::numeric_limits<gflags::uint32>::max();
}
// Pass the method reference string as the first argument to the generic
// autofuzz fuzz target. Subseqeuent arguments are interpreted as exception
// class names that should be ignored.
FLAGS_target_args = FLAGS_autofuzz;
if (!FLAGS_autofuzz_ignore.empty()) {
FLAGS_target_args = absl::StrCat(
FLAGS_target_args, " ",
absl::StrReplaceAll(FLAGS_autofuzz_ignore, {{",", " "}}));
}
}
// Set --keep_going to its real default.
if (FLAGS_keep_going == 0) {
FLAGS_keep_going = 1;
}
if ((!FLAGS_ignore.empty() || FLAGS_keep_going > 1) && !FLAGS_dedup) {
std::cerr << "--nodedup is not supported with --ignore or --keep_going"
<< std::endl;
exit(1);
}
jazzer_ = jvm.FindClass(kJazzerClass);
last_finding_ =
env.GetStaticFieldID(jazzer_, "lastFinding", "Ljava/lang/Throwable;");
// Inform the agent about the fuzz target class.
// Important note: This has to be done *before*
// jvm.FindClass(FLAGS_target_class) so that hooks can enable themselves in
// time for the fuzz target's static initializer.
auto on_fuzz_target_ready = jvm.GetStaticMethodID(
jazzer_, "onFuzzTargetReady", "(Ljava/lang/String;)V", true);
jstring fuzz_target_class = env.NewStringUTF(FLAGS_target_class.c_str());
env.CallStaticObjectMethod(jazzer_, on_fuzz_target_ready, fuzz_target_class);
if (env.ExceptionCheck()) {
env.ExceptionDescribe();
return;
}
env.DeleteLocalRef(fuzz_target_class);
try {
jclass_ = jvm.FindClass(FLAGS_target_class);
} catch (const std::runtime_error &error) {
std::cerr << "ERROR: " << error.what() << std::endl;
exit(1);
}
// one of the following functions is required:
// public static void fuzzerTestOneInput(byte[] input)
// public static void fuzzerTestOneInput(FuzzedDataProvider data)
fuzzer_test_one_input_bytes_ =
jvm.GetStaticMethodID(jclass_, "fuzzerTestOneInput", "([B)V", false);
fuzzer_test_one_input_data_ = jvm.GetStaticMethodID(
jclass_, "fuzzerTestOneInput",
"(Lcom/code_intelligence/jazzer/api/FuzzedDataProvider;)V", false);
bool using_bytes = fuzzer_test_one_input_bytes_ != nullptr;
bool using_data = fuzzer_test_one_input_data_ != nullptr;
// Fail if none ore both of the two possible fuzzerTestOneInput versions is
// defined in the class.
if (using_bytes == using_data) {
LOG(ERROR) << FLAGS_target_class
<< " must define exactly one of the following two functions:";
LOG(ERROR) << "public static void fuzzerTestOneInput(byte[] ...)";
LOG(ERROR)
<< "public static void fuzzerTestOneInput(FuzzedDataProvider ...)";
LOG(ERROR) << "Note: Fuzz targets returning boolean are no longer "
"supported; exceptions should be thrown instead of "
"returning true.";
exit(1);
}
// check existence of optional methods for initialization and destruction
fuzzer_initialize_ =
jvm.GetStaticMethodID(jclass_, "fuzzerInitialize", "()V", false);
fuzzer_tear_down_ =
jvm.GetStaticMethodID(jclass_, "fuzzerTearDown", "()V", false);
fuzzer_initialize_with_args_ = jvm.GetStaticMethodID(
jclass_, "fuzzerInitialize", "([Ljava/lang/String;)V", false);
auto fuzz_target_args_tokens = splitOnSpace(FLAGS_target_args);
fuzz_target_args_tokens.insert(fuzz_target_args_tokens.end(),
additional_target_args.begin(),
additional_target_args.end());
if (fuzzer_initialize_with_args_) {
// fuzzerInitialize with arguments gets priority
jclass string_class = jvm.FindClass("java/lang/String");
jobjectArray arg_array = jvm.GetEnv().NewObjectArray(
fuzz_target_args_tokens.size(), string_class, nullptr);
for (jint i = 0; i < fuzz_target_args_tokens.size(); i++) {
jstring str = env.NewStringUTF(fuzz_target_args_tokens[i].c_str());
env.SetObjectArrayElement(arg_array, i, str);
}
env.CallStaticObjectMethod(jclass_, fuzzer_initialize_with_args_,
arg_array);
} else if (fuzzer_initialize_) {
env.CallStaticVoidMethod(jclass_, fuzzer_initialize_);
} else {
LOG(INFO) << "did not call any fuzz target initialize functions";
}
if (jthrowable exception = env.ExceptionOccurred()) {
LOG(ERROR) << "== Java Exception in fuzzerInitialize: ";
LOG(ERROR) << getStackTrace(exception);
std::exit(1);
}
if (FLAGS_hooks) {
CoverageTracker::RecordInitialCoverage(env);
}
SetUpFuzzedDataProvider(jvm_.GetEnv());
// Parse a comma-separated list of hex dedup tokens.
std::vector<std::string> str_ignore_tokens =
absl::StrSplit(FLAGS_ignore, ',');
for (const std::string &str_token : str_ignore_tokens) {
if (str_token.empty()) continue;
try {
ignore_tokens_.push_back(std::stoull(str_token, nullptr, 16));
} catch (...) {
LOG(ERROR) << "Invalid dedup token (expected up to 16 hex digits): '"
<< str_token << "'";
// Don't let libFuzzer print a crash stack trace.
_Exit(1);
}
}
}
FuzzTargetRunner::~FuzzTargetRunner() {
auto &env = jvm_.GetEnv();
if (FLAGS_hooks && !FLAGS_coverage_report.empty()) {
CoverageTracker::ReportCoverage(env, FLAGS_coverage_report);
}
if (FLAGS_hooks && !FLAGS_coverage_dump.empty()) {
CoverageTracker::DumpCoverage(env, FLAGS_coverage_dump);
}
if (fuzzer_tear_down_ != nullptr) {
std::cerr << "calling fuzzer teardown function" << std::endl;
env.CallStaticVoidMethod(jclass_, fuzzer_tear_down_);
if (jthrowable exception = env.ExceptionOccurred()) {
std::cerr << getStackTrace(exception) << std::endl;
_Exit(1);
}
}
}
RunResult FuzzTargetRunner::Run(const uint8_t *data, const std::size_t size) {
auto &env = jvm_.GetEnv();
static std::size_t run_count = 0;
if (run_count < 2 && FLAGS_hooks) {
run_count++;
// For the first two runs only, replay the coverage recorded from static
// initializers. libFuzzer cleared the coverage map after they ran and could
// fail to see any coverage, triggering an early exit, if we don't replay it
// here.
// https://github.com/llvm/llvm-project/blob/957a5e987444d3193575d6ad8afe6c75da00d794/compiler-rt/lib/fuzzer/FuzzerLoop.cpp#L804-L809
CoverageTracker::ReplayInitialCoverage(env);
}
if (fuzzer_test_one_input_data_ != nullptr) {
FeedFuzzedDataProvider(data, size);
env.CallStaticVoidMethod(jclass_, fuzzer_test_one_input_data_,
GetFuzzedDataProviderJavaObject(jvm_));
} else {
jbyteArray byte_array = env.NewByteArray(size);
if (byte_array == nullptr) {
env.ExceptionDescribe();
throw std::runtime_error(std::string("Cannot create byte array"));
}
env.SetByteArrayRegion(byte_array, 0, size,
reinterpret_cast<const jbyte *>(data));
env.CallStaticVoidMethod(jclass_, fuzzer_test_one_input_bytes_, byte_array);
env.DeleteLocalRef(byte_array);
}
const auto finding = GetFinding();
if (finding != nullptr) {
jlong dedup_token = computeDedupToken(finding);
// Check whether this stack trace has been encountered before if
// `--keep_going` has been supplied.
if (dedup_token != 0 && FLAGS_keep_going > 1 &&
std::find(ignore_tokens_.cbegin(), ignore_tokens_.cend(),
dedup_token) != ignore_tokens_.end()) {
env.DeleteLocalRef(finding);
return RunResult::kOk;
} else {
ignore_tokens_.push_back(dedup_token);
std::cout << std::endl;
std::cerr << "== Java Exception: " << getStackTrace(finding);
env.DeleteLocalRef(finding);
if (FLAGS_dedup) {
std::cout << "DEDUP_TOKEN: " << std::hex << std::setfill('0')
<< std::setw(16) << dedup_token << std::endl;
}
if (ignore_tokens_.size() < static_cast<std::size_t>(FLAGS_keep_going)) {
return RunResult::kDumpAndContinue;
} else {
return RunResult::kException;
}
}
}
return RunResult::kOk;
}
// Returns a fuzzer finding as a Throwable (or nullptr if there is none),
// clearing any JVM exceptions in the process.
jthrowable FuzzTargetRunner::GetFinding() const {
auto &env = jvm_.GetEnv();
jthrowable unprocessed_finding = nullptr;
if (env.ExceptionCheck()) {
unprocessed_finding = env.ExceptionOccurred();
env.ExceptionClear();
}
// Explicitly reported findings take precedence over uncaught exceptions.
if (auto reported_finding =
(jthrowable)env.GetStaticObjectField(jazzer_, last_finding_);
reported_finding != nullptr) {
env.DeleteLocalRef(unprocessed_finding);
unprocessed_finding = reported_finding;
}
jthrowable processed_finding = preprocessException(unprocessed_finding);
env.DeleteLocalRef(unprocessed_finding);
return processed_finding;
}
void FuzzTargetRunner::DumpReproducer(const uint8_t *data, std::size_t size) {
auto &env = jvm_.GetEnv();
std::string data_sha1 = jazzer::Sha1Hash(data, size);
if (!FLAGS_autofuzz.empty()) {
auto autofuzz_fuzz_target_class = env.FindClass(kAutofuzzFuzzTargetClass);
if (env.ExceptionCheck()) {
env.ExceptionDescribe();
return;
}
auto dump_reproducer = env.GetStaticMethodID(
autofuzz_fuzz_target_class, "dumpReproducer",
"(Lcom/code_intelligence/jazzer/api/FuzzedDataProvider;Ljava/lang/"
"String;Ljava/lang/String;)V");
if (env.ExceptionCheck()) {
env.ExceptionDescribe();
return;
}
FeedFuzzedDataProvider(data, size);
auto reproducer_path_jni = env.NewStringUTF(FLAGS_reproducer_path.c_str());
auto data_sha1_jni = env.NewStringUTF(data_sha1.c_str());
env.CallStaticVoidMethod(autofuzz_fuzz_target_class, dump_reproducer,
GetFuzzedDataProviderJavaObject(jvm_),
reproducer_path_jni, data_sha1_jni);
if (env.ExceptionCheck()) {
env.ExceptionDescribe();
return;
}
env.DeleteLocalRef(data_sha1_jni);
env.DeleteLocalRef(reproducer_path_jni);
return;
}
std::string base64_data;
if (fuzzer_test_one_input_data_) {
// Record the data retrieved from the FuzzedDataProvider and supply it to a
// Java-only CannedFuzzedDataProvider in the reproducer.
FeedFuzzedDataProvider(data, size);
jobject recorder = GetRecordingFuzzedDataProviderJavaObject(jvm_);
env.CallStaticVoidMethod(jclass_, fuzzer_test_one_input_data_, recorder);
const auto finding = GetFinding();
if (finding == nullptr) {
LOG(ERROR) << "Failed to reproduce crash when rerunning with recorder";
return;
}
base64_data = SerializeRecordingFuzzedDataProvider(jvm_, recorder);
} else {
absl::string_view data_str(reinterpret_cast<const char *>(data), size);
absl::Base64Escape(data_str, &base64_data);
}
const char *fuzz_target_call = fuzzer_test_one_input_data_
? kTestOneInputWithData
: kTestOneInputWithBytes;
// The serialization of recorded FuzzedDataProvider invocations can get to
// long to be stored in one String variable in the template. This is
// mitigated by chunking the data and concatenating it again in the generated
// code.
absl::ByLength chunk_delimiter = absl::ByLength(dataChunkMaxLength);
std::string chunked_base64_data =
absl::StrJoin(absl::StrSplit(base64_data, chunk_delimiter), "\", \"");
std::string reproducer =
absl::Substitute(kBaseReproducer, data_sha1, chunked_base64_data,
FLAGS_target_class, fuzz_target_call);
std::string reproducer_filename = absl::StrFormat("Crash_%s.java", data_sha1);
std::string reproducer_full_path = absl::StrFormat(
"%s%c%s", FLAGS_reproducer_path, kPathSeparator, reproducer_filename);
std::ofstream reproducer_out(reproducer_full_path);
reproducer_out << reproducer;
std::cout << absl::StrFormat(
"reproducer_path='%s'; Java reproducer written to %s",
FLAGS_reproducer_path, reproducer_full_path)
<< std::endl;
}
std::string FuzzTargetRunner::DetectFuzzTargetClass() const {
jclass manifest_utils = jvm_.FindClass(kManifestUtilsClass);
jmethodID detect_fuzz_target_class = jvm_.GetStaticMethodID(
manifest_utils, "detectFuzzTargetClass", "()Ljava/lang/String;", true);
auto &env = jvm_.GetEnv();
auto jni_fuzz_target_class = (jstring)(env.CallStaticObjectMethod(
manifest_utils, detect_fuzz_target_class));
if (env.ExceptionCheck()) {
env.ExceptionDescribe();
exit(1);
}
if (jni_fuzz_target_class == nullptr) return "";
const char *fuzz_target_class_cstr =
env.GetStringUTFChars(jni_fuzz_target_class, nullptr);
std::string fuzz_target_class = std::string(fuzz_target_class_cstr);
env.ReleaseStringUTFChars(jni_fuzz_target_class, fuzz_target_class_cstr);
env.DeleteLocalRef(jni_fuzz_target_class);
return fuzz_target_class;
}
} // namespace jazzer
|
//
// ModifiedRenderingExample.cpp
// ExampleApp
//
// Created by eeGeo on 03/05/2013.
// Copyright (c) 2013 eeGeo. All rights reserved.
//
#include "ModifiedRenderingExample.h"
#include "PooledMesh.h"
#include "IStreamingVolume.h"
#include "DiffuseTexturedVertex.h"
#include "MathsHelpers.h"
#include "IInterestPointProvider.h"
#include "CameraHelpers.h"
using namespace Eegeo;
using namespace Eegeo::Rendering;
namespace Examples
{
ModifiedRenderingExample::ModifiedRenderingExample(RenderContext& renderContext,
Eegeo::Camera::ICameraProvider& cameraProvider,
Eegeo::Location::IInterestPointProvider& interestPointProvider,
Eegeo::Streaming::IStreamingVolume& visibleVolume,
Eegeo::Lighting::GlobalLighting& lighting,
Eegeo::Resources::MeshPool<Eegeo::Rendering::RenderableItem*>& buildingPool,
Eegeo::Resources::MeshPool<Eegeo::Rendering::RenderableItem*>& shadowPool)
:renderContext(renderContext)
,cameraProvider(cameraProvider)
,interestPointProvider(interestPointProvider)
,visibleVolume(visibleVolume)
,buildingPool(buildingPool)
,shadowPool(shadowPool)
,lighting(lighting)
,pCriteria(NULL)
{
}
void ModifiedRenderingExample::Start()
{
//MyPoolFilterCriteria implemented below... uses camera interest point as selection criteria
pCriteria = new ModifiedRenderingExample::MyPoolFilterCriteria(this);
//apply to pools, but lifetime responsibility is ours
buildingPool.SetFilterCriteria(pCriteria);
shadowPool.SetFilterCriteria(pCriteria);
}
void ModifiedRenderingExample::Suspend()
{
//remove it from the pools, and destroy the criteria
buildingPool.SetFilterCriteria(NULL);
shadowPool.SetFilterCriteria(NULL);
delete pCriteria;
pCriteria = NULL;
}
void ModifiedRenderingExample::Update()
{
}
void ModifiedRenderingExample::Draw()
{
//i want to draw the buildings matching the criteria a flat color and transparent...
//if shadows match the filter criteria, just don't draw them
//
//if the buildings match, DrawItems uses my shader and sets state to draw transparently
typedef Eegeo::Resources::PooledMesh<RenderableItem*>* TPooledMeshPtr;
typedef Eegeo::DataStructures::PoolEntry<TPooledMeshPtr> TPoolEntry;
typedef std::vector<TPoolEntry> TResVec;
TResVec filtered;
buildingPool.GetEntriesMeetingFilterCriteria(filtered);
std::vector<RenderableItem*> toRender;
for(TResVec::const_iterator it = filtered.begin(); it != filtered.end(); ++ it)
{
const TPoolEntry& item = *it;
RenderableItem* resource = item.instance->GetResource();
if(item.allocated && resource != NULL && item.instance->ShouldDraw())
{
toRender.push_back(resource);
}
}
//ok, the toRender items were not drawn by the platform, so I should draw them now
DrawItems(toRender);
}
void ModifiedRenderingExample::DrawItems(const std::vector<Eegeo::Rendering::RenderableItem*>& items)
{
GLState& glState = renderContext.GetGLState();
std::vector<Eegeo::Culling::IndexBufferRange> rangesToDraw;
if (glState.UseProgram.TrySet(shader.ProgramHandle))
{
const Eegeo::m44 &colors = lighting.GetColors();
Eegeo_GL(glUniformMatrix4fv(shader.LightColorsUniform, 1, 0, (const GLfloat*)&colors));
}
for(std::vector<RenderableItem*>::const_iterator it = items.begin(); it != items.end(); ++ it)
{
RenderableItem* item = *it;
if(item->IndexCount() == 0) {
continue;
}
//semt-transparent, so we're gonna be blending
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
Eegeo::v3 cameraLocalPos = Eegeo::Camera::CameraHelpers::CameraRelativePoint(item->GetEcefPosition(), renderContext.GetCameraOriginEcef());
Eegeo::m44 model, mvp;
Helpers::MathsHelpers::ComputeScaleAndOffset(model, 1.0f, item->GetEcefPosition().Norm().ToSingle(), cameraLocalPos);
Eegeo::m44::Mul(mvp, renderContext.GetViewProjectionMatrix(), model);
Eegeo_GL(glUniformMatrix4fv(shader.ModelViewProjectionUniform, 1, 0, (const GLfloat*)&mvp))
Eegeo_GL(glUniform3f(shader.MinVertRangeUniform,
item->GetMinVertexRange().GetX(),
item->GetMinVertexRange().GetY(),
item->GetMinVertexRange().GetZ()));
Eegeo_GL(glUniform3f(shader.MaxVertRangeUniform,
item->GetMaxVertexRange().GetX(),
item->GetMaxVertexRange().GetY(),
item->GetMaxVertexRange().GetZ()));
Eegeo_GL(glUniform4f(shader.DiffuseColorUniform, 0.0f, 0.0f, 1.0f, 0.1f)); //alpha 10%
Eegeo_GL(glEnableVertexAttribArray(shader.PositionAttribute));
Eegeo_GL(glEnableVertexAttribArray(shader.LightDotAttribute));
glState.BindArrayBuffer(item->GetVertexBuffer());
glState.BindElementArrayBuffer(item->GetIndexBuffer());
//i don't need the UV channel as not texturing them, but it is part of the buulding vertex so must be considered
Eegeo_GL(glVertexAttribPointer(shader.PositionAttribute, 3, GL_UNSIGNED_SHORT, GL_TRUE, sizeof(ShortDiffuseTexturedVertex), 0));
Eegeo_GL(glVertexAttribPointer(shader.LightDotAttribute, 1, GL_FLOAT, GL_FALSE, sizeof(ShortDiffuseTexturedVertex), (GLvoid*) (sizeof(short)*6)));
Eegeo_GL(glDrawElements(GL_TRIANGLES, item->IndexCount(), GL_UNSIGNED_SHORT, (void*)0 ));
}
glDisable(GL_BLEND);
glState.BindArrayBuffer(0);
glState.BindElementArrayBuffer(0);
}
bool ModifiedRenderingExample::MyPoolFilterCriteria::operator()(Eegeo::Rendering::RenderableItem* item)
{
const double filterRadius = 400.0f;
const double filterRadiusSq = filterRadius*filterRadius;
Eegeo::v3 cameraRelativePos = Eegeo::Camera::CameraHelpers::CameraRelativePoint(item->GetEcefPosition(), owner->interestPointProvider.GetEcefInterestPoint());
double delta = cameraRelativePos.LengthSq();
bool closeToInterest = delta < filterRadiusSq;
if (closeToInterest)
{
return true; //i want to draw with custom semi-transparent rendering method
}
return false; //let the platform do the default rendering
}
}
Fix for move of vertex types in platform. Buddy:Jonty
//
// ModifiedRenderingExample.cpp
// ExampleApp
//
// Created by eeGeo on 03/05/2013.
// Copyright (c) 2013 eeGeo. All rights reserved.
//
#include "ModifiedRenderingExample.h"
#include "PooledMesh.h"
#include "IStreamingVolume.h"
#include "DiffuseTexturedVertex.h"
#include "MathsHelpers.h"
#include "IInterestPointProvider.h"
#include "CameraHelpers.h"
using namespace Eegeo;
using namespace Eegeo::Rendering;
namespace Examples
{
ModifiedRenderingExample::ModifiedRenderingExample(RenderContext& renderContext,
Eegeo::Camera::ICameraProvider& cameraProvider,
Eegeo::Location::IInterestPointProvider& interestPointProvider,
Eegeo::Streaming::IStreamingVolume& visibleVolume,
Eegeo::Lighting::GlobalLighting& lighting,
Eegeo::Resources::MeshPool<Eegeo::Rendering::RenderableItem*>& buildingPool,
Eegeo::Resources::MeshPool<Eegeo::Rendering::RenderableItem*>& shadowPool)
:renderContext(renderContext)
,cameraProvider(cameraProvider)
,interestPointProvider(interestPointProvider)
,visibleVolume(visibleVolume)
,buildingPool(buildingPool)
,shadowPool(shadowPool)
,lighting(lighting)
,pCriteria(NULL)
{
}
void ModifiedRenderingExample::Start()
{
//MyPoolFilterCriteria implemented below... uses camera interest point as selection criteria
pCriteria = new ModifiedRenderingExample::MyPoolFilterCriteria(this);
//apply to pools, but lifetime responsibility is ours
buildingPool.SetFilterCriteria(pCriteria);
shadowPool.SetFilterCriteria(pCriteria);
}
void ModifiedRenderingExample::Suspend()
{
//remove it from the pools, and destroy the criteria
buildingPool.SetFilterCriteria(NULL);
shadowPool.SetFilterCriteria(NULL);
delete pCriteria;
pCriteria = NULL;
}
void ModifiedRenderingExample::Update()
{
}
void ModifiedRenderingExample::Draw()
{
//i want to draw the buildings matching the criteria a flat color and transparent...
//if shadows match the filter criteria, just don't draw them
//
//if the buildings match, DrawItems uses my shader and sets state to draw transparently
typedef Eegeo::Resources::PooledMesh<RenderableItem*>* TPooledMeshPtr;
typedef Eegeo::DataStructures::PoolEntry<TPooledMeshPtr> TPoolEntry;
typedef std::vector<TPoolEntry> TResVec;
TResVec filtered;
buildingPool.GetEntriesMeetingFilterCriteria(filtered);
std::vector<RenderableItem*> toRender;
for(TResVec::const_iterator it = filtered.begin(); it != filtered.end(); ++ it)
{
const TPoolEntry& item = *it;
RenderableItem* resource = item.instance->GetResource();
if(item.allocated && resource != NULL && item.instance->ShouldDraw())
{
toRender.push_back(resource);
}
}
//ok, the toRender items were not drawn by the platform, so I should draw them now
DrawItems(toRender);
}
void ModifiedRenderingExample::DrawItems(const std::vector<Eegeo::Rendering::RenderableItem*>& items)
{
GLState& glState = renderContext.GetGLState();
std::vector<Eegeo::Culling::IndexBufferRange> rangesToDraw;
if (glState.UseProgram.TrySet(shader.ProgramHandle))
{
const Eegeo::m44 &colors = lighting.GetColors();
Eegeo_GL(glUniformMatrix4fv(shader.LightColorsUniform, 1, 0, (const GLfloat*)&colors));
}
for(std::vector<RenderableItem*>::const_iterator it = items.begin(); it != items.end(); ++ it)
{
RenderableItem* item = *it;
if(item->IndexCount() == 0) {
continue;
}
//semt-transparent, so we're gonna be blending
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
Eegeo::v3 cameraLocalPos = Eegeo::Camera::CameraHelpers::CameraRelativePoint(item->GetEcefPosition(), renderContext.GetCameraOriginEcef());
Eegeo::m44 model, mvp;
Helpers::MathsHelpers::ComputeScaleAndOffset(model, 1.0f, item->GetEcefPosition().Norm().ToSingle(), cameraLocalPos);
Eegeo::m44::Mul(mvp, renderContext.GetViewProjectionMatrix(), model);
Eegeo_GL(glUniformMatrix4fv(shader.ModelViewProjectionUniform, 1, 0, (const GLfloat*)&mvp))
Eegeo_GL(glUniform3f(shader.MinVertRangeUniform,
item->GetMinVertexRange().GetX(),
item->GetMinVertexRange().GetY(),
item->GetMinVertexRange().GetZ()));
Eegeo_GL(glUniform3f(shader.MaxVertRangeUniform,
item->GetMaxVertexRange().GetX(),
item->GetMaxVertexRange().GetY(),
item->GetMaxVertexRange().GetZ()));
Eegeo_GL(glUniform4f(shader.DiffuseColorUniform, 0.0f, 0.0f, 1.0f, 0.1f)); //alpha 10%
Eegeo_GL(glEnableVertexAttribArray(shader.PositionAttribute));
Eegeo_GL(glEnableVertexAttribArray(shader.LightDotAttribute));
glState.BindArrayBuffer(item->GetVertexBuffer());
glState.BindElementArrayBuffer(item->GetIndexBuffer());
//i don't need the UV channel as not texturing them, but it is part of the buulding vertex so must be considered
Eegeo_GL(glVertexAttribPointer(shader.PositionAttribute, 3, GL_UNSIGNED_SHORT, GL_TRUE, sizeof(VertexTypes::ShortDiffuseTexturedVertex), 0));
Eegeo_GL(glVertexAttribPointer(shader.LightDotAttribute, 1, GL_FLOAT, GL_FALSE, sizeof(VertexTypes::ShortDiffuseTexturedVertex), (GLvoid*) (sizeof(short)*6)));
Eegeo_GL(glDrawElements(GL_TRIANGLES, item->IndexCount(), GL_UNSIGNED_SHORT, (void*)0 ));
}
glDisable(GL_BLEND);
glState.BindArrayBuffer(0);
glState.BindElementArrayBuffer(0);
}
bool ModifiedRenderingExample::MyPoolFilterCriteria::operator()(Eegeo::Rendering::RenderableItem* item)
{
const double filterRadius = 400.0f;
const double filterRadiusSq = filterRadius*filterRadius;
Eegeo::v3 cameraRelativePos = Eegeo::Camera::CameraHelpers::CameraRelativePoint(item->GetEcefPosition(), owner->interestPointProvider.GetEcefInterestPoint());
double delta = cameraRelativePos.LengthSq();
bool closeToInterest = delta < filterRadiusSq;
if (closeToInterest)
{
return true; //i want to draw with custom semi-transparent rendering method
}
return false; //let the platform do the default rendering
}
} |
#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkCommand.h"
#include "vtkImageData.h"
#include "vtkImagePlaneWidget.h"
#include "vtkInteractorEventRecorder.h"
#include "vtkKochanekSpline.h"
#include "vtkOutlineFilter.h"
#include "vtkPlaneSource.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkPolyDataMapper.h"
#include "vtkProbeFilter.h"
#include "vtkProperty.h"
#include "vtkProperty2D.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkSplineWidget.h"
#include "vtkTextProperty.h"
#include "vtkVolume16Reader.h"
#include "vtkXYPlotActor.h"
#include "vtkRegressionTestImage.h"
#include "vtkDebugLeaks.h"
char TSWeventLog[] =
"# StreamVersion 1\n"
"CharEvent 133 125 0 0 98 1 i\n"
"KeyReleaseEvent 133 125 0 0 98 1 i\n"
"MouseMoveEvent 133 125 0 0 0 0 i\n"
"RightButtonPressEvent 133 125 0 0 0 0 i\n"
"MouseMoveEvent 133 123 0 0 0 0 i\n"
"MouseMoveEvent 133 119 0 0 0 0 i\n"
"MouseMoveEvent 132 115 0 0 0 0 i\n"
"MouseMoveEvent 132 111 0 0 0 0 i\n"
"MouseMoveEvent 132 107 0 0 0 0 i\n"
"RightButtonReleaseEvent 132 107 0 0 0 0 i\n"
"MouseMoveEvent 132 129 0 0 0 0 i\n"
"LeftButtonPressEvent 132 129 0 0 0 0 i\n"
"MouseMoveEvent 132 130 0 0 0 0 i\n"
"MouseMoveEvent 132 135 0 0 0 0 i\n"
"MouseMoveEvent 132 143 0 0 0 0 i\n"
"MouseMoveEvent 131 152 0 0 0 0 i\n"
"MouseMoveEvent 130 159 0 0 0 0 i\n"
"MouseMoveEvent 129 165 0 0 0 0 i\n"
"MouseMoveEvent 127 170 0 0 0 0 i\n"
"MouseMoveEvent 125 176 0 0 0 0 i\n"
"MouseMoveEvent 124 181 0 0 0 0 i\n"
"MouseMoveEvent 122 183 0 0 0 0 i\n"
"LeftButtonReleaseEvent 122 183 0 0 0 0 i\n"
"MouseMoveEvent 133 163 0 0 0 0 i\n"
"MiddleButtonPressEvent 133 163 0 0 0 0 i\n"
"MouseMoveEvent 132 161 0 0 0 0 i\n"
"MouseMoveEvent 128 158 0 0 0 0 i\n"
"MouseMoveEvent 124 155 0 0 0 0 i\n"
"MouseMoveEvent 120 151 0 0 0 0 i\n"
"MouseMoveEvent 116 147 0 0 0 0 i\n"
"MouseMoveEvent 118 146 0 0 0 0 i\n"
"MouseMoveEvent 121 148 0 0 0 0 i\n"
"MouseMoveEvent 123 150 0 0 0 0 i\n"
"MouseMoveEvent 125 154 0 0 0 0 i\n"
"MouseMoveEvent 129 158 0 0 0 0 i\n"
"MouseMoveEvent 132 161 0 0 0 0 i\n"
"MouseMoveEvent 134 165 0 0 0 0 i\n"
"MouseMoveEvent 136 168 0 0 0 0 i\n"
"MiddleButtonReleaseEvent 136 168 0 0 0 0 i\n"
"MouseMoveEvent 178 186 0 0 0 0 i\n"
"KeyPressEvent 178 186 -128 0 0 1 Control_L\n"
"MiddleButtonPressEvent 178 186 8 0 0 0 Control_L\n"
"MouseMoveEvent 178 185 8 0 0 0 Control_L\n"
"MouseMoveEvent 179 183 8 0 0 0 Control_L\n"
"MouseMoveEvent 179 181 8 0 0 0 Control_L\n"
"MouseMoveEvent 179 179 8 0 0 0 Control_L\n"
"MouseMoveEvent 179 177 8 0 0 0 Control_L\n"
"MouseMoveEvent 179 175 8 0 0 0 Control_L\n"
"MouseMoveEvent 179 173 8 0 0 0 Control_L\n"
"MouseMoveEvent 179 171 8 0 0 0 Control_L\n"
"MouseMoveEvent 177 169 8 0 0 0 Control_L\n"
"MouseMoveEvent 176 167 8 0 0 0 Control_L\n"
"MouseMoveEvent 174 165 8 0 0 0 Control_L\n"
"MouseMoveEvent 172 164 8 0 0 0 Control_L\n"
"MouseMoveEvent 171 163 8 0 0 0 Control_L\n"
"MiddleButtonReleaseEvent 171 163 8 0 0 0 Control_L\n"
"KeyReleaseEvent 171 163 0 0 0 1 Control_L\n"
"MouseMoveEvent 170 167 0 0 0 0 Control_L\n"
"MiddleButtonPressEvent 170 167 0 0 0 0 Control_L\n"
"MouseMoveEvent 172 167 0 0 0 0 Control_L\n"
"MouseMoveEvent 176 167 0 0 0 0 Control_L\n"
"MouseMoveEvent 181 167 0 0 0 0 Control_L\n"
"MouseMoveEvent 188 167 0 0 0 0 Control_L\n"
"MouseMoveEvent 198 165 0 0 0 0 Control_L\n"
"MouseMoveEvent 205 163 0 0 0 0 Control_L\n"
"MouseMoveEvent 211 161 0 0 0 0 Control_L\n"
"MouseMoveEvent 216 160 0 0 0 0 Control_L\n"
"MouseMoveEvent 222 158 0 0 0 0 Control_L\n"
"MiddleButtonReleaseEvent 222 158 0 0 0 0 Control_L\n"
"MouseMoveEvent 230 158 0 0 0 0 Control_L\n"
"MiddleButtonPressEvent 230 158 0 0 0 0 Control_L\n"
"MouseMoveEvent 229 156 0 0 0 0 Control_L\n"
"MouseMoveEvent 228 153 0 0 0 0 Control_L\n"
"MouseMoveEvent 226 150 0 0 0 0 Control_L\n"
"MouseMoveEvent 224 148 0 0 0 0 Control_L\n"
"MouseMoveEvent 222 145 0 0 0 0 Control_L\n"
"MouseMoveEvent 220 141 0 0 0 0 Control_L\n"
"MouseMoveEvent 216 135 0 0 0 0 Control_L\n"
"MouseMoveEvent 214 129 0 0 0 0 Control_L\n"
"MouseMoveEvent 212 123 0 0 0 0 Control_L\n"
"MouseMoveEvent 209 118 0 0 0 0 Control_L\n"
"MouseMoveEvent 207 113 0 0 0 0 Control_L\n"
"MouseMoveEvent 204 109 0 0 0 0 Control_L\n"
"MouseMoveEvent 202 105 0 0 0 0 Control_L\n"
"MouseMoveEvent 200 103 0 0 0 0 Control_L\n"
"MouseMoveEvent 198 99 0 0 0 0 Control_L\n"
"MouseMoveEvent 196 97 0 0 0 0 Control_L\n"
"MouseMoveEvent 194 93 0 0 0 0 Control_L\n"
"MiddleButtonReleaseEvent 194 93 0 0 0 0 Control_L\n"
"MouseMoveEvent 254 98 0 0 0 0 Control_L\n"
"MiddleButtonPressEvent 254 98 0 0 0 0 Control_L\n"
"MouseMoveEvent 254 100 0 0 0 0 Control_L\n"
"MouseMoveEvent 254 104 0 0 0 0 Control_L\n"
"MouseMoveEvent 255 108 0 0 0 0 Control_L\n"
"MouseMoveEvent 255 112 0 0 0 0 Control_L\n"
"MouseMoveEvent 255 116 0 0 0 0 Control_L\n"
"MouseMoveEvent 255 120 0 0 0 0 Control_L\n"
"MouseMoveEvent 256 124 0 0 0 0 Control_L\n"
"MouseMoveEvent 257 128 0 0 0 0 Control_L\n"
"MouseMoveEvent 257 132 0 0 0 0 Control_L\n"
"MouseMoveEvent 257 136 0 0 0 0 Control_L\n"
"MouseMoveEvent 258 141 0 0 0 0 Control_L\n"
"MouseMoveEvent 258 146 0 0 0 0 Control_L\n"
"MouseMoveEvent 258 151 0 0 0 0 Control_L\n"
"MouseMoveEvent 258 157 0 0 0 0 Control_L\n"
"MouseMoveEvent 258 159 0 0 0 0 Control_L\n"
"MiddleButtonReleaseEvent 80 206 0 0 0 0 Control_L\n"
;
// Callback for the image plane widget interaction
class vtkIPWCallback : public vtkCommand
{
public:
static vtkIPWCallback *New()
{ return new vtkIPWCallback; }
virtual void Execute(vtkObject *caller, unsigned long, void*)
{
vtkImagePlaneWidget *planeWidget = reinterpret_cast<vtkImagePlaneWidget*>(caller);
if(planeWidget->GetPlaneOrientation() == 3)
{
Spline->SetProjectionPosition(0);
}
else
{
Spline->SetProjectionPosition(planeWidget->GetSlicePosition());
}
Spline->GetPolyData(Poly);
}
vtkIPWCallback():Spline(0),Poly(0){};
vtkSplineWidget* Spline;
vtkPolyData* Poly;
};
// Callback for the spline widget interaction
class vtkSWCallback : public vtkCommand
{
public:
static vtkSWCallback *New()
{ return new vtkSWCallback; }
virtual void Execute(vtkObject *caller, unsigned long, void*)
{
vtkSplineWidget *spline = reinterpret_cast<vtkSplineWidget*>(caller);
spline->GetPolyData(Poly);
}
vtkSWCallback():Poly(0){};
vtkPolyData* Poly;
};
int TestSplineWidget( int argc, char *argv[] )
{
char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/headsq/quarter");
vtkVolume16Reader* v16 = vtkVolume16Reader::New();
v16->SetDataDimensions( 64, 64);
v16->SetDataByteOrderToLittleEndian();
v16->SetImageRange( 1, 93);
v16->SetDataSpacing( 3.2, 3.2, 1.5);
v16->SetFilePrefix( fname);
v16->SetDataMask( 0x7fff);
v16->Update();
delete[] fname;
vtkRenderer* ren1 = vtkRenderer::New();
vtkRenderer* ren2 = vtkRenderer::New();
vtkRenderWindow* renWin = vtkRenderWindow::New();
renWin->AddRenderer( ren1);
renWin->AddRenderer( ren2);
vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow( renWin);
vtkOutlineFilter* outline = vtkOutlineFilter::New();
outline->SetInput(v16->GetOutput());
vtkPolyDataMapper* outlineMapper = vtkPolyDataMapper::New();
outlineMapper->SetInput(outline->GetOutput());
vtkActor* outlineActor = vtkActor::New();
outlineActor->SetMapper(outlineMapper);
vtkImagePlaneWidget* ipw = vtkImagePlaneWidget::New();
ipw->DisplayTextOn();
ipw->TextureInterpolateOff();
ipw->SetInput(v16->GetOutput());
ipw->SetKeyPressActivationValue('x');
ipw->SetResliceInterpolateToNearestNeighbour();
ipw->SetInteractor(iren);
ipw->SetPlaneOrientationToXAxes();
ipw->SetSliceIndex(32);
ipw->GetPlaneProperty()->SetColor(1,0,0);
vtkSplineWidget* spline = vtkSplineWidget::New();
spline->SetInteractor( iren);
spline->SetInput(v16->GetOutput());
spline->SetPriority(1.0);
spline->PlaceWidget();
spline->ProjectToPlaneOn();
spline->SetProjectionNormal(0);
spline->SetProjectionPosition(102.4); //initial plane oriented position
spline->SetProjectionNormal(3); //allow arbitrary oblique orientations
spline->SetPlaneSource((vtkPlaneSource*)ipw->GetPolyDataSource());
// Specify the type of spline (change from default vtkCardinalSpline)
vtkKochanekSpline* xspline = vtkKochanekSpline::New();
vtkKochanekSpline* yspline = vtkKochanekSpline::New();
vtkKochanekSpline* zspline = vtkKochanekSpline::New();
spline->SetXSpline(xspline);
spline->SetYSpline(yspline);
spline->SetZSpline(zspline);
xspline->Delete();
yspline->Delete();
zspline->Delete();
vtkPolyData* poly = vtkPolyData::New();
spline->GetPolyData(poly);
vtkProbeFilter* probe = vtkProbeFilter::New();
probe->SetInput(poly);
probe->SetSource(v16->GetOutput());
vtkIPWCallback* ipwcb = vtkIPWCallback::New();
ipwcb->Spline = spline;
ipwcb->Poly = poly;
ipw->AddObserver(vtkCommand::InteractionEvent,ipwcb);
vtkSWCallback* swcb = vtkSWCallback::New();
swcb->Poly = poly;
spline->AddObserver(vtkCommand::InteractionEvent,swcb);
vtkImageData* data = v16->GetOutput();
float* range = data->GetPointData()->GetScalars()->GetRange();
vtkXYPlotActor* profile = vtkXYPlotActor::New();
profile->AddInput(probe->GetOutput());
profile->GetPositionCoordinate()->SetValue( 0.05, 0.05, 0);
profile->GetPosition2Coordinate()->SetValue( 0.95, 0.95, 0);
profile->SetXValuesToNormalizedArcLength();
profile->SetNumberOfXLabels( 6);
profile->SetTitle( "Profile Data ");
profile->SetXTitle( "s");
profile->SetYTitle( "I(s)");
profile->SetXRange( 0, 1);
profile->SetYRange( range[0], range[1]);
profile->GetProperty()->SetColor( 0, 0, 0);
profile->GetProperty()->SetLineWidth( 2);
profile->SetLabelFormat("%g");
vtkTextProperty* tprop = profile->GetTitleTextProperty();
tprop->SetColor(0.02,0.06,0.62);
tprop->SetFontFamilyToArial();
profile->SetAxisTitleTextProperty(tprop);
profile->SetAxisLabelTextProperty(tprop);
profile->SetTitleTextProperty(tprop);
ren1->SetBackground( 0.1, 0.2, 0.4);
ren1->SetViewport( 0, 0, 0.5, 1);
ren1->AddActor(outlineActor);
ren2->SetBackground( 1, 1, 1);
ren2->SetViewport( 0.5, 0, 1, 1);
ren2->AddActor2D( profile);
renWin->SetSize( 600, 300);
ipw->On();
ipw->SetInteraction(0);
ipw->SetInteraction(1);
spline->On();
spline->SetNumberOfHandles(4);
spline->SetNumberOfHandles(5);
spline->SetResolution(399);
// Set up an interesting viewpoint
vtkCamera* camera = ren1->GetActiveCamera();
camera->Elevation(110);
camera->SetViewUp(0, 0, -1);
camera->Azimuth(45);
ren1->ResetCameraClippingRange();
// Position the actors
renWin->Render();
iren->SetEventPosition(200,200);
iren->SetKeyCode('r');
iren->InvokeEvent(vtkCommand::CharEvent,NULL);
ren1->ResetCameraClippingRange();
renWin->Render();
iren->SetKeyCode('t');
iren->InvokeEvent(vtkCommand::CharEvent,NULL);
// Playback recorded events
vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New();
recorder->SetInteractor(iren);
recorder->ReadFromInputStringOn();
recorder->SetInputString(TSWeventLog);
// Render the image
iren->Initialize();
renWin->Render();
recorder->Play();
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
// Clean up
recorder->Off();
recorder->Delete();
outlineActor->Delete();
outlineMapper->Delete();
outline->Delete();
renWin->Delete();
ren1->Delete();
ren2->Delete();
iren->Delete();
ipw->RemoveObserver(ipwcb);
ipw->Delete();
ipwcb->Delete();
spline->RemoveObserver(swcb);
spline->Delete();
swcb->Delete();
poly->Delete();
probe->Delete();
profile->Delete();
v16->Delete();
return !retVal;
}
ENH: increasing coverage for vtkInteractorObserver, vtkImagePlaneWidget, vtkSplineWidget
#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkCommand.h"
#include "vtkImageData.h"
#include "vtkImagePlaneWidget.h"
#include "vtkInteractorEventRecorder.h"
#include "vtkKochanekSpline.h"
#include "vtkOutlineFilter.h"
#include "vtkPlaneSource.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkPolyDataMapper.h"
#include "vtkProbeFilter.h"
#include "vtkProperty.h"
#include "vtkProperty2D.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkSplineWidget.h"
#include "vtkTextProperty.h"
#include "vtkVolume16Reader.h"
#include "vtkXYPlotActor.h"
#include "vtkRegressionTestImage.h"
#include "vtkDebugLeaks.h"
char TSWeventLog[] =
"# StreamVersion 1\n"
"CharEvent 133 125 0 0 98 1 i\n"
"KeyReleaseEvent 133 125 0 0 98 1 i\n"
"MouseMoveEvent 133 125 0 0 0 0 i\n"
"RightButtonPressEvent 133 125 0 0 0 0 i\n"
"MouseMoveEvent 133 123 0 0 0 0 i\n"
"MouseMoveEvent 133 119 0 0 0 0 i\n"
"MouseMoveEvent 132 115 0 0 0 0 i\n"
"MouseMoveEvent 132 111 0 0 0 0 i\n"
"MouseMoveEvent 132 107 0 0 0 0 i\n"
"RightButtonReleaseEvent 132 107 0 0 0 0 i\n"
"MouseMoveEvent 132 129 0 0 0 0 i\n"
"LeftButtonPressEvent 132 129 0 0 0 0 i\n"
"MouseMoveEvent 132 130 0 0 0 0 i\n"
"MouseMoveEvent 132 135 0 0 0 0 i\n"
"MouseMoveEvent 132 143 0 0 0 0 i\n"
"MouseMoveEvent 131 152 0 0 0 0 i\n"
"MouseMoveEvent 130 159 0 0 0 0 i\n"
"MouseMoveEvent 129 165 0 0 0 0 i\n"
"MouseMoveEvent 127 170 0 0 0 0 i\n"
"MouseMoveEvent 125 176 0 0 0 0 i\n"
"MouseMoveEvent 124 181 0 0 0 0 i\n"
"MouseMoveEvent 122 183 0 0 0 0 i\n"
"LeftButtonReleaseEvent 122 183 0 0 0 0 i\n"
"MouseMoveEvent 133 163 0 0 0 0 i\n"
"MiddleButtonPressEvent 133 163 0 0 0 0 i\n"
"MouseMoveEvent 132 161 0 0 0 0 i\n"
"MouseMoveEvent 128 158 0 0 0 0 i\n"
"MouseMoveEvent 124 155 0 0 0 0 i\n"
"MouseMoveEvent 120 151 0 0 0 0 i\n"
"MouseMoveEvent 116 147 0 0 0 0 i\n"
"MouseMoveEvent 118 146 0 0 0 0 i\n"
"MouseMoveEvent 121 148 0 0 0 0 i\n"
"MouseMoveEvent 123 150 0 0 0 0 i\n"
"MouseMoveEvent 125 154 0 0 0 0 i\n"
"MouseMoveEvent 129 158 0 0 0 0 i\n"
"MouseMoveEvent 132 161 0 0 0 0 i\n"
"MouseMoveEvent 134 165 0 0 0 0 i\n"
"MouseMoveEvent 136 168 0 0 0 0 i\n"
"MiddleButtonReleaseEvent 136 168 0 0 0 0 i\n"
"MouseMoveEvent 178 186 0 0 0 0 i\n"
"KeyPressEvent 178 186 -128 0 0 1 Control_L\n"
"MiddleButtonPressEvent 178 186 8 0 0 0 Control_L\n"
"MouseMoveEvent 178 185 8 0 0 0 Control_L\n"
"MouseMoveEvent 179 183 8 0 0 0 Control_L\n"
"MouseMoveEvent 179 181 8 0 0 0 Control_L\n"
"MouseMoveEvent 179 179 8 0 0 0 Control_L\n"
"MouseMoveEvent 179 177 8 0 0 0 Control_L\n"
"MouseMoveEvent 179 175 8 0 0 0 Control_L\n"
"MouseMoveEvent 179 173 8 0 0 0 Control_L\n"
"MouseMoveEvent 179 171 8 0 0 0 Control_L\n"
"MouseMoveEvent 177 169 8 0 0 0 Control_L\n"
"MouseMoveEvent 176 167 8 0 0 0 Control_L\n"
"MouseMoveEvent 174 165 8 0 0 0 Control_L\n"
"MouseMoveEvent 172 164 8 0 0 0 Control_L\n"
"MouseMoveEvent 171 163 8 0 0 0 Control_L\n"
"MiddleButtonReleaseEvent 171 163 8 0 0 0 Control_L\n"
"KeyReleaseEvent 171 163 0 0 0 1 Control_L\n"
"MouseMoveEvent 170 167 0 0 0 0 Control_L\n"
"MiddleButtonPressEvent 170 167 0 0 0 0 Control_L\n"
"MouseMoveEvent 172 167 0 0 0 0 Control_L\n"
"MouseMoveEvent 176 167 0 0 0 0 Control_L\n"
"MouseMoveEvent 181 167 0 0 0 0 Control_L\n"
"MouseMoveEvent 188 167 0 0 0 0 Control_L\n"
"MouseMoveEvent 198 165 0 0 0 0 Control_L\n"
"MouseMoveEvent 205 163 0 0 0 0 Control_L\n"
"MouseMoveEvent 211 161 0 0 0 0 Control_L\n"
"MouseMoveEvent 216 160 0 0 0 0 Control_L\n"
"MouseMoveEvent 222 158 0 0 0 0 Control_L\n"
"MiddleButtonReleaseEvent 222 158 0 0 0 0 Control_L\n"
"MouseMoveEvent 230 158 0 0 0 0 Control_L\n"
"MiddleButtonPressEvent 230 158 0 0 0 0 Control_L\n"
"MouseMoveEvent 229 156 0 0 0 0 Control_L\n"
"MouseMoveEvent 228 153 0 0 0 0 Control_L\n"
"MouseMoveEvent 226 150 0 0 0 0 Control_L\n"
"MouseMoveEvent 224 148 0 0 0 0 Control_L\n"
"MouseMoveEvent 222 145 0 0 0 0 Control_L\n"
"MouseMoveEvent 220 141 0 0 0 0 Control_L\n"
"MouseMoveEvent 216 135 0 0 0 0 Control_L\n"
"MouseMoveEvent 214 129 0 0 0 0 Control_L\n"
"MouseMoveEvent 212 123 0 0 0 0 Control_L\n"
"MouseMoveEvent 209 118 0 0 0 0 Control_L\n"
"MouseMoveEvent 207 113 0 0 0 0 Control_L\n"
"MouseMoveEvent 204 109 0 0 0 0 Control_L\n"
"MouseMoveEvent 202 105 0 0 0 0 Control_L\n"
"MouseMoveEvent 200 103 0 0 0 0 Control_L\n"
"MouseMoveEvent 198 99 0 0 0 0 Control_L\n"
"MouseMoveEvent 196 97 0 0 0 0 Control_L\n"
"MouseMoveEvent 194 93 0 0 0 0 Control_L\n"
"MiddleButtonReleaseEvent 194 93 0 0 0 0 Control_L\n"
"MouseMoveEvent 254 98 0 0 0 0 Control_L\n"
"MiddleButtonPressEvent 254 98 0 0 0 0 Control_L\n"
"MouseMoveEvent 254 100 0 0 0 0 Control_L\n"
"MouseMoveEvent 254 104 0 0 0 0 Control_L\n"
"MouseMoveEvent 255 108 0 0 0 0 Control_L\n"
"MouseMoveEvent 255 112 0 0 0 0 Control_L\n"
"MouseMoveEvent 255 116 0 0 0 0 Control_L\n"
"MouseMoveEvent 255 120 0 0 0 0 Control_L\n"
"MouseMoveEvent 256 124 0 0 0 0 Control_L\n"
"MouseMoveEvent 257 128 0 0 0 0 Control_L\n"
"MouseMoveEvent 257 132 0 0 0 0 Control_L\n"
"MouseMoveEvent 257 136 0 0 0 0 Control_L\n"
"MouseMoveEvent 258 141 0 0 0 0 Control_L\n"
"MouseMoveEvent 258 146 0 0 0 0 Control_L\n"
"MouseMoveEvent 258 151 0 0 0 0 Control_L\n"
"MouseMoveEvent 258 157 0 0 0 0 Control_L\n"
"MouseMoveEvent 258 159 0 0 0 0 Control_L\n"
"MiddleButtonReleaseEvent 80 206 0 0 0 0 Control_L\n"
;
// Callback for the image plane widget interaction
class vtkIPWCallback : public vtkCommand
{
public:
static vtkIPWCallback *New()
{ return new vtkIPWCallback; }
virtual void Execute(vtkObject *caller, unsigned long, void*)
{
vtkImagePlaneWidget *planeWidget = reinterpret_cast<vtkImagePlaneWidget*>(caller);
if(planeWidget->GetPlaneOrientation() == 3)
{
Spline->SetProjectionPosition(0);
}
else
{
Spline->SetProjectionPosition(planeWidget->GetSlicePosition());
}
Spline->GetPolyData(Poly);
}
vtkIPWCallback():Spline(0),Poly(0){};
vtkSplineWidget* Spline;
vtkPolyData* Poly;
};
// Callback for the spline widget interaction
class vtkSWCallback : public vtkCommand
{
public:
static vtkSWCallback *New()
{ return new vtkSWCallback; }
virtual void Execute(vtkObject *caller, unsigned long, void*)
{
vtkSplineWidget *spline = reinterpret_cast<vtkSplineWidget*>(caller);
spline->GetPolyData(Poly);
}
vtkSWCallback():Poly(0){};
vtkPolyData* Poly;
};
int TestSplineWidget( int argc, char *argv[] )
{
char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/headsq/quarter");
vtkVolume16Reader* v16 = vtkVolume16Reader::New();
v16->SetDataDimensions( 64, 64);
v16->SetDataByteOrderToLittleEndian();
v16->SetImageRange( 1, 93);
v16->SetDataSpacing( 3.2, 3.2, 1.5);
v16->SetFilePrefix( fname);
v16->SetDataMask( 0x7fff);
v16->Update();
delete[] fname;
vtkRenderer* ren1 = vtkRenderer::New();
vtkRenderer* ren2 = vtkRenderer::New();
vtkRenderWindow* renWin = vtkRenderWindow::New();
renWin->AddRenderer( ren1);
renWin->AddRenderer( ren2);
vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow( renWin);
vtkOutlineFilter* outline = vtkOutlineFilter::New();
outline->SetInput(v16->GetOutput());
vtkPolyDataMapper* outlineMapper = vtkPolyDataMapper::New();
outlineMapper->SetInput(outline->GetOutput());
vtkActor* outlineActor = vtkActor::New();
outlineActor->SetMapper(outlineMapper);
vtkImagePlaneWidget* ipw = vtkImagePlaneWidget::New();
ipw->DisplayTextOn();
ipw->TextureInterpolateOff();
ipw->UserControlledLookupTableOff();
ipw->SetInput(v16->GetOutput());
ipw->KeyPressActivationOn();
ipw->SetKeyPressActivationValue('x');
ipw->SetResliceInterpolateToNearestNeighbour();
ipw->SetInteractor(iren);
ipw->SetPlaneOrientationToXAxes();
ipw->SetSliceIndex(32);
ipw->GetPlaneProperty()->SetColor(1,0,0);
vtkSplineWidget* spline = vtkSplineWidget::New();
spline->SetInteractor( iren);
spline->SetInput(v16->GetOutput());
spline->SetPriority(1.0);
spline->KeyPressActivationOff();
spline->PlaceWidget();
spline->ProjectToPlaneOn();
spline->SetProjectionNormal(0);
spline->SetProjectionPosition(102.4); //initial plane oriented position
spline->SetProjectionNormal(3); //allow arbitrary oblique orientations
spline->SetPlaneSource((vtkPlaneSource*)ipw->GetPolyDataSource());
// Specify the type of spline (change from default vtkCardinalSpline)
vtkKochanekSpline* xspline = vtkKochanekSpline::New();
vtkKochanekSpline* yspline = vtkKochanekSpline::New();
vtkKochanekSpline* zspline = vtkKochanekSpline::New();
spline->SetXSpline(xspline);
spline->SetYSpline(yspline);
spline->SetZSpline(zspline);
xspline->Delete();
yspline->Delete();
zspline->Delete();
vtkPolyData* poly = vtkPolyData::New();
spline->GetPolyData(poly);
vtkProbeFilter* probe = vtkProbeFilter::New();
probe->SetInput(poly);
probe->SetSource(v16->GetOutput());
vtkIPWCallback* ipwcb = vtkIPWCallback::New();
ipwcb->Spline = spline;
ipwcb->Poly = poly;
ipw->AddObserver(vtkCommand::InteractionEvent,ipwcb);
vtkSWCallback* swcb = vtkSWCallback::New();
swcb->Poly = poly;
spline->AddObserver(vtkCommand::InteractionEvent,swcb);
vtkImageData* data = v16->GetOutput();
float* range = data->GetPointData()->GetScalars()->GetRange();
vtkXYPlotActor* profile = vtkXYPlotActor::New();
profile->AddInput(probe->GetOutput());
profile->GetPositionCoordinate()->SetValue( 0.05, 0.05, 0);
profile->GetPosition2Coordinate()->SetValue( 0.95, 0.95, 0);
profile->SetXValuesToNormalizedArcLength();
profile->SetNumberOfXLabels( 6);
profile->SetTitle( "Profile Data ");
profile->SetXTitle( "s");
profile->SetYTitle( "I(s)");
profile->SetXRange( 0, 1);
profile->SetYRange( range[0], range[1]);
profile->GetProperty()->SetColor( 0, 0, 0);
profile->GetProperty()->SetLineWidth( 2);
profile->SetLabelFormat("%g");
vtkTextProperty* tprop = profile->GetTitleTextProperty();
tprop->SetColor(0.02,0.06,0.62);
tprop->SetFontFamilyToArial();
profile->SetAxisTitleTextProperty(tprop);
profile->SetAxisLabelTextProperty(tprop);
profile->SetTitleTextProperty(tprop);
ren1->SetBackground( 0.1, 0.2, 0.4);
ren1->SetViewport( 0, 0, 0.5, 1);
ren1->AddActor(outlineActor);
ren2->SetBackground( 1, 1, 1);
ren2->SetViewport( 0.5, 0, 1, 1);
ren2->AddActor2D( profile);
renWin->SetSize( 600, 300);
ipw->On();
ipw->SetInteraction(0);
ipw->SetInteraction(1);
spline->On();
spline->SetNumberOfHandles(4);
spline->SetNumberOfHandles(5);
spline->SetResolution(399);
// Set up an interesting viewpoint
vtkCamera* camera = ren1->GetActiveCamera();
camera->Elevation(110);
camera->SetViewUp(0, 0, -1);
camera->Azimuth(45);
ren1->ResetCameraClippingRange();
// Position the actors
renWin->Render();
iren->SetEventPosition(200,200);
iren->SetKeyCode('r');
iren->InvokeEvent(vtkCommand::CharEvent,NULL);
ren1->ResetCameraClippingRange();
renWin->Render();
iren->SetKeyCode('t');
iren->InvokeEvent(vtkCommand::CharEvent,NULL);
// Playback recorded events
vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New();
recorder->SetInteractor(iren);
recorder->ReadFromInputStringOn();
recorder->SetInputString(TSWeventLog);
// Test On Off mechanism
ipw->SetEnabled(0);
spline->EnabledOff();
ipw->SetEnabled(1);
spline->EnabledOn();
// Test Set Get handle positions
float pos[3];
int i;
for(i=0;i<spline->GetNumberOfHandles();i++)
{
spline->GetHandlePosition(i,pos);
spline->SetHandlePosition(i,pos);
}
// Test Closed On Off
spline->ClosedOn();
spline->ClosedOff();
// Render the image
iren->Initialize();
renWin->Render();
recorder->Play();
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
// Clean up
recorder->Off();
recorder->Delete();
outlineActor->Delete();
outlineMapper->Delete();
outline->Delete();
renWin->Delete();
ren1->Delete();
ren2->Delete();
iren->Delete();
ipw->RemoveObserver(ipwcb);
ipw->Delete();
ipwcb->Delete();
spline->RemoveObserver(swcb);
spline->Delete();
swcb->Delete();
poly->Delete();
probe->Delete();
profile->Delete();
v16->Delete();
return !retVal;
}
|
// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
#define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
#include <type_traits>
#include <dune/common/typetraits.hh>
#include <dune/common/dynvector.hh>
#include <dune/geometry/genericreferenceelements.hh>
#include <dune/stuff/common/exceptions.hh>
#include "../interface.hh"
namespace Dune {
namespace GDT {
namespace Spaces {
// forward, to allow for specialization
template< class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class ContinuousLagrangeBase
{
static_assert(AlwaysFalse< ImpTraits >::value, "Untested for these dimensions!");
};
template< class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim >
class ContinuousLagrangeBase< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >
: public SpaceInterface< ImpTraits >
{
typedef SpaceInterface< ImpTraits > BaseType;
typedef ContinuousLagrangeBase< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 > ThisType;
static const RangeFieldImp compare_tolerance_ = 1e-13;
public:
typedef ImpTraits Traits;
using BaseType::polOrder;
using typename BaseType::DomainFieldType;
using BaseType::dimDomain;
using typename BaseType::DomainType;
typedef typename Traits::RangeFieldType RangeFieldType;
using BaseType::dimRange;
using BaseType::dimRangeCols;
using typename BaseType::EntityType;
using typename BaseType::IntersectionType;
using typename BaseType::BoundaryInfoType;
using typename BaseType::PatternType;
virtual ~ContinuousLagrangeBase() {}
using BaseType::compute_pattern;
template< class G, class S >
PatternType compute_pattern(const GridView< G >& local_grid_view, const SpaceInterface< S >& ansatz_space) const
{
return BaseType::compute_volume_pattern(local_grid_view, ansatz_space);
}
virtual std::vector< DomainType > lagrange_points(const EntityType& entity) const
{
// check
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1) DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
assert(this->grid_view()->indexSet().contains(entity));
// get the basis and reference element
const auto basis = this->base_function_set(entity);
const auto& reference_element = ReferenceElements< DomainFieldType, dimDomain >::general(entity.type());
const int num_vertices = reference_element.size(dimDomain);
assert(num_vertices >= 0);
assert(size_t(num_vertices) == basis.size() && "This should not happen with polOrder 1!");
// prepare return vector
std::vector< DomainType > local_vertices(num_vertices, DomainType(0));
if (this->tmp_basis_values_.size() < basis.size())
this->tmp_basis_values_.resize(basis.size());
// loop over all vertices
for (int ii = 0; ii < num_vertices; ++ii) {
// get the local coordinate of the iith vertex
const auto local_vertex = reference_element.position(ii, dimDomain);
// evaluate the basefunctionset
basis.evaluate(local_vertex, this->tmp_basis_values_);
// find the basis function that evaluates to one here (has to be only one!)
size_t ones = 0;
size_t zeros = 0;
size_t failures = 0;
for (size_t jj = 0; jj < basis.size(); ++jj) {
if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
local_vertices[jj] = local_vertex;
++ones;
} else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_)
++zeros;
else
++failures;
}
assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
}
return local_vertices;
} // ... lagrange_points(...)
virtual std::set< size_t > local_dirichlet_DoFs(const EntityType& entity,
const BoundaryInfoType& boundaryInfo) const
{
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1) DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
// check
assert(this->grid_view()->indexSet().contains(entity));
// prepare
std::set< size_t > localDirichletDofs;
std::vector< DomainType > dirichlet_vertices;
// get all dirichlet vertices of this entity, therefore
// * loop over all intersections
const auto intersection_it_end = this->grid_view()->iend(entity);
for (auto intersection_it = this->grid_view()->ibegin(entity);
intersection_it != intersection_it_end;
++intersection_it) {
// only work on dirichlet ones
const auto& intersection = *intersection_it;
if (boundaryInfo.dirichlet(intersection)) {
// and get the vertices of the intersection
const auto geometry = intersection.geometry();
for (int cc = 0; cc < geometry.corners(); ++cc)
dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc)));
} // only work on dirichlet ones
} // loop over all intersections
// find the corresponding basis functions
const auto basis = this->base_function_set(entity);
if (this->tmp_basis_values_.size() < basis.size())
this->tmp_basis_values_.resize(basis.size());
for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) {
// find the basis function that evaluates to one here (has to be only one!)
basis.evaluate(dirichlet_vertices[cc], this->tmp_basis_values_);
size_t ones = 0;
size_t zeros = 0;
size_t failures = 0;
for (size_t jj = 0; jj < basis.size(); ++jj) {
if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
localDirichletDofs.insert(jj);
++ones;
} else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_)
++zeros;
else
++failures;
}
assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
}
return localDirichletDofs;
} // ... local_dirichlet_DoFs(...)
private:
template< class C, bool set_row >
struct DirichletConstraints;
template< class C >
struct DirichletConstraints< C, true > { static RangeFieldType value() { return RangeFieldType(1); } };
template< class C >
struct DirichletConstraints< C, false > { static RangeFieldType value() { return RangeFieldType(0); } };
template< class T, bool set_row >
void compute_local_constraints(const SpaceInterface< T >& other,
const EntityType& entity,
Constraints::Dirichlet< IntersectionType, RangeFieldType, set_row >& ret) const
{
// check
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1) DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
assert(this->grid_view()->indexSet().contains(entity));
typedef DirichletConstraints
< Constraints::Dirichlet< IntersectionType, RangeFieldType, set_row >, set_row > SetRow;
const std::set< size_t > localDirichletDofs = this->local_dirichlet_DoFs(entity, ret.gridBoundary());
const size_t numRows = localDirichletDofs.size();
if (numRows > 0) {
const size_t numCols = this->mapper().numDofs(entity);
ret.setSize(numRows, numCols);
this->mapper().globalIndices(entity, tmpMappedRows_);
other.mapper().globalIndices(entity, tmpMappedCols_);
size_t localRow = 0;
const RangeFieldType zero(0);
for (auto localDirichletDofIt = localDirichletDofs.begin();
localDirichletDofIt != localDirichletDofs.end();
++localDirichletDofIt) {
const size_t& localDirichletDofIndex = * localDirichletDofIt;
ret.globalRow(localRow) = tmpMappedRows_[localDirichletDofIndex];
for (size_t jj = 0; jj < ret.cols(); ++jj) {
ret.globalCol(jj) = tmpMappedCols_[jj];
if (tmpMappedCols_[jj] == tmpMappedRows_[localDirichletDofIndex])
ret.value(localRow, jj) = SetRow::value();
else
ret.value(localRow, jj) = zero;
}
++localRow;
}
} else {
ret.setSize(0, 0);
}
} // ... compute_local_constraints(..., Dirichlet< ..., true >)
public:
template< bool set >
void local_constraints(const EntityType& entity,
Constraints::Dirichlet< IntersectionType, RangeFieldType, set >& ret) const
{
local_constraints(*this, entity, ret);
}
virtual void local_constraints(const ThisType& other,
const EntityType& entity,
Constraints::Dirichlet< IntersectionType, RangeFieldType, true >& ret) const
{
compute_local_constraints(other, entity, ret);
}
virtual void local_constraints(const ThisType& other,
const EntityType& entity,
Constraints::Dirichlet< IntersectionType, RangeFieldType, false >& ret) const
{
compute_local_constraints(other, entity, ret);
}
protected:
mutable Dune::DynamicVector< size_t > tmpMappedRows_;
mutable Dune::DynamicVector< size_t > tmpMappedCols_;
}; // class ContinuousLagrangeBase
} // namespace Spaces
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
[spaces.cg.base] make gcc-4.8 happy
// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
#define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
#include <type_traits>
#include <dune/common/typetraits.hh>
#include <dune/common/dynvector.hh>
#include <dune/geometry/genericreferenceelements.hh>
#include <dune/stuff/common/exceptions.hh>
#include "../interface.hh"
namespace Dune {
namespace GDT {
namespace Spaces {
// forward, to allow for specialization
template< class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class ContinuousLagrangeBase
{
static_assert(AlwaysFalse< ImpTraits >::value, "Untested for these dimensions!");
};
template< class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim >
class ContinuousLagrangeBase< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >
: public SpaceInterface< ImpTraits >
{
typedef SpaceInterface< ImpTraits > BaseType;
typedef ContinuousLagrangeBase< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 > ThisType;
static const constexpr RangeFieldImp compare_tolerance_ = 1e-13;
public:
typedef ImpTraits Traits;
using BaseType::polOrder;
using typename BaseType::DomainFieldType;
using BaseType::dimDomain;
using typename BaseType::DomainType;
typedef typename Traits::RangeFieldType RangeFieldType;
using BaseType::dimRange;
using BaseType::dimRangeCols;
using typename BaseType::EntityType;
using typename BaseType::IntersectionType;
using typename BaseType::BoundaryInfoType;
using typename BaseType::PatternType;
virtual ~ContinuousLagrangeBase() {}
using BaseType::compute_pattern;
template< class G, class S >
PatternType compute_pattern(const GridView< G >& local_grid_view, const SpaceInterface< S >& ansatz_space) const
{
return BaseType::compute_volume_pattern(local_grid_view, ansatz_space);
}
virtual std::vector< DomainType > lagrange_points(const EntityType& entity) const
{
// check
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1) DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
assert(this->grid_view()->indexSet().contains(entity));
// get the basis and reference element
const auto basis = this->base_function_set(entity);
const auto& reference_element = ReferenceElements< DomainFieldType, dimDomain >::general(entity.type());
const int num_vertices = reference_element.size(dimDomain);
assert(num_vertices >= 0);
assert(size_t(num_vertices) == basis.size() && "This should not happen with polOrder 1!");
// prepare return vector
std::vector< DomainType > local_vertices(num_vertices, DomainType(0));
if (this->tmp_basis_values_.size() < basis.size())
this->tmp_basis_values_.resize(basis.size());
// loop over all vertices
for (int ii = 0; ii < num_vertices; ++ii) {
// get the local coordinate of the iith vertex
const auto local_vertex = reference_element.position(ii, dimDomain);
// evaluate the basefunctionset
basis.evaluate(local_vertex, this->tmp_basis_values_);
// find the basis function that evaluates to one here (has to be only one!)
size_t ones = 0;
size_t zeros = 0;
size_t failures = 0;
for (size_t jj = 0; jj < basis.size(); ++jj) {
if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
local_vertices[jj] = local_vertex;
++ones;
} else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_)
++zeros;
else
++failures;
}
assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
}
return local_vertices;
} // ... lagrange_points(...)
virtual std::set< size_t > local_dirichlet_DoFs(const EntityType& entity,
const BoundaryInfoType& boundaryInfo) const
{
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1) DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
// check
assert(this->grid_view()->indexSet().contains(entity));
// prepare
std::set< size_t > localDirichletDofs;
std::vector< DomainType > dirichlet_vertices;
// get all dirichlet vertices of this entity, therefore
// * loop over all intersections
const auto intersection_it_end = this->grid_view()->iend(entity);
for (auto intersection_it = this->grid_view()->ibegin(entity);
intersection_it != intersection_it_end;
++intersection_it) {
// only work on dirichlet ones
const auto& intersection = *intersection_it;
if (boundaryInfo.dirichlet(intersection)) {
// and get the vertices of the intersection
const auto geometry = intersection.geometry();
for (int cc = 0; cc < geometry.corners(); ++cc)
dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc)));
} // only work on dirichlet ones
} // loop over all intersections
// find the corresponding basis functions
const auto basis = this->base_function_set(entity);
if (this->tmp_basis_values_.size() < basis.size())
this->tmp_basis_values_.resize(basis.size());
for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) {
// find the basis function that evaluates to one here (has to be only one!)
basis.evaluate(dirichlet_vertices[cc], this->tmp_basis_values_);
size_t ones = 0;
size_t zeros = 0;
size_t failures = 0;
for (size_t jj = 0; jj < basis.size(); ++jj) {
if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
localDirichletDofs.insert(jj);
++ones;
} else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_)
++zeros;
else
++failures;
}
assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
}
return localDirichletDofs;
} // ... local_dirichlet_DoFs(...)
private:
template< class C, bool set_row >
struct DirichletConstraints;
template< class C >
struct DirichletConstraints< C, true > { static RangeFieldType value() { return RangeFieldType(1); } };
template< class C >
struct DirichletConstraints< C, false > { static RangeFieldType value() { return RangeFieldType(0); } };
template< class T, bool set_row >
void compute_local_constraints(const SpaceInterface< T >& other,
const EntityType& entity,
Constraints::Dirichlet< IntersectionType, RangeFieldType, set_row >& ret) const
{
// check
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1) DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
assert(this->grid_view()->indexSet().contains(entity));
typedef DirichletConstraints
< Constraints::Dirichlet< IntersectionType, RangeFieldType, set_row >, set_row > SetRow;
const std::set< size_t > localDirichletDofs = this->local_dirichlet_DoFs(entity, ret.gridBoundary());
const size_t numRows = localDirichletDofs.size();
if (numRows > 0) {
const size_t numCols = this->mapper().numDofs(entity);
ret.setSize(numRows, numCols);
this->mapper().globalIndices(entity, tmpMappedRows_);
other.mapper().globalIndices(entity, tmpMappedCols_);
size_t localRow = 0;
const RangeFieldType zero(0);
for (auto localDirichletDofIt = localDirichletDofs.begin();
localDirichletDofIt != localDirichletDofs.end();
++localDirichletDofIt) {
const size_t& localDirichletDofIndex = * localDirichletDofIt;
ret.globalRow(localRow) = tmpMappedRows_[localDirichletDofIndex];
for (size_t jj = 0; jj < ret.cols(); ++jj) {
ret.globalCol(jj) = tmpMappedCols_[jj];
if (tmpMappedCols_[jj] == tmpMappedRows_[localDirichletDofIndex])
ret.value(localRow, jj) = SetRow::value();
else
ret.value(localRow, jj) = zero;
}
++localRow;
}
} else {
ret.setSize(0, 0);
}
} // ... compute_local_constraints(..., Dirichlet< ..., true >)
public:
template< bool set >
void local_constraints(const EntityType& entity,
Constraints::Dirichlet< IntersectionType, RangeFieldType, set >& ret) const
{
local_constraints(*this, entity, ret);
}
virtual void local_constraints(const ThisType& other,
const EntityType& entity,
Constraints::Dirichlet< IntersectionType, RangeFieldType, true >& ret) const
{
compute_local_constraints(other, entity, ret);
}
virtual void local_constraints(const ThisType& other,
const EntityType& entity,
Constraints::Dirichlet< IntersectionType, RangeFieldType, false >& ret) const
{
compute_local_constraints(other, entity, ret);
}
protected:
mutable Dune::DynamicVector< size_t > tmpMappedRows_;
mutable Dune::DynamicVector< size_t > tmpMappedCols_;
}; // class ContinuousLagrangeBase
} // namespace Spaces
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
|
// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_OPERATOR_PRODUCTS_HH
#define DUNE_GDT_OPERATOR_PRODUCTS_HH
#include <type_traits>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/functions/constant.hh>
#include "../localoperator/codim0.hh"
#include "../localfunctional/codim0.hh"
#include "../localevaluation/product.hh"
#include "../localevaluation/elliptic.hh"
namespace Dune {
namespace GDT {
namespace ProductOperator {
template< class GridPartType >
class L2
{
public:
typedef typename GridPartType::template Codim< 0 >::EntityType EntityType;
typedef typename GridPartType::ctype DomainFieldType;
static const unsigned int dimDomain = GridPartType::dimension;
L2(const GridPartType& grid_part)
: grid_part_(grid_part)
{}
template< class RR, int rRR, int rCR, class RS, int rRS, int rCS >
void apply2(const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RR, rRR, rCR >& /*range*/,
const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RS, rRS, rCS >& /*source*/) const
{
static_assert((Dune::AlwaysFalse< RR >::value), "Not implemented for this combination!");
}
template< class RangeFieldType, int dimRangeRows, int dimRangeCols >
RangeFieldType apply2(const Stuff::LocalizableFunctionInterface
< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols >&
range,
const Stuff::LocalizableFunctionInterface
< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols >&
source) const
{
typedef Stuff::LocalizableFunctionInterface
< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols >
RangeType;
// some preparations
const LocalFunctional::Codim0Integral< LocalEvaluation::Product< RangeType > > local_functional(range);
RangeFieldType ret = 0;
DynamicVector< RangeFieldType > local_functional_result(1, 0);
std::vector< DynamicVector< RangeFieldType > > tmp_vectors(local_functional.numTmpObjectsRequired(),
DynamicVector< RangeFieldType >(1, 0));
// walk the grid
const auto entity_it_end = grid_part_.template end< 0 >();
for (auto entity_it = grid_part_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) {
const auto& entity = *entity_it;
// get the local function
const auto source_local_function = source.local_function(entity);
// apply local functional
local_functional.apply(*source_local_function, local_functional_result, tmp_vectors);
assert(local_functional_result.size() == 1);
ret += local_functional_result[0];
} // walk the grid
return ret;
} // ... apply2(...)
private:
const GridPartType& grid_part_;
}; // class L2
template< class GridPartType >
class H1
{
public:
typedef typename GridPartType::template Codim< 0 >::EntityType EntityType;
typedef typename GridPartType::ctype DomainFieldType;
static const unsigned int dimDomain = GridPartType::dimension;
H1(const GridPartType& grid_part)
: grid_part_(grid_part)
{}
template< class RR, int rRR, int rCR, class RS, int rRS, int rCS >
void apply2(const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RR, rRR, rCR >& /*range*/,
const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RS, rRS, rCS >& /*source*/) const
{
static_assert((Dune::AlwaysFalse< RR >::value), "Not implemented for this combination!");
}
template< class RangeFieldType, int dimRangeRows, int dimRangeCols >
RangeFieldType apply2(const Stuff::LocalizableFunctionInterface
< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols >&
range,
const Stuff::LocalizableFunctionInterface
< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols >&
source) const
{
// some preparations
typedef Stuff::Function::Constant< EntityType, DomainFieldType, dimDomain, RangeFieldType, 1 > ConstantFunctionType;
const ConstantFunctionType one(1);
const LocalOperator::Codim0Integral< LocalEvaluation::Elliptic< ConstantFunctionType > > local_operator(one);
RangeFieldType ret = 0;
DynamicMatrix< RangeFieldType > local_operator_result(1, 1, 0);
std::vector< DynamicMatrix< RangeFieldType > > tmp_matrices(local_operator.numTmpObjectsRequired(),
DynamicMatrix< RangeFieldType >(1, 1, 0));
// walk the grid
const auto entity_it_end = grid_part_.template end< 0 >();
for (auto entity_it = grid_part_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) {
const auto& entity = *entity_it;
// get the local functions
const auto source_local_function = source.local_function(entity);
const auto range_local_function = range.local_function(entity);
// apply local operator
local_operator.apply(*source_local_function, *range_local_function, local_operator_result, tmp_matrices);
assert(local_operator_result.rows() == 1);
assert(local_operator_result.cols() == 1);
ret += local_operator_result[0][0];
} // walk the grid
return ret;
} // ... apply2(...)
private:
const GridPartType& grid_part_;
}; // class H1
} // namespace ProductOperator
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_OPERATOR_PRODUCTS_HH
[operator.products] renamed H1 -> H1Semi
// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_OPERATOR_PRODUCTS_HH
#define DUNE_GDT_OPERATOR_PRODUCTS_HH
#include <type_traits>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/functions/constant.hh>
#include "../localoperator/codim0.hh"
#include "../localfunctional/codim0.hh"
#include "../localevaluation/product.hh"
#include "../localevaluation/elliptic.hh"
namespace Dune {
namespace GDT {
namespace ProductOperator {
template< class GridPartType >
class L2
{
public:
typedef typename GridPartType::template Codim< 0 >::EntityType EntityType;
typedef typename GridPartType::ctype DomainFieldType;
static const unsigned int dimDomain = GridPartType::dimension;
L2(const GridPartType& grid_part)
: grid_part_(grid_part)
{}
template< class RR, int rRR, int rCR, class RS, int rRS, int rCS >
void apply2(const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RR, rRR, rCR >& /*range*/,
const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RS, rRS, rCS >& /*source*/) const
{
static_assert((Dune::AlwaysFalse< RR >::value), "Not implemented for this combination!");
}
template< class RangeFieldType, int dimRangeRows, int dimRangeCols >
RangeFieldType apply2(const Stuff::LocalizableFunctionInterface
< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols >&
range,
const Stuff::LocalizableFunctionInterface
< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols >&
source) const
{
typedef Stuff::LocalizableFunctionInterface
< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols >
RangeType;
// some preparations
const LocalFunctional::Codim0Integral< LocalEvaluation::Product< RangeType > > local_functional(range);
RangeFieldType ret = 0;
DynamicVector< RangeFieldType > local_functional_result(1, 0);
std::vector< DynamicVector< RangeFieldType > > tmp_vectors(local_functional.numTmpObjectsRequired(),
DynamicVector< RangeFieldType >(1, 0));
// walk the grid
const auto entity_it_end = grid_part_.template end< 0 >();
for (auto entity_it = grid_part_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) {
const auto& entity = *entity_it;
// get the local function
const auto source_local_function = source.local_function(entity);
// apply local functional
local_functional.apply(*source_local_function, local_functional_result, tmp_vectors);
assert(local_functional_result.size() == 1);
ret += local_functional_result[0];
} // walk the grid
return ret;
} // ... apply2(...)
private:
const GridPartType& grid_part_;
}; // class L2
template< class GridPartType >
class H1Semi
{
public:
typedef typename GridPartType::template Codim< 0 >::EntityType EntityType;
typedef typename GridPartType::ctype DomainFieldType;
static const unsigned int dimDomain = GridPartType::dimension;
H1Semi(const GridPartType& grid_part)
: grid_part_(grid_part)
{}
template< class RR, int rRR, int rCR, class RS, int rRS, int rCS >
void apply2(const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RR, rRR, rCR >& /*range*/,
const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RS, rRS, rCS >& /*source*/) const
{
static_assert((Dune::AlwaysFalse< RR >::value), "Not implemented for this combination!");
}
template< class RangeFieldType, int dimRangeRows, int dimRangeCols >
RangeFieldType apply2(const Stuff::LocalizableFunctionInterface
< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols >&
range,
const Stuff::LocalizableFunctionInterface
< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols >&
source) const
{
// some preparations
typedef Stuff::Function::Constant< EntityType, DomainFieldType, dimDomain, RangeFieldType, 1 > ConstantFunctionType;
const ConstantFunctionType one(1);
const LocalOperator::Codim0Integral< LocalEvaluation::Elliptic< ConstantFunctionType > > local_operator(one);
RangeFieldType ret = 0;
DynamicMatrix< RangeFieldType > local_operator_result(1, 1, 0);
std::vector< DynamicMatrix< RangeFieldType > > tmp_matrices(local_operator.numTmpObjectsRequired(),
DynamicMatrix< RangeFieldType >(1, 1, 0));
// walk the grid
const auto entity_it_end = grid_part_.template end< 0 >();
for (auto entity_it = grid_part_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) {
const auto& entity = *entity_it;
// get the local functions
const auto source_local_function = source.local_function(entity);
const auto range_local_function = range.local_function(entity);
// apply local operator
local_operator.apply(*source_local_function, *range_local_function, local_operator_result, tmp_matrices);
assert(local_operator_result.rows() == 1);
assert(local_operator_result.cols() == 1);
ret += local_operator_result[0][0];
} // walk the grid
return ret;
} // ... apply2(...)
private:
const GridPartType& grid_part_;
}; // class H1Semi
} // namespace ProductOperator
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_OPERATOR_PRODUCTS_HH
|
// This file is part of the dune-stuff project:
// https://users.dune-project.org/projects/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_FUNCTIONS_SPE10_HH
#define DUNE_STUFF_FUNCTIONS_SPE10_HH
#include <iostream>
#include <memory>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/configtree.hh>
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/string.hh>
#include "checkerboard.hh"
namespace Dune {
namespace Stuff {
namespace Functions {
// default, to allow for specialization
template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class Spe10Model1
{
public:
Spe10Model1() = delete;
}; // class FunctionSpe10Model1
/**
* \note For dimRange 1 we only read the Kx values from the file.
*/
template< class EntityImp, class DomainFieldImp, class RangeFieldImp >
class Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 >
: public Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 >
{
typedef Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > BaseType;
typedef Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > ThisType;
public:
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::LocalfunctionType LocalfunctionType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const int dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const int dimRange = BaseType::dimRange;
typedef typename BaseType::RangeType RangeType;
static std::string static_id()
{
return BaseType::static_id() + ".spe10.model1";
}
private:
static const size_t numXelements;
static const size_t numYelements;
static const size_t numZelements;
static const RangeFieldType minValue;
static const RangeFieldType maxValue;
static std::vector< RangeType > read_values_from_file(const std::string& filename,
const RangeFieldType& min,
const RangeFieldType& max)
{
if (!(max > min))
DUNE_THROW_COLORFULLY(Dune::RangeError,
"max (is " << max << ") has to be larger than min (is " << min << ")!");
const RangeFieldType scale = (max - min) / (maxValue - minValue);
const RangeType shift = min - scale*minValue;
// read all the data from the file
std::ifstream datafile(filename);
if (datafile.is_open()) {
static const size_t entriesPerDim = numXelements*numYelements*numZelements;
// create storage (there should be exactly 6000 values in the file, but we onyl read the first 2000)
std::vector< RangeType > data(entriesPerDim, RangeFieldType(0));
double tmp = 0;
size_t counter = 0;
while (datafile >> tmp && counter < entriesPerDim) {
data[counter] = (tmp * scale) + shift;
++counter;
}
datafile.close();
if (counter != entriesPerDim)
DUNE_THROW_COLORFULLY(Dune::IOError,
"wrong number of entries in '" << filename << "' (are " << counter << ", should be "
<< entriesPerDim << ")!");
return data;
} else
DUNE_THROW_COLORFULLY(Dune::IOError, "could not open '" << filename << "'!");
} // Spe10Model1()
public:
Spe10Model1(const std::string& filename,
std::vector< DomainFieldType >&& lowerLeft,
std::vector< DomainFieldType >&& upperRight,
const RangeFieldType min = minValue,
const RangeFieldType max = maxValue,
const std::string nm = static_id())
: BaseType(std::move(lowerLeft),
std::move(upperRight),
{numXelements, numZelements},
read_values_from_file(filename, min, max), nm)
{}
virtual ThisType* copy() const DS_OVERRIDE
{
return new ThisType(*this);
}
static Common::ConfigTree default_config(const std::string sub_name = "")
{
Common::ConfigTree config;
config["filename"] = "perm_case1.dat";
config["lower_left"] = "[0.0; 0.0]";
config["upper_right"] = "[762.0; 15.24]";
config["min_value"] = "0.001";
config["max_value"] = "998.915";
config["name"] = static_id();
if (sub_name.empty())
return config;
else {
Common::ConfigTree tmp;
tmp.add(config, sub_name);
return tmp;
}
} // ... default_config(...)
static std::unique_ptr< ThisType > create(const Common::ConfigTree config = default_config(), const std::string sub_name = static_id())
{
// get correct config
const Common::ConfigTree cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;
// extract needed data
const auto filename = cfg.get< std::string >("filename");
auto lower_left = cfg.get< std::vector< DomainFieldType > >("lower_left", dimDomain);
auto upper_right = cfg.get< std::vector< DomainFieldType > >("upper_right", dimDomain);
const auto min_val = cfg.get< RangeFieldType >("min_value", minValue);
const auto max_val = cfg.get< RangeFieldType >("max_value", maxValue);
const auto nm = cfg.get< std::string >("name", static_id());
// create and return, leave the checks to the constructor
return Common::make_unique< ThisType >(filename, std::move(lower_left), std::move(upper_right), min_val, max_val, nm);
} // ... create(...)
}; // class Spe10Model1< ..., 2, ..., 1, 1 >
template< class E, class D, class R >
const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numXelements = 100;
template< class E, class D, class R >
const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numYelements = 1;
template< class E, class D, class R >
const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numZelements = 20;
template< class E, class D, class R >
const typename Spe10Model1< E, D, 2, R, 1, 1 >::RangeFieldType Spe10Model1< E, D, 2, R, 1, 1 >::minValue = 0.001;
template< class E, class D, class R >
const typename Spe10Model1< E, D, 2, R, 1, 1 >::RangeFieldType Spe10Model1< E, D, 2, R, 1, 1 >::maxValue = 998.915;
} // namespace Functions
} // namespace Stuff
} // namespace Dune
#ifdef DUNE_STUFF_FUNCTIONS_TO_LIB
# define DUNE_STUFF_FUNCTIONS_SPE10_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, rcdim) \
DUNE_STUFF_FUNCTIONS_SPE10_LIST_RANGEFIELDTYPES(etype, double, ddim, rdim, rcdim)
# define DUNE_STUFF_FUNCTIONS_SPE10_LIST_RANGEFIELDTYPES(etype, dftype, ddim, rdim, rcdim) \
DUNE_STUFF_FUNCTIONS_SPE10_LAST_EXPANSION(etype, dftype, ddim, double, rdim, rcdim) \
DUNE_STUFF_FUNCTIONS_SPE10_LAST_EXPANSION(etype, dftype, ddim, long double, rdim, rcdim)
# define DUNE_STUFF_FUNCTIONS_SPE10_LAST_EXPANSION(etype, dftype, ddim, rftype, rdim, rcdim) \
extern template class Dune::Stuff::Functions::Spe10Model1< etype, dftype, ddim, rftype, rdim, rcdim >;
# if HAVE_DUNE_GRID
DUNE_STUFF_FUNCTIONS_SPE10_LIST_DOMAINFIELDTYPES(DuneStuffFunctionsInterfacesSGrid2dEntityType, 2, 1, 1)
DUNE_STUFF_FUNCTIONS_SPE10_LIST_DOMAINFIELDTYPES(DuneStuffFunctionsInterfacesYaspGrid2dEntityType, 2, 1, 1)
# if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
DUNE_STUFF_FUNCTIONS_SPE10_LIST_DOMAINFIELDTYPES(DuneStuffFunctionsInterfacesAluSimplexGrid2dEntityType, 2, 1, 1)
# endif // HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
# endif // HAVE_DUNE_GRID
# undef DUNE_STUFF_FUNCTIONS_SPE10_LAST_EXPANSION
# undef DUNE_STUFF_FUNCTIONS_SPE10_LIST_RANGEFIELDTYPES
# undef DUNE_STUFF_FUNCTIONS_SPE10_LIST_DOMAINFIELDTYPES
# endif // DUNE_STUFF_FUNCTIONS_TO_LIB
#endif // DUNE_STUFF_FUNCTIONS_SPE10_HH
[functions.spe10] use new vector notation and new get method
// This file is part of the dune-stuff project:
// https://users.dune-project.org/projects/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_FUNCTIONS_SPE10_HH
#define DUNE_STUFF_FUNCTIONS_SPE10_HH
#include <iostream>
#include <memory>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/configtree.hh>
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/string.hh>
#include "checkerboard.hh"
namespace Dune {
namespace Stuff {
namespace Functions {
// default, to allow for specialization
template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class Spe10Model1
{
public:
Spe10Model1() = delete;
}; // class FunctionSpe10Model1
/**
* \note For dimRange 1 we only read the Kx values from the file.
*/
template< class EntityImp, class DomainFieldImp, class RangeFieldImp >
class Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 >
: public Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 >
{
typedef Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > BaseType;
typedef Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > ThisType;
public:
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::LocalfunctionType LocalfunctionType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const int dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const int dimRange = BaseType::dimRange;
typedef typename BaseType::RangeType RangeType;
static std::string static_id()
{
return BaseType::static_id() + ".spe10.model1";
}
private:
static const size_t numXelements;
static const size_t numYelements;
static const size_t numZelements;
static const RangeFieldType minValue;
static const RangeFieldType maxValue;
static std::vector< RangeType > read_values_from_file(const std::string& filename,
const RangeFieldType& min,
const RangeFieldType& max)
{
if (!(max > min))
DUNE_THROW_COLORFULLY(Dune::RangeError,
"max (is " << max << ") has to be larger than min (is " << min << ")!");
const RangeFieldType scale = (max - min) / (maxValue - minValue);
const RangeType shift = min - scale*minValue;
// read all the data from the file
std::ifstream datafile(filename);
if (datafile.is_open()) {
static const size_t entriesPerDim = numXelements*numYelements*numZelements;
// create storage (there should be exactly 6000 values in the file, but we onyl read the first 2000)
std::vector< RangeType > data(entriesPerDim, RangeFieldType(0));
double tmp = 0;
size_t counter = 0;
while (datafile >> tmp && counter < entriesPerDim) {
data[counter] = (tmp * scale) + shift;
++counter;
}
datafile.close();
if (counter != entriesPerDim)
DUNE_THROW_COLORFULLY(Dune::IOError,
"wrong number of entries in '" << filename << "' (are " << counter << ", should be "
<< entriesPerDim << ")!");
return data;
} else
DUNE_THROW_COLORFULLY(Dune::IOError, "could not open '" << filename << "'!");
} // Spe10Model1()
public:
Spe10Model1(const std::string& filename,
std::vector< DomainFieldType >&& lowerLeft,
std::vector< DomainFieldType >&& upperRight,
const RangeFieldType min = minValue,
const RangeFieldType max = maxValue,
const std::string nm = static_id())
: BaseType(std::move(lowerLeft),
std::move(upperRight),
{numXelements, numZelements},
read_values_from_file(filename, min, max), nm)
{}
virtual ThisType* copy() const DS_OVERRIDE
{
return new ThisType(*this);
}
static Common::ConfigTree default_config(const std::string sub_name = "")
{
Common::ConfigTree config;
config["filename"] = "perm_case1.dat";
config["lower_left"] = "[0.0 0.0]";
config["upper_right"] = "[762.0 15.24]";
config["min_value"] = "0.001";
config["max_value"] = "998.915";
config["name"] = static_id();
if (sub_name.empty())
return config;
else {
Common::ConfigTree tmp;
tmp.add(config, sub_name);
return tmp;
}
} // ... default_config(...)
static std::unique_ptr< ThisType > create(const Common::ConfigTree config = default_config(), const std::string sub_name = static_id())
{
// get correct config
const Common::ConfigTree cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;
const Common::ConfigTree default_cfg = default_config();
// create
return Common::make_unique< ThisType >(
cfg.get("filename", default_cfg.get< std::string >("filename")),
cfg.get("lower_left", default_cfg.get< std::vector< DomainFieldType > >("lower_left"), dimDomain),
cfg.get("upper_right", default_cfg.get< std::vector< DomainFieldType > >("upper_right"), dimDomain),
cfg.get("min_val", minValue),
cfg.get("max_val", maxValue),
cfg.get("name", default_cfg.get< std::string >("name")));
} // ... create(...)
}; // class Spe10Model1< ..., 2, ..., 1, 1 >
template< class E, class D, class R >
const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numXelements = 100;
template< class E, class D, class R >
const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numYelements = 1;
template< class E, class D, class R >
const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numZelements = 20;
template< class E, class D, class R >
const typename Spe10Model1< E, D, 2, R, 1, 1 >::RangeFieldType Spe10Model1< E, D, 2, R, 1, 1 >::minValue = 0.001;
template< class E, class D, class R >
const typename Spe10Model1< E, D, 2, R, 1, 1 >::RangeFieldType Spe10Model1< E, D, 2, R, 1, 1 >::maxValue = 998.915;
} // namespace Functions
} // namespace Stuff
} // namespace Dune
#ifdef DUNE_STUFF_FUNCTIONS_TO_LIB
# define DUNE_STUFF_FUNCTIONS_SPE10_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, rcdim) \
DUNE_STUFF_FUNCTIONS_SPE10_LIST_RANGEFIELDTYPES(etype, double, ddim, rdim, rcdim)
# define DUNE_STUFF_FUNCTIONS_SPE10_LIST_RANGEFIELDTYPES(etype, dftype, ddim, rdim, rcdim) \
DUNE_STUFF_FUNCTIONS_SPE10_LAST_EXPANSION(etype, dftype, ddim, double, rdim, rcdim) \
DUNE_STUFF_FUNCTIONS_SPE10_LAST_EXPANSION(etype, dftype, ddim, long double, rdim, rcdim)
# define DUNE_STUFF_FUNCTIONS_SPE10_LAST_EXPANSION(etype, dftype, ddim, rftype, rdim, rcdim) \
extern template class Dune::Stuff::Functions::Spe10Model1< etype, dftype, ddim, rftype, rdim, rcdim >;
# if HAVE_DUNE_GRID
DUNE_STUFF_FUNCTIONS_SPE10_LIST_DOMAINFIELDTYPES(DuneStuffFunctionsInterfacesSGrid2dEntityType, 2, 1, 1)
DUNE_STUFF_FUNCTIONS_SPE10_LIST_DOMAINFIELDTYPES(DuneStuffFunctionsInterfacesYaspGrid2dEntityType, 2, 1, 1)
# if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
DUNE_STUFF_FUNCTIONS_SPE10_LIST_DOMAINFIELDTYPES(DuneStuffFunctionsInterfacesAluSimplexGrid2dEntityType, 2, 1, 1)
# endif // HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
# endif // HAVE_DUNE_GRID
# undef DUNE_STUFF_FUNCTIONS_SPE10_LAST_EXPANSION
# undef DUNE_STUFF_FUNCTIONS_SPE10_LIST_RANGEFIELDTYPES
# undef DUNE_STUFF_FUNCTIONS_SPE10_LIST_DOMAINFIELDTYPES
# endif // DUNE_STUFF_FUNCTIONS_TO_LIB
#endif // DUNE_STUFF_FUNCTIONS_SPE10_HH
|
/*************************************************************************/
/* editor_file_system.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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. */
/*************************************************************************/
#include "editor_file_system.h"
#include "core/config/project_settings.h"
#include "core/io/resource_importer.h"
#include "core/io/resource_loader.h"
#include "core/io/resource_saver.h"
#include "core/os/file_access.h"
#include "core/os/os.h"
#include "core/variant/variant_parser.h"
#include "editor_node.h"
#include "editor_resource_preview.h"
#include "editor_settings.h"
EditorFileSystem *EditorFileSystem::singleton = nullptr;
//the name is the version, to keep compatibility with different versions of Godot
#define CACHE_FILE_NAME "filesystem_cache6"
void EditorFileSystemDirectory::sort_files() {
files.sort_custom<FileInfoSort>();
}
int EditorFileSystemDirectory::find_file_index(const String &p_file) const {
for (int i = 0; i < files.size(); i++) {
if (files[i]->file == p_file) {
return i;
}
}
return -1;
}
int EditorFileSystemDirectory::find_dir_index(const String &p_dir) const {
for (int i = 0; i < subdirs.size(); i++) {
if (subdirs[i]->name == p_dir) {
return i;
}
}
return -1;
}
int EditorFileSystemDirectory::get_subdir_count() const {
return subdirs.size();
}
EditorFileSystemDirectory *EditorFileSystemDirectory::get_subdir(int p_idx) {
ERR_FAIL_INDEX_V(p_idx, subdirs.size(), nullptr);
return subdirs[p_idx];
}
int EditorFileSystemDirectory::get_file_count() const {
return files.size();
}
String EditorFileSystemDirectory::get_file(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, files.size(), "");
return files[p_idx]->file;
}
String EditorFileSystemDirectory::get_path() const {
String p;
const EditorFileSystemDirectory *d = this;
while (d->parent) {
p = d->name.plus_file(p);
d = d->parent;
}
return "res://" + p;
}
String EditorFileSystemDirectory::get_file_path(int p_idx) const {
String file = get_file(p_idx);
const EditorFileSystemDirectory *d = this;
while (d->parent) {
file = d->name.plus_file(file);
d = d->parent;
}
return "res://" + file;
}
Vector<String> EditorFileSystemDirectory::get_file_deps(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, files.size(), Vector<String>());
return files[p_idx]->deps;
}
bool EditorFileSystemDirectory::get_file_import_is_valid(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, files.size(), false);
return files[p_idx]->import_valid;
}
uint64_t EditorFileSystemDirectory::get_file_modified_time(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, files.size(), 0);
return files[p_idx]->modified_time;
}
String EditorFileSystemDirectory::get_file_script_class_name(int p_idx) const {
return files[p_idx]->script_class_name;
}
String EditorFileSystemDirectory::get_file_script_class_extends(int p_idx) const {
return files[p_idx]->script_class_extends;
}
String EditorFileSystemDirectory::get_file_script_class_icon_path(int p_idx) const {
return files[p_idx]->script_class_icon_path;
}
StringName EditorFileSystemDirectory::get_file_type(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, files.size(), "");
return files[p_idx]->type;
}
String EditorFileSystemDirectory::get_name() {
return name;
}
EditorFileSystemDirectory *EditorFileSystemDirectory::get_parent() {
return parent;
}
void EditorFileSystemDirectory::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_subdir_count"), &EditorFileSystemDirectory::get_subdir_count);
ClassDB::bind_method(D_METHOD("get_subdir", "idx"), &EditorFileSystemDirectory::get_subdir);
ClassDB::bind_method(D_METHOD("get_file_count"), &EditorFileSystemDirectory::get_file_count);
ClassDB::bind_method(D_METHOD("get_file", "idx"), &EditorFileSystemDirectory::get_file);
ClassDB::bind_method(D_METHOD("get_file_path", "idx"), &EditorFileSystemDirectory::get_file_path);
ClassDB::bind_method(D_METHOD("get_file_type", "idx"), &EditorFileSystemDirectory::get_file_type);
ClassDB::bind_method(D_METHOD("get_file_script_class_name", "idx"), &EditorFileSystemDirectory::get_file_script_class_name);
ClassDB::bind_method(D_METHOD("get_file_script_class_extends", "idx"), &EditorFileSystemDirectory::get_file_script_class_extends);
ClassDB::bind_method(D_METHOD("get_file_import_is_valid", "idx"), &EditorFileSystemDirectory::get_file_import_is_valid);
ClassDB::bind_method(D_METHOD("get_name"), &EditorFileSystemDirectory::get_name);
ClassDB::bind_method(D_METHOD("get_path"), &EditorFileSystemDirectory::get_path);
ClassDB::bind_method(D_METHOD("get_parent"), &EditorFileSystemDirectory::get_parent);
ClassDB::bind_method(D_METHOD("find_file_index", "name"), &EditorFileSystemDirectory::find_file_index);
ClassDB::bind_method(D_METHOD("find_dir_index", "name"), &EditorFileSystemDirectory::find_dir_index);
}
EditorFileSystemDirectory::EditorFileSystemDirectory() {
modified_time = 0;
parent = nullptr;
verified = false;
}
EditorFileSystemDirectory::~EditorFileSystemDirectory() {
for (int i = 0; i < files.size(); i++) {
memdelete(files[i]);
}
for (int i = 0; i < subdirs.size(); i++) {
memdelete(subdirs[i]);
}
}
void EditorFileSystem::_scan_filesystem() {
ERR_FAIL_COND(!scanning || new_filesystem);
//read .fscache
String cpath;
sources_changed.clear();
file_cache.clear();
String project = ProjectSettings::get_singleton()->get_resource_path();
String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(CACHE_FILE_NAME);
FileAccess *f = FileAccess::open(fscache, FileAccess::READ);
bool first = true;
if (f) {
//read the disk cache
while (!f->eof_reached()) {
String l = f->get_line().strip_edges();
if (first) {
if (first_scan) {
// only use this on first scan, afterwards it gets ignored
// this is so on first reimport we synchronize versions, then
// we don't care until editor restart. This is for usability mainly so
// your workflow is not killed after changing a setting by forceful reimporting
// everything there is.
filesystem_settings_version_for_import = l.strip_edges();
if (filesystem_settings_version_for_import != ResourceFormatImporter::get_singleton()->get_import_settings_hash()) {
revalidate_import_files = true;
}
}
first = false;
continue;
}
if (l == String()) {
continue;
}
if (l.begins_with("::")) {
Vector<String> split = l.split("::");
ERR_CONTINUE(split.size() != 3);
String name = split[1];
cpath = name;
} else {
Vector<String> split = l.split("::");
ERR_CONTINUE(split.size() != 8);
String name = split[0];
String file;
file = name;
name = cpath.plus_file(name);
FileCache fc;
fc.type = split[1];
fc.modification_time = split[2].to_int();
fc.import_modification_time = split[3].to_int();
fc.import_valid = split[4].to_int() != 0;
fc.import_group_file = split[5].strip_edges();
fc.script_class_name = split[6].get_slice("<>", 0);
fc.script_class_extends = split[6].get_slice("<>", 1);
fc.script_class_icon_path = split[6].get_slice("<>", 2);
String deps = split[7].strip_edges();
if (deps.length()) {
Vector<String> dp = deps.split("<>");
for (int i = 0; i < dp.size(); i++) {
String path = dp[i];
fc.deps.push_back(path);
}
}
file_cache[name] = fc;
}
}
f->close();
memdelete(f);
}
String update_cache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file("filesystem_update4");
if (FileAccess::exists(update_cache)) {
{
FileAccessRef f2 = FileAccess::open(update_cache, FileAccess::READ);
String l = f2->get_line().strip_edges();
while (l != String()) {
file_cache.erase(l); //erase cache for this, so it gets updated
l = f2->get_line().strip_edges();
}
}
DirAccessRef d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
d->remove(update_cache); //bye bye update cache
}
EditorProgressBG scan_progress("efs", "ScanFS", 1000);
ScanProgress sp;
sp.low = 0;
sp.hi = 1;
sp.progress = &scan_progress;
new_filesystem = memnew(EditorFileSystemDirectory);
new_filesystem->parent = nullptr;
DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
d->change_dir("res://");
_scan_new_dir(new_filesystem, d, sp);
file_cache.clear(); //clear caches, no longer needed
memdelete(d);
if (!first_scan) {
//on the first scan this is done from the main thread after re-importing
_save_filesystem_cache();
}
scanning = false;
}
void EditorFileSystem::_save_filesystem_cache() {
group_file_cache.clear();
String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(CACHE_FILE_NAME);
FileAccess *f = FileAccess::open(fscache, FileAccess::WRITE);
ERR_FAIL_COND_MSG(!f, "Cannot create file '" + fscache + "'. Check user write permissions.");
f->store_line(filesystem_settings_version_for_import);
_save_filesystem_cache(filesystem, f);
f->close();
memdelete(f);
}
void EditorFileSystem::_thread_func(void *_userdata) {
EditorFileSystem *sd = (EditorFileSystem *)_userdata;
sd->_scan_filesystem();
}
bool EditorFileSystem::_test_for_reimport(const String &p_path, bool p_only_imported_files) {
if (!reimport_on_missing_imported_files && p_only_imported_files) {
return false;
}
if (!FileAccess::exists(p_path + ".import")) {
return true;
}
if (!ResourceFormatImporter::get_singleton()->are_import_settings_valid(p_path)) {
//reimport settings are not valid, reimport
return true;
}
Error err;
FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err);
if (!f) { //no import file, do reimport
return true;
}
VariantParser::StreamFile stream;
stream.f = f;
String assign;
Variant value;
VariantParser::Tag next_tag;
int lines = 0;
String error_text;
List<String> to_check;
String importer_name;
String source_file = "";
String source_md5 = "";
Vector<String> dest_files;
String dest_md5 = "";
int version = 0;
while (true) {
assign = Variant();
next_tag.fields.clear();
next_tag.name = String();
err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
if (err == ERR_FILE_EOF) {
break;
} else if (err != OK) {
ERR_PRINT("ResourceFormatImporter::load - '" + p_path + ".import:" + itos(lines) + "' error '" + error_text + "'.");
memdelete(f);
return false; //parse error, try reimport manually (Avoid reimport loop on broken file)
}
if (assign != String()) {
if (assign.begins_with("path")) {
to_check.push_back(value);
} else if (assign == "files") {
Array fa = value;
for (int i = 0; i < fa.size(); i++) {
to_check.push_back(fa[i]);
}
} else if (assign == "importer_version") {
version = value;
} else if (assign == "importer") {
importer_name = value;
} else if (!p_only_imported_files) {
if (assign == "source_file") {
source_file = value;
} else if (assign == "dest_files") {
dest_files = value;
}
}
} else if (next_tag.name != "remap" && next_tag.name != "deps") {
break;
}
}
memdelete(f);
Ref<ResourceImporter> importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name);
if (importer->get_format_version() > version) {
return true; // version changed, reimport
}
// Read the md5's from a separate file (so the import parameters aren't dependent on the file version
String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(p_path);
FileAccess *md5s = FileAccess::open(base_path + ".md5", FileAccess::READ, &err);
if (!md5s) { // No md5's stored for this resource
return true;
}
VariantParser::StreamFile md5_stream;
md5_stream.f = md5s;
while (true) {
assign = Variant();
next_tag.fields.clear();
next_tag.name = String();
err = VariantParser::parse_tag_assign_eof(&md5_stream, lines, error_text, next_tag, assign, value, nullptr, true);
if (err == ERR_FILE_EOF) {
break;
} else if (err != OK) {
ERR_PRINT("ResourceFormatImporter::load - '" + p_path + ".import.md5:" + itos(lines) + "' error '" + error_text + "'.");
memdelete(md5s);
return false; // parse error
}
if (assign != String()) {
if (!p_only_imported_files) {
if (assign == "source_md5") {
source_md5 = value;
} else if (assign == "dest_md5") {
dest_md5 = value;
}
}
}
}
memdelete(md5s);
//imported files are gone, reimport
for (List<String>::Element *E = to_check.front(); E; E = E->next()) {
if (!FileAccess::exists(E->get())) {
return true;
}
}
//check source md5 matching
if (!p_only_imported_files) {
if (source_file != String() && source_file != p_path) {
return true; //file was moved, reimport
}
if (source_md5 == String()) {
return true; //lacks md5, so just reimport
}
String md5 = FileAccess::get_md5(p_path);
if (md5 != source_md5) {
return true;
}
if (dest_files.size() && dest_md5 != String()) {
md5 = FileAccess::get_multiple_md5(dest_files);
if (md5 != dest_md5) {
return true;
}
}
}
return false; //nothing changed
}
bool EditorFileSystem::_update_scan_actions() {
sources_changed.clear();
bool fs_changed = false;
Vector<String> reimports;
Vector<String> reloads;
for (List<ItemAction>::Element *E = scan_actions.front(); E; E = E->next()) {
ItemAction &ia = E->get();
switch (ia.action) {
case ItemAction::ACTION_NONE: {
} break;
case ItemAction::ACTION_DIR_ADD: {
int idx = 0;
for (int i = 0; i < ia.dir->subdirs.size(); i++) {
if (ia.new_dir->name < ia.dir->subdirs[i]->name) {
break;
}
idx++;
}
if (idx == ia.dir->subdirs.size()) {
ia.dir->subdirs.push_back(ia.new_dir);
} else {
ia.dir->subdirs.insert(idx, ia.new_dir);
}
fs_changed = true;
} break;
case ItemAction::ACTION_DIR_REMOVE: {
ERR_CONTINUE(!ia.dir->parent);
ia.dir->parent->subdirs.erase(ia.dir);
memdelete(ia.dir);
fs_changed = true;
} break;
case ItemAction::ACTION_FILE_ADD: {
int idx = 0;
for (int i = 0; i < ia.dir->files.size(); i++) {
if (ia.new_file->file < ia.dir->files[i]->file) {
break;
}
idx++;
}
if (idx == ia.dir->files.size()) {
ia.dir->files.push_back(ia.new_file);
} else {
ia.dir->files.insert(idx, ia.new_file);
}
fs_changed = true;
} break;
case ItemAction::ACTION_FILE_REMOVE: {
int idx = ia.dir->find_file_index(ia.file);
ERR_CONTINUE(idx == -1);
_delete_internal_files(ia.dir->files[idx]->file);
memdelete(ia.dir->files[idx]);
ia.dir->files.remove(idx);
fs_changed = true;
} break;
case ItemAction::ACTION_FILE_TEST_REIMPORT: {
int idx = ia.dir->find_file_index(ia.file);
ERR_CONTINUE(idx == -1);
String full_path = ia.dir->get_file_path(idx);
if (_test_for_reimport(full_path, false)) {
//must reimport
reimports.push_back(full_path);
reimports.append_array(_get_dependencies(full_path));
} else {
//must not reimport, all was good
//update modified times, to avoid reimport
ia.dir->files[idx]->modified_time = FileAccess::get_modified_time(full_path);
ia.dir->files[idx]->import_modified_time = FileAccess::get_modified_time(full_path + ".import");
}
fs_changed = true;
} break;
case ItemAction::ACTION_FILE_RELOAD: {
int idx = ia.dir->find_file_index(ia.file);
ERR_CONTINUE(idx == -1);
String full_path = ia.dir->get_file_path(idx);
reloads.push_back(full_path);
} break;
}
}
if (reimports.size()) {
reimport_files(reimports);
}
if (first_scan) {
//only on first scan this is valid and updated, then settings changed.
revalidate_import_files = false;
filesystem_settings_version_for_import = ResourceFormatImporter::get_singleton()->get_import_settings_hash();
_save_filesystem_cache();
}
if (reloads.size()) {
emit_signal("resources_reload", reloads);
}
scan_actions.clear();
return fs_changed;
}
void EditorFileSystem::scan() {
if (false /*&& bool(Globals::get_singleton()->get("debug/disable_scan"))*/) {
return;
}
if (scanning || scanning_changes || thread) {
return;
}
_update_extensions();
abort_scan = false;
if (!use_threads) {
scanning = true;
scan_total = 0;
_scan_filesystem();
if (filesystem) {
memdelete(filesystem);
}
//file_type_cache.clear();
filesystem = new_filesystem;
new_filesystem = nullptr;
_update_scan_actions();
scanning = false;
emit_signal("filesystem_changed");
emit_signal("sources_changed", sources_changed.size() > 0);
_queue_update_script_classes();
first_scan = false;
} else {
ERR_FAIL_COND(thread);
set_process(true);
Thread::Settings s;
scanning = true;
scan_total = 0;
s.priority = Thread::PRIORITY_LOW;
thread = Thread::create(_thread_func, this, s);
//tree->hide();
//progress->show();
}
}
void EditorFileSystem::ScanProgress::update(int p_current, int p_total) const {
float ratio = low + ((hi - low) / p_total) * p_current;
progress->step(ratio * 1000);
EditorFileSystem::singleton->scan_total = ratio;
}
EditorFileSystem::ScanProgress EditorFileSystem::ScanProgress::get_sub(int p_current, int p_total) const {
ScanProgress sp = *this;
float slice = (sp.hi - sp.low) / p_total;
sp.low += slice * p_current;
sp.hi = slice;
return sp;
}
void EditorFileSystem::_scan_new_dir(EditorFileSystemDirectory *p_dir, DirAccess *da, const ScanProgress &p_progress) {
List<String> dirs;
List<String> files;
String cd = da->get_current_dir();
p_dir->modified_time = FileAccess::get_modified_time(cd);
da->list_dir_begin();
while (true) {
String f = da->get_next();
if (f == "") {
break;
}
if (da->current_is_hidden()) {
continue;
}
if (da->current_is_dir()) {
if (f.begins_with(".")) { // Ignore special and . / ..
continue;
}
if (FileAccess::exists(cd.plus_file(f).plus_file("project.godot"))) { // skip if another project inside this
continue;
}
if (FileAccess::exists(cd.plus_file(f).plus_file(".gdignore"))) { // skip if another project inside this
continue;
}
dirs.push_back(f);
} else {
files.push_back(f);
}
}
da->list_dir_end();
dirs.sort_custom<NaturalNoCaseComparator>();
files.sort_custom<NaturalNoCaseComparator>();
int total = dirs.size() + files.size();
int idx = 0;
for (List<String>::Element *E = dirs.front(); E; E = E->next(), idx++) {
if (da->change_dir(E->get()) == OK) {
String d = da->get_current_dir();
if (d == cd || !d.begins_with(cd)) {
da->change_dir(cd); //avoid recursion
} else {
EditorFileSystemDirectory *efd = memnew(EditorFileSystemDirectory);
efd->parent = p_dir;
efd->name = E->get();
_scan_new_dir(efd, da, p_progress.get_sub(idx, total));
int idx2 = 0;
for (int i = 0; i < p_dir->subdirs.size(); i++) {
if (efd->name < p_dir->subdirs[i]->name) {
break;
}
idx2++;
}
if (idx2 == p_dir->subdirs.size()) {
p_dir->subdirs.push_back(efd);
} else {
p_dir->subdirs.insert(idx2, efd);
}
da->change_dir("..");
}
} else {
ERR_PRINT("Cannot go into subdir '" + E->get() + "'.");
}
p_progress.update(idx, total);
}
for (List<String>::Element *E = files.front(); E; E = E->next(), idx++) {
String ext = E->get().get_extension().to_lower();
if (!valid_extensions.has(ext)) {
continue; //invalid
}
EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo);
fi->file = E->get();
String path = cd.plus_file(fi->file);
FileCache *fc = file_cache.getptr(path);
uint64_t mt = FileAccess::get_modified_time(path);
if (import_extensions.has(ext)) {
//is imported
uint64_t import_mt = 0;
if (FileAccess::exists(path + ".import")) {
import_mt = FileAccess::get_modified_time(path + ".import");
}
if (fc && fc->modification_time == mt && fc->import_modification_time == import_mt && !_test_for_reimport(path, true)) {
fi->type = fc->type;
fi->deps = fc->deps;
fi->modified_time = fc->modification_time;
fi->import_modified_time = fc->import_modification_time;
fi->import_valid = fc->import_valid;
fi->script_class_name = fc->script_class_name;
fi->import_group_file = fc->import_group_file;
fi->script_class_extends = fc->script_class_extends;
fi->script_class_icon_path = fc->script_class_icon_path;
if (revalidate_import_files && !ResourceFormatImporter::get_singleton()->are_import_settings_valid(path)) {
ItemAction ia;
ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT;
ia.dir = p_dir;
ia.file = E->get();
scan_actions.push_back(ia);
}
if (fc->type == String()) {
fi->type = ResourceLoader::get_resource_type(path);
fi->import_group_file = ResourceLoader::get_import_group_file(path);
//there is also the chance that file type changed due to reimport, must probably check this somehow here (or kind of note it for next time in another file?)
//note: I think this should not happen any longer..
}
} else {
fi->type = ResourceFormatImporter::get_singleton()->get_resource_type(path);
fi->import_group_file = ResourceFormatImporter::get_singleton()->get_import_group_file(path);
fi->script_class_name = _get_global_script_class(fi->type, path, &fi->script_class_extends, &fi->script_class_icon_path);
fi->modified_time = 0;
fi->import_modified_time = 0;
fi->import_valid = ResourceLoader::is_import_valid(path);
ItemAction ia;
ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT;
ia.dir = p_dir;
ia.file = E->get();
scan_actions.push_back(ia);
}
} else {
if (fc && fc->modification_time == mt) {
//not imported, so just update type if changed
fi->type = fc->type;
fi->modified_time = fc->modification_time;
fi->deps = fc->deps;
fi->import_modified_time = 0;
fi->import_valid = true;
fi->script_class_name = fc->script_class_name;
fi->script_class_extends = fc->script_class_extends;
fi->script_class_icon_path = fc->script_class_icon_path;
} else {
//new or modified time
fi->type = ResourceLoader::get_resource_type(path);
fi->script_class_name = _get_global_script_class(fi->type, path, &fi->script_class_extends, &fi->script_class_icon_path);
fi->deps = _get_dependencies(path);
fi->modified_time = mt;
fi->import_modified_time = 0;
fi->import_valid = true;
}
}
for (int i = 0; i < ScriptServer::get_language_count(); i++) {
ScriptLanguage *lang = ScriptServer::get_language(i);
if (lang->supports_documentation() && fi->type == lang->get_type()) {
Ref<Script> script = ResourceLoader::load(path);
if (script == nullptr) {
continue;
}
const Vector<DocData::ClassDoc> &docs = script->get_documentation();
for (int j = 0; j < docs.size(); j++) {
EditorHelp::get_doc_data()->add_doc(docs[j]);
}
}
}
p_dir->files.push_back(fi);
p_progress.update(idx, total);
}
}
void EditorFileSystem::_scan_fs_changes(EditorFileSystemDirectory *p_dir, const ScanProgress &p_progress) {
uint64_t current_mtime = FileAccess::get_modified_time(p_dir->get_path());
bool updated_dir = false;
String cd = p_dir->get_path();
if (current_mtime != p_dir->modified_time || using_fat32_or_exfat) {
updated_dir = true;
p_dir->modified_time = current_mtime;
//ooooops, dir changed, see what's going on
//first mark everything as veryfied
for (int i = 0; i < p_dir->files.size(); i++) {
p_dir->files[i]->verified = false;
}
for (int i = 0; i < p_dir->subdirs.size(); i++) {
p_dir->get_subdir(i)->verified = false;
}
//then scan files and directories and check what's different
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
da->change_dir(cd);
da->list_dir_begin();
while (true) {
String f = da->get_next();
if (f == "") {
break;
}
if (da->current_is_hidden()) {
continue;
}
if (da->current_is_dir()) {
if (f.begins_with(".")) { // Ignore special and . / ..
continue;
}
int idx = p_dir->find_dir_index(f);
if (idx == -1) {
if (FileAccess::exists(cd.plus_file(f).plus_file("project.godot"))) { // skip if another project inside this
continue;
}
if (FileAccess::exists(cd.plus_file(f).plus_file(".gdignore"))) { // skip if another project inside this
continue;
}
EditorFileSystemDirectory *efd = memnew(EditorFileSystemDirectory);
efd->parent = p_dir;
efd->name = f;
DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
d->change_dir(cd.plus_file(f));
_scan_new_dir(efd, d, p_progress.get_sub(1, 1));
memdelete(d);
ItemAction ia;
ia.action = ItemAction::ACTION_DIR_ADD;
ia.dir = p_dir;
ia.file = f;
ia.new_dir = efd;
scan_actions.push_back(ia);
} else {
p_dir->subdirs[idx]->verified = true;
}
} else {
String ext = f.get_extension().to_lower();
if (!valid_extensions.has(ext)) {
continue; //invalid
}
int idx = p_dir->find_file_index(f);
if (idx == -1) {
//never seen this file, add actition to add it
EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo);
fi->file = f;
String path = cd.plus_file(fi->file);
fi->modified_time = FileAccess::get_modified_time(path);
fi->import_modified_time = 0;
fi->type = ResourceLoader::get_resource_type(path);
fi->script_class_name = _get_global_script_class(fi->type, path, &fi->script_class_extends, &fi->script_class_icon_path);
fi->import_valid = ResourceLoader::is_import_valid(path);
fi->import_group_file = ResourceLoader::get_import_group_file(path);
{
ItemAction ia;
ia.action = ItemAction::ACTION_FILE_ADD;
ia.dir = p_dir;
ia.file = f;
ia.new_file = fi;
scan_actions.push_back(ia);
}
if (import_extensions.has(ext)) {
//if it can be imported, and it was added, it needs to be reimported
ItemAction ia;
ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT;
ia.dir = p_dir;
ia.file = f;
scan_actions.push_back(ia);
}
} else {
p_dir->files[idx]->verified = true;
}
}
}
da->list_dir_end();
memdelete(da);
}
for (int i = 0; i < p_dir->files.size(); i++) {
if (updated_dir && !p_dir->files[i]->verified) {
//this file was removed, add action to remove it
ItemAction ia;
ia.action = ItemAction::ACTION_FILE_REMOVE;
ia.dir = p_dir;
ia.file = p_dir->files[i]->file;
scan_actions.push_back(ia);
continue;
}
String path = cd.plus_file(p_dir->files[i]->file);
if (import_extensions.has(p_dir->files[i]->file.get_extension().to_lower())) {
//check here if file must be imported or not
uint64_t mt = FileAccess::get_modified_time(path);
bool reimport = false;
if (mt != p_dir->files[i]->modified_time) {
reimport = true; //it was modified, must be reimported.
} else if (!FileAccess::exists(path + ".import")) {
reimport = true; //no .import file, obviously reimport
} else {
uint64_t import_mt = FileAccess::get_modified_time(path + ".import");
if (import_mt != p_dir->files[i]->import_modified_time) {
reimport = true;
} else if (_test_for_reimport(path, true)) {
reimport = true;
}
}
if (reimport) {
ItemAction ia;
ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT;
ia.dir = p_dir;
ia.file = p_dir->files[i]->file;
scan_actions.push_back(ia);
}
} else if (ResourceCache::has(path)) { //test for potential reload
uint64_t mt = FileAccess::get_modified_time(path);
if (mt != p_dir->files[i]->modified_time) {
p_dir->files[i]->modified_time = mt; //save new time, but test for reload
ItemAction ia;
ia.action = ItemAction::ACTION_FILE_RELOAD;
ia.dir = p_dir;
ia.file = p_dir->files[i]->file;
scan_actions.push_back(ia);
}
}
}
for (int i = 0; i < p_dir->subdirs.size(); i++) {
if (updated_dir && !p_dir->subdirs[i]->verified) {
//this directory was removed, add action to remove it
ItemAction ia;
ia.action = ItemAction::ACTION_DIR_REMOVE;
ia.dir = p_dir->subdirs[i];
scan_actions.push_back(ia);
continue;
}
_scan_fs_changes(p_dir->get_subdir(i), p_progress);
}
}
void EditorFileSystem::_delete_internal_files(String p_file) {
if (FileAccess::exists(p_file + ".import")) {
List<String> paths;
ResourceFormatImporter::get_singleton()->get_internal_resource_path_list(p_file, &paths);
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
for (List<String>::Element *E = paths.front(); E; E = E->next()) {
da->remove(E->get());
}
da->remove(p_file + ".import");
memdelete(da);
}
}
void EditorFileSystem::_thread_func_sources(void *_userdata) {
EditorFileSystem *efs = (EditorFileSystem *)_userdata;
if (efs->filesystem) {
EditorProgressBG pr("sources", TTR("ScanSources"), 1000);
ScanProgress sp;
sp.progress = ≺
sp.hi = 1;
sp.low = 0;
efs->_scan_fs_changes(efs->filesystem, sp);
}
efs->scanning_changes_done = true;
}
void EditorFileSystem::scan_changes() {
if (first_scan || // Prevent a premature changes scan from inhibiting the first full scan
scanning || scanning_changes || thread) {
scan_changes_pending = true;
set_process(true);
return;
}
_update_extensions();
sources_changed.clear();
scanning_changes = true;
scanning_changes_done = false;
abort_scan = false;
if (!use_threads) {
if (filesystem) {
EditorProgressBG pr("sources", TTR("ScanSources"), 1000);
ScanProgress sp;
sp.progress = ≺
sp.hi = 1;
sp.low = 0;
scan_total = 0;
_scan_fs_changes(filesystem, sp);
if (_update_scan_actions()) {
emit_signal("filesystem_changed");
}
}
scanning_changes = false;
scanning_changes_done = true;
emit_signal("sources_changed", sources_changed.size() > 0);
} else {
ERR_FAIL_COND(thread_sources);
set_process(true);
scan_total = 0;
Thread::Settings s;
s.priority = Thread::PRIORITY_LOW;
thread_sources = Thread::create(_thread_func_sources, this, s);
}
}
void EditorFileSystem::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
call_deferred("scan"); //this should happen after every editor node entered the tree
} break;
case NOTIFICATION_EXIT_TREE: {
Thread *active_thread = thread ? thread : thread_sources;
if (use_threads && active_thread) {
//abort thread if in progress
abort_scan = true;
while (scanning) {
OS::get_singleton()->delay_usec(1000);
}
Thread::wait_to_finish(active_thread);
memdelete(active_thread);
thread = nullptr;
thread_sources = nullptr;
WARN_PRINT("Scan thread aborted...");
set_process(false);
}
if (filesystem) {
memdelete(filesystem);
}
if (new_filesystem) {
memdelete(new_filesystem);
}
filesystem = nullptr;
new_filesystem = nullptr;
} break;
case NOTIFICATION_PROCESS: {
if (use_threads) {
if (scanning_changes) {
if (scanning_changes_done) {
scanning_changes = false;
set_process(false);
Thread::wait_to_finish(thread_sources);
memdelete(thread_sources);
thread_sources = nullptr;
if (_update_scan_actions()) {
emit_signal("filesystem_changed");
}
emit_signal("sources_changed", sources_changed.size() > 0);
_queue_update_script_classes();
first_scan = false;
}
} else if (!scanning && thread) {
set_process(false);
if (filesystem) {
memdelete(filesystem);
}
filesystem = new_filesystem;
new_filesystem = nullptr;
Thread::wait_to_finish(thread);
memdelete(thread);
thread = nullptr;
_update_scan_actions();
emit_signal("filesystem_changed");
emit_signal("sources_changed", sources_changed.size() > 0);
_queue_update_script_classes();
first_scan = false;
}
if (!is_processing() && scan_changes_pending) {
scan_changes_pending = false;
scan_changes();
}
}
} break;
}
}
bool EditorFileSystem::is_scanning() const {
return scanning || scanning_changes;
}
float EditorFileSystem::get_scanning_progress() const {
return scan_total;
}
EditorFileSystemDirectory *EditorFileSystem::get_filesystem() {
return filesystem;
}
void EditorFileSystem::_save_filesystem_cache(EditorFileSystemDirectory *p_dir, FileAccess *p_file) {
if (!p_dir) {
return; //none
}
p_file->store_line("::" + p_dir->get_path() + "::" + String::num(p_dir->modified_time));
for (int i = 0; i < p_dir->files.size(); i++) {
if (p_dir->files[i]->import_group_file != String()) {
group_file_cache.insert(p_dir->files[i]->import_group_file);
}
String s = p_dir->files[i]->file + "::" + p_dir->files[i]->type + "::" + itos(p_dir->files[i]->modified_time) + "::" + itos(p_dir->files[i]->import_modified_time) + "::" + itos(p_dir->files[i]->import_valid) + "::" + p_dir->files[i]->import_group_file + "::" + p_dir->files[i]->script_class_name + "<>" + p_dir->files[i]->script_class_extends + "<>" + p_dir->files[i]->script_class_icon_path;
s += "::";
for (int j = 0; j < p_dir->files[i]->deps.size(); j++) {
if (j > 0) {
s += "<>";
}
s += p_dir->files[i]->deps[j];
}
p_file->store_line(s);
}
for (int i = 0; i < p_dir->subdirs.size(); i++) {
_save_filesystem_cache(p_dir->subdirs[i], p_file);
}
}
bool EditorFileSystem::_find_file(const String &p_file, EditorFileSystemDirectory **r_d, int &r_file_pos) const {
//todo make faster
if (!filesystem || scanning) {
return false;
}
String f = ProjectSettings::get_singleton()->localize_path(p_file);
if (!f.begins_with("res://")) {
return false;
}
f = f.substr(6, f.length());
f = f.replace("\\", "/");
Vector<String> path = f.split("/");
if (path.size() == 0) {
return false;
}
String file = path[path.size() - 1];
path.resize(path.size() - 1);
EditorFileSystemDirectory *fs = filesystem;
for (int i = 0; i < path.size(); i++) {
if (path[i].begins_with(".")) {
return false;
}
int idx = -1;
for (int j = 0; j < fs->get_subdir_count(); j++) {
if (fs->get_subdir(j)->get_name() == path[i]) {
idx = j;
break;
}
}
if (idx == -1) {
//does not exist, create i guess?
EditorFileSystemDirectory *efsd = memnew(EditorFileSystemDirectory);
efsd->name = path[i];
efsd->parent = fs;
int idx2 = 0;
for (int j = 0; j < fs->get_subdir_count(); j++) {
if (efsd->name < fs->get_subdir(j)->get_name()) {
break;
}
idx2++;
}
if (idx2 == fs->get_subdir_count()) {
fs->subdirs.push_back(efsd);
} else {
fs->subdirs.insert(idx2, efsd);
}
fs = efsd;
} else {
fs = fs->get_subdir(idx);
}
}
int cpos = -1;
for (int i = 0; i < fs->files.size(); i++) {
if (fs->files[i]->file == file) {
cpos = i;
break;
}
}
r_file_pos = cpos;
*r_d = fs;
return cpos != -1;
}
String EditorFileSystem::get_file_type(const String &p_file) const {
EditorFileSystemDirectory *fs = nullptr;
int cpos = -1;
if (!_find_file(p_file, &fs, cpos)) {
return "";
}
return fs->files[cpos]->type;
}
EditorFileSystemDirectory *EditorFileSystem::find_file(const String &p_file, int *r_index) const {
if (!filesystem || scanning) {
return nullptr;
}
EditorFileSystemDirectory *fs = nullptr;
int cpos = -1;
if (!_find_file(p_file, &fs, cpos)) {
return nullptr;
}
if (r_index) {
*r_index = cpos;
}
return fs;
}
EditorFileSystemDirectory *EditorFileSystem::get_filesystem_path(const String &p_path) {
if (!filesystem || scanning) {
return nullptr;
}
String f = ProjectSettings::get_singleton()->localize_path(p_path);
if (!f.begins_with("res://")) {
return nullptr;
}
f = f.substr(6, f.length());
f = f.replace("\\", "/");
if (f == String()) {
return filesystem;
}
if (f.ends_with("/")) {
f = f.substr(0, f.length() - 1);
}
Vector<String> path = f.split("/");
if (path.size() == 0) {
return nullptr;
}
EditorFileSystemDirectory *fs = filesystem;
for (int i = 0; i < path.size(); i++) {
int idx = -1;
for (int j = 0; j < fs->get_subdir_count(); j++) {
if (fs->get_subdir(j)->get_name() == path[i]) {
idx = j;
break;
}
}
if (idx == -1) {
return nullptr;
} else {
fs = fs->get_subdir(idx);
}
}
return fs;
}
void EditorFileSystem::_save_late_updated_files() {
//files that already existed, and were modified, need re-scanning for dependencies upon project restart. This is done via saving this special file
String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file("filesystem_update4");
FileAccessRef f = FileAccess::open(fscache, FileAccess::WRITE);
ERR_FAIL_COND_MSG(!f, "Cannot create file '" + fscache + "'. Check user write permissions.");
for (Set<String>::Element *E = late_update_files.front(); E; E = E->next()) {
f->store_line(E->get());
}
}
Vector<String> EditorFileSystem::_get_dependencies(const String &p_path) {
List<String> deps;
ResourceLoader::get_dependencies(p_path, &deps);
Vector<String> ret;
for (List<String>::Element *E = deps.front(); E; E = E->next()) {
ret.push_back(E->get());
}
return ret;
}
String EditorFileSystem::_get_global_script_class(const String &p_type, const String &p_path, String *r_extends, String *r_icon_path) const {
for (int i = 0; i < ScriptServer::get_language_count(); i++) {
if (ScriptServer::get_language(i)->handles_global_class_type(p_type)) {
String global_name;
String extends;
String icon_path;
global_name = ScriptServer::get_language(i)->get_global_class_name(p_path, &extends, &icon_path);
*r_extends = extends;
*r_icon_path = icon_path;
return global_name;
}
}
*r_extends = String();
*r_icon_path = String();
return String();
}
void EditorFileSystem::_scan_script_classes(EditorFileSystemDirectory *p_dir) {
int filecount = p_dir->files.size();
const EditorFileSystemDirectory::FileInfo *const *files = p_dir->files.ptr();
for (int i = 0; i < filecount; i++) {
if (files[i]->script_class_name == String()) {
continue;
}
String lang;
for (int j = 0; j < ScriptServer::get_language_count(); j++) {
if (ScriptServer::get_language(j)->handles_global_class_type(files[i]->type)) {
lang = ScriptServer::get_language(j)->get_name();
}
}
ScriptServer::add_global_class(files[i]->script_class_name, files[i]->script_class_extends, lang, p_dir->get_file_path(i));
EditorNode::get_editor_data().script_class_set_icon_path(files[i]->script_class_name, files[i]->script_class_icon_path);
EditorNode::get_editor_data().script_class_set_name(files[i]->file, files[i]->script_class_name);
}
for (int i = 0; i < p_dir->get_subdir_count(); i++) {
_scan_script_classes(p_dir->get_subdir(i));
}
}
void EditorFileSystem::update_script_classes() {
if (!update_script_classes_queued) {
return;
}
update_script_classes_queued = false;
ScriptServer::global_classes_clear();
if (get_filesystem()) {
_scan_script_classes(get_filesystem());
}
ScriptServer::save_global_classes();
EditorNode::get_editor_data().script_class_save_icon_paths();
// Rescan custom loaders and savers.
// Doing the following here because the `filesystem_changed` signal fires multiple times and isn't always followed by script classes update.
// So I thought it's better to do this when script classes really get updated
ResourceLoader::remove_custom_loaders();
ResourceLoader::add_custom_loaders();
ResourceSaver::remove_custom_savers();
ResourceSaver::add_custom_savers();
}
void EditorFileSystem::_queue_update_script_classes() {
if (update_script_classes_queued) {
return;
}
update_script_classes_queued = true;
call_deferred("update_script_classes");
}
void EditorFileSystem::update_file(const String &p_file) {
EditorFileSystemDirectory *fs = nullptr;
int cpos = -1;
if (!_find_file(p_file, &fs, cpos)) {
if (!fs) {
return;
}
}
if (!FileAccess::exists(p_file)) {
//was removed
_delete_internal_files(p_file);
if (cpos != -1) { // Might've never been part of the editor file system (*.* files deleted in Open dialog).
memdelete(fs->files[cpos]);
fs->files.remove(cpos);
}
call_deferred("emit_signal", "filesystem_changed"); //update later
_queue_update_script_classes();
return;
}
String type = ResourceLoader::get_resource_type(p_file);
if (cpos == -1) {
//the file did not exist, it was added
late_added_files.insert(p_file); //remember that it was added. This mean it will be scanned and imported on editor restart
int idx = 0;
for (int i = 0; i < fs->files.size(); i++) {
if (p_file < fs->files[i]->file) {
break;
}
idx++;
}
EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo);
fi->file = p_file.get_file();
fi->import_modified_time = 0;
fi->import_valid = ResourceLoader::is_import_valid(p_file);
if (idx == fs->files.size()) {
fs->files.push_back(fi);
} else {
fs->files.insert(idx, fi);
}
cpos = idx;
} else {
//the file exists and it was updated, and was not added in this step.
//this means we must force upon next restart to scan it again, to get proper type and dependencies
late_update_files.insert(p_file);
_save_late_updated_files(); //files need to be updated in the re-scan
}
fs->files[cpos]->type = type;
fs->files[cpos]->script_class_name = _get_global_script_class(type, p_file, &fs->files[cpos]->script_class_extends, &fs->files[cpos]->script_class_icon_path);
fs->files[cpos]->import_group_file = ResourceLoader::get_import_group_file(p_file);
fs->files[cpos]->modified_time = FileAccess::get_modified_time(p_file);
fs->files[cpos]->deps = _get_dependencies(p_file);
fs->files[cpos]->import_valid = ResourceLoader::is_import_valid(p_file);
// Update preview
EditorResourcePreview::get_singleton()->check_for_invalidation(p_file);
call_deferred("emit_signal", "filesystem_changed"); //update later
_queue_update_script_classes();
}
Error EditorFileSystem::_reimport_group(const String &p_group_file, const Vector<String> &p_files) {
String importer_name;
Map<String, Map<StringName, Variant>> source_file_options;
Map<String, String> base_paths;
for (int i = 0; i < p_files.size(); i++) {
Ref<ConfigFile> config;
config.instance();
Error err = config->load(p_files[i] + ".import");
ERR_CONTINUE(err != OK);
ERR_CONTINUE(!config->has_section_key("remap", "importer"));
String file_importer_name = config->get_value("remap", "importer");
ERR_CONTINUE(file_importer_name == String());
if (importer_name != String() && importer_name != file_importer_name) {
print_line("one importer '" + importer_name + "' the other '" + file_importer_name + "'.");
EditorNode::get_singleton()->show_warning(vformat(TTR("There are multiple importers for different types pointing to file %s, import aborted"), p_group_file));
ERR_FAIL_V(ERR_FILE_CORRUPT);
}
source_file_options[p_files[i]] = Map<StringName, Variant>();
importer_name = file_importer_name;
Ref<ResourceImporter> importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name);
ERR_FAIL_COND_V(!importer.is_valid(), ERR_FILE_CORRUPT);
List<ResourceImporter::ImportOption> options;
importer->get_import_options(&options);
//set default values
for (List<ResourceImporter::ImportOption>::Element *E = options.front(); E; E = E->next()) {
source_file_options[p_files[i]][E->get().option.name] = E->get().default_value;
}
if (config->has_section("params")) {
List<String> sk;
config->get_section_keys("params", &sk);
for (List<String>::Element *E = sk.front(); E; E = E->next()) {
String param = E->get();
Variant value = config->get_value("params", param);
//override with whathever is in file
source_file_options[p_files[i]][param] = value;
}
}
base_paths[p_files[i]] = ResourceFormatImporter::get_singleton()->get_import_base_path(p_files[i]);
}
ERR_FAIL_COND_V(importer_name == String(), ERR_UNCONFIGURED);
Ref<ResourceImporter> importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name);
Error err = importer->import_group_file(p_group_file, source_file_options, base_paths);
//all went well, overwrite config files with proper remaps and md5s
for (Map<String, Map<StringName, Variant>>::Element *E = source_file_options.front(); E; E = E->next()) {
const String &file = E->key();
String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(file);
FileAccessRef f = FileAccess::open(file + ".import", FileAccess::WRITE);
ERR_FAIL_COND_V_MSG(!f, ERR_FILE_CANT_OPEN, "Cannot open import file '" + file + ".import'.");
//write manually, as order matters ([remap] has to go first for performance).
f->store_line("[remap]");
f->store_line("");
f->store_line("importer=\"" + importer->get_importer_name() + "\"");
int version = importer->get_format_version();
if (version > 0) {
f->store_line("importer_version=" + itos(version));
}
if (importer->get_resource_type() != "") {
f->store_line("type=\"" + importer->get_resource_type() + "\"");
}
Vector<String> dest_paths;
if (err == OK) {
String path = base_path + "." + importer->get_save_extension();
f->store_line("path=\"" + path + "\"");
dest_paths.push_back(path);
}
f->store_line("group_file=" + Variant(p_group_file).get_construct_string());
if (err == OK) {
f->store_line("valid=true");
} else {
f->store_line("valid=false");
}
f->store_line("[deps]\n");
f->store_line("");
f->store_line("source_file=" + Variant(file).get_construct_string());
if (dest_paths.size()) {
Array dp;
for (int i = 0; i < dest_paths.size(); i++) {
dp.push_back(dest_paths[i]);
}
f->store_line("dest_files=" + Variant(dp).get_construct_string() + "\n");
}
f->store_line("[params]");
f->store_line("");
//store options in provided order, to avoid file changing. Order is also important because first match is accepted first.
List<ResourceImporter::ImportOption> options;
importer->get_import_options(&options);
//set default values
for (List<ResourceImporter::ImportOption>::Element *F = options.front(); F; F = F->next()) {
String base = F->get().option.name;
Variant v = F->get().default_value;
if (source_file_options[file].has(base)) {
v = source_file_options[file][base];
}
String value;
VariantWriter::write_to_string(v, value);
f->store_line(base + "=" + value);
}
f->close();
// Store the md5's of the various files. These are stored separately so that the .import files can be version controlled.
FileAccessRef md5s = FileAccess::open(base_path + ".md5", FileAccess::WRITE);
ERR_FAIL_COND_V_MSG(!md5s, ERR_FILE_CANT_OPEN, "Cannot open MD5 file '" + base_path + ".md5'.");
md5s->store_line("source_md5=\"" + FileAccess::get_md5(file) + "\"");
if (dest_paths.size()) {
md5s->store_line("dest_md5=\"" + FileAccess::get_multiple_md5(dest_paths) + "\"\n");
}
md5s->close();
EditorFileSystemDirectory *fs = nullptr;
int cpos = -1;
bool found = _find_file(file, &fs, cpos);
ERR_FAIL_COND_V_MSG(!found, ERR_UNCONFIGURED, "Can't find file '" + file + "'.");
//update modified times, to avoid reimport
fs->files[cpos]->modified_time = FileAccess::get_modified_time(file);
fs->files[cpos]->import_modified_time = FileAccess::get_modified_time(file + ".import");
fs->files[cpos]->deps = _get_dependencies(file);
fs->files[cpos]->type = importer->get_resource_type();
fs->files[cpos]->import_valid = err == OK;
//if file is currently up, maybe the source it was loaded from changed, so import math must be updated for it
//to reload properly
if (ResourceCache::has(file)) {
Resource *r = ResourceCache::get(file);
if (r->get_import_path() != String()) {
String dst_path = ResourceFormatImporter::get_singleton()->get_internal_resource_path(file);
r->set_import_path(dst_path);
r->set_import_last_modified_time(0);
}
}
EditorResourcePreview::get_singleton()->check_for_invalidation(file);
}
return err;
}
void EditorFileSystem::_reimport_file(const String &p_file) {
EditorFileSystemDirectory *fs = nullptr;
int cpos = -1;
bool found = _find_file(p_file, &fs, cpos);
ERR_FAIL_COND_MSG(!found, "Can't find file '" + p_file + "'.");
//try to obtain existing params
Map<StringName, Variant> params;
String importer_name;
if (FileAccess::exists(p_file + ".import")) {
//use existing
Ref<ConfigFile> cf;
cf.instance();
Error err = cf->load(p_file + ".import");
if (err == OK) {
if (cf->has_section("params")) {
List<String> sk;
cf->get_section_keys("params", &sk);
for (List<String>::Element *E = sk.front(); E; E = E->next()) {
params[E->get()] = cf->get_value("params", E->get());
}
}
if (cf->has_section("remap")) {
importer_name = cf->get_value("remap", "importer");
}
}
} else {
late_added_files.insert(p_file); //imported files do not call update_file(), but just in case..
}
Ref<ResourceImporter> importer;
bool load_default = false;
//find the importer
if (importer_name != "") {
importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name);
}
if (importer.is_null()) {
//not found by name, find by extension
importer = ResourceFormatImporter::get_singleton()->get_importer_by_extension(p_file.get_extension());
load_default = true;
if (importer.is_null()) {
ERR_PRINT("BUG: File queued for import, but can't be imported, importer for type '" + importer_name + "' not found.");
ERR_FAIL();
}
}
//mix with default params, in case a parameter is missing
List<ResourceImporter::ImportOption> opts;
importer->get_import_options(&opts);
for (List<ResourceImporter::ImportOption>::Element *E = opts.front(); E; E = E->next()) {
if (!params.has(E->get().option.name)) { //this one is not present
params[E->get().option.name] = E->get().default_value;
}
}
if (load_default && ProjectSettings::get_singleton()->has_setting("importer_defaults/" + importer->get_importer_name())) {
//use defaults if exist
Dictionary d = ProjectSettings::get_singleton()->get("importer_defaults/" + importer->get_importer_name());
List<Variant> v;
d.get_key_list(&v);
for (List<Variant>::Element *E = v.front(); E; E = E->next()) {
params[E->get()] = d[E->get()];
}
}
//finally, perform import!!
String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(p_file);
List<String> import_variants;
List<String> gen_files;
Variant metadata;
Error err = importer->import(p_file, base_path, params, &import_variants, &gen_files, &metadata);
if (err != OK) {
ERR_PRINT("Error importing '" + p_file + "'.");
}
//as import is complete, save the .import file
FileAccess *f = FileAccess::open(p_file + ".import", FileAccess::WRITE);
ERR_FAIL_COND_MSG(!f, "Cannot open file from path '" + p_file + ".import'.");
//write manually, as order matters ([remap] has to go first for performance).
f->store_line("[remap]");
f->store_line("");
f->store_line("importer=\"" + importer->get_importer_name() + "\"");
int version = importer->get_format_version();
if (version > 0) {
f->store_line("importer_version=" + itos(version));
}
if (importer->get_resource_type() != "") {
f->store_line("type=\"" + importer->get_resource_type() + "\"");
}
Vector<String> dest_paths;
if (err == OK) {
if (importer->get_save_extension() == "") {
//no path
} else if (import_variants.size()) {
//import with variants
for (List<String>::Element *E = import_variants.front(); E; E = E->next()) {
String path = base_path.c_escape() + "." + E->get() + "." + importer->get_save_extension();
f->store_line("path." + E->get() + "=\"" + path + "\"");
dest_paths.push_back(path);
}
} else {
String path = base_path + "." + importer->get_save_extension();
f->store_line("path=\"" + path + "\"");
dest_paths.push_back(path);
}
} else {
f->store_line("valid=false");
}
if (metadata != Variant()) {
f->store_line("metadata=" + metadata.get_construct_string());
}
f->store_line("");
f->store_line("[deps]\n");
if (gen_files.size()) {
Array genf;
for (List<String>::Element *E = gen_files.front(); E; E = E->next()) {
genf.push_back(E->get());
dest_paths.push_back(E->get());
}
String value;
VariantWriter::write_to_string(genf, value);
f->store_line("files=" + value);
f->store_line("");
}
f->store_line("source_file=" + Variant(p_file).get_construct_string());
if (dest_paths.size()) {
Array dp;
for (int i = 0; i < dest_paths.size(); i++) {
dp.push_back(dest_paths[i]);
}
f->store_line("dest_files=" + Variant(dp).get_construct_string() + "\n");
}
f->store_line("[params]");
f->store_line("");
//store options in provided order, to avoid file changing. Order is also important because first match is accepted first.
for (List<ResourceImporter::ImportOption>::Element *E = opts.front(); E; E = E->next()) {
String base = E->get().option.name;
String value;
VariantWriter::write_to_string(params[base], value);
f->store_line(base + "=" + value);
}
f->close();
memdelete(f);
// Store the md5's of the various files. These are stored separately so that the .import files can be version controlled.
FileAccess *md5s = FileAccess::open(base_path + ".md5", FileAccess::WRITE);
ERR_FAIL_COND_MSG(!md5s, "Cannot open MD5 file '" + base_path + ".md5'.");
md5s->store_line("source_md5=\"" + FileAccess::get_md5(p_file) + "\"");
if (dest_paths.size()) {
md5s->store_line("dest_md5=\"" + FileAccess::get_multiple_md5(dest_paths) + "\"\n");
}
md5s->close();
memdelete(md5s);
//update modified times, to avoid reimport
fs->files[cpos]->modified_time = FileAccess::get_modified_time(p_file);
fs->files[cpos]->import_modified_time = FileAccess::get_modified_time(p_file + ".import");
fs->files[cpos]->deps = _get_dependencies(p_file);
fs->files[cpos]->type = importer->get_resource_type();
fs->files[cpos]->import_valid = ResourceLoader::is_import_valid(p_file);
//if file is currently up, maybe the source it was loaded from changed, so import math must be updated for it
//to reload properly
if (ResourceCache::has(p_file)) {
Resource *r = ResourceCache::get(p_file);
if (r->get_import_path() != String()) {
String dst_path = ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_file);
r->set_import_path(dst_path);
r->set_import_last_modified_time(0);
}
}
EditorResourcePreview::get_singleton()->check_for_invalidation(p_file);
}
void EditorFileSystem::_find_group_files(EditorFileSystemDirectory *efd, Map<String, Vector<String>> &group_files, Set<String> &groups_to_reimport) {
int fc = efd->files.size();
const EditorFileSystemDirectory::FileInfo *const *files = efd->files.ptr();
for (int i = 0; i < fc; i++) {
if (groups_to_reimport.has(files[i]->import_group_file)) {
if (!group_files.has(files[i]->import_group_file)) {
group_files[files[i]->import_group_file] = Vector<String>();
}
group_files[files[i]->import_group_file].push_back(efd->get_file_path(i));
}
}
for (int i = 0; i < efd->get_subdir_count(); i++) {
_find_group_files(efd->get_subdir(i), group_files, groups_to_reimport);
}
}
void EditorFileSystem::reimport_files(const Vector<String> &p_files) {
{
// Ensure that ProjectSettings::IMPORTED_FILES_PATH exists.
DirAccess *da = DirAccess::open("res://");
if (da->change_dir(ProjectSettings::IMPORTED_FILES_PATH) != OK) {
Error err = da->make_dir_recursive(ProjectSettings::IMPORTED_FILES_PATH);
if (err || da->change_dir(ProjectSettings::IMPORTED_FILES_PATH) != OK) {
memdelete(da);
ERR_FAIL_MSG("Failed to create '" + ProjectSettings::IMPORTED_FILES_PATH + "' folder.");
}
}
memdelete(da);
}
importing = true;
EditorProgress pr("reimport", TTR("(Re)Importing Assets"), p_files.size());
Vector<ImportFile> files;
Set<String> groups_to_reimport;
for (int i = 0; i < p_files.size(); i++) {
String group_file = ResourceFormatImporter::get_singleton()->get_import_group_file(p_files[i]);
if (group_file_cache.has(p_files[i])) {
//maybe the file itself is a group!
groups_to_reimport.insert(p_files[i]);
//groups do not belong to grups
group_file = String();
} else if (group_file != String()) {
//it's a group file, add group to import and skip this file
groups_to_reimport.insert(group_file);
} else {
//it's a regular file
ImportFile ifile;
ifile.path = p_files[i];
ifile.order = ResourceFormatImporter::get_singleton()->get_import_order(p_files[i]);
files.push_back(ifile);
}
//group may have changed, so also update group reference
EditorFileSystemDirectory *fs = nullptr;
int cpos = -1;
if (_find_file(p_files[i], &fs, cpos)) {
fs->files.write[cpos]->import_group_file = group_file;
}
}
files.sort();
for (int i = 0; i < files.size(); i++) {
pr.step(files[i].path.get_file(), i);
_reimport_file(files[i].path);
}
//reimport groups
if (groups_to_reimport.size()) {
Map<String, Vector<String>> group_files;
_find_group_files(filesystem, group_files, groups_to_reimport);
for (Map<String, Vector<String>>::Element *E = group_files.front(); E; E = E->next()) {
Error err = _reimport_group(E->key(), E->get());
if (err == OK) {
_reimport_file(E->key());
}
}
}
_save_filesystem_cache();
importing = false;
if (!is_scanning()) {
emit_signal("filesystem_changed");
}
emit_signal("resources_reimported", p_files);
}
Error EditorFileSystem::_resource_import(const String &p_path) {
Vector<String> files;
files.push_back(p_path);
singleton->update_file(p_path);
singleton->reimport_files(files);
return OK;
}
bool EditorFileSystem::is_group_file(const String &p_path) const {
return group_file_cache.has(p_path);
}
void EditorFileSystem::_move_group_files(EditorFileSystemDirectory *efd, const String &p_group_file, const String &p_new_location) {
int fc = efd->files.size();
EditorFileSystemDirectory::FileInfo *const *files = efd->files.ptrw();
for (int i = 0; i < fc; i++) {
if (files[i]->import_group_file == p_group_file) {
files[i]->import_group_file = p_new_location;
Ref<ConfigFile> config;
config.instance();
String path = efd->get_file_path(i) + ".import";
Error err = config->load(path);
if (err != OK) {
continue;
}
if (config->has_section_key("remap", "group_file")) {
config->set_value("remap", "group_file", p_new_location);
}
List<String> sk;
config->get_section_keys("params", &sk);
for (List<String>::Element *E = sk.front(); E; E = E->next()) {
//not very clean, but should work
String param = E->get();
String value = config->get_value("params", param);
if (value == p_group_file) {
config->set_value("params", param, p_new_location);
}
}
config->save(path);
}
}
for (int i = 0; i < efd->get_subdir_count(); i++) {
_move_group_files(efd->get_subdir(i), p_group_file, p_new_location);
}
}
void EditorFileSystem::move_group_file(const String &p_path, const String &p_new_path) {
if (get_filesystem()) {
_move_group_files(get_filesystem(), p_path, p_new_path);
if (group_file_cache.has(p_path)) {
group_file_cache.erase(p_path);
group_file_cache.insert(p_new_path);
}
}
}
void EditorFileSystem::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_filesystem"), &EditorFileSystem::get_filesystem);
ClassDB::bind_method(D_METHOD("is_scanning"), &EditorFileSystem::is_scanning);
ClassDB::bind_method(D_METHOD("get_scanning_progress"), &EditorFileSystem::get_scanning_progress);
ClassDB::bind_method(D_METHOD("scan"), &EditorFileSystem::scan);
ClassDB::bind_method(D_METHOD("scan_sources"), &EditorFileSystem::scan_changes);
ClassDB::bind_method(D_METHOD("update_file", "path"), &EditorFileSystem::update_file);
ClassDB::bind_method(D_METHOD("get_filesystem_path", "path"), &EditorFileSystem::get_filesystem_path);
ClassDB::bind_method(D_METHOD("get_file_type", "path"), &EditorFileSystem::get_file_type);
ClassDB::bind_method(D_METHOD("update_script_classes"), &EditorFileSystem::update_script_classes);
ADD_SIGNAL(MethodInfo("filesystem_changed"));
ADD_SIGNAL(MethodInfo("sources_changed", PropertyInfo(Variant::BOOL, "exist")));
ADD_SIGNAL(MethodInfo("resources_reimported", PropertyInfo(Variant::PACKED_STRING_ARRAY, "resources")));
ADD_SIGNAL(MethodInfo("resources_reload", PropertyInfo(Variant::PACKED_STRING_ARRAY, "resources")));
}
void EditorFileSystem::_update_extensions() {
valid_extensions.clear();
import_extensions.clear();
List<String> extensionsl;
ResourceLoader::get_recognized_extensions_for_type("", &extensionsl);
for (List<String>::Element *E = extensionsl.front(); E; E = E->next()) {
valid_extensions.insert(E->get());
}
extensionsl.clear();
ResourceFormatImporter::get_singleton()->get_recognized_extensions(&extensionsl);
for (List<String>::Element *E = extensionsl.front(); E; E = E->next()) {
import_extensions.insert(E->get());
}
}
EditorFileSystem::EditorFileSystem() {
ResourceLoader::import = _resource_import;
reimport_on_missing_imported_files = GLOBAL_DEF("editor/reimport_missing_imported_files", true);
singleton = this;
filesystem = memnew(EditorFileSystemDirectory); //like, empty
filesystem->parent = nullptr;
thread = nullptr;
scanning = false;
importing = false;
use_threads = true;
thread_sources = nullptr;
new_filesystem = nullptr;
abort_scan = false;
scanning_changes = false;
scanning_changes_done = false;
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
if (da->change_dir(ProjectSettings::IMPORTED_FILES_PATH) != OK) {
da->make_dir(ProjectSettings::IMPORTED_FILES_PATH);
}
// This should probably also work on Unix and use the string it returns for FAT32 or exFAT
using_fat32_or_exfat = (da->get_filesystem_type() == "FAT32" || da->get_filesystem_type() == "exFAT");
memdelete(da);
scan_total = 0;
update_script_classes_queued = false;
first_scan = true;
scan_changes_pending = false;
revalidate_import_files = false;
}
EditorFileSystem::~EditorFileSystem() {
}
Fix file name comparison when new file is added to file system
/*************************************************************************/
/* editor_file_system.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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. */
/*************************************************************************/
#include "editor_file_system.h"
#include "core/config/project_settings.h"
#include "core/io/resource_importer.h"
#include "core/io/resource_loader.h"
#include "core/io/resource_saver.h"
#include "core/os/file_access.h"
#include "core/os/os.h"
#include "core/variant/variant_parser.h"
#include "editor_node.h"
#include "editor_resource_preview.h"
#include "editor_settings.h"
EditorFileSystem *EditorFileSystem::singleton = nullptr;
//the name is the version, to keep compatibility with different versions of Godot
#define CACHE_FILE_NAME "filesystem_cache6"
void EditorFileSystemDirectory::sort_files() {
files.sort_custom<FileInfoSort>();
}
int EditorFileSystemDirectory::find_file_index(const String &p_file) const {
for (int i = 0; i < files.size(); i++) {
if (files[i]->file == p_file) {
return i;
}
}
return -1;
}
int EditorFileSystemDirectory::find_dir_index(const String &p_dir) const {
for (int i = 0; i < subdirs.size(); i++) {
if (subdirs[i]->name == p_dir) {
return i;
}
}
return -1;
}
int EditorFileSystemDirectory::get_subdir_count() const {
return subdirs.size();
}
EditorFileSystemDirectory *EditorFileSystemDirectory::get_subdir(int p_idx) {
ERR_FAIL_INDEX_V(p_idx, subdirs.size(), nullptr);
return subdirs[p_idx];
}
int EditorFileSystemDirectory::get_file_count() const {
return files.size();
}
String EditorFileSystemDirectory::get_file(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, files.size(), "");
return files[p_idx]->file;
}
String EditorFileSystemDirectory::get_path() const {
String p;
const EditorFileSystemDirectory *d = this;
while (d->parent) {
p = d->name.plus_file(p);
d = d->parent;
}
return "res://" + p;
}
String EditorFileSystemDirectory::get_file_path(int p_idx) const {
String file = get_file(p_idx);
const EditorFileSystemDirectory *d = this;
while (d->parent) {
file = d->name.plus_file(file);
d = d->parent;
}
return "res://" + file;
}
Vector<String> EditorFileSystemDirectory::get_file_deps(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, files.size(), Vector<String>());
return files[p_idx]->deps;
}
bool EditorFileSystemDirectory::get_file_import_is_valid(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, files.size(), false);
return files[p_idx]->import_valid;
}
uint64_t EditorFileSystemDirectory::get_file_modified_time(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, files.size(), 0);
return files[p_idx]->modified_time;
}
String EditorFileSystemDirectory::get_file_script_class_name(int p_idx) const {
return files[p_idx]->script_class_name;
}
String EditorFileSystemDirectory::get_file_script_class_extends(int p_idx) const {
return files[p_idx]->script_class_extends;
}
String EditorFileSystemDirectory::get_file_script_class_icon_path(int p_idx) const {
return files[p_idx]->script_class_icon_path;
}
StringName EditorFileSystemDirectory::get_file_type(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, files.size(), "");
return files[p_idx]->type;
}
String EditorFileSystemDirectory::get_name() {
return name;
}
EditorFileSystemDirectory *EditorFileSystemDirectory::get_parent() {
return parent;
}
void EditorFileSystemDirectory::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_subdir_count"), &EditorFileSystemDirectory::get_subdir_count);
ClassDB::bind_method(D_METHOD("get_subdir", "idx"), &EditorFileSystemDirectory::get_subdir);
ClassDB::bind_method(D_METHOD("get_file_count"), &EditorFileSystemDirectory::get_file_count);
ClassDB::bind_method(D_METHOD("get_file", "idx"), &EditorFileSystemDirectory::get_file);
ClassDB::bind_method(D_METHOD("get_file_path", "idx"), &EditorFileSystemDirectory::get_file_path);
ClassDB::bind_method(D_METHOD("get_file_type", "idx"), &EditorFileSystemDirectory::get_file_type);
ClassDB::bind_method(D_METHOD("get_file_script_class_name", "idx"), &EditorFileSystemDirectory::get_file_script_class_name);
ClassDB::bind_method(D_METHOD("get_file_script_class_extends", "idx"), &EditorFileSystemDirectory::get_file_script_class_extends);
ClassDB::bind_method(D_METHOD("get_file_import_is_valid", "idx"), &EditorFileSystemDirectory::get_file_import_is_valid);
ClassDB::bind_method(D_METHOD("get_name"), &EditorFileSystemDirectory::get_name);
ClassDB::bind_method(D_METHOD("get_path"), &EditorFileSystemDirectory::get_path);
ClassDB::bind_method(D_METHOD("get_parent"), &EditorFileSystemDirectory::get_parent);
ClassDB::bind_method(D_METHOD("find_file_index", "name"), &EditorFileSystemDirectory::find_file_index);
ClassDB::bind_method(D_METHOD("find_dir_index", "name"), &EditorFileSystemDirectory::find_dir_index);
}
EditorFileSystemDirectory::EditorFileSystemDirectory() {
modified_time = 0;
parent = nullptr;
verified = false;
}
EditorFileSystemDirectory::~EditorFileSystemDirectory() {
for (int i = 0; i < files.size(); i++) {
memdelete(files[i]);
}
for (int i = 0; i < subdirs.size(); i++) {
memdelete(subdirs[i]);
}
}
void EditorFileSystem::_scan_filesystem() {
ERR_FAIL_COND(!scanning || new_filesystem);
//read .fscache
String cpath;
sources_changed.clear();
file_cache.clear();
String project = ProjectSettings::get_singleton()->get_resource_path();
String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(CACHE_FILE_NAME);
FileAccess *f = FileAccess::open(fscache, FileAccess::READ);
bool first = true;
if (f) {
//read the disk cache
while (!f->eof_reached()) {
String l = f->get_line().strip_edges();
if (first) {
if (first_scan) {
// only use this on first scan, afterwards it gets ignored
// this is so on first reimport we synchronize versions, then
// we don't care until editor restart. This is for usability mainly so
// your workflow is not killed after changing a setting by forceful reimporting
// everything there is.
filesystem_settings_version_for_import = l.strip_edges();
if (filesystem_settings_version_for_import != ResourceFormatImporter::get_singleton()->get_import_settings_hash()) {
revalidate_import_files = true;
}
}
first = false;
continue;
}
if (l == String()) {
continue;
}
if (l.begins_with("::")) {
Vector<String> split = l.split("::");
ERR_CONTINUE(split.size() != 3);
String name = split[1];
cpath = name;
} else {
Vector<String> split = l.split("::");
ERR_CONTINUE(split.size() != 8);
String name = split[0];
String file;
file = name;
name = cpath.plus_file(name);
FileCache fc;
fc.type = split[1];
fc.modification_time = split[2].to_int();
fc.import_modification_time = split[3].to_int();
fc.import_valid = split[4].to_int() != 0;
fc.import_group_file = split[5].strip_edges();
fc.script_class_name = split[6].get_slice("<>", 0);
fc.script_class_extends = split[6].get_slice("<>", 1);
fc.script_class_icon_path = split[6].get_slice("<>", 2);
String deps = split[7].strip_edges();
if (deps.length()) {
Vector<String> dp = deps.split("<>");
for (int i = 0; i < dp.size(); i++) {
String path = dp[i];
fc.deps.push_back(path);
}
}
file_cache[name] = fc;
}
}
f->close();
memdelete(f);
}
String update_cache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file("filesystem_update4");
if (FileAccess::exists(update_cache)) {
{
FileAccessRef f2 = FileAccess::open(update_cache, FileAccess::READ);
String l = f2->get_line().strip_edges();
while (l != String()) {
file_cache.erase(l); //erase cache for this, so it gets updated
l = f2->get_line().strip_edges();
}
}
DirAccessRef d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
d->remove(update_cache); //bye bye update cache
}
EditorProgressBG scan_progress("efs", "ScanFS", 1000);
ScanProgress sp;
sp.low = 0;
sp.hi = 1;
sp.progress = &scan_progress;
new_filesystem = memnew(EditorFileSystemDirectory);
new_filesystem->parent = nullptr;
DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
d->change_dir("res://");
_scan_new_dir(new_filesystem, d, sp);
file_cache.clear(); //clear caches, no longer needed
memdelete(d);
if (!first_scan) {
//on the first scan this is done from the main thread after re-importing
_save_filesystem_cache();
}
scanning = false;
}
void EditorFileSystem::_save_filesystem_cache() {
group_file_cache.clear();
String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(CACHE_FILE_NAME);
FileAccess *f = FileAccess::open(fscache, FileAccess::WRITE);
ERR_FAIL_COND_MSG(!f, "Cannot create file '" + fscache + "'. Check user write permissions.");
f->store_line(filesystem_settings_version_for_import);
_save_filesystem_cache(filesystem, f);
f->close();
memdelete(f);
}
void EditorFileSystem::_thread_func(void *_userdata) {
EditorFileSystem *sd = (EditorFileSystem *)_userdata;
sd->_scan_filesystem();
}
bool EditorFileSystem::_test_for_reimport(const String &p_path, bool p_only_imported_files) {
if (!reimport_on_missing_imported_files && p_only_imported_files) {
return false;
}
if (!FileAccess::exists(p_path + ".import")) {
return true;
}
if (!ResourceFormatImporter::get_singleton()->are_import_settings_valid(p_path)) {
//reimport settings are not valid, reimport
return true;
}
Error err;
FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err);
if (!f) { //no import file, do reimport
return true;
}
VariantParser::StreamFile stream;
stream.f = f;
String assign;
Variant value;
VariantParser::Tag next_tag;
int lines = 0;
String error_text;
List<String> to_check;
String importer_name;
String source_file = "";
String source_md5 = "";
Vector<String> dest_files;
String dest_md5 = "";
int version = 0;
while (true) {
assign = Variant();
next_tag.fields.clear();
next_tag.name = String();
err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
if (err == ERR_FILE_EOF) {
break;
} else if (err != OK) {
ERR_PRINT("ResourceFormatImporter::load - '" + p_path + ".import:" + itos(lines) + "' error '" + error_text + "'.");
memdelete(f);
return false; //parse error, try reimport manually (Avoid reimport loop on broken file)
}
if (assign != String()) {
if (assign.begins_with("path")) {
to_check.push_back(value);
} else if (assign == "files") {
Array fa = value;
for (int i = 0; i < fa.size(); i++) {
to_check.push_back(fa[i]);
}
} else if (assign == "importer_version") {
version = value;
} else if (assign == "importer") {
importer_name = value;
} else if (!p_only_imported_files) {
if (assign == "source_file") {
source_file = value;
} else if (assign == "dest_files") {
dest_files = value;
}
}
} else if (next_tag.name != "remap" && next_tag.name != "deps") {
break;
}
}
memdelete(f);
Ref<ResourceImporter> importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name);
if (importer->get_format_version() > version) {
return true; // version changed, reimport
}
// Read the md5's from a separate file (so the import parameters aren't dependent on the file version
String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(p_path);
FileAccess *md5s = FileAccess::open(base_path + ".md5", FileAccess::READ, &err);
if (!md5s) { // No md5's stored for this resource
return true;
}
VariantParser::StreamFile md5_stream;
md5_stream.f = md5s;
while (true) {
assign = Variant();
next_tag.fields.clear();
next_tag.name = String();
err = VariantParser::parse_tag_assign_eof(&md5_stream, lines, error_text, next_tag, assign, value, nullptr, true);
if (err == ERR_FILE_EOF) {
break;
} else if (err != OK) {
ERR_PRINT("ResourceFormatImporter::load - '" + p_path + ".import.md5:" + itos(lines) + "' error '" + error_text + "'.");
memdelete(md5s);
return false; // parse error
}
if (assign != String()) {
if (!p_only_imported_files) {
if (assign == "source_md5") {
source_md5 = value;
} else if (assign == "dest_md5") {
dest_md5 = value;
}
}
}
}
memdelete(md5s);
//imported files are gone, reimport
for (List<String>::Element *E = to_check.front(); E; E = E->next()) {
if (!FileAccess::exists(E->get())) {
return true;
}
}
//check source md5 matching
if (!p_only_imported_files) {
if (source_file != String() && source_file != p_path) {
return true; //file was moved, reimport
}
if (source_md5 == String()) {
return true; //lacks md5, so just reimport
}
String md5 = FileAccess::get_md5(p_path);
if (md5 != source_md5) {
return true;
}
if (dest_files.size() && dest_md5 != String()) {
md5 = FileAccess::get_multiple_md5(dest_files);
if (md5 != dest_md5) {
return true;
}
}
}
return false; //nothing changed
}
bool EditorFileSystem::_update_scan_actions() {
sources_changed.clear();
bool fs_changed = false;
Vector<String> reimports;
Vector<String> reloads;
for (List<ItemAction>::Element *E = scan_actions.front(); E; E = E->next()) {
ItemAction &ia = E->get();
switch (ia.action) {
case ItemAction::ACTION_NONE: {
} break;
case ItemAction::ACTION_DIR_ADD: {
int idx = 0;
for (int i = 0; i < ia.dir->subdirs.size(); i++) {
if (ia.new_dir->name < ia.dir->subdirs[i]->name) {
break;
}
idx++;
}
if (idx == ia.dir->subdirs.size()) {
ia.dir->subdirs.push_back(ia.new_dir);
} else {
ia.dir->subdirs.insert(idx, ia.new_dir);
}
fs_changed = true;
} break;
case ItemAction::ACTION_DIR_REMOVE: {
ERR_CONTINUE(!ia.dir->parent);
ia.dir->parent->subdirs.erase(ia.dir);
memdelete(ia.dir);
fs_changed = true;
} break;
case ItemAction::ACTION_FILE_ADD: {
int idx = 0;
for (int i = 0; i < ia.dir->files.size(); i++) {
if (ia.new_file->file < ia.dir->files[i]->file) {
break;
}
idx++;
}
if (idx == ia.dir->files.size()) {
ia.dir->files.push_back(ia.new_file);
} else {
ia.dir->files.insert(idx, ia.new_file);
}
fs_changed = true;
} break;
case ItemAction::ACTION_FILE_REMOVE: {
int idx = ia.dir->find_file_index(ia.file);
ERR_CONTINUE(idx == -1);
_delete_internal_files(ia.dir->files[idx]->file);
memdelete(ia.dir->files[idx]);
ia.dir->files.remove(idx);
fs_changed = true;
} break;
case ItemAction::ACTION_FILE_TEST_REIMPORT: {
int idx = ia.dir->find_file_index(ia.file);
ERR_CONTINUE(idx == -1);
String full_path = ia.dir->get_file_path(idx);
if (_test_for_reimport(full_path, false)) {
//must reimport
reimports.push_back(full_path);
reimports.append_array(_get_dependencies(full_path));
} else {
//must not reimport, all was good
//update modified times, to avoid reimport
ia.dir->files[idx]->modified_time = FileAccess::get_modified_time(full_path);
ia.dir->files[idx]->import_modified_time = FileAccess::get_modified_time(full_path + ".import");
}
fs_changed = true;
} break;
case ItemAction::ACTION_FILE_RELOAD: {
int idx = ia.dir->find_file_index(ia.file);
ERR_CONTINUE(idx == -1);
String full_path = ia.dir->get_file_path(idx);
reloads.push_back(full_path);
} break;
}
}
if (reimports.size()) {
reimport_files(reimports);
}
if (first_scan) {
//only on first scan this is valid and updated, then settings changed.
revalidate_import_files = false;
filesystem_settings_version_for_import = ResourceFormatImporter::get_singleton()->get_import_settings_hash();
_save_filesystem_cache();
}
if (reloads.size()) {
emit_signal("resources_reload", reloads);
}
scan_actions.clear();
return fs_changed;
}
void EditorFileSystem::scan() {
if (false /*&& bool(Globals::get_singleton()->get("debug/disable_scan"))*/) {
return;
}
if (scanning || scanning_changes || thread) {
return;
}
_update_extensions();
abort_scan = false;
if (!use_threads) {
scanning = true;
scan_total = 0;
_scan_filesystem();
if (filesystem) {
memdelete(filesystem);
}
//file_type_cache.clear();
filesystem = new_filesystem;
new_filesystem = nullptr;
_update_scan_actions();
scanning = false;
emit_signal("filesystem_changed");
emit_signal("sources_changed", sources_changed.size() > 0);
_queue_update_script_classes();
first_scan = false;
} else {
ERR_FAIL_COND(thread);
set_process(true);
Thread::Settings s;
scanning = true;
scan_total = 0;
s.priority = Thread::PRIORITY_LOW;
thread = Thread::create(_thread_func, this, s);
//tree->hide();
//progress->show();
}
}
void EditorFileSystem::ScanProgress::update(int p_current, int p_total) const {
float ratio = low + ((hi - low) / p_total) * p_current;
progress->step(ratio * 1000);
EditorFileSystem::singleton->scan_total = ratio;
}
EditorFileSystem::ScanProgress EditorFileSystem::ScanProgress::get_sub(int p_current, int p_total) const {
ScanProgress sp = *this;
float slice = (sp.hi - sp.low) / p_total;
sp.low += slice * p_current;
sp.hi = slice;
return sp;
}
void EditorFileSystem::_scan_new_dir(EditorFileSystemDirectory *p_dir, DirAccess *da, const ScanProgress &p_progress) {
List<String> dirs;
List<String> files;
String cd = da->get_current_dir();
p_dir->modified_time = FileAccess::get_modified_time(cd);
da->list_dir_begin();
while (true) {
String f = da->get_next();
if (f == "") {
break;
}
if (da->current_is_hidden()) {
continue;
}
if (da->current_is_dir()) {
if (f.begins_with(".")) { // Ignore special and . / ..
continue;
}
if (FileAccess::exists(cd.plus_file(f).plus_file("project.godot"))) { // skip if another project inside this
continue;
}
if (FileAccess::exists(cd.plus_file(f).plus_file(".gdignore"))) { // skip if another project inside this
continue;
}
dirs.push_back(f);
} else {
files.push_back(f);
}
}
da->list_dir_end();
dirs.sort_custom<NaturalNoCaseComparator>();
files.sort_custom<NaturalNoCaseComparator>();
int total = dirs.size() + files.size();
int idx = 0;
for (List<String>::Element *E = dirs.front(); E; E = E->next(), idx++) {
if (da->change_dir(E->get()) == OK) {
String d = da->get_current_dir();
if (d == cd || !d.begins_with(cd)) {
da->change_dir(cd); //avoid recursion
} else {
EditorFileSystemDirectory *efd = memnew(EditorFileSystemDirectory);
efd->parent = p_dir;
efd->name = E->get();
_scan_new_dir(efd, da, p_progress.get_sub(idx, total));
int idx2 = 0;
for (int i = 0; i < p_dir->subdirs.size(); i++) {
if (efd->name < p_dir->subdirs[i]->name) {
break;
}
idx2++;
}
if (idx2 == p_dir->subdirs.size()) {
p_dir->subdirs.push_back(efd);
} else {
p_dir->subdirs.insert(idx2, efd);
}
da->change_dir("..");
}
} else {
ERR_PRINT("Cannot go into subdir '" + E->get() + "'.");
}
p_progress.update(idx, total);
}
for (List<String>::Element *E = files.front(); E; E = E->next(), idx++) {
String ext = E->get().get_extension().to_lower();
if (!valid_extensions.has(ext)) {
continue; //invalid
}
EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo);
fi->file = E->get();
String path = cd.plus_file(fi->file);
FileCache *fc = file_cache.getptr(path);
uint64_t mt = FileAccess::get_modified_time(path);
if (import_extensions.has(ext)) {
//is imported
uint64_t import_mt = 0;
if (FileAccess::exists(path + ".import")) {
import_mt = FileAccess::get_modified_time(path + ".import");
}
if (fc && fc->modification_time == mt && fc->import_modification_time == import_mt && !_test_for_reimport(path, true)) {
fi->type = fc->type;
fi->deps = fc->deps;
fi->modified_time = fc->modification_time;
fi->import_modified_time = fc->import_modification_time;
fi->import_valid = fc->import_valid;
fi->script_class_name = fc->script_class_name;
fi->import_group_file = fc->import_group_file;
fi->script_class_extends = fc->script_class_extends;
fi->script_class_icon_path = fc->script_class_icon_path;
if (revalidate_import_files && !ResourceFormatImporter::get_singleton()->are_import_settings_valid(path)) {
ItemAction ia;
ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT;
ia.dir = p_dir;
ia.file = E->get();
scan_actions.push_back(ia);
}
if (fc->type == String()) {
fi->type = ResourceLoader::get_resource_type(path);
fi->import_group_file = ResourceLoader::get_import_group_file(path);
//there is also the chance that file type changed due to reimport, must probably check this somehow here (or kind of note it for next time in another file?)
//note: I think this should not happen any longer..
}
} else {
fi->type = ResourceFormatImporter::get_singleton()->get_resource_type(path);
fi->import_group_file = ResourceFormatImporter::get_singleton()->get_import_group_file(path);
fi->script_class_name = _get_global_script_class(fi->type, path, &fi->script_class_extends, &fi->script_class_icon_path);
fi->modified_time = 0;
fi->import_modified_time = 0;
fi->import_valid = ResourceLoader::is_import_valid(path);
ItemAction ia;
ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT;
ia.dir = p_dir;
ia.file = E->get();
scan_actions.push_back(ia);
}
} else {
if (fc && fc->modification_time == mt) {
//not imported, so just update type if changed
fi->type = fc->type;
fi->modified_time = fc->modification_time;
fi->deps = fc->deps;
fi->import_modified_time = 0;
fi->import_valid = true;
fi->script_class_name = fc->script_class_name;
fi->script_class_extends = fc->script_class_extends;
fi->script_class_icon_path = fc->script_class_icon_path;
} else {
//new or modified time
fi->type = ResourceLoader::get_resource_type(path);
fi->script_class_name = _get_global_script_class(fi->type, path, &fi->script_class_extends, &fi->script_class_icon_path);
fi->deps = _get_dependencies(path);
fi->modified_time = mt;
fi->import_modified_time = 0;
fi->import_valid = true;
}
}
for (int i = 0; i < ScriptServer::get_language_count(); i++) {
ScriptLanguage *lang = ScriptServer::get_language(i);
if (lang->supports_documentation() && fi->type == lang->get_type()) {
Ref<Script> script = ResourceLoader::load(path);
if (script == nullptr) {
continue;
}
const Vector<DocData::ClassDoc> &docs = script->get_documentation();
for (int j = 0; j < docs.size(); j++) {
EditorHelp::get_doc_data()->add_doc(docs[j]);
}
}
}
p_dir->files.push_back(fi);
p_progress.update(idx, total);
}
}
void EditorFileSystem::_scan_fs_changes(EditorFileSystemDirectory *p_dir, const ScanProgress &p_progress) {
uint64_t current_mtime = FileAccess::get_modified_time(p_dir->get_path());
bool updated_dir = false;
String cd = p_dir->get_path();
if (current_mtime != p_dir->modified_time || using_fat32_or_exfat) {
updated_dir = true;
p_dir->modified_time = current_mtime;
//ooooops, dir changed, see what's going on
//first mark everything as veryfied
for (int i = 0; i < p_dir->files.size(); i++) {
p_dir->files[i]->verified = false;
}
for (int i = 0; i < p_dir->subdirs.size(); i++) {
p_dir->get_subdir(i)->verified = false;
}
//then scan files and directories and check what's different
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
da->change_dir(cd);
da->list_dir_begin();
while (true) {
String f = da->get_next();
if (f == "") {
break;
}
if (da->current_is_hidden()) {
continue;
}
if (da->current_is_dir()) {
if (f.begins_with(".")) { // Ignore special and . / ..
continue;
}
int idx = p_dir->find_dir_index(f);
if (idx == -1) {
if (FileAccess::exists(cd.plus_file(f).plus_file("project.godot"))) { // skip if another project inside this
continue;
}
if (FileAccess::exists(cd.plus_file(f).plus_file(".gdignore"))) { // skip if another project inside this
continue;
}
EditorFileSystemDirectory *efd = memnew(EditorFileSystemDirectory);
efd->parent = p_dir;
efd->name = f;
DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
d->change_dir(cd.plus_file(f));
_scan_new_dir(efd, d, p_progress.get_sub(1, 1));
memdelete(d);
ItemAction ia;
ia.action = ItemAction::ACTION_DIR_ADD;
ia.dir = p_dir;
ia.file = f;
ia.new_dir = efd;
scan_actions.push_back(ia);
} else {
p_dir->subdirs[idx]->verified = true;
}
} else {
String ext = f.get_extension().to_lower();
if (!valid_extensions.has(ext)) {
continue; //invalid
}
int idx = p_dir->find_file_index(f);
if (idx == -1) {
//never seen this file, add actition to add it
EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo);
fi->file = f;
String path = cd.plus_file(fi->file);
fi->modified_time = FileAccess::get_modified_time(path);
fi->import_modified_time = 0;
fi->type = ResourceLoader::get_resource_type(path);
fi->script_class_name = _get_global_script_class(fi->type, path, &fi->script_class_extends, &fi->script_class_icon_path);
fi->import_valid = ResourceLoader::is_import_valid(path);
fi->import_group_file = ResourceLoader::get_import_group_file(path);
{
ItemAction ia;
ia.action = ItemAction::ACTION_FILE_ADD;
ia.dir = p_dir;
ia.file = f;
ia.new_file = fi;
scan_actions.push_back(ia);
}
if (import_extensions.has(ext)) {
//if it can be imported, and it was added, it needs to be reimported
ItemAction ia;
ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT;
ia.dir = p_dir;
ia.file = f;
scan_actions.push_back(ia);
}
} else {
p_dir->files[idx]->verified = true;
}
}
}
da->list_dir_end();
memdelete(da);
}
for (int i = 0; i < p_dir->files.size(); i++) {
if (updated_dir && !p_dir->files[i]->verified) {
//this file was removed, add action to remove it
ItemAction ia;
ia.action = ItemAction::ACTION_FILE_REMOVE;
ia.dir = p_dir;
ia.file = p_dir->files[i]->file;
scan_actions.push_back(ia);
continue;
}
String path = cd.plus_file(p_dir->files[i]->file);
if (import_extensions.has(p_dir->files[i]->file.get_extension().to_lower())) {
//check here if file must be imported or not
uint64_t mt = FileAccess::get_modified_time(path);
bool reimport = false;
if (mt != p_dir->files[i]->modified_time) {
reimport = true; //it was modified, must be reimported.
} else if (!FileAccess::exists(path + ".import")) {
reimport = true; //no .import file, obviously reimport
} else {
uint64_t import_mt = FileAccess::get_modified_time(path + ".import");
if (import_mt != p_dir->files[i]->import_modified_time) {
reimport = true;
} else if (_test_for_reimport(path, true)) {
reimport = true;
}
}
if (reimport) {
ItemAction ia;
ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT;
ia.dir = p_dir;
ia.file = p_dir->files[i]->file;
scan_actions.push_back(ia);
}
} else if (ResourceCache::has(path)) { //test for potential reload
uint64_t mt = FileAccess::get_modified_time(path);
if (mt != p_dir->files[i]->modified_time) {
p_dir->files[i]->modified_time = mt; //save new time, but test for reload
ItemAction ia;
ia.action = ItemAction::ACTION_FILE_RELOAD;
ia.dir = p_dir;
ia.file = p_dir->files[i]->file;
scan_actions.push_back(ia);
}
}
}
for (int i = 0; i < p_dir->subdirs.size(); i++) {
if (updated_dir && !p_dir->subdirs[i]->verified) {
//this directory was removed, add action to remove it
ItemAction ia;
ia.action = ItemAction::ACTION_DIR_REMOVE;
ia.dir = p_dir->subdirs[i];
scan_actions.push_back(ia);
continue;
}
_scan_fs_changes(p_dir->get_subdir(i), p_progress);
}
}
void EditorFileSystem::_delete_internal_files(String p_file) {
if (FileAccess::exists(p_file + ".import")) {
List<String> paths;
ResourceFormatImporter::get_singleton()->get_internal_resource_path_list(p_file, &paths);
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
for (List<String>::Element *E = paths.front(); E; E = E->next()) {
da->remove(E->get());
}
da->remove(p_file + ".import");
memdelete(da);
}
}
void EditorFileSystem::_thread_func_sources(void *_userdata) {
EditorFileSystem *efs = (EditorFileSystem *)_userdata;
if (efs->filesystem) {
EditorProgressBG pr("sources", TTR("ScanSources"), 1000);
ScanProgress sp;
sp.progress = ≺
sp.hi = 1;
sp.low = 0;
efs->_scan_fs_changes(efs->filesystem, sp);
}
efs->scanning_changes_done = true;
}
void EditorFileSystem::scan_changes() {
if (first_scan || // Prevent a premature changes scan from inhibiting the first full scan
scanning || scanning_changes || thread) {
scan_changes_pending = true;
set_process(true);
return;
}
_update_extensions();
sources_changed.clear();
scanning_changes = true;
scanning_changes_done = false;
abort_scan = false;
if (!use_threads) {
if (filesystem) {
EditorProgressBG pr("sources", TTR("ScanSources"), 1000);
ScanProgress sp;
sp.progress = ≺
sp.hi = 1;
sp.low = 0;
scan_total = 0;
_scan_fs_changes(filesystem, sp);
if (_update_scan_actions()) {
emit_signal("filesystem_changed");
}
}
scanning_changes = false;
scanning_changes_done = true;
emit_signal("sources_changed", sources_changed.size() > 0);
} else {
ERR_FAIL_COND(thread_sources);
set_process(true);
scan_total = 0;
Thread::Settings s;
s.priority = Thread::PRIORITY_LOW;
thread_sources = Thread::create(_thread_func_sources, this, s);
}
}
void EditorFileSystem::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
call_deferred("scan"); //this should happen after every editor node entered the tree
} break;
case NOTIFICATION_EXIT_TREE: {
Thread *active_thread = thread ? thread : thread_sources;
if (use_threads && active_thread) {
//abort thread if in progress
abort_scan = true;
while (scanning) {
OS::get_singleton()->delay_usec(1000);
}
Thread::wait_to_finish(active_thread);
memdelete(active_thread);
thread = nullptr;
thread_sources = nullptr;
WARN_PRINT("Scan thread aborted...");
set_process(false);
}
if (filesystem) {
memdelete(filesystem);
}
if (new_filesystem) {
memdelete(new_filesystem);
}
filesystem = nullptr;
new_filesystem = nullptr;
} break;
case NOTIFICATION_PROCESS: {
if (use_threads) {
if (scanning_changes) {
if (scanning_changes_done) {
scanning_changes = false;
set_process(false);
Thread::wait_to_finish(thread_sources);
memdelete(thread_sources);
thread_sources = nullptr;
if (_update_scan_actions()) {
emit_signal("filesystem_changed");
}
emit_signal("sources_changed", sources_changed.size() > 0);
_queue_update_script_classes();
first_scan = false;
}
} else if (!scanning && thread) {
set_process(false);
if (filesystem) {
memdelete(filesystem);
}
filesystem = new_filesystem;
new_filesystem = nullptr;
Thread::wait_to_finish(thread);
memdelete(thread);
thread = nullptr;
_update_scan_actions();
emit_signal("filesystem_changed");
emit_signal("sources_changed", sources_changed.size() > 0);
_queue_update_script_classes();
first_scan = false;
}
if (!is_processing() && scan_changes_pending) {
scan_changes_pending = false;
scan_changes();
}
}
} break;
}
}
bool EditorFileSystem::is_scanning() const {
return scanning || scanning_changes;
}
float EditorFileSystem::get_scanning_progress() const {
return scan_total;
}
EditorFileSystemDirectory *EditorFileSystem::get_filesystem() {
return filesystem;
}
void EditorFileSystem::_save_filesystem_cache(EditorFileSystemDirectory *p_dir, FileAccess *p_file) {
if (!p_dir) {
return; //none
}
p_file->store_line("::" + p_dir->get_path() + "::" + String::num(p_dir->modified_time));
for (int i = 0; i < p_dir->files.size(); i++) {
if (p_dir->files[i]->import_group_file != String()) {
group_file_cache.insert(p_dir->files[i]->import_group_file);
}
String s = p_dir->files[i]->file + "::" + p_dir->files[i]->type + "::" + itos(p_dir->files[i]->modified_time) + "::" + itos(p_dir->files[i]->import_modified_time) + "::" + itos(p_dir->files[i]->import_valid) + "::" + p_dir->files[i]->import_group_file + "::" + p_dir->files[i]->script_class_name + "<>" + p_dir->files[i]->script_class_extends + "<>" + p_dir->files[i]->script_class_icon_path;
s += "::";
for (int j = 0; j < p_dir->files[i]->deps.size(); j++) {
if (j > 0) {
s += "<>";
}
s += p_dir->files[i]->deps[j];
}
p_file->store_line(s);
}
for (int i = 0; i < p_dir->subdirs.size(); i++) {
_save_filesystem_cache(p_dir->subdirs[i], p_file);
}
}
bool EditorFileSystem::_find_file(const String &p_file, EditorFileSystemDirectory **r_d, int &r_file_pos) const {
//todo make faster
if (!filesystem || scanning) {
return false;
}
String f = ProjectSettings::get_singleton()->localize_path(p_file);
if (!f.begins_with("res://")) {
return false;
}
f = f.substr(6, f.length());
f = f.replace("\\", "/");
Vector<String> path = f.split("/");
if (path.size() == 0) {
return false;
}
String file = path[path.size() - 1];
path.resize(path.size() - 1);
EditorFileSystemDirectory *fs = filesystem;
for (int i = 0; i < path.size(); i++) {
if (path[i].begins_with(".")) {
return false;
}
int idx = -1;
for (int j = 0; j < fs->get_subdir_count(); j++) {
if (fs->get_subdir(j)->get_name() == path[i]) {
idx = j;
break;
}
}
if (idx == -1) {
//does not exist, create i guess?
EditorFileSystemDirectory *efsd = memnew(EditorFileSystemDirectory);
efsd->name = path[i];
efsd->parent = fs;
int idx2 = 0;
for (int j = 0; j < fs->get_subdir_count(); j++) {
if (efsd->name < fs->get_subdir(j)->get_name()) {
break;
}
idx2++;
}
if (idx2 == fs->get_subdir_count()) {
fs->subdirs.push_back(efsd);
} else {
fs->subdirs.insert(idx2, efsd);
}
fs = efsd;
} else {
fs = fs->get_subdir(idx);
}
}
int cpos = -1;
for (int i = 0; i < fs->files.size(); i++) {
if (fs->files[i]->file == file) {
cpos = i;
break;
}
}
r_file_pos = cpos;
*r_d = fs;
return cpos != -1;
}
String EditorFileSystem::get_file_type(const String &p_file) const {
EditorFileSystemDirectory *fs = nullptr;
int cpos = -1;
if (!_find_file(p_file, &fs, cpos)) {
return "";
}
return fs->files[cpos]->type;
}
EditorFileSystemDirectory *EditorFileSystem::find_file(const String &p_file, int *r_index) const {
if (!filesystem || scanning) {
return nullptr;
}
EditorFileSystemDirectory *fs = nullptr;
int cpos = -1;
if (!_find_file(p_file, &fs, cpos)) {
return nullptr;
}
if (r_index) {
*r_index = cpos;
}
return fs;
}
EditorFileSystemDirectory *EditorFileSystem::get_filesystem_path(const String &p_path) {
if (!filesystem || scanning) {
return nullptr;
}
String f = ProjectSettings::get_singleton()->localize_path(p_path);
if (!f.begins_with("res://")) {
return nullptr;
}
f = f.substr(6, f.length());
f = f.replace("\\", "/");
if (f == String()) {
return filesystem;
}
if (f.ends_with("/")) {
f = f.substr(0, f.length() - 1);
}
Vector<String> path = f.split("/");
if (path.size() == 0) {
return nullptr;
}
EditorFileSystemDirectory *fs = filesystem;
for (int i = 0; i < path.size(); i++) {
int idx = -1;
for (int j = 0; j < fs->get_subdir_count(); j++) {
if (fs->get_subdir(j)->get_name() == path[i]) {
idx = j;
break;
}
}
if (idx == -1) {
return nullptr;
} else {
fs = fs->get_subdir(idx);
}
}
return fs;
}
void EditorFileSystem::_save_late_updated_files() {
//files that already existed, and were modified, need re-scanning for dependencies upon project restart. This is done via saving this special file
String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file("filesystem_update4");
FileAccessRef f = FileAccess::open(fscache, FileAccess::WRITE);
ERR_FAIL_COND_MSG(!f, "Cannot create file '" + fscache + "'. Check user write permissions.");
for (Set<String>::Element *E = late_update_files.front(); E; E = E->next()) {
f->store_line(E->get());
}
}
Vector<String> EditorFileSystem::_get_dependencies(const String &p_path) {
List<String> deps;
ResourceLoader::get_dependencies(p_path, &deps);
Vector<String> ret;
for (List<String>::Element *E = deps.front(); E; E = E->next()) {
ret.push_back(E->get());
}
return ret;
}
String EditorFileSystem::_get_global_script_class(const String &p_type, const String &p_path, String *r_extends, String *r_icon_path) const {
for (int i = 0; i < ScriptServer::get_language_count(); i++) {
if (ScriptServer::get_language(i)->handles_global_class_type(p_type)) {
String global_name;
String extends;
String icon_path;
global_name = ScriptServer::get_language(i)->get_global_class_name(p_path, &extends, &icon_path);
*r_extends = extends;
*r_icon_path = icon_path;
return global_name;
}
}
*r_extends = String();
*r_icon_path = String();
return String();
}
void EditorFileSystem::_scan_script_classes(EditorFileSystemDirectory *p_dir) {
int filecount = p_dir->files.size();
const EditorFileSystemDirectory::FileInfo *const *files = p_dir->files.ptr();
for (int i = 0; i < filecount; i++) {
if (files[i]->script_class_name == String()) {
continue;
}
String lang;
for (int j = 0; j < ScriptServer::get_language_count(); j++) {
if (ScriptServer::get_language(j)->handles_global_class_type(files[i]->type)) {
lang = ScriptServer::get_language(j)->get_name();
}
}
ScriptServer::add_global_class(files[i]->script_class_name, files[i]->script_class_extends, lang, p_dir->get_file_path(i));
EditorNode::get_editor_data().script_class_set_icon_path(files[i]->script_class_name, files[i]->script_class_icon_path);
EditorNode::get_editor_data().script_class_set_name(files[i]->file, files[i]->script_class_name);
}
for (int i = 0; i < p_dir->get_subdir_count(); i++) {
_scan_script_classes(p_dir->get_subdir(i));
}
}
void EditorFileSystem::update_script_classes() {
if (!update_script_classes_queued) {
return;
}
update_script_classes_queued = false;
ScriptServer::global_classes_clear();
if (get_filesystem()) {
_scan_script_classes(get_filesystem());
}
ScriptServer::save_global_classes();
EditorNode::get_editor_data().script_class_save_icon_paths();
// Rescan custom loaders and savers.
// Doing the following here because the `filesystem_changed` signal fires multiple times and isn't always followed by script classes update.
// So I thought it's better to do this when script classes really get updated
ResourceLoader::remove_custom_loaders();
ResourceLoader::add_custom_loaders();
ResourceSaver::remove_custom_savers();
ResourceSaver::add_custom_savers();
}
void EditorFileSystem::_queue_update_script_classes() {
if (update_script_classes_queued) {
return;
}
update_script_classes_queued = true;
call_deferred("update_script_classes");
}
void EditorFileSystem::update_file(const String &p_file) {
EditorFileSystemDirectory *fs = nullptr;
int cpos = -1;
if (!_find_file(p_file, &fs, cpos)) {
if (!fs) {
return;
}
}
if (!FileAccess::exists(p_file)) {
//was removed
_delete_internal_files(p_file);
if (cpos != -1) { // Might've never been part of the editor file system (*.* files deleted in Open dialog).
memdelete(fs->files[cpos]);
fs->files.remove(cpos);
}
call_deferred("emit_signal", "filesystem_changed"); //update later
_queue_update_script_classes();
return;
}
String type = ResourceLoader::get_resource_type(p_file);
if (cpos == -1) {
// The file did not exist, it was added.
late_added_files.insert(p_file); // Remember that it was added. This mean it will be scanned and imported on editor restart.
int idx = 0;
String file_name = p_file.get_file();
for (int i = 0; i < fs->files.size(); i++) {
if (file_name < fs->files[i]->file) {
break;
}
idx++;
}
EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo);
fi->file = file_name;
fi->import_modified_time = 0;
fi->import_valid = ResourceLoader::is_import_valid(p_file);
if (idx == fs->files.size()) {
fs->files.push_back(fi);
} else {
fs->files.insert(idx, fi);
}
cpos = idx;
} else {
//the file exists and it was updated, and was not added in this step.
//this means we must force upon next restart to scan it again, to get proper type and dependencies
late_update_files.insert(p_file);
_save_late_updated_files(); //files need to be updated in the re-scan
}
fs->files[cpos]->type = type;
fs->files[cpos]->script_class_name = _get_global_script_class(type, p_file, &fs->files[cpos]->script_class_extends, &fs->files[cpos]->script_class_icon_path);
fs->files[cpos]->import_group_file = ResourceLoader::get_import_group_file(p_file);
fs->files[cpos]->modified_time = FileAccess::get_modified_time(p_file);
fs->files[cpos]->deps = _get_dependencies(p_file);
fs->files[cpos]->import_valid = ResourceLoader::is_import_valid(p_file);
// Update preview
EditorResourcePreview::get_singleton()->check_for_invalidation(p_file);
call_deferred("emit_signal", "filesystem_changed"); //update later
_queue_update_script_classes();
}
Error EditorFileSystem::_reimport_group(const String &p_group_file, const Vector<String> &p_files) {
String importer_name;
Map<String, Map<StringName, Variant>> source_file_options;
Map<String, String> base_paths;
for (int i = 0; i < p_files.size(); i++) {
Ref<ConfigFile> config;
config.instance();
Error err = config->load(p_files[i] + ".import");
ERR_CONTINUE(err != OK);
ERR_CONTINUE(!config->has_section_key("remap", "importer"));
String file_importer_name = config->get_value("remap", "importer");
ERR_CONTINUE(file_importer_name == String());
if (importer_name != String() && importer_name != file_importer_name) {
print_line("one importer '" + importer_name + "' the other '" + file_importer_name + "'.");
EditorNode::get_singleton()->show_warning(vformat(TTR("There are multiple importers for different types pointing to file %s, import aborted"), p_group_file));
ERR_FAIL_V(ERR_FILE_CORRUPT);
}
source_file_options[p_files[i]] = Map<StringName, Variant>();
importer_name = file_importer_name;
Ref<ResourceImporter> importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name);
ERR_FAIL_COND_V(!importer.is_valid(), ERR_FILE_CORRUPT);
List<ResourceImporter::ImportOption> options;
importer->get_import_options(&options);
//set default values
for (List<ResourceImporter::ImportOption>::Element *E = options.front(); E; E = E->next()) {
source_file_options[p_files[i]][E->get().option.name] = E->get().default_value;
}
if (config->has_section("params")) {
List<String> sk;
config->get_section_keys("params", &sk);
for (List<String>::Element *E = sk.front(); E; E = E->next()) {
String param = E->get();
Variant value = config->get_value("params", param);
//override with whathever is in file
source_file_options[p_files[i]][param] = value;
}
}
base_paths[p_files[i]] = ResourceFormatImporter::get_singleton()->get_import_base_path(p_files[i]);
}
ERR_FAIL_COND_V(importer_name == String(), ERR_UNCONFIGURED);
Ref<ResourceImporter> importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name);
Error err = importer->import_group_file(p_group_file, source_file_options, base_paths);
//all went well, overwrite config files with proper remaps and md5s
for (Map<String, Map<StringName, Variant>>::Element *E = source_file_options.front(); E; E = E->next()) {
const String &file = E->key();
String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(file);
FileAccessRef f = FileAccess::open(file + ".import", FileAccess::WRITE);
ERR_FAIL_COND_V_MSG(!f, ERR_FILE_CANT_OPEN, "Cannot open import file '" + file + ".import'.");
//write manually, as order matters ([remap] has to go first for performance).
f->store_line("[remap]");
f->store_line("");
f->store_line("importer=\"" + importer->get_importer_name() + "\"");
int version = importer->get_format_version();
if (version > 0) {
f->store_line("importer_version=" + itos(version));
}
if (importer->get_resource_type() != "") {
f->store_line("type=\"" + importer->get_resource_type() + "\"");
}
Vector<String> dest_paths;
if (err == OK) {
String path = base_path + "." + importer->get_save_extension();
f->store_line("path=\"" + path + "\"");
dest_paths.push_back(path);
}
f->store_line("group_file=" + Variant(p_group_file).get_construct_string());
if (err == OK) {
f->store_line("valid=true");
} else {
f->store_line("valid=false");
}
f->store_line("[deps]\n");
f->store_line("");
f->store_line("source_file=" + Variant(file).get_construct_string());
if (dest_paths.size()) {
Array dp;
for (int i = 0; i < dest_paths.size(); i++) {
dp.push_back(dest_paths[i]);
}
f->store_line("dest_files=" + Variant(dp).get_construct_string() + "\n");
}
f->store_line("[params]");
f->store_line("");
//store options in provided order, to avoid file changing. Order is also important because first match is accepted first.
List<ResourceImporter::ImportOption> options;
importer->get_import_options(&options);
//set default values
for (List<ResourceImporter::ImportOption>::Element *F = options.front(); F; F = F->next()) {
String base = F->get().option.name;
Variant v = F->get().default_value;
if (source_file_options[file].has(base)) {
v = source_file_options[file][base];
}
String value;
VariantWriter::write_to_string(v, value);
f->store_line(base + "=" + value);
}
f->close();
// Store the md5's of the various files. These are stored separately so that the .import files can be version controlled.
FileAccessRef md5s = FileAccess::open(base_path + ".md5", FileAccess::WRITE);
ERR_FAIL_COND_V_MSG(!md5s, ERR_FILE_CANT_OPEN, "Cannot open MD5 file '" + base_path + ".md5'.");
md5s->store_line("source_md5=\"" + FileAccess::get_md5(file) + "\"");
if (dest_paths.size()) {
md5s->store_line("dest_md5=\"" + FileAccess::get_multiple_md5(dest_paths) + "\"\n");
}
md5s->close();
EditorFileSystemDirectory *fs = nullptr;
int cpos = -1;
bool found = _find_file(file, &fs, cpos);
ERR_FAIL_COND_V_MSG(!found, ERR_UNCONFIGURED, "Can't find file '" + file + "'.");
//update modified times, to avoid reimport
fs->files[cpos]->modified_time = FileAccess::get_modified_time(file);
fs->files[cpos]->import_modified_time = FileAccess::get_modified_time(file + ".import");
fs->files[cpos]->deps = _get_dependencies(file);
fs->files[cpos]->type = importer->get_resource_type();
fs->files[cpos]->import_valid = err == OK;
//if file is currently up, maybe the source it was loaded from changed, so import math must be updated for it
//to reload properly
if (ResourceCache::has(file)) {
Resource *r = ResourceCache::get(file);
if (r->get_import_path() != String()) {
String dst_path = ResourceFormatImporter::get_singleton()->get_internal_resource_path(file);
r->set_import_path(dst_path);
r->set_import_last_modified_time(0);
}
}
EditorResourcePreview::get_singleton()->check_for_invalidation(file);
}
return err;
}
void EditorFileSystem::_reimport_file(const String &p_file) {
EditorFileSystemDirectory *fs = nullptr;
int cpos = -1;
bool found = _find_file(p_file, &fs, cpos);
ERR_FAIL_COND_MSG(!found, "Can't find file '" + p_file + "'.");
//try to obtain existing params
Map<StringName, Variant> params;
String importer_name;
if (FileAccess::exists(p_file + ".import")) {
//use existing
Ref<ConfigFile> cf;
cf.instance();
Error err = cf->load(p_file + ".import");
if (err == OK) {
if (cf->has_section("params")) {
List<String> sk;
cf->get_section_keys("params", &sk);
for (List<String>::Element *E = sk.front(); E; E = E->next()) {
params[E->get()] = cf->get_value("params", E->get());
}
}
if (cf->has_section("remap")) {
importer_name = cf->get_value("remap", "importer");
}
}
} else {
late_added_files.insert(p_file); //imported files do not call update_file(), but just in case..
}
Ref<ResourceImporter> importer;
bool load_default = false;
//find the importer
if (importer_name != "") {
importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name);
}
if (importer.is_null()) {
//not found by name, find by extension
importer = ResourceFormatImporter::get_singleton()->get_importer_by_extension(p_file.get_extension());
load_default = true;
if (importer.is_null()) {
ERR_PRINT("BUG: File queued for import, but can't be imported, importer for type '" + importer_name + "' not found.");
ERR_FAIL();
}
}
//mix with default params, in case a parameter is missing
List<ResourceImporter::ImportOption> opts;
importer->get_import_options(&opts);
for (List<ResourceImporter::ImportOption>::Element *E = opts.front(); E; E = E->next()) {
if (!params.has(E->get().option.name)) { //this one is not present
params[E->get().option.name] = E->get().default_value;
}
}
if (load_default && ProjectSettings::get_singleton()->has_setting("importer_defaults/" + importer->get_importer_name())) {
//use defaults if exist
Dictionary d = ProjectSettings::get_singleton()->get("importer_defaults/" + importer->get_importer_name());
List<Variant> v;
d.get_key_list(&v);
for (List<Variant>::Element *E = v.front(); E; E = E->next()) {
params[E->get()] = d[E->get()];
}
}
//finally, perform import!!
String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(p_file);
List<String> import_variants;
List<String> gen_files;
Variant metadata;
Error err = importer->import(p_file, base_path, params, &import_variants, &gen_files, &metadata);
if (err != OK) {
ERR_PRINT("Error importing '" + p_file + "'.");
}
//as import is complete, save the .import file
FileAccess *f = FileAccess::open(p_file + ".import", FileAccess::WRITE);
ERR_FAIL_COND_MSG(!f, "Cannot open file from path '" + p_file + ".import'.");
//write manually, as order matters ([remap] has to go first for performance).
f->store_line("[remap]");
f->store_line("");
f->store_line("importer=\"" + importer->get_importer_name() + "\"");
int version = importer->get_format_version();
if (version > 0) {
f->store_line("importer_version=" + itos(version));
}
if (importer->get_resource_type() != "") {
f->store_line("type=\"" + importer->get_resource_type() + "\"");
}
Vector<String> dest_paths;
if (err == OK) {
if (importer->get_save_extension() == "") {
//no path
} else if (import_variants.size()) {
//import with variants
for (List<String>::Element *E = import_variants.front(); E; E = E->next()) {
String path = base_path.c_escape() + "." + E->get() + "." + importer->get_save_extension();
f->store_line("path." + E->get() + "=\"" + path + "\"");
dest_paths.push_back(path);
}
} else {
String path = base_path + "." + importer->get_save_extension();
f->store_line("path=\"" + path + "\"");
dest_paths.push_back(path);
}
} else {
f->store_line("valid=false");
}
if (metadata != Variant()) {
f->store_line("metadata=" + metadata.get_construct_string());
}
f->store_line("");
f->store_line("[deps]\n");
if (gen_files.size()) {
Array genf;
for (List<String>::Element *E = gen_files.front(); E; E = E->next()) {
genf.push_back(E->get());
dest_paths.push_back(E->get());
}
String value;
VariantWriter::write_to_string(genf, value);
f->store_line("files=" + value);
f->store_line("");
}
f->store_line("source_file=" + Variant(p_file).get_construct_string());
if (dest_paths.size()) {
Array dp;
for (int i = 0; i < dest_paths.size(); i++) {
dp.push_back(dest_paths[i]);
}
f->store_line("dest_files=" + Variant(dp).get_construct_string() + "\n");
}
f->store_line("[params]");
f->store_line("");
//store options in provided order, to avoid file changing. Order is also important because first match is accepted first.
for (List<ResourceImporter::ImportOption>::Element *E = opts.front(); E; E = E->next()) {
String base = E->get().option.name;
String value;
VariantWriter::write_to_string(params[base], value);
f->store_line(base + "=" + value);
}
f->close();
memdelete(f);
// Store the md5's of the various files. These are stored separately so that the .import files can be version controlled.
FileAccess *md5s = FileAccess::open(base_path + ".md5", FileAccess::WRITE);
ERR_FAIL_COND_MSG(!md5s, "Cannot open MD5 file '" + base_path + ".md5'.");
md5s->store_line("source_md5=\"" + FileAccess::get_md5(p_file) + "\"");
if (dest_paths.size()) {
md5s->store_line("dest_md5=\"" + FileAccess::get_multiple_md5(dest_paths) + "\"\n");
}
md5s->close();
memdelete(md5s);
//update modified times, to avoid reimport
fs->files[cpos]->modified_time = FileAccess::get_modified_time(p_file);
fs->files[cpos]->import_modified_time = FileAccess::get_modified_time(p_file + ".import");
fs->files[cpos]->deps = _get_dependencies(p_file);
fs->files[cpos]->type = importer->get_resource_type();
fs->files[cpos]->import_valid = ResourceLoader::is_import_valid(p_file);
//if file is currently up, maybe the source it was loaded from changed, so import math must be updated for it
//to reload properly
if (ResourceCache::has(p_file)) {
Resource *r = ResourceCache::get(p_file);
if (r->get_import_path() != String()) {
String dst_path = ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_file);
r->set_import_path(dst_path);
r->set_import_last_modified_time(0);
}
}
EditorResourcePreview::get_singleton()->check_for_invalidation(p_file);
}
void EditorFileSystem::_find_group_files(EditorFileSystemDirectory *efd, Map<String, Vector<String>> &group_files, Set<String> &groups_to_reimport) {
int fc = efd->files.size();
const EditorFileSystemDirectory::FileInfo *const *files = efd->files.ptr();
for (int i = 0; i < fc; i++) {
if (groups_to_reimport.has(files[i]->import_group_file)) {
if (!group_files.has(files[i]->import_group_file)) {
group_files[files[i]->import_group_file] = Vector<String>();
}
group_files[files[i]->import_group_file].push_back(efd->get_file_path(i));
}
}
for (int i = 0; i < efd->get_subdir_count(); i++) {
_find_group_files(efd->get_subdir(i), group_files, groups_to_reimport);
}
}
void EditorFileSystem::reimport_files(const Vector<String> &p_files) {
{
// Ensure that ProjectSettings::IMPORTED_FILES_PATH exists.
DirAccess *da = DirAccess::open("res://");
if (da->change_dir(ProjectSettings::IMPORTED_FILES_PATH) != OK) {
Error err = da->make_dir_recursive(ProjectSettings::IMPORTED_FILES_PATH);
if (err || da->change_dir(ProjectSettings::IMPORTED_FILES_PATH) != OK) {
memdelete(da);
ERR_FAIL_MSG("Failed to create '" + ProjectSettings::IMPORTED_FILES_PATH + "' folder.");
}
}
memdelete(da);
}
importing = true;
EditorProgress pr("reimport", TTR("(Re)Importing Assets"), p_files.size());
Vector<ImportFile> files;
Set<String> groups_to_reimport;
for (int i = 0; i < p_files.size(); i++) {
String group_file = ResourceFormatImporter::get_singleton()->get_import_group_file(p_files[i]);
if (group_file_cache.has(p_files[i])) {
//maybe the file itself is a group!
groups_to_reimport.insert(p_files[i]);
//groups do not belong to grups
group_file = String();
} else if (group_file != String()) {
//it's a group file, add group to import and skip this file
groups_to_reimport.insert(group_file);
} else {
//it's a regular file
ImportFile ifile;
ifile.path = p_files[i];
ifile.order = ResourceFormatImporter::get_singleton()->get_import_order(p_files[i]);
files.push_back(ifile);
}
//group may have changed, so also update group reference
EditorFileSystemDirectory *fs = nullptr;
int cpos = -1;
if (_find_file(p_files[i], &fs, cpos)) {
fs->files.write[cpos]->import_group_file = group_file;
}
}
files.sort();
for (int i = 0; i < files.size(); i++) {
pr.step(files[i].path.get_file(), i);
_reimport_file(files[i].path);
}
//reimport groups
if (groups_to_reimport.size()) {
Map<String, Vector<String>> group_files;
_find_group_files(filesystem, group_files, groups_to_reimport);
for (Map<String, Vector<String>>::Element *E = group_files.front(); E; E = E->next()) {
Error err = _reimport_group(E->key(), E->get());
if (err == OK) {
_reimport_file(E->key());
}
}
}
_save_filesystem_cache();
importing = false;
if (!is_scanning()) {
emit_signal("filesystem_changed");
}
emit_signal("resources_reimported", p_files);
}
Error EditorFileSystem::_resource_import(const String &p_path) {
Vector<String> files;
files.push_back(p_path);
singleton->update_file(p_path);
singleton->reimport_files(files);
return OK;
}
bool EditorFileSystem::is_group_file(const String &p_path) const {
return group_file_cache.has(p_path);
}
void EditorFileSystem::_move_group_files(EditorFileSystemDirectory *efd, const String &p_group_file, const String &p_new_location) {
int fc = efd->files.size();
EditorFileSystemDirectory::FileInfo *const *files = efd->files.ptrw();
for (int i = 0; i < fc; i++) {
if (files[i]->import_group_file == p_group_file) {
files[i]->import_group_file = p_new_location;
Ref<ConfigFile> config;
config.instance();
String path = efd->get_file_path(i) + ".import";
Error err = config->load(path);
if (err != OK) {
continue;
}
if (config->has_section_key("remap", "group_file")) {
config->set_value("remap", "group_file", p_new_location);
}
List<String> sk;
config->get_section_keys("params", &sk);
for (List<String>::Element *E = sk.front(); E; E = E->next()) {
//not very clean, but should work
String param = E->get();
String value = config->get_value("params", param);
if (value == p_group_file) {
config->set_value("params", param, p_new_location);
}
}
config->save(path);
}
}
for (int i = 0; i < efd->get_subdir_count(); i++) {
_move_group_files(efd->get_subdir(i), p_group_file, p_new_location);
}
}
void EditorFileSystem::move_group_file(const String &p_path, const String &p_new_path) {
if (get_filesystem()) {
_move_group_files(get_filesystem(), p_path, p_new_path);
if (group_file_cache.has(p_path)) {
group_file_cache.erase(p_path);
group_file_cache.insert(p_new_path);
}
}
}
void EditorFileSystem::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_filesystem"), &EditorFileSystem::get_filesystem);
ClassDB::bind_method(D_METHOD("is_scanning"), &EditorFileSystem::is_scanning);
ClassDB::bind_method(D_METHOD("get_scanning_progress"), &EditorFileSystem::get_scanning_progress);
ClassDB::bind_method(D_METHOD("scan"), &EditorFileSystem::scan);
ClassDB::bind_method(D_METHOD("scan_sources"), &EditorFileSystem::scan_changes);
ClassDB::bind_method(D_METHOD("update_file", "path"), &EditorFileSystem::update_file);
ClassDB::bind_method(D_METHOD("get_filesystem_path", "path"), &EditorFileSystem::get_filesystem_path);
ClassDB::bind_method(D_METHOD("get_file_type", "path"), &EditorFileSystem::get_file_type);
ClassDB::bind_method(D_METHOD("update_script_classes"), &EditorFileSystem::update_script_classes);
ADD_SIGNAL(MethodInfo("filesystem_changed"));
ADD_SIGNAL(MethodInfo("sources_changed", PropertyInfo(Variant::BOOL, "exist")));
ADD_SIGNAL(MethodInfo("resources_reimported", PropertyInfo(Variant::PACKED_STRING_ARRAY, "resources")));
ADD_SIGNAL(MethodInfo("resources_reload", PropertyInfo(Variant::PACKED_STRING_ARRAY, "resources")));
}
void EditorFileSystem::_update_extensions() {
valid_extensions.clear();
import_extensions.clear();
List<String> extensionsl;
ResourceLoader::get_recognized_extensions_for_type("", &extensionsl);
for (List<String>::Element *E = extensionsl.front(); E; E = E->next()) {
valid_extensions.insert(E->get());
}
extensionsl.clear();
ResourceFormatImporter::get_singleton()->get_recognized_extensions(&extensionsl);
for (List<String>::Element *E = extensionsl.front(); E; E = E->next()) {
import_extensions.insert(E->get());
}
}
EditorFileSystem::EditorFileSystem() {
ResourceLoader::import = _resource_import;
reimport_on_missing_imported_files = GLOBAL_DEF("editor/reimport_missing_imported_files", true);
singleton = this;
filesystem = memnew(EditorFileSystemDirectory); //like, empty
filesystem->parent = nullptr;
thread = nullptr;
scanning = false;
importing = false;
use_threads = true;
thread_sources = nullptr;
new_filesystem = nullptr;
abort_scan = false;
scanning_changes = false;
scanning_changes_done = false;
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
if (da->change_dir(ProjectSettings::IMPORTED_FILES_PATH) != OK) {
da->make_dir(ProjectSettings::IMPORTED_FILES_PATH);
}
// This should probably also work on Unix and use the string it returns for FAT32 or exFAT
using_fat32_or_exfat = (da->get_filesystem_type() == "FAT32" || da->get_filesystem_type() == "exFAT");
memdelete(da);
scan_total = 0;
update_script_classes_queued = false;
first_scan = true;
scan_changes_pending = false;
revalidate_import_files = false;
}
EditorFileSystem::~EditorFileSystem() {
}
|
/*
* This file is part of the Electron Orbital Explorer. The Electron
* Orbital Explorer is distributed under the Simplified BSD License
* (also called the "BSD 2-Clause License"), in hopes that these
* rendering techniques might be used by other programmers in
* applications such as scientific visualization, video gaming, and so
* on. If you find value in this software and use its technologies for
* another purpose, I would love to hear back from you at bjthinks (at)
* gmail (dot) com. If you improve this software and agree to release
* your modifications under the below license, I encourage you to fork
* the development tree on github and push your modifications. The
* Electron Orbital Explorer's development URL is:
* https://github.com/bjthinks/orbital-explorer
* (This paragraph is not part of the software license and may be
* removed.)
*
* Copyright (c) 2013, Brian W. Johnson
* 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.
*
* 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.
*/
/*
* This file is a derivative work of Philippe Decaudin's AntTweakBar
* library, version 1.16, which is distributed under the following terms:
*
* Copyright (C) 2005-2013 Philippe Decaudin
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must
* not claim that you wrote the original software. If you use this
* software in a product, an acknowledgment in the product documentation
* would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must
* not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include <AntTweakBar.h>
#include "SDLtoATB.hh"
// TwEventSDL returns zero if msg has not been handled,
// and a non-zero value if it has been handled by the AntTweakBar library.
int TW_CALL myTwEventSDL20(const SDL_Event &event)
{
int handled = 0;
//static int s_KeyMod = 0;
switch (event.type) {
#if 0
case SDL_TEXTINPUT:
if (event.text.text[0] != 0 && event.text.text[1] == 0) {
if (s_KeyMod & TW_KMOD_CTRL && event.text.text[0] < 32)
handled = TwKeyPressed(event.text.text[0] + 'a' - 1, s_KeyMod);
else {
if (s_KeyMod & KMOD_RALT)
s_KeyMod &= ~KMOD_CTRL;
handled = TwKeyPressed(event.text.text[0], s_KeyMod);
}
}
s_KeyMod = 0;
break;
case SDL_KEYDOWN:
if (event.key.keysym.sym & SDLK_SCANCODE_MASK) {
int key = 0;
switch (event.key.keysym.sym) {
case SDLK_UP:
key = TW_KEY_UP;
break;
case SDLK_DOWN:
key = TW_KEY_DOWN;
break;
case SDLK_RIGHT:
key = TW_KEY_RIGHT;
break;
case SDLK_LEFT:
key = TW_KEY_LEFT;
break;
case SDLK_INSERT:
key = TW_KEY_INSERT;
break;
case SDLK_HOME:
key = TW_KEY_HOME;
break;
case SDLK_END:
key = TW_KEY_END;
break;
case SDLK_PAGEUP:
key = TW_KEY_PAGE_UP;
break;
case SDLK_PAGEDOWN:
key = TW_KEY_PAGE_DOWN;
break;
default:
if (event.key.keysym.sym >= SDLK_F1 &&
event.key.keysym.sym <= SDLK_F12)
key = event.key.keysym.sym + TW_KEY_F1 - SDLK_F1;
}
if (key != 0)
handled = TwKeyPressed(key, event.key.keysym.mod);
}
else if (event.key.keysym.mod & TW_KMOD_ALT)
handled = TwKeyPressed(event.key.keysym.sym & 0xFF,
event.key.keysym.mod);
else
s_KeyMod = event.key.keysym.mod;
break;
case SDL_KEYUP:
s_KeyMod = 0;
break;
#endif
case SDL_MOUSEMOTION:
handled = TwMouseMotion(event.motion.x, event.motion.y);
break;
case SDL_MOUSEWHEEL:
handled = TwMouseWheel(event.wheel.y);
break;
case SDL_MOUSEBUTTONUP:
case SDL_MOUSEBUTTONDOWN:
TwMouseAction action;
if (event.button.state == SDL_PRESSED)
action = TW_MOUSE_PRESSED;
else if (event.button.state == SDL_RELEASED)
action = TW_MOUSE_RELEASED;
else
break;
TwMouseButtonID button;
if (event.button.button == SDL_BUTTON_LMASK)
button = TW_MOUSE_LEFT;
else if (event.button.button == SDL_BUTTON_MMASK)
button = TW_MOUSE_MIDDLE;
else if (event.button.button == SDL_BUTTON_RMASK)
button = TW_MOUSE_RIGHT;
else
break;
handled = TwMouseButton(action, button);
break;
case SDL_WINDOWEVENT:
if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
// tell the new size to TweakBar
TwWindowSize(event.window.data1, event.window.data2);
// do not set 'handled', SDL_VIDEORESIZE may be also processed by
// the calling application
}
break;
}
return handled;
}
Handle ATB mouse wheel events correctly
/*
* This file is part of the Electron Orbital Explorer. The Electron
* Orbital Explorer is distributed under the Simplified BSD License
* (also called the "BSD 2-Clause License"), in hopes that these
* rendering techniques might be used by other programmers in
* applications such as scientific visualization, video gaming, and so
* on. If you find value in this software and use its technologies for
* another purpose, I would love to hear back from you at bjthinks (at)
* gmail (dot) com. If you improve this software and agree to release
* your modifications under the below license, I encourage you to fork
* the development tree on github and push your modifications. The
* Electron Orbital Explorer's development URL is:
* https://github.com/bjthinks/orbital-explorer
* (This paragraph is not part of the software license and may be
* removed.)
*
* Copyright (c) 2013, Brian W. Johnson
* 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.
*
* 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.
*/
/*
* This file is a derivative work of Philippe Decaudin's AntTweakBar
* library, version 1.16, which is distributed under the following terms:
*
* Copyright (C) 2005-2013 Philippe Decaudin
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must
* not claim that you wrote the original software. If you use this
* software in a product, an acknowledgment in the product documentation
* would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must
* not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include <AntTweakBar.h>
#include "SDLtoATB.hh"
// TwEventSDL returns zero if msg has not been handled,
// and a non-zero value if it has been handled by the AntTweakBar library.
int TW_CALL myTwEventSDL20(const SDL_Event &event)
{
int handled = 0;
//static int s_KeyMod = 0;
switch (event.type) {
#if 0
case SDL_TEXTINPUT:
if (event.text.text[0] != 0 && event.text.text[1] == 0) {
if (s_KeyMod & TW_KMOD_CTRL && event.text.text[0] < 32)
handled = TwKeyPressed(event.text.text[0] + 'a' - 1, s_KeyMod);
else {
if (s_KeyMod & KMOD_RALT)
s_KeyMod &= ~KMOD_CTRL;
handled = TwKeyPressed(event.text.text[0], s_KeyMod);
}
}
s_KeyMod = 0;
break;
case SDL_KEYDOWN:
if (event.key.keysym.sym & SDLK_SCANCODE_MASK) {
int key = 0;
switch (event.key.keysym.sym) {
case SDLK_UP:
key = TW_KEY_UP;
break;
case SDLK_DOWN:
key = TW_KEY_DOWN;
break;
case SDLK_RIGHT:
key = TW_KEY_RIGHT;
break;
case SDLK_LEFT:
key = TW_KEY_LEFT;
break;
case SDLK_INSERT:
key = TW_KEY_INSERT;
break;
case SDLK_HOME:
key = TW_KEY_HOME;
break;
case SDLK_END:
key = TW_KEY_END;
break;
case SDLK_PAGEUP:
key = TW_KEY_PAGE_UP;
break;
case SDLK_PAGEDOWN:
key = TW_KEY_PAGE_DOWN;
break;
default:
if (event.key.keysym.sym >= SDLK_F1 &&
event.key.keysym.sym <= SDLK_F12)
key = event.key.keysym.sym + TW_KEY_F1 - SDLK_F1;
}
if (key != 0)
handled = TwKeyPressed(key, event.key.keysym.mod);
}
else if (event.key.keysym.mod & TW_KMOD_ALT)
handled = TwKeyPressed(event.key.keysym.sym & 0xFF,
event.key.keysym.mod);
else
s_KeyMod = event.key.keysym.mod;
break;
case SDL_KEYUP:
s_KeyMod = 0;
break;
#endif
case SDL_MOUSEMOTION:
handled = TwMouseMotion(event.motion.x, event.motion.y);
break;
case SDL_MOUSEWHEEL:
{
static int s_WheelPos = 0;
s_WheelPos += event.wheel.y;
handled = TwMouseWheel(s_WheelPos);
}
break;
case SDL_MOUSEBUTTONUP:
case SDL_MOUSEBUTTONDOWN:
TwMouseAction action;
if (event.button.state == SDL_PRESSED)
action = TW_MOUSE_PRESSED;
else if (event.button.state == SDL_RELEASED)
action = TW_MOUSE_RELEASED;
else
break;
TwMouseButtonID button;
if (event.button.button == SDL_BUTTON_LMASK)
button = TW_MOUSE_LEFT;
else if (event.button.button == SDL_BUTTON_MMASK)
button = TW_MOUSE_MIDDLE;
else if (event.button.button == SDL_BUTTON_RMASK)
button = TW_MOUSE_RIGHT;
else
break;
handled = TwMouseButton(action, button);
break;
case SDL_WINDOWEVENT:
if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
// tell the new size to TweakBar
TwWindowSize(event.window.data1, event.window.data2);
// do not set 'handled', SDL_VIDEORESIZE may be also processed by
// the calling application
}
break;
}
return handled;
}
|
#include <stdlib.h>
#include <boost/bind.hpp>
#include "Log.h"
#include "Timestamp.h"
#include "NetDb.h"
#include "SSU.h"
#include "SSUData.h"
namespace i2p
{
namespace transport
{
void IncompleteMessage::AttachNextFragment (const uint8_t * fragment, size_t fragmentSize)
{
if (msg->len + fragmentSize > msg->maxLen)
{
LogPrint (eLogWarning, "SSU: I2NP message size ", msg->maxLen, " is not enough");
auto newMsg = NewI2NPMessage ();
*newMsg = *msg;
msg = newMsg;
}
if (msg->Concat (fragment, fragmentSize) < fragmentSize)
LogPrint (eLogError, "SSU: I2NP buffer overflow ", msg->maxLen);
nextFragmentNum++;
}
SSUData::SSUData (SSUSession& session):
m_Session (session), m_ResendTimer (session.GetService ()), m_DecayTimer (session.GetService ()),
m_IncompleteMessagesCleanupTimer (session.GetService ()),
m_MaxPacketSize (session.IsV6 () ? SSU_V6_MAX_PACKET_SIZE : SSU_V4_MAX_PACKET_SIZE),
m_PacketSize (m_MaxPacketSize)
{
}
SSUData::~SSUData ()
{
}
void SSUData::Start ()
{
ScheduleIncompleteMessagesCleanup ();
}
void SSUData::Stop ()
{
m_ResendTimer.cancel ();
m_DecayTimer.cancel ();
m_IncompleteMessagesCleanupTimer.cancel ();
}
void SSUData::AdjustPacketSize (std::shared_ptr<const i2p::data::RouterInfo> remoteRouter)
{
if (remoteRouter) return;
auto ssuAddress = remoteRouter->GetSSUAddress ();
if (ssuAddress && ssuAddress->mtu)
{
if (m_Session.IsV6 ())
m_PacketSize = ssuAddress->mtu - IPV6_HEADER_SIZE - UDP_HEADER_SIZE;
else
m_PacketSize = ssuAddress->mtu - IPV4_HEADER_SIZE - UDP_HEADER_SIZE;
if (m_PacketSize > 0)
{
// make sure packet size multiple of 16
m_PacketSize >>= 4;
m_PacketSize <<= 4;
if (m_PacketSize > m_MaxPacketSize) m_PacketSize = m_MaxPacketSize;
LogPrint (eLogDebug, "SSU: MTU=", ssuAddress->mtu, " packet size=", m_PacketSize);
}
else
{
LogPrint (eLogWarning, "SSU: Unexpected MTU ", ssuAddress->mtu);
m_PacketSize = m_MaxPacketSize;
}
}
}
void SSUData::UpdatePacketSize (const i2p::data::IdentHash& remoteIdent)
{
auto routerInfo = i2p::data::netdb.FindRouter (remoteIdent);
if (routerInfo)
AdjustPacketSize (routerInfo);
}
void SSUData::ProcessSentMessageAck (uint32_t msgID)
{
auto it = m_SentMessages.find (msgID);
if (it != m_SentMessages.end ())
{
m_SentMessages.erase (it);
if (m_SentMessages.empty ())
m_ResendTimer.cancel ();
}
}
void SSUData::ProcessAcks (uint8_t *& buf, uint8_t flag)
{
if (flag & DATA_FLAG_EXPLICIT_ACKS_INCLUDED)
{
// explicit ACKs
uint8_t numAcks =*buf;
buf++;
for (int i = 0; i < numAcks; i++)
ProcessSentMessageAck (bufbe32toh (buf+i*4));
buf += numAcks*4;
}
if (flag & DATA_FLAG_ACK_BITFIELDS_INCLUDED)
{
// explicit ACK bitfields
uint8_t numBitfields =*buf;
buf++;
for (int i = 0; i < numBitfields; i++)
{
uint32_t msgID = bufbe32toh (buf);
buf += 4; // msgID
auto it = m_SentMessages.find (msgID);
// process individual Ack bitfields
bool isNonLast = false;
int fragment = 0;
do
{
uint8_t bitfield = *buf;
isNonLast = bitfield & 0x80;
bitfield &= 0x7F; // clear MSB
if (bitfield && it != m_SentMessages.end ())
{
int numSentFragments = it->second->fragments.size ();
// process bits
uint8_t mask = 0x01;
for (int j = 0; j < 7; j++)
{
if (bitfield & mask)
{
if (fragment < numSentFragments)
it->second->fragments[fragment].reset (nullptr);
}
fragment++;
mask <<= 1;
}
}
buf++;
}
while (isNonLast);
}
}
}
void SSUData::ProcessFragments (uint8_t * buf)
{
uint8_t numFragments = *buf; // number of fragments
buf++;
for (int i = 0; i < numFragments; i++)
{
uint32_t msgID = bufbe32toh (buf); // message ID
buf += 4;
uint8_t frag[4];
frag[0] = 0;
memcpy (frag + 1, buf, 3);
buf += 3;
uint32_t fragmentInfo = bufbe32toh (frag); // fragment info
uint16_t fragmentSize = fragmentInfo & 0x1FFF; // bits 0 - 13
bool isLast = fragmentInfo & 0x010000; // bit 16
uint8_t fragmentNum = fragmentInfo >> 17; // bits 23 - 17
if (fragmentSize >= SSU_V4_MAX_PACKET_SIZE)
{
LogPrint (eLogError, "SSU: Fragment size ", fragmentSize, " exceeds max SSU packet size");
return;
}
// find message with msgID
auto it = m_IncompleteMessages.find (msgID);
if (it == m_IncompleteMessages.end ())
{
// create new message
auto msg = NewI2NPShortMessage ();
msg->len -= I2NP_SHORT_HEADER_SIZE;
it = m_IncompleteMessages.insert (std::make_pair (msgID,
std::unique_ptr<IncompleteMessage>(new IncompleteMessage (msg)))).first;
}
std::unique_ptr<IncompleteMessage>& incompleteMessage = it->second;
// handle current fragment
if (fragmentNum == incompleteMessage->nextFragmentNum)
{
// expected fragment
incompleteMessage->AttachNextFragment (buf, fragmentSize);
if (!isLast && !incompleteMessage->savedFragments.empty ())
{
// try saved fragments
for (auto it1 = incompleteMessage->savedFragments.begin (); it1 != incompleteMessage->savedFragments.end ();)
{
auto& savedFragment = *it1;
if (savedFragment->fragmentNum == incompleteMessage->nextFragmentNum)
{
incompleteMessage->AttachNextFragment (savedFragment->buf, savedFragment->len);
isLast = savedFragment->isLast;
incompleteMessage->savedFragments.erase (it1++);
}
else
break;
}
if (isLast)
LogPrint (eLogDebug, "SSU: Message ", msgID, " complete");
}
}
else
{
if (fragmentNum < incompleteMessage->nextFragmentNum)
// duplicate fragment
LogPrint (eLogWarning, "SSU: Duplicate fragment ", (int)fragmentNum, " of message ", msgID, ", ignored");
else
{
// missing fragment
LogPrint (eLogWarning, "SSU: Missing fragments from ", (int)incompleteMessage->nextFragmentNum, " to ", fragmentNum - 1, " of message ", msgID);
auto savedFragment = new Fragment (fragmentNum, buf, fragmentSize, isLast);
if (incompleteMessage->savedFragments.insert (std::unique_ptr<Fragment>(savedFragment)).second)
incompleteMessage->lastFragmentInsertTime = i2p::util::GetSecondsSinceEpoch ();
else
LogPrint (eLogWarning, "SSU: Fragment ", (int)fragmentNum, " of message ", msgID, " already saved");
}
isLast = false;
}
if (isLast)
{
// delete incomplete message
auto msg = incompleteMessage->msg;
incompleteMessage->msg = nullptr;
m_IncompleteMessages.erase (msgID);
// process message
SendMsgAck (msgID);
msg->FromSSU (msgID);
if (m_Session.GetState () == eSessionStateEstablished)
{
if (!m_ReceivedMessages.count (msgID))
{
if (m_ReceivedMessages.size () > MAX_NUM_RECEIVED_MESSAGES)
m_ReceivedMessages.clear ();
else
ScheduleDecay ();
m_ReceivedMessages.insert (msgID);
if (!msg->IsExpired ())
m_Handler.PutNextMessage (msg);
else
LogPrint (eLogInfo, "SSU: message expired");
}
else
LogPrint (eLogWarning, "SSU: Message ", msgID, " already received");
}
else
{
// we expect DeliveryStatus
if (msg->GetTypeID () == eI2NPDeliveryStatus)
{
LogPrint (eLogDebug, "SSU: session established");
m_Session.Established ();
}
else
LogPrint (eLogError, "SSU: unexpected message ", (int)msg->GetTypeID ());
}
}
else
SendFragmentAck (msgID, fragmentNum);
buf += fragmentSize;
}
}
void SSUData::FlushReceivedMessage ()
{
m_Handler.Flush ();
}
void SSUData::ProcessMessage (uint8_t * buf, size_t len)
{
//uint8_t * start = buf;
uint8_t flag = *buf;
buf++;
LogPrint (eLogDebug, "SSU: Process data, flags=", (int)flag, ", len=", len);
// process acks if presented
if (flag & (DATA_FLAG_ACK_BITFIELDS_INCLUDED | DATA_FLAG_EXPLICIT_ACKS_INCLUDED))
ProcessAcks (buf, flag);
// extended data if presented
if (flag & DATA_FLAG_EXTENDED_DATA_INCLUDED)
{
uint8_t extendedDataSize = *buf;
buf++; // size
LogPrint (eLogDebug, "SSU: extended data of ", extendedDataSize, " bytes present");
buf += extendedDataSize;
}
// process data
ProcessFragments (buf);
}
void SSUData::Send (std::shared_ptr<i2p::I2NPMessage> msg)
{
uint32_t msgID = msg->ToSSU ();
if (m_SentMessages.count (msgID) > 0)
{
LogPrint (eLogWarning, "SSU: message ", msgID, " already sent");
return;
}
if (m_SentMessages.empty ()) // schedule resend at first message only
ScheduleResend ();
auto ret = m_SentMessages.insert (std::make_pair (msgID, std::unique_ptr<SentMessage>(new SentMessage)));
std::unique_ptr<SentMessage>& sentMessage = ret.first->second;
if (ret.second)
{
sentMessage->nextResendTime = i2p::util::GetSecondsSinceEpoch () + RESEND_INTERVAL;
sentMessage->numResends = 0;
}
auto& fragments = sentMessage->fragments;
size_t payloadSize = m_PacketSize - sizeof (SSUHeader) - 9; // 9 = flag + #frg(1) + messageID(4) + frag info (3)
size_t len = msg->GetLength ();
uint8_t * msgBuf = msg->GetSSUHeader ();
uint32_t fragmentNum = 0;
while (len > 0)
{
Fragment * fragment = new Fragment;
fragment->fragmentNum = fragmentNum;
uint8_t * buf = fragment->buf;
uint8_t * payload = buf + sizeof (SSUHeader);
*payload = DATA_FLAG_WANT_REPLY; // for compatibility
payload++;
*payload = 1; // always 1 message fragment per message
payload++;
htobe32buf (payload, msgID);
payload += 4;
bool isLast = (len <= payloadSize);
size_t size = isLast ? len : payloadSize;
uint32_t fragmentInfo = (fragmentNum << 17);
if (isLast)
fragmentInfo |= 0x010000;
fragmentInfo |= size;
fragmentInfo = htobe32 (fragmentInfo);
memcpy (payload, (uint8_t *)(&fragmentInfo) + 1, 3);
payload += 3;
memcpy (payload, msgBuf, size);
size += payload - buf;
if (size & 0x0F) // make sure 16 bytes boundary
size = ((size >> 4) + 1) << 4; // (/16 + 1)*16
fragment->len = size;
fragments.push_back (std::unique_ptr<Fragment> (fragment));
// encrypt message with session key
m_Session.FillHeaderAndEncrypt (PAYLOAD_TYPE_DATA, buf, size);
try
{
m_Session.Send (buf, size);
}
catch (boost::system::system_error& ec)
{
LogPrint (eLogWarning, "SSU: Can't send data fragment ", ec.what ());
}
if (!isLast)
{
len -= payloadSize;
msgBuf += payloadSize;
}
else
len = 0;
fragmentNum++;
}
}
void SSUData::SendMsgAck (uint32_t msgID)
{
uint8_t buf[48 + 18]; // actual length is 44 = 37 + 7 but pad it to multiple of 16
uint8_t * payload = buf + sizeof (SSUHeader);
*payload = DATA_FLAG_EXPLICIT_ACKS_INCLUDED; // flag
payload++;
*payload = 1; // number of ACKs
payload++;
htobe32buf (payload, msgID); // msgID
payload += 4;
*payload = 0; // number of fragments
// encrypt message with session key
m_Session.FillHeaderAndEncrypt (PAYLOAD_TYPE_DATA, buf, 48);
m_Session.Send (buf, 48);
}
void SSUData::SendFragmentAck (uint32_t msgID, int fragmentNum)
{
if (fragmentNum > 64)
{
LogPrint (eLogWarning, "SSU: Fragment number ", fragmentNum, " exceeds 64");
return;
}
uint8_t buf[64 + 18];
uint8_t * payload = buf + sizeof (SSUHeader);
*payload = DATA_FLAG_ACK_BITFIELDS_INCLUDED; // flag
payload++;
*payload = 1; // number of ACK bitfields
payload++;
// one ack
*(uint32_t *)(payload) = htobe32 (msgID); // msgID
payload += 4;
div_t d = div (fragmentNum, 7);
memset (payload, 0x80, d.quot); // 0x80 means non-last
payload += d.quot;
*payload = 0x01 << d.rem; // set corresponding bit
payload++;
*payload = 0; // number of fragments
size_t len = d.quot < 4 ? 48 : 64; // 48 = 37 + 7 + 4 (3+1)
// encrypt message with session key
m_Session.FillHeaderAndEncrypt (PAYLOAD_TYPE_DATA, buf, len);
m_Session.Send (buf, len);
}
void SSUData::ScheduleResend()
{
m_ResendTimer.cancel ();
m_ResendTimer.expires_from_now (boost::posix_time::seconds(RESEND_INTERVAL));
auto s = m_Session.shared_from_this();
m_ResendTimer.async_wait ([s](const boost::system::error_code& ecode)
{ s->m_Data.HandleResendTimer (ecode); });
}
void SSUData::HandleResendTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
for (auto it = m_SentMessages.begin (); it != m_SentMessages.end ();)
{
if (ts >= it->second->nextResendTime)
{
if (it->second->numResends < MAX_NUM_RESENDS)
{
for (auto& f: it->second->fragments)
if (f)
{
try
{
m_Session.Send (f->buf, f->len); // resend
}
catch (boost::system::system_error& ec)
{
LogPrint (eLogWarning, "SSU: Can't resend data fragment ", ec.what ());
}
}
it->second->numResends++;
it->second->nextResendTime += it->second->numResends*RESEND_INTERVAL;
it++;
}
else
{
LogPrint (eLogInfo, "SSU: message has not been ACKed after ", MAX_NUM_RESENDS, " attempts, deleted");
it = m_SentMessages.erase (it);
}
}
else
it++;
}
ScheduleResend ();
}
}
void SSUData::ScheduleDecay ()
{
m_DecayTimer.cancel ();
m_DecayTimer.expires_from_now (boost::posix_time::seconds(DECAY_INTERVAL));
auto s = m_Session.shared_from_this();
m_ResendTimer.async_wait ([s](const boost::system::error_code& ecode)
{ s->m_Data.HandleDecayTimer (ecode); });
}
void SSUData::HandleDecayTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
m_ReceivedMessages.clear ();
}
void SSUData::ScheduleIncompleteMessagesCleanup ()
{
m_IncompleteMessagesCleanupTimer.cancel ();
m_IncompleteMessagesCleanupTimer.expires_from_now (boost::posix_time::seconds(INCOMPLETE_MESSAGES_CLEANUP_TIMEOUT));
auto s = m_Session.shared_from_this();
m_IncompleteMessagesCleanupTimer.async_wait ([s](const boost::system::error_code& ecode)
{ s->m_Data.HandleIncompleteMessagesCleanupTimer (ecode); });
}
void SSUData::HandleIncompleteMessagesCleanupTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
for (auto it = m_IncompleteMessages.begin (); it != m_IncompleteMessages.end ();)
{
if (ts > it->second->lastFragmentInsertTime + INCOMPLETE_MESSAGES_CLEANUP_TIMEOUT)
{
LogPrint (eLogWarning, "SSU: message ", it->first, " was not completed in ", INCOMPLETE_MESSAGES_CLEANUP_TIMEOUT, " seconds, deleted");
it = m_IncompleteMessages.erase (it);
}
else
it++;
}
ScheduleIncompleteMessagesCleanup ();
}
}
}
}
fixed incorrect long fragment size
#include <stdlib.h>
#include <boost/bind.hpp>
#include "Log.h"
#include "Timestamp.h"
#include "NetDb.h"
#include "SSU.h"
#include "SSUData.h"
namespace i2p
{
namespace transport
{
void IncompleteMessage::AttachNextFragment (const uint8_t * fragment, size_t fragmentSize)
{
if (msg->len + fragmentSize > msg->maxLen)
{
LogPrint (eLogWarning, "SSU: I2NP message size ", msg->maxLen, " is not enough");
auto newMsg = NewI2NPMessage ();
*newMsg = *msg;
msg = newMsg;
}
if (msg->Concat (fragment, fragmentSize) < fragmentSize)
LogPrint (eLogError, "SSU: I2NP buffer overflow ", msg->maxLen);
nextFragmentNum++;
}
SSUData::SSUData (SSUSession& session):
m_Session (session), m_ResendTimer (session.GetService ()), m_DecayTimer (session.GetService ()),
m_IncompleteMessagesCleanupTimer (session.GetService ()),
m_MaxPacketSize (session.IsV6 () ? SSU_V6_MAX_PACKET_SIZE : SSU_V4_MAX_PACKET_SIZE),
m_PacketSize (m_MaxPacketSize)
{
}
SSUData::~SSUData ()
{
}
void SSUData::Start ()
{
ScheduleIncompleteMessagesCleanup ();
}
void SSUData::Stop ()
{
m_ResendTimer.cancel ();
m_DecayTimer.cancel ();
m_IncompleteMessagesCleanupTimer.cancel ();
}
void SSUData::AdjustPacketSize (std::shared_ptr<const i2p::data::RouterInfo> remoteRouter)
{
if (remoteRouter) return;
auto ssuAddress = remoteRouter->GetSSUAddress ();
if (ssuAddress && ssuAddress->mtu)
{
if (m_Session.IsV6 ())
m_PacketSize = ssuAddress->mtu - IPV6_HEADER_SIZE - UDP_HEADER_SIZE;
else
m_PacketSize = ssuAddress->mtu - IPV4_HEADER_SIZE - UDP_HEADER_SIZE;
if (m_PacketSize > 0)
{
// make sure packet size multiple of 16
m_PacketSize >>= 4;
m_PacketSize <<= 4;
if (m_PacketSize > m_MaxPacketSize) m_PacketSize = m_MaxPacketSize;
LogPrint (eLogDebug, "SSU: MTU=", ssuAddress->mtu, " packet size=", m_PacketSize);
}
else
{
LogPrint (eLogWarning, "SSU: Unexpected MTU ", ssuAddress->mtu);
m_PacketSize = m_MaxPacketSize;
}
}
}
void SSUData::UpdatePacketSize (const i2p::data::IdentHash& remoteIdent)
{
auto routerInfo = i2p::data::netdb.FindRouter (remoteIdent);
if (routerInfo)
AdjustPacketSize (routerInfo);
}
void SSUData::ProcessSentMessageAck (uint32_t msgID)
{
auto it = m_SentMessages.find (msgID);
if (it != m_SentMessages.end ())
{
m_SentMessages.erase (it);
if (m_SentMessages.empty ())
m_ResendTimer.cancel ();
}
}
void SSUData::ProcessAcks (uint8_t *& buf, uint8_t flag)
{
if (flag & DATA_FLAG_EXPLICIT_ACKS_INCLUDED)
{
// explicit ACKs
uint8_t numAcks =*buf;
buf++;
for (int i = 0; i < numAcks; i++)
ProcessSentMessageAck (bufbe32toh (buf+i*4));
buf += numAcks*4;
}
if (flag & DATA_FLAG_ACK_BITFIELDS_INCLUDED)
{
// explicit ACK bitfields
uint8_t numBitfields =*buf;
buf++;
for (int i = 0; i < numBitfields; i++)
{
uint32_t msgID = bufbe32toh (buf);
buf += 4; // msgID
auto it = m_SentMessages.find (msgID);
// process individual Ack bitfields
bool isNonLast = false;
int fragment = 0;
do
{
uint8_t bitfield = *buf;
isNonLast = bitfield & 0x80;
bitfield &= 0x7F; // clear MSB
if (bitfield && it != m_SentMessages.end ())
{
int numSentFragments = it->second->fragments.size ();
// process bits
uint8_t mask = 0x01;
for (int j = 0; j < 7; j++)
{
if (bitfield & mask)
{
if (fragment < numSentFragments)
it->second->fragments[fragment].reset (nullptr);
}
fragment++;
mask <<= 1;
}
}
buf++;
}
while (isNonLast);
}
}
}
void SSUData::ProcessFragments (uint8_t * buf)
{
uint8_t numFragments = *buf; // number of fragments
buf++;
for (int i = 0; i < numFragments; i++)
{
uint32_t msgID = bufbe32toh (buf); // message ID
buf += 4;
uint8_t frag[4];
frag[0] = 0;
memcpy (frag + 1, buf, 3);
buf += 3;
uint32_t fragmentInfo = bufbe32toh (frag); // fragment info
uint16_t fragmentSize = fragmentInfo & 0x3FFF; // bits 0 - 13
bool isLast = fragmentInfo & 0x010000; // bit 16
uint8_t fragmentNum = fragmentInfo >> 17; // bits 23 - 17
if (fragmentSize >= SSU_V4_MAX_PACKET_SIZE)
{
LogPrint (eLogError, "SSU: Fragment size ", fragmentSize, " exceeds max SSU packet size");
return;
}
// find message with msgID
auto it = m_IncompleteMessages.find (msgID);
if (it == m_IncompleteMessages.end ())
{
// create new message
auto msg = NewI2NPShortMessage ();
msg->len -= I2NP_SHORT_HEADER_SIZE;
it = m_IncompleteMessages.insert (std::make_pair (msgID,
std::unique_ptr<IncompleteMessage>(new IncompleteMessage (msg)))).first;
}
std::unique_ptr<IncompleteMessage>& incompleteMessage = it->second;
// handle current fragment
if (fragmentNum == incompleteMessage->nextFragmentNum)
{
// expected fragment
incompleteMessage->AttachNextFragment (buf, fragmentSize);
if (!isLast && !incompleteMessage->savedFragments.empty ())
{
// try saved fragments
for (auto it1 = incompleteMessage->savedFragments.begin (); it1 != incompleteMessage->savedFragments.end ();)
{
auto& savedFragment = *it1;
if (savedFragment->fragmentNum == incompleteMessage->nextFragmentNum)
{
incompleteMessage->AttachNextFragment (savedFragment->buf, savedFragment->len);
isLast = savedFragment->isLast;
incompleteMessage->savedFragments.erase (it1++);
}
else
break;
}
if (isLast)
LogPrint (eLogDebug, "SSU: Message ", msgID, " complete");
}
}
else
{
if (fragmentNum < incompleteMessage->nextFragmentNum)
// duplicate fragment
LogPrint (eLogWarning, "SSU: Duplicate fragment ", (int)fragmentNum, " of message ", msgID, ", ignored");
else
{
// missing fragment
LogPrint (eLogWarning, "SSU: Missing fragments from ", (int)incompleteMessage->nextFragmentNum, " to ", fragmentNum - 1, " of message ", msgID);
auto savedFragment = new Fragment (fragmentNum, buf, fragmentSize, isLast);
if (incompleteMessage->savedFragments.insert (std::unique_ptr<Fragment>(savedFragment)).second)
incompleteMessage->lastFragmentInsertTime = i2p::util::GetSecondsSinceEpoch ();
else
LogPrint (eLogWarning, "SSU: Fragment ", (int)fragmentNum, " of message ", msgID, " already saved");
}
isLast = false;
}
if (isLast)
{
// delete incomplete message
auto msg = incompleteMessage->msg;
incompleteMessage->msg = nullptr;
m_IncompleteMessages.erase (msgID);
// process message
SendMsgAck (msgID);
msg->FromSSU (msgID);
if (m_Session.GetState () == eSessionStateEstablished)
{
if (!m_ReceivedMessages.count (msgID))
{
if (m_ReceivedMessages.size () > MAX_NUM_RECEIVED_MESSAGES)
m_ReceivedMessages.clear ();
else
ScheduleDecay ();
m_ReceivedMessages.insert (msgID);
if (!msg->IsExpired ())
m_Handler.PutNextMessage (msg);
else
LogPrint (eLogInfo, "SSU: message expired");
}
else
LogPrint (eLogWarning, "SSU: Message ", msgID, " already received");
}
else
{
// we expect DeliveryStatus
if (msg->GetTypeID () == eI2NPDeliveryStatus)
{
LogPrint (eLogDebug, "SSU: session established");
m_Session.Established ();
}
else
LogPrint (eLogError, "SSU: unexpected message ", (int)msg->GetTypeID ());
}
}
else
SendFragmentAck (msgID, fragmentNum);
buf += fragmentSize;
}
}
void SSUData::FlushReceivedMessage ()
{
m_Handler.Flush ();
}
void SSUData::ProcessMessage (uint8_t * buf, size_t len)
{
//uint8_t * start = buf;
uint8_t flag = *buf;
buf++;
LogPrint (eLogDebug, "SSU: Process data, flags=", (int)flag, ", len=", len);
// process acks if presented
if (flag & (DATA_FLAG_ACK_BITFIELDS_INCLUDED | DATA_FLAG_EXPLICIT_ACKS_INCLUDED))
ProcessAcks (buf, flag);
// extended data if presented
if (flag & DATA_FLAG_EXTENDED_DATA_INCLUDED)
{
uint8_t extendedDataSize = *buf;
buf++; // size
LogPrint (eLogDebug, "SSU: extended data of ", extendedDataSize, " bytes present");
buf += extendedDataSize;
}
// process data
ProcessFragments (buf);
}
void SSUData::Send (std::shared_ptr<i2p::I2NPMessage> msg)
{
uint32_t msgID = msg->ToSSU ();
if (m_SentMessages.count (msgID) > 0)
{
LogPrint (eLogWarning, "SSU: message ", msgID, " already sent");
return;
}
if (m_SentMessages.empty ()) // schedule resend at first message only
ScheduleResend ();
auto ret = m_SentMessages.insert (std::make_pair (msgID, std::unique_ptr<SentMessage>(new SentMessage)));
std::unique_ptr<SentMessage>& sentMessage = ret.first->second;
if (ret.second)
{
sentMessage->nextResendTime = i2p::util::GetSecondsSinceEpoch () + RESEND_INTERVAL;
sentMessage->numResends = 0;
}
auto& fragments = sentMessage->fragments;
size_t payloadSize = m_PacketSize - sizeof (SSUHeader) - 9; // 9 = flag + #frg(1) + messageID(4) + frag info (3)
size_t len = msg->GetLength ();
uint8_t * msgBuf = msg->GetSSUHeader ();
uint32_t fragmentNum = 0;
while (len > 0)
{
Fragment * fragment = new Fragment;
fragment->fragmentNum = fragmentNum;
uint8_t * buf = fragment->buf;
uint8_t * payload = buf + sizeof (SSUHeader);
*payload = DATA_FLAG_WANT_REPLY; // for compatibility
payload++;
*payload = 1; // always 1 message fragment per message
payload++;
htobe32buf (payload, msgID);
payload += 4;
bool isLast = (len <= payloadSize);
size_t size = isLast ? len : payloadSize;
uint32_t fragmentInfo = (fragmentNum << 17);
if (isLast)
fragmentInfo |= 0x010000;
fragmentInfo |= size;
fragmentInfo = htobe32 (fragmentInfo);
memcpy (payload, (uint8_t *)(&fragmentInfo) + 1, 3);
payload += 3;
memcpy (payload, msgBuf, size);
size += payload - buf;
if (size & 0x0F) // make sure 16 bytes boundary
size = ((size >> 4) + 1) << 4; // (/16 + 1)*16
fragment->len = size;
fragments.push_back (std::unique_ptr<Fragment> (fragment));
// encrypt message with session key
m_Session.FillHeaderAndEncrypt (PAYLOAD_TYPE_DATA, buf, size);
try
{
m_Session.Send (buf, size);
}
catch (boost::system::system_error& ec)
{
LogPrint (eLogWarning, "SSU: Can't send data fragment ", ec.what ());
}
if (!isLast)
{
len -= payloadSize;
msgBuf += payloadSize;
}
else
len = 0;
fragmentNum++;
}
}
void SSUData::SendMsgAck (uint32_t msgID)
{
uint8_t buf[48 + 18]; // actual length is 44 = 37 + 7 but pad it to multiple of 16
uint8_t * payload = buf + sizeof (SSUHeader);
*payload = DATA_FLAG_EXPLICIT_ACKS_INCLUDED; // flag
payload++;
*payload = 1; // number of ACKs
payload++;
htobe32buf (payload, msgID); // msgID
payload += 4;
*payload = 0; // number of fragments
// encrypt message with session key
m_Session.FillHeaderAndEncrypt (PAYLOAD_TYPE_DATA, buf, 48);
m_Session.Send (buf, 48);
}
void SSUData::SendFragmentAck (uint32_t msgID, int fragmentNum)
{
if (fragmentNum > 64)
{
LogPrint (eLogWarning, "SSU: Fragment number ", fragmentNum, " exceeds 64");
return;
}
uint8_t buf[64 + 18];
uint8_t * payload = buf + sizeof (SSUHeader);
*payload = DATA_FLAG_ACK_BITFIELDS_INCLUDED; // flag
payload++;
*payload = 1; // number of ACK bitfields
payload++;
// one ack
*(uint32_t *)(payload) = htobe32 (msgID); // msgID
payload += 4;
div_t d = div (fragmentNum, 7);
memset (payload, 0x80, d.quot); // 0x80 means non-last
payload += d.quot;
*payload = 0x01 << d.rem; // set corresponding bit
payload++;
*payload = 0; // number of fragments
size_t len = d.quot < 4 ? 48 : 64; // 48 = 37 + 7 + 4 (3+1)
// encrypt message with session key
m_Session.FillHeaderAndEncrypt (PAYLOAD_TYPE_DATA, buf, len);
m_Session.Send (buf, len);
}
void SSUData::ScheduleResend()
{
m_ResendTimer.cancel ();
m_ResendTimer.expires_from_now (boost::posix_time::seconds(RESEND_INTERVAL));
auto s = m_Session.shared_from_this();
m_ResendTimer.async_wait ([s](const boost::system::error_code& ecode)
{ s->m_Data.HandleResendTimer (ecode); });
}
void SSUData::HandleResendTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
for (auto it = m_SentMessages.begin (); it != m_SentMessages.end ();)
{
if (ts >= it->second->nextResendTime)
{
if (it->second->numResends < MAX_NUM_RESENDS)
{
for (auto& f: it->second->fragments)
if (f)
{
try
{
m_Session.Send (f->buf, f->len); // resend
}
catch (boost::system::system_error& ec)
{
LogPrint (eLogWarning, "SSU: Can't resend data fragment ", ec.what ());
}
}
it->second->numResends++;
it->second->nextResendTime += it->second->numResends*RESEND_INTERVAL;
it++;
}
else
{
LogPrint (eLogInfo, "SSU: message has not been ACKed after ", MAX_NUM_RESENDS, " attempts, deleted");
it = m_SentMessages.erase (it);
}
}
else
it++;
}
ScheduleResend ();
}
}
void SSUData::ScheduleDecay ()
{
m_DecayTimer.cancel ();
m_DecayTimer.expires_from_now (boost::posix_time::seconds(DECAY_INTERVAL));
auto s = m_Session.shared_from_this();
m_ResendTimer.async_wait ([s](const boost::system::error_code& ecode)
{ s->m_Data.HandleDecayTimer (ecode); });
}
void SSUData::HandleDecayTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
m_ReceivedMessages.clear ();
}
void SSUData::ScheduleIncompleteMessagesCleanup ()
{
m_IncompleteMessagesCleanupTimer.cancel ();
m_IncompleteMessagesCleanupTimer.expires_from_now (boost::posix_time::seconds(INCOMPLETE_MESSAGES_CLEANUP_TIMEOUT));
auto s = m_Session.shared_from_this();
m_IncompleteMessagesCleanupTimer.async_wait ([s](const boost::system::error_code& ecode)
{ s->m_Data.HandleIncompleteMessagesCleanupTimer (ecode); });
}
void SSUData::HandleIncompleteMessagesCleanupTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
for (auto it = m_IncompleteMessages.begin (); it != m_IncompleteMessages.end ();)
{
if (ts > it->second->lastFragmentInsertTime + INCOMPLETE_MESSAGES_CLEANUP_TIMEOUT)
{
LogPrint (eLogWarning, "SSU: message ", it->first, " was not completed in ", INCOMPLETE_MESSAGES_CLEANUP_TIMEOUT, " seconds, deleted");
it = m_IncompleteMessages.erase (it);
}
else
it++;
}
ScheduleIncompleteMessagesCleanup ();
}
}
}
}
|
// Time: O(logn)
// Space: O(1)
// Iterative solution.
class Solution {
public:
double myPow(double x, int n) {
double result = 1;
long long abs_n = abs(static_cast<long long>(n));
while (abs_n > 0) {
if (abs_n & 1) {
result *= x;
}
abs_n >>= 1;
x *= x;
}
return n < 0 ? 1 / result : result;
}
};
// Time: O(logn)
// Space: O(logn)
// Recursive solution.
class Solution2 {
public:
double myPow(double x, int n) {
if (n < 0 && n != -n) {
return 1.0 / myPow(x, -n);
}
if (n == 0) {
return 1;
}
double v = myPow(x, n / 2);
if (n % 2 == 0) {
return v * v;
} else {
return v * v * x;
}
}
};
Update powx-n.cpp
// Time: O(logn) = O(1)
// Space: O(1)
// Iterative solution.
class Solution {
public:
double myPow(double x, int n) {
double result = 1;
long long abs_n = abs(static_cast<long long>(n));
while (abs_n > 0) {
if (abs_n & 1) {
result *= x;
}
abs_n >>= 1;
x *= x;
}
return n < 0 ? 1 / result : result;
}
};
// Time: O(logn) = O(1)
// Space: O(logn) = O(1)
// Recursive solution.
class Solution2 {
public:
double myPow(double x, int n) {
if (n < 0 && n != -n) {
return 1.0 / myPow(x, -n);
}
if (n == 0) {
return 1;
}
double v = myPow(x, n / 2);
if (n % 2 == 0) {
return v * v;
} else {
return v * v * x;
}
}
};
|
/*************************************************************************
*
* $RCSfile: shapeexport2.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: aw $ $Date: 2001-06-26 15:35:06 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART_XCHARTDOCUMENT_HPP_
#include <com/sun/star/chart/XChartDocument.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_CIRCLEKIND_HPP_
#include <com/sun/star/drawing/CircleKind.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_CONNECTORTYPE_HPP_
#include <com/sun/star/drawing/ConnectorType.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XCONTROLSHAPE_HPP_
#include <com/sun/star/drawing/XControlShape.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POLYPOLYGONBEZIERCOORDS_HPP_
#include <com/sun/star/drawing/PolyPolygonBezierCoords.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_
#include <com/sun/star/document/XEventsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_HOMOGENMATRIX3_HPP_
#include <com/sun/star/drawing/HomogenMatrix3.hpp>
#endif
#ifndef _XMLOFF_ANIM_HXX
#include "anim.hxx"
#endif
#ifndef _XMLOFF_SHAPEEXPORT_HXX
#include "shapeexport.hxx"
#endif
#ifndef _SDPROPLS_HXX
#include "sdpropls.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_XMLIMAGEMAPEXPORT_HXX_
#include "XMLImageMapExport.hxx"
#endif
#ifndef _XEXPTRANSFORM_HXX
#include "xexptran.hxx"
#endif
#ifndef _SV_SALBTYPE_HXX
#include <vcl/salbtype.hxx> // FRound
#endif
#include "xmlkywd.hxx"
#include "xmlnmspe.hxx"
using namespace ::rtl;
using namespace ::com::sun::star;
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportNewTrans(const uno::Reference< beans::XPropertySet >& xPropSet,
sal_Int32 nFeatures, awt::Point* pRefPoint)
{
// get matrix
Matrix3D aMat;
ImpExportNewTrans_GetMatrix3D(aMat, xPropSet);
// decompose and correct abour pRefPoint
Vector2D aTRScale;
double fTRShear(0.0);
double fTRRotate(0.0);
Vector2D aTRTranslate;
ImpExportNewTrans_DecomposeAndRefPoint(aMat, aTRScale, fTRShear, fTRRotate, aTRTranslate, pRefPoint);
// use features and write
ImpExportNewTrans_FeaturesAndWrite(aTRScale, fTRShear, fTRRotate, aTRTranslate, nFeatures);
}
void XMLShapeExport::ImpExportNewTrans_GetMatrix3D(Matrix3D& rMat,
const uno::Reference< beans::XPropertySet >& xPropSet)
{
uno::Any aAny = xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("Transformation")));
drawing::HomogenMatrix3 aMatrix;
aAny >>= aMatrix;
rMat[0] = Point3D( aMatrix.Line1.Column1, aMatrix.Line1.Column2, aMatrix.Line1.Column3 );
rMat[1] = Point3D( aMatrix.Line2.Column1, aMatrix.Line2.Column2, aMatrix.Line2.Column3 );
rMat[2] = Point3D( aMatrix.Line3.Column1, aMatrix.Line3.Column2, aMatrix.Line3.Column3 );
}
void XMLShapeExport::ImpExportNewTrans_DecomposeAndRefPoint(const Matrix3D& rMat,
Vector2D& rTRScale, double& fTRShear, double& fTRRotate, Vector2D& rTRTranslate,
awt::Point* pRefPoint)
{
// decompose matrix
rMat.DecomposeAndCorrect(rTRScale, fTRShear, fTRRotate, rTRTranslate);
// correct translation about pRefPoint
if(pRefPoint)
{
rTRTranslate.X() -= pRefPoint->X;
rTRTranslate.Y() -= pRefPoint->Y;
}
}
void XMLShapeExport::ImpExportNewTrans_FeaturesAndWrite(Vector2D& rTRScale, double fTRShear,
double fTRRotate, Vector2D& rTRTranslate, const sal_Int32 nFeatures)
{
// allways write Size (rTRScale) since this statement carries the union
// of the object
OUString aStr;
OUStringBuffer sStringBuffer;
Vector2D aTRScale = rTRScale;
// svg: width
if(!(nFeatures & SEF_EXPORT_WIDTH))
aTRScale.X() = 1.0;
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, FRound(aTRScale.X()));
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_width, aStr);
// svg: height
if(!(nFeatures & SEF_EXPORT_HEIGHT))
aTRScale.Y() = 1.0;
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, FRound(aTRScale.Y()));
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_height, aStr);
// decide if transformation is neccessary
BOOL bTransformationIsNeccessary(fTRShear != 0.0 || fTRRotate != 0.0);
if(bTransformationIsNeccessary)
{
// write transformation, but WITHOUT scale which is exported as size above
SdXMLImExTransform2D aTransform;
aTransform.AddSkewX(atan(fTRShear));
aTransform.AddRotate(fTRRotate);
aTransform.AddTranslate(rTRTranslate);
// does transformation need to be exported?
if(aTransform.NeedsAction())
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_transform, aTransform.GetExportString(rExport.GetMM100UnitConverter()));
}
else
{
// no shear, no rotate; just add object position to export and we are done
if(nFeatures & SEF_EXPORT_X)
{
// svg: x
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, FRound(rTRTranslate.X()));
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_x, aStr);
}
if(nFeatures & SEF_EXPORT_Y)
{
// svg: y
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, FRound(rTRTranslate.Y()));
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_y, aStr);
}
}
}
//////////////////////////////////////////////////////////////////////////////
sal_Bool XMLShapeExport::ImpExportPresentationAttributes( const uno::Reference< beans::XPropertySet >& xPropSet, const rtl::OUString& rClass )
{
sal_Bool bIsEmpty = sal_False;
OUStringBuffer sStringBuffer;
// write presentation class entry
rExport.AddAttribute(XML_NAMESPACE_PRESENTATION, sXML_class, rClass);
if( xPropSet.is() )
{
uno::Reference< beans::XPropertySetInfo > xPropSetInfo( xPropSet->getPropertySetInfo() );
sal_Bool bTemp;
// is empty pes shape?
if( xPropSetInfo.is() && xPropSetInfo->hasPropertyByName(OUString(RTL_CONSTASCII_USTRINGPARAM("IsEmptyPresentationObject"))))
{
xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("IsEmptyPresentationObject"))) >>= bIsEmpty;
if( bIsEmpty )
rExport.AddAttribute(XML_NAMESPACE_PRESENTATION, sXML_placeholder, OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_true)));
}
// is user-transformed?
if( xPropSetInfo.is() && xPropSetInfo->hasPropertyByName(OUString(RTL_CONSTASCII_USTRINGPARAM("IsPlaceholderDependent"))))
{
xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("IsPlaceholderDependent"))) >>= bTemp;
if(!bTemp)
rExport.AddAttribute(XML_NAMESPACE_PRESENTATION, sXML_user_transformed, OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_true)));
}
}
return bIsEmpty;
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportText( const uno::Reference< drawing::XShape >& xShape )
{
uno::Reference< text::XText > xText( xShape, uno::UNO_QUERY );
if( xText.is() && xText->getString().getLength() )
rExport.GetTextParagraphExport()->exportText( xText );
}
//////////////////////////////////////////////////////////////////////////////
#ifndef _COM_SUN_STAR_PRESENTATION_CLICKACTION_HPP_
#include <com/sun/star/presentation/ClickAction.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONSPEED_HPP_
#include <com/sun/star/presentation/AnimationSpeed.hpp>
#endif
#define FOUND_CLICKACTION 0x0001
#define FOUND_BOOKMARK 0x0002
#define FOUND_EFFECT 0x0004
#define FOUND_PLAYFULL 0x0008
#define FOUND_VERB 0x0010
#define FOUND_SOUNDURL 0x0020
#define FOUND_SPEED 0x0040
#define FOUND_EVENTTYPE 0x0080
#define FOUND_MACRO 0x0100
#define FOUND_LIBRARY 0x0200
void XMLShapeExport::ImpExportEvents( const uno::Reference< drawing::XShape >& xShape )
{
do
{
uno::Reference< document::XEventsSupplier > xEventsSupplier( xShape, uno::UNO_QUERY );
if( !xEventsSupplier.is() )
break;
uno::Reference< container::XNameReplace > xEvents( xEventsSupplier->getEvents() );
DBG_ASSERT( xEvents.is(), "XEventsSupplier::getEvents() returned NULL" );
if( !xEvents.is() )
break;
uno::Sequence< beans::PropertyValue > aProperties;
if( !xEvents->hasByName( msOnClick ) )
break;
if( !(xEvents->getByName( msOnClick ) >>= aProperties) )
break;
sal_Int32 nFound = 0;
const beans::PropertyValue* pProperties = aProperties.getConstArray();
OUString aStrEventType;
presentation::ClickAction eClickAction;
presentation::AnimationEffect eEffect;
presentation::AnimationSpeed eSpeed;
OUString aStrSoundURL;
sal_Bool bPlayFull;
sal_Int32 nVerb;
OUString aStrMacro;
OUString aStrLibrary;
OUString aStrBookmark;
const sal_Int32 nCount = aProperties.getLength();
sal_Int32 nIndex;
for( nIndex = 0; nIndex < nCount; nIndex++, pProperties++ )
{
if( ( ( nFound & FOUND_EVENTTYPE ) == 0 ) && pProperties->Name == msEventType )
{
if( pProperties->Value >>= aStrEventType )
nFound |= FOUND_EVENTTYPE;
}
else if( ( ( nFound & FOUND_CLICKACTION ) == 0 ) && pProperties->Name == msClickAction )
{
if( pProperties->Value >>= eClickAction )
nFound |= FOUND_CLICKACTION;
}
else if( ( ( nFound & FOUND_MACRO ) == 0 ) && pProperties->Name == msMacroName )
{
if( pProperties->Value >>= aStrMacro )
nFound |= FOUND_MACRO;
}
else if( ( ( nFound & FOUND_LIBRARY ) == 0 ) && pProperties->Name == msLibrary )
{
if( pProperties->Value >>= aStrLibrary )
nFound |= FOUND_LIBRARY;
}
else if( ( ( nFound & FOUND_EFFECT ) == 0 ) && pProperties->Name == msEffect )
{
if( pProperties->Value >>= eEffect )
nFound |= FOUND_EFFECT;
}
else if( ( ( nFound & FOUND_BOOKMARK ) == 0 ) && pProperties->Name == msBookmark )
{
if( pProperties->Value >>= aStrBookmark )
nFound |= FOUND_BOOKMARK;
}
else if( ( ( nFound & FOUND_SPEED ) == 0 ) && pProperties->Name == msSpeed )
{
if( pProperties->Value >>= eSpeed )
nFound |= FOUND_SPEED;
}
else if( ( ( nFound & FOUND_SOUNDURL ) == 0 ) && pProperties->Name == msSoundURL )
{
if( pProperties->Value >>= aStrSoundURL )
nFound |= FOUND_SOUNDURL;
}
else if( ( ( nFound & FOUND_PLAYFULL ) == 0 ) && pProperties->Name == msPlayFull )
{
if( pProperties->Value >>= bPlayFull )
nFound |= FOUND_PLAYFULL;
}
else if( ( ( nFound & FOUND_VERB ) == 0 ) && pProperties->Name == msVerb )
{
if( pProperties->Value >>= nVerb )
nFound |= FOUND_VERB;
}
}
if( ( nFound & FOUND_EVENTTYPE ) == 0 )
break;
if( aStrEventType == msPresentation )
{
if( ( nFound & FOUND_CLICKACTION ) == 0 )
break;
if( eClickAction == presentation::ClickAction_NONE )
break;
SvXMLElementExport aEventsElemt(rExport, XML_NAMESPACE_OFFICE, sXML_events, sal_True, sal_True);
OUString aStrAction;
switch( eClickAction )
{
case presentation::ClickAction_PREVPAGE: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_previous_page ) ); break;
case presentation::ClickAction_NEXTPAGE: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_next_page ) ); break;
case presentation::ClickAction_FIRSTPAGE: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_first_page ) ); break;
case presentation::ClickAction_LASTPAGE: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_last_page ) ); break;
case presentation::ClickAction_INVISIBLE: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_hide ) ); break;
case presentation::ClickAction_STOPPRESENTATION:aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_stop ) ); break;
case presentation::ClickAction_PROGRAM: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_execute ) ); break;
case presentation::ClickAction_BOOKMARK: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_show ) ); break;
case presentation::ClickAction_DOCUMENT: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_show ) ); break;
case presentation::ClickAction_MACRO: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_execute_macro ) ); break;
case presentation::ClickAction_VERB: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_verb ) ); break;
case presentation::ClickAction_VANISH: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_fade_out ) ); break;
case presentation::ClickAction_SOUND: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_sound ) ); break;
default:
DBG_ERROR( "unknown presentation::ClickAction found!" );
}
rExport.AddAttribute( XML_NAMESPACE_SCRIPT, sXML_event_name, OUString( RTL_CONSTASCII_USTRINGPARAM( "on-click" ) ) );
rExport.AddAttribute( XML_NAMESPACE_PRESENTATION, sXML_action, aStrAction );
if( eClickAction == presentation::ClickAction_VANISH )
{
if( nFound & FOUND_EFFECT )
{
XMLEffect eKind;
XMLEffectDirection eDirection;
sal_Int16 nStartScale;
sal_Bool bIn;
SdXMLImplSetEffect( eEffect, eKind, eDirection, nStartScale, bIn );
if( eEffect != EK_none )
{
SvXMLUnitConverter::convertEnum( msBuffer, eKind, aXML_AnimationEffect_EnumMap );
rExport.AddAttribute( XML_NAMESPACE_PRESENTATION, sXML_effect, msBuffer.makeStringAndClear() );
}
if( eDirection != ED_none )
{
SvXMLUnitConverter::convertEnum( msBuffer, eDirection, aXML_AnimationDirection_EnumMap );
rExport.AddAttribute( XML_NAMESPACE_PRESENTATION, sXML_direction, msBuffer.makeStringAndClear() );
}
if( nStartScale != -1 )
{
SvXMLUnitConverter::convertPercent( msBuffer, nStartScale );
rExport.AddAttribute( XML_NAMESPACE_PRESENTATION, sXML_start_scale, msBuffer.makeStringAndClear() );
}
}
if( nFound & FOUND_SPEED && eEffect != presentation::AnimationEffect_NONE )
{
if( eSpeed != presentation::AnimationSpeed_MEDIUM )
{
SvXMLUnitConverter::convertEnum( msBuffer, eSpeed, aXML_AnimationSpeed_EnumMap );
rExport.AddAttribute( XML_NAMESPACE_PRESENTATION, sXML_speed, msBuffer.makeStringAndClear() );
}
}
}
if( eClickAction == presentation::ClickAction_PROGRAM ||
eClickAction == presentation::ClickAction_BOOKMARK ||
eClickAction == presentation::ClickAction_DOCUMENT )
{
if( eClickAction == presentation::ClickAction_BOOKMARK )
msBuffer.append( sal_Unicode('#') );
msBuffer.append( aStrBookmark );
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_href, msBuffer.makeStringAndClear() );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_type, sXML_simple );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_show, sXML_new );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_actuate, sXML_onRequest );
}
if( ( nFound & FOUND_VERB ) && eClickAction == presentation::ClickAction_VERB )
{
msBuffer.append( nVerb );
rExport.AddAttribute(XML_NAMESPACE_PRESENTATION, sXML_verb, msBuffer.makeStringAndClear());
}
SvXMLElementExport aEventElemt(rExport, XML_NAMESPACE_PRESENTATION, sXML_event, sal_True, sal_True);
if( eClickAction == presentation::ClickAction_VANISH || eClickAction == presentation::ClickAction_SOUND )
{
if( ( nFound & FOUND_SOUNDURL ) && aStrSoundURL.getLength() != 0 )
{
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_href, aStrSoundURL );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_type, sXML_simple );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_show, sXML_new );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_actuate, sXML_onRequest );
if( nFound & FOUND_PLAYFULL && bPlayFull )
rExport.AddAttributeASCII( XML_NAMESPACE_PRESENTATION, sXML_play_full, sXML_true );
SvXMLElementExport aElem( rExport, XML_NAMESPACE_PRESENTATION, sXML_sound, sal_True, sal_True );
}
}
break;
}
else if( aStrEventType == msStarBasic )
{
if( nFound & FOUND_MACRO )
{
SvXMLElementExport aEventsElemt(rExport, XML_NAMESPACE_OFFICE, sXML_events, sal_True, sal_True);
rExport.AddAttribute( XML_NAMESPACE_SCRIPT, sXML_language, OUString( RTL_CONSTASCII_USTRINGPARAM( "starbasic" ) ) );
rExport.AddAttribute( XML_NAMESPACE_SCRIPT, sXML_event_name, OUString( RTL_CONSTASCII_USTRINGPARAM( "on-click" ) ) );
rExport.AddAttribute( XML_NAMESPACE_SCRIPT, sXML_macro_name, aStrMacro );
if( nFound & FOUND_LIBRARY )
rExport.AddAttribute( XML_NAMESPACE_SCRIPT, sXML_library, aStrLibrary );
SvXMLElementExport aEventElemt(rExport, XML_NAMESPACE_SCRIPT, sXML_event, sal_True, sal_True);
}
}
}
while(0);
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportGroupShape( const uno::Reference< drawing::XShape >& xShape, XmlShapeType eShapeType, sal_Int32 nFeatures, awt::Point* pRefPoint)
{
uno::Reference< drawing::XShapes > xShapes(xShape, uno::UNO_QUERY);
if(xShapes.is() && xShapes->getCount())
{
// write group shape
SvXMLElementExport aPGR(rExport, XML_NAMESPACE_DRAW, sXML_g, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
// write members
exportShapes( xShapes, nFeatures, pRefPoint );
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportTextBoxShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
uno::Reference< beans::XPropertySetInfo > xPropSetInfo( xPropSet->getPropertySetInfo() );
// presentation attribute (if presentation)
sal_Bool bIsPresShape(FALSE);
sal_Bool bIsEmptyPresObj(FALSE);
OUString aStr;
switch(eShapeType)
{
case XmlShapeTypePresSubtitleShape:
{
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_subtitle));
bIsPresShape = TRUE;
break;
}
case XmlShapeTypePresTitleTextShape:
{
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_title));
bIsPresShape = TRUE;
break;
}
case XmlShapeTypePresOutlinerShape:
{
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_outline));
bIsPresShape = TRUE;
break;
}
case XmlShapeTypePresNotesShape:
{
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_notes));
bIsPresShape = TRUE;
break;
}
}
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
if(bIsPresShape)
bIsEmptyPresObj = ImpExportPresentationAttributes( xPropSet, aStr );
// write text-box
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_text_box, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
if(!bIsEmptyPresObj)
ImpExportText( xShape );
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportRectangleShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, com::sun::star::awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
// evtl. corner radius?
sal_Int32 nCornerRadius(0L);
xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("CornerRadius"))) >>= nCornerRadius;
if(nCornerRadius)
{
OUStringBuffer sStringBuffer;
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, nCornerRadius);
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_corner_radius, sStringBuffer.makeStringAndClear());
}
// write rectangle
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_rect, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportLineShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
OUString aStr;
OUStringBuffer sStringBuffer;
awt::Point aStart(0,0);
awt::Point aEnd(1,1);
// #85920# use 'Geometry' to get the points of the line
// since this slot take anchor pos into account.
// get matrix
Matrix3D aMat;
ImpExportNewTrans_GetMatrix3D(aMat, xPropSet);
// decompose and correct about pRefPoint
Vector2D aTRScale;
double fTRShear(0.0);
double fTRRotate(0.0);
Vector2D aTRTranslate;
ImpExportNewTrans_DecomposeAndRefPoint(aMat, aTRScale, fTRShear, fTRRotate, aTRTranslate, pRefPoint);
// create base position
awt::Point aBasePosition(FRound(aTRTranslate.X()), FRound(aTRTranslate.Y()));
// get the two points
uno::Any aAny(xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("Geometry"))));
drawing::PointSequenceSequence* pSourcePolyPolygon = (drawing::PointSequenceSequence*)aAny.getValue();
if(pSourcePolyPolygon)
{
drawing::PointSequence* pOuterSequence = pSourcePolyPolygon->getArray();
if(pOuterSequence)
{
drawing::PointSequence* pInnerSequence = pOuterSequence++;
if(pInnerSequence)
{
awt::Point* pArray = pInnerSequence->getArray();
if(pArray)
{
if(pInnerSequence->getLength() > 0)
{
aStart = awt::Point(
pArray->X + aBasePosition.X,
pArray->Y + aBasePosition.Y);
pArray++;
}
if(pInnerSequence->getLength() > 1)
{
aEnd = awt::Point(
pArray->X + aBasePosition.X,
pArray->Y + aBasePosition.Y);
}
}
}
}
}
if( nFeatures & SEF_EXPORT_X )
{
// svg: x1
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aStart.X);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_x1, aStr);
}
else
{
aEnd.X -= aStart.X;
}
if( nFeatures & SEF_EXPORT_Y )
{
// svg: y1
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aStart.Y);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_y1, aStr);
}
else
{
aEnd.Y -= aStart.Y;
}
// svg: x2
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aEnd.X);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_x2, aStr);
// svg: y2
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aEnd.Y);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_y2, aStr);
// write line
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_line, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportEllipseShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
// get size to decide between Circle and Ellipse
awt::Size aSize = xShape->getSize();
sal_Int32 nRx((aSize.Width + 1) / 2);
sal_Int32 nRy((aSize.Height + 1) / 2);
BOOL bCircle(nRx == nRy);
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
drawing::CircleKind eKind = drawing::CircleKind_FULL;
xPropSet->getPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("CircleKind")) ) >>= eKind;
if( eKind != drawing::CircleKind_FULL )
{
OUStringBuffer sStringBuffer;
sal_Int32 nStartAngle;
sal_Int32 nEndAngle;
xPropSet->getPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("CircleStartAngle")) ) >>= nStartAngle;
xPropSet->getPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("CircleEndAngle")) ) >>= nEndAngle;
const double dStartAngle = nStartAngle / 100.0;
const double dEndAngle = nEndAngle / 100.0;
// export circle kind
SvXMLUnitConverter::convertEnum( sStringBuffer, (USHORT)eKind, aXML_CircleKind_EnumMap );
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_kind, sStringBuffer.makeStringAndClear() );
// export start angle
SvXMLUnitConverter::convertDouble( sStringBuffer, dStartAngle );
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_start_angle, sStringBuffer.makeStringAndClear() );
// export end angle
SvXMLUnitConverter::convertDouble( sStringBuffer, dEndAngle );
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_end_angle, sStringBuffer.makeStringAndClear() );
}
if(bCircle)
{
// write circle
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_circle, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
else
{
// write ellipse
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_ellipse, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportPolygonShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
BOOL bClosed(eShapeType == XmlShapeTypeDrawPolyPolygonShape
|| eShapeType == XmlShapeTypeDrawClosedBezierShape);
BOOL bBezier(eShapeType == XmlShapeTypeDrawClosedBezierShape
|| eShapeType == XmlShapeTypeDrawOpenBezierShape);
// get matrix
Matrix3D aMat;
ImpExportNewTrans_GetMatrix3D(aMat, xPropSet);
// decompose and correct abour pRefPoint
Vector2D aTRScale;
double fTRShear(0.0);
double fTRRotate(0.0);
Vector2D aTRTranslate;
ImpExportNewTrans_DecomposeAndRefPoint(aMat, aTRScale, fTRShear, fTRRotate, aTRTranslate, pRefPoint);
// use features and write
ImpExportNewTrans_FeaturesAndWrite(aTRScale, fTRShear, fTRRotate, aTRTranslate, nFeatures);
// create and export ViewBox
awt::Point aPoint(0, 0);
awt::Size aSize(FRound(aTRScale.X()), FRound(aTRScale.Y()));
SdXMLImExViewBox aViewBox(0, 0, aSize.Width, aSize.Height);
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_viewBox, aViewBox.GetExportString(rExport.GetMM100UnitConverter()));
if(bBezier)
{
// get PolygonBezier
uno::Any aAny( xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("Geometry"))) );
drawing::PolyPolygonBezierCoords* pSourcePolyPolygon =
(drawing::PolyPolygonBezierCoords*)aAny.getValue();
if(pSourcePolyPolygon && pSourcePolyPolygon->Coordinates.getLength())
{
sal_Int32 nOuterCnt(pSourcePolyPolygon->Coordinates.getLength());
drawing::PointSequence* pOuterSequence = pSourcePolyPolygon->Coordinates.getArray();
drawing::FlagSequence* pOuterFlags = pSourcePolyPolygon->Flags.getArray();
if(pOuterSequence && pOuterFlags)
{
// prepare svx:d element export
SdXMLImExSvgDElement aSvgDElement(aViewBox);
for(sal_Int32 a(0L); a < nOuterCnt; a++)
{
drawing::PointSequence* pSequence = pOuterSequence++;
drawing::FlagSequence* pFlags = pOuterFlags++;
if(pSequence && pFlags)
{
aSvgDElement.AddPolygon(pSequence, pFlags,
aPoint, aSize, rExport.GetMM100UnitConverter(), bClosed);
}
}
// write point array
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_d, aSvgDElement.GetExportString());
}
// write object now
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_path, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
}
else
{
// get non-bezier polygon
uno::Any aAny( xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("Geometry"))) );
drawing::PointSequenceSequence* pSourcePolyPolygon = (drawing::PointSequenceSequence*)aAny.getValue();
if(pSourcePolyPolygon && pSourcePolyPolygon->getLength())
{
sal_Int32 nOuterCnt(pSourcePolyPolygon->getLength());
if(1L == nOuterCnt && !bBezier)
{
// simple polygon shape, can be written as svg:points sequence
drawing::PointSequence* pSequence = pSourcePolyPolygon->getArray();
if(pSequence)
{
SdXMLImExPointsElement aPoints(pSequence, aViewBox, aPoint, aSize, rExport.GetMM100UnitConverter());
// write point array
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_points, aPoints.GetExportString());
}
// write object now
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW,
bClosed ? sXML_polygon : sXML_polyline , sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
else
{
// polypolygon or bezier, needs to be written as a svg:path sequence
drawing::PointSequence* pOuterSequence = pSourcePolyPolygon->getArray();
if(pOuterSequence)
{
// prepare svx:d element export
SdXMLImExSvgDElement aSvgDElement(aViewBox);
for(sal_Int32 a(0L); a < nOuterCnt; a++)
{
drawing::PointSequence* pSequence = pOuterSequence++;
if(pSequence)
{
aSvgDElement.AddPolygon(pSequence, 0L, aPoint,
aSize, rExport.GetMM100UnitConverter(), bClosed);
}
}
// write point array
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_d, aSvgDElement.GetExportString());
}
// write object now
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_path, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportGraphicObjectShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
sal_Bool bIsEmptyPresObj = sal_False;
uno::Reference< beans::XPropertySetInfo > xPropSetInfo( xPropSet->getPropertySetInfo() );
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
if(eShapeType == XmlShapeTypePresGraphicObjectShape)
bIsEmptyPresObj = ImpExportPresentationAttributes( xPropSet, OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_graphic)) );
if( !bIsEmptyPresObj )
{
OUString aStreamURL;
OUString aStr;
xPropSet->getPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("GraphicURL"))) >>= aStr;
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_href, aStr = rExport.AddEmbeddedGraphicObject( aStr ) );
if( aStr.getLength() && aStr[ 0 ] == '#' )
{
aStreamURL = OUString::createFromAscii( "vnd.sun.star.Package:" );
aStreamURL = aStreamURL.concat( aStr.copy( 1, aStr.getLength() - 1 ) );
}
// update stream URL for load on demand
uno::Any aAny;
aAny <<= aStreamURL;
xPropSet->setPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("GraphicStreamURL")), aAny );
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_simple));
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_type, aStr );
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_embed));
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_show, aStr );
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_onLoad));
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_actuate, aStr );
}
// write graphic object
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_image, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
// image map
GetExport().GetImageMapExport().Export( xPropSet );
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportChartShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, awt::Point* pRefPoint)
{
ImpExportOLE2Shape( xShape, eShapeType, nFeatures, pRefPoint );
/*
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
uno::Reference< chart::XChartDocument > xChartDoc;
if( !bIsEmptyPresObj )
xPropSet->getPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("Model") ) ) >>= xChartDoc;
if( xChartDoc.is() )
{
// export chart data if the flag is not set (default)
sal_Bool bExportOwnData = ( nFeatures & SEF_EXPORT_NO_CHART_DATA ) == 0;
rExport.GetChartExport()->exportChart( xChartDoc, bExportOwnData );
}
else
{
// write chart object (fake for now, replace later)
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_CHART, sXML_chart, sal_True, sal_True);
}
}
*/
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportSpreadsheetShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures /* = SEF_DEFAULT */, awt::Point* pRefPoint /* = NULL */)
{
ImpExportOLE2Shape( xShape, eShapeType, nFeatures, pRefPoint );
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportControlShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
}
uno::Reference< drawing::XControlShape > xControl( xShape, uno::UNO_QUERY );
DBG_ASSERT( xControl.is(), "Control shape is not supporting XControlShape" );
if( xControl.is() )
{
uno::Reference< beans::XPropertySet > xControlModel( xControl->getControl(), uno::UNO_QUERY );
DBG_ASSERT( xControlModel.is(), "Control shape has not XControlModel" );
if( xControlModel.is() )
{
rExport.AddAttribute( XML_NAMESPACE_FORM, sXML_id, rExport.GetFormExport()->getControlId( xControlModel ) );
}
}
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_control, sal_True, sal_True);
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportConnectorShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures /* = SEF_DEFAULT */, awt::Point* pRefPoint /* = NULL */)
{
uno::Reference< beans::XPropertySet > xProps( xShape, uno::UNO_QUERY );
OUString aStr;
OUStringBuffer sStringBuffer;
// export connection kind
drawing::ConnectorType eType = drawing::ConnectorType_STANDARD;
uno::Any aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("EdgeKind")));
aAny >>= eType;
if( eType != drawing::ConnectorType_STANDARD )
{
SvXMLUnitConverter::convertEnum( sStringBuffer, (sal_uInt16)eType, aXML_ConnectionKind_EnumMap );
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_type, aStr);
}
// export line skew
sal_Int32 nDelta1 = 0, nDelta2 = 0, nDelta3 = 0;
aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("EdgeLine1Delta")));
aAny >>= nDelta1;
aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("EdgeLine2Delta")));
aAny >>= nDelta2;
aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("EdgeLine3Delta")));
aAny >>= nDelta3;
if( nDelta1 != 0 || nDelta2 != 0 || nDelta3 != 0 )
{
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, nDelta1);
if( nDelta2 != 0 || nDelta3 != 0 )
{
const char aSpace = ' ';
sStringBuffer.appendAscii( &aSpace, 1 );
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, nDelta2);
if( nDelta3 != 0 )
{
sStringBuffer.appendAscii( &aSpace, 1 );
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, nDelta3);
}
}
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_line_skew, aStr);
}
// export start and end point
awt::Point aStart(0,0);
awt::Point aEnd(1,1);
xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("StartPosition"))) >>= aStart;
xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("EndPosition"))) >>= aEnd;
if( pRefPoint )
{
aStart.X -= pRefPoint->X;
aStart.Y -= pRefPoint->Y;
aEnd.X -= pRefPoint->X;
aEnd.Y -= pRefPoint->Y;
}
if( nFeatures & SEF_EXPORT_X )
{
// svg: x1
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aStart.X);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_x1, aStr);
}
else
{
aEnd.X -= aStart.X;
}
if( nFeatures & SEF_EXPORT_Y )
{
// svg: y1
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aStart.Y);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_y1, aStr);
}
else
{
aEnd.Y -= aStart.Y;
}
// svg: x2
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aEnd.X);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_x2, aStr);
// svg: y2
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aEnd.Y);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_y2, aStr);
uno::Reference< drawing::XShape > xTempShape;
// export start connection
aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("StartShape") ) );
if( aAny >>= xTempShape )
{
sal_Int32 nShapeId = rExport.GetShapeExport()->getShapeId( xTempShape );
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_start_shape, OUString::valueOf( nShapeId ));
aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("StartGluePointIndex")) );
sal_Int32 nGluePointId;
if( aAny >>= nGluePointId )
{
if( nGluePointId != -1 )
{
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_start_glue_point, OUString::valueOf( nGluePointId ));
}
}
}
// export end connection
aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("EndShape")) );
if( aAny >>= xTempShape )
{
sal_Int32 nShapeId = rExport.GetShapeExport()->getShapeId( xTempShape );
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_end_shape, OUString::valueOf( nShapeId ));
aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("EndGluePointIndex")) );
sal_Int32 nGluePointId;
if( aAny >>= nGluePointId )
{
if( nGluePointId != -1 )
{
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_end_glue_point, OUString::valueOf( nGluePointId ));
}
}
}
// write connector shape. Add Export later.
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_connector, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportMeasureShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures /* = SEF_DEFAULT */, awt::Point* pRefPoint /* = NULL */)
{
uno::Reference< beans::XPropertySet > xProps( xShape, uno::UNO_QUERY );
OUString aStr;
OUStringBuffer sStringBuffer;
// export start and end point
awt::Point aStart(0,0);
awt::Point aEnd(1,1);
uno::Any aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("StartPosition")));
aAny >>= aStart;
aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("EndPosition")));
aAny >>= aEnd;
if( pRefPoint )
{
aStart.X -= pRefPoint->X;
aStart.Y -= pRefPoint->Y;
aEnd.X -= pRefPoint->X;
aEnd.Y -= pRefPoint->Y;
}
if( nFeatures & SEF_EXPORT_X )
{
// svg: x1
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aStart.X);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_x1, aStr);
}
else
{
aEnd.X -= aStart.X;
}
if( nFeatures & SEF_EXPORT_Y )
{
// svg: y1
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aStart.Y);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_y1, aStr);
}
else
{
aEnd.Y -= aStart.Y;
}
// svg: x2
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aEnd.X);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_x2, aStr);
// svg: y2
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aEnd.Y);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_y2, aStr);
// write measure shape
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_measure, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
uno::Reference< text::XText > xText( xShape, uno::UNO_QUERY );
if( xText.is() )
rExport.GetTextParagraphExport()->exportText( xText );
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportOLE2Shape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures /* = SEF_DEFAULT */, awt::Point* pRefPoint /* = NULL */)
{
uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
uno::Reference< container::XNamed > xNamed(xShape, uno::UNO_QUERY);
DBG_ASSERT( xPropSet.is() && xNamed.is(), "ole shape is not implementing needed interfaces");
if(xPropSet.is() && xNamed.is())
{
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
sal_Bool bIsEmptyPresObj = sal_False;
// presentation settings
if(eShapeType == XmlShapeTypePresOLE2Shape)
bIsEmptyPresObj = ImpExportPresentationAttributes( xPropSet, OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_object)));
else if(eShapeType == XmlShapeTypePresChartShape)
bIsEmptyPresObj = ImpExportPresentationAttributes( xPropSet, OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_chart)) );
else if(eShapeType == XmlShapeTypePresTableShape)
bIsEmptyPresObj = ImpExportPresentationAttributes( xPropSet, OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_table)) );
OUString sClassId;
if( !bIsEmptyPresObj )
{
// xlink:href
OUString sURL(RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.EmbeddedObject:" ));
sURL += xNamed->getName();
sal_Bool bInternal;
xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("IsInternal"))) >>= bInternal;
if( !bInternal )
xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("CLSID"))) >>= sClassId;
if( sClassId.getLength() )
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_class_id, sClassId );
sURL = rExport.AddEmbeddedObject( sURL );
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_href, sURL );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_type, sXML_simple );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_show, sXML_embed );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_actuate, sXML_onLoad );
}
const sal_Char *pElem = sClassId.getLength() ? sXML_object_ole : sXML_object;
SvXMLElementExport aElem( rExport, XML_NAMESPACE_DRAW, pElem, sal_False, sal_True );
// see if we need to export a thumbnail bitmap
OUString aStr;
xPropSet->getPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("ThumbnailGraphicURL")) ) >>= aStr;
if( aStr.getLength() )
{
aStr = rExport.AddEmbeddedGraphicObject( aStr );
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_href, aStr );
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_simple));
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_type, aStr );
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_embed));
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_show, aStr );
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_onLoad));
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_actuate, aStr );
SvXMLElementExport aElem( rExport, XML_NAMESPACE_DRAW, sXML_thumbnail, sal_True, sal_True );
}
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportPageShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures /* = SEF_DEFAULT */, awt::Point* pRefPoint /* = NULL */)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
// #86163# Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
// export page number used for this page
uno::Reference< beans::XPropertySetInfo > xPropSetInfo( xPropSet->getPropertySetInfo() );
const OUString aPageNumberStr(RTL_CONSTASCII_USTRINGPARAM("PageNumber"));
if( xPropSetInfo.is() && xPropSetInfo->hasPropertyByName(aPageNumberStr))
{
sal_Int32 nPageNumber = 0;
xPropSet->getPropertyValue(aPageNumberStr) >>= nPageNumber;
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_page_number, OUString::valueOf(nPageNumber));
}
// a presentation page shape, normally used on notes pages only. If
// it is used not as presentation shape, it may have been created with
// copy-paste exchange between draw and impress (this IS possible...)
if(eShapeType == XmlShapeTypePresPageShape)
{
rExport.AddAttribute(XML_NAMESPACE_PRESENTATION, sXML_class,
OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_page)));
}
// write Page shape
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_page_thumbnail, sal_True, sal_True);
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportCaptionShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures /* = SEF_DEFAULT */, awt::Point* pRefPoint /* = NULL */)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
// evtl. corner radius?
sal_Int32 nCornerRadius(0L);
xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("CornerRadius"))) >>= nCornerRadius;
if(nCornerRadius)
{
OUStringBuffer sStringBuffer;
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, nCornerRadius);
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_corner_radius, sStringBuffer.makeStringAndClear());
}
awt::Point aCaptionPoint;
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "CaptionPoint" ) ) ) >>= aCaptionPoint;
// #88491# correct CaptionPoint position about pRefPoint
if(pRefPoint)
{
aCaptionPoint.X = aCaptionPoint.X - pRefPoint->X;
aCaptionPoint.Y = aCaptionPoint.Y - pRefPoint->Y;
}
rExport.GetMM100UnitConverter().convertMeasure(msBuffer, aCaptionPoint.X);
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_caption_point_x, msBuffer.makeStringAndClear() );
rExport.GetMM100UnitConverter().convertMeasure(msBuffer, aCaptionPoint.Y);
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_caption_point_y, msBuffer.makeStringAndClear() );
// write Caption shape. Add export later.
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_caption, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportFrameShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, com::sun::star::awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
// export frame url
OUString aStr;
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "FrameURL" ) ) ) >>= aStr;
rExport.AddAttribute ( XML_NAMESPACE_XLINK, sXML_href, aStr );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_type, sXML_simple );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_show, sXML_embed );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_actuate, sXML_onLoad );
// export name
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "FrameName" ) ) ) >>= aStr;
if( aStr.getLength() )
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_frame_name, aStr );
// write floating frame
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_floating_frame, sal_True, sal_True);
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportAppletShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, com::sun::star::awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
// export frame url
OUString aStr;
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "AppletCodeBase" ) ) ) >>= aStr;
rExport.AddAttribute ( XML_NAMESPACE_XLINK, sXML_href, aStr );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_type, sXML_simple );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_show, sXML_embed );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_actuate, sXML_onLoad );
// export draw:applet-name
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "AppletName" ) ) ) >>= aStr;
if( aStr.getLength() )
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_applet_name, aStr );
// export draw:code
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "AppletCode" ) ) ) >>= aStr;
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_code, aStr );
// export draw:may-script
sal_Bool bIsScript;
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "AppletIsScript" ) ) ) >>= bIsScript;
rExport.AddAttributeASCII( XML_NAMESPACE_DRAW, sXML_may_script, bIsScript ? sXML_true : sXML_false );
// write applet
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_applet, sal_True, sal_True);
// export parameters
uno::Sequence< beans::PropertyValue > aCommands;
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "AppletCommands" ) ) ) >>= aCommands;
const sal_Int32 nCount = aCommands.getLength();
for( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++ )
{
aCommands[nIndex].Value >>= aStr;
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_name, aCommands[nIndex].Name );
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_value, aStr );
SvXMLElementExport aElem( rExport, XML_NAMESPACE_DRAW, sXML_param, sal_False, sal_True );
}
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportPluginShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, com::sun::star::awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
// export plugin url
OUString aStr;
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "PluginURL" ) ) ) >>= aStr;
rExport.AddAttribute ( XML_NAMESPACE_XLINK, sXML_href, aStr );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_type, sXML_simple );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_show, sXML_embed );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_actuate, sXML_onLoad );
// export mime-type
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "PluginMimeType" ) ) ) >>= aStr;
if(aStr.getLength())
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_mime_type, aStr );
// write plugin
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_plugin, sal_True, sal_True);
// export parameters
uno::Sequence< beans::PropertyValue > aCommands;
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "PluginCommands" ) ) ) >>= aCommands;
const sal_Int32 nCount = aCommands.getLength();
for( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++ )
{
aCommands[nIndex].Value >>= aStr;
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_name, aCommands[nIndex].Name );
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_value, aStr );
SvXMLElementExport aElem( rExport, XML_NAMESPACE_DRAW, sXML_param, sal_False, sal_True );
}
}
}
#88691# added relative urls
/*************************************************************************
*
* $RCSfile: shapeexport2.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: cl $ $Date: 2001-06-27 14:40:42 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART_XCHARTDOCUMENT_HPP_
#include <com/sun/star/chart/XChartDocument.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_CIRCLEKIND_HPP_
#include <com/sun/star/drawing/CircleKind.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_CONNECTORTYPE_HPP_
#include <com/sun/star/drawing/ConnectorType.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XCONTROLSHAPE_HPP_
#include <com/sun/star/drawing/XControlShape.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POLYPOLYGONBEZIERCOORDS_HPP_
#include <com/sun/star/drawing/PolyPolygonBezierCoords.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_
#include <com/sun/star/document/XEventsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_HOMOGENMATRIX3_HPP_
#include <com/sun/star/drawing/HomogenMatrix3.hpp>
#endif
#ifndef _XMLOFF_ANIM_HXX
#include "anim.hxx"
#endif
#ifndef _XMLOFF_SHAPEEXPORT_HXX
#include "shapeexport.hxx"
#endif
#ifndef _SDPROPLS_HXX
#include "sdpropls.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_XMLIMAGEMAPEXPORT_HXX_
#include "XMLImageMapExport.hxx"
#endif
#ifndef _XEXPTRANSFORM_HXX
#include "xexptran.hxx"
#endif
#ifndef _SV_SALBTYPE_HXX
#include <vcl/salbtype.hxx> // FRound
#endif
#include "xmlkywd.hxx"
#include "xmlnmspe.hxx"
using namespace ::rtl;
using namespace ::com::sun::star;
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportNewTrans(const uno::Reference< beans::XPropertySet >& xPropSet,
sal_Int32 nFeatures, awt::Point* pRefPoint)
{
// get matrix
Matrix3D aMat;
ImpExportNewTrans_GetMatrix3D(aMat, xPropSet);
// decompose and correct abour pRefPoint
Vector2D aTRScale;
double fTRShear(0.0);
double fTRRotate(0.0);
Vector2D aTRTranslate;
ImpExportNewTrans_DecomposeAndRefPoint(aMat, aTRScale, fTRShear, fTRRotate, aTRTranslate, pRefPoint);
// use features and write
ImpExportNewTrans_FeaturesAndWrite(aTRScale, fTRShear, fTRRotate, aTRTranslate, nFeatures);
}
void XMLShapeExport::ImpExportNewTrans_GetMatrix3D(Matrix3D& rMat,
const uno::Reference< beans::XPropertySet >& xPropSet)
{
uno::Any aAny = xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("Transformation")));
drawing::HomogenMatrix3 aMatrix;
aAny >>= aMatrix;
rMat[0] = Point3D( aMatrix.Line1.Column1, aMatrix.Line1.Column2, aMatrix.Line1.Column3 );
rMat[1] = Point3D( aMatrix.Line2.Column1, aMatrix.Line2.Column2, aMatrix.Line2.Column3 );
rMat[2] = Point3D( aMatrix.Line3.Column1, aMatrix.Line3.Column2, aMatrix.Line3.Column3 );
}
void XMLShapeExport::ImpExportNewTrans_DecomposeAndRefPoint(const Matrix3D& rMat,
Vector2D& rTRScale, double& fTRShear, double& fTRRotate, Vector2D& rTRTranslate,
awt::Point* pRefPoint)
{
// decompose matrix
rMat.DecomposeAndCorrect(rTRScale, fTRShear, fTRRotate, rTRTranslate);
// correct translation about pRefPoint
if(pRefPoint)
{
rTRTranslate.X() -= pRefPoint->X;
rTRTranslate.Y() -= pRefPoint->Y;
}
}
void XMLShapeExport::ImpExportNewTrans_FeaturesAndWrite(Vector2D& rTRScale, double fTRShear,
double fTRRotate, Vector2D& rTRTranslate, const sal_Int32 nFeatures)
{
// allways write Size (rTRScale) since this statement carries the union
// of the object
OUString aStr;
OUStringBuffer sStringBuffer;
Vector2D aTRScale = rTRScale;
// svg: width
if(!(nFeatures & SEF_EXPORT_WIDTH))
aTRScale.X() = 1.0;
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, FRound(aTRScale.X()));
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_width, aStr);
// svg: height
if(!(nFeatures & SEF_EXPORT_HEIGHT))
aTRScale.Y() = 1.0;
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, FRound(aTRScale.Y()));
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_height, aStr);
// decide if transformation is neccessary
BOOL bTransformationIsNeccessary(fTRShear != 0.0 || fTRRotate != 0.0);
if(bTransformationIsNeccessary)
{
// write transformation, but WITHOUT scale which is exported as size above
SdXMLImExTransform2D aTransform;
aTransform.AddSkewX(atan(fTRShear));
aTransform.AddRotate(fTRRotate);
aTransform.AddTranslate(rTRTranslate);
// does transformation need to be exported?
if(aTransform.NeedsAction())
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_transform, aTransform.GetExportString(rExport.GetMM100UnitConverter()));
}
else
{
// no shear, no rotate; just add object position to export and we are done
if(nFeatures & SEF_EXPORT_X)
{
// svg: x
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, FRound(rTRTranslate.X()));
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_x, aStr);
}
if(nFeatures & SEF_EXPORT_Y)
{
// svg: y
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, FRound(rTRTranslate.Y()));
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_y, aStr);
}
}
}
//////////////////////////////////////////////////////////////////////////////
sal_Bool XMLShapeExport::ImpExportPresentationAttributes( const uno::Reference< beans::XPropertySet >& xPropSet, const rtl::OUString& rClass )
{
sal_Bool bIsEmpty = sal_False;
OUStringBuffer sStringBuffer;
// write presentation class entry
rExport.AddAttribute(XML_NAMESPACE_PRESENTATION, sXML_class, rClass);
if( xPropSet.is() )
{
uno::Reference< beans::XPropertySetInfo > xPropSetInfo( xPropSet->getPropertySetInfo() );
sal_Bool bTemp;
// is empty pes shape?
if( xPropSetInfo.is() && xPropSetInfo->hasPropertyByName(OUString(RTL_CONSTASCII_USTRINGPARAM("IsEmptyPresentationObject"))))
{
xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("IsEmptyPresentationObject"))) >>= bIsEmpty;
if( bIsEmpty )
rExport.AddAttribute(XML_NAMESPACE_PRESENTATION, sXML_placeholder, OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_true)));
}
// is user-transformed?
if( xPropSetInfo.is() && xPropSetInfo->hasPropertyByName(OUString(RTL_CONSTASCII_USTRINGPARAM("IsPlaceholderDependent"))))
{
xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("IsPlaceholderDependent"))) >>= bTemp;
if(!bTemp)
rExport.AddAttribute(XML_NAMESPACE_PRESENTATION, sXML_user_transformed, OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_true)));
}
}
return bIsEmpty;
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportText( const uno::Reference< drawing::XShape >& xShape )
{
uno::Reference< text::XText > xText( xShape, uno::UNO_QUERY );
if( xText.is() && xText->getString().getLength() )
rExport.GetTextParagraphExport()->exportText( xText );
}
//////////////////////////////////////////////////////////////////////////////
#ifndef _COM_SUN_STAR_PRESENTATION_CLICKACTION_HPP_
#include <com/sun/star/presentation/ClickAction.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONSPEED_HPP_
#include <com/sun/star/presentation/AnimationSpeed.hpp>
#endif
#define FOUND_CLICKACTION 0x0001
#define FOUND_BOOKMARK 0x0002
#define FOUND_EFFECT 0x0004
#define FOUND_PLAYFULL 0x0008
#define FOUND_VERB 0x0010
#define FOUND_SOUNDURL 0x0020
#define FOUND_SPEED 0x0040
#define FOUND_EVENTTYPE 0x0080
#define FOUND_MACRO 0x0100
#define FOUND_LIBRARY 0x0200
void XMLShapeExport::ImpExportEvents( const uno::Reference< drawing::XShape >& xShape )
{
do
{
uno::Reference< document::XEventsSupplier > xEventsSupplier( xShape, uno::UNO_QUERY );
if( !xEventsSupplier.is() )
break;
uno::Reference< container::XNameReplace > xEvents( xEventsSupplier->getEvents() );
DBG_ASSERT( xEvents.is(), "XEventsSupplier::getEvents() returned NULL" );
if( !xEvents.is() )
break;
uno::Sequence< beans::PropertyValue > aProperties;
if( !xEvents->hasByName( msOnClick ) )
break;
if( !(xEvents->getByName( msOnClick ) >>= aProperties) )
break;
sal_Int32 nFound = 0;
const beans::PropertyValue* pProperties = aProperties.getConstArray();
OUString aStrEventType;
presentation::ClickAction eClickAction;
presentation::AnimationEffect eEffect;
presentation::AnimationSpeed eSpeed;
OUString aStrSoundURL;
sal_Bool bPlayFull;
sal_Int32 nVerb;
OUString aStrMacro;
OUString aStrLibrary;
OUString aStrBookmark;
const sal_Int32 nCount = aProperties.getLength();
sal_Int32 nIndex;
for( nIndex = 0; nIndex < nCount; nIndex++, pProperties++ )
{
if( ( ( nFound & FOUND_EVENTTYPE ) == 0 ) && pProperties->Name == msEventType )
{
if( pProperties->Value >>= aStrEventType )
nFound |= FOUND_EVENTTYPE;
}
else if( ( ( nFound & FOUND_CLICKACTION ) == 0 ) && pProperties->Name == msClickAction )
{
if( pProperties->Value >>= eClickAction )
nFound |= FOUND_CLICKACTION;
}
else if( ( ( nFound & FOUND_MACRO ) == 0 ) && pProperties->Name == msMacroName )
{
if( pProperties->Value >>= aStrMacro )
nFound |= FOUND_MACRO;
}
else if( ( ( nFound & FOUND_LIBRARY ) == 0 ) && pProperties->Name == msLibrary )
{
if( pProperties->Value >>= aStrLibrary )
nFound |= FOUND_LIBRARY;
}
else if( ( ( nFound & FOUND_EFFECT ) == 0 ) && pProperties->Name == msEffect )
{
if( pProperties->Value >>= eEffect )
nFound |= FOUND_EFFECT;
}
else if( ( ( nFound & FOUND_BOOKMARK ) == 0 ) && pProperties->Name == msBookmark )
{
if( pProperties->Value >>= aStrBookmark )
nFound |= FOUND_BOOKMARK;
}
else if( ( ( nFound & FOUND_SPEED ) == 0 ) && pProperties->Name == msSpeed )
{
if( pProperties->Value >>= eSpeed )
nFound |= FOUND_SPEED;
}
else if( ( ( nFound & FOUND_SOUNDURL ) == 0 ) && pProperties->Name == msSoundURL )
{
if( pProperties->Value >>= aStrSoundURL )
nFound |= FOUND_SOUNDURL;
}
else if( ( ( nFound & FOUND_PLAYFULL ) == 0 ) && pProperties->Name == msPlayFull )
{
if( pProperties->Value >>= bPlayFull )
nFound |= FOUND_PLAYFULL;
}
else if( ( ( nFound & FOUND_VERB ) == 0 ) && pProperties->Name == msVerb )
{
if( pProperties->Value >>= nVerb )
nFound |= FOUND_VERB;
}
}
if( ( nFound & FOUND_EVENTTYPE ) == 0 )
break;
if( aStrEventType == msPresentation )
{
if( ( nFound & FOUND_CLICKACTION ) == 0 )
break;
if( eClickAction == presentation::ClickAction_NONE )
break;
SvXMLElementExport aEventsElemt(rExport, XML_NAMESPACE_OFFICE, sXML_events, sal_True, sal_True);
OUString aStrAction;
switch( eClickAction )
{
case presentation::ClickAction_PREVPAGE: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_previous_page ) ); break;
case presentation::ClickAction_NEXTPAGE: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_next_page ) ); break;
case presentation::ClickAction_FIRSTPAGE: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_first_page ) ); break;
case presentation::ClickAction_LASTPAGE: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_last_page ) ); break;
case presentation::ClickAction_INVISIBLE: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_hide ) ); break;
case presentation::ClickAction_STOPPRESENTATION:aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_stop ) ); break;
case presentation::ClickAction_PROGRAM: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_execute ) ); break;
case presentation::ClickAction_BOOKMARK: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_show ) ); break;
case presentation::ClickAction_DOCUMENT: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_show ) ); break;
case presentation::ClickAction_MACRO: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_execute_macro ) ); break;
case presentation::ClickAction_VERB: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_verb ) ); break;
case presentation::ClickAction_VANISH: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_fade_out ) ); break;
case presentation::ClickAction_SOUND: aStrAction = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_sound ) ); break;
default:
DBG_ERROR( "unknown presentation::ClickAction found!" );
}
rExport.AddAttribute( XML_NAMESPACE_SCRIPT, sXML_event_name, OUString( RTL_CONSTASCII_USTRINGPARAM( "on-click" ) ) );
rExport.AddAttribute( XML_NAMESPACE_PRESENTATION, sXML_action, aStrAction );
if( eClickAction == presentation::ClickAction_VANISH )
{
if( nFound & FOUND_EFFECT )
{
XMLEffect eKind;
XMLEffectDirection eDirection;
sal_Int16 nStartScale;
sal_Bool bIn;
SdXMLImplSetEffect( eEffect, eKind, eDirection, nStartScale, bIn );
if( eEffect != EK_none )
{
SvXMLUnitConverter::convertEnum( msBuffer, eKind, aXML_AnimationEffect_EnumMap );
rExport.AddAttribute( XML_NAMESPACE_PRESENTATION, sXML_effect, msBuffer.makeStringAndClear() );
}
if( eDirection != ED_none )
{
SvXMLUnitConverter::convertEnum( msBuffer, eDirection, aXML_AnimationDirection_EnumMap );
rExport.AddAttribute( XML_NAMESPACE_PRESENTATION, sXML_direction, msBuffer.makeStringAndClear() );
}
if( nStartScale != -1 )
{
SvXMLUnitConverter::convertPercent( msBuffer, nStartScale );
rExport.AddAttribute( XML_NAMESPACE_PRESENTATION, sXML_start_scale, msBuffer.makeStringAndClear() );
}
}
if( nFound & FOUND_SPEED && eEffect != presentation::AnimationEffect_NONE )
{
if( eSpeed != presentation::AnimationSpeed_MEDIUM )
{
SvXMLUnitConverter::convertEnum( msBuffer, eSpeed, aXML_AnimationSpeed_EnumMap );
rExport.AddAttribute( XML_NAMESPACE_PRESENTATION, sXML_speed, msBuffer.makeStringAndClear() );
}
}
}
if( eClickAction == presentation::ClickAction_PROGRAM ||
eClickAction == presentation::ClickAction_BOOKMARK ||
eClickAction == presentation::ClickAction_DOCUMENT )
{
if( eClickAction == presentation::ClickAction_BOOKMARK )
msBuffer.append( sal_Unicode('#') );
msBuffer.append( aStrBookmark );
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_href, GetExport().GetRelativeReference(msBuffer.makeStringAndClear()) );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_type, sXML_simple );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_show, sXML_new );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_actuate, sXML_onRequest );
}
if( ( nFound & FOUND_VERB ) && eClickAction == presentation::ClickAction_VERB )
{
msBuffer.append( nVerb );
rExport.AddAttribute(XML_NAMESPACE_PRESENTATION, sXML_verb, msBuffer.makeStringAndClear());
}
SvXMLElementExport aEventElemt(rExport, XML_NAMESPACE_PRESENTATION, sXML_event, sal_True, sal_True);
if( eClickAction == presentation::ClickAction_VANISH || eClickAction == presentation::ClickAction_SOUND )
{
if( ( nFound & FOUND_SOUNDURL ) && aStrSoundURL.getLength() != 0 )
{
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_href, GetExport().GetRelativeReference(aStrSoundURL) );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_type, sXML_simple );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_show, sXML_new );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_actuate, sXML_onRequest );
if( nFound & FOUND_PLAYFULL && bPlayFull )
rExport.AddAttributeASCII( XML_NAMESPACE_PRESENTATION, sXML_play_full, sXML_true );
SvXMLElementExport aElem( rExport, XML_NAMESPACE_PRESENTATION, sXML_sound, sal_True, sal_True );
}
}
break;
}
else if( aStrEventType == msStarBasic )
{
if( nFound & FOUND_MACRO )
{
SvXMLElementExport aEventsElemt(rExport, XML_NAMESPACE_OFFICE, sXML_events, sal_True, sal_True);
rExport.AddAttribute( XML_NAMESPACE_SCRIPT, sXML_language, OUString( RTL_CONSTASCII_USTRINGPARAM( "starbasic" ) ) );
rExport.AddAttribute( XML_NAMESPACE_SCRIPT, sXML_event_name, OUString( RTL_CONSTASCII_USTRINGPARAM( "on-click" ) ) );
rExport.AddAttribute( XML_NAMESPACE_SCRIPT, sXML_macro_name, aStrMacro );
if( nFound & FOUND_LIBRARY )
rExport.AddAttribute( XML_NAMESPACE_SCRIPT, sXML_library, aStrLibrary );
SvXMLElementExport aEventElemt(rExport, XML_NAMESPACE_SCRIPT, sXML_event, sal_True, sal_True);
}
}
}
while(0);
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportGroupShape( const uno::Reference< drawing::XShape >& xShape, XmlShapeType eShapeType, sal_Int32 nFeatures, awt::Point* pRefPoint)
{
uno::Reference< drawing::XShapes > xShapes(xShape, uno::UNO_QUERY);
if(xShapes.is() && xShapes->getCount())
{
// write group shape
SvXMLElementExport aPGR(rExport, XML_NAMESPACE_DRAW, sXML_g, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
// write members
exportShapes( xShapes, nFeatures, pRefPoint );
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportTextBoxShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
uno::Reference< beans::XPropertySetInfo > xPropSetInfo( xPropSet->getPropertySetInfo() );
// presentation attribute (if presentation)
sal_Bool bIsPresShape(FALSE);
sal_Bool bIsEmptyPresObj(FALSE);
OUString aStr;
switch(eShapeType)
{
case XmlShapeTypePresSubtitleShape:
{
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_subtitle));
bIsPresShape = TRUE;
break;
}
case XmlShapeTypePresTitleTextShape:
{
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_title));
bIsPresShape = TRUE;
break;
}
case XmlShapeTypePresOutlinerShape:
{
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_outline));
bIsPresShape = TRUE;
break;
}
case XmlShapeTypePresNotesShape:
{
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_notes));
bIsPresShape = TRUE;
break;
}
}
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
if(bIsPresShape)
bIsEmptyPresObj = ImpExportPresentationAttributes( xPropSet, aStr );
// write text-box
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_text_box, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
if(!bIsEmptyPresObj)
ImpExportText( xShape );
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportRectangleShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, com::sun::star::awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
// evtl. corner radius?
sal_Int32 nCornerRadius(0L);
xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("CornerRadius"))) >>= nCornerRadius;
if(nCornerRadius)
{
OUStringBuffer sStringBuffer;
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, nCornerRadius);
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_corner_radius, sStringBuffer.makeStringAndClear());
}
// write rectangle
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_rect, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportLineShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
OUString aStr;
OUStringBuffer sStringBuffer;
awt::Point aStart(0,0);
awt::Point aEnd(1,1);
// #85920# use 'Geometry' to get the points of the line
// since this slot take anchor pos into account.
// get matrix
Matrix3D aMat;
ImpExportNewTrans_GetMatrix3D(aMat, xPropSet);
// decompose and correct about pRefPoint
Vector2D aTRScale;
double fTRShear(0.0);
double fTRRotate(0.0);
Vector2D aTRTranslate;
ImpExportNewTrans_DecomposeAndRefPoint(aMat, aTRScale, fTRShear, fTRRotate, aTRTranslate, pRefPoint);
// create base position
awt::Point aBasePosition(FRound(aTRTranslate.X()), FRound(aTRTranslate.Y()));
// get the two points
uno::Any aAny(xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("Geometry"))));
drawing::PointSequenceSequence* pSourcePolyPolygon = (drawing::PointSequenceSequence*)aAny.getValue();
if(pSourcePolyPolygon)
{
drawing::PointSequence* pOuterSequence = pSourcePolyPolygon->getArray();
if(pOuterSequence)
{
drawing::PointSequence* pInnerSequence = pOuterSequence++;
if(pInnerSequence)
{
awt::Point* pArray = pInnerSequence->getArray();
if(pArray)
{
if(pInnerSequence->getLength() > 0)
{
aStart = awt::Point(
pArray->X + aBasePosition.X,
pArray->Y + aBasePosition.Y);
pArray++;
}
if(pInnerSequence->getLength() > 1)
{
aEnd = awt::Point(
pArray->X + aBasePosition.X,
pArray->Y + aBasePosition.Y);
}
}
}
}
}
if( nFeatures & SEF_EXPORT_X )
{
// svg: x1
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aStart.X);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_x1, aStr);
}
else
{
aEnd.X -= aStart.X;
}
if( nFeatures & SEF_EXPORT_Y )
{
// svg: y1
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aStart.Y);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_y1, aStr);
}
else
{
aEnd.Y -= aStart.Y;
}
// svg: x2
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aEnd.X);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_x2, aStr);
// svg: y2
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aEnd.Y);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_y2, aStr);
// write line
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_line, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportEllipseShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
// get size to decide between Circle and Ellipse
awt::Size aSize = xShape->getSize();
sal_Int32 nRx((aSize.Width + 1) / 2);
sal_Int32 nRy((aSize.Height + 1) / 2);
BOOL bCircle(nRx == nRy);
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
drawing::CircleKind eKind = drawing::CircleKind_FULL;
xPropSet->getPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("CircleKind")) ) >>= eKind;
if( eKind != drawing::CircleKind_FULL )
{
OUStringBuffer sStringBuffer;
sal_Int32 nStartAngle;
sal_Int32 nEndAngle;
xPropSet->getPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("CircleStartAngle")) ) >>= nStartAngle;
xPropSet->getPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("CircleEndAngle")) ) >>= nEndAngle;
const double dStartAngle = nStartAngle / 100.0;
const double dEndAngle = nEndAngle / 100.0;
// export circle kind
SvXMLUnitConverter::convertEnum( sStringBuffer, (USHORT)eKind, aXML_CircleKind_EnumMap );
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_kind, sStringBuffer.makeStringAndClear() );
// export start angle
SvXMLUnitConverter::convertDouble( sStringBuffer, dStartAngle );
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_start_angle, sStringBuffer.makeStringAndClear() );
// export end angle
SvXMLUnitConverter::convertDouble( sStringBuffer, dEndAngle );
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_end_angle, sStringBuffer.makeStringAndClear() );
}
if(bCircle)
{
// write circle
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_circle, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
else
{
// write ellipse
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_ellipse, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportPolygonShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
BOOL bClosed(eShapeType == XmlShapeTypeDrawPolyPolygonShape
|| eShapeType == XmlShapeTypeDrawClosedBezierShape);
BOOL bBezier(eShapeType == XmlShapeTypeDrawClosedBezierShape
|| eShapeType == XmlShapeTypeDrawOpenBezierShape);
// get matrix
Matrix3D aMat;
ImpExportNewTrans_GetMatrix3D(aMat, xPropSet);
// decompose and correct abour pRefPoint
Vector2D aTRScale;
double fTRShear(0.0);
double fTRRotate(0.0);
Vector2D aTRTranslate;
ImpExportNewTrans_DecomposeAndRefPoint(aMat, aTRScale, fTRShear, fTRRotate, aTRTranslate, pRefPoint);
// use features and write
ImpExportNewTrans_FeaturesAndWrite(aTRScale, fTRShear, fTRRotate, aTRTranslate, nFeatures);
// create and export ViewBox
awt::Point aPoint(0, 0);
awt::Size aSize(FRound(aTRScale.X()), FRound(aTRScale.Y()));
SdXMLImExViewBox aViewBox(0, 0, aSize.Width, aSize.Height);
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_viewBox, aViewBox.GetExportString(rExport.GetMM100UnitConverter()));
if(bBezier)
{
// get PolygonBezier
uno::Any aAny( xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("Geometry"))) );
drawing::PolyPolygonBezierCoords* pSourcePolyPolygon =
(drawing::PolyPolygonBezierCoords*)aAny.getValue();
if(pSourcePolyPolygon && pSourcePolyPolygon->Coordinates.getLength())
{
sal_Int32 nOuterCnt(pSourcePolyPolygon->Coordinates.getLength());
drawing::PointSequence* pOuterSequence = pSourcePolyPolygon->Coordinates.getArray();
drawing::FlagSequence* pOuterFlags = pSourcePolyPolygon->Flags.getArray();
if(pOuterSequence && pOuterFlags)
{
// prepare svx:d element export
SdXMLImExSvgDElement aSvgDElement(aViewBox);
for(sal_Int32 a(0L); a < nOuterCnt; a++)
{
drawing::PointSequence* pSequence = pOuterSequence++;
drawing::FlagSequence* pFlags = pOuterFlags++;
if(pSequence && pFlags)
{
aSvgDElement.AddPolygon(pSequence, pFlags,
aPoint, aSize, rExport.GetMM100UnitConverter(), bClosed);
}
}
// write point array
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_d, aSvgDElement.GetExportString());
}
// write object now
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_path, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
}
else
{
// get non-bezier polygon
uno::Any aAny( xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("Geometry"))) );
drawing::PointSequenceSequence* pSourcePolyPolygon = (drawing::PointSequenceSequence*)aAny.getValue();
if(pSourcePolyPolygon && pSourcePolyPolygon->getLength())
{
sal_Int32 nOuterCnt(pSourcePolyPolygon->getLength());
if(1L == nOuterCnt && !bBezier)
{
// simple polygon shape, can be written as svg:points sequence
drawing::PointSequence* pSequence = pSourcePolyPolygon->getArray();
if(pSequence)
{
SdXMLImExPointsElement aPoints(pSequence, aViewBox, aPoint, aSize, rExport.GetMM100UnitConverter());
// write point array
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_points, aPoints.GetExportString());
}
// write object now
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW,
bClosed ? sXML_polygon : sXML_polyline , sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
else
{
// polypolygon or bezier, needs to be written as a svg:path sequence
drawing::PointSequence* pOuterSequence = pSourcePolyPolygon->getArray();
if(pOuterSequence)
{
// prepare svx:d element export
SdXMLImExSvgDElement aSvgDElement(aViewBox);
for(sal_Int32 a(0L); a < nOuterCnt; a++)
{
drawing::PointSequence* pSequence = pOuterSequence++;
if(pSequence)
{
aSvgDElement.AddPolygon(pSequence, 0L, aPoint,
aSize, rExport.GetMM100UnitConverter(), bClosed);
}
}
// write point array
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_d, aSvgDElement.GetExportString());
}
// write object now
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_path, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportGraphicObjectShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
sal_Bool bIsEmptyPresObj = sal_False;
uno::Reference< beans::XPropertySetInfo > xPropSetInfo( xPropSet->getPropertySetInfo() );
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
if(eShapeType == XmlShapeTypePresGraphicObjectShape)
bIsEmptyPresObj = ImpExportPresentationAttributes( xPropSet, OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_graphic)) );
if( !bIsEmptyPresObj )
{
OUString aStreamURL;
OUString aStr;
xPropSet->getPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("GraphicURL"))) >>= aStr;
aStr = GetExport().GetRelativeReference( rExport.AddEmbeddedGraphicObject( aStr ) );
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_href, aStr );
if( aStr.getLength() && aStr[ 0 ] == '#' )
{
aStreamURL = OUString::createFromAscii( "vnd.sun.star.Package:" );
aStreamURL = aStreamURL.concat( aStr.copy( 1, aStr.getLength() - 1 ) );
}
// update stream URL for load on demand
uno::Any aAny;
aAny <<= aStreamURL;
xPropSet->setPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("GraphicStreamURL")), aAny );
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_simple));
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_type, aStr );
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_embed));
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_show, aStr );
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_onLoad));
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_actuate, aStr );
}
// write graphic object
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_image, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
// image map
GetExport().GetImageMapExport().Export( xPropSet );
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportChartShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, awt::Point* pRefPoint)
{
ImpExportOLE2Shape( xShape, eShapeType, nFeatures, pRefPoint );
/*
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
uno::Reference< chart::XChartDocument > xChartDoc;
if( !bIsEmptyPresObj )
xPropSet->getPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("Model") ) ) >>= xChartDoc;
if( xChartDoc.is() )
{
// export chart data if the flag is not set (default)
sal_Bool bExportOwnData = ( nFeatures & SEF_EXPORT_NO_CHART_DATA ) == 0;
rExport.GetChartExport()->exportChart( xChartDoc, bExportOwnData );
}
else
{
// write chart object (fake for now, replace later)
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_CHART, sXML_chart, sal_True, sal_True);
}
}
*/
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportSpreadsheetShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures /* = SEF_DEFAULT */, awt::Point* pRefPoint /* = NULL */)
{
ImpExportOLE2Shape( xShape, eShapeType, nFeatures, pRefPoint );
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportControlShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
}
uno::Reference< drawing::XControlShape > xControl( xShape, uno::UNO_QUERY );
DBG_ASSERT( xControl.is(), "Control shape is not supporting XControlShape" );
if( xControl.is() )
{
uno::Reference< beans::XPropertySet > xControlModel( xControl->getControl(), uno::UNO_QUERY );
DBG_ASSERT( xControlModel.is(), "Control shape has not XControlModel" );
if( xControlModel.is() )
{
rExport.AddAttribute( XML_NAMESPACE_FORM, sXML_id, rExport.GetFormExport()->getControlId( xControlModel ) );
}
}
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_control, sal_True, sal_True);
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportConnectorShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures /* = SEF_DEFAULT */, awt::Point* pRefPoint /* = NULL */)
{
uno::Reference< beans::XPropertySet > xProps( xShape, uno::UNO_QUERY );
OUString aStr;
OUStringBuffer sStringBuffer;
// export connection kind
drawing::ConnectorType eType = drawing::ConnectorType_STANDARD;
uno::Any aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("EdgeKind")));
aAny >>= eType;
if( eType != drawing::ConnectorType_STANDARD )
{
SvXMLUnitConverter::convertEnum( sStringBuffer, (sal_uInt16)eType, aXML_ConnectionKind_EnumMap );
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_type, aStr);
}
// export line skew
sal_Int32 nDelta1 = 0, nDelta2 = 0, nDelta3 = 0;
aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("EdgeLine1Delta")));
aAny >>= nDelta1;
aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("EdgeLine2Delta")));
aAny >>= nDelta2;
aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("EdgeLine3Delta")));
aAny >>= nDelta3;
if( nDelta1 != 0 || nDelta2 != 0 || nDelta3 != 0 )
{
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, nDelta1);
if( nDelta2 != 0 || nDelta3 != 0 )
{
const char aSpace = ' ';
sStringBuffer.appendAscii( &aSpace, 1 );
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, nDelta2);
if( nDelta3 != 0 )
{
sStringBuffer.appendAscii( &aSpace, 1 );
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, nDelta3);
}
}
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_line_skew, aStr);
}
// export start and end point
awt::Point aStart(0,0);
awt::Point aEnd(1,1);
xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("StartPosition"))) >>= aStart;
xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("EndPosition"))) >>= aEnd;
if( pRefPoint )
{
aStart.X -= pRefPoint->X;
aStart.Y -= pRefPoint->Y;
aEnd.X -= pRefPoint->X;
aEnd.Y -= pRefPoint->Y;
}
if( nFeatures & SEF_EXPORT_X )
{
// svg: x1
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aStart.X);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_x1, aStr);
}
else
{
aEnd.X -= aStart.X;
}
if( nFeatures & SEF_EXPORT_Y )
{
// svg: y1
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aStart.Y);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_y1, aStr);
}
else
{
aEnd.Y -= aStart.Y;
}
// svg: x2
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aEnd.X);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_x2, aStr);
// svg: y2
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aEnd.Y);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_y2, aStr);
uno::Reference< drawing::XShape > xTempShape;
// export start connection
aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("StartShape") ) );
if( aAny >>= xTempShape )
{
sal_Int32 nShapeId = rExport.GetShapeExport()->getShapeId( xTempShape );
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_start_shape, OUString::valueOf( nShapeId ));
aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("StartGluePointIndex")) );
sal_Int32 nGluePointId;
if( aAny >>= nGluePointId )
{
if( nGluePointId != -1 )
{
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_start_glue_point, OUString::valueOf( nGluePointId ));
}
}
}
// export end connection
aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("EndShape")) );
if( aAny >>= xTempShape )
{
sal_Int32 nShapeId = rExport.GetShapeExport()->getShapeId( xTempShape );
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_end_shape, OUString::valueOf( nShapeId ));
aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("EndGluePointIndex")) );
sal_Int32 nGluePointId;
if( aAny >>= nGluePointId )
{
if( nGluePointId != -1 )
{
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_end_glue_point, OUString::valueOf( nGluePointId ));
}
}
}
// write connector shape. Add Export later.
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_connector, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportMeasureShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures /* = SEF_DEFAULT */, awt::Point* pRefPoint /* = NULL */)
{
uno::Reference< beans::XPropertySet > xProps( xShape, uno::UNO_QUERY );
OUString aStr;
OUStringBuffer sStringBuffer;
// export start and end point
awt::Point aStart(0,0);
awt::Point aEnd(1,1);
uno::Any aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("StartPosition")));
aAny >>= aStart;
aAny = xProps->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("EndPosition")));
aAny >>= aEnd;
if( pRefPoint )
{
aStart.X -= pRefPoint->X;
aStart.Y -= pRefPoint->Y;
aEnd.X -= pRefPoint->X;
aEnd.Y -= pRefPoint->Y;
}
if( nFeatures & SEF_EXPORT_X )
{
// svg: x1
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aStart.X);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_x1, aStr);
}
else
{
aEnd.X -= aStart.X;
}
if( nFeatures & SEF_EXPORT_Y )
{
// svg: y1
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aStart.Y);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_y1, aStr);
}
else
{
aEnd.Y -= aStart.Y;
}
// svg: x2
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aEnd.X);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_x2, aStr);
// svg: y2
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, aEnd.Y);
aStr = sStringBuffer.makeStringAndClear();
rExport.AddAttribute(XML_NAMESPACE_SVG, sXML_y2, aStr);
// write measure shape
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_measure, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
uno::Reference< text::XText > xText( xShape, uno::UNO_QUERY );
if( xText.is() )
rExport.GetTextParagraphExport()->exportText( xText );
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportOLE2Shape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures /* = SEF_DEFAULT */, awt::Point* pRefPoint /* = NULL */)
{
uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
uno::Reference< container::XNamed > xNamed(xShape, uno::UNO_QUERY);
DBG_ASSERT( xPropSet.is() && xNamed.is(), "ole shape is not implementing needed interfaces");
if(xPropSet.is() && xNamed.is())
{
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
sal_Bool bIsEmptyPresObj = sal_False;
// presentation settings
if(eShapeType == XmlShapeTypePresOLE2Shape)
bIsEmptyPresObj = ImpExportPresentationAttributes( xPropSet, OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_object)));
else if(eShapeType == XmlShapeTypePresChartShape)
bIsEmptyPresObj = ImpExportPresentationAttributes( xPropSet, OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_chart)) );
else if(eShapeType == XmlShapeTypePresTableShape)
bIsEmptyPresObj = ImpExportPresentationAttributes( xPropSet, OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_table)) );
OUString sClassId;
if( !bIsEmptyPresObj )
{
// xlink:href
OUString sURL(RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.EmbeddedObject:" ));
sURL += xNamed->getName();
sal_Bool bInternal;
xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("IsInternal"))) >>= bInternal;
if( !bInternal )
xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("CLSID"))) >>= sClassId;
if( sClassId.getLength() )
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_class_id, sClassId );
sURL = rExport.AddEmbeddedObject( sURL );
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_href, GetExport().GetRelativeReference(sURL) );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_type, sXML_simple );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_show, sXML_embed );
rExport.AddAttributeASCII( XML_NAMESPACE_XLINK, sXML_actuate, sXML_onLoad );
}
const sal_Char *pElem = sClassId.getLength() ? sXML_object_ole : sXML_object;
SvXMLElementExport aElem( rExport, XML_NAMESPACE_DRAW, pElem, sal_False, sal_True );
// see if we need to export a thumbnail bitmap
OUString aStr;
xPropSet->getPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("ThumbnailGraphicURL")) ) >>= aStr;
if( aStr.getLength() )
{
aStr = rExport.AddEmbeddedGraphicObject( GetExport().GetRelativeReference(aStr) );
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_href, aStr );
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_simple));
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_type, aStr );
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_embed));
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_show, aStr );
aStr = OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_onLoad));
rExport.AddAttribute(XML_NAMESPACE_XLINK, sXML_actuate, aStr );
SvXMLElementExport aElem( rExport, XML_NAMESPACE_DRAW, sXML_thumbnail, sal_True, sal_True );
}
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportPageShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures /* = SEF_DEFAULT */, awt::Point* pRefPoint /* = NULL */)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
// #86163# Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
// export page number used for this page
uno::Reference< beans::XPropertySetInfo > xPropSetInfo( xPropSet->getPropertySetInfo() );
const OUString aPageNumberStr(RTL_CONSTASCII_USTRINGPARAM("PageNumber"));
if( xPropSetInfo.is() && xPropSetInfo->hasPropertyByName(aPageNumberStr))
{
sal_Int32 nPageNumber = 0;
xPropSet->getPropertyValue(aPageNumberStr) >>= nPageNumber;
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_page_number, OUString::valueOf(nPageNumber));
}
// a presentation page shape, normally used on notes pages only. If
// it is used not as presentation shape, it may have been created with
// copy-paste exchange between draw and impress (this IS possible...)
if(eShapeType == XmlShapeTypePresPageShape)
{
rExport.AddAttribute(XML_NAMESPACE_PRESENTATION, sXML_class,
OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_presentation_page)));
}
// write Page shape
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_page_thumbnail, sal_True, sal_True);
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportCaptionShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures /* = SEF_DEFAULT */, awt::Point* pRefPoint /* = NULL */)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
// evtl. corner radius?
sal_Int32 nCornerRadius(0L);
xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("CornerRadius"))) >>= nCornerRadius;
if(nCornerRadius)
{
OUStringBuffer sStringBuffer;
rExport.GetMM100UnitConverter().convertMeasure(sStringBuffer, nCornerRadius);
rExport.AddAttribute(XML_NAMESPACE_DRAW, sXML_corner_radius, sStringBuffer.makeStringAndClear());
}
awt::Point aCaptionPoint;
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "CaptionPoint" ) ) ) >>= aCaptionPoint;
// #88491# correct CaptionPoint position about pRefPoint
if(pRefPoint)
{
aCaptionPoint.X = aCaptionPoint.X - pRefPoint->X;
aCaptionPoint.Y = aCaptionPoint.Y - pRefPoint->Y;
}
rExport.GetMM100UnitConverter().convertMeasure(msBuffer, aCaptionPoint.X);
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_caption_point_x, msBuffer.makeStringAndClear() );
rExport.GetMM100UnitConverter().convertMeasure(msBuffer, aCaptionPoint.Y);
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_caption_point_y, msBuffer.makeStringAndClear() );
// write Caption shape. Add export later.
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_caption, sal_True, sal_True);
ImpExportEvents( xShape );
ImpExportGluePoints( xShape );
ImpExportText( xShape );
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportFrameShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, com::sun::star::awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
// export frame url
OUString aStr;
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "FrameURL" ) ) ) >>= aStr;
rExport.AddAttribute ( XML_NAMESPACE_XLINK, sXML_href, GetExport().GetRelativeReference(aStr) );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_type, sXML_simple );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_show, sXML_embed );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_actuate, sXML_onLoad );
// export name
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "FrameName" ) ) ) >>= aStr;
if( aStr.getLength() )
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_frame_name, aStr );
// write floating frame
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_floating_frame, sal_True, sal_True);
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportAppletShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, com::sun::star::awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
// export frame url
OUString aStr;
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "AppletCodeBase" ) ) ) >>= aStr;
rExport.AddAttribute ( XML_NAMESPACE_XLINK, sXML_href, GetExport().GetRelativeReference(aStr) );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_type, sXML_simple );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_show, sXML_embed );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_actuate, sXML_onLoad );
// export draw:applet-name
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "AppletName" ) ) ) >>= aStr;
if( aStr.getLength() )
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_applet_name, aStr );
// export draw:code
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "AppletCode" ) ) ) >>= aStr;
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_code, aStr );
// export draw:may-script
sal_Bool bIsScript;
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "AppletIsScript" ) ) ) >>= bIsScript;
rExport.AddAttributeASCII( XML_NAMESPACE_DRAW, sXML_may_script, bIsScript ? sXML_true : sXML_false );
// write applet
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_applet, sal_True, sal_True);
// export parameters
uno::Sequence< beans::PropertyValue > aCommands;
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "AppletCommands" ) ) ) >>= aCommands;
const sal_Int32 nCount = aCommands.getLength();
for( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++ )
{
aCommands[nIndex].Value >>= aStr;
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_name, aCommands[nIndex].Name );
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_value, aStr );
SvXMLElementExport aElem( rExport, XML_NAMESPACE_DRAW, sXML_param, sal_False, sal_True );
}
}
}
//////////////////////////////////////////////////////////////////////////////
void XMLShapeExport::ImpExportPluginShape(
const uno::Reference< drawing::XShape >& xShape,
XmlShapeType eShapeType, sal_Int32 nFeatures, com::sun::star::awt::Point* pRefPoint)
{
const uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
if(xPropSet.is())
{
// Transformation
ImpExportNewTrans(xPropSet, nFeatures, pRefPoint);
// export plugin url
OUString aStr;
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "PluginURL" ) ) ) >>= aStr;
rExport.AddAttribute ( XML_NAMESPACE_XLINK, sXML_href, GetExport().GetRelativeReference(aStr) );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_type, sXML_simple );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_show, sXML_embed );
rExport.AddAttributeASCII ( XML_NAMESPACE_XLINK, sXML_actuate, sXML_onLoad );
// export mime-type
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "PluginMimeType" ) ) ) >>= aStr;
if(aStr.getLength())
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_mime_type, aStr );
// write plugin
SvXMLElementExport aOBJ(rExport, XML_NAMESPACE_DRAW, sXML_plugin, sal_True, sal_True);
// export parameters
uno::Sequence< beans::PropertyValue > aCommands;
xPropSet->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "PluginCommands" ) ) ) >>= aCommands;
const sal_Int32 nCount = aCommands.getLength();
for( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++ )
{
aCommands[nIndex].Value >>= aStr;
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_name, aCommands[nIndex].Name );
rExport.AddAttribute( XML_NAMESPACE_DRAW, sXML_value, aStr );
SvXMLElementExport aElem( rExport, XML_NAMESPACE_DRAW, sXML_param, sal_False, sal_True );
}
}
}
|
/*-----------------------------------------------------------------------------------------------------------
SafeInt.hpp
Version 3.0.12p
This software is licensed under the Microsoft Public License (Ms-PL).
For more information about Microsoft open source licenses, refer to
http://www.microsoft.com/opensource/licenses.mspx
This license governs use of the accompanying software. If you use the software, you accept this license.
If you do not accept the license, do not use the software.
Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here
as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to
the software. A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations
in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to
reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution
or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in
section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed
patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution
in the software or derivative works of the contribution in the software.
Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo,
or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the
software, your patent license from such contributor to the software ends automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and
attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only under this license
by including a complete copy of this license with your distribution. If you distribute any portion of the
software in compiled or object code form, you may only do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties,
guarantees, or conditions. You may have additional consumer rights under your local laws which this license
cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties
of merchantability, fitness for a particular purpose and non-infringement.
Copyright (c) Microsoft Corporation. All rights reserved.
This header implements an integer handling class designed to catch
unsafe integer operations
This header compiles properly at warning level 4.
Please read the leading comments before using the class.
Version 3.0
---------------------------------------------------------------*/
#ifndef SAFEINT_HPP
#define SAFEINT_HPP
#include <assert.h>
#ifndef C_ASSERT
#define C_ASSERT(e) typedef char __C_ASSERT__[(e)?1:-1]
#endif
/************* Compiler Options *****************************************************************************************************
SafeInt supports several compile-time options that can change the behavior of the class.
Compiler options:
SAFEINT_WARN_64BIT_PORTABILITY - this re-enables various warnings that happen when /Wp64 is used. Enabling this option is not
recommended.
NEEDS_INT_DEFINED - if your compiler does not support __int8, __int16, __int32 and __int64, you can enable this.
SAFEINT_ASSERT_ON_EXCEPTION - it is often easier to stop on an assert and figure out a problem than to try and figure out
how you landed in the catch block.
SafeIntDefaultExceptionHandler - if you'd like to replace the exception handlers SafeInt provides, define your replacement and
define this.
SAFEINT_DISALLOW_UNSIGNED_NEGATION - Invoking the unary negation operator creates warnings, but if you'd like it to completely fail
to compile, define this.
ANSI_CONVERSIONS - This changes the class to use default comparison behavior, which may be unsafe. Enabling this
option is not recommended.
SAFEINT_DISABLE_BINARY_ASSERT - binary AND, OR or XOR operations on mixed size types can produce unexpected results. If you do
this, the default is to assert. Set this if you prefer not to assert under these conditions.
SIZE_T_CAST_NEEDED - some compilers complain if there is not a cast to size_t, others complain if there is one.
This lets you not have your compiler complain.
SAFEINT_DISABLE_SHIFT_ASSERT - Set this option if you don't want to assert when shifting more bits than the type has. Enabling
this option is not recommended.
************************************************************************************************************************************/
/*
* The SafeInt class is designed to have as low an overhead as possible
* while still ensuring that all integer operations are conducted safely.
* Nearly every operator has been overloaded, with a very few exceptions.
*
* A usability-safety trade-off has been made to help ensure safety. This
* requires that every operation return either a SafeInt or a bool. If we
* allowed an operator to return a base integer type T, then the following
* can happen:
*
* char i = SafeInt<char>(32) * 2 + SafeInt<char>(16) * 4;
*
* The * operators take precedence, get overloaded, return a char, and then
* you have:
*
* char i = (char)64 + (char)64; //overflow!
*
* This situation would mean that safety would depend on usage, which isn't
* acceptable.
*
* One key operator that is missing is an implicit cast to type T. The reason for
* this is that if there is an implicit cast operator, then we end up with
* an ambiguous compile-time precedence. Because of this amiguity, there
* are two methods that are provided:
*
* Casting operators for every native integer type
* Version 3 note - it now compiles correctly for size_t without warnings
*
* SafeInt::Ptr() - returns the address of the internal integer
* Note - the '&' (address of) operator has been overloaded and returns
* the address of the internal integer.
*
* The SafeInt class should be used in any circumstances where ensuring
* integrity of the calculations is more important than performance. See Performance
* Notes below for additional information.
*
* Many of the conditionals will optimize out or be inlined for a release
* build (especially with /Ox), but it does have significantly more overhead,
* especially for signed numbers. If you do not _require_ negative numbers, use
* unsigned integer types - certain types of problems cannot occur, and this class
* performs most efficiently.
*
* Here's an example of when the class should ideally be used -
*
* void* AllocateMemForStructs(int StructSize, int HowMany)
* {
* SafeInt<unsigned long> s(StructSize);
*
* s *= HowMany;
*
* return malloc(s);
*
* }
*
* Here's when it should NOT be used:
*
* void foo()
* {
* int i;
*
* for(i = 0; i < 0xffff; i++)
* ....
* }
*
* Error handling - a SafeInt class will throw exceptions if something
* objectionable happens. The exceptions are SafeIntException classes,
* which contain an enum as a code.
*
* Typical usage might be:
*
* bool foo()
* {
* SafeInt<unsigned long> s; //note that s == 0 unless set
*
* try{
* s *= 23;
* ....
* }
* catch(SafeIntException err)
* {
* //handle errors here
* }
* }
*
* Update for 3.0 - the exception class is now a template parameter.
* You can replace the exception class with any exception class you like. This is accomplished by:
* 1) Create a class that has the following interface:
*
template <> class YourSafeIntExceptionHandler < YourException >
{
public:
static __declspec(noreturn) void __stdcall SafeIntOnOverflow()
{
throw YourException( YourSafeIntArithmeticOverflowError );
}
static __declspec(noreturn) void __stdcall SafeIntOnDivZero()
{
throw YourException( YourSafeIntDivideByZeroError );
}
};
*
* Note that you don't have to throw C++ exceptions, you can throw Win32 exceptions, or do
* anything you like, just don't return from the call back into the code.
*
* 2) Either explicitly declare SafeInts like so:
* SafeInt< int, YourSafeIntExceptionHandler > si;
* or
* #define SafeIntDefaultExceptionHandler YourSafeIntExceptionHandler
*
* Performance:
*
* Due to the highly nested nature of this class, you can expect relatively poor
* performance in unoptimized code. In tests of optimized code vs. correct inline checks
* in native code, this class has been found to take approximately 8% more CPU time (this varies),
* most of which is due to exception handling. Solutions:
*
* 1) Compile optimized code - /Ox is best, /O2 also performs well. Interestingly, /O1
* (optimize for size) does not work as well.
* 2) If that 8% hit is really a serious problem, walk through the code and inline the
* exact same checks as the class uses.
* 3) Some operations are more difficult than others - avoid using signed integers, and if
* possible keep them all the same size. 64-bit integers are also expensive. Mixing
* different integer sizes and types may prove expensive. Be aware that literals are
* actually ints. For best performance, cast literals to the type desired.
*
*
* Performance update
* The current version of SafeInt uses template specialization to force the compiler to invoke only the
* operator implementation needed for any given pair of types. This will dramatically improve the perf
* of debug builds.
*
* 3.0 update - not only have we maintained the specialization, there were some cases that were overly complex,
* and using some additional cases (e.g. signed __int64 and unsigned __int64) resulted in some simplification.
* Additionally, there was a lot of work done to better optimize the 64-bit multiplication.
*
* Binary Operators
*
* All of the binary operators have certain assumptions built into the class design.
* This is to ensure correctness. Notes on each class of operator follow:
*
* Arithmetic Operators (*,/,+,-,%)
* There are three possible variants:
* SafeInt< T, E > op SafeInt< T, E >
* SafeInt< T, E > op U
* U op SafeInt< T, E >
*
* The SafeInt< T, E > op SafeInt< U, E > variant is explicitly not supported, and if you try to do
* this the compiler with throw the following error:
*
* error C2593: 'operator *' is ambiguous
*
* This is because the arithmetic operators are required to return a SafeInt of some type.
* The compiler cannot know whether you'd prefer to get a type T or a type U returned. If
* you need to do this, you need to extract the value contained within one of the two using
* the casting operator. For example:
*
* SafeInt< T, E > t, result;
* SafeInt< U, E > u;
*
* result = t * (U)u;
*
* Comparison Operators
* Because each of these operators return type bool, mixing SafeInts of differing types is
* allowed.
*
* Shift Operators
* Shift operators always return the type on the left hand side of the operator. Mixed type
* operations are allowed because the return type is always known.
*
* Boolean Operators
* Like comparison operators, these overloads always return type bool, and mixed-type SafeInts
* are allowed. Additionally, specific overloads exist for type bool on both sides of the
* operator.
*
* Binary Operators
* Mixed-type operations are discouraged, however some provision has been made in order to
* enable things like:
*
* SafeInt<char> c = 2;
*
* if(c & 0x02)
* ...
*
* The "0x02" is actually an int, and it needs to work.
* In the case of binary operations on integers smaller than 32-bit, or of mixed type, corner
* cases do exist where you could get unexpected results. In any case where SafeInt returns a different
* result than the underlying operator, it will call assert(). You should examine your code and cast things
* properly so that you are not programming with side effects.
*
* Documented issues:
*
* This header compiles correctly at /W4 using VC++ 8 (Version 14.00.50727.42) and later.
* As of this writing, I believe it will also work for VC 7.1, but not for VC 7.0 or below.
* If you need a version that will work with lower level compilers, try version 1.0.7. None
* of them work with Visual C++ 6, and gcc didn't work very well, either, though this hasn't
* been tried recently.
*
* It is strongly recommended that any code doing integer manipulation be compiled at /W4
* - there are a number of warnings which pertain to integer manipulation enabled that are
* not enabled at /W3 (default for VC++)
*
* Perf note - postfix operators are slightly more costly than prefix operators.
* Unless you're actually assigning it to something, ++SafeInt is less expensive than SafeInt++
*
* The comparison operator behavior in this class varies from the ANSI definition, which is
* arguably broken. As an example, consider the following:
*
* unsigned int l = 0xffffffff;
* char c = -1;
*
* if(c == l)
* printf("Why is -1 equal to 4 billion???\n");
*
* The problem here is that c gets cast to an int, now has a value of 0xffffffff, and then gets
* cast again to an unsigned int, losing the true value. This behavior is despite the fact that
* an __int64 exists, and the following code will yield a different (and intuitively correct)
* answer:
*
* if((__int64)c == (__int64)l))
* printf("Why is -1 equal to 4 billion???\n");
* else
* printf("Why doesn't the compiler upcast to 64-bits when needed?\n");
*
* Note that combinations with smaller integers won't display the problem - if you
* changed "unsigned int" above to "unsigned short", you'd get the right answer.
*
* If you prefer to retain the ANSI standard behavior insert
* #define ANSI_CONVERSIONS
* into your source. Behavior differences occur in the following cases:
* 8, 16, and 32-bit signed int, unsigned 32-bit int
* any signed int, unsigned 64-bit int
* Note - the signed int must be negative to show the problem
*
*
* Revision history:
*
* Oct 12, 2003 - Created
* Author - David LeBlanc - dleblanc@microsoft.com
*
* Oct 27, 2003 - fixed numerous items pointed out by michmarc and bdawson
* Dec 28, 2003 - 1.0
* added support for mixed-type operations
* thanks to vikramh
* also fixed broken __int64 multiplication section
* added extended support for mixed-type operations where possible
* Jan 28, 2004 - 1.0.1
* changed WCHAR to wchar_t
* fixed a construct in two mixed-type assignment overloads that was
* not compiling on some compilers
* Also changed name of private method to comply with standards on
* reserved names
* Thanks to Niels Dekker for the input
* Feb 12, 2004 - 1.0.2
* Minor changes to remove dependency on Windows headers
* Consistently used __int16, __int32 and __int64 to ensure
* portability
* May 10, 2004 - 1.0.3
* Corrected bug in one case of GreaterThan
* July 22, 2004 - 1.0.4
* Tightened logic in addition check (saving 2 instructions)
* Pulled error handler out into function to enable user-defined replacement
* Made internal type of SafeIntException an enum (as per Niels' suggestion)
* Added casts for base integer types (as per Scott Meyers' suggestion)
* Updated usage information - see important new perf notes.
* Cleaned up several const issues (more thanks to Niels)
*
* Oct 1, 2004 - 1.0.5
* Added support for SEH exceptions instead of C++ exceptions - Win32 only
* Made handlers for DIV0 and overflows individually overridable
* Commented out the destructor - major perf gains here
* Added cast operator for type long, since long != __int32
* Corrected a couple of missing const modifiers
* Fixed broken >= and <= operators for type U op SafeInt< T, E >
* Nov 5, 2004 - 1.0.6
* Implemented new logic in binary operators to resolve issues with
* implicit casts
* Fixed casting operator because char != signed char
* Defined __int32 as int instead of long
* Removed unsafe SafeInt::Value method
* Re-implemented casting operator as a result of removing Value method
* Dec 1, 2004 - 1.0.7
* Implemented specialized operators for pointer arithmetic
* Created overloads for cases of U op= SafeInt. What you do with U
* after that may be dangerous.
* Fixed bug in corner case of MixedSizeModulus
* Fixed bug in MixedSizeMultiply and MixedSizeDivision with input of 0
* Added throw() decorations
*
* Apr 12, 2005 - 2.0
* Extensive revisions to leverage template specialization.
* April, 2007 Extensive revisions for version 3.0
* Nov 22, 2009 Forked from MS internal code
* Changes needed to support gcc compiler - many thanks to Niels Dekker
* for determining not just the issues, but also suggesting fixes.
* Also updating some of the header internals to be the same as the upcoming Visual Studio version.
*
* Note about code style - throughout this class, casts will be written using C-style (T),
* not C++ style static_cast< T >. This is because the class is nearly always dealing with integer
* types, and in this case static_cast and a C cast are equivalent. Given the large number of casts,
* the code is a little more readable this way. In the event a cast is needed where static_cast couldn't
* be substituted, we'll use the new templatized cast to make it explicit what the operation is doing.
*
************************************************************************************************************
* Version 3.0 changes:
*
* 1) The exception type thrown is now replacable, and you can throw your own exception types. This should help
* those using well-developed exception classes.
* 2) The 64-bit multiplication code has had a lot of perf work done, and should be faster than 2.0.
* 3) There is now limited floating point support. You can initialize a SafeInt with a floating point type,
* and you can cast it out (or assign) to a float as well.
* 4) There is now an Align method. I noticed people use this a lot, and rarely check errors, so now you have one.
*
* Another major improvement is the addition of external functions - if you just want to check an operation, this can now happen:
* All of the following can be invoked without dealing with creating a class, or managing exceptions. This is especially handy
* for 64-bit porting, since SafeCast compiles away for a 32-bit cast from size_t to unsigned long, but checks it for 64-bit.
*
* inline bool SafeCast( const T From, U& To ) throw()
* inline bool SafeEquals( const T t, const U u ) throw()
* inline bool SafeNotEquals( const T t, const U u ) throw()
* inline bool SafeGreaterThan( const T t, const U u ) throw()
* inline bool SafeGreaterThanEquals( const T t, const U u ) throw()
* inline bool SafeLessThan( const T t, const U u ) throw()
* inline bool SafeLessThanEquals( const T t, const U u ) throw()
* inline bool SafeModulus( const T& t, const U& u, T& result ) throw()
* inline bool SafeMultiply( T t, U u, T& result ) throw()
* inline bool SafeDivide( T t, U u, T& result ) throw()
* inline bool SafeAdd( T t, U u, T& result ) throw()
* inline bool SafeSubtract( T t, U u, T& result ) throw()
*
* * */
#pragma warning(push)
//this avoids warnings from the unary '-' operator being applied to unsigned numbers
#pragma warning(disable:4146)
// conditional expression is constant - these are used intentionally
#pragma warning(disable:4127)
//cast truncates constant value
#pragma warning(disable:4310)
#if !defined SAFEINT_WARN_64BIT_PORTABILITY
// Internally to SafeInt, these should always be false positives.
// If actually compiled with the 64-bit compiler, it would pull in a different template specialization.
#pragma warning(disable:4242)
#pragma warning(disable:4244)
#pragma warning(disable:4267)
#endif
//use these if the compiler does not support _intXX
#ifdef NEEDS_INT_DEFINED
#define __int8 char
#define __int16 short
#define __int32 int
#define __int64 long long
#endif
/* catch these to handle errors
** Currently implemented code values:
** ERROR_ARITHMETIC_OVERFLOW
** EXCEPTION_INT_DIVIDE_BY_ZERO
*/
enum SafeIntError
{
SafeIntNoError = 0,
SafeIntArithmeticOverflow,
SafeIntDivideByZero
};
/*
* Error handler classes
* Using classes to deal with exceptions is going to allow the most
* flexibility, and we can mix different error handlers in the same project
* or even the same file. It isn't advisable to do this in the same function
* because a SafeInt< int, MyExceptionHandler > isn't the same thing as
* SafeInt< int, YourExceptionHander >.
* If for some reason you have to translate between the two, cast one of them back to its
* native type.
*
* To use your own exception class with SafeInt, first create your exception class,
* which may look something like the SafeIntException class below. The second step is to
* create a template specialization that implements SafeIntOnOverflow and SafeIntOnDivZero.
* For example:
*
* template <> class SafeIntExceptionHandler < YourExceptionClass >
* {
* static __declspec(noreturn) void __stdcall SafeIntOnOverflow()
* {
* throw YourExceptionClass( EXCEPTION_INT_OVERFLOW );
* }
*
* static __declspec(noreturn) void __stdcall SafeIntOnDivZero()
* {
* throw YourExceptionClass( EXCEPTION_INT_DIVIDE_BY_ZERO );
* }
* };
*
* typedef SafeIntExceptionHandler < YourExceptionClass > YourSafeIntExceptionHandler
* You'd then declare your SafeInt objects like this:
* SafeInt< int, YourSafeIntExceptionHandler >
*
* Unfortunately, there is no such thing as partial template specialization in typedef
* statements, so you have three options if you find this cumbersome:
*
* 1) Create a holder class:
*
* template < typename T >
* class MySafeInt
* {
* public:
* SafeInt< T, MyExceptionClass> si;
* };
*
* You'd then declare an instance like so:
* MySafeInt< int > i;
*
* You'd lose handy things like initialization - it would have to be initialized as:
*
* i.si = 0;
*
* 2) You could create a typedef for every int type you deal with:
*
* typedef SafeInt< int, MyExceptionClass > MySafeInt;
* typedef SafeInt< char, MyExceptionClass > MySafeChar;
*
* and so on. The second approach is probably more usable, and will just drop into code
* better, which is the original intent of the SafeInt class.
*
* 3) If you're going to consistently use a different class to handle your exceptions,
* you can override the default typedef like so:
*
* #define SafeIntDefaultExceptionHandler YourSafeIntExceptionHandler
*
* Overall, this is probably the best approach.
* */
class SafeIntException
{
public:
SafeIntException() { m_code = SafeIntNoError; }
SafeIntException( SafeIntError code )
{
m_code = code;
}
SafeIntError m_code;
};
#if defined SAFEINT_ASSERT_ON_EXCEPTION
inline void SafeIntExceptionAssert(){ assert(false); }
#else
inline void SafeIntExceptionAssert(){}
#endif
namespace SafeIntInternal
{
template < typename E > class SafeIntExceptionHandler;
template <> class SafeIntExceptionHandler < SafeIntException >
{
public:
#if defined SAFEINT_GCC_HPP
static void SafeIntOnOverflow()
#else
static __declspec(noreturn) void __stdcall SafeIntOnOverflow()
#endif
{
SafeIntExceptionAssert();
throw SafeIntException( SafeIntArithmeticOverflow );
}
#if defined SAFEINT_GCC_HPP
static void SafeIntOnDivZero()
#else
static __declspec(noreturn) void __stdcall SafeIntOnDivZero()
#endif
{
SafeIntExceptionAssert();
throw SafeIntException( SafeIntDivideByZero );
}
};
#if defined _WINDOWS_
class SafeIntWin32Exception
{
public:
SafeIntWin32Exception( DWORD dwExceptionCode, DWORD dwExceptionFlags = EXCEPTION_NONCONTINUABLE )
{
SafeIntExceptionAssert();
RaiseException( dwExceptionCode, dwExceptionFlags, 0, 0 );
}
};
template <> class SafeIntExceptionHandler < SafeIntWin32Exception >
{
public:
static __declspec(noreturn) void __stdcall SafeIntOnOverflow()
{
SafeIntExceptionAssert();
SafeIntWin32Exception( EXCEPTION_INT_OVERFLOW );
}
static __declspec(noreturn) void __stdcall SafeIntOnDivZero()
{
SafeIntExceptionAssert();
SafeIntWin32Exception( EXCEPTION_INT_DIVIDE_BY_ZERO );
}
};
#endif
} // namespace SafeIntInternal
typedef SafeIntInternal::SafeIntExceptionHandler < SafeIntException > CPlusPlusExceptionHandler;
#if defined _WINDOWS_
typedef SafeIntInternal::SafeIntExceptionHandler < SafeIntInternal::SafeIntWin32Exception > Win32ExceptionHandler;
#endif
// If the user hasn't defined a default exception handler,
// define one now, depending on whether they would like Win32 or C++ exceptions
#if !defined SafeIntDefaultExceptionHandler
#if defined SAFEINT_RAISE_EXCEPTION
#if !defined _WINDOWS_
#error Include windows.h in order to use Win32 exceptions
#endif
#define SafeIntDefaultExceptionHandler Win32ExceptionHandler
#else
#define SafeIntDefaultExceptionHandler CPlusPlusExceptionHandler
#endif
#endif
/*
* The following template magic is because we're now not allowed
* to cast a float to an enum. This means that if we happen to assign
* an enum to a SafeInt of some type, it won't compile, unless we prevent
* isFloat = ( (T)( (float)1.1 ) > (T)1 )
* from compiling in the case of an enum, which is the point of the specialization
* that follows.
*/
template < typename T > class NumericType;
template <> class NumericType<bool> { public: enum{ isBool = true, isFloat = false, isInt = false }; };
template <> class NumericType<char> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<unsigned char> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<signed char> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<short> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<unsigned short> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
#if defined SAFEINT_USE_WCHAR_T || _NATIVE_WCHAR_T_DEFINED
template <> class NumericType<wchar_t> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
#endif
template <> class NumericType<int> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<unsigned int> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<long> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<unsigned long> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<__int64> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<unsigned __int64> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<float> { public: enum{ isBool = false, isFloat = true, isInt = false }; };
template <> class NumericType<double> { public: enum{ isBool = false, isFloat = true, isInt = false }; };
template <> class NumericType<long double> { public: enum{ isBool = false, isFloat = true, isInt = false }; };
// Catch-all for anything not supported
template < typename T > class NumericType { public: enum{ isBool = false, isFloat = false, isInt = false }; };
template < typename T > class IntTraits
{
public:
C_ASSERT( NumericType<T>::isInt );
enum
{
#pragma warning(suppress:4804)
isSigned = ( (T)(-1) < 0 ),
is64Bit = ( sizeof(T) == 8 ),
is32Bit = ( sizeof(T) == 4 ),
is16Bit = ( sizeof(T) == 2 ),
is8Bit = ( sizeof(T) == 1 ),
isLT32Bit = ( sizeof(T) < 4 ),
isLT64Bit = ( sizeof(T) < 8 ),
isInt8 = ( sizeof(T) == 1 && isSigned ),
isUint8 = ( sizeof(T) == 1 && !isSigned ),
isInt16 = ( sizeof(T) == 2 && isSigned ),
isUint16 = ( sizeof(T) == 2 && !isSigned ),
isInt32 = ( sizeof(T) == 4 && isSigned ),
isUint32 = ( sizeof(T) == 4 && !isSigned ),
isInt64 = ( sizeof(T) == 8 && isSigned ),
isUint64 = ( sizeof(T) == 8 && !isSigned ),
bitCount = ( sizeof(T)*8 ),
#pragma warning(suppress:4804)
isBool = ( (T)2 == (T)1 )
};
// On version 13.10 enums cannot define __int64 values
// so we'll use const statics instead!
const static T maxInt = isSigned ? ((T)~((T)1 << (T)(bitCount-1))) : ((T)(~(T)0));
const static T minInt = isSigned ? ((T)((T)1 << (T)(bitCount-1))) : ((T)0);
};
template < typename T, typename U > class SafeIntCompare
{
public:
enum
{
isBothSigned = (IntTraits< T >::isSigned && IntTraits< U >::isSigned),
isBothUnsigned = (!IntTraits< T >::isSigned && !IntTraits< U >::isSigned),
isLikeSigned = ((bool)(IntTraits< T >::isSigned) == (bool)(IntTraits< U >::isSigned)),
isCastOK = ((isLikeSigned && sizeof(T) >= sizeof(U)) ||
(IntTraits< T >::isSigned && sizeof(T) > sizeof(U))),
isBothLT32Bit = (IntTraits< T >::isLT32Bit && IntTraits< U >::isLT32Bit),
isBothLT64Bit = (IntTraits< T >::isLT64Bit && IntTraits< U >::isLT64Bit)
};
};
//all of the arithmetic operators can be solved by the same code within
//each of these regions without resorting to compile-time constant conditionals
//most operators collapse the problem into less than the 22 zones, but this is used
//as the first cut
//using this also helps ensure that we handle all of the possible cases correctly
template < typename T, typename U > class IntRegion
{
public:
enum
{
//unsigned-unsigned zone
IntZone_UintLT32_UintLT32 = SafeIntCompare< T,U >::isBothUnsigned && SafeIntCompare< T,U >::isBothLT32Bit,
IntZone_Uint32_UintLT64 = SafeIntCompare< T,U >::isBothUnsigned && IntTraits< T >::is32Bit && IntTraits< U >::isLT64Bit,
IntZone_UintLT32_Uint32 = SafeIntCompare< T,U >::isBothUnsigned && IntTraits< T >::isLT32Bit && IntTraits< U >::is32Bit,
IntZone_Uint64_Uint = SafeIntCompare< T,U >::isBothUnsigned && IntTraits< T >::is64Bit,
IntZone_UintLT64_Uint64 = SafeIntCompare< T,U >::isBothUnsigned && IntTraits< T >::isLT64Bit && IntTraits< U >::is64Bit,
//unsigned-signed
IntZone_UintLT32_IntLT32 = !IntTraits< T >::isSigned && IntTraits< U >::isSigned && SafeIntCompare< T,U >::isBothLT32Bit,
IntZone_Uint32_IntLT64 = IntTraits< T >::isUint32 && IntTraits< U >::isSigned && IntTraits< U >::isLT64Bit,
IntZone_UintLT32_Int32 = !IntTraits< T >::isSigned && IntTraits< T >::isLT32Bit && IntTraits< U >::isInt32,
IntZone_Uint64_Int = IntTraits< T >::isUint64 && IntTraits< U >::isSigned && IntTraits< U >::isLT64Bit,
IntZone_UintLT64_Int64 = !IntTraits< T >::isSigned && IntTraits< T >::isLT64Bit && IntTraits< U >::isInt64,
IntZone_Uint64_Int64 = IntTraits< T >::isUint64 && IntTraits< U >::isInt64,
//signed-signed
IntZone_IntLT32_IntLT32 = SafeIntCompare< T,U >::isBothSigned && ::SafeIntCompare< T, U >::isBothLT32Bit,
IntZone_Int32_IntLT64 = SafeIntCompare< T,U >::isBothSigned && IntTraits< T >::is32Bit && IntTraits< U >::isLT64Bit,
IntZone_IntLT32_Int32 = SafeIntCompare< T,U >::isBothSigned && IntTraits< T >::isLT32Bit && IntTraits< U >::is32Bit,
IntZone_Int64_Int64 = SafeIntCompare< T,U >::isBothSigned && IntTraits< T >::isInt64 && IntTraits< U >::isInt64,
IntZone_Int64_Int = SafeIntCompare< T,U >::isBothSigned && IntTraits< T >::is64Bit && IntTraits< U >::isLT64Bit,
IntZone_IntLT64_Int64 = SafeIntCompare< T,U >::isBothSigned && IntTraits< T >::isLT64Bit && IntTraits< U >::is64Bit,
//signed-unsigned
IntZone_IntLT32_UintLT32 = IntTraits< T >::isSigned && !IntTraits< U >::isSigned && SafeIntCompare< T,U >::isBothLT32Bit,
IntZone_Int32_UintLT32 = IntTraits< T >::isInt32 && !IntTraits< U >::isSigned && IntTraits< U >::isLT32Bit,
IntZone_IntLT64_Uint32 = IntTraits< T >::isSigned && IntTraits< T >::isLT64Bit && IntTraits< U >::isUint32,
IntZone_Int64_UintLT64 = IntTraits< T >::isInt64 && !IntTraits< U >::isSigned && IntTraits< U >::isLT64Bit,
IntZone_Int_Uint64 = IntTraits< T >::isSigned && IntTraits< U >::isUint64 && IntTraits< T >::isLT64Bit,
IntZone_Int64_Uint64 = IntTraits< T >::isInt64 && IntTraits< U >::isUint64
};
};
// In all of the following functions, we have two versions
// One for SafeInt, which throws C++ (or possibly SEH) exceptions
// The non-throwing versions are for use by the helper functions that return success and failure.
// Some of the non-throwing functions are not used, but are maintained for completeness.
// There's no real alternative to duplicating logic, but keeping the two versions
// immediately next to one another will help reduce problems
// useful function to help with getting the magnitude of a negative number
enum AbsMethod
{
AbsMethodInt,
AbsMethodInt64,
AbsMethodNoop
};
template < typename T >
class GetAbsMethod
{
public:
enum
{
method = IntTraits< T >::isLT64Bit && IntTraits< T >::isSigned ? AbsMethodInt :
IntTraits< T >::isInt64 ? AbsMethodInt64 : AbsMethodNoop
};
};
template < typename T, int > class AbsValueHelper;
template < typename T > class AbsValueHelper < T, AbsMethodInt>
{
public:
static unsigned __int32 Abs( T t ) throw()
{
assert( t < 0 );
return (unsigned __int32)-t;
}
};
template < typename T > class AbsValueHelper < T, AbsMethodInt64 >
{
public:
static unsigned __int64 Abs( T t ) throw()
{
assert( t < 0 );
return (unsigned __int64)-t;
}
};
template < typename T > class AbsValueHelper < T, AbsMethodNoop >
{
public:
static T Abs( T t ) throw()
{
// Why are you calling Abs on an unsigned number ???
assert( false );
return t;
}
};
template < typename T, bool > class NegationHelper;
template < typename T > class NegationHelper <T, true> // Signed
{
public:
template <typename E>
static T NegativeThrow( T t )
{
// corner case
if( t != IntTraits< T >::minInt )
{
// cast prevents unneeded checks in the case of small ints
return -t;
}
E::SafeIntOnOverflow();
}
static bool Negative( T t, T& ret ) throw()
{
// corner case
if( t != IntTraits< T >::minInt )
{
// cast prevents unneeded checks in the case of small ints
ret = -t;
return true;
}
return false;
}
};
template < typename T > class NegationHelper <T, false> // unsigned
{
public:
template <typename E>
static T NegativeThrow( T t ) throw()
{
if( IntTraits<T>::isLT32Bit )
{
// This will normally upcast to int
// For example -(unsigned short)0xffff == (int)0xffff0001
// This class will retain the type, and will truncate, which may not be what
// you wanted
// If you want normal operator casting behavior, do this:
// SafeInt<unsigned short> ss = 0xffff;
// then:
// -(SafeInt<int>(ss))
// will then emit a signed int with the correct value and bitfield
assert( false );
}
#if defined SAFEINT_DISALLOW_UNSIGNED_NEGATION
C_ASSERT( sizeof(T) == 0 );
#endif
return -t;
}
static bool Negative( T t, T& ret )
{
if( IntTraits<T>::isLT32Bit )
{
// See above
assert( false );
}
#if defined SAFEINT_DISALLOW_UNSIGNED_NEGATION
C_ASSERT( sizeof(T) == 0 );
#endif
ret = -t;
return true;
}
};
//core logic to determine casting behavior
enum CastMethod
{
CastOK = 0,
CastCheckLTZero,
CastCheckGTMax,
CastCheckMinMaxUnsigned,
CastCheckMinMaxSigned,
CastToFloat,
CastFromFloat,
CastToBool,
CastFromBool
};
template < typename ToType, typename FromType >
class GetCastMethod
{
public:
enum
{
method = ( IntTraits< FromType >::isBool &&
!IntTraits< ToType >::isBool ) ? CastFromBool :
( !IntTraits< FromType >::isBool &&
IntTraits< ToType >::isBool ) ? CastToBool :
( SafeIntCompare< ToType, FromType >::isCastOK ) ? CastOK :
( ( IntTraits< ToType >::isSigned &&
!IntTraits< FromType >::isSigned &&
sizeof( FromType ) >= sizeof( ToType ) ) ||
( SafeIntCompare< ToType, FromType >::isBothUnsigned &&
sizeof( FromType ) > sizeof( ToType ) ) ) ? CastCheckGTMax :
( !IntTraits< ToType >::isSigned &&
IntTraits< FromType >::isSigned &&
sizeof( ToType ) >= sizeof( FromType ) ) ? CastCheckLTZero :
( !IntTraits< ToType >::isSigned ) ? CastCheckMinMaxUnsigned
: CastCheckMinMaxSigned
};
};
template < typename FromType > class GetCastMethod < float, FromType >
{
public:
enum{ method = CastOK };
};
template < typename FromType > class GetCastMethod < double, FromType >
{
public:
enum{ method = CastOK };
};
template < typename FromType > class GetCastMethod < long double, FromType >
{
public:
enum{ method = CastOK };
};
template < typename ToType > class GetCastMethod < ToType, float >
{
public:
enum{ method = CastFromFloat };
};
template < typename ToType > class GetCastMethod < ToType, double >
{
public:
enum{ method = CastFromFloat };
};
template < typename ToType > class GetCastMethod < ToType, long double >
{
public:
enum{ method = CastFromFloat };
};
template < typename T, typename U, int > class SafeCastHelper;
template < typename T, typename U > class SafeCastHelper < T, U, CastOK >
{
public:
static bool Cast( U u, T& t ) throw()
{
t = (T)u;
return true;
}
template < typename E >
static void CastThrow( U u, T& t )
{
t = (T)u;
}
};
// special case floats and doubles
// tolerate loss of precision
template < typename T, typename U > class SafeCastHelper < T, U, CastFromFloat >
{
public:
static bool Cast( U u, T& t ) throw()
{
if( u <= (U)IntTraits< T >::maxInt &&
u >= (U)IntTraits< T >::minInt )
{
t = (T)u;
return true;
}
return false;
}
template < typename E >
static void CastThrow( U u, T& t )
{
if( u <= (U)IntTraits< T >::maxInt &&
u >= (U)IntTraits< T >::minInt )
{
t = (T)u;
return;
}
E::SafeIntOnOverflow();
}
};
// Match on any method where a bool is cast to type T
template < typename T > class SafeCastHelper < T, bool, CastFromBool >
{
public:
static bool Cast( bool b, T& t ) throw()
{
t = (T)( b ? 1 : 0 );
return true;
}
template < typename E >
static void CastThrow( bool b, T& t )
{
t = (T)( b ? 1 : 0 );
}
};
template < typename T > class SafeCastHelper < bool, T, CastToBool >
{
public:
static bool Cast( T t, bool& b ) throw()
{
b = !!t;
return true;
}
template < typename E >
static void CastThrow( bool b, T& t )
{
b = !!t;
}
};
template < typename T, typename U > class SafeCastHelper < T, U, CastCheckLTZero >
{
public:
static bool Cast( U u, T& t ) throw()
{
if( u < 0 )
return false;
t = (T)u;
return true;
}
template < typename E >
static void CastThrow( U u, T& t )
{
if( u < 0 )
E::SafeIntOnOverflow();
t = (T)u;
}
};
template < typename T, typename U > class SafeCastHelper < T, U, CastCheckGTMax >
{
public:
static bool Cast( U u, T& t ) throw()
{
if( u > IntTraits< T >::maxInt )
return false;
t = (T)u;
return true;
}
template < typename E >
static void CastThrow( U u, T& t )
{
if( u > IntTraits< T >::maxInt )
E::SafeIntOnOverflow();
t = (T)u;
}
};
template < typename T, typename U > class SafeCastHelper < T, U, CastCheckMinMaxUnsigned >
{
public:
static bool Cast( U u, T& t ) throw()
{
// U is signed - T could be either signed or unsigned
if( u > IntTraits< T >::maxInt || u < 0 )
return false;
t = (T)u;
return true;
}
template < typename E >
static void CastThrow( U u, T& t )
{
// U is signed - T could be either signed or unsigned
if( u > IntTraits< T >::maxInt || u < 0 )
E::SafeIntOnOverflow();
t = (T)u;
}
};
template < typename T, typename U > class SafeCastHelper < T, U, CastCheckMinMaxSigned >
{
public:
static bool Cast( U u, T& t ) throw()
{
// T, U are signed
if( u > IntTraits< T >::maxInt || u < IntTraits< T >::minInt )
return false;
t = (T)u;
return true;
}
template < typename E >
static void CastThrow( U u, T& t )
{
//T, U are signed
if( u > IntTraits< T >::maxInt || u < IntTraits< T >::minInt )
E::SafeIntOnOverflow();
t = (T)u;
}
};
//core logic to determine whether a comparison is valid, or needs special treatment
enum ComparisonMethod
{
ComparisonMethod_Ok = 0,
ComparisonMethod_CastInt,
ComparisonMethod_CastInt64,
ComparisonMethod_UnsignedT,
ComparisonMethod_UnsignedU
};
// Note - the standard is arguably broken in the case of some integer
// conversion operations
// For example, signed char a = -1 = 0xff
// unsigned int b = 0xffffffff
// If you then test if a < b, a value-preserving cast
// is made, and you're essentially testing
// (unsigned int)a < b == false
//
// I do not think this makes sense - if you perform
// a cast to an __int64, which can clearly preserve both value and signedness
// then you get a different and intuitively correct answer
// IMHO, -1 should be less than 4 billion
// If you prefer to retain the ANSI standard behavior
// insert #define ANSI_CONVERSIONS into your source
// Behavior differences occur in the following cases:
// 8, 16, and 32-bit signed int, unsigned 32-bit int
// any signed int, unsigned 64-bit int
// Note - the signed int must be negative to show the problem
template < typename T, typename U >
class ValidComparison
{
public:
enum
{
#ifdef ANSI_CONVERSIONS
method = ComparisonMethod_Ok
#else
method = ( ( SafeIntCompare< T, U >::isLikeSigned ) ? ComparisonMethod_Ok :
( ( IntTraits< T >::isSigned && sizeof(T) < 8 && sizeof(U) < 4 ) ||
( IntTraits< U >::isSigned && sizeof(T) < 4 && sizeof(U) < 8 ) ) ? ComparisonMethod_CastInt :
( ( IntTraits< T >::isSigned && sizeof(U) < 8 ) ||
( IntTraits< U >::isSigned && sizeof(T) < 8 ) ) ? ComparisonMethod_CastInt64 :
( !IntTraits< T >::isSigned ) ? ComparisonMethod_UnsignedT :
ComparisonMethod_UnsignedU )
#endif
};
};
template <typename T, typename U, int state> class EqualityTest;
template < typename T, typename U > class EqualityTest< T, U, ComparisonMethod_Ok >
{
public:
static bool IsEquals( const T t, const U u ) throw() { return ( t == u ); }
};
template < typename T, typename U > class EqualityTest< T, U, ComparisonMethod_CastInt >
{
public:
static bool IsEquals( const T t, const U u ) throw() { return ( (int)t == (int)u ); }
};
template < typename T, typename U > class EqualityTest< T, U, ComparisonMethod_CastInt64 >
{
public:
static bool IsEquals( const T t, const U u ) throw() { return ( (__int64)t == (__int64)u ); }
};
template < typename T, typename U > class EqualityTest< T, U, ComparisonMethod_UnsignedT >
{
public:
static bool IsEquals( const T t, const U u ) throw()
{
//one operand is 32 or 64-bit unsigned, and the other is signed and the same size or smaller
if( u < 0 )
return false;
//else safe to cast to type T
return ( t == (T)u );
}
};
template < typename T, typename U > class EqualityTest< T, U, ComparisonMethod_UnsignedU>
{
public:
static bool IsEquals( const T t, const U u ) throw()
{
//one operand is 32 or 64-bit unsigned, and the other is signed and the same size or smaller
if( t < 0 )
return false;
//else safe to cast to type U
return ( (U)t == u );
}
};
template <typename T, typename U, int state> class GreaterThanTest;
template < typename T, typename U > class GreaterThanTest< T, U, ComparisonMethod_Ok >
{
public:
static bool GreaterThan( const T t, const U u ) throw() { return ( t > u ); }
};
template < typename T, typename U > class GreaterThanTest< T, U, ComparisonMethod_CastInt >
{
public:
static bool GreaterThan( const T t, const U u ) throw() { return ( (int)t > (int)u ); }
};
template < typename T, typename U > class GreaterThanTest< T, U, ComparisonMethod_CastInt64 >
{
public:
static bool GreaterThan( const T t, const U u ) throw() { return ( (__int64)t > (__int64)u ); }
};
template < typename T, typename U > class GreaterThanTest< T, U, ComparisonMethod_UnsignedT >
{
public:
static bool GreaterThan( const T t, const U u ) throw()
{
// one operand is 32 or 64-bit unsigned, and the other is signed and the same size or smaller
if( u < 0 )
return true;
// else safe to cast to type T
return ( t > (T)u );
}
};
template < typename T, typename U > class GreaterThanTest< T, U, ComparisonMethod_UnsignedU >
{
public:
static bool GreaterThan( const T t, const U u ) throw()
{
// one operand is 32 or 64-bit unsigned, and the other is signed and the same size or smaller
if( t < 0 )
return false;
// else safe to cast to type U
return ( (U)t > u );
}
};
// Modulus is simpler than comparison, but follows much the same logic
// using this set of functions, it can't fail except in a div 0 situation
template <typename T, typename U, int method > class ModulusHelper;
template <typename T, typename U> class ModulusHelper <T, U, ComparisonMethod_Ok>
{
public:
static SafeIntError Modulus( const T& t, const U& u, T& result ) throw()
{
if(u == 0)
return SafeIntDivideByZero;
//trap corner case
if( IntTraits< U >::isSigned )
{
if(u == -1)
{
result = 0;
return SafeIntNoError;
}
}
result = (T)(t % u);
return SafeIntNoError;
}
template < typename E >
static void ModulusThrow( const T& t, const U& u, T& result )
{
if(u == 0)
E::SafeIntOnDivZero();
//trap corner case
if( IntTraits< U >::isSigned )
{
if(u == -1)
{
result = 0;
return;
}
}
result = (T)(t % u);
}
};
template <typename T, typename U> class ModulusHelper <T, U, ComparisonMethod_CastInt>
{
public:
static SafeIntError Modulus( const T& t, const U& u, T& result ) throw()
{
if(u == 0)
return SafeIntDivideByZero;
//trap corner case
if( IntTraits< U >::isSigned )
{
if(u == -1)
{
result = 0;
return SafeIntNoError;
}
}
result = (T)(t % u);
return SafeIntNoError;
}
template < typename E >
static void ModulusThrow( const T& t, const U& u, T& result )
{
if(u == 0)
E::SafeIntOnDivZero();
//trap corner case
if( IntTraits< U >::isSigned )
{
if(u == -1)
{
result = 0;
return;
}
}
result = (T)(t % u);
}
};
template < typename T, typename U > class ModulusHelper< T, U, ComparisonMethod_CastInt64>
{
public:
static SafeIntError Modulus( const T& t, const U& u, T& result ) throw()
{
if(u == 0)
return SafeIntDivideByZero;
if(IntTraits< U >::isSigned && u == -1)
result = 0;
else
result = (T)((__int64)t % (__int64)u);
return SafeIntNoError;
}
template < typename E >
static void ModulusThrow( const T& t, const U& u, T& result )
{
if(u == 0)
E::SafeIntOnDivZero();
if(IntTraits< U >::isSigned && u == -1)
result = 0;
else
result = (T)((__int64)t % (__int64)u);
}
};
// T is unsigned __int64, U is any signed int
template < typename T, typename U > class ModulusHelper< T, U, ComparisonMethod_UnsignedT>
{
public:
static SafeIntError Modulus( const T& t, const U& u, T& result ) throw()
{
if(u == 0)
return SafeIntDivideByZero;
// u could be negative - if so, need to convert to positive
// casts below are always safe due to the way modulus works
if(u < 0)
result = (T)(t % AbsValueHelper< U, GetAbsMethod< U >::method >::Abs(u));
else
result = (T)(t % u);
return SafeIntNoError;
}
template < typename E >
static void ModulusThrow( const T& t, const U& u, T& result )
{
if(u == 0)
E::SafeIntOnDivZero();
// u could be negative - if so, need to convert to positive
if(u < 0)
result = (T)(t % AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( u ));
else
result = (T)(t % u);
}
};
// U is unsigned __int64, T any signed int
template < typename T, typename U > class ModulusHelper< T, U, ComparisonMethod_UnsignedU>
{
public:
static SafeIntError Modulus( const T& t, const U& u, T& result ) throw()
{
if(u == 0)
return SafeIntDivideByZero;
//t could be negative - if so, need to convert to positive
if(t < 0)
result = -(T)( AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( t ) % u );
else
result = (T)((T)t % u);
return SafeIntNoError;
}
template < typename E >
static void ModulusThrow( const T& t, const U& u, T& result )
{
if(u == 0)
E::SafeIntOnDivZero();
//t could be negative - if so, need to convert to positive
if(t < 0)
result = -(T)( AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( t ) % u );
else
result = (T)( (T)t % u );
}
};
//core logic to determine method to check multiplication
enum MultiplicationState
{
MultiplicationState_CastInt = 0, // One or both signed, smaller than 32-bit
MultiplicationState_CastInt64, // One or both signed, smaller than 64-bit
MultiplicationState_CastUint, // Both are unsigned, smaller than 32-bit
MultiplicationState_CastUint64, // Both are unsigned, both 32-bit or smaller
MultiplicationState_Uint64Uint, // Both are unsigned, lhs 64-bit, rhs 32-bit or smaller
MultiplicationState_Uint64Uint64, // Both are unsigned int64
MultiplicationState_Uint64Int, // lhs is unsigned int64, rhs int32
MultiplicationState_Uint64Int64, // lhs is unsigned int64, rhs signed int64
MultiplicationState_UintUint64, // Both are unsigned, lhs 32-bit or smaller, rhs 64-bit
MultiplicationState_UintInt64, // lhs unsigned 32-bit or less, rhs int64
MultiplicationState_Int64Uint, // lhs int64, rhs unsigned int32
MultiplicationState_Int64Int64, // lhs int64, rhs int64
MultiplicationState_Int64Int, // lhs int64, rhs int32
MultiplicationState_IntUint64, // lhs int, rhs unsigned int64
MultiplicationState_IntInt64, // lhs int, rhs int64
MultiplicationState_Int64Uint64, // lhs int64, rhs uint64
MultiplicationState_Error
};
template < typename T, typename U >
class MultiplicationMethod
{
public:
enum
{
// unsigned-unsigned
method = (IntRegion< T,U >::IntZone_UintLT32_UintLT32 ? MultiplicationState_CastUint :
(IntRegion< T,U >::IntZone_Uint32_UintLT64 ||
IntRegion< T,U >::IntZone_UintLT32_Uint32) ? MultiplicationState_CastUint64 :
SafeIntCompare< T,U >::isBothUnsigned &&
IntTraits< T >::isUint64 && IntTraits< U >::isUint64 ? MultiplicationState_Uint64Uint64 :
(IntRegion< T,U >::IntZone_Uint64_Uint) ? MultiplicationState_Uint64Uint :
(IntRegion< T,U >::IntZone_UintLT64_Uint64) ? MultiplicationState_UintUint64 :
// unsigned-signed
(IntRegion< T,U >::IntZone_UintLT32_IntLT32) ? MultiplicationState_CastInt :
(IntRegion< T,U >::IntZone_Uint32_IntLT64 ||
IntRegion< T,U >::IntZone_UintLT32_Int32) ? MultiplicationState_CastInt64 :
(IntRegion< T,U >::IntZone_Uint64_Int) ? MultiplicationState_Uint64Int :
(IntRegion< T,U >::IntZone_UintLT64_Int64) ? MultiplicationState_UintInt64 :
(IntRegion< T,U >::IntZone_Uint64_Int64) ? MultiplicationState_Uint64Int64 :
// signed-signed
(IntRegion< T,U >::IntZone_IntLT32_IntLT32) ? MultiplicationState_CastInt :
(IntRegion< T,U >::IntZone_Int32_IntLT64 ||
IntRegion< T,U >::IntZone_IntLT32_Int32) ? MultiplicationState_CastInt64 :
(IntRegion< T,U >::IntZone_Int64_Int64) ? MultiplicationState_Int64Int64 :
(IntRegion< T,U >::IntZone_Int64_Int) ? MultiplicationState_Int64Int :
(IntRegion< T,U >::IntZone_IntLT64_Int64) ? MultiplicationState_IntInt64 :
// signed-unsigned
(IntRegion< T,U >::IntZone_IntLT32_UintLT32) ? MultiplicationState_CastInt :
(IntRegion< T,U >::IntZone_Int32_UintLT32 ||
IntRegion< T,U >::IntZone_IntLT64_Uint32) ? MultiplicationState_CastInt64 :
(IntRegion< T,U >::IntZone_Int64_UintLT64) ? MultiplicationState_Int64Uint :
(IntRegion< T,U >::IntZone_Int_Uint64) ? MultiplicationState_IntUint64 :
(IntRegion< T,U >::IntZone_Int64_Uint64 ? MultiplicationState_Int64Uint64 :
MultiplicationState_Error ) )
};
};
template <typename T, typename U, int state> class MultiplicationHelper;
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_CastInt>
{
public:
//accepts signed, both less than 32-bit
static bool Multiply( const T& t, const U& u, T& ret ) throw()
{
int tmp = t * u;
if( tmp > IntTraits< T >::maxInt || tmp < IntTraits< T >::minInt )
return false;
ret = (T)tmp;
return true;
}
template < typename E >
static void MultiplyThrow( const T& t, const U& u, T& ret )
{
int tmp = t * u;
if( tmp > IntTraits< T >::maxInt || tmp < IntTraits< T >::minInt )
E::SafeIntOnOverflow();
ret = (T)tmp;
}
};
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_CastUint >
{
public:
//accepts unsigned, both less than 32-bit
static bool Multiply( const T& t, const U& u, T& ret ) throw()
{
unsigned int tmp = t * u;
if( tmp > IntTraits< T >::maxInt )
return false;
ret = (T)tmp;
return true;
}
template < typename E >
static void MultiplyThrow( const T& t, const U& u, T& ret )
{
unsigned int tmp = t * u;
if( tmp > IntTraits< T >::maxInt )
E::SafeIntOnOverflow();
ret = (T)tmp;
}
};
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_CastInt64>
{
public:
//mixed signed or both signed where at least one argument is 32-bit, and both a 32-bit or less
static bool Multiply( const T& t, const U& u, T& ret ) throw()
{
__int64 tmp = (__int64)t * (__int64)u;
if(tmp > (__int64)IntTraits< T >::maxInt || tmp < (__int64)IntTraits< T >::minInt)
return false;
ret = (T)tmp;
return true;
}
template < typename E >
static void MultiplyThrow( const T& t, const U& u, T& ret )
{
__int64 tmp = (__int64)t * (__int64)u;
if(tmp > (__int64)IntTraits< T >::maxInt || tmp < (__int64)IntTraits< T >::minInt)
E::SafeIntOnOverflow();
ret = (T)tmp;
}
};
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_CastUint64>
{
public:
//both unsigned where at least one argument is 32-bit, and both are 32-bit or less
static bool Multiply( const T& t, const U& u, T& ret ) throw()
{
unsigned __int64 tmp = (unsigned __int64)t * (unsigned __int64)u;
if(tmp > (unsigned __int64)IntTraits< T >::maxInt)
return false;
ret = (T)tmp;
return true;
}
template < typename E >
static void MultiplyThrow( const T& t, const U& u, T& ret )
{
unsigned __int64 tmp = (unsigned __int64)t * (unsigned __int64)u;
if(tmp > (unsigned __int64)IntTraits< T >::maxInt)
E::SafeIntOnOverflow();
ret = (T)tmp;
}
};
// T = left arg and return type
// U = right arg
template < typename T, typename U > class LargeIntRegMultiply;
template<> class LargeIntRegMultiply< unsigned __int64, unsigned __int64 >
{
public:
static bool RegMultiply( const unsigned __int64& a, const unsigned __int64& b, unsigned __int64& ret ) throw()
{
unsigned __int32 aHigh, aLow, bHigh, bLow;
// Consider that a*b can be broken up into:
// (aHigh * 2^32 + aLow) * (bHigh * 2^32 + bLow)
// => (aHigh * bHigh * 2^64) + (aLow * bHigh * 2^32) + (aHigh * bLow * 2^32) + (aLow * bLow)
// Note - same approach applies for 128 bit math on a 64-bit system
aHigh = (unsigned __int32)(a >> 32);
aLow = (unsigned __int32)a;
bHigh = (unsigned __int32)(b >> 32);
bLow = (unsigned __int32)b;
ret = 0;
if(aHigh == 0)
{
if(bHigh != 0)
{
ret = (unsigned __int64)aLow * (unsigned __int64)bHigh;
}
}
else if(bHigh == 0)
{
if(aHigh != 0)
{
ret = (unsigned __int64)aHigh * (unsigned __int64)bLow;
}
}
else
{
return false;
}
if(ret != 0)
{
unsigned __int64 tmp;
if((unsigned __int32)(ret >> 32) != 0)
return false;
ret <<= 32;
tmp = (unsigned __int64)aLow * (unsigned __int64)bLow;
ret += tmp;
if(ret < tmp)
return false;
return true;
}
ret = (unsigned __int64)aLow * (unsigned __int64)bLow;
return true;
}
template < typename E >
static void RegMultiplyThrow( const unsigned __int64& a, const unsigned __int64& b, unsigned __int64& ret )
{
unsigned __int32 aHigh, aLow, bHigh, bLow;
// Consider that a*b can be broken up into:
// (aHigh * 2^32 + aLow) * (bHigh * 2^32 + bLow)
// => (aHigh * bHigh * 2^64) + (aLow * bHigh * 2^32) + (aHigh * bLow * 2^32) + (aLow * bLow)
// Note - same approach applies for 128 bit math on a 64-bit system
aHigh = (unsigned __int32)(a >> 32);
aLow = (unsigned __int32)a;
bHigh = (unsigned __int32)(b >> 32);
bLow = (unsigned __int32)b;
ret = 0;
if(aHigh == 0)
{
if(bHigh != 0)
{
ret = (unsigned __int64)aLow * (unsigned __int64)bHigh;
}
}
else if(bHigh == 0)
{
if(aHigh != 0)
{
ret = (unsigned __int64)aHigh * (unsigned __int64)bLow;
}
}
else
{
E::SafeIntOnOverflow();
}
if(ret != 0)
{
unsigned __int64 tmp;
if((unsigned __int32)(ret >> 32) != 0)
E::SafeIntOnOverflow();
ret <<= 32;
tmp = (unsigned __int64)aLow * (unsigned __int64)bLow;
ret += tmp;
if(ret < tmp)
E::SafeIntOnOverflow();
return;
}
ret = (unsigned __int64)aLow * (unsigned __int64)bLow;
}
};
template<> class LargeIntRegMultiply< unsigned __int64, unsigned __int32 >
{
public:
static bool RegMultiply( const unsigned __int64& a, unsigned __int32 b, unsigned __int64& ret ) throw()
{
unsigned __int32 aHigh, aLow;
// Consider that a*b can be broken up into:
// (aHigh * 2^32 + aLow) * b
// => (aHigh * b * 2^32) + (aLow * b)
aHigh = (unsigned __int32)(a >> 32);
aLow = (unsigned __int32)a;
ret = 0;
if(aHigh != 0)
{
ret = (unsigned __int64)aHigh * (unsigned __int64)b;
unsigned __int64 tmp;
if((unsigned __int32)(ret >> 32) != 0)
return false;
ret <<= 32;
tmp = (unsigned __int64)aLow * (unsigned __int64)b;
ret += tmp;
if(ret < tmp)
return false;
return true;
}
ret = (unsigned __int64)aLow * (unsigned __int64)b;
return true;
}
template < typename E >
static void RegMultiplyThrow( const unsigned __int64& a, unsigned __int32 b, unsigned __int64& ret )
{
unsigned __int32 aHigh, aLow;
// Consider that a*b can be broken up into:
// (aHigh * 2^32 + aLow) * b
// => (aHigh * b * 2^32) + (aLow * b)
aHigh = (unsigned __int32)(a >> 32);
aLow = (unsigned __int32)a;
ret = 0;
if(aHigh != 0)
{
ret = (unsigned __int64)aHigh * (unsigned __int64)b;
unsigned __int64 tmp;
if((unsigned __int32)(ret >> 32) != 0)
E::SafeIntOnOverflow();
ret <<= 32;
tmp = (unsigned __int64)aLow * (unsigned __int64)b;
ret += tmp;
if(ret < tmp)
E::SafeIntOnOverflow();
return;
}
ret = (unsigned __int64)aLow * (unsigned __int64)b;
return;
}
};
template<> class LargeIntRegMultiply< unsigned __int64, signed __int32 >
{
public:
static bool RegMultiply( const unsigned __int64& a, signed __int32 b, unsigned __int64& ret ) throw()
{
if( b < 0 && a != 0 )
return false;
return LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::RegMultiply(a, (unsigned __int32)b, ret);
}
template < typename E >
static void RegMultiplyThrow( const unsigned __int64& a, signed __int32 b, unsigned __int64& ret )
{
if( b < 0 && a != 0 )
E::SafeIntOnOverflow();
LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::template RegMultiplyThrow< E >( a, (unsigned __int32)b, ret );
}
};
template<> class LargeIntRegMultiply< unsigned __int64, signed __int64 >
{
public:
static bool RegMultiply( const unsigned __int64& a, signed __int64 b, unsigned __int64& ret ) throw()
{
if( b < 0 && a != 0 )
return false;
return LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::RegMultiply(a, (unsigned __int64)b, ret);
}
template < typename E >
static void RegMultiplyThrow( const unsigned __int64& a, signed __int64 b, unsigned __int64& ret )
{
if( b < 0 && a != 0 )
E::SafeIntOnOverflow();
LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::template RegMultiplyThrow< E >( a, (unsigned __int64)b, ret );
}
};
template<> class LargeIntRegMultiply< signed __int32, unsigned __int64 >
{
public:
static bool RegMultiply( signed __int32 a, const unsigned __int64& b, signed __int32& ret ) throw()
{
signed __int32 bHigh, bLow;
bool fIsNegative = false;
// Consider that a*b can be broken up into:
// (aHigh * 2^32 + aLow) * (bHigh * 2^32 + bLow)
// => (aHigh * bHigh * 2^64) + (aLow * bHigh * 2^32) + (aHigh * bLow * 2^32) + (aLow * bLow)
bHigh = (unsigned __int32)(b >> 32);
bLow = (unsigned __int32)b;
ret = 0;
if(bHigh != 0 && a != 0)
return false;
if( a < 0 )
{
a = -a;
fIsNegative = true;
}
unsigned __int64 tmp = (unsigned __int32)a * (unsigned __int64)bLow;
if( !fIsNegative )
{
if( tmp <= (unsigned __int64)IntTraits< signed __int32 >::maxInt )
{
ret = (signed __int32)tmp;
return true;
}
}
else
{
if( tmp <= (unsigned __int64)IntTraits< signed __int32 >::maxInt+1 )
{
ret = -( (signed __int32)tmp );
return true;
}
}
return false;
}
template < typename E >
static void RegMultiplyThrow( signed __int32 a, const unsigned __int64& b, signed __int32& ret )
{
signed __int32 bHigh, bLow;
bool fIsNegative = false;
// Consider that a*b can be broken up into:
// (aHigh * 2^32 + aLow) * (bHigh * 2^32 + bLow)
// => (aHigh * bHigh * 2^64) + (aLow * bHigh * 2^32) + (aHigh * bLow * 2^32) + (aLow * bLow)
bHigh = (signed __int32)(b >> 32);
bLow = (signed __int32)b;
ret = 0;
if(bHigh != 0 && a != 0)
E::SafeIntOnOverflow();
if( a < 0 )
{
a = -a;
fIsNegative = true;
}
unsigned __int64 tmp = (unsigned __int32)a * (unsigned __int64)bLow;
if( !fIsNegative )
{
if( tmp <= (unsigned __int64)IntTraits< signed __int32 >::maxInt )
{
ret = (signed __int32)tmp;
return;
}
}
else
{
if( tmp <= (unsigned __int64)IntTraits< signed __int32 >::maxInt+1 )
{
ret = -( (signed __int32)tmp );
return;
}
}
E::SafeIntOnOverflow();
}
};
template<> class LargeIntRegMultiply< unsigned __int32, unsigned __int64 >
{
public:
static bool RegMultiply( unsigned __int32 a, const unsigned __int64& b, unsigned __int32& ret ) throw()
{
// Consider that a*b can be broken up into:
// (bHigh * 2^32 + bLow) * a
// => (bHigh * a * 2^32) + (bLow * a)
// In this case, the result must fit into 32-bits
// If bHigh != 0 && a != 0, immediate error.
if( (unsigned __int32)(b >> 32) != 0 && a != 0 )
return false;
unsigned __int64 tmp = b * (unsigned __int64)a;
if( (unsigned __int32)(tmp >> 32) != 0 ) // overflow
return false;
ret = (unsigned __int32)tmp;
return true;
}
template < typename E >
static void RegMultiplyThrow( unsigned __int32 a, const unsigned __int64& b, unsigned __int32& ret )
{
if( (unsigned __int32)(b >> 32) != 0 && a != 0 )
E::SafeIntOnOverflow();
unsigned __int64 tmp = b * (unsigned __int64)a;
if( (unsigned __int32)(tmp >> 32) != 0 ) // overflow
E::SafeIntOnOverflow();
ret = (unsigned __int32)tmp;
}
};
template<> class LargeIntRegMultiply< unsigned __int32, signed __int64 >
{
public:
static bool RegMultiply( unsigned __int32 a, const signed __int64& b, unsigned __int32& ret ) throw()
{
if( b < 0 && a != 0 )
return false;
return LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::RegMultiply( a, (unsigned __int64)b, ret );
}
template < typename E >
static void RegMultiplyThrow( unsigned __int32 a, const signed __int64& b, unsigned __int32& ret )
{
if( b < 0 && a != 0 )
E::SafeIntOnOverflow();
LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::template RegMultiplyThrow< E >( a, (unsigned __int64)b, ret );
}
};
template<> class LargeIntRegMultiply< signed __int64, signed __int64 >
{
public:
static bool RegMultiply( const signed __int64& a, const signed __int64& b, signed __int64& ret ) throw()
{
bool aNegative = false;
bool bNegative = false;
unsigned __int64 tmp;
__int64 a1 = a;
__int64 b1 = b;
if( a1 < 0 )
{
aNegative = true;
a1 = -a1;
}
if( b1 < 0 )
{
bNegative = true;
b1 = -b1;
}
if( LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::RegMultiply( (unsigned __int64)a1, (unsigned __int64)b1, tmp ) )
{
// The unsigned multiplication didn't overflow
if( aNegative ^ bNegative )
{
// Result must be negative
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt )
{
ret = -(signed __int64)tmp;
return true;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt )
{
ret = (signed __int64)tmp;
return true;
}
}
}
return false;
}
template < typename E >
static void RegMultiplyThrow( const signed __int64& a, const signed __int64& b, signed __int64& ret )
{
bool aNegative = false;
bool bNegative = false;
unsigned __int64 tmp;
__int64 a1 = a;
__int64 b1 = b;
if( a1 < 0 )
{
aNegative = true;
a1 = -a1;
}
if( b1 < 0 )
{
bNegative = true;
b1 = -b1;
}
LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::template RegMultiplyThrow< E >( (unsigned __int64)a1, (unsigned __int64)b1, tmp );
// The unsigned multiplication didn't overflow or we'd be in the exception handler
if( aNegative ^ bNegative )
{
// Result must be negative
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt )
{
ret = -(signed __int64)tmp;
return;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt )
{
ret = (signed __int64)tmp;
return;
}
}
E::SafeIntOnOverflow();
}
};
template<> class LargeIntRegMultiply< signed __int64, unsigned __int32 >
{
public:
static bool RegMultiply( const signed __int64& a, unsigned __int32 b, signed __int64& ret ) throw()
{
bool aNegative = false;
unsigned __int64 tmp;
__int64 a1 = a;
if( a1 < 0 )
{
aNegative = true;
a1 = -a1;
}
if( LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::RegMultiply( (unsigned __int64)a1, b, tmp ) )
{
// The unsigned multiplication didn't overflow
if( aNegative )
{
// Result must be negative
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt )
{
ret = -(signed __int64)tmp;
return true;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt )
{
ret = (signed __int64)tmp;
return true;
}
}
}
return false;
}
template < typename E >
static void RegMultiplyThrow( const signed __int64& a, unsigned __int32 b, signed __int64& ret )
{
bool aNegative = false;
unsigned __int64 tmp;
__int64 a1 = a;
if( a1 < 0 )
{
aNegative = true;
a1 = -a1;
}
LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::template RegMultiplyThrow< E >( (unsigned __int64)a1, b, tmp );
// The unsigned multiplication didn't overflow
if( aNegative )
{
// Result must be negative
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt )
{
ret = -(signed __int64)tmp;
return;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt )
{
ret = (signed __int64)tmp;
return;
}
}
E::SafeIntOnOverflow();
}
};
template<> class LargeIntRegMultiply< signed __int64, signed __int32 >
{
public:
static bool RegMultiply( const signed __int64& a, signed __int32 b, signed __int64& ret ) throw()
{
bool aNegative = false;
bool bNegative = false;
unsigned __int64 tmp;
__int64 a1 = a;
__int64 b1 = b;
if( a1 < 0 )
{
aNegative = true;
a1 = -a1;
}
if( b1 < 0 )
{
bNegative = true;
b1 = -b1;
}
if( LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::RegMultiply( (unsigned __int64)a1, (unsigned __int32)b1, tmp ) )
{
// The unsigned multiplication didn't overflow
if( aNegative ^ bNegative )
{
// Result must be negative
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt )
{
ret = -(signed __int64)tmp;
return true;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt )
{
ret = (signed __int64)tmp;
return true;
}
}
}
return false;
}
template < typename E >
static void RegMultiplyThrow( signed __int64 a, signed __int32 b, signed __int64& ret )
{
bool aNegative = false;
bool bNegative = false;
unsigned __int64 tmp;
if( a < 0 )
{
aNegative = true;
a = -a;
}
if( b < 0 )
{
bNegative = true;
b = -b;
}
LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::template RegMultiplyThrow< E >( (unsigned __int64)a, (unsigned __int32)b, tmp );
// The unsigned multiplication didn't overflow
if( aNegative ^ bNegative )
{
// Result must be negative
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt )
{
ret = -(signed __int64)tmp;
return;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt )
{
ret = (signed __int64)tmp;
return;
}
}
E::SafeIntOnOverflow();
}
};
template<> class LargeIntRegMultiply< signed __int32, signed __int64 >
{
public:
static bool RegMultiply( signed __int32 a, const signed __int64& b, signed __int32& ret ) throw()
{
bool aNegative = false;
bool bNegative = false;
unsigned __int32 tmp;
__int64 b1 = b;
if( a < 0 )
{
aNegative = true;
a = -a;
}
if( b1 < 0 )
{
bNegative = true;
b1 = -b1;
}
if( LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::RegMultiply( (unsigned __int32)a, (unsigned __int64)b1, tmp ) )
{
// The unsigned multiplication didn't overflow
if( aNegative ^ bNegative )
{
// Result must be negative
if( tmp <= (unsigned __int32)IntTraits< signed __int32 >::minInt )
{
ret = -tmp;
return true;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int32)IntTraits< signed __int32 >::maxInt )
{
ret = (signed __int32)tmp;
return true;
}
}
}
return false;
}
template < typename E >
static void RegMultiplyThrow( signed __int32 a, const signed __int64& b, signed __int32& ret )
{
bool aNegative = false;
bool bNegative = false;
unsigned __int32 tmp;
signed __int64 b2 = b;
if( a < 0 )
{
aNegative = true;
a = -a;
}
if( b < 0 )
{
bNegative = true;
b2 = -b2;
}
LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::template RegMultiplyThrow< E >( (unsigned __int32)a, (unsigned __int64)b2, tmp );
// The unsigned multiplication didn't overflow
if( aNegative ^ bNegative )
{
// Result must be negative
if( tmp <= (unsigned __int32)IntTraits< signed __int32 >::minInt )
{
ret = -(signed __int32)tmp;
return;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int32)IntTraits< signed __int32 >::maxInt )
{
ret = (signed __int32)tmp;
return;
}
}
E::SafeIntOnOverflow();
}
};
template<> class LargeIntRegMultiply< signed __int64, unsigned __int64 >
{
public:
static bool RegMultiply( const signed __int64& a, const unsigned __int64& b, signed __int64& ret ) throw()
{
bool aNegative = false;
unsigned __int64 tmp;
__int64 a1 = a;
if( a1 < 0 )
{
aNegative = true;
a1 = -a1;
}
if( LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::RegMultiply( (unsigned __int64)a1, (unsigned __int64)b, tmp ) )
{
// The unsigned multiplication didn't overflow
if( aNegative )
{
// Result must be negative
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt )
{
ret = -((signed __int64)tmp);
return true;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt )
{
ret = (signed __int64)tmp;
return true;
}
}
}
return false;
}
template < typename E >
static void RegMultiplyThrow( const signed __int64& a, const unsigned __int64& b, signed __int64& ret )
{
bool aNegative = false;
unsigned __int64 tmp;
__int64 a1 = a;
if( a1 < 0 )
{
aNegative = true;
a1 = -a1;
}
if( LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::RegMultiply( (unsigned __int64)a1, (unsigned __int64)b, tmp ) )
{
// The unsigned multiplication didn't overflow
if( aNegative )
{
// Result must be negative
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt )
{
ret = -((signed __int64)tmp);
return;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt )
{
ret = (signed __int64)tmp;
return;
}
}
}
E::SafeIntOnOverflow();
}
};
template <> class MultiplicationHelper< unsigned __int64, unsigned __int64, MultiplicationState_Uint64Uint64 >
{
public:
static bool Multiply( const unsigned __int64& t, const unsigned __int64& u, unsigned __int64& ret ) throw()
{
return LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::RegMultiply( t, u, ret );
}
template < typename E >
static void MultiplyThrow(const unsigned __int64& t, const unsigned __int64& u, unsigned __int64& ret)
{
LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::template RegMultiplyThrow< E >( t, u, ret );
}
};
template < typename U > class MultiplicationHelper<unsigned __int64, U, MultiplicationState_Uint64Uint >
{
public:
//U is any unsigned int 32-bit or less
static bool Multiply( const unsigned __int64& t, const U& u, unsigned __int64& ret ) throw()
{
return LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::RegMultiply( t, (unsigned __int32)u, ret );
}
template < typename E >
static void MultiplyThrow( const unsigned __int64& t, const U& u, unsigned __int64& ret )
{
LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::template RegMultiplyThrow< E >( t, (unsigned __int32)u, ret );
}
};
// converse of the previous function
template <typename T> class MultiplicationHelper< T, unsigned __int64, MultiplicationState_UintUint64 >
{
public:
// T is any unsigned int up to 32-bit
static bool Multiply(const T& t, const unsigned __int64& u, T& ret) throw()
{
unsigned __int32 tmp;
if( LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::RegMultiply( t, u, tmp ) &&
SafeCastHelper< T, unsigned __int32, GetCastMethod< T, unsigned __int32 >::method >::Cast(tmp, ret) )
{
return true;
}
return false;
}
template < typename E >
static void MultiplyThrow(const T& t, const unsigned __int64& u, T& ret)
{
unsigned __int32 tmp;
LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::template RegMultiplyThrow< E >( t, u, tmp );
SafeCastHelper< T, unsigned __int32, GetCastMethod< T, unsigned __int32 >::method >::template CastThrow< E >(tmp, ret);
}
};
template < typename U > class MultiplicationHelper<unsigned __int64, U, MultiplicationState_Uint64Int >
{
public:
//U is any signed int, up to 64-bit
static bool Multiply(const unsigned __int64& t, const U& u, unsigned __int64& ret) throw()
{
return LargeIntRegMultiply< unsigned __int64, signed __int32 >::RegMultiply(t, (signed __int32)u, ret);
}
template < typename E >
static void MultiplyThrow(const unsigned __int64& t, const U& u, unsigned __int64& ret)
{
LargeIntRegMultiply< unsigned __int64, signed __int32 >::template RegMultiplyThrow< E >(t, (signed __int32)u, ret);
}
};
template < > class MultiplicationHelper<unsigned __int64, __int64, MultiplicationState_Uint64Int64 >
{
public:
static bool Multiply(const unsigned __int64& t, const __int64& u, unsigned __int64& ret) throw()
{
return LargeIntRegMultiply< unsigned __int64, __int64 >::RegMultiply(t, u, ret);
}
template < typename E >
static void MultiplyThrow(const unsigned __int64& t, const __int64& u, unsigned __int64& ret)
{
LargeIntRegMultiply< unsigned __int64, __int64 >::template RegMultiplyThrow< E >(t, u, ret);
}
};
template <typename T> class MultiplicationHelper< T, __int64, MultiplicationState_UintInt64 >
{
public:
//T is unsigned up to 32-bit
static bool Multiply(const T& t, const __int64& u, T& ret) throw()
{
unsigned __int32 tmp;
if( LargeIntRegMultiply< unsigned __int32, __int64 >::RegMultiply( (unsigned __int32)t, u, tmp ) &&
SafeCastHelper< T, unsigned __int32, GetCastMethod< T, unsigned __int32 >::method >::Cast(tmp, ret) )
{
return true;
}
return false;
}
template < typename E >
static void MultiplyThrow(const T& t, const __int64& u, T& ret)
{
unsigned __int32 tmp;
LargeIntRegMultiply< unsigned __int32, __int64 >::template RegMultiplyThrow< E >( (unsigned __int32)t, u, tmp );
SafeCastHelper< T, unsigned __int32, GetCastMethod< T, unsigned __int32 >::method >::template CastThrow< E >(tmp, ret);
}
};
template < typename U > class MultiplicationHelper<__int64, U, MultiplicationState_Int64Uint >
{
public:
//U is unsigned up to 32-bit
static bool Multiply( const __int64& t, const U& u, __int64& ret ) throw()
{
return LargeIntRegMultiply< __int64, unsigned __int32 >::RegMultiply( t, (unsigned __int32)u, ret );
}
template < typename E >
static void MultiplyThrow( const __int64& t, const U& u, __int64& ret )
{
LargeIntRegMultiply< __int64, unsigned __int32 >::template RegMultiplyThrow< E >(t, (unsigned __int32)u, ret);
}
};
template <> class MultiplicationHelper<__int64, __int64, MultiplicationState_Int64Int64 >
{
public:
static bool Multiply( const __int64& t, const __int64& u, __int64& ret ) throw()
{
return LargeIntRegMultiply< __int64, __int64 >::RegMultiply( t, u, ret );
}
template < typename E >
static void MultiplyThrow( const __int64& t, const __int64& u, __int64& ret )
{
LargeIntRegMultiply< __int64, __int64 >::template RegMultiplyThrow< E >(t, u, ret);
}
};
template < typename U > class MultiplicationHelper<__int64, U, MultiplicationState_Int64Int>
{
public:
//U is signed up to 32-bit
static bool Multiply( const __int64& t, U u, __int64& ret ) throw()
{
return LargeIntRegMultiply< __int64, __int32 >::RegMultiply( t, (__int32)u, ret );
}
template < typename E >
static void MultiplyThrow( const __int64& t, U u, __int64& ret )
{
LargeIntRegMultiply< __int64, __int32 >::template RegMultiplyThrow< E >(t, (__int32)u, ret);
}
};
template <typename T> class MultiplicationHelper< T, unsigned __int64, MultiplicationState_IntUint64 >
{
public:
//T is signed up to 32-bit
static bool Multiply(T t, const unsigned __int64& u, T& ret) throw()
{
__int32 tmp;
if( LargeIntRegMultiply< __int32, unsigned __int64 >::RegMultiply( (__int32)t, u, tmp ) &&
SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::Cast( tmp, ret ) )
{
return true;
}
return false;
}
template < typename E >
static void MultiplyThrow(T t, const unsigned __int64& u, T& ret)
{
__int32 tmp;
LargeIntRegMultiply< __int32, unsigned __int64 >::template RegMultiplyThrow< E >( (__int32)t, u, tmp );
SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::template CastThrow< E >( tmp, ret );
}
};
template <> class MultiplicationHelper<__int64, unsigned __int64, MultiplicationState_Int64Uint64>
{
public:
//U is signed up to 32-bit
static bool Multiply( const __int64& t, const unsigned __int64& u, __int64& ret ) throw()
{
return LargeIntRegMultiply< __int64, unsigned __int64 >::RegMultiply( t, u, ret );
}
template < typename E >
static void MultiplyThrow( const __int64& t, const unsigned __int64& u, __int64& ret )
{
LargeIntRegMultiply< __int64, unsigned __int64 >::template RegMultiplyThrow< E >( t, u, ret );
}
};
template <typename T> class MultiplicationHelper< T, __int64, MultiplicationState_IntInt64>
{
public:
//T is signed, up to 32-bit
static bool Multiply( T t, const __int64& u, T& ret ) throw()
{
__int32 tmp;
if( LargeIntRegMultiply< __int32, __int64 >::RegMultiply( (__int32)t, u, tmp ) &&
SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::Cast( tmp, ret ) )
{
return true;
}
return false;
}
template < typename E >
static void MultiplyThrow(T t, const __int64& u, T& ret)
{
__int32 tmp;
LargeIntRegMultiply< __int32, __int64 >::template RegMultiplyThrow< E >( (__int32)t, u, tmp );
SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::template CastThrow< E >( tmp, ret );
}
};
enum DivisionState
{
DivisionState_OK,
DivisionState_UnsignedSigned,
DivisionState_SignedUnsigned32,
DivisionState_SignedUnsigned64,
DivisionState_SignedUnsigned,
DivisionState_SignedSigned
};
template < typename T, typename U > class DivisionMethod
{
public:
enum
{
method = (SafeIntCompare< T, U >::isBothUnsigned ? DivisionState_OK :
(!IntTraits< T >::isSigned && IntTraits< U >::isSigned) ? DivisionState_UnsignedSigned :
(IntTraits< T >::isSigned &&
IntTraits< U >::isUint32 &&
IntTraits< T >::isLT64Bit) ? DivisionState_SignedUnsigned32 :
(IntTraits< T >::isSigned && IntTraits< U >::isUint64) ? DivisionState_SignedUnsigned64 :
(IntTraits< T >::isSigned && !IntTraits< U >::isSigned) ? DivisionState_SignedUnsigned :
DivisionState_SignedSigned)
};
};
template < typename T, typename U, int state > class DivisionHelper;
template < typename T, typename U > class DivisionHelper< T, U, DivisionState_OK >
{
public:
static SafeIntError Divide( const T& t, const U& u, T& result ) throw()
{
if( t == 0 )
{
result = 0;
return SafeIntNoError;
}
if( u == 0 )
return SafeIntDivideByZero;
result = (T)( t/u );
return SafeIntNoError;
}
template < typename E >
static void DivideThrow( const T& t, const U& u, T& result )
{
if( t == 0 )
{
result = 0;
return;
}
if( u == 0 )
E::SafeIntOnDivZero();
result = (T)( t/u );
}
};
template < typename T, typename U > class DivisionHelper< T, U, DivisionState_UnsignedSigned>
{
public:
static SafeIntError Divide( const T& t, const U& u, T& result ) throw()
{
if( t == 0 )
{
result = 0;
return SafeIntNoError;
}
if( u > 0 )
{
result = (T)( t/u );
return SafeIntNoError;
}
if( u == 0 )
return SafeIntDivideByZero;
// it is always an error to try and divide an unsigned number by a negative signed number
// unless u is bigger than t
if( AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( u ) > t )
{
result = 0;
return SafeIntNoError;
}
return SafeIntArithmeticOverflow;
}
template < typename E >
static void DivideThrow( const T& t, const U& u, T& result )
{
if( t == 0 )
{
result = 0;
return;
}
if( u > 0 )
{
result = (T)( t/u );
return;
}
if( u == 0 )
E::SafeIntOnDivZero();
// it is always an error to try and divide an unsigned number by a negative signed number
// unless u is bigger than t
if( AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( u ) > t )
{
result = 0;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class DivisionHelper< T, U, DivisionState_SignedUnsigned32 >
{
public:
static SafeIntError Divide( const T& t, const U& u, T& result ) throw()
{
if( t == 0 )
{
result = 0;
return SafeIntNoError;
}
if( u == 0 )
return SafeIntDivideByZero;
// Test for t > 0
// If t < 0, must explicitly upcast, or implicit upcast to ulong will cause errors
// As it turns out, 32-bit division is about twice as fast, which justifies the extra conditional
if( t > 0 )
result = (T)( t/u );
else
result = (T)( (__int64)t/(__int64)u );
return SafeIntNoError;
}
template < typename E >
static void DivideThrow( const T& t, const U& u, T& result )
{
if( t == 0 )
{
result = 0;
return;
}
if( u == 0 )
{
E::SafeIntOnDivZero();
}
// Test for t > 0
// If t < 0, must explicitly upcast, or implicit upcast to ulong will cause errors
// As it turns out, 32-bit division is about twice as fast, which justifies the extra conditional
if( t > 0 )
result = (T)( t/u );
else
result = (T)( (__int64)t/(__int64)u );
}
};
template < typename T > class DivisionHelper< T, unsigned __int64, DivisionState_SignedUnsigned64 >
{
public:
static SafeIntError Divide( const T& t, const unsigned __int64& u, T& result ) throw()
{
if( t == 0 )
{
result = 0;
return SafeIntNoError;
}
if( u == 0 )
{
return SafeIntDivideByZero;
}
if( u <= (unsigned __int64)IntTraits< T >::maxInt )
{
// Else u can safely be cast to T
if( sizeof( T ) < sizeof( __int64 ) )
result = (T)( (int)t/(int)u );
else
result = (T)((__int64)t/(__int64)u);
}
else // Corner case
if( t == IntTraits< T >::minInt && u == (unsigned __int64)IntTraits< T >::minInt )
{
// Min int divided by it's own magnitude is -1
result = -1;
}
else
{
result = 0;
}
return SafeIntNoError;
}
template < typename E >
static void DivideThrow( const T& t, const unsigned __int64& u, T& result )
{
if( t == 0 )
{
result = 0;
return;
}
if( u == 0 )
{
E::SafeIntOnDivZero();
}
if( u <= (unsigned __int64)IntTraits< T >::maxInt )
{
// Else u can safely be cast to T
if( sizeof( T ) < sizeof( __int64 ) )
result = (T)( (int)t/(int)u );
else
result = (T)((__int64)t/(__int64)u);
}
else // Corner case
if( t == IntTraits< T >::minInt && u == (unsigned __int64)IntTraits< T >::minInt )
{
// Min int divided by it's own magnitude is -1
result = -1;
}
else
{
result = 0;
}
}
};
template < typename T, typename U > class DivisionHelper< T, U, DivisionState_SignedUnsigned>
{
public:
// T is any signed, U is unsigned and smaller than 32-bit
// In this case, standard operator casting is correct
static SafeIntError Divide( const T& t, const U& u, T& result ) throw()
{
if( t == 0 )
{
result = 0;
return SafeIntNoError;
}
if( u == 0 )
{
return SafeIntDivideByZero;
}
result = (T)( t/u );
return SafeIntNoError;
}
template < typename E >
static void DivideThrow( const T& t, const U& u, T& result )
{
if( t == 0 )
{
result = 0;
return;
}
if( u == 0 )
{
E::SafeIntOnDivZero();
}
result = (T)( t/u );
}
};
template < typename T, typename U > class DivisionHelper< T, U, DivisionState_SignedSigned>
{
public:
static SafeIntError Divide( const T& t, const U& u, T& result ) throw()
{
if( t == 0 )
{
result = 0;
return SafeIntNoError;
}
if( u == 0 )
{
return SafeIntDivideByZero;
}
// Must test for corner case
if( t == IntTraits< T >::minInt && u == -1 )
return SafeIntArithmeticOverflow;
result = (T)( t/u );
return SafeIntNoError;
}
template < typename E >
static void DivideThrow( const T& t, const U& u, T& result )
{
if( t == 0 )
{
result = 0;
return;
}
if(u == 0)
{
E::SafeIntOnDivZero();
}
// Must test for corner case
if( t == IntTraits< T >::minInt && u == -1 )
E::SafeIntOnOverflow();
result = (T)( t/u );
}
};
enum AdditionState
{
AdditionState_CastIntCheckMax,
AdditionState_CastUintCheckOverflow,
AdditionState_CastUintCheckOverflowMax,
AdditionState_CastUint64CheckOverflow,
AdditionState_CastUint64CheckOverflowMax,
AdditionState_CastIntCheckMinMax,
AdditionState_CastInt64CheckMinMax,
AdditionState_CastInt64CheckMax,
AdditionState_CastUint64CheckMinMax,
AdditionState_CastUint64CheckMinMax2,
AdditionState_CastInt64CheckOverflow,
AdditionState_CastInt64CheckOverflowMinMax,
AdditionState_CastInt64CheckOverflowMax,
AdditionState_ManualCheckInt64Uint64,
AdditionState_ManualCheck,
AdditionState_Error
};
template< typename T, typename U >
class AdditionMethod
{
public:
enum
{
//unsigned-unsigned
method = (IntRegion< T,U >::IntZone_UintLT32_UintLT32 ? AdditionState_CastIntCheckMax :
(IntRegion< T,U >::IntZone_Uint32_UintLT64) ? AdditionState_CastUintCheckOverflow :
(IntRegion< T,U >::IntZone_UintLT32_Uint32) ? AdditionState_CastUintCheckOverflowMax :
(IntRegion< T,U >::IntZone_Uint64_Uint) ? AdditionState_CastUint64CheckOverflow :
(IntRegion< T,U >::IntZone_UintLT64_Uint64) ? AdditionState_CastUint64CheckOverflowMax :
//unsigned-signed
(IntRegion< T,U >::IntZone_UintLT32_IntLT32) ? AdditionState_CastIntCheckMinMax :
(IntRegion< T,U >::IntZone_Uint32_IntLT64 ||
IntRegion< T,U >::IntZone_UintLT32_Int32) ? AdditionState_CastInt64CheckMinMax :
(IntRegion< T,U >::IntZone_Uint64_Int ||
IntRegion< T,U >::IntZone_Uint64_Int64) ? AdditionState_CastUint64CheckMinMax :
(IntRegion< T,U >::IntZone_UintLT64_Int64) ? AdditionState_CastUint64CheckMinMax2 :
//signed-signed
(IntRegion< T,U >::IntZone_IntLT32_IntLT32) ? AdditionState_CastIntCheckMinMax :
(IntRegion< T,U >::IntZone_Int32_IntLT64 ||
IntRegion< T,U >::IntZone_IntLT32_Int32) ? AdditionState_CastInt64CheckMinMax :
(IntRegion< T,U >::IntZone_Int64_Int ||
IntRegion< T,U >::IntZone_Int64_Int64) ? AdditionState_CastInt64CheckOverflow :
(IntRegion< T,U >::IntZone_IntLT64_Int64) ? AdditionState_CastInt64CheckOverflowMinMax :
//signed-unsigned
(IntRegion< T,U >::IntZone_IntLT32_UintLT32) ? AdditionState_CastIntCheckMax :
(IntRegion< T,U >::IntZone_Int32_UintLT32 ||
IntRegion< T,U >::IntZone_IntLT64_Uint32) ? AdditionState_CastInt64CheckMax :
(IntRegion< T,U >::IntZone_Int64_UintLT64) ? AdditionState_CastInt64CheckOverflowMax :
(IntRegion< T,U >::IntZone_Int64_Uint64) ? AdditionState_ManualCheckInt64Uint64 :
(IntRegion< T,U >::IntZone_Int_Uint64) ? AdditionState_ManualCheck :
AdditionState_Error)
};
};
template < typename T, typename U, int method > class AdditionHelper;
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastIntCheckMax >
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
//16-bit or less unsigned addition
__int32 tmp = lhs + rhs;
if( tmp <= (__int32)IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
//16-bit or less unsigned addition
__int32 tmp = lhs + rhs;
if( tmp <= (__int32)IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUintCheckOverflow >
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// 32-bit or less - both are unsigned
unsigned __int32 tmp = (unsigned __int32)lhs + (unsigned __int32)rhs;
//we added didn't get smaller
if( tmp >= lhs )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// 32-bit or less - both are unsigned
unsigned __int32 tmp = (unsigned __int32)lhs + (unsigned __int32)rhs;
//we added didn't get smaller
if( tmp >= lhs )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUintCheckOverflowMax>
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// 32-bit or less - both are unsigned
unsigned __int32 tmp = (unsigned __int32)lhs + (unsigned __int32)rhs;
// We added and it didn't get smaller or exceed maxInt
if( tmp >= lhs && tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
//32-bit or less - both are unsigned
unsigned __int32 tmp = (unsigned __int32)lhs + (unsigned __int32)rhs;
// We added and it didn't get smaller or exceed maxInt
if( tmp >= lhs && tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUint64CheckOverflow>
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs unsigned __int64, rhs unsigned
unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs;
// We added and it didn't get smaller
if(tmp >= lhs)
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// lhs unsigned __int64, rhs unsigned
unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs;
// We added and it didn't get smaller
if(tmp >= lhs)
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUint64CheckOverflowMax >
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
//lhs unsigned __int64, rhs unsigned
unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs;
// We added and it didn't get smaller
if( tmp >= lhs && tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
//lhs unsigned __int64, rhs unsigned
unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs;
// We added and it didn't get smaller
if( tmp >= lhs && tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastIntCheckMinMax >
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// 16-bit or less - one or both are signed
__int32 tmp = lhs + rhs;
if( tmp <= (__int32)IntTraits< T >::maxInt && tmp >= (__int32)IntTraits< T >::minInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// 16-bit or less - one or both are signed
__int32 tmp = lhs + rhs;
if( tmp <= (__int32)IntTraits< T >::maxInt && tmp >= (__int32)IntTraits< T >::minInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastInt64CheckMinMax >
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// 32-bit or less - one or both are signed
__int64 tmp = (__int64)lhs + (__int64)rhs;
if( tmp <= (__int64)IntTraits< T >::maxInt && tmp >= (__int64)IntTraits< T >::minInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// 32-bit or less - one or both are signed
__int64 tmp = (__int64)lhs + (__int64)rhs;
if( tmp <= (__int64)IntTraits< T >::maxInt && tmp >= (__int64)IntTraits< T >::minInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastInt64CheckMax >
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// 32-bit or less - lhs signed, rhs unsigned
__int64 tmp = (__int64)lhs + (__int64)rhs;
if( tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// 32-bit or less - lhs signed, rhs unsigned
__int64 tmp = (__int64)lhs + (__int64)rhs;
if( tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUint64CheckMinMax >
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is unsigned __int64, rhs signed
unsigned __int64 tmp;
if( rhs < 0 )
{
// So we're effectively subtracting
tmp = AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( rhs );
if( tmp <= lhs )
{
result = lhs - tmp;
return true;
}
}
else
{
// now we know that rhs can be safely cast into an unsigned __int64
tmp = (unsigned __int64)lhs + (unsigned __int64)rhs;
// We added and it did not become smaller
if( tmp >= lhs )
{
result = (T)tmp;
return true;
}
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is unsigned __int64, rhs signed
unsigned __int64 tmp;
if( rhs < 0 )
{
// So we're effectively subtracting
tmp = AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( rhs );
if( tmp <= lhs )
{
result = lhs - tmp;
return;
}
}
else
{
// now we know that rhs can be safely cast into an unsigned __int64
tmp = (unsigned __int64)lhs + (unsigned __int64)rhs;
// We added and it did not become smaller
if( tmp >= lhs )
{
result = (T)tmp;
return;
}
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUint64CheckMinMax2>
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is unsigned and < 64-bit, rhs signed __int64
if( rhs < 0 )
{
if( lhs >= (unsigned __int64)( -rhs ) )//negation is safe, since rhs is 64-bit
{
result = (T)( lhs + rhs );
return true;
}
}
else
{
// now we know that rhs can be safely cast into an unsigned __int64
unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs;
// special case - rhs cannot be larger than 0x7fffffffffffffff, lhs cannot be larger than 0xffffffff
// it is not possible for the operation above to overflow, so just check max
if( tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is unsigned and < 64-bit, rhs signed __int64
if( rhs < 0 )
{
if( lhs >= (unsigned __int64)( -rhs ) )//negation is safe, since rhs is 64-bit
{
result = (T)( lhs + rhs );
return;
}
}
else
{
// now we know that rhs can be safely cast into an unsigned __int64
unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs;
// special case - rhs cannot be larger than 0x7fffffffffffffff, lhs cannot be larger than 0xffffffff
// it is not possible for the operation above to overflow, so just check max
if( tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastInt64CheckOverflow>
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is signed __int64, rhs signed
__int64 tmp = (__int64)lhs + (__int64)rhs;
if( lhs >= 0 )
{
// mixed sign cannot overflow
if( rhs >= 0 && tmp < lhs )
return false;
}
else
{
// lhs negative
if( rhs < 0 && tmp > lhs )
return false;
}
result = (T)tmp;
return true;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is signed __int64, rhs signed
__int64 tmp = (__int64)lhs + (__int64)rhs;
if( lhs >= 0 )
{
// mixed sign cannot overflow
if( rhs >= 0 && tmp < lhs )
E::SafeIntOnOverflow();
}
else
{
// lhs negative
if( rhs < 0 && tmp > lhs )
E::SafeIntOnOverflow();
}
result = (T)tmp;
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastInt64CheckOverflowMinMax>
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
//rhs is signed __int64, lhs signed
__int64 tmp;
if( AdditionHelper< __int64, __int64, AdditionState_CastInt64CheckOverflow >::Addition( (__int64)lhs, (__int64)rhs, tmp ) &&
tmp <= IntTraits< T >::maxInt &&
tmp >= IntTraits< T >::minInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
//rhs is signed __int64, lhs signed
__int64 tmp;
AdditionHelper< __int64, __int64, AdditionState_CastInt64CheckOverflow >::AdditionThrow< E >( (__int64)lhs, (__int64)rhs, tmp );
if( tmp <= IntTraits< T >::maxInt &&
tmp >= IntTraits< T >::minInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastInt64CheckOverflowMax>
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
//lhs is signed __int64, rhs unsigned < 64-bit
__int64 tmp = lhs + (__int64)rhs;
if( tmp >= lhs )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
//lhs is signed __int64, rhs unsigned < 64-bit
__int64 tmp = lhs + (__int64)rhs;
if( tmp >= lhs )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < > class AdditionHelper < __int64, unsigned __int64, AdditionState_ManualCheckInt64Uint64 >
{
public:
static bool Addition( const __int64& lhs, const unsigned __int64& rhs, __int64& result ) throw()
{
// rhs is unsigned __int64, lhs __int64
__int64 tmp = lhs + (__int64)rhs;
if( tmp >= lhs )
{
result = tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const __int64& lhs, const unsigned __int64& rhs, __int64& result )
{
// rhs is unsigned __int64, lhs __int64
__int64 tmp = lhs + (__int64)rhs;
if( tmp >= lhs )
{
result = tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_ManualCheck>
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// rhs is unsigned __int64, lhs signed, 32-bit or less
if( (unsigned __int32)( rhs >> 32 ) == 0 )
{
// Now it just happens to work out that the standard behavior does what we want
// Adding explicit casts to show exactly what's happening here
__int32 tmp = (__int32)( (unsigned __int32)rhs + (unsigned __int32)lhs );
if( tmp >= lhs && SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::Cast( tmp, result ) )
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// rhs is unsigned __int64, lhs signed, 32-bit or less
if( (unsigned __int32)( rhs >> 32 ) == 0 )
{
// Now it just happens to work out that the standard behavior does what we want
// Adding explicit casts to show exactly what's happening here
__int32 tmp = (__int32)( (unsigned __int32)rhs + (unsigned __int32)lhs );
if( tmp >= lhs )
{
SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::template CastThrow< E >( tmp, result );
return;
}
}
E::SafeIntOnOverflow();
}
};
enum SubtractionState
{
SubtractionState_BothUnsigned,
SubtractionState_CastIntCheckMinMax,
SubtractionState_CastIntCheckMin,
SubtractionState_CastInt64CheckMinMax,
SubtractionState_CastInt64CheckMin,
SubtractionState_Uint64Int,
SubtractionState_UintInt64,
SubtractionState_Int64Int,
SubtractionState_IntInt64,
SubtractionState_Int64Uint,
SubtractionState_IntUint64,
SubtractionState_Int64Uint64,
// states for SubtractionMethod2
SubtractionState_BothUnsigned2,
SubtractionState_CastIntCheckMinMax2,
SubtractionState_CastInt64CheckMinMax2,
SubtractionState_Uint64Int2,
SubtractionState_UintInt642,
SubtractionState_Int64Int2,
SubtractionState_IntInt642,
SubtractionState_Int64Uint2,
SubtractionState_IntUint642,
SubtractionState_Int64Uint642,
SubtractionState_Error
};
template < typename T, typename U > class SubtractionMethod
{
public:
enum
{
// unsigned-unsigned
method = ((IntRegion< T,U >::IntZone_UintLT32_UintLT32 ||
(IntRegion< T,U >::IntZone_Uint32_UintLT64) ||
(IntRegion< T,U >::IntZone_UintLT32_Uint32) ||
(IntRegion< T,U >::IntZone_Uint64_Uint) ||
(IntRegion< T,U >::IntZone_UintLT64_Uint64)) ? SubtractionState_BothUnsigned :
// unsigned-signed
(IntRegion< T,U >::IntZone_UintLT32_IntLT32) ? SubtractionState_CastIntCheckMinMax :
(IntRegion< T,U >::IntZone_Uint32_IntLT64 ||
IntRegion< T,U >::IntZone_UintLT32_Int32) ? SubtractionState_CastInt64CheckMinMax :
(IntRegion< T,U >::IntZone_Uint64_Int ||
IntRegion< T,U >::IntZone_Uint64_Int64) ? SubtractionState_Uint64Int :
(IntRegion< T,U >::IntZone_UintLT64_Int64) ? SubtractionState_UintInt64 :
// signed-signed
(IntRegion< T,U >::IntZone_IntLT32_IntLT32) ? SubtractionState_CastIntCheckMinMax :
(IntRegion< T,U >::IntZone_Int32_IntLT64 ||
IntRegion< T,U >::IntZone_IntLT32_Int32) ? SubtractionState_CastInt64CheckMinMax :
(IntRegion< T,U >::IntZone_Int64_Int ||
IntRegion< T,U >::IntZone_Int64_Int64) ? SubtractionState_Int64Int :
(IntRegion< T,U >::IntZone_IntLT64_Int64) ? SubtractionState_IntInt64 :
// signed-unsigned
(IntRegion< T,U >::IntZone_IntLT32_UintLT32) ? SubtractionState_CastIntCheckMin :
(IntRegion< T,U >::IntZone_Int32_UintLT32 ||
IntRegion< T,U >::IntZone_IntLT64_Uint32) ? SubtractionState_CastInt64CheckMin :
(IntRegion< T,U >::IntZone_Int64_UintLT64) ? SubtractionState_Int64Uint :
(IntRegion< T,U >::IntZone_Int_Uint64) ? SubtractionState_IntUint64 :
(IntRegion< T,U >::IntZone_Int64_Uint64) ? SubtractionState_Int64Uint64 :
SubtractionState_Error)
};
};
// this is for the case of U - SafeInt< T, E >
template < typename T, typename U > class SubtractionMethod2
{
public:
enum
{
// unsigned-unsigned
method = ((IntRegion< T,U >::IntZone_UintLT32_UintLT32 ||
(IntRegion< T,U >::IntZone_Uint32_UintLT64) ||
(IntRegion< T,U >::IntZone_UintLT32_Uint32) ||
(IntRegion< T,U >::IntZone_Uint64_Uint) ||
(IntRegion< T,U >::IntZone_UintLT64_Uint64)) ? SubtractionState_BothUnsigned2 :
// unsigned-signed
(IntRegion< T,U >::IntZone_UintLT32_IntLT32) ? SubtractionState_CastIntCheckMinMax2 :
(IntRegion< T,U >::IntZone_Uint32_IntLT64 ||
IntRegion< T,U >::IntZone_UintLT32_Int32) ? SubtractionState_CastInt64CheckMinMax2 :
(IntRegion< T,U >::IntZone_Uint64_Int ||
IntRegion< T,U >::IntZone_Uint64_Int64) ? SubtractionState_Uint64Int2 :
(IntRegion< T,U >::IntZone_UintLT64_Int64) ? SubtractionState_UintInt642 :
// signed-signed
(IntRegion< T,U >::IntZone_IntLT32_IntLT32) ? SubtractionState_CastIntCheckMinMax2 :
(IntRegion< T,U >::IntZone_Int32_IntLT64 ||
IntRegion< T,U >::IntZone_IntLT32_Int32) ? SubtractionState_CastInt64CheckMinMax2 :
(IntRegion< T,U >::IntZone_Int64_Int ||
IntRegion< T,U >::IntZone_Int64_Int64) ? SubtractionState_Int64Int2 :
(IntRegion< T,U >::IntZone_IntLT64_Int64) ? SubtractionState_IntInt642 :
// signed-unsigned
(IntRegion< T,U >::IntZone_IntLT32_UintLT32) ? SubtractionState_CastIntCheckMinMax2 :
(IntRegion< T,U >::IntZone_Int32_UintLT32 ||
IntRegion< T,U >::IntZone_IntLT64_Uint32) ? SubtractionState_CastInt64CheckMinMax2 :
(IntRegion< T,U >::IntZone_Int64_UintLT64) ? SubtractionState_Int64Uint2 :
(IntRegion< T,U >::IntZone_Int_Uint64) ? SubtractionState_IntUint642 :
(IntRegion< T,U >::IntZone_Int64_Uint64) ? SubtractionState_Int64Uint642 :
SubtractionState_Error)
};
};
template < typename T, typename U, int method > class SubtractionHelper;
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_BothUnsigned >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// both are unsigned - easy case
if( rhs <= lhs )
{
result = (T)( lhs - rhs );
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// both are unsigned - easy case
if( rhs <= lhs )
{
result = (T)( lhs - rhs );
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_BothUnsigned2 >
{
public:
static bool Subtract( const T& lhs, const U& rhs, U& result ) throw()
{
// both are unsigned - easy case
// Except we do have to check for overflow - lhs could be larger than result can hold
if( rhs <= lhs )
{
T tmp = (T)(lhs - rhs);
return SafeCastHelper< U, T, GetCastMethod<U, T>::method>::Cast( tmp, result);
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, U& result )
{
// both are unsigned - easy case
if( rhs <= lhs )
{
T tmp = (T)(lhs - rhs);
SafeCastHelper< U, T, GetCastMethod<U, T>::method >::template CastThrow<E>( tmp, result);
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_CastIntCheckMinMax >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// both values are 16-bit or less
// rhs is signed, so could end up increasing or decreasing
__int32 tmp = lhs - rhs;
if( SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::Cast( tmp, result ) )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// both values are 16-bit or less
// rhs is signed, so could end up increasing or decreasing
__int32 tmp = lhs - rhs;
SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::template CastThrow< E >( tmp, result );
}
};
template <typename U, typename T> class SubtractionHelper< U, T, SubtractionState_CastIntCheckMinMax2 >
{
public:
static bool Subtract( const U& lhs, const T& rhs, T& result ) throw()
{
// both values are 16-bit or less
// rhs is signed, so could end up increasing or decreasing
__int32 tmp = lhs - rhs;
return SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::Cast( tmp, result );
}
template < typename E >
static void SubtractThrow( const U& lhs, const T& rhs, T& result )
{
// both values are 16-bit or less
// rhs is signed, so could end up increasing or decreasing
__int32 tmp = lhs - rhs;
SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::template CastThrow< E >( tmp, result );
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_CastIntCheckMin >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// both values are 16-bit or less
// rhs is unsigned - check only minimum
__int32 tmp = lhs - rhs;
if( tmp >= (__int32)IntTraits< T >::minInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// both values are 16-bit or less
// rhs is unsigned - check only minimum
__int32 tmp = lhs - rhs;
if( tmp >= (__int32)IntTraits< T >::minInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_CastInt64CheckMinMax >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// both values are 32-bit or less
// rhs is signed, so could end up increasing or decreasing
__int64 tmp = (__int64)lhs - (__int64)rhs;
return SafeCastHelper< T, __int64, GetCastMethod< T, __int64 >::method >::Cast( tmp, result );
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// both values are 32-bit or less
// rhs is signed, so could end up increasing or decreasing
__int64 tmp = (__int64)lhs - (__int64)rhs;
SafeCastHelper< T, __int64, GetCastMethod< T, __int64 >::method >::template CastThrow< E >( tmp, result );
}
};
template <typename U, typename T> class SubtractionHelper< U, T, SubtractionState_CastInt64CheckMinMax2 >
{
public:
static bool Subtract( const U& lhs, const T& rhs, T& result ) throw()
{
// both values are 32-bit or less
// rhs is signed, so could end up increasing or decreasing
__int64 tmp = (__int64)lhs - (__int64)rhs;
return SafeCastHelper< T, __int64, GetCastMethod< T, __int64 >::method >::Cast( tmp, result );
}
template < typename E >
static void SubtractThrow( const U& lhs, const T& rhs, T& result )
{
// both values are 32-bit or less
// rhs is signed, so could end up increasing or decreasing
__int64 tmp = (__int64)lhs - (__int64)rhs;
SafeCastHelper< T, __int64, GetCastMethod< T, __int64 >::method >::template CastThrow< E >( tmp, result );
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_CastInt64CheckMin >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// both values are 32-bit or less
// rhs is unsigned - check only minimum
__int64 tmp = (__int64)lhs - (__int64)rhs;
if( tmp >= (__int64)IntTraits< T >::minInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// both values are 32-bit or less
// rhs is unsigned - check only minimum
__int64 tmp = (__int64)lhs - (__int64)rhs;
if( tmp >= (__int64)IntTraits< T >::minInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_Uint64Int >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is an unsigned __int64, rhs signed
// must first see if rhs is positive or negative
if( rhs >= 0 )
{
if( (unsigned __int64)rhs <= lhs )
{
result = (T)( lhs - (unsigned __int64)rhs );
return true;
}
}
else
{
// we're now effectively adding
result = lhs + AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( rhs );
if(result >= lhs)
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is an unsigned __int64, rhs signed
// must first see if rhs is positive or negative
if( rhs >= 0 )
{
if( (unsigned __int64)rhs <= lhs )
{
result = (T)( lhs - (unsigned __int64)rhs );
return;
}
}
else
{
// we're now effectively adding
result = lhs + AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( rhs );
if(result >= lhs)
return;
}
E::SafeIntOnOverflow();
}
};
template < typename U, typename T > class SubtractionHelper< U, T, SubtractionState_Uint64Int2 >
{
public:
static bool Subtract( const U& lhs, const T& rhs, T& result ) throw()
{
// U is unsigned __int64, T is signed
if( rhs < 0 )
{
// treat this as addition
unsigned __int64 tmp;
tmp = lhs + (unsigned __int64)AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( rhs );
// must check for addition overflow and max
if( tmp >= lhs && tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
}
else if( (unsigned __int64)rhs > lhs ) // now both are positive, so comparison always works
{
// result is negative
// implies that lhs must fit into T, and result cannot overflow
// Also allows us to drop to 32-bit math, which is faster on a 32-bit system
result = (T)lhs - (T)rhs;
return true;
}
else
{
// result is positive
unsigned __int64 tmp = (unsigned __int64)lhs - (unsigned __int64)rhs;
if( tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
}
return false;
}
template < typename E >
static void SubtractThrow( const U& lhs, const T& rhs, T& result )
{
// U is unsigned __int64, T is signed
if( rhs < 0 )
{
// treat this as addition
unsigned __int64 tmp;
tmp = lhs + (unsigned __int64)AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( rhs );
// must check for addition overflow and max
if( tmp >= lhs && tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
}
else if( (unsigned __int64)rhs > lhs ) // now both are positive, so comparison always works
{
// result is negative
// implies that lhs must fit into T, and result cannot overflow
// Also allows us to drop to 32-bit math, which is faster on a 32-bit system
result = (T)lhs - (T)rhs;
return;
}
else
{
// result is positive
unsigned __int64 tmp = (unsigned __int64)lhs - (unsigned __int64)rhs;
if( tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_UintInt64 >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is an unsigned int32 or smaller, rhs signed __int64
// must first see if rhs is positive or negative
if( rhs >= 0 )
{
if( (unsigned __int64)rhs <= lhs )
{
result = (T)( lhs - (T)rhs );
return true;
}
}
else
{
// we're now effectively adding
// since lhs is 32-bit, and rhs cannot exceed 2^63
// this addition cannot overflow
unsigned __int64 tmp = lhs + (unsigned __int64)( -rhs ); // negation safe
// but we could exceed MaxInt
if(tmp <= IntTraits< T >::maxInt)
{
result = (T)tmp;
return true;
}
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is an unsigned int32 or smaller, rhs signed __int64
// must first see if rhs is positive or negative
if( rhs >= 0 )
{
if( (unsigned __int64)rhs <= lhs )
{
result = (T)( lhs - (T)rhs );
return;
}
}
else
{
// we're now effectively adding
// since lhs is 32-bit, and rhs cannot exceed 2^63
// this addition cannot overflow
unsigned __int64 tmp = lhs + (unsigned __int64)( -rhs ); // negation safe
// but we could exceed MaxInt
if(tmp <= IntTraits< T >::maxInt)
{
result = (T)tmp;
return;
}
}
E::SafeIntOnOverflow();
}
};
template <typename U, typename T> class SubtractionHelper< U, T, SubtractionState_UintInt642 >
{
public:
static bool Subtract( const U& lhs, const T& rhs, T& result ) throw()
{
// U unsigned 32-bit or less, T __int64
if( rhs >= 0 )
{
// overflow not possible
result = (T)( (__int64)lhs - rhs );
return true;
}
else
{
// we effectively have an addition
// which cannot overflow internally
unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)( -rhs );
if( tmp <= (unsigned __int64)IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
}
return false;
}
template < typename E >
static void SubtractThrow( const U& lhs, const T& rhs, T& result )
{
// U unsigned 32-bit or less, T __int64
if( rhs >= 0 )
{
// overflow not possible
result = (T)( (__int64)lhs - rhs );
return;
}
else
{
// we effectively have an addition
// which cannot overflow internally
unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)( -rhs );
if( tmp <= (unsigned __int64)IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_Int64Int >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is an __int64, rhs signed (up to 64-bit)
// we have essentially 4 cases:
//
// 1) lhs positive, rhs positive - overflow not possible
// 2) lhs positive, rhs negative - equivalent to addition - result >= lhs or error
// 3) lhs negative, rhs positive - check result <= lhs
// 4) lhs negative, rhs negative - overflow not possible
__int64 tmp = lhs - rhs;
// Note - ideally, we can order these so that true conditionals
// lead to success, which enables better pipelining
// It isn't practical here
if( ( lhs >= 0 && rhs < 0 && tmp < lhs ) || // condition 2
( rhs >= 0 && tmp > lhs ) ) // condition 3
{
return false;
}
result = (T)tmp;
return true;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is an __int64, rhs signed (up to 64-bit)
// we have essentially 4 cases:
//
// 1) lhs positive, rhs positive - overflow not possible
// 2) lhs positive, rhs negative - equivalent to addition - result >= lhs or error
// 3) lhs negative, rhs positive - check result <= lhs
// 4) lhs negative, rhs negative - overflow not possible
__int64 tmp = lhs - rhs;
// Note - ideally, we can order these so that true conditionals
// lead to success, which enables better pipelining
// It isn't practical here
if( ( lhs >= 0 && rhs < 0 && tmp < lhs ) || // condition 2
( rhs >= 0 && tmp > lhs ) ) // condition 3
{
E::SafeIntOnOverflow();
}
result = (T)tmp;
}
};
template < typename U, typename T > class SubtractionHelper< U, T, SubtractionState_Int64Int2 >
{
public:
static bool Subtract( const U& lhs, const T& rhs, T& result ) throw()
{
// lhs __int64, rhs any signed int (including __int64)
__int64 tmp = lhs - rhs;
// we have essentially 4 cases:
//
// 1) lhs positive, rhs positive - overflow not possible in tmp
// 2) lhs positive, rhs negative - equivalent to addition - result >= lhs or error
// 3) lhs negative, rhs positive - check result <= lhs
// 4) lhs negative, rhs negative - overflow not possible in tmp
if( lhs >= 0 )
{
// if both positive, overflow to negative not possible
// which is why we'll explicitly check maxInt, and not call SafeCast
if( ( IntTraits< T >::isLT64Bit && tmp > IntTraits< T >::maxInt ) ||
( rhs < 0 && tmp < lhs ) )
{
return false;
}
}
else
{
// lhs negative
if( ( IntTraits< T >::isLT64Bit && tmp < IntTraits< T >::minInt) ||
( rhs >=0 && tmp > lhs ) )
{
return false;
}
}
result = (T)tmp;
return true;
}
template < typename E >
static void SubtractThrow( const U& lhs, const T& rhs, T& result )
{
// lhs __int64, rhs any signed int (including __int64)
__int64 tmp = lhs - rhs;
// we have essentially 4 cases:
//
// 1) lhs positive, rhs positive - overflow not possible in tmp
// 2) lhs positive, rhs negative - equivalent to addition - result >= lhs or error
// 3) lhs negative, rhs positive - check result <= lhs
// 4) lhs negative, rhs negative - overflow not possible in tmp
if( lhs >= 0 )
{
// if both positive, overflow to negative not possible
// which is why we'll explicitly check maxInt, and not call SafeCast
if( ( IntTraits< T >::isLT64Bit && tmp > IntTraits< T >::maxInt ) ||
( rhs < 0 && tmp < lhs ) )
{
E::SafeIntOnOverflow();
}
}
else
{
// lhs negative
if( ( IntTraits< T >::isLT64Bit && tmp < IntTraits< T >::minInt) ||
( rhs >=0 && tmp > lhs ) )
{
E::SafeIntOnOverflow();
}
}
result = (T)tmp;
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_IntInt64 >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is a 32-bit int or less, rhs __int64
// we have essentially 4 cases:
//
// lhs positive, rhs positive - rhs could be larger than lhs can represent
// lhs positive, rhs negative - additive case - check tmp >= lhs and tmp > max int
// lhs negative, rhs positive - check tmp <= lhs and tmp < min int
// lhs negative, rhs negative - addition cannot internally overflow, check against max
__int64 tmp = (__int64)lhs - rhs;
if( lhs >= 0 )
{
// first case
if( rhs >= 0 )
{
if( tmp >= IntTraits< T >::minInt )
{
result = (T)tmp;
return true;
}
}
else
{
// second case
if( tmp >= lhs && tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
}
}
else
{
// lhs < 0
// third case
if( rhs >= 0 )
{
if( tmp <= lhs && tmp >= IntTraits< T >::minInt )
{
result = (T)tmp;
return true;
}
}
else
{
// fourth case
if( tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
}
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is a 32-bit int or less, rhs __int64
// we have essentially 4 cases:
//
// lhs positive, rhs positive - rhs could be larger than lhs can represent
// lhs positive, rhs negative - additive case - check tmp >= lhs and tmp > max int
// lhs negative, rhs positive - check tmp <= lhs and tmp < min int
// lhs negative, rhs negative - addition cannot internally overflow, check against max
__int64 tmp = (__int64)lhs - rhs;
if( lhs >= 0 )
{
// first case
if( rhs >= 0 )
{
if( tmp >= IntTraits< T >::minInt )
{
result = (T)tmp;
return;
}
}
else
{
// second case
if( tmp >= lhs && tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
}
}
else
{
// lhs < 0
// third case
if( rhs >= 0 )
{
if( tmp <= lhs && tmp >= IntTraits< T >::minInt )
{
result = (T)tmp;
return;
}
}
else
{
// fourth case
if( tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
}
}
E::SafeIntOnOverflow();
}
};
template < typename U, typename T > class SubtractionHelper< U, T, SubtractionState_IntInt642 >
{
public:
static bool Subtract( const U& lhs, const T& rhs, T& result ) throw()
{
// lhs is any signed int32 or smaller, rhs is int64
__int64 tmp = (__int64)lhs - rhs;
if( ( lhs >= 0 && rhs < 0 && tmp < lhs ) ||
( rhs > 0 && tmp > lhs ) )
{
return false;
//else OK
}
result = (T)tmp;
return true;
}
template < typename E >
static void SubtractThrow( const U& lhs, const T& rhs, T& result )
{
// lhs is any signed int32 or smaller, rhs is int64
__int64 tmp = (__int64)lhs - rhs;
if( ( lhs >= 0 && rhs < 0 && tmp < lhs ) ||
( rhs > 0 && tmp > lhs ) )
{
E::SafeIntOnOverflow();
//else OK
}
result = (T)tmp;
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_Int64Uint >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is a 64-bit int, rhs unsigned int32 or smaller
__int64 tmp = lhs - (__int64)rhs;
if( tmp <= lhs )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is a 64-bit int, rhs unsigned int32 or smaller
__int64 tmp = lhs - (__int64)rhs;
if( tmp <= lhs )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename U, typename T > class SubtractionHelper< U, T, SubtractionState_Int64Uint2 >
{
public:
// lhs is __int64, rhs is unsigned 32-bit or smaller
static bool Subtract( const U& lhs, const T& rhs, T& result ) throw()
{
__int64 tmp = lhs - (__int64)rhs;
if( tmp <= IntTraits< T >::maxInt && tmp >= IntTraits< T >::minInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const U& lhs, const T& rhs, T& result )
{
__int64 tmp = lhs - (__int64)rhs;
if( tmp <= IntTraits< T >::maxInt && tmp >= IntTraits< T >::minInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_IntUint64 >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is any signed int, rhs unsigned int64
// check against available range
// We need the absolute value of IntTraits< T >::minInt
// This will give it to us without extraneous compiler warnings
const unsigned __int64 AbsMinIntT = (unsigned __int64)IntTraits< T >::maxInt + 1;
if( lhs < 0 )
{
if( rhs <= AbsMinIntT - AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( lhs ) )
{
result = (T)( lhs - rhs );
return true;
}
}
else
{
if( rhs <= AbsMinIntT + (unsigned __int64)lhs )
{
result = (T)( lhs - rhs );
return true;
}
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is any signed int, rhs unsigned int64
// check against available range
// We need the absolute value of IntTraits< T >::minInt
// This will give it to us without extraneous compiler warnings
const unsigned __int64 AbsMinIntT = (unsigned __int64)IntTraits< T >::maxInt + 1;
if( lhs < 0 )
{
if( rhs <= AbsMinIntT - AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( lhs ) )
{
result = (T)( lhs - rhs );
return;
}
}
else
{
if( rhs <= AbsMinIntT + (unsigned __int64)lhs )
{
result = (T)( lhs - rhs );
return;
}
}
E::SafeIntOnOverflow();
}
};
template < typename U, typename T > class SubtractionHelper< U, T, SubtractionState_IntUint642 >
{
public:
static bool Subtract( const U& lhs, const T& rhs, T& result ) throw()
{
// We run into upcasting problems on comparison - needs 2 checks
if( lhs >= 0 && (T)lhs >= rhs )
{
result = (T)((U)lhs - (U)rhs);
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const U& lhs, const T& rhs, T& result )
{
// We run into upcasting problems on comparison - needs 2 checks
if( lhs >= 0 && (T)lhs >= rhs )
{
result = (T)((U)lhs - (U)rhs);
return;
}
E::SafeIntOnOverflow();
}
};
template < > class SubtractionHelper< __int64, unsigned __int64, SubtractionState_Int64Uint64 >
{
public:
static bool Subtract( const __int64& lhs, const unsigned __int64& rhs, __int64& result ) throw()
{
// if we subtract, and it gets larger, there's a problem
__int64 tmp = lhs - (__int64)rhs;
if( tmp <= lhs )
{
result = tmp;
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const __int64& lhs, const unsigned __int64& rhs, __int64& result )
{
// if we subtract, and it gets larger, there's a problem
__int64 tmp = lhs - (__int64)rhs;
if( tmp <= lhs )
{
result = tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < > class SubtractionHelper< __int64, unsigned __int64, SubtractionState_Int64Uint642 >
{
public:
// If lhs is negative, immediate problem - return must be positive, and subtracting only makes it
// get smaller. If rhs > lhs, then it would also go negative, which is the other case
static bool Subtract( const __int64& lhs, const unsigned __int64& rhs, unsigned __int64& result ) throw()
{
if( lhs >= 0 && (unsigned __int64)lhs >= rhs )
{
result = (unsigned __int64)lhs - rhs;
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const __int64& lhs, const unsigned __int64& rhs, unsigned __int64& result )
{
if( lhs >= 0 && (unsigned __int64)lhs >= rhs )
{
result = (unsigned __int64)lhs - rhs;
return;
}
E::SafeIntOnOverflow();
}
};
enum BinaryState
{
BinaryState_OK,
BinaryState_Int8,
BinaryState_Int16,
BinaryState_Int32
};
template < typename T, typename U > class BinaryMethod
{
public:
enum
{
// If both operands are unsigned OR
// return type is smaller than rhs OR
// return type is larger and rhs is unsigned
// Then binary operations won't produce unexpected results
method = ( sizeof( T ) <= sizeof( U ) ||
SafeIntCompare< T, U >::isBothUnsigned ||
!IntTraits< U >::isSigned ) ? BinaryState_OK :
IntTraits< U >::isInt8 ? BinaryState_Int8 :
IntTraits< U >::isInt16 ? BinaryState_Int16
: BinaryState_Int32
};
};
#ifdef SAFEINT_DISABLE_BINARY_ASSERT
#define BinaryAssert(x)
#else
#define BinaryAssert(x) assert(x)
#endif
template < typename T, typename U, int method > class BinaryAndHelper;
template < typename T, typename U > class BinaryAndHelper< T, U, BinaryState_OK >
{
public:
static T And( T lhs, U rhs ){ return (T)( lhs & rhs ); }
};
template < typename T, typename U > class BinaryAndHelper< T, U, BinaryState_Int8 >
{
public:
static T And( T lhs, U rhs )
{
// cast forces sign extension to be zeros
BinaryAssert( ( lhs & rhs ) == ( lhs & (unsigned __int8)rhs ) );
return (T)( lhs & (unsigned __int8)rhs );
}
};
template < typename T, typename U > class BinaryAndHelper< T, U, BinaryState_Int16 >
{
public:
static T And( T lhs, U rhs )
{
//cast forces sign extension to be zeros
BinaryAssert( ( lhs & rhs ) == ( lhs & (unsigned __int16)rhs ) );
return (T)( lhs & (unsigned __int16)rhs );
}
};
template < typename T, typename U > class BinaryAndHelper< T, U, BinaryState_Int32 >
{
public:
static T And( T lhs, U rhs )
{
//cast forces sign extension to be zeros
BinaryAssert( ( lhs & rhs ) == ( lhs & (unsigned __int32)rhs ) );
return (T)( lhs & (unsigned __int32)rhs );
}
};
template < typename T, typename U, int method > class BinaryOrHelper;
template < typename T, typename U > class BinaryOrHelper< T, U, BinaryState_OK >
{
public:
static T Or( T lhs, U rhs ){ return (T)( lhs | rhs ); }
};
template < typename T, typename U > class BinaryOrHelper< T, U, BinaryState_Int8 >
{
public:
static T Or( T lhs, U rhs )
{
//cast forces sign extension to be zeros
BinaryAssert( ( lhs | rhs ) == ( lhs | (unsigned __int8)rhs ) );
return (T)( lhs | (unsigned __int8)rhs );
}
};
template < typename T, typename U > class BinaryOrHelper< T, U, BinaryState_Int16 >
{
public:
static T Or( T lhs, U rhs )
{
//cast forces sign extension to be zeros
BinaryAssert( ( lhs | rhs ) == ( lhs | (unsigned __int16)rhs ) );
return (T)( lhs | (unsigned __int16)rhs );
}
};
template < typename T, typename U > class BinaryOrHelper< T, U, BinaryState_Int32 >
{
public:
static T Or( T lhs, U rhs )
{
//cast forces sign extension to be zeros
BinaryAssert( ( lhs | rhs ) == ( lhs | (unsigned __int32)rhs ) );
return (T)( lhs | (unsigned __int32)rhs );
}
};
template <typename T, typename U, int method > class BinaryXorHelper;
template < typename T, typename U > class BinaryXorHelper< T, U, BinaryState_OK >
{
public:
static T Xor( T lhs, U rhs ){ return (T)( lhs ^ rhs ); }
};
template < typename T, typename U > class BinaryXorHelper< T, U, BinaryState_Int8 >
{
public:
static T Xor( T lhs, U rhs )
{
// cast forces sign extension to be zeros
BinaryAssert( ( lhs ^ rhs ) == ( lhs ^ (unsigned __int8)rhs ) );
return (T)( lhs ^ (unsigned __int8)rhs );
}
};
template < typename T, typename U > class BinaryXorHelper< T, U, BinaryState_Int16 >
{
public:
static T Xor( T lhs, U rhs )
{
// cast forces sign extension to be zeros
BinaryAssert( ( lhs ^ rhs ) == ( lhs ^ (unsigned __int16)rhs ) );
return (T)( lhs ^ (unsigned __int16)rhs );
}
};
template < typename T, typename U > class BinaryXorHelper< T, U, BinaryState_Int32 >
{
public:
static T Xor( T lhs, U rhs )
{
// cast forces sign extension to be zeros
BinaryAssert( ( lhs ^ rhs ) == ( lhs ^ (unsigned __int32)rhs ) );
return (T)( lhs ^ (unsigned __int32)rhs );
}
};
/***************** External functions ****************************************/
// External functions that can be used where you only need to check one operation
// non-class helper function so that you can check for a cast's validity
// and handle errors how you like
template < typename T, typename U >
inline bool SafeCast( const T From, U& To )
{
return SafeCastHelper< U, T, GetCastMethod< U, T >::method >::Cast( From, To );
}
template < typename T, typename U >
inline bool SafeEquals( const T t, const U u ) throw()
{
return EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( t, u );
}
template < typename T, typename U >
inline bool SafeNotEquals( const T t, const U u ) throw()
{
return !EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( t, u );
}
template < typename T, typename U >
inline bool SafeGreaterThan( const T t, const U u ) throw()
{
return GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( t, u );
}
template < typename T, typename U >
inline bool SafeGreaterThanEquals( const T t, const U u ) throw()
{
return !GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( u, t );
}
template < typename T, typename U >
inline bool SafeLessThan( const T t, const U u ) throw()
{
return GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( u, t );
}
template < typename T, typename U >
inline bool SafeLessThanEquals( const T t, const U u ) throw()
{
return !GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( t, u );
}
template < typename T, typename U >
inline bool SafeModulus( const T& t, const U& u, T& result ) throw()
{
return ( ModulusHelper< T, U, ValidComparison< T, U >::method >::Modulus( t, u, result ) == SafeIntNoError );
}
template < typename T, typename U >
inline bool SafeMultiply( T t, U u, T& result ) throw()
{
return MultiplicationHelper< T, U, MultiplicationMethod< T, U >::method >::Multiply( t, u, result );
}
template < typename T, typename U >
inline bool SafeDivide( T t, U u, T& result ) throw()
{
return ( DivisionHelper< T, U, DivisionMethod< T, U >::method >::Divide( t, u, result ) == SafeIntNoError );
}
template < typename T, typename U >
inline bool SafeAdd( T t, U u, T& result ) throw()
{
return AdditionHelper< T, U, AdditionMethod< T, U >::method >::Addition( t, u, result );
}
template < typename T, typename U >
inline bool SafeSubtract( T t, U u, T& result ) throw()
{
return SubtractionHelper< T, U, SubtractionMethod< T, U >::method >::Subtract( t, u, result );
}
/***************** end external functions ************************************/
// Main SafeInt class
// Assumes exceptions can be thrown
template < typename T, typename E = SafeIntDefaultExceptionHandler > class SafeInt
{
public:
SafeInt() throw()
{
C_ASSERT( NumericType< T >::isInt );
m_int = 0;
}
// Having a constructor for every type of int
// avoids having the compiler evade our checks when doing implicit casts -
// e.g., SafeInt<char> s = 0x7fffffff;
SafeInt( const T& i ) throw()
{
C_ASSERT( NumericType< T >::isInt );
//always safe
m_int = i;
}
// provide explicit boolean converter
SafeInt( bool b ) throw()
{
C_ASSERT( NumericType< T >::isInt );
m_int = b ? 1 : 0;
}
template < typename U >
SafeInt(const SafeInt< U, E >& u)
{
C_ASSERT( NumericType< T >::isInt );
*this = SafeInt< T, E >( (U)u );
}
template < typename U >
SafeInt( const U& i )
{
C_ASSERT( NumericType< T >::isInt );
// SafeCast will throw exceptions if i won't fit in type T
SafeCastHelper< T, U, GetCastMethod< T, U >::method >::template CastThrow< E >( i, m_int );
}
// The destructor is intentionally commented out - no destructor
// vs. a do-nothing destructor makes a huge difference in
// inlining characteristics. It wasn't doing anything anyway.
// ~SafeInt(){};
// now start overloading operators
// assignment operator
// constructors exist for all int types and will ensure safety
template < typename U >
SafeInt< T, E >& operator =( const U& rhs )
{
// use constructor to test size
// constructor is optimized to do minimal checking based
// on whether T can contain U
// note - do not change this
*this = SafeInt< T, E >( rhs );
return *this;
}
SafeInt< T, E >& operator =( const T& rhs ) throw()
{
m_int = rhs;
return *this;
}
template < typename U >
SafeInt< T, E >& operator =( const SafeInt< U, E >& rhs )
{
SafeCastHelper< T, U, GetCastMethod< T, U >::method >::template CastThrow< E >( rhs.Ref(), m_int );
return *this;
}
SafeInt< T, E >& operator =( const SafeInt< T, E >& rhs ) throw()
{
m_int = rhs.m_int;
return *this;
}
// Casting operators
operator bool() const throw()
{
return !!m_int;
}
operator char() const
{
char val;
SafeCastHelper< char, T, GetCastMethod< char, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator signed char() const
{
signed char val;
SafeCastHelper< signed char, T, GetCastMethod< signed char, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator unsigned char() const
{
unsigned char val;
SafeCastHelper< unsigned char, T, GetCastMethod< unsigned char, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator __int16() const
{
__int16 val;
SafeCastHelper< __int16, T, GetCastMethod< __int16, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator unsigned __int16() const
{
unsigned __int16 val;
SafeCastHelper< unsigned __int16, T, GetCastMethod< unsigned __int16, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator __int32() const
{
__int32 val;
SafeCastHelper< __int32, T, GetCastMethod< __int32, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator unsigned __int32() const
{
unsigned __int32 val;
SafeCastHelper< unsigned __int32, T, GetCastMethod< unsigned __int32, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
// The compiler knows that int == __int32
// but not that long == __int32
operator long() const
{
long val;
SafeCastHelper< long, T, GetCastMethod< long, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator unsigned long() const
{
unsigned long val;
SafeCastHelper< unsigned long, T, GetCastMethod< unsigned long, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator __int64() const
{
__int64 val;
SafeCastHelper< __int64, T, GetCastMethod< __int64, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator unsigned __int64() const
{
unsigned __int64 val;
SafeCastHelper< unsigned __int64, T, GetCastMethod< unsigned __int64, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
#ifdef SIZE_T_CAST_NEEDED
// We also need an explicit cast to size_t, or the compiler will complain
// Apparently, only SOME compilers complain, and cl 14.00.50727.42 isn't one of them
// Leave here in case we decide to backport this to an earlier compiler
operator size_t() const
{
size_t val;
SafeCastHelper< size_t, T, GetCastMethod< size_t, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
#endif
// Also provide a cast operator for floating point types
operator float() const
{
float val;
SafeCastHelper< float, T, GetCastMethod< float, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator double() const
{
double val;
SafeCastHelper< double, T, GetCastMethod< double, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator long double() const
{
long double val;
SafeCastHelper< long double, T, GetCastMethod< long double, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
// If you need a pointer to the data
// this could be dangerous, but allows you to correctly pass
// instances of this class to APIs that take a pointer to an integer
// also see overloaded address-of operator below
T* Ptr() throw() { return &m_int; }
const T* Ptr() const throw() { return &m_int; }
const T& Ref() const throw() { return m_int; }
// Or if SafeInt< T, E >::Ptr() is inconvenient, use the overload
// operator &
// This allows you to do unsafe things!
// It is meant to allow you to more easily
// pass a SafeInt into things like ReadFile
T* operator &() throw() { return &m_int; }
const T* operator &() const throw() { return &m_int; }
// Unary operators
bool operator !() const throw() { return (!m_int) ? true : false; }
// operator + (unary)
// note - normally, the '+' and '-' operators will upcast to a signed int
// for T < 32 bits. This class changes behavior to preserve type
const SafeInt< T, E >& operator +() const throw() { return *this; };
//unary -
SafeInt< T, E > operator -() const
{
// Note - unsigned still performs the bitwise manipulation
// will warn at level 2 or higher if the value is 32-bit or larger
return SafeInt<T, E>(NegationHelper<T, IntTraits<T>::isSigned>::template NegativeThrow<E>(m_int));
}
// prefix increment operator
SafeInt< T, E >& operator ++()
{
if( m_int != IntTraits< T >::maxInt )
{
++m_int;
return *this;
}
E::SafeIntOnOverflow();
}
// prefix decrement operator
SafeInt< T, E >& operator --()
{
if( m_int != IntTraits< T >::minInt )
{
--m_int;
return *this;
}
E::SafeIntOnOverflow();
}
// note that postfix operators have inherently worse perf
// characteristics
// postfix increment operator
SafeInt< T, E > operator ++( int ) // dummy arg to comply with spec
{
if( m_int != IntTraits< T >::maxInt )
{
SafeInt< T, E > tmp( m_int );
m_int++;
return tmp;
}
E::SafeIntOnOverflow();
}
// postfix decrement operator
SafeInt< T, E > operator --( int ) // dummy arg to comply with spec
{
if( m_int != IntTraits< T >::minInt )
{
SafeInt< T, E > tmp( m_int );
m_int--;
return tmp;
}
E::SafeIntOnOverflow();
}
// One's complement
// Note - this operator will normally change size to an int
// cast in return improves perf and maintains type
SafeInt< T, E > operator ~() const throw() { return SafeInt< T, E >( (T)~m_int ); }
// Binary operators
//
// arithmetic binary operators
// % modulus
// * multiplication
// / division
// + addition
// - subtraction
//
// For each of the arithmetic operators, you will need to
// use them as follows:
//
// SafeInt<char> c = 2;
// SafeInt<int> i = 3;
//
// SafeInt<int> i2 = i op (char)c;
// OR
// SafeInt<char> i2 = (int)i op c;
//
// The base problem is that if the lhs and rhs inputs are different SafeInt types
// it is not possible in this implementation to determine what type of SafeInt
// should be returned. You have to let the class know which of the two inputs
// need to be the return type by forcing the other value to the base integer type.
//
// Note - as per feedback from Scott Meyers, I'm exploring how to get around this.
// 3.0 update - I'm still thinking about this. It can be done with template metaprogramming,
// but it is tricky, and there's a perf vs. correctness tradeoff where the right answer
// is situational.
//
// The case of:
//
// SafeInt< T, E > i, j, k;
// i = j op k;
//
// works just fine and no unboxing is needed because the return type is not ambiguous.
// Modulus
// Modulus has some convenient properties -
// first, the magnitude of the return can never be
// larger than the lhs operand, and it must be the same sign
// as well. It does, however, suffer from the same promotion
// problems as comparisons, division and other operations
template < typename U >
SafeInt< T, E > operator %( U rhs ) const
{
T result;
ModulusHelper< T, U, ValidComparison< T, U >::method >::template ModulusThrow< E >( m_int, rhs, result );
return SafeInt< T, E >( result );
}
SafeInt< T, E > operator %( SafeInt< T, E > rhs ) const
{
T result;
ModulusHelper< T, T, ValidComparison< T, T >::method >::template ModulusThrow< E >( m_int, rhs, result );
return SafeInt< T, E >( result );
}
// Modulus assignment
template < typename U >
SafeInt< T, E >& operator %=( U rhs )
{
ModulusHelper< T, U, ValidComparison< T, U >::method >::template ModulusThrow< E >( m_int, rhs, m_int );
return *this;
}
template < typename U >
SafeInt< T, E >& operator %=( SafeInt< U, E > rhs )
{
ModulusHelper< T, U, ValidComparison< T, U >::method >::template ModulusThrow< E >( m_int, (U)rhs, m_int );
return *this;
}
// Multiplication
template < typename U >
SafeInt< T, E > operator *( U rhs ) const
{
T ret( 0 );
MultiplicationHelper< T, U, MultiplicationMethod< T, U >::method >::template MultiplyThrow< E >( m_int, rhs, ret );
return SafeInt< T, E >( ret );
}
SafeInt< T, E > operator *( SafeInt< T, E > rhs ) const
{
T ret( 0 );
MultiplicationHelper< T, T, MultiplicationMethod< T, T >::method >::template MultiplyThrow< E >( m_int, (T)rhs, ret );
return SafeInt< T, E >( ret );
}
// Multiplication assignment
SafeInt< T, E >& operator *=( SafeInt< T, E > rhs )
{
MultiplicationHelper< T, T, MultiplicationMethod< T, T >::method >::template MultiplyThrow< E >( m_int, (T)rhs, m_int );
return *this;
}
template < typename U >
SafeInt< T, E >& operator *=( U rhs )
{
MultiplicationHelper< T, U, MultiplicationMethod< T, U >::method >::template MultiplyThrow< E >( m_int, rhs, m_int );
return *this;
}
template < typename U >
SafeInt< T, E >& operator *=( SafeInt< U, E > rhs )
{
MultiplicationHelper< T, U, MultiplicationMethod< T, U >::method >::template MultiplyThrow< E >( m_int, rhs.Ref(), m_int );
return *this;
}
// Division
template < typename U >
SafeInt< T, E > operator /( U rhs ) const
{
T ret( 0 );
DivisionHelper< T, U, DivisionMethod< T, U >::method >::template DivideThrow< E >( m_int, rhs, ret );
return SafeInt< T, E >( ret );
}
SafeInt< T, E > operator /( SafeInt< T, E > rhs ) const
{
T ret( 0 );
DivisionHelper< T, T, DivisionMethod< T, T >::method >::template DivideThrow< E >( m_int, (T)rhs, ret );
return SafeInt< T, E >( ret );
}
// Division assignment
SafeInt< T, E >& operator /=( SafeInt< T, E > i )
{
DivisionHelper< T, T, DivisionMethod< T, T >::method >::template DivideThrow< E >( m_int, (T)i, m_int );
return *this;
}
template < typename U > SafeInt< T, E >& operator /=( U i )
{
DivisionHelper< T, U, DivisionMethod< T, U >::method >::template DivideThrow< E >( m_int, i, m_int );
return *this;
}
template < typename U > SafeInt< T, E >& operator /=( SafeInt< U, E > i )
{
DivisionHelper< T, U, DivisionMethod< T, U >::method >::template DivideThrow< E >( m_int, (U)i, m_int );
return *this;
}
// For addition and subtraction
// Addition
SafeInt< T, E > operator +( SafeInt< T, E > rhs ) const
{
T ret( 0 );
AdditionHelper< T, T, AdditionMethod< T, T >::method >::template AdditionThrow< E >( m_int, (T)rhs, ret );
return SafeInt< T, E >( ret );
}
template < typename U >
SafeInt< T, E > operator +( U rhs ) const
{
T ret( 0 );
AdditionHelper< T, U, AdditionMethod< T, U >::method >::template AdditionThrow< E >( m_int, rhs, ret );
return SafeInt< T, E >( ret );
}
//addition assignment
SafeInt< T, E >& operator +=( SafeInt< T, E > rhs )
{
AdditionHelper< T, T, AdditionMethod< T, T >::method >::template AdditionThrow< E >( m_int, (T)rhs, m_int );
return *this;
}
template < typename U >
SafeInt< T, E >& operator +=( U rhs )
{
AdditionHelper< T, U, AdditionMethod< T, U >::method >::template AdditionThrow< E >( m_int, rhs, m_int );
return *this;
}
template < typename U >
SafeInt< T, E >& operator +=( SafeInt< U, E > rhs )
{
AdditionHelper< T, U, AdditionMethod< T, U >::method >::template AdditionThrow< E >( m_int, (U)rhs, m_int );
return *this;
}
// Subtraction
template < typename U >
SafeInt< T, E > operator -( U rhs ) const
{
T ret( 0 );
SubtractionHelper< T, U, SubtractionMethod< T, U >::method >::template SubtractThrow< E >( m_int, rhs, ret );
return SafeInt< T, E >( ret );
}
SafeInt< T, E > operator -(SafeInt< T, E > rhs) const
{
T ret( 0 );
SubtractionHelper< T, T, SubtractionMethod< T, T >::method >::template SubtractThrow< E >( m_int, (T)rhs, ret );
return SafeInt< T, E >( ret );
}
// Subtraction assignment
SafeInt< T, E >& operator -=( SafeInt< T, E > rhs )
{
SubtractionHelper< T, T, SubtractionMethod< T, T >::method >::template SubtractThrow< E >( m_int, (T)rhs, m_int );
return *this;
}
template < typename U >
SafeInt< T, E >& operator -=( U rhs )
{
SubtractionHelper< T, U, SubtractionMethod< T, U >::method >::template SubtractThrow< E >( m_int, rhs, m_int );
return *this;
}
template < typename U >
SafeInt< T, E >& operator -=( SafeInt< U, E > rhs )
{
SubtractionHelper< T, U, SubtractionMethod< T, U >::method >::template SubtractThrow< E >( m_int, (U)rhs, m_int );
return *this;
}
// Comparison operators
// Additional overloads defined outside the class
// to allow for cases where the SafeInt is the rhs value
// Less than
template < typename U >
bool operator <( U rhs ) const throw()
{
return GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( rhs, m_int );
}
bool operator <( SafeInt< T, E > rhs ) const throw()
{
return m_int < (T)rhs;
}
// Greater than or eq.
template < typename U >
bool operator >=( U rhs ) const throw()
{
return !GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( rhs, m_int );
}
bool operator >=( SafeInt< T, E > rhs ) const throw()
{
return m_int >= (T)rhs;
}
// Greater than
template < typename U >
bool operator >( U rhs ) const throw()
{
return GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( m_int, rhs );
}
bool operator >( SafeInt< T, E > rhs ) const throw()
{
return m_int > (T)rhs;
}
// Less than or eq.
template < typename U >
bool operator <=( U rhs ) const throw()
{
return !GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( m_int, rhs );
}
bool operator <=( SafeInt< T, E > rhs ) const throw()
{
return m_int <= (T)rhs;
}
// Equality
template < typename U >
bool operator ==( U rhs ) const throw()
{
return EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( m_int, rhs );
}
// Need an explicit override for type bool
bool operator ==( bool rhs ) const throw()
{
return ( m_int == 0 ? false : true ) == rhs;
}
bool operator ==( SafeInt< T, E > rhs ) const throw() { return m_int == (T)rhs; }
// != operators
template < typename U >
bool operator !=( U rhs ) const throw()
{
return !EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( m_int, rhs );
}
bool operator !=( bool b ) const throw()
{
return ( m_int == 0 ? false : true ) != b;
}
bool operator !=( SafeInt< T, E > rhs ) const throw() { return m_int != (T)rhs; }
// Shift operators
// Note - shift operators ALWAYS return the same type as the lhs
// specific version for SafeInt< T, E > not needed -
// code path is exactly the same as for SafeInt< U, E > as rhs
// Left shift
// Also, shifting > bitcount is undefined - trap in debug
#ifdef SAFEINT_DISABLE_SHIFT_ASSERT
#define ShiftAssert(x)
#else
#define ShiftAssert(x) assert(x)
#endif
template < typename U >
SafeInt< T, E > operator <<( U bits ) const throw()
{
ShiftAssert( !IntTraits< U >::isSigned || bits >= 0 );
ShiftAssert( bits < (int)IntTraits< T >::bitCount );
return SafeInt< T, E >( (T)( m_int << bits ) );
}
template < typename U >
SafeInt< T, E > operator <<( SafeInt< U, E > bits ) const throw()
{
ShiftAssert( !IntTraits< U >::isSigned || (U)bits >= 0 );
ShiftAssert( (U)bits < (int)IntTraits< T >::bitCount );
return SafeInt< T, E >( (T)( m_int << (U)bits ) );
}
// Left shift assignment
template < typename U >
SafeInt< T, E >& operator <<=( U bits ) throw()
{
ShiftAssert( !IntTraits< U >::isSigned || bits >= 0 );
ShiftAssert( bits < (int)IntTraits< T >::bitCount );
m_int <<= bits;
return *this;
}
template < typename U >
SafeInt< T, E >& operator <<=( SafeInt< U, E > bits ) throw()
{
ShiftAssert( !IntTraits< U >::isSigned || (U)bits >= 0 );
ShiftAssert( (U)bits < (int)IntTraits< T >::bitCount );
m_int <<= (U)bits;
return *this;
}
// Right shift
template < typename U >
SafeInt< T, E > operator >>( U bits ) const throw()
{
ShiftAssert( !IntTraits< U >::isSigned || bits >= 0 );
ShiftAssert( bits < (int)IntTraits< T >::bitCount );
return SafeInt< T, E >( (T)( m_int >> bits ) );
}
template < typename U >
SafeInt< T, E > operator >>( SafeInt< U, E > bits ) const throw()
{
ShiftAssert( !IntTraits< U >::isSigned || (U)bits >= 0 );
ShiftAssert( bits < (int)IntTraits< T >::bitCount );
return SafeInt< T, E >( (T)(m_int >> (U)bits) );
}
// Right shift assignment
template < typename U >
SafeInt< T, E >& operator >>=( U bits ) throw()
{
ShiftAssert( !IntTraits< U >::isSigned || bits >= 0 );
ShiftAssert( bits < (int)IntTraits< T >::bitCount );
m_int >>= bits;
return *this;
}
template < typename U >
SafeInt< T, E >& operator >>=( SafeInt< U, E > bits ) throw()
{
ShiftAssert( !IntTraits< U >::isSigned || (U)bits >= 0 );
ShiftAssert( (U)bits < (int)IntTraits< T >::bitCount );
m_int >>= (U)bits;
return *this;
}
// Bitwise operators
// This only makes sense if we're dealing with the same type and size
// demand a type T, or something that fits into a type T
// Bitwise &
SafeInt< T, E > operator &( SafeInt< T, E > rhs ) const throw()
{
return SafeInt< T, E >( m_int & (T)rhs );
}
template < typename U >
SafeInt< T, E > operator &( U rhs ) const throw()
{
// we want to avoid setting bits by surprise
// consider the case of lhs = int, value = 0xffffffff
// rhs = char, value = 0xff
//
// programmer intent is to get only the lower 8 bits
// normal behavior is to upcast both sides to an int
// which then sign extends rhs, setting all the bits
// If you land in the assert, this is because the bitwise operator
// was causing unexpected behavior. Fix is to properly cast your inputs
// so that it works like you meant, not unexpectedly
return SafeInt< T, E >( BinaryAndHelper< T, U, BinaryMethod< T, U >::method >::And( m_int, rhs ) );
}
// Bitwise & assignment
SafeInt< T, E >& operator &=( SafeInt< T, E > rhs ) throw()
{
m_int &= (T)rhs;
return *this;
}
template < typename U >
SafeInt< T, E >& operator &=( U rhs ) throw()
{
m_int = BinaryAndHelper< T, U, BinaryMethod< T, U >::method >::And( m_int, rhs );
return *this;
}
template < typename U >
SafeInt< T, E >& operator &=( SafeInt< U, E > rhs ) throw()
{
m_int = BinaryAndHelper< T, U, BinaryMethod< T, U >::method >::And( m_int, (U)rhs );
return *this;
}
// XOR
SafeInt< T, E > operator ^( SafeInt< T, E > rhs ) const throw()
{
return SafeInt< T, E >( (T)( m_int ^ (T)rhs ) );
}
template < typename U >
SafeInt< T, E > operator ^( U rhs ) const throw()
{
// If you land in the assert, this is because the bitwise operator
// was causing unexpected behavior. Fix is to properly cast your inputs
// so that it works like you meant, not unexpectedly
return SafeInt< T, E >( BinaryXorHelper< T, U, BinaryMethod< T, U >::method >::Xor( m_int, rhs ) );
}
// XOR assignment
SafeInt< T, E >& operator ^=( SafeInt< T, E > rhs ) throw()
{
m_int ^= (T)rhs;
return *this;
}
template < typename U >
SafeInt< T, E >& operator ^=( U rhs ) throw()
{
m_int = BinaryXorHelper< T, U, BinaryMethod< T, U >::method >::Xor( m_int, rhs );
return *this;
}
template < typename U >
SafeInt< T, E >& operator ^=( SafeInt< U, E > rhs ) throw()
{
m_int = BinaryXorHelper< T, U, BinaryMethod< T, U >::method >::Xor( m_int, (U)rhs );
return *this;
}
// bitwise OR
SafeInt< T, E > operator |( SafeInt< T, E > rhs ) const throw()
{
return SafeInt< T, E >( (T)( m_int | (T)rhs ) );
}
template < typename U >
SafeInt< T, E > operator |( U rhs ) const throw()
{
return SafeInt< T, E >( BinaryOrHelper< T, U, BinaryMethod< T, U >::method >::Or( m_int, rhs ) );
}
// bitwise OR assignment
SafeInt< T, E >& operator |=( SafeInt< T, E > rhs ) throw()
{
m_int |= (T)rhs;
return *this;
}
template < typename U >
SafeInt< T, E >& operator |=( U rhs ) throw()
{
m_int = BinaryOrHelper< T, U, BinaryMethod< T, U >::method >::Or( m_int, rhs );
return *this;
}
template < typename U >
SafeInt< T, E >& operator |=( SafeInt< U, E > rhs ) throw()
{
m_int = BinaryOrHelper< T, U, BinaryMethod< T, U >::method >::Or( m_int, (U)rhs );
return *this;
}
// Miscellaneous helper functions
SafeInt< T, E > Min( SafeInt< T, E > test, SafeInt< T, E > floor = IntTraits< T >::minInt ) const throw()
{
T tmp = test < m_int ? (T)test : m_int;
return tmp < floor ? (T)floor : tmp;
}
SafeInt< T, E > Max( SafeInt< T, E > test, SafeInt< T, E > upper = IntTraits< T >::maxInt ) const throw()
{
T tmp = test > m_int ? (T)test : m_int;
return tmp > upper ? (T)upper : tmp;
}
void Swap( SafeInt< T, E >& with ) throw()
{
T temp( m_int );
m_int = with.m_int;
with.m_int = temp;
}
static SafeInt< T, E > SafeAtoI( const char* input )
{
return SafeTtoI( input );
}
static SafeInt< T, E > SafeWtoI( const wchar_t* input )
{
return SafeTtoI( input );
}
enum alignBits
{
align2 = 1,
align4 = 2,
align8 = 3,
align16 = 4,
align32 = 5,
align64 = 6,
align128 = 7,
align256 = 8
};
template < alignBits bits >
const SafeInt< T, E >& Align()
{
// Zero is always aligned
if( m_int == 0 )
return *this;
// We don't support aligning negative numbers at this time
// Can't align unsigned numbers on bitCount (e.g., 8 bits = 256, unsigned char max = 255)
// or signed numbers on bitCount-1 (e.g., 7 bits = 128, signed char max = 127).
// Also makes no sense to try to align on negative or no bits.
ShiftAssert( ( ( IntTraits<T>::isSigned && bits < (int)IntTraits< T >::bitCount - 1 )
|| ( !IntTraits<T>::isSigned && bits < (int)IntTraits< T >::bitCount ) ) &&
bits >= 0 && ( !IntTraits<T>::isSigned || m_int > 0 ) );
const T AlignValue = ( (T)1 << bits ) - 1;
m_int = ( m_int + AlignValue ) & ~AlignValue;
if( m_int <= 0 )
E::SafeIntOnOverflow();
return *this;
}
// Commonly needed alignments:
const SafeInt< T, E >& Align2() { return Align< align2 >(); }
const SafeInt< T, E >& Align4() { return Align< align4 >(); }
const SafeInt< T, E >& Align8() { return Align< align8 >(); }
const SafeInt< T, E >& Align16() { return Align< align16 >(); }
const SafeInt< T, E >& Align32() { return Align< align32 >(); }
const SafeInt< T, E >& Align64() { return Align< align64 >(); }
private:
// This is almost certainly not the best optimized version of atoi,
// but it does not display a typical bug where it isn't possible to set MinInt
// and it won't allow you to overflow your integer.
// This is here because it is useful, and it is an example of what
// can be done easily with SafeInt.
template < typename U >
static SafeInt< T, E > SafeTtoI( U* input )
{
U* tmp = input;
SafeInt< T, E > s;
bool negative = false;
// Bad input, or empty string
if( input == NULL || input[0] == 0 )
E::SafeIntOnOverflow();
switch( *tmp )
{
case '-':
tmp++;
negative = true;
break;
case '+':
tmp++;
break;
}
while( *tmp != 0 )
{
if( *tmp < '0' || *tmp > '9' )
break;
if( (T)s != 0 )
s *= (T)10;
if( !negative )
s += (T)( *tmp - '0' );
else
s -= (T)( *tmp - '0' );
tmp++;
}
return s;
}
T m_int;
};
// Helper function used to subtract pointers.
// Used to squelch warnings
template <typename P>
SafeInt<ptrdiff_t, SafeIntDefaultExceptionHandler> SafePtrDiff(const P* p1, const P* p2)
{
return SafeInt<ptrdiff_t, SafeIntDefaultExceptionHandler>( p1 - p2 );
}
// Externally defined functions for the case of U op SafeInt< T, E >
template < typename T, typename U, typename E >
bool operator <( U lhs, SafeInt< T, E > rhs ) throw()
{
return GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( (T)rhs, lhs );
}
template < typename T, typename U, typename E >
bool operator <( SafeInt< U, E > lhs, SafeInt< T, E > rhs ) throw()
{
return GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( (T)rhs, (U)lhs );
}
// Greater than
template < typename T, typename U, typename E >
bool operator >( U lhs, SafeInt< T, E > rhs ) throw()
{
return GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( lhs, (T)rhs );
}
template < typename T, typename U, typename E >
bool operator >( SafeInt< T, E > lhs, SafeInt< U, E > rhs ) throw()
{
return GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( (T)lhs, (U)rhs );
}
// Greater than or equal
template < typename T, typename U, typename E >
bool operator >=( U lhs, SafeInt< T, E > rhs ) throw()
{
return !GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( (T)rhs, lhs );
}
template < typename T, typename U, typename E >
bool operator >=( SafeInt< T, E > lhs, SafeInt< U, E > rhs ) throw()
{
return !GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( (U)rhs, (T)lhs );
}
// Less than or equal
template < typename T, typename U, typename E >
bool operator <=( U lhs, SafeInt< T, E > rhs ) throw()
{
return !GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( lhs, (T)rhs );
}
template < typename T, typename U, typename E >
bool operator <=( SafeInt< T, E > lhs, SafeInt< U, E > rhs ) throw()
{
return !GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( (T)lhs, (U)rhs );
}
// equality
// explicit overload for bool
template < typename T, typename E >
bool operator ==( bool lhs, SafeInt< T, E > rhs ) throw()
{
return lhs == ( (T)rhs == 0 ? false : true );
}
template < typename T, typename U, typename E >
bool operator ==( U lhs, SafeInt< T, E > rhs ) throw()
{
return EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals((T)rhs, lhs);
}
template < typename T, typename U, typename E >
bool operator ==( SafeInt< T, E > lhs, SafeInt< U, E > rhs ) throw()
{
return EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( (T)lhs, (U)rhs );
}
//not equals
template < typename T, typename U, typename E >
bool operator !=( U lhs, SafeInt< T, E > rhs ) throw()
{
return !EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( rhs, lhs );
}
template < typename T, typename E >
bool operator !=( bool lhs, SafeInt< T, E > rhs ) throw()
{
return ( (T)rhs == 0 ? false : true ) != lhs;
}
template < typename T, typename U, typename E >
bool operator !=( SafeInt< T, E > lhs, SafeInt< U, E > rhs ) throw()
{
return !EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( lhs, rhs );
}
// Modulus
template < typename T, typename U, typename E >
SafeInt< T, E > operator %( U lhs, SafeInt< T, E > rhs )
{
// Value of return depends on sign of lhs
// This one may not be safe - bounds check in constructor
// if lhs is negative and rhs is unsigned, this will throw an exception.
// Fast-track the simple case
// same size and same sign
if( sizeof(T) == sizeof(U) &&
(bool)IntTraits< T >::isSigned == (bool)IntTraits< U >::isSigned )
{
if( rhs != 0 )
{
if( IntTraits< T >::isSigned && (T)rhs == -1 )
return 0;
return SafeInt< T, E >( (T)( lhs % (T)rhs ) );
}
E::SafeIntOnDivZero();
}
return SafeInt< T, E >( ( SafeInt< U, E >( lhs ) % (T)rhs ) );
}
// Multiplication
template < typename T, typename U, typename E >
SafeInt< T, E > operator *( U lhs, SafeInt< T, E > rhs )
{
T ret( 0 );
MultiplicationHelper< T, U, MultiplicationMethod< T, U >::method >::template MultiplyThrow< E >( (T)rhs, lhs, ret );
return SafeInt< T, E >(ret);
}
// Division
template < typename T, typename U, typename E > SafeInt< T, E > operator /( U lhs, SafeInt< T, E > rhs )
{
// Corner case - has to be handled seperately
if( (int)DivisionMethod< U, T >::method == (int)DivisionState_UnsignedSigned )
{
if( (T)rhs > 0 )
return SafeInt< T, E >( lhs/(T)rhs );
// Now rhs is either negative, or zero
if( (T)rhs != 0 )
{
if( sizeof( U ) >= 4 && sizeof( T ) <= sizeof( U ) )
{
// Problem case - normal casting behavior changes meaning
// flip rhs to positive
// any operator casts now do the right thing
U tmp;
if( sizeof(T) == 4 )
tmp = lhs/(U)(unsigned __int32)( -(T)rhs );
else
tmp = lhs/(U)( -(T)rhs );
if( tmp <= IntTraits< T >::maxInt )
return SafeInt< T, E >( -( (T)tmp ) );
// Corner case
#pragma warning(push)
#pragma warning(disable:4307)
// Note - this warning happens because we're not using partial
// template specialization in this case. For any real cases where
// this block isn't optimized out, the warning won't be present.
T maxT = IntTraits< T >::maxInt;
if( tmp == (U)maxT + 1 )
{
T minT = IntTraits< T >::minInt;
return SafeInt< T, E >( minT );
}
#pragma warning(pop)
E::SafeIntOnOverflow();
}
return SafeInt< T, E >(lhs/(T)rhs);
}
E::SafeIntOnDivZero();
} // method == DivisionState_UnsignedSigned
if( SafeIntCompare< T, U >::isBothSigned )
{
if( lhs == IntTraits< U >::minInt && (T)rhs == -1 )
{
// corner case of a corner case - lhs = min int, rhs = -1,
// but rhs is the return type, so in essence, we can return -lhs
// if rhs is a larger type than lhs
if( sizeof( U ) < sizeof( T ) )
return SafeInt< T, E >( (T)( -(T)IntTraits< U >::minInt ) );
// If rhs is smaller or the same size int, then -minInt won't work
E::SafeIntOnOverflow();
}
}
// Otherwise normal logic works with addition of bounds check when casting from U->T
U ret;
DivisionHelper< U, T, DivisionMethod< U, T >::method >::template DivideThrow< E >( lhs, (T)rhs, ret );
return SafeInt< T, E >( ret );
}
// Addition
template < typename T, typename U, typename E >
SafeInt< T, E > operator +( U lhs, SafeInt< T, E > rhs )
{
T ret( 0 );
AdditionHelper< T, U, AdditionMethod< T, U >::method >::template AdditionThrow< E >( (T)rhs, lhs, ret );
return SafeInt< T, E >( ret );
}
// Subtraction
template < typename T, typename U, typename E >
SafeInt< T, E > operator -( U lhs, SafeInt< T, E > rhs )
{
T ret( 0 );
SubtractionHelper< U, T, SubtractionMethod2< U, T >::method >::template SubtractThrow< E >( lhs, rhs.Ref(), ret );
return SafeInt< T, E >( ret );
}
// Overrides designed to deal with cases where a SafeInt is assigned out
// to a normal int - this at least makes the last operation safe
// +=
template < typename T, typename U, typename E >
T& operator +=( T& lhs, SafeInt< U, E > rhs )
{
T ret( 0 );
AdditionHelper< T, U, AdditionMethod< T, U >::method >::template AdditionThrow< E >( lhs, (U)rhs, ret );
lhs = ret;
return lhs;
}
template < typename T, typename U, typename E >
T& operator -=( T& lhs, SafeInt< U, E > rhs )
{
T ret( 0 );
SubtractionHelper< T, U, SubtractionMethod< T, U >::method >::template SubtractThrow< E >( lhs, (U)rhs, ret );
lhs = ret;
return lhs;
}
template < typename T, typename U, typename E >
T& operator *=( T& lhs, SafeInt< U, E > rhs )
{
T ret( 0 );
MultiplicationHelper< T, U, MultiplicationMethod< T, U >::method >::template MultiplyThrow< E >( lhs, (U)rhs, ret );
lhs = ret;
return lhs;
}
template < typename T, typename U, typename E >
T& operator /=( T& lhs, SafeInt< U, E > rhs )
{
T ret( 0 );
DivisionHelper< T, U, DivisionMethod< T, U >::method >::template DivideThrow< E >( lhs, (U)rhs, ret );
lhs = ret;
return lhs;
}
template < typename T, typename U, typename E >
T& operator %=( T& lhs, SafeInt< U, E > rhs )
{
T ret( 0 );
ModulusHelper< T, U, ValidComparison< T, U >::method >::template ModulusThrow< E >( lhs, (U)rhs, ret );
lhs = ret;
return lhs;
}
template < typename T, typename U, typename E >
T& operator &=( T& lhs, SafeInt< U, E > rhs ) throw()
{
lhs = BinaryAndHelper< T, U, BinaryMethod< T, U >::method >::And( lhs, (U)rhs );
return lhs;
}
template < typename T, typename U, typename E >
T& operator ^=( T& lhs, SafeInt< U, E > rhs ) throw()
{
lhs = BinaryXorHelper< T, U, BinaryMethod< T, U >::method >::Xor( lhs, (U)rhs );
return lhs;
}
template < typename T, typename U, typename E >
T& operator |=( T& lhs, SafeInt< U, E > rhs ) throw()
{
lhs = BinaryOrHelper< T, U, BinaryMethod< T, U >::method >::Or( lhs, (U)rhs );
return lhs;
}
template < typename T, typename U, typename E >
T& operator <<=( T& lhs, SafeInt< U, E > rhs ) throw()
{
lhs = (T)( SafeInt< T, E >( lhs ) << (U)rhs );
return lhs;
}
template < typename T, typename U, typename E >
T& operator >>=( T& lhs, SafeInt< U, E > rhs ) throw()
{
lhs = (T)( SafeInt< T, E >( lhs ) >> (U)rhs );
return lhs;
}
// Specific pointer overrides
// Note - this function makes no attempt to ensure
// that the resulting pointer is still in the buffer, only
// that no int overflows happened on the way to getting the new pointer
template < typename T, typename U, typename E >
T*& operator +=( T*& lhs, SafeInt< U, E > rhs )
{
// Cast the pointer to a number so we can do arithmetic
SafeInt< uintptr_t, E > ptr_val = reinterpret_cast< uintptr_t >( lhs );
// Check first that rhs is valid for the type of ptrdiff_t
// and that multiplying by sizeof( T ) doesn't overflow a ptrdiff_t
// Next, we need to add 2 SafeInts of different types, so unbox the ptr_diff
// Finally, cast the number back to a pointer of the correct type
lhs = reinterpret_cast< T* >( (uintptr_t)( ptr_val + (ptrdiff_t)( SafeInt< ptrdiff_t, E >( rhs ) * sizeof( T ) ) ) );
return lhs;
}
template < typename T, typename U, typename E >
T*& operator -=( T*& lhs, SafeInt< U, E > rhs )
{
// Cast the pointer to a number so we can do arithmetic
SafeInt< size_t, E > ptr_val = reinterpret_cast< uintptr_t >( lhs );
// See above for comments
lhs = reinterpret_cast< T* >( (uintptr_t)( ptr_val - (ptrdiff_t)( SafeInt< ptrdiff_t, E >( rhs ) * sizeof( T ) ) ) );
return lhs;
}
template < typename T, typename U, typename E >
T*& operator *=( T*& lhs, SafeInt< U, E > rhs )
{
// This operator explicitly not supported
C_ASSERT( sizeof(T) == 0 );
return (lhs = NULL);
}
template < typename T, typename U, typename E >
T*& operator /=( T*& lhs, SafeInt< U, E > rhs )
{
// This operator explicitly not supported
C_ASSERT( sizeof(T) == 0 );
return (lhs = NULL);
}
template < typename T, typename U, typename E >
T*& operator %=( T*& lhs, SafeInt< U, E > rhs )
{
// This operator explicitly not supported
C_ASSERT( sizeof(T) == 0 );
return (lhs = NULL);
}
template < typename T, typename U, typename E >
T*& operator &=( T*& lhs, SafeInt< U, E > rhs )
{
// This operator explicitly not supported
C_ASSERT( sizeof(T) == 0 );
return (lhs = NULL);
}
template < typename T, typename U, typename E >
T*& operator ^=( T*& lhs, SafeInt< U, E > rhs )
{
// This operator explicitly not supported
C_ASSERT( sizeof(T) == 0 );
return (lhs = NULL);
}
template < typename T, typename U, typename E >
T*& operator |=( T*& lhs, SafeInt< U, E > rhs )
{
// This operator explicitly not supported
C_ASSERT( sizeof(T) == 0 );
return (lhs = NULL);
}
template < typename T, typename U, typename E >
T*& operator <<=( T*& lhs, SafeInt< U, E > rhs )
{
// This operator explicitly not supported
C_ASSERT( sizeof(T) == 0 );
return (lhs = NULL);
}
template < typename T, typename U, typename E >
T*& operator >>=( T*& lhs, SafeInt< U, E > rhs )
{
// This operator explicitly not supported
C_ASSERT( sizeof(T) == 0 );
return (lhs = NULL);
}
// Shift operators
// NOTE - shift operators always return the type of the lhs argument
// Left shift
template < typename T, typename U, typename E >
SafeInt< U, E > operator <<( U lhs, SafeInt< T, E > bits ) throw()
{
ShiftAssert( !IntTraits< T >::isSigned || (T)bits >= 0 );
ShiftAssert( (T)bits < (int)IntTraits< U >::bitCount );
return SafeInt< U, E >( (U)( lhs << (T)bits ) );
}
// Right shift
template < typename T, typename U, typename E >
SafeInt< U, E > operator >>( U lhs, SafeInt< T, E > bits ) throw()
{
ShiftAssert( !IntTraits< T >::isSigned || (T)bits >= 0 );
ShiftAssert( (T)bits < (int)IntTraits< U >::bitCount );
return SafeInt< U, E >( (U)( lhs >> (T)bits ) );
}
// Bitwise operators
// This only makes sense if we're dealing with the same type and size
// demand a type T, or something that fits into a type T.
// Bitwise &
template < typename T, typename U, typename E >
SafeInt< T, E > operator &( U lhs, SafeInt< T, E > rhs ) throw()
{
return SafeInt< T, E >( BinaryAndHelper< T, U, BinaryMethod< T, U >::method >::And( (T)rhs, lhs ) );
}
// Bitwise XOR
template < typename T, typename U, typename E >
SafeInt< T, E > operator ^( U lhs, SafeInt< T, E > rhs ) throw()
{
return SafeInt< T, E >(BinaryXorHelper< T, U, BinaryMethod< T, U >::method >::Xor( (T)rhs, lhs ) );
}
// Bitwise OR
template < typename T, typename U, typename E >
SafeInt< T, E > operator |( U lhs, SafeInt< T, E > rhs ) throw()
{
return SafeInt< T, E >( BinaryOrHelper< T, U, BinaryMethod< T, U >::method >::Or( (T)rhs, lhs ) );
}
#pragma warning(pop)
#endif //SAFEINT_HPP
Version 3.0.14p
/*-----------------------------------------------------------------------------------------------------------
SafeInt.hpp
Version 3.0.14p
This software is licensed under the Microsoft Public License (Ms-PL).
For more information about Microsoft open source licenses, refer to
http://www.microsoft.com/opensource/licenses.mspx
This license governs use of the accompanying software. If you use the software, you accept this license.
If you do not accept the license, do not use the software.
Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here
as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to
the software. A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations
in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to
reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution
or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in
section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed
patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution
in the software or derivative works of the contribution in the software.
Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo,
or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the
software, your patent license from such contributor to the software ends automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and
attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only under this license
by including a complete copy of this license with your distribution. If you distribute any portion of the
software in compiled or object code form, you may only do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties,
guarantees, or conditions. You may have additional consumer rights under your local laws which this license
cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties
of merchantability, fitness for a particular purpose and non-infringement.
Copyright (c) Microsoft Corporation. All rights reserved.
This header implements an integer handling class designed to catch
unsafe integer operations
This header compiles properly at warning level 4.
Please read the leading comments before using the class.
Version 3.0
---------------------------------------------------------------*/
#ifndef SAFEINT_HPP
#define SAFEINT_HPP
#include <assert.h>
#ifndef C_ASSERT
#define C_ASSERT(e) typedef char __C_ASSERT__[(e)?1:-1]
#endif
/************* Compiler Options *****************************************************************************************************
SafeInt supports several compile-time options that can change the behavior of the class.
Compiler options:
SAFEINT_WARN_64BIT_PORTABILITY - this re-enables various warnings that happen when /Wp64 is used. Enabling this option is not
recommended.
NEEDS_INT_DEFINED - if your compiler does not support __int8, __int16, __int32 and __int64, you can enable this.
SAFEINT_ASSERT_ON_EXCEPTION - it is often easier to stop on an assert and figure out a problem than to try and figure out
how you landed in the catch block.
SafeIntDefaultExceptionHandler - if you'd like to replace the exception handlers SafeInt provides, define your replacement and
define this.
SAFEINT_DISALLOW_UNSIGNED_NEGATION - Invoking the unary negation operator creates warnings, but if you'd like it to completely fail
to compile, define this.
ANSI_CONVERSIONS - This changes the class to use default comparison behavior, which may be unsafe. Enabling this
option is not recommended.
SAFEINT_DISABLE_BINARY_ASSERT - binary AND, OR or XOR operations on mixed size types can produce unexpected results. If you do
this, the default is to assert. Set this if you prefer not to assert under these conditions.
SIZE_T_CAST_NEEDED - some compilers complain if there is not a cast to size_t, others complain if there is one.
This lets you not have your compiler complain.
SAFEINT_DISABLE_SHIFT_ASSERT - Set this option if you don't want to assert when shifting more bits than the type has. Enabling
this option is not recommended.
************************************************************************************************************************************/
/*
* The SafeInt class is designed to have as low an overhead as possible
* while still ensuring that all integer operations are conducted safely.
* Nearly every operator has been overloaded, with a very few exceptions.
*
* A usability-safety trade-off has been made to help ensure safety. This
* requires that every operation return either a SafeInt or a bool. If we
* allowed an operator to return a base integer type T, then the following
* can happen:
*
* char i = SafeInt<char>(32) * 2 + SafeInt<char>(16) * 4;
*
* The * operators take precedence, get overloaded, return a char, and then
* you have:
*
* char i = (char)64 + (char)64; //overflow!
*
* This situation would mean that safety would depend on usage, which isn't
* acceptable.
*
* One key operator that is missing is an implicit cast to type T. The reason for
* this is that if there is an implicit cast operator, then we end up with
* an ambiguous compile-time precedence. Because of this amiguity, there
* are two methods that are provided:
*
* Casting operators for every native integer type
* Version 3 note - it now compiles correctly for size_t without warnings
*
* SafeInt::Ptr() - returns the address of the internal integer
* Note - the '&' (address of) operator has been overloaded and returns
* the address of the internal integer.
*
* The SafeInt class should be used in any circumstances where ensuring
* integrity of the calculations is more important than performance. See Performance
* Notes below for additional information.
*
* Many of the conditionals will optimize out or be inlined for a release
* build (especially with /Ox), but it does have significantly more overhead,
* especially for signed numbers. If you do not _require_ negative numbers, use
* unsigned integer types - certain types of problems cannot occur, and this class
* performs most efficiently.
*
* Here's an example of when the class should ideally be used -
*
* void* AllocateMemForStructs(int StructSize, int HowMany)
* {
* SafeInt<unsigned long> s(StructSize);
*
* s *= HowMany;
*
* return malloc(s);
*
* }
*
* Here's when it should NOT be used:
*
* void foo()
* {
* int i;
*
* for(i = 0; i < 0xffff; i++)
* ....
* }
*
* Error handling - a SafeInt class will throw exceptions if something
* objectionable happens. The exceptions are SafeIntException classes,
* which contain an enum as a code.
*
* Typical usage might be:
*
* bool foo()
* {
* SafeInt<unsigned long> s; //note that s == 0 unless set
*
* try{
* s *= 23;
* ....
* }
* catch(SafeIntException err)
* {
* //handle errors here
* }
* }
*
* Update for 3.0 - the exception class is now a template parameter.
* You can replace the exception class with any exception class you like. This is accomplished by:
* 1) Create a class that has the following interface:
*
template <> class YourSafeIntExceptionHandler < YourException >
{
public:
static __declspec(noreturn) void __stdcall SafeIntOnOverflow()
{
throw YourException( YourSafeIntArithmeticOverflowError );
}
static __declspec(noreturn) void __stdcall SafeIntOnDivZero()
{
throw YourException( YourSafeIntDivideByZeroError );
}
};
*
* Note that you don't have to throw C++ exceptions, you can throw Win32 exceptions, or do
* anything you like, just don't return from the call back into the code.
*
* 2) Either explicitly declare SafeInts like so:
* SafeInt< int, YourSafeIntExceptionHandler > si;
* or
* #define SafeIntDefaultExceptionHandler YourSafeIntExceptionHandler
*
* Performance:
*
* Due to the highly nested nature of this class, you can expect relatively poor
* performance in unoptimized code. In tests of optimized code vs. correct inline checks
* in native code, this class has been found to take approximately 8% more CPU time (this varies),
* most of which is due to exception handling. Solutions:
*
* 1) Compile optimized code - /Ox is best, /O2 also performs well. Interestingly, /O1
* (optimize for size) does not work as well.
* 2) If that 8% hit is really a serious problem, walk through the code and inline the
* exact same checks as the class uses.
* 3) Some operations are more difficult than others - avoid using signed integers, and if
* possible keep them all the same size. 64-bit integers are also expensive. Mixing
* different integer sizes and types may prove expensive. Be aware that literals are
* actually ints. For best performance, cast literals to the type desired.
*
*
* Performance update
* The current version of SafeInt uses template specialization to force the compiler to invoke only the
* operator implementation needed for any given pair of types. This will dramatically improve the perf
* of debug builds.
*
* 3.0 update - not only have we maintained the specialization, there were some cases that were overly complex,
* and using some additional cases (e.g. signed __int64 and unsigned __int64) resulted in some simplification.
* Additionally, there was a lot of work done to better optimize the 64-bit multiplication.
*
* Binary Operators
*
* All of the binary operators have certain assumptions built into the class design.
* This is to ensure correctness. Notes on each class of operator follow:
*
* Arithmetic Operators (*,/,+,-,%)
* There are three possible variants:
* SafeInt< T, E > op SafeInt< T, E >
* SafeInt< T, E > op U
* U op SafeInt< T, E >
*
* The SafeInt< T, E > op SafeInt< U, E > variant is explicitly not supported, and if you try to do
* this the compiler with throw the following error:
*
* error C2593: 'operator *' is ambiguous
*
* This is because the arithmetic operators are required to return a SafeInt of some type.
* The compiler cannot know whether you'd prefer to get a type T or a type U returned. If
* you need to do this, you need to extract the value contained within one of the two using
* the casting operator. For example:
*
* SafeInt< T, E > t, result;
* SafeInt< U, E > u;
*
* result = t * (U)u;
*
* Comparison Operators
* Because each of these operators return type bool, mixing SafeInts of differing types is
* allowed.
*
* Shift Operators
* Shift operators always return the type on the left hand side of the operator. Mixed type
* operations are allowed because the return type is always known.
*
* Boolean Operators
* Like comparison operators, these overloads always return type bool, and mixed-type SafeInts
* are allowed. Additionally, specific overloads exist for type bool on both sides of the
* operator.
*
* Binary Operators
* Mixed-type operations are discouraged, however some provision has been made in order to
* enable things like:
*
* SafeInt<char> c = 2;
*
* if(c & 0x02)
* ...
*
* The "0x02" is actually an int, and it needs to work.
* In the case of binary operations on integers smaller than 32-bit, or of mixed type, corner
* cases do exist where you could get unexpected results. In any case where SafeInt returns a different
* result than the underlying operator, it will call assert(). You should examine your code and cast things
* properly so that you are not programming with side effects.
*
* Documented issues:
*
* This header compiles correctly at /W4 using VC++ 8 (Version 14.00.50727.42) and later.
* As of this writing, I believe it will also work for VC 7.1, but not for VC 7.0 or below.
* If you need a version that will work with lower level compilers, try version 1.0.7. None
* of them work with Visual C++ 6, and gcc didn't work very well, either, though this hasn't
* been tried recently.
*
* It is strongly recommended that any code doing integer manipulation be compiled at /W4
* - there are a number of warnings which pertain to integer manipulation enabled that are
* not enabled at /W3 (default for VC++)
*
* Perf note - postfix operators are slightly more costly than prefix operators.
* Unless you're actually assigning it to something, ++SafeInt is less expensive than SafeInt++
*
* The comparison operator behavior in this class varies from the ANSI definition, which is
* arguably broken. As an example, consider the following:
*
* unsigned int l = 0xffffffff;
* char c = -1;
*
* if(c == l)
* printf("Why is -1 equal to 4 billion???\n");
*
* The problem here is that c gets cast to an int, now has a value of 0xffffffff, and then gets
* cast again to an unsigned int, losing the true value. This behavior is despite the fact that
* an __int64 exists, and the following code will yield a different (and intuitively correct)
* answer:
*
* if((__int64)c == (__int64)l))
* printf("Why is -1 equal to 4 billion???\n");
* else
* printf("Why doesn't the compiler upcast to 64-bits when needed?\n");
*
* Note that combinations with smaller integers won't display the problem - if you
* changed "unsigned int" above to "unsigned short", you'd get the right answer.
*
* If you prefer to retain the ANSI standard behavior insert
* #define ANSI_CONVERSIONS
* into your source. Behavior differences occur in the following cases:
* 8, 16, and 32-bit signed int, unsigned 32-bit int
* any signed int, unsigned 64-bit int
* Note - the signed int must be negative to show the problem
*
*
* Revision history:
*
* Oct 12, 2003 - Created
* Author - David LeBlanc - dleblanc@microsoft.com
*
* Oct 27, 2003 - fixed numerous items pointed out by michmarc and bdawson
* Dec 28, 2003 - 1.0
* added support for mixed-type operations
* thanks to vikramh
* also fixed broken __int64 multiplication section
* added extended support for mixed-type operations where possible
* Jan 28, 2004 - 1.0.1
* changed WCHAR to wchar_t
* fixed a construct in two mixed-type assignment overloads that was
* not compiling on some compilers
* Also changed name of private method to comply with standards on
* reserved names
* Thanks to Niels Dekker for the input
* Feb 12, 2004 - 1.0.2
* Minor changes to remove dependency on Windows headers
* Consistently used __int16, __int32 and __int64 to ensure
* portability
* May 10, 2004 - 1.0.3
* Corrected bug in one case of GreaterThan
* July 22, 2004 - 1.0.4
* Tightened logic in addition check (saving 2 instructions)
* Pulled error handler out into function to enable user-defined replacement
* Made internal type of SafeIntException an enum (as per Niels' suggestion)
* Added casts for base integer types (as per Scott Meyers' suggestion)
* Updated usage information - see important new perf notes.
* Cleaned up several const issues (more thanks to Niels)
*
* Oct 1, 2004 - 1.0.5
* Added support for SEH exceptions instead of C++ exceptions - Win32 only
* Made handlers for DIV0 and overflows individually overridable
* Commented out the destructor - major perf gains here
* Added cast operator for type long, since long != __int32
* Corrected a couple of missing const modifiers
* Fixed broken >= and <= operators for type U op SafeInt< T, E >
* Nov 5, 2004 - 1.0.6
* Implemented new logic in binary operators to resolve issues with
* implicit casts
* Fixed casting operator because char != signed char
* Defined __int32 as int instead of long
* Removed unsafe SafeInt::Value method
* Re-implemented casting operator as a result of removing Value method
* Dec 1, 2004 - 1.0.7
* Implemented specialized operators for pointer arithmetic
* Created overloads for cases of U op= SafeInt. What you do with U
* after that may be dangerous.
* Fixed bug in corner case of MixedSizeModulus
* Fixed bug in MixedSizeMultiply and MixedSizeDivision with input of 0
* Added throw() decorations
*
* Apr 12, 2005 - 2.0
* Extensive revisions to leverage template specialization.
* April, 2007 Extensive revisions for version 3.0
* Nov 22, 2009 Forked from MS internal code
* Changes needed to support gcc compiler - many thanks to Niels Dekker
* for determining not just the issues, but also suggesting fixes.
* Also updating some of the header internals to be the same as the upcoming Visual Studio version.
*
* Jan 16, 2010 64-bit gcc has long == __int64, which means that many of the existing 64-bit
* templates are over-specialized. This forces a redefinition of all the 64-bit
* multiplication routines to use pointers instead of references for return
* values. Also, let's use some intrinsics for x64 Microsoft compiler to
* reduce code size, and hopefully improve efficiency.
*
* Note about code style - throughout this class, casts will be written using C-style (T),
* not C++ style static_cast< T >. This is because the class is nearly always dealing with integer
* types, and in this case static_cast and a C cast are equivalent. Given the large number of casts,
* the code is a little more readable this way. In the event a cast is needed where static_cast couldn't
* be substituted, we'll use the new templatized cast to make it explicit what the operation is doing.
*
************************************************************************************************************
* Version 3.0 changes:
*
* 1) The exception type thrown is now replacable, and you can throw your own exception types. This should help
* those using well-developed exception classes.
* 2) The 64-bit multiplication code has had a lot of perf work done, and should be faster than 2.0.
* 3) There is now limited floating point support. You can initialize a SafeInt with a floating point type,
* and you can cast it out (or assign) to a float as well.
* 4) There is now an Align method. I noticed people use this a lot, and rarely check errors, so now you have one.
*
* Another major improvement is the addition of external functions - if you just want to check an operation, this can now happen:
* All of the following can be invoked without dealing with creating a class, or managing exceptions. This is especially handy
* for 64-bit porting, since SafeCast compiles away for a 32-bit cast from size_t to unsigned long, but checks it for 64-bit.
*
* inline bool SafeCast( const T From, U& To ) throw()
* inline bool SafeEquals( const T t, const U u ) throw()
* inline bool SafeNotEquals( const T t, const U u ) throw()
* inline bool SafeGreaterThan( const T t, const U u ) throw()
* inline bool SafeGreaterThanEquals( const T t, const U u ) throw()
* inline bool SafeLessThan( const T t, const U u ) throw()
* inline bool SafeLessThanEquals( const T t, const U u ) throw()
* inline bool SafeModulus( const T& t, const U& u, T& result ) throw()
* inline bool SafeMultiply( T t, U u, T& result ) throw()
* inline bool SafeDivide( T t, U u, T& result ) throw()
* inline bool SafeAdd( T t, U u, T& result ) throw()
* inline bool SafeSubtract( T t, U u, T& result ) throw()
*
* * */
#pragma warning(push)
//this avoids warnings from the unary '-' operator being applied to unsigned numbers
#pragma warning(disable:4146)
// conditional expression is constant - these are used intentionally
#pragma warning(disable:4127)
//cast truncates constant value
#pragma warning(disable:4310)
#if !defined SAFEINT_WARN_64BIT_PORTABILITY
// Internally to SafeInt, these should always be false positives.
// If actually compiled with the 64-bit compiler, it would pull in a different template specialization.
#pragma warning(disable:4242)
#pragma warning(disable:4244)
#pragma warning(disable:4267)
#endif
//use these if the compiler does not support _intXX
#ifdef NEEDS_INT_DEFINED
#define __int8 char
#define __int16 short
#define __int32 int
#define __int64 long long
#endif
/* catch these to handle errors
** Currently implemented code values:
** ERROR_ARITHMETIC_OVERFLOW
** EXCEPTION_INT_DIVIDE_BY_ZERO
*/
enum SafeIntError
{
SafeIntNoError = 0,
SafeIntArithmeticOverflow,
SafeIntDivideByZero
};
/*
* Error handler classes
* Using classes to deal with exceptions is going to allow the most
* flexibility, and we can mix different error handlers in the same project
* or even the same file. It isn't advisable to do this in the same function
* because a SafeInt< int, MyExceptionHandler > isn't the same thing as
* SafeInt< int, YourExceptionHander >.
* If for some reason you have to translate between the two, cast one of them back to its
* native type.
*
* To use your own exception class with SafeInt, first create your exception class,
* which may look something like the SafeIntException class below. The second step is to
* create a template specialization that implements SafeIntOnOverflow and SafeIntOnDivZero.
* For example:
*
* template <> class SafeIntExceptionHandler < YourExceptionClass >
* {
* static __declspec(noreturn) void __stdcall SafeIntOnOverflow()
* {
* throw YourExceptionClass( EXCEPTION_INT_OVERFLOW );
* }
*
* static __declspec(noreturn) void __stdcall SafeIntOnDivZero()
* {
* throw YourExceptionClass( EXCEPTION_INT_DIVIDE_BY_ZERO );
* }
* };
*
* typedef SafeIntExceptionHandler < YourExceptionClass > YourSafeIntExceptionHandler
* You'd then declare your SafeInt objects like this:
* SafeInt< int, YourSafeIntExceptionHandler >
*
* Unfortunately, there is no such thing as partial template specialization in typedef
* statements, so you have three options if you find this cumbersome:
*
* 1) Create a holder class:
*
* template < typename T >
* class MySafeInt
* {
* public:
* SafeInt< T, MyExceptionClass> si;
* };
*
* You'd then declare an instance like so:
* MySafeInt< int > i;
*
* You'd lose handy things like initialization - it would have to be initialized as:
*
* i.si = 0;
*
* 2) You could create a typedef for every int type you deal with:
*
* typedef SafeInt< int, MyExceptionClass > MySafeInt;
* typedef SafeInt< char, MyExceptionClass > MySafeChar;
*
* and so on. The second approach is probably more usable, and will just drop into code
* better, which is the original intent of the SafeInt class.
*
* 3) If you're going to consistently use a different class to handle your exceptions,
* you can override the default typedef like so:
*
* #define SafeIntDefaultExceptionHandler YourSafeIntExceptionHandler
*
* Overall, this is probably the best approach.
* */
class SafeIntException
{
public:
SafeIntException() { m_code = SafeIntNoError; }
SafeIntException( SafeIntError code )
{
m_code = code;
}
SafeIntError m_code;
};
#if defined SAFEINT_ASSERT_ON_EXCEPTION
inline void SafeIntExceptionAssert(){ assert(false); }
#else
inline void SafeIntExceptionAssert(){}
#endif
namespace SafeIntInternal
{
template < typename E > class SafeIntExceptionHandler;
template <> class SafeIntExceptionHandler < SafeIntException >
{
public:
#if defined __GNUC__
static void SafeIntOnOverflow()
#else
static __declspec(noreturn) void __stdcall SafeIntOnOverflow()
#endif
{
SafeIntExceptionAssert();
throw SafeIntException( SafeIntArithmeticOverflow );
}
#if defined __GNUC__
static void SafeIntOnDivZero()
#else
static __declspec(noreturn) void __stdcall SafeIntOnDivZero()
#endif
{
SafeIntExceptionAssert();
throw SafeIntException( SafeIntDivideByZero );
}
};
#if defined _WINDOWS_
class SafeIntWin32Exception
{
public:
SafeIntWin32Exception( DWORD dwExceptionCode, DWORD dwExceptionFlags = EXCEPTION_NONCONTINUABLE )
{
SafeIntExceptionAssert();
RaiseException( dwExceptionCode, dwExceptionFlags, 0, 0 );
}
};
template <> class SafeIntExceptionHandler < SafeIntWin32Exception >
{
public:
static __declspec(noreturn) void __stdcall SafeIntOnOverflow()
{
SafeIntExceptionAssert();
SafeIntWin32Exception( EXCEPTION_INT_OVERFLOW );
}
static __declspec(noreturn) void __stdcall SafeIntOnDivZero()
{
SafeIntExceptionAssert();
SafeIntWin32Exception( EXCEPTION_INT_DIVIDE_BY_ZERO );
}
};
#endif
} // namespace SafeIntInternal
typedef SafeIntInternal::SafeIntExceptionHandler < SafeIntException > CPlusPlusExceptionHandler;
#if defined _WINDOWS_
typedef SafeIntInternal::SafeIntExceptionHandler < SafeIntInternal::SafeIntWin32Exception > Win32ExceptionHandler;
#endif
// If the user hasn't defined a default exception handler,
// define one now, depending on whether they would like Win32 or C++ exceptions
#if !defined SafeIntDefaultExceptionHandler
#if defined SAFEINT_RAISE_EXCEPTION
#if !defined _WINDOWS_
#error Include windows.h in order to use Win32 exceptions
#endif
#define SafeIntDefaultExceptionHandler Win32ExceptionHandler
#else
#define SafeIntDefaultExceptionHandler CPlusPlusExceptionHandler
#endif
#endif
/*
* The following template magic is because we're now not allowed
* to cast a float to an enum. This means that if we happen to assign
* an enum to a SafeInt of some type, it won't compile, unless we prevent
* isFloat = ( (T)( (float)1.1 ) > (T)1 )
* from compiling in the case of an enum, which is the point of the specialization
* that follows.
*/
template < typename T > class NumericType;
template <> class NumericType<bool> { public: enum{ isBool = true, isFloat = false, isInt = false }; };
template <> class NumericType<char> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<unsigned char> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<signed char> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<short> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<unsigned short> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
#if defined SAFEINT_USE_WCHAR_T || _NATIVE_WCHAR_T_DEFINED
template <> class NumericType<wchar_t> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
#endif
template <> class NumericType<int> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<unsigned int> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<long> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<unsigned long> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<__int64> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<unsigned __int64> { public: enum{ isBool = false, isFloat = false, isInt = true }; };
template <> class NumericType<float> { public: enum{ isBool = false, isFloat = true, isInt = false }; };
template <> class NumericType<double> { public: enum{ isBool = false, isFloat = true, isInt = false }; };
template <> class NumericType<long double> { public: enum{ isBool = false, isFloat = true, isInt = false }; };
// Catch-all for anything not supported
template < typename T > class NumericType { public: enum{ isBool = false, isFloat = false, isInt = false }; };
template < typename T > class IntTraits
{
public:
C_ASSERT( NumericType<T>::isInt );
enum
{
#pragma warning(suppress:4804)
isSigned = ( (T)(-1) < 0 ),
is64Bit = ( sizeof(T) == 8 ),
is32Bit = ( sizeof(T) == 4 ),
is16Bit = ( sizeof(T) == 2 ),
is8Bit = ( sizeof(T) == 1 ),
isLT32Bit = ( sizeof(T) < 4 ),
isLT64Bit = ( sizeof(T) < 8 ),
isInt8 = ( sizeof(T) == 1 && isSigned ),
isUint8 = ( sizeof(T) == 1 && !isSigned ),
isInt16 = ( sizeof(T) == 2 && isSigned ),
isUint16 = ( sizeof(T) == 2 && !isSigned ),
isInt32 = ( sizeof(T) == 4 && isSigned ),
isUint32 = ( sizeof(T) == 4 && !isSigned ),
isInt64 = ( sizeof(T) == 8 && isSigned ),
isUint64 = ( sizeof(T) == 8 && !isSigned ),
bitCount = ( sizeof(T)*8 ),
#pragma warning(suppress:4804)
isBool = ( (T)2 == (T)1 )
};
// On version 13.10 enums cannot define __int64 values
// so we'll use const statics instead!
const static T maxInt = isSigned ? ((T)~((T)1 << (T)(bitCount-1))) : ((T)(~(T)0));
const static T minInt = isSigned ? ((T)((T)1 << (T)(bitCount-1))) : ((T)0);
};
template < typename T, typename U > class SafeIntCompare
{
public:
enum
{
isBothSigned = (IntTraits< T >::isSigned && IntTraits< U >::isSigned),
isBothUnsigned = (!IntTraits< T >::isSigned && !IntTraits< U >::isSigned),
isLikeSigned = ((bool)(IntTraits< T >::isSigned) == (bool)(IntTraits< U >::isSigned)),
isCastOK = ((isLikeSigned && sizeof(T) >= sizeof(U)) ||
(IntTraits< T >::isSigned && sizeof(T) > sizeof(U))),
isBothLT32Bit = (IntTraits< T >::isLT32Bit && IntTraits< U >::isLT32Bit),
isBothLT64Bit = (IntTraits< T >::isLT64Bit && IntTraits< U >::isLT64Bit)
};
};
//all of the arithmetic operators can be solved by the same code within
//each of these regions without resorting to compile-time constant conditionals
//most operators collapse the problem into less than the 22 zones, but this is used
//as the first cut
//using this also helps ensure that we handle all of the possible cases correctly
template < typename T, typename U > class IntRegion
{
public:
enum
{
//unsigned-unsigned zone
IntZone_UintLT32_UintLT32 = SafeIntCompare< T,U >::isBothUnsigned && SafeIntCompare< T,U >::isBothLT32Bit,
IntZone_Uint32_UintLT64 = SafeIntCompare< T,U >::isBothUnsigned && IntTraits< T >::is32Bit && IntTraits< U >::isLT64Bit,
IntZone_UintLT32_Uint32 = SafeIntCompare< T,U >::isBothUnsigned && IntTraits< T >::isLT32Bit && IntTraits< U >::is32Bit,
IntZone_Uint64_Uint = SafeIntCompare< T,U >::isBothUnsigned && IntTraits< T >::is64Bit,
IntZone_UintLT64_Uint64 = SafeIntCompare< T,U >::isBothUnsigned && IntTraits< T >::isLT64Bit && IntTraits< U >::is64Bit,
//unsigned-signed
IntZone_UintLT32_IntLT32 = !IntTraits< T >::isSigned && IntTraits< U >::isSigned && SafeIntCompare< T,U >::isBothLT32Bit,
IntZone_Uint32_IntLT64 = IntTraits< T >::isUint32 && IntTraits< U >::isSigned && IntTraits< U >::isLT64Bit,
IntZone_UintLT32_Int32 = !IntTraits< T >::isSigned && IntTraits< T >::isLT32Bit && IntTraits< U >::isInt32,
IntZone_Uint64_Int = IntTraits< T >::isUint64 && IntTraits< U >::isSigned && IntTraits< U >::isLT64Bit,
IntZone_UintLT64_Int64 = !IntTraits< T >::isSigned && IntTraits< T >::isLT64Bit && IntTraits< U >::isInt64,
IntZone_Uint64_Int64 = IntTraits< T >::isUint64 && IntTraits< U >::isInt64,
//signed-signed
IntZone_IntLT32_IntLT32 = SafeIntCompare< T,U >::isBothSigned && ::SafeIntCompare< T, U >::isBothLT32Bit,
IntZone_Int32_IntLT64 = SafeIntCompare< T,U >::isBothSigned && IntTraits< T >::is32Bit && IntTraits< U >::isLT64Bit,
IntZone_IntLT32_Int32 = SafeIntCompare< T,U >::isBothSigned && IntTraits< T >::isLT32Bit && IntTraits< U >::is32Bit,
IntZone_Int64_Int64 = SafeIntCompare< T,U >::isBothSigned && IntTraits< T >::isInt64 && IntTraits< U >::isInt64,
IntZone_Int64_Int = SafeIntCompare< T,U >::isBothSigned && IntTraits< T >::is64Bit && IntTraits< U >::isLT64Bit,
IntZone_IntLT64_Int64 = SafeIntCompare< T,U >::isBothSigned && IntTraits< T >::isLT64Bit && IntTraits< U >::is64Bit,
//signed-unsigned
IntZone_IntLT32_UintLT32 = IntTraits< T >::isSigned && !IntTraits< U >::isSigned && SafeIntCompare< T,U >::isBothLT32Bit,
IntZone_Int32_UintLT32 = IntTraits< T >::isInt32 && !IntTraits< U >::isSigned && IntTraits< U >::isLT32Bit,
IntZone_IntLT64_Uint32 = IntTraits< T >::isSigned && IntTraits< T >::isLT64Bit && IntTraits< U >::isUint32,
IntZone_Int64_UintLT64 = IntTraits< T >::isInt64 && !IntTraits< U >::isSigned && IntTraits< U >::isLT64Bit,
IntZone_Int_Uint64 = IntTraits< T >::isSigned && IntTraits< U >::isUint64 && IntTraits< T >::isLT64Bit,
IntZone_Int64_Uint64 = IntTraits< T >::isInt64 && IntTraits< U >::isUint64
};
};
// In all of the following functions, we have two versions
// One for SafeInt, which throws C++ (or possibly SEH) exceptions
// The non-throwing versions are for use by the helper functions that return success and failure.
// Some of the non-throwing functions are not used, but are maintained for completeness.
// There's no real alternative to duplicating logic, but keeping the two versions
// immediately next to one another will help reduce problems
// useful function to help with getting the magnitude of a negative number
enum AbsMethod
{
AbsMethodInt,
AbsMethodInt64,
AbsMethodNoop
};
template < typename T >
class GetAbsMethod
{
public:
enum
{
method = IntTraits< T >::isLT64Bit && IntTraits< T >::isSigned ? AbsMethodInt :
IntTraits< T >::isInt64 ? AbsMethodInt64 : AbsMethodNoop
};
};
template < typename T, int > class AbsValueHelper;
template < typename T > class AbsValueHelper < T, AbsMethodInt>
{
public:
static unsigned __int32 Abs( T t ) throw()
{
assert( t < 0 );
return (unsigned __int32)-t;
}
};
template < typename T > class AbsValueHelper < T, AbsMethodInt64 >
{
public:
static unsigned __int64 Abs( T t ) throw()
{
assert( t < 0 );
return (unsigned __int64)-t;
}
};
template < typename T > class AbsValueHelper < T, AbsMethodNoop >
{
public:
static T Abs( T t ) throw()
{
// Why are you calling Abs on an unsigned number ???
assert( false );
return t;
}
};
template < typename T, bool > class NegationHelper;
template < typename T > class NegationHelper <T, true> // Signed
{
public:
template <typename E>
static T NegativeThrow( T t )
{
// corner case
if( t != IntTraits< T >::minInt )
{
// cast prevents unneeded checks in the case of small ints
return -t;
}
E::SafeIntOnOverflow();
}
static bool Negative( T t, T& ret ) throw()
{
// corner case
if( t != IntTraits< T >::minInt )
{
// cast prevents unneeded checks in the case of small ints
ret = -t;
return true;
}
return false;
}
};
template < typename T > class NegationHelper <T, false> // unsigned
{
public:
template <typename E>
static T NegativeThrow( T t ) throw()
{
if( IntTraits<T>::isLT32Bit )
{
// This will normally upcast to int
// For example -(unsigned short)0xffff == (int)0xffff0001
// This class will retain the type, and will truncate, which may not be what
// you wanted
// If you want normal operator casting behavior, do this:
// SafeInt<unsigned short> ss = 0xffff;
// then:
// -(SafeInt<int>(ss))
// will then emit a signed int with the correct value and bitfield
assert( false );
}
#if defined SAFEINT_DISALLOW_UNSIGNED_NEGATION
C_ASSERT( sizeof(T) == 0 );
#endif
return -t;
}
static bool Negative( T t, T& ret )
{
if( IntTraits<T>::isLT32Bit )
{
// See above
assert( false );
}
#if defined SAFEINT_DISALLOW_UNSIGNED_NEGATION
C_ASSERT( sizeof(T) == 0 );
#endif
ret = -t;
return true;
}
};
//core logic to determine casting behavior
enum CastMethod
{
CastOK = 0,
CastCheckLTZero,
CastCheckGTMax,
CastCheckMinMaxUnsigned,
CastCheckMinMaxSigned,
CastToFloat,
CastFromFloat,
CastToBool,
CastFromBool
};
template < typename ToType, typename FromType >
class GetCastMethod
{
public:
enum
{
method = ( IntTraits< FromType >::isBool &&
!IntTraits< ToType >::isBool ) ? CastFromBool :
( !IntTraits< FromType >::isBool &&
IntTraits< ToType >::isBool ) ? CastToBool :
( SafeIntCompare< ToType, FromType >::isCastOK ) ? CastOK :
( ( IntTraits< ToType >::isSigned &&
!IntTraits< FromType >::isSigned &&
sizeof( FromType ) >= sizeof( ToType ) ) ||
( SafeIntCompare< ToType, FromType >::isBothUnsigned &&
sizeof( FromType ) > sizeof( ToType ) ) ) ? CastCheckGTMax :
( !IntTraits< ToType >::isSigned &&
IntTraits< FromType >::isSigned &&
sizeof( ToType ) >= sizeof( FromType ) ) ? CastCheckLTZero :
( !IntTraits< ToType >::isSigned ) ? CastCheckMinMaxUnsigned
: CastCheckMinMaxSigned
};
};
template < typename FromType > class GetCastMethod < float, FromType >
{
public:
enum{ method = CastOK };
};
template < typename FromType > class GetCastMethod < double, FromType >
{
public:
enum{ method = CastOK };
};
template < typename FromType > class GetCastMethod < long double, FromType >
{
public:
enum{ method = CastOK };
};
template < typename ToType > class GetCastMethod < ToType, float >
{
public:
enum{ method = CastFromFloat };
};
template < typename ToType > class GetCastMethod < ToType, double >
{
public:
enum{ method = CastFromFloat };
};
template < typename ToType > class GetCastMethod < ToType, long double >
{
public:
enum{ method = CastFromFloat };
};
template < typename T, typename U, int > class SafeCastHelper;
template < typename T, typename U > class SafeCastHelper < T, U, CastOK >
{
public:
static bool Cast( U u, T& t ) throw()
{
t = (T)u;
return true;
}
template < typename E >
static void CastThrow( U u, T& t )
{
t = (T)u;
}
};
// special case floats and doubles
// tolerate loss of precision
template < typename T, typename U > class SafeCastHelper < T, U, CastFromFloat >
{
public:
static bool Cast( U u, T& t ) throw()
{
if( u <= (U)IntTraits< T >::maxInt &&
u >= (U)IntTraits< T >::minInt )
{
t = (T)u;
return true;
}
return false;
}
template < typename E >
static void CastThrow( U u, T& t )
{
if( u <= (U)IntTraits< T >::maxInt &&
u >= (U)IntTraits< T >::minInt )
{
t = (T)u;
return;
}
E::SafeIntOnOverflow();
}
};
// Match on any method where a bool is cast to type T
template < typename T > class SafeCastHelper < T, bool, CastFromBool >
{
public:
static bool Cast( bool b, T& t ) throw()
{
t = (T)( b ? 1 : 0 );
return true;
}
template < typename E >
static void CastThrow( bool b, T& t )
{
t = (T)( b ? 1 : 0 );
}
};
template < typename T > class SafeCastHelper < bool, T, CastToBool >
{
public:
static bool Cast( T t, bool& b ) throw()
{
b = !!t;
return true;
}
template < typename E >
static void CastThrow( bool b, T& t )
{
b = !!t;
}
};
template < typename T, typename U > class SafeCastHelper < T, U, CastCheckLTZero >
{
public:
static bool Cast( U u, T& t ) throw()
{
if( u < 0 )
return false;
t = (T)u;
return true;
}
template < typename E >
static void CastThrow( U u, T& t )
{
if( u < 0 )
E::SafeIntOnOverflow();
t = (T)u;
}
};
template < typename T, typename U > class SafeCastHelper < T, U, CastCheckGTMax >
{
public:
static bool Cast( U u, T& t ) throw()
{
if( u > IntTraits< T >::maxInt )
return false;
t = (T)u;
return true;
}
template < typename E >
static void CastThrow( U u, T& t )
{
if( u > IntTraits< T >::maxInt )
E::SafeIntOnOverflow();
t = (T)u;
}
};
template < typename T, typename U > class SafeCastHelper < T, U, CastCheckMinMaxUnsigned >
{
public:
static bool Cast( U u, T& t ) throw()
{
// U is signed - T could be either signed or unsigned
if( u > IntTraits< T >::maxInt || u < 0 )
return false;
t = (T)u;
return true;
}
template < typename E >
static void CastThrow( U u, T& t )
{
// U is signed - T could be either signed or unsigned
if( u > IntTraits< T >::maxInt || u < 0 )
E::SafeIntOnOverflow();
t = (T)u;
}
};
template < typename T, typename U > class SafeCastHelper < T, U, CastCheckMinMaxSigned >
{
public:
static bool Cast( U u, T& t ) throw()
{
// T, U are signed
if( u > IntTraits< T >::maxInt || u < IntTraits< T >::minInt )
return false;
t = (T)u;
return true;
}
template < typename E >
static void CastThrow( U u, T& t )
{
//T, U are signed
if( u > IntTraits< T >::maxInt || u < IntTraits< T >::minInt )
E::SafeIntOnOverflow();
t = (T)u;
}
};
//core logic to determine whether a comparison is valid, or needs special treatment
enum ComparisonMethod
{
ComparisonMethod_Ok = 0,
ComparisonMethod_CastInt,
ComparisonMethod_CastInt64,
ComparisonMethod_UnsignedT,
ComparisonMethod_UnsignedU
};
// Note - the standard is arguably broken in the case of some integer
// conversion operations
// For example, signed char a = -1 = 0xff
// unsigned int b = 0xffffffff
// If you then test if a < b, a value-preserving cast
// is made, and you're essentially testing
// (unsigned int)a < b == false
//
// I do not think this makes sense - if you perform
// a cast to an __int64, which can clearly preserve both value and signedness
// then you get a different and intuitively correct answer
// IMHO, -1 should be less than 4 billion
// If you prefer to retain the ANSI standard behavior
// insert #define ANSI_CONVERSIONS into your source
// Behavior differences occur in the following cases:
// 8, 16, and 32-bit signed int, unsigned 32-bit int
// any signed int, unsigned 64-bit int
// Note - the signed int must be negative to show the problem
template < typename T, typename U >
class ValidComparison
{
public:
enum
{
#ifdef ANSI_CONVERSIONS
method = ComparisonMethod_Ok
#else
method = ( ( SafeIntCompare< T, U >::isLikeSigned ) ? ComparisonMethod_Ok :
( ( IntTraits< T >::isSigned && sizeof(T) < 8 && sizeof(U) < 4 ) ||
( IntTraits< U >::isSigned && sizeof(T) < 4 && sizeof(U) < 8 ) ) ? ComparisonMethod_CastInt :
( ( IntTraits< T >::isSigned && sizeof(U) < 8 ) ||
( IntTraits< U >::isSigned && sizeof(T) < 8 ) ) ? ComparisonMethod_CastInt64 :
( !IntTraits< T >::isSigned ) ? ComparisonMethod_UnsignedT :
ComparisonMethod_UnsignedU )
#endif
};
};
template <typename T, typename U, int state> class EqualityTest;
template < typename T, typename U > class EqualityTest< T, U, ComparisonMethod_Ok >
{
public:
static bool IsEquals( const T t, const U u ) throw() { return ( t == u ); }
};
template < typename T, typename U > class EqualityTest< T, U, ComparisonMethod_CastInt >
{
public:
static bool IsEquals( const T t, const U u ) throw() { return ( (int)t == (int)u ); }
};
template < typename T, typename U > class EqualityTest< T, U, ComparisonMethod_CastInt64 >
{
public:
static bool IsEquals( const T t, const U u ) throw() { return ( (__int64)t == (__int64)u ); }
};
template < typename T, typename U > class EqualityTest< T, U, ComparisonMethod_UnsignedT >
{
public:
static bool IsEquals( const T t, const U u ) throw()
{
//one operand is 32 or 64-bit unsigned, and the other is signed and the same size or smaller
if( u < 0 )
return false;
//else safe to cast to type T
return ( t == (T)u );
}
};
template < typename T, typename U > class EqualityTest< T, U, ComparisonMethod_UnsignedU>
{
public:
static bool IsEquals( const T t, const U u ) throw()
{
//one operand is 32 or 64-bit unsigned, and the other is signed and the same size or smaller
if( t < 0 )
return false;
//else safe to cast to type U
return ( (U)t == u );
}
};
template <typename T, typename U, int state> class GreaterThanTest;
template < typename T, typename U > class GreaterThanTest< T, U, ComparisonMethod_Ok >
{
public:
static bool GreaterThan( const T t, const U u ) throw() { return ( t > u ); }
};
template < typename T, typename U > class GreaterThanTest< T, U, ComparisonMethod_CastInt >
{
public:
static bool GreaterThan( const T t, const U u ) throw() { return ( (int)t > (int)u ); }
};
template < typename T, typename U > class GreaterThanTest< T, U, ComparisonMethod_CastInt64 >
{
public:
static bool GreaterThan( const T t, const U u ) throw() { return ( (__int64)t > (__int64)u ); }
};
template < typename T, typename U > class GreaterThanTest< T, U, ComparisonMethod_UnsignedT >
{
public:
static bool GreaterThan( const T t, const U u ) throw()
{
// one operand is 32 or 64-bit unsigned, and the other is signed and the same size or smaller
if( u < 0 )
return true;
// else safe to cast to type T
return ( t > (T)u );
}
};
template < typename T, typename U > class GreaterThanTest< T, U, ComparisonMethod_UnsignedU >
{
public:
static bool GreaterThan( const T t, const U u ) throw()
{
// one operand is 32 or 64-bit unsigned, and the other is signed and the same size or smaller
if( t < 0 )
return false;
// else safe to cast to type U
return ( (U)t > u );
}
};
// Modulus is simpler than comparison, but follows much the same logic
// using this set of functions, it can't fail except in a div 0 situation
template <typename T, typename U, int method > class ModulusHelper;
template <typename T, typename U> class ModulusHelper <T, U, ComparisonMethod_Ok>
{
public:
static SafeIntError Modulus( const T& t, const U& u, T& result ) throw()
{
if(u == 0)
return SafeIntDivideByZero;
//trap corner case
if( IntTraits< U >::isSigned )
{
if(u == -1)
{
result = 0;
return SafeIntNoError;
}
}
result = (T)(t % u);
return SafeIntNoError;
}
template < typename E >
static void ModulusThrow( const T& t, const U& u, T& result )
{
if(u == 0)
E::SafeIntOnDivZero();
//trap corner case
if( IntTraits< U >::isSigned )
{
if(u == -1)
{
result = 0;
return;
}
}
result = (T)(t % u);
}
};
template <typename T, typename U> class ModulusHelper <T, U, ComparisonMethod_CastInt>
{
public:
static SafeIntError Modulus( const T& t, const U& u, T& result ) throw()
{
if(u == 0)
return SafeIntDivideByZero;
//trap corner case
if( IntTraits< U >::isSigned )
{
if(u == -1)
{
result = 0;
return SafeIntNoError;
}
}
result = (T)(t % u);
return SafeIntNoError;
}
template < typename E >
static void ModulusThrow( const T& t, const U& u, T& result )
{
if(u == 0)
E::SafeIntOnDivZero();
//trap corner case
if( IntTraits< U >::isSigned )
{
if(u == -1)
{
result = 0;
return;
}
}
result = (T)(t % u);
}
};
template < typename T, typename U > class ModulusHelper< T, U, ComparisonMethod_CastInt64>
{
public:
static SafeIntError Modulus( const T& t, const U& u, T& result ) throw()
{
if(u == 0)
return SafeIntDivideByZero;
if(IntTraits< U >::isSigned && u == -1)
result = 0;
else
result = (T)((__int64)t % (__int64)u);
return SafeIntNoError;
}
template < typename E >
static void ModulusThrow( const T& t, const U& u, T& result )
{
if(u == 0)
E::SafeIntOnDivZero();
if(IntTraits< U >::isSigned && u == -1)
result = 0;
else
result = (T)((__int64)t % (__int64)u);
}
};
// T is unsigned __int64, U is any signed int
template < typename T, typename U > class ModulusHelper< T, U, ComparisonMethod_UnsignedT>
{
public:
static SafeIntError Modulus( const T& t, const U& u, T& result ) throw()
{
if(u == 0)
return SafeIntDivideByZero;
// u could be negative - if so, need to convert to positive
// casts below are always safe due to the way modulus works
if(u < 0)
result = (T)(t % AbsValueHelper< U, GetAbsMethod< U >::method >::Abs(u));
else
result = (T)(t % u);
return SafeIntNoError;
}
template < typename E >
static void ModulusThrow( const T& t, const U& u, T& result )
{
if(u == 0)
E::SafeIntOnDivZero();
// u could be negative - if so, need to convert to positive
if(u < 0)
result = (T)(t % AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( u ));
else
result = (T)(t % u);
}
};
// U is unsigned __int64, T any signed int
template < typename T, typename U > class ModulusHelper< T, U, ComparisonMethod_UnsignedU>
{
public:
static SafeIntError Modulus( const T& t, const U& u, T& result ) throw()
{
if(u == 0)
return SafeIntDivideByZero;
//t could be negative - if so, need to convert to positive
if(t < 0)
result = -(T)( AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( t ) % u );
else
result = (T)((T)t % u);
return SafeIntNoError;
}
template < typename E >
static void ModulusThrow( const T& t, const U& u, T& result )
{
if(u == 0)
E::SafeIntOnDivZero();
//t could be negative - if so, need to convert to positive
if(t < 0)
result = -(T)( AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( t ) % u );
else
result = (T)( (T)t % u );
}
};
//core logic to determine method to check multiplication
enum MultiplicationState
{
MultiplicationState_CastInt = 0, // One or both signed, smaller than 32-bit
MultiplicationState_CastInt64, // One or both signed, smaller than 64-bit
MultiplicationState_CastUint, // Both are unsigned, smaller than 32-bit
MultiplicationState_CastUint64, // Both are unsigned, both 32-bit or smaller
MultiplicationState_Uint64Uint, // Both are unsigned, lhs 64-bit, rhs 32-bit or smaller
MultiplicationState_Uint64Uint64, // Both are unsigned int64
MultiplicationState_Uint64Int, // lhs is unsigned int64, rhs int32
MultiplicationState_Uint64Int64, // lhs is unsigned int64, rhs signed int64
MultiplicationState_UintUint64, // Both are unsigned, lhs 32-bit or smaller, rhs 64-bit
MultiplicationState_UintInt64, // lhs unsigned 32-bit or less, rhs int64
MultiplicationState_Int64Uint, // lhs int64, rhs unsigned int32
MultiplicationState_Int64Int64, // lhs int64, rhs int64
MultiplicationState_Int64Int, // lhs int64, rhs int32
MultiplicationState_IntUint64, // lhs int, rhs unsigned int64
MultiplicationState_IntInt64, // lhs int, rhs int64
MultiplicationState_Int64Uint64, // lhs int64, rhs uint64
MultiplicationState_Error
};
template < typename T, typename U >
class MultiplicationMethod
{
public:
enum
{
// unsigned-unsigned
method = (IntRegion< T,U >::IntZone_UintLT32_UintLT32 ? MultiplicationState_CastUint :
(IntRegion< T,U >::IntZone_Uint32_UintLT64 ||
IntRegion< T,U >::IntZone_UintLT32_Uint32) ? MultiplicationState_CastUint64 :
SafeIntCompare< T,U >::isBothUnsigned &&
IntTraits< T >::isUint64 && IntTraits< U >::isUint64 ? MultiplicationState_Uint64Uint64 :
(IntRegion< T,U >::IntZone_Uint64_Uint) ? MultiplicationState_Uint64Uint :
(IntRegion< T,U >::IntZone_UintLT64_Uint64) ? MultiplicationState_UintUint64 :
// unsigned-signed
(IntRegion< T,U >::IntZone_UintLT32_IntLT32) ? MultiplicationState_CastInt :
(IntRegion< T,U >::IntZone_Uint32_IntLT64 ||
IntRegion< T,U >::IntZone_UintLT32_Int32) ? MultiplicationState_CastInt64 :
(IntRegion< T,U >::IntZone_Uint64_Int) ? MultiplicationState_Uint64Int :
(IntRegion< T,U >::IntZone_UintLT64_Int64) ? MultiplicationState_UintInt64 :
(IntRegion< T,U >::IntZone_Uint64_Int64) ? MultiplicationState_Uint64Int64 :
// signed-signed
(IntRegion< T,U >::IntZone_IntLT32_IntLT32) ? MultiplicationState_CastInt :
(IntRegion< T,U >::IntZone_Int32_IntLT64 ||
IntRegion< T,U >::IntZone_IntLT32_Int32) ? MultiplicationState_CastInt64 :
(IntRegion< T,U >::IntZone_Int64_Int64) ? MultiplicationState_Int64Int64 :
(IntRegion< T,U >::IntZone_Int64_Int) ? MultiplicationState_Int64Int :
(IntRegion< T,U >::IntZone_IntLT64_Int64) ? MultiplicationState_IntInt64 :
// signed-unsigned
(IntRegion< T,U >::IntZone_IntLT32_UintLT32) ? MultiplicationState_CastInt :
(IntRegion< T,U >::IntZone_Int32_UintLT32 ||
IntRegion< T,U >::IntZone_IntLT64_Uint32) ? MultiplicationState_CastInt64 :
(IntRegion< T,U >::IntZone_Int64_UintLT64) ? MultiplicationState_Int64Uint :
(IntRegion< T,U >::IntZone_Int_Uint64) ? MultiplicationState_IntUint64 :
(IntRegion< T,U >::IntZone_Int64_Uint64 ? MultiplicationState_Int64Uint64 :
MultiplicationState_Error ) )
};
};
template <typename T, typename U, int state> class MultiplicationHelper;
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_CastInt>
{
public:
//accepts signed, both less than 32-bit
static bool Multiply( const T& t, const U& u, T& ret ) throw()
{
int tmp = t * u;
if( tmp > IntTraits< T >::maxInt || tmp < IntTraits< T >::minInt )
return false;
ret = (T)tmp;
return true;
}
template < typename E >
static void MultiplyThrow( const T& t, const U& u, T& ret )
{
int tmp = t * u;
if( tmp > IntTraits< T >::maxInt || tmp < IntTraits< T >::minInt )
E::SafeIntOnOverflow();
ret = (T)tmp;
}
};
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_CastUint >
{
public:
//accepts unsigned, both less than 32-bit
static bool Multiply( const T& t, const U& u, T& ret ) throw()
{
unsigned int tmp = t * u;
if( tmp > IntTraits< T >::maxInt )
return false;
ret = (T)tmp;
return true;
}
template < typename E >
static void MultiplyThrow( const T& t, const U& u, T& ret )
{
unsigned int tmp = t * u;
if( tmp > IntTraits< T >::maxInt )
E::SafeIntOnOverflow();
ret = (T)tmp;
}
};
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_CastInt64>
{
public:
//mixed signed or both signed where at least one argument is 32-bit, and both a 32-bit or less
static bool Multiply( const T& t, const U& u, T& ret ) throw()
{
__int64 tmp = (__int64)t * (__int64)u;
if(tmp > (__int64)IntTraits< T >::maxInt || tmp < (__int64)IntTraits< T >::minInt)
return false;
ret = (T)tmp;
return true;
}
template < typename E >
static void MultiplyThrow( const T& t, const U& u, T& ret )
{
__int64 tmp = (__int64)t * (__int64)u;
if(tmp > (__int64)IntTraits< T >::maxInt || tmp < (__int64)IntTraits< T >::minInt)
E::SafeIntOnOverflow();
ret = (T)tmp;
}
};
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_CastUint64>
{
public:
//both unsigned where at least one argument is 32-bit, and both are 32-bit or less
static bool Multiply( const T& t, const U& u, T& ret ) throw()
{
unsigned __int64 tmp = (unsigned __int64)t * (unsigned __int64)u;
if(tmp > (unsigned __int64)IntTraits< T >::maxInt)
return false;
ret = (T)tmp;
return true;
}
template < typename E >
static void MultiplyThrow( const T& t, const U& u, T& ret )
{
unsigned __int64 tmp = (unsigned __int64)t * (unsigned __int64)u;
if(tmp > (unsigned __int64)IntTraits< T >::maxInt)
E::SafeIntOnOverflow();
ret = (T)tmp;
}
};
#if !defined __GNUC__ && defined _M_AMD64
#include <intrin.h>
#define SAFEINT_USE_INTRINSICS 1
#else
#define SAFEINT_USE_INTRINSICS 0
#endif
// T = left arg and return type
// U = right arg
template < typename T, typename U > class LargeIntRegMultiply;
#if SAFEINT_USE_INTRINSICS
// As usual, unsigned is easy
bool IntrinsicMultiplyUint64( const unsigned __int64& a, const unsigned __int64& b, unsigned __int64* pRet )
{
unsigned __int64 ulHigh = 0;
*pRet = _umul128(a , b, &ulHigh);
return ulHigh == 0;
}
// Signed, is not so easy
bool IntrinsicMultiplyInt64( const signed __int64& a, const signed __int64& b, signed __int64* pRet )
{
__int64 llHigh = 0;
*pRet = _mul128(a , b, &llHigh);
// Now we need to figure out what we expect
// If llHigh is 0, then treat *pRet as unsigned
// If llHigh is < 0, then treat *pRet as signed
if( (a ^ b) < 0 )
{
// Negative result expected
if( llHigh == -1 && *pRet < 0 ||
llHigh == 0 && *pRet == 0 )
{
// Everything is within range
return true;
}
}
else
{
// Result should be positive
// Check for overflow
if( llHigh == 0 && (unsigned __int64)*pRet <= IntTraits< signed __int64 >::maxInt )
return true;
}
return false;
}
#endif
template<> class LargeIntRegMultiply< unsigned __int64, unsigned __int64 >
{
public:
static bool RegMultiply( const unsigned __int64& a, const unsigned __int64& b, unsigned __int64* pRet ) throw()
{
#if SAFEINT_USE_INTRINSICS
return IntrinsicMultiplyUint64( a, b, pRet );
#else
unsigned __int32 aHigh, aLow, bHigh, bLow;
// Consider that a*b can be broken up into:
// (aHigh * 2^32 + aLow) * (bHigh * 2^32 + bLow)
// => (aHigh * bHigh * 2^64) + (aLow * bHigh * 2^32) + (aHigh * bLow * 2^32) + (aLow * bLow)
// Note - same approach applies for 128 bit math on a 64-bit system
aHigh = (unsigned __int32)(a >> 32);
aLow = (unsigned __int32)a;
bHigh = (unsigned __int32)(b >> 32);
bLow = (unsigned __int32)b;
*pRet = 0;
if(aHigh == 0)
{
if(bHigh != 0)
{
*pRet = (unsigned __int64)aLow * (unsigned __int64)bHigh;
}
}
else if(bHigh == 0)
{
if(aHigh != 0)
{
*pRet = (unsigned __int64)aHigh * (unsigned __int64)bLow;
}
}
else
{
return false;
}
if(*pRet != 0)
{
unsigned __int64 tmp;
if((unsigned __int32)(*pRet >> 32) != 0)
return false;
*pRet <<= 32;
tmp = (unsigned __int64)aLow * (unsigned __int64)bLow;
*pRet += tmp;
if(*pRet < tmp)
return false;
return true;
}
*pRet = (unsigned __int64)aLow * (unsigned __int64)bLow;
return true;
#endif
}
template < typename E >
static void RegMultiplyThrow( const unsigned __int64& a, const unsigned __int64& b, unsigned __int64* pRet )
{
#if SAFEINT_USE_INTRINSICS
if( !IntrinsicMultiplyUint64( a, b, pRet ) )
E::SafeIntOnOverflow();
#else
unsigned __int32 aHigh, aLow, bHigh, bLow;
// Consider that a*b can be broken up into:
// (aHigh * 2^32 + aLow) * (bHigh * 2^32 + bLow)
// => (aHigh * bHigh * 2^64) + (aLow * bHigh * 2^32) + (aHigh * bLow * 2^32) + (aLow * bLow)
// Note - same approach applies for 128 bit math on a 64-bit system
aHigh = (unsigned __int32)(a >> 32);
aLow = (unsigned __int32)a;
bHigh = (unsigned __int32)(b >> 32);
bLow = (unsigned __int32)b;
*pRet = 0;
if(aHigh == 0)
{
if(bHigh != 0)
{
*pRet = (unsigned __int64)aLow * (unsigned __int64)bHigh;
}
}
else if(bHigh == 0)
{
if(aHigh != 0)
{
*pRet = (unsigned __int64)aHigh * (unsigned __int64)bLow;
}
}
else
{
E::SafeIntOnOverflow();
}
if(*pRet != 0)
{
unsigned __int64 tmp;
if((unsigned __int32)(*pRet >> 32) != 0)
E::SafeIntOnOverflow();
*pRet <<= 32;
tmp = (unsigned __int64)aLow * (unsigned __int64)bLow;
*pRet += tmp;
if(*pRet < tmp)
E::SafeIntOnOverflow();
return;
}
*pRet = (unsigned __int64)aLow * (unsigned __int64)bLow;
#endif
}
};
template<> class LargeIntRegMultiply< unsigned __int64, unsigned __int32 >
{
public:
static bool RegMultiply( const unsigned __int64& a, unsigned __int32 b, unsigned __int64* pRet ) throw()
{
#if SAFEINT_USE_INTRINSICS
return IntrinsicMultiplyUint64( a, (unsigned __int64)b, pRet );
#else
unsigned __int32 aHigh, aLow;
// Consider that a*b can be broken up into:
// (aHigh * 2^32 + aLow) * b
// => (aHigh * b * 2^32) + (aLow * b)
aHigh = (unsigned __int32)(a >> 32);
aLow = (unsigned __int32)a;
*pRet = 0;
if(aHigh != 0)
{
*pRet = (unsigned __int64)aHigh * (unsigned __int64)b;
unsigned __int64 tmp;
if((unsigned __int32)(*pRet >> 32) != 0)
return false;
*pRet <<= 32;
tmp = (unsigned __int64)aLow * (unsigned __int64)b;
*pRet += tmp;
if(*pRet < tmp)
return false;
return true;
}
*pRet = (unsigned __int64)aLow * (unsigned __int64)b;
return true;
#endif
}
template < typename E >
static void RegMultiplyThrow( const unsigned __int64& a, unsigned __int32 b, unsigned __int64* pRet )
{
#if SAFEINT_USE_INTRINSICS
if( !IntrinsicMultiplyUint64( a, (unsigned __int64)b, pRet ) )
E::SafeIntOnOverflow();
#else
unsigned __int32 aHigh, aLow;
// Consider that a*b can be broken up into:
// (aHigh * 2^32 + aLow) * b
// => (aHigh * b * 2^32) + (aLow * b)
aHigh = (unsigned __int32)(a >> 32);
aLow = (unsigned __int32)a;
*pRet = 0;
if(aHigh != 0)
{
*pRet = (unsigned __int64)aHigh * (unsigned __int64)b;
unsigned __int64 tmp;
if((unsigned __int32)(*pRet >> 32) != 0)
E::SafeIntOnOverflow();
*pRet <<= 32;
tmp = (unsigned __int64)aLow * (unsigned __int64)b;
*pRet += tmp;
if(*pRet < tmp)
E::SafeIntOnOverflow();
return;
}
*pRet = (unsigned __int64)aLow * (unsigned __int64)b;
return;
#endif
}
};
template<> class LargeIntRegMultiply< unsigned __int64, signed __int32 >
{
public:
// Intrinsic not needed
static bool RegMultiply( const unsigned __int64& a, signed __int32 b, unsigned __int64* pRet ) throw()
{
if( b < 0 && a != 0 )
return false;
#if SAFEINT_USE_INTRINSICS
return IntrinsicMultiplyUint64( a, (unsigned __int64)b, pRet );
#else
return LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::RegMultiply(a, (unsigned __int32)b, pRet);
#endif
}
template < typename E >
static void RegMultiplyThrow( const unsigned __int64& a, signed __int32 b, unsigned __int64* pRet )
{
if( b < 0 && a != 0 )
E::SafeIntOnOverflow();
#if SAFEINT_USE_INTRINSICS
if( !IntrinsicMultiplyUint64( a, (unsigned __int64)b, pRet ) )
E::SafeIntOnOverflow();
#else
LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::template RegMultiplyThrow< E >( a, (unsigned __int32)b, pRet );
#endif
}
};
template<> class LargeIntRegMultiply< unsigned __int64, signed __int64 >
{
public:
static bool RegMultiply( const unsigned __int64& a, signed __int64 b, unsigned __int64* pRet ) throw()
{
if( b < 0 && a != 0 )
return false;
#if SAFEINT_USE_INTRINSICS
return IntrinsicMultiplyUint64( a, (unsigned __int64)b, pRet );
#else
return LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::RegMultiply(a, (unsigned __int64)b, pRet);
#endif
}
template < typename E >
static void RegMultiplyThrow( const unsigned __int64& a, signed __int64 b, unsigned __int64* pRet )
{
if( b < 0 && a != 0 )
E::SafeIntOnOverflow();
#if SAFEINT_USE_INTRINSICS
if( !IntrinsicMultiplyUint64( a, (unsigned __int64)b, pRet ) )
E::SafeIntOnOverflow();
#else
LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::template RegMultiplyThrow< E >( a, (unsigned __int64)b, pRet );
#endif
}
};
template<> class LargeIntRegMultiply< signed __int32, unsigned __int64 >
{
public:
// Devolves into ordinary 64-bit calculation
static bool RegMultiply( signed __int32 a, const unsigned __int64& b, signed __int32* pRet ) throw()
{
unsigned __int32 bHigh, bLow;
bool fIsNegative = false;
// Consider that a*b can be broken up into:
// (aHigh * 2^32 + aLow) * (bHigh * 2^32 + bLow)
// => (aHigh * bHigh * 2^64) + (aLow * bHigh * 2^32) + (aHigh * bLow * 2^32) + (aLow * bLow)
// aHigh == 0 implies:
// ( aLow * bHigh * 2^32 ) + ( aLow + bLow )
// If the first part is != 0, fail
bHigh = (unsigned __int32)(b >> 32);
bLow = (unsigned __int32)b;
*pRet = 0;
if(bHigh != 0 && a != 0)
return false;
if( a < 0 )
{
a = -a;
fIsNegative = true;
}
unsigned __int64 tmp = (unsigned __int32)a * (unsigned __int64)bLow;
if( !fIsNegative )
{
if( tmp <= (unsigned __int64)IntTraits< signed __int32 >::maxInt )
{
*pRet = (signed __int32)tmp;
return true;
}
}
else
{
if( tmp <= (unsigned __int64)IntTraits< signed __int32 >::maxInt+1 )
{
*pRet = -( (signed __int32)tmp );
return true;
}
}
return false;
}
template < typename E >
static void RegMultiplyThrow( signed __int32 a, const unsigned __int64& b, signed __int32* pRet )
{
unsigned __int32 bHigh, bLow;
bool fIsNegative = false;
// Consider that a*b can be broken up into:
// (aHigh * 2^32 + aLow) * (bHigh * 2^32 + bLow)
// => (aHigh * bHigh * 2^64) + (aLow * bHigh * 2^32) + (aHigh * bLow * 2^32) + (aLow * bLow)
bHigh = (signed __int32)(b >> 32);
bLow = (signed __int32)b;
*pRet = 0;
if(bHigh != 0 && a != 0)
E::SafeIntOnOverflow();
if( a < 0 )
{
a = -a;
fIsNegative = true;
}
unsigned __int64 tmp = (unsigned __int32)a * (unsigned __int64)bLow;
if( !fIsNegative )
{
if( tmp <= (unsigned __int64)IntTraits< signed __int32 >::maxInt )
{
*pRet = (signed __int32)tmp;
return;
}
}
else
{
if( tmp <= (unsigned __int64)IntTraits< signed __int32 >::maxInt+1 )
{
*pRet = -( (signed __int32)tmp );
return;
}
}
E::SafeIntOnOverflow();
}
};
template<> class LargeIntRegMultiply< unsigned __int32, unsigned __int64 >
{
public:
// Becomes ordinary 64-bit multiplication, intrinsic not needed
static bool RegMultiply( unsigned __int32 a, const unsigned __int64& b, unsigned __int32* pRet ) throw()
{
// Consider that a*b can be broken up into:
// (bHigh * 2^32 + bLow) * a
// => (bHigh * a * 2^32) + (bLow * a)
// In this case, the result must fit into 32-bits
// If bHigh != 0 && a != 0, immediate error.
if( (unsigned __int32)(b >> 32) != 0 && a != 0 )
return false;
unsigned __int64 tmp = b * (unsigned __int64)a;
if( (unsigned __int32)(tmp >> 32) != 0 ) // overflow
return false;
*pRet = (unsigned __int32)tmp;
return true;
}
template < typename E >
static void RegMultiplyThrow( unsigned __int32 a, const unsigned __int64& b, unsigned __int32* pRet )
{
if( (unsigned __int32)(b >> 32) != 0 && a != 0 )
E::SafeIntOnOverflow();
unsigned __int64 tmp = b * (unsigned __int64)a;
if( (unsigned __int32)(tmp >> 32) != 0 ) // overflow
E::SafeIntOnOverflow();
*pRet = (unsigned __int32)tmp;
}
};
template<> class LargeIntRegMultiply< unsigned __int32, signed __int64 >
{
public:
static bool RegMultiply( unsigned __int32 a, const signed __int64& b, unsigned __int32* pRet ) throw()
{
if( b < 0 && a != 0 )
return false;
return LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::RegMultiply( a, (unsigned __int64)b, pRet );
}
template < typename E >
static void RegMultiplyThrow( unsigned __int32 a, const signed __int64& b, unsigned __int32* pRet )
{
if( b < 0 && a != 0 )
E::SafeIntOnOverflow();
LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::template RegMultiplyThrow< E >( a, (unsigned __int64)b, pRet );
}
};
template<> class LargeIntRegMultiply< signed __int64, signed __int64 >
{
public:
static bool RegMultiply( const signed __int64& a, const signed __int64& b, signed __int64* pRet ) throw()
{
#if SAFEINT_USE_INTRINSICS
return IntrinsicMultiplyInt64( a, b, pRet );
#else
bool aNegative = false;
bool bNegative = false;
unsigned __int64 tmp;
__int64 a1 = a;
__int64 b1 = b;
if( a1 < 0 )
{
aNegative = true;
a1 = -a1;
}
if( b1 < 0 )
{
bNegative = true;
b1 = -b1;
}
if( LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::RegMultiply( (unsigned __int64)a1, (unsigned __int64)b1, &tmp ) )
{
// The unsigned multiplication didn't overflow
if( aNegative ^ bNegative )
{
// Result must be negative
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt )
{
*pRet = -(signed __int64)tmp;
return true;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt )
{
*pRet = (signed __int64)tmp;
return true;
}
}
}
return false;
#endif
}
template < typename E >
static void RegMultiplyThrow( const signed __int64& a, const signed __int64& b, signed __int64* pRet )
{
#if SAFEINT_USE_INTRINSICS
if( !IntrinsicMultiplyInt64( a, b, pRet ) )
E::SafeIntOnOverflow();
#else
bool aNegative = false;
bool bNegative = false;
unsigned __int64 tmp;
__int64 a1 = a;
__int64 b1 = b;
if( a1 < 0 )
{
aNegative = true;
a1 = -a1;
}
if( b1 < 0 )
{
bNegative = true;
b1 = -b1;
}
LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::template RegMultiplyThrow< E >( (unsigned __int64)a1, (unsigned __int64)b1, &tmp );
// The unsigned multiplication didn't overflow or we'd be in the exception handler
if( aNegative ^ bNegative )
{
// Result must be negative
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt )
{
*pRet = -(signed __int64)tmp;
return;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt )
{
*pRet = (signed __int64)tmp;
return;
}
}
E::SafeIntOnOverflow();
#endif
}
};
template<> class LargeIntRegMultiply< signed __int64, unsigned __int32 >
{
public:
static bool RegMultiply( const signed __int64& a, unsigned __int32 b, signed __int64* pRet ) throw()
{
#if SAFEINT_USE_INTRINSICS
return IntrinsicMultiplyInt64( a, (signed __int64)b, pRet );
#else
bool aNegative = false;
unsigned __int64 tmp;
__int64 a1 = a;
if( a1 < 0 )
{
aNegative = true;
a1 = -a1;
}
if( LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::RegMultiply( (unsigned __int64)a1, b, &tmp ) )
{
// The unsigned multiplication didn't overflow
if( aNegative )
{
// Result must be negative
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt )
{
*pRet = -(signed __int64)tmp;
return true;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt )
{
*pRet = (signed __int64)tmp;
return true;
}
}
}
return false;
#endif
}
template < typename E >
static void RegMultiplyThrow( const signed __int64& a, unsigned __int32 b, signed __int64* pRet )
{
#if SAFEINT_USE_INTRINSICS
if( !IntrinsicMultiplyInt64( a, (signed __int64)b, pRet ) )
E::SafeIntOnOverflow();
#else
bool aNegative = false;
unsigned __int64 tmp;
__int64 a1 = a;
if( a1 < 0 )
{
aNegative = true;
a1 = -a1;
}
LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::template RegMultiplyThrow< E >( (unsigned __int64)a1, b, &tmp );
// The unsigned multiplication didn't overflow
if( aNegative )
{
// Result must be negative
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt )
{
*pRet = -(signed __int64)tmp;
return;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt )
{
*pRet = (signed __int64)tmp;
return;
}
}
E::SafeIntOnOverflow();
#endif
}
};
template<> class LargeIntRegMultiply< signed __int64, signed __int32 >
{
public:
static bool RegMultiply( const signed __int64& a, signed __int32 b, signed __int64* pRet ) throw()
{
#if SAFEINT_USE_INTRINSICS
return IntrinsicMultiplyInt64( a, (signed __int64)b, pRet );
#else
bool aNegative = false;
bool bNegative = false;
unsigned __int64 tmp;
__int64 a1 = a;
__int64 b1 = b;
if( a1 < 0 )
{
aNegative = true;
a1 = -a1;
}
if( b1 < 0 )
{
bNegative = true;
b1 = -b1;
}
if( LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::RegMultiply( (unsigned __int64)a1, (unsigned __int32)b1, &tmp ) )
{
// The unsigned multiplication didn't overflow
if( aNegative ^ bNegative )
{
// Result must be negative
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt )
{
*pRet = -(signed __int64)tmp;
return true;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt )
{
*pRet = (signed __int64)tmp;
return true;
}
}
}
return false;
#endif
}
template < typename E >
static void RegMultiplyThrow( signed __int64 a, signed __int32 b, signed __int64* pRet )
{
#if SAFEINT_USE_INTRINSICS
if( !IntrinsicMultiplyInt64( a, (signed __int64)b, pRet ) )
E::SafeIntOnOverflow();
#else
bool aNegative = false;
bool bNegative = false;
unsigned __int64 tmp;
if( a < 0 )
{
aNegative = true;
a = -a;
}
if( b < 0 )
{
bNegative = true;
b = -b;
}
LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::template RegMultiplyThrow< E >( (unsigned __int64)a, (unsigned __int32)b, &tmp );
// The unsigned multiplication didn't overflow
if( aNegative ^ bNegative )
{
// Result must be negative
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt )
{
*pRet = -(signed __int64)tmp;
return;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt )
{
*pRet = (signed __int64)tmp;
return;
}
}
E::SafeIntOnOverflow();
#endif
}
};
template<> class LargeIntRegMultiply< signed __int32, signed __int64 >
{
public:
static bool RegMultiply( signed __int32 a, const signed __int64& b, signed __int32* pRet ) throw()
{
#if SAFEINT_USE_INTRINSICS
__int64 tmp;
if( IntrinsicMultiplyInt64( a, b, &tmp ) )
{
if( tmp > IntTraits< signed __int32 >::maxInt ||
tmp < IntTraits< signed __int32 >::minInt )
{
return false;
}
*pRet = (__int32)tmp;
return true;
}
return false;
#else
bool aNegative = false;
bool bNegative = false;
unsigned __int32 tmp;
__int64 b1 = b;
if( a < 0 )
{
aNegative = true;
a = -a;
}
if( b1 < 0 )
{
bNegative = true;
b1 = -b1;
}
if( LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::RegMultiply( (unsigned __int32)a, (unsigned __int64)b1, &tmp ) )
{
// The unsigned multiplication didn't overflow
if( aNegative ^ bNegative )
{
// Result must be negative
if( tmp <= (unsigned __int32)IntTraits< signed __int32 >::minInt )
{
*pRet = -tmp;
return true;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int32)IntTraits< signed __int32 >::maxInt )
{
*pRet = (signed __int32)tmp;
return true;
}
}
}
return false;
#endif
}
template < typename E >
static void RegMultiplyThrow( signed __int32 a, const signed __int64& b, signed __int32* pRet )
{
#if SAFEINT_USE_INTRINSICS
__int64 tmp;
if( IntrinsicMultiplyInt64( a, b, &tmp ) )
{
if( tmp > IntTraits< signed __int32 >::maxInt ||
tmp < IntTraits< signed __int32 >::minInt )
{
E::SafeIntOnOverflow();
}
*pRet = (__int32)tmp;
return;
}
E::SafeIntOnOverflow();
#else
bool aNegative = false;
bool bNegative = false;
unsigned __int32 tmp;
signed __int64 b2 = b;
if( a < 0 )
{
aNegative = true;
a = -a;
}
if( b < 0 )
{
bNegative = true;
b2 = -b2;
}
LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::template RegMultiplyThrow< E >( (unsigned __int32)a, (unsigned __int64)b2, &tmp );
// The unsigned multiplication didn't overflow
if( aNegative ^ bNegative )
{
// Result must be negative
if( tmp <= (unsigned __int32)IntTraits< signed __int32 >::minInt )
{
*pRet = -(signed __int32)tmp;
return;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int32)IntTraits< signed __int32 >::maxInt )
{
*pRet = (signed __int32)tmp;
return;
}
}
E::SafeIntOnOverflow();
#endif
}
};
template<> class LargeIntRegMultiply< signed __int64, unsigned __int64 >
{
public:
// Leave this one as-is - will call unsigned intrinsic internally
static bool RegMultiply( const signed __int64& a, const unsigned __int64& b, signed __int64* pRet ) throw()
{
bool aNegative = false;
unsigned __int64 tmp;
__int64 a1 = a;
if( a1 < 0 )
{
aNegative = true;
a1 = -a1;
}
if( LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::RegMultiply( (unsigned __int64)a1, (unsigned __int64)b, &tmp ) )
{
// The unsigned multiplication didn't overflow
if( aNegative )
{
// Result must be negative
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt )
{
*pRet = -((signed __int64)tmp);
return true;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt )
{
*pRet = (signed __int64)tmp;
return true;
}
}
}
return false;
}
template < typename E >
static void RegMultiplyThrow( const signed __int64& a, const unsigned __int64& b, signed __int64* pRet )
{
bool aNegative = false;
unsigned __int64 tmp;
__int64 a1 = a;
if( a1 < 0 )
{
aNegative = true;
a1 = -a1;
}
if( LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::RegMultiply( (unsigned __int64)a1, (unsigned __int64)b, &tmp ) )
{
// The unsigned multiplication didn't overflow
if( aNegative )
{
// Result must be negative
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt )
{
*pRet = -((signed __int64)tmp);
return;
}
}
else
{
// Result must be positive
if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt )
{
*pRet = (signed __int64)tmp;
return;
}
}
}
E::SafeIntOnOverflow();
}
};
// In all of the following functions where LargeIntRegMultiply methods are called,
// we need to properly transition types. The methods need __int64, __int32, etc.
// but the variables being passed to us could be long long, long int, or long, depending on
// the compiler. Microsoft compiler knows that long long is the same type as __int64, but gcc doesn't
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_Uint64Uint64 >
{
public:
// T, U are unsigned __int64
static bool Multiply( const T& t, const U& u, T& ret ) throw()
{
C_ASSERT( IntTraits<T>::isUint64 && IntTraits<U>::isUint64 );
unsigned __int64 t1 = t;
unsigned __int64 u1 = u;
return LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::RegMultiply( t1, u1, reinterpret_cast<unsigned __int64*>(&ret) );
}
template < typename E >
static void MultiplyThrow(const unsigned __int64& t, const unsigned __int64& u, unsigned __int64& ret)
{
C_ASSERT( IntTraits<T>::isUint64 && IntTraits<U>::isUint64 );
unsigned __int64 t1 = t;
unsigned __int64 u1 = u;
LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::template RegMultiplyThrow< E >( t1, u1, reinterpret_cast<unsigned __int64*>(&ret) );
}
};
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_Uint64Uint >
{
public:
// T is unsigned __int64
// U is any unsigned int 32-bit or less
static bool Multiply( const T& t, const U& u, T& ret ) throw()
{
C_ASSERT( IntTraits<T>::isUint64 );
unsigned __int64 t1 = t;
return LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::RegMultiply( t1, (unsigned __int32)u, reinterpret_cast<unsigned __int64*>(&ret) );
}
template < typename E >
static void MultiplyThrow( const T& t, const U& u, unsigned __int64& ret )
{
C_ASSERT( IntTraits<T>::isUint64 );
unsigned __int64 t1 = t;
LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::template RegMultiplyThrow< E >( t1, (unsigned __int32)u, reinterpret_cast<unsigned __int64*>(&ret) );
}
};
// converse of the previous function
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_UintUint64 >
{
public:
// T is any unsigned int up to 32-bit
// U is unsigned __int64
static bool Multiply(const T& t, const U& u, T& ret) throw()
{
C_ASSERT( IntTraits<U>::isUint64 );
unsigned __int64 u1 = u;
unsigned __int32 tmp;
if( LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::RegMultiply( t, u1, &tmp ) &&
SafeCastHelper< T, unsigned __int32, GetCastMethod< T, unsigned __int32 >::method >::Cast(tmp, ret) )
{
return true;
}
return false;
}
template < typename E >
static void MultiplyThrow(const T& t, const U& u, T& ret)
{
C_ASSERT( IntTraits<U>::isUint64 );
unsigned __int64 u1 = u;
unsigned __int32 tmp;
LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::template RegMultiplyThrow< E >( t, u1, &tmp );
SafeCastHelper< T, unsigned __int32, GetCastMethod< T, unsigned __int32 >::method >::template CastThrow< E >(tmp, ret);
}
};
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_Uint64Int >
{
public:
// T is unsigned __int64
// U is any signed int, up to 64-bit
static bool Multiply(const T& t, const U& u, T& ret) throw()
{
C_ASSERT( IntTraits<T>::isUint64 );
unsigned __int64 t1 = t;
return LargeIntRegMultiply< unsigned __int64, signed __int32 >::RegMultiply(t1, (signed __int32)u, reinterpret_cast< unsigned __int64* >(&ret));
}
template < typename E >
static void MultiplyThrow(const T& t, const U& u, T& ret)
{
C_ASSERT( IntTraits<T>::isUint64 );
unsigned __int64 t1 = t;
LargeIntRegMultiply< unsigned __int64, signed __int32 >::template RegMultiplyThrow< E >(t1, (signed __int32)u, reinterpret_cast< unsigned __int64* >(&ret));
}
};
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_Uint64Int64 >
{
public:
// T is unsigned __int64
// U is __int64
static bool Multiply(const T& t, const U& u, T& ret) throw()
{
C_ASSERT( IntTraits<T>::isUint64 && IntTraits<U>::isInt64 );
unsigned __int64 t1 = t;
__int64 u1 = u;
return LargeIntRegMultiply< unsigned __int64, __int64 >::RegMultiply(t1, u1, reinterpret_cast< unsigned __int64* >(&ret));
}
template < typename E >
static void MultiplyThrow(const T& t, const U& u, T& ret)
{
C_ASSERT( IntTraits<T>::isUint64 && IntTraits<U>::isInt64 );
unsigned __int64 t1 = t;
__int64 u1 = u;
LargeIntRegMultiply< unsigned __int64, __int64 >::template RegMultiplyThrow< E >(t1, u1, reinterpret_cast< unsigned __int64* >(&ret));
}
};
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_UintInt64 >
{
public:
// T is unsigned up to 32-bit
// U is __int64
static bool Multiply(const T& t, const U& u, T& ret) throw()
{
C_ASSERT( IntTraits<U>::isInt64 );
__int64 u1 = u;
unsigned __int32 tmp;
if( LargeIntRegMultiply< unsigned __int32, __int64 >::RegMultiply( (unsigned __int32)t, u1, &tmp ) &&
SafeCastHelper< T, unsigned __int32, GetCastMethod< T, unsigned __int32 >::method >::Cast(tmp, ret) )
{
return true;
}
return false;
}
template < typename E >
static void MultiplyThrow(const T& t, const U& u, T& ret)
{
C_ASSERT( IntTraits<U>::isInt64 );
__int64 u1 = u;
unsigned __int32 tmp;
LargeIntRegMultiply< unsigned __int32, __int64 >::template RegMultiplyThrow< E >( (unsigned __int32)t, u1, &tmp );
SafeCastHelper< T, unsigned __int32, GetCastMethod< T, unsigned __int32 >::method >::template CastThrow< E >(tmp, ret);
}
};
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_Int64Uint >
{
public:
// T is __int64
// U is unsigned up to 32-bit
static bool Multiply( const T& t, const U& u, T& ret ) throw()
{
C_ASSERT( IntTraits<T>::isInt64 );
__int64 t1 = t;
return LargeIntRegMultiply< __int64, unsigned __int32 >::RegMultiply( t1, (unsigned __int32)u, reinterpret_cast< __int64* >(&ret) );
}
template < typename E >
static void MultiplyThrow( const T& t, const U& u, T& ret )
{
C_ASSERT( IntTraits<T>::isInt64 );
__int64 t1 = t;
LargeIntRegMultiply< __int64, unsigned __int32 >::template RegMultiplyThrow< E >( t1, (unsigned __int32)u, reinterpret_cast< __int64* >(&ret) );
}
};
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_Int64Int64 >
{
public:
// T, U are __int64
static bool Multiply( const T& t, const U& u, T& ret ) throw()
{
C_ASSERT( IntTraits<T>::isInt64 && IntTraits<U>::isInt64 );
__int64 t1 = t;
__int64 u1 = u;
return LargeIntRegMultiply< __int64, __int64 >::RegMultiply( t1, u1, reinterpret_cast< __int64* >(&ret) );
}
template < typename E >
static void MultiplyThrow( const T& t, const U& u, T& ret )
{
C_ASSERT( IntTraits<T>::isInt64 && IntTraits<U>::isInt64 );
__int64 t1 = t;
__int64 u1 = u;
LargeIntRegMultiply< __int64, __int64 >::template RegMultiplyThrow< E >( t1, u1, reinterpret_cast< __int64* >(&ret));
}
};
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_Int64Int >
{
public:
// T is __int64
// U is signed up to 32-bit
static bool Multiply( const T& t, U u, T& ret ) throw()
{
C_ASSERT( IntTraits<T>::isInt64 );
__int64 t1 = t;
return LargeIntRegMultiply< __int64, __int32 >::RegMultiply( t1, (__int32)u, reinterpret_cast< __int64* >(&ret));
}
template < typename E >
static void MultiplyThrow( const __int64& t, U u, __int64& ret )
{
C_ASSERT( IntTraits<T>::isInt64 );
__int64 t1 = t;
LargeIntRegMultiply< __int64, __int32 >::template RegMultiplyThrow< E >(t1, (__int32)u, reinterpret_cast< __int64* >(&ret));
}
};
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_IntUint64 >
{
public:
// T is signed up to 32-bit
// U is unsigned __int64
static bool Multiply(T t, const U& u, T& ret) throw()
{
C_ASSERT( IntTraits<U>::isUint64 );
__int64 u1 = u;
__int32 tmp;
if( LargeIntRegMultiply< __int32, unsigned __int64 >::RegMultiply( (__int32)t, u1, &tmp ) &&
SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::Cast( tmp, ret ) )
{
return true;
}
return false;
}
template < typename E >
static void MultiplyThrow(T t, const unsigned __int64& u, T& ret)
{
C_ASSERT( IntTraits<U>::isUint64 );
__int64 u1 = u;
__int32 tmp;
LargeIntRegMultiply< __int32, unsigned __int64 >::template RegMultiplyThrow< E >( (__int32)t, u1, &tmp );
SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::template CastThrow< E >( tmp, ret );
}
};
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_Int64Uint64>
{
public:
// T is __int64
// U is unsigned __int64
static bool Multiply( const T& t, const U& u, T& ret ) throw()
{
C_ASSERT( IntTraits<T>::isInt64 && IntTraits<U>::isUint64 );
__int64 t1 = t;
unsigned __int64 u1 = u;
return LargeIntRegMultiply< __int64, unsigned __int64 >::RegMultiply( t1, u1, reinterpret_cast< __int64* >(&ret) );
}
template < typename E >
static void MultiplyThrow( const __int64& t, const unsigned __int64& u, __int64& ret )
{
C_ASSERT( IntTraits<T>::isInt64 && IntTraits<U>::isUint64 );
__int64 t1 = t;
unsigned __int64 u1 = u;
LargeIntRegMultiply< __int64, unsigned __int64 >::template RegMultiplyThrow< E >( t1, u1, reinterpret_cast< __int64* >(&ret) );
}
};
template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_IntInt64>
{
public:
// T is signed, up to 32-bit
// U is __int64
static bool Multiply( T t, const U& u, T& ret ) throw()
{
C_ASSERT( IntTraits<U>::isInt64 );
__int64 u1 = u;
__int32 tmp;
if( LargeIntRegMultiply< __int32, __int64 >::RegMultiply( (__int32)t, u1, &tmp ) &&
SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::Cast( tmp, ret ) )
{
return true;
}
return false;
}
template < typename E >
static void MultiplyThrow(T t, const U& u, T& ret)
{
C_ASSERT( IntTraits<U>::isInt64 );
__int64 u1 = u;
__int32 tmp;
LargeIntRegMultiply< __int32, __int64 >::template RegMultiplyThrow< E >( (__int32)t, u1, &tmp );
SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::template CastThrow< E >( tmp, ret );
}
};
enum DivisionState
{
DivisionState_OK,
DivisionState_UnsignedSigned,
DivisionState_SignedUnsigned32,
DivisionState_SignedUnsigned64,
DivisionState_SignedUnsigned,
DivisionState_SignedSigned
};
template < typename T, typename U > class DivisionMethod
{
public:
enum
{
method = (SafeIntCompare< T, U >::isBothUnsigned ? DivisionState_OK :
(!IntTraits< T >::isSigned && IntTraits< U >::isSigned) ? DivisionState_UnsignedSigned :
(IntTraits< T >::isSigned &&
IntTraits< U >::isUint32 &&
IntTraits< T >::isLT64Bit) ? DivisionState_SignedUnsigned32 :
(IntTraits< T >::isSigned && IntTraits< U >::isUint64) ? DivisionState_SignedUnsigned64 :
(IntTraits< T >::isSigned && !IntTraits< U >::isSigned) ? DivisionState_SignedUnsigned :
DivisionState_SignedSigned)
};
};
template < typename T, typename U, int state > class DivisionHelper;
template < typename T, typename U > class DivisionHelper< T, U, DivisionState_OK >
{
public:
static SafeIntError Divide( const T& t, const U& u, T& result ) throw()
{
if( t == 0 )
{
result = 0;
return SafeIntNoError;
}
if( u == 0 )
return SafeIntDivideByZero;
result = (T)( t/u );
return SafeIntNoError;
}
template < typename E >
static void DivideThrow( const T& t, const U& u, T& result )
{
if( t == 0 )
{
result = 0;
return;
}
if( u == 0 )
E::SafeIntOnDivZero();
result = (T)( t/u );
}
};
template < typename T, typename U > class DivisionHelper< T, U, DivisionState_UnsignedSigned>
{
public:
static SafeIntError Divide( const T& t, const U& u, T& result ) throw()
{
if( t == 0 )
{
result = 0;
return SafeIntNoError;
}
if( u > 0 )
{
result = (T)( t/u );
return SafeIntNoError;
}
if( u == 0 )
return SafeIntDivideByZero;
// it is always an error to try and divide an unsigned number by a negative signed number
// unless u is bigger than t
if( AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( u ) > t )
{
result = 0;
return SafeIntNoError;
}
return SafeIntArithmeticOverflow;
}
template < typename E >
static void DivideThrow( const T& t, const U& u, T& result )
{
if( t == 0 )
{
result = 0;
return;
}
if( u > 0 )
{
result = (T)( t/u );
return;
}
if( u == 0 )
E::SafeIntOnDivZero();
// it is always an error to try and divide an unsigned number by a negative signed number
// unless u is bigger than t
if( AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( u ) > t )
{
result = 0;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class DivisionHelper< T, U, DivisionState_SignedUnsigned32 >
{
public:
static SafeIntError Divide( const T& t, const U& u, T& result ) throw()
{
if( t == 0 )
{
result = 0;
return SafeIntNoError;
}
if( u == 0 )
return SafeIntDivideByZero;
// Test for t > 0
// If t < 0, must explicitly upcast, or implicit upcast to ulong will cause errors
// As it turns out, 32-bit division is about twice as fast, which justifies the extra conditional
if( t > 0 )
result = (T)( t/u );
else
result = (T)( (__int64)t/(__int64)u );
return SafeIntNoError;
}
template < typename E >
static void DivideThrow( const T& t, const U& u, T& result )
{
if( t == 0 )
{
result = 0;
return;
}
if( u == 0 )
{
E::SafeIntOnDivZero();
}
// Test for t > 0
// If t < 0, must explicitly upcast, or implicit upcast to ulong will cause errors
// As it turns out, 32-bit division is about twice as fast, which justifies the extra conditional
if( t > 0 )
result = (T)( t/u );
else
result = (T)( (__int64)t/(__int64)u );
}
};
template < typename T > class DivisionHelper< T, unsigned __int64, DivisionState_SignedUnsigned64 >
{
public:
static SafeIntError Divide( const T& t, const unsigned __int64& u, T& result ) throw()
{
if( t == 0 )
{
result = 0;
return SafeIntNoError;
}
if( u == 0 )
{
return SafeIntDivideByZero;
}
if( u <= (unsigned __int64)IntTraits< T >::maxInt )
{
// Else u can safely be cast to T
if( sizeof( T ) < sizeof( __int64 ) )
result = (T)( (int)t/(int)u );
else
result = (T)((__int64)t/(__int64)u);
}
else // Corner case
if( t == IntTraits< T >::minInt && u == (unsigned __int64)IntTraits< T >::minInt )
{
// Min int divided by it's own magnitude is -1
result = -1;
}
else
{
result = 0;
}
return SafeIntNoError;
}
template < typename E >
static void DivideThrow( const T& t, const unsigned __int64& u, T& result )
{
if( t == 0 )
{
result = 0;
return;
}
if( u == 0 )
{
E::SafeIntOnDivZero();
}
if( u <= (unsigned __int64)IntTraits< T >::maxInt )
{
// Else u can safely be cast to T
if( sizeof( T ) < sizeof( __int64 ) )
result = (T)( (int)t/(int)u );
else
result = (T)((__int64)t/(__int64)u);
}
else // Corner case
if( t == IntTraits< T >::minInt && u == (unsigned __int64)IntTraits< T >::minInt )
{
// Min int divided by it's own magnitude is -1
result = -1;
}
else
{
result = 0;
}
}
};
template < typename T, typename U > class DivisionHelper< T, U, DivisionState_SignedUnsigned>
{
public:
// T is any signed, U is unsigned and smaller than 32-bit
// In this case, standard operator casting is correct
static SafeIntError Divide( const T& t, const U& u, T& result ) throw()
{
if( t == 0 )
{
result = 0;
return SafeIntNoError;
}
if( u == 0 )
{
return SafeIntDivideByZero;
}
result = (T)( t/u );
return SafeIntNoError;
}
template < typename E >
static void DivideThrow( const T& t, const U& u, T& result )
{
if( t == 0 )
{
result = 0;
return;
}
if( u == 0 )
{
E::SafeIntOnDivZero();
}
result = (T)( t/u );
}
};
template < typename T, typename U > class DivisionHelper< T, U, DivisionState_SignedSigned>
{
public:
static SafeIntError Divide( const T& t, const U& u, T& result ) throw()
{
if( t == 0 )
{
result = 0;
return SafeIntNoError;
}
if( u == 0 )
{
return SafeIntDivideByZero;
}
// Must test for corner case
if( t == IntTraits< T >::minInt && u == -1 )
return SafeIntArithmeticOverflow;
result = (T)( t/u );
return SafeIntNoError;
}
template < typename E >
static void DivideThrow( const T& t, const U& u, T& result )
{
if( t == 0 )
{
result = 0;
return;
}
if(u == 0)
{
E::SafeIntOnDivZero();
}
// Must test for corner case
if( t == IntTraits< T >::minInt && u == -1 )
E::SafeIntOnOverflow();
result = (T)( t/u );
}
};
enum AdditionState
{
AdditionState_CastIntCheckMax,
AdditionState_CastUintCheckOverflow,
AdditionState_CastUintCheckOverflowMax,
AdditionState_CastUint64CheckOverflow,
AdditionState_CastUint64CheckOverflowMax,
AdditionState_CastIntCheckMinMax,
AdditionState_CastInt64CheckMinMax,
AdditionState_CastInt64CheckMax,
AdditionState_CastUint64CheckMinMax,
AdditionState_CastUint64CheckMinMax2,
AdditionState_CastInt64CheckOverflow,
AdditionState_CastInt64CheckOverflowMinMax,
AdditionState_CastInt64CheckOverflowMax,
AdditionState_ManualCheckInt64Uint64,
AdditionState_ManualCheck,
AdditionState_Error
};
template< typename T, typename U >
class AdditionMethod
{
public:
enum
{
//unsigned-unsigned
method = (IntRegion< T,U >::IntZone_UintLT32_UintLT32 ? AdditionState_CastIntCheckMax :
(IntRegion< T,U >::IntZone_Uint32_UintLT64) ? AdditionState_CastUintCheckOverflow :
(IntRegion< T,U >::IntZone_UintLT32_Uint32) ? AdditionState_CastUintCheckOverflowMax :
(IntRegion< T,U >::IntZone_Uint64_Uint) ? AdditionState_CastUint64CheckOverflow :
(IntRegion< T,U >::IntZone_UintLT64_Uint64) ? AdditionState_CastUint64CheckOverflowMax :
//unsigned-signed
(IntRegion< T,U >::IntZone_UintLT32_IntLT32) ? AdditionState_CastIntCheckMinMax :
(IntRegion< T,U >::IntZone_Uint32_IntLT64 ||
IntRegion< T,U >::IntZone_UintLT32_Int32) ? AdditionState_CastInt64CheckMinMax :
(IntRegion< T,U >::IntZone_Uint64_Int ||
IntRegion< T,U >::IntZone_Uint64_Int64) ? AdditionState_CastUint64CheckMinMax :
(IntRegion< T,U >::IntZone_UintLT64_Int64) ? AdditionState_CastUint64CheckMinMax2 :
//signed-signed
(IntRegion< T,U >::IntZone_IntLT32_IntLT32) ? AdditionState_CastIntCheckMinMax :
(IntRegion< T,U >::IntZone_Int32_IntLT64 ||
IntRegion< T,U >::IntZone_IntLT32_Int32) ? AdditionState_CastInt64CheckMinMax :
(IntRegion< T,U >::IntZone_Int64_Int ||
IntRegion< T,U >::IntZone_Int64_Int64) ? AdditionState_CastInt64CheckOverflow :
(IntRegion< T,U >::IntZone_IntLT64_Int64) ? AdditionState_CastInt64CheckOverflowMinMax :
//signed-unsigned
(IntRegion< T,U >::IntZone_IntLT32_UintLT32) ? AdditionState_CastIntCheckMax :
(IntRegion< T,U >::IntZone_Int32_UintLT32 ||
IntRegion< T,U >::IntZone_IntLT64_Uint32) ? AdditionState_CastInt64CheckMax :
(IntRegion< T,U >::IntZone_Int64_UintLT64) ? AdditionState_CastInt64CheckOverflowMax :
(IntRegion< T,U >::IntZone_Int64_Uint64) ? AdditionState_ManualCheckInt64Uint64 :
(IntRegion< T,U >::IntZone_Int_Uint64) ? AdditionState_ManualCheck :
AdditionState_Error)
};
};
template < typename T, typename U, int method > class AdditionHelper;
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastIntCheckMax >
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
//16-bit or less unsigned addition
__int32 tmp = lhs + rhs;
if( tmp <= (__int32)IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
//16-bit or less unsigned addition
__int32 tmp = lhs + rhs;
if( tmp <= (__int32)IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUintCheckOverflow >
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// 32-bit or less - both are unsigned
unsigned __int32 tmp = (unsigned __int32)lhs + (unsigned __int32)rhs;
//we added didn't get smaller
if( tmp >= lhs )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// 32-bit or less - both are unsigned
unsigned __int32 tmp = (unsigned __int32)lhs + (unsigned __int32)rhs;
//we added didn't get smaller
if( tmp >= lhs )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUintCheckOverflowMax>
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// 32-bit or less - both are unsigned
unsigned __int32 tmp = (unsigned __int32)lhs + (unsigned __int32)rhs;
// We added and it didn't get smaller or exceed maxInt
if( tmp >= lhs && tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
//32-bit or less - both are unsigned
unsigned __int32 tmp = (unsigned __int32)lhs + (unsigned __int32)rhs;
// We added and it didn't get smaller or exceed maxInt
if( tmp >= lhs && tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUint64CheckOverflow>
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs unsigned __int64, rhs unsigned
unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs;
// We added and it didn't get smaller
if(tmp >= lhs)
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// lhs unsigned __int64, rhs unsigned
unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs;
// We added and it didn't get smaller
if(tmp >= lhs)
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUint64CheckOverflowMax >
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
//lhs unsigned __int64, rhs unsigned
unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs;
// We added and it didn't get smaller
if( tmp >= lhs && tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
//lhs unsigned __int64, rhs unsigned
unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs;
// We added and it didn't get smaller
if( tmp >= lhs && tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastIntCheckMinMax >
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// 16-bit or less - one or both are signed
__int32 tmp = lhs + rhs;
if( tmp <= (__int32)IntTraits< T >::maxInt && tmp >= (__int32)IntTraits< T >::minInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// 16-bit or less - one or both are signed
__int32 tmp = lhs + rhs;
if( tmp <= (__int32)IntTraits< T >::maxInt && tmp >= (__int32)IntTraits< T >::minInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastInt64CheckMinMax >
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// 32-bit or less - one or both are signed
__int64 tmp = (__int64)lhs + (__int64)rhs;
if( tmp <= (__int64)IntTraits< T >::maxInt && tmp >= (__int64)IntTraits< T >::minInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// 32-bit or less - one or both are signed
__int64 tmp = (__int64)lhs + (__int64)rhs;
if( tmp <= (__int64)IntTraits< T >::maxInt && tmp >= (__int64)IntTraits< T >::minInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastInt64CheckMax >
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// 32-bit or less - lhs signed, rhs unsigned
__int64 tmp = (__int64)lhs + (__int64)rhs;
if( tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// 32-bit or less - lhs signed, rhs unsigned
__int64 tmp = (__int64)lhs + (__int64)rhs;
if( tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUint64CheckMinMax >
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is unsigned __int64, rhs signed
unsigned __int64 tmp;
if( rhs < 0 )
{
// So we're effectively subtracting
tmp = AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( rhs );
if( tmp <= lhs )
{
result = lhs - tmp;
return true;
}
}
else
{
// now we know that rhs can be safely cast into an unsigned __int64
tmp = (unsigned __int64)lhs + (unsigned __int64)rhs;
// We added and it did not become smaller
if( tmp >= lhs )
{
result = (T)tmp;
return true;
}
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is unsigned __int64, rhs signed
unsigned __int64 tmp;
if( rhs < 0 )
{
// So we're effectively subtracting
tmp = AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( rhs );
if( tmp <= lhs )
{
result = lhs - tmp;
return;
}
}
else
{
// now we know that rhs can be safely cast into an unsigned __int64
tmp = (unsigned __int64)lhs + (unsigned __int64)rhs;
// We added and it did not become smaller
if( tmp >= lhs )
{
result = (T)tmp;
return;
}
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUint64CheckMinMax2>
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is unsigned and < 64-bit, rhs signed __int64
if( rhs < 0 )
{
if( lhs >= (unsigned __int64)( -rhs ) )//negation is safe, since rhs is 64-bit
{
result = (T)( lhs + rhs );
return true;
}
}
else
{
// now we know that rhs can be safely cast into an unsigned __int64
unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs;
// special case - rhs cannot be larger than 0x7fffffffffffffff, lhs cannot be larger than 0xffffffff
// it is not possible for the operation above to overflow, so just check max
if( tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is unsigned and < 64-bit, rhs signed __int64
if( rhs < 0 )
{
if( lhs >= (unsigned __int64)( -rhs ) )//negation is safe, since rhs is 64-bit
{
result = (T)( lhs + rhs );
return;
}
}
else
{
// now we know that rhs can be safely cast into an unsigned __int64
unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs;
// special case - rhs cannot be larger than 0x7fffffffffffffff, lhs cannot be larger than 0xffffffff
// it is not possible for the operation above to overflow, so just check max
if( tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastInt64CheckOverflow>
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is signed __int64, rhs signed
__int64 tmp = (__int64)lhs + (__int64)rhs;
if( lhs >= 0 )
{
// mixed sign cannot overflow
if( rhs >= 0 && tmp < lhs )
return false;
}
else
{
// lhs negative
if( rhs < 0 && tmp > lhs )
return false;
}
result = (T)tmp;
return true;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is signed __int64, rhs signed
__int64 tmp = (__int64)lhs + (__int64)rhs;
if( lhs >= 0 )
{
// mixed sign cannot overflow
if( rhs >= 0 && tmp < lhs )
E::SafeIntOnOverflow();
}
else
{
// lhs negative
if( rhs < 0 && tmp > lhs )
E::SafeIntOnOverflow();
}
result = (T)tmp;
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastInt64CheckOverflowMinMax>
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
//rhs is signed __int64, lhs signed
__int64 tmp;
if( AdditionHelper< __int64, __int64, AdditionState_CastInt64CheckOverflow >::Addition( (__int64)lhs, (__int64)rhs, tmp ) &&
tmp <= IntTraits< T >::maxInt &&
tmp >= IntTraits< T >::minInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
//rhs is signed __int64, lhs signed
__int64 tmp;
AdditionHelper< __int64, __int64, AdditionState_CastInt64CheckOverflow >::AdditionThrow< E >( (__int64)lhs, (__int64)rhs, tmp );
if( tmp <= IntTraits< T >::maxInt &&
tmp >= IntTraits< T >::minInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastInt64CheckOverflowMax>
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
//lhs is signed __int64, rhs unsigned < 64-bit
__int64 tmp = lhs + (__int64)rhs;
if( tmp >= lhs )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
//lhs is signed __int64, rhs unsigned < 64-bit
__int64 tmp = lhs + (__int64)rhs;
if( tmp >= lhs )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < > class AdditionHelper < __int64, unsigned __int64, AdditionState_ManualCheckInt64Uint64 >
{
public:
static bool Addition( const __int64& lhs, const unsigned __int64& rhs, __int64& result ) throw()
{
// rhs is unsigned __int64, lhs __int64
__int64 tmp = lhs + (__int64)rhs;
if( tmp >= lhs )
{
result = tmp;
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const __int64& lhs, const unsigned __int64& rhs, __int64& result )
{
// rhs is unsigned __int64, lhs __int64
__int64 tmp = lhs + (__int64)rhs;
if( tmp >= lhs )
{
result = tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class AdditionHelper < T, U, AdditionState_ManualCheck>
{
public:
static bool Addition( const T& lhs, const U& rhs, T& result ) throw()
{
// rhs is unsigned __int64, lhs signed, 32-bit or less
if( (unsigned __int32)( rhs >> 32 ) == 0 )
{
// Now it just happens to work out that the standard behavior does what we want
// Adding explicit casts to show exactly what's happening here
__int32 tmp = (__int32)( (unsigned __int32)rhs + (unsigned __int32)lhs );
if( tmp >= lhs && SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::Cast( tmp, result ) )
return true;
}
return false;
}
template < typename E >
static void AdditionThrow( const T& lhs, const U& rhs, T& result )
{
// rhs is unsigned __int64, lhs signed, 32-bit or less
if( (unsigned __int32)( rhs >> 32 ) == 0 )
{
// Now it just happens to work out that the standard behavior does what we want
// Adding explicit casts to show exactly what's happening here
__int32 tmp = (__int32)( (unsigned __int32)rhs + (unsigned __int32)lhs );
if( tmp >= lhs )
{
SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::template CastThrow< E >( tmp, result );
return;
}
}
E::SafeIntOnOverflow();
}
};
enum SubtractionState
{
SubtractionState_BothUnsigned,
SubtractionState_CastIntCheckMinMax,
SubtractionState_CastIntCheckMin,
SubtractionState_CastInt64CheckMinMax,
SubtractionState_CastInt64CheckMin,
SubtractionState_Uint64Int,
SubtractionState_UintInt64,
SubtractionState_Int64Int,
SubtractionState_IntInt64,
SubtractionState_Int64Uint,
SubtractionState_IntUint64,
SubtractionState_Int64Uint64,
// states for SubtractionMethod2
SubtractionState_BothUnsigned2,
SubtractionState_CastIntCheckMinMax2,
SubtractionState_CastInt64CheckMinMax2,
SubtractionState_Uint64Int2,
SubtractionState_UintInt642,
SubtractionState_Int64Int2,
SubtractionState_IntInt642,
SubtractionState_Int64Uint2,
SubtractionState_IntUint642,
SubtractionState_Int64Uint642,
SubtractionState_Error
};
template < typename T, typename U > class SubtractionMethod
{
public:
enum
{
// unsigned-unsigned
method = ((IntRegion< T,U >::IntZone_UintLT32_UintLT32 ||
(IntRegion< T,U >::IntZone_Uint32_UintLT64) ||
(IntRegion< T,U >::IntZone_UintLT32_Uint32) ||
(IntRegion< T,U >::IntZone_Uint64_Uint) ||
(IntRegion< T,U >::IntZone_UintLT64_Uint64)) ? SubtractionState_BothUnsigned :
// unsigned-signed
(IntRegion< T,U >::IntZone_UintLT32_IntLT32) ? SubtractionState_CastIntCheckMinMax :
(IntRegion< T,U >::IntZone_Uint32_IntLT64 ||
IntRegion< T,U >::IntZone_UintLT32_Int32) ? SubtractionState_CastInt64CheckMinMax :
(IntRegion< T,U >::IntZone_Uint64_Int ||
IntRegion< T,U >::IntZone_Uint64_Int64) ? SubtractionState_Uint64Int :
(IntRegion< T,U >::IntZone_UintLT64_Int64) ? SubtractionState_UintInt64 :
// signed-signed
(IntRegion< T,U >::IntZone_IntLT32_IntLT32) ? SubtractionState_CastIntCheckMinMax :
(IntRegion< T,U >::IntZone_Int32_IntLT64 ||
IntRegion< T,U >::IntZone_IntLT32_Int32) ? SubtractionState_CastInt64CheckMinMax :
(IntRegion< T,U >::IntZone_Int64_Int ||
IntRegion< T,U >::IntZone_Int64_Int64) ? SubtractionState_Int64Int :
(IntRegion< T,U >::IntZone_IntLT64_Int64) ? SubtractionState_IntInt64 :
// signed-unsigned
(IntRegion< T,U >::IntZone_IntLT32_UintLT32) ? SubtractionState_CastIntCheckMin :
(IntRegion< T,U >::IntZone_Int32_UintLT32 ||
IntRegion< T,U >::IntZone_IntLT64_Uint32) ? SubtractionState_CastInt64CheckMin :
(IntRegion< T,U >::IntZone_Int64_UintLT64) ? SubtractionState_Int64Uint :
(IntRegion< T,U >::IntZone_Int_Uint64) ? SubtractionState_IntUint64 :
(IntRegion< T,U >::IntZone_Int64_Uint64) ? SubtractionState_Int64Uint64 :
SubtractionState_Error)
};
};
// this is for the case of U - SafeInt< T, E >
template < typename T, typename U > class SubtractionMethod2
{
public:
enum
{
// unsigned-unsigned
method = ((IntRegion< T,U >::IntZone_UintLT32_UintLT32 ||
(IntRegion< T,U >::IntZone_Uint32_UintLT64) ||
(IntRegion< T,U >::IntZone_UintLT32_Uint32) ||
(IntRegion< T,U >::IntZone_Uint64_Uint) ||
(IntRegion< T,U >::IntZone_UintLT64_Uint64)) ? SubtractionState_BothUnsigned2 :
// unsigned-signed
(IntRegion< T,U >::IntZone_UintLT32_IntLT32) ? SubtractionState_CastIntCheckMinMax2 :
(IntRegion< T,U >::IntZone_Uint32_IntLT64 ||
IntRegion< T,U >::IntZone_UintLT32_Int32) ? SubtractionState_CastInt64CheckMinMax2 :
(IntRegion< T,U >::IntZone_Uint64_Int ||
IntRegion< T,U >::IntZone_Uint64_Int64) ? SubtractionState_Uint64Int2 :
(IntRegion< T,U >::IntZone_UintLT64_Int64) ? SubtractionState_UintInt642 :
// signed-signed
(IntRegion< T,U >::IntZone_IntLT32_IntLT32) ? SubtractionState_CastIntCheckMinMax2 :
(IntRegion< T,U >::IntZone_Int32_IntLT64 ||
IntRegion< T,U >::IntZone_IntLT32_Int32) ? SubtractionState_CastInt64CheckMinMax2 :
(IntRegion< T,U >::IntZone_Int64_Int ||
IntRegion< T,U >::IntZone_Int64_Int64) ? SubtractionState_Int64Int2 :
(IntRegion< T,U >::IntZone_IntLT64_Int64) ? SubtractionState_IntInt642 :
// signed-unsigned
(IntRegion< T,U >::IntZone_IntLT32_UintLT32) ? SubtractionState_CastIntCheckMinMax2 :
(IntRegion< T,U >::IntZone_Int32_UintLT32 ||
IntRegion< T,U >::IntZone_IntLT64_Uint32) ? SubtractionState_CastInt64CheckMinMax2 :
(IntRegion< T,U >::IntZone_Int64_UintLT64) ? SubtractionState_Int64Uint2 :
(IntRegion< T,U >::IntZone_Int_Uint64) ? SubtractionState_IntUint642 :
(IntRegion< T,U >::IntZone_Int64_Uint64) ? SubtractionState_Int64Uint642 :
SubtractionState_Error)
};
};
template < typename T, typename U, int method > class SubtractionHelper;
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_BothUnsigned >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// both are unsigned - easy case
if( rhs <= lhs )
{
result = (T)( lhs - rhs );
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// both are unsigned - easy case
if( rhs <= lhs )
{
result = (T)( lhs - rhs );
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_BothUnsigned2 >
{
public:
static bool Subtract( const T& lhs, const U& rhs, U& result ) throw()
{
// both are unsigned - easy case
// Except we do have to check for overflow - lhs could be larger than result can hold
if( rhs <= lhs )
{
T tmp = (T)(lhs - rhs);
return SafeCastHelper< U, T, GetCastMethod<U, T>::method>::Cast( tmp, result);
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, U& result )
{
// both are unsigned - easy case
if( rhs <= lhs )
{
T tmp = (T)(lhs - rhs);
SafeCastHelper< U, T, GetCastMethod<U, T>::method >::template CastThrow<E>( tmp, result);
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_CastIntCheckMinMax >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// both values are 16-bit or less
// rhs is signed, so could end up increasing or decreasing
__int32 tmp = lhs - rhs;
if( SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::Cast( tmp, result ) )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// both values are 16-bit or less
// rhs is signed, so could end up increasing or decreasing
__int32 tmp = lhs - rhs;
SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::template CastThrow< E >( tmp, result );
}
};
template <typename U, typename T> class SubtractionHelper< U, T, SubtractionState_CastIntCheckMinMax2 >
{
public:
static bool Subtract( const U& lhs, const T& rhs, T& result ) throw()
{
// both values are 16-bit or less
// rhs is signed, so could end up increasing or decreasing
__int32 tmp = lhs - rhs;
return SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::Cast( tmp, result );
}
template < typename E >
static void SubtractThrow( const U& lhs, const T& rhs, T& result )
{
// both values are 16-bit or less
// rhs is signed, so could end up increasing or decreasing
__int32 tmp = lhs - rhs;
SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::template CastThrow< E >( tmp, result );
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_CastIntCheckMin >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// both values are 16-bit or less
// rhs is unsigned - check only minimum
__int32 tmp = lhs - rhs;
if( tmp >= (__int32)IntTraits< T >::minInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// both values are 16-bit or less
// rhs is unsigned - check only minimum
__int32 tmp = lhs - rhs;
if( tmp >= (__int32)IntTraits< T >::minInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_CastInt64CheckMinMax >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// both values are 32-bit or less
// rhs is signed, so could end up increasing or decreasing
__int64 tmp = (__int64)lhs - (__int64)rhs;
return SafeCastHelper< T, __int64, GetCastMethod< T, __int64 >::method >::Cast( tmp, result );
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// both values are 32-bit or less
// rhs is signed, so could end up increasing or decreasing
__int64 tmp = (__int64)lhs - (__int64)rhs;
SafeCastHelper< T, __int64, GetCastMethod< T, __int64 >::method >::template CastThrow< E >( tmp, result );
}
};
template <typename U, typename T> class SubtractionHelper< U, T, SubtractionState_CastInt64CheckMinMax2 >
{
public:
static bool Subtract( const U& lhs, const T& rhs, T& result ) throw()
{
// both values are 32-bit or less
// rhs is signed, so could end up increasing or decreasing
__int64 tmp = (__int64)lhs - (__int64)rhs;
return SafeCastHelper< T, __int64, GetCastMethod< T, __int64 >::method >::Cast( tmp, result );
}
template < typename E >
static void SubtractThrow( const U& lhs, const T& rhs, T& result )
{
// both values are 32-bit or less
// rhs is signed, so could end up increasing or decreasing
__int64 tmp = (__int64)lhs - (__int64)rhs;
SafeCastHelper< T, __int64, GetCastMethod< T, __int64 >::method >::template CastThrow< E >( tmp, result );
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_CastInt64CheckMin >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// both values are 32-bit or less
// rhs is unsigned - check only minimum
__int64 tmp = (__int64)lhs - (__int64)rhs;
if( tmp >= (__int64)IntTraits< T >::minInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// both values are 32-bit or less
// rhs is unsigned - check only minimum
__int64 tmp = (__int64)lhs - (__int64)rhs;
if( tmp >= (__int64)IntTraits< T >::minInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_Uint64Int >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is an unsigned __int64, rhs signed
// must first see if rhs is positive or negative
if( rhs >= 0 )
{
if( (unsigned __int64)rhs <= lhs )
{
result = (T)( lhs - (unsigned __int64)rhs );
return true;
}
}
else
{
// we're now effectively adding
result = lhs + AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( rhs );
if(result >= lhs)
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is an unsigned __int64, rhs signed
// must first see if rhs is positive or negative
if( rhs >= 0 )
{
if( (unsigned __int64)rhs <= lhs )
{
result = (T)( lhs - (unsigned __int64)rhs );
return;
}
}
else
{
// we're now effectively adding
result = lhs + AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( rhs );
if(result >= lhs)
return;
}
E::SafeIntOnOverflow();
}
};
template < typename U, typename T > class SubtractionHelper< U, T, SubtractionState_Uint64Int2 >
{
public:
static bool Subtract( const U& lhs, const T& rhs, T& result ) throw()
{
// U is unsigned __int64, T is signed
if( rhs < 0 )
{
// treat this as addition
unsigned __int64 tmp;
tmp = lhs + (unsigned __int64)AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( rhs );
// must check for addition overflow and max
if( tmp >= lhs && tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
}
else if( (unsigned __int64)rhs > lhs ) // now both are positive, so comparison always works
{
// result is negative
// implies that lhs must fit into T, and result cannot overflow
// Also allows us to drop to 32-bit math, which is faster on a 32-bit system
result = (T)lhs - (T)rhs;
return true;
}
else
{
// result is positive
unsigned __int64 tmp = (unsigned __int64)lhs - (unsigned __int64)rhs;
if( tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
}
return false;
}
template < typename E >
static void SubtractThrow( const U& lhs, const T& rhs, T& result )
{
// U is unsigned __int64, T is signed
if( rhs < 0 )
{
// treat this as addition
unsigned __int64 tmp;
tmp = lhs + (unsigned __int64)AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( rhs );
// must check for addition overflow and max
if( tmp >= lhs && tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
}
else if( (unsigned __int64)rhs > lhs ) // now both are positive, so comparison always works
{
// result is negative
// implies that lhs must fit into T, and result cannot overflow
// Also allows us to drop to 32-bit math, which is faster on a 32-bit system
result = (T)lhs - (T)rhs;
return;
}
else
{
// result is positive
unsigned __int64 tmp = (unsigned __int64)lhs - (unsigned __int64)rhs;
if( tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_UintInt64 >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is an unsigned int32 or smaller, rhs signed __int64
// must first see if rhs is positive or negative
if( rhs >= 0 )
{
if( (unsigned __int64)rhs <= lhs )
{
result = (T)( lhs - (T)rhs );
return true;
}
}
else
{
// we're now effectively adding
// since lhs is 32-bit, and rhs cannot exceed 2^63
// this addition cannot overflow
unsigned __int64 tmp = lhs + (unsigned __int64)( -rhs ); // negation safe
// but we could exceed MaxInt
if(tmp <= IntTraits< T >::maxInt)
{
result = (T)tmp;
return true;
}
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is an unsigned int32 or smaller, rhs signed __int64
// must first see if rhs is positive or negative
if( rhs >= 0 )
{
if( (unsigned __int64)rhs <= lhs )
{
result = (T)( lhs - (T)rhs );
return;
}
}
else
{
// we're now effectively adding
// since lhs is 32-bit, and rhs cannot exceed 2^63
// this addition cannot overflow
unsigned __int64 tmp = lhs + (unsigned __int64)( -rhs ); // negation safe
// but we could exceed MaxInt
if(tmp <= IntTraits< T >::maxInt)
{
result = (T)tmp;
return;
}
}
E::SafeIntOnOverflow();
}
};
template <typename U, typename T> class SubtractionHelper< U, T, SubtractionState_UintInt642 >
{
public:
static bool Subtract( const U& lhs, const T& rhs, T& result ) throw()
{
// U unsigned 32-bit or less, T __int64
if( rhs >= 0 )
{
// overflow not possible
result = (T)( (__int64)lhs - rhs );
return true;
}
else
{
// we effectively have an addition
// which cannot overflow internally
unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)( -rhs );
if( tmp <= (unsigned __int64)IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
}
return false;
}
template < typename E >
static void SubtractThrow( const U& lhs, const T& rhs, T& result )
{
// U unsigned 32-bit or less, T __int64
if( rhs >= 0 )
{
// overflow not possible
result = (T)( (__int64)lhs - rhs );
return;
}
else
{
// we effectively have an addition
// which cannot overflow internally
unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)( -rhs );
if( tmp <= (unsigned __int64)IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_Int64Int >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is an __int64, rhs signed (up to 64-bit)
// we have essentially 4 cases:
//
// 1) lhs positive, rhs positive - overflow not possible
// 2) lhs positive, rhs negative - equivalent to addition - result >= lhs or error
// 3) lhs negative, rhs positive - check result <= lhs
// 4) lhs negative, rhs negative - overflow not possible
__int64 tmp = lhs - rhs;
// Note - ideally, we can order these so that true conditionals
// lead to success, which enables better pipelining
// It isn't practical here
if( ( lhs >= 0 && rhs < 0 && tmp < lhs ) || // condition 2
( rhs >= 0 && tmp > lhs ) ) // condition 3
{
return false;
}
result = (T)tmp;
return true;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is an __int64, rhs signed (up to 64-bit)
// we have essentially 4 cases:
//
// 1) lhs positive, rhs positive - overflow not possible
// 2) lhs positive, rhs negative - equivalent to addition - result >= lhs or error
// 3) lhs negative, rhs positive - check result <= lhs
// 4) lhs negative, rhs negative - overflow not possible
__int64 tmp = lhs - rhs;
// Note - ideally, we can order these so that true conditionals
// lead to success, which enables better pipelining
// It isn't practical here
if( ( lhs >= 0 && rhs < 0 && tmp < lhs ) || // condition 2
( rhs >= 0 && tmp > lhs ) ) // condition 3
{
E::SafeIntOnOverflow();
}
result = (T)tmp;
}
};
template < typename U, typename T > class SubtractionHelper< U, T, SubtractionState_Int64Int2 >
{
public:
static bool Subtract( const U& lhs, const T& rhs, T& result ) throw()
{
// lhs __int64, rhs any signed int (including __int64)
__int64 tmp = lhs - rhs;
// we have essentially 4 cases:
//
// 1) lhs positive, rhs positive - overflow not possible in tmp
// 2) lhs positive, rhs negative - equivalent to addition - result >= lhs or error
// 3) lhs negative, rhs positive - check result <= lhs
// 4) lhs negative, rhs negative - overflow not possible in tmp
if( lhs >= 0 )
{
// if both positive, overflow to negative not possible
// which is why we'll explicitly check maxInt, and not call SafeCast
if( ( IntTraits< T >::isLT64Bit && tmp > IntTraits< T >::maxInt ) ||
( rhs < 0 && tmp < lhs ) )
{
return false;
}
}
else
{
// lhs negative
if( ( IntTraits< T >::isLT64Bit && tmp < IntTraits< T >::minInt) ||
( rhs >=0 && tmp > lhs ) )
{
return false;
}
}
result = (T)tmp;
return true;
}
template < typename E >
static void SubtractThrow( const U& lhs, const T& rhs, T& result )
{
// lhs __int64, rhs any signed int (including __int64)
__int64 tmp = lhs - rhs;
// we have essentially 4 cases:
//
// 1) lhs positive, rhs positive - overflow not possible in tmp
// 2) lhs positive, rhs negative - equivalent to addition - result >= lhs or error
// 3) lhs negative, rhs positive - check result <= lhs
// 4) lhs negative, rhs negative - overflow not possible in tmp
if( lhs >= 0 )
{
// if both positive, overflow to negative not possible
// which is why we'll explicitly check maxInt, and not call SafeCast
if( ( IntTraits< T >::isLT64Bit && tmp > IntTraits< T >::maxInt ) ||
( rhs < 0 && tmp < lhs ) )
{
E::SafeIntOnOverflow();
}
}
else
{
// lhs negative
if( ( IntTraits< T >::isLT64Bit && tmp < IntTraits< T >::minInt) ||
( rhs >=0 && tmp > lhs ) )
{
E::SafeIntOnOverflow();
}
}
result = (T)tmp;
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_IntInt64 >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is a 32-bit int or less, rhs __int64
// we have essentially 4 cases:
//
// lhs positive, rhs positive - rhs could be larger than lhs can represent
// lhs positive, rhs negative - additive case - check tmp >= lhs and tmp > max int
// lhs negative, rhs positive - check tmp <= lhs and tmp < min int
// lhs negative, rhs negative - addition cannot internally overflow, check against max
__int64 tmp = (__int64)lhs - rhs;
if( lhs >= 0 )
{
// first case
if( rhs >= 0 )
{
if( tmp >= IntTraits< T >::minInt )
{
result = (T)tmp;
return true;
}
}
else
{
// second case
if( tmp >= lhs && tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
}
}
else
{
// lhs < 0
// third case
if( rhs >= 0 )
{
if( tmp <= lhs && tmp >= IntTraits< T >::minInt )
{
result = (T)tmp;
return true;
}
}
else
{
// fourth case
if( tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return true;
}
}
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is a 32-bit int or less, rhs __int64
// we have essentially 4 cases:
//
// lhs positive, rhs positive - rhs could be larger than lhs can represent
// lhs positive, rhs negative - additive case - check tmp >= lhs and tmp > max int
// lhs negative, rhs positive - check tmp <= lhs and tmp < min int
// lhs negative, rhs negative - addition cannot internally overflow, check against max
__int64 tmp = (__int64)lhs - rhs;
if( lhs >= 0 )
{
// first case
if( rhs >= 0 )
{
if( tmp >= IntTraits< T >::minInt )
{
result = (T)tmp;
return;
}
}
else
{
// second case
if( tmp >= lhs && tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
}
}
else
{
// lhs < 0
// third case
if( rhs >= 0 )
{
if( tmp <= lhs && tmp >= IntTraits< T >::minInt )
{
result = (T)tmp;
return;
}
}
else
{
// fourth case
if( tmp <= IntTraits< T >::maxInt )
{
result = (T)tmp;
return;
}
}
}
E::SafeIntOnOverflow();
}
};
template < typename U, typename T > class SubtractionHelper< U, T, SubtractionState_IntInt642 >
{
public:
static bool Subtract( const U& lhs, const T& rhs, T& result ) throw()
{
// lhs is any signed int32 or smaller, rhs is int64
__int64 tmp = (__int64)lhs - rhs;
if( ( lhs >= 0 && rhs < 0 && tmp < lhs ) ||
( rhs > 0 && tmp > lhs ) )
{
return false;
//else OK
}
result = (T)tmp;
return true;
}
template < typename E >
static void SubtractThrow( const U& lhs, const T& rhs, T& result )
{
// lhs is any signed int32 or smaller, rhs is int64
__int64 tmp = (__int64)lhs - rhs;
if( ( lhs >= 0 && rhs < 0 && tmp < lhs ) ||
( rhs > 0 && tmp > lhs ) )
{
E::SafeIntOnOverflow();
//else OK
}
result = (T)tmp;
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_Int64Uint >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is a 64-bit int, rhs unsigned int32 or smaller
__int64 tmp = lhs - (__int64)rhs;
if( tmp <= lhs )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is a 64-bit int, rhs unsigned int32 or smaller
__int64 tmp = lhs - (__int64)rhs;
if( tmp <= lhs )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename U, typename T > class SubtractionHelper< U, T, SubtractionState_Int64Uint2 >
{
public:
// lhs is __int64, rhs is unsigned 32-bit or smaller
static bool Subtract( const U& lhs, const T& rhs, T& result ) throw()
{
__int64 tmp = lhs - (__int64)rhs;
if( tmp <= IntTraits< T >::maxInt && tmp >= IntTraits< T >::minInt )
{
result = (T)tmp;
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const U& lhs, const T& rhs, T& result )
{
__int64 tmp = lhs - (__int64)rhs;
if( tmp <= IntTraits< T >::maxInt && tmp >= IntTraits< T >::minInt )
{
result = (T)tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_IntUint64 >
{
public:
static bool Subtract( const T& lhs, const U& rhs, T& result ) throw()
{
// lhs is any signed int, rhs unsigned int64
// check against available range
// We need the absolute value of IntTraits< T >::minInt
// This will give it to us without extraneous compiler warnings
const unsigned __int64 AbsMinIntT = (unsigned __int64)IntTraits< T >::maxInt + 1;
if( lhs < 0 )
{
if( rhs <= AbsMinIntT - AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( lhs ) )
{
result = (T)( lhs - rhs );
return true;
}
}
else
{
if( rhs <= AbsMinIntT + (unsigned __int64)lhs )
{
result = (T)( lhs - rhs );
return true;
}
}
return false;
}
template < typename E >
static void SubtractThrow( const T& lhs, const U& rhs, T& result )
{
// lhs is any signed int, rhs unsigned int64
// check against available range
// We need the absolute value of IntTraits< T >::minInt
// This will give it to us without extraneous compiler warnings
const unsigned __int64 AbsMinIntT = (unsigned __int64)IntTraits< T >::maxInt + 1;
if( lhs < 0 )
{
if( rhs <= AbsMinIntT - AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( lhs ) )
{
result = (T)( lhs - rhs );
return;
}
}
else
{
if( rhs <= AbsMinIntT + (unsigned __int64)lhs )
{
result = (T)( lhs - rhs );
return;
}
}
E::SafeIntOnOverflow();
}
};
template < typename U, typename T > class SubtractionHelper< U, T, SubtractionState_IntUint642 >
{
public:
static bool Subtract( const U& lhs, const T& rhs, T& result ) throw()
{
// We run into upcasting problems on comparison - needs 2 checks
if( lhs >= 0 && (T)lhs >= rhs )
{
result = (T)((U)lhs - (U)rhs);
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const U& lhs, const T& rhs, T& result )
{
// We run into upcasting problems on comparison - needs 2 checks
if( lhs >= 0 && (T)lhs >= rhs )
{
result = (T)((U)lhs - (U)rhs);
return;
}
E::SafeIntOnOverflow();
}
};
template < > class SubtractionHelper< __int64, unsigned __int64, SubtractionState_Int64Uint64 >
{
public:
static bool Subtract( const __int64& lhs, const unsigned __int64& rhs, __int64& result ) throw()
{
// if we subtract, and it gets larger, there's a problem
__int64 tmp = lhs - (__int64)rhs;
if( tmp <= lhs )
{
result = tmp;
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const __int64& lhs, const unsigned __int64& rhs, __int64& result )
{
// if we subtract, and it gets larger, there's a problem
__int64 tmp = lhs - (__int64)rhs;
if( tmp <= lhs )
{
result = tmp;
return;
}
E::SafeIntOnOverflow();
}
};
template < > class SubtractionHelper< __int64, unsigned __int64, SubtractionState_Int64Uint642 >
{
public:
// If lhs is negative, immediate problem - return must be positive, and subtracting only makes it
// get smaller. If rhs > lhs, then it would also go negative, which is the other case
static bool Subtract( const __int64& lhs, const unsigned __int64& rhs, unsigned __int64& result ) throw()
{
if( lhs >= 0 && (unsigned __int64)lhs >= rhs )
{
result = (unsigned __int64)lhs - rhs;
return true;
}
return false;
}
template < typename E >
static void SubtractThrow( const __int64& lhs, const unsigned __int64& rhs, unsigned __int64& result )
{
if( lhs >= 0 && (unsigned __int64)lhs >= rhs )
{
result = (unsigned __int64)lhs - rhs;
return;
}
E::SafeIntOnOverflow();
}
};
enum BinaryState
{
BinaryState_OK,
BinaryState_Int8,
BinaryState_Int16,
BinaryState_Int32
};
template < typename T, typename U > class BinaryMethod
{
public:
enum
{
// If both operands are unsigned OR
// return type is smaller than rhs OR
// return type is larger and rhs is unsigned
// Then binary operations won't produce unexpected results
method = ( sizeof( T ) <= sizeof( U ) ||
SafeIntCompare< T, U >::isBothUnsigned ||
!IntTraits< U >::isSigned ) ? BinaryState_OK :
IntTraits< U >::isInt8 ? BinaryState_Int8 :
IntTraits< U >::isInt16 ? BinaryState_Int16
: BinaryState_Int32
};
};
#ifdef SAFEINT_DISABLE_BINARY_ASSERT
#define BinaryAssert(x)
#else
#define BinaryAssert(x) assert(x)
#endif
template < typename T, typename U, int method > class BinaryAndHelper;
template < typename T, typename U > class BinaryAndHelper< T, U, BinaryState_OK >
{
public:
static T And( T lhs, U rhs ){ return (T)( lhs & rhs ); }
};
template < typename T, typename U > class BinaryAndHelper< T, U, BinaryState_Int8 >
{
public:
static T And( T lhs, U rhs )
{
// cast forces sign extension to be zeros
BinaryAssert( ( lhs & rhs ) == ( lhs & (unsigned __int8)rhs ) );
return (T)( lhs & (unsigned __int8)rhs );
}
};
template < typename T, typename U > class BinaryAndHelper< T, U, BinaryState_Int16 >
{
public:
static T And( T lhs, U rhs )
{
//cast forces sign extension to be zeros
BinaryAssert( ( lhs & rhs ) == ( lhs & (unsigned __int16)rhs ) );
return (T)( lhs & (unsigned __int16)rhs );
}
};
template < typename T, typename U > class BinaryAndHelper< T, U, BinaryState_Int32 >
{
public:
static T And( T lhs, U rhs )
{
//cast forces sign extension to be zeros
BinaryAssert( ( lhs & rhs ) == ( lhs & (unsigned __int32)rhs ) );
return (T)( lhs & (unsigned __int32)rhs );
}
};
template < typename T, typename U, int method > class BinaryOrHelper;
template < typename T, typename U > class BinaryOrHelper< T, U, BinaryState_OK >
{
public:
static T Or( T lhs, U rhs ){ return (T)( lhs | rhs ); }
};
template < typename T, typename U > class BinaryOrHelper< T, U, BinaryState_Int8 >
{
public:
static T Or( T lhs, U rhs )
{
//cast forces sign extension to be zeros
BinaryAssert( ( lhs | rhs ) == ( lhs | (unsigned __int8)rhs ) );
return (T)( lhs | (unsigned __int8)rhs );
}
};
template < typename T, typename U > class BinaryOrHelper< T, U, BinaryState_Int16 >
{
public:
static T Or( T lhs, U rhs )
{
//cast forces sign extension to be zeros
BinaryAssert( ( lhs | rhs ) == ( lhs | (unsigned __int16)rhs ) );
return (T)( lhs | (unsigned __int16)rhs );
}
};
template < typename T, typename U > class BinaryOrHelper< T, U, BinaryState_Int32 >
{
public:
static T Or( T lhs, U rhs )
{
//cast forces sign extension to be zeros
BinaryAssert( ( lhs | rhs ) == ( lhs | (unsigned __int32)rhs ) );
return (T)( lhs | (unsigned __int32)rhs );
}
};
template <typename T, typename U, int method > class BinaryXorHelper;
template < typename T, typename U > class BinaryXorHelper< T, U, BinaryState_OK >
{
public:
static T Xor( T lhs, U rhs ){ return (T)( lhs ^ rhs ); }
};
template < typename T, typename U > class BinaryXorHelper< T, U, BinaryState_Int8 >
{
public:
static T Xor( T lhs, U rhs )
{
// cast forces sign extension to be zeros
BinaryAssert( ( lhs ^ rhs ) == ( lhs ^ (unsigned __int8)rhs ) );
return (T)( lhs ^ (unsigned __int8)rhs );
}
};
template < typename T, typename U > class BinaryXorHelper< T, U, BinaryState_Int16 >
{
public:
static T Xor( T lhs, U rhs )
{
// cast forces sign extension to be zeros
BinaryAssert( ( lhs ^ rhs ) == ( lhs ^ (unsigned __int16)rhs ) );
return (T)( lhs ^ (unsigned __int16)rhs );
}
};
template < typename T, typename U > class BinaryXorHelper< T, U, BinaryState_Int32 >
{
public:
static T Xor( T lhs, U rhs )
{
// cast forces sign extension to be zeros
BinaryAssert( ( lhs ^ rhs ) == ( lhs ^ (unsigned __int32)rhs ) );
return (T)( lhs ^ (unsigned __int32)rhs );
}
};
/***************** External functions ****************************************/
// External functions that can be used where you only need to check one operation
// non-class helper function so that you can check for a cast's validity
// and handle errors how you like
template < typename T, typename U >
inline bool SafeCast( const T From, U& To )
{
return SafeCastHelper< U, T, GetCastMethod< U, T >::method >::Cast( From, To );
}
template < typename T, typename U >
inline bool SafeEquals( const T t, const U u ) throw()
{
return EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( t, u );
}
template < typename T, typename U >
inline bool SafeNotEquals( const T t, const U u ) throw()
{
return !EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( t, u );
}
template < typename T, typename U >
inline bool SafeGreaterThan( const T t, const U u ) throw()
{
return GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( t, u );
}
template < typename T, typename U >
inline bool SafeGreaterThanEquals( const T t, const U u ) throw()
{
return !GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( u, t );
}
template < typename T, typename U >
inline bool SafeLessThan( const T t, const U u ) throw()
{
return GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( u, t );
}
template < typename T, typename U >
inline bool SafeLessThanEquals( const T t, const U u ) throw()
{
return !GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( t, u );
}
template < typename T, typename U >
inline bool SafeModulus( const T& t, const U& u, T& result ) throw()
{
return ( ModulusHelper< T, U, ValidComparison< T, U >::method >::Modulus( t, u, result ) == SafeIntNoError );
}
template < typename T, typename U >
inline bool SafeMultiply( T t, U u, T& result ) throw()
{
return MultiplicationHelper< T, U, MultiplicationMethod< T, U >::method >::Multiply( t, u, result );
}
template < typename T, typename U >
inline bool SafeDivide( T t, U u, T& result ) throw()
{
return ( DivisionHelper< T, U, DivisionMethod< T, U >::method >::Divide( t, u, result ) == SafeIntNoError );
}
template < typename T, typename U >
inline bool SafeAdd( T t, U u, T& result ) throw()
{
return AdditionHelper< T, U, AdditionMethod< T, U >::method >::Addition( t, u, result );
}
template < typename T, typename U >
inline bool SafeSubtract( T t, U u, T& result ) throw()
{
return SubtractionHelper< T, U, SubtractionMethod< T, U >::method >::Subtract( t, u, result );
}
/***************** end external functions ************************************/
// Main SafeInt class
// Assumes exceptions can be thrown
template < typename T, typename E = SafeIntDefaultExceptionHandler > class SafeInt
{
public:
SafeInt() throw()
{
C_ASSERT( NumericType< T >::isInt );
m_int = 0;
}
// Having a constructor for every type of int
// avoids having the compiler evade our checks when doing implicit casts -
// e.g., SafeInt<char> s = 0x7fffffff;
SafeInt( const T& i ) throw()
{
C_ASSERT( NumericType< T >::isInt );
//always safe
m_int = i;
}
// provide explicit boolean converter
SafeInt( bool b ) throw()
{
C_ASSERT( NumericType< T >::isInt );
m_int = b ? 1 : 0;
}
template < typename U >
SafeInt(const SafeInt< U, E >& u)
{
C_ASSERT( NumericType< T >::isInt );
*this = SafeInt< T, E >( (U)u );
}
template < typename U >
SafeInt( const U& i )
{
C_ASSERT( NumericType< T >::isInt );
// SafeCast will throw exceptions if i won't fit in type T
SafeCastHelper< T, U, GetCastMethod< T, U >::method >::template CastThrow< E >( i, m_int );
}
// The destructor is intentionally commented out - no destructor
// vs. a do-nothing destructor makes a huge difference in
// inlining characteristics. It wasn't doing anything anyway.
// ~SafeInt(){};
// now start overloading operators
// assignment operator
// constructors exist for all int types and will ensure safety
template < typename U >
SafeInt< T, E >& operator =( const U& rhs )
{
// use constructor to test size
// constructor is optimized to do minimal checking based
// on whether T can contain U
// note - do not change this
*this = SafeInt< T, E >( rhs );
return *this;
}
SafeInt< T, E >& operator =( const T& rhs ) throw()
{
m_int = rhs;
return *this;
}
template < typename U >
SafeInt< T, E >& operator =( const SafeInt< U, E >& rhs )
{
SafeCastHelper< T, U, GetCastMethod< T, U >::method >::template CastThrow< E >( rhs.Ref(), m_int );
return *this;
}
SafeInt< T, E >& operator =( const SafeInt< T, E >& rhs ) throw()
{
m_int = rhs.m_int;
return *this;
}
// Casting operators
operator bool() const throw()
{
return !!m_int;
}
operator char() const
{
char val;
SafeCastHelper< char, T, GetCastMethod< char, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator signed char() const
{
signed char val;
SafeCastHelper< signed char, T, GetCastMethod< signed char, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator unsigned char() const
{
unsigned char val;
SafeCastHelper< unsigned char, T, GetCastMethod< unsigned char, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator __int16() const
{
__int16 val;
SafeCastHelper< __int16, T, GetCastMethod< __int16, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator unsigned __int16() const
{
unsigned __int16 val;
SafeCastHelper< unsigned __int16, T, GetCastMethod< unsigned __int16, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator __int32() const
{
__int32 val;
SafeCastHelper< __int32, T, GetCastMethod< __int32, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator unsigned __int32() const
{
unsigned __int32 val;
SafeCastHelper< unsigned __int32, T, GetCastMethod< unsigned __int32, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
// The compiler knows that int == __int32
// but not that long == __int32
operator long() const
{
long val;
SafeCastHelper< long, T, GetCastMethod< long, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator unsigned long() const
{
unsigned long val;
SafeCastHelper< unsigned long, T, GetCastMethod< unsigned long, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator __int64() const
{
__int64 val;
SafeCastHelper< __int64, T, GetCastMethod< __int64, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator unsigned __int64() const
{
unsigned __int64 val;
SafeCastHelper< unsigned __int64, T, GetCastMethod< unsigned __int64, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
#ifdef SIZE_T_CAST_NEEDED
// We also need an explicit cast to size_t, or the compiler will complain
// Apparently, only SOME compilers complain, and cl 14.00.50727.42 isn't one of them
// Leave here in case we decide to backport this to an earlier compiler
operator size_t() const
{
size_t val;
SafeCastHelper< size_t, T, GetCastMethod< size_t, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
#endif
// Also provide a cast operator for floating point types
operator float() const
{
float val;
SafeCastHelper< float, T, GetCastMethod< float, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator double() const
{
double val;
SafeCastHelper< double, T, GetCastMethod< double, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
operator long double() const
{
long double val;
SafeCastHelper< long double, T, GetCastMethod< long double, T >::method >::template CastThrow< E >( m_int, val );
return val;
}
// If you need a pointer to the data
// this could be dangerous, but allows you to correctly pass
// instances of this class to APIs that take a pointer to an integer
// also see overloaded address-of operator below
T* Ptr() throw() { return &m_int; }
const T* Ptr() const throw() { return &m_int; }
const T& Ref() const throw() { return m_int; }
// Or if SafeInt< T, E >::Ptr() is inconvenient, use the overload
// operator &
// This allows you to do unsafe things!
// It is meant to allow you to more easily
// pass a SafeInt into things like ReadFile
T* operator &() throw() { return &m_int; }
const T* operator &() const throw() { return &m_int; }
// Unary operators
bool operator !() const throw() { return (!m_int) ? true : false; }
// operator + (unary)
// note - normally, the '+' and '-' operators will upcast to a signed int
// for T < 32 bits. This class changes behavior to preserve type
const SafeInt< T, E >& operator +() const throw() { return *this; };
//unary -
SafeInt< T, E > operator -() const
{
// Note - unsigned still performs the bitwise manipulation
// will warn at level 2 or higher if the value is 32-bit or larger
return SafeInt<T, E>(NegationHelper<T, IntTraits<T>::isSigned>::template NegativeThrow<E>(m_int));
}
// prefix increment operator
SafeInt< T, E >& operator ++()
{
if( m_int != IntTraits< T >::maxInt )
{
++m_int;
return *this;
}
E::SafeIntOnOverflow();
}
// prefix decrement operator
SafeInt< T, E >& operator --()
{
if( m_int != IntTraits< T >::minInt )
{
--m_int;
return *this;
}
E::SafeIntOnOverflow();
}
// note that postfix operators have inherently worse perf
// characteristics
// postfix increment operator
SafeInt< T, E > operator ++( int ) // dummy arg to comply with spec
{
if( m_int != IntTraits< T >::maxInt )
{
SafeInt< T, E > tmp( m_int );
m_int++;
return tmp;
}
E::SafeIntOnOverflow();
}
// postfix decrement operator
SafeInt< T, E > operator --( int ) // dummy arg to comply with spec
{
if( m_int != IntTraits< T >::minInt )
{
SafeInt< T, E > tmp( m_int );
m_int--;
return tmp;
}
E::SafeIntOnOverflow();
}
// One's complement
// Note - this operator will normally change size to an int
// cast in return improves perf and maintains type
SafeInt< T, E > operator ~() const throw() { return SafeInt< T, E >( (T)~m_int ); }
// Binary operators
//
// arithmetic binary operators
// % modulus
// * multiplication
// / division
// + addition
// - subtraction
//
// For each of the arithmetic operators, you will need to
// use them as follows:
//
// SafeInt<char> c = 2;
// SafeInt<int> i = 3;
//
// SafeInt<int> i2 = i op (char)c;
// OR
// SafeInt<char> i2 = (int)i op c;
//
// The base problem is that if the lhs and rhs inputs are different SafeInt types
// it is not possible in this implementation to determine what type of SafeInt
// should be returned. You have to let the class know which of the two inputs
// need to be the return type by forcing the other value to the base integer type.
//
// Note - as per feedback from Scott Meyers, I'm exploring how to get around this.
// 3.0 update - I'm still thinking about this. It can be done with template metaprogramming,
// but it is tricky, and there's a perf vs. correctness tradeoff where the right answer
// is situational.
//
// The case of:
//
// SafeInt< T, E > i, j, k;
// i = j op k;
//
// works just fine and no unboxing is needed because the return type is not ambiguous.
// Modulus
// Modulus has some convenient properties -
// first, the magnitude of the return can never be
// larger than the lhs operand, and it must be the same sign
// as well. It does, however, suffer from the same promotion
// problems as comparisons, division and other operations
template < typename U >
SafeInt< T, E > operator %( U rhs ) const
{
T result;
ModulusHelper< T, U, ValidComparison< T, U >::method >::template ModulusThrow< E >( m_int, rhs, result );
return SafeInt< T, E >( result );
}
SafeInt< T, E > operator %( SafeInt< T, E > rhs ) const
{
T result;
ModulusHelper< T, T, ValidComparison< T, T >::method >::template ModulusThrow< E >( m_int, rhs, result );
return SafeInt< T, E >( result );
}
// Modulus assignment
template < typename U >
SafeInt< T, E >& operator %=( U rhs )
{
ModulusHelper< T, U, ValidComparison< T, U >::method >::template ModulusThrow< E >( m_int, rhs, m_int );
return *this;
}
template < typename U >
SafeInt< T, E >& operator %=( SafeInt< U, E > rhs )
{
ModulusHelper< T, U, ValidComparison< T, U >::method >::template ModulusThrow< E >( m_int, (U)rhs, m_int );
return *this;
}
// Multiplication
template < typename U >
SafeInt< T, E > operator *( U rhs ) const
{
T ret( 0 );
MultiplicationHelper< T, U, MultiplicationMethod< T, U >::method >::template MultiplyThrow< E >( m_int, rhs, ret );
return SafeInt< T, E >( ret );
}
SafeInt< T, E > operator *( SafeInt< T, E > rhs ) const
{
T ret( 0 );
MultiplicationHelper< T, T, MultiplicationMethod< T, T >::method >::template MultiplyThrow< E >( m_int, (T)rhs, ret );
return SafeInt< T, E >( ret );
}
// Multiplication assignment
SafeInt< T, E >& operator *=( SafeInt< T, E > rhs )
{
MultiplicationHelper< T, T, MultiplicationMethod< T, T >::method >::template MultiplyThrow< E >( m_int, (T)rhs, m_int );
return *this;
}
template < typename U >
SafeInt< T, E >& operator *=( U rhs )
{
MultiplicationHelper< T, U, MultiplicationMethod< T, U >::method >::template MultiplyThrow< E >( m_int, rhs, m_int );
return *this;
}
template < typename U >
SafeInt< T, E >& operator *=( SafeInt< U, E > rhs )
{
MultiplicationHelper< T, U, MultiplicationMethod< T, U >::method >::template MultiplyThrow< E >( m_int, rhs.Ref(), m_int );
return *this;
}
// Division
template < typename U >
SafeInt< T, E > operator /( U rhs ) const
{
T ret( 0 );
DivisionHelper< T, U, DivisionMethod< T, U >::method >::template DivideThrow< E >( m_int, rhs, ret );
return SafeInt< T, E >( ret );
}
SafeInt< T, E > operator /( SafeInt< T, E > rhs ) const
{
T ret( 0 );
DivisionHelper< T, T, DivisionMethod< T, T >::method >::template DivideThrow< E >( m_int, (T)rhs, ret );
return SafeInt< T, E >( ret );
}
// Division assignment
SafeInt< T, E >& operator /=( SafeInt< T, E > i )
{
DivisionHelper< T, T, DivisionMethod< T, T >::method >::template DivideThrow< E >( m_int, (T)i, m_int );
return *this;
}
template < typename U > SafeInt< T, E >& operator /=( U i )
{
DivisionHelper< T, U, DivisionMethod< T, U >::method >::template DivideThrow< E >( m_int, i, m_int );
return *this;
}
template < typename U > SafeInt< T, E >& operator /=( SafeInt< U, E > i )
{
DivisionHelper< T, U, DivisionMethod< T, U >::method >::template DivideThrow< E >( m_int, (U)i, m_int );
return *this;
}
// For addition and subtraction
// Addition
SafeInt< T, E > operator +( SafeInt< T, E > rhs ) const
{
T ret( 0 );
AdditionHelper< T, T, AdditionMethod< T, T >::method >::template AdditionThrow< E >( m_int, (T)rhs, ret );
return SafeInt< T, E >( ret );
}
template < typename U >
SafeInt< T, E > operator +( U rhs ) const
{
T ret( 0 );
AdditionHelper< T, U, AdditionMethod< T, U >::method >::template AdditionThrow< E >( m_int, rhs, ret );
return SafeInt< T, E >( ret );
}
//addition assignment
SafeInt< T, E >& operator +=( SafeInt< T, E > rhs )
{
AdditionHelper< T, T, AdditionMethod< T, T >::method >::template AdditionThrow< E >( m_int, (T)rhs, m_int );
return *this;
}
template < typename U >
SafeInt< T, E >& operator +=( U rhs )
{
AdditionHelper< T, U, AdditionMethod< T, U >::method >::template AdditionThrow< E >( m_int, rhs, m_int );
return *this;
}
template < typename U >
SafeInt< T, E >& operator +=( SafeInt< U, E > rhs )
{
AdditionHelper< T, U, AdditionMethod< T, U >::method >::template AdditionThrow< E >( m_int, (U)rhs, m_int );
return *this;
}
// Subtraction
template < typename U >
SafeInt< T, E > operator -( U rhs ) const
{
T ret( 0 );
SubtractionHelper< T, U, SubtractionMethod< T, U >::method >::template SubtractThrow< E >( m_int, rhs, ret );
return SafeInt< T, E >( ret );
}
SafeInt< T, E > operator -(SafeInt< T, E > rhs) const
{
T ret( 0 );
SubtractionHelper< T, T, SubtractionMethod< T, T >::method >::template SubtractThrow< E >( m_int, (T)rhs, ret );
return SafeInt< T, E >( ret );
}
// Subtraction assignment
SafeInt< T, E >& operator -=( SafeInt< T, E > rhs )
{
SubtractionHelper< T, T, SubtractionMethod< T, T >::method >::template SubtractThrow< E >( m_int, (T)rhs, m_int );
return *this;
}
template < typename U >
SafeInt< T, E >& operator -=( U rhs )
{
SubtractionHelper< T, U, SubtractionMethod< T, U >::method >::template SubtractThrow< E >( m_int, rhs, m_int );
return *this;
}
template < typename U >
SafeInt< T, E >& operator -=( SafeInt< U, E > rhs )
{
SubtractionHelper< T, U, SubtractionMethod< T, U >::method >::template SubtractThrow< E >( m_int, (U)rhs, m_int );
return *this;
}
// Comparison operators
// Additional overloads defined outside the class
// to allow for cases where the SafeInt is the rhs value
// Less than
template < typename U >
bool operator <( U rhs ) const throw()
{
return GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( rhs, m_int );
}
bool operator <( SafeInt< T, E > rhs ) const throw()
{
return m_int < (T)rhs;
}
// Greater than or eq.
template < typename U >
bool operator >=( U rhs ) const throw()
{
return !GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( rhs, m_int );
}
bool operator >=( SafeInt< T, E > rhs ) const throw()
{
return m_int >= (T)rhs;
}
// Greater than
template < typename U >
bool operator >( U rhs ) const throw()
{
return GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( m_int, rhs );
}
bool operator >( SafeInt< T, E > rhs ) const throw()
{
return m_int > (T)rhs;
}
// Less than or eq.
template < typename U >
bool operator <=( U rhs ) const throw()
{
return !GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( m_int, rhs );
}
bool operator <=( SafeInt< T, E > rhs ) const throw()
{
return m_int <= (T)rhs;
}
// Equality
template < typename U >
bool operator ==( U rhs ) const throw()
{
return EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( m_int, rhs );
}
// Need an explicit override for type bool
bool operator ==( bool rhs ) const throw()
{
return ( m_int == 0 ? false : true ) == rhs;
}
bool operator ==( SafeInt< T, E > rhs ) const throw() { return m_int == (T)rhs; }
// != operators
template < typename U >
bool operator !=( U rhs ) const throw()
{
return !EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( m_int, rhs );
}
bool operator !=( bool b ) const throw()
{
return ( m_int == 0 ? false : true ) != b;
}
bool operator !=( SafeInt< T, E > rhs ) const throw() { return m_int != (T)rhs; }
// Shift operators
// Note - shift operators ALWAYS return the same type as the lhs
// specific version for SafeInt< T, E > not needed -
// code path is exactly the same as for SafeInt< U, E > as rhs
// Left shift
// Also, shifting > bitcount is undefined - trap in debug
#ifdef SAFEINT_DISABLE_SHIFT_ASSERT
#define ShiftAssert(x)
#else
#define ShiftAssert(x) assert(x)
#endif
template < typename U >
SafeInt< T, E > operator <<( U bits ) const throw()
{
ShiftAssert( !IntTraits< U >::isSigned || bits >= 0 );
ShiftAssert( bits < (int)IntTraits< T >::bitCount );
return SafeInt< T, E >( (T)( m_int << bits ) );
}
template < typename U >
SafeInt< T, E > operator <<( SafeInt< U, E > bits ) const throw()
{
ShiftAssert( !IntTraits< U >::isSigned || (U)bits >= 0 );
ShiftAssert( (U)bits < (int)IntTraits< T >::bitCount );
return SafeInt< T, E >( (T)( m_int << (U)bits ) );
}
// Left shift assignment
template < typename U >
SafeInt< T, E >& operator <<=( U bits ) throw()
{
ShiftAssert( !IntTraits< U >::isSigned || bits >= 0 );
ShiftAssert( bits < (int)IntTraits< T >::bitCount );
m_int <<= bits;
return *this;
}
template < typename U >
SafeInt< T, E >& operator <<=( SafeInt< U, E > bits ) throw()
{
ShiftAssert( !IntTraits< U >::isSigned || (U)bits >= 0 );
ShiftAssert( (U)bits < (int)IntTraits< T >::bitCount );
m_int <<= (U)bits;
return *this;
}
// Right shift
template < typename U >
SafeInt< T, E > operator >>( U bits ) const throw()
{
ShiftAssert( !IntTraits< U >::isSigned || bits >= 0 );
ShiftAssert( bits < (int)IntTraits< T >::bitCount );
return SafeInt< T, E >( (T)( m_int >> bits ) );
}
template < typename U >
SafeInt< T, E > operator >>( SafeInt< U, E > bits ) const throw()
{
ShiftAssert( !IntTraits< U >::isSigned || (U)bits >= 0 );
ShiftAssert( bits < (int)IntTraits< T >::bitCount );
return SafeInt< T, E >( (T)(m_int >> (U)bits) );
}
// Right shift assignment
template < typename U >
SafeInt< T, E >& operator >>=( U bits ) throw()
{
ShiftAssert( !IntTraits< U >::isSigned || bits >= 0 );
ShiftAssert( bits < (int)IntTraits< T >::bitCount );
m_int >>= bits;
return *this;
}
template < typename U >
SafeInt< T, E >& operator >>=( SafeInt< U, E > bits ) throw()
{
ShiftAssert( !IntTraits< U >::isSigned || (U)bits >= 0 );
ShiftAssert( (U)bits < (int)IntTraits< T >::bitCount );
m_int >>= (U)bits;
return *this;
}
// Bitwise operators
// This only makes sense if we're dealing with the same type and size
// demand a type T, or something that fits into a type T
// Bitwise &
SafeInt< T, E > operator &( SafeInt< T, E > rhs ) const throw()
{
return SafeInt< T, E >( m_int & (T)rhs );
}
template < typename U >
SafeInt< T, E > operator &( U rhs ) const throw()
{
// we want to avoid setting bits by surprise
// consider the case of lhs = int, value = 0xffffffff
// rhs = char, value = 0xff
//
// programmer intent is to get only the lower 8 bits
// normal behavior is to upcast both sides to an int
// which then sign extends rhs, setting all the bits
// If you land in the assert, this is because the bitwise operator
// was causing unexpected behavior. Fix is to properly cast your inputs
// so that it works like you meant, not unexpectedly
return SafeInt< T, E >( BinaryAndHelper< T, U, BinaryMethod< T, U >::method >::And( m_int, rhs ) );
}
// Bitwise & assignment
SafeInt< T, E >& operator &=( SafeInt< T, E > rhs ) throw()
{
m_int &= (T)rhs;
return *this;
}
template < typename U >
SafeInt< T, E >& operator &=( U rhs ) throw()
{
m_int = BinaryAndHelper< T, U, BinaryMethod< T, U >::method >::And( m_int, rhs );
return *this;
}
template < typename U >
SafeInt< T, E >& operator &=( SafeInt< U, E > rhs ) throw()
{
m_int = BinaryAndHelper< T, U, BinaryMethod< T, U >::method >::And( m_int, (U)rhs );
return *this;
}
// XOR
SafeInt< T, E > operator ^( SafeInt< T, E > rhs ) const throw()
{
return SafeInt< T, E >( (T)( m_int ^ (T)rhs ) );
}
template < typename U >
SafeInt< T, E > operator ^( U rhs ) const throw()
{
// If you land in the assert, this is because the bitwise operator
// was causing unexpected behavior. Fix is to properly cast your inputs
// so that it works like you meant, not unexpectedly
return SafeInt< T, E >( BinaryXorHelper< T, U, BinaryMethod< T, U >::method >::Xor( m_int, rhs ) );
}
// XOR assignment
SafeInt< T, E >& operator ^=( SafeInt< T, E > rhs ) throw()
{
m_int ^= (T)rhs;
return *this;
}
template < typename U >
SafeInt< T, E >& operator ^=( U rhs ) throw()
{
m_int = BinaryXorHelper< T, U, BinaryMethod< T, U >::method >::Xor( m_int, rhs );
return *this;
}
template < typename U >
SafeInt< T, E >& operator ^=( SafeInt< U, E > rhs ) throw()
{
m_int = BinaryXorHelper< T, U, BinaryMethod< T, U >::method >::Xor( m_int, (U)rhs );
return *this;
}
// bitwise OR
SafeInt< T, E > operator |( SafeInt< T, E > rhs ) const throw()
{
return SafeInt< T, E >( (T)( m_int | (T)rhs ) );
}
template < typename U >
SafeInt< T, E > operator |( U rhs ) const throw()
{
return SafeInt< T, E >( BinaryOrHelper< T, U, BinaryMethod< T, U >::method >::Or( m_int, rhs ) );
}
// bitwise OR assignment
SafeInt< T, E >& operator |=( SafeInt< T, E > rhs ) throw()
{
m_int |= (T)rhs;
return *this;
}
template < typename U >
SafeInt< T, E >& operator |=( U rhs ) throw()
{
m_int = BinaryOrHelper< T, U, BinaryMethod< T, U >::method >::Or( m_int, rhs );
return *this;
}
template < typename U >
SafeInt< T, E >& operator |=( SafeInt< U, E > rhs ) throw()
{
m_int = BinaryOrHelper< T, U, BinaryMethod< T, U >::method >::Or( m_int, (U)rhs );
return *this;
}
// Miscellaneous helper functions
SafeInt< T, E > Min( SafeInt< T, E > test, SafeInt< T, E > floor = IntTraits< T >::minInt ) const throw()
{
T tmp = test < m_int ? (T)test : m_int;
return tmp < floor ? (T)floor : tmp;
}
SafeInt< T, E > Max( SafeInt< T, E > test, SafeInt< T, E > upper = IntTraits< T >::maxInt ) const throw()
{
T tmp = test > m_int ? (T)test : m_int;
return tmp > upper ? (T)upper : tmp;
}
void Swap( SafeInt< T, E >& with ) throw()
{
T temp( m_int );
m_int = with.m_int;
with.m_int = temp;
}
static SafeInt< T, E > SafeAtoI( const char* input )
{
return SafeTtoI( input );
}
static SafeInt< T, E > SafeWtoI( const wchar_t* input )
{
return SafeTtoI( input );
}
enum alignBits
{
align2 = 1,
align4 = 2,
align8 = 3,
align16 = 4,
align32 = 5,
align64 = 6,
align128 = 7,
align256 = 8
};
template < alignBits bits >
const SafeInt< T, E >& Align()
{
// Zero is always aligned
if( m_int == 0 )
return *this;
// We don't support aligning negative numbers at this time
// Can't align unsigned numbers on bitCount (e.g., 8 bits = 256, unsigned char max = 255)
// or signed numbers on bitCount-1 (e.g., 7 bits = 128, signed char max = 127).
// Also makes no sense to try to align on negative or no bits.
ShiftAssert( ( ( IntTraits<T>::isSigned && bits < (int)IntTraits< T >::bitCount - 1 )
|| ( !IntTraits<T>::isSigned && bits < (int)IntTraits< T >::bitCount ) ) &&
bits >= 0 && ( !IntTraits<T>::isSigned || m_int > 0 ) );
const T AlignValue = ( (T)1 << bits ) - 1;
m_int = ( m_int + AlignValue ) & ~AlignValue;
if( m_int <= 0 )
E::SafeIntOnOverflow();
return *this;
}
// Commonly needed alignments:
const SafeInt< T, E >& Align2() { return Align< align2 >(); }
const SafeInt< T, E >& Align4() { return Align< align4 >(); }
const SafeInt< T, E >& Align8() { return Align< align8 >(); }
const SafeInt< T, E >& Align16() { return Align< align16 >(); }
const SafeInt< T, E >& Align32() { return Align< align32 >(); }
const SafeInt< T, E >& Align64() { return Align< align64 >(); }
private:
// This is almost certainly not the best optimized version of atoi,
// but it does not display a typical bug where it isn't possible to set MinInt
// and it won't allow you to overflow your integer.
// This is here because it is useful, and it is an example of what
// can be done easily with SafeInt.
template < typename U >
static SafeInt< T, E > SafeTtoI( U* input )
{
U* tmp = input;
SafeInt< T, E > s;
bool negative = false;
// Bad input, or empty string
if( input == NULL || input[0] == 0 )
E::SafeIntOnOverflow();
switch( *tmp )
{
case '-':
tmp++;
negative = true;
break;
case '+':
tmp++;
break;
}
while( *tmp != 0 )
{
if( *tmp < '0' || *tmp > '9' )
break;
if( (T)s != 0 )
s *= (T)10;
if( !negative )
s += (T)( *tmp - '0' );
else
s -= (T)( *tmp - '0' );
tmp++;
}
return s;
}
T m_int;
};
// Helper function used to subtract pointers.
// Used to squelch warnings
template <typename P>
SafeInt<ptrdiff_t, SafeIntDefaultExceptionHandler> SafePtrDiff(const P* p1, const P* p2)
{
return SafeInt<ptrdiff_t, SafeIntDefaultExceptionHandler>( p1 - p2 );
}
// Externally defined functions for the case of U op SafeInt< T, E >
template < typename T, typename U, typename E >
bool operator <( U lhs, SafeInt< T, E > rhs ) throw()
{
return GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( (T)rhs, lhs );
}
template < typename T, typename U, typename E >
bool operator <( SafeInt< U, E > lhs, SafeInt< T, E > rhs ) throw()
{
return GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( (T)rhs, (U)lhs );
}
// Greater than
template < typename T, typename U, typename E >
bool operator >( U lhs, SafeInt< T, E > rhs ) throw()
{
return GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( lhs, (T)rhs );
}
template < typename T, typename U, typename E >
bool operator >( SafeInt< T, E > lhs, SafeInt< U, E > rhs ) throw()
{
return GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( (T)lhs, (U)rhs );
}
// Greater than or equal
template < typename T, typename U, typename E >
bool operator >=( U lhs, SafeInt< T, E > rhs ) throw()
{
return !GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( (T)rhs, lhs );
}
template < typename T, typename U, typename E >
bool operator >=( SafeInt< T, E > lhs, SafeInt< U, E > rhs ) throw()
{
return !GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( (U)rhs, (T)lhs );
}
// Less than or equal
template < typename T, typename U, typename E >
bool operator <=( U lhs, SafeInt< T, E > rhs ) throw()
{
return !GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( lhs, (T)rhs );
}
template < typename T, typename U, typename E >
bool operator <=( SafeInt< T, E > lhs, SafeInt< U, E > rhs ) throw()
{
return !GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( (T)lhs, (U)rhs );
}
// equality
// explicit overload for bool
template < typename T, typename E >
bool operator ==( bool lhs, SafeInt< T, E > rhs ) throw()
{
return lhs == ( (T)rhs == 0 ? false : true );
}
template < typename T, typename U, typename E >
bool operator ==( U lhs, SafeInt< T, E > rhs ) throw()
{
return EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals((T)rhs, lhs);
}
template < typename T, typename U, typename E >
bool operator ==( SafeInt< T, E > lhs, SafeInt< U, E > rhs ) throw()
{
return EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( (T)lhs, (U)rhs );
}
//not equals
template < typename T, typename U, typename E >
bool operator !=( U lhs, SafeInt< T, E > rhs ) throw()
{
return !EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( rhs, lhs );
}
template < typename T, typename E >
bool operator !=( bool lhs, SafeInt< T, E > rhs ) throw()
{
return ( (T)rhs == 0 ? false : true ) != lhs;
}
template < typename T, typename U, typename E >
bool operator !=( SafeInt< T, E > lhs, SafeInt< U, E > rhs ) throw()
{
return !EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( lhs, rhs );
}
// Modulus
template < typename T, typename U, typename E >
SafeInt< T, E > operator %( U lhs, SafeInt< T, E > rhs )
{
// Value of return depends on sign of lhs
// This one may not be safe - bounds check in constructor
// if lhs is negative and rhs is unsigned, this will throw an exception.
// Fast-track the simple case
// same size and same sign
if( sizeof(T) == sizeof(U) &&
(bool)IntTraits< T >::isSigned == (bool)IntTraits< U >::isSigned )
{
if( rhs != 0 )
{
if( IntTraits< T >::isSigned && (T)rhs == -1 )
return 0;
return SafeInt< T, E >( (T)( lhs % (T)rhs ) );
}
E::SafeIntOnDivZero();
}
return SafeInt< T, E >( ( SafeInt< U, E >( lhs ) % (T)rhs ) );
}
// Multiplication
template < typename T, typename U, typename E >
SafeInt< T, E > operator *( U lhs, SafeInt< T, E > rhs )
{
T ret( 0 );
MultiplicationHelper< T, U, MultiplicationMethod< T, U >::method >::template MultiplyThrow< E >( (T)rhs, lhs, ret );
return SafeInt< T, E >(ret);
}
// Division
template < typename T, typename U, typename E > SafeInt< T, E > operator /( U lhs, SafeInt< T, E > rhs )
{
// Corner case - has to be handled seperately
if( (int)DivisionMethod< U, T >::method == (int)DivisionState_UnsignedSigned )
{
if( (T)rhs > 0 )
return SafeInt< T, E >( lhs/(T)rhs );
// Now rhs is either negative, or zero
if( (T)rhs != 0 )
{
if( sizeof( U ) >= 4 && sizeof( T ) <= sizeof( U ) )
{
// Problem case - normal casting behavior changes meaning
// flip rhs to positive
// any operator casts now do the right thing
U tmp;
if( sizeof(T) == 4 )
tmp = lhs/(U)(unsigned __int32)( -(T)rhs );
else
tmp = lhs/(U)( -(T)rhs );
if( tmp <= IntTraits< T >::maxInt )
return SafeInt< T, E >( -( (T)tmp ) );
// Corner case
#pragma warning(push)
#pragma warning(disable:4307)
// Note - this warning happens because we're not using partial
// template specialization in this case. For any real cases where
// this block isn't optimized out, the warning won't be present.
T maxT = IntTraits< T >::maxInt;
if( tmp == (U)maxT + 1 )
{
T minT = IntTraits< T >::minInt;
return SafeInt< T, E >( minT );
}
#pragma warning(pop)
E::SafeIntOnOverflow();
}
return SafeInt< T, E >(lhs/(T)rhs);
}
E::SafeIntOnDivZero();
} // method == DivisionState_UnsignedSigned
if( SafeIntCompare< T, U >::isBothSigned )
{
if( lhs == IntTraits< U >::minInt && (T)rhs == -1 )
{
// corner case of a corner case - lhs = min int, rhs = -1,
// but rhs is the return type, so in essence, we can return -lhs
// if rhs is a larger type than lhs
if( sizeof( U ) < sizeof( T ) )
return SafeInt< T, E >( (T)( -(T)IntTraits< U >::minInt ) );
// If rhs is smaller or the same size int, then -minInt won't work
E::SafeIntOnOverflow();
}
}
// Otherwise normal logic works with addition of bounds check when casting from U->T
U ret;
DivisionHelper< U, T, DivisionMethod< U, T >::method >::template DivideThrow< E >( lhs, (T)rhs, ret );
return SafeInt< T, E >( ret );
}
// Addition
template < typename T, typename U, typename E >
SafeInt< T, E > operator +( U lhs, SafeInt< T, E > rhs )
{
T ret( 0 );
AdditionHelper< T, U, AdditionMethod< T, U >::method >::template AdditionThrow< E >( (T)rhs, lhs, ret );
return SafeInt< T, E >( ret );
}
// Subtraction
template < typename T, typename U, typename E >
SafeInt< T, E > operator -( U lhs, SafeInt< T, E > rhs )
{
T ret( 0 );
SubtractionHelper< U, T, SubtractionMethod2< U, T >::method >::template SubtractThrow< E >( lhs, rhs.Ref(), ret );
return SafeInt< T, E >( ret );
}
// Overrides designed to deal with cases where a SafeInt is assigned out
// to a normal int - this at least makes the last operation safe
// +=
template < typename T, typename U, typename E >
T& operator +=( T& lhs, SafeInt< U, E > rhs )
{
T ret( 0 );
AdditionHelper< T, U, AdditionMethod< T, U >::method >::template AdditionThrow< E >( lhs, (U)rhs, ret );
lhs = ret;
return lhs;
}
template < typename T, typename U, typename E >
T& operator -=( T& lhs, SafeInt< U, E > rhs )
{
T ret( 0 );
SubtractionHelper< T, U, SubtractionMethod< T, U >::method >::template SubtractThrow< E >( lhs, (U)rhs, ret );
lhs = ret;
return lhs;
}
template < typename T, typename U, typename E >
T& operator *=( T& lhs, SafeInt< U, E > rhs )
{
T ret( 0 );
MultiplicationHelper< T, U, MultiplicationMethod< T, U >::method >::template MultiplyThrow< E >( lhs, (U)rhs, ret );
lhs = ret;
return lhs;
}
template < typename T, typename U, typename E >
T& operator /=( T& lhs, SafeInt< U, E > rhs )
{
T ret( 0 );
DivisionHelper< T, U, DivisionMethod< T, U >::method >::template DivideThrow< E >( lhs, (U)rhs, ret );
lhs = ret;
return lhs;
}
template < typename T, typename U, typename E >
T& operator %=( T& lhs, SafeInt< U, E > rhs )
{
T ret( 0 );
ModulusHelper< T, U, ValidComparison< T, U >::method >::template ModulusThrow< E >( lhs, (U)rhs, ret );
lhs = ret;
return lhs;
}
template < typename T, typename U, typename E >
T& operator &=( T& lhs, SafeInt< U, E > rhs ) throw()
{
lhs = BinaryAndHelper< T, U, BinaryMethod< T, U >::method >::And( lhs, (U)rhs );
return lhs;
}
template < typename T, typename U, typename E >
T& operator ^=( T& lhs, SafeInt< U, E > rhs ) throw()
{
lhs = BinaryXorHelper< T, U, BinaryMethod< T, U >::method >::Xor( lhs, (U)rhs );
return lhs;
}
template < typename T, typename U, typename E >
T& operator |=( T& lhs, SafeInt< U, E > rhs ) throw()
{
lhs = BinaryOrHelper< T, U, BinaryMethod< T, U >::method >::Or( lhs, (U)rhs );
return lhs;
}
template < typename T, typename U, typename E >
T& operator <<=( T& lhs, SafeInt< U, E > rhs ) throw()
{
lhs = (T)( SafeInt< T, E >( lhs ) << (U)rhs );
return lhs;
}
template < typename T, typename U, typename E >
T& operator >>=( T& lhs, SafeInt< U, E > rhs ) throw()
{
lhs = (T)( SafeInt< T, E >( lhs ) >> (U)rhs );
return lhs;
}
// Specific pointer overrides
// Note - this function makes no attempt to ensure
// that the resulting pointer is still in the buffer, only
// that no int overflows happened on the way to getting the new pointer
template < typename T, typename U, typename E >
T*& operator +=( T*& lhs, SafeInt< U, E > rhs )
{
// Cast the pointer to a number so we can do arithmetic
SafeInt< uintptr_t, E > ptr_val = reinterpret_cast< uintptr_t >( lhs );
// Check first that rhs is valid for the type of ptrdiff_t
// and that multiplying by sizeof( T ) doesn't overflow a ptrdiff_t
// Next, we need to add 2 SafeInts of different types, so unbox the ptr_diff
// Finally, cast the number back to a pointer of the correct type
lhs = reinterpret_cast< T* >( (uintptr_t)( ptr_val + (ptrdiff_t)( SafeInt< ptrdiff_t, E >( rhs ) * sizeof( T ) ) ) );
return lhs;
}
template < typename T, typename U, typename E >
T*& operator -=( T*& lhs, SafeInt< U, E > rhs )
{
// Cast the pointer to a number so we can do arithmetic
SafeInt< size_t, E > ptr_val = reinterpret_cast< uintptr_t >( lhs );
// See above for comments
lhs = reinterpret_cast< T* >( (uintptr_t)( ptr_val - (ptrdiff_t)( SafeInt< ptrdiff_t, E >( rhs ) * sizeof( T ) ) ) );
return lhs;
}
template < typename T, typename U, typename E >
T*& operator *=( T*& lhs, SafeInt< U, E > rhs )
{
// This operator explicitly not supported
C_ASSERT( sizeof(T) == 0 );
return (lhs = NULL);
}
template < typename T, typename U, typename E >
T*& operator /=( T*& lhs, SafeInt< U, E > rhs )
{
// This operator explicitly not supported
C_ASSERT( sizeof(T) == 0 );
return (lhs = NULL);
}
template < typename T, typename U, typename E >
T*& operator %=( T*& lhs, SafeInt< U, E > rhs )
{
// This operator explicitly not supported
C_ASSERT( sizeof(T) == 0 );
return (lhs = NULL);
}
template < typename T, typename U, typename E >
T*& operator &=( T*& lhs, SafeInt< U, E > rhs )
{
// This operator explicitly not supported
C_ASSERT( sizeof(T) == 0 );
return (lhs = NULL);
}
template < typename T, typename U, typename E >
T*& operator ^=( T*& lhs, SafeInt< U, E > rhs )
{
// This operator explicitly not supported
C_ASSERT( sizeof(T) == 0 );
return (lhs = NULL);
}
template < typename T, typename U, typename E >
T*& operator |=( T*& lhs, SafeInt< U, E > rhs )
{
// This operator explicitly not supported
C_ASSERT( sizeof(T) == 0 );
return (lhs = NULL);
}
template < typename T, typename U, typename E >
T*& operator <<=( T*& lhs, SafeInt< U, E > rhs )
{
// This operator explicitly not supported
C_ASSERT( sizeof(T) == 0 );
return (lhs = NULL);
}
template < typename T, typename U, typename E >
T*& operator >>=( T*& lhs, SafeInt< U, E > rhs )
{
// This operator explicitly not supported
C_ASSERT( sizeof(T) == 0 );
return (lhs = NULL);
}
// Shift operators
// NOTE - shift operators always return the type of the lhs argument
// Left shift
template < typename T, typename U, typename E >
SafeInt< U, E > operator <<( U lhs, SafeInt< T, E > bits ) throw()
{
ShiftAssert( !IntTraits< T >::isSigned || (T)bits >= 0 );
ShiftAssert( (T)bits < (int)IntTraits< U >::bitCount );
return SafeInt< U, E >( (U)( lhs << (T)bits ) );
}
// Right shift
template < typename T, typename U, typename E >
SafeInt< U, E > operator >>( U lhs, SafeInt< T, E > bits ) throw()
{
ShiftAssert( !IntTraits< T >::isSigned || (T)bits >= 0 );
ShiftAssert( (T)bits < (int)IntTraits< U >::bitCount );
return SafeInt< U, E >( (U)( lhs >> (T)bits ) );
}
// Bitwise operators
// This only makes sense if we're dealing with the same type and size
// demand a type T, or something that fits into a type T.
// Bitwise &
template < typename T, typename U, typename E >
SafeInt< T, E > operator &( U lhs, SafeInt< T, E > rhs ) throw()
{
return SafeInt< T, E >( BinaryAndHelper< T, U, BinaryMethod< T, U >::method >::And( (T)rhs, lhs ) );
}
// Bitwise XOR
template < typename T, typename U, typename E >
SafeInt< T, E > operator ^( U lhs, SafeInt< T, E > rhs ) throw()
{
return SafeInt< T, E >(BinaryXorHelper< T, U, BinaryMethod< T, U >::method >::Xor( (T)rhs, lhs ) );
}
// Bitwise OR
template < typename T, typename U, typename E >
SafeInt< T, E > operator |( U lhs, SafeInt< T, E > rhs ) throw()
{
return SafeInt< T, E >( BinaryOrHelper< T, U, BinaryMethod< T, U >::method >::Or( (T)rhs, lhs ) );
}
#pragma warning(pop)
#endif //SAFEINT_HPP
|
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: layerexport.cxx,v $
*
* $Revision: 1.30 $
*
* last change: $Author: rt $ $Date: 2005-09-09 14:12:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <stdio.h>
#ifndef _XMLOFF_FORMS_LAYEREXPORT_HXX_
#include "layerexport.hxx"
#endif
#ifndef _XMLOFF_FORMS_STRINGS_HXX_
#include "strings.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include "xmlprmap.hxx"
#endif
#ifndef _XMLOFF_PROPERTYHANDLERFACTORY_HXX
#include "prhdlfac.hxx"
#endif
#ifndef _XMLOFF_ELEMENTEXPORT_HXX_
#include "elementexport.hxx"
#endif
#ifndef _XMLOFF_FAMILIES_HXX_
#include "families.hxx"
#endif
#ifndef _XMLOFF_CONTEXTID_HXX_
#include "contextid.hxx"
#endif
#ifndef _XMLOFF_FORMS_CONTROLPROPERTYHDL_HXX_
#include "controlpropertyhdl.hxx"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _XMLOFF_FORMS_CONTROLPROPERTYMAP_HXX_
#include "controlpropertymap.hxx"
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XFORMSSUPPLIER2_HPP_
#include <com/sun/star/form/XFormsSupplier2.hpp>
#endif
#ifndef _COM_SUN_STAR_XFORMS_XFORMSSUPPLIER_HPP_
#include <com/sun/star/xforms/XFormsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_FORMCOMPONENTTYPE_HPP_
#include <com/sun/star/form/FormComponentType.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_SCRIPT_XEVENTATTACHERMANAGER_HPP_
#include <com/sun/star/script/XEventAttacherManager.hpp>
#endif
#ifndef _XMLOFF_FORMS_EVENTEXPORT_HXX_
#include "eventexport.hxx"
#endif
#ifndef _XMLOFF_XMLEVENTEXPORT_HXX
#include "XMLEventExport.hxx"
#endif
#ifndef _XMLOFF_FORMS_FORMEVENTS_HXX_
#include "formevents.hxx"
#endif
#ifndef _XMLOFF_XMLNUMFE_HXX
#include "xmlnumfe.hxx"
#endif
#ifndef _XMLOFF_XFORMSEXPORT_HXX
#include "xformsexport.hxx"
#endif
/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif
/** === end UNO includes === **/
//.........................................................................
namespace xmloff
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::drawing;
using namespace ::com::sun::star::form;
using namespace ::com::sun::star::script;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::text;
typedef ::com::sun::star::xforms::XFormsSupplier XXFormsSupplier;
//=====================================================================
//= OFormLayerXMLExport_Impl
//=====================================================================
//---------------------------------------------------------------------
const ::rtl::OUString& OFormLayerXMLExport_Impl::getControlNumberStyleNamePrefix()
{
static const ::rtl::OUString s_sControlNumberStyleNamePrefix = ::rtl::OUString::createFromAscii("C");
return s_sControlNumberStyleNamePrefix;
}
//---------------------------------------------------------------------
OFormLayerXMLExport_Impl::OFormLayerXMLExport_Impl(SvXMLExport& _rContext)
:m_rContext(_rContext)
,m_pControlNumberStyles(NULL)
{
initializePropertyMaps();
// add our style family to the export context's style pool
m_xPropertyHandlerFactory = new OControlPropertyHandlerFactory();
::vos::ORef< XMLPropertySetMapper > xStylePropertiesMapper = new XMLPropertySetMapper( getControlStylePropertyMap(), m_xPropertyHandlerFactory.getBodyPtr() );
m_xExportMapper = new OFormExportPropertyMapper( xStylePropertiesMapper.getBodyPtr() );
// our style family
m_rContext.GetAutoStylePool()->AddFamily(
XML_STYLE_FAMILY_CONTROL_ID, token::GetXMLToken(token::XML_PARAGRAPH),
m_xExportMapper.getBodyPtr(),
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( XML_STYLE_FAMILY_CONTROL_PREFIX) )
);
// add our event translation table
m_rContext.GetEventExport().AddTranslationTable(g_pFormsEventTranslation);
clear();
}
//---------------------------------------------------------------------
sal_Bool OFormLayerXMLExport_Impl::impl_isFormPageContainingForms(const Reference< XDrawPage >& _rxDrawPage, Reference< XIndexAccess >& _rxForms)
{
Reference< XFormsSupplier2 > xFormsSupp(_rxDrawPage, UNO_QUERY);
OSL_ENSURE(xFormsSupp.is(), "OFormLayerXMLExport_Impl::impl_isFormPageContainingForms: invalid draw page (no XFormsSupplier)! Doin' nothing!");
if (!xFormsSupp.is())
return sal_False;
if ( !xFormsSupp->hasForms() )
// nothing to do at all
return sal_False;
_rxForms = Reference< XIndexAccess >(xFormsSupp->getForms(), UNO_QUERY);
Reference< XServiceInfo > xSI(_rxForms, UNO_QUERY); // order is important!
OSL_ENSURE(xSI.is(), "OFormLayerXMLExport_Impl::impl_isFormPageContainingForms: invalid collection (must not be NULL and must have a ServiceInfo)!");
if (!xSI.is())
return sal_False;
if (!xSI->supportsService(SERVICE_FORMSCOLLECTION))
{
OSL_ENSURE(sal_False, "OFormLayerXMLExport_Impl::impl_isFormPageContainingForms: invalid collection (is no com.sun.star.form.Forms)!");
// nothing to do
return sal_False;
}
return sal_True;
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportGridColumn(const Reference< XPropertySet >& _rxColumn,
const Sequence< ScriptEventDescriptor >& _rEvents)
{
// do the exporting
OColumnExport aExportImpl(*this, _rxColumn, _rEvents);
aExportImpl.doExport();
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportControl(const Reference< XPropertySet >& _rxControl,
const Sequence< ScriptEventDescriptor >& _rEvents)
{
// the list of the referring controls
::rtl::OUString sReferringControls;
ConstMapPropertySet2StringIterator aReferring = m_aCurrentPageReferring->second.find(_rxControl);
if (aReferring != m_aCurrentPageReferring->second.end())
sReferringControls = aReferring->second;
// the control id (should already have been created in examineForms)
::rtl::OUString sControlId;
ConstMapPropertySet2StringIterator aControlId = m_aCurrentPageIds->second.find(_rxControl);
OSL_ENSURE(aControlId != m_aCurrentPageIds->second.end(), "OFormLayerXMLExport_Impl::exportControl: could not find the control id!");
if (aControlId != m_aCurrentPageIds->second.end())
sControlId = aControlId->second;
// do the exporting
OControlExport aExportImpl(*this, _rxControl, sControlId, sReferringControls, _rEvents);
aExportImpl.doExport();
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportForm(const Reference< XPropertySet >& _rxProps,
const Sequence< ScriptEventDescriptor >& _rEvents)
{
OSL_ENSURE(_rxProps.is(), "OFormLayerXMLExport_Impl::exportForm: invalid property set!");
OFormExport aAttributeHandler(*this, _rxProps, _rEvents);
aAttributeHandler.doExport();
}
//---------------------------------------------------------------------
::vos::ORef< SvXMLExportPropertyMapper > OFormLayerXMLExport_Impl::getStylePropertyMapper()
{
return m_xExportMapper;
}
//---------------------------------------------------------------------
SvXMLExport& OFormLayerXMLExport_Impl::getGlobalContext()
{
return m_rContext;
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportCollectionElements(const Reference< XIndexAccess >& _rxCollection)
{
// step through all the elements of the collection
sal_Int32 nElements = _rxCollection->getCount();
Reference< XEventAttacherManager > xElementEventManager(_rxCollection, UNO_QUERY);
Sequence< ScriptEventDescriptor > aElementEvents;
Reference< XPropertySet > xCurrentProps;
Reference< XPropertySetInfo > xPropsInfo;
Reference< XIndexAccess > xCurrentContainer;
for (sal_Int32 i=0; i<nElements; ++i)
{
try
{
// extract the current element
::cppu::extractInterface(xCurrentProps, _rxCollection->getByIndex(i));
OSL_ENSURE(xCurrentProps.is(), "OFormLayerXMLExport_Impl::exportCollectionElements: invalid child element, skipping!");
if (!xCurrentProps.is())
continue;
// check if there is a ClassId property on the current element. If so, we assume it to be a control
xPropsInfo = xCurrentProps->getPropertySetInfo();
OSL_ENSURE(xPropsInfo.is(), "OFormLayerXMLExport_Impl::exportCollectionElements: no property set info!");
if (!xPropsInfo.is())
// without this, a lot of stuff in the export routines may fail
continue;
// if the element is part of a ignore list, we are not allowed to export it
if ( m_aIgnoreList.end() != m_aIgnoreList.find( xCurrentProps ) )
continue;
if (xElementEventManager.is())
aElementEvents = xElementEventManager->getScriptEvents(i);
if (xPropsInfo->hasPropertyByName(PROPERTY_COLUMNSERVICENAME))
{
exportGridColumn(xCurrentProps, aElementEvents);
}
else if (xPropsInfo->hasPropertyByName(PROPERTY_CLASSID))
{
exportControl(xCurrentProps, aElementEvents);
}
else
{
exportForm(xCurrentProps, aElementEvents);
}
}
catch(Exception&)
{
OSL_ENSURE(sal_False, "OFormLayerXMLExport_Impl::exportCollectionElements: caught an exception ... skipping the current element!");
continue;
}
}
}
//---------------------------------------------------------------------
::rtl::OUString OFormLayerXMLExport_Impl::getObjectStyleName( const Reference< XPropertySet >& _rxObject )
{
::rtl::OUString aObjectStyle;
MapPropertySet2String::const_iterator aObjectStylePos = m_aGridColumnStyles.find( _rxObject );
if ( m_aGridColumnStyles.end() != aObjectStylePos )
aObjectStyle = aObjectStylePos->second;
return aObjectStyle;
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::clear()
{
m_aControlIds.clear();
m_aReferringControls.clear();
m_aCurrentPageIds = m_aControlIds.end();
m_aCurrentPageReferring = m_aReferringControls.end();
m_aControlNumberFormats.clear();
m_aGridColumnStyles.clear();
m_aIgnoreList.clear();
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportControlNumberStyles()
{
if (m_pControlNumberStyles)
m_pControlNumberStyles->Export(sal_False);
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportAutoControlNumberStyles()
{
if ( m_pControlNumberStyles )
m_pControlNumberStyles->Export( sal_True );
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportAutoStyles()
{
m_rContext.GetAutoStylePool()->exportXML(
XML_STYLE_FAMILY_CONTROL_ID,
m_rContext.GetDocHandler(),
m_rContext.GetMM100UnitConverter(),
m_rContext.GetNamespaceMap()
);
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportForms(const Reference< XDrawPage >& _rxDrawPage)
{
// get the forms collection of the page
Reference< XIndexAccess > xCollectionIndex;
if (!impl_isFormPageContainingForms(_rxDrawPage, xCollectionIndex))
return;
#if OSL_DEBUG_LEVEL > 0
sal_Bool bPageIsKnown =
#endif
implMoveIterators(_rxDrawPage, sal_False);
OSL_ENSURE(bPageIsKnown, "OFormLayerXMLExport_Impl::exportForms: exporting a page which has not been examined!");
// export forms collection
exportCollectionElements(xCollectionIndex);
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportXForms() const
{
// export XForms models
::exportXForms( m_rContext );
}
//---------------------------------------------------------------------
bool OFormLayerXMLExport_Impl::pageContainsForms( const Reference< XDrawPage >& _rxDrawPage ) const
{
Reference< XFormsSupplier2 > xFormsSupp( _rxDrawPage, UNO_QUERY );
DBG_ASSERT( xFormsSupp.is(), "OFormLayerXMLExport_Impl::pageContainsForms: no XFormsSupplier2!" );
return xFormsSupp.is() && xFormsSupp->hasForms();
}
//---------------------------------------------------------------------
bool OFormLayerXMLExport_Impl::documentContainsXForms() const
{
Reference< XXFormsSupplier > xXFormSupp( m_rContext.GetModel(), UNO_QUERY );
Reference< XNameContainer > xForms;
if ( xXFormSupp.is() )
xForms = xXFormSupp->getXForms();
return xForms.is() && xForms->hasElements();
}
//---------------------------------------------------------------------
sal_Bool OFormLayerXMLExport_Impl::implMoveIterators(const Reference< XDrawPage >& _rxDrawPage, sal_Bool _bClear)
{
sal_Bool bKnownPage = sal_False;
// the one for the ids
m_aCurrentPageIds = m_aControlIds.find(_rxDrawPage);
if (m_aControlIds.end() == m_aCurrentPageIds)
{
m_aControlIds[_rxDrawPage] = MapPropertySet2String();
m_aCurrentPageIds = m_aControlIds.find(_rxDrawPage);
}
else
{
bKnownPage = sal_True;
if (_bClear && m_aCurrentPageIds->second.size())
m_aCurrentPageIds->second.clear();
}
// the one for the ids of the referring controls
m_aCurrentPageReferring = m_aReferringControls.find(_rxDrawPage);
if (m_aReferringControls.end() == m_aCurrentPageReferring)
{
m_aReferringControls[_rxDrawPage] = MapPropertySet2String();
m_aCurrentPageReferring = m_aReferringControls.find(_rxDrawPage);
}
else
{
bKnownPage = sal_True;
if (_bClear && m_aCurrentPageReferring->second.size())
m_aCurrentPageReferring->second.clear();
}
return bKnownPage;
}
//---------------------------------------------------------------------
sal_Bool OFormLayerXMLExport_Impl::seekPage(const Reference< XDrawPage >& _rxDrawPage)
{
sal_Bool bKnownPage = implMoveIterators( _rxDrawPage, sal_False );
if ( bKnownPage )
return sal_True;
// if the page is not yet know, this does not automatically mean that it has
// not been examined. Instead, examineForms returns silently and successfully
// if a page is a XFormsPageSupplier2, but does not have a forms collection
// (This behaviour of examineForms is a performance optimization, to not force
// the page to create a forms container just to see that it's empty.)
// So, in such a case, seekPage is considered to be successfull, too, though the
// page was not yet known
Reference< XFormsSupplier2 > xFormsSupp( _rxDrawPage, UNO_QUERY );
if ( xFormsSupp.is() && !xFormsSupp->hasForms() )
return sal_True;
// anything else means that the page has not been examined before, or it's no
// valid form page. Both cases are Bad (TM).
return sal_False;
}
//---------------------------------------------------------------------
::rtl::OUString OFormLayerXMLExport_Impl::getControlId(const Reference< XPropertySet >& _rxControl)
{
OSL_ENSURE(m_aCurrentPageIds != m_aControlIds.end(), "OFormLayerXMLExport_Impl::getControlId: invalid current page!");
OSL_ENSURE(m_aCurrentPageIds->second.end() != m_aCurrentPageIds->second.find(_rxControl),
"OFormLayerXMLExport_Impl::getControlId: can not find the control!");
return m_aCurrentPageIds->second[_rxControl];
}
//---------------------------------------------------------------------
::rtl::OUString OFormLayerXMLExport_Impl::getImmediateNumberStyle( const Reference< XPropertySet >& _rxObject )
{
::rtl::OUString sNumberStyle;
sal_Int32 nOwnFormatKey = implExamineControlNumberFormat( _rxObject );
if ( -1 != nOwnFormatKey )
sNumberStyle = getControlNumberStyleExport()->GetStyleName( nOwnFormatKey );
return sNumberStyle;
}
//---------------------------------------------------------------------
::rtl::OUString OFormLayerXMLExport_Impl::getControlNumberStyle( const Reference< XPropertySet >& _rxControl )
{
::rtl::OUString sNumberStyle;
ConstMapPropertySet2IntIterator aControlFormatPos = m_aControlNumberFormats.find(_rxControl);
if (m_aControlNumberFormats.end() != aControlFormatPos)
{
OSL_ENSURE(m_pControlNumberStyles, "OFormLayerXMLExport_Impl::getControlNumberStyle: have a control which has a format style, but no style exporter!");
sNumberStyle = getControlNumberStyleExport()->GetStyleName(aControlFormatPos->second);
}
// it's allowed to ask for a control which does not have format information.
// (This is for performance reasons)
return sNumberStyle;
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::examineForms(const Reference< XDrawPage >& _rxDrawPage)
{
// get the forms collection of the page
Reference< XIndexAccess > xCollectionIndex;
if (!impl_isFormPageContainingForms(_rxDrawPage, xCollectionIndex))
return;
// move the iterator which specify the currently handled page
#if OSL_DEBUG_LEVEL > 0
sal_Bool bPageIsKnown =
#endif
implMoveIterators(_rxDrawPage, sal_True);
OSL_ENSURE(!bPageIsKnown, "OFormLayerXMLExport_Impl::examineForms: examining a page twice!");
::std::stack< Reference< XIndexAccess > > aContainerHistory;
::std::stack< sal_Int32 > aIndexHistory;
Reference< XPropertySet > xCurrent;
Reference< XIndexAccess > xLoop = xCollectionIndex;
sal_Int32 nChildPos = 0;
do
{
if (nChildPos < xLoop->getCount())
{
::cppu::extractInterface(xCurrent, xLoop->getByIndex(nChildPos));
OSL_ENSURE(xCurrent.is(), "OFormLayerXMLExport_Impl::examineForms: invalid child object");
if (!xCurrent.is())
continue;
if (!checkExamineControl(xCurrent))
{
// step down
Reference< XIndexAccess > xNextContainer(xCurrent, UNO_QUERY);
OSL_ENSURE(xNextContainer.is(), "OFormLayerXMLExport_Impl::examineForms: what the heck is this ... no control, no container?");
aContainerHistory.push(xLoop);
aIndexHistory.push(nChildPos);
xLoop = xNextContainer;
nChildPos = -1; // will be incremented below
}
++nChildPos;
}
else
{
// step up
while ((nChildPos >= xLoop->getCount()) && aContainerHistory.size())
{
xLoop = aContainerHistory.top();
aContainerHistory.pop();
nChildPos = aIndexHistory.top();
aIndexHistory.pop();
++nChildPos;
}
if (nChildPos >= xLoop->getCount())
// exited the loop above because we have no history anymore (0 == aContainerHistory.size()),
// and on the current level there are no more children
// -> leave
break;
}
}
while (xLoop.is());
}
//---------------------------------------------------------------------
sal_Bool OFormLayerXMLExport_Impl::checkExamineControl(const Reference< XPropertySet >& _rxObject)
{
static const ::rtl::OUString sControlId(RTL_CONSTASCII_USTRINGPARAM("control"));
Reference< XPropertySetInfo > xCurrentInfo = _rxObject->getPropertySetInfo();
OSL_ENSURE(xCurrentInfo.is(), "OFormLayerXMLExport_Impl::checkExamineControl: no property set info");
sal_Bool bIsControl = xCurrentInfo->hasPropertyByName( PROPERTY_CLASSID );
if (bIsControl)
{
// ----------------------------------
// generate a new control id
// find a free id
::rtl::OUString sCurrentId = sControlId;
sCurrentId += ::rtl::OUString::valueOf((sal_Int32)(m_aCurrentPageIds->second.size() + 1));
#ifdef DBG_UTIL
// Check if the id is already used. It shouldn't, as we currently have no mechanism for removing entries
// from the map, so the approach used above (take the map size) should be sufficient. But if somebody
// changes this (e.g. allows removing entries from the map), this assertion here probably will fail.
for ( ConstMapPropertySet2StringIterator aCheck = m_aCurrentPageIds->second.begin();
aCheck != m_aCurrentPageIds->second.end();
++aCheck
)
OSL_ENSURE(aCheck->second != sCurrentId,
"OFormLayerXMLExport_Impl::checkExamineControl: auto-generated control ID is already used!");
#endif
// add it to the map
m_aCurrentPageIds->second[_rxObject] = sCurrentId;
// ----------------------------------
// check if this control has a "LabelControl" property referring another control
if ( xCurrentInfo->hasPropertyByName( PROPERTY_CONTROLLABEL ) )
{
Reference< XPropertySet > xCurrentReference;
::cppu::extractInterface( xCurrentReference, _rxObject->getPropertyValue( PROPERTY_CONTROLLABEL ) );
if (xCurrentReference.is())
{
::rtl::OUString& sReferencedBy = m_aCurrentPageReferring->second[xCurrentReference];
if (sReferencedBy.getLength())
// it's not the first _rxObject referring to the xCurrentReference
// -> separate the id
sReferencedBy += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(","));
sReferencedBy += sCurrentId;
}
}
// ----------------------------------
// check if the control needs a number format style
if ( xCurrentInfo->hasPropertyByName( PROPERTY_FORMATKEY ) )
{
examineControlNumberFormat(_rxObject);
}
// ----------------------------------
// check if it's a control providing text
Reference< XText > xControlText( _rxObject, UNO_QUERY );
if ( xControlText.is() )
{
m_rContext.GetTextParagraphExport()->collectTextAutoStyles( xControlText );
}
// ----------------------------------
// check if it is a grid control - in this case, we need special handling for the columns
sal_Int16 nControlType = FormComponentType::CONTROL;
_rxObject->getPropertyValue( PROPERTY_CLASSID ) >>= nControlType;
if ( FormComponentType::GRIDCONTROL == nControlType )
{
collectGridAutoStyles( _rxObject );
}
}
return bIsControl;
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::collectGridAutoStyles( const Reference< XPropertySet >& _rxControl )
{
// loop through all columns of the grid
try
{
Reference< XIndexAccess > xContainer( _rxControl, UNO_QUERY );
OSL_ENSURE( xContainer.is(), "OFormLayerXMLExport_Impl::collectGridAutoStyles: grid control not being a container?!" );
if ( xContainer.is() )
{
Reference< XPropertySet > xColumnProperties;
Reference< XPropertySetInfo > xColumnPropertiesMeta;
sal_Int32 nCount = xContainer->getCount();
for ( sal_Int32 i=0; i<nCount; ++i )
{
if ( xContainer->getByIndex( i ) >>= xColumnProperties )
{
xColumnPropertiesMeta = xColumnProperties->getPropertySetInfo();
// get the styles of the column
::std::vector< XMLPropertyState > aPropertyStates = m_xExportMapper->Filter( xColumnProperties );
// care for the number format, additionally
::rtl::OUString sColumnNumberStyle;
if ( xColumnPropertiesMeta.is() && xColumnPropertiesMeta->hasPropertyByName( PROPERTY_FORMATKEY ) )
sColumnNumberStyle = getImmediateNumberStyle( xColumnProperties );
if ( sColumnNumberStyle.getLength() )
{ // the column indeed has a formatting
sal_Int32 nStyleMapIndex = m_xExportMapper->getPropertySetMapper()->FindEntryIndex( CTF_FORMS_DATA_STYLE );
// TODO: move this to the ctor
OSL_ENSURE ( -1 != nStyleMapIndex, "XMLShapeExport::collectShapeAutoStyles: could not obtain the index for our context id!");
XMLPropertyState aNumberStyleState( nStyleMapIndex, makeAny( sColumnNumberStyle ) );
aPropertyStates.push_back( aNumberStyleState );
}
#if OSL_DEBUG_LEVEL > 0
::std::vector< XMLPropertyState >::const_iterator aHaveALook = aPropertyStates.begin();
for ( ; aHaveALook != aPropertyStates.end(); ++aHaveALook )
{
sal_Int32 nDummy = 0;
}
#endif
if ( aPropertyStates.size() )
{ // add to the style pool
::rtl::OUString sColumnStyleName = m_rContext.GetAutoStylePool()->Add( XML_STYLE_FAMILY_CONTROL_ID, aPropertyStates );
OSL_ENSURE( m_aGridColumnStyles.end() == m_aGridColumnStyles.find( xColumnProperties ),
"OFormLayerXMLExport_Impl::collectGridAutoStyles: already have a style for this column!" );
m_aGridColumnStyles.insert( MapPropertySet2String::value_type( xColumnProperties, sColumnStyleName ) );
}
}
else
OSL_ENSURE( sal_False, "OFormLayerXMLExport_Impl::collectGridAutoStyles: invalid grid column encountered!" );
}
}
}
catch( const Exception& e )
{
e; // make compiler happy
OSL_ENSURE( sal_False, "OFormLayerXMLExport_Impl::collectGridAutoStyles: error examining the grid colums!" );
}
}
//---------------------------------------------------------------------
sal_Int32 OFormLayerXMLExport_Impl::implExamineControlNumberFormat( const Reference< XPropertySet >& _rxObject )
{
// get the format key relative to our own formats supplier
sal_Int32 nOwnFormatKey = ensureTranslateFormat( _rxObject );
if ( -1 != nOwnFormatKey )
// tell the exporter that we used this format
getControlNumberStyleExport()->SetUsed( nOwnFormatKey );
return nOwnFormatKey;
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::examineControlNumberFormat( const Reference< XPropertySet >& _rxControl )
{
sal_Int32 nOwnFormatKey = implExamineControlNumberFormat( _rxControl );
if ( -1 == nOwnFormatKey )
// nothing to do, the number format of this control is void
return;
// remember the format key for this control (we'll be asked in getControlNumberStyle for this)
OSL_ENSURE(m_aControlNumberFormats.end() == m_aControlNumberFormats.find(_rxControl),
"OFormLayerXMLExport_Impl::examineControlNumberFormat: already handled this control!");
m_aControlNumberFormats[_rxControl] = nOwnFormatKey;
}
//---------------------------------------------------------------------
sal_Int32 OFormLayerXMLExport_Impl::ensureTranslateFormat(const Reference< XPropertySet >& _rxFormattedControl)
{
ensureControlNumberStyleExport();
OSL_ENSURE(m_xControlNumberFormats.is(), "OFormLayerXMLExport_Impl::ensureTranslateFormat: no own formats supplier!");
// (should have been created in ensureControlNumberStyleExport)
sal_Int32 nOwnFormatKey = -1;
// the format key (relative to the control's supplier)
sal_Int32 nControlFormatKey = -1;
Any aControlFormatKey = _rxFormattedControl->getPropertyValue(PROPERTY_FORMATKEY);
if (aControlFormatKey >>= nControlFormatKey)
{
// the control's number format
Reference< XNumberFormatsSupplier > xControlFormatsSupplier;
_rxFormattedControl->getPropertyValue(PROPERTY_FORMATSSUPPLIER) >>= xControlFormatsSupplier;
Reference< XNumberFormats > xControlFormats;
if (xControlFormatsSupplier.is())
xControlFormats = xControlFormatsSupplier->getNumberFormats();
OSL_ENSURE(xControlFormats.is(), "OFormLayerXMLExport_Impl::ensureTranslateFormat: formatted control without supplier!");
// obtain the persistent (does not depend on the formats supplier) representation of the control's format
Locale aFormatLocale;
::rtl::OUString sFormatDescription;
if (xControlFormats.is())
{
Reference< XPropertySet > xControlFormat = xControlFormats->getByKey(nControlFormatKey);
xControlFormat->getPropertyValue(PROPERTY_LOCALE) >>= aFormatLocale;
xControlFormat->getPropertyValue(PROPERTY_FORMATSTRING) >>= sFormatDescription;
}
// check if our own formats collection already knows the format
nOwnFormatKey = m_xControlNumberFormats->queryKey(sFormatDescription, aFormatLocale, sal_False);
if (-1 == nOwnFormatKey)
{ // no, we don't
// -> create a new format
nOwnFormatKey = m_xControlNumberFormats->addNew(sFormatDescription, aFormatLocale);
}
OSL_ENSURE(-1 != nOwnFormatKey, "OFormLayerXMLExport_Impl::ensureTranslateFormat: could not translate the controls format key!");
}
else
OSL_ENSURE(!aControlFormatKey.hasValue(), "OFormLayerXMLExport_Impl::ensureTranslateFormat: invalid number format property value!");
return nOwnFormatKey;
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::ensureControlNumberStyleExport()
{
if (!m_pControlNumberStyles)
{
// create our number formats supplier (if necessary)
Reference< XNumberFormatsSupplier > xFormatsSupplier;
OSL_ENSURE(!m_xControlNumberFormats.is(), "OFormLayerXMLExport_Impl::getControlNumberStyleExport: inconsistence!");
// the m_xControlNumberFormats and m_pControlNumberStyles should be maintained together
try
{
// create it for en-US (does not really matter, as we will specify a locale for every
// concrete language to use)
Sequence< Any > aSupplierArgs(1);
aSupplierArgs[0] <<= Locale ( ::rtl::OUString::createFromAscii("en"),
::rtl::OUString::createFromAscii("US"),
::rtl::OUString()
);
// #110680#
//Reference< XInterface > xFormatsSupplierUntyped =
// ::comphelper::getProcessServiceFactory()->createInstanceWithArguments(
// SERVICE_NUMBERFORMATSSUPPLIER,
// aSupplierArgs
// );
Reference< XInterface > xFormatsSupplierUntyped =
m_rContext.getServiceFactory()->createInstanceWithArguments(
SERVICE_NUMBERFORMATSSUPPLIER,
aSupplierArgs
);
OSL_ENSURE(xFormatsSupplierUntyped.is(), "OFormLayerXMLExport_Impl::getControlNumberStyleExport: could not instantiate a number formats supplier!");
xFormatsSupplier = Reference< XNumberFormatsSupplier >(xFormatsSupplierUntyped, UNO_QUERY);
if (xFormatsSupplier.is())
m_xControlNumberFormats = xFormatsSupplier->getNumberFormats();
}
catch(const Exception&)
{
}
OSL_ENSURE(m_xControlNumberFormats.is(), "OFormLayerXMLExport_Impl::getControlNumberStyleExport: could not obtain my default number formats!");
// create the exporter
m_pControlNumberStyles = new SvXMLNumFmtExport(m_rContext, xFormatsSupplier, getControlNumberStyleNamePrefix());
}
}
//---------------------------------------------------------------------
SvXMLNumFmtExport* OFormLayerXMLExport_Impl::getControlNumberStyleExport()
{
ensureControlNumberStyleExport();
return m_pControlNumberStyles;
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::excludeFromExport( const Reference< XControlModel > _rxControl )
{
Reference< XPropertySet > xProps( _rxControl, UNO_QUERY );
OSL_ENSURE( xProps.is(), "OFormLayerXMLExport_Impl::excludeFromExport: invalid control model!" );
#if OSL_DEBUG_LEVEL > 0
::std::pair< PropertySetBag::iterator, bool > aPos =
#endif
m_aIgnoreList.insert( xProps );
OSL_ENSURE( aPos.second, "OFormLayerXMLExport_Impl::excludeFromExport: element already exists in the ignore list!" );
}
//.........................................................................
} // namespace xmloff
//.........................................................................
INTEGRATION: CWS warnings01 (1.30.34); FILE MERGED
2005/11/04 14:50:30 cl 1.30.34.2: warning free code changes
2005/11/03 17:47:00 cl 1.30.34.1: warning free code changes for unxlngi6
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: layerexport.cxx,v $
*
* $Revision: 1.31 $
*
* last change: $Author: hr $ $Date: 2006-06-19 18:19:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <stdio.h>
#ifndef _XMLOFF_FORMS_LAYEREXPORT_HXX_
#include "layerexport.hxx"
#endif
#ifndef _XMLOFF_FORMS_STRINGS_HXX_
#include "strings.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include "xmlprmap.hxx"
#endif
#ifndef _XMLOFF_PROPERTYHANDLERFACTORY_HXX
#include "prhdlfac.hxx"
#endif
#ifndef _XMLOFF_ELEMENTEXPORT_HXX_
#include "elementexport.hxx"
#endif
#ifndef _XMLOFF_FAMILIES_HXX_
#include "families.hxx"
#endif
#ifndef _XMLOFF_CONTEXTID_HXX_
#include "contextid.hxx"
#endif
#ifndef _XMLOFF_FORMS_CONTROLPROPERTYHDL_HXX_
#include "controlpropertyhdl.hxx"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _XMLOFF_FORMS_CONTROLPROPERTYMAP_HXX_
#include "controlpropertymap.hxx"
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XFORMSSUPPLIER2_HPP_
#include <com/sun/star/form/XFormsSupplier2.hpp>
#endif
#ifndef _COM_SUN_STAR_XFORMS_XFORMSSUPPLIER_HPP_
#include <com/sun/star/xforms/XFormsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_FORMCOMPONENTTYPE_HPP_
#include <com/sun/star/form/FormComponentType.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_SCRIPT_XEVENTATTACHERMANAGER_HPP_
#include <com/sun/star/script/XEventAttacherManager.hpp>
#endif
#ifndef _XMLOFF_FORMS_EVENTEXPORT_HXX_
#include "eventexport.hxx"
#endif
#ifndef _XMLOFF_XMLEVENTEXPORT_HXX
#include "XMLEventExport.hxx"
#endif
#ifndef _XMLOFF_FORMS_FORMEVENTS_HXX_
#include "formevents.hxx"
#endif
#ifndef _XMLOFF_XMLNUMFE_HXX
#include "xmlnumfe.hxx"
#endif
#ifndef _XMLOFF_XFORMSEXPORT_HXX
#include "xformsexport.hxx"
#endif
/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif
/** === end UNO includes === **/
//.........................................................................
namespace xmloff
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::drawing;
using namespace ::com::sun::star::form;
using namespace ::com::sun::star::script;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::text;
typedef ::com::sun::star::xforms::XFormsSupplier XXFormsSupplier;
//=====================================================================
//= OFormLayerXMLExport_Impl
//=====================================================================
//---------------------------------------------------------------------
const ::rtl::OUString& OFormLayerXMLExport_Impl::getControlNumberStyleNamePrefix()
{
static const ::rtl::OUString s_sControlNumberStyleNamePrefix = ::rtl::OUString::createFromAscii("C");
return s_sControlNumberStyleNamePrefix;
}
//---------------------------------------------------------------------
OFormLayerXMLExport_Impl::OFormLayerXMLExport_Impl(SvXMLExport& _rContext)
:m_rContext(_rContext)
,m_pControlNumberStyles(NULL)
{
initializePropertyMaps();
// add our style family to the export context's style pool
m_xPropertyHandlerFactory = new OControlPropertyHandlerFactory();
::vos::ORef< XMLPropertySetMapper > xStylePropertiesMapper = new XMLPropertySetMapper( getControlStylePropertyMap(), m_xPropertyHandlerFactory.getBodyPtr() );
m_xExportMapper = new OFormExportPropertyMapper( xStylePropertiesMapper.getBodyPtr() );
// our style family
m_rContext.GetAutoStylePool()->AddFamily(
XML_STYLE_FAMILY_CONTROL_ID, token::GetXMLToken(token::XML_PARAGRAPH),
m_xExportMapper.getBodyPtr(),
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( XML_STYLE_FAMILY_CONTROL_PREFIX) )
);
// add our event translation table
m_rContext.GetEventExport().AddTranslationTable(g_pFormsEventTranslation);
clear();
}
OFormLayerXMLExport_Impl::~OFormLayerXMLExport_Impl()
{
}
//---------------------------------------------------------------------
sal_Bool OFormLayerXMLExport_Impl::impl_isFormPageContainingForms(const Reference< XDrawPage >& _rxDrawPage, Reference< XIndexAccess >& _rxForms)
{
Reference< XFormsSupplier2 > xFormsSupp(_rxDrawPage, UNO_QUERY);
OSL_ENSURE(xFormsSupp.is(), "OFormLayerXMLExport_Impl::impl_isFormPageContainingForms: invalid draw page (no XFormsSupplier)! Doin' nothing!");
if (!xFormsSupp.is())
return sal_False;
if ( !xFormsSupp->hasForms() )
// nothing to do at all
return sal_False;
_rxForms = Reference< XIndexAccess >(xFormsSupp->getForms(), UNO_QUERY);
Reference< XServiceInfo > xSI(_rxForms, UNO_QUERY); // order is important!
OSL_ENSURE(xSI.is(), "OFormLayerXMLExport_Impl::impl_isFormPageContainingForms: invalid collection (must not be NULL and must have a ServiceInfo)!");
if (!xSI.is())
return sal_False;
if (!xSI->supportsService(SERVICE_FORMSCOLLECTION))
{
OSL_ENSURE(sal_False, "OFormLayerXMLExport_Impl::impl_isFormPageContainingForms: invalid collection (is no com.sun.star.form.Forms)!");
// nothing to do
return sal_False;
}
return sal_True;
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportGridColumn(const Reference< XPropertySet >& _rxColumn,
const Sequence< ScriptEventDescriptor >& _rEvents)
{
// do the exporting
OColumnExport aExportImpl(*this, _rxColumn, _rEvents);
aExportImpl.doExport();
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportControl(const Reference< XPropertySet >& _rxControl,
const Sequence< ScriptEventDescriptor >& _rEvents)
{
// the list of the referring controls
::rtl::OUString sReferringControls;
ConstMapPropertySet2StringIterator aReferring = m_aCurrentPageReferring->second.find(_rxControl);
if (aReferring != m_aCurrentPageReferring->second.end())
sReferringControls = aReferring->second;
// the control id (should already have been created in examineForms)
::rtl::OUString sControlId;
ConstMapPropertySet2StringIterator aControlId = m_aCurrentPageIds->second.find(_rxControl);
OSL_ENSURE(aControlId != m_aCurrentPageIds->second.end(), "OFormLayerXMLExport_Impl::exportControl: could not find the control id!");
if (aControlId != m_aCurrentPageIds->second.end())
sControlId = aControlId->second;
// do the exporting
OControlExport aExportImpl(*this, _rxControl, sControlId, sReferringControls, _rEvents);
aExportImpl.doExport();
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportForm(const Reference< XPropertySet >& _rxProps,
const Sequence< ScriptEventDescriptor >& _rEvents)
{
OSL_ENSURE(_rxProps.is(), "OFormLayerXMLExport_Impl::exportForm: invalid property set!");
OFormExport aAttributeHandler(*this, _rxProps, _rEvents);
aAttributeHandler.doExport();
}
//---------------------------------------------------------------------
::vos::ORef< SvXMLExportPropertyMapper > OFormLayerXMLExport_Impl::getStylePropertyMapper()
{
return m_xExportMapper;
}
//---------------------------------------------------------------------
SvXMLExport& OFormLayerXMLExport_Impl::getGlobalContext()
{
return m_rContext;
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportCollectionElements(const Reference< XIndexAccess >& _rxCollection)
{
// step through all the elements of the collection
sal_Int32 nElements = _rxCollection->getCount();
Reference< XEventAttacherManager > xElementEventManager(_rxCollection, UNO_QUERY);
Sequence< ScriptEventDescriptor > aElementEvents;
Reference< XPropertySet > xCurrentProps;
Reference< XPropertySetInfo > xPropsInfo;
Reference< XIndexAccess > xCurrentContainer;
for (sal_Int32 i=0; i<nElements; ++i)
{
try
{
// extract the current element
::cppu::extractInterface(xCurrentProps, _rxCollection->getByIndex(i));
OSL_ENSURE(xCurrentProps.is(), "OFormLayerXMLExport_Impl::exportCollectionElements: invalid child element, skipping!");
if (!xCurrentProps.is())
continue;
// check if there is a ClassId property on the current element. If so, we assume it to be a control
xPropsInfo = xCurrentProps->getPropertySetInfo();
OSL_ENSURE(xPropsInfo.is(), "OFormLayerXMLExport_Impl::exportCollectionElements: no property set info!");
if (!xPropsInfo.is())
// without this, a lot of stuff in the export routines may fail
continue;
// if the element is part of a ignore list, we are not allowed to export it
if ( m_aIgnoreList.end() != m_aIgnoreList.find( xCurrentProps ) )
continue;
if (xElementEventManager.is())
aElementEvents = xElementEventManager->getScriptEvents(i);
if (xPropsInfo->hasPropertyByName(PROPERTY_COLUMNSERVICENAME))
{
exportGridColumn(xCurrentProps, aElementEvents);
}
else if (xPropsInfo->hasPropertyByName(PROPERTY_CLASSID))
{
exportControl(xCurrentProps, aElementEvents);
}
else
{
exportForm(xCurrentProps, aElementEvents);
}
}
catch(Exception&)
{
OSL_ENSURE(sal_False, "OFormLayerXMLExport_Impl::exportCollectionElements: caught an exception ... skipping the current element!");
continue;
}
}
}
//---------------------------------------------------------------------
::rtl::OUString OFormLayerXMLExport_Impl::getObjectStyleName( const Reference< XPropertySet >& _rxObject )
{
::rtl::OUString aObjectStyle;
MapPropertySet2String::const_iterator aObjectStylePos = m_aGridColumnStyles.find( _rxObject );
if ( m_aGridColumnStyles.end() != aObjectStylePos )
aObjectStyle = aObjectStylePos->second;
return aObjectStyle;
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::clear()
{
m_aControlIds.clear();
m_aReferringControls.clear();
m_aCurrentPageIds = m_aControlIds.end();
m_aCurrentPageReferring = m_aReferringControls.end();
m_aControlNumberFormats.clear();
m_aGridColumnStyles.clear();
m_aIgnoreList.clear();
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportControlNumberStyles()
{
if (m_pControlNumberStyles)
m_pControlNumberStyles->Export(sal_False);
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportAutoControlNumberStyles()
{
if ( m_pControlNumberStyles )
m_pControlNumberStyles->Export( sal_True );
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportAutoStyles()
{
m_rContext.GetAutoStylePool()->exportXML(
XML_STYLE_FAMILY_CONTROL_ID,
m_rContext.GetDocHandler(),
m_rContext.GetMM100UnitConverter(),
m_rContext.GetNamespaceMap()
);
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportForms(const Reference< XDrawPage >& _rxDrawPage)
{
// get the forms collection of the page
Reference< XIndexAccess > xCollectionIndex;
if (!impl_isFormPageContainingForms(_rxDrawPage, xCollectionIndex))
return;
#if OSL_DEBUG_LEVEL > 0
sal_Bool bPageIsKnown =
#endif
implMoveIterators(_rxDrawPage, sal_False);
OSL_ENSURE(bPageIsKnown, "OFormLayerXMLExport_Impl::exportForms: exporting a page which has not been examined!");
// export forms collection
exportCollectionElements(xCollectionIndex);
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::exportXForms() const
{
// export XForms models
::exportXForms( m_rContext );
}
//---------------------------------------------------------------------
bool OFormLayerXMLExport_Impl::pageContainsForms( const Reference< XDrawPage >& _rxDrawPage ) const
{
Reference< XFormsSupplier2 > xFormsSupp( _rxDrawPage, UNO_QUERY );
DBG_ASSERT( xFormsSupp.is(), "OFormLayerXMLExport_Impl::pageContainsForms: no XFormsSupplier2!" );
return xFormsSupp.is() && xFormsSupp->hasForms();
}
//---------------------------------------------------------------------
bool OFormLayerXMLExport_Impl::documentContainsXForms() const
{
Reference< XXFormsSupplier > xXFormSupp( m_rContext.GetModel(), UNO_QUERY );
Reference< XNameContainer > xForms;
if ( xXFormSupp.is() )
xForms = xXFormSupp->getXForms();
return xForms.is() && xForms->hasElements();
}
//---------------------------------------------------------------------
sal_Bool OFormLayerXMLExport_Impl::implMoveIterators(const Reference< XDrawPage >& _rxDrawPage, sal_Bool _bClear)
{
sal_Bool bKnownPage = sal_False;
// the one for the ids
m_aCurrentPageIds = m_aControlIds.find(_rxDrawPage);
if (m_aControlIds.end() == m_aCurrentPageIds)
{
m_aControlIds[_rxDrawPage] = MapPropertySet2String();
m_aCurrentPageIds = m_aControlIds.find(_rxDrawPage);
}
else
{
bKnownPage = sal_True;
if (_bClear && m_aCurrentPageIds->second.size())
m_aCurrentPageIds->second.clear();
}
// the one for the ids of the referring controls
m_aCurrentPageReferring = m_aReferringControls.find(_rxDrawPage);
if (m_aReferringControls.end() == m_aCurrentPageReferring)
{
m_aReferringControls[_rxDrawPage] = MapPropertySet2String();
m_aCurrentPageReferring = m_aReferringControls.find(_rxDrawPage);
}
else
{
bKnownPage = sal_True;
if (_bClear && m_aCurrentPageReferring->second.size())
m_aCurrentPageReferring->second.clear();
}
return bKnownPage;
}
//---------------------------------------------------------------------
sal_Bool OFormLayerXMLExport_Impl::seekPage(const Reference< XDrawPage >& _rxDrawPage)
{
sal_Bool bKnownPage = implMoveIterators( _rxDrawPage, sal_False );
if ( bKnownPage )
return sal_True;
// if the page is not yet know, this does not automatically mean that it has
// not been examined. Instead, examineForms returns silently and successfully
// if a page is a XFormsPageSupplier2, but does not have a forms collection
// (This behaviour of examineForms is a performance optimization, to not force
// the page to create a forms container just to see that it's empty.)
// So, in such a case, seekPage is considered to be successfull, too, though the
// page was not yet known
Reference< XFormsSupplier2 > xFormsSupp( _rxDrawPage, UNO_QUERY );
if ( xFormsSupp.is() && !xFormsSupp->hasForms() )
return sal_True;
// anything else means that the page has not been examined before, or it's no
// valid form page. Both cases are Bad (TM).
return sal_False;
}
//---------------------------------------------------------------------
::rtl::OUString OFormLayerXMLExport_Impl::getControlId(const Reference< XPropertySet >& _rxControl)
{
OSL_ENSURE(m_aCurrentPageIds != m_aControlIds.end(), "OFormLayerXMLExport_Impl::getControlId: invalid current page!");
OSL_ENSURE(m_aCurrentPageIds->second.end() != m_aCurrentPageIds->second.find(_rxControl),
"OFormLayerXMLExport_Impl::getControlId: can not find the control!");
return m_aCurrentPageIds->second[_rxControl];
}
//---------------------------------------------------------------------
::rtl::OUString OFormLayerXMLExport_Impl::getImmediateNumberStyle( const Reference< XPropertySet >& _rxObject )
{
::rtl::OUString sNumberStyle;
sal_Int32 nOwnFormatKey = implExamineControlNumberFormat( _rxObject );
if ( -1 != nOwnFormatKey )
sNumberStyle = getControlNumberStyleExport()->GetStyleName( nOwnFormatKey );
return sNumberStyle;
}
//---------------------------------------------------------------------
::rtl::OUString OFormLayerXMLExport_Impl::getControlNumberStyle( const Reference< XPropertySet >& _rxControl )
{
::rtl::OUString sNumberStyle;
ConstMapPropertySet2IntIterator aControlFormatPos = m_aControlNumberFormats.find(_rxControl);
if (m_aControlNumberFormats.end() != aControlFormatPos)
{
OSL_ENSURE(m_pControlNumberStyles, "OFormLayerXMLExport_Impl::getControlNumberStyle: have a control which has a format style, but no style exporter!");
sNumberStyle = getControlNumberStyleExport()->GetStyleName(aControlFormatPos->second);
}
// it's allowed to ask for a control which does not have format information.
// (This is for performance reasons)
return sNumberStyle;
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::examineForms(const Reference< XDrawPage >& _rxDrawPage)
{
// get the forms collection of the page
Reference< XIndexAccess > xCollectionIndex;
if (!impl_isFormPageContainingForms(_rxDrawPage, xCollectionIndex))
return;
// move the iterator which specify the currently handled page
#if OSL_DEBUG_LEVEL > 0
sal_Bool bPageIsKnown =
#endif
implMoveIterators(_rxDrawPage, sal_True);
OSL_ENSURE(!bPageIsKnown, "OFormLayerXMLExport_Impl::examineForms: examining a page twice!");
::std::stack< Reference< XIndexAccess > > aContainerHistory;
::std::stack< sal_Int32 > aIndexHistory;
Reference< XPropertySet > xCurrent;
Reference< XIndexAccess > xLoop = xCollectionIndex;
sal_Int32 nChildPos = 0;
do
{
if (nChildPos < xLoop->getCount())
{
::cppu::extractInterface(xCurrent, xLoop->getByIndex(nChildPos));
OSL_ENSURE(xCurrent.is(), "OFormLayerXMLExport_Impl::examineForms: invalid child object");
if (!xCurrent.is())
continue;
if (!checkExamineControl(xCurrent))
{
// step down
Reference< XIndexAccess > xNextContainer(xCurrent, UNO_QUERY);
OSL_ENSURE(xNextContainer.is(), "OFormLayerXMLExport_Impl::examineForms: what the heck is this ... no control, no container?");
aContainerHistory.push(xLoop);
aIndexHistory.push(nChildPos);
xLoop = xNextContainer;
nChildPos = -1; // will be incremented below
}
++nChildPos;
}
else
{
// step up
while ((nChildPos >= xLoop->getCount()) && aContainerHistory.size())
{
xLoop = aContainerHistory.top();
aContainerHistory.pop();
nChildPos = aIndexHistory.top();
aIndexHistory.pop();
++nChildPos;
}
if (nChildPos >= xLoop->getCount())
// exited the loop above because we have no history anymore (0 == aContainerHistory.size()),
// and on the current level there are no more children
// -> leave
break;
}
}
while (xLoop.is());
}
//---------------------------------------------------------------------
sal_Bool OFormLayerXMLExport_Impl::checkExamineControl(const Reference< XPropertySet >& _rxObject)
{
static const ::rtl::OUString sControlId(RTL_CONSTASCII_USTRINGPARAM("control"));
Reference< XPropertySetInfo > xCurrentInfo = _rxObject->getPropertySetInfo();
OSL_ENSURE(xCurrentInfo.is(), "OFormLayerXMLExport_Impl::checkExamineControl: no property set info");
sal_Bool bIsControl = xCurrentInfo->hasPropertyByName( PROPERTY_CLASSID );
if (bIsControl)
{
// ----------------------------------
// generate a new control id
// find a free id
::rtl::OUString sCurrentId = sControlId;
sCurrentId += ::rtl::OUString::valueOf((sal_Int32)(m_aCurrentPageIds->second.size() + 1));
#ifdef DBG_UTIL
// Check if the id is already used. It shouldn't, as we currently have no mechanism for removing entries
// from the map, so the approach used above (take the map size) should be sufficient. But if somebody
// changes this (e.g. allows removing entries from the map), this assertion here probably will fail.
for ( ConstMapPropertySet2StringIterator aCheck = m_aCurrentPageIds->second.begin();
aCheck != m_aCurrentPageIds->second.end();
++aCheck
)
OSL_ENSURE(aCheck->second != sCurrentId,
"OFormLayerXMLExport_Impl::checkExamineControl: auto-generated control ID is already used!");
#endif
// add it to the map
m_aCurrentPageIds->second[_rxObject] = sCurrentId;
// ----------------------------------
// check if this control has a "LabelControl" property referring another control
if ( xCurrentInfo->hasPropertyByName( PROPERTY_CONTROLLABEL ) )
{
Reference< XPropertySet > xCurrentReference;
::cppu::extractInterface( xCurrentReference, _rxObject->getPropertyValue( PROPERTY_CONTROLLABEL ) );
if (xCurrentReference.is())
{
::rtl::OUString& sReferencedBy = m_aCurrentPageReferring->second[xCurrentReference];
if (sReferencedBy.getLength())
// it's not the first _rxObject referring to the xCurrentReference
// -> separate the id
sReferencedBy += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(","));
sReferencedBy += sCurrentId;
}
}
// ----------------------------------
// check if the control needs a number format style
if ( xCurrentInfo->hasPropertyByName( PROPERTY_FORMATKEY ) )
{
examineControlNumberFormat(_rxObject);
}
// ----------------------------------
// check if it's a control providing text
Reference< XText > xControlText( _rxObject, UNO_QUERY );
if ( xControlText.is() )
{
m_rContext.GetTextParagraphExport()->collectTextAutoStyles( xControlText );
}
// ----------------------------------
// check if it is a grid control - in this case, we need special handling for the columns
sal_Int16 nControlType = FormComponentType::CONTROL;
_rxObject->getPropertyValue( PROPERTY_CLASSID ) >>= nControlType;
if ( FormComponentType::GRIDCONTROL == nControlType )
{
collectGridAutoStyles( _rxObject );
}
}
return bIsControl;
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::collectGridAutoStyles( const Reference< XPropertySet >& _rxControl )
{
// loop through all columns of the grid
try
{
Reference< XIndexAccess > xContainer( _rxControl, UNO_QUERY );
OSL_ENSURE( xContainer.is(), "OFormLayerXMLExport_Impl::collectGridAutoStyles: grid control not being a container?!" );
if ( xContainer.is() )
{
Reference< XPropertySet > xColumnProperties;
Reference< XPropertySetInfo > xColumnPropertiesMeta;
sal_Int32 nCount = xContainer->getCount();
for ( sal_Int32 i=0; i<nCount; ++i )
{
if ( xContainer->getByIndex( i ) >>= xColumnProperties )
{
xColumnPropertiesMeta = xColumnProperties->getPropertySetInfo();
// get the styles of the column
::std::vector< XMLPropertyState > aPropertyStates = m_xExportMapper->Filter( xColumnProperties );
// care for the number format, additionally
::rtl::OUString sColumnNumberStyle;
if ( xColumnPropertiesMeta.is() && xColumnPropertiesMeta->hasPropertyByName( PROPERTY_FORMATKEY ) )
sColumnNumberStyle = getImmediateNumberStyle( xColumnProperties );
if ( sColumnNumberStyle.getLength() )
{ // the column indeed has a formatting
sal_Int32 nStyleMapIndex = m_xExportMapper->getPropertySetMapper()->FindEntryIndex( CTF_FORMS_DATA_STYLE );
// TODO: move this to the ctor
OSL_ENSURE ( -1 != nStyleMapIndex, "XMLShapeExport::collectShapeAutoStyles: could not obtain the index for our context id!");
XMLPropertyState aNumberStyleState( nStyleMapIndex, makeAny( sColumnNumberStyle ) );
aPropertyStates.push_back( aNumberStyleState );
}
#if OSL_DEBUG_LEVEL > 0
::std::vector< XMLPropertyState >::const_iterator aHaveALook = aPropertyStates.begin();
for ( ; aHaveALook != aPropertyStates.end(); ++aHaveALook )
{
(void)aHaveALook;
}
#endif
if ( aPropertyStates.size() )
{ // add to the style pool
::rtl::OUString sColumnStyleName = m_rContext.GetAutoStylePool()->Add( XML_STYLE_FAMILY_CONTROL_ID, aPropertyStates );
OSL_ENSURE( m_aGridColumnStyles.end() == m_aGridColumnStyles.find( xColumnProperties ),
"OFormLayerXMLExport_Impl::collectGridAutoStyles: already have a style for this column!" );
m_aGridColumnStyles.insert( MapPropertySet2String::value_type( xColumnProperties, sColumnStyleName ) );
}
}
else
OSL_ENSURE( sal_False, "OFormLayerXMLExport_Impl::collectGridAutoStyles: invalid grid column encountered!" );
}
}
}
catch( const Exception& e )
{
(void)e; // make compiler happy
OSL_ENSURE( sal_False, "OFormLayerXMLExport_Impl::collectGridAutoStyles: error examining the grid colums!" );
}
}
//---------------------------------------------------------------------
sal_Int32 OFormLayerXMLExport_Impl::implExamineControlNumberFormat( const Reference< XPropertySet >& _rxObject )
{
// get the format key relative to our own formats supplier
sal_Int32 nOwnFormatKey = ensureTranslateFormat( _rxObject );
if ( -1 != nOwnFormatKey )
// tell the exporter that we used this format
getControlNumberStyleExport()->SetUsed( nOwnFormatKey );
return nOwnFormatKey;
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::examineControlNumberFormat( const Reference< XPropertySet >& _rxControl )
{
sal_Int32 nOwnFormatKey = implExamineControlNumberFormat( _rxControl );
if ( -1 == nOwnFormatKey )
// nothing to do, the number format of this control is void
return;
// remember the format key for this control (we'll be asked in getControlNumberStyle for this)
OSL_ENSURE(m_aControlNumberFormats.end() == m_aControlNumberFormats.find(_rxControl),
"OFormLayerXMLExport_Impl::examineControlNumberFormat: already handled this control!");
m_aControlNumberFormats[_rxControl] = nOwnFormatKey;
}
//---------------------------------------------------------------------
sal_Int32 OFormLayerXMLExport_Impl::ensureTranslateFormat(const Reference< XPropertySet >& _rxFormattedControl)
{
ensureControlNumberStyleExport();
OSL_ENSURE(m_xControlNumberFormats.is(), "OFormLayerXMLExport_Impl::ensureTranslateFormat: no own formats supplier!");
// (should have been created in ensureControlNumberStyleExport)
sal_Int32 nOwnFormatKey = -1;
// the format key (relative to the control's supplier)
sal_Int32 nControlFormatKey = -1;
Any aControlFormatKey = _rxFormattedControl->getPropertyValue(PROPERTY_FORMATKEY);
if (aControlFormatKey >>= nControlFormatKey)
{
// the control's number format
Reference< XNumberFormatsSupplier > xControlFormatsSupplier;
_rxFormattedControl->getPropertyValue(PROPERTY_FORMATSSUPPLIER) >>= xControlFormatsSupplier;
Reference< XNumberFormats > xControlFormats;
if (xControlFormatsSupplier.is())
xControlFormats = xControlFormatsSupplier->getNumberFormats();
OSL_ENSURE(xControlFormats.is(), "OFormLayerXMLExport_Impl::ensureTranslateFormat: formatted control without supplier!");
// obtain the persistent (does not depend on the formats supplier) representation of the control's format
Locale aFormatLocale;
::rtl::OUString sFormatDescription;
if (xControlFormats.is())
{
Reference< XPropertySet > xControlFormat = xControlFormats->getByKey(nControlFormatKey);
xControlFormat->getPropertyValue(PROPERTY_LOCALE) >>= aFormatLocale;
xControlFormat->getPropertyValue(PROPERTY_FORMATSTRING) >>= sFormatDescription;
}
// check if our own formats collection already knows the format
nOwnFormatKey = m_xControlNumberFormats->queryKey(sFormatDescription, aFormatLocale, sal_False);
if (-1 == nOwnFormatKey)
{ // no, we don't
// -> create a new format
nOwnFormatKey = m_xControlNumberFormats->addNew(sFormatDescription, aFormatLocale);
}
OSL_ENSURE(-1 != nOwnFormatKey, "OFormLayerXMLExport_Impl::ensureTranslateFormat: could not translate the controls format key!");
}
else
OSL_ENSURE(!aControlFormatKey.hasValue(), "OFormLayerXMLExport_Impl::ensureTranslateFormat: invalid number format property value!");
return nOwnFormatKey;
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::ensureControlNumberStyleExport()
{
if (!m_pControlNumberStyles)
{
// create our number formats supplier (if necessary)
Reference< XNumberFormatsSupplier > xFormatsSupplier;
OSL_ENSURE(!m_xControlNumberFormats.is(), "OFormLayerXMLExport_Impl::getControlNumberStyleExport: inconsistence!");
// the m_xControlNumberFormats and m_pControlNumberStyles should be maintained together
try
{
// create it for en-US (does not really matter, as we will specify a locale for every
// concrete language to use)
Sequence< Any > aSupplierArgs(1);
aSupplierArgs[0] <<= Locale ( ::rtl::OUString::createFromAscii("en"),
::rtl::OUString::createFromAscii("US"),
::rtl::OUString()
);
// #110680#
//Reference< XInterface > xFormatsSupplierUntyped =
// ::comphelper::getProcessServiceFactory()->createInstanceWithArguments(
// SERVICE_NUMBERFORMATSSUPPLIER,
// aSupplierArgs
// );
Reference< XInterface > xFormatsSupplierUntyped =
m_rContext.getServiceFactory()->createInstanceWithArguments(
SERVICE_NUMBERFORMATSSUPPLIER,
aSupplierArgs
);
OSL_ENSURE(xFormatsSupplierUntyped.is(), "OFormLayerXMLExport_Impl::getControlNumberStyleExport: could not instantiate a number formats supplier!");
xFormatsSupplier = Reference< XNumberFormatsSupplier >(xFormatsSupplierUntyped, UNO_QUERY);
if (xFormatsSupplier.is())
m_xControlNumberFormats = xFormatsSupplier->getNumberFormats();
}
catch(const Exception&)
{
}
OSL_ENSURE(m_xControlNumberFormats.is(), "OFormLayerXMLExport_Impl::getControlNumberStyleExport: could not obtain my default number formats!");
// create the exporter
m_pControlNumberStyles = new SvXMLNumFmtExport(m_rContext, xFormatsSupplier, getControlNumberStyleNamePrefix());
}
}
//---------------------------------------------------------------------
SvXMLNumFmtExport* OFormLayerXMLExport_Impl::getControlNumberStyleExport()
{
ensureControlNumberStyleExport();
return m_pControlNumberStyles;
}
//---------------------------------------------------------------------
void OFormLayerXMLExport_Impl::excludeFromExport( const Reference< XControlModel > _rxControl )
{
Reference< XPropertySet > xProps( _rxControl, UNO_QUERY );
OSL_ENSURE( xProps.is(), "OFormLayerXMLExport_Impl::excludeFromExport: invalid control model!" );
#if OSL_DEBUG_LEVEL > 0
::std::pair< PropertySetBag::iterator, bool > aPos =
#endif
m_aIgnoreList.insert( xProps );
OSL_ENSURE( aPos.second, "OFormLayerXMLExport_Impl::excludeFromExport: element already exists in the ignore list!" );
}
//.........................................................................
} // namespace xmloff
//.........................................................................
|
/**
* \file minimizer_mapper.cpp
* Defines the code for the minimizer-and-GBWT-based mapper.
*/
#include "minimizer_mapper.hpp"
#include "annotation.hpp"
#include "path_subgraph.hpp"
#include "multipath_alignment.hpp"
#include "split_strand_graph.hpp"
#include "algorithms/dagify.hpp"
#include "algorithms/dijkstra.hpp"
#include <bdsg/overlays/strand_split_overlay.hpp>
#include <gbwtgraph/algorithms.h>
#include <gbwtgraph/cached_gbwtgraph.h>
#include <iostream>
#include <algorithm>
#include <cmath>
//#define debug
//#define print_minimizers
namespace vg {
using namespace std;
MinimizerMapper::MinimizerMapper(const gbwtgraph::GBWTGraph& graph,
const std::vector<gbwtgraph::DefaultMinimizerIndex*>& minimizer_indexes,
MinimumDistanceIndex& distance_index, const PathPositionHandleGraph* path_graph) :
path_graph(path_graph), minimizer_indexes(minimizer_indexes),
distance_index(distance_index), gbwt_graph(graph),
extender(gbwt_graph, *(get_regular_aligner())), clusterer(distance_index),
fragment_length_distr(1000,1000,0.95) {
}
//-----------------------------------------------------------------------------
void MinimizerMapper::map(Alignment& aln, AlignmentEmitter& alignment_emitter) {
// Ship out all the aligned alignments
alignment_emitter.emit_mapped_single(map(aln));
}
vector<Alignment> MinimizerMapper::map(Alignment& aln) {
#ifdef debug
cerr << "Read " << aln.name() << ": " << aln.sequence() << endl;
#endif
// Make a new funnel instrumenter to watch us map this read.
Funnel funnel;
funnel.start(aln.name());
// Minimizers sorted by score in descending order.
std::vector<Minimizer> minimizers = this->find_minimizers(aln.sequence(), funnel);
// Find the seeds and mark the minimizers that were located.
std::vector<Seed> seeds = this->find_seeds(minimizers, aln, funnel);
// Cluster the seeds. Get sets of input seed indexes that go together.
if (track_provenance) {
funnel.stage("cluster");
}
std::vector<Cluster> clusters = clusterer.cluster_seeds(seeds, get_distance_limit(aln.sequence().size()));
// Determine the scores and read coverages for each cluster.
// Also find the best and second-best cluster scores.
if (this->track_provenance) {
funnel.substage("score");
}
double best_cluster_score = 0.0, second_best_cluster_score = 0.0;
for (size_t i = 0; i < clusters.size(); i++) {
Cluster& cluster = clusters[i];
this->score_cluster(cluster, i, minimizers, seeds, aln.sequence().length(), funnel);
if (cluster.score > best_cluster_score) {
second_best_cluster_score = best_cluster_score;
best_cluster_score = cluster.score;
} else if (cluster.score > second_best_cluster_score) {
second_best_cluster_score = cluster.score;
}
}
#ifdef debug
cerr << "Found " << clusters.size() << " clusters" << endl;
#endif
// We will set a score cutoff based on the best, but move it down to the
// second best if it does not include the second best and the second best
// is within pad_cluster_score_threshold of where the cutoff would
// otherwise be. This ensures that we won't throw away all but one cluster
// based on score alone, unless it is really bad.
double cluster_score_cutoff = best_cluster_score - cluster_score_threshold;
if (cluster_score_cutoff - pad_cluster_score_threshold < second_best_cluster_score) {
cluster_score_cutoff = std::min(cluster_score_cutoff, second_best_cluster_score);
}
if (track_provenance) {
// Now we go from clusters to gapless extensions
funnel.stage("extend");
}
// These are the GaplessExtensions for all the clusters.
vector<vector<GaplessExtension>> cluster_extensions;
cluster_extensions.reserve(clusters.size());
// To compute the windows for explored minimizers, we need to get
// all the minimizers that are explored.
SmallBitset minimizer_explored(minimizers.size());
//How many hits of each minimizer ended up in each extended cluster?
vector<vector<size_t>> minimizer_extended_cluster_count;
//For each cluster, what fraction of "equivalent" clusters did we keep?
vector<double> probability_cluster_lost;
//What is the score and coverage we are considering and how many reads
size_t curr_coverage = 0;
size_t curr_score = 0;
size_t curr_kept = 0;
size_t curr_count = 0;
// We track unextended clusters.
vector<size_t> unextended_clusters;
unextended_clusters.reserve(clusters.size());
//Process clusters sorted by both score and read coverage
process_until_threshold_c<Cluster, double>(clusters, [&](size_t i) -> double {
return clusters[i].coverage;
}, [&](size_t a, size_t b) -> bool {
return ((clusters[a].coverage > clusters[b].coverage) ||
(clusters[a].coverage == clusters[b].coverage && clusters[a].score > clusters[b].score));
},
cluster_coverage_threshold, 1, max_extensions,
[&](size_t cluster_num) {
// Handle sufficiently good clusters in descending coverage order
Cluster& cluster = clusters[cluster_num];
if (track_provenance) {
funnel.pass("cluster-coverage", cluster_num, cluster.coverage);
funnel.pass("max-extensions", cluster_num);
}
// First check against the additional score filter
if (cluster_score_threshold != 0 && cluster.score < cluster_score_cutoff) {
//If the score isn't good enough, ignore this cluster
if (track_provenance) {
funnel.fail("cluster-score", cluster_num, cluster.score);
}
// Record MAPQ implications of not extending this cluster.
unextended_clusters.push_back(cluster_num);
#ifdef debug
cerr << "Cluster " << cluster_num << " fails cluster score cutoff" << endl;
cerr << "Covers " << clusters[cluster_num].coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << clusters[cluster_num].score << "/" << cluster_score_cutoff << endl;
#endif
return false;
}
if (track_provenance) {
funnel.pass("cluster-score", cluster_num, cluster.score);
funnel.processing_input(cluster_num);
}
if (cluster.coverage == curr_coverage &&
cluster.score == curr_score &&
curr_kept < max_extensions * 0.75) {
curr_kept++;
curr_count++;
} else if (cluster.coverage != curr_coverage ||
cluster.score != curr_score) {
//If this is a cluster that has scores different than the previous one
for (size_t i = 0 ; i < curr_kept ; i++ ) {
probability_cluster_lost.push_back(1.0 - (double(curr_kept) / double(curr_count)));
}
curr_coverage = cluster.coverage;
curr_score = cluster.score;
curr_kept = 1;
curr_count = 1;
} else {
//If this cluster is equivalent to the previous one and we already took enough
//equivalent clusters
curr_count ++;
// TODO: shouldn't we fail something for the funnel here?
// Record MAPQ implications of not extending this cluster.
unextended_clusters.push_back(cluster_num);
#ifdef debug
cerr << "Cluster " << cluster_num << " fails because we took too many identical clusters" << endl;
cerr << "Covers " << clusters[cluster_num].coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << clusters[cluster_num].score << "/" << cluster_score_cutoff << endl;
#endif
return false;
}
//Only keep this cluster if we have few enough equivalent clusters
#ifdef debug
cerr << "Cluster " << cluster_num << endl;
cerr << "Covers " << cluster.coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << cluster.score << "/" << cluster_score_cutoff << endl;
#endif
minimizer_extended_cluster_count.emplace_back(minimizers.size(), 0);
// Pack the seeds for GaplessExtender.
GaplessExtender::cluster_type seed_matchings;
for (auto seed_index : cluster.seeds) {
// Insert the (graph position, read offset) pair.
const Seed& seed = seeds[seed_index];
seed_matchings.insert(GaplessExtender::to_seed(seed.pos, minimizers[seed.source].value.offset));
minimizer_extended_cluster_count.back()[seed.source]++;
#ifdef debug
const Minimizer& minimizer = minimizers[seed.source];
cerr << "Seed read:" << minimizer.value.offset << " = " << seed.pos
<< " from minimizer " << seed.source << "(" << minimizer.hits << ")" << endl;
#endif
}
// Extend seed hits in the cluster into one or more gapless extensions
cluster_extensions.emplace_back(std::move(extender.extend(seed_matchings, aln.sequence())));
if (track_provenance) {
// Record with the funnel that the previous group became a group of this size.
// Don't bother recording the seed to extension matching...
funnel.project_group(cluster_num, cluster_extensions.back().size());
// Say we finished with this cluster, for now.
funnel.processed_input();
}
return true;
}, [&](size_t cluster_num) {
// There are too many sufficiently good clusters
Cluster& cluster = clusters[cluster_num];
if (track_provenance) {
funnel.pass("cluster-coverage", cluster_num, cluster.coverage);
funnel.fail("max-extensions", cluster_num);
}
if (cluster.coverage == curr_coverage &&
cluster.score == curr_score) {
curr_count ++;
} else {
for (size_t i = 0 ; i < curr_kept ; i++ ) {
probability_cluster_lost.push_back(1.0 - (double(curr_kept) / double(curr_count)));
}
curr_score = 0;
curr_coverage = 0;
curr_kept = 0;
curr_count = 0;
}
// Record MAPQ implications of not extending this cluster.
unextended_clusters.push_back(cluster_num);
#ifdef debug
cerr << "Cluster " << cluster_num << " passes cluster cutoffs but we have too many" << endl;
cerr << "Covers " << cluster.coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << cluster.score << "/" << cluster_score_cutoff << endl;
#endif
}, [&](size_t cluster_num) {
// This cluster is not sufficiently good.
if (track_provenance) {
funnel.fail("cluster-coverage", cluster_num, clusters[cluster_num].coverage);
}
for (size_t i = 0 ; i < curr_kept ; i++ ) {
probability_cluster_lost.push_back(1.0 - (double(curr_kept) / double(curr_count)));
}
curr_kept = 0;
curr_count = 0;
curr_score = 0;
curr_coverage = 0;
// Record MAPQ implications of not extending this cluster.
unextended_clusters.push_back(cluster_num);
#ifdef debug
cerr << "Cluster " << cluster_num << " fails cluster coverage cutoffs" << endl;
cerr << "Covers " << clusters[cluster_num].coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << clusters[cluster_num].score << "/" << cluster_score_cutoff << endl;
#endif
});
for (size_t i = 0 ; i < curr_kept ; i++ ) {
probability_cluster_lost.push_back(1.0 - (double(curr_kept) / double(curr_count)));
}
std::vector<int> cluster_extension_scores = this->score_extensions(cluster_extensions, aln, funnel);
if (track_provenance) {
funnel.stage("align");
}
//How many of each minimizer ends up in an extension set that actually gets turned into an alignment?
vector<size_t> minimizer_extensions_count(minimizers.size(), 0);
// Now start the alignment step. Everything has to become an alignment.
// We will fill this with all computed alignments in estimated score order.
vector<Alignment> alignments;
alignments.reserve(cluster_extensions.size());
// This maps from alignment index back to cluster extension index, for
// tracing back to minimizers for MAPQ. Can hold
// numeric_limits<size_t>::max() for an unaligned alignment.
vector<size_t> alignments_to_source;
alignments_to_source.reserve(cluster_extensions.size());
//probability_cluster_lost but ordered by alignment
vector<double> probability_alignment_lost;
probability_alignment_lost.reserve(cluster_extensions.size());
// Create a new alignment object to get rid of old annotations.
{
Alignment temp;
temp.set_sequence(aln.sequence());
temp.set_name(aln.name());
temp.set_quality(aln.quality());
aln = std::move(temp);
}
// Annotate the read with metadata
if (!sample_name.empty()) {
aln.set_sample_name(sample_name);
}
if (!read_group.empty()) {
aln.set_read_group(read_group);
}
// Go through the gapless extension groups in score order.
process_until_threshold_b(cluster_extensions, cluster_extension_scores,
extension_set_score_threshold, 2, max_alignments,
[&](size_t extension_num) {
// This extension set is good enough.
// Called in descending score order.
if (track_provenance) {
funnel.pass("extension-set", extension_num, cluster_extension_scores[extension_num]);
funnel.pass("max-alignments", extension_num);
funnel.processing_input(extension_num);
}
auto& extensions = cluster_extensions[extension_num];
// Get an Alignments best_ and second_best_alignment of it somehow, and throw it in.
Alignment best_alignment = aln;
Alignment second_best_alignment = aln;
// Determine if we got full-length alignments or local alignments.
bool full_length_extensions = (extensions.size() <= 2);
for (auto& extension : extensions) {
full_length_extensions &= extension.full();
}
if (full_length_extensions) {
// We got full-length extensions, so directly convert to an Alignment.
if (track_provenance) {
funnel.substage("direct");
}
//Fill in the best alignments from the extension
this->extension_to_alignment(extensions.front(), best_alignment);
if (extensions.size() > 1) {
//Do the same thing for the second extension, if one exists
this->extension_to_alignment(extensions.back(), second_best_alignment);
}
if (track_provenance) {
// Stop the current substage
funnel.substage_stop();
}
} else if (do_dp) {
// We need to do chaining.
if (track_provenance) {
funnel.substage("chain");
}
// Do the DP and compute alignment into best_alignment and
// second_best_extension, if there is a second best
find_optimal_tail_alignments(aln, extensions, best_alignment, second_best_alignment);
if (track_provenance) {
// We're done chaining. Next alignment may not go through this substage.
funnel.substage_stop();
}
} else {
// We would do chaining but it is disabled.
// Leave best_alignment unaligned
}
if (second_best_alignment.score() != 0 &&
second_best_alignment.score() > best_alignment.score() * 0.8) {
//If there is a second extension and its score is at least half of the best score, bring it along
#ifdef debug
cerr << "Found second best alignment from gapless extension " << extension_num << ": " << pb2json(second_best_alignment) << endl;
#endif
alignments.emplace_back(std::move(second_best_alignment));
alignments_to_source.push_back(extension_num);
probability_alignment_lost.push_back(probability_cluster_lost[extension_num]);
if (track_provenance) {
funnel.project(extension_num);
funnel.score(alignments.size() - 1, alignments.back().score());
// We're done with this input item
funnel.processed_input();
}
}
#ifdef debug
cerr << "Found best alignment from gapless extension " << extension_num << ": " << pb2json(best_alignment) << endl;
#endif
alignments.push_back(std::move(best_alignment));
alignments_to_source.push_back(extension_num);
probability_alignment_lost.push_back(probability_cluster_lost[extension_num]);
if (track_provenance) {
funnel.project(extension_num);
funnel.score(alignments.size() - 1, alignments.back().score());
// We're done with this input item
funnel.processed_input();
}
for (size_t i = 0 ; i < minimizer_extended_cluster_count[extension_num].size() ; i++) {
minimizer_extensions_count[i] += minimizer_extended_cluster_count[extension_num][i];
if (minimizer_extended_cluster_count[extension_num][i] > 0) {
// This minimizer is in an extended cluster that gave rise
// to at least one alignment, so it is explored.
minimizer_explored.insert(i);
}
}
return true;
}, [&](size_t extension_num) {
// There are too many sufficiently good extensions
if (track_provenance) {
funnel.pass("extension-set", extension_num, cluster_extension_scores[extension_num]);
funnel.fail("max-alignments", extension_num);
}
#ifdef debug
cerr << "gapless extension " << extension_num << " failed because there were too many good extensions" << endl;
#endif
}, [&](size_t extension_num) {
// This extension is not good enough.
if (track_provenance) {
funnel.fail("extension-set", extension_num, cluster_extension_scores[extension_num]);
}
#ifdef debug
cerr << "gapless extension " << extension_num << " failed because its score was not good enough (score=" << cluster_extension_scores[extension_num] << ")" << endl;
#endif
});
if (alignments.size() == 0) {
// Produce an unaligned Alignment
alignments.emplace_back(aln);
alignments_to_source.push_back(numeric_limits<size_t>::max());
probability_alignment_lost.push_back(0);
if (track_provenance) {
// Say it came from nowhere
funnel.introduce();
}
}
if (track_provenance) {
// Now say we are finding the winner(s)
funnel.stage("winner");
}
// Fill this in with the alignments we will output as mappings
vector<Alignment> mappings;
mappings.reserve(min(alignments.size(), max_multimaps));
// Track which Alignments they are
vector<size_t> mappings_to_source;
mappings_to_source.reserve(min(alignments.size(), max_multimaps));
// Grab all the scores in order for MAPQ computation.
vector<double> scores;
scores.reserve(alignments.size());
vector<double> probability_mapping_lost;
process_until_threshold_a(alignments, (std::function<double(size_t)>) [&](size_t i) -> double {
return alignments.at(i).score();
}, 0, 1, max_multimaps, [&](size_t alignment_num) {
// This alignment makes it
// Called in score order
// Remember the score at its rank
scores.emplace_back(alignments[alignment_num].score());
// Remember the output alignment
mappings.emplace_back(std::move(alignments[alignment_num]));
mappings_to_source.push_back(alignment_num);
probability_mapping_lost.push_back(probability_alignment_lost[alignment_num]);
if (track_provenance) {
// Tell the funnel
funnel.pass("max-multimaps", alignment_num);
funnel.project(alignment_num);
funnel.score(alignment_num, scores.back());
}
return true;
}, [&](size_t alignment_num) {
// We already have enough alignments, although this one has a good score
// Remember the score at its rank anyway
scores.emplace_back(alignments[alignment_num].score());
if (track_provenance) {
funnel.fail("max-multimaps", alignment_num);
}
}, [&](size_t alignment_num) {
// This alignment does not have a sufficiently good score
// Score threshold is 0; this should never happen
assert(false);
});
if (track_provenance) {
funnel.substage("mapq");
}
#ifdef debug
cerr << "Picked best alignment " << pb2json(mappings[0]) << endl;
cerr << "For scores ";
for (auto& score : scores) cerr << score << " ";
#endif
size_t winning_index;
assert(!mappings.empty());
// Compute MAPQ if not unmapped. Otherwise use 0 instead of the 50% this would give us.
double mapq = (mappings.front().path().mapping_size() == 0) ? 0 :
get_regular_aligner()->maximum_mapping_quality_exact(scores, &winning_index) / 2;
#ifdef print_minimizers
double uncapped_mapq = mapq;
#endif
#ifdef debug
cerr << "uncapped MAPQ is " << mapq << endl;
#endif
if (probability_mapping_lost.front() > 0) {
mapq = min(mapq,round(prob_to_phred(probability_mapping_lost.front())));
}
// TODO: give SmallBitset iterators so we can use it instead of an index vector.
vector<size_t> explored_minimizers;
for (size_t i = 0; i < minimizers.size(); i++) {
if (minimizer_explored.contains(i)) {
explored_minimizers.push_back(i);
}
}
// Compute caps on MAPQ. TODO: avoid needing to pass as much stuff along.
double mapq_explored_cap = 2 * faster_cap(minimizers, explored_minimizers, aln.sequence(), aln.quality());
// Remember the uncapped MAPQ and the caps
set_annotation(mappings.front(), "mapq_uncapped", mapq);
set_annotation(mappings.front(), "mapq_explored_cap", mapq_explored_cap);
// Apply the caps and transformations
mapq = round(0.85 * min(mapq_explored_cap, min(mapq, 70.0)));
#ifdef debug
cerr << "Explored cap is " << mapq_explored_cap << endl;
cerr << "MAPQ is " << mapq << endl;
#endif
// Make sure to clamp 0-60.
mappings.front().set_mapping_quality(max(min(mapq, 60.0), 0.0));
if (track_provenance) {
funnel.substage_stop();
}
for (size_t i = 0; i < mappings.size(); i++) {
// For each output alignment in score order
auto& out = mappings[i];
// Assign primary and secondary status
out.set_is_secondary(i > 0);
}
// Stop this alignment
funnel.stop();
if (track_provenance) {
// Annotate with the number of results in play at each stage
funnel.for_each_stage([&](const string& stage, const vector<size_t>& result_sizes) {
// Save the number of items
set_annotation(mappings[0], "stage_" + stage + "_results", (double)result_sizes.size());
});
if (track_correctness) {
// And with the last stage at which we had any descendants of the correct seed hit locations
set_annotation(mappings[0], "last_correct_stage", funnel.last_correct_stage());
}
// Annotate with the performances of all the filters
// We need to track filter number
size_t filter_num = 0;
funnel.for_each_filter([&](const string& stage, const string& filter,
const Funnel::FilterPerformance& by_count, const Funnel::FilterPerformance& by_size,
const vector<double>& filter_statistics_correct, const vector<double>& filter_statistics_non_correct) {
string filter_id = to_string(filter_num) + "_" + filter + "_" + stage;
// Save the stats
set_annotation(mappings[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(mappings[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(mappings[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(mappings[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(mappings[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(mappings[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(mappings[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(mappings[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(mappings[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(mappings[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
filter_num++;
});
// Annotate with parameters used for the filters.
set_annotation(mappings[0], "param_hit-cap", (double) hit_cap);
set_annotation(mappings[0], "param_hard-hit-cap", (double) hard_hit_cap);
set_annotation(mappings[0], "param_score-fraction", (double) minimizer_score_fraction);
set_annotation(mappings[0], "param_max-extensions", (double) max_extensions);
set_annotation(mappings[0], "param_max-alignments", (double) max_alignments);
set_annotation(mappings[0], "param_cluster-score", (double) cluster_score_threshold);
set_annotation(mappings[0], "param_cluster-coverage", (double) cluster_coverage_threshold);
set_annotation(mappings[0], "param_extension-set", (double) extension_set_score_threshold);
set_annotation(mappings[0], "param_max-multimaps", (double) max_multimaps);
}
#ifdef print_minimizers
cerr << aln.sequence() << "\t";
for (char c : aln.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << clusters.size();
for (size_t i = 0 ; i < minimizers.size() ; i++) {
auto& minimizer = minimizers[i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_extensions_count[i];
if (minimizer_extensions_count[i]>0) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << uncapped_mapq << "\t" << mapq_explored_cap << "\t" << probability_mapping_lost.front() << "\t" << mappings.front().mapping_quality();
if (track_correctness) {
cerr << "\t" << funnel.last_correct_stage() << endl;
} else {
cerr << "\t" << "?" << endl;
}
#endif
#ifdef debug
// Dump the funnel info graph.
funnel.to_dot(cerr);
#endif
return mappings;
}
//-----------------------------------------------------------------------------
pair<vector<Alignment>, vector<Alignment>> MinimizerMapper::map_paired(Alignment& aln1, Alignment& aln2,
vector<pair<Alignment, Alignment>>& ambiguous_pair_buffer){
if (fragment_length_distr.is_finalized()) {
//If we know the fragment length distribution then we just map paired ended
return map_paired(aln1, aln2);
} else {
//If we don't know the fragment length distribution, map the reads single ended
vector<Alignment> alns1(map(aln1));
vector<Alignment> alns2(map(aln2));
// Check if the separately-mapped ends are both sufficiently perfect and sufficiently unique
int32_t max_score_aln_1 = get_regular_aligner()->score_exact_match(aln1, 0, aln1.sequence().size());
int32_t max_score_aln_2 = get_regular_aligner()->score_exact_match(aln2, 0, aln2.sequence().size());
if (!alns1.empty() && ! alns2.empty() &&
alns1.front().mapping_quality() == 60 && alns2.front().mapping_quality() == 60 &&
alns1.front().score() >= max_score_aln_1 * 0.85 && alns2.front().score() >= max_score_aln_2 * 0.85) {
//Flip the second alignment to get the proper fragment distance
reverse_complement_alignment_in_place(&alns2.front(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
int64_t dist = distance_between(alns1.front(), alns2.front());
// And that they have an actual pair distance and set of relative orientations
if (dist == std::numeric_limits<int64_t>::max()) {
//If the distance between them is ambiguous, leave them unmapped
ambiguous_pair_buffer.emplace_back(aln1, aln2);
pair<vector<Alignment>, vector<Alignment>> empty;
return empty;
}
//If we're keeping this alignment, flip the second alignment back
reverse_complement_alignment_in_place(&alns2.front(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
// If that all checks out, say they're mapped, emit them, and register their distance and orientations
fragment_length_distr.register_fragment_length(dist);
pair<vector<Alignment>, vector<Alignment>> mapped_pair;
mapped_pair.first.emplace_back(alns1.front());
mapped_pair.second.emplace_back(alns2.front());
return mapped_pair;
} else {
// Otherwise, discard the mappings and put them in the ambiguous buffer
ambiguous_pair_buffer.emplace_back(aln1, aln2);
pair<vector<Alignment>, vector<Alignment>> empty;
return empty;
}
}
}
pair<vector<Alignment>, vector< Alignment>> MinimizerMapper::map_paired(Alignment& aln1, Alignment& aln2) {
// For each input alignment
#ifdef debug
cerr << "Read pair " << aln1.name() << ": " << aln1.sequence() << " and " << aln2.name() << ": " << aln2.sequence() << endl;
#endif
// Assume reads are in inward orientations on input, and
// convert to rightward orientations before mapping
// and flip the second read back before output
aln2.clear_path();
reverse_complement_alignment_in_place(&aln2, [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
// Make two new funnel instrumenters to watch us map this read pair.
vector<Funnel> funnels;
funnels.resize(2);
// Start this alignment
funnels[0].start(aln1.name());
funnels[1].start(aln2.name());
// Annotate the original read with metadata
if (!sample_name.empty()) {
aln1.set_sample_name(sample_name);
aln2.set_sample_name(sample_name);
}
if (!read_group.empty()) {
aln1.set_read_group(read_group);
aln2.set_read_group(read_group);
}
// Minimizers for both reads, sorted by score in descending order.
std::vector<std::vector<Minimizer>> minimizers_by_read(2);
minimizers_by_read[0] = this->find_minimizers(aln1.sequence(), funnels[0]);
minimizers_by_read[1] = this->find_minimizers(aln2.sequence(), funnels[1]);
// Seeds for both reads, stored in separate vectors.
std::vector<std::vector<Seed>> seeds_by_read(2);
seeds_by_read[0] = this->find_seeds(minimizers_by_read[0], aln1, funnels[0]);
seeds_by_read[1] = this->find_seeds(minimizers_by_read[1], aln2, funnels[1]);
// Cluster the seeds. Get sets of input seed indexes that go together.
// If the fragment length distribution hasn't been fixed yet (if the expected fragment length = 0),
// then everything will be in the same cluster and the best pair will be the two best independent mappings
if (track_provenance) {
funnels[0].stage("cluster");
funnels[1].stage("cluster");
}
std::vector<std::vector<Cluster>> all_clusters = clusterer.cluster_seeds(seeds_by_read, get_distance_limit(aln1.sequence().size()),
fragment_length_distr.mean() + paired_distance_stdevs * fragment_length_distr.std_dev());
//For each fragment cluster, determine if it has clusters from both reads
size_t max_fragment_num = 0;
for (auto& cluster : all_clusters[0]) {
max_fragment_num = std::max(max_fragment_num, cluster.fragment);
}
for (auto& cluster : all_clusters[1]) {
max_fragment_num = std::max(max_fragment_num, cluster.fragment);
}
#ifdef debug
cerr << "Found " << max_fragment_num << " fragment clusters" << endl;
#endif
vector<bool> has_first_read (max_fragment_num+1, false);//For each fragment cluster, does it have a cluster for the first read
vector<bool> fragment_cluster_has_pair (max_fragment_num+1, false);//Does a fragment cluster have both reads
bool found_paired_cluster = false;
for (auto& cluster : all_clusters[0]) {
size_t fragment_num = cluster.fragment;
has_first_read[fragment_num] = true;
}
for (auto& cluster : all_clusters[1]) {
size_t fragment_num = cluster.fragment;
fragment_cluster_has_pair[fragment_num] = has_first_read[fragment_num];
if (has_first_read[fragment_num]) {
found_paired_cluster = true;
#ifdef debug
cerr << "Fragment cluster " << fragment_num << " has read clusters from both reads" << endl;
#endif
}
}
if (track_provenance) {
funnels[0].substage("score");
funnels[1].substage("score");
}
//For each fragment cluster (cluster of clusters), for each read, a vector of all alignments + the order they were fed into the funnel
//so the funnel can track them
vector<pair<vector<Alignment>, vector<Alignment>>> alignments;
vector<pair<vector<size_t>, vector<size_t>>> alignment_indices;
pair<int, int> best_alignment_scores (0, 0); // The best alignment score for each end
//Keep track of the best cluster score and coverage per end for each fragment cluster
pair<vector<double>, vector<double>> cluster_score_by_fragment;
cluster_score_by_fragment.first.resize(max_fragment_num + 1, 0.0);
cluster_score_by_fragment.second.resize(max_fragment_num + 1, 0.0);
pair<vector<double>, vector<double>> cluster_coverage_by_fragment;
cluster_coverage_by_fragment.first.resize(max_fragment_num + 1, 0.0);
cluster_coverage_by_fragment.second.resize(max_fragment_num + 1, 0.0);
for (size_t read_num = 0 ; read_num < 2 ; read_num++) {
Alignment& aln = read_num == 0 ? aln1 : aln2;
std::vector<Cluster>& clusters = all_clusters[read_num];
std::vector<Minimizer>& minimizers = minimizers_by_read[read_num];
std::vector<Seed>& seeds = seeds_by_read[read_num];
vector<double>& best_cluster_score = read_num == 0 ? cluster_score_by_fragment.first : cluster_score_by_fragment.second;
vector<double>& best_cluster_coverage = read_num == 0 ? cluster_coverage_by_fragment.first : cluster_coverage_by_fragment.second;
for (size_t i = 0; i < clusters.size(); i++) {
// Deterimine cluster score and read coverage.
Cluster& cluster = clusters[i];
this->score_cluster(cluster, i, minimizers, seeds, aln.sequence().length(), funnels[read_num]);
size_t fragment = cluster.fragment;
best_cluster_score[fragment] = std::max(best_cluster_score[fragment], cluster.score);
best_cluster_coverage[fragment] = std::max(best_cluster_coverage[fragment], cluster.coverage);
}
}
//For each fragment cluster, we want to know how many equivalent or better clusters we found
vector<size_t> fragment_cluster_indices_by_score (max_fragment_num + 1);
for (size_t i = 0 ; i < fragment_cluster_indices_by_score.size() ; i++) {
fragment_cluster_indices_by_score[i] = i;
}
std::sort(fragment_cluster_indices_by_score.begin(), fragment_cluster_indices_by_score.end(), [&](size_t a, size_t b) {
return cluster_coverage_by_fragment.first[a] + cluster_coverage_by_fragment.second[a] + cluster_score_by_fragment.first[a] + cluster_score_by_fragment.second[a]
> cluster_coverage_by_fragment.first[b] + cluster_coverage_by_fragment.second[b] + cluster_score_by_fragment.first[b] + cluster_score_by_fragment.second[b];
});
vector<size_t> better_cluster_count (max_fragment_num+1); // How many fragment clusters are at least as good as the one at each index
for (int j = fragment_cluster_indices_by_score.size() - 1 ; j >= 0 ; j--) {
size_t i = fragment_cluster_indices_by_score[j];
if (j == fragment_cluster_indices_by_score.size()-1) {
better_cluster_count[i] = j;
} else {
size_t i2 = fragment_cluster_indices_by_score[j+1];
if(cluster_coverage_by_fragment.first[i] + cluster_coverage_by_fragment.second[i] + cluster_score_by_fragment.first[i] + cluster_score_by_fragment.second[i]
== cluster_coverage_by_fragment.first[i2] + cluster_coverage_by_fragment.second[i2] + cluster_score_by_fragment.first[i2] + cluster_score_by_fragment.second[i2]) {
better_cluster_count[i] = better_cluster_count[i2];
} else {
better_cluster_count[i] = j;
}
}
}
// We track unextended clusters.
vector<vector<size_t>> unextended_clusters_by_read(2);
// To compute the windows that are explored, we need to get
// all the minimizers that are explored.
vector<SmallBitset> minimizer_explored_by_read(2);
vector<vector<size_t>> minimizer_aligned_count_by_read(2);
//How many hits of each minimizer ended up in each extended cluster?
vector<vector<vector<size_t>>> minimizer_extended_cluster_count_by_read(2);
//Now that we've scored each of the clusters, extend and align them
for (size_t read_num = 0 ; read_num < 2 ; read_num++) {
Alignment& aln = read_num == 0 ? aln1 : aln2;
std::vector<Cluster>& clusters = all_clusters[read_num];
std::vector<Minimizer>& minimizers = minimizers_by_read[read_num];
std::vector<Seed>& seeds = seeds_by_read[read_num];
#ifdef debug
cerr << "Found " << clusters.size() << " clusters for read " << read_num << endl;
#endif
// Retain clusters only if their score is better than this, in addition to the coverage cutoff
double cluster_score_cutoff = 0.0, cluster_coverage_cutoff = 0.0;
for (auto& cluster : clusters) {
cluster_score_cutoff = std::max(cluster_score_cutoff, cluster.score);
cluster_coverage_cutoff = std::max(cluster_coverage_cutoff, cluster.coverage);
}
cluster_score_cutoff -= cluster_score_threshold;
cluster_coverage_cutoff -= cluster_coverage_threshold;
if (track_provenance) {
// Now we go from clusters to gapless extensions
funnels[read_num].stage("extend");
}
// These are the GaplessExtensions for all the clusters (and fragment cluster assignments), in cluster_indexes_in_order order.
vector<pair<vector<GaplessExtension>, size_t>> cluster_extensions;
cluster_extensions.reserve(clusters.size());
//TODO: Maybe put this back
//For each cluster, what fraction of "equivalent" clusters did we keep?
//vector<vector<double>> probability_cluster_lost;
//What is the score and coverage we are considering and how many reads
//size_t curr_coverage = 0;
//size_t curr_score = 0;
//size_t curr_kept = 0;
//size_t curr_count = 0;
unextended_clusters_by_read[read_num].reserve(clusters.size());
minimizer_explored_by_read[read_num] = SmallBitset(minimizers.size());
minimizer_aligned_count_by_read[read_num].resize(minimizers.size(), 0);
//Process clusters sorted by both score and read coverage
process_until_threshold_c<Cluster, double>(clusters, [&](size_t i) -> double {
return clusters[i].coverage;
}, [&](size_t a, size_t b) -> bool {
//Sort clusters first by whether it was paired, then by the best coverage and score of any pair in the fragment cluster,
//then by its coverage and score
size_t fragment_a = clusters[a].fragment;
size_t fragment_b = clusters[b].fragment;
double coverage_a = cluster_coverage_by_fragment.first[fragment_a]+cluster_coverage_by_fragment.second[fragment_a];
double coverage_b = cluster_coverage_by_fragment.first[fragment_b]+cluster_coverage_by_fragment.second[fragment_b];
double score_a = cluster_score_by_fragment.first[fragment_a]+cluster_score_by_fragment.second[fragment_a];
double score_b = cluster_score_by_fragment.first[fragment_b]+cluster_score_by_fragment.second[fragment_b];
if (fragment_cluster_has_pair[fragment_a] != fragment_cluster_has_pair[fragment_b]) {
return fragment_cluster_has_pair[fragment_a];
} else if (coverage_a != coverage_b){
return coverage_a > coverage_b;
} else if (score_a != score_b) {
return score_a > score_b;
} else if (clusters[a].coverage != clusters[b].coverage){
return clusters[a].coverage > clusters[b].coverage;
} else {
return clusters[a].score > clusters[b].score;
}
},
0, 1, max_extensions,
[&](size_t cluster_num) {
// Handle sufficiently good clusters
Cluster& cluster = clusters[cluster_num];
if (!found_paired_cluster || fragment_cluster_has_pair[cluster.fragment] ||
(cluster.coverage == cluster_coverage_cutoff + cluster_coverage_threshold &&
cluster.score == cluster_score_cutoff + cluster_score_threshold)) {
//If this cluster has a pair or if we aren't looking at pairs
//Or if it is the best cluster
// First check against the additional score filter
if (cluster_coverage_threshold != 0 && cluster.coverage < cluster_coverage_cutoff) {
//If the score isn't good enough, ignore this cluster
if (track_provenance) {
funnels[read_num].fail("cluster-coverage", cluster_num, cluster.coverage);
}
unextended_clusters_by_read[read_num].push_back(cluster_num);
return false;
}
if (cluster_score_threshold != 0 && cluster.score < cluster_score_cutoff) {
//If the score isn't good enough, ignore this cluster
if (track_provenance) {
funnels[read_num].pass("cluster-coverage", cluster_num, cluster.coverage);
funnels[read_num].pass("max-extensions", cluster_num);
funnels[read_num].fail("cluster-score", cluster_num, cluster.score);
}
unextended_clusters_by_read[read_num].push_back(cluster_num);
return false;
}
if (track_provenance) {
funnels[read_num].pass("cluster-coverage", cluster_num, cluster.coverage);
funnels[read_num].pass("max-extensions", cluster_num);
funnels[read_num].pass("cluster-score", cluster_num, cluster.score);
funnels[read_num].pass("paired-clusters", cluster_num);
funnels[read_num].processing_input(cluster_num);
}
#ifdef debug
cerr << "Cluster " << cluster_num << endl;
#endif
//Count how many of each minimizer is in each cluster extension
minimizer_extended_cluster_count_by_read[read_num].emplace_back(minimizers.size(), 0);
// Pack the seeds for GaplessExtender.
GaplessExtender::cluster_type seed_matchings;
for (auto seed_index : cluster.seeds) {
// Insert the (graph position, read offset) pair.
const Seed& seed = seeds[seed_index];
seed_matchings.insert(GaplessExtender::to_seed(seed.pos, minimizers[seed.source].value.offset));
minimizer_extended_cluster_count_by_read[read_num].back()[seed.source]++;
#ifdef debug
cerr << "Seed read:" << minimizers[seed.source].value.offset << " = " << seed.pos
<< " from minimizer " << seed.source << endl;
#endif
}
// Extend seed hits in the cluster into one or more gapless extensions
cluster_extensions.emplace_back(std::move(extender.extend(seed_matchings, aln.sequence())),
cluster.fragment);
if (track_provenance) {
// Record with the funnel that the previous group became a group of this size.
// Don't bother recording the seed to extension matching...
funnels[read_num].project_group(cluster_num, cluster_extensions.back().first.size());
// Say we finished with this cluster, for now.
funnels[read_num].processed_input();
}
return true;
} else {
//We were looking for clusters in a paired fragment cluster but this one doesn't have any on the other end
if (track_provenance) {
funnels[read_num].pass("cluster-coverage", cluster_num, cluster.coverage);
funnels[read_num].pass("max-extensions", cluster_num);
funnels[read_num].pass("cluster-score", cluster_num, cluster.score);
funnels[read_num].fail("paired-clusters", cluster_num);
}
unextended_clusters_by_read[read_num].push_back(cluster_num);
return false;
}
}, [&](size_t cluster_num) {
// There are too many sufficiently good clusters
if (track_provenance) {
funnels[read_num].pass("cluster-coverage", cluster_num, clusters[cluster_num].coverage);
funnels[read_num].fail("max-extensions", cluster_num);
}
unextended_clusters_by_read[read_num].push_back(cluster_num);
}, [&](size_t cluster_num) {
// This cluster is not sufficiently good.
// TODO: I don't think it should ever get here unless we limit the scores of the fragment clusters we look at
unextended_clusters_by_read[read_num].push_back(cluster_num);
});
// We now estimate the best possible alignment score for each cluster.
std::vector<int> cluster_extension_scores = this->score_extensions(cluster_extensions, aln, funnels[read_num]);
if (track_provenance) {
funnels[read_num].stage("align");
}
// Now start the alignment step. Everything has to become an alignment.
// We will fill this with all computed alignments in estimated score order.
alignments.resize(max_fragment_num + 2);
alignment_indices.resize(max_fragment_num + 2);
// Clear any old refpos annotation and path
aln.clear_refpos();
aln.clear_path();
aln.set_score(0);
aln.set_identity(0);
aln.set_mapping_quality(0);
//Since we will lose the order in which we pass alignments to the funnel, use this to keep track
size_t curr_funnel_index = 0;
// Go through the gapless extension groups in score order.
process_until_threshold_b(cluster_extensions, cluster_extension_scores,
extension_set_score_threshold, 2, max_alignments,
[&](size_t extension_num) {
// This extension set is good enough.
// Called in descending score order.
if (track_provenance) {
funnels[read_num].pass("extension-set", extension_num, cluster_extension_scores[extension_num]);
funnels[read_num].pass("max-alignments", extension_num);
funnels[read_num].processing_input(extension_num);
}
auto& extensions = cluster_extensions[extension_num].first;
// Get an Alignments best_ and second_best_alignment of it somehow, and throw it in.
Alignment best_alignment = aln;
Alignment second_best_alignment = aln;
// Determine if we got full-length alignments or local alignments.
bool full_length_extensions = (extensions.size() <= 2);
for (auto& extension : extensions) {
full_length_extensions &= extension.full();
}
if (full_length_extensions) {
// We got full-length extensions, so directly convert to an Alignment.
if (track_provenance) {
funnels[read_num].substage("direct");
}
//Fill in the best alignments from the extension
this->extension_to_alignment(extensions.front(), best_alignment);
if (extensions.size() > 1) {
//Do the same thing for the second extension, if one exists
this->extension_to_alignment(extensions.back(), second_best_alignment);
}
if (track_provenance) {
// Stop the current substage
funnels[read_num].substage_stop();
}
} else if (do_dp) {
// We need to do chaining.
if (track_provenance) {
funnels[read_num].substage("chain");
}
// Do the DP and compute alignment into best_alignment and
// second_best_alignment, if there is a second best
find_optimal_tail_alignments(aln, extensions, best_alignment, second_best_alignment);
if (track_provenance) {
// We're done chaining. Next alignment may not go through this substage.
funnels[read_num].substage_stop();
}
} else {
// We would do chaining but it is disabled.
// Leave best_alignment unaligned
}
size_t fragment_num = cluster_extensions[extension_num].second;
if (second_best_alignment.score() != 0 &&
second_best_alignment.score() > best_alignment.score() * 0.8) {
//If there is a second extension and its score is at least half of the best score
read_num == 0 ? best_alignment_scores.first = max(best_alignment_scores.first, second_best_alignment.score())
: best_alignment_scores.second = max(best_alignment_scores.second, second_best_alignment.score());
read_num == 0 ? alignments[fragment_num ].first.emplace_back(std::move(second_best_alignment) ) :
alignments[fragment_num ].second.emplace_back(std::move(second_best_alignment));
read_num == 0 ? alignment_indices[fragment_num].first.emplace_back(curr_funnel_index)
: alignment_indices[fragment_num].second.emplace_back(curr_funnel_index);
curr_funnel_index++;
if (track_provenance) {
funnels[read_num].project(extension_num);
read_num == 0 ? funnels[read_num].score(extension_num, alignments[fragment_num ].first.back().score()) :
funnels[read_num].score(extension_num, alignments[fragment_num].second.back().score());
}
}
read_num == 0 ? best_alignment_scores.first = max(best_alignment_scores.first, best_alignment.score())
: best_alignment_scores.second = max(best_alignment_scores.second, best_alignment.score());
read_num == 0 ? alignments[fragment_num].first.emplace_back(std::move(best_alignment))
: alignments[fragment_num].second.emplace_back(std::move(best_alignment));
read_num == 0 ? alignment_indices[fragment_num].first.emplace_back(curr_funnel_index)
: alignment_indices[fragment_num].second.emplace_back(curr_funnel_index);
curr_funnel_index++;
if (track_provenance) {
funnels[read_num].project(extension_num);
read_num == 0 ? funnels[read_num].score(extension_num, alignments[fragment_num].first.back().score())
: funnels[read_num].score(extension_num, alignments[fragment_num].second.back().score());
// We're done with this input item
funnels[read_num].processed_input();
}
for (size_t i = 0 ; i < minimizer_extended_cluster_count_by_read[read_num][extension_num].size() ; i++) {
if (minimizer_extended_cluster_count_by_read[read_num][extension_num][i] > 0) {
// This minimizer is in an extended cluster that gave rise
// to at least one alignment, so it is explored.
minimizer_explored_by_read[read_num].insert(i);
minimizer_aligned_count_by_read[read_num][i] += minimizer_extended_cluster_count_by_read[read_num][extension_num][i];
}
}
return true;
}, [&](size_t extension_num) {
// There are too many sufficiently good extensions
if (track_provenance) {
funnels[read_num].pass("extension-set", extension_num, cluster_extension_scores[extension_num]);
funnels[read_num].fail("max-alignments", extension_num);
}
}, [&](size_t extension_num) {
// This extension is not good enough.
if (track_provenance) {
funnels[read_num].fail("extension-set", extension_num, cluster_extension_scores[extension_num]);
}
});
}
if (track_provenance) {
// Now say we are finding the winner(s)
funnels[0].stage("pairing");
funnels[1].stage("pairing");
}
// Fill this in with the pairs of alignments we will output
// each alignment is stored as <fragment index, alignment index> into alignments
vector<pair<pair<size_t, size_t>, pair<size_t, size_t>>> paired_alignments;
paired_alignments.reserve(alignments.size());
#ifdef print_minimizers
vector<pair<bool, bool>> alignment_was_rescued;
#endif
//For each alignment in alignments, which paired_alignment includes it. Follows structure of alignments
vector<pair<vector<vector<size_t>>, vector<vector<size_t>>>> alignment_groups(alignments.size());
// Grab all the scores in order for MAPQ computation.
vector<double> paired_scores;
paired_scores.reserve(alignments.size());
vector<int64_t> fragment_distances;
fragment_distances.reserve(alignments.size());
//For each fragment cluster, get the fraction of equivalent or better clusters that got thrown away
vector<size_t> better_cluster_count_alignment_pairs;
better_cluster_count_alignment_pairs.reserve(alignments.size());
//Keep track of alignments with no pairs in the same fragment cluster
bool found_pair = false;
//Alignments that don't have a mate
// <fragment index, alignment_index, true if its the first end>
vector<tuple<size_t, size_t, bool>> unpaired_alignments;
size_t unpaired_count_1 = 0;
size_t unpaired_count_2 = 0;
for (size_t fragment_num = 0 ; fragment_num < alignments.size() ; fragment_num ++ ) {
//Get pairs of plausible alignments
alignment_groups[fragment_num].first.resize(alignments[fragment_num].first.size());
alignment_groups[fragment_num].second.resize(alignments[fragment_num].second.size());
pair<vector<Alignment>, vector<Alignment>>& fragment_alignments = alignments[fragment_num];
if (!fragment_alignments.first.empty() && ! fragment_alignments.second.empty()) {
//Only keep pairs of alignments that were in the same fragment cluster
found_pair = true;
for (size_t i1 = 0 ; i1 < fragment_alignments.first.size() ; i1++) {
Alignment& alignment1 = fragment_alignments.first[i1];
size_t j1 = alignment_indices[fragment_num].first[i1];
for (size_t i2 = 0 ; i2 < fragment_alignments.second.size() ; i2++) {
Alignment& alignment2 = fragment_alignments.second[i2];
size_t j2 = alignment_indices[fragment_num].second[i2];
//Get the likelihood of the fragment distance
int64_t fragment_distance = distance_between(alignment1, alignment2);
double dev = fragment_distance - fragment_length_distr.mean();
double fragment_length_log_likelihood = -dev * dev / (2.0 * fragment_length_distr.std_dev() * fragment_length_distr.std_dev());
if (fragment_distance != std::numeric_limits<int64_t>::max() ) {
double score = alignment1.score() + alignment2.score() + (fragment_length_log_likelihood / get_aligner()->log_base);
alignment_groups[fragment_num].first[i1].emplace_back(paired_alignments.size());
alignment_groups[fragment_num].second[i2].emplace_back(paired_alignments.size());
paired_alignments.emplace_back(make_pair(fragment_num, i1), make_pair(fragment_num, i2));
paired_scores.emplace_back(score);
fragment_distances.emplace_back(fragment_distance);
better_cluster_count_alignment_pairs.emplace_back(better_cluster_count[fragment_num]);
#ifdef print_minimizers
alignment_was_rescued.emplace_back(false, false);
#endif
#ifdef debug
cerr << "Found pair of alignments from fragment " << fragment_num << " with scores "
<< alignment1.score() << " " << alignment2.score() << " at distance " << fragment_distance
<< " gets pair score " << score << endl;
cerr << "Alignment 1: " << pb2json(alignment1) << endl << "Alignment 2: " << pb2json(alignment2) << endl;
#endif
}
if (track_provenance) {
funnels[0].processing_input(j1);
funnels[1].processing_input(j2);
funnels[0].substage("pair-clusters");
funnels[1].substage("pair-clusters");
funnels[0].pass("max-rescue-attempts", j1);
funnels[0].project(j1);
funnels[1].pass("max-rescue-attempts", j2);
funnels[1].project(j2);
funnels[0].substage_stop();
funnels[1].substage_stop();
funnels[0].processed_input();
funnels[1].processed_input();
}
}
}
} else if (!fragment_alignments.first.empty()) {
#ifdef debug
cerr << "Found unpaired alignments from fragment " << fragment_num << " for first read" << endl;
#endif
for (size_t i = 0 ; i < fragment_alignments.first.size() ; i++) {
unpaired_alignments.emplace_back(fragment_num, i, true);
unpaired_count_1++;
#ifdef debug
cerr << "\t" << pb2json(fragment_alignments.first[i]) << endl;
#endif
}
} else if (!fragment_alignments.second.empty()) {
#ifdef debug
cerr << "Found unpaired alignments from fragment " << fragment_num << " for second read" << endl;
#endif
for (size_t i = 0 ; i < fragment_alignments.second.size() ; i++) {
unpaired_alignments.emplace_back(fragment_num, i, false);
unpaired_count_2++;
#ifdef debug
cerr << "\t" << pb2json(fragment_alignments.second[i]) << endl;
#endif
}
}
}
size_t rescued_count_1 = 0;
size_t rescued_count_2 = 0;
vector<bool> rescued_from;
if (!unpaired_alignments.empty()) {
//If we found some clusters that don't belong to a fragment cluster
if (!found_pair && max_rescue_attempts == 0 ) {
//If we didn't find any pairs and we aren't attempting rescue, just return the best for each end
#ifdef debug
cerr << "Found no pairs and we aren't doing rescue: return best alignment for each read" << endl;
#endif
Alignment& best_aln1 = aln1;
Alignment& best_aln2 = aln2;
best_aln1.clear_refpos();
best_aln1.clear_path();
best_aln1.set_score(0);
best_aln1.set_identity(0);
best_aln1.set_mapping_quality(0);
best_aln2.clear_refpos();
best_aln2.clear_path();
best_aln2.set_score(0);
best_aln2.set_identity(0);
best_aln2.set_mapping_quality(0);
for (tuple<size_t, size_t, bool> index : unpaired_alignments ) {
Alignment& alignment = std::get<2>(index) ? alignments[std::get<0>(index)].first[std::get<1>(index)]
: alignments[std::get<0>(index)].second[std::get<1>(index)];
if (std::get<2>(index)) {
if (alignment.score() > best_aln1.score()) {
best_aln1 = alignment;
}
} else {
if (alignment.score() > best_aln2.score()) {
best_aln2 = alignment;
}
}
}
set_annotation(best_aln1, "unpaired", true);
set_annotation(best_aln2, "unpaired", true);
pair<vector<Alignment>, vector<Alignment>> paired_mappings;
paired_mappings.first.emplace_back(std::move(best_aln1));
paired_mappings.second.emplace_back(std::move(best_aln2));
// Flip aln2 back to input orientation
reverse_complement_alignment_in_place(&paired_mappings.second.back(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
paired_mappings.first.back().set_mapping_quality(1);
paired_mappings.second.back().set_mapping_quality(1);
// Stop this alignment
funnels[0].stop();
funnels[1].stop();
if (track_provenance) {
// Annotate with the number of results in play at each stage
for (size_t read_num = 0 ; read_num < 2 ; read_num++) {
funnels[read_num].for_each_stage([&](const string& stage, const vector<size_t>& result_sizes) {
// Save the number of items
set_annotation(read_num == 0 ? paired_mappings.first[0] : paired_mappings.second[0], "stage_" + stage + "_results", (double)result_sizes.size());
});
if (track_correctness) {
// And with the last stage at which we had any descendants of the correct seed hit locations
set_annotation(read_num == 0 ? paired_mappings.first[0] : paired_mappings.second[0], "last_correct_stage", funnels[read_num].last_correct_stage());
}
// Annotate with the performances of all the filters
// We need to track filter number
size_t filter_num = 0;
funnels[read_num].for_each_filter([&](const string& stage, const string& filter,
const Funnel::FilterPerformance& by_count, const Funnel::FilterPerformance& by_size,
const vector<double>& filter_statistics_correct, const vector<double>& filter_statistics_non_correct) {
string filter_id = to_string(filter_num) + "_" + filter + "_" + stage;
if (read_num == 0) {
// Save the stats
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(paired_mappings.first[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(paired_mappings.first[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
} else {
// Save the stats
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(paired_mappings.second[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(paired_mappings.second[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
}
filter_num++;
});
}
}
#ifdef print_minimizers
cerr << aln1.sequence() << "\t";
for (char c : aln1.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << max_fragment_num << "\t" << 0 << "\t" << 0 << "\t?";
for (size_t i = 0 ; i < minimizers_by_read[0].size() ; i++) {
auto& minimizer = minimizers_by_read[0][i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_aligned_count_by_read[0][i];
if (minimizer_aligned_count_by_read[0][i] > 0) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << 1 << "\t" << 1 << "\t" << 1 << "\t" << 1;
if (track_correctness) {
cerr << "\t" << funnels[0].last_correct_stage() << endl;
} else {
cerr << "\t?" << endl;
}
cerr << aln2.sequence() << "\t";
for (char c : aln2.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << max_fragment_num << "\t" << 0 << "\t" << 0 << "\t?";
for (size_t i = 0 ; i < minimizers_by_read[1].size() ; i++) {
auto& minimizer = minimizers_by_read[1][i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_aligned_count_by_read[1][i];
if (minimizer_aligned_count_by_read[1][i] > 0) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << 1 << "\t" << 1 << "\t" << 1 << "\t" << 1;
if (track_correctness) {
cerr << "\t" << funnels[1].last_correct_stage() << endl;
} else {
cerr << "\t?" << endl;
}
#endif
return paired_mappings;
} else {
//Attempt rescue on unpaired alignments if either we didn't find any pairs or if the unpaired alignments are very good
process_until_threshold_a(unpaired_alignments, (std::function<double(size_t)>) [&](size_t i) -> double{
tuple<size_t, size_t, bool> index = unpaired_alignments.at(i);
return (double) std::get<2>(index) ? alignments[std::get<0>(index)].first[std::get<1>(index)].score()
: alignments[std::get<0>(index)].second[std::get<1>(index)].score();
}, 0, 1, max_rescue_attempts, [&](size_t i) {
tuple<size_t, size_t, bool> index = unpaired_alignments.at(i);
bool found_first = std::get<2>(index);
size_t j = found_first ? alignment_indices[std::get<0>(index)].first[std::get<1>(index)]
: alignment_indices[std::get<0>(index)].second[std::get<1>(index)];
if (track_provenance) {
funnels[found_first ? 0 : 1].processing_input(j);
funnels[found_first ? 0 : 1].substage("rescue");
}
Alignment& mapped_aln = found_first ? alignments[std::get<0>(index)].first[std::get<1>(index)]
: alignments[std::get<0>(index)].second[std::get<1>(index)];
Alignment rescued_aln = found_first ? aln2 : aln1;
rescued_aln.clear_path();
if (found_pair && (double) mapped_aln.score() < (double) (found_first ? best_alignment_scores.first : best_alignment_scores.second) * paired_rescue_score_limit) {
//If we have already found paired clusters and this unpaired alignment is not good enough, do nothing
return true;
}
attempt_rescue(mapped_aln, rescued_aln, minimizers_by_read[(found_first ? 1 : 0)], found_first);
int64_t fragment_dist = found_first ? distance_between(mapped_aln, rescued_aln)
: distance_between(rescued_aln, mapped_aln);
if (fragment_dist != std::numeric_limits<int64_t>::max()) {
bool duplicated = false;
double dev = fragment_dist - fragment_length_distr.mean();
double fragment_length_log_likelihood = -dev * dev / (2.0 * fragment_length_distr.std_dev() * fragment_length_distr.std_dev());
double score = mapped_aln.score() + rescued_aln.score() + (fragment_length_log_likelihood / get_aligner()->log_base);
set_annotation(mapped_aln, "rescuer", true);
set_annotation(rescued_aln, "rescued", true);
set_annotation(mapped_aln, "fragment_length", (double)fragment_dist);
set_annotation(rescued_aln, "fragment_length", (double)fragment_dist);
pair<size_t, size_t> mapped_index (std::get<0>(index), std::get<1>(index));
pair<size_t, size_t> rescued_index (alignments.size() - 1,
found_first ? alignments.back().second.size() : alignments.back().first.size());
found_first ? alignments.back().second.emplace_back(std::move(rescued_aln))
: alignments.back().first.emplace_back(std::move(rescued_aln));
found_first ? rescued_count_1++ : rescued_count_2++;
found_first ? alignment_groups.back().second.emplace_back() : alignment_groups.back().first.emplace_back();
pair<pair<size_t, size_t>, pair<size_t, size_t>> index_pair = found_first ?
make_pair(mapped_index, rescued_index) : make_pair(rescued_index, mapped_index);
paired_alignments.push_back(index_pair);
paired_scores.emplace_back(score);
fragment_distances.emplace_back(fragment_dist);
better_cluster_count_alignment_pairs.emplace_back(0);
rescued_from.push_back(found_first);
#ifdef print_minimizers
alignment_was_rescued.emplace_back(!found_first, found_first);
#endif
if (track_provenance) {
funnels[found_first ? 0 : 1].pass("max-rescue-attempts", j);
funnels[found_first ? 0 : 1].project(j);
funnels[found_first ? 1 : 0].introduce();
}
}
if (track_provenance) {
funnels[found_first ? 0 : 1].processed_input();
funnels[found_first ? 0 : 1].substage_stop();
}
return true;
}, [&](size_t i) {
if (track_provenance) {
tuple<size_t, size_t, bool> index = unpaired_alignments.at(i);
bool found_first = std::get<2>(index);
size_t j = found_first ? alignment_indices[std::get<0>(index)].first[std::get<1>(index)]
: alignment_indices[std::get<0>(index)].second[std::get<1>(index)];
funnels[found_first ? 0 : 1].fail("max-rescue-attempts", j);
}
return;
}, [&] (size_t i) {
if (track_provenance) {
tuple<size_t, size_t, bool> index = unpaired_alignments.at(i);
bool found_first = std::get<2>(index);
size_t j = found_first ? alignment_indices[std::get<0>(index)].first[std::get<1>(index)]
: alignment_indices[std::get<0>(index)].second[std::get<1>(index)];
}
return;
});
}
}
if (track_provenance) {
// Now say we are finding the winner(s)
funnels[0].stage("winner");
funnels[1].stage("winner");
}
double estimated_multiplicity_from_1 = unpaired_count_1 > 0 ? (double) unpaired_count_1 / min(rescued_count_1, max_rescue_attempts) : 1.0;
double estimated_multiplicity_from_2 = unpaired_count_2 > 0 ? (double) unpaired_count_2 / min(rescued_count_2, max_rescue_attempts) : 1.0;
vector<double> paired_multiplicities;
for (bool rescued_from_first : rescued_from) {
paired_multiplicities.push_back(rescued_from_first ? estimated_multiplicity_from_1 : estimated_multiplicity_from_2);
}
// Fill this in with the alignments we will output
pair<vector<Alignment>, vector<Alignment>> mappings;
// Grab all the scores in order for MAPQ computation.
vector<double> scores;
vector<double> scores_group_1;
vector<double> scores_group_2;
vector<int64_t> distances;
mappings.first.reserve(paired_alignments.size());
mappings.second.reserve(paired_alignments.size());
scores.reserve(paired_scores.size());
distances.reserve(fragment_distances.size());
vector<size_t> better_cluster_count_mappings;
better_cluster_count_mappings.reserve(better_cluster_count_alignment_pairs.size());
#ifdef print_minimizers
vector<pair<bool, bool>> mapping_was_rescued;
#endif
process_until_threshold_a(paired_alignments, (std::function<double(size_t)>) [&](size_t i) -> double {
return paired_scores[i];
}, 0, 1, max_multimaps, [&](size_t alignment_num) {
// This alignment makes it
// Called in score order
pair<pair<size_t, size_t>, pair<size_t, size_t>> index_pair = paired_alignments[alignment_num];
// Remember the score at its rank
scores.emplace_back(paired_scores[alignment_num]);
distances.emplace_back(fragment_distances[alignment_num]);
// Remember the output alignment
mappings.first.emplace_back( alignments[index_pair.first.first].first[index_pair.first.second]);
mappings.second.emplace_back(alignments[index_pair.second.first].second[index_pair.second.second]);
better_cluster_count_mappings.emplace_back(better_cluster_count_alignment_pairs[alignment_num]);
if (mappings.first.size() == 1 && found_pair) {
//If this is the best pair of alignments that we're going to return and we didn't attempt rescue,
//get the group scores for mapq
//Get the scores of
scores_group_1.push_back(paired_scores[alignment_num]);
scores_group_2.push_back(paired_scores[alignment_num]);
//The indices (into paired_alignments) of pairs with the same first read as this
vector<size_t>& alignment_group_1 = alignment_groups[index_pair.first.first].first[index_pair.first.second];
vector<size_t>& alignment_group_2 = alignment_groups[index_pair.second.first].second[index_pair.second.second];
for (size_t other_alignment_num : alignment_group_1) {
if (other_alignment_num != alignment_num) {
scores_group_1.push_back(paired_scores[other_alignment_num]);
}
}
for (size_t other_alignment_num : alignment_group_2) {
if (other_alignment_num != alignment_num) {
scores_group_2.push_back(paired_scores[other_alignment_num]);
}
}
}
// Flip aln2 back to input orientation
reverse_complement_alignment_in_place(&mappings.second.back(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
if (mappings.first.size() > 1) {
mappings.first.back().set_is_secondary(true);
mappings.second.back().set_is_secondary(true);
}
#ifdef print_minimizers
mapping_was_rescued.emplace_back(alignment_was_rescued[alignment_num]);
#endif
if (track_provenance) {
// Tell the funnel
funnels[0].pass("max-multimaps", alignment_num);
funnels[0].project(alignment_num);
funnels[0].score(alignment_num, scores.back());
funnels[1].pass("max-multimaps", alignment_num);
funnels[1].project(alignment_num);
funnels[1].score(alignment_num, scores.back());
}
return true;
}, [&](size_t alignment_num) {
// We already have enough alignments, although this one has a good score
// Remember the score at its rank anyway
scores.emplace_back(paired_scores[alignment_num]);
distances.emplace_back(fragment_distances[alignment_num]);
if (track_provenance) {
funnels[0].fail("max-multimaps", alignment_num);
funnels[1].fail("max-multimaps", alignment_num);
}
}, [&](size_t alignment_num) {
// This alignment does not have a sufficiently good score
// Score threshold is 0; this should never happen
assert(false);
});
if (track_provenance) {
funnels[0].substage("mapq");
funnels[1].substage("mapq");
}
// Compute raw explored caps (with 2.0 scaling, like for single-end) and raw group caps.
// Non-capping caps stay at infinity.
vector<double> mapq_explored_caps(2, std::numeric_limits<float>::infinity());
vector<double> mapq_score_groups(2, std::numeric_limits<float>::infinity());
// We also have one fragment_cluster_cap across both ends.
double fragment_cluster_cap = std::numeric_limits<float>::infinity();
// And one base uncapped MAPQ
double uncapped_mapq = 0;
if (mappings.first.empty()) {
//If we didn't get an alignment, return empty alignments
mappings.first.emplace_back(aln1);
mappings.second.emplace_back(aln2);
// Flip aln2 back to input orientation
reverse_complement_alignment_in_place(&mappings.second.back(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
mappings.first.back().clear_refpos();
mappings.first.back().clear_path();
mappings.first.back().set_score(0);
mappings.first.back().set_identity(0);
mappings.first.back().set_mapping_quality(0);
mappings.second.back().clear_refpos();
mappings.second.back().clear_path();
mappings.second.back().set_score(0);
mappings.second.back().set_identity(0);
mappings.second.back().set_mapping_quality(0);
#ifdef print_minimizers
mapping_was_rescued.emplace_back(false, false);
#endif
} else {
#ifdef debug
cerr << "For scores ";
for (auto& score : scores) cerr << score << " ";
#endif
size_t winning_index;
const vector<double>* multiplicities = paired_multiplicities.size() == scores.size() ? &paired_multiplicities : nullptr;
// Compute base MAPQ if not unmapped. Otherwise use 0 instead of the 50% this would give us.
// If either of the mappings was duplicated in other pairs, use the group scores to determine mapq
uncapped_mapq = scores[0] == 0 ? 0 :
get_regular_aligner()->maximum_mapping_quality_exact(scores, &winning_index, multiplicities) / 2;
//Cap mapq at 1 - 1 / # equivalent or better fragment clusters, excluding self
if (better_cluster_count_mappings.size() != 0) {
if (better_cluster_count_mappings.front() == 1) {
// One cluster excluding us is equivalent or better.
// Old logic gave a -0 which was interpreted as uncapped.
// So leave uncapped.
} else if (better_cluster_count_mappings.front() > 1) {
// Actually compute the cap the right way around
// TODO: why is this a sensible cap?
fragment_cluster_cap = prob_to_phred(1.0 - (1.0 / (double) better_cluster_count_mappings.front()));
// Leave zeros in here and don't round.
}
}
//If one alignment was duplicated in other pairs, cap the mapq for that alignment at the mapq
//of the group of duplicated alignments
mapq_score_groups[0] = scores_group_1.size() <= 1 ? std::numeric_limits<float>::infinity() : get_regular_aligner()->maximum_mapping_quality_exact(scores_group_1, &winning_index);
mapq_score_groups[1] = scores_group_2.size() <= 1 ? std::numeric_limits<float>::infinity() : get_regular_aligner()->maximum_mapping_quality_exact(scores_group_2, &winning_index);
for (auto read_num : {0, 1}) {
// For each fragment
// Find the source read
auto& aln = read_num == 0 ? aln1 : aln2;
vector<size_t> explored_minimizers;
for (size_t i = 0; i < minimizers_by_read[read_num].size(); i++) {
if (minimizer_explored_by_read[read_num].contains(i)) {
explored_minimizers.push_back(i);
}
}
// Compute exploration cap on MAPQ. TODO: avoid needing to pass as much stuff along.
double mapq_explored_cap = 2 * faster_cap(minimizers_by_read[read_num], explored_minimizers, aln.sequence(), aln.quality());
mapq_explored_caps[read_num] = mapq_explored_cap;
// Remember the caps
auto& to_annotate = (read_num == 0 ? mappings.first : mappings.second).front();
set_annotation(to_annotate, "mapq_explored_cap", mapq_explored_cap);
set_annotation(to_annotate, "mapq_score_group", mapq_score_groups[read_num]);
}
// Have a function to transform interesting cap values to uncapped.
auto preprocess_cap = [&](double cap) {
return (cap != -numeric_limits<double>::infinity()) ? cap : numeric_limits<double>::infinity();
};
for (auto read_num : {0, 1}) {
// For each fragment
// Compute the overall cap for just this read, now that the individual cap components are filled in for both reads.
double mapq_cap = std::min(preprocess_cap(mapq_score_groups[read_num] / 2.0), std::min(fragment_cluster_cap, (mapq_explored_caps[0] + mapq_explored_caps[1]) / 2.0));
// Find the MAPQ to cap
double read_mapq = uncapped_mapq;
// Remember the uncapped MAPQ
auto& to_annotate = (read_num == 0 ? mappings.first : mappings.second).front();
set_annotation(to_annotate, "mapq_uncapped", read_mapq);
// And the cap we actually applied (possibly from the pair partner)
set_annotation(to_annotate, "mapq_applied_cap", mapq_cap);
// Apply the cap, and limit to 0-60
read_mapq = max(min(mapq_cap, min(read_mapq, 60.0)), 0.0);
// Save the MAPQ
to_annotate.set_mapping_quality(read_mapq);
#ifdef debug
cerr << "MAPQ for read " << read_num << " is " << read_mapq << ", was " << uncapped_mapq
<< " capped by fragment cluster cap " << fragment_cluster_cap
<< ", score group cap " << (mapq_score_groups[read_num] / 2.0)
<< ", combined explored cap " << ((mapq_explored_caps[0] + mapq_explored_caps[1]) / 2.0) << endl;
#endif
}
//Annotate top pair with its fragment distance, fragment length distrubution, and secondary scores
set_annotation(mappings.first.front(), "fragment_length", (double) distances.front());
set_annotation(mappings.second.front(), "fragment_length", (double) distances.front());
string distribution = "-I " + to_string(fragment_length_distr.mean()) + " -D " + to_string(fragment_length_distr.std_dev());
set_annotation(mappings.first.front(),"fragment_length_distribution", distribution);
set_annotation(mappings.second.front(),"fragment_length_distribution", distribution);
set_annotation(mappings.first.front(),"secondary_scores", scores);
set_annotation(mappings.second.front(),"secondary_scores", scores);
}
if (track_provenance) {
funnels[0].substage_stop();
funnels[1].substage_stop();
}
// Stop this alignment
funnels[0].stop();
funnels[1].stop();
if (track_provenance) {
// Annotate with the number of results in play at each stage
for (size_t read_num = 0 ; read_num < 2 ; read_num++) {
funnels[read_num].for_each_stage([&](const string& stage, const vector<size_t>& result_sizes) {
// Save the number of items
set_annotation(read_num == 0 ? mappings.first[0] : mappings.second[0], "stage_" + stage + "_results", (double)result_sizes.size());
});
if (track_correctness) {
// And with the last stage at which we had any descendants of the correct seed hit locations
set_annotation(read_num == 0 ? mappings.first[0] : mappings.second[0], "last_correct_stage", funnels[read_num].last_correct_stage());
}
// Annotate with the performances of all the filters
// We need to track filter number
size_t filter_num = 0;
funnels[read_num].for_each_filter([&](const string& stage, const string& filter,
const Funnel::FilterPerformance& by_count, const Funnel::FilterPerformance& by_size,
const vector<double>& filter_statistics_correct, const vector<double>& filter_statistics_non_correct) {
string filter_id = to_string(filter_num) + "_" + filter + "_" + stage;
if (read_num == 0) {
// Save the stats
set_annotation(mappings.first[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(mappings.first[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(mappings.first[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(mappings.first[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(mappings.first[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(mappings.first[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(mappings.first[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(mappings.first[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(mappings.first[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(mappings.first[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
} else {
// Save the stats
set_annotation(mappings.second[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(mappings.second[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(mappings.second[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(mappings.second[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(mappings.second[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(mappings.second[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(mappings.second[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(mappings.second[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(mappings.second[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(mappings.second[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
}
filter_num++;
});
}
// Annotate with parameters used for the filters.
set_annotation(mappings.first[0] , "param_hit-cap", (double) hit_cap);
set_annotation(mappings.first[0] , "param_hard-hit-cap", (double) hard_hit_cap);
set_annotation(mappings.first[0] , "param_score-fraction", (double) minimizer_score_fraction);
set_annotation(mappings.first[0] , "param_max-extensions", (double) max_extensions);
set_annotation(mappings.first[0] , "param_max-alignments", (double) max_alignments);
set_annotation(mappings.first[0] , "param_cluster-score", (double) cluster_score_threshold);
set_annotation(mappings.first[0] , "param_cluster-coverage", (double) cluster_coverage_threshold);
set_annotation(mappings.first[0] , "param_extension-set", (double) extension_set_score_threshold);
set_annotation(mappings.first[0] , "param_max-multimaps", (double) max_multimaps);
set_annotation(mappings.first[0] , "param_max-rescue-attempts", (double) max_rescue_attempts);
set_annotation(mappings.second[0], "param_hit-cap", (double) hit_cap);
set_annotation(mappings.second[0], "param_hard-hit-cap", (double) hard_hit_cap);
set_annotation(mappings.second[0], "param_score-fraction", (double) minimizer_score_fraction);
set_annotation(mappings.second[0], "param_max-extensions", (double) max_extensions);
set_annotation(mappings.second[0], "param_max-alignments", (double) max_alignments);
set_annotation(mappings.second[0], "param_cluster-score", (double) cluster_score_threshold);
set_annotation(mappings.second[0], "param_cluster-coverage", (double) cluster_coverage_threshold);
set_annotation(mappings.second[0], "param_extension-set", (double) extension_set_score_threshold);
set_annotation(mappings.second[0], "param_max-multimaps", (double) max_multimaps);
set_annotation(mappings.second[0] , "param_max-rescue-attempts", (double) max_rescue_attempts);
}
#ifdef print_minimizers
if (distances.size() == 0) {
distances.emplace_back(0);
}
cerr << aln1.sequence() << "\t";
for (char c : aln1.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << max_fragment_num << "\t" << mapping_was_rescued[0].first << "\t" << mapping_was_rescued[0].second << "\t" << distances.front();
for (size_t i = 0 ; i < minimizers_by_read[0].size() ; i++) {
auto& minimizer = minimizers_by_read[0][i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_explored_by_read[0].contains(i);
if (minimizer_explored_by_read[0].contains(i)) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << uncapped_mapq << "\t" << fragment_cluster_cap << "\t" << mapq_score_groups[0] << "\t" << mapq_explored_caps[0] << "\t" << mappings.first.front().mapping_quality();
if (track_correctness) {
cerr << "\t" << funnels[0].last_correct_stage() << endl;
} else {
cerr << "\t?" << endl;
}
cerr << aln2.sequence() << "\t";
for (char c : aln2.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << max_fragment_num << "\t" << mapping_was_rescued[0].second << "\t" << mapping_was_rescued[0].first << "\t" << distances.front();
for (size_t i = 0 ; i < minimizers_by_read[1].size() ; i++) {
auto& minimizer = minimizers_by_read[1][i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_explored_by_read[1].contains(i);
if (minimizer_explored_by_read[1].contains(i)) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << uncapped_mapq << "\t" << fragment_cluster_cap << "\t" << mapq_score_groups[1] << "\t" << mapq_explored_caps[1] << "\t" << mappings.second.front().mapping_quality();
if (track_correctness) {
cerr << "\t" << funnels[1].last_correct_stage() << endl;
} else {
cerr << "\t?" << endl;
}
#endif
// Ship out all the aligned alignments
return mappings;
#ifdef debug
// Dump the funnel info graph.
funnels[0].to_dot(cerr);
funnels[1].to_dot(cerr);
#endif
}
//-----------------------------------------------------------------------------
double MinimizerMapper::compute_mapq_caps(const Alignment& aln,
const std::vector<Minimizer>& minimizers,
const SmallBitset& explored) {
// We need to cap MAPQ based on the likelihood of generating all the windows in the explored minimizers by chance, too.
#ifdef debug
cerr << "Cap based on explored minimizers all being faked by errors..." << endl;
#endif
// Convert our flag vector to a list of the minimizers actually in extended clusters
vector<size_t> explored_minimizers;
explored_minimizers.reserve(minimizers.size());
for (size_t i = 0; i < minimizers.size(); i++) {
if (explored.contains(i)) {
explored_minimizers.push_back(i);
}
}
double mapq_explored_cap = window_breaking_quality(minimizers, explored_minimizers, aln.sequence(), aln.quality());
return mapq_explored_cap;
}
double MinimizerMapper::window_breaking_quality(const vector<Minimizer>& minimizers, vector<size_t>& broken,
const string& sequence, const string& quality_bytes) {
#ifdef debug
cerr << "Computing MAPQ cap based on " << broken.size() << "/" << minimizers.size() << " minimizers' windows" << endl;
#endif
if (broken.empty() || quality_bytes.empty()) {
// If we have no agglomerations or no qualities, bail
return numeric_limits<double>::infinity();
}
assert(sequence.size() == quality_bytes.size());
// Sort the agglomerations by start position
std::sort(broken.begin(), broken.end(), [&](const size_t& a, const size_t& b) {
return minimizers[a].agglomeration_start < minimizers[b].agglomeration_start;
});
// Have a priority queue for tracking the agglomerations that a base is currently overlapping.
// Prioritize earliest-ending best, and then latest-starting best.
// This is less, and greater priority is at the front of the queue (better).
// TODO: do we really need to care about the start here?
auto agglomeration_priority = [&](const size_t& a, const size_t& b) {
// Returns true if a is worse (ends later, or ends at the same place and starts earlier).
auto& ma = minimizers[a];
auto& mb = minimizers[b];
auto a_end = ma.agglomeration_start + ma.agglomeration_length;
auto b_end = mb.agglomeration_start + mb.agglomeration_length;
return (a_end > b_end) || (a_end == b_end && ma.agglomeration_start < mb.agglomeration_start);
};
// We maintain our own heap so we can iterate over it.
vector<size_t> active_agglomerations;
// A window in flight is a pair of start position, inclusive end position
struct window_t {
size_t first;
size_t last;
};
// Have a priority queue of window starts and ends, prioritized earliest-ending best, and then latest-starting best.
// This is less, and greater priority is at the front of the queue (better).
auto window_priority = [&](const window_t& a, const window_t& b) {
// Returns true if a is worse (ends later, or ends at the same place and starts earlier).
return (a.last > b.last) || (a.last == b.last && a.first < b.first);
};
priority_queue<window_t, vector<window_t>, decltype(window_priority)> active_windows(window_priority);
// Have a cursor for which agglomeration should come in next.
auto next_agglomeration = broken.begin();
// Have a DP table with the cost of the cheapest solution to the problem up to here, including a hit at this base.
// Or numeric_limits<double>::infinity() if base cannot be hit.
// We pre-fill it because I am scared to use end() if we change its size.
vector<double> costs(sequence.size(), numeric_limits<double>::infinity());
// Keep track of the latest-starting window ending before here. If none, this will be two numeric_limits<size_t>::max() values.
window_t latest_starting_ending_before = { numeric_limits<size_t>::max(), numeric_limits<size_t>::max() };
// And keep track of the min cost DP table entry, or end if not computed yet.
auto latest_starting_ending_before_winner = costs.end();
for (size_t i = 0; i < sequence.size(); i++) {
// For each base in the read
#ifdef debug
cerr << "At base " << i << endl;
#endif
// Bring in new agglomerations and windows that start at this base.
while (next_agglomeration != broken.end() && minimizers[*next_agglomeration].agglomeration_start == i) {
// While the next agglomeration starts here
// Record it
active_agglomerations.push_back(*next_agglomeration);
std::push_heap(active_agglomerations.begin(), active_agglomerations.end(), agglomeration_priority);
// Look it up
auto& minimizer = minimizers[*next_agglomeration];
// Determine its window size from its index.
size_t window_size = minimizer.window_size();
#ifdef debug
cerr << "\tBegin agglomeration of " << (minimizer.agglomeration_length - window_size + 1)
<< " windows of " << window_size << " bp each for minimizer "
<< *next_agglomeration << " (" << minimizer.forward_offset()
<< "-" << (minimizer.forward_offset() + minimizer.length) << ")" << endl;
#endif
// Make sure the minimizer instance isn't too far into the agglomeration to actually be conatined in the same k+w-1 window as the first base.
assert(minimizer.agglomeration_start + minimizer.candidates_per_window >= minimizer.forward_offset());
for (size_t start = minimizer.agglomeration_start;
start + window_size - 1 < minimizer.agglomeration_start + minimizer.agglomeration_length;
start++) {
// Add all the agglomeration's windows to the queue, looping over their start bases in the read.
window_t add = {start, start + window_size - 1};
#ifdef debug
cerr << "\t\t" << add.first << " - " << add.last << endl;
#endif
active_windows.push(add);
}
// And advance the cursor
++next_agglomeration;
}
// We have the start and end of the latest-starting window ending before here (may be none)
if (isATGC(sequence[i]) &&
(!active_windows.empty() ||
(next_agglomeration != broken.end() && minimizers[*next_agglomeration].agglomeration_start == i))) {
// This base is not N, and it is either covered by an agglomeration
// that hasn't ended yet, or a new agglomeration starts here.
#ifdef debug
cerr << "\tBase is acceptable (" << sequence[i] << ", " << active_agglomerations.size() << " active agglomerations, "
<< active_windows.size() << " active windows)" << endl;
#endif
// Score mutating the base itself, thus causing all the windows it touches to be wrong.
// TODO: account for windows with multiple hits not having to be explained at full cost here.
// We start with the cost to mutate the base.
double base_cost = quality_bytes[i];
#ifdef debug
cerr << "\t\tBase base quality: " << base_cost << endl;
#endif
for (const size_t& active_index : active_agglomerations) {
// Then, we look at each agglomeration the base overlaps
// Find the minimizer whose agglomeration we are looking at
auto& active = minimizers[active_index];
if (i >= active.forward_offset() &&
i < active.forward_offset() + active.length) {
// If the base falls in the minimizer, we don't do anything. Just mutating the base is enough to create this wrong minimizer.
#ifdef debug
cerr << "\t\tBase in minimizer " << active_index << " (" << active.forward_offset()
<< "-" << (active.forward_offset() + active.length) << ") for agglomeration "
<< active.agglomeration_start << "-" << (active.agglomeration_start + active.agglomeration_length) << endl;
#endif
continue;
}
// If the base falls outside the minimizer, it participates in
// some number of other possible minimizers in the
// agglomeration. Compute that, accounting for edge effects.
size_t possible_minimizers = min((size_t) active.length, min(i - active.agglomeration_start + 1, (active.agglomeration_start + active.agglomeration_length) - i));
// Then for each of those possible minimizers, we need P(would have beaten the current minimizer).
// We approximate this as constant across the possible minimizers.
// And since we want to OR together beating, we actually AND together not-beating and then not it.
// So we track the probability of not beating.
double any_beat_phred = phred_for_at_least_one(active.value.hash, possible_minimizers);
#ifdef debug
cerr << "\t\tBase flanks minimizer " << active_index << " (" << active.forward_offset()
<< "-" << (active.forward_offset() + active.length) << ") for agglomeration "
<< active.agglomeration_start << "-" << (active.agglomeration_start + active.agglomeration_length)
<< " and has " << possible_minimizers
<< " chances to have beaten it; cost to have beaten with any is Phred " << any_beat_phred << endl;
#endif
// Then we AND (sum) the Phred of that in, as an additional cost to mutating this base and kitting all the windows it covers.
// This makes low-quality bases outside of minimizers produce fewer low MAPQ caps, and accounts for the robustness of minimizers to some errors.
base_cost += any_beat_phred;
}
// Now we know the cost of mutating this base, so we need to
// compute the total cost of a solution through here, mutating this
// base.
// Look at the start of that latest-starting window ending before here.
if (latest_starting_ending_before.first == numeric_limits<size_t>::max()) {
// If there is no such window, this is the first base hit, so
// record the cost of hitting it.
costs[i] = base_cost;
#ifdef debug
cerr << "\tFirst base hit, costs " << costs[i] << endl;
#endif
} else {
// Else, scan from that window's start to its end in the DP
// table, and find the min cost.
if (latest_starting_ending_before_winner == costs.end()) {
// We haven't found the min in the window we come from yet, so do that.
latest_starting_ending_before_winner = std::min_element(costs.begin() + latest_starting_ending_before.first,
costs.begin() + latest_starting_ending_before.last + 1);
}
double min_prev_cost = *latest_starting_ending_before_winner;
// Add the cost of hitting this base
costs[i] = min_prev_cost + base_cost;
#ifdef debug
cerr << "\tComes from prev base at " << (latest_starting_ending_before_winner - costs.begin()) << ", costs " << costs[i] << endl;
#endif
}
} else {
// This base is N, or not covered by an agglomeration.
// Leave infinity there to say we can't hit it.
// Nothing to do!
}
// Now we compute the start of the latest-starting window ending here or before, and deactivate agglomerations/windows.
while (!active_agglomerations.empty() &&
minimizers[active_agglomerations.front()].agglomeration_start + minimizers[active_agglomerations.front()].agglomeration_length - 1 == i) {
// Look at the queue to see if an agglomeration ends here.
#ifdef debug
cerr << "\tEnd agglomeration " << active_agglomerations.front() << endl;
#endif
std::pop_heap(active_agglomerations.begin(), active_agglomerations.end(), agglomeration_priority);
active_agglomerations.pop_back();
}
while (!active_windows.empty() && active_windows.top().last == i) {
// The look at the queue to see if a window ends here. This is
// after windows are added so that we can handle 1-base windows.
#ifdef debug
cerr << "\tEnd window " << active_windows.top().first << " - " << active_windows.top().last << endl;
#endif
if (latest_starting_ending_before.first == numeric_limits<size_t>::max() ||
active_windows.top().first > latest_starting_ending_before.first) {
#ifdef debug
cerr << "\t\tNew latest-starting-before-here!" << endl;
#endif
// If so, use the latest-starting of all such windows as our latest starting window ending here or before result.
latest_starting_ending_before = active_windows.top();
// And clear our cache of the lowest cost base to hit it.
latest_starting_ending_before_winner = costs.end();
#ifdef debug
cerr << "\t\t\tNow have: " << latest_starting_ending_before.first << " - " << latest_starting_ending_before.last << endl;
#endif
}
// And pop them all off.
active_windows.pop();
}
// If not, use the latest-starting window ending at the previous base or before (i.e. do nothing).
// Loop around; we will have the latest-starting window ending before the next here.
}
#ifdef debug
cerr << "Final window to scan: " << latest_starting_ending_before.first << " - " << latest_starting_ending_before.last << endl;
#endif
// When we get here, all the agglomerations should have been handled
assert(next_agglomeration == broken.end());
// And all the windows should be off the queue.
assert(active_windows.empty());
// When we get to the end, we have the latest-starting window overall. It must exist.
assert(latest_starting_ending_before.first != numeric_limits<size_t>::max());
// Scan it for the best final base to hit and return the cost there.
// Don't use the cache here because nothing can come after the last-ending window.
auto min_cost_at = std::min_element(costs.begin() + latest_starting_ending_before.first,
costs.begin() + latest_starting_ending_before.last + 1);
#ifdef debug
cerr << "Overall min cost: " << *min_cost_at << " at base " << (min_cost_at - costs.begin()) << endl;
#endif
return *min_cost_at;
}
double MinimizerMapper::faster_cap(const vector<Minimizer>& minimizers, vector<size_t>& minimizers_explored,
const string& sequence, const string& quality_bytes) {
// Sort minimizer subset so we go through minimizers in increasing order of start position
std::sort(minimizers_explored.begin(), minimizers_explored.end(), [&](size_t a, size_t b) {
// Return true if a must come before b, and false otherwise
return minimizers[a].forward_offset() < minimizers[b].forward_offset();
});
#ifdef debug
cerr << "Sorted " << minimizers_explored.size() << " minimizers" << endl;
#endif
#ifdef debug
// Dump read and minimizers
int digits_needed = (int) ceil(log10(sequence.size()));
for (int digit = digits_needed - 1; digit >= 0; digit--) {
for (size_t i = 0; i < sequence.size(); i++) {
// Output the correct digit for this place in this number
cerr << (char) ('0' + (uint8_t) round(i % (int) round(pow(10, digit + 1)) / pow(10, digit)));
}
cerr << endl;
}
cerr << sequence << endl;
for (auto& explored_index : minimizers_explored) {
// For each explored minimizer
auto& m = minimizers[explored_index];
for (size_t i = 0; i < m.agglomeration_start; i++) {
// Space until its agglomeration starts
cerr << ' ';
}
for (size_t i = m.agglomeration_start; i < m.forward_offset(); i++) {
// Do the beginnign of the agglomeration
cerr << '-';
}
// Do the minimizer itself
cerr << m.value.key.decode(m.length);
for (size_t i = m.forward_offset() + m.length ; i < m.agglomeration_start + m.agglomeration_length; i++) {
// Do the tail end of the agglomeration
cerr << '-';
}
cerr << endl;
}
#endif
// Make a DP table holding the log10 probability of having an error disrupt each minimizer.
// Entry i+1 is log prob of mutating minimizers 0, 1, 2, ..., i.
// Make sure to have an extra field at the end to support this.
// Initialize with -inf for unfilled.
vector<double> c(minimizers_explored.size() + 1, -numeric_limits<double>::infinity());
c[0] = 0.0;
for_each_aglomeration_interval(minimizers, sequence, quality_bytes, minimizers_explored, [&](size_t left, size_t right, size_t bottom, size_t top) {
// For each overlap range in the agglomerations
#ifdef debug
cerr << "Consider overlap range " << left << " to " << right << " in minimizer ranks " << bottom << " to " << top << endl;
cerr << "log10prob for bottom: " << c[bottom] << endl;
#endif
// Calculate the probability of a disruption here
double p_here = get_log10_prob_of_disruption_in_interval(minimizers, sequence, quality_bytes,
minimizers_explored.begin() + bottom, minimizers_explored.begin() + top, left, right);
#ifdef debug
cerr << "log10prob for here: " << p_here << endl;
#endif
// Calculate prob of all intervals up to top being disrupted
double p = c[bottom] + p_here;
#ifdef debug
cerr << "log10prob overall: " << p << endl;
#endif
for (size_t i = bottom + 1; i < top + 1; i++) {
// Replace min-prob for minimizers in the interval
if (c[i] < p) {
#ifdef debug
cerr << "\tBeats " << c[i] << " at rank " << i-1 << endl;
#endif
c[i] = p;
} else {
#ifdef debug
cerr << "\tBeaten by " << c[i] << " at rank " << i-1 << endl;
#endif
}
}
});
#ifdef debug
cerr << "log10prob after all minimizers is " << c.back() << endl;
#endif
assert(!isinf(c.back()));
// Conver to Phred.
double result = -c.back() * 10;
return result;
}
void MinimizerMapper::for_each_aglomeration_interval(const vector<Minimizer>& minimizers,
const string& sequence, const string& quality_bytes,
const vector<size_t>& minimizer_indices,
const function<void(size_t, size_t, size_t, size_t)>& iteratee) {
if (minimizer_indices.empty()) {
// Handle no item case
return;
}
// Items currently being iterated over
list<const Minimizer*> stack = {&minimizers[minimizer_indices.front()]};
// The left end of an item interval
size_t left = stack.front()->agglomeration_start;
// The index of the first item in the interval in the sequence of selected items
size_t bottom = 0;
// Emit all intervals that precede a given point "right"
auto emit_preceding_intervals = [&](size_t right) {
while (left < right) {
// Work out the end position of the top thing on the stack
size_t stack_top_end = stack.front()->agglomeration_start + stack.front()->agglomeration_length;
if (stack_top_end <= right) {
// Case where the left-most item ends before the start of the new item
iteratee(left, stack_top_end, bottom, bottom + stack.size());
// If the stack contains only one item there is a gap between the item
// and the new item, otherwise just shift to the end of the leftmost item
left = stack.size() == 1 ? right : stack_top_end;
bottom += 1;
stack.pop_front();
} else {
// Case where the left-most item ends at or after the beginning of the new new item
iteratee(left, right, bottom, bottom + stack.size());
left = right;
}
}
};
for (auto it = minimizer_indices.begin() + 1; it != minimizer_indices.end(); ++it) {
// For each item in turn
auto& item = minimizers[*it];
assert(stack.size() > 0);
// For each new item we return all intervals that
// precede its start
emit_preceding_intervals(item.agglomeration_start);
// Add the new item for the next loop
stack.push_back(&item);
}
// Intervals of the remaining intervals on the stack
emit_preceding_intervals(sequence.size());
}
double MinimizerMapper::get_log10_prob_of_disruption_in_interval(const vector<Minimizer>& minimizers,
const string& sequence, const string& quality_bytes,
const vector<size_t>::iterator& disrupt_begin, const vector<size_t>::iterator& disrupt_end,
size_t left, size_t right) {
#ifdef debug
cerr << "Compute log10 probability in interval " << left << "-" << right << endl;
#endif
if (left == right) {
// 0-length intervals need no disruption.
return 0;
}
// Ww eant an OR over all the columns, so we compute an AND of NOT all the columns, and then NOT at the end.
// Start with the first column.
double p = 1.0 - get_prob_of_disruption_in_column(minimizers, sequence, quality_bytes, disrupt_begin, disrupt_end, left);
#ifdef debug
cerr << "\tProbability not disrupted at column " << left << ": " << p << endl;
#endif
for(size_t i = left + 1 ; i < right; i++) {
// OR up probability of all the other columns
double col_p = 1.0 - get_prob_of_disruption_in_column(minimizers, sequence, quality_bytes, disrupt_begin, disrupt_end, i);
#ifdef debug
cerr << "\tProbability not disrupted at column " << i << ": " << col_p << endl;
#endif
p *= col_p;
#ifdef debug
cerr << "\tRunning AND of not disrupted anywhere: " << p << endl;
#endif
}
// NOT the AND of NOT, so we actually OR over the columns.
// Also convert to log10prob.
return log10(1.0 - p);
}
double MinimizerMapper::get_prob_of_disruption_in_column(const vector<Minimizer>& minimizers,
const string& sequence, const string& quality_bytes,
const vector<size_t>::iterator& disrupt_begin, const vector<size_t>::iterator& disrupt_end,
size_t index) {
#ifdef debug
cerr << "\tCompute probability at column " << index << endl;
#endif
// Base cost is quality. Make sure to compute a non-integral answer.
double p = phred_to_prob((uint8_t)quality_bytes[index]);
#ifdef debug
cerr << "\t\tBase probability from quality: " << p << endl;
#endif
for (auto it = disrupt_begin; it != disrupt_end; ++it) {
// For each minimizer to disrupt
auto m = minimizers[*it];
#ifdef debug
cerr << "\t\tRelative rank " << (it - disrupt_begin) << " is minimizer " << m.value.key.decode(m.length) << endl;
#endif
if (!(m.forward_offset() <= index && index < m.forward_offset() + m.length)) {
// Index is out of range of the minimizer itself. We're in the flank.
#ifdef debug
cerr << "\t\t\tColumn " << index << " is in flank." << endl;
#endif
// How many new possible minimizers would an error here create in this agglomeration,
// to compete with its minimizer?
// No more than one per position in a minimizer sequence.
// No more than 1 per base from the start of the agglomeration to here, inclusive.
// No more than 1 per base from here to the last base of the agglomeration, inclusive.
size_t possible_minimizers = min((size_t) m.length,
min(index - m.agglomeration_start + 1,
(m.agglomeration_start + m.agglomeration_length) - index));
// Account for at least one of them beating the minimizer.
double any_beat_prob = prob_for_at_least_one(m.value.hash, possible_minimizers);
#ifdef debug
cerr << "\t\t\tBeat hash " << m.value.hash << " at least 1 time in " << possible_minimizers << " gives probability: " << any_beat_prob << endl;
#endif
p *= any_beat_prob;
// TODO: handle N somehow??? It can occur outside the minimizer itself, here in the flank.
}
#ifdef debug
cerr << "\t\t\tRunning AND prob: " << p << endl;
#endif
}
return p;
}
//-----------------------------------------------------------------------------
void MinimizerMapper::attempt_rescue(const Alignment& aligned_read, Alignment& rescued_alignment, const std::vector<Minimizer>& minimizers, bool rescue_forward ) {
if (this->rescue_algorithm == rescue_none) { return; }
// We are traversing the same small subgraph repeatedly, so it's better to use a cache.
gbwtgraph::CachedGBWTGraph cached_graph(this->gbwt_graph);
// Find all nodes within a reasonable range from aligned_read.
std::unordered_set<id_t> rescue_nodes;
int64_t min_distance = max(0.0, fragment_length_distr.mean() - rescued_alignment.sequence().size() - rescue_subgraph_stdevs * fragment_length_distr.std_dev());
int64_t max_distance = fragment_length_distr.mean() + rescue_subgraph_stdevs * fragment_length_distr.std_dev();
distance_index.subgraph_in_range(aligned_read.path(), &cached_graph, min_distance, max_distance, rescue_nodes, rescue_forward);
// Remove node ids that do not exist in the GBWTGraph from the subgraph.
// We may be using the distance index of the original graph, and nodes
// not visited by any thread are missing from the GBWTGraph.
for (auto iter = rescue_nodes.begin(); iter != rescue_nodes.end(); ) {
if (!cached_graph.has_node(*iter)) {
iter = rescue_nodes.erase(iter);
} else {
++iter;
}
}
// Get rid of the old path.
rescued_alignment.clear_path();
// Find all seeds in the subgraph and try to get a full-length extension.
GaplessExtender::cluster_type seeds = this->seeds_in_subgraph(minimizers, rescue_nodes);
std::vector<GaplessExtension> extensions = this->extender.extend(seeds, rescued_alignment.sequence(), &cached_graph);
size_t best = extensions.size();
for (size_t i = 0; i < extensions.size(); i++) {
if (best >= extensions.size() || extensions[i].score > extensions[best].score) {
best = i;
}
}
// If we have a full-length extension, use it as the rescued alignment.
if (best < extensions.size() && extensions[best].full()) {
this->extension_to_alignment(extensions[best], rescued_alignment);
return;
}
// The haplotype-based algorithm is a special case.
if (this->rescue_algorithm == rescue_haplotypes) {
// Find and unfold the local haplotypes in the subgraph.
std::vector<std::vector<handle_t>> haplotype_paths;
bdsg::HashGraph align_graph;
this->extender.unfold_haplotypes(rescue_nodes, haplotype_paths, align_graph);
// Align to the subgraph.
this->get_regular_aligner()->align_xdrop(rescued_alignment, align_graph,
std::vector<MaximalExactMatch>(), false);
this->fix_dozeu_score(rescued_alignment, align_graph, std::vector<handle_t>());
// Get the corresponding alignment to the original graph.
this->extender.transform_alignment(rescued_alignment, haplotype_paths);
return;
}
// Use the best extension as a seed for dozeu.
// Also ensure that the entire extension is in the subgraph.
std::vector<MaximalExactMatch> dozeu_seed;
if (best < extensions.size()) {
const GaplessExtension& extension = extensions[best];
for (handle_t handle : extension.path) {
rescue_nodes.insert(cached_graph.get_id(handle));
}
dozeu_seed.emplace_back();
dozeu_seed.back().begin = rescued_alignment.sequence().begin() + extension.read_interval.first;
dozeu_seed.back().end = rescued_alignment.sequence().begin() + extension.read_interval.second;
nid_t id = cached_graph.get_id(extension.path.front());
bool is_reverse = cached_graph.get_is_reverse(extension.path.front());
gcsa::node_type node = gcsa::Node::encode(id, extension.offset, is_reverse);
dozeu_seed.back().nodes.push_back(node);
}
// GSSW and dozeu assume that the graph is a DAG.
std::vector<handle_t> topological_order = gbwtgraph::topological_order(cached_graph, rescue_nodes);
if (!topological_order.empty()) {
if (rescue_algorithm == rescue_dozeu) {
get_regular_aligner()->align_xdrop(rescued_alignment, cached_graph, topological_order,
dozeu_seed, false);
this->fix_dozeu_score(rescued_alignment, cached_graph, topological_order);
} else {
get_regular_aligner()->align(rescued_alignment, cached_graph, topological_order);
}
return;
}
// Build a subgraph overlay.
SubHandleGraph sub_graph(&cached_graph);
for (id_t id : rescue_nodes) {
sub_graph.add_handle(cached_graph.get_handle(id));
}
// Create an overlay where each strand is a separate node.
StrandSplitGraph split_graph(&sub_graph);
// Dagify the subgraph.
bdsg::HashGraph dagified;
std::unordered_map<id_t, id_t> dagify_trans =
algorithms::dagify(&split_graph, &dagified, rescued_alignment.sequence().size());
// Align to the subgraph.
// TODO: Map the seed to the dagified subgraph.
if (this->rescue_algorithm == rescue_dozeu) {
get_regular_aligner()->align_xdrop(rescued_alignment, dagified, std::vector<MaximalExactMatch>(), false);
this->fix_dozeu_score(rescued_alignment, dagified, std::vector<handle_t>());
} else if (this->rescue_algorithm == rescue_gssw) {
get_regular_aligner()->align(rescued_alignment, dagified, true);
}
// Map the alignment back to the original graph.
Path& path = *(rescued_alignment.mutable_path());
for (size_t i = 0; i < path.mapping_size(); i++) {
Position& pos = *(path.mutable_mapping(i)->mutable_position());
id_t id = dagify_trans[pos.node_id()];
handle_t handle = split_graph.get_underlying_handle(split_graph.get_handle(id));
pos.set_node_id(sub_graph.get_id(handle));
pos.set_is_reverse(sub_graph.get_is_reverse(handle));
}
}
GaplessExtender::cluster_type MinimizerMapper::seeds_in_subgraph(const std::vector<Minimizer>& minimizers,
const std::unordered_set<id_t>& subgraph) const {
std::vector<id_t> sorted_ids(subgraph.begin(), subgraph.end());
std::sort(sorted_ids.begin(), sorted_ids.end());
GaplessExtender::cluster_type result;
for (const Minimizer& minimizer : minimizers) {
gbwtgraph::hits_in_subgraph(minimizer.hits, minimizer.occs, sorted_ids, [&](pos_t pos, gbwtgraph::payload_type) {
if (minimizer.value.is_reverse) {
size_t node_length = this->gbwt_graph.get_length(this->gbwt_graph.get_handle(id(pos)));
pos = reverse_base_pos(pos, node_length);
}
result.insert(GaplessExtender::to_seed(pos, minimizer.value.offset));
});
}
return result;
}
void MinimizerMapper::fix_dozeu_score(Alignment& rescued_alignment, const HandleGraph& rescue_graph,
const std::vector<handle_t>& topological_order) const {
const Aligner* aligner = this->get_regular_aligner();
int32_t score = aligner->score_ungapped_alignment(rescued_alignment);
if (score > 0) {
rescued_alignment.set_score(score);
} else {
rescued_alignment.clear_path();
if (topological_order.empty()) {
aligner->align(rescued_alignment, rescue_graph, true);
} else {
aligner->align(rescued_alignment, rescue_graph, topological_order);
}
}
}
//-----------------------------------------------------------------------------
int64_t MinimizerMapper::distance_between(const Alignment& aln1, const Alignment& aln2) {
assert(aln1.path().mapping_size() != 0);
assert(aln2.path().mapping_size() != 0);
pos_t pos1 = initial_position(aln1.path());
pos_t pos2 = final_position(aln2.path());
int64_t min_dist = distance_index.min_distance(pos1, pos2);
return min_dist == -1 ? numeric_limits<int64_t>::max() : min_dist;
}
void MinimizerMapper::extension_to_alignment(const GaplessExtension& extension, Alignment& alignment) const {
*(alignment.mutable_path()) = extension.to_path(this->gbwt_graph, alignment.sequence());
alignment.set_score(extension.score);
double identity = 0.0;
if (!alignment.sequence().empty()) {
size_t len = alignment.sequence().length();
identity = (len - extension.mismatches()) / static_cast<double>(len);
}
alignment.set_identity(identity);
}
//-----------------------------------------------------------------------------
std::vector<MinimizerMapper::Minimizer> MinimizerMapper::find_minimizers(const std::string& sequence, Funnel& funnel) const {
if (this->track_provenance) {
// Start the minimizer finding stage
funnel.stage("minimizer");
}
std::vector<Minimizer> result;
double base_score = 1.0 + std::log(this->hard_hit_cap);
for (size_t i = 0; i < this->minimizer_indexes.size(); i++) {
// Get minimizers and their window agglomeration starts and lengths
vector<tuple<gbwtgraph::DefaultMinimizerIndex::minimizer_type, size_t, size_t>> current_minimizers =
minimizer_indexes[i]->minimizer_regions(sequence);
for (auto& m : current_minimizers) {
double score = 0.0;
auto hits = this->minimizer_indexes[i]->count_and_find(get<0>(m));
if (hits.first > 0) {
if (hits.first <= this->hard_hit_cap) {
score = base_score - std::log(hits.first);
} else {
score = 1.0;
}
}
result.push_back({ std::get<0>(m), std::get<1>(m), std::get<2>(m), hits.first, hits.second,
(int32_t) minimizer_indexes[i]->k(), (int32_t) minimizer_indexes[i]->w(), score });
}
}
std::sort(result.begin(), result.end());
if (this->track_provenance) {
// Record how many we found, as new lines.
funnel.introduce(result.size());
}
return result;
}
std::vector<MinimizerMapper::Seed> MinimizerMapper::find_seeds(const std::vector<Minimizer>& minimizers, const Alignment& aln, Funnel& funnel) const {
if (this->track_provenance) {
// Start the minimizer locating stage
funnel.stage("seed");
}
// One of the filters accepts minimizers until selected_score reaches target_score.
double base_target_score = 0.0;
for (const Minimizer& minimizer : minimizers) {
base_target_score += minimizer.score;
}
double target_score = (base_target_score * this->minimizer_score_fraction) + 0.000001;
double selected_score = 0.0;
// In order to consistently take either all or none of the minimizers in
// the read with a particular sequence, we track whether we took the
// previous one.
bool took_last = false;
// Select the minimizers we use for seeds.
size_t rejected_count = 0;
std::vector<Seed> seeds;
// Flag whether each minimizer in the read was located or not, for MAPQ capping.
// We ignore minimizers with no hits (count them as not located), because
// they would have to be created in the read no matter where we say it came
// from, and because adding more of them should lower the MAPQ cap, whereas
// locating more of the minimizers that are present and letting them pass
// to the enxt stage should raise the cap.
for (size_t i = 0; i < minimizers.size(); i++) {
if (this->track_provenance) {
// Say we're working on it
funnel.processing_input(i);
}
// Select the minimizer if it is informative enough or if the total score
// of the selected minimizers is not high enough.
const Minimizer& minimizer = minimizers[i];
#ifdef debug
std::cerr << "Minimizer " << i << " = " << minimizer.value.key.decode(minimizer.length)
<< " has " << minimizer.hits << " hits" << std::endl;
#endif
if (minimizer.hits == 0) {
// A minimizer with no hits can't go on.
took_last = false;
// We do not treat it as located for MAPQ capping purposes.
if (this->track_provenance) {
funnel.fail("any-hits", i);
}
} else if (minimizer.hits <= this->hit_cap ||
(minimizer.hits <= this->hard_hit_cap && selected_score + minimizer.score <= target_score) ||
(took_last && i > 0 && minimizer.value.key == minimizers[i - 1].value.key)) {
// We should keep this minimizer instance because it is
// sufficiently rare, or we want it to make target_score, or it is
// the same sequence as the previous minimizer which we also took.
// Locate the hits.
for (size_t j = 0; j < minimizer.hits; j++) {
pos_t hit = gbwtgraph::Position::decode(minimizer.occs[j].pos);
// Reverse the hits for a reverse minimizer
if (minimizer.value.is_reverse) {
size_t node_length = this->gbwt_graph.get_length(this->gbwt_graph.get_handle(id(hit)));
hit = reverse_base_pos(hit, node_length);
}
// Extract component id and offset in the root chain, if we have them for this seed.
// TODO: Get all the seed values here
tuple<bool, size_t, size_t, bool, size_t, size_t, size_t, size_t, bool> chain_info
(false, MIPayload::NO_VALUE, MIPayload::NO_VALUE, false, MIPayload::NO_VALUE, MIPayload::NO_VALUE, MIPayload::NO_VALUE, MIPayload::NO_VALUE, false );
if (minimizer.occs[j].payload != MIPayload::NO_CODE) {
chain_info = MIPayload::decode(minimizer.occs[j].payload);
}
seeds.push_back({ hit, i, std::get<0>(chain_info), std::get<1>(chain_info), std::get<2>(chain_info),
std::get<3>(chain_info), std::get<4>(chain_info), std::get<5>(chain_info), std::get<6>(chain_info), std::get<7>(chain_info), std::get<8>(chain_info) });
}
if (!(took_last && i > 0 && minimizer.value.key == minimizers[i - 1].value.key)) {
// We did not also take a previous identical-sequence minimizer, so count this one towards the score.
selected_score += minimizer.score;
}
// Remember that we took this minimizer
took_last = true;
if (this->track_provenance) {
// Record in the funnel that this minimizer gave rise to these seeds.
funnel.pass("any-hits", i);
funnel.pass("hard-hit-cap", i);
funnel.pass("hit-cap||score-fraction", i, selected_score / base_target_score);
funnel.expand(i, minimizer.hits);
}
} else if (minimizer.hits <= this->hard_hit_cap) {
// Passed hard hit cap but failed score fraction/normal hit cap
took_last = false;
rejected_count++;
if (this->track_provenance) {
funnel.pass("any-hits", i);
funnel.pass("hard-hit-cap", i);
funnel.fail("hit-cap||score-fraction", i, (selected_score + minimizer.score) / base_target_score);
}
//Stop looking for more minimizers once we fail the score fraction
target_score = selected_score;
} else {
// Failed hard hit cap
took_last = false;
rejected_count++;
if (this->track_provenance) {
funnel.pass("any-hits", i);
funnel.fail("hard-hit-cap", i);
}
}
if (this->track_provenance) {
// Say we're done with this input item
funnel.processed_input();
}
}
if (this->track_provenance && this->track_correctness) {
// Tag seeds with correctness based on proximity along paths to the input read's refpos
funnel.substage("correct");
if (this->path_graph == nullptr) {
cerr << "error[vg::MinimizerMapper] Cannot use track_correctness with no XG index" << endl;
exit(1);
}
if (aln.refpos_size() != 0) {
// Take the first refpos as the true position.
auto& true_pos = aln.refpos(0);
for (size_t i = 0; i < seeds.size(); i++) {
// Find every seed's reference positions. This maps from path name to pairs of offset and orientation.
auto offsets = algorithms::nearest_offsets_in_paths(this->path_graph, seeds[i].pos, 100);
for (auto& hit_pos : offsets[this->path_graph->get_path_handle(true_pos.name())]) {
// Look at all the ones on the path the read's true position is on.
if (abs((int64_t)hit_pos.first - (int64_t) true_pos.offset()) < 200) {
// Call this seed hit close enough to be correct
funnel.tag_correct(i);
}
}
}
}
}
#ifdef debug
std::cerr << "Found " << seeds.size() << " seeds from " << (minimizers.size() - rejected_count) << " minimizers, rejected " << rejected_count << std::endl;
#endif
return seeds;
}
//-----------------------------------------------------------------------------
void MinimizerMapper::score_cluster(Cluster& cluster, size_t i, const std::vector<Minimizer>& minimizers, const std::vector<Seed>& seeds, size_t seq_length, Funnel& funnel) const {
if (this->track_provenance) {
// Say we're making it
funnel.producing_output(i);
}
// Initialize the values.
cluster.score = 0.0;
cluster.coverage = 0.0;
cluster.present = SmallBitset(minimizers.size());
// Determine the minimizers that are present in the cluster.
for (auto hit_index : cluster.seeds) {
cluster.present.insert(seeds[hit_index].source);
#ifdef debug
cerr << "Minimizer " << seeds[hit_index].source << " is present in cluster " << i << endl;
#endif
}
// Compute the score and cluster coverage.
sdsl::bit_vector covered(seq_length, 0);
for (size_t j = 0; j < minimizers.size(); j++) {
if (cluster.present.contains(j)) {
const Minimizer& minimizer = minimizers[j];
cluster.score += minimizer.score;
// The offset of a reverse minimizer is the endpoint of the kmer
size_t start_offset = minimizer.forward_offset();
size_t k = minimizer.length;
// Set the k bits starting at start_offset.
covered.set_int(start_offset, sdsl::bits::lo_set[k], k);
}
}
// Count up the covered positions and turn it into a fraction.
cluster.coverage = sdsl::util::cnt_one_bits(covered) / static_cast<double>(seq_length);
if (this->track_provenance) {
// Record the cluster in the funnel as a group of the size of the number of items.
funnel.merge_group(cluster.seeds.begin(), cluster.seeds.end());
funnel.score(funnel.latest(), cluster.score);
// Say we made it.
funnel.produced_output();
}
}
//-----------------------------------------------------------------------------
int MinimizerMapper::score_extension_group(const Alignment& aln, const vector<GaplessExtension>& extended_seeds,
int gap_open_penalty, int gap_extend_penalty) {
if (extended_seeds.empty()) {
// TODO: We should never see an empty group of extensions
return 0;
} else if (extended_seeds.front().full()) {
// These are length matches. We already have the score.
int best_score = 0;
for (auto& extension : extended_seeds) {
best_score = max(best_score, extension.score);
}
return best_score;
} else {
// This is a collection of one or more non-full-length extended seeds.
if (aln.sequence().size() == 0) {
// No score here
return 0;
}
// We use a sweep line algorithm to find relevant points along the read: extension starts or ends.
// This records the last base to be covered by the current sweep line.
int64_t sweep_line = 0;
// This records the first base not covered by the last sweep line.
int64_t last_sweep_line = 0;
// And we track the next unentered gapless extension
size_t unentered = 0;
// Extensions we are in are in this min-heap of past-end position and gapless extension number.
vector<pair<size_t, size_t>> end_heap;
// The heap uses this comparator
auto min_heap_on_first = [](const pair<size_t, size_t>& a, const pair<size_t, size_t>& b) {
// Return true if a must come later in the heap than b
return a.first > b.first;
};
// We track the best score for a chain reaching the position before this one and ending in a gap.
// We never let it go below 0.
// Will be 0 when there's no gap that can be open
int best_gap_score = 0;
// We track the score for the best chain ending with each gapless extension
vector<int> best_chain_score(extended_seeds.size(), 0);
// And we're after the best score overall that we can reach when an extension ends
int best_past_ending_score_ever = 0;
// Overlaps are more complicated.
// We need a heap of all the extensions for which we have seen the
// start and that we can thus overlap.
// We filter things at the top of the heap if their past-end positions
// have occurred.
// So we store pairs of score we get backtracking to the current
// position, and past-end position for the thing we are backtracking
// from.
vector<pair<int, size_t>> overlap_heap;
// We can just use the standard max-heap comparator
// We encode the score relative to a counter that we increase by the
// gap extend every base we go through, so we don't need to update and
// re-sort the heap.
int overlap_score_offset = 0;
while(last_sweep_line <= aln.sequence().size()) {
// We are processed through the position before last_sweep_line.
// Find a place for sweep_line to go
// Find the next seed start
int64_t next_seed_start = numeric_limits<int64_t>::max();
if (unentered < extended_seeds.size()) {
next_seed_start = extended_seeds[unentered].read_interval.first;
}
// Find the next seed end
int64_t next_seed_end = numeric_limits<int64_t>::max();
if (!end_heap.empty()) {
next_seed_end = end_heap.front().first;
}
// Whichever is closer between those points and the end, do that.
sweep_line = min(min(next_seed_end, next_seed_start), (int64_t) aln.sequence().size());
// So now we're only interested in things that happen at sweep_line.
// Compute the distance from the previous sweep line position
// Make sure to account for last_sweep_line's semantics as the next unswept base.
int sweep_distance = sweep_line - last_sweep_line + 1;
// We need to track the score of the best thing that past-ended here
int best_past_ending_score_here = 0;
while(!end_heap.empty() && end_heap.front().first == sweep_line) {
// Find anything that past-ends here
size_t past_ending = end_heap.front().second;
// Mix it into the score
best_past_ending_score_here = std::max(best_past_ending_score_here, best_chain_score[past_ending]);
// Remove it from the end-tracking heap
std::pop_heap(end_heap.begin(), end_heap.end(), min_heap_on_first);
end_heap.pop_back();
}
// Mix that into the best score overall
best_past_ending_score_ever = std::max(best_past_ending_score_ever, best_past_ending_score_here);
if (sweep_line == aln.sequence().size()) {
// We don't need to think about gaps or backtracking anymore since everything has ended
break;
}
// Update the overlap score offset by removing some gap extends from it.
overlap_score_offset += sweep_distance * gap_extend_penalty;
// The best way to backtrack to here is whatever is on top of the heap, if anything, that doesn't past-end here.
int best_overlap_score = 0;
while (!overlap_heap.empty()) {
// While there is stuff on the heap
if (overlap_heap.front().second <= sweep_line) {
// We are already past this thing, so drop it
std::pop_heap(overlap_heap.begin(), overlap_heap.end());
overlap_heap.pop_back();
} else {
// This is at the top of the heap and we aren't past it
// Decode and use its score offset if we only backtrack to here.
best_overlap_score = overlap_heap.front().first + overlap_score_offset;
// Stop looking in the heap
break;
}
}
// The best way to end 1 before here in a gap is either:
if (best_gap_score != 0) {
// Best way to end 1 before our last sweep line position with a gap, plus distance times gap extend penalty
best_gap_score -= sweep_distance * gap_extend_penalty;
}
// Best way to end 1 before here with an actual extension, plus the gap open part of the gap open penalty.
// (Will never be taken over an actual adjacency)
best_gap_score = std::max(0, std::max(best_gap_score, best_past_ending_score_here - (gap_open_penalty - gap_extend_penalty)));
while (unentered < extended_seeds.size() && extended_seeds[unentered].read_interval.first == sweep_line) {
// For each thing that starts here
// Compute its chain score
best_chain_score[unentered] = std::max(best_overlap_score,
std::max(best_gap_score, best_past_ending_score_here)) + extended_seeds[unentered].score;
// Compute its backtrack-to-here score and add it to the backtracking heap
// We want how far we would have had to have backtracked to be
// able to preceed the base we are at now, where this thing
// starts.
size_t extension_length = extended_seeds[unentered].read_interval.second - extended_seeds[unentered].read_interval.first;
int raw_overlap_score = best_chain_score[unentered] - gap_open_penalty - gap_extend_penalty * extension_length;
int encoded_overlap_score = raw_overlap_score - overlap_score_offset;
// Stick it in the heap
overlap_heap.emplace_back(encoded_overlap_score, extended_seeds[unentered].read_interval.second);
std::push_heap(overlap_heap.begin(), overlap_heap.end());
// Add it to the end finding heap
end_heap.emplace_back(extended_seeds[unentered].read_interval.second, unentered);
std::push_heap(end_heap.begin(), end_heap.end(), min_heap_on_first);
// Advance and check the next thing to start
unentered++;
}
// Move last_sweep_line to sweep_line.
// We need to add 1 since last_sweep_line is the next *un*included base
last_sweep_line = sweep_line + 1;
}
// When we get here, we've seen the end of every extension and so we
// have the best score at the end of any of them.
return best_past_ending_score_ever;
}
}
std::vector<int> MinimizerMapper::score_extensions(const std::vector<std::vector<GaplessExtension>>& extensions, const Alignment& aln, Funnel& funnel) const {
// Extension scoring substage.
if (this->track_provenance) {
funnel.substage("score");
}
// We now estimate the best possible alignment score for each cluster.
std::vector<int> result(extensions.size(), 0);
for (size_t i = 0; i < extensions.size(); i++) {
if (this->track_provenance) {
funnel.producing_output(i);
}
result[i] = score_extension_group(aln, extensions[i], get_regular_aligner()->gap_open, get_regular_aligner()->gap_extension);
// Record the score with the funnel.
if (this->track_provenance) {
funnel.score(i, result[i]);
funnel.produced_output();
}
}
return result;
}
std::vector<int> MinimizerMapper::score_extensions(const std::vector<std::pair<std::vector<GaplessExtension>, size_t>>& extensions, const Alignment& aln, Funnel& funnel) const {
// Extension scoring substage.
if (this->track_provenance) {
funnel.substage("score");
}
// We now estimate the best possible alignment score for each cluster.
std::vector<int> result(extensions.size(), 0);
for (size_t i = 0; i < extensions.size(); i++) {
if (this->track_provenance) {
funnel.producing_output(i);
}
result[i] = score_extension_group(aln, extensions[i].first, get_regular_aligner()->gap_open, get_regular_aligner()->gap_extension);
// Record the score with the funnel.
if (this->track_provenance) {
funnel.score(i, result[i]);
funnel.produced_output();
}
}
return result;
}
//-----------------------------------------------------------------------------
void MinimizerMapper::find_optimal_tail_alignments(const Alignment& aln, const vector<GaplessExtension>& extended_seeds, Alignment& best, Alignment& second_best) const {
#ifdef debug
cerr << "Trying to find tail alignments for " << extended_seeds.size() << " extended seeds" << endl;
#endif
// Make paths for all the extensions
vector<Path> extension_paths;
vector<double> extension_path_scores;
extension_paths.reserve(extended_seeds.size());
extension_path_scores.reserve(extended_seeds.size());
for (auto& extended_seed : extended_seeds) {
// Compute the path for each extension
extension_paths.push_back(extended_seed.to_path(gbwt_graph, aln.sequence()));
// And the extension's score
extension_path_scores.push_back(get_regular_aligner()->score_partial_alignment(aln, gbwt_graph, extension_paths.back(),
aln.sequence().begin() + extended_seed.read_interval.first));
}
// We will keep the winning alignment here, in pieces
Path winning_left;
Path winning_middle;
Path winning_right;
size_t winning_score = 0;
Path second_left;
Path second_middle;
Path second_right;
size_t second_score = 0;
// Handle each extension in the set
process_until_threshold_b(extended_seeds, extension_path_scores,
extension_score_threshold, 1, max_local_extensions,
(function<double(size_t)>) [&](size_t extended_seed_num) {
// This extended seed looks good enough.
// TODO: We don't track this filter with the funnel because it
// operates within a single "item" (i.e. cluster/extension set).
// We track provenance at the item level, so throwing out wrong
// local alignments in a correct cluster would look like throwing
// out correct things.
// TODO: Revise how we track correctness and provenance to follow
// sub-cluster things.
// We start with the path in extension_paths[extended_seed_num],
// scored in extension_path_scores[extended_seed_num]
// We also have a left tail path and score
pair<Path, int64_t> left_tail_result {{}, 0};
// And a right tail path and score
pair<Path, int64_t> right_tail_result {{}, 0};
if (extended_seeds[extended_seed_num].read_interval.first != 0) {
// There is a left tail
// Get the forest of all left tail placements
auto forest = get_tail_forest(extended_seeds[extended_seed_num], aln.sequence().size(), true);
// Grab the part of the read sequence that comes before the extension
string before_sequence = aln.sequence().substr(0, extended_seeds[extended_seed_num].read_interval.first);
// Do right-pinned alignment
left_tail_result = std::move(get_best_alignment_against_any_tree(forest, before_sequence,
extended_seeds[extended_seed_num].starting_position(gbwt_graph), false));
}
if (extended_seeds[extended_seed_num].read_interval.second != aln.sequence().size()) {
// There is a right tail
// Get the forest of all right tail placements
auto forest = get_tail_forest(extended_seeds[extended_seed_num], aln.sequence().size(), false);
// Find the sequence
string trailing_sequence = aln.sequence().substr(extended_seeds[extended_seed_num].read_interval.second);
// Do left-pinned alignment
right_tail_result = std::move(get_best_alignment_against_any_tree(forest, trailing_sequence,
extended_seeds[extended_seed_num].tail_position(gbwt_graph), true));
}
// Compute total score
size_t total_score = extension_path_scores[extended_seed_num] + left_tail_result.second + right_tail_result.second;
//Get the node ids of the beginning and end of each alignment
id_t winning_start = winning_score == 0 ? 0 : (winning_left.mapping_size() == 0
? winning_middle.mapping(0).position().node_id()
: winning_left.mapping(0).position().node_id());
id_t current_start = left_tail_result.first.mapping_size() == 0
? extension_paths[extended_seed_num].mapping(0).position().node_id()
: left_tail_result.first.mapping(0).position().node_id();
id_t winning_end = winning_score == 0 ? 0 : (winning_right.mapping_size() == 0
? winning_middle.mapping(winning_middle.mapping_size() - 1).position().node_id()
: winning_right.mapping(winning_right.mapping_size()-1).position().node_id());
id_t current_end = right_tail_result.first.mapping_size() == 0
? extension_paths[extended_seed_num].mapping(extension_paths[extended_seed_num].mapping_size() - 1).position().node_id()
: right_tail_result.first.mapping(right_tail_result.first.mapping_size()-1).position().node_id();
//Is this left tail different from the currently winning left tail?
bool different_left = winning_start != current_start;
bool different_right = winning_end != current_end;
if (total_score > winning_score || winning_score == 0) {
// This is the new best alignment seen so far.
if (winning_score != 0 && different_left && different_right) {
//The previous best scoring alignment replaces the second best
second_score = winning_score;
second_left = std::move(winning_left);
second_middle = std::move(winning_middle);
second_right = std::move(winning_right);
}
// Save the score
winning_score = total_score;
// And the path parts
winning_left = std::move(left_tail_result.first);
winning_middle = std::move(extension_paths[extended_seed_num]);
winning_right = std::move(right_tail_result.first);
} else if ((total_score > second_score || second_score == 0) && different_left && different_right) {
// This is the new second best alignment seen so far and it is
// different from the best alignment.
// Save the score
second_score = total_score;
// And the path parts
second_left = std::move(left_tail_result.first);
second_middle = std::move(extension_paths[extended_seed_num]);
second_right = std::move(right_tail_result.first);
}
return true;
}, [&](size_t extended_seed_num) {
// This extended seed is good enough by its own score, but we have too many.
// Do nothing
}, [&](size_t extended_seed_num) {
// This extended seed isn't good enough by its own score.
// Do nothing
});
// Now we know the winning path and score. Move them over to out
best.set_score(winning_score);
second_best.set_score(second_score);
// Concatenate the paths. We know there must be at least an edit boundary
// between each part, because the maximal extension doesn't end in a
// mismatch or indel and eats all matches.
// We also don't need to worry about jumps that skip intervening sequence.
*best.mutable_path() = std::move(winning_left);
for (auto* to_append : {&winning_middle, &winning_right}) {
// For each path to append
for (auto& mapping : *to_append->mutable_mapping()) {
// For each mapping to append
if (mapping.position().offset() != 0 && best.path().mapping_size() > 0) {
// If we have a nonzero offset in our mapping, and we follow
// something, we must be continuing on from a previous mapping to
// the node.
assert(mapping.position().node_id() == best.path().mapping(best.path().mapping_size() - 1).position().node_id());
// Find that previous mapping
auto* prev_mapping = best.mutable_path()->mutable_mapping(best.path().mapping_size() - 1);
for (auto& edit : *mapping.mutable_edit()) {
// Move over all the edits in this mapping onto the end of that one.
*prev_mapping->add_edit() = std::move(edit);
}
} else {
// If we start at offset 0 or there's nothing before us, we need to just move the whole mapping
*best.mutable_path()->add_mapping() = std::move(mapping);
}
}
}
best.set_identity(identity(best.path()));
//Do the same for the second best
*second_best.mutable_path() = std::move(second_left);
for (auto* to_append : {&second_middle, &second_right}) {
// For each path to append
for (auto& mapping : *to_append->mutable_mapping()) {
// For each mapping to append
if (mapping.position().offset() != 0 && second_best.path().mapping_size() > 0) {
// If we have a nonzero offset in our mapping, and we follow
// something, we must be continuing on from a previous mapping to
// the node.
assert(mapping.position().node_id() == second_best.path().mapping(second_best.path().mapping_size() - 1).position().node_id());
// Find that previous mapping
auto* prev_mapping = second_best.mutable_path()->mutable_mapping(second_best.path().mapping_size() - 1);
for (auto& edit : *mapping.mutable_edit()) {
// Move over all the edits in this mapping onto the end of that one.
*prev_mapping->add_edit() = std::move(edit);
}
} else {
// If we start at offset 0 or there's nothing before us, we need to just move the whole mapping
*second_best.mutable_path()->add_mapping() = std::move(mapping);
}
}
}
// Compute the identity from the path.
second_best.set_identity(identity(second_best.path()));
}
pair<Path, size_t> MinimizerMapper::get_best_alignment_against_any_tree(const vector<TreeSubgraph>& trees,
const string& sequence, const Position& default_position, bool pin_left) const {
// We want the best alignment, to the base graph, done against any target path
Path best_path;
// And its score
int64_t best_score = 0;
if (!sequence.empty()) {
// We start out with the best alignment being a pure softclip.
// If we don't have any trees, or all trees are empty, or there's nothing beter, this is what we return.
Mapping* m = best_path.add_mapping();
Edit* e = m->add_edit();
e->set_from_length(0);
e->set_to_length(sequence.size());
e->set_sequence(sequence);
// Since the softclip consumes no graph, we place it on the node we are going to.
*m->mutable_position() = default_position;
#ifdef debug
cerr << "First best alignment: " << pb2json(best_path) << " score " << best_score << endl;
#endif
}
// We can align it once per target tree
for (auto& subgraph : trees) {
// For each tree we can map against, map pinning the correct edge of the sequence to the root.
if (subgraph.get_node_count() != 0) {
// This path has bases in it and could potentially be better than
// the default full-length softclip
// Do alignment to the subgraph with GSSWAligner.
Alignment current_alignment;
// If pinning right, we need to reverse the sequence, since we are
// always pinning left to the left edge of the tree subgraph.
current_alignment.set_sequence(pin_left ? sequence : reverse_complement(sequence));
#ifdef debug
cerr << "Align " << pb2json(current_alignment) << " pinned left";
#ifdef debug_dump_graph
cerr << " vs graph:" << endl;
subgraph.for_each_handle([&](const handle_t& here) {
cerr << subgraph.get_id(here) << " (" << subgraph.get_sequence(here) << "): " << endl;
subgraph.follow_edges(here, true, [&](const handle_t& there) {
cerr << "\t" << subgraph.get_id(there) << " (" << subgraph.get_sequence(there) << ") ->" << endl;
});
subgraph.follow_edges(here, false, [&](const handle_t& there) {
cerr << "\t-> " << subgraph.get_id(there) << " (" << subgraph.get_sequence(there) << ")" << endl;
});
});
#else
cerr << endl;
#endif
#endif
// X-drop align, accounting for full length bonus.
// We *always* do left-pinned alignment internally, since that's the shape of trees we get.
get_regular_aligner()->align_pinned(current_alignment, subgraph, true, true);
#ifdef debug
cerr << "\tScore: " << current_alignment.score() << endl;
#endif
if (current_alignment.score() > best_score) {
// This is a new best alignment.
best_path = current_alignment.path();
if (!pin_left) {
// Un-reverse it if we were pinning right
best_path = reverse_complement_path(best_path, [&](id_t node) {
return subgraph.get_length(subgraph.get_handle(node, false));
});
}
// Translate from subgraph into base graph and keep it.
best_path = subgraph.translate_down(best_path);
best_score = current_alignment.score();
#ifdef debug
cerr << "New best alignment is "
<< pb2json(best_path) << " score " << best_score << endl;
#endif
}
}
}
return make_pair(best_path, best_score);
}
vector<TreeSubgraph> MinimizerMapper::get_tail_forest(const GaplessExtension& extended_seed,
size_t read_length, bool left_tails) const {
// We will fill this in with all the trees we return
vector<TreeSubgraph> to_return;
// Now for this extension, walk the GBWT in the appropriate direction
#ifdef debug
cerr << "Look for " << (left_tails ? "left" : "right") << " tails from extension" << endl;
#endif
// TODO: Come up with a better way to do this with more accessors on the extension and less get_handle
// Get the Position reading out of the extension on the appropriate tail
Position from;
// And the length of that tail
size_t tail_length;
// And the GBWT search state we want to start with
const gbwt::SearchState* base_state = nullptr;
if (left_tails) {
// Look right from start
from = extended_seed.starting_position(gbwt_graph);
// And then flip to look the other way at the prev base
from = reverse(from, gbwt_graph.get_length(gbwt_graph.get_handle(from.node_id(), false)));
// Use the search state going backward
base_state = &extended_seed.state.backward;
tail_length = extended_seed.read_interval.first;
} else {
// Look right from end
from = extended_seed.tail_position(gbwt_graph);
// Use the search state going forward
base_state = &extended_seed.state.forward;
tail_length = read_length - extended_seed.read_interval.second;
}
if (tail_length == 0) {
// Don't go looking for places to put no tail.
return to_return;
}
// This is one tree that we are filling in
vector<pair<int64_t, handle_t>> tree;
// This is a stack of indexes at which we put parents in the tree
list<int64_t> parent_stack;
// Get the handle we are starting from
// TODO: is it cheaper to get this out of base_state?
handle_t start_handle = gbwt_graph.get_handle(from.node_id(), from.is_reverse());
// Decide if the start node will end up included in the tree, or if we cut it all off with the offset.
bool start_included = (from.offset() < gbwt_graph.get_length(start_handle));
// How long should we search? It should be the longest detectable gap plus the remaining sequence.
size_t search_limit = get_regular_aligner()->longest_detectable_gap(tail_length, read_length) + tail_length;
// Do a DFS over the haplotypes in the GBWT out to that distance.
dfs_gbwt(*base_state, from.offset(), search_limit, [&](const handle_t& entered) {
// Enter a new handle.
if (parent_stack.empty()) {
// This is the root of a new tree in the forrest
if (!tree.empty()) {
// Save the old tree and start a new one.
// We need to cut off from.offset() from the root, unless we would cut off the whole root.
// In that case, the GBWT DFS will have skipped the empty root entirely, so we cut off nothing.
to_return.emplace_back(&gbwt_graph, std::move(tree), start_included ? from.offset() : 0);
tree.clear();
}
// Add this to the tree with no parent
tree.emplace_back(-1, entered);
} else {
// Just say this is visitable from our parent.
tree.emplace_back(parent_stack.back(), entered);
}
// Record the parent index
parent_stack.push_back(tree.size() - 1);
}, [&]() {
// Exit the last visited handle. Pop off the stack.
parent_stack.pop_back();
});
if (!tree.empty()) {
// Now save the last tree
to_return.emplace_back(&gbwt_graph, std::move(tree), start_included ? from.offset() : 0);
tree.clear();
}
#ifdef debug
cerr << "Found " << to_return.size() << " trees" << endl;
#endif
// Now we have all the trees!
return to_return;
}
size_t MinimizerMapper::immutable_path_from_length(const ImmutablePath& path) {
size_t to_return = 0;
for (auto& m : path) {
// Sum up the from lengths of all the component Mappings
to_return += mapping_from_length(m);
}
return to_return;
}
Path MinimizerMapper::to_path(const ImmutablePath& path) {
Path to_return;
for (auto& m : path) {
// Copy all the Mappings into the Path.
*to_return.add_mapping() = m;
}
// Flip the order around to actual path order.
std::reverse(to_return.mutable_mapping()->begin(), to_return.mutable_mapping()->end());
// Return the completed path
return to_return;
}
void MinimizerMapper::dfs_gbwt(const Position& from, size_t walk_distance,
const function<void(const handle_t&)>& enter_handle, const function<void(void)> exit_handle) const {
// Get a handle to the node the from position is on, in the position's forward orientation
handle_t start_handle = gbwt_graph.get_handle(from.node_id(), from.is_reverse());
// Delegate to the handle-based version
dfs_gbwt(start_handle, from.offset(), walk_distance, enter_handle, exit_handle);
}
void MinimizerMapper::dfs_gbwt(handle_t from_handle, size_t from_offset, size_t walk_distance,
const function<void(const handle_t&)>& enter_handle, const function<void(void)> exit_handle) const {
// Turn from_handle into a SearchState for everything on it.
gbwt::SearchState start_state = gbwt_graph.get_state(from_handle);
// Delegate to the state-based version
dfs_gbwt(start_state, from_offset, walk_distance, enter_handle, exit_handle);
}
void MinimizerMapper::dfs_gbwt(const gbwt::SearchState& start_state, size_t from_offset, size_t walk_distance,
const function<void(const handle_t&)>& enter_handle, const function<void(void)> exit_handle) const {
// Holds the gbwt::SearchState we are at, and the distance we have consumed
using traversal_state_t = pair<gbwt::SearchState, size_t>;
if (start_state.empty()) {
// No haplotypes even visit the first node. Stop.
return;
}
// Get the handle we are starting on
handle_t from_handle = gbwt_graph.node_to_handle(start_state.node);
// The search state represents searching through the end of the node, so we have to consume that much search limit.
// Tack on how much search limit distance we consume by going to the end of
// the node. Our start position is a cut *between* bases, and we take everything after it.
// If the cut is at the offset of the whole length of the node, we take 0 bases.
// If it is at 0, we take all the bases in the node.
size_t distance_to_node_end = gbwt_graph.get_length(from_handle) - from_offset;
#ifdef debug
cerr << "DFS starting at offset " << from_offset << " on node of length "
<< gbwt_graph.get_length(from_handle) << " leaving " << distance_to_node_end << " bp" << endl;
#endif
// Have a recursive function that does the DFS. We fire the enter and exit
// callbacks, and the user can keep their own stack.
function<void(const gbwt::SearchState&, size_t, bool)> recursive_dfs = [&](const gbwt::SearchState& here_state,
size_t used_distance, bool hide_root) {
handle_t here_handle = gbwt_graph.node_to_handle(here_state.node);
if (!hide_root) {
// Enter this handle if there are any bases on it to visit
#ifdef debug
cerr << "Enter handle " << gbwt_graph.get_id(here_handle) << " " << gbwt_graph.get_is_reverse(here_handle) << endl;
#endif
enter_handle(here_handle);
}
// Up the used distance with our length
used_distance += gbwt_graph.get_length(here_handle);
if (used_distance < walk_distance) {
// If we haven't used up all our distance yet
gbwt_graph.follow_paths(here_state, [&](const gbwt::SearchState& there_state) -> bool {
// For each next state
// Otherwise, do it with the new distance value.
// Don't hide the root on any child subtrees; only the top root can need hiding.
recursive_dfs(there_state, used_distance, false);
return true;
});
}
if (!hide_root) {
// Exit this handle if we entered it
#ifdef debug
cerr << "Exit handle " << gbwt_graph.get_id(here_handle) << " " << gbwt_graph.get_is_reverse(here_handle) << endl;
#endif
exit_handle();
}
};
// Start the DFS with our stating node, consuming the distance from our
// offset to its end. Don't show the root state to the user if we don't
// actually visit any bases on that node.
recursive_dfs(start_state, distance_to_node_end, distance_to_node_end == 0);
}
}
Go back to always running maximum_mapping_quality_exact to generate the score_group cap
/**
* \file minimizer_mapper.cpp
* Defines the code for the minimizer-and-GBWT-based mapper.
*/
#include "minimizer_mapper.hpp"
#include "annotation.hpp"
#include "path_subgraph.hpp"
#include "multipath_alignment.hpp"
#include "split_strand_graph.hpp"
#include "algorithms/dagify.hpp"
#include "algorithms/dijkstra.hpp"
#include <bdsg/overlays/strand_split_overlay.hpp>
#include <gbwtgraph/algorithms.h>
#include <gbwtgraph/cached_gbwtgraph.h>
#include <iostream>
#include <algorithm>
#include <cmath>
//#define debug
//#define print_minimizers
namespace vg {
using namespace std;
MinimizerMapper::MinimizerMapper(const gbwtgraph::GBWTGraph& graph,
const std::vector<gbwtgraph::DefaultMinimizerIndex*>& minimizer_indexes,
MinimumDistanceIndex& distance_index, const PathPositionHandleGraph* path_graph) :
path_graph(path_graph), minimizer_indexes(minimizer_indexes),
distance_index(distance_index), gbwt_graph(graph),
extender(gbwt_graph, *(get_regular_aligner())), clusterer(distance_index),
fragment_length_distr(1000,1000,0.95) {
}
//-----------------------------------------------------------------------------
void MinimizerMapper::map(Alignment& aln, AlignmentEmitter& alignment_emitter) {
// Ship out all the aligned alignments
alignment_emitter.emit_mapped_single(map(aln));
}
vector<Alignment> MinimizerMapper::map(Alignment& aln) {
#ifdef debug
cerr << "Read " << aln.name() << ": " << aln.sequence() << endl;
#endif
// Make a new funnel instrumenter to watch us map this read.
Funnel funnel;
funnel.start(aln.name());
// Minimizers sorted by score in descending order.
std::vector<Minimizer> minimizers = this->find_minimizers(aln.sequence(), funnel);
// Find the seeds and mark the minimizers that were located.
std::vector<Seed> seeds = this->find_seeds(minimizers, aln, funnel);
// Cluster the seeds. Get sets of input seed indexes that go together.
if (track_provenance) {
funnel.stage("cluster");
}
std::vector<Cluster> clusters = clusterer.cluster_seeds(seeds, get_distance_limit(aln.sequence().size()));
// Determine the scores and read coverages for each cluster.
// Also find the best and second-best cluster scores.
if (this->track_provenance) {
funnel.substage("score");
}
double best_cluster_score = 0.0, second_best_cluster_score = 0.0;
for (size_t i = 0; i < clusters.size(); i++) {
Cluster& cluster = clusters[i];
this->score_cluster(cluster, i, minimizers, seeds, aln.sequence().length(), funnel);
if (cluster.score > best_cluster_score) {
second_best_cluster_score = best_cluster_score;
best_cluster_score = cluster.score;
} else if (cluster.score > second_best_cluster_score) {
second_best_cluster_score = cluster.score;
}
}
#ifdef debug
cerr << "Found " << clusters.size() << " clusters" << endl;
#endif
// We will set a score cutoff based on the best, but move it down to the
// second best if it does not include the second best and the second best
// is within pad_cluster_score_threshold of where the cutoff would
// otherwise be. This ensures that we won't throw away all but one cluster
// based on score alone, unless it is really bad.
double cluster_score_cutoff = best_cluster_score - cluster_score_threshold;
if (cluster_score_cutoff - pad_cluster_score_threshold < second_best_cluster_score) {
cluster_score_cutoff = std::min(cluster_score_cutoff, second_best_cluster_score);
}
if (track_provenance) {
// Now we go from clusters to gapless extensions
funnel.stage("extend");
}
// These are the GaplessExtensions for all the clusters.
vector<vector<GaplessExtension>> cluster_extensions;
cluster_extensions.reserve(clusters.size());
// To compute the windows for explored minimizers, we need to get
// all the minimizers that are explored.
SmallBitset minimizer_explored(minimizers.size());
//How many hits of each minimizer ended up in each extended cluster?
vector<vector<size_t>> minimizer_extended_cluster_count;
//For each cluster, what fraction of "equivalent" clusters did we keep?
vector<double> probability_cluster_lost;
//What is the score and coverage we are considering and how many reads
size_t curr_coverage = 0;
size_t curr_score = 0;
size_t curr_kept = 0;
size_t curr_count = 0;
// We track unextended clusters.
vector<size_t> unextended_clusters;
unextended_clusters.reserve(clusters.size());
//Process clusters sorted by both score and read coverage
process_until_threshold_c<Cluster, double>(clusters, [&](size_t i) -> double {
return clusters[i].coverage;
}, [&](size_t a, size_t b) -> bool {
return ((clusters[a].coverage > clusters[b].coverage) ||
(clusters[a].coverage == clusters[b].coverage && clusters[a].score > clusters[b].score));
},
cluster_coverage_threshold, 1, max_extensions,
[&](size_t cluster_num) {
// Handle sufficiently good clusters in descending coverage order
Cluster& cluster = clusters[cluster_num];
if (track_provenance) {
funnel.pass("cluster-coverage", cluster_num, cluster.coverage);
funnel.pass("max-extensions", cluster_num);
}
// First check against the additional score filter
if (cluster_score_threshold != 0 && cluster.score < cluster_score_cutoff) {
//If the score isn't good enough, ignore this cluster
if (track_provenance) {
funnel.fail("cluster-score", cluster_num, cluster.score);
}
// Record MAPQ implications of not extending this cluster.
unextended_clusters.push_back(cluster_num);
#ifdef debug
cerr << "Cluster " << cluster_num << " fails cluster score cutoff" << endl;
cerr << "Covers " << clusters[cluster_num].coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << clusters[cluster_num].score << "/" << cluster_score_cutoff << endl;
#endif
return false;
}
if (track_provenance) {
funnel.pass("cluster-score", cluster_num, cluster.score);
funnel.processing_input(cluster_num);
}
if (cluster.coverage == curr_coverage &&
cluster.score == curr_score &&
curr_kept < max_extensions * 0.75) {
curr_kept++;
curr_count++;
} else if (cluster.coverage != curr_coverage ||
cluster.score != curr_score) {
//If this is a cluster that has scores different than the previous one
for (size_t i = 0 ; i < curr_kept ; i++ ) {
probability_cluster_lost.push_back(1.0 - (double(curr_kept) / double(curr_count)));
}
curr_coverage = cluster.coverage;
curr_score = cluster.score;
curr_kept = 1;
curr_count = 1;
} else {
//If this cluster is equivalent to the previous one and we already took enough
//equivalent clusters
curr_count ++;
// TODO: shouldn't we fail something for the funnel here?
// Record MAPQ implications of not extending this cluster.
unextended_clusters.push_back(cluster_num);
#ifdef debug
cerr << "Cluster " << cluster_num << " fails because we took too many identical clusters" << endl;
cerr << "Covers " << clusters[cluster_num].coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << clusters[cluster_num].score << "/" << cluster_score_cutoff << endl;
#endif
return false;
}
//Only keep this cluster if we have few enough equivalent clusters
#ifdef debug
cerr << "Cluster " << cluster_num << endl;
cerr << "Covers " << cluster.coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << cluster.score << "/" << cluster_score_cutoff << endl;
#endif
minimizer_extended_cluster_count.emplace_back(minimizers.size(), 0);
// Pack the seeds for GaplessExtender.
GaplessExtender::cluster_type seed_matchings;
for (auto seed_index : cluster.seeds) {
// Insert the (graph position, read offset) pair.
const Seed& seed = seeds[seed_index];
seed_matchings.insert(GaplessExtender::to_seed(seed.pos, minimizers[seed.source].value.offset));
minimizer_extended_cluster_count.back()[seed.source]++;
#ifdef debug
const Minimizer& minimizer = minimizers[seed.source];
cerr << "Seed read:" << minimizer.value.offset << " = " << seed.pos
<< " from minimizer " << seed.source << "(" << minimizer.hits << ")" << endl;
#endif
}
// Extend seed hits in the cluster into one or more gapless extensions
cluster_extensions.emplace_back(std::move(extender.extend(seed_matchings, aln.sequence())));
if (track_provenance) {
// Record with the funnel that the previous group became a group of this size.
// Don't bother recording the seed to extension matching...
funnel.project_group(cluster_num, cluster_extensions.back().size());
// Say we finished with this cluster, for now.
funnel.processed_input();
}
return true;
}, [&](size_t cluster_num) {
// There are too many sufficiently good clusters
Cluster& cluster = clusters[cluster_num];
if (track_provenance) {
funnel.pass("cluster-coverage", cluster_num, cluster.coverage);
funnel.fail("max-extensions", cluster_num);
}
if (cluster.coverage == curr_coverage &&
cluster.score == curr_score) {
curr_count ++;
} else {
for (size_t i = 0 ; i < curr_kept ; i++ ) {
probability_cluster_lost.push_back(1.0 - (double(curr_kept) / double(curr_count)));
}
curr_score = 0;
curr_coverage = 0;
curr_kept = 0;
curr_count = 0;
}
// Record MAPQ implications of not extending this cluster.
unextended_clusters.push_back(cluster_num);
#ifdef debug
cerr << "Cluster " << cluster_num << " passes cluster cutoffs but we have too many" << endl;
cerr << "Covers " << cluster.coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << cluster.score << "/" << cluster_score_cutoff << endl;
#endif
}, [&](size_t cluster_num) {
// This cluster is not sufficiently good.
if (track_provenance) {
funnel.fail("cluster-coverage", cluster_num, clusters[cluster_num].coverage);
}
for (size_t i = 0 ; i < curr_kept ; i++ ) {
probability_cluster_lost.push_back(1.0 - (double(curr_kept) / double(curr_count)));
}
curr_kept = 0;
curr_count = 0;
curr_score = 0;
curr_coverage = 0;
// Record MAPQ implications of not extending this cluster.
unextended_clusters.push_back(cluster_num);
#ifdef debug
cerr << "Cluster " << cluster_num << " fails cluster coverage cutoffs" << endl;
cerr << "Covers " << clusters[cluster_num].coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << clusters[cluster_num].score << "/" << cluster_score_cutoff << endl;
#endif
});
for (size_t i = 0 ; i < curr_kept ; i++ ) {
probability_cluster_lost.push_back(1.0 - (double(curr_kept) / double(curr_count)));
}
std::vector<int> cluster_extension_scores = this->score_extensions(cluster_extensions, aln, funnel);
if (track_provenance) {
funnel.stage("align");
}
//How many of each minimizer ends up in an extension set that actually gets turned into an alignment?
vector<size_t> minimizer_extensions_count(minimizers.size(), 0);
// Now start the alignment step. Everything has to become an alignment.
// We will fill this with all computed alignments in estimated score order.
vector<Alignment> alignments;
alignments.reserve(cluster_extensions.size());
// This maps from alignment index back to cluster extension index, for
// tracing back to minimizers for MAPQ. Can hold
// numeric_limits<size_t>::max() for an unaligned alignment.
vector<size_t> alignments_to_source;
alignments_to_source.reserve(cluster_extensions.size());
//probability_cluster_lost but ordered by alignment
vector<double> probability_alignment_lost;
probability_alignment_lost.reserve(cluster_extensions.size());
// Create a new alignment object to get rid of old annotations.
{
Alignment temp;
temp.set_sequence(aln.sequence());
temp.set_name(aln.name());
temp.set_quality(aln.quality());
aln = std::move(temp);
}
// Annotate the read with metadata
if (!sample_name.empty()) {
aln.set_sample_name(sample_name);
}
if (!read_group.empty()) {
aln.set_read_group(read_group);
}
// Go through the gapless extension groups in score order.
process_until_threshold_b(cluster_extensions, cluster_extension_scores,
extension_set_score_threshold, 2, max_alignments,
[&](size_t extension_num) {
// This extension set is good enough.
// Called in descending score order.
if (track_provenance) {
funnel.pass("extension-set", extension_num, cluster_extension_scores[extension_num]);
funnel.pass("max-alignments", extension_num);
funnel.processing_input(extension_num);
}
auto& extensions = cluster_extensions[extension_num];
// Get an Alignments best_ and second_best_alignment of it somehow, and throw it in.
Alignment best_alignment = aln;
Alignment second_best_alignment = aln;
// Determine if we got full-length alignments or local alignments.
bool full_length_extensions = (extensions.size() <= 2);
for (auto& extension : extensions) {
full_length_extensions &= extension.full();
}
if (full_length_extensions) {
// We got full-length extensions, so directly convert to an Alignment.
if (track_provenance) {
funnel.substage("direct");
}
//Fill in the best alignments from the extension
this->extension_to_alignment(extensions.front(), best_alignment);
if (extensions.size() > 1) {
//Do the same thing for the second extension, if one exists
this->extension_to_alignment(extensions.back(), second_best_alignment);
}
if (track_provenance) {
// Stop the current substage
funnel.substage_stop();
}
} else if (do_dp) {
// We need to do chaining.
if (track_provenance) {
funnel.substage("chain");
}
// Do the DP and compute alignment into best_alignment and
// second_best_extension, if there is a second best
find_optimal_tail_alignments(aln, extensions, best_alignment, second_best_alignment);
if (track_provenance) {
// We're done chaining. Next alignment may not go through this substage.
funnel.substage_stop();
}
} else {
// We would do chaining but it is disabled.
// Leave best_alignment unaligned
}
if (second_best_alignment.score() != 0 &&
second_best_alignment.score() > best_alignment.score() * 0.8) {
//If there is a second extension and its score is at least half of the best score, bring it along
#ifdef debug
cerr << "Found second best alignment from gapless extension " << extension_num << ": " << pb2json(second_best_alignment) << endl;
#endif
alignments.emplace_back(std::move(second_best_alignment));
alignments_to_source.push_back(extension_num);
probability_alignment_lost.push_back(probability_cluster_lost[extension_num]);
if (track_provenance) {
funnel.project(extension_num);
funnel.score(alignments.size() - 1, alignments.back().score());
// We're done with this input item
funnel.processed_input();
}
}
#ifdef debug
cerr << "Found best alignment from gapless extension " << extension_num << ": " << pb2json(best_alignment) << endl;
#endif
alignments.push_back(std::move(best_alignment));
alignments_to_source.push_back(extension_num);
probability_alignment_lost.push_back(probability_cluster_lost[extension_num]);
if (track_provenance) {
funnel.project(extension_num);
funnel.score(alignments.size() - 1, alignments.back().score());
// We're done with this input item
funnel.processed_input();
}
for (size_t i = 0 ; i < minimizer_extended_cluster_count[extension_num].size() ; i++) {
minimizer_extensions_count[i] += minimizer_extended_cluster_count[extension_num][i];
if (minimizer_extended_cluster_count[extension_num][i] > 0) {
// This minimizer is in an extended cluster that gave rise
// to at least one alignment, so it is explored.
minimizer_explored.insert(i);
}
}
return true;
}, [&](size_t extension_num) {
// There are too many sufficiently good extensions
if (track_provenance) {
funnel.pass("extension-set", extension_num, cluster_extension_scores[extension_num]);
funnel.fail("max-alignments", extension_num);
}
#ifdef debug
cerr << "gapless extension " << extension_num << " failed because there were too many good extensions" << endl;
#endif
}, [&](size_t extension_num) {
// This extension is not good enough.
if (track_provenance) {
funnel.fail("extension-set", extension_num, cluster_extension_scores[extension_num]);
}
#ifdef debug
cerr << "gapless extension " << extension_num << " failed because its score was not good enough (score=" << cluster_extension_scores[extension_num] << ")" << endl;
#endif
});
if (alignments.size() == 0) {
// Produce an unaligned Alignment
alignments.emplace_back(aln);
alignments_to_source.push_back(numeric_limits<size_t>::max());
probability_alignment_lost.push_back(0);
if (track_provenance) {
// Say it came from nowhere
funnel.introduce();
}
}
if (track_provenance) {
// Now say we are finding the winner(s)
funnel.stage("winner");
}
// Fill this in with the alignments we will output as mappings
vector<Alignment> mappings;
mappings.reserve(min(alignments.size(), max_multimaps));
// Track which Alignments they are
vector<size_t> mappings_to_source;
mappings_to_source.reserve(min(alignments.size(), max_multimaps));
// Grab all the scores in order for MAPQ computation.
vector<double> scores;
scores.reserve(alignments.size());
vector<double> probability_mapping_lost;
process_until_threshold_a(alignments, (std::function<double(size_t)>) [&](size_t i) -> double {
return alignments.at(i).score();
}, 0, 1, max_multimaps, [&](size_t alignment_num) {
// This alignment makes it
// Called in score order
// Remember the score at its rank
scores.emplace_back(alignments[alignment_num].score());
// Remember the output alignment
mappings.emplace_back(std::move(alignments[alignment_num]));
mappings_to_source.push_back(alignment_num);
probability_mapping_lost.push_back(probability_alignment_lost[alignment_num]);
if (track_provenance) {
// Tell the funnel
funnel.pass("max-multimaps", alignment_num);
funnel.project(alignment_num);
funnel.score(alignment_num, scores.back());
}
return true;
}, [&](size_t alignment_num) {
// We already have enough alignments, although this one has a good score
// Remember the score at its rank anyway
scores.emplace_back(alignments[alignment_num].score());
if (track_provenance) {
funnel.fail("max-multimaps", alignment_num);
}
}, [&](size_t alignment_num) {
// This alignment does not have a sufficiently good score
// Score threshold is 0; this should never happen
assert(false);
});
if (track_provenance) {
funnel.substage("mapq");
}
#ifdef debug
cerr << "Picked best alignment " << pb2json(mappings[0]) << endl;
cerr << "For scores ";
for (auto& score : scores) cerr << score << " ";
#endif
size_t winning_index;
assert(!mappings.empty());
// Compute MAPQ if not unmapped. Otherwise use 0 instead of the 50% this would give us.
double mapq = (mappings.front().path().mapping_size() == 0) ? 0 :
get_regular_aligner()->maximum_mapping_quality_exact(scores, &winning_index) / 2;
#ifdef print_minimizers
double uncapped_mapq = mapq;
#endif
#ifdef debug
cerr << "uncapped MAPQ is " << mapq << endl;
#endif
if (probability_mapping_lost.front() > 0) {
mapq = min(mapq,round(prob_to_phred(probability_mapping_lost.front())));
}
// TODO: give SmallBitset iterators so we can use it instead of an index vector.
vector<size_t> explored_minimizers;
for (size_t i = 0; i < minimizers.size(); i++) {
if (minimizer_explored.contains(i)) {
explored_minimizers.push_back(i);
}
}
// Compute caps on MAPQ. TODO: avoid needing to pass as much stuff along.
double mapq_explored_cap = 2 * faster_cap(minimizers, explored_minimizers, aln.sequence(), aln.quality());
// Remember the uncapped MAPQ and the caps
set_annotation(mappings.front(), "mapq_uncapped", mapq);
set_annotation(mappings.front(), "mapq_explored_cap", mapq_explored_cap);
// Apply the caps and transformations
mapq = round(0.85 * min(mapq_explored_cap, min(mapq, 70.0)));
#ifdef debug
cerr << "Explored cap is " << mapq_explored_cap << endl;
cerr << "MAPQ is " << mapq << endl;
#endif
// Make sure to clamp 0-60.
mappings.front().set_mapping_quality(max(min(mapq, 60.0), 0.0));
if (track_provenance) {
funnel.substage_stop();
}
for (size_t i = 0; i < mappings.size(); i++) {
// For each output alignment in score order
auto& out = mappings[i];
// Assign primary and secondary status
out.set_is_secondary(i > 0);
}
// Stop this alignment
funnel.stop();
if (track_provenance) {
// Annotate with the number of results in play at each stage
funnel.for_each_stage([&](const string& stage, const vector<size_t>& result_sizes) {
// Save the number of items
set_annotation(mappings[0], "stage_" + stage + "_results", (double)result_sizes.size());
});
if (track_correctness) {
// And with the last stage at which we had any descendants of the correct seed hit locations
set_annotation(mappings[0], "last_correct_stage", funnel.last_correct_stage());
}
// Annotate with the performances of all the filters
// We need to track filter number
size_t filter_num = 0;
funnel.for_each_filter([&](const string& stage, const string& filter,
const Funnel::FilterPerformance& by_count, const Funnel::FilterPerformance& by_size,
const vector<double>& filter_statistics_correct, const vector<double>& filter_statistics_non_correct) {
string filter_id = to_string(filter_num) + "_" + filter + "_" + stage;
// Save the stats
set_annotation(mappings[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(mappings[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(mappings[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(mappings[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(mappings[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(mappings[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(mappings[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(mappings[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(mappings[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(mappings[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
filter_num++;
});
// Annotate with parameters used for the filters.
set_annotation(mappings[0], "param_hit-cap", (double) hit_cap);
set_annotation(mappings[0], "param_hard-hit-cap", (double) hard_hit_cap);
set_annotation(mappings[0], "param_score-fraction", (double) minimizer_score_fraction);
set_annotation(mappings[0], "param_max-extensions", (double) max_extensions);
set_annotation(mappings[0], "param_max-alignments", (double) max_alignments);
set_annotation(mappings[0], "param_cluster-score", (double) cluster_score_threshold);
set_annotation(mappings[0], "param_cluster-coverage", (double) cluster_coverage_threshold);
set_annotation(mappings[0], "param_extension-set", (double) extension_set_score_threshold);
set_annotation(mappings[0], "param_max-multimaps", (double) max_multimaps);
}
#ifdef print_minimizers
cerr << aln.sequence() << "\t";
for (char c : aln.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << clusters.size();
for (size_t i = 0 ; i < minimizers.size() ; i++) {
auto& minimizer = minimizers[i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_extensions_count[i];
if (minimizer_extensions_count[i]>0) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << uncapped_mapq << "\t" << mapq_explored_cap << "\t" << probability_mapping_lost.front() << "\t" << mappings.front().mapping_quality();
if (track_correctness) {
cerr << "\t" << funnel.last_correct_stage() << endl;
} else {
cerr << "\t" << "?" << endl;
}
#endif
#ifdef debug
// Dump the funnel info graph.
funnel.to_dot(cerr);
#endif
return mappings;
}
//-----------------------------------------------------------------------------
pair<vector<Alignment>, vector<Alignment>> MinimizerMapper::map_paired(Alignment& aln1, Alignment& aln2,
vector<pair<Alignment, Alignment>>& ambiguous_pair_buffer){
if (fragment_length_distr.is_finalized()) {
//If we know the fragment length distribution then we just map paired ended
return map_paired(aln1, aln2);
} else {
//If we don't know the fragment length distribution, map the reads single ended
vector<Alignment> alns1(map(aln1));
vector<Alignment> alns2(map(aln2));
// Check if the separately-mapped ends are both sufficiently perfect and sufficiently unique
int32_t max_score_aln_1 = get_regular_aligner()->score_exact_match(aln1, 0, aln1.sequence().size());
int32_t max_score_aln_2 = get_regular_aligner()->score_exact_match(aln2, 0, aln2.sequence().size());
if (!alns1.empty() && ! alns2.empty() &&
alns1.front().mapping_quality() == 60 && alns2.front().mapping_quality() == 60 &&
alns1.front().score() >= max_score_aln_1 * 0.85 && alns2.front().score() >= max_score_aln_2 * 0.85) {
//Flip the second alignment to get the proper fragment distance
reverse_complement_alignment_in_place(&alns2.front(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
int64_t dist = distance_between(alns1.front(), alns2.front());
// And that they have an actual pair distance and set of relative orientations
if (dist == std::numeric_limits<int64_t>::max()) {
//If the distance between them is ambiguous, leave them unmapped
ambiguous_pair_buffer.emplace_back(aln1, aln2);
pair<vector<Alignment>, vector<Alignment>> empty;
return empty;
}
//If we're keeping this alignment, flip the second alignment back
reverse_complement_alignment_in_place(&alns2.front(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
// If that all checks out, say they're mapped, emit them, and register their distance and orientations
fragment_length_distr.register_fragment_length(dist);
pair<vector<Alignment>, vector<Alignment>> mapped_pair;
mapped_pair.first.emplace_back(alns1.front());
mapped_pair.second.emplace_back(alns2.front());
return mapped_pair;
} else {
// Otherwise, discard the mappings and put them in the ambiguous buffer
ambiguous_pair_buffer.emplace_back(aln1, aln2);
pair<vector<Alignment>, vector<Alignment>> empty;
return empty;
}
}
}
pair<vector<Alignment>, vector< Alignment>> MinimizerMapper::map_paired(Alignment& aln1, Alignment& aln2) {
// For each input alignment
#ifdef debug
cerr << "Read pair " << aln1.name() << ": " << aln1.sequence() << " and " << aln2.name() << ": " << aln2.sequence() << endl;
#endif
// Assume reads are in inward orientations on input, and
// convert to rightward orientations before mapping
// and flip the second read back before output
aln2.clear_path();
reverse_complement_alignment_in_place(&aln2, [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
// Make two new funnel instrumenters to watch us map this read pair.
vector<Funnel> funnels;
funnels.resize(2);
// Start this alignment
funnels[0].start(aln1.name());
funnels[1].start(aln2.name());
// Annotate the original read with metadata
if (!sample_name.empty()) {
aln1.set_sample_name(sample_name);
aln2.set_sample_name(sample_name);
}
if (!read_group.empty()) {
aln1.set_read_group(read_group);
aln2.set_read_group(read_group);
}
// Minimizers for both reads, sorted by score in descending order.
std::vector<std::vector<Minimizer>> minimizers_by_read(2);
minimizers_by_read[0] = this->find_minimizers(aln1.sequence(), funnels[0]);
minimizers_by_read[1] = this->find_minimizers(aln2.sequence(), funnels[1]);
// Seeds for both reads, stored in separate vectors.
std::vector<std::vector<Seed>> seeds_by_read(2);
seeds_by_read[0] = this->find_seeds(minimizers_by_read[0], aln1, funnels[0]);
seeds_by_read[1] = this->find_seeds(minimizers_by_read[1], aln2, funnels[1]);
// Cluster the seeds. Get sets of input seed indexes that go together.
// If the fragment length distribution hasn't been fixed yet (if the expected fragment length = 0),
// then everything will be in the same cluster and the best pair will be the two best independent mappings
if (track_provenance) {
funnels[0].stage("cluster");
funnels[1].stage("cluster");
}
std::vector<std::vector<Cluster>> all_clusters = clusterer.cluster_seeds(seeds_by_read, get_distance_limit(aln1.sequence().size()),
fragment_length_distr.mean() + paired_distance_stdevs * fragment_length_distr.std_dev());
//For each fragment cluster, determine if it has clusters from both reads
size_t max_fragment_num = 0;
for (auto& cluster : all_clusters[0]) {
max_fragment_num = std::max(max_fragment_num, cluster.fragment);
}
for (auto& cluster : all_clusters[1]) {
max_fragment_num = std::max(max_fragment_num, cluster.fragment);
}
#ifdef debug
cerr << "Found " << max_fragment_num << " fragment clusters" << endl;
#endif
vector<bool> has_first_read (max_fragment_num+1, false);//For each fragment cluster, does it have a cluster for the first read
vector<bool> fragment_cluster_has_pair (max_fragment_num+1, false);//Does a fragment cluster have both reads
bool found_paired_cluster = false;
for (auto& cluster : all_clusters[0]) {
size_t fragment_num = cluster.fragment;
has_first_read[fragment_num] = true;
}
for (auto& cluster : all_clusters[1]) {
size_t fragment_num = cluster.fragment;
fragment_cluster_has_pair[fragment_num] = has_first_read[fragment_num];
if (has_first_read[fragment_num]) {
found_paired_cluster = true;
#ifdef debug
cerr << "Fragment cluster " << fragment_num << " has read clusters from both reads" << endl;
#endif
}
}
if (track_provenance) {
funnels[0].substage("score");
funnels[1].substage("score");
}
//For each fragment cluster (cluster of clusters), for each read, a vector of all alignments + the order they were fed into the funnel
//so the funnel can track them
vector<pair<vector<Alignment>, vector<Alignment>>> alignments;
vector<pair<vector<size_t>, vector<size_t>>> alignment_indices;
pair<int, int> best_alignment_scores (0, 0); // The best alignment score for each end
//Keep track of the best cluster score and coverage per end for each fragment cluster
pair<vector<double>, vector<double>> cluster_score_by_fragment;
cluster_score_by_fragment.first.resize(max_fragment_num + 1, 0.0);
cluster_score_by_fragment.second.resize(max_fragment_num + 1, 0.0);
pair<vector<double>, vector<double>> cluster_coverage_by_fragment;
cluster_coverage_by_fragment.first.resize(max_fragment_num + 1, 0.0);
cluster_coverage_by_fragment.second.resize(max_fragment_num + 1, 0.0);
for (size_t read_num = 0 ; read_num < 2 ; read_num++) {
Alignment& aln = read_num == 0 ? aln1 : aln2;
std::vector<Cluster>& clusters = all_clusters[read_num];
std::vector<Minimizer>& minimizers = minimizers_by_read[read_num];
std::vector<Seed>& seeds = seeds_by_read[read_num];
vector<double>& best_cluster_score = read_num == 0 ? cluster_score_by_fragment.first : cluster_score_by_fragment.second;
vector<double>& best_cluster_coverage = read_num == 0 ? cluster_coverage_by_fragment.first : cluster_coverage_by_fragment.second;
for (size_t i = 0; i < clusters.size(); i++) {
// Deterimine cluster score and read coverage.
Cluster& cluster = clusters[i];
this->score_cluster(cluster, i, minimizers, seeds, aln.sequence().length(), funnels[read_num]);
size_t fragment = cluster.fragment;
best_cluster_score[fragment] = std::max(best_cluster_score[fragment], cluster.score);
best_cluster_coverage[fragment] = std::max(best_cluster_coverage[fragment], cluster.coverage);
}
}
//For each fragment cluster, we want to know how many equivalent or better clusters we found
vector<size_t> fragment_cluster_indices_by_score (max_fragment_num + 1);
for (size_t i = 0 ; i < fragment_cluster_indices_by_score.size() ; i++) {
fragment_cluster_indices_by_score[i] = i;
}
std::sort(fragment_cluster_indices_by_score.begin(), fragment_cluster_indices_by_score.end(), [&](size_t a, size_t b) {
return cluster_coverage_by_fragment.first[a] + cluster_coverage_by_fragment.second[a] + cluster_score_by_fragment.first[a] + cluster_score_by_fragment.second[a]
> cluster_coverage_by_fragment.first[b] + cluster_coverage_by_fragment.second[b] + cluster_score_by_fragment.first[b] + cluster_score_by_fragment.second[b];
});
vector<size_t> better_cluster_count (max_fragment_num+1); // How many fragment clusters are at least as good as the one at each index
for (int j = fragment_cluster_indices_by_score.size() - 1 ; j >= 0 ; j--) {
size_t i = fragment_cluster_indices_by_score[j];
if (j == fragment_cluster_indices_by_score.size()-1) {
better_cluster_count[i] = j;
} else {
size_t i2 = fragment_cluster_indices_by_score[j+1];
if(cluster_coverage_by_fragment.first[i] + cluster_coverage_by_fragment.second[i] + cluster_score_by_fragment.first[i] + cluster_score_by_fragment.second[i]
== cluster_coverage_by_fragment.first[i2] + cluster_coverage_by_fragment.second[i2] + cluster_score_by_fragment.first[i2] + cluster_score_by_fragment.second[i2]) {
better_cluster_count[i] = better_cluster_count[i2];
} else {
better_cluster_count[i] = j;
}
}
}
// We track unextended clusters.
vector<vector<size_t>> unextended_clusters_by_read(2);
// To compute the windows that are explored, we need to get
// all the minimizers that are explored.
vector<SmallBitset> minimizer_explored_by_read(2);
vector<vector<size_t>> minimizer_aligned_count_by_read(2);
//How many hits of each minimizer ended up in each extended cluster?
vector<vector<vector<size_t>>> minimizer_extended_cluster_count_by_read(2);
//Now that we've scored each of the clusters, extend and align them
for (size_t read_num = 0 ; read_num < 2 ; read_num++) {
Alignment& aln = read_num == 0 ? aln1 : aln2;
std::vector<Cluster>& clusters = all_clusters[read_num];
std::vector<Minimizer>& minimizers = minimizers_by_read[read_num];
std::vector<Seed>& seeds = seeds_by_read[read_num];
#ifdef debug
cerr << "Found " << clusters.size() << " clusters for read " << read_num << endl;
#endif
// Retain clusters only if their score is better than this, in addition to the coverage cutoff
double cluster_score_cutoff = 0.0, cluster_coverage_cutoff = 0.0;
for (auto& cluster : clusters) {
cluster_score_cutoff = std::max(cluster_score_cutoff, cluster.score);
cluster_coverage_cutoff = std::max(cluster_coverage_cutoff, cluster.coverage);
}
cluster_score_cutoff -= cluster_score_threshold;
cluster_coverage_cutoff -= cluster_coverage_threshold;
if (track_provenance) {
// Now we go from clusters to gapless extensions
funnels[read_num].stage("extend");
}
// These are the GaplessExtensions for all the clusters (and fragment cluster assignments), in cluster_indexes_in_order order.
vector<pair<vector<GaplessExtension>, size_t>> cluster_extensions;
cluster_extensions.reserve(clusters.size());
//TODO: Maybe put this back
//For each cluster, what fraction of "equivalent" clusters did we keep?
//vector<vector<double>> probability_cluster_lost;
//What is the score and coverage we are considering and how many reads
//size_t curr_coverage = 0;
//size_t curr_score = 0;
//size_t curr_kept = 0;
//size_t curr_count = 0;
unextended_clusters_by_read[read_num].reserve(clusters.size());
minimizer_explored_by_read[read_num] = SmallBitset(minimizers.size());
minimizer_aligned_count_by_read[read_num].resize(minimizers.size(), 0);
//Process clusters sorted by both score and read coverage
process_until_threshold_c<Cluster, double>(clusters, [&](size_t i) -> double {
return clusters[i].coverage;
}, [&](size_t a, size_t b) -> bool {
//Sort clusters first by whether it was paired, then by the best coverage and score of any pair in the fragment cluster,
//then by its coverage and score
size_t fragment_a = clusters[a].fragment;
size_t fragment_b = clusters[b].fragment;
double coverage_a = cluster_coverage_by_fragment.first[fragment_a]+cluster_coverage_by_fragment.second[fragment_a];
double coverage_b = cluster_coverage_by_fragment.first[fragment_b]+cluster_coverage_by_fragment.second[fragment_b];
double score_a = cluster_score_by_fragment.first[fragment_a]+cluster_score_by_fragment.second[fragment_a];
double score_b = cluster_score_by_fragment.first[fragment_b]+cluster_score_by_fragment.second[fragment_b];
if (fragment_cluster_has_pair[fragment_a] != fragment_cluster_has_pair[fragment_b]) {
return fragment_cluster_has_pair[fragment_a];
} else if (coverage_a != coverage_b){
return coverage_a > coverage_b;
} else if (score_a != score_b) {
return score_a > score_b;
} else if (clusters[a].coverage != clusters[b].coverage){
return clusters[a].coverage > clusters[b].coverage;
} else {
return clusters[a].score > clusters[b].score;
}
},
0, 1, max_extensions,
[&](size_t cluster_num) {
// Handle sufficiently good clusters
Cluster& cluster = clusters[cluster_num];
if (!found_paired_cluster || fragment_cluster_has_pair[cluster.fragment] ||
(cluster.coverage == cluster_coverage_cutoff + cluster_coverage_threshold &&
cluster.score == cluster_score_cutoff + cluster_score_threshold)) {
//If this cluster has a pair or if we aren't looking at pairs
//Or if it is the best cluster
// First check against the additional score filter
if (cluster_coverage_threshold != 0 && cluster.coverage < cluster_coverage_cutoff) {
//If the score isn't good enough, ignore this cluster
if (track_provenance) {
funnels[read_num].fail("cluster-coverage", cluster_num, cluster.coverage);
}
unextended_clusters_by_read[read_num].push_back(cluster_num);
return false;
}
if (cluster_score_threshold != 0 && cluster.score < cluster_score_cutoff) {
//If the score isn't good enough, ignore this cluster
if (track_provenance) {
funnels[read_num].pass("cluster-coverage", cluster_num, cluster.coverage);
funnels[read_num].pass("max-extensions", cluster_num);
funnels[read_num].fail("cluster-score", cluster_num, cluster.score);
}
unextended_clusters_by_read[read_num].push_back(cluster_num);
return false;
}
if (track_provenance) {
funnels[read_num].pass("cluster-coverage", cluster_num, cluster.coverage);
funnels[read_num].pass("max-extensions", cluster_num);
funnels[read_num].pass("cluster-score", cluster_num, cluster.score);
funnels[read_num].pass("paired-clusters", cluster_num);
funnels[read_num].processing_input(cluster_num);
}
#ifdef debug
cerr << "Cluster " << cluster_num << endl;
#endif
//Count how many of each minimizer is in each cluster extension
minimizer_extended_cluster_count_by_read[read_num].emplace_back(minimizers.size(), 0);
// Pack the seeds for GaplessExtender.
GaplessExtender::cluster_type seed_matchings;
for (auto seed_index : cluster.seeds) {
// Insert the (graph position, read offset) pair.
const Seed& seed = seeds[seed_index];
seed_matchings.insert(GaplessExtender::to_seed(seed.pos, minimizers[seed.source].value.offset));
minimizer_extended_cluster_count_by_read[read_num].back()[seed.source]++;
#ifdef debug
cerr << "Seed read:" << minimizers[seed.source].value.offset << " = " << seed.pos
<< " from minimizer " << seed.source << endl;
#endif
}
// Extend seed hits in the cluster into one or more gapless extensions
cluster_extensions.emplace_back(std::move(extender.extend(seed_matchings, aln.sequence())),
cluster.fragment);
if (track_provenance) {
// Record with the funnel that the previous group became a group of this size.
// Don't bother recording the seed to extension matching...
funnels[read_num].project_group(cluster_num, cluster_extensions.back().first.size());
// Say we finished with this cluster, for now.
funnels[read_num].processed_input();
}
return true;
} else {
//We were looking for clusters in a paired fragment cluster but this one doesn't have any on the other end
if (track_provenance) {
funnels[read_num].pass("cluster-coverage", cluster_num, cluster.coverage);
funnels[read_num].pass("max-extensions", cluster_num);
funnels[read_num].pass("cluster-score", cluster_num, cluster.score);
funnels[read_num].fail("paired-clusters", cluster_num);
}
unextended_clusters_by_read[read_num].push_back(cluster_num);
return false;
}
}, [&](size_t cluster_num) {
// There are too many sufficiently good clusters
if (track_provenance) {
funnels[read_num].pass("cluster-coverage", cluster_num, clusters[cluster_num].coverage);
funnels[read_num].fail("max-extensions", cluster_num);
}
unextended_clusters_by_read[read_num].push_back(cluster_num);
}, [&](size_t cluster_num) {
// This cluster is not sufficiently good.
// TODO: I don't think it should ever get here unless we limit the scores of the fragment clusters we look at
unextended_clusters_by_read[read_num].push_back(cluster_num);
});
// We now estimate the best possible alignment score for each cluster.
std::vector<int> cluster_extension_scores = this->score_extensions(cluster_extensions, aln, funnels[read_num]);
if (track_provenance) {
funnels[read_num].stage("align");
}
// Now start the alignment step. Everything has to become an alignment.
// We will fill this with all computed alignments in estimated score order.
alignments.resize(max_fragment_num + 2);
alignment_indices.resize(max_fragment_num + 2);
// Clear any old refpos annotation and path
aln.clear_refpos();
aln.clear_path();
aln.set_score(0);
aln.set_identity(0);
aln.set_mapping_quality(0);
//Since we will lose the order in which we pass alignments to the funnel, use this to keep track
size_t curr_funnel_index = 0;
// Go through the gapless extension groups in score order.
process_until_threshold_b(cluster_extensions, cluster_extension_scores,
extension_set_score_threshold, 2, max_alignments,
[&](size_t extension_num) {
// This extension set is good enough.
// Called in descending score order.
if (track_provenance) {
funnels[read_num].pass("extension-set", extension_num, cluster_extension_scores[extension_num]);
funnels[read_num].pass("max-alignments", extension_num);
funnels[read_num].processing_input(extension_num);
}
auto& extensions = cluster_extensions[extension_num].first;
// Get an Alignments best_ and second_best_alignment of it somehow, and throw it in.
Alignment best_alignment = aln;
Alignment second_best_alignment = aln;
// Determine if we got full-length alignments or local alignments.
bool full_length_extensions = (extensions.size() <= 2);
for (auto& extension : extensions) {
full_length_extensions &= extension.full();
}
if (full_length_extensions) {
// We got full-length extensions, so directly convert to an Alignment.
if (track_provenance) {
funnels[read_num].substage("direct");
}
//Fill in the best alignments from the extension
this->extension_to_alignment(extensions.front(), best_alignment);
if (extensions.size() > 1) {
//Do the same thing for the second extension, if one exists
this->extension_to_alignment(extensions.back(), second_best_alignment);
}
if (track_provenance) {
// Stop the current substage
funnels[read_num].substage_stop();
}
} else if (do_dp) {
// We need to do chaining.
if (track_provenance) {
funnels[read_num].substage("chain");
}
// Do the DP and compute alignment into best_alignment and
// second_best_alignment, if there is a second best
find_optimal_tail_alignments(aln, extensions, best_alignment, second_best_alignment);
if (track_provenance) {
// We're done chaining. Next alignment may not go through this substage.
funnels[read_num].substage_stop();
}
} else {
// We would do chaining but it is disabled.
// Leave best_alignment unaligned
}
size_t fragment_num = cluster_extensions[extension_num].second;
if (second_best_alignment.score() != 0 &&
second_best_alignment.score() > best_alignment.score() * 0.8) {
//If there is a second extension and its score is at least half of the best score
read_num == 0 ? best_alignment_scores.first = max(best_alignment_scores.first, second_best_alignment.score())
: best_alignment_scores.second = max(best_alignment_scores.second, second_best_alignment.score());
read_num == 0 ? alignments[fragment_num ].first.emplace_back(std::move(second_best_alignment) ) :
alignments[fragment_num ].second.emplace_back(std::move(second_best_alignment));
read_num == 0 ? alignment_indices[fragment_num].first.emplace_back(curr_funnel_index)
: alignment_indices[fragment_num].second.emplace_back(curr_funnel_index);
curr_funnel_index++;
if (track_provenance) {
funnels[read_num].project(extension_num);
read_num == 0 ? funnels[read_num].score(extension_num, alignments[fragment_num ].first.back().score()) :
funnels[read_num].score(extension_num, alignments[fragment_num].second.back().score());
}
}
read_num == 0 ? best_alignment_scores.first = max(best_alignment_scores.first, best_alignment.score())
: best_alignment_scores.second = max(best_alignment_scores.second, best_alignment.score());
read_num == 0 ? alignments[fragment_num].first.emplace_back(std::move(best_alignment))
: alignments[fragment_num].second.emplace_back(std::move(best_alignment));
read_num == 0 ? alignment_indices[fragment_num].first.emplace_back(curr_funnel_index)
: alignment_indices[fragment_num].second.emplace_back(curr_funnel_index);
curr_funnel_index++;
if (track_provenance) {
funnels[read_num].project(extension_num);
read_num == 0 ? funnels[read_num].score(extension_num, alignments[fragment_num].first.back().score())
: funnels[read_num].score(extension_num, alignments[fragment_num].second.back().score());
// We're done with this input item
funnels[read_num].processed_input();
}
for (size_t i = 0 ; i < minimizer_extended_cluster_count_by_read[read_num][extension_num].size() ; i++) {
if (minimizer_extended_cluster_count_by_read[read_num][extension_num][i] > 0) {
// This minimizer is in an extended cluster that gave rise
// to at least one alignment, so it is explored.
minimizer_explored_by_read[read_num].insert(i);
minimizer_aligned_count_by_read[read_num][i] += minimizer_extended_cluster_count_by_read[read_num][extension_num][i];
}
}
return true;
}, [&](size_t extension_num) {
// There are too many sufficiently good extensions
if (track_provenance) {
funnels[read_num].pass("extension-set", extension_num, cluster_extension_scores[extension_num]);
funnels[read_num].fail("max-alignments", extension_num);
}
}, [&](size_t extension_num) {
// This extension is not good enough.
if (track_provenance) {
funnels[read_num].fail("extension-set", extension_num, cluster_extension_scores[extension_num]);
}
});
}
if (track_provenance) {
// Now say we are finding the winner(s)
funnels[0].stage("pairing");
funnels[1].stage("pairing");
}
// Fill this in with the pairs of alignments we will output
// each alignment is stored as <fragment index, alignment index> into alignments
vector<pair<pair<size_t, size_t>, pair<size_t, size_t>>> paired_alignments;
paired_alignments.reserve(alignments.size());
#ifdef print_minimizers
vector<pair<bool, bool>> alignment_was_rescued;
#endif
//For each alignment in alignments, which paired_alignment includes it. Follows structure of alignments
vector<pair<vector<vector<size_t>>, vector<vector<size_t>>>> alignment_groups(alignments.size());
// Grab all the scores in order for MAPQ computation.
vector<double> paired_scores;
paired_scores.reserve(alignments.size());
vector<int64_t> fragment_distances;
fragment_distances.reserve(alignments.size());
//For each fragment cluster, get the fraction of equivalent or better clusters that got thrown away
vector<size_t> better_cluster_count_alignment_pairs;
better_cluster_count_alignment_pairs.reserve(alignments.size());
//Keep track of alignments with no pairs in the same fragment cluster
bool found_pair = false;
//Alignments that don't have a mate
// <fragment index, alignment_index, true if its the first end>
vector<tuple<size_t, size_t, bool>> unpaired_alignments;
size_t unpaired_count_1 = 0;
size_t unpaired_count_2 = 0;
for (size_t fragment_num = 0 ; fragment_num < alignments.size() ; fragment_num ++ ) {
//Get pairs of plausible alignments
alignment_groups[fragment_num].first.resize(alignments[fragment_num].first.size());
alignment_groups[fragment_num].second.resize(alignments[fragment_num].second.size());
pair<vector<Alignment>, vector<Alignment>>& fragment_alignments = alignments[fragment_num];
if (!fragment_alignments.first.empty() && ! fragment_alignments.second.empty()) {
//Only keep pairs of alignments that were in the same fragment cluster
found_pair = true;
for (size_t i1 = 0 ; i1 < fragment_alignments.first.size() ; i1++) {
Alignment& alignment1 = fragment_alignments.first[i1];
size_t j1 = alignment_indices[fragment_num].first[i1];
for (size_t i2 = 0 ; i2 < fragment_alignments.second.size() ; i2++) {
Alignment& alignment2 = fragment_alignments.second[i2];
size_t j2 = alignment_indices[fragment_num].second[i2];
//Get the likelihood of the fragment distance
int64_t fragment_distance = distance_between(alignment1, alignment2);
double dev = fragment_distance - fragment_length_distr.mean();
double fragment_length_log_likelihood = -dev * dev / (2.0 * fragment_length_distr.std_dev() * fragment_length_distr.std_dev());
if (fragment_distance != std::numeric_limits<int64_t>::max() ) {
double score = alignment1.score() + alignment2.score() + (fragment_length_log_likelihood / get_aligner()->log_base);
alignment_groups[fragment_num].first[i1].emplace_back(paired_alignments.size());
alignment_groups[fragment_num].second[i2].emplace_back(paired_alignments.size());
paired_alignments.emplace_back(make_pair(fragment_num, i1), make_pair(fragment_num, i2));
paired_scores.emplace_back(score);
fragment_distances.emplace_back(fragment_distance);
better_cluster_count_alignment_pairs.emplace_back(better_cluster_count[fragment_num]);
#ifdef print_minimizers
alignment_was_rescued.emplace_back(false, false);
#endif
#ifdef debug
cerr << "Found pair of alignments from fragment " << fragment_num << " with scores "
<< alignment1.score() << " " << alignment2.score() << " at distance " << fragment_distance
<< " gets pair score " << score << endl;
cerr << "Alignment 1: " << pb2json(alignment1) << endl << "Alignment 2: " << pb2json(alignment2) << endl;
#endif
}
if (track_provenance) {
funnels[0].processing_input(j1);
funnels[1].processing_input(j2);
funnels[0].substage("pair-clusters");
funnels[1].substage("pair-clusters");
funnels[0].pass("max-rescue-attempts", j1);
funnels[0].project(j1);
funnels[1].pass("max-rescue-attempts", j2);
funnels[1].project(j2);
funnels[0].substage_stop();
funnels[1].substage_stop();
funnels[0].processed_input();
funnels[1].processed_input();
}
}
}
} else if (!fragment_alignments.first.empty()) {
#ifdef debug
cerr << "Found unpaired alignments from fragment " << fragment_num << " for first read" << endl;
#endif
for (size_t i = 0 ; i < fragment_alignments.first.size() ; i++) {
unpaired_alignments.emplace_back(fragment_num, i, true);
unpaired_count_1++;
#ifdef debug
cerr << "\t" << pb2json(fragment_alignments.first[i]) << endl;
#endif
}
} else if (!fragment_alignments.second.empty()) {
#ifdef debug
cerr << "Found unpaired alignments from fragment " << fragment_num << " for second read" << endl;
#endif
for (size_t i = 0 ; i < fragment_alignments.second.size() ; i++) {
unpaired_alignments.emplace_back(fragment_num, i, false);
unpaired_count_2++;
#ifdef debug
cerr << "\t" << pb2json(fragment_alignments.second[i]) << endl;
#endif
}
}
}
size_t rescued_count_1 = 0;
size_t rescued_count_2 = 0;
vector<bool> rescued_from;
if (!unpaired_alignments.empty()) {
//If we found some clusters that don't belong to a fragment cluster
if (!found_pair && max_rescue_attempts == 0 ) {
//If we didn't find any pairs and we aren't attempting rescue, just return the best for each end
#ifdef debug
cerr << "Found no pairs and we aren't doing rescue: return best alignment for each read" << endl;
#endif
Alignment& best_aln1 = aln1;
Alignment& best_aln2 = aln2;
best_aln1.clear_refpos();
best_aln1.clear_path();
best_aln1.set_score(0);
best_aln1.set_identity(0);
best_aln1.set_mapping_quality(0);
best_aln2.clear_refpos();
best_aln2.clear_path();
best_aln2.set_score(0);
best_aln2.set_identity(0);
best_aln2.set_mapping_quality(0);
for (tuple<size_t, size_t, bool> index : unpaired_alignments ) {
Alignment& alignment = std::get<2>(index) ? alignments[std::get<0>(index)].first[std::get<1>(index)]
: alignments[std::get<0>(index)].second[std::get<1>(index)];
if (std::get<2>(index)) {
if (alignment.score() > best_aln1.score()) {
best_aln1 = alignment;
}
} else {
if (alignment.score() > best_aln2.score()) {
best_aln2 = alignment;
}
}
}
set_annotation(best_aln1, "unpaired", true);
set_annotation(best_aln2, "unpaired", true);
pair<vector<Alignment>, vector<Alignment>> paired_mappings;
paired_mappings.first.emplace_back(std::move(best_aln1));
paired_mappings.second.emplace_back(std::move(best_aln2));
// Flip aln2 back to input orientation
reverse_complement_alignment_in_place(&paired_mappings.second.back(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
paired_mappings.first.back().set_mapping_quality(1);
paired_mappings.second.back().set_mapping_quality(1);
// Stop this alignment
funnels[0].stop();
funnels[1].stop();
if (track_provenance) {
// Annotate with the number of results in play at each stage
for (size_t read_num = 0 ; read_num < 2 ; read_num++) {
funnels[read_num].for_each_stage([&](const string& stage, const vector<size_t>& result_sizes) {
// Save the number of items
set_annotation(read_num == 0 ? paired_mappings.first[0] : paired_mappings.second[0], "stage_" + stage + "_results", (double)result_sizes.size());
});
if (track_correctness) {
// And with the last stage at which we had any descendants of the correct seed hit locations
set_annotation(read_num == 0 ? paired_mappings.first[0] : paired_mappings.second[0], "last_correct_stage", funnels[read_num].last_correct_stage());
}
// Annotate with the performances of all the filters
// We need to track filter number
size_t filter_num = 0;
funnels[read_num].for_each_filter([&](const string& stage, const string& filter,
const Funnel::FilterPerformance& by_count, const Funnel::FilterPerformance& by_size,
const vector<double>& filter_statistics_correct, const vector<double>& filter_statistics_non_correct) {
string filter_id = to_string(filter_num) + "_" + filter + "_" + stage;
if (read_num == 0) {
// Save the stats
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(paired_mappings.first[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(paired_mappings.first[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
} else {
// Save the stats
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(paired_mappings.second[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(paired_mappings.second[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
}
filter_num++;
});
}
}
#ifdef print_minimizers
cerr << aln1.sequence() << "\t";
for (char c : aln1.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << max_fragment_num << "\t" << 0 << "\t" << 0 << "\t?";
for (size_t i = 0 ; i < minimizers_by_read[0].size() ; i++) {
auto& minimizer = minimizers_by_read[0][i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_aligned_count_by_read[0][i];
if (minimizer_aligned_count_by_read[0][i] > 0) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << 1 << "\t" << 1 << "\t" << 1 << "\t" << 1;
if (track_correctness) {
cerr << "\t" << funnels[0].last_correct_stage() << endl;
} else {
cerr << "\t?" << endl;
}
cerr << aln2.sequence() << "\t";
for (char c : aln2.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << max_fragment_num << "\t" << 0 << "\t" << 0 << "\t?";
for (size_t i = 0 ; i < minimizers_by_read[1].size() ; i++) {
auto& minimizer = minimizers_by_read[1][i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_aligned_count_by_read[1][i];
if (minimizer_aligned_count_by_read[1][i] > 0) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << 1 << "\t" << 1 << "\t" << 1 << "\t" << 1;
if (track_correctness) {
cerr << "\t" << funnels[1].last_correct_stage() << endl;
} else {
cerr << "\t?" << endl;
}
#endif
return paired_mappings;
} else {
//Attempt rescue on unpaired alignments if either we didn't find any pairs or if the unpaired alignments are very good
process_until_threshold_a(unpaired_alignments, (std::function<double(size_t)>) [&](size_t i) -> double{
tuple<size_t, size_t, bool> index = unpaired_alignments.at(i);
return (double) std::get<2>(index) ? alignments[std::get<0>(index)].first[std::get<1>(index)].score()
: alignments[std::get<0>(index)].second[std::get<1>(index)].score();
}, 0, 1, max_rescue_attempts, [&](size_t i) {
tuple<size_t, size_t, bool> index = unpaired_alignments.at(i);
bool found_first = std::get<2>(index);
size_t j = found_first ? alignment_indices[std::get<0>(index)].first[std::get<1>(index)]
: alignment_indices[std::get<0>(index)].second[std::get<1>(index)];
if (track_provenance) {
funnels[found_first ? 0 : 1].processing_input(j);
funnels[found_first ? 0 : 1].substage("rescue");
}
Alignment& mapped_aln = found_first ? alignments[std::get<0>(index)].first[std::get<1>(index)]
: alignments[std::get<0>(index)].second[std::get<1>(index)];
Alignment rescued_aln = found_first ? aln2 : aln1;
rescued_aln.clear_path();
if (found_pair && (double) mapped_aln.score() < (double) (found_first ? best_alignment_scores.first : best_alignment_scores.second) * paired_rescue_score_limit) {
//If we have already found paired clusters and this unpaired alignment is not good enough, do nothing
return true;
}
attempt_rescue(mapped_aln, rescued_aln, minimizers_by_read[(found_first ? 1 : 0)], found_first);
int64_t fragment_dist = found_first ? distance_between(mapped_aln, rescued_aln)
: distance_between(rescued_aln, mapped_aln);
if (fragment_dist != std::numeric_limits<int64_t>::max()) {
bool duplicated = false;
double dev = fragment_dist - fragment_length_distr.mean();
double fragment_length_log_likelihood = -dev * dev / (2.0 * fragment_length_distr.std_dev() * fragment_length_distr.std_dev());
double score = mapped_aln.score() + rescued_aln.score() + (fragment_length_log_likelihood / get_aligner()->log_base);
set_annotation(mapped_aln, "rescuer", true);
set_annotation(rescued_aln, "rescued", true);
set_annotation(mapped_aln, "fragment_length", (double)fragment_dist);
set_annotation(rescued_aln, "fragment_length", (double)fragment_dist);
pair<size_t, size_t> mapped_index (std::get<0>(index), std::get<1>(index));
pair<size_t, size_t> rescued_index (alignments.size() - 1,
found_first ? alignments.back().second.size() : alignments.back().first.size());
found_first ? alignments.back().second.emplace_back(std::move(rescued_aln))
: alignments.back().first.emplace_back(std::move(rescued_aln));
found_first ? rescued_count_1++ : rescued_count_2++;
found_first ? alignment_groups.back().second.emplace_back() : alignment_groups.back().first.emplace_back();
pair<pair<size_t, size_t>, pair<size_t, size_t>> index_pair = found_first ?
make_pair(mapped_index, rescued_index) : make_pair(rescued_index, mapped_index);
paired_alignments.push_back(index_pair);
paired_scores.emplace_back(score);
fragment_distances.emplace_back(fragment_dist);
better_cluster_count_alignment_pairs.emplace_back(0);
rescued_from.push_back(found_first);
#ifdef print_minimizers
alignment_was_rescued.emplace_back(!found_first, found_first);
#endif
if (track_provenance) {
funnels[found_first ? 0 : 1].pass("max-rescue-attempts", j);
funnels[found_first ? 0 : 1].project(j);
funnels[found_first ? 1 : 0].introduce();
}
}
if (track_provenance) {
funnels[found_first ? 0 : 1].processed_input();
funnels[found_first ? 0 : 1].substage_stop();
}
return true;
}, [&](size_t i) {
if (track_provenance) {
tuple<size_t, size_t, bool> index = unpaired_alignments.at(i);
bool found_first = std::get<2>(index);
size_t j = found_first ? alignment_indices[std::get<0>(index)].first[std::get<1>(index)]
: alignment_indices[std::get<0>(index)].second[std::get<1>(index)];
funnels[found_first ? 0 : 1].fail("max-rescue-attempts", j);
}
return;
}, [&] (size_t i) {
if (track_provenance) {
tuple<size_t, size_t, bool> index = unpaired_alignments.at(i);
bool found_first = std::get<2>(index);
size_t j = found_first ? alignment_indices[std::get<0>(index)].first[std::get<1>(index)]
: alignment_indices[std::get<0>(index)].second[std::get<1>(index)];
}
return;
});
}
}
if (track_provenance) {
// Now say we are finding the winner(s)
funnels[0].stage("winner");
funnels[1].stage("winner");
}
double estimated_multiplicity_from_1 = unpaired_count_1 > 0 ? (double) unpaired_count_1 / min(rescued_count_1, max_rescue_attempts) : 1.0;
double estimated_multiplicity_from_2 = unpaired_count_2 > 0 ? (double) unpaired_count_2 / min(rescued_count_2, max_rescue_attempts) : 1.0;
vector<double> paired_multiplicities;
for (bool rescued_from_first : rescued_from) {
paired_multiplicities.push_back(rescued_from_first ? estimated_multiplicity_from_1 : estimated_multiplicity_from_2);
}
// Fill this in with the alignments we will output
pair<vector<Alignment>, vector<Alignment>> mappings;
// Grab all the scores in order for MAPQ computation.
vector<double> scores;
vector<double> scores_group_1;
vector<double> scores_group_2;
vector<int64_t> distances;
mappings.first.reserve(paired_alignments.size());
mappings.second.reserve(paired_alignments.size());
scores.reserve(paired_scores.size());
distances.reserve(fragment_distances.size());
vector<size_t> better_cluster_count_mappings;
better_cluster_count_mappings.reserve(better_cluster_count_alignment_pairs.size());
#ifdef print_minimizers
vector<pair<bool, bool>> mapping_was_rescued;
#endif
process_until_threshold_a(paired_alignments, (std::function<double(size_t)>) [&](size_t i) -> double {
return paired_scores[i];
}, 0, 1, max_multimaps, [&](size_t alignment_num) {
// This alignment makes it
// Called in score order
pair<pair<size_t, size_t>, pair<size_t, size_t>> index_pair = paired_alignments[alignment_num];
// Remember the score at its rank
scores.emplace_back(paired_scores[alignment_num]);
distances.emplace_back(fragment_distances[alignment_num]);
// Remember the output alignment
mappings.first.emplace_back( alignments[index_pair.first.first].first[index_pair.first.second]);
mappings.second.emplace_back(alignments[index_pair.second.first].second[index_pair.second.second]);
better_cluster_count_mappings.emplace_back(better_cluster_count_alignment_pairs[alignment_num]);
if (mappings.first.size() == 1 && found_pair) {
//If this is the best pair of alignments that we're going to return and we didn't attempt rescue,
//get the group scores for mapq
//Get the scores of
scores_group_1.push_back(paired_scores[alignment_num]);
scores_group_2.push_back(paired_scores[alignment_num]);
//The indices (into paired_alignments) of pairs with the same first read as this
vector<size_t>& alignment_group_1 = alignment_groups[index_pair.first.first].first[index_pair.first.second];
vector<size_t>& alignment_group_2 = alignment_groups[index_pair.second.first].second[index_pair.second.second];
for (size_t other_alignment_num : alignment_group_1) {
if (other_alignment_num != alignment_num) {
scores_group_1.push_back(paired_scores[other_alignment_num]);
}
}
for (size_t other_alignment_num : alignment_group_2) {
if (other_alignment_num != alignment_num) {
scores_group_2.push_back(paired_scores[other_alignment_num]);
}
}
}
// Flip aln2 back to input orientation
reverse_complement_alignment_in_place(&mappings.second.back(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
if (mappings.first.size() > 1) {
mappings.first.back().set_is_secondary(true);
mappings.second.back().set_is_secondary(true);
}
#ifdef print_minimizers
mapping_was_rescued.emplace_back(alignment_was_rescued[alignment_num]);
#endif
if (track_provenance) {
// Tell the funnel
funnels[0].pass("max-multimaps", alignment_num);
funnels[0].project(alignment_num);
funnels[0].score(alignment_num, scores.back());
funnels[1].pass("max-multimaps", alignment_num);
funnels[1].project(alignment_num);
funnels[1].score(alignment_num, scores.back());
}
return true;
}, [&](size_t alignment_num) {
// We already have enough alignments, although this one has a good score
// Remember the score at its rank anyway
scores.emplace_back(paired_scores[alignment_num]);
distances.emplace_back(fragment_distances[alignment_num]);
if (track_provenance) {
funnels[0].fail("max-multimaps", alignment_num);
funnels[1].fail("max-multimaps", alignment_num);
}
}, [&](size_t alignment_num) {
// This alignment does not have a sufficiently good score
// Score threshold is 0; this should never happen
assert(false);
});
if (track_provenance) {
funnels[0].substage("mapq");
funnels[1].substage("mapq");
}
// Compute raw explored caps (with 2.0 scaling, like for single-end) and raw group caps.
// Non-capping caps stay at infinity.
vector<double> mapq_explored_caps(2, std::numeric_limits<float>::infinity());
vector<double> mapq_score_groups(2, std::numeric_limits<float>::infinity());
// We also have one fragment_cluster_cap across both ends.
double fragment_cluster_cap = std::numeric_limits<float>::infinity();
// And one base uncapped MAPQ
double uncapped_mapq = 0;
if (mappings.first.empty()) {
//If we didn't get an alignment, return empty alignments
mappings.first.emplace_back(aln1);
mappings.second.emplace_back(aln2);
// Flip aln2 back to input orientation
reverse_complement_alignment_in_place(&mappings.second.back(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
mappings.first.back().clear_refpos();
mappings.first.back().clear_path();
mappings.first.back().set_score(0);
mappings.first.back().set_identity(0);
mappings.first.back().set_mapping_quality(0);
mappings.second.back().clear_refpos();
mappings.second.back().clear_path();
mappings.second.back().set_score(0);
mappings.second.back().set_identity(0);
mappings.second.back().set_mapping_quality(0);
#ifdef print_minimizers
mapping_was_rescued.emplace_back(false, false);
#endif
} else {
#ifdef debug
cerr << "For scores ";
for (auto& score : scores) cerr << score << " ";
#endif
size_t winning_index;
const vector<double>* multiplicities = paired_multiplicities.size() == scores.size() ? &paired_multiplicities : nullptr;
// Compute base MAPQ if not unmapped. Otherwise use 0 instead of the 50% this would give us.
// If either of the mappings was duplicated in other pairs, use the group scores to determine mapq
uncapped_mapq = scores[0] == 0 ? 0 :
get_regular_aligner()->maximum_mapping_quality_exact(scores, &winning_index, multiplicities) / 2;
//Cap mapq at 1 - 1 / # equivalent or better fragment clusters, excluding self
if (better_cluster_count_mappings.size() != 0) {
if (better_cluster_count_mappings.front() == 1) {
// One cluster excluding us is equivalent or better.
// Old logic gave a -0 which was interpreted as uncapped.
// So leave uncapped.
} else if (better_cluster_count_mappings.front() > 1) {
// Actually compute the cap the right way around
// TODO: why is this a sensible cap?
fragment_cluster_cap = prob_to_phred(1.0 - (1.0 / (double) better_cluster_count_mappings.front()));
// Leave zeros in here and don't round.
}
}
//If one alignment was duplicated in other pairs, cap the mapq for that alignment at the mapq
//of the group of duplicated alignments. Always compute this even if not quite sensible.
mapq_score_groups[0] = get_regular_aligner()->maximum_mapping_quality_exact(scores_group_1, &winning_index);
mapq_score_groups[1] = get_regular_aligner()->maximum_mapping_quality_exact(scores_group_2, &winning_index);
for (auto read_num : {0, 1}) {
// For each fragment
// Find the source read
auto& aln = read_num == 0 ? aln1 : aln2;
vector<size_t> explored_minimizers;
for (size_t i = 0; i < minimizers_by_read[read_num].size(); i++) {
if (minimizer_explored_by_read[read_num].contains(i)) {
explored_minimizers.push_back(i);
}
}
// Compute exploration cap on MAPQ. TODO: avoid needing to pass as much stuff along.
double mapq_explored_cap = 2 * faster_cap(minimizers_by_read[read_num], explored_minimizers, aln.sequence(), aln.quality());
mapq_explored_caps[read_num] = mapq_explored_cap;
// Remember the caps
auto& to_annotate = (read_num == 0 ? mappings.first : mappings.second).front();
set_annotation(to_annotate, "mapq_explored_cap", mapq_explored_cap);
set_annotation(to_annotate, "mapq_score_group", mapq_score_groups[read_num]);
}
// Have a function to transform interesting cap values to uncapped.
auto preprocess_cap = [&](double cap) {
return (cap != -numeric_limits<double>::infinity()) ? cap : numeric_limits<double>::infinity();
};
for (auto read_num : {0, 1}) {
// For each fragment
// Compute the overall cap for just this read, now that the individual cap components are filled in for both reads.
double mapq_cap = std::min(preprocess_cap(mapq_score_groups[read_num] / 2.0), std::min(fragment_cluster_cap, (mapq_explored_caps[0] + mapq_explored_caps[1]) / 2.0));
// Find the MAPQ to cap
double read_mapq = uncapped_mapq;
// Remember the uncapped MAPQ
auto& to_annotate = (read_num == 0 ? mappings.first : mappings.second).front();
set_annotation(to_annotate, "mapq_uncapped", read_mapq);
// And the cap we actually applied (possibly from the pair partner)
set_annotation(to_annotate, "mapq_applied_cap", mapq_cap);
// Apply the cap, and limit to 0-60
read_mapq = max(min(mapq_cap, min(read_mapq, 60.0)), 0.0);
// Save the MAPQ
to_annotate.set_mapping_quality(read_mapq);
#ifdef debug
cerr << "MAPQ for read " << read_num << " is " << read_mapq << ", was " << uncapped_mapq
<< " capped by fragment cluster cap " << fragment_cluster_cap
<< ", score group cap " << (mapq_score_groups[read_num] / 2.0)
<< ", combined explored cap " << ((mapq_explored_caps[0] + mapq_explored_caps[1]) / 2.0) << endl;
#endif
}
//Annotate top pair with its fragment distance, fragment length distrubution, and secondary scores
set_annotation(mappings.first.front(), "fragment_length", (double) distances.front());
set_annotation(mappings.second.front(), "fragment_length", (double) distances.front());
string distribution = "-I " + to_string(fragment_length_distr.mean()) + " -D " + to_string(fragment_length_distr.std_dev());
set_annotation(mappings.first.front(),"fragment_length_distribution", distribution);
set_annotation(mappings.second.front(),"fragment_length_distribution", distribution);
set_annotation(mappings.first.front(),"secondary_scores", scores);
set_annotation(mappings.second.front(),"secondary_scores", scores);
}
if (track_provenance) {
funnels[0].substage_stop();
funnels[1].substage_stop();
}
// Stop this alignment
funnels[0].stop();
funnels[1].stop();
if (track_provenance) {
// Annotate with the number of results in play at each stage
for (size_t read_num = 0 ; read_num < 2 ; read_num++) {
funnels[read_num].for_each_stage([&](const string& stage, const vector<size_t>& result_sizes) {
// Save the number of items
set_annotation(read_num == 0 ? mappings.first[0] : mappings.second[0], "stage_" + stage + "_results", (double)result_sizes.size());
});
if (track_correctness) {
// And with the last stage at which we had any descendants of the correct seed hit locations
set_annotation(read_num == 0 ? mappings.first[0] : mappings.second[0], "last_correct_stage", funnels[read_num].last_correct_stage());
}
// Annotate with the performances of all the filters
// We need to track filter number
size_t filter_num = 0;
funnels[read_num].for_each_filter([&](const string& stage, const string& filter,
const Funnel::FilterPerformance& by_count, const Funnel::FilterPerformance& by_size,
const vector<double>& filter_statistics_correct, const vector<double>& filter_statistics_non_correct) {
string filter_id = to_string(filter_num) + "_" + filter + "_" + stage;
if (read_num == 0) {
// Save the stats
set_annotation(mappings.first[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(mappings.first[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(mappings.first[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(mappings.first[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(mappings.first[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(mappings.first[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(mappings.first[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(mappings.first[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(mappings.first[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(mappings.first[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
} else {
// Save the stats
set_annotation(mappings.second[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(mappings.second[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(mappings.second[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(mappings.second[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(mappings.second[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(mappings.second[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(mappings.second[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(mappings.second[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(mappings.second[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(mappings.second[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
}
filter_num++;
});
}
// Annotate with parameters used for the filters.
set_annotation(mappings.first[0] , "param_hit-cap", (double) hit_cap);
set_annotation(mappings.first[0] , "param_hard-hit-cap", (double) hard_hit_cap);
set_annotation(mappings.first[0] , "param_score-fraction", (double) minimizer_score_fraction);
set_annotation(mappings.first[0] , "param_max-extensions", (double) max_extensions);
set_annotation(mappings.first[0] , "param_max-alignments", (double) max_alignments);
set_annotation(mappings.first[0] , "param_cluster-score", (double) cluster_score_threshold);
set_annotation(mappings.first[0] , "param_cluster-coverage", (double) cluster_coverage_threshold);
set_annotation(mappings.first[0] , "param_extension-set", (double) extension_set_score_threshold);
set_annotation(mappings.first[0] , "param_max-multimaps", (double) max_multimaps);
set_annotation(mappings.first[0] , "param_max-rescue-attempts", (double) max_rescue_attempts);
set_annotation(mappings.second[0], "param_hit-cap", (double) hit_cap);
set_annotation(mappings.second[0], "param_hard-hit-cap", (double) hard_hit_cap);
set_annotation(mappings.second[0], "param_score-fraction", (double) minimizer_score_fraction);
set_annotation(mappings.second[0], "param_max-extensions", (double) max_extensions);
set_annotation(mappings.second[0], "param_max-alignments", (double) max_alignments);
set_annotation(mappings.second[0], "param_cluster-score", (double) cluster_score_threshold);
set_annotation(mappings.second[0], "param_cluster-coverage", (double) cluster_coverage_threshold);
set_annotation(mappings.second[0], "param_extension-set", (double) extension_set_score_threshold);
set_annotation(mappings.second[0], "param_max-multimaps", (double) max_multimaps);
set_annotation(mappings.second[0] , "param_max-rescue-attempts", (double) max_rescue_attempts);
}
#ifdef print_minimizers
if (distances.size() == 0) {
distances.emplace_back(0);
}
cerr << aln1.sequence() << "\t";
for (char c : aln1.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << max_fragment_num << "\t" << mapping_was_rescued[0].first << "\t" << mapping_was_rescued[0].second << "\t" << distances.front();
for (size_t i = 0 ; i < minimizers_by_read[0].size() ; i++) {
auto& minimizer = minimizers_by_read[0][i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_explored_by_read[0].contains(i);
if (minimizer_explored_by_read[0].contains(i)) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << uncapped_mapq << "\t" << fragment_cluster_cap << "\t" << mapq_score_groups[0] << "\t" << mapq_explored_caps[0] << "\t" << mappings.first.front().mapping_quality();
if (track_correctness) {
cerr << "\t" << funnels[0].last_correct_stage() << endl;
} else {
cerr << "\t?" << endl;
}
cerr << aln2.sequence() << "\t";
for (char c : aln2.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << max_fragment_num << "\t" << mapping_was_rescued[0].second << "\t" << mapping_was_rescued[0].first << "\t" << distances.front();
for (size_t i = 0 ; i < minimizers_by_read[1].size() ; i++) {
auto& minimizer = minimizers_by_read[1][i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_explored_by_read[1].contains(i);
if (minimizer_explored_by_read[1].contains(i)) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << uncapped_mapq << "\t" << fragment_cluster_cap << "\t" << mapq_score_groups[1] << "\t" << mapq_explored_caps[1] << "\t" << mappings.second.front().mapping_quality();
if (track_correctness) {
cerr << "\t" << funnels[1].last_correct_stage() << endl;
} else {
cerr << "\t?" << endl;
}
#endif
// Ship out all the aligned alignments
return mappings;
#ifdef debug
// Dump the funnel info graph.
funnels[0].to_dot(cerr);
funnels[1].to_dot(cerr);
#endif
}
//-----------------------------------------------------------------------------
double MinimizerMapper::compute_mapq_caps(const Alignment& aln,
const std::vector<Minimizer>& minimizers,
const SmallBitset& explored) {
// We need to cap MAPQ based on the likelihood of generating all the windows in the explored minimizers by chance, too.
#ifdef debug
cerr << "Cap based on explored minimizers all being faked by errors..." << endl;
#endif
// Convert our flag vector to a list of the minimizers actually in extended clusters
vector<size_t> explored_minimizers;
explored_minimizers.reserve(minimizers.size());
for (size_t i = 0; i < minimizers.size(); i++) {
if (explored.contains(i)) {
explored_minimizers.push_back(i);
}
}
double mapq_explored_cap = window_breaking_quality(minimizers, explored_minimizers, aln.sequence(), aln.quality());
return mapq_explored_cap;
}
double MinimizerMapper::window_breaking_quality(const vector<Minimizer>& minimizers, vector<size_t>& broken,
const string& sequence, const string& quality_bytes) {
#ifdef debug
cerr << "Computing MAPQ cap based on " << broken.size() << "/" << minimizers.size() << " minimizers' windows" << endl;
#endif
if (broken.empty() || quality_bytes.empty()) {
// If we have no agglomerations or no qualities, bail
return numeric_limits<double>::infinity();
}
assert(sequence.size() == quality_bytes.size());
// Sort the agglomerations by start position
std::sort(broken.begin(), broken.end(), [&](const size_t& a, const size_t& b) {
return minimizers[a].agglomeration_start < minimizers[b].agglomeration_start;
});
// Have a priority queue for tracking the agglomerations that a base is currently overlapping.
// Prioritize earliest-ending best, and then latest-starting best.
// This is less, and greater priority is at the front of the queue (better).
// TODO: do we really need to care about the start here?
auto agglomeration_priority = [&](const size_t& a, const size_t& b) {
// Returns true if a is worse (ends later, or ends at the same place and starts earlier).
auto& ma = minimizers[a];
auto& mb = minimizers[b];
auto a_end = ma.agglomeration_start + ma.agglomeration_length;
auto b_end = mb.agglomeration_start + mb.agglomeration_length;
return (a_end > b_end) || (a_end == b_end && ma.agglomeration_start < mb.agglomeration_start);
};
// We maintain our own heap so we can iterate over it.
vector<size_t> active_agglomerations;
// A window in flight is a pair of start position, inclusive end position
struct window_t {
size_t first;
size_t last;
};
// Have a priority queue of window starts and ends, prioritized earliest-ending best, and then latest-starting best.
// This is less, and greater priority is at the front of the queue (better).
auto window_priority = [&](const window_t& a, const window_t& b) {
// Returns true if a is worse (ends later, or ends at the same place and starts earlier).
return (a.last > b.last) || (a.last == b.last && a.first < b.first);
};
priority_queue<window_t, vector<window_t>, decltype(window_priority)> active_windows(window_priority);
// Have a cursor for which agglomeration should come in next.
auto next_agglomeration = broken.begin();
// Have a DP table with the cost of the cheapest solution to the problem up to here, including a hit at this base.
// Or numeric_limits<double>::infinity() if base cannot be hit.
// We pre-fill it because I am scared to use end() if we change its size.
vector<double> costs(sequence.size(), numeric_limits<double>::infinity());
// Keep track of the latest-starting window ending before here. If none, this will be two numeric_limits<size_t>::max() values.
window_t latest_starting_ending_before = { numeric_limits<size_t>::max(), numeric_limits<size_t>::max() };
// And keep track of the min cost DP table entry, or end if not computed yet.
auto latest_starting_ending_before_winner = costs.end();
for (size_t i = 0; i < sequence.size(); i++) {
// For each base in the read
#ifdef debug
cerr << "At base " << i << endl;
#endif
// Bring in new agglomerations and windows that start at this base.
while (next_agglomeration != broken.end() && minimizers[*next_agglomeration].agglomeration_start == i) {
// While the next agglomeration starts here
// Record it
active_agglomerations.push_back(*next_agglomeration);
std::push_heap(active_agglomerations.begin(), active_agglomerations.end(), agglomeration_priority);
// Look it up
auto& minimizer = minimizers[*next_agglomeration];
// Determine its window size from its index.
size_t window_size = minimizer.window_size();
#ifdef debug
cerr << "\tBegin agglomeration of " << (minimizer.agglomeration_length - window_size + 1)
<< " windows of " << window_size << " bp each for minimizer "
<< *next_agglomeration << " (" << minimizer.forward_offset()
<< "-" << (minimizer.forward_offset() + minimizer.length) << ")" << endl;
#endif
// Make sure the minimizer instance isn't too far into the agglomeration to actually be conatined in the same k+w-1 window as the first base.
assert(minimizer.agglomeration_start + minimizer.candidates_per_window >= minimizer.forward_offset());
for (size_t start = minimizer.agglomeration_start;
start + window_size - 1 < minimizer.agglomeration_start + minimizer.agglomeration_length;
start++) {
// Add all the agglomeration's windows to the queue, looping over their start bases in the read.
window_t add = {start, start + window_size - 1};
#ifdef debug
cerr << "\t\t" << add.first << " - " << add.last << endl;
#endif
active_windows.push(add);
}
// And advance the cursor
++next_agglomeration;
}
// We have the start and end of the latest-starting window ending before here (may be none)
if (isATGC(sequence[i]) &&
(!active_windows.empty() ||
(next_agglomeration != broken.end() && minimizers[*next_agglomeration].agglomeration_start == i))) {
// This base is not N, and it is either covered by an agglomeration
// that hasn't ended yet, or a new agglomeration starts here.
#ifdef debug
cerr << "\tBase is acceptable (" << sequence[i] << ", " << active_agglomerations.size() << " active agglomerations, "
<< active_windows.size() << " active windows)" << endl;
#endif
// Score mutating the base itself, thus causing all the windows it touches to be wrong.
// TODO: account for windows with multiple hits not having to be explained at full cost here.
// We start with the cost to mutate the base.
double base_cost = quality_bytes[i];
#ifdef debug
cerr << "\t\tBase base quality: " << base_cost << endl;
#endif
for (const size_t& active_index : active_agglomerations) {
// Then, we look at each agglomeration the base overlaps
// Find the minimizer whose agglomeration we are looking at
auto& active = minimizers[active_index];
if (i >= active.forward_offset() &&
i < active.forward_offset() + active.length) {
// If the base falls in the minimizer, we don't do anything. Just mutating the base is enough to create this wrong minimizer.
#ifdef debug
cerr << "\t\tBase in minimizer " << active_index << " (" << active.forward_offset()
<< "-" << (active.forward_offset() + active.length) << ") for agglomeration "
<< active.agglomeration_start << "-" << (active.agglomeration_start + active.agglomeration_length) << endl;
#endif
continue;
}
// If the base falls outside the minimizer, it participates in
// some number of other possible minimizers in the
// agglomeration. Compute that, accounting for edge effects.
size_t possible_minimizers = min((size_t) active.length, min(i - active.agglomeration_start + 1, (active.agglomeration_start + active.agglomeration_length) - i));
// Then for each of those possible minimizers, we need P(would have beaten the current minimizer).
// We approximate this as constant across the possible minimizers.
// And since we want to OR together beating, we actually AND together not-beating and then not it.
// So we track the probability of not beating.
double any_beat_phred = phred_for_at_least_one(active.value.hash, possible_minimizers);
#ifdef debug
cerr << "\t\tBase flanks minimizer " << active_index << " (" << active.forward_offset()
<< "-" << (active.forward_offset() + active.length) << ") for agglomeration "
<< active.agglomeration_start << "-" << (active.agglomeration_start + active.agglomeration_length)
<< " and has " << possible_minimizers
<< " chances to have beaten it; cost to have beaten with any is Phred " << any_beat_phred << endl;
#endif
// Then we AND (sum) the Phred of that in, as an additional cost to mutating this base and kitting all the windows it covers.
// This makes low-quality bases outside of minimizers produce fewer low MAPQ caps, and accounts for the robustness of minimizers to some errors.
base_cost += any_beat_phred;
}
// Now we know the cost of mutating this base, so we need to
// compute the total cost of a solution through here, mutating this
// base.
// Look at the start of that latest-starting window ending before here.
if (latest_starting_ending_before.first == numeric_limits<size_t>::max()) {
// If there is no such window, this is the first base hit, so
// record the cost of hitting it.
costs[i] = base_cost;
#ifdef debug
cerr << "\tFirst base hit, costs " << costs[i] << endl;
#endif
} else {
// Else, scan from that window's start to its end in the DP
// table, and find the min cost.
if (latest_starting_ending_before_winner == costs.end()) {
// We haven't found the min in the window we come from yet, so do that.
latest_starting_ending_before_winner = std::min_element(costs.begin() + latest_starting_ending_before.first,
costs.begin() + latest_starting_ending_before.last + 1);
}
double min_prev_cost = *latest_starting_ending_before_winner;
// Add the cost of hitting this base
costs[i] = min_prev_cost + base_cost;
#ifdef debug
cerr << "\tComes from prev base at " << (latest_starting_ending_before_winner - costs.begin()) << ", costs " << costs[i] << endl;
#endif
}
} else {
// This base is N, or not covered by an agglomeration.
// Leave infinity there to say we can't hit it.
// Nothing to do!
}
// Now we compute the start of the latest-starting window ending here or before, and deactivate agglomerations/windows.
while (!active_agglomerations.empty() &&
minimizers[active_agglomerations.front()].agglomeration_start + minimizers[active_agglomerations.front()].agglomeration_length - 1 == i) {
// Look at the queue to see if an agglomeration ends here.
#ifdef debug
cerr << "\tEnd agglomeration " << active_agglomerations.front() << endl;
#endif
std::pop_heap(active_agglomerations.begin(), active_agglomerations.end(), agglomeration_priority);
active_agglomerations.pop_back();
}
while (!active_windows.empty() && active_windows.top().last == i) {
// The look at the queue to see if a window ends here. This is
// after windows are added so that we can handle 1-base windows.
#ifdef debug
cerr << "\tEnd window " << active_windows.top().first << " - " << active_windows.top().last << endl;
#endif
if (latest_starting_ending_before.first == numeric_limits<size_t>::max() ||
active_windows.top().first > latest_starting_ending_before.first) {
#ifdef debug
cerr << "\t\tNew latest-starting-before-here!" << endl;
#endif
// If so, use the latest-starting of all such windows as our latest starting window ending here or before result.
latest_starting_ending_before = active_windows.top();
// And clear our cache of the lowest cost base to hit it.
latest_starting_ending_before_winner = costs.end();
#ifdef debug
cerr << "\t\t\tNow have: " << latest_starting_ending_before.first << " - " << latest_starting_ending_before.last << endl;
#endif
}
// And pop them all off.
active_windows.pop();
}
// If not, use the latest-starting window ending at the previous base or before (i.e. do nothing).
// Loop around; we will have the latest-starting window ending before the next here.
}
#ifdef debug
cerr << "Final window to scan: " << latest_starting_ending_before.first << " - " << latest_starting_ending_before.last << endl;
#endif
// When we get here, all the agglomerations should have been handled
assert(next_agglomeration == broken.end());
// And all the windows should be off the queue.
assert(active_windows.empty());
// When we get to the end, we have the latest-starting window overall. It must exist.
assert(latest_starting_ending_before.first != numeric_limits<size_t>::max());
// Scan it for the best final base to hit and return the cost there.
// Don't use the cache here because nothing can come after the last-ending window.
auto min_cost_at = std::min_element(costs.begin() + latest_starting_ending_before.first,
costs.begin() + latest_starting_ending_before.last + 1);
#ifdef debug
cerr << "Overall min cost: " << *min_cost_at << " at base " << (min_cost_at - costs.begin()) << endl;
#endif
return *min_cost_at;
}
double MinimizerMapper::faster_cap(const vector<Minimizer>& minimizers, vector<size_t>& minimizers_explored,
const string& sequence, const string& quality_bytes) {
// Sort minimizer subset so we go through minimizers in increasing order of start position
std::sort(minimizers_explored.begin(), minimizers_explored.end(), [&](size_t a, size_t b) {
// Return true if a must come before b, and false otherwise
return minimizers[a].forward_offset() < minimizers[b].forward_offset();
});
#ifdef debug
cerr << "Sorted " << minimizers_explored.size() << " minimizers" << endl;
#endif
#ifdef debug
// Dump read and minimizers
int digits_needed = (int) ceil(log10(sequence.size()));
for (int digit = digits_needed - 1; digit >= 0; digit--) {
for (size_t i = 0; i < sequence.size(); i++) {
// Output the correct digit for this place in this number
cerr << (char) ('0' + (uint8_t) round(i % (int) round(pow(10, digit + 1)) / pow(10, digit)));
}
cerr << endl;
}
cerr << sequence << endl;
for (auto& explored_index : minimizers_explored) {
// For each explored minimizer
auto& m = minimizers[explored_index];
for (size_t i = 0; i < m.agglomeration_start; i++) {
// Space until its agglomeration starts
cerr << ' ';
}
for (size_t i = m.agglomeration_start; i < m.forward_offset(); i++) {
// Do the beginnign of the agglomeration
cerr << '-';
}
// Do the minimizer itself
cerr << m.value.key.decode(m.length);
for (size_t i = m.forward_offset() + m.length ; i < m.agglomeration_start + m.agglomeration_length; i++) {
// Do the tail end of the agglomeration
cerr << '-';
}
cerr << endl;
}
#endif
// Make a DP table holding the log10 probability of having an error disrupt each minimizer.
// Entry i+1 is log prob of mutating minimizers 0, 1, 2, ..., i.
// Make sure to have an extra field at the end to support this.
// Initialize with -inf for unfilled.
vector<double> c(minimizers_explored.size() + 1, -numeric_limits<double>::infinity());
c[0] = 0.0;
for_each_aglomeration_interval(minimizers, sequence, quality_bytes, minimizers_explored, [&](size_t left, size_t right, size_t bottom, size_t top) {
// For each overlap range in the agglomerations
#ifdef debug
cerr << "Consider overlap range " << left << " to " << right << " in minimizer ranks " << bottom << " to " << top << endl;
cerr << "log10prob for bottom: " << c[bottom] << endl;
#endif
// Calculate the probability of a disruption here
double p_here = get_log10_prob_of_disruption_in_interval(minimizers, sequence, quality_bytes,
minimizers_explored.begin() + bottom, minimizers_explored.begin() + top, left, right);
#ifdef debug
cerr << "log10prob for here: " << p_here << endl;
#endif
// Calculate prob of all intervals up to top being disrupted
double p = c[bottom] + p_here;
#ifdef debug
cerr << "log10prob overall: " << p << endl;
#endif
for (size_t i = bottom + 1; i < top + 1; i++) {
// Replace min-prob for minimizers in the interval
if (c[i] < p) {
#ifdef debug
cerr << "\tBeats " << c[i] << " at rank " << i-1 << endl;
#endif
c[i] = p;
} else {
#ifdef debug
cerr << "\tBeaten by " << c[i] << " at rank " << i-1 << endl;
#endif
}
}
});
#ifdef debug
cerr << "log10prob after all minimizers is " << c.back() << endl;
#endif
assert(!isinf(c.back()));
// Conver to Phred.
double result = -c.back() * 10;
return result;
}
void MinimizerMapper::for_each_aglomeration_interval(const vector<Minimizer>& minimizers,
const string& sequence, const string& quality_bytes,
const vector<size_t>& minimizer_indices,
const function<void(size_t, size_t, size_t, size_t)>& iteratee) {
if (minimizer_indices.empty()) {
// Handle no item case
return;
}
// Items currently being iterated over
list<const Minimizer*> stack = {&minimizers[minimizer_indices.front()]};
// The left end of an item interval
size_t left = stack.front()->agglomeration_start;
// The index of the first item in the interval in the sequence of selected items
size_t bottom = 0;
// Emit all intervals that precede a given point "right"
auto emit_preceding_intervals = [&](size_t right) {
while (left < right) {
// Work out the end position of the top thing on the stack
size_t stack_top_end = stack.front()->agglomeration_start + stack.front()->agglomeration_length;
if (stack_top_end <= right) {
// Case where the left-most item ends before the start of the new item
iteratee(left, stack_top_end, bottom, bottom + stack.size());
// If the stack contains only one item there is a gap between the item
// and the new item, otherwise just shift to the end of the leftmost item
left = stack.size() == 1 ? right : stack_top_end;
bottom += 1;
stack.pop_front();
} else {
// Case where the left-most item ends at or after the beginning of the new new item
iteratee(left, right, bottom, bottom + stack.size());
left = right;
}
}
};
for (auto it = minimizer_indices.begin() + 1; it != minimizer_indices.end(); ++it) {
// For each item in turn
auto& item = minimizers[*it];
assert(stack.size() > 0);
// For each new item we return all intervals that
// precede its start
emit_preceding_intervals(item.agglomeration_start);
// Add the new item for the next loop
stack.push_back(&item);
}
// Intervals of the remaining intervals on the stack
emit_preceding_intervals(sequence.size());
}
double MinimizerMapper::get_log10_prob_of_disruption_in_interval(const vector<Minimizer>& minimizers,
const string& sequence, const string& quality_bytes,
const vector<size_t>::iterator& disrupt_begin, const vector<size_t>::iterator& disrupt_end,
size_t left, size_t right) {
#ifdef debug
cerr << "Compute log10 probability in interval " << left << "-" << right << endl;
#endif
if (left == right) {
// 0-length intervals need no disruption.
return 0;
}
// Ww eant an OR over all the columns, so we compute an AND of NOT all the columns, and then NOT at the end.
// Start with the first column.
double p = 1.0 - get_prob_of_disruption_in_column(minimizers, sequence, quality_bytes, disrupt_begin, disrupt_end, left);
#ifdef debug
cerr << "\tProbability not disrupted at column " << left << ": " << p << endl;
#endif
for(size_t i = left + 1 ; i < right; i++) {
// OR up probability of all the other columns
double col_p = 1.0 - get_prob_of_disruption_in_column(minimizers, sequence, quality_bytes, disrupt_begin, disrupt_end, i);
#ifdef debug
cerr << "\tProbability not disrupted at column " << i << ": " << col_p << endl;
#endif
p *= col_p;
#ifdef debug
cerr << "\tRunning AND of not disrupted anywhere: " << p << endl;
#endif
}
// NOT the AND of NOT, so we actually OR over the columns.
// Also convert to log10prob.
return log10(1.0 - p);
}
double MinimizerMapper::get_prob_of_disruption_in_column(const vector<Minimizer>& minimizers,
const string& sequence, const string& quality_bytes,
const vector<size_t>::iterator& disrupt_begin, const vector<size_t>::iterator& disrupt_end,
size_t index) {
#ifdef debug
cerr << "\tCompute probability at column " << index << endl;
#endif
// Base cost is quality. Make sure to compute a non-integral answer.
double p = phred_to_prob((uint8_t)quality_bytes[index]);
#ifdef debug
cerr << "\t\tBase probability from quality: " << p << endl;
#endif
for (auto it = disrupt_begin; it != disrupt_end; ++it) {
// For each minimizer to disrupt
auto m = minimizers[*it];
#ifdef debug
cerr << "\t\tRelative rank " << (it - disrupt_begin) << " is minimizer " << m.value.key.decode(m.length) << endl;
#endif
if (!(m.forward_offset() <= index && index < m.forward_offset() + m.length)) {
// Index is out of range of the minimizer itself. We're in the flank.
#ifdef debug
cerr << "\t\t\tColumn " << index << " is in flank." << endl;
#endif
// How many new possible minimizers would an error here create in this agglomeration,
// to compete with its minimizer?
// No more than one per position in a minimizer sequence.
// No more than 1 per base from the start of the agglomeration to here, inclusive.
// No more than 1 per base from here to the last base of the agglomeration, inclusive.
size_t possible_minimizers = min((size_t) m.length,
min(index - m.agglomeration_start + 1,
(m.agglomeration_start + m.agglomeration_length) - index));
// Account for at least one of them beating the minimizer.
double any_beat_prob = prob_for_at_least_one(m.value.hash, possible_minimizers);
#ifdef debug
cerr << "\t\t\tBeat hash " << m.value.hash << " at least 1 time in " << possible_minimizers << " gives probability: " << any_beat_prob << endl;
#endif
p *= any_beat_prob;
// TODO: handle N somehow??? It can occur outside the minimizer itself, here in the flank.
}
#ifdef debug
cerr << "\t\t\tRunning AND prob: " << p << endl;
#endif
}
return p;
}
//-----------------------------------------------------------------------------
void MinimizerMapper::attempt_rescue(const Alignment& aligned_read, Alignment& rescued_alignment, const std::vector<Minimizer>& minimizers, bool rescue_forward ) {
if (this->rescue_algorithm == rescue_none) { return; }
// We are traversing the same small subgraph repeatedly, so it's better to use a cache.
gbwtgraph::CachedGBWTGraph cached_graph(this->gbwt_graph);
// Find all nodes within a reasonable range from aligned_read.
std::unordered_set<id_t> rescue_nodes;
int64_t min_distance = max(0.0, fragment_length_distr.mean() - rescued_alignment.sequence().size() - rescue_subgraph_stdevs * fragment_length_distr.std_dev());
int64_t max_distance = fragment_length_distr.mean() + rescue_subgraph_stdevs * fragment_length_distr.std_dev();
distance_index.subgraph_in_range(aligned_read.path(), &cached_graph, min_distance, max_distance, rescue_nodes, rescue_forward);
// Remove node ids that do not exist in the GBWTGraph from the subgraph.
// We may be using the distance index of the original graph, and nodes
// not visited by any thread are missing from the GBWTGraph.
for (auto iter = rescue_nodes.begin(); iter != rescue_nodes.end(); ) {
if (!cached_graph.has_node(*iter)) {
iter = rescue_nodes.erase(iter);
} else {
++iter;
}
}
// Get rid of the old path.
rescued_alignment.clear_path();
// Find all seeds in the subgraph and try to get a full-length extension.
GaplessExtender::cluster_type seeds = this->seeds_in_subgraph(minimizers, rescue_nodes);
std::vector<GaplessExtension> extensions = this->extender.extend(seeds, rescued_alignment.sequence(), &cached_graph);
size_t best = extensions.size();
for (size_t i = 0; i < extensions.size(); i++) {
if (best >= extensions.size() || extensions[i].score > extensions[best].score) {
best = i;
}
}
// If we have a full-length extension, use it as the rescued alignment.
if (best < extensions.size() && extensions[best].full()) {
this->extension_to_alignment(extensions[best], rescued_alignment);
return;
}
// The haplotype-based algorithm is a special case.
if (this->rescue_algorithm == rescue_haplotypes) {
// Find and unfold the local haplotypes in the subgraph.
std::vector<std::vector<handle_t>> haplotype_paths;
bdsg::HashGraph align_graph;
this->extender.unfold_haplotypes(rescue_nodes, haplotype_paths, align_graph);
// Align to the subgraph.
this->get_regular_aligner()->align_xdrop(rescued_alignment, align_graph,
std::vector<MaximalExactMatch>(), false);
this->fix_dozeu_score(rescued_alignment, align_graph, std::vector<handle_t>());
// Get the corresponding alignment to the original graph.
this->extender.transform_alignment(rescued_alignment, haplotype_paths);
return;
}
// Use the best extension as a seed for dozeu.
// Also ensure that the entire extension is in the subgraph.
std::vector<MaximalExactMatch> dozeu_seed;
if (best < extensions.size()) {
const GaplessExtension& extension = extensions[best];
for (handle_t handle : extension.path) {
rescue_nodes.insert(cached_graph.get_id(handle));
}
dozeu_seed.emplace_back();
dozeu_seed.back().begin = rescued_alignment.sequence().begin() + extension.read_interval.first;
dozeu_seed.back().end = rescued_alignment.sequence().begin() + extension.read_interval.second;
nid_t id = cached_graph.get_id(extension.path.front());
bool is_reverse = cached_graph.get_is_reverse(extension.path.front());
gcsa::node_type node = gcsa::Node::encode(id, extension.offset, is_reverse);
dozeu_seed.back().nodes.push_back(node);
}
// GSSW and dozeu assume that the graph is a DAG.
std::vector<handle_t> topological_order = gbwtgraph::topological_order(cached_graph, rescue_nodes);
if (!topological_order.empty()) {
if (rescue_algorithm == rescue_dozeu) {
get_regular_aligner()->align_xdrop(rescued_alignment, cached_graph, topological_order,
dozeu_seed, false);
this->fix_dozeu_score(rescued_alignment, cached_graph, topological_order);
} else {
get_regular_aligner()->align(rescued_alignment, cached_graph, topological_order);
}
return;
}
// Build a subgraph overlay.
SubHandleGraph sub_graph(&cached_graph);
for (id_t id : rescue_nodes) {
sub_graph.add_handle(cached_graph.get_handle(id));
}
// Create an overlay where each strand is a separate node.
StrandSplitGraph split_graph(&sub_graph);
// Dagify the subgraph.
bdsg::HashGraph dagified;
std::unordered_map<id_t, id_t> dagify_trans =
algorithms::dagify(&split_graph, &dagified, rescued_alignment.sequence().size());
// Align to the subgraph.
// TODO: Map the seed to the dagified subgraph.
if (this->rescue_algorithm == rescue_dozeu) {
get_regular_aligner()->align_xdrop(rescued_alignment, dagified, std::vector<MaximalExactMatch>(), false);
this->fix_dozeu_score(rescued_alignment, dagified, std::vector<handle_t>());
} else if (this->rescue_algorithm == rescue_gssw) {
get_regular_aligner()->align(rescued_alignment, dagified, true);
}
// Map the alignment back to the original graph.
Path& path = *(rescued_alignment.mutable_path());
for (size_t i = 0; i < path.mapping_size(); i++) {
Position& pos = *(path.mutable_mapping(i)->mutable_position());
id_t id = dagify_trans[pos.node_id()];
handle_t handle = split_graph.get_underlying_handle(split_graph.get_handle(id));
pos.set_node_id(sub_graph.get_id(handle));
pos.set_is_reverse(sub_graph.get_is_reverse(handle));
}
}
GaplessExtender::cluster_type MinimizerMapper::seeds_in_subgraph(const std::vector<Minimizer>& minimizers,
const std::unordered_set<id_t>& subgraph) const {
std::vector<id_t> sorted_ids(subgraph.begin(), subgraph.end());
std::sort(sorted_ids.begin(), sorted_ids.end());
GaplessExtender::cluster_type result;
for (const Minimizer& minimizer : minimizers) {
gbwtgraph::hits_in_subgraph(minimizer.hits, minimizer.occs, sorted_ids, [&](pos_t pos, gbwtgraph::payload_type) {
if (minimizer.value.is_reverse) {
size_t node_length = this->gbwt_graph.get_length(this->gbwt_graph.get_handle(id(pos)));
pos = reverse_base_pos(pos, node_length);
}
result.insert(GaplessExtender::to_seed(pos, minimizer.value.offset));
});
}
return result;
}
void MinimizerMapper::fix_dozeu_score(Alignment& rescued_alignment, const HandleGraph& rescue_graph,
const std::vector<handle_t>& topological_order) const {
const Aligner* aligner = this->get_regular_aligner();
int32_t score = aligner->score_ungapped_alignment(rescued_alignment);
if (score > 0) {
rescued_alignment.set_score(score);
} else {
rescued_alignment.clear_path();
if (topological_order.empty()) {
aligner->align(rescued_alignment, rescue_graph, true);
} else {
aligner->align(rescued_alignment, rescue_graph, topological_order);
}
}
}
//-----------------------------------------------------------------------------
int64_t MinimizerMapper::distance_between(const Alignment& aln1, const Alignment& aln2) {
assert(aln1.path().mapping_size() != 0);
assert(aln2.path().mapping_size() != 0);
pos_t pos1 = initial_position(aln1.path());
pos_t pos2 = final_position(aln2.path());
int64_t min_dist = distance_index.min_distance(pos1, pos2);
return min_dist == -1 ? numeric_limits<int64_t>::max() : min_dist;
}
void MinimizerMapper::extension_to_alignment(const GaplessExtension& extension, Alignment& alignment) const {
*(alignment.mutable_path()) = extension.to_path(this->gbwt_graph, alignment.sequence());
alignment.set_score(extension.score);
double identity = 0.0;
if (!alignment.sequence().empty()) {
size_t len = alignment.sequence().length();
identity = (len - extension.mismatches()) / static_cast<double>(len);
}
alignment.set_identity(identity);
}
//-----------------------------------------------------------------------------
std::vector<MinimizerMapper::Minimizer> MinimizerMapper::find_minimizers(const std::string& sequence, Funnel& funnel) const {
if (this->track_provenance) {
// Start the minimizer finding stage
funnel.stage("minimizer");
}
std::vector<Minimizer> result;
double base_score = 1.0 + std::log(this->hard_hit_cap);
for (size_t i = 0; i < this->minimizer_indexes.size(); i++) {
// Get minimizers and their window agglomeration starts and lengths
vector<tuple<gbwtgraph::DefaultMinimizerIndex::minimizer_type, size_t, size_t>> current_minimizers =
minimizer_indexes[i]->minimizer_regions(sequence);
for (auto& m : current_minimizers) {
double score = 0.0;
auto hits = this->minimizer_indexes[i]->count_and_find(get<0>(m));
if (hits.first > 0) {
if (hits.first <= this->hard_hit_cap) {
score = base_score - std::log(hits.first);
} else {
score = 1.0;
}
}
result.push_back({ std::get<0>(m), std::get<1>(m), std::get<2>(m), hits.first, hits.second,
(int32_t) minimizer_indexes[i]->k(), (int32_t) minimizer_indexes[i]->w(), score });
}
}
std::sort(result.begin(), result.end());
if (this->track_provenance) {
// Record how many we found, as new lines.
funnel.introduce(result.size());
}
return result;
}
std::vector<MinimizerMapper::Seed> MinimizerMapper::find_seeds(const std::vector<Minimizer>& minimizers, const Alignment& aln, Funnel& funnel) const {
if (this->track_provenance) {
// Start the minimizer locating stage
funnel.stage("seed");
}
// One of the filters accepts minimizers until selected_score reaches target_score.
double base_target_score = 0.0;
for (const Minimizer& minimizer : minimizers) {
base_target_score += minimizer.score;
}
double target_score = (base_target_score * this->minimizer_score_fraction) + 0.000001;
double selected_score = 0.0;
// In order to consistently take either all or none of the minimizers in
// the read with a particular sequence, we track whether we took the
// previous one.
bool took_last = false;
// Select the minimizers we use for seeds.
size_t rejected_count = 0;
std::vector<Seed> seeds;
// Flag whether each minimizer in the read was located or not, for MAPQ capping.
// We ignore minimizers with no hits (count them as not located), because
// they would have to be created in the read no matter where we say it came
// from, and because adding more of them should lower the MAPQ cap, whereas
// locating more of the minimizers that are present and letting them pass
// to the enxt stage should raise the cap.
for (size_t i = 0; i < minimizers.size(); i++) {
if (this->track_provenance) {
// Say we're working on it
funnel.processing_input(i);
}
// Select the minimizer if it is informative enough or if the total score
// of the selected minimizers is not high enough.
const Minimizer& minimizer = minimizers[i];
#ifdef debug
std::cerr << "Minimizer " << i << " = " << minimizer.value.key.decode(minimizer.length)
<< " has " << minimizer.hits << " hits" << std::endl;
#endif
if (minimizer.hits == 0) {
// A minimizer with no hits can't go on.
took_last = false;
// We do not treat it as located for MAPQ capping purposes.
if (this->track_provenance) {
funnel.fail("any-hits", i);
}
} else if (minimizer.hits <= this->hit_cap ||
(minimizer.hits <= this->hard_hit_cap && selected_score + minimizer.score <= target_score) ||
(took_last && i > 0 && minimizer.value.key == minimizers[i - 1].value.key)) {
// We should keep this minimizer instance because it is
// sufficiently rare, or we want it to make target_score, or it is
// the same sequence as the previous minimizer which we also took.
// Locate the hits.
for (size_t j = 0; j < minimizer.hits; j++) {
pos_t hit = gbwtgraph::Position::decode(minimizer.occs[j].pos);
// Reverse the hits for a reverse minimizer
if (minimizer.value.is_reverse) {
size_t node_length = this->gbwt_graph.get_length(this->gbwt_graph.get_handle(id(hit)));
hit = reverse_base_pos(hit, node_length);
}
// Extract component id and offset in the root chain, if we have them for this seed.
// TODO: Get all the seed values here
tuple<bool, size_t, size_t, bool, size_t, size_t, size_t, size_t, bool> chain_info
(false, MIPayload::NO_VALUE, MIPayload::NO_VALUE, false, MIPayload::NO_VALUE, MIPayload::NO_VALUE, MIPayload::NO_VALUE, MIPayload::NO_VALUE, false );
if (minimizer.occs[j].payload != MIPayload::NO_CODE) {
chain_info = MIPayload::decode(minimizer.occs[j].payload);
}
seeds.push_back({ hit, i, std::get<0>(chain_info), std::get<1>(chain_info), std::get<2>(chain_info),
std::get<3>(chain_info), std::get<4>(chain_info), std::get<5>(chain_info), std::get<6>(chain_info), std::get<7>(chain_info), std::get<8>(chain_info) });
}
if (!(took_last && i > 0 && minimizer.value.key == minimizers[i - 1].value.key)) {
// We did not also take a previous identical-sequence minimizer, so count this one towards the score.
selected_score += minimizer.score;
}
// Remember that we took this minimizer
took_last = true;
if (this->track_provenance) {
// Record in the funnel that this minimizer gave rise to these seeds.
funnel.pass("any-hits", i);
funnel.pass("hard-hit-cap", i);
funnel.pass("hit-cap||score-fraction", i, selected_score / base_target_score);
funnel.expand(i, minimizer.hits);
}
} else if (minimizer.hits <= this->hard_hit_cap) {
// Passed hard hit cap but failed score fraction/normal hit cap
took_last = false;
rejected_count++;
if (this->track_provenance) {
funnel.pass("any-hits", i);
funnel.pass("hard-hit-cap", i);
funnel.fail("hit-cap||score-fraction", i, (selected_score + minimizer.score) / base_target_score);
}
//Stop looking for more minimizers once we fail the score fraction
target_score = selected_score;
} else {
// Failed hard hit cap
took_last = false;
rejected_count++;
if (this->track_provenance) {
funnel.pass("any-hits", i);
funnel.fail("hard-hit-cap", i);
}
}
if (this->track_provenance) {
// Say we're done with this input item
funnel.processed_input();
}
}
if (this->track_provenance && this->track_correctness) {
// Tag seeds with correctness based on proximity along paths to the input read's refpos
funnel.substage("correct");
if (this->path_graph == nullptr) {
cerr << "error[vg::MinimizerMapper] Cannot use track_correctness with no XG index" << endl;
exit(1);
}
if (aln.refpos_size() != 0) {
// Take the first refpos as the true position.
auto& true_pos = aln.refpos(0);
for (size_t i = 0; i < seeds.size(); i++) {
// Find every seed's reference positions. This maps from path name to pairs of offset and orientation.
auto offsets = algorithms::nearest_offsets_in_paths(this->path_graph, seeds[i].pos, 100);
for (auto& hit_pos : offsets[this->path_graph->get_path_handle(true_pos.name())]) {
// Look at all the ones on the path the read's true position is on.
if (abs((int64_t)hit_pos.first - (int64_t) true_pos.offset()) < 200) {
// Call this seed hit close enough to be correct
funnel.tag_correct(i);
}
}
}
}
}
#ifdef debug
std::cerr << "Found " << seeds.size() << " seeds from " << (minimizers.size() - rejected_count) << " minimizers, rejected " << rejected_count << std::endl;
#endif
return seeds;
}
//-----------------------------------------------------------------------------
void MinimizerMapper::score_cluster(Cluster& cluster, size_t i, const std::vector<Minimizer>& minimizers, const std::vector<Seed>& seeds, size_t seq_length, Funnel& funnel) const {
if (this->track_provenance) {
// Say we're making it
funnel.producing_output(i);
}
// Initialize the values.
cluster.score = 0.0;
cluster.coverage = 0.0;
cluster.present = SmallBitset(minimizers.size());
// Determine the minimizers that are present in the cluster.
for (auto hit_index : cluster.seeds) {
cluster.present.insert(seeds[hit_index].source);
#ifdef debug
cerr << "Minimizer " << seeds[hit_index].source << " is present in cluster " << i << endl;
#endif
}
// Compute the score and cluster coverage.
sdsl::bit_vector covered(seq_length, 0);
for (size_t j = 0; j < minimizers.size(); j++) {
if (cluster.present.contains(j)) {
const Minimizer& minimizer = minimizers[j];
cluster.score += minimizer.score;
// The offset of a reverse minimizer is the endpoint of the kmer
size_t start_offset = minimizer.forward_offset();
size_t k = minimizer.length;
// Set the k bits starting at start_offset.
covered.set_int(start_offset, sdsl::bits::lo_set[k], k);
}
}
// Count up the covered positions and turn it into a fraction.
cluster.coverage = sdsl::util::cnt_one_bits(covered) / static_cast<double>(seq_length);
if (this->track_provenance) {
// Record the cluster in the funnel as a group of the size of the number of items.
funnel.merge_group(cluster.seeds.begin(), cluster.seeds.end());
funnel.score(funnel.latest(), cluster.score);
// Say we made it.
funnel.produced_output();
}
}
//-----------------------------------------------------------------------------
int MinimizerMapper::score_extension_group(const Alignment& aln, const vector<GaplessExtension>& extended_seeds,
int gap_open_penalty, int gap_extend_penalty) {
if (extended_seeds.empty()) {
// TODO: We should never see an empty group of extensions
return 0;
} else if (extended_seeds.front().full()) {
// These are length matches. We already have the score.
int best_score = 0;
for (auto& extension : extended_seeds) {
best_score = max(best_score, extension.score);
}
return best_score;
} else {
// This is a collection of one or more non-full-length extended seeds.
if (aln.sequence().size() == 0) {
// No score here
return 0;
}
// We use a sweep line algorithm to find relevant points along the read: extension starts or ends.
// This records the last base to be covered by the current sweep line.
int64_t sweep_line = 0;
// This records the first base not covered by the last sweep line.
int64_t last_sweep_line = 0;
// And we track the next unentered gapless extension
size_t unentered = 0;
// Extensions we are in are in this min-heap of past-end position and gapless extension number.
vector<pair<size_t, size_t>> end_heap;
// The heap uses this comparator
auto min_heap_on_first = [](const pair<size_t, size_t>& a, const pair<size_t, size_t>& b) {
// Return true if a must come later in the heap than b
return a.first > b.first;
};
// We track the best score for a chain reaching the position before this one and ending in a gap.
// We never let it go below 0.
// Will be 0 when there's no gap that can be open
int best_gap_score = 0;
// We track the score for the best chain ending with each gapless extension
vector<int> best_chain_score(extended_seeds.size(), 0);
// And we're after the best score overall that we can reach when an extension ends
int best_past_ending_score_ever = 0;
// Overlaps are more complicated.
// We need a heap of all the extensions for which we have seen the
// start and that we can thus overlap.
// We filter things at the top of the heap if their past-end positions
// have occurred.
// So we store pairs of score we get backtracking to the current
// position, and past-end position for the thing we are backtracking
// from.
vector<pair<int, size_t>> overlap_heap;
// We can just use the standard max-heap comparator
// We encode the score relative to a counter that we increase by the
// gap extend every base we go through, so we don't need to update and
// re-sort the heap.
int overlap_score_offset = 0;
while(last_sweep_line <= aln.sequence().size()) {
// We are processed through the position before last_sweep_line.
// Find a place for sweep_line to go
// Find the next seed start
int64_t next_seed_start = numeric_limits<int64_t>::max();
if (unentered < extended_seeds.size()) {
next_seed_start = extended_seeds[unentered].read_interval.first;
}
// Find the next seed end
int64_t next_seed_end = numeric_limits<int64_t>::max();
if (!end_heap.empty()) {
next_seed_end = end_heap.front().first;
}
// Whichever is closer between those points and the end, do that.
sweep_line = min(min(next_seed_end, next_seed_start), (int64_t) aln.sequence().size());
// So now we're only interested in things that happen at sweep_line.
// Compute the distance from the previous sweep line position
// Make sure to account for last_sweep_line's semantics as the next unswept base.
int sweep_distance = sweep_line - last_sweep_line + 1;
// We need to track the score of the best thing that past-ended here
int best_past_ending_score_here = 0;
while(!end_heap.empty() && end_heap.front().first == sweep_line) {
// Find anything that past-ends here
size_t past_ending = end_heap.front().second;
// Mix it into the score
best_past_ending_score_here = std::max(best_past_ending_score_here, best_chain_score[past_ending]);
// Remove it from the end-tracking heap
std::pop_heap(end_heap.begin(), end_heap.end(), min_heap_on_first);
end_heap.pop_back();
}
// Mix that into the best score overall
best_past_ending_score_ever = std::max(best_past_ending_score_ever, best_past_ending_score_here);
if (sweep_line == aln.sequence().size()) {
// We don't need to think about gaps or backtracking anymore since everything has ended
break;
}
// Update the overlap score offset by removing some gap extends from it.
overlap_score_offset += sweep_distance * gap_extend_penalty;
// The best way to backtrack to here is whatever is on top of the heap, if anything, that doesn't past-end here.
int best_overlap_score = 0;
while (!overlap_heap.empty()) {
// While there is stuff on the heap
if (overlap_heap.front().second <= sweep_line) {
// We are already past this thing, so drop it
std::pop_heap(overlap_heap.begin(), overlap_heap.end());
overlap_heap.pop_back();
} else {
// This is at the top of the heap and we aren't past it
// Decode and use its score offset if we only backtrack to here.
best_overlap_score = overlap_heap.front().first + overlap_score_offset;
// Stop looking in the heap
break;
}
}
// The best way to end 1 before here in a gap is either:
if (best_gap_score != 0) {
// Best way to end 1 before our last sweep line position with a gap, plus distance times gap extend penalty
best_gap_score -= sweep_distance * gap_extend_penalty;
}
// Best way to end 1 before here with an actual extension, plus the gap open part of the gap open penalty.
// (Will never be taken over an actual adjacency)
best_gap_score = std::max(0, std::max(best_gap_score, best_past_ending_score_here - (gap_open_penalty - gap_extend_penalty)));
while (unentered < extended_seeds.size() && extended_seeds[unentered].read_interval.first == sweep_line) {
// For each thing that starts here
// Compute its chain score
best_chain_score[unentered] = std::max(best_overlap_score,
std::max(best_gap_score, best_past_ending_score_here)) + extended_seeds[unentered].score;
// Compute its backtrack-to-here score and add it to the backtracking heap
// We want how far we would have had to have backtracked to be
// able to preceed the base we are at now, where this thing
// starts.
size_t extension_length = extended_seeds[unentered].read_interval.second - extended_seeds[unentered].read_interval.first;
int raw_overlap_score = best_chain_score[unentered] - gap_open_penalty - gap_extend_penalty * extension_length;
int encoded_overlap_score = raw_overlap_score - overlap_score_offset;
// Stick it in the heap
overlap_heap.emplace_back(encoded_overlap_score, extended_seeds[unentered].read_interval.second);
std::push_heap(overlap_heap.begin(), overlap_heap.end());
// Add it to the end finding heap
end_heap.emplace_back(extended_seeds[unentered].read_interval.second, unentered);
std::push_heap(end_heap.begin(), end_heap.end(), min_heap_on_first);
// Advance and check the next thing to start
unentered++;
}
// Move last_sweep_line to sweep_line.
// We need to add 1 since last_sweep_line is the next *un*included base
last_sweep_line = sweep_line + 1;
}
// When we get here, we've seen the end of every extension and so we
// have the best score at the end of any of them.
return best_past_ending_score_ever;
}
}
std::vector<int> MinimizerMapper::score_extensions(const std::vector<std::vector<GaplessExtension>>& extensions, const Alignment& aln, Funnel& funnel) const {
// Extension scoring substage.
if (this->track_provenance) {
funnel.substage("score");
}
// We now estimate the best possible alignment score for each cluster.
std::vector<int> result(extensions.size(), 0);
for (size_t i = 0; i < extensions.size(); i++) {
if (this->track_provenance) {
funnel.producing_output(i);
}
result[i] = score_extension_group(aln, extensions[i], get_regular_aligner()->gap_open, get_regular_aligner()->gap_extension);
// Record the score with the funnel.
if (this->track_provenance) {
funnel.score(i, result[i]);
funnel.produced_output();
}
}
return result;
}
std::vector<int> MinimizerMapper::score_extensions(const std::vector<std::pair<std::vector<GaplessExtension>, size_t>>& extensions, const Alignment& aln, Funnel& funnel) const {
// Extension scoring substage.
if (this->track_provenance) {
funnel.substage("score");
}
// We now estimate the best possible alignment score for each cluster.
std::vector<int> result(extensions.size(), 0);
for (size_t i = 0; i < extensions.size(); i++) {
if (this->track_provenance) {
funnel.producing_output(i);
}
result[i] = score_extension_group(aln, extensions[i].first, get_regular_aligner()->gap_open, get_regular_aligner()->gap_extension);
// Record the score with the funnel.
if (this->track_provenance) {
funnel.score(i, result[i]);
funnel.produced_output();
}
}
return result;
}
//-----------------------------------------------------------------------------
void MinimizerMapper::find_optimal_tail_alignments(const Alignment& aln, const vector<GaplessExtension>& extended_seeds, Alignment& best, Alignment& second_best) const {
#ifdef debug
cerr << "Trying to find tail alignments for " << extended_seeds.size() << " extended seeds" << endl;
#endif
// Make paths for all the extensions
vector<Path> extension_paths;
vector<double> extension_path_scores;
extension_paths.reserve(extended_seeds.size());
extension_path_scores.reserve(extended_seeds.size());
for (auto& extended_seed : extended_seeds) {
// Compute the path for each extension
extension_paths.push_back(extended_seed.to_path(gbwt_graph, aln.sequence()));
// And the extension's score
extension_path_scores.push_back(get_regular_aligner()->score_partial_alignment(aln, gbwt_graph, extension_paths.back(),
aln.sequence().begin() + extended_seed.read_interval.first));
}
// We will keep the winning alignment here, in pieces
Path winning_left;
Path winning_middle;
Path winning_right;
size_t winning_score = 0;
Path second_left;
Path second_middle;
Path second_right;
size_t second_score = 0;
// Handle each extension in the set
process_until_threshold_b(extended_seeds, extension_path_scores,
extension_score_threshold, 1, max_local_extensions,
(function<double(size_t)>) [&](size_t extended_seed_num) {
// This extended seed looks good enough.
// TODO: We don't track this filter with the funnel because it
// operates within a single "item" (i.e. cluster/extension set).
// We track provenance at the item level, so throwing out wrong
// local alignments in a correct cluster would look like throwing
// out correct things.
// TODO: Revise how we track correctness and provenance to follow
// sub-cluster things.
// We start with the path in extension_paths[extended_seed_num],
// scored in extension_path_scores[extended_seed_num]
// We also have a left tail path and score
pair<Path, int64_t> left_tail_result {{}, 0};
// And a right tail path and score
pair<Path, int64_t> right_tail_result {{}, 0};
if (extended_seeds[extended_seed_num].read_interval.first != 0) {
// There is a left tail
// Get the forest of all left tail placements
auto forest = get_tail_forest(extended_seeds[extended_seed_num], aln.sequence().size(), true);
// Grab the part of the read sequence that comes before the extension
string before_sequence = aln.sequence().substr(0, extended_seeds[extended_seed_num].read_interval.first);
// Do right-pinned alignment
left_tail_result = std::move(get_best_alignment_against_any_tree(forest, before_sequence,
extended_seeds[extended_seed_num].starting_position(gbwt_graph), false));
}
if (extended_seeds[extended_seed_num].read_interval.second != aln.sequence().size()) {
// There is a right tail
// Get the forest of all right tail placements
auto forest = get_tail_forest(extended_seeds[extended_seed_num], aln.sequence().size(), false);
// Find the sequence
string trailing_sequence = aln.sequence().substr(extended_seeds[extended_seed_num].read_interval.second);
// Do left-pinned alignment
right_tail_result = std::move(get_best_alignment_against_any_tree(forest, trailing_sequence,
extended_seeds[extended_seed_num].tail_position(gbwt_graph), true));
}
// Compute total score
size_t total_score = extension_path_scores[extended_seed_num] + left_tail_result.second + right_tail_result.second;
//Get the node ids of the beginning and end of each alignment
id_t winning_start = winning_score == 0 ? 0 : (winning_left.mapping_size() == 0
? winning_middle.mapping(0).position().node_id()
: winning_left.mapping(0).position().node_id());
id_t current_start = left_tail_result.first.mapping_size() == 0
? extension_paths[extended_seed_num].mapping(0).position().node_id()
: left_tail_result.first.mapping(0).position().node_id();
id_t winning_end = winning_score == 0 ? 0 : (winning_right.mapping_size() == 0
? winning_middle.mapping(winning_middle.mapping_size() - 1).position().node_id()
: winning_right.mapping(winning_right.mapping_size()-1).position().node_id());
id_t current_end = right_tail_result.first.mapping_size() == 0
? extension_paths[extended_seed_num].mapping(extension_paths[extended_seed_num].mapping_size() - 1).position().node_id()
: right_tail_result.first.mapping(right_tail_result.first.mapping_size()-1).position().node_id();
//Is this left tail different from the currently winning left tail?
bool different_left = winning_start != current_start;
bool different_right = winning_end != current_end;
if (total_score > winning_score || winning_score == 0) {
// This is the new best alignment seen so far.
if (winning_score != 0 && different_left && different_right) {
//The previous best scoring alignment replaces the second best
second_score = winning_score;
second_left = std::move(winning_left);
second_middle = std::move(winning_middle);
second_right = std::move(winning_right);
}
// Save the score
winning_score = total_score;
// And the path parts
winning_left = std::move(left_tail_result.first);
winning_middle = std::move(extension_paths[extended_seed_num]);
winning_right = std::move(right_tail_result.first);
} else if ((total_score > second_score || second_score == 0) && different_left && different_right) {
// This is the new second best alignment seen so far and it is
// different from the best alignment.
// Save the score
second_score = total_score;
// And the path parts
second_left = std::move(left_tail_result.first);
second_middle = std::move(extension_paths[extended_seed_num]);
second_right = std::move(right_tail_result.first);
}
return true;
}, [&](size_t extended_seed_num) {
// This extended seed is good enough by its own score, but we have too many.
// Do nothing
}, [&](size_t extended_seed_num) {
// This extended seed isn't good enough by its own score.
// Do nothing
});
// Now we know the winning path and score. Move them over to out
best.set_score(winning_score);
second_best.set_score(second_score);
// Concatenate the paths. We know there must be at least an edit boundary
// between each part, because the maximal extension doesn't end in a
// mismatch or indel and eats all matches.
// We also don't need to worry about jumps that skip intervening sequence.
*best.mutable_path() = std::move(winning_left);
for (auto* to_append : {&winning_middle, &winning_right}) {
// For each path to append
for (auto& mapping : *to_append->mutable_mapping()) {
// For each mapping to append
if (mapping.position().offset() != 0 && best.path().mapping_size() > 0) {
// If we have a nonzero offset in our mapping, and we follow
// something, we must be continuing on from a previous mapping to
// the node.
assert(mapping.position().node_id() == best.path().mapping(best.path().mapping_size() - 1).position().node_id());
// Find that previous mapping
auto* prev_mapping = best.mutable_path()->mutable_mapping(best.path().mapping_size() - 1);
for (auto& edit : *mapping.mutable_edit()) {
// Move over all the edits in this mapping onto the end of that one.
*prev_mapping->add_edit() = std::move(edit);
}
} else {
// If we start at offset 0 or there's nothing before us, we need to just move the whole mapping
*best.mutable_path()->add_mapping() = std::move(mapping);
}
}
}
best.set_identity(identity(best.path()));
//Do the same for the second best
*second_best.mutable_path() = std::move(second_left);
for (auto* to_append : {&second_middle, &second_right}) {
// For each path to append
for (auto& mapping : *to_append->mutable_mapping()) {
// For each mapping to append
if (mapping.position().offset() != 0 && second_best.path().mapping_size() > 0) {
// If we have a nonzero offset in our mapping, and we follow
// something, we must be continuing on from a previous mapping to
// the node.
assert(mapping.position().node_id() == second_best.path().mapping(second_best.path().mapping_size() - 1).position().node_id());
// Find that previous mapping
auto* prev_mapping = second_best.mutable_path()->mutable_mapping(second_best.path().mapping_size() - 1);
for (auto& edit : *mapping.mutable_edit()) {
// Move over all the edits in this mapping onto the end of that one.
*prev_mapping->add_edit() = std::move(edit);
}
} else {
// If we start at offset 0 or there's nothing before us, we need to just move the whole mapping
*second_best.mutable_path()->add_mapping() = std::move(mapping);
}
}
}
// Compute the identity from the path.
second_best.set_identity(identity(second_best.path()));
}
pair<Path, size_t> MinimizerMapper::get_best_alignment_against_any_tree(const vector<TreeSubgraph>& trees,
const string& sequence, const Position& default_position, bool pin_left) const {
// We want the best alignment, to the base graph, done against any target path
Path best_path;
// And its score
int64_t best_score = 0;
if (!sequence.empty()) {
// We start out with the best alignment being a pure softclip.
// If we don't have any trees, or all trees are empty, or there's nothing beter, this is what we return.
Mapping* m = best_path.add_mapping();
Edit* e = m->add_edit();
e->set_from_length(0);
e->set_to_length(sequence.size());
e->set_sequence(sequence);
// Since the softclip consumes no graph, we place it on the node we are going to.
*m->mutable_position() = default_position;
#ifdef debug
cerr << "First best alignment: " << pb2json(best_path) << " score " << best_score << endl;
#endif
}
// We can align it once per target tree
for (auto& subgraph : trees) {
// For each tree we can map against, map pinning the correct edge of the sequence to the root.
if (subgraph.get_node_count() != 0) {
// This path has bases in it and could potentially be better than
// the default full-length softclip
// Do alignment to the subgraph with GSSWAligner.
Alignment current_alignment;
// If pinning right, we need to reverse the sequence, since we are
// always pinning left to the left edge of the tree subgraph.
current_alignment.set_sequence(pin_left ? sequence : reverse_complement(sequence));
#ifdef debug
cerr << "Align " << pb2json(current_alignment) << " pinned left";
#ifdef debug_dump_graph
cerr << " vs graph:" << endl;
subgraph.for_each_handle([&](const handle_t& here) {
cerr << subgraph.get_id(here) << " (" << subgraph.get_sequence(here) << "): " << endl;
subgraph.follow_edges(here, true, [&](const handle_t& there) {
cerr << "\t" << subgraph.get_id(there) << " (" << subgraph.get_sequence(there) << ") ->" << endl;
});
subgraph.follow_edges(here, false, [&](const handle_t& there) {
cerr << "\t-> " << subgraph.get_id(there) << " (" << subgraph.get_sequence(there) << ")" << endl;
});
});
#else
cerr << endl;
#endif
#endif
// X-drop align, accounting for full length bonus.
// We *always* do left-pinned alignment internally, since that's the shape of trees we get.
get_regular_aligner()->align_pinned(current_alignment, subgraph, true, true);
#ifdef debug
cerr << "\tScore: " << current_alignment.score() << endl;
#endif
if (current_alignment.score() > best_score) {
// This is a new best alignment.
best_path = current_alignment.path();
if (!pin_left) {
// Un-reverse it if we were pinning right
best_path = reverse_complement_path(best_path, [&](id_t node) {
return subgraph.get_length(subgraph.get_handle(node, false));
});
}
// Translate from subgraph into base graph and keep it.
best_path = subgraph.translate_down(best_path);
best_score = current_alignment.score();
#ifdef debug
cerr << "New best alignment is "
<< pb2json(best_path) << " score " << best_score << endl;
#endif
}
}
}
return make_pair(best_path, best_score);
}
vector<TreeSubgraph> MinimizerMapper::get_tail_forest(const GaplessExtension& extended_seed,
size_t read_length, bool left_tails) const {
// We will fill this in with all the trees we return
vector<TreeSubgraph> to_return;
// Now for this extension, walk the GBWT in the appropriate direction
#ifdef debug
cerr << "Look for " << (left_tails ? "left" : "right") << " tails from extension" << endl;
#endif
// TODO: Come up with a better way to do this with more accessors on the extension and less get_handle
// Get the Position reading out of the extension on the appropriate tail
Position from;
// And the length of that tail
size_t tail_length;
// And the GBWT search state we want to start with
const gbwt::SearchState* base_state = nullptr;
if (left_tails) {
// Look right from start
from = extended_seed.starting_position(gbwt_graph);
// And then flip to look the other way at the prev base
from = reverse(from, gbwt_graph.get_length(gbwt_graph.get_handle(from.node_id(), false)));
// Use the search state going backward
base_state = &extended_seed.state.backward;
tail_length = extended_seed.read_interval.first;
} else {
// Look right from end
from = extended_seed.tail_position(gbwt_graph);
// Use the search state going forward
base_state = &extended_seed.state.forward;
tail_length = read_length - extended_seed.read_interval.second;
}
if (tail_length == 0) {
// Don't go looking for places to put no tail.
return to_return;
}
// This is one tree that we are filling in
vector<pair<int64_t, handle_t>> tree;
// This is a stack of indexes at which we put parents in the tree
list<int64_t> parent_stack;
// Get the handle we are starting from
// TODO: is it cheaper to get this out of base_state?
handle_t start_handle = gbwt_graph.get_handle(from.node_id(), from.is_reverse());
// Decide if the start node will end up included in the tree, or if we cut it all off with the offset.
bool start_included = (from.offset() < gbwt_graph.get_length(start_handle));
// How long should we search? It should be the longest detectable gap plus the remaining sequence.
size_t search_limit = get_regular_aligner()->longest_detectable_gap(tail_length, read_length) + tail_length;
// Do a DFS over the haplotypes in the GBWT out to that distance.
dfs_gbwt(*base_state, from.offset(), search_limit, [&](const handle_t& entered) {
// Enter a new handle.
if (parent_stack.empty()) {
// This is the root of a new tree in the forrest
if (!tree.empty()) {
// Save the old tree and start a new one.
// We need to cut off from.offset() from the root, unless we would cut off the whole root.
// In that case, the GBWT DFS will have skipped the empty root entirely, so we cut off nothing.
to_return.emplace_back(&gbwt_graph, std::move(tree), start_included ? from.offset() : 0);
tree.clear();
}
// Add this to the tree with no parent
tree.emplace_back(-1, entered);
} else {
// Just say this is visitable from our parent.
tree.emplace_back(parent_stack.back(), entered);
}
// Record the parent index
parent_stack.push_back(tree.size() - 1);
}, [&]() {
// Exit the last visited handle. Pop off the stack.
parent_stack.pop_back();
});
if (!tree.empty()) {
// Now save the last tree
to_return.emplace_back(&gbwt_graph, std::move(tree), start_included ? from.offset() : 0);
tree.clear();
}
#ifdef debug
cerr << "Found " << to_return.size() << " trees" << endl;
#endif
// Now we have all the trees!
return to_return;
}
size_t MinimizerMapper::immutable_path_from_length(const ImmutablePath& path) {
size_t to_return = 0;
for (auto& m : path) {
// Sum up the from lengths of all the component Mappings
to_return += mapping_from_length(m);
}
return to_return;
}
Path MinimizerMapper::to_path(const ImmutablePath& path) {
Path to_return;
for (auto& m : path) {
// Copy all the Mappings into the Path.
*to_return.add_mapping() = m;
}
// Flip the order around to actual path order.
std::reverse(to_return.mutable_mapping()->begin(), to_return.mutable_mapping()->end());
// Return the completed path
return to_return;
}
void MinimizerMapper::dfs_gbwt(const Position& from, size_t walk_distance,
const function<void(const handle_t&)>& enter_handle, const function<void(void)> exit_handle) const {
// Get a handle to the node the from position is on, in the position's forward orientation
handle_t start_handle = gbwt_graph.get_handle(from.node_id(), from.is_reverse());
// Delegate to the handle-based version
dfs_gbwt(start_handle, from.offset(), walk_distance, enter_handle, exit_handle);
}
void MinimizerMapper::dfs_gbwt(handle_t from_handle, size_t from_offset, size_t walk_distance,
const function<void(const handle_t&)>& enter_handle, const function<void(void)> exit_handle) const {
// Turn from_handle into a SearchState for everything on it.
gbwt::SearchState start_state = gbwt_graph.get_state(from_handle);
// Delegate to the state-based version
dfs_gbwt(start_state, from_offset, walk_distance, enter_handle, exit_handle);
}
void MinimizerMapper::dfs_gbwt(const gbwt::SearchState& start_state, size_t from_offset, size_t walk_distance,
const function<void(const handle_t&)>& enter_handle, const function<void(void)> exit_handle) const {
// Holds the gbwt::SearchState we are at, and the distance we have consumed
using traversal_state_t = pair<gbwt::SearchState, size_t>;
if (start_state.empty()) {
// No haplotypes even visit the first node. Stop.
return;
}
// Get the handle we are starting on
handle_t from_handle = gbwt_graph.node_to_handle(start_state.node);
// The search state represents searching through the end of the node, so we have to consume that much search limit.
// Tack on how much search limit distance we consume by going to the end of
// the node. Our start position is a cut *between* bases, and we take everything after it.
// If the cut is at the offset of the whole length of the node, we take 0 bases.
// If it is at 0, we take all the bases in the node.
size_t distance_to_node_end = gbwt_graph.get_length(from_handle) - from_offset;
#ifdef debug
cerr << "DFS starting at offset " << from_offset << " on node of length "
<< gbwt_graph.get_length(from_handle) << " leaving " << distance_to_node_end << " bp" << endl;
#endif
// Have a recursive function that does the DFS. We fire the enter and exit
// callbacks, and the user can keep their own stack.
function<void(const gbwt::SearchState&, size_t, bool)> recursive_dfs = [&](const gbwt::SearchState& here_state,
size_t used_distance, bool hide_root) {
handle_t here_handle = gbwt_graph.node_to_handle(here_state.node);
if (!hide_root) {
// Enter this handle if there are any bases on it to visit
#ifdef debug
cerr << "Enter handle " << gbwt_graph.get_id(here_handle) << " " << gbwt_graph.get_is_reverse(here_handle) << endl;
#endif
enter_handle(here_handle);
}
// Up the used distance with our length
used_distance += gbwt_graph.get_length(here_handle);
if (used_distance < walk_distance) {
// If we haven't used up all our distance yet
gbwt_graph.follow_paths(here_state, [&](const gbwt::SearchState& there_state) -> bool {
// For each next state
// Otherwise, do it with the new distance value.
// Don't hide the root on any child subtrees; only the top root can need hiding.
recursive_dfs(there_state, used_distance, false);
return true;
});
}
if (!hide_root) {
// Exit this handle if we entered it
#ifdef debug
cerr << "Exit handle " << gbwt_graph.get_id(here_handle) << " " << gbwt_graph.get_is_reverse(here_handle) << endl;
#endif
exit_handle();
}
};
// Start the DFS with our stating node, consuming the distance from our
// offset to its end. Don't show the root state to the user if we don't
// actually visit any bases on that node.
recursive_dfs(start_state, distance_to_node_end, distance_to_node_end == 0);
}
}
|
/***************************************************************************
copyright : (C) 2002 - 2008 by Scott Wheeler
email : wheeler@kde.org
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* 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 *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include "config.h"
#include "tdebug.h"
#include "tstring.h"
#include "tdebuglistener.h"
#include <bitset>
#include <cstdio>
#include <cstdarg>
using namespace TagLib;
namespace
{
String format(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
char buf[256];
#if defined(HAVE_SNPRINTF)
vsnprintf(buf, sizeof(buf), fmt, args);
#elif defined(HAVE_SPRINTF_S)
vsprintf_s(buf, fmt, args);
#else
// Be careful. May cause a buffer overflow.
vsprintf(buf, fmt, args);
#endif
va_end(args);
return String(buf);
}
}
namespace TagLib
{
// The instance is defined in tdebuglistener.cpp.
extern DebugListener *debugListener;
void debug(const String &s)
{
#if !defined(NDEBUG) || defined(TRACE_IN_RELEASE)
debugListener->printMessage("TagLib: " + s + "\n");
#endif
}
void debugData(const ByteVector &v)
{
#if !defined(NDEBUG) || defined(TRACE_IN_RELEASE)
for(size_t i = 0; i < v.size(); ++i)
{
String msg
= format("*** [%d] - char '%c' - int %d, 0x%02x, 0b", i, v[i], v[i], v[i]);
std::bitset<8> b(v[i]);
for(int j = 7; j >= 0; --j)
msg += format("%d", (b.test(j) ? 1 : 0));
msg += "\n";
debugListener->printMessage(msg);
}
#endif
}
}
Making use of std::bitset::to_string()
/***************************************************************************
copyright : (C) 2002 - 2008 by Scott Wheeler
email : wheeler@kde.org
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* 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 *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include "config.h"
#include "tdebug.h"
#include "tstring.h"
#include "tdebuglistener.h"
#include <bitset>
#include <cstdio>
#include <cstdarg>
using namespace TagLib;
namespace
{
String format(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
char buf[256];
#if defined(HAVE_SNPRINTF)
vsnprintf(buf, sizeof(buf), fmt, args);
#elif defined(HAVE_SPRINTF_S)
vsprintf_s(buf, fmt, args);
#else
// Be careful. May cause a buffer overflow.
vsprintf(buf, fmt, args);
#endif
va_end(args);
return String(buf);
}
}
namespace TagLib
{
// The instance is defined in tdebuglistener.cpp.
extern DebugListener *debugListener;
void debug(const String &s)
{
#if !defined(NDEBUG) || defined(TRACE_IN_RELEASE)
debugListener->printMessage("TagLib: " + s + "\n");
#endif
}
void debugData(const ByteVector &v)
{
#if !defined(NDEBUG) || defined(TRACE_IN_RELEASE)
for(size_t i = 0; i < v.size(); ++i)
{
std::string bits = std::bitset<8>(v[i]).to_string();
String msg = format("*** [%d] - char '%c' - int %d, 0x%02x, 0b%s\n",
i, v[i], v[i], v[i], bits.c_str());
debugListener->printMessage(msg);
}
#endif
}
}
|
/**
* \file minimizer_mapper.cpp
* Defines the code for the minimizer-and-GBWT-based mapper.
*/
#include "minimizer_mapper.hpp"
#include "annotation.hpp"
#include "path_subgraph.hpp"
#include "multipath_alignment.hpp"
#include "split_strand_graph.hpp"
#include "algorithms/dagify.hpp"
#include "algorithms/dijkstra.hpp"
#include <bdsg/overlays/strand_split_overlay.hpp>
#include <gbwtgraph/algorithms.h>
#include <gbwtgraph/cached_gbwtgraph.h>
#include <iostream>
#include <algorithm>
#include <cmath>
//#define debug
#define print_minimizers
namespace vg {
using namespace std;
MinimizerMapper::MinimizerMapper(const gbwtgraph::GBWTGraph& graph,
const std::vector<gbwtgraph::DefaultMinimizerIndex*>& minimizer_indexes,
MinimumDistanceIndex& distance_index, const PathPositionHandleGraph* path_graph) :
path_graph(path_graph), minimizer_indexes(minimizer_indexes),
distance_index(distance_index), gbwt_graph(graph),
extender(gbwt_graph, *(get_regular_aligner())), clusterer(distance_index),
fragment_length_distr(1000,1000,0.95) {
}
//-----------------------------------------------------------------------------
void MinimizerMapper::map(Alignment& aln, AlignmentEmitter& alignment_emitter) {
// Ship out all the aligned alignments
alignment_emitter.emit_mapped_single(map(aln));
}
vector<Alignment> MinimizerMapper::map(Alignment& aln) {
#ifdef debug
cerr << "Read " << aln.name() << ": " << aln.sequence() << endl;
#endif
#ifdef print_minimizers
cerr << aln.sequence() << "\t";
for (char c : aln.quality()) {
cerr << (char)(c+33);
}
#endif
// Make a new funnel instrumenter to watch us map this read.
Funnel funnel;
funnel.start(aln.name());
// Minimizers sorted by score in descending order.
std::vector<Minimizer> minimizers = this->find_minimizers(aln.sequence(), funnel);
// Find the seeds and mark the minimizers that were located.
std::vector<Seed> seeds = this->find_seeds(minimizers, aln, funnel);
// Cluster the seeds. Get sets of input seed indexes that go together.
if (track_provenance) {
funnel.stage("cluster");
}
std::vector<Cluster> clusters = clusterer.cluster_seeds(seeds, get_distance_limit(aln.sequence().size()));
// Determine the scores and read coverages for each cluster.
// Also find the best and second-best cluster scores.
if (this->track_provenance) {
funnel.substage("score");
}
double best_cluster_score = 0.0, second_best_cluster_score = 0.0;
for (size_t i = 0; i < clusters.size(); i++) {
Cluster& cluster = clusters[i];
this->score_cluster(cluster, i, minimizers, seeds, aln.sequence().length(), funnel);
if (cluster.score > best_cluster_score) {
second_best_cluster_score = best_cluster_score;
best_cluster_score = cluster.score;
} else if (cluster.score > second_best_cluster_score) {
second_best_cluster_score = cluster.score;
}
}
#ifdef debug
cerr << "Found " << clusters.size() << " clusters" << endl;
#endif
#ifdef print_minimizers
cerr << "\t" << clusters.size();
#endif
// We will set a score cutoff based on the best, but move it down to the
// second best if it does not include the second best and the second best
// is within pad_cluster_score_threshold of where the cutoff would
// otherwise be. This ensures that we won't throw away all but one cluster
// based on score alone, unless it is really bad.
double cluster_score_cutoff = best_cluster_score - cluster_score_threshold;
if (cluster_score_cutoff - pad_cluster_score_threshold < second_best_cluster_score) {
cluster_score_cutoff = std::min(cluster_score_cutoff, second_best_cluster_score);
}
if (track_provenance) {
// Now we go from clusters to gapless extensions
funnel.stage("extend");
}
// These are the GaplessExtensions for all the clusters.
vector<vector<GaplessExtension>> cluster_extensions;
cluster_extensions.reserve(clusters.size());
// To compute the windows for explored minimizers, we need to get
// all the minimizers that are explored.
SmallBitset minimizer_explored(minimizers.size());
//How many hits of each minimizer ended up in each extended cluster?
vector<vector<size_t>> minimizer_extended_cluster_count;
//For each cluster, what fraction of "equivalent" clusters did we keep?
vector<double> probability_cluster_lost;
//What is the score and coverage we are considering and how many reads
size_t curr_coverage = 0;
size_t curr_score = 0;
size_t curr_kept = 0;
size_t curr_count = 0;
// We track unextended clusters.
vector<size_t> unextended_clusters;
unextended_clusters.reserve(clusters.size());
//Process clusters sorted by both score and read coverage
process_until_threshold_c<Cluster, double>(clusters, [&](size_t i) -> double {
return clusters[i].coverage;
}, [&](size_t a, size_t b) -> bool {
return ((clusters[a].coverage > clusters[b].coverage) ||
(clusters[a].coverage == clusters[b].coverage && clusters[a].score > clusters[b].score));
},
cluster_coverage_threshold, 1, max_extensions,
[&](size_t cluster_num) {
// Handle sufficiently good clusters in descending coverage order
Cluster& cluster = clusters[cluster_num];
if (track_provenance) {
funnel.pass("cluster-coverage", cluster_num, cluster.coverage);
funnel.pass("max-extensions", cluster_num);
}
// First check against the additional score filter
if (cluster_score_threshold != 0 && cluster.score < cluster_score_cutoff) {
//If the score isn't good enough, ignore this cluster
if (track_provenance) {
funnel.fail("cluster-score", cluster_num, cluster.score);
}
// Record MAPQ implications of not extending this cluster.
unextended_clusters.push_back(cluster_num);
#ifdef debug
cerr << "Cluster " << cluster_num << " fails cluster score cutoff" << endl;
cerr << "Covers " << clusters[cluster_num].coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << clusters[cluster_num].score << "/" << cluster_score_cutoff << endl;
#endif
return false;
}
if (track_provenance) {
funnel.pass("cluster-score", cluster_num, cluster.score);
funnel.processing_input(cluster_num);
}
if (cluster.coverage == curr_coverage &&
cluster.score == curr_score &&
curr_kept < max_extensions * 0.75) {
curr_kept++;
curr_count++;
} else if (cluster.coverage != curr_coverage ||
cluster.score != curr_score) {
//If this is a cluster that has scores different than the previous one
for (size_t i = 0 ; i < curr_kept ; i++ ) {
probability_cluster_lost.push_back(1.0 - (double(curr_kept) / double(curr_count)));
}
curr_coverage = cluster.coverage;
curr_score = cluster.score;
curr_kept = 1;
curr_count = 1;
} else {
//If this cluster is equivalent to the previous one and we already took enough
//equivalent clusters
curr_count ++;
// TODO: shouldn't we fail something for the funnel here?
// Record MAPQ implications of not extending this cluster.
unextended_clusters.push_back(cluster_num);
#ifdef debug
cerr << "Cluster " << cluster_num << " fails because we took too many identical clusters" << endl;
cerr << "Covers " << clusters[cluster_num].coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << clusters[cluster_num].score << "/" << cluster_score_cutoff << endl;
#endif
return false;
}
//Only keep this cluster if we have few enough equivalent clusters
#ifdef debug
cerr << "Cluster " << cluster_num << endl;
cerr << "Covers " << cluster.coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << cluster.score << "/" << cluster_score_cutoff << endl;
#endif
minimizer_extended_cluster_count.emplace_back(minimizers.size(), 0);
// Pack the seeds for GaplessExtender.
GaplessExtender::cluster_type seed_matchings;
for (auto seed_index : cluster.seeds) {
// Insert the (graph position, read offset) pair.
const Seed& seed = seeds[seed_index];
seed_matchings.insert(GaplessExtender::to_seed(seed.pos, minimizers[seed.source].value.offset));
minimizer_extended_cluster_count.back()[seed.source]++;
#ifdef debug
const Minimizer& minimizer = minimizers[seed.source];
cerr << "Seed read:" << minimizer.value.offset << " = " << seed.pos
<< " from minimizer " << seed.source << "(" << minimizer.hits << ")" << endl;
#endif
}
// Extend seed hits in the cluster into one or more gapless extensions
cluster_extensions.emplace_back(std::move(extender.extend(seed_matchings, aln.sequence())));
if (track_provenance) {
// Record with the funnel that the previous group became a group of this size.
// Don't bother recording the seed to extension matching...
funnel.project_group(cluster_num, cluster_extensions.back().size());
// Say we finished with this cluster, for now.
funnel.processed_input();
}
return true;
}, [&](size_t cluster_num) {
// There are too many sufficiently good clusters
Cluster& cluster = clusters[cluster_num];
if (track_provenance) {
funnel.pass("cluster-coverage", cluster_num, cluster.coverage);
funnel.fail("max-extensions", cluster_num);
}
if (cluster.coverage == curr_coverage &&
cluster.score == curr_score) {
curr_count ++;
} else {
for (size_t i = 0 ; i < curr_kept ; i++ ) {
probability_cluster_lost.push_back(1.0 - (double(curr_kept) / double(curr_count)));
}
curr_score = 0;
curr_coverage = 0;
curr_kept = 0;
curr_count = 0;
}
// Record MAPQ implications of not extending this cluster.
unextended_clusters.push_back(cluster_num);
#ifdef debug
cerr << "Cluster " << cluster_num << " passes cluster cutoffs but we have too many" << endl;
cerr << "Covers " << cluster.coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << cluster.score << "/" << cluster_score_cutoff << endl;
#endif
}, [&](size_t cluster_num) {
// This cluster is not sufficiently good.
if (track_provenance) {
funnel.fail("cluster-coverage", cluster_num, clusters[cluster_num].coverage);
}
for (size_t i = 0 ; i < curr_kept ; i++ ) {
probability_cluster_lost.push_back(1.0 - (double(curr_kept) / double(curr_count)));
}
curr_kept = 0;
curr_count = 0;
curr_score = 0;
curr_coverage = 0;
// Record MAPQ implications of not extending this cluster.
unextended_clusters.push_back(cluster_num);
#ifdef debug
cerr << "Cluster " << cluster_num << " fails cluster coverage cutoffs" << endl;
cerr << "Covers " << clusters[cluster_num].coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << clusters[cluster_num].score << "/" << cluster_score_cutoff << endl;
#endif
});
for (size_t i = 0 ; i < curr_kept ; i++ ) {
probability_cluster_lost.push_back(1.0 - (double(curr_kept) / double(curr_count)));
}
std::vector<int> cluster_extension_scores = this->score_extensions(cluster_extensions, aln, funnel);
if (track_provenance) {
funnel.stage("align");
}
//How many of each minimizer ends up in an extension set that actually gets turned into an alignment?
vector<size_t> minimizer_extensions_count(minimizers.size(), 0);
// Now start the alignment step. Everything has to become an alignment.
// We will fill this with all computed alignments in estimated score order.
vector<Alignment> alignments;
alignments.reserve(cluster_extensions.size());
// This maps from alignment index back to cluster extension index, for
// tracing back to minimizers for MAPQ. Can hold
// numeric_limits<size_t>::max() for an unaligned alignment.
vector<size_t> alignments_to_source;
alignments_to_source.reserve(cluster_extensions.size());
//probability_cluster_lost but ordered by alignment
vector<double> probability_alignment_lost;
probability_alignment_lost.reserve(cluster_extensions.size());
// Create a new alignment object to get rid of old annotations.
{
Alignment temp;
temp.set_sequence(aln.sequence());
temp.set_name(aln.name());
temp.set_quality(aln.quality());
aln = std::move(temp);
}
// Annotate the read with metadata
if (!sample_name.empty()) {
aln.set_sample_name(sample_name);
}
if (!read_group.empty()) {
aln.set_read_group(read_group);
}
// Go through the gapless extension groups in score order.
process_until_threshold_b(cluster_extensions, cluster_extension_scores,
extension_set_score_threshold, 2, max_alignments,
[&](size_t extension_num) {
// This extension set is good enough.
// Called in descending score order.
if (track_provenance) {
funnel.pass("extension-set", extension_num, cluster_extension_scores[extension_num]);
funnel.pass("max-alignments", extension_num);
funnel.processing_input(extension_num);
}
auto& extensions = cluster_extensions[extension_num];
// Get an Alignments best_ and second_best_alignment of it somehow, and throw it in.
Alignment best_alignment = aln;
Alignment second_best_alignment = aln;
// Determine if we got full-length alignments or local alignments.
bool full_length_extensions = (extensions.size() <= 2);
for (auto& extension : extensions) {
full_length_extensions &= extension.full();
}
if (full_length_extensions) {
// We got full-length extensions, so directly convert to an Alignment.
if (track_provenance) {
funnel.substage("direct");
}
//Fill in the best alignments from the extension
this->extension_to_alignment(extensions.front(), best_alignment);
if (extensions.size() > 1) {
//Do the same thing for the second extension, if one exists
this->extension_to_alignment(extensions.back(), second_best_alignment);
}
if (track_provenance) {
// Stop the current substage
funnel.substage_stop();
}
} else if (do_dp) {
// We need to do chaining.
if (track_provenance) {
funnel.substage("chain");
}
// Do the DP and compute alignment into best_alignment and
// second_best_extension, if there is a second best
find_optimal_tail_alignments(aln, extensions, best_alignment, second_best_alignment);
if (track_provenance) {
// We're done chaining. Next alignment may not go through this substage.
funnel.substage_stop();
}
} else {
// We would do chaining but it is disabled.
// Leave best_alignment unaligned
}
if (second_best_alignment.score() != 0 &&
second_best_alignment.score() > best_alignment.score() * 0.8) {
//If there is a second extension and its score is at least half of the best score, bring it along
#ifdef debug
cerr << "Found second best alignment from gapless extension " << extension_num << ": " << pb2json(second_best_alignment) << endl;
#endif
alignments.emplace_back(std::move(second_best_alignment));
alignments_to_source.push_back(extension_num);
probability_alignment_lost.push_back(probability_cluster_lost[extension_num]);
if (track_provenance) {
funnel.project(extension_num);
funnel.score(alignments.size() - 1, alignments.back().score());
// We're done with this input item
funnel.processed_input();
}
}
#ifdef debug
cerr << "Found best alignment from gapless extension " << extension_num << ": " << pb2json(best_alignment) << endl;
#endif
alignments.push_back(std::move(best_alignment));
alignments_to_source.push_back(extension_num);
probability_alignment_lost.push_back(probability_cluster_lost[extension_num]);
if (track_provenance) {
funnel.project(extension_num);
funnel.score(alignments.size() - 1, alignments.back().score());
// We're done with this input item
funnel.processed_input();
}
for (size_t i = 0 ; i < minimizer_extended_cluster_count[extension_num].size() ; i++) {
minimizer_extensions_count[i] += minimizer_extended_cluster_count[extension_num][i];
if (minimizer_extended_cluster_count[extension_num][i] > 0) {
// This minimizer is in an extended cluster that gave rise
// to at least one alignment, so it is explored.
minimizer_explored.insert(i);
}
}
return true;
}, [&](size_t extension_num) {
// There are too many sufficiently good extensions
if (track_provenance) {
funnel.pass("extension-set", extension_num, cluster_extension_scores[extension_num]);
funnel.fail("max-alignments", extension_num);
}
#ifdef debug
cerr << "gapless extension " << extension_num << " failed because there were too many good extensions" << endl;
#endif
}, [&](size_t extension_num) {
// This extension is not good enough.
if (track_provenance) {
funnel.fail("extension-set", extension_num, cluster_extension_scores[extension_num]);
}
#ifdef debug
cerr << "gapless extension " << extension_num << " failed because its score was not good enough (score=" << cluster_extension_scores[extension_num] << ")" << endl;
#endif
});
if (alignments.size() == 0) {
// Produce an unaligned Alignment
alignments.emplace_back(aln);
alignments_to_source.push_back(numeric_limits<size_t>::max());
probability_alignment_lost.push_back(0);
if (track_provenance) {
// Say it came from nowhere
funnel.introduce();
}
}
if (track_provenance) {
// Now say we are finding the winner(s)
funnel.stage("winner");
}
// Fill this in with the alignments we will output as mappings
vector<Alignment> mappings;
mappings.reserve(min(alignments.size(), max_multimaps));
// Track which Alignments they are
vector<size_t> mappings_to_source;
mappings_to_source.reserve(min(alignments.size(), max_multimaps));
// Grab all the scores in order for MAPQ computation.
vector<double> scores;
scores.reserve(alignments.size());
vector<double> probability_mapping_lost;
process_until_threshold_a(alignments, (std::function<double(size_t)>) [&](size_t i) -> double {
return alignments.at(i).score();
}, 0, 1, max_multimaps, [&](size_t alignment_num) {
// This alignment makes it
// Called in score order
// Remember the score at its rank
scores.emplace_back(alignments[alignment_num].score());
// Remember the output alignment
mappings.emplace_back(std::move(alignments[alignment_num]));
mappings_to_source.push_back(alignment_num);
probability_mapping_lost.push_back(probability_alignment_lost[alignment_num]);
if (track_provenance) {
// Tell the funnel
funnel.pass("max-multimaps", alignment_num);
funnel.project(alignment_num);
funnel.score(alignment_num, scores.back());
}
return true;
}, [&](size_t alignment_num) {
// We already have enough alignments, although this one has a good score
// Remember the score at its rank anyway
scores.emplace_back(alignments[alignment_num].score());
if (track_provenance) {
funnel.fail("max-multimaps", alignment_num);
}
}, [&](size_t alignment_num) {
// This alignment does not have a sufficiently good score
// Score threshold is 0; this should never happen
assert(false);
});
if (track_provenance) {
funnel.substage("mapq");
}
#ifdef debug
cerr << "Picked best alignment " << pb2json(mappings[0]) << endl;
cerr << "For scores ";
for (auto& score : scores) cerr << score << " ";
#endif
size_t winning_index;
assert(!mappings.empty());
// Compute MAPQ if not unmapped. Otherwise use 0 instead of the 50% this would give us.
double mapq = (mappings.front().path().mapping_size() == 0) ? 0 :
get_regular_aligner()->maximum_mapping_quality_exact(scores, &winning_index) / 2;
#ifdef print_minimizers
double uncapped_mapq = mapq;
#endif
#ifdef debug
cerr << "uncapped MAPQ is " << mapq << endl;
#endif
if (probability_mapping_lost.front() > 0) {
mapq = min(mapq,round(prob_to_phred(probability_mapping_lost.front())));
}
// TODO: give SmallBitset iterators so we can use it instead of an index vector.
vector<size_t> explored_minimizers;
for (size_t i = 0; i < minimizers.size(); i++) {
if (minimizer_explored.contains(i)) {
explored_minimizers.push_back(i);
}
}
// Compute caps on MAPQ. TODO: avoid needing to pass as much stuff along.
double mapq_explored_cap = 2 * faster_cap(minimizers, explored_minimizers, aln.sequence(), aln.quality());
// Remember the uncapped MAPQ and the caps
set_annotation(mappings.front(), "mapq_uncapped", mapq);
set_annotation(mappings.front(), "mapq_explored_cap", mapq_explored_cap);
// Apply the caps and transformations
mapq = round(0.85 * min(mapq_explored_cap, min(mapq, 70.0)));
#ifdef debug
cerr << "Explored cap is " << mapq_explored_cap << endl;
cerr << "MAPQ is " << mapq << endl;
#endif
// Make sure to clamp 0-60.
mappings.front().set_mapping_quality(max(min(mapq, 60.0), 0.0));
if (track_provenance) {
funnel.substage_stop();
}
for (size_t i = 0; i < mappings.size(); i++) {
// For each output alignment in score order
auto& out = mappings[i];
// Assign primary and secondary status
out.set_is_secondary(i > 0);
}
// Stop this alignment
funnel.stop();
if (track_provenance) {
// Annotate with the number of results in play at each stage
funnel.for_each_stage([&](const string& stage, const vector<size_t>& result_sizes) {
// Save the number of items
set_annotation(mappings[0], "stage_" + stage + "_results", (double)result_sizes.size());
});
if (track_correctness) {
// And with the last stage at which we had any descendants of the correct seed hit locations
set_annotation(mappings[0], "last_correct_stage", funnel.last_correct_stage());
}
// Annotate with the performances of all the filters
// We need to track filter number
size_t filter_num = 0;
funnel.for_each_filter([&](const string& stage, const string& filter,
const Funnel::FilterPerformance& by_count, const Funnel::FilterPerformance& by_size,
const vector<double>& filter_statistics_correct, const vector<double>& filter_statistics_non_correct) {
string filter_id = to_string(filter_num) + "_" + filter + "_" + stage;
// Save the stats
set_annotation(mappings[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(mappings[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(mappings[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(mappings[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(mappings[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(mappings[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(mappings[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(mappings[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(mappings[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(mappings[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
filter_num++;
});
// Annotate with parameters used for the filters.
set_annotation(mappings[0], "param_hit-cap", (double) hit_cap);
set_annotation(mappings[0], "param_hard-hit-cap", (double) hard_hit_cap);
set_annotation(mappings[0], "param_score-fraction", (double) minimizer_score_fraction);
set_annotation(mappings[0], "param_max-extensions", (double) max_extensions);
set_annotation(mappings[0], "param_max-alignments", (double) max_alignments);
set_annotation(mappings[0], "param_cluster-score", (double) cluster_score_threshold);
set_annotation(mappings[0], "param_cluster-coverage", (double) cluster_coverage_threshold);
set_annotation(mappings[0], "param_extension-set", (double) extension_set_score_threshold);
set_annotation(mappings[0], "param_max-multimaps", (double) max_multimaps);
}
#ifdef print_minimizers
for (size_t i = 0 ; i < minimizers.size() ; i++) {
auto& minimizer = minimizers[i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_extensions_count[i];
if (minimizer_extensions_count[i]>0) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << uncapped_mapq << "\t" << mapq_explored_cap << "\t" << probability_mapping_lost.front();
if (track_correctness) {
cerr << "\t" << funnel.last_correct_stage() << endl;
} else {
cerr << endl;
}
#endif
#ifdef debug
// Dump the funnel info graph.
funnel.to_dot(cerr);
#endif
return mappings;
}
//-----------------------------------------------------------------------------
pair<vector<Alignment>, vector<Alignment>> MinimizerMapper::map_paired(Alignment& aln1, Alignment& aln2,
vector<pair<Alignment, Alignment>>& ambiguous_pair_buffer){
if (fragment_length_distr.is_finalized()) {
//If we know the fragment length distribution then we just map paired ended
return map_paired(aln1, aln2);
} else {
//If we don't know the fragment length distribution, map the reads single ended
vector<Alignment> alns1(map(aln1));
vector<Alignment> alns2(map(aln2));
// Check if the separately-mapped ends are both sufficiently perfect and sufficiently unique
int32_t max_score_aln_1 = get_regular_aligner()->score_exact_match(aln1, 0, aln1.sequence().size());
int32_t max_score_aln_2 = get_regular_aligner()->score_exact_match(aln2, 0, aln2.sequence().size());
if (!alns1.empty() && ! alns2.empty() &&
alns1.front().mapping_quality() == 60 && alns2.front().mapping_quality() == 60 &&
alns1.front().score() >= max_score_aln_1 * 0.85 && alns2.front().score() >= max_score_aln_2 * 0.85) {
//Flip the second alignment to get the proper fragment distance
reverse_complement_alignment_in_place(&alns2.front(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
int64_t dist = distance_between(alns1.front(), alns2.front());
// And that they have an actual pair distance and set of relative orientations
if (dist == std::numeric_limits<int64_t>::max()) {
//If the distance between them is ambiguous, leave them unmapped
ambiguous_pair_buffer.emplace_back(aln1, aln2);
pair<vector<Alignment>, vector<Alignment>> empty;
return empty;
}
//If we're keeping this alignment, flip the second alignment back
reverse_complement_alignment_in_place(&alns2.front(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
// If that all checks out, say they're mapped, emit them, and register their distance and orientations
fragment_length_distr.register_fragment_length(dist);
pair<vector<Alignment>, vector<Alignment>> mapped_pair;
mapped_pair.first.emplace_back(alns1.front());
mapped_pair.second.emplace_back(alns2.front());
return mapped_pair;
} else {
// Otherwise, discard the mappings and put them in the ambiguous buffer
ambiguous_pair_buffer.emplace_back(aln1, aln2);
pair<vector<Alignment>, vector<Alignment>> empty;
return empty;
}
}
}
pair<vector<Alignment>, vector< Alignment>> MinimizerMapper::map_paired(Alignment& aln1, Alignment& aln2) {
// For each input alignment
#ifdef debug
cerr << "Read pair " << aln1.name() << ": " << aln1.sequence() << " and " << aln2.name() << ": " << aln2.sequence() << endl;
#endif
// Assume reads are in inward orientations on input, and
// convert to rightward orientations before mapping
// and flip the second read back before output
aln2.clear_path();
reverse_complement_alignment_in_place(&aln2, [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
// Make two new funnel instrumenters to watch us map this read pair.
vector<Funnel> funnels;
funnels.resize(2);
// Start this alignment
funnels[0].start(aln1.name());
funnels[1].start(aln2.name());
// Annotate the original read with metadata
if (!sample_name.empty()) {
aln1.set_sample_name(sample_name);
aln2.set_sample_name(sample_name);
}
if (!read_group.empty()) {
aln1.set_read_group(read_group);
aln2.set_read_group(read_group);
}
// Minimizers for both reads, sorted by score in descending order.
std::vector<std::vector<Minimizer>> minimizers_by_read(2);
minimizers_by_read[0] = this->find_minimizers(aln1.sequence(), funnels[0]);
minimizers_by_read[1] = this->find_minimizers(aln2.sequence(), funnels[1]);
// Seeds for both reads, stored in separate vectors.
std::vector<std::vector<Seed>> seeds_by_read(2);
seeds_by_read[0] = this->find_seeds(minimizers_by_read[0], aln1, funnels[0]);
seeds_by_read[1] = this->find_seeds(minimizers_by_read[1], aln2, funnels[1]);
// Cluster the seeds. Get sets of input seed indexes that go together.
// If the fragment length distribution hasn't been fixed yet (if the expected fragment length = 0),
// then everything will be in the same cluster and the best pair will be the two best independent mappings
if (track_provenance) {
funnels[0].stage("cluster");
funnels[1].stage("cluster");
}
std::vector<std::vector<Cluster>> all_clusters = clusterer.cluster_seeds(seeds_by_read, get_distance_limit(aln1.sequence().size()),
fragment_length_distr.mean() + paired_distance_stdevs * fragment_length_distr.std_dev());
//For each fragment cluster, determine if it has clusters from both reads
size_t max_fragment_num = 0;
for (auto& cluster : all_clusters[0]) {
max_fragment_num = std::max(max_fragment_num, cluster.fragment);
}
for (auto& cluster : all_clusters[1]) {
max_fragment_num = std::max(max_fragment_num, cluster.fragment);
}
#ifdef debug
cerr << "Found " << max_fragment_num << " fragment clusters" << endl;
#endif
vector<bool> has_first_read (max_fragment_num+1, false);//For each fragment cluster, does it have a cluster for the first read
vector<bool> fragment_cluster_has_pair (max_fragment_num+1, false);//Does a fragment cluster have both reads
bool found_paired_cluster = false;
for (auto& cluster : all_clusters[0]) {
size_t fragment_num = cluster.fragment;
has_first_read[fragment_num] = true;
}
for (auto& cluster : all_clusters[1]) {
size_t fragment_num = cluster.fragment;
fragment_cluster_has_pair[fragment_num] = has_first_read[fragment_num];
if (has_first_read[fragment_num]) {
found_paired_cluster = true;
#ifdef debug
cerr << "Fragment cluster " << fragment_num << " has read clusters from both reads" << endl;
#endif
}
}
if (track_provenance) {
funnels[0].substage("score");
funnels[1].substage("score");
}
//For each fragment cluster (cluster of clusters), for each read, a vector of all alignments + the order they were fed into the funnel
//so the funnel can track them
vector<pair<vector<Alignment>, vector<Alignment>>> alignments;
vector<pair<vector<size_t>, vector<size_t>>> alignment_indices;
pair<int, int> best_alignment_scores (0, 0); // The best alignment score for each end
//Keep track of the best cluster score and coverage per end for each fragment cluster
pair<vector<double>, vector<double>> cluster_score_by_fragment;
cluster_score_by_fragment.first.resize(max_fragment_num + 1, 0.0);
cluster_score_by_fragment.second.resize(max_fragment_num + 1, 0.0);
pair<vector<double>, vector<double>> cluster_coverage_by_fragment;
cluster_coverage_by_fragment.first.resize(max_fragment_num + 1, 0.0);
cluster_coverage_by_fragment.second.resize(max_fragment_num + 1, 0.0);
for (size_t read_num = 0 ; read_num < 2 ; read_num++) {
Alignment& aln = read_num == 0 ? aln1 : aln2;
std::vector<Cluster>& clusters = all_clusters[read_num];
std::vector<Minimizer>& minimizers = minimizers_by_read[read_num];
std::vector<Seed>& seeds = seeds_by_read[read_num];
vector<double>& best_cluster_score = read_num == 0 ? cluster_score_by_fragment.first : cluster_score_by_fragment.second;
vector<double>& best_cluster_coverage = read_num == 0 ? cluster_coverage_by_fragment.first : cluster_coverage_by_fragment.second;
for (size_t i = 0; i < clusters.size(); i++) {
// Deterimine cluster score and read coverage.
Cluster& cluster = clusters[i];
this->score_cluster(cluster, i, minimizers, seeds, aln.sequence().length(), funnels[read_num]);
size_t fragment = cluster.fragment;
best_cluster_score[fragment] = std::max(best_cluster_score[fragment], cluster.score);
best_cluster_coverage[fragment] = std::max(best_cluster_coverage[fragment], cluster.coverage);
}
}
//For each fragment cluster, we want to know how many equivalent or better clusters we found
vector<size_t> fragment_cluster_indices_by_score (max_fragment_num + 1);
for (size_t i = 0 ; i < fragment_cluster_indices_by_score.size() ; i++) {
fragment_cluster_indices_by_score[i] = i;
}
std::sort(fragment_cluster_indices_by_score.begin(), fragment_cluster_indices_by_score.end(), [&](size_t a, size_t b) {
return cluster_coverage_by_fragment.first[a] + cluster_coverage_by_fragment.second[a] + cluster_score_by_fragment.first[a] + cluster_score_by_fragment.second[a]
> cluster_coverage_by_fragment.first[b] + cluster_coverage_by_fragment.second[b] + cluster_score_by_fragment.first[b] + cluster_score_by_fragment.second[b];
});
vector<size_t> better_cluster_count (max_fragment_num+1); // How many fragment clusters are at least as good as the one at each index
for (int j = fragment_cluster_indices_by_score.size() - 1 ; j >= 0 ; j--) {
size_t i = fragment_cluster_indices_by_score[j];
if (j == fragment_cluster_indices_by_score.size()-1) {
better_cluster_count[i] = j;
} else {
size_t i2 = fragment_cluster_indices_by_score[j+1];
if(cluster_coverage_by_fragment.first[i] + cluster_coverage_by_fragment.second[i] + cluster_score_by_fragment.first[i] + cluster_score_by_fragment.second[i]
== cluster_coverage_by_fragment.first[i2] + cluster_coverage_by_fragment.second[i2] + cluster_score_by_fragment.first[i2] + cluster_score_by_fragment.second[i2]) {
better_cluster_count[i] = better_cluster_count[i2];
} else {
better_cluster_count[i] = j;
}
}
}
// We track unextended clusters.
vector<vector<size_t>> unextended_clusters_by_read(2);
// To compute the windows that are explored, we need to get
// all the minimizers that are explored.
vector<SmallBitset> minimizer_explored_by_read(2);
//How many hits of each minimizer ended up in each extended cluster?
vector<vector<vector<size_t>>> minimizer_extended_cluster_count_by_read(2);
//Now that we've scored each of the clusters, extend and align them
for (size_t read_num = 0 ; read_num < 2 ; read_num++) {
Alignment& aln = read_num == 0 ? aln1 : aln2;
std::vector<Cluster>& clusters = all_clusters[read_num];
std::vector<Minimizer>& minimizers = minimizers_by_read[read_num];
std::vector<Seed>& seeds = seeds_by_read[read_num];
#ifdef debug
cerr << "Found " << clusters.size() << " clusters for read " << read_num << endl;
#endif
// Retain clusters only if their score is better than this, in addition to the coverage cutoff
double cluster_score_cutoff = 0.0, cluster_coverage_cutoff = 0.0;
for (auto& cluster : clusters) {
cluster_score_cutoff = std::max(cluster_score_cutoff, cluster.score);
cluster_coverage_cutoff = std::max(cluster_coverage_cutoff, cluster.coverage);
}
cluster_score_cutoff -= cluster_score_threshold;
cluster_coverage_cutoff -= cluster_coverage_threshold;
if (track_provenance) {
// Now we go from clusters to gapless extensions
funnels[read_num].stage("extend");
}
// These are the GaplessExtensions for all the clusters (and fragment cluster assignments), in cluster_indexes_in_order order.
vector<pair<vector<GaplessExtension>, size_t>> cluster_extensions;
cluster_extensions.reserve(clusters.size());
//TODO: Maybe put this back
//For each cluster, what fraction of "equivalent" clusters did we keep?
//vector<vector<double>> probability_cluster_lost;
//What is the score and coverage we are considering and how many reads
//size_t curr_coverage = 0;
//size_t curr_score = 0;
//size_t curr_kept = 0;
//size_t curr_count = 0;
unextended_clusters_by_read[read_num].reserve(clusters.size());
minimizer_explored_by_read[read_num] = SmallBitset(minimizers.size());
//Process clusters sorted by both score and read coverage
process_until_threshold_c<Cluster, double>(clusters, [&](size_t i) -> double {
return clusters[i].coverage;
}, [&](size_t a, size_t b) -> bool {
//Sort clusters first by whether it was paired, then by the best coverage and score of any pair in the fragment cluster,
//then by its coverage and score
size_t fragment_a = clusters[a].fragment;
size_t fragment_b = clusters[b].fragment;
double coverage_a = cluster_coverage_by_fragment.first[fragment_a]+cluster_coverage_by_fragment.second[fragment_a];
double coverage_b = cluster_coverage_by_fragment.first[fragment_b]+cluster_coverage_by_fragment.second[fragment_b];
double score_a = cluster_score_by_fragment.first[fragment_a]+cluster_score_by_fragment.second[fragment_a];
double score_b = cluster_score_by_fragment.first[fragment_b]+cluster_score_by_fragment.second[fragment_b];
if (fragment_cluster_has_pair[fragment_a] != fragment_cluster_has_pair[fragment_b]) {
return fragment_cluster_has_pair[fragment_a];
} else if (coverage_a != coverage_b){
return coverage_a > coverage_b;
} else if (score_a != score_b) {
return score_a > score_b;
} else if (clusters[a].coverage != clusters[b].coverage){
return clusters[a].coverage > clusters[b].coverage;
} else {
return clusters[a].score > clusters[b].score;
}
},
0, 1, max_extensions,
[&](size_t cluster_num) {
// Handle sufficiently good clusters
Cluster& cluster = clusters[cluster_num];
if (!found_paired_cluster || fragment_cluster_has_pair[cluster.fragment] ||
(cluster.coverage == cluster_coverage_cutoff + cluster_coverage_threshold &&
cluster.score == cluster_score_cutoff + cluster_score_threshold)) {
//If this cluster has a pair or if we aren't looking at pairs
//Or if it is the best cluster
// First check against the additional score filter
if (cluster_coverage_threshold != 0 && cluster.coverage < cluster_coverage_cutoff) {
//If the score isn't good enough, ignore this cluster
if (track_provenance) {
funnels[read_num].fail("cluster-coverage", cluster_num, cluster.coverage);
}
unextended_clusters_by_read[read_num].push_back(cluster_num);
return false;
}
if (cluster_score_threshold != 0 && cluster.score < cluster_score_cutoff) {
//If the score isn't good enough, ignore this cluster
if (track_provenance) {
funnels[read_num].pass("cluster-coverage", cluster_num, cluster.coverage);
funnels[read_num].pass("max-extensions", cluster_num);
funnels[read_num].fail("cluster-score", cluster_num, cluster.score);
}
unextended_clusters_by_read[read_num].push_back(cluster_num);
return false;
}
if (track_provenance) {
funnels[read_num].pass("cluster-coverage", cluster_num, cluster.coverage);
funnels[read_num].pass("max-extensions", cluster_num);
funnels[read_num].pass("cluster-score", cluster_num, cluster.score);
funnels[read_num].pass("paired-clusters", cluster_num);
funnels[read_num].processing_input(cluster_num);
}
#ifdef debug
cerr << "Cluster " << cluster_num << endl;
#endif
//Count how many of each minimizer is in each cluster extension
minimizer_extended_cluster_count_by_read[read_num].emplace_back(minimizers.size(), 0);
// Pack the seeds for GaplessExtender.
GaplessExtender::cluster_type seed_matchings;
for (auto seed_index : cluster.seeds) {
// Insert the (graph position, read offset) pair.
const Seed& seed = seeds[seed_index];
seed_matchings.insert(GaplessExtender::to_seed(seed.pos, minimizers[seed.source].value.offset));
minimizer_extended_cluster_count_by_read[read_num].back()[seed.source]++;
#ifdef debug
cerr << "Seed read:" << minimizers[seed.source].value.offset << " = " << seed.pos
<< " from minimizer " << seed.source << endl;
#endif
}
// Extend seed hits in the cluster into one or more gapless extensions
cluster_extensions.emplace_back(std::move(extender.extend(seed_matchings, aln.sequence())),
cluster.fragment);
if (track_provenance) {
// Record with the funnel that the previous group became a group of this size.
// Don't bother recording the seed to extension matching...
funnels[read_num].project_group(cluster_num, cluster_extensions.back().first.size());
// Say we finished with this cluster, for now.
funnels[read_num].processed_input();
}
return true;
} else {
//We were looking for clusters in a paired fragment cluster but this one doesn't have any on the other end
if (track_provenance) {
funnels[read_num].pass("cluster-coverage", cluster_num, cluster.coverage);
funnels[read_num].pass("max-extensions", cluster_num);
funnels[read_num].pass("cluster-score", cluster_num, cluster.score);
funnels[read_num].fail("paired-clusters", cluster_num);
}
unextended_clusters_by_read[read_num].push_back(cluster_num);
return false;
}
}, [&](size_t cluster_num) {
// There are too many sufficiently good clusters
if (track_provenance) {
funnels[read_num].pass("cluster-coverage", cluster_num, clusters[cluster_num].coverage);
funnels[read_num].fail("max-extensions", cluster_num);
}
unextended_clusters_by_read[read_num].push_back(cluster_num);
}, [&](size_t cluster_num) {
// This cluster is not sufficiently good.
// TODO: I don't think it should ever get here unless we limit the scores of the fragment clusters we look at
unextended_clusters_by_read[read_num].push_back(cluster_num);
});
// We now estimate the best possible alignment score for each cluster.
std::vector<int> cluster_extension_scores = this->score_extensions(cluster_extensions, aln, funnels[read_num]);
if (track_provenance) {
funnels[read_num].stage("align");
}
// Now start the alignment step. Everything has to become an alignment.
// We will fill this with all computed alignments in estimated score order.
alignments.resize(max_fragment_num + 2);
alignment_indices.resize(max_fragment_num + 2);
// Clear any old refpos annotation and path
aln.clear_refpos();
aln.clear_path();
aln.set_score(0);
aln.set_identity(0);
aln.set_mapping_quality(0);
//Since we will lose the order in which we pass alignments to the funnel, use this to keep track
size_t curr_funnel_index = 0;
// Go through the gapless extension groups in score order.
process_until_threshold_b(cluster_extensions, cluster_extension_scores,
extension_set_score_threshold, 2, max_alignments,
[&](size_t extension_num) {
// This extension set is good enough.
// Called in descending score order.
if (track_provenance) {
funnels[read_num].pass("extension-set", extension_num, cluster_extension_scores[extension_num]);
funnels[read_num].pass("max-alignments", extension_num);
funnels[read_num].processing_input(extension_num);
}
auto& extensions = cluster_extensions[extension_num].first;
// Get an Alignments best_ and second_best_alignment of it somehow, and throw it in.
Alignment best_alignment = aln;
Alignment second_best_alignment = aln;
// Determine if we got full-length alignments or local alignments.
bool full_length_extensions = (extensions.size() <= 2);
for (auto& extension : extensions) {
full_length_extensions &= extension.full();
}
if (full_length_extensions) {
// We got full-length extensions, so directly convert to an Alignment.
if (track_provenance) {
funnels[read_num].substage("direct");
}
//Fill in the best alignments from the extension
this->extension_to_alignment(extensions.front(), best_alignment);
if (extensions.size() > 1) {
//Do the same thing for the second extension, if one exists
this->extension_to_alignment(extensions.back(), second_best_alignment);
}
if (track_provenance) {
// Stop the current substage
funnels[read_num].substage_stop();
}
} else if (do_dp) {
// We need to do chaining.
if (track_provenance) {
funnels[read_num].substage("chain");
}
// Do the DP and compute alignment into best_alignment and
// second_best_alignment, if there is a second best
find_optimal_tail_alignments(aln, extensions, best_alignment, second_best_alignment);
if (track_provenance) {
// We're done chaining. Next alignment may not go through this substage.
funnels[read_num].substage_stop();
}
} else {
// We would do chaining but it is disabled.
// Leave best_alignment unaligned
}
size_t fragment_num = cluster_extensions[extension_num].second;
if (second_best_alignment.score() != 0 &&
second_best_alignment.score() > best_alignment.score() * 0.8) {
//If there is a second extension and its score is at least half of the best score
read_num == 0 ? best_alignment_scores.first = max(best_alignment_scores.first, second_best_alignment.score())
: best_alignment_scores.second = max(best_alignment_scores.second, second_best_alignment.score());
read_num == 0 ? alignments[fragment_num ].first.emplace_back(std::move(second_best_alignment) ) :
alignments[fragment_num ].second.emplace_back(std::move(second_best_alignment));
read_num == 0 ? alignment_indices[fragment_num].first.emplace_back(curr_funnel_index)
: alignment_indices[fragment_num].second.emplace_back(curr_funnel_index);
curr_funnel_index++;
if (track_provenance) {
funnels[read_num].project(extension_num);
read_num == 0 ? funnels[read_num].score(extension_num, alignments[fragment_num ].first.back().score()) :
funnels[read_num].score(extension_num, alignments[fragment_num].second.back().score());
}
}
read_num == 0 ? best_alignment_scores.first = max(best_alignment_scores.first, best_alignment.score())
: best_alignment_scores.second = max(best_alignment_scores.second, best_alignment.score());
read_num == 0 ? alignments[fragment_num].first.emplace_back(std::move(best_alignment))
: alignments[fragment_num].second.emplace_back(std::move(best_alignment));
read_num == 0 ? alignment_indices[fragment_num].first.emplace_back(curr_funnel_index)
: alignment_indices[fragment_num].second.emplace_back(curr_funnel_index);
curr_funnel_index++;
if (track_provenance) {
funnels[read_num].project(extension_num);
read_num == 0 ? funnels[read_num].score(extension_num, alignments[fragment_num].first.back().score())
: funnels[read_num].score(extension_num, alignments[fragment_num].second.back().score());
// We're done with this input item
funnels[read_num].processed_input();
}
for (size_t i = 0 ; i < minimizer_extended_cluster_count_by_read[read_num][extension_num].size() ; i++) {
if (minimizer_extended_cluster_count_by_read[read_num][extension_num][i] > 0) {
// This minimizer is in an extended cluster that gave rise
// to at least one alignment, so it is explored.
minimizer_explored_by_read[read_num].insert(i);
}
}
return true;
}, [&](size_t extension_num) {
// There are too many sufficiently good extensions
if (track_provenance) {
funnels[read_num].pass("extension-set", extension_num, cluster_extension_scores[extension_num]);
funnels[read_num].fail("max-alignments", extension_num);
}
}, [&](size_t extension_num) {
// This extension is not good enough.
if (track_provenance) {
funnels[read_num].fail("extension-set", extension_num, cluster_extension_scores[extension_num]);
}
});
}
if (track_provenance) {
// Now say we are finding the winner(s)
funnels[0].stage("pairing");
funnels[1].stage("pairing");
}
// Fill this in with the pairs of alignments we will output
// each alignment is stored as <fragment index, alignment index> into alignments
vector<pair<pair<size_t, size_t>, pair<size_t, size_t>>> paired_alignments;
paired_alignments.reserve(alignments.size());
#ifdef print_minimizers
vector<pair<bool, bool>> alignment_was_rescued;
#endif
//For each alignment in alignments, which paired_alignment includes it. Follows structure of alignments
vector<pair<vector<vector<size_t>>, vector<vector<size_t>>>> alignment_groups(alignments.size());
// Grab all the scores in order for MAPQ computation.
vector<double> paired_scores;
paired_scores.reserve(alignments.size());
vector<int64_t> fragment_distances;
fragment_distances.reserve(alignments.size());
//For each fragment cluster, get the fraction of equivalent or better clusters that got thrown away
vector<size_t> better_cluster_count_alignment_pairs;
better_cluster_count_alignment_pairs.reserve(alignments.size());
//Keep track of alignments with no pairs in the same fragment cluster
bool found_pair = false;
//Alignments that don't have a mate
// <fragment index, alignment_index, true if its the first end>
vector<tuple<size_t, size_t, bool>> unpaired_alignments;
size_t unpaired_count_1 = 0;
size_t unpaired_count_2 = 0;
for (size_t fragment_num = 0 ; fragment_num < alignments.size() ; fragment_num ++ ) {
//Get pairs of plausible alignments
alignment_groups[fragment_num].first.resize(alignments[fragment_num].first.size());
alignment_groups[fragment_num].second.resize(alignments[fragment_num].second.size());
pair<vector<Alignment>, vector<Alignment>>& fragment_alignments = alignments[fragment_num];
if (!fragment_alignments.first.empty() && ! fragment_alignments.second.empty()) {
//Only keep pairs of alignments that were in the same fragment cluster
found_pair = true;
for (size_t i1 = 0 ; i1 < fragment_alignments.first.size() ; i1++) {
Alignment& alignment1 = fragment_alignments.first[i1];
size_t j1 = alignment_indices[fragment_num].first[i1];
for (size_t i2 = 0 ; i2 < fragment_alignments.second.size() ; i2++) {
Alignment& alignment2 = fragment_alignments.second[i2];
size_t j2 = alignment_indices[fragment_num].second[i2];
//Get the likelihood of the fragment distance
int64_t fragment_distance = distance_between(alignment1, alignment2);
double dev = fragment_distance - fragment_length_distr.mean();
double fragment_length_log_likelihood = -dev * dev / (2.0 * fragment_length_distr.std_dev() * fragment_length_distr.std_dev());
if (fragment_distance != std::numeric_limits<int64_t>::max() ) {
double score = alignment1.score() + alignment2.score() + (fragment_length_log_likelihood / get_aligner()->log_base);
alignment_groups[fragment_num].first[i1].emplace_back(paired_alignments.size());
alignment_groups[fragment_num].second[i2].emplace_back(paired_alignments.size());
paired_alignments.emplace_back(make_pair(fragment_num, i1), make_pair(fragment_num, i2));
paired_scores.emplace_back(score);
fragment_distances.emplace_back(fragment_distance);
better_cluster_count_alignment_pairs.emplace_back(better_cluster_count[fragment_num]);
#ifdef print_minimizers
alignment_was_rescued.emplace_back(false, false);
#endif
#ifdef debug
cerr << "Found pair of alignments from fragment " << fragment_num << " with scores "
<< alignment1.score() << " " << alignment2.score() << " at distance " << fragment_distance
<< " gets pair score " << score << endl;
cerr << "Alignment 1: " << pb2json(alignment1) << endl << "Alignment 2: " << pb2json(alignment2) << endl;
#endif
}
if (track_provenance) {
funnels[0].processing_input(j1);
funnels[1].processing_input(j2);
funnels[0].substage("pair-clusters");
funnels[1].substage("pair-clusters");
funnels[0].pass("max-rescue-attempts", j1);
funnels[0].project(j1);
funnels[1].pass("max-rescue-attempts", j2);
funnels[1].project(j2);
funnels[0].substage_stop();
funnels[1].substage_stop();
funnels[0].processed_input();
funnels[1].processed_input();
}
}
}
} else if (!fragment_alignments.first.empty()) {
#ifdef debug
cerr << "Found unpaired alignments from fragment " << fragment_num << " for first read" << endl;
#endif
for (size_t i = 0 ; i < fragment_alignments.first.size() ; i++) {
unpaired_alignments.emplace_back(fragment_num, i, true);
unpaired_count_1++;
#ifdef debug
cerr << "\t" << pb2json(fragment_alignments.first[i]) << endl;
#endif
}
} else if (!fragment_alignments.second.empty()) {
#ifdef debug
cerr << "Found unpaired alignments from fragment " << fragment_num << " for second read" << endl;
#endif
for (size_t i = 0 ; i < fragment_alignments.second.size() ; i++) {
unpaired_alignments.emplace_back(fragment_num, i, false);
unpaired_count_2++;
#ifdef debug
cerr << "\t" << pb2json(fragment_alignments.second[i]) << endl;
#endif
}
}
}
size_t rescued_count_1 = 0;
size_t rescued_count_2 = 0;
vector<bool> rescued_from;
if (!unpaired_alignments.empty()) {
//If we found some clusters that don't belong to a fragment cluster
if (!found_pair && max_rescue_attempts == 0 ) {
//If we didn't find any pairs and we aren't attempting rescue, just return the best for each end
#ifdef debug
cerr << "Found no pairs and we aren't doing rescue: return best alignment for each read" << endl;
#endif
Alignment& best_aln1 = aln1;
Alignment& best_aln2 = aln2;
best_aln1.clear_refpos();
best_aln1.clear_path();
best_aln1.set_score(0);
best_aln1.set_identity(0);
best_aln1.set_mapping_quality(0);
best_aln2.clear_refpos();
best_aln2.clear_path();
best_aln2.set_score(0);
best_aln2.set_identity(0);
best_aln2.set_mapping_quality(0);
for (tuple<size_t, size_t, bool> index : unpaired_alignments ) {
Alignment& alignment = std::get<2>(index) ? alignments[std::get<0>(index)].first[std::get<1>(index)]
: alignments[std::get<0>(index)].second[std::get<1>(index)];
if (std::get<2>(index)) {
if (alignment.score() > best_aln1.score()) {
best_aln1 = alignment;
}
} else {
if (alignment.score() > best_aln2.score()) {
best_aln2 = alignment;
}
}
}
set_annotation(best_aln1, "unpaired", true);
set_annotation(best_aln2, "unpaired", true);
pair<vector<Alignment>, vector<Alignment>> paired_mappings;
paired_mappings.first.emplace_back(std::move(best_aln1));
paired_mappings.second.emplace_back(std::move(best_aln2));
// Flip aln2 back to input orientation
reverse_complement_alignment_in_place(&paired_mappings.second.back(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
paired_mappings.first.back().set_mapping_quality(1);
paired_mappings.second.back().set_mapping_quality(1);
// Stop this alignment
funnels[0].stop();
funnels[1].stop();
if (track_provenance) {
// Annotate with the number of results in play at each stage
for (size_t read_num = 0 ; read_num < 2 ; read_num++) {
funnels[read_num].for_each_stage([&](const string& stage, const vector<size_t>& result_sizes) {
// Save the number of items
set_annotation(read_num == 0 ? paired_mappings.first[0] : paired_mappings.second[0], "stage_" + stage + "_results", (double)result_sizes.size());
});
if (track_correctness) {
// And with the last stage at which we had any descendants of the correct seed hit locations
set_annotation(read_num == 0 ? paired_mappings.first[0] : paired_mappings.second[0], "last_correct_stage", funnels[read_num].last_correct_stage());
}
// Annotate with the performances of all the filters
// We need to track filter number
size_t filter_num = 0;
funnels[read_num].for_each_filter([&](const string& stage, const string& filter,
const Funnel::FilterPerformance& by_count, const Funnel::FilterPerformance& by_size,
const vector<double>& filter_statistics_correct, const vector<double>& filter_statistics_non_correct) {
string filter_id = to_string(filter_num) + "_" + filter + "_" + stage;
if (read_num == 0) {
// Save the stats
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(paired_mappings.first[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(paired_mappings.first[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
} else {
// Save the stats
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(paired_mappings.second[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(paired_mappings.second[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
}
filter_num++;
});
}
}
#ifdef print_minimizers
cerr << aln1.sequence() << "\t";
for (char c : aln1.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << all_clusters.size() << "\t" << 0 << "\t" << 0 << "\t?";
for (size_t i = 0 ; i < minimizers_by_read[0].size() ; i++) {
auto& minimizer = minimizers_by_read[0][i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_explored_by_read[0].contains(i);
if (minimizer_explored_by_read[0].contains(i)) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << 1 << "\t" << 1 << "\t" << 1 << "\t" << 1;
if (track_correctness) {
cerr << "\t" << funnels[0].last_correct_stage() << endl;
} else {
cerr << "\t?" << endl;
}
cerr << aln2.sequence() << "\t";
for (char c : aln2.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << all_clusters.size() << "\t" << 0 << "\t" << 0 << "\t?";
for (size_t i = 0 ; i < minimizers_by_read[1].size() ; i++) {
auto& minimizer = minimizers_by_read[1][i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_explored_by_read[0].contains(i);
if (minimizer_explored_by_read[0].contains(i)) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << 1 << "\t" << 1 << "\t" << 1 << "\t" << 1;
if (track_correctness) {
cerr << "\t" << funnels[1].last_correct_stage() << endl;
} else {
cerr << "\t?" << endl;
}
#endif
return paired_mappings;
} else {
//Attempt rescue on unpaired alignments if either we didn't find any pairs or if the unpaired alignments are very good
process_until_threshold_a(unpaired_alignments, (std::function<double(size_t)>) [&](size_t i) -> double{
tuple<size_t, size_t, bool> index = unpaired_alignments.at(i);
return (double) std::get<2>(index) ? alignments[std::get<0>(index)].first[std::get<1>(index)].score()
: alignments[std::get<0>(index)].second[std::get<1>(index)].score();
}, 0, 1, max_rescue_attempts, [&](size_t i) {
tuple<size_t, size_t, bool> index = unpaired_alignments.at(i);
bool found_first = std::get<2>(index);
size_t j = found_first ? alignment_indices[std::get<0>(index)].first[std::get<1>(index)]
: alignment_indices[std::get<0>(index)].second[std::get<1>(index)];
if (track_provenance) {
funnels[found_first ? 0 : 1].processing_input(j);
funnels[found_first ? 0 : 1].substage("rescue");
}
Alignment& mapped_aln = found_first ? alignments[std::get<0>(index)].first[std::get<1>(index)]
: alignments[std::get<0>(index)].second[std::get<1>(index)];
Alignment rescued_aln = found_first ? aln2 : aln1;
rescued_aln.clear_path();
if (found_pair && (double) mapped_aln.score() < (double) (found_first ? best_alignment_scores.first : best_alignment_scores.second) * paired_rescue_score_limit) {
//If we have already found paired clusters and this unpaired alignment is not good enough, do nothing
return true;
}
attempt_rescue(mapped_aln, rescued_aln, minimizers_by_read[(found_first ? 1 : 0)], found_first);
int64_t fragment_dist = found_first ? distance_between(mapped_aln, rescued_aln)
: distance_between(rescued_aln, mapped_aln);
if (fragment_dist != std::numeric_limits<int64_t>::max()) {
bool duplicated = false;
double dev = fragment_dist - fragment_length_distr.mean();
double fragment_length_log_likelihood = -dev * dev / (2.0 * fragment_length_distr.std_dev() * fragment_length_distr.std_dev());
double score = mapped_aln.score() + rescued_aln.score() + (fragment_length_log_likelihood / get_aligner()->log_base);
set_annotation(mapped_aln, "rescuer", true);
set_annotation(rescued_aln, "rescued", true);
set_annotation(mapped_aln, "fragment_length", (double)fragment_dist);
set_annotation(rescued_aln, "fragment_length", (double)fragment_dist);
pair<size_t, size_t> mapped_index (std::get<0>(index), std::get<1>(index));
pair<size_t, size_t> rescued_index (alignments.size() - 1,
found_first ? alignments.back().second.size() : alignments.back().first.size());
found_first ? alignments.back().second.emplace_back(std::move(rescued_aln))
: alignments.back().first.emplace_back(std::move(rescued_aln));
found_first ? rescued_count_1++ : rescued_count_2++;
found_first ? alignment_groups.back().second.emplace_back() : alignment_groups.back().first.emplace_back();
pair<pair<size_t, size_t>, pair<size_t, size_t>> index_pair = found_first ?
make_pair(mapped_index, rescued_index) : make_pair(rescued_index, mapped_index);
paired_alignments.push_back(index_pair);
paired_scores.emplace_back(score);
fragment_distances.emplace_back(fragment_dist);
better_cluster_count_alignment_pairs.emplace_back(0);
rescued_from.push_back(found_first);
#ifdef print_minimizers
alignment_was_rescued.emplace_back(!found_first, found_first);
#endif
if (track_provenance) {
funnels[found_first ? 0 : 1].pass("max-rescue-attempts", j);
funnels[found_first ? 0 : 1].project(j);
funnels[found_first ? 1 : 0].introduce();
}
}
if (track_provenance) {
funnels[found_first ? 0 : 1].processed_input();
funnels[found_first ? 0 : 1].substage_stop();
}
return true;
}, [&](size_t i) {
if (track_provenance) {
tuple<size_t, size_t, bool> index = unpaired_alignments.at(i);
bool found_first = std::get<2>(index);
size_t j = found_first ? alignment_indices[std::get<0>(index)].first[std::get<1>(index)]
: alignment_indices[std::get<0>(index)].second[std::get<1>(index)];
funnels[found_first ? 0 : 1].fail("max-rescue-attempts", j);
}
return;
}, [&] (size_t i) {
if (track_provenance) {
tuple<size_t, size_t, bool> index = unpaired_alignments.at(i);
bool found_first = std::get<2>(index);
size_t j = found_first ? alignment_indices[std::get<0>(index)].first[std::get<1>(index)]
: alignment_indices[std::get<0>(index)].second[std::get<1>(index)];
}
return;
});
}
}
if (track_provenance) {
// Now say we are finding the winner(s)
funnels[0].stage("winner");
funnels[1].stage("winner");
}
double estimated_multiplicity_from_1 = unpaired_count_1 > 0 ? (double) unpaired_count_1 / min(rescued_count_1, max_rescue_attempts) : 1.0;
double estimated_multiplicity_from_2 = unpaired_count_2 > 0 ? (double) unpaired_count_2 / min(rescued_count_2, max_rescue_attempts) : 1.0;
vector<double> paired_multiplicities;
for (bool rescued_from_first : rescued_from) {
paired_multiplicities.push_back(rescued_from_first ? estimated_multiplicity_from_1 : estimated_multiplicity_from_2);
}
// Fill this in with the alignments we will output
pair<vector<Alignment>, vector<Alignment>> mappings;
// Grab all the scores in order for MAPQ computation.
vector<double> scores;
vector<double> scores_group_1;
vector<double> scores_group_2;
vector<int64_t> distances;
mappings.first.reserve(paired_alignments.size());
mappings.second.reserve(paired_alignments.size());
scores.reserve(paired_scores.size());
distances.reserve(fragment_distances.size());
vector<size_t> better_cluster_count_mappings;
better_cluster_count_mappings.reserve(better_cluster_count_alignment_pairs.size());
#ifdef print_minimizers
vector<pair<bool, bool>> mapping_was_rescued;
#endif
process_until_threshold_a(paired_alignments, (std::function<double(size_t)>) [&](size_t i) -> double {
return paired_scores[i];
}, 0, 1, max_multimaps, [&](size_t alignment_num) {
// This alignment makes it
// Called in score order
pair<pair<size_t, size_t>, pair<size_t, size_t>> index_pair = paired_alignments[alignment_num];
// Remember the score at its rank
scores.emplace_back(paired_scores[alignment_num]);
distances.emplace_back(fragment_distances[alignment_num]);
// Remember the output alignment
mappings.first.emplace_back( alignments[index_pair.first.first].first[index_pair.first.second]);
mappings.second.emplace_back(alignments[index_pair.second.first].second[index_pair.second.second]);
better_cluster_count_mappings.emplace_back(better_cluster_count_alignment_pairs[alignment_num]);
if (mappings.first.size() == 1 && found_pair) {
//If this is the best pair of alignments that we're going to return and we didn't attempt rescue,
//get the group scores for mapq
//Get the scores of
scores_group_1.push_back(paired_scores[alignment_num]);
scores_group_2.push_back(paired_scores[alignment_num]);
//The indices (into paired_alignments) of pairs with the same first read as this
vector<size_t>& alignment_group_1 = alignment_groups[index_pair.first.first].first[index_pair.first.second];
vector<size_t>& alignment_group_2 = alignment_groups[index_pair.second.first].second[index_pair.second.second];
for (size_t other_alignment_num : alignment_group_1) {
if (other_alignment_num != alignment_num) {
scores_group_1.push_back(paired_scores[other_alignment_num]);
}
}
for (size_t other_alignment_num : alignment_group_2) {
if (other_alignment_num != alignment_num) {
scores_group_2.push_back(paired_scores[other_alignment_num]);
}
}
}
// Flip aln2 back to input orientation
reverse_complement_alignment_in_place(&mappings.second.back(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
if (mappings.first.size() > 1) {
mappings.first.back().set_is_secondary(true);
mappings.second.back().set_is_secondary(true);
}
#ifdef print_minimizers
mapping_was_rescued.emplace_back(alignment_was_rescued[alignment_num]);
#endif
if (track_provenance) {
// Tell the funnel
funnels[0].pass("max-multimaps", alignment_num);
funnels[0].project(alignment_num);
funnels[0].score(alignment_num, scores.back());
funnels[1].pass("max-multimaps", alignment_num);
funnels[1].project(alignment_num);
funnels[1].score(alignment_num, scores.back());
}
return true;
}, [&](size_t alignment_num) {
// We already have enough alignments, although this one has a good score
// Remember the score at its rank anyway
scores.emplace_back(paired_scores[alignment_num]);
distances.emplace_back(fragment_distances[alignment_num]);
if (track_provenance) {
funnels[0].fail("max-multimaps", alignment_num);
funnels[1].fail("max-multimaps", alignment_num);
}
}, [&](size_t alignment_num) {
// This alignment does not have a sufficiently good score
// Score threshold is 0; this should never happen
assert(false);
});
if (track_provenance) {
funnels[0].substage("mapq");
funnels[1].substage("mapq");
}
#ifdef print_minimizers
double uncapped_mapq = 0.0;
double fragment_cluster_cap = 0.0;
vector<double> mapq_extend_caps;
double mapq_score_group_1 = 0.0;
double mapq_score_group_2 = 0.0;
#endif
if (mappings.first.empty()) {
//If we didn't get an alignment, return empty alignments
mappings.first.emplace_back(aln1);
mappings.second.emplace_back(aln2);
// Flip aln2 back to input orientation
reverse_complement_alignment_in_place(&mappings.second.back(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
mappings.first.back().clear_refpos();
mappings.first.back().clear_path();
mappings.first.back().set_score(0);
mappings.first.back().set_identity(0);
mappings.first.back().set_mapping_quality(0);
mappings.second.back().clear_refpos();
mappings.second.back().clear_path();
mappings.second.back().set_score(0);
mappings.second.back().set_identity(0);
mappings.second.back().set_mapping_quality(0);
#ifdef print_minimizers
mapping_was_rescued.emplace_back(false, false);
#endif
} else {
#ifdef debug
cerr << "For scores ";
for (auto& score : scores) cerr << score << " ";
#endif
size_t winning_index;
// Compute MAPQ if not unmapped. Otherwise use 0 instead of the 50% this would give us.
// If either of the mappings was duplicated in other pairs, use the group scores to determine mapq
const vector<double>* multiplicities = paired_multiplicities.size() == scores.size() ? &paired_multiplicities : nullptr;
// Compute MAPQ if not unmapped. Otherwise use 0 instead of the 50% this would give us.
// If either of the mappings was duplicated in other pairs, use the group scores to determine mapq
double mapq = scores[0] == 0 ? 0 :
get_regular_aligner()->maximum_mapping_quality_exact(scores, &winning_index, multiplicities) / 2;
#ifdef print_minimizers
uncapped_mapq = mapq;
#endif
//Cap mapq at 1 / # equivalent or better fragment clusters
if (better_cluster_count_mappings.size() != 0 && better_cluster_count_mappings.front() > 0) {
mapq = min(mapq,round(prob_to_phred((1.0 / (double) better_cluster_count_mappings.front()))));
}
#ifdef print_minimizers
if (better_cluster_count_mappings.size() != 0 && better_cluster_count_mappings.front() > 0) {
fragment_cluster_cap = round(prob_to_phred((1.0 / (double) better_cluster_count_mappings.front())));
}
#endif
//If one alignment was duplicated in other pairs, cap the mapq for that alignment at the mapq
//of the group of duplicated alignments
double mapq_group1 = scores_group_1.size() <= 1 ? mapq :
min(mapq, get_regular_aligner()->maximum_mapping_quality_exact(scores_group_1, &winning_index) / 2);
double mapq_group2 = scores_group_2.size() <= 1 ? mapq :
min(mapq, get_regular_aligner()->maximum_mapping_quality_exact(scores_group_2, &winning_index) / 2);
#ifdef print_minimizers
mapq_score_group_1 = scores_group_1.size() <= 1 ? 0.0 : get_regular_aligner()->maximum_mapping_quality_exact(scores_group_1, &winning_index);
mapq_score_group_2 = scores_group_2.size() <= 1 ? 0.0 : get_regular_aligner()->maximum_mapping_quality_exact(scores_group_2, &winning_index);
#endif
// Compute one MAPQ cap across all the fragments
double mapq_cap = -std::numeric_limits<float>::infinity();
for (auto read_num : {0, 1}) {
// For each fragment
// Find the source read
auto& aln = read_num == 0 ? aln1 : aln2;
vector<size_t> explored_minimizers;
for (size_t i = 0; i < minimizers_by_read[read_num].size(); i++) {
if (minimizer_explored_by_read[read_num].contains(i)) {
explored_minimizers.push_back(i);
}
}
// Compute caps on MAPQ. TODO: avoid needing to pass as much stuff along.
double mapq_explored_cap = 2 * faster_cap(minimizers_by_read[read_num], explored_minimizers, aln.sequence(), aln.quality());
#ifdef print_minimizers
mapq_extend_caps.emplace_back(mapq_explored_cap);
#endif
// Remember the caps
auto& to_annotate = (read_num == 0 ? mappings.first : mappings.second).front();
set_annotation(to_annotate, "mapq_explored_cap", mapq_explored_cap);
// Compute the cap. It should be the higher of the caps for the two reads
// (unless one has no minimizers, i.e. if it was rescued)
// The individual cap values are either actual numbers or +inf, so the cap can't stay as -inf.
mapq_cap = mapq_explored_cap == numeric_limits<double>::infinity() ? mapq_cap : max(mapq_cap, mapq_explored_cap);
}
mapq_cap = mapq_cap == -std::numeric_limits<float>::infinity() ? numeric_limits<double>::infinity() : mapq_cap;
for (auto read_num : {0, 1}) {
// For each fragment
// Find the source read
auto& aln = read_num == 0 ? aln1 : aln2;
// Find the MAPQ to cap
auto& read_mapq = read_num == 0 ? mapq_group1 : mapq_group2;
// Remember the uncapped MAPQ
auto& to_annotate = (read_num == 0 ? mappings.first : mappings.second).front();
set_annotation(to_annotate, "mapq_uncapped", read_mapq);
// And the cap we actually applied (possibly from the pair partner)
set_annotation(to_annotate, "mapq_applied_cap", mapq_cap);
// Apply the cap and transformation
read_mapq = round(0.85 * min(mapq_cap, min(read_mapq, 70.0)));
}
#ifdef debug
cerr << "MAPQ is " << mapq << ", capped group MAPQ scores are " << mapq_group1 << " and " << mapq_group2 << endl;
#endif
mappings.first.front().set_mapping_quality(max(min(mapq_group1, 60.0), 0.0)) ;
mappings.second.front().set_mapping_quality(max(min(mapq_group2, 60.0), 0.0)) ;
//Annotate top pair with its fragment distance, fragment length distrubution, and secondary scores
set_annotation(mappings.first.front(), "fragment_length", (double) distances.front());
set_annotation(mappings.second.front(), "fragment_length", (double) distances.front());
string distribution = "-I " + to_string(fragment_length_distr.mean()) + " -D " + to_string(fragment_length_distr.std_dev());
set_annotation(mappings.first.front(),"fragment_length_distribution", distribution);
set_annotation(mappings.second.front(),"fragment_length_distribution", distribution);
set_annotation(mappings.first.front(),"secondary_scores", scores);
set_annotation(mappings.second.front(),"secondary_scores", scores);
}
if (track_provenance) {
funnels[0].substage_stop();
funnels[1].substage_stop();
}
// Stop this alignment
funnels[0].stop();
funnels[1].stop();
if (track_provenance) {
// Annotate with the number of results in play at each stage
for (size_t read_num = 0 ; read_num < 2 ; read_num++) {
funnels[read_num].for_each_stage([&](const string& stage, const vector<size_t>& result_sizes) {
// Save the number of items
set_annotation(read_num == 0 ? mappings.first[0] : mappings.second[0], "stage_" + stage + "_results", (double)result_sizes.size());
});
if (track_correctness) {
// And with the last stage at which we had any descendants of the correct seed hit locations
set_annotation(read_num == 0 ? mappings.first[0] : mappings.second[0], "last_correct_stage", funnels[read_num].last_correct_stage());
}
// Annotate with the performances of all the filters
// We need to track filter number
size_t filter_num = 0;
funnels[read_num].for_each_filter([&](const string& stage, const string& filter,
const Funnel::FilterPerformance& by_count, const Funnel::FilterPerformance& by_size,
const vector<double>& filter_statistics_correct, const vector<double>& filter_statistics_non_correct) {
string filter_id = to_string(filter_num) + "_" + filter + "_" + stage;
if (read_num == 0) {
// Save the stats
set_annotation(mappings.first[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(mappings.first[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(mappings.first[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(mappings.first[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(mappings.first[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(mappings.first[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(mappings.first[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(mappings.first[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(mappings.first[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(mappings.first[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
} else {
// Save the stats
set_annotation(mappings.second[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(mappings.second[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(mappings.second[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(mappings.second[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(mappings.second[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(mappings.second[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(mappings.second[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(mappings.second[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(mappings.second[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(mappings.second[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
}
filter_num++;
});
}
// Annotate with parameters used for the filters.
set_annotation(mappings.first[0] , "param_hit-cap", (double) hit_cap);
set_annotation(mappings.first[0] , "param_hard-hit-cap", (double) hard_hit_cap);
set_annotation(mappings.first[0] , "param_score-fraction", (double) minimizer_score_fraction);
set_annotation(mappings.first[0] , "param_max-extensions", (double) max_extensions);
set_annotation(mappings.first[0] , "param_max-alignments", (double) max_alignments);
set_annotation(mappings.first[0] , "param_cluster-score", (double) cluster_score_threshold);
set_annotation(mappings.first[0] , "param_cluster-coverage", (double) cluster_coverage_threshold);
set_annotation(mappings.first[0] , "param_extension-set", (double) extension_set_score_threshold);
set_annotation(mappings.first[0] , "param_max-multimaps", (double) max_multimaps);
set_annotation(mappings.first[0] , "param_max-rescue-attempts", (double) max_rescue_attempts);
set_annotation(mappings.second[0], "param_hit-cap", (double) hit_cap);
set_annotation(mappings.second[0], "param_hard-hit-cap", (double) hard_hit_cap);
set_annotation(mappings.second[0], "param_score-fraction", (double) minimizer_score_fraction);
set_annotation(mappings.second[0], "param_max-extensions", (double) max_extensions);
set_annotation(mappings.second[0], "param_max-alignments", (double) max_alignments);
set_annotation(mappings.second[0], "param_cluster-score", (double) cluster_score_threshold);
set_annotation(mappings.second[0], "param_cluster-coverage", (double) cluster_coverage_threshold);
set_annotation(mappings.second[0], "param_extension-set", (double) extension_set_score_threshold);
set_annotation(mappings.second[0], "param_max-multimaps", (double) max_multimaps);
set_annotation(mappings.second[0] , "param_max-rescue-attempts", (double) max_rescue_attempts);
}
#ifdef print_minimizers
if (mapq_extend_caps.size() == 0) {
mapq_extend_caps.resize(2,0.0);
}
if (distances.size() == 0) {
distances.emplace_back(0);
}
cerr << aln1.sequence() << "\t";
for (char c : aln1.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << all_clusters.size() << "\t" << mapping_was_rescued[0].first << "\t" << mapping_was_rescued[0].second << "\t" << distances.front();
for (size_t i = 0 ; i < minimizers_by_read[0].size() ; i++) {
auto& minimizer = minimizers_by_read[0][i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_explored_by_read[0].contains(i);
if (minimizer_explored_by_read[0].contains(i)) {
assert(minimizer.hits<=hard_hit_cap) ;
}
} cerr << "\t" << uncapped_mapq << "\t" << fragment_cluster_cap << "\t" << mapq_score_group_1 << "\t" << mapq_extend_caps[0];
if (track_correctness) {
cerr << "\t" << funnels[0].last_correct_stage() << endl;
} else {
cerr << "\t?" << endl;
}
cerr << aln2.sequence() << "\t";
for (char c : aln2.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << all_clusters.size() << "\t" << mapping_was_rescued[0].second << "\t" << mapping_was_rescued[0].first << "\t" << distances.front();
for (size_t i = 0 ; i < minimizers_by_read[1].size() ; i++) {
auto& minimizer = minimizers_by_read[1][i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_explored_by_read[1].contains(i);
if (minimizer_explored_by_read[1].contains(i)) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << uncapped_mapq << "\t" << fragment_cluster_cap << "\t" << mapq_score_group_1 << "\t" << mapq_extend_caps[1];
if (track_correctness) {
cerr << "\t" << funnels[1].last_correct_stage() << endl;
} else {
cerr << "\t?" << endl;
}
#endif
// Ship out all the aligned alignments
return mappings;
#ifdef debug
// Dump the funnel info graph.
funnels[0].to_dot(cerr);
funnels[1].to_dot(cerr);
#endif
}
//-----------------------------------------------------------------------------
double MinimizerMapper::compute_mapq_caps(const Alignment& aln,
const std::vector<Minimizer>& minimizers,
const SmallBitset& explored) {
// We need to cap MAPQ based on the likelihood of generating all the windows in the explored minimizers by chance, too.
#ifdef debug
cerr << "Cap based on explored minimizers all being faked by errors..." << endl;
#endif
// Convert our flag vector to a list of the minimizers actually in extended clusters
vector<size_t> explored_minimizers;
explored_minimizers.reserve(minimizers.size());
for (size_t i = 0; i < minimizers.size(); i++) {
if (explored.contains(i)) {
explored_minimizers.push_back(i);
}
}
double mapq_explored_cap = window_breaking_quality(minimizers, explored_minimizers, aln.sequence(), aln.quality());
return mapq_explored_cap;
}
double MinimizerMapper::window_breaking_quality(const vector<Minimizer>& minimizers, vector<size_t>& broken,
const string& sequence, const string& quality_bytes) {
#ifdef debug
cerr << "Computing MAPQ cap based on " << broken.size() << "/" << minimizers.size() << " minimizers' windows" << endl;
#endif
if (broken.empty() || quality_bytes.empty()) {
// If we have no agglomerations or no qualities, bail
return numeric_limits<double>::infinity();
}
assert(sequence.size() == quality_bytes.size());
// Sort the agglomerations by start position
std::sort(broken.begin(), broken.end(), [&](const size_t& a, const size_t& b) {
return minimizers[a].agglomeration_start < minimizers[b].agglomeration_start;
});
// Have a priority queue for tracking the agglomerations that a base is currently overlapping.
// Prioritize earliest-ending best, and then latest-starting best.
// This is less, and greater priority is at the front of the queue (better).
// TODO: do we really need to care about the start here?
auto agglomeration_priority = [&](const size_t& a, const size_t& b) {
// Returns true if a is worse (ends later, or ends at the same place and starts earlier).
auto& ma = minimizers[a];
auto& mb = minimizers[b];
auto a_end = ma.agglomeration_start + ma.agglomeration_length;
auto b_end = mb.agglomeration_start + mb.agglomeration_length;
return (a_end > b_end) || (a_end == b_end && ma.agglomeration_start < mb.agglomeration_start);
};
// We maintain our own heap so we can iterate over it.
vector<size_t> active_agglomerations;
// A window in flight is a pair of start position, inclusive end position
struct window_t {
size_t first;
size_t last;
};
// Have a priority queue of window starts and ends, prioritized earliest-ending best, and then latest-starting best.
// This is less, and greater priority is at the front of the queue (better).
auto window_priority = [&](const window_t& a, const window_t& b) {
// Returns true if a is worse (ends later, or ends at the same place and starts earlier).
return (a.last > b.last) || (a.last == b.last && a.first < b.first);
};
priority_queue<window_t, vector<window_t>, decltype(window_priority)> active_windows(window_priority);
// Have a cursor for which agglomeration should come in next.
auto next_agglomeration = broken.begin();
// Have a DP table with the cost of the cheapest solution to the problem up to here, including a hit at this base.
// Or numeric_limits<double>::infinity() if base cannot be hit.
// We pre-fill it because I am scared to use end() if we change its size.
vector<double> costs(sequence.size(), numeric_limits<double>::infinity());
// Keep track of the latest-starting window ending before here. If none, this will be two numeric_limits<size_t>::max() values.
window_t latest_starting_ending_before = { numeric_limits<size_t>::max(), numeric_limits<size_t>::max() };
// And keep track of the min cost DP table entry, or end if not computed yet.
auto latest_starting_ending_before_winner = costs.end();
for (size_t i = 0; i < sequence.size(); i++) {
// For each base in the read
#ifdef debug
cerr << "At base " << i << endl;
#endif
// Bring in new agglomerations and windows that start at this base.
while (next_agglomeration != broken.end() && minimizers[*next_agglomeration].agglomeration_start == i) {
// While the next agglomeration starts here
// Record it
active_agglomerations.push_back(*next_agglomeration);
std::push_heap(active_agglomerations.begin(), active_agglomerations.end(), agglomeration_priority);
// Look it up
auto& minimizer = minimizers[*next_agglomeration];
// Determine its window size from its index.
size_t window_size = minimizer.window_size();
#ifdef debug
cerr << "\tBegin agglomeration of " << (minimizer.agglomeration_length - window_size + 1)
<< " windows of " << window_size << " bp each for minimizer "
<< *next_agglomeration << " (" << minimizer.forward_offset()
<< "-" << (minimizer.forward_offset() + minimizer.length) << ")" << endl;
#endif
// Make sure the minimizer instance isn't too far into the agglomeration to actually be conatined in the same k+w-1 window as the first base.
assert(minimizer.agglomeration_start + minimizer.candidates_per_window >= minimizer.forward_offset());
for (size_t start = minimizer.agglomeration_start;
start + window_size - 1 < minimizer.agglomeration_start + minimizer.agglomeration_length;
start++) {
// Add all the agglomeration's windows to the queue, looping over their start bases in the read.
window_t add = {start, start + window_size - 1};
#ifdef debug
cerr << "\t\t" << add.first << " - " << add.last << endl;
#endif
active_windows.push(add);
}
// And advance the cursor
++next_agglomeration;
}
// We have the start and end of the latest-starting window ending before here (may be none)
if (isATGC(sequence[i]) &&
(!active_windows.empty() ||
(next_agglomeration != broken.end() && minimizers[*next_agglomeration].agglomeration_start == i))) {
// This base is not N, and it is either covered by an agglomeration
// that hasn't ended yet, or a new agglomeration starts here.
#ifdef debug
cerr << "\tBase is acceptable (" << sequence[i] << ", " << active_agglomerations.size() << " active agglomerations, "
<< active_windows.size() << " active windows)" << endl;
#endif
// Score mutating the base itself, thus causing all the windows it touches to be wrong.
// TODO: account for windows with multiple hits not having to be explained at full cost here.
// We start with the cost to mutate the base.
double base_cost = quality_bytes[i];
#ifdef debug
cerr << "\t\tBase base quality: " << base_cost << endl;
#endif
for (const size_t& active_index : active_agglomerations) {
// Then, we look at each agglomeration the base overlaps
// Find the minimizer whose agglomeration we are looking at
auto& active = minimizers[active_index];
if (i >= active.forward_offset() &&
i < active.forward_offset() + active.length) {
// If the base falls in the minimizer, we don't do anything. Just mutating the base is enough to create this wrong minimizer.
#ifdef debug
cerr << "\t\tBase in minimizer " << active_index << " (" << active.forward_offset()
<< "-" << (active.forward_offset() + active.length) << ") for agglomeration "
<< active.agglomeration_start << "-" << (active.agglomeration_start + active.agglomeration_length) << endl;
#endif
continue;
}
// If the base falls outside the minimizer, it participates in
// some number of other possible minimizers in the
// agglomeration. Compute that, accounting for edge effects.
size_t possible_minimizers = min((size_t) active.length, min(i - active.agglomeration_start + 1, (active.agglomeration_start + active.agglomeration_length) - i));
// Then for each of those possible minimizers, we need P(would have beaten the current minimizer).
// We approximate this as constant across the possible minimizers.
// And since we want to OR together beating, we actually AND together not-beating and then not it.
// So we track the probability of not beating.
double any_beat_phred = phred_for_at_least_one(active.value.hash, possible_minimizers);
#ifdef debug
cerr << "\t\tBase flanks minimizer " << active_index << " (" << active.forward_offset()
<< "-" << (active.forward_offset() + active.length) << ") for agglomeration "
<< active.agglomeration_start << "-" << (active.agglomeration_start + active.agglomeration_length)
<< " and has " << possible_minimizers
<< " chances to have beaten it; cost to have beaten with any is Phred " << any_beat_phred << endl;
#endif
// Then we AND (sum) the Phred of that in, as an additional cost to mutating this base and kitting all the windows it covers.
// This makes low-quality bases outside of minimizers produce fewer low MAPQ caps, and accounts for the robustness of minimizers to some errors.
base_cost += any_beat_phred;
}
// Now we know the cost of mutating this base, so we need to
// compute the total cost of a solution through here, mutating this
// base.
// Look at the start of that latest-starting window ending before here.
if (latest_starting_ending_before.first == numeric_limits<size_t>::max()) {
// If there is no such window, this is the first base hit, so
// record the cost of hitting it.
costs[i] = base_cost;
#ifdef debug
cerr << "\tFirst base hit, costs " << costs[i] << endl;
#endif
} else {
// Else, scan from that window's start to its end in the DP
// table, and find the min cost.
if (latest_starting_ending_before_winner == costs.end()) {
// We haven't found the min in the window we come from yet, so do that.
latest_starting_ending_before_winner = std::min_element(costs.begin() + latest_starting_ending_before.first,
costs.begin() + latest_starting_ending_before.last + 1);
}
double min_prev_cost = *latest_starting_ending_before_winner;
// Add the cost of hitting this base
costs[i] = min_prev_cost + base_cost;
#ifdef debug
cerr << "\tComes from prev base at " << (latest_starting_ending_before_winner - costs.begin()) << ", costs " << costs[i] << endl;
#endif
}
} else {
// This base is N, or not covered by an agglomeration.
// Leave infinity there to say we can't hit it.
// Nothing to do!
}
// Now we compute the start of the latest-starting window ending here or before, and deactivate agglomerations/windows.
while (!active_agglomerations.empty() &&
minimizers[active_agglomerations.front()].agglomeration_start + minimizers[active_agglomerations.front()].agglomeration_length - 1 == i) {
// Look at the queue to see if an agglomeration ends here.
#ifdef debug
cerr << "\tEnd agglomeration " << active_agglomerations.front() << endl;
#endif
std::pop_heap(active_agglomerations.begin(), active_agglomerations.end(), agglomeration_priority);
active_agglomerations.pop_back();
}
while (!active_windows.empty() && active_windows.top().last == i) {
// The look at the queue to see if a window ends here. This is
// after windows are added so that we can handle 1-base windows.
#ifdef debug
cerr << "\tEnd window " << active_windows.top().first << " - " << active_windows.top().last << endl;
#endif
if (latest_starting_ending_before.first == numeric_limits<size_t>::max() ||
active_windows.top().first > latest_starting_ending_before.first) {
#ifdef debug
cerr << "\t\tNew latest-starting-before-here!" << endl;
#endif
// If so, use the latest-starting of all such windows as our latest starting window ending here or before result.
latest_starting_ending_before = active_windows.top();
// And clear our cache of the lowest cost base to hit it.
latest_starting_ending_before_winner = costs.end();
#ifdef debug
cerr << "\t\t\tNow have: " << latest_starting_ending_before.first << " - " << latest_starting_ending_before.last << endl;
#endif
}
// And pop them all off.
active_windows.pop();
}
// If not, use the latest-starting window ending at the previous base or before (i.e. do nothing).
// Loop around; we will have the latest-starting window ending before the next here.
}
#ifdef debug
cerr << "Final window to scan: " << latest_starting_ending_before.first << " - " << latest_starting_ending_before.last << endl;
#endif
// When we get here, all the agglomerations should have been handled
assert(next_agglomeration == broken.end());
// And all the windows should be off the queue.
assert(active_windows.empty());
// When we get to the end, we have the latest-starting window overall. It must exist.
assert(latest_starting_ending_before.first != numeric_limits<size_t>::max());
// Scan it for the best final base to hit and return the cost there.
// Don't use the cache here because nothing can come after the last-ending window.
auto min_cost_at = std::min_element(costs.begin() + latest_starting_ending_before.first,
costs.begin() + latest_starting_ending_before.last + 1);
#ifdef debug
cerr << "Overall min cost: " << *min_cost_at << " at base " << (min_cost_at - costs.begin()) << endl;
#endif
return *min_cost_at;
}
double MinimizerMapper::faster_cap(const vector<Minimizer>& minimizers, vector<size_t>& minimizers_explored,
const string& sequence, const string& quality_bytes) {
// Sort minimizer subset so we go through minimizers in increasing order of start position
std::sort(minimizers_explored.begin(), minimizers_explored.end(), [&](size_t a, size_t b) {
// Return true if a must come before b, and false otherwise
return minimizers[a].forward_offset() < minimizers[b].forward_offset();
});
#ifdef debug
cerr << "Sorted " << minimizers_explored.size() << " minimizers" << endl;
#endif
#ifdef debug
// Dump read and minimizers
int digits_needed = (int) ceil(log10(sequence.size()));
for (int digit = digits_needed - 1; digit >= 0; digit--) {
for (size_t i = 0; i < sequence.size(); i++) {
// Output the correct digit for this place in this number
cerr << (char) ('0' + (uint8_t) round(i % (int) round(pow(10, digit + 1)) / pow(10, digit)));
}
cerr << endl;
}
cerr << sequence << endl;
for (auto& explored_index : minimizers_explored) {
// For each explored minimizer
auto& m = minimizers[explored_index];
for (size_t i = 0; i < m.agglomeration_start; i++) {
// Space until its agglomeration starts
cerr << ' ';
}
for (size_t i = m.agglomeration_start; i < m.forward_offset(); i++) {
// Do the beginnign of the agglomeration
cerr << '-';
}
// Do the minimizer itself
cerr << m.value.key.decode(m.length);
for (size_t i = m.forward_offset() + m.length ; i < m.agglomeration_start + m.agglomeration_length; i++) {
// Do the tail end of the agglomeration
cerr << '-';
}
cerr << endl;
}
#endif
// Make a DP table holding the log10 probability of having an error disrupt each minimizer.
// Entry i+1 is log prob of mutating minimizers 0, 1, 2, ..., i.
// Make sure to have an extra field at the end to support this.
// Initialize with -inf for unfilled.
vector<double> c(minimizers_explored.size() + 1, -numeric_limits<double>::infinity());
c[0] = 0.0;
for_each_aglomeration_interval(minimizers, sequence, quality_bytes, minimizers_explored, [&](size_t left, size_t right, size_t bottom, size_t top) {
// For each overlap range in the agglomerations
#ifdef debug
cerr << "Consider overlap range " << left << " to " << right << " in minimizer ranks " << bottom << " to " << top << endl;
cerr << "log10prob for bottom: " << c[bottom] << endl;
#endif
// Calculate the probability of a disruption here
double p_here = get_log10_prob_of_disruption_in_interval(minimizers, sequence, quality_bytes,
minimizers_explored.begin() + bottom, minimizers_explored.begin() + top, left, right);
#ifdef debug
cerr << "log10prob for here: " << p_here << endl;
#endif
// Calculate prob of all intervals up to top being disrupted
double p = c[bottom] + p_here;
#ifdef debug
cerr << "log10prob overall: " << p << endl;
#endif
for (size_t i = bottom + 1; i < top + 1; i++) {
// Replace min-prob for minimizers in the interval
if (c[i] < p) {
#ifdef debug
cerr << "\tBeats " << c[i] << " at rank " << i-1 << endl;
#endif
c[i] = p;
} else {
#ifdef debug
cerr << "\tBeaten by " << c[i] << " at rank " << i-1 << endl;
#endif
}
}
});
#ifdef debug
cerr << "log10prob after all minimizers is " << c.back() << endl;
#endif
assert(!isinf(c.back()));
// Conver to Phred.
double result = -c.back() * 10;
return result;
}
void MinimizerMapper::for_each_aglomeration_interval(const vector<Minimizer>& minimizers,
const string& sequence, const string& quality_bytes,
const vector<size_t>& minimizer_indices,
const function<void(size_t, size_t, size_t, size_t)>& iteratee) {
if (minimizer_indices.empty()) {
// Handle no item case
return;
}
// Items currently being iterated over
list<const Minimizer*> stack = {&minimizers[minimizer_indices.front()]};
// The left end of an item interval
size_t left = stack.front()->agglomeration_start;
// The index of the first item in the interval in the sequence of selected items
size_t bottom = 0;
// Emit all intervals that precede a given point "right"
auto emit_preceding_intervals = [&](size_t right) {
while (left < right) {
// Work out the end position of the top thing on the stack
size_t stack_top_end = stack.front()->agglomeration_start + stack.front()->agglomeration_length;
if (stack_top_end <= right) {
// Case where the left-most item ends before the start of the new item
iteratee(left, stack_top_end, bottom, bottom + stack.size());
// If the stack contains only one item there is a gap between the item
// and the new item, otherwise just shift to the end of the leftmost item
left = stack.size() == 1 ? right : stack_top_end;
bottom += 1;
stack.pop_front();
} else {
// Case where the left-most item ends at or after the beginning of the new new item
iteratee(left, right, bottom, bottom + stack.size());
left = right;
}
}
};
for (auto it = minimizer_indices.begin() + 1; it != minimizer_indices.end(); ++it) {
// For each item in turn
auto& item = minimizers[*it];
assert(stack.size() > 0);
// For each new item we return all intervals that
// precede its start
emit_preceding_intervals(item.agglomeration_start);
// Add the new item for the next loop
stack.push_back(&item);
}
// Intervals of the remaining intervals on the stack
emit_preceding_intervals(sequence.size());
}
double MinimizerMapper::get_log10_prob_of_disruption_in_interval(const vector<Minimizer>& minimizers,
const string& sequence, const string& quality_bytes,
const vector<size_t>::iterator& disrupt_begin, const vector<size_t>::iterator& disrupt_end,
size_t left, size_t right) {
#ifdef debug
cerr << "Compute log10 probability in interval " << left << "-" << right << endl;
#endif
if (left == right) {
// 0-length intervals need no disruption.
return 0;
}
// Start with the first column
double p = get_log10_prob_of_disruption_in_column(minimizers, sequence, quality_bytes, disrupt_begin, disrupt_end, left);
#ifdef debug
cerr << "\tlog10 probability at column " << left << ": " << p << endl;
#endif
for(size_t i = left + 1 ; i < right; i++) {
// OR up probability of all the other columns
double col_p = get_log10_prob_of_disruption_in_column(minimizers, sequence, quality_bytes, disrupt_begin, disrupt_end, i);
#ifdef debug
cerr << "\tlog10 probability at column " << i << ": " << col_p << endl;
#endif
p = add_log10(col_p, p);
#ifdef debug
cerr << "\tRunning total OR: " << p << endl;
#endif
}
// Make sure that we don't go above certainty when our bases are really bad
// and OR ~= sum assumption breaks down due to non-tiny probabilities.
p = std::min(p, 0.0);
// Return the result
return p;
}
double MinimizerMapper::get_log10_prob_of_disruption_in_column(const vector<Minimizer>& minimizers,
const string& sequence, const string& quality_bytes,
const vector<size_t>::iterator& disrupt_begin, const vector<size_t>::iterator& disrupt_end,
size_t index) {
#ifdef debug
cerr << "\tCompute log10 probability at column " << index << endl;
#endif
// Base cost is quality. Make sure to compute a non-integral answer.
double p = -(uint8_t)quality_bytes[index] / 10.0;
#ifdef debug
cerr << "\t\tBase log10 probability from quality: " << p << endl;
#endif
for (auto it = disrupt_begin; it != disrupt_end; ++it) {
// For each minimizer to disrupt
auto m = minimizers[*it];
#ifdef debug
cerr << "\t\tRelative rank " << (it - disrupt_begin) << " is minimizer " << m.value.key.decode(m.length) << endl;
#endif
if (!(m.forward_offset() <= index && index < m.forward_offset() + m.length)) {
// Index is out of range of the minimizer itself. We're in the flank.
#ifdef debug
cerr << "\t\t\tColumn " << index << " is in flank." << endl;
#endif
// How many new possible minimizers would an error here create in this agglomeration,
// to compete with its minimizer?
// No more than one per position in a minimizer sequence.
// No more than 1 per base from the start of the agglomeration to here, inclusive.
// No more than 1 per base from here to the last base of the agglomeration, inclusive.
size_t possible_minimizers = min((size_t) m.length,
min(index - m.agglomeration_start + 1,
(m.agglomeration_start + m.agglomeration_length) - index));
// Account for at least one of them beating the minimizer.
double any_beat_phred = phred_for_at_least_one(m.value.hash, possible_minimizers);
// Make sure to convert to log10 probability
double any_beat_log10_prob = -any_beat_phred / 10;
#ifdef debug
cerr << "\t\t\tBeat hash " << m.value.hash << " at least 1 time in " << possible_minimizers << " gives log10 probability: " << any_beat_log10_prob << endl;
#endif
p += any_beat_log10_prob;
// TODO: handle N somehow??? It can occur outside the minimizer itself, here in the flank.
}
#ifdef debug
cerr << "\t\t\tRunning AND log10 prob: " << p << endl;
#endif
}
return p;
}
//-----------------------------------------------------------------------------
void MinimizerMapper::attempt_rescue(const Alignment& aligned_read, Alignment& rescued_alignment, const std::vector<Minimizer>& minimizers, bool rescue_forward ) {
if (this->rescue_algorithm == rescue_none) { return; }
// We are traversing the same small subgraph repeatedly, so it's better to use a cache.
gbwtgraph::CachedGBWTGraph cached_graph(this->gbwt_graph);
// Find all nodes within a reasonable range from aligned_read.
std::unordered_set<id_t> rescue_nodes;
int64_t min_distance = max(0.0, fragment_length_distr.mean() - rescued_alignment.sequence().size() - rescue_subgraph_stdevs * fragment_length_distr.std_dev());
int64_t max_distance = fragment_length_distr.mean() + rescue_subgraph_stdevs * fragment_length_distr.std_dev();
distance_index.subgraph_in_range(aligned_read.path(), &cached_graph, min_distance, max_distance, rescue_nodes, rescue_forward);
// Remove node ids that do not exist in the GBWTGraph from the subgraph.
// We may be using the distance index of the original graph, and nodes
// not visited by any thread are missing from the GBWTGraph.
for (auto iter = rescue_nodes.begin(); iter != rescue_nodes.end(); ) {
if (!cached_graph.has_node(*iter)) {
iter = rescue_nodes.erase(iter);
} else {
++iter;
}
}
// Get rid of the old path.
rescued_alignment.clear_path();
// Find all seeds in the subgraph and try to get a full-length extension.
GaplessExtender::cluster_type seeds = this->seeds_in_subgraph(minimizers, rescue_nodes);
std::vector<GaplessExtension> extensions = this->extender.extend(seeds, rescued_alignment.sequence(), &cached_graph);
size_t best = extensions.size();
for (size_t i = 0; i < extensions.size(); i++) {
if (best >= extensions.size() || extensions[i].score > extensions[best].score) {
best = i;
}
}
// If we have a full-length extension, use it as the rescued alignment.
if (best < extensions.size() && extensions[best].full()) {
this->extension_to_alignment(extensions[best], rescued_alignment);
return;
}
// The haplotype-based algorithm is a special case.
if (this->rescue_algorithm == rescue_haplotypes) {
// Find and unfold the local haplotypes in the subgraph.
std::vector<std::vector<handle_t>> haplotype_paths;
bdsg::HashGraph align_graph;
this->extender.unfold_haplotypes(rescue_nodes, haplotype_paths, align_graph);
// Align to the subgraph.
this->get_regular_aligner()->align_xdrop(rescued_alignment, align_graph,
std::vector<MaximalExactMatch>(), false);
this->fix_dozeu_score(rescued_alignment, align_graph, std::vector<handle_t>());
// Get the corresponding alignment to the original graph.
this->extender.transform_alignment(rescued_alignment, haplotype_paths);
return;
}
// Use the best extension as a seed for dozeu.
// Also ensure that the entire extension is in the subgraph.
std::vector<MaximalExactMatch> dozeu_seed;
if (best < extensions.size()) {
const GaplessExtension& extension = extensions[best];
for (handle_t handle : extension.path) {
rescue_nodes.insert(cached_graph.get_id(handle));
}
dozeu_seed.emplace_back();
dozeu_seed.back().begin = rescued_alignment.sequence().begin() + extension.read_interval.first;
dozeu_seed.back().end = rescued_alignment.sequence().begin() + extension.read_interval.second;
nid_t id = cached_graph.get_id(extension.path.front());
bool is_reverse = cached_graph.get_is_reverse(extension.path.front());
gcsa::node_type node = gcsa::Node::encode(id, extension.offset, is_reverse);
dozeu_seed.back().nodes.push_back(node);
}
// GSSW and dozeu assume that the graph is a DAG.
std::vector<handle_t> topological_order = gbwtgraph::topological_order(cached_graph, rescue_nodes);
if (!topological_order.empty()) {
if (rescue_algorithm == rescue_dozeu) {
get_regular_aligner()->align_xdrop(rescued_alignment, cached_graph, topological_order,
dozeu_seed, false);
this->fix_dozeu_score(rescued_alignment, cached_graph, topological_order);
} else {
get_regular_aligner()->align(rescued_alignment, cached_graph, topological_order);
}
return;
}
// Build a subgraph overlay.
SubHandleGraph sub_graph(&cached_graph);
for (id_t id : rescue_nodes) {
sub_graph.add_handle(cached_graph.get_handle(id));
}
// Create an overlay where each strand is a separate node.
StrandSplitGraph split_graph(&sub_graph);
// Dagify the subgraph.
bdsg::HashGraph dagified;
std::unordered_map<id_t, id_t> dagify_trans =
algorithms::dagify(&split_graph, &dagified, rescued_alignment.sequence().size());
// Align to the subgraph.
// TODO: Map the seed to the dagified subgraph.
if (this->rescue_algorithm == rescue_dozeu) {
get_regular_aligner()->align_xdrop(rescued_alignment, dagified, std::vector<MaximalExactMatch>(), false);
this->fix_dozeu_score(rescued_alignment, dagified, std::vector<handle_t>());
} else if (this->rescue_algorithm == rescue_gssw) {
get_regular_aligner()->align(rescued_alignment, dagified, true);
}
// Map the alignment back to the original graph.
Path& path = *(rescued_alignment.mutable_path());
for (size_t i = 0; i < path.mapping_size(); i++) {
Position& pos = *(path.mutable_mapping(i)->mutable_position());
id_t id = dagify_trans[pos.node_id()];
handle_t handle = split_graph.get_underlying_handle(split_graph.get_handle(id));
pos.set_node_id(sub_graph.get_id(handle));
pos.set_is_reverse(sub_graph.get_is_reverse(handle));
}
}
GaplessExtender::cluster_type MinimizerMapper::seeds_in_subgraph(const std::vector<Minimizer>& minimizers,
const std::unordered_set<id_t>& subgraph) const {
std::vector<id_t> sorted_ids(subgraph.begin(), subgraph.end());
std::sort(sorted_ids.begin(), sorted_ids.end());
GaplessExtender::cluster_type result;
for (const Minimizer& minimizer : minimizers) {
gbwtgraph::hits_in_subgraph(minimizer.hits, minimizer.occs, sorted_ids, [&](pos_t pos, gbwtgraph::payload_type) {
if (minimizer.value.is_reverse) {
size_t node_length = this->gbwt_graph.get_length(this->gbwt_graph.get_handle(id(pos)));
pos = reverse_base_pos(pos, node_length);
}
result.insert(GaplessExtender::to_seed(pos, minimizer.value.offset));
});
}
return result;
}
void MinimizerMapper::fix_dozeu_score(Alignment& rescued_alignment, const HandleGraph& rescue_graph,
const std::vector<handle_t>& topological_order) const {
const Aligner* aligner = this->get_regular_aligner();
int32_t score = aligner->score_ungapped_alignment(rescued_alignment);
if (score > 0) {
rescued_alignment.set_score(score);
} else {
rescued_alignment.clear_path();
if (topological_order.empty()) {
aligner->align(rescued_alignment, rescue_graph, true);
} else {
aligner->align(rescued_alignment, rescue_graph, topological_order);
}
}
}
//-----------------------------------------------------------------------------
int64_t MinimizerMapper::distance_between(const Alignment& aln1, const Alignment& aln2) {
assert(aln1.path().mapping_size() != 0);
assert(aln2.path().mapping_size() != 0);
pos_t pos1 = initial_position(aln1.path());
pos_t pos2 = final_position(aln2.path());
int64_t min_dist = distance_index.min_distance(pos1, pos2);
return min_dist == -1 ? numeric_limits<int64_t>::max() : min_dist;
}
void MinimizerMapper::extension_to_alignment(const GaplessExtension& extension, Alignment& alignment) const {
*(alignment.mutable_path()) = extension.to_path(this->gbwt_graph, alignment.sequence());
alignment.set_score(extension.score);
double identity = 0.0;
if (!alignment.sequence().empty()) {
size_t len = alignment.sequence().length();
identity = (len - extension.mismatches()) / static_cast<double>(len);
}
alignment.set_identity(identity);
}
//-----------------------------------------------------------------------------
std::vector<MinimizerMapper::Minimizer> MinimizerMapper::find_minimizers(const std::string& sequence, Funnel& funnel) const {
if (this->track_provenance) {
// Start the minimizer finding stage
funnel.stage("minimizer");
}
std::vector<Minimizer> result;
double base_score = 1.0 + std::log(this->hard_hit_cap);
for (size_t i = 0; i < this->minimizer_indexes.size(); i++) {
// Get minimizers and their window agglomeration starts and lengths
vector<tuple<gbwtgraph::DefaultMinimizerIndex::minimizer_type, size_t, size_t>> current_minimizers =
minimizer_indexes[i]->minimizer_regions(sequence);
for (auto& m : current_minimizers) {
double score = 0.0;
auto hits = this->minimizer_indexes[i]->count_and_find(get<0>(m));
if (hits.first > 0) {
if (hits.first <= this->hard_hit_cap) {
score = base_score - std::log(hits.first);
} else {
score = 1.0;
}
}
result.push_back({ std::get<0>(m), std::get<1>(m), std::get<2>(m), hits.first, hits.second,
(int32_t) minimizer_indexes[i]->k(), (int32_t) minimizer_indexes[i]->w(), score });
}
}
std::sort(result.begin(), result.end());
if (this->track_provenance) {
// Record how many we found, as new lines.
funnel.introduce(result.size());
}
return result;
}
std::vector<MinimizerMapper::Seed> MinimizerMapper::find_seeds(const std::vector<Minimizer>& minimizers, const Alignment& aln, Funnel& funnel) const {
if (this->track_provenance) {
// Start the minimizer locating stage
funnel.stage("seed");
}
// One of the filters accepts minimizers until selected_score reaches target_score.
double base_target_score = 0.0;
for (const Minimizer& minimizer : minimizers) {
base_target_score += minimizer.score;
}
double target_score = (base_target_score * this->minimizer_score_fraction) + 0.000001;
double selected_score = 0.0;
// In order to consistently take either all or none of the minimizers in
// the read with a particular sequence, we track whether we took the
// previous one.
bool took_last = false;
// Select the minimizers we use for seeds.
size_t rejected_count = 0;
std::vector<Seed> seeds;
// Flag whether each minimizer in the read was located or not, for MAPQ capping.
// We ignore minimizers with no hits (count them as not located), because
// they would have to be created in the read no matter where we say it came
// from, and because adding more of them should lower the MAPQ cap, whereas
// locating more of the minimizers that are present and letting them pass
// to the enxt stage should raise the cap.
for (size_t i = 0; i < minimizers.size(); i++) {
if (this->track_provenance) {
// Say we're working on it
funnel.processing_input(i);
}
// Select the minimizer if it is informative enough or if the total score
// of the selected minimizers is not high enough.
const Minimizer& minimizer = minimizers[i];
#ifdef debug
std::cerr << "Minimizer " << i << " = " << minimizer.value.key.decode(minimizer.length)
<< " has " << minimizer.hits << " hits" << std::endl;
#endif
if (minimizer.hits == 0) {
// A minimizer with no hits can't go on.
took_last = false;
// We do not treat it as located for MAPQ capping purposes.
if (this->track_provenance) {
funnel.fail("any-hits", i);
}
} else if (minimizer.hits <= this->hit_cap ||
(minimizer.hits <= this->hard_hit_cap && selected_score + minimizer.score <= target_score) ||
(took_last && i > 0 && minimizer.value.key == minimizers[i - 1].value.key)) {
// We should keep this minimizer instance because it is
// sufficiently rare, or we want it to make target_score, or it is
// the same sequence as the previous minimizer which we also took.
// Locate the hits.
for (size_t j = 0; j < minimizer.hits; j++) {
pos_t hit = gbwtgraph::Position::decode(minimizer.occs[j].pos);
// Reverse the hits for a reverse minimizer
if (minimizer.value.is_reverse) {
size_t node_length = this->gbwt_graph.get_length(this->gbwt_graph.get_handle(id(hit)));
hit = reverse_base_pos(hit, node_length);
}
// Extract component id and offset in the root chain, if we have them for this seed.
// TODO: Get all the seed values here
tuple<bool, size_t, size_t, bool, size_t, size_t, size_t, size_t, bool> chain_info
(false, MIPayload::NO_VALUE, MIPayload::NO_VALUE, false, MIPayload::NO_VALUE, MIPayload::NO_VALUE, MIPayload::NO_VALUE, MIPayload::NO_VALUE, false );
if (minimizer.occs[j].payload != MIPayload::NO_CODE) {
chain_info = MIPayload::decode(minimizer.occs[j].payload);
}
seeds.push_back({ hit, i, std::get<0>(chain_info), std::get<1>(chain_info), std::get<2>(chain_info),
std::get<3>(chain_info), std::get<4>(chain_info), std::get<5>(chain_info), std::get<6>(chain_info), std::get<7>(chain_info), std::get<8>(chain_info) });
}
if (!(took_last && i > 0 && minimizer.value.key == minimizers[i - 1].value.key)) {
// We did not also take a previous identical-sequence minimizer, so count this one towards the score.
selected_score += minimizer.score;
}
// Remember that we took this minimizer
took_last = true;
if (this->track_provenance) {
// Record in the funnel that this minimizer gave rise to these seeds.
funnel.pass("any-hits", i);
funnel.pass("hard-hit-cap", i);
funnel.pass("hit-cap||score-fraction", i, selected_score / base_target_score);
funnel.expand(i, minimizer.hits);
}
} else if (minimizer.hits <= this->hard_hit_cap) {
// Passed hard hit cap but failed score fraction/normal hit cap
took_last = false;
rejected_count++;
if (this->track_provenance) {
funnel.pass("any-hits", i);
funnel.pass("hard-hit-cap", i);
funnel.fail("hit-cap||score-fraction", i, (selected_score + minimizer.score) / base_target_score);
}
//Stop looking for more minimizers once we fail the score fraction
target_score = selected_score;
} else {
// Failed hard hit cap
took_last = false;
rejected_count++;
if (this->track_provenance) {
funnel.pass("any-hits", i);
funnel.fail("hard-hit-cap", i);
}
}
if (this->track_provenance) {
// Say we're done with this input item
funnel.processed_input();
}
}
if (this->track_provenance && this->track_correctness) {
// Tag seeds with correctness based on proximity along paths to the input read's refpos
funnel.substage("correct");
if (this->path_graph == nullptr) {
cerr << "error[vg::MinimizerMapper] Cannot use track_correctness with no XG index" << endl;
exit(1);
}
if (aln.refpos_size() != 0) {
// Take the first refpos as the true position.
auto& true_pos = aln.refpos(0);
for (size_t i = 0; i < seeds.size(); i++) {
// Find every seed's reference positions. This maps from path name to pairs of offset and orientation.
auto offsets = algorithms::nearest_offsets_in_paths(this->path_graph, seeds[i].pos, 100);
for (auto& hit_pos : offsets[this->path_graph->get_path_handle(true_pos.name())]) {
// Look at all the ones on the path the read's true position is on.
if (abs((int64_t)hit_pos.first - (int64_t) true_pos.offset()) < 200) {
// Call this seed hit close enough to be correct
funnel.tag_correct(i);
}
}
}
}
}
#ifdef debug
std::cerr << "Found " << seeds.size() << " seeds from " << (minimizers.size() - rejected_count) << " minimizers, rejected " << rejected_count << std::endl;
#endif
return seeds;
}
//-----------------------------------------------------------------------------
void MinimizerMapper::score_cluster(Cluster& cluster, size_t i, const std::vector<Minimizer>& minimizers, const std::vector<Seed>& seeds, size_t seq_length, Funnel& funnel) const {
if (this->track_provenance) {
// Say we're making it
funnel.producing_output(i);
}
// Initialize the values.
cluster.score = 0.0;
cluster.coverage = 0.0;
cluster.present = SmallBitset(minimizers.size());
// Determine the minimizers that are present in the cluster.
for (auto hit_index : cluster.seeds) {
cluster.present.insert(seeds[hit_index].source);
#ifdef debug
cerr << "Minimizer " << seeds[hit_index].source << " is present in cluster " << i << endl;
#endif
}
// Compute the score and cluster coverage.
sdsl::bit_vector covered(seq_length, 0);
for (size_t j = 0; j < minimizers.size(); j++) {
if (cluster.present.contains(j)) {
const Minimizer& minimizer = minimizers[j];
cluster.score += minimizer.score;
// The offset of a reverse minimizer is the endpoint of the kmer
size_t start_offset = minimizer.forward_offset();
size_t k = minimizer.length;
// Set the k bits starting at start_offset.
covered.set_int(start_offset, sdsl::bits::lo_set[k], k);
}
}
// Count up the covered positions and turn it into a fraction.
cluster.coverage = sdsl::util::cnt_one_bits(covered) / static_cast<double>(seq_length);
if (this->track_provenance) {
// Record the cluster in the funnel as a group of the size of the number of items.
funnel.merge_group(cluster.seeds.begin(), cluster.seeds.end());
funnel.score(funnel.latest(), cluster.score);
// Say we made it.
funnel.produced_output();
}
}
//-----------------------------------------------------------------------------
int MinimizerMapper::score_extension_group(const Alignment& aln, const vector<GaplessExtension>& extended_seeds,
int gap_open_penalty, int gap_extend_penalty) {
if (extended_seeds.empty()) {
// TODO: We should never see an empty group of extensions
return 0;
} else if (extended_seeds.front().full()) {
// These are length matches. We already have the score.
int best_score = 0;
for (auto& extension : extended_seeds) {
best_score = max(best_score, extension.score);
}
return best_score;
} else {
// This is a collection of one or more non-full-length extended seeds.
if (aln.sequence().size() == 0) {
// No score here
return 0;
}
// We use a sweep line algorithm to find relevant points along the read: extension starts or ends.
// This records the last base to be covered by the current sweep line.
int64_t sweep_line = 0;
// This records the first base not covered by the last sweep line.
int64_t last_sweep_line = 0;
// And we track the next unentered gapless extension
size_t unentered = 0;
// Extensions we are in are in this min-heap of past-end position and gapless extension number.
vector<pair<size_t, size_t>> end_heap;
// The heap uses this comparator
auto min_heap_on_first = [](const pair<size_t, size_t>& a, const pair<size_t, size_t>& b) {
// Return true if a must come later in the heap than b
return a.first > b.first;
};
// We track the best score for a chain reaching the position before this one and ending in a gap.
// We never let it go below 0.
// Will be 0 when there's no gap that can be open
int best_gap_score = 0;
// We track the score for the best chain ending with each gapless extension
vector<int> best_chain_score(extended_seeds.size(), 0);
// And we're after the best score overall that we can reach when an extension ends
int best_past_ending_score_ever = 0;
// Overlaps are more complicated.
// We need a heap of all the extensions for which we have seen the
// start and that we can thus overlap.
// We filter things at the top of the heap if their past-end positions
// have occurred.
// So we store pairs of score we get backtracking to the current
// position, and past-end position for the thing we are backtracking
// from.
vector<pair<int, size_t>> overlap_heap;
// We can just use the standard max-heap comparator
// We encode the score relative to a counter that we increase by the
// gap extend every base we go through, so we don't need to update and
// re-sort the heap.
int overlap_score_offset = 0;
while(last_sweep_line <= aln.sequence().size()) {
// We are processed through the position before last_sweep_line.
// Find a place for sweep_line to go
// Find the next seed start
int64_t next_seed_start = numeric_limits<int64_t>::max();
if (unentered < extended_seeds.size()) {
next_seed_start = extended_seeds[unentered].read_interval.first;
}
// Find the next seed end
int64_t next_seed_end = numeric_limits<int64_t>::max();
if (!end_heap.empty()) {
next_seed_end = end_heap.front().first;
}
// Whichever is closer between those points and the end, do that.
sweep_line = min(min(next_seed_end, next_seed_start), (int64_t) aln.sequence().size());
// So now we're only interested in things that happen at sweep_line.
// Compute the distance from the previous sweep line position
// Make sure to account for last_sweep_line's semantics as the next unswept base.
int sweep_distance = sweep_line - last_sweep_line + 1;
// We need to track the score of the best thing that past-ended here
int best_past_ending_score_here = 0;
while(!end_heap.empty() && end_heap.front().first == sweep_line) {
// Find anything that past-ends here
size_t past_ending = end_heap.front().second;
// Mix it into the score
best_past_ending_score_here = std::max(best_past_ending_score_here, best_chain_score[past_ending]);
// Remove it from the end-tracking heap
std::pop_heap(end_heap.begin(), end_heap.end(), min_heap_on_first);
end_heap.pop_back();
}
// Mix that into the best score overall
best_past_ending_score_ever = std::max(best_past_ending_score_ever, best_past_ending_score_here);
if (sweep_line == aln.sequence().size()) {
// We don't need to think about gaps or backtracking anymore since everything has ended
break;
}
// Update the overlap score offset by removing some gap extends from it.
overlap_score_offset += sweep_distance * gap_extend_penalty;
// The best way to backtrack to here is whatever is on top of the heap, if anything, that doesn't past-end here.
int best_overlap_score = 0;
while (!overlap_heap.empty()) {
// While there is stuff on the heap
if (overlap_heap.front().second <= sweep_line) {
// We are already past this thing, so drop it
std::pop_heap(overlap_heap.begin(), overlap_heap.end());
overlap_heap.pop_back();
} else {
// This is at the top of the heap and we aren't past it
// Decode and use its score offset if we only backtrack to here.
best_overlap_score = overlap_heap.front().first + overlap_score_offset;
// Stop looking in the heap
break;
}
}
// The best way to end 1 before here in a gap is either:
if (best_gap_score != 0) {
// Best way to end 1 before our last sweep line position with a gap, plus distance times gap extend penalty
best_gap_score -= sweep_distance * gap_extend_penalty;
}
// Best way to end 1 before here with an actual extension, plus the gap open part of the gap open penalty.
// (Will never be taken over an actual adjacency)
best_gap_score = std::max(0, std::max(best_gap_score, best_past_ending_score_here - (gap_open_penalty - gap_extend_penalty)));
while (unentered < extended_seeds.size() && extended_seeds[unentered].read_interval.first == sweep_line) {
// For each thing that starts here
// Compute its chain score
best_chain_score[unentered] = std::max(best_overlap_score,
std::max(best_gap_score, best_past_ending_score_here)) + extended_seeds[unentered].score;
// Compute its backtrack-to-here score and add it to the backtracking heap
// We want how far we would have had to have backtracked to be
// able to preceed the base we are at now, where this thing
// starts.
size_t extension_length = extended_seeds[unentered].read_interval.second - extended_seeds[unentered].read_interval.first;
int raw_overlap_score = best_chain_score[unentered] - gap_open_penalty - gap_extend_penalty * extension_length;
int encoded_overlap_score = raw_overlap_score - overlap_score_offset;
// Stick it in the heap
overlap_heap.emplace_back(encoded_overlap_score, extended_seeds[unentered].read_interval.second);
std::push_heap(overlap_heap.begin(), overlap_heap.end());
// Add it to the end finding heap
end_heap.emplace_back(extended_seeds[unentered].read_interval.second, unentered);
std::push_heap(end_heap.begin(), end_heap.end(), min_heap_on_first);
// Advance and check the next thing to start
unentered++;
}
// Move last_sweep_line to sweep_line.
// We need to add 1 since last_sweep_line is the next *un*included base
last_sweep_line = sweep_line + 1;
}
// When we get here, we've seen the end of every extension and so we
// have the best score at the end of any of them.
return best_past_ending_score_ever;
}
}
std::vector<int> MinimizerMapper::score_extensions(const std::vector<std::vector<GaplessExtension>>& extensions, const Alignment& aln, Funnel& funnel) const {
// Extension scoring substage.
if (this->track_provenance) {
funnel.substage("score");
}
// We now estimate the best possible alignment score for each cluster.
std::vector<int> result(extensions.size(), 0);
for (size_t i = 0; i < extensions.size(); i++) {
if (this->track_provenance) {
funnel.producing_output(i);
}
result[i] = score_extension_group(aln, extensions[i], get_regular_aligner()->gap_open, get_regular_aligner()->gap_extension);
// Record the score with the funnel.
if (this->track_provenance) {
funnel.score(i, result[i]);
funnel.produced_output();
}
}
return result;
}
std::vector<int> MinimizerMapper::score_extensions(const std::vector<std::pair<std::vector<GaplessExtension>, size_t>>& extensions, const Alignment& aln, Funnel& funnel) const {
// Extension scoring substage.
if (this->track_provenance) {
funnel.substage("score");
}
// We now estimate the best possible alignment score for each cluster.
std::vector<int> result(extensions.size(), 0);
for (size_t i = 0; i < extensions.size(); i++) {
if (this->track_provenance) {
funnel.producing_output(i);
}
result[i] = score_extension_group(aln, extensions[i].first, get_regular_aligner()->gap_open, get_regular_aligner()->gap_extension);
// Record the score with the funnel.
if (this->track_provenance) {
funnel.score(i, result[i]);
funnel.produced_output();
}
}
return result;
}
//-----------------------------------------------------------------------------
void MinimizerMapper::find_optimal_tail_alignments(const Alignment& aln, const vector<GaplessExtension>& extended_seeds, Alignment& best, Alignment& second_best) const {
#ifdef debug
cerr << "Trying to find tail alignments for " << extended_seeds.size() << " extended seeds" << endl;
#endif
// Make paths for all the extensions
vector<Path> extension_paths;
vector<double> extension_path_scores;
extension_paths.reserve(extended_seeds.size());
extension_path_scores.reserve(extended_seeds.size());
for (auto& extended_seed : extended_seeds) {
// Compute the path for each extension
extension_paths.push_back(extended_seed.to_path(gbwt_graph, aln.sequence()));
// And the extension's score
extension_path_scores.push_back(get_regular_aligner()->score_partial_alignment(aln, gbwt_graph, extension_paths.back(),
aln.sequence().begin() + extended_seed.read_interval.first));
}
// We will keep the winning alignment here, in pieces
Path winning_left;
Path winning_middle;
Path winning_right;
size_t winning_score = 0;
Path second_left;
Path second_middle;
Path second_right;
size_t second_score = 0;
// Handle each extension in the set
process_until_threshold_b(extended_seeds, extension_path_scores,
extension_score_threshold, 1, max_local_extensions,
(function<double(size_t)>) [&](size_t extended_seed_num) {
// This extended seed looks good enough.
// TODO: We don't track this filter with the funnel because it
// operates within a single "item" (i.e. cluster/extension set).
// We track provenance at the item level, so throwing out wrong
// local alignments in a correct cluster would look like throwing
// out correct things.
// TODO: Revise how we track correctness and provenance to follow
// sub-cluster things.
// We start with the path in extension_paths[extended_seed_num],
// scored in extension_path_scores[extended_seed_num]
// We also have a left tail path and score
pair<Path, int64_t> left_tail_result {{}, 0};
// And a right tail path and score
pair<Path, int64_t> right_tail_result {{}, 0};
if (extended_seeds[extended_seed_num].read_interval.first != 0) {
// There is a left tail
// Get the forest of all left tail placements
auto forest = get_tail_forest(extended_seeds[extended_seed_num], aln.sequence().size(), true);
// Grab the part of the read sequence that comes before the extension
string before_sequence = aln.sequence().substr(0, extended_seeds[extended_seed_num].read_interval.first);
// Do right-pinned alignment
left_tail_result = std::move(get_best_alignment_against_any_tree(forest, before_sequence,
extended_seeds[extended_seed_num].starting_position(gbwt_graph), false));
}
if (extended_seeds[extended_seed_num].read_interval.second != aln.sequence().size()) {
// There is a right tail
// Get the forest of all right tail placements
auto forest = get_tail_forest(extended_seeds[extended_seed_num], aln.sequence().size(), false);
// Find the sequence
string trailing_sequence = aln.sequence().substr(extended_seeds[extended_seed_num].read_interval.second);
// Do left-pinned alignment
right_tail_result = std::move(get_best_alignment_against_any_tree(forest, trailing_sequence,
extended_seeds[extended_seed_num].tail_position(gbwt_graph), true));
}
// Compute total score
size_t total_score = extension_path_scores[extended_seed_num] + left_tail_result.second + right_tail_result.second;
//Get the node ids of the beginning and end of each alignment
id_t winning_start = winning_score == 0 ? 0 : (winning_left.mapping_size() == 0
? winning_middle.mapping(0).position().node_id()
: winning_left.mapping(0).position().node_id());
id_t current_start = left_tail_result.first.mapping_size() == 0
? extension_paths[extended_seed_num].mapping(0).position().node_id()
: left_tail_result.first.mapping(0).position().node_id();
id_t winning_end = winning_score == 0 ? 0 : (winning_right.mapping_size() == 0
? winning_middle.mapping(winning_middle.mapping_size() - 1).position().node_id()
: winning_right.mapping(winning_right.mapping_size()-1).position().node_id());
id_t current_end = right_tail_result.first.mapping_size() == 0
? extension_paths[extended_seed_num].mapping(extension_paths[extended_seed_num].mapping_size() - 1).position().node_id()
: right_tail_result.first.mapping(right_tail_result.first.mapping_size()-1).position().node_id();
//Is this left tail different from the currently winning left tail?
bool different_left = winning_start != current_start;
bool different_right = winning_end != current_end;
if (total_score > winning_score || winning_score == 0) {
// This is the new best alignment seen so far.
if (winning_score != 0 && different_left && different_right) {
//The previous best scoring alignment replaces the second best
second_score = winning_score;
second_left = std::move(winning_left);
second_middle = std::move(winning_middle);
second_right = std::move(winning_right);
}
// Save the score
winning_score = total_score;
// And the path parts
winning_left = std::move(left_tail_result.first);
winning_middle = std::move(extension_paths[extended_seed_num]);
winning_right = std::move(right_tail_result.first);
} else if ((total_score > second_score || second_score == 0) && different_left && different_right) {
// This is the new second best alignment seen so far and it is
// different from the best alignment.
// Save the score
second_score = total_score;
// And the path parts
second_left = std::move(left_tail_result.first);
second_middle = std::move(extension_paths[extended_seed_num]);
second_right = std::move(right_tail_result.first);
}
return true;
}, [&](size_t extended_seed_num) {
// This extended seed is good enough by its own score, but we have too many.
// Do nothing
}, [&](size_t extended_seed_num) {
// This extended seed isn't good enough by its own score.
// Do nothing
});
// Now we know the winning path and score. Move them over to out
best.set_score(winning_score);
second_best.set_score(second_score);
// Concatenate the paths. We know there must be at least an edit boundary
// between each part, because the maximal extension doesn't end in a
// mismatch or indel and eats all matches.
// We also don't need to worry about jumps that skip intervening sequence.
*best.mutable_path() = std::move(winning_left);
for (auto* to_append : {&winning_middle, &winning_right}) {
// For each path to append
for (auto& mapping : *to_append->mutable_mapping()) {
// For each mapping to append
if (mapping.position().offset() != 0 && best.path().mapping_size() > 0) {
// If we have a nonzero offset in our mapping, and we follow
// something, we must be continuing on from a previous mapping to
// the node.
assert(mapping.position().node_id() == best.path().mapping(best.path().mapping_size() - 1).position().node_id());
// Find that previous mapping
auto* prev_mapping = best.mutable_path()->mutable_mapping(best.path().mapping_size() - 1);
for (auto& edit : *mapping.mutable_edit()) {
// Move over all the edits in this mapping onto the end of that one.
*prev_mapping->add_edit() = std::move(edit);
}
} else {
// If we start at offset 0 or there's nothing before us, we need to just move the whole mapping
*best.mutable_path()->add_mapping() = std::move(mapping);
}
}
}
best.set_identity(identity(best.path()));
//Do the same for the second best
*second_best.mutable_path() = std::move(second_left);
for (auto* to_append : {&second_middle, &second_right}) {
// For each path to append
for (auto& mapping : *to_append->mutable_mapping()) {
// For each mapping to append
if (mapping.position().offset() != 0 && second_best.path().mapping_size() > 0) {
// If we have a nonzero offset in our mapping, and we follow
// something, we must be continuing on from a previous mapping to
// the node.
assert(mapping.position().node_id() == second_best.path().mapping(second_best.path().mapping_size() - 1).position().node_id());
// Find that previous mapping
auto* prev_mapping = second_best.mutable_path()->mutable_mapping(second_best.path().mapping_size() - 1);
for (auto& edit : *mapping.mutable_edit()) {
// Move over all the edits in this mapping onto the end of that one.
*prev_mapping->add_edit() = std::move(edit);
}
} else {
// If we start at offset 0 or there's nothing before us, we need to just move the whole mapping
*second_best.mutable_path()->add_mapping() = std::move(mapping);
}
}
}
// Compute the identity from the path.
second_best.set_identity(identity(second_best.path()));
}
pair<Path, size_t> MinimizerMapper::get_best_alignment_against_any_tree(const vector<TreeSubgraph>& trees,
const string& sequence, const Position& default_position, bool pin_left) const {
// We want the best alignment, to the base graph, done against any target path
Path best_path;
// And its score
int64_t best_score = 0;
if (!sequence.empty()) {
// We start out with the best alignment being a pure softclip.
// If we don't have any trees, or all trees are empty, or there's nothing beter, this is what we return.
Mapping* m = best_path.add_mapping();
Edit* e = m->add_edit();
e->set_from_length(0);
e->set_to_length(sequence.size());
e->set_sequence(sequence);
// Since the softclip consumes no graph, we place it on the node we are going to.
*m->mutable_position() = default_position;
#ifdef debug
cerr << "First best alignment: " << pb2json(best_path) << " score " << best_score << endl;
#endif
}
// We can align it once per target tree
for (auto& subgraph : trees) {
// For each tree we can map against, map pinning the correct edge of the sequence to the root.
if (subgraph.get_node_count() != 0) {
// This path has bases in it and could potentially be better than
// the default full-length softclip
// Do alignment to the subgraph with GSSWAligner.
Alignment current_alignment;
// If pinning right, we need to reverse the sequence, since we are
// always pinning left to the left edge of the tree subgraph.
current_alignment.set_sequence(pin_left ? sequence : reverse_complement(sequence));
#ifdef debug
cerr << "Align " << pb2json(current_alignment) << " pinned left";
#ifdef debug_dump_graph
cerr << " vs graph:" << endl;
subgraph.for_each_handle([&](const handle_t& here) {
cerr << subgraph.get_id(here) << " (" << subgraph.get_sequence(here) << "): " << endl;
subgraph.follow_edges(here, true, [&](const handle_t& there) {
cerr << "\t" << subgraph.get_id(there) << " (" << subgraph.get_sequence(there) << ") ->" << endl;
});
subgraph.follow_edges(here, false, [&](const handle_t& there) {
cerr << "\t-> " << subgraph.get_id(there) << " (" << subgraph.get_sequence(there) << ")" << endl;
});
});
#else
cerr << endl;
#endif
#endif
// X-drop align, accounting for full length bonus.
// We *always* do left-pinned alignment internally, since that's the shape of trees we get.
get_regular_aligner()->align_pinned(current_alignment, subgraph, true, true);
#ifdef debug
cerr << "\tScore: " << current_alignment.score() << endl;
#endif
if (current_alignment.score() > best_score) {
// This is a new best alignment.
best_path = current_alignment.path();
if (!pin_left) {
// Un-reverse it if we were pinning right
best_path = reverse_complement_path(best_path, [&](id_t node) {
return subgraph.get_length(subgraph.get_handle(node, false));
});
}
// Translate from subgraph into base graph and keep it.
best_path = subgraph.translate_down(best_path);
best_score = current_alignment.score();
#ifdef debug
cerr << "New best alignment is "
<< pb2json(best_path) << " score " << best_score << endl;
#endif
}
}
}
return make_pair(best_path, best_score);
}
vector<TreeSubgraph> MinimizerMapper::get_tail_forest(const GaplessExtension& extended_seed,
size_t read_length, bool left_tails) const {
// We will fill this in with all the trees we return
vector<TreeSubgraph> to_return;
// Now for this extension, walk the GBWT in the appropriate direction
#ifdef debug
cerr << "Look for " << (left_tails ? "left" : "right") << " tails from extension" << endl;
#endif
// TODO: Come up with a better way to do this with more accessors on the extension and less get_handle
// Get the Position reading out of the extension on the appropriate tail
Position from;
// And the length of that tail
size_t tail_length;
// And the GBWT search state we want to start with
const gbwt::SearchState* base_state = nullptr;
if (left_tails) {
// Look right from start
from = extended_seed.starting_position(gbwt_graph);
// And then flip to look the other way at the prev base
from = reverse(from, gbwt_graph.get_length(gbwt_graph.get_handle(from.node_id(), false)));
// Use the search state going backward
base_state = &extended_seed.state.backward;
tail_length = extended_seed.read_interval.first;
} else {
// Look right from end
from = extended_seed.tail_position(gbwt_graph);
// Use the search state going forward
base_state = &extended_seed.state.forward;
tail_length = read_length - extended_seed.read_interval.second;
}
if (tail_length == 0) {
// Don't go looking for places to put no tail.
return to_return;
}
// This is one tree that we are filling in
vector<pair<int64_t, handle_t>> tree;
// This is a stack of indexes at which we put parents in the tree
list<int64_t> parent_stack;
// Get the handle we are starting from
// TODO: is it cheaper to get this out of base_state?
handle_t start_handle = gbwt_graph.get_handle(from.node_id(), from.is_reverse());
// Decide if the start node will end up included in the tree, or if we cut it all off with the offset.
bool start_included = (from.offset() < gbwt_graph.get_length(start_handle));
// How long should we search? It should be the longest detectable gap plus the remaining sequence.
size_t search_limit = get_regular_aligner()->longest_detectable_gap(tail_length, read_length) + tail_length;
// Do a DFS over the haplotypes in the GBWT out to that distance.
dfs_gbwt(*base_state, from.offset(), search_limit, [&](const handle_t& entered) {
// Enter a new handle.
if (parent_stack.empty()) {
// This is the root of a new tree in the forrest
if (!tree.empty()) {
// Save the old tree and start a new one.
// We need to cut off from.offset() from the root, unless we would cut off the whole root.
// In that case, the GBWT DFS will have skipped the empty root entirely, so we cut off nothing.
to_return.emplace_back(&gbwt_graph, std::move(tree), start_included ? from.offset() : 0);
tree.clear();
}
// Add this to the tree with no parent
tree.emplace_back(-1, entered);
} else {
// Just say this is visitable from our parent.
tree.emplace_back(parent_stack.back(), entered);
}
// Record the parent index
parent_stack.push_back(tree.size() - 1);
}, [&]() {
// Exit the last visited handle. Pop off the stack.
parent_stack.pop_back();
});
if (!tree.empty()) {
// Now save the last tree
to_return.emplace_back(&gbwt_graph, std::move(tree), start_included ? from.offset() : 0);
tree.clear();
}
#ifdef debug
cerr << "Found " << to_return.size() << " trees" << endl;
#endif
// Now we have all the trees!
return to_return;
}
size_t MinimizerMapper::immutable_path_from_length(const ImmutablePath& path) {
size_t to_return = 0;
for (auto& m : path) {
// Sum up the from lengths of all the component Mappings
to_return += mapping_from_length(m);
}
return to_return;
}
Path MinimizerMapper::to_path(const ImmutablePath& path) {
Path to_return;
for (auto& m : path) {
// Copy all the Mappings into the Path.
*to_return.add_mapping() = m;
}
// Flip the order around to actual path order.
std::reverse(to_return.mutable_mapping()->begin(), to_return.mutable_mapping()->end());
// Return the completed path
return to_return;
}
void MinimizerMapper::dfs_gbwt(const Position& from, size_t walk_distance,
const function<void(const handle_t&)>& enter_handle, const function<void(void)> exit_handle) const {
// Get a handle to the node the from position is on, in the position's forward orientation
handle_t start_handle = gbwt_graph.get_handle(from.node_id(), from.is_reverse());
// Delegate to the handle-based version
dfs_gbwt(start_handle, from.offset(), walk_distance, enter_handle, exit_handle);
}
void MinimizerMapper::dfs_gbwt(handle_t from_handle, size_t from_offset, size_t walk_distance,
const function<void(const handle_t&)>& enter_handle, const function<void(void)> exit_handle) const {
// Turn from_handle into a SearchState for everything on it.
gbwt::SearchState start_state = gbwt_graph.get_state(from_handle);
// Delegate to the state-based version
dfs_gbwt(start_state, from_offset, walk_distance, enter_handle, exit_handle);
}
void MinimizerMapper::dfs_gbwt(const gbwt::SearchState& start_state, size_t from_offset, size_t walk_distance,
const function<void(const handle_t&)>& enter_handle, const function<void(void)> exit_handle) const {
// Holds the gbwt::SearchState we are at, and the distance we have consumed
using traversal_state_t = pair<gbwt::SearchState, size_t>;
if (start_state.empty()) {
// No haplotypes even visit the first node. Stop.
return;
}
// Get the handle we are starting on
handle_t from_handle = gbwt_graph.node_to_handle(start_state.node);
// The search state represents searching through the end of the node, so we have to consume that much search limit.
// Tack on how much search limit distance we consume by going to the end of
// the node. Our start position is a cut *between* bases, and we take everything after it.
// If the cut is at the offset of the whole length of the node, we take 0 bases.
// If it is at 0, we take all the bases in the node.
size_t distance_to_node_end = gbwt_graph.get_length(from_handle) - from_offset;
#ifdef debug
cerr << "DFS starting at offset " << from_offset << " on node of length "
<< gbwt_graph.get_length(from_handle) << " leaving " << distance_to_node_end << " bp" << endl;
#endif
// Have a recursive function that does the DFS. We fire the enter and exit
// callbacks, and the user can keep their own stack.
function<void(const gbwt::SearchState&, size_t, bool)> recursive_dfs = [&](const gbwt::SearchState& here_state,
size_t used_distance, bool hide_root) {
handle_t here_handle = gbwt_graph.node_to_handle(here_state.node);
if (!hide_root) {
// Enter this handle if there are any bases on it to visit
#ifdef debug
cerr << "Enter handle " << gbwt_graph.get_id(here_handle) << " " << gbwt_graph.get_is_reverse(here_handle) << endl;
#endif
enter_handle(here_handle);
}
// Up the used distance with our length
used_distance += gbwt_graph.get_length(here_handle);
if (used_distance < walk_distance) {
// If we haven't used up all our distance yet
gbwt_graph.follow_paths(here_state, [&](const gbwt::SearchState& there_state) -> bool {
// For each next state
// Otherwise, do it with the new distance value.
// Don't hide the root on any child subtrees; only the top root can need hiding.
recursive_dfs(there_state, used_distance, false);
return true;
});
}
if (!hide_root) {
// Exit this handle if we entered it
#ifdef debug
cerr << "Exit handle " << gbwt_graph.get_id(here_handle) << " " << gbwt_graph.get_is_reverse(here_handle) << endl;
#endif
exit_handle();
}
};
// Start the DFS with our stating node, consuming the distance from our
// offset to its end. Don't show the root state to the user if we don't
// actually visit any bases on that node.
recursive_dfs(start_state, distance_to_node_end, distance_to_node_end == 0);
}
}
Turn of printing minimizers
/**
* \file minimizer_mapper.cpp
* Defines the code for the minimizer-and-GBWT-based mapper.
*/
#include "minimizer_mapper.hpp"
#include "annotation.hpp"
#include "path_subgraph.hpp"
#include "multipath_alignment.hpp"
#include "split_strand_graph.hpp"
#include "algorithms/dagify.hpp"
#include "algorithms/dijkstra.hpp"
#include <bdsg/overlays/strand_split_overlay.hpp>
#include <gbwtgraph/algorithms.h>
#include <gbwtgraph/cached_gbwtgraph.h>
#include <iostream>
#include <algorithm>
#include <cmath>
//#define debug
//#define print_minimizers
namespace vg {
using namespace std;
MinimizerMapper::MinimizerMapper(const gbwtgraph::GBWTGraph& graph,
const std::vector<gbwtgraph::DefaultMinimizerIndex*>& minimizer_indexes,
MinimumDistanceIndex& distance_index, const PathPositionHandleGraph* path_graph) :
path_graph(path_graph), minimizer_indexes(minimizer_indexes),
distance_index(distance_index), gbwt_graph(graph),
extender(gbwt_graph, *(get_regular_aligner())), clusterer(distance_index),
fragment_length_distr(1000,1000,0.95) {
}
//-----------------------------------------------------------------------------
void MinimizerMapper::map(Alignment& aln, AlignmentEmitter& alignment_emitter) {
// Ship out all the aligned alignments
alignment_emitter.emit_mapped_single(map(aln));
}
vector<Alignment> MinimizerMapper::map(Alignment& aln) {
#ifdef debug
cerr << "Read " << aln.name() << ": " << aln.sequence() << endl;
#endif
#ifdef print_minimizers
cerr << aln.sequence() << "\t";
for (char c : aln.quality()) {
cerr << (char)(c+33);
}
#endif
// Make a new funnel instrumenter to watch us map this read.
Funnel funnel;
funnel.start(aln.name());
// Minimizers sorted by score in descending order.
std::vector<Minimizer> minimizers = this->find_minimizers(aln.sequence(), funnel);
// Find the seeds and mark the minimizers that were located.
std::vector<Seed> seeds = this->find_seeds(minimizers, aln, funnel);
// Cluster the seeds. Get sets of input seed indexes that go together.
if (track_provenance) {
funnel.stage("cluster");
}
std::vector<Cluster> clusters = clusterer.cluster_seeds(seeds, get_distance_limit(aln.sequence().size()));
// Determine the scores and read coverages for each cluster.
// Also find the best and second-best cluster scores.
if (this->track_provenance) {
funnel.substage("score");
}
double best_cluster_score = 0.0, second_best_cluster_score = 0.0;
for (size_t i = 0; i < clusters.size(); i++) {
Cluster& cluster = clusters[i];
this->score_cluster(cluster, i, minimizers, seeds, aln.sequence().length(), funnel);
if (cluster.score > best_cluster_score) {
second_best_cluster_score = best_cluster_score;
best_cluster_score = cluster.score;
} else if (cluster.score > second_best_cluster_score) {
second_best_cluster_score = cluster.score;
}
}
#ifdef debug
cerr << "Found " << clusters.size() << " clusters" << endl;
#endif
#ifdef print_minimizers
cerr << "\t" << clusters.size();
#endif
// We will set a score cutoff based on the best, but move it down to the
// second best if it does not include the second best and the second best
// is within pad_cluster_score_threshold of where the cutoff would
// otherwise be. This ensures that we won't throw away all but one cluster
// based on score alone, unless it is really bad.
double cluster_score_cutoff = best_cluster_score - cluster_score_threshold;
if (cluster_score_cutoff - pad_cluster_score_threshold < second_best_cluster_score) {
cluster_score_cutoff = std::min(cluster_score_cutoff, second_best_cluster_score);
}
if (track_provenance) {
// Now we go from clusters to gapless extensions
funnel.stage("extend");
}
// These are the GaplessExtensions for all the clusters.
vector<vector<GaplessExtension>> cluster_extensions;
cluster_extensions.reserve(clusters.size());
// To compute the windows for explored minimizers, we need to get
// all the minimizers that are explored.
SmallBitset minimizer_explored(minimizers.size());
//How many hits of each minimizer ended up in each extended cluster?
vector<vector<size_t>> minimizer_extended_cluster_count;
//For each cluster, what fraction of "equivalent" clusters did we keep?
vector<double> probability_cluster_lost;
//What is the score and coverage we are considering and how many reads
size_t curr_coverage = 0;
size_t curr_score = 0;
size_t curr_kept = 0;
size_t curr_count = 0;
// We track unextended clusters.
vector<size_t> unextended_clusters;
unextended_clusters.reserve(clusters.size());
//Process clusters sorted by both score and read coverage
process_until_threshold_c<Cluster, double>(clusters, [&](size_t i) -> double {
return clusters[i].coverage;
}, [&](size_t a, size_t b) -> bool {
return ((clusters[a].coverage > clusters[b].coverage) ||
(clusters[a].coverage == clusters[b].coverage && clusters[a].score > clusters[b].score));
},
cluster_coverage_threshold, 1, max_extensions,
[&](size_t cluster_num) {
// Handle sufficiently good clusters in descending coverage order
Cluster& cluster = clusters[cluster_num];
if (track_provenance) {
funnel.pass("cluster-coverage", cluster_num, cluster.coverage);
funnel.pass("max-extensions", cluster_num);
}
// First check against the additional score filter
if (cluster_score_threshold != 0 && cluster.score < cluster_score_cutoff) {
//If the score isn't good enough, ignore this cluster
if (track_provenance) {
funnel.fail("cluster-score", cluster_num, cluster.score);
}
// Record MAPQ implications of not extending this cluster.
unextended_clusters.push_back(cluster_num);
#ifdef debug
cerr << "Cluster " << cluster_num << " fails cluster score cutoff" << endl;
cerr << "Covers " << clusters[cluster_num].coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << clusters[cluster_num].score << "/" << cluster_score_cutoff << endl;
#endif
return false;
}
if (track_provenance) {
funnel.pass("cluster-score", cluster_num, cluster.score);
funnel.processing_input(cluster_num);
}
if (cluster.coverage == curr_coverage &&
cluster.score == curr_score &&
curr_kept < max_extensions * 0.75) {
curr_kept++;
curr_count++;
} else if (cluster.coverage != curr_coverage ||
cluster.score != curr_score) {
//If this is a cluster that has scores different than the previous one
for (size_t i = 0 ; i < curr_kept ; i++ ) {
probability_cluster_lost.push_back(1.0 - (double(curr_kept) / double(curr_count)));
}
curr_coverage = cluster.coverage;
curr_score = cluster.score;
curr_kept = 1;
curr_count = 1;
} else {
//If this cluster is equivalent to the previous one and we already took enough
//equivalent clusters
curr_count ++;
// TODO: shouldn't we fail something for the funnel here?
// Record MAPQ implications of not extending this cluster.
unextended_clusters.push_back(cluster_num);
#ifdef debug
cerr << "Cluster " << cluster_num << " fails because we took too many identical clusters" << endl;
cerr << "Covers " << clusters[cluster_num].coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << clusters[cluster_num].score << "/" << cluster_score_cutoff << endl;
#endif
return false;
}
//Only keep this cluster if we have few enough equivalent clusters
#ifdef debug
cerr << "Cluster " << cluster_num << endl;
cerr << "Covers " << cluster.coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << cluster.score << "/" << cluster_score_cutoff << endl;
#endif
minimizer_extended_cluster_count.emplace_back(minimizers.size(), 0);
// Pack the seeds for GaplessExtender.
GaplessExtender::cluster_type seed_matchings;
for (auto seed_index : cluster.seeds) {
// Insert the (graph position, read offset) pair.
const Seed& seed = seeds[seed_index];
seed_matchings.insert(GaplessExtender::to_seed(seed.pos, minimizers[seed.source].value.offset));
minimizer_extended_cluster_count.back()[seed.source]++;
#ifdef debug
const Minimizer& minimizer = minimizers[seed.source];
cerr << "Seed read:" << minimizer.value.offset << " = " << seed.pos
<< " from minimizer " << seed.source << "(" << minimizer.hits << ")" << endl;
#endif
}
// Extend seed hits in the cluster into one or more gapless extensions
cluster_extensions.emplace_back(std::move(extender.extend(seed_matchings, aln.sequence())));
if (track_provenance) {
// Record with the funnel that the previous group became a group of this size.
// Don't bother recording the seed to extension matching...
funnel.project_group(cluster_num, cluster_extensions.back().size());
// Say we finished with this cluster, for now.
funnel.processed_input();
}
return true;
}, [&](size_t cluster_num) {
// There are too many sufficiently good clusters
Cluster& cluster = clusters[cluster_num];
if (track_provenance) {
funnel.pass("cluster-coverage", cluster_num, cluster.coverage);
funnel.fail("max-extensions", cluster_num);
}
if (cluster.coverage == curr_coverage &&
cluster.score == curr_score) {
curr_count ++;
} else {
for (size_t i = 0 ; i < curr_kept ; i++ ) {
probability_cluster_lost.push_back(1.0 - (double(curr_kept) / double(curr_count)));
}
curr_score = 0;
curr_coverage = 0;
curr_kept = 0;
curr_count = 0;
}
// Record MAPQ implications of not extending this cluster.
unextended_clusters.push_back(cluster_num);
#ifdef debug
cerr << "Cluster " << cluster_num << " passes cluster cutoffs but we have too many" << endl;
cerr << "Covers " << cluster.coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << cluster.score << "/" << cluster_score_cutoff << endl;
#endif
}, [&](size_t cluster_num) {
// This cluster is not sufficiently good.
if (track_provenance) {
funnel.fail("cluster-coverage", cluster_num, clusters[cluster_num].coverage);
}
for (size_t i = 0 ; i < curr_kept ; i++ ) {
probability_cluster_lost.push_back(1.0 - (double(curr_kept) / double(curr_count)));
}
curr_kept = 0;
curr_count = 0;
curr_score = 0;
curr_coverage = 0;
// Record MAPQ implications of not extending this cluster.
unextended_clusters.push_back(cluster_num);
#ifdef debug
cerr << "Cluster " << cluster_num << " fails cluster coverage cutoffs" << endl;
cerr << "Covers " << clusters[cluster_num].coverage << "/best-" << cluster_coverage_threshold << " of read" << endl;
cerr << "Scores " << clusters[cluster_num].score << "/" << cluster_score_cutoff << endl;
#endif
});
for (size_t i = 0 ; i < curr_kept ; i++ ) {
probability_cluster_lost.push_back(1.0 - (double(curr_kept) / double(curr_count)));
}
std::vector<int> cluster_extension_scores = this->score_extensions(cluster_extensions, aln, funnel);
if (track_provenance) {
funnel.stage("align");
}
//How many of each minimizer ends up in an extension set that actually gets turned into an alignment?
vector<size_t> minimizer_extensions_count(minimizers.size(), 0);
// Now start the alignment step. Everything has to become an alignment.
// We will fill this with all computed alignments in estimated score order.
vector<Alignment> alignments;
alignments.reserve(cluster_extensions.size());
// This maps from alignment index back to cluster extension index, for
// tracing back to minimizers for MAPQ. Can hold
// numeric_limits<size_t>::max() for an unaligned alignment.
vector<size_t> alignments_to_source;
alignments_to_source.reserve(cluster_extensions.size());
//probability_cluster_lost but ordered by alignment
vector<double> probability_alignment_lost;
probability_alignment_lost.reserve(cluster_extensions.size());
// Create a new alignment object to get rid of old annotations.
{
Alignment temp;
temp.set_sequence(aln.sequence());
temp.set_name(aln.name());
temp.set_quality(aln.quality());
aln = std::move(temp);
}
// Annotate the read with metadata
if (!sample_name.empty()) {
aln.set_sample_name(sample_name);
}
if (!read_group.empty()) {
aln.set_read_group(read_group);
}
// Go through the gapless extension groups in score order.
process_until_threshold_b(cluster_extensions, cluster_extension_scores,
extension_set_score_threshold, 2, max_alignments,
[&](size_t extension_num) {
// This extension set is good enough.
// Called in descending score order.
if (track_provenance) {
funnel.pass("extension-set", extension_num, cluster_extension_scores[extension_num]);
funnel.pass("max-alignments", extension_num);
funnel.processing_input(extension_num);
}
auto& extensions = cluster_extensions[extension_num];
// Get an Alignments best_ and second_best_alignment of it somehow, and throw it in.
Alignment best_alignment = aln;
Alignment second_best_alignment = aln;
// Determine if we got full-length alignments or local alignments.
bool full_length_extensions = (extensions.size() <= 2);
for (auto& extension : extensions) {
full_length_extensions &= extension.full();
}
if (full_length_extensions) {
// We got full-length extensions, so directly convert to an Alignment.
if (track_provenance) {
funnel.substage("direct");
}
//Fill in the best alignments from the extension
this->extension_to_alignment(extensions.front(), best_alignment);
if (extensions.size() > 1) {
//Do the same thing for the second extension, if one exists
this->extension_to_alignment(extensions.back(), second_best_alignment);
}
if (track_provenance) {
// Stop the current substage
funnel.substage_stop();
}
} else if (do_dp) {
// We need to do chaining.
if (track_provenance) {
funnel.substage("chain");
}
// Do the DP and compute alignment into best_alignment and
// second_best_extension, if there is a second best
find_optimal_tail_alignments(aln, extensions, best_alignment, second_best_alignment);
if (track_provenance) {
// We're done chaining. Next alignment may not go through this substage.
funnel.substage_stop();
}
} else {
// We would do chaining but it is disabled.
// Leave best_alignment unaligned
}
if (second_best_alignment.score() != 0 &&
second_best_alignment.score() > best_alignment.score() * 0.8) {
//If there is a second extension and its score is at least half of the best score, bring it along
#ifdef debug
cerr << "Found second best alignment from gapless extension " << extension_num << ": " << pb2json(second_best_alignment) << endl;
#endif
alignments.emplace_back(std::move(second_best_alignment));
alignments_to_source.push_back(extension_num);
probability_alignment_lost.push_back(probability_cluster_lost[extension_num]);
if (track_provenance) {
funnel.project(extension_num);
funnel.score(alignments.size() - 1, alignments.back().score());
// We're done with this input item
funnel.processed_input();
}
}
#ifdef debug
cerr << "Found best alignment from gapless extension " << extension_num << ": " << pb2json(best_alignment) << endl;
#endif
alignments.push_back(std::move(best_alignment));
alignments_to_source.push_back(extension_num);
probability_alignment_lost.push_back(probability_cluster_lost[extension_num]);
if (track_provenance) {
funnel.project(extension_num);
funnel.score(alignments.size() - 1, alignments.back().score());
// We're done with this input item
funnel.processed_input();
}
for (size_t i = 0 ; i < minimizer_extended_cluster_count[extension_num].size() ; i++) {
minimizer_extensions_count[i] += minimizer_extended_cluster_count[extension_num][i];
if (minimizer_extended_cluster_count[extension_num][i] > 0) {
// This minimizer is in an extended cluster that gave rise
// to at least one alignment, so it is explored.
minimizer_explored.insert(i);
}
}
return true;
}, [&](size_t extension_num) {
// There are too many sufficiently good extensions
if (track_provenance) {
funnel.pass("extension-set", extension_num, cluster_extension_scores[extension_num]);
funnel.fail("max-alignments", extension_num);
}
#ifdef debug
cerr << "gapless extension " << extension_num << " failed because there were too many good extensions" << endl;
#endif
}, [&](size_t extension_num) {
// This extension is not good enough.
if (track_provenance) {
funnel.fail("extension-set", extension_num, cluster_extension_scores[extension_num]);
}
#ifdef debug
cerr << "gapless extension " << extension_num << " failed because its score was not good enough (score=" << cluster_extension_scores[extension_num] << ")" << endl;
#endif
});
if (alignments.size() == 0) {
// Produce an unaligned Alignment
alignments.emplace_back(aln);
alignments_to_source.push_back(numeric_limits<size_t>::max());
probability_alignment_lost.push_back(0);
if (track_provenance) {
// Say it came from nowhere
funnel.introduce();
}
}
if (track_provenance) {
// Now say we are finding the winner(s)
funnel.stage("winner");
}
// Fill this in with the alignments we will output as mappings
vector<Alignment> mappings;
mappings.reserve(min(alignments.size(), max_multimaps));
// Track which Alignments they are
vector<size_t> mappings_to_source;
mappings_to_source.reserve(min(alignments.size(), max_multimaps));
// Grab all the scores in order for MAPQ computation.
vector<double> scores;
scores.reserve(alignments.size());
vector<double> probability_mapping_lost;
process_until_threshold_a(alignments, (std::function<double(size_t)>) [&](size_t i) -> double {
return alignments.at(i).score();
}, 0, 1, max_multimaps, [&](size_t alignment_num) {
// This alignment makes it
// Called in score order
// Remember the score at its rank
scores.emplace_back(alignments[alignment_num].score());
// Remember the output alignment
mappings.emplace_back(std::move(alignments[alignment_num]));
mappings_to_source.push_back(alignment_num);
probability_mapping_lost.push_back(probability_alignment_lost[alignment_num]);
if (track_provenance) {
// Tell the funnel
funnel.pass("max-multimaps", alignment_num);
funnel.project(alignment_num);
funnel.score(alignment_num, scores.back());
}
return true;
}, [&](size_t alignment_num) {
// We already have enough alignments, although this one has a good score
// Remember the score at its rank anyway
scores.emplace_back(alignments[alignment_num].score());
if (track_provenance) {
funnel.fail("max-multimaps", alignment_num);
}
}, [&](size_t alignment_num) {
// This alignment does not have a sufficiently good score
// Score threshold is 0; this should never happen
assert(false);
});
if (track_provenance) {
funnel.substage("mapq");
}
#ifdef debug
cerr << "Picked best alignment " << pb2json(mappings[0]) << endl;
cerr << "For scores ";
for (auto& score : scores) cerr << score << " ";
#endif
size_t winning_index;
assert(!mappings.empty());
// Compute MAPQ if not unmapped. Otherwise use 0 instead of the 50% this would give us.
double mapq = (mappings.front().path().mapping_size() == 0) ? 0 :
get_regular_aligner()->maximum_mapping_quality_exact(scores, &winning_index) / 2;
#ifdef print_minimizers
double uncapped_mapq = mapq;
#endif
#ifdef debug
cerr << "uncapped MAPQ is " << mapq << endl;
#endif
if (probability_mapping_lost.front() > 0) {
mapq = min(mapq,round(prob_to_phred(probability_mapping_lost.front())));
}
// TODO: give SmallBitset iterators so we can use it instead of an index vector.
vector<size_t> explored_minimizers;
for (size_t i = 0; i < minimizers.size(); i++) {
if (minimizer_explored.contains(i)) {
explored_minimizers.push_back(i);
}
}
// Compute caps on MAPQ. TODO: avoid needing to pass as much stuff along.
double mapq_explored_cap = 2 * faster_cap(minimizers, explored_minimizers, aln.sequence(), aln.quality());
// Remember the uncapped MAPQ and the caps
set_annotation(mappings.front(), "mapq_uncapped", mapq);
set_annotation(mappings.front(), "mapq_explored_cap", mapq_explored_cap);
// Apply the caps and transformations
mapq = round(0.85 * min(mapq_explored_cap, min(mapq, 70.0)));
#ifdef debug
cerr << "Explored cap is " << mapq_explored_cap << endl;
cerr << "MAPQ is " << mapq << endl;
#endif
// Make sure to clamp 0-60.
mappings.front().set_mapping_quality(max(min(mapq, 60.0), 0.0));
if (track_provenance) {
funnel.substage_stop();
}
for (size_t i = 0; i < mappings.size(); i++) {
// For each output alignment in score order
auto& out = mappings[i];
// Assign primary and secondary status
out.set_is_secondary(i > 0);
}
// Stop this alignment
funnel.stop();
if (track_provenance) {
// Annotate with the number of results in play at each stage
funnel.for_each_stage([&](const string& stage, const vector<size_t>& result_sizes) {
// Save the number of items
set_annotation(mappings[0], "stage_" + stage + "_results", (double)result_sizes.size());
});
if (track_correctness) {
// And with the last stage at which we had any descendants of the correct seed hit locations
set_annotation(mappings[0], "last_correct_stage", funnel.last_correct_stage());
}
// Annotate with the performances of all the filters
// We need to track filter number
size_t filter_num = 0;
funnel.for_each_filter([&](const string& stage, const string& filter,
const Funnel::FilterPerformance& by_count, const Funnel::FilterPerformance& by_size,
const vector<double>& filter_statistics_correct, const vector<double>& filter_statistics_non_correct) {
string filter_id = to_string(filter_num) + "_" + filter + "_" + stage;
// Save the stats
set_annotation(mappings[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(mappings[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(mappings[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(mappings[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(mappings[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(mappings[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(mappings[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(mappings[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(mappings[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(mappings[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
filter_num++;
});
// Annotate with parameters used for the filters.
set_annotation(mappings[0], "param_hit-cap", (double) hit_cap);
set_annotation(mappings[0], "param_hard-hit-cap", (double) hard_hit_cap);
set_annotation(mappings[0], "param_score-fraction", (double) minimizer_score_fraction);
set_annotation(mappings[0], "param_max-extensions", (double) max_extensions);
set_annotation(mappings[0], "param_max-alignments", (double) max_alignments);
set_annotation(mappings[0], "param_cluster-score", (double) cluster_score_threshold);
set_annotation(mappings[0], "param_cluster-coverage", (double) cluster_coverage_threshold);
set_annotation(mappings[0], "param_extension-set", (double) extension_set_score_threshold);
set_annotation(mappings[0], "param_max-multimaps", (double) max_multimaps);
}
#ifdef print_minimizers
for (size_t i = 0 ; i < minimizers.size() ; i++) {
auto& minimizer = minimizers[i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_extensions_count[i];
if (minimizer_extensions_count[i]>0) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << uncapped_mapq << "\t" << mapq_explored_cap << "\t" << probability_mapping_lost.front();
if (track_correctness) {
cerr << "\t" << funnel.last_correct_stage() << endl;
} else {
cerr << endl;
}
#endif
#ifdef debug
// Dump the funnel info graph.
funnel.to_dot(cerr);
#endif
return mappings;
}
//-----------------------------------------------------------------------------
pair<vector<Alignment>, vector<Alignment>> MinimizerMapper::map_paired(Alignment& aln1, Alignment& aln2,
vector<pair<Alignment, Alignment>>& ambiguous_pair_buffer){
if (fragment_length_distr.is_finalized()) {
//If we know the fragment length distribution then we just map paired ended
return map_paired(aln1, aln2);
} else {
//If we don't know the fragment length distribution, map the reads single ended
vector<Alignment> alns1(map(aln1));
vector<Alignment> alns2(map(aln2));
// Check if the separately-mapped ends are both sufficiently perfect and sufficiently unique
int32_t max_score_aln_1 = get_regular_aligner()->score_exact_match(aln1, 0, aln1.sequence().size());
int32_t max_score_aln_2 = get_regular_aligner()->score_exact_match(aln2, 0, aln2.sequence().size());
if (!alns1.empty() && ! alns2.empty() &&
alns1.front().mapping_quality() == 60 && alns2.front().mapping_quality() == 60 &&
alns1.front().score() >= max_score_aln_1 * 0.85 && alns2.front().score() >= max_score_aln_2 * 0.85) {
//Flip the second alignment to get the proper fragment distance
reverse_complement_alignment_in_place(&alns2.front(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
int64_t dist = distance_between(alns1.front(), alns2.front());
// And that they have an actual pair distance and set of relative orientations
if (dist == std::numeric_limits<int64_t>::max()) {
//If the distance between them is ambiguous, leave them unmapped
ambiguous_pair_buffer.emplace_back(aln1, aln2);
pair<vector<Alignment>, vector<Alignment>> empty;
return empty;
}
//If we're keeping this alignment, flip the second alignment back
reverse_complement_alignment_in_place(&alns2.front(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
// If that all checks out, say they're mapped, emit them, and register their distance and orientations
fragment_length_distr.register_fragment_length(dist);
pair<vector<Alignment>, vector<Alignment>> mapped_pair;
mapped_pair.first.emplace_back(alns1.front());
mapped_pair.second.emplace_back(alns2.front());
return mapped_pair;
} else {
// Otherwise, discard the mappings and put them in the ambiguous buffer
ambiguous_pair_buffer.emplace_back(aln1, aln2);
pair<vector<Alignment>, vector<Alignment>> empty;
return empty;
}
}
}
pair<vector<Alignment>, vector< Alignment>> MinimizerMapper::map_paired(Alignment& aln1, Alignment& aln2) {
// For each input alignment
#ifdef debug
cerr << "Read pair " << aln1.name() << ": " << aln1.sequence() << " and " << aln2.name() << ": " << aln2.sequence() << endl;
#endif
// Assume reads are in inward orientations on input, and
// convert to rightward orientations before mapping
// and flip the second read back before output
aln2.clear_path();
reverse_complement_alignment_in_place(&aln2, [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
// Make two new funnel instrumenters to watch us map this read pair.
vector<Funnel> funnels;
funnels.resize(2);
// Start this alignment
funnels[0].start(aln1.name());
funnels[1].start(aln2.name());
// Annotate the original read with metadata
if (!sample_name.empty()) {
aln1.set_sample_name(sample_name);
aln2.set_sample_name(sample_name);
}
if (!read_group.empty()) {
aln1.set_read_group(read_group);
aln2.set_read_group(read_group);
}
// Minimizers for both reads, sorted by score in descending order.
std::vector<std::vector<Minimizer>> minimizers_by_read(2);
minimizers_by_read[0] = this->find_minimizers(aln1.sequence(), funnels[0]);
minimizers_by_read[1] = this->find_minimizers(aln2.sequence(), funnels[1]);
// Seeds for both reads, stored in separate vectors.
std::vector<std::vector<Seed>> seeds_by_read(2);
seeds_by_read[0] = this->find_seeds(minimizers_by_read[0], aln1, funnels[0]);
seeds_by_read[1] = this->find_seeds(minimizers_by_read[1], aln2, funnels[1]);
// Cluster the seeds. Get sets of input seed indexes that go together.
// If the fragment length distribution hasn't been fixed yet (if the expected fragment length = 0),
// then everything will be in the same cluster and the best pair will be the two best independent mappings
if (track_provenance) {
funnels[0].stage("cluster");
funnels[1].stage("cluster");
}
std::vector<std::vector<Cluster>> all_clusters = clusterer.cluster_seeds(seeds_by_read, get_distance_limit(aln1.sequence().size()),
fragment_length_distr.mean() + paired_distance_stdevs * fragment_length_distr.std_dev());
//For each fragment cluster, determine if it has clusters from both reads
size_t max_fragment_num = 0;
for (auto& cluster : all_clusters[0]) {
max_fragment_num = std::max(max_fragment_num, cluster.fragment);
}
for (auto& cluster : all_clusters[1]) {
max_fragment_num = std::max(max_fragment_num, cluster.fragment);
}
#ifdef debug
cerr << "Found " << max_fragment_num << " fragment clusters" << endl;
#endif
vector<bool> has_first_read (max_fragment_num+1, false);//For each fragment cluster, does it have a cluster for the first read
vector<bool> fragment_cluster_has_pair (max_fragment_num+1, false);//Does a fragment cluster have both reads
bool found_paired_cluster = false;
for (auto& cluster : all_clusters[0]) {
size_t fragment_num = cluster.fragment;
has_first_read[fragment_num] = true;
}
for (auto& cluster : all_clusters[1]) {
size_t fragment_num = cluster.fragment;
fragment_cluster_has_pair[fragment_num] = has_first_read[fragment_num];
if (has_first_read[fragment_num]) {
found_paired_cluster = true;
#ifdef debug
cerr << "Fragment cluster " << fragment_num << " has read clusters from both reads" << endl;
#endif
}
}
if (track_provenance) {
funnels[0].substage("score");
funnels[1].substage("score");
}
//For each fragment cluster (cluster of clusters), for each read, a vector of all alignments + the order they were fed into the funnel
//so the funnel can track them
vector<pair<vector<Alignment>, vector<Alignment>>> alignments;
vector<pair<vector<size_t>, vector<size_t>>> alignment_indices;
pair<int, int> best_alignment_scores (0, 0); // The best alignment score for each end
//Keep track of the best cluster score and coverage per end for each fragment cluster
pair<vector<double>, vector<double>> cluster_score_by_fragment;
cluster_score_by_fragment.first.resize(max_fragment_num + 1, 0.0);
cluster_score_by_fragment.second.resize(max_fragment_num + 1, 0.0);
pair<vector<double>, vector<double>> cluster_coverage_by_fragment;
cluster_coverage_by_fragment.first.resize(max_fragment_num + 1, 0.0);
cluster_coverage_by_fragment.second.resize(max_fragment_num + 1, 0.0);
for (size_t read_num = 0 ; read_num < 2 ; read_num++) {
Alignment& aln = read_num == 0 ? aln1 : aln2;
std::vector<Cluster>& clusters = all_clusters[read_num];
std::vector<Minimizer>& minimizers = minimizers_by_read[read_num];
std::vector<Seed>& seeds = seeds_by_read[read_num];
vector<double>& best_cluster_score = read_num == 0 ? cluster_score_by_fragment.first : cluster_score_by_fragment.second;
vector<double>& best_cluster_coverage = read_num == 0 ? cluster_coverage_by_fragment.first : cluster_coverage_by_fragment.second;
for (size_t i = 0; i < clusters.size(); i++) {
// Deterimine cluster score and read coverage.
Cluster& cluster = clusters[i];
this->score_cluster(cluster, i, minimizers, seeds, aln.sequence().length(), funnels[read_num]);
size_t fragment = cluster.fragment;
best_cluster_score[fragment] = std::max(best_cluster_score[fragment], cluster.score);
best_cluster_coverage[fragment] = std::max(best_cluster_coverage[fragment], cluster.coverage);
}
}
//For each fragment cluster, we want to know how many equivalent or better clusters we found
vector<size_t> fragment_cluster_indices_by_score (max_fragment_num + 1);
for (size_t i = 0 ; i < fragment_cluster_indices_by_score.size() ; i++) {
fragment_cluster_indices_by_score[i] = i;
}
std::sort(fragment_cluster_indices_by_score.begin(), fragment_cluster_indices_by_score.end(), [&](size_t a, size_t b) {
return cluster_coverage_by_fragment.first[a] + cluster_coverage_by_fragment.second[a] + cluster_score_by_fragment.first[a] + cluster_score_by_fragment.second[a]
> cluster_coverage_by_fragment.first[b] + cluster_coverage_by_fragment.second[b] + cluster_score_by_fragment.first[b] + cluster_score_by_fragment.second[b];
});
vector<size_t> better_cluster_count (max_fragment_num+1); // How many fragment clusters are at least as good as the one at each index
for (int j = fragment_cluster_indices_by_score.size() - 1 ; j >= 0 ; j--) {
size_t i = fragment_cluster_indices_by_score[j];
if (j == fragment_cluster_indices_by_score.size()-1) {
better_cluster_count[i] = j;
} else {
size_t i2 = fragment_cluster_indices_by_score[j+1];
if(cluster_coverage_by_fragment.first[i] + cluster_coverage_by_fragment.second[i] + cluster_score_by_fragment.first[i] + cluster_score_by_fragment.second[i]
== cluster_coverage_by_fragment.first[i2] + cluster_coverage_by_fragment.second[i2] + cluster_score_by_fragment.first[i2] + cluster_score_by_fragment.second[i2]) {
better_cluster_count[i] = better_cluster_count[i2];
} else {
better_cluster_count[i] = j;
}
}
}
// We track unextended clusters.
vector<vector<size_t>> unextended_clusters_by_read(2);
// To compute the windows that are explored, we need to get
// all the minimizers that are explored.
vector<SmallBitset> minimizer_explored_by_read(2);
//How many hits of each minimizer ended up in each extended cluster?
vector<vector<vector<size_t>>> minimizer_extended_cluster_count_by_read(2);
//Now that we've scored each of the clusters, extend and align them
for (size_t read_num = 0 ; read_num < 2 ; read_num++) {
Alignment& aln = read_num == 0 ? aln1 : aln2;
std::vector<Cluster>& clusters = all_clusters[read_num];
std::vector<Minimizer>& minimizers = minimizers_by_read[read_num];
std::vector<Seed>& seeds = seeds_by_read[read_num];
#ifdef debug
cerr << "Found " << clusters.size() << " clusters for read " << read_num << endl;
#endif
// Retain clusters only if their score is better than this, in addition to the coverage cutoff
double cluster_score_cutoff = 0.0, cluster_coverage_cutoff = 0.0;
for (auto& cluster : clusters) {
cluster_score_cutoff = std::max(cluster_score_cutoff, cluster.score);
cluster_coverage_cutoff = std::max(cluster_coverage_cutoff, cluster.coverage);
}
cluster_score_cutoff -= cluster_score_threshold;
cluster_coverage_cutoff -= cluster_coverage_threshold;
if (track_provenance) {
// Now we go from clusters to gapless extensions
funnels[read_num].stage("extend");
}
// These are the GaplessExtensions for all the clusters (and fragment cluster assignments), in cluster_indexes_in_order order.
vector<pair<vector<GaplessExtension>, size_t>> cluster_extensions;
cluster_extensions.reserve(clusters.size());
//TODO: Maybe put this back
//For each cluster, what fraction of "equivalent" clusters did we keep?
//vector<vector<double>> probability_cluster_lost;
//What is the score and coverage we are considering and how many reads
//size_t curr_coverage = 0;
//size_t curr_score = 0;
//size_t curr_kept = 0;
//size_t curr_count = 0;
unextended_clusters_by_read[read_num].reserve(clusters.size());
minimizer_explored_by_read[read_num] = SmallBitset(minimizers.size());
//Process clusters sorted by both score and read coverage
process_until_threshold_c<Cluster, double>(clusters, [&](size_t i) -> double {
return clusters[i].coverage;
}, [&](size_t a, size_t b) -> bool {
//Sort clusters first by whether it was paired, then by the best coverage and score of any pair in the fragment cluster,
//then by its coverage and score
size_t fragment_a = clusters[a].fragment;
size_t fragment_b = clusters[b].fragment;
double coverage_a = cluster_coverage_by_fragment.first[fragment_a]+cluster_coverage_by_fragment.second[fragment_a];
double coverage_b = cluster_coverage_by_fragment.first[fragment_b]+cluster_coverage_by_fragment.second[fragment_b];
double score_a = cluster_score_by_fragment.first[fragment_a]+cluster_score_by_fragment.second[fragment_a];
double score_b = cluster_score_by_fragment.first[fragment_b]+cluster_score_by_fragment.second[fragment_b];
if (fragment_cluster_has_pair[fragment_a] != fragment_cluster_has_pair[fragment_b]) {
return fragment_cluster_has_pair[fragment_a];
} else if (coverage_a != coverage_b){
return coverage_a > coverage_b;
} else if (score_a != score_b) {
return score_a > score_b;
} else if (clusters[a].coverage != clusters[b].coverage){
return clusters[a].coverage > clusters[b].coverage;
} else {
return clusters[a].score > clusters[b].score;
}
},
0, 1, max_extensions,
[&](size_t cluster_num) {
// Handle sufficiently good clusters
Cluster& cluster = clusters[cluster_num];
if (!found_paired_cluster || fragment_cluster_has_pair[cluster.fragment] ||
(cluster.coverage == cluster_coverage_cutoff + cluster_coverage_threshold &&
cluster.score == cluster_score_cutoff + cluster_score_threshold)) {
//If this cluster has a pair or if we aren't looking at pairs
//Or if it is the best cluster
// First check against the additional score filter
if (cluster_coverage_threshold != 0 && cluster.coverage < cluster_coverage_cutoff) {
//If the score isn't good enough, ignore this cluster
if (track_provenance) {
funnels[read_num].fail("cluster-coverage", cluster_num, cluster.coverage);
}
unextended_clusters_by_read[read_num].push_back(cluster_num);
return false;
}
if (cluster_score_threshold != 0 && cluster.score < cluster_score_cutoff) {
//If the score isn't good enough, ignore this cluster
if (track_provenance) {
funnels[read_num].pass("cluster-coverage", cluster_num, cluster.coverage);
funnels[read_num].pass("max-extensions", cluster_num);
funnels[read_num].fail("cluster-score", cluster_num, cluster.score);
}
unextended_clusters_by_read[read_num].push_back(cluster_num);
return false;
}
if (track_provenance) {
funnels[read_num].pass("cluster-coverage", cluster_num, cluster.coverage);
funnels[read_num].pass("max-extensions", cluster_num);
funnels[read_num].pass("cluster-score", cluster_num, cluster.score);
funnels[read_num].pass("paired-clusters", cluster_num);
funnels[read_num].processing_input(cluster_num);
}
#ifdef debug
cerr << "Cluster " << cluster_num << endl;
#endif
//Count how many of each minimizer is in each cluster extension
minimizer_extended_cluster_count_by_read[read_num].emplace_back(minimizers.size(), 0);
// Pack the seeds for GaplessExtender.
GaplessExtender::cluster_type seed_matchings;
for (auto seed_index : cluster.seeds) {
// Insert the (graph position, read offset) pair.
const Seed& seed = seeds[seed_index];
seed_matchings.insert(GaplessExtender::to_seed(seed.pos, minimizers[seed.source].value.offset));
minimizer_extended_cluster_count_by_read[read_num].back()[seed.source]++;
#ifdef debug
cerr << "Seed read:" << minimizers[seed.source].value.offset << " = " << seed.pos
<< " from minimizer " << seed.source << endl;
#endif
}
// Extend seed hits in the cluster into one or more gapless extensions
cluster_extensions.emplace_back(std::move(extender.extend(seed_matchings, aln.sequence())),
cluster.fragment);
if (track_provenance) {
// Record with the funnel that the previous group became a group of this size.
// Don't bother recording the seed to extension matching...
funnels[read_num].project_group(cluster_num, cluster_extensions.back().first.size());
// Say we finished with this cluster, for now.
funnels[read_num].processed_input();
}
return true;
} else {
//We were looking for clusters in a paired fragment cluster but this one doesn't have any on the other end
if (track_provenance) {
funnels[read_num].pass("cluster-coverage", cluster_num, cluster.coverage);
funnels[read_num].pass("max-extensions", cluster_num);
funnels[read_num].pass("cluster-score", cluster_num, cluster.score);
funnels[read_num].fail("paired-clusters", cluster_num);
}
unextended_clusters_by_read[read_num].push_back(cluster_num);
return false;
}
}, [&](size_t cluster_num) {
// There are too many sufficiently good clusters
if (track_provenance) {
funnels[read_num].pass("cluster-coverage", cluster_num, clusters[cluster_num].coverage);
funnels[read_num].fail("max-extensions", cluster_num);
}
unextended_clusters_by_read[read_num].push_back(cluster_num);
}, [&](size_t cluster_num) {
// This cluster is not sufficiently good.
// TODO: I don't think it should ever get here unless we limit the scores of the fragment clusters we look at
unextended_clusters_by_read[read_num].push_back(cluster_num);
});
// We now estimate the best possible alignment score for each cluster.
std::vector<int> cluster_extension_scores = this->score_extensions(cluster_extensions, aln, funnels[read_num]);
if (track_provenance) {
funnels[read_num].stage("align");
}
// Now start the alignment step. Everything has to become an alignment.
// We will fill this with all computed alignments in estimated score order.
alignments.resize(max_fragment_num + 2);
alignment_indices.resize(max_fragment_num + 2);
// Clear any old refpos annotation and path
aln.clear_refpos();
aln.clear_path();
aln.set_score(0);
aln.set_identity(0);
aln.set_mapping_quality(0);
//Since we will lose the order in which we pass alignments to the funnel, use this to keep track
size_t curr_funnel_index = 0;
// Go through the gapless extension groups in score order.
process_until_threshold_b(cluster_extensions, cluster_extension_scores,
extension_set_score_threshold, 2, max_alignments,
[&](size_t extension_num) {
// This extension set is good enough.
// Called in descending score order.
if (track_provenance) {
funnels[read_num].pass("extension-set", extension_num, cluster_extension_scores[extension_num]);
funnels[read_num].pass("max-alignments", extension_num);
funnels[read_num].processing_input(extension_num);
}
auto& extensions = cluster_extensions[extension_num].first;
// Get an Alignments best_ and second_best_alignment of it somehow, and throw it in.
Alignment best_alignment = aln;
Alignment second_best_alignment = aln;
// Determine if we got full-length alignments or local alignments.
bool full_length_extensions = (extensions.size() <= 2);
for (auto& extension : extensions) {
full_length_extensions &= extension.full();
}
if (full_length_extensions) {
// We got full-length extensions, so directly convert to an Alignment.
if (track_provenance) {
funnels[read_num].substage("direct");
}
//Fill in the best alignments from the extension
this->extension_to_alignment(extensions.front(), best_alignment);
if (extensions.size() > 1) {
//Do the same thing for the second extension, if one exists
this->extension_to_alignment(extensions.back(), second_best_alignment);
}
if (track_provenance) {
// Stop the current substage
funnels[read_num].substage_stop();
}
} else if (do_dp) {
// We need to do chaining.
if (track_provenance) {
funnels[read_num].substage("chain");
}
// Do the DP and compute alignment into best_alignment and
// second_best_alignment, if there is a second best
find_optimal_tail_alignments(aln, extensions, best_alignment, second_best_alignment);
if (track_provenance) {
// We're done chaining. Next alignment may not go through this substage.
funnels[read_num].substage_stop();
}
} else {
// We would do chaining but it is disabled.
// Leave best_alignment unaligned
}
size_t fragment_num = cluster_extensions[extension_num].second;
if (second_best_alignment.score() != 0 &&
second_best_alignment.score() > best_alignment.score() * 0.8) {
//If there is a second extension and its score is at least half of the best score
read_num == 0 ? best_alignment_scores.first = max(best_alignment_scores.first, second_best_alignment.score())
: best_alignment_scores.second = max(best_alignment_scores.second, second_best_alignment.score());
read_num == 0 ? alignments[fragment_num ].first.emplace_back(std::move(second_best_alignment) ) :
alignments[fragment_num ].second.emplace_back(std::move(second_best_alignment));
read_num == 0 ? alignment_indices[fragment_num].first.emplace_back(curr_funnel_index)
: alignment_indices[fragment_num].second.emplace_back(curr_funnel_index);
curr_funnel_index++;
if (track_provenance) {
funnels[read_num].project(extension_num);
read_num == 0 ? funnels[read_num].score(extension_num, alignments[fragment_num ].first.back().score()) :
funnels[read_num].score(extension_num, alignments[fragment_num].second.back().score());
}
}
read_num == 0 ? best_alignment_scores.first = max(best_alignment_scores.first, best_alignment.score())
: best_alignment_scores.second = max(best_alignment_scores.second, best_alignment.score());
read_num == 0 ? alignments[fragment_num].first.emplace_back(std::move(best_alignment))
: alignments[fragment_num].second.emplace_back(std::move(best_alignment));
read_num == 0 ? alignment_indices[fragment_num].first.emplace_back(curr_funnel_index)
: alignment_indices[fragment_num].second.emplace_back(curr_funnel_index);
curr_funnel_index++;
if (track_provenance) {
funnels[read_num].project(extension_num);
read_num == 0 ? funnels[read_num].score(extension_num, alignments[fragment_num].first.back().score())
: funnels[read_num].score(extension_num, alignments[fragment_num].second.back().score());
// We're done with this input item
funnels[read_num].processed_input();
}
for (size_t i = 0 ; i < minimizer_extended_cluster_count_by_read[read_num][extension_num].size() ; i++) {
if (minimizer_extended_cluster_count_by_read[read_num][extension_num][i] > 0) {
// This minimizer is in an extended cluster that gave rise
// to at least one alignment, so it is explored.
minimizer_explored_by_read[read_num].insert(i);
}
}
return true;
}, [&](size_t extension_num) {
// There are too many sufficiently good extensions
if (track_provenance) {
funnels[read_num].pass("extension-set", extension_num, cluster_extension_scores[extension_num]);
funnels[read_num].fail("max-alignments", extension_num);
}
}, [&](size_t extension_num) {
// This extension is not good enough.
if (track_provenance) {
funnels[read_num].fail("extension-set", extension_num, cluster_extension_scores[extension_num]);
}
});
}
if (track_provenance) {
// Now say we are finding the winner(s)
funnels[0].stage("pairing");
funnels[1].stage("pairing");
}
// Fill this in with the pairs of alignments we will output
// each alignment is stored as <fragment index, alignment index> into alignments
vector<pair<pair<size_t, size_t>, pair<size_t, size_t>>> paired_alignments;
paired_alignments.reserve(alignments.size());
#ifdef print_minimizers
vector<pair<bool, bool>> alignment_was_rescued;
#endif
//For each alignment in alignments, which paired_alignment includes it. Follows structure of alignments
vector<pair<vector<vector<size_t>>, vector<vector<size_t>>>> alignment_groups(alignments.size());
// Grab all the scores in order for MAPQ computation.
vector<double> paired_scores;
paired_scores.reserve(alignments.size());
vector<int64_t> fragment_distances;
fragment_distances.reserve(alignments.size());
//For each fragment cluster, get the fraction of equivalent or better clusters that got thrown away
vector<size_t> better_cluster_count_alignment_pairs;
better_cluster_count_alignment_pairs.reserve(alignments.size());
//Keep track of alignments with no pairs in the same fragment cluster
bool found_pair = false;
//Alignments that don't have a mate
// <fragment index, alignment_index, true if its the first end>
vector<tuple<size_t, size_t, bool>> unpaired_alignments;
size_t unpaired_count_1 = 0;
size_t unpaired_count_2 = 0;
for (size_t fragment_num = 0 ; fragment_num < alignments.size() ; fragment_num ++ ) {
//Get pairs of plausible alignments
alignment_groups[fragment_num].first.resize(alignments[fragment_num].first.size());
alignment_groups[fragment_num].second.resize(alignments[fragment_num].second.size());
pair<vector<Alignment>, vector<Alignment>>& fragment_alignments = alignments[fragment_num];
if (!fragment_alignments.first.empty() && ! fragment_alignments.second.empty()) {
//Only keep pairs of alignments that were in the same fragment cluster
found_pair = true;
for (size_t i1 = 0 ; i1 < fragment_alignments.first.size() ; i1++) {
Alignment& alignment1 = fragment_alignments.first[i1];
size_t j1 = alignment_indices[fragment_num].first[i1];
for (size_t i2 = 0 ; i2 < fragment_alignments.second.size() ; i2++) {
Alignment& alignment2 = fragment_alignments.second[i2];
size_t j2 = alignment_indices[fragment_num].second[i2];
//Get the likelihood of the fragment distance
int64_t fragment_distance = distance_between(alignment1, alignment2);
double dev = fragment_distance - fragment_length_distr.mean();
double fragment_length_log_likelihood = -dev * dev / (2.0 * fragment_length_distr.std_dev() * fragment_length_distr.std_dev());
if (fragment_distance != std::numeric_limits<int64_t>::max() ) {
double score = alignment1.score() + alignment2.score() + (fragment_length_log_likelihood / get_aligner()->log_base);
alignment_groups[fragment_num].first[i1].emplace_back(paired_alignments.size());
alignment_groups[fragment_num].second[i2].emplace_back(paired_alignments.size());
paired_alignments.emplace_back(make_pair(fragment_num, i1), make_pair(fragment_num, i2));
paired_scores.emplace_back(score);
fragment_distances.emplace_back(fragment_distance);
better_cluster_count_alignment_pairs.emplace_back(better_cluster_count[fragment_num]);
#ifdef print_minimizers
alignment_was_rescued.emplace_back(false, false);
#endif
#ifdef debug
cerr << "Found pair of alignments from fragment " << fragment_num << " with scores "
<< alignment1.score() << " " << alignment2.score() << " at distance " << fragment_distance
<< " gets pair score " << score << endl;
cerr << "Alignment 1: " << pb2json(alignment1) << endl << "Alignment 2: " << pb2json(alignment2) << endl;
#endif
}
if (track_provenance) {
funnels[0].processing_input(j1);
funnels[1].processing_input(j2);
funnels[0].substage("pair-clusters");
funnels[1].substage("pair-clusters");
funnels[0].pass("max-rescue-attempts", j1);
funnels[0].project(j1);
funnels[1].pass("max-rescue-attempts", j2);
funnels[1].project(j2);
funnels[0].substage_stop();
funnels[1].substage_stop();
funnels[0].processed_input();
funnels[1].processed_input();
}
}
}
} else if (!fragment_alignments.first.empty()) {
#ifdef debug
cerr << "Found unpaired alignments from fragment " << fragment_num << " for first read" << endl;
#endif
for (size_t i = 0 ; i < fragment_alignments.first.size() ; i++) {
unpaired_alignments.emplace_back(fragment_num, i, true);
unpaired_count_1++;
#ifdef debug
cerr << "\t" << pb2json(fragment_alignments.first[i]) << endl;
#endif
}
} else if (!fragment_alignments.second.empty()) {
#ifdef debug
cerr << "Found unpaired alignments from fragment " << fragment_num << " for second read" << endl;
#endif
for (size_t i = 0 ; i < fragment_alignments.second.size() ; i++) {
unpaired_alignments.emplace_back(fragment_num, i, false);
unpaired_count_2++;
#ifdef debug
cerr << "\t" << pb2json(fragment_alignments.second[i]) << endl;
#endif
}
}
}
size_t rescued_count_1 = 0;
size_t rescued_count_2 = 0;
vector<bool> rescued_from;
if (!unpaired_alignments.empty()) {
//If we found some clusters that don't belong to a fragment cluster
if (!found_pair && max_rescue_attempts == 0 ) {
//If we didn't find any pairs and we aren't attempting rescue, just return the best for each end
#ifdef debug
cerr << "Found no pairs and we aren't doing rescue: return best alignment for each read" << endl;
#endif
Alignment& best_aln1 = aln1;
Alignment& best_aln2 = aln2;
best_aln1.clear_refpos();
best_aln1.clear_path();
best_aln1.set_score(0);
best_aln1.set_identity(0);
best_aln1.set_mapping_quality(0);
best_aln2.clear_refpos();
best_aln2.clear_path();
best_aln2.set_score(0);
best_aln2.set_identity(0);
best_aln2.set_mapping_quality(0);
for (tuple<size_t, size_t, bool> index : unpaired_alignments ) {
Alignment& alignment = std::get<2>(index) ? alignments[std::get<0>(index)].first[std::get<1>(index)]
: alignments[std::get<0>(index)].second[std::get<1>(index)];
if (std::get<2>(index)) {
if (alignment.score() > best_aln1.score()) {
best_aln1 = alignment;
}
} else {
if (alignment.score() > best_aln2.score()) {
best_aln2 = alignment;
}
}
}
set_annotation(best_aln1, "unpaired", true);
set_annotation(best_aln2, "unpaired", true);
pair<vector<Alignment>, vector<Alignment>> paired_mappings;
paired_mappings.first.emplace_back(std::move(best_aln1));
paired_mappings.second.emplace_back(std::move(best_aln2));
// Flip aln2 back to input orientation
reverse_complement_alignment_in_place(&paired_mappings.second.back(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
paired_mappings.first.back().set_mapping_quality(1);
paired_mappings.second.back().set_mapping_quality(1);
// Stop this alignment
funnels[0].stop();
funnels[1].stop();
if (track_provenance) {
// Annotate with the number of results in play at each stage
for (size_t read_num = 0 ; read_num < 2 ; read_num++) {
funnels[read_num].for_each_stage([&](const string& stage, const vector<size_t>& result_sizes) {
// Save the number of items
set_annotation(read_num == 0 ? paired_mappings.first[0] : paired_mappings.second[0], "stage_" + stage + "_results", (double)result_sizes.size());
});
if (track_correctness) {
// And with the last stage at which we had any descendants of the correct seed hit locations
set_annotation(read_num == 0 ? paired_mappings.first[0] : paired_mappings.second[0], "last_correct_stage", funnels[read_num].last_correct_stage());
}
// Annotate with the performances of all the filters
// We need to track filter number
size_t filter_num = 0;
funnels[read_num].for_each_filter([&](const string& stage, const string& filter,
const Funnel::FilterPerformance& by_count, const Funnel::FilterPerformance& by_size,
const vector<double>& filter_statistics_correct, const vector<double>& filter_statistics_non_correct) {
string filter_id = to_string(filter_num) + "_" + filter + "_" + stage;
if (read_num == 0) {
// Save the stats
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(paired_mappings.first[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(paired_mappings.first[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(paired_mappings.first[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
} else {
// Save the stats
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(paired_mappings.second[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(paired_mappings.second[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(paired_mappings.second[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
}
filter_num++;
});
}
}
#ifdef print_minimizers
cerr << aln1.sequence() << "\t";
for (char c : aln1.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << all_clusters.size() << "\t" << 0 << "\t" << 0 << "\t?";
for (size_t i = 0 ; i < minimizers_by_read[0].size() ; i++) {
auto& minimizer = minimizers_by_read[0][i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_explored_by_read[0].contains(i);
if (minimizer_explored_by_read[0].contains(i)) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << 1 << "\t" << 1 << "\t" << 1 << "\t" << 1;
if (track_correctness) {
cerr << "\t" << funnels[0].last_correct_stage() << endl;
} else {
cerr << "\t?" << endl;
}
cerr << aln2.sequence() << "\t";
for (char c : aln2.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << all_clusters.size() << "\t" << 0 << "\t" << 0 << "\t?";
for (size_t i = 0 ; i < minimizers_by_read[1].size() ; i++) {
auto& minimizer = minimizers_by_read[1][i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_explored_by_read[0].contains(i);
if (minimizer_explored_by_read[0].contains(i)) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << 1 << "\t" << 1 << "\t" << 1 << "\t" << 1;
if (track_correctness) {
cerr << "\t" << funnels[1].last_correct_stage() << endl;
} else {
cerr << "\t?" << endl;
}
#endif
return paired_mappings;
} else {
//Attempt rescue on unpaired alignments if either we didn't find any pairs or if the unpaired alignments are very good
process_until_threshold_a(unpaired_alignments, (std::function<double(size_t)>) [&](size_t i) -> double{
tuple<size_t, size_t, bool> index = unpaired_alignments.at(i);
return (double) std::get<2>(index) ? alignments[std::get<0>(index)].first[std::get<1>(index)].score()
: alignments[std::get<0>(index)].second[std::get<1>(index)].score();
}, 0, 1, max_rescue_attempts, [&](size_t i) {
tuple<size_t, size_t, bool> index = unpaired_alignments.at(i);
bool found_first = std::get<2>(index);
size_t j = found_first ? alignment_indices[std::get<0>(index)].first[std::get<1>(index)]
: alignment_indices[std::get<0>(index)].second[std::get<1>(index)];
if (track_provenance) {
funnels[found_first ? 0 : 1].processing_input(j);
funnels[found_first ? 0 : 1].substage("rescue");
}
Alignment& mapped_aln = found_first ? alignments[std::get<0>(index)].first[std::get<1>(index)]
: alignments[std::get<0>(index)].second[std::get<1>(index)];
Alignment rescued_aln = found_first ? aln2 : aln1;
rescued_aln.clear_path();
if (found_pair && (double) mapped_aln.score() < (double) (found_first ? best_alignment_scores.first : best_alignment_scores.second) * paired_rescue_score_limit) {
//If we have already found paired clusters and this unpaired alignment is not good enough, do nothing
return true;
}
attempt_rescue(mapped_aln, rescued_aln, minimizers_by_read[(found_first ? 1 : 0)], found_first);
int64_t fragment_dist = found_first ? distance_between(mapped_aln, rescued_aln)
: distance_between(rescued_aln, mapped_aln);
if (fragment_dist != std::numeric_limits<int64_t>::max()) {
bool duplicated = false;
double dev = fragment_dist - fragment_length_distr.mean();
double fragment_length_log_likelihood = -dev * dev / (2.0 * fragment_length_distr.std_dev() * fragment_length_distr.std_dev());
double score = mapped_aln.score() + rescued_aln.score() + (fragment_length_log_likelihood / get_aligner()->log_base);
set_annotation(mapped_aln, "rescuer", true);
set_annotation(rescued_aln, "rescued", true);
set_annotation(mapped_aln, "fragment_length", (double)fragment_dist);
set_annotation(rescued_aln, "fragment_length", (double)fragment_dist);
pair<size_t, size_t> mapped_index (std::get<0>(index), std::get<1>(index));
pair<size_t, size_t> rescued_index (alignments.size() - 1,
found_first ? alignments.back().second.size() : alignments.back().first.size());
found_first ? alignments.back().second.emplace_back(std::move(rescued_aln))
: alignments.back().first.emplace_back(std::move(rescued_aln));
found_first ? rescued_count_1++ : rescued_count_2++;
found_first ? alignment_groups.back().second.emplace_back() : alignment_groups.back().first.emplace_back();
pair<pair<size_t, size_t>, pair<size_t, size_t>> index_pair = found_first ?
make_pair(mapped_index, rescued_index) : make_pair(rescued_index, mapped_index);
paired_alignments.push_back(index_pair);
paired_scores.emplace_back(score);
fragment_distances.emplace_back(fragment_dist);
better_cluster_count_alignment_pairs.emplace_back(0);
rescued_from.push_back(found_first);
#ifdef print_minimizers
alignment_was_rescued.emplace_back(!found_first, found_first);
#endif
if (track_provenance) {
funnels[found_first ? 0 : 1].pass("max-rescue-attempts", j);
funnels[found_first ? 0 : 1].project(j);
funnels[found_first ? 1 : 0].introduce();
}
}
if (track_provenance) {
funnels[found_first ? 0 : 1].processed_input();
funnels[found_first ? 0 : 1].substage_stop();
}
return true;
}, [&](size_t i) {
if (track_provenance) {
tuple<size_t, size_t, bool> index = unpaired_alignments.at(i);
bool found_first = std::get<2>(index);
size_t j = found_first ? alignment_indices[std::get<0>(index)].first[std::get<1>(index)]
: alignment_indices[std::get<0>(index)].second[std::get<1>(index)];
funnels[found_first ? 0 : 1].fail("max-rescue-attempts", j);
}
return;
}, [&] (size_t i) {
if (track_provenance) {
tuple<size_t, size_t, bool> index = unpaired_alignments.at(i);
bool found_first = std::get<2>(index);
size_t j = found_first ? alignment_indices[std::get<0>(index)].first[std::get<1>(index)]
: alignment_indices[std::get<0>(index)].second[std::get<1>(index)];
}
return;
});
}
}
if (track_provenance) {
// Now say we are finding the winner(s)
funnels[0].stage("winner");
funnels[1].stage("winner");
}
double estimated_multiplicity_from_1 = unpaired_count_1 > 0 ? (double) unpaired_count_1 / min(rescued_count_1, max_rescue_attempts) : 1.0;
double estimated_multiplicity_from_2 = unpaired_count_2 > 0 ? (double) unpaired_count_2 / min(rescued_count_2, max_rescue_attempts) : 1.0;
vector<double> paired_multiplicities;
for (bool rescued_from_first : rescued_from) {
paired_multiplicities.push_back(rescued_from_first ? estimated_multiplicity_from_1 : estimated_multiplicity_from_2);
}
// Fill this in with the alignments we will output
pair<vector<Alignment>, vector<Alignment>> mappings;
// Grab all the scores in order for MAPQ computation.
vector<double> scores;
vector<double> scores_group_1;
vector<double> scores_group_2;
vector<int64_t> distances;
mappings.first.reserve(paired_alignments.size());
mappings.second.reserve(paired_alignments.size());
scores.reserve(paired_scores.size());
distances.reserve(fragment_distances.size());
vector<size_t> better_cluster_count_mappings;
better_cluster_count_mappings.reserve(better_cluster_count_alignment_pairs.size());
#ifdef print_minimizers
vector<pair<bool, bool>> mapping_was_rescued;
#endif
process_until_threshold_a(paired_alignments, (std::function<double(size_t)>) [&](size_t i) -> double {
return paired_scores[i];
}, 0, 1, max_multimaps, [&](size_t alignment_num) {
// This alignment makes it
// Called in score order
pair<pair<size_t, size_t>, pair<size_t, size_t>> index_pair = paired_alignments[alignment_num];
// Remember the score at its rank
scores.emplace_back(paired_scores[alignment_num]);
distances.emplace_back(fragment_distances[alignment_num]);
// Remember the output alignment
mappings.first.emplace_back( alignments[index_pair.first.first].first[index_pair.first.second]);
mappings.second.emplace_back(alignments[index_pair.second.first].second[index_pair.second.second]);
better_cluster_count_mappings.emplace_back(better_cluster_count_alignment_pairs[alignment_num]);
if (mappings.first.size() == 1 && found_pair) {
//If this is the best pair of alignments that we're going to return and we didn't attempt rescue,
//get the group scores for mapq
//Get the scores of
scores_group_1.push_back(paired_scores[alignment_num]);
scores_group_2.push_back(paired_scores[alignment_num]);
//The indices (into paired_alignments) of pairs with the same first read as this
vector<size_t>& alignment_group_1 = alignment_groups[index_pair.first.first].first[index_pair.first.second];
vector<size_t>& alignment_group_2 = alignment_groups[index_pair.second.first].second[index_pair.second.second];
for (size_t other_alignment_num : alignment_group_1) {
if (other_alignment_num != alignment_num) {
scores_group_1.push_back(paired_scores[other_alignment_num]);
}
}
for (size_t other_alignment_num : alignment_group_2) {
if (other_alignment_num != alignment_num) {
scores_group_2.push_back(paired_scores[other_alignment_num]);
}
}
}
// Flip aln2 back to input orientation
reverse_complement_alignment_in_place(&mappings.second.back(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
if (mappings.first.size() > 1) {
mappings.first.back().set_is_secondary(true);
mappings.second.back().set_is_secondary(true);
}
#ifdef print_minimizers
mapping_was_rescued.emplace_back(alignment_was_rescued[alignment_num]);
#endif
if (track_provenance) {
// Tell the funnel
funnels[0].pass("max-multimaps", alignment_num);
funnels[0].project(alignment_num);
funnels[0].score(alignment_num, scores.back());
funnels[1].pass("max-multimaps", alignment_num);
funnels[1].project(alignment_num);
funnels[1].score(alignment_num, scores.back());
}
return true;
}, [&](size_t alignment_num) {
// We already have enough alignments, although this one has a good score
// Remember the score at its rank anyway
scores.emplace_back(paired_scores[alignment_num]);
distances.emplace_back(fragment_distances[alignment_num]);
if (track_provenance) {
funnels[0].fail("max-multimaps", alignment_num);
funnels[1].fail("max-multimaps", alignment_num);
}
}, [&](size_t alignment_num) {
// This alignment does not have a sufficiently good score
// Score threshold is 0; this should never happen
assert(false);
});
if (track_provenance) {
funnels[0].substage("mapq");
funnels[1].substage("mapq");
}
#ifdef print_minimizers
double uncapped_mapq = 0.0;
double fragment_cluster_cap = 0.0;
vector<double> mapq_extend_caps;
double mapq_score_group_1 = 0.0;
double mapq_score_group_2 = 0.0;
#endif
if (mappings.first.empty()) {
//If we didn't get an alignment, return empty alignments
mappings.first.emplace_back(aln1);
mappings.second.emplace_back(aln2);
// Flip aln2 back to input orientation
reverse_complement_alignment_in_place(&mappings.second.back(), [&](vg::id_t node_id) {
return gbwt_graph.get_length(gbwt_graph.get_handle(node_id));
});
mappings.first.back().clear_refpos();
mappings.first.back().clear_path();
mappings.first.back().set_score(0);
mappings.first.back().set_identity(0);
mappings.first.back().set_mapping_quality(0);
mappings.second.back().clear_refpos();
mappings.second.back().clear_path();
mappings.second.back().set_score(0);
mappings.second.back().set_identity(0);
mappings.second.back().set_mapping_quality(0);
#ifdef print_minimizers
mapping_was_rescued.emplace_back(false, false);
#endif
} else {
#ifdef debug
cerr << "For scores ";
for (auto& score : scores) cerr << score << " ";
#endif
size_t winning_index;
// Compute MAPQ if not unmapped. Otherwise use 0 instead of the 50% this would give us.
// If either of the mappings was duplicated in other pairs, use the group scores to determine mapq
const vector<double>* multiplicities = paired_multiplicities.size() == scores.size() ? &paired_multiplicities : nullptr;
// Compute MAPQ if not unmapped. Otherwise use 0 instead of the 50% this would give us.
// If either of the mappings was duplicated in other pairs, use the group scores to determine mapq
double mapq = scores[0] == 0 ? 0 :
get_regular_aligner()->maximum_mapping_quality_exact(scores, &winning_index, multiplicities) / 2;
#ifdef print_minimizers
uncapped_mapq = mapq;
#endif
//Cap mapq at 1 / # equivalent or better fragment clusters
if (better_cluster_count_mappings.size() != 0 && better_cluster_count_mappings.front() > 0) {
mapq = min(mapq,round(prob_to_phred((1.0 / (double) better_cluster_count_mappings.front()))));
}
#ifdef print_minimizers
if (better_cluster_count_mappings.size() != 0 && better_cluster_count_mappings.front() > 0) {
fragment_cluster_cap = round(prob_to_phred((1.0 / (double) better_cluster_count_mappings.front())));
}
#endif
//If one alignment was duplicated in other pairs, cap the mapq for that alignment at the mapq
//of the group of duplicated alignments
double mapq_group1 = scores_group_1.size() <= 1 ? mapq :
min(mapq, get_regular_aligner()->maximum_mapping_quality_exact(scores_group_1, &winning_index) / 2);
double mapq_group2 = scores_group_2.size() <= 1 ? mapq :
min(mapq, get_regular_aligner()->maximum_mapping_quality_exact(scores_group_2, &winning_index) / 2);
#ifdef print_minimizers
mapq_score_group_1 = scores_group_1.size() <= 1 ? 0.0 : get_regular_aligner()->maximum_mapping_quality_exact(scores_group_1, &winning_index);
mapq_score_group_2 = scores_group_2.size() <= 1 ? 0.0 : get_regular_aligner()->maximum_mapping_quality_exact(scores_group_2, &winning_index);
#endif
// Compute one MAPQ cap across all the fragments
double mapq_cap = -std::numeric_limits<float>::infinity();
for (auto read_num : {0, 1}) {
// For each fragment
// Find the source read
auto& aln = read_num == 0 ? aln1 : aln2;
vector<size_t> explored_minimizers;
for (size_t i = 0; i < minimizers_by_read[read_num].size(); i++) {
if (minimizer_explored_by_read[read_num].contains(i)) {
explored_minimizers.push_back(i);
}
}
// Compute caps on MAPQ. TODO: avoid needing to pass as much stuff along.
double mapq_explored_cap = 2 * faster_cap(minimizers_by_read[read_num], explored_minimizers, aln.sequence(), aln.quality());
#ifdef print_minimizers
mapq_extend_caps.emplace_back(mapq_explored_cap);
#endif
// Remember the caps
auto& to_annotate = (read_num == 0 ? mappings.first : mappings.second).front();
set_annotation(to_annotate, "mapq_explored_cap", mapq_explored_cap);
// Compute the cap. It should be the higher of the caps for the two reads
// (unless one has no minimizers, i.e. if it was rescued)
// The individual cap values are either actual numbers or +inf, so the cap can't stay as -inf.
mapq_cap = mapq_explored_cap == numeric_limits<double>::infinity() ? mapq_cap : max(mapq_cap, mapq_explored_cap);
}
mapq_cap = mapq_cap == -std::numeric_limits<float>::infinity() ? numeric_limits<double>::infinity() : mapq_cap;
for (auto read_num : {0, 1}) {
// For each fragment
// Find the source read
auto& aln = read_num == 0 ? aln1 : aln2;
// Find the MAPQ to cap
auto& read_mapq = read_num == 0 ? mapq_group1 : mapq_group2;
// Remember the uncapped MAPQ
auto& to_annotate = (read_num == 0 ? mappings.first : mappings.second).front();
set_annotation(to_annotate, "mapq_uncapped", read_mapq);
// And the cap we actually applied (possibly from the pair partner)
set_annotation(to_annotate, "mapq_applied_cap", mapq_cap);
// Apply the cap and transformation
read_mapq = round(0.85 * min(mapq_cap, min(read_mapq, 70.0)));
}
#ifdef debug
cerr << "MAPQ is " << mapq << ", capped group MAPQ scores are " << mapq_group1 << " and " << mapq_group2 << endl;
#endif
mappings.first.front().set_mapping_quality(max(min(mapq_group1, 60.0), 0.0)) ;
mappings.second.front().set_mapping_quality(max(min(mapq_group2, 60.0), 0.0)) ;
//Annotate top pair with its fragment distance, fragment length distrubution, and secondary scores
set_annotation(mappings.first.front(), "fragment_length", (double) distances.front());
set_annotation(mappings.second.front(), "fragment_length", (double) distances.front());
string distribution = "-I " + to_string(fragment_length_distr.mean()) + " -D " + to_string(fragment_length_distr.std_dev());
set_annotation(mappings.first.front(),"fragment_length_distribution", distribution);
set_annotation(mappings.second.front(),"fragment_length_distribution", distribution);
set_annotation(mappings.first.front(),"secondary_scores", scores);
set_annotation(mappings.second.front(),"secondary_scores", scores);
}
if (track_provenance) {
funnels[0].substage_stop();
funnels[1].substage_stop();
}
// Stop this alignment
funnels[0].stop();
funnels[1].stop();
if (track_provenance) {
// Annotate with the number of results in play at each stage
for (size_t read_num = 0 ; read_num < 2 ; read_num++) {
funnels[read_num].for_each_stage([&](const string& stage, const vector<size_t>& result_sizes) {
// Save the number of items
set_annotation(read_num == 0 ? mappings.first[0] : mappings.second[0], "stage_" + stage + "_results", (double)result_sizes.size());
});
if (track_correctness) {
// And with the last stage at which we had any descendants of the correct seed hit locations
set_annotation(read_num == 0 ? mappings.first[0] : mappings.second[0], "last_correct_stage", funnels[read_num].last_correct_stage());
}
// Annotate with the performances of all the filters
// We need to track filter number
size_t filter_num = 0;
funnels[read_num].for_each_filter([&](const string& stage, const string& filter,
const Funnel::FilterPerformance& by_count, const Funnel::FilterPerformance& by_size,
const vector<double>& filter_statistics_correct, const vector<double>& filter_statistics_non_correct) {
string filter_id = to_string(filter_num) + "_" + filter + "_" + stage;
if (read_num == 0) {
// Save the stats
set_annotation(mappings.first[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(mappings.first[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(mappings.first[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(mappings.first[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(mappings.first[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(mappings.first[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(mappings.first[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(mappings.first[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(mappings.first[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(mappings.first[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
} else {
// Save the stats
set_annotation(mappings.second[0], "filter_" + filter_id + "_passed_count_total", (double) by_count.passing);
set_annotation(mappings.second[0], "filter_" + filter_id + "_failed_count_total", (double) by_count.failing);
set_annotation(mappings.second[0], "filter_" + filter_id + "_passed_size_total", (double) by_size.passing);
set_annotation(mappings.second[0], "filter_" + filter_id + "_failed_size_total", (double) by_size.failing);
if (track_correctness) {
set_annotation(mappings.second[0], "filter_" + filter_id + "_passed_count_correct", (double) by_count.passing_correct);
set_annotation(mappings.second[0], "filter_" + filter_id + "_failed_count_correct", (double) by_count.failing_correct);
set_annotation(mappings.second[0], "filter_" + filter_id + "_passed_size_correct", (double) by_size.passing_correct);
set_annotation(mappings.second[0], "filter_" + filter_id + "_failed_size_correct", (double) by_size.failing_correct);
}
// Save the correct and non-correct filter statistics, even if
// everything is non-correct because correctness isn't computed
set_annotation(mappings.second[0], "filterstats_" + filter_id + "_correct", filter_statistics_correct);
set_annotation(mappings.second[0], "filterstats_" + filter_id + "_noncorrect", filter_statistics_non_correct);
}
filter_num++;
});
}
// Annotate with parameters used for the filters.
set_annotation(mappings.first[0] , "param_hit-cap", (double) hit_cap);
set_annotation(mappings.first[0] , "param_hard-hit-cap", (double) hard_hit_cap);
set_annotation(mappings.first[0] , "param_score-fraction", (double) minimizer_score_fraction);
set_annotation(mappings.first[0] , "param_max-extensions", (double) max_extensions);
set_annotation(mappings.first[0] , "param_max-alignments", (double) max_alignments);
set_annotation(mappings.first[0] , "param_cluster-score", (double) cluster_score_threshold);
set_annotation(mappings.first[0] , "param_cluster-coverage", (double) cluster_coverage_threshold);
set_annotation(mappings.first[0] , "param_extension-set", (double) extension_set_score_threshold);
set_annotation(mappings.first[0] , "param_max-multimaps", (double) max_multimaps);
set_annotation(mappings.first[0] , "param_max-rescue-attempts", (double) max_rescue_attempts);
set_annotation(mappings.second[0], "param_hit-cap", (double) hit_cap);
set_annotation(mappings.second[0], "param_hard-hit-cap", (double) hard_hit_cap);
set_annotation(mappings.second[0], "param_score-fraction", (double) minimizer_score_fraction);
set_annotation(mappings.second[0], "param_max-extensions", (double) max_extensions);
set_annotation(mappings.second[0], "param_max-alignments", (double) max_alignments);
set_annotation(mappings.second[0], "param_cluster-score", (double) cluster_score_threshold);
set_annotation(mappings.second[0], "param_cluster-coverage", (double) cluster_coverage_threshold);
set_annotation(mappings.second[0], "param_extension-set", (double) extension_set_score_threshold);
set_annotation(mappings.second[0], "param_max-multimaps", (double) max_multimaps);
set_annotation(mappings.second[0] , "param_max-rescue-attempts", (double) max_rescue_attempts);
}
#ifdef print_minimizers
if (mapq_extend_caps.size() == 0) {
mapq_extend_caps.resize(2,0.0);
}
if (distances.size() == 0) {
distances.emplace_back(0);
}
cerr << aln1.sequence() << "\t";
for (char c : aln1.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << all_clusters.size() << "\t" << mapping_was_rescued[0].first << "\t" << mapping_was_rescued[0].second << "\t" << distances.front();
for (size_t i = 0 ; i < minimizers_by_read[0].size() ; i++) {
auto& minimizer = minimizers_by_read[0][i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_explored_by_read[0].contains(i);
if (minimizer_explored_by_read[0].contains(i)) {
assert(minimizer.hits<=hard_hit_cap) ;
}
} cerr << "\t" << uncapped_mapq << "\t" << fragment_cluster_cap << "\t" << mapq_score_group_1 << "\t" << mapq_extend_caps[0];
if (track_correctness) {
cerr << "\t" << funnels[0].last_correct_stage() << endl;
} else {
cerr << "\t?" << endl;
}
cerr << aln2.sequence() << "\t";
for (char c : aln2.quality()) {
cerr << (char)(c+33);
}
cerr << "\t" << all_clusters.size() << "\t" << mapping_was_rescued[0].second << "\t" << mapping_was_rescued[0].first << "\t" << distances.front();
for (size_t i = 0 ; i < minimizers_by_read[1].size() ; i++) {
auto& minimizer = minimizers_by_read[1][i];
cerr << "\t"
<< minimizer.value.key.decode(minimizer.length) << "\t"
<< minimizer.forward_offset() << "\t"
<< minimizer.agglomeration_start << "\t"
<< minimizer.agglomeration_length << "\t"
<< minimizer.hits << "\t"
<< minimizer_explored_by_read[1].contains(i);
if (minimizer_explored_by_read[1].contains(i)) {
assert(minimizer.hits<=hard_hit_cap) ;
}
}
cerr << "\t" << uncapped_mapq << "\t" << fragment_cluster_cap << "\t" << mapq_score_group_1 << "\t" << mapq_extend_caps[1];
if (track_correctness) {
cerr << "\t" << funnels[1].last_correct_stage() << endl;
} else {
cerr << "\t?" << endl;
}
#endif
// Ship out all the aligned alignments
return mappings;
#ifdef debug
// Dump the funnel info graph.
funnels[0].to_dot(cerr);
funnels[1].to_dot(cerr);
#endif
}
//-----------------------------------------------------------------------------
double MinimizerMapper::compute_mapq_caps(const Alignment& aln,
const std::vector<Minimizer>& minimizers,
const SmallBitset& explored) {
// We need to cap MAPQ based on the likelihood of generating all the windows in the explored minimizers by chance, too.
#ifdef debug
cerr << "Cap based on explored minimizers all being faked by errors..." << endl;
#endif
// Convert our flag vector to a list of the minimizers actually in extended clusters
vector<size_t> explored_minimizers;
explored_minimizers.reserve(minimizers.size());
for (size_t i = 0; i < minimizers.size(); i++) {
if (explored.contains(i)) {
explored_minimizers.push_back(i);
}
}
double mapq_explored_cap = window_breaking_quality(minimizers, explored_minimizers, aln.sequence(), aln.quality());
return mapq_explored_cap;
}
double MinimizerMapper::window_breaking_quality(const vector<Minimizer>& minimizers, vector<size_t>& broken,
const string& sequence, const string& quality_bytes) {
#ifdef debug
cerr << "Computing MAPQ cap based on " << broken.size() << "/" << minimizers.size() << " minimizers' windows" << endl;
#endif
if (broken.empty() || quality_bytes.empty()) {
// If we have no agglomerations or no qualities, bail
return numeric_limits<double>::infinity();
}
assert(sequence.size() == quality_bytes.size());
// Sort the agglomerations by start position
std::sort(broken.begin(), broken.end(), [&](const size_t& a, const size_t& b) {
return minimizers[a].agglomeration_start < minimizers[b].agglomeration_start;
});
// Have a priority queue for tracking the agglomerations that a base is currently overlapping.
// Prioritize earliest-ending best, and then latest-starting best.
// This is less, and greater priority is at the front of the queue (better).
// TODO: do we really need to care about the start here?
auto agglomeration_priority = [&](const size_t& a, const size_t& b) {
// Returns true if a is worse (ends later, or ends at the same place and starts earlier).
auto& ma = minimizers[a];
auto& mb = minimizers[b];
auto a_end = ma.agglomeration_start + ma.agglomeration_length;
auto b_end = mb.agglomeration_start + mb.agglomeration_length;
return (a_end > b_end) || (a_end == b_end && ma.agglomeration_start < mb.agglomeration_start);
};
// We maintain our own heap so we can iterate over it.
vector<size_t> active_agglomerations;
// A window in flight is a pair of start position, inclusive end position
struct window_t {
size_t first;
size_t last;
};
// Have a priority queue of window starts and ends, prioritized earliest-ending best, and then latest-starting best.
// This is less, and greater priority is at the front of the queue (better).
auto window_priority = [&](const window_t& a, const window_t& b) {
// Returns true if a is worse (ends later, or ends at the same place and starts earlier).
return (a.last > b.last) || (a.last == b.last && a.first < b.first);
};
priority_queue<window_t, vector<window_t>, decltype(window_priority)> active_windows(window_priority);
// Have a cursor for which agglomeration should come in next.
auto next_agglomeration = broken.begin();
// Have a DP table with the cost of the cheapest solution to the problem up to here, including a hit at this base.
// Or numeric_limits<double>::infinity() if base cannot be hit.
// We pre-fill it because I am scared to use end() if we change its size.
vector<double> costs(sequence.size(), numeric_limits<double>::infinity());
// Keep track of the latest-starting window ending before here. If none, this will be two numeric_limits<size_t>::max() values.
window_t latest_starting_ending_before = { numeric_limits<size_t>::max(), numeric_limits<size_t>::max() };
// And keep track of the min cost DP table entry, or end if not computed yet.
auto latest_starting_ending_before_winner = costs.end();
for (size_t i = 0; i < sequence.size(); i++) {
// For each base in the read
#ifdef debug
cerr << "At base " << i << endl;
#endif
// Bring in new agglomerations and windows that start at this base.
while (next_agglomeration != broken.end() && minimizers[*next_agglomeration].agglomeration_start == i) {
// While the next agglomeration starts here
// Record it
active_agglomerations.push_back(*next_agglomeration);
std::push_heap(active_agglomerations.begin(), active_agglomerations.end(), agglomeration_priority);
// Look it up
auto& minimizer = minimizers[*next_agglomeration];
// Determine its window size from its index.
size_t window_size = minimizer.window_size();
#ifdef debug
cerr << "\tBegin agglomeration of " << (minimizer.agglomeration_length - window_size + 1)
<< " windows of " << window_size << " bp each for minimizer "
<< *next_agglomeration << " (" << minimizer.forward_offset()
<< "-" << (minimizer.forward_offset() + minimizer.length) << ")" << endl;
#endif
// Make sure the minimizer instance isn't too far into the agglomeration to actually be conatined in the same k+w-1 window as the first base.
assert(minimizer.agglomeration_start + minimizer.candidates_per_window >= minimizer.forward_offset());
for (size_t start = minimizer.agglomeration_start;
start + window_size - 1 < minimizer.agglomeration_start + minimizer.agglomeration_length;
start++) {
// Add all the agglomeration's windows to the queue, looping over their start bases in the read.
window_t add = {start, start + window_size - 1};
#ifdef debug
cerr << "\t\t" << add.first << " - " << add.last << endl;
#endif
active_windows.push(add);
}
// And advance the cursor
++next_agglomeration;
}
// We have the start and end of the latest-starting window ending before here (may be none)
if (isATGC(sequence[i]) &&
(!active_windows.empty() ||
(next_agglomeration != broken.end() && minimizers[*next_agglomeration].agglomeration_start == i))) {
// This base is not N, and it is either covered by an agglomeration
// that hasn't ended yet, or a new agglomeration starts here.
#ifdef debug
cerr << "\tBase is acceptable (" << sequence[i] << ", " << active_agglomerations.size() << " active agglomerations, "
<< active_windows.size() << " active windows)" << endl;
#endif
// Score mutating the base itself, thus causing all the windows it touches to be wrong.
// TODO: account for windows with multiple hits not having to be explained at full cost here.
// We start with the cost to mutate the base.
double base_cost = quality_bytes[i];
#ifdef debug
cerr << "\t\tBase base quality: " << base_cost << endl;
#endif
for (const size_t& active_index : active_agglomerations) {
// Then, we look at each agglomeration the base overlaps
// Find the minimizer whose agglomeration we are looking at
auto& active = minimizers[active_index];
if (i >= active.forward_offset() &&
i < active.forward_offset() + active.length) {
// If the base falls in the minimizer, we don't do anything. Just mutating the base is enough to create this wrong minimizer.
#ifdef debug
cerr << "\t\tBase in minimizer " << active_index << " (" << active.forward_offset()
<< "-" << (active.forward_offset() + active.length) << ") for agglomeration "
<< active.agglomeration_start << "-" << (active.agglomeration_start + active.agglomeration_length) << endl;
#endif
continue;
}
// If the base falls outside the minimizer, it participates in
// some number of other possible minimizers in the
// agglomeration. Compute that, accounting for edge effects.
size_t possible_minimizers = min((size_t) active.length, min(i - active.agglomeration_start + 1, (active.agglomeration_start + active.agglomeration_length) - i));
// Then for each of those possible minimizers, we need P(would have beaten the current minimizer).
// We approximate this as constant across the possible minimizers.
// And since we want to OR together beating, we actually AND together not-beating and then not it.
// So we track the probability of not beating.
double any_beat_phred = phred_for_at_least_one(active.value.hash, possible_minimizers);
#ifdef debug
cerr << "\t\tBase flanks minimizer " << active_index << " (" << active.forward_offset()
<< "-" << (active.forward_offset() + active.length) << ") for agglomeration "
<< active.agglomeration_start << "-" << (active.agglomeration_start + active.agglomeration_length)
<< " and has " << possible_minimizers
<< " chances to have beaten it; cost to have beaten with any is Phred " << any_beat_phred << endl;
#endif
// Then we AND (sum) the Phred of that in, as an additional cost to mutating this base and kitting all the windows it covers.
// This makes low-quality bases outside of minimizers produce fewer low MAPQ caps, and accounts for the robustness of minimizers to some errors.
base_cost += any_beat_phred;
}
// Now we know the cost of mutating this base, so we need to
// compute the total cost of a solution through here, mutating this
// base.
// Look at the start of that latest-starting window ending before here.
if (latest_starting_ending_before.first == numeric_limits<size_t>::max()) {
// If there is no such window, this is the first base hit, so
// record the cost of hitting it.
costs[i] = base_cost;
#ifdef debug
cerr << "\tFirst base hit, costs " << costs[i] << endl;
#endif
} else {
// Else, scan from that window's start to its end in the DP
// table, and find the min cost.
if (latest_starting_ending_before_winner == costs.end()) {
// We haven't found the min in the window we come from yet, so do that.
latest_starting_ending_before_winner = std::min_element(costs.begin() + latest_starting_ending_before.first,
costs.begin() + latest_starting_ending_before.last + 1);
}
double min_prev_cost = *latest_starting_ending_before_winner;
// Add the cost of hitting this base
costs[i] = min_prev_cost + base_cost;
#ifdef debug
cerr << "\tComes from prev base at " << (latest_starting_ending_before_winner - costs.begin()) << ", costs " << costs[i] << endl;
#endif
}
} else {
// This base is N, or not covered by an agglomeration.
// Leave infinity there to say we can't hit it.
// Nothing to do!
}
// Now we compute the start of the latest-starting window ending here or before, and deactivate agglomerations/windows.
while (!active_agglomerations.empty() &&
minimizers[active_agglomerations.front()].agglomeration_start + minimizers[active_agglomerations.front()].agglomeration_length - 1 == i) {
// Look at the queue to see if an agglomeration ends here.
#ifdef debug
cerr << "\tEnd agglomeration " << active_agglomerations.front() << endl;
#endif
std::pop_heap(active_agglomerations.begin(), active_agglomerations.end(), agglomeration_priority);
active_agglomerations.pop_back();
}
while (!active_windows.empty() && active_windows.top().last == i) {
// The look at the queue to see if a window ends here. This is
// after windows are added so that we can handle 1-base windows.
#ifdef debug
cerr << "\tEnd window " << active_windows.top().first << " - " << active_windows.top().last << endl;
#endif
if (latest_starting_ending_before.first == numeric_limits<size_t>::max() ||
active_windows.top().first > latest_starting_ending_before.first) {
#ifdef debug
cerr << "\t\tNew latest-starting-before-here!" << endl;
#endif
// If so, use the latest-starting of all such windows as our latest starting window ending here or before result.
latest_starting_ending_before = active_windows.top();
// And clear our cache of the lowest cost base to hit it.
latest_starting_ending_before_winner = costs.end();
#ifdef debug
cerr << "\t\t\tNow have: " << latest_starting_ending_before.first << " - " << latest_starting_ending_before.last << endl;
#endif
}
// And pop them all off.
active_windows.pop();
}
// If not, use the latest-starting window ending at the previous base or before (i.e. do nothing).
// Loop around; we will have the latest-starting window ending before the next here.
}
#ifdef debug
cerr << "Final window to scan: " << latest_starting_ending_before.first << " - " << latest_starting_ending_before.last << endl;
#endif
// When we get here, all the agglomerations should have been handled
assert(next_agglomeration == broken.end());
// And all the windows should be off the queue.
assert(active_windows.empty());
// When we get to the end, we have the latest-starting window overall. It must exist.
assert(latest_starting_ending_before.first != numeric_limits<size_t>::max());
// Scan it for the best final base to hit and return the cost there.
// Don't use the cache here because nothing can come after the last-ending window.
auto min_cost_at = std::min_element(costs.begin() + latest_starting_ending_before.first,
costs.begin() + latest_starting_ending_before.last + 1);
#ifdef debug
cerr << "Overall min cost: " << *min_cost_at << " at base " << (min_cost_at - costs.begin()) << endl;
#endif
return *min_cost_at;
}
double MinimizerMapper::faster_cap(const vector<Minimizer>& minimizers, vector<size_t>& minimizers_explored,
const string& sequence, const string& quality_bytes) {
// Sort minimizer subset so we go through minimizers in increasing order of start position
std::sort(minimizers_explored.begin(), minimizers_explored.end(), [&](size_t a, size_t b) {
// Return true if a must come before b, and false otherwise
return minimizers[a].forward_offset() < minimizers[b].forward_offset();
});
#ifdef debug
cerr << "Sorted " << minimizers_explored.size() << " minimizers" << endl;
#endif
#ifdef debug
// Dump read and minimizers
int digits_needed = (int) ceil(log10(sequence.size()));
for (int digit = digits_needed - 1; digit >= 0; digit--) {
for (size_t i = 0; i < sequence.size(); i++) {
// Output the correct digit for this place in this number
cerr << (char) ('0' + (uint8_t) round(i % (int) round(pow(10, digit + 1)) / pow(10, digit)));
}
cerr << endl;
}
cerr << sequence << endl;
for (auto& explored_index : minimizers_explored) {
// For each explored minimizer
auto& m = minimizers[explored_index];
for (size_t i = 0; i < m.agglomeration_start; i++) {
// Space until its agglomeration starts
cerr << ' ';
}
for (size_t i = m.agglomeration_start; i < m.forward_offset(); i++) {
// Do the beginnign of the agglomeration
cerr << '-';
}
// Do the minimizer itself
cerr << m.value.key.decode(m.length);
for (size_t i = m.forward_offset() + m.length ; i < m.agglomeration_start + m.agglomeration_length; i++) {
// Do the tail end of the agglomeration
cerr << '-';
}
cerr << endl;
}
#endif
// Make a DP table holding the log10 probability of having an error disrupt each minimizer.
// Entry i+1 is log prob of mutating minimizers 0, 1, 2, ..., i.
// Make sure to have an extra field at the end to support this.
// Initialize with -inf for unfilled.
vector<double> c(minimizers_explored.size() + 1, -numeric_limits<double>::infinity());
c[0] = 0.0;
for_each_aglomeration_interval(minimizers, sequence, quality_bytes, minimizers_explored, [&](size_t left, size_t right, size_t bottom, size_t top) {
// For each overlap range in the agglomerations
#ifdef debug
cerr << "Consider overlap range " << left << " to " << right << " in minimizer ranks " << bottom << " to " << top << endl;
cerr << "log10prob for bottom: " << c[bottom] << endl;
#endif
// Calculate the probability of a disruption here
double p_here = get_log10_prob_of_disruption_in_interval(minimizers, sequence, quality_bytes,
minimizers_explored.begin() + bottom, minimizers_explored.begin() + top, left, right);
#ifdef debug
cerr << "log10prob for here: " << p_here << endl;
#endif
// Calculate prob of all intervals up to top being disrupted
double p = c[bottom] + p_here;
#ifdef debug
cerr << "log10prob overall: " << p << endl;
#endif
for (size_t i = bottom + 1; i < top + 1; i++) {
// Replace min-prob for minimizers in the interval
if (c[i] < p) {
#ifdef debug
cerr << "\tBeats " << c[i] << " at rank " << i-1 << endl;
#endif
c[i] = p;
} else {
#ifdef debug
cerr << "\tBeaten by " << c[i] << " at rank " << i-1 << endl;
#endif
}
}
});
#ifdef debug
cerr << "log10prob after all minimizers is " << c.back() << endl;
#endif
assert(!isinf(c.back()));
// Conver to Phred.
double result = -c.back() * 10;
return result;
}
void MinimizerMapper::for_each_aglomeration_interval(const vector<Minimizer>& minimizers,
const string& sequence, const string& quality_bytes,
const vector<size_t>& minimizer_indices,
const function<void(size_t, size_t, size_t, size_t)>& iteratee) {
if (minimizer_indices.empty()) {
// Handle no item case
return;
}
// Items currently being iterated over
list<const Minimizer*> stack = {&minimizers[minimizer_indices.front()]};
// The left end of an item interval
size_t left = stack.front()->agglomeration_start;
// The index of the first item in the interval in the sequence of selected items
size_t bottom = 0;
// Emit all intervals that precede a given point "right"
auto emit_preceding_intervals = [&](size_t right) {
while (left < right) {
// Work out the end position of the top thing on the stack
size_t stack_top_end = stack.front()->agglomeration_start + stack.front()->agglomeration_length;
if (stack_top_end <= right) {
// Case where the left-most item ends before the start of the new item
iteratee(left, stack_top_end, bottom, bottom + stack.size());
// If the stack contains only one item there is a gap between the item
// and the new item, otherwise just shift to the end of the leftmost item
left = stack.size() == 1 ? right : stack_top_end;
bottom += 1;
stack.pop_front();
} else {
// Case where the left-most item ends at or after the beginning of the new new item
iteratee(left, right, bottom, bottom + stack.size());
left = right;
}
}
};
for (auto it = minimizer_indices.begin() + 1; it != minimizer_indices.end(); ++it) {
// For each item in turn
auto& item = minimizers[*it];
assert(stack.size() > 0);
// For each new item we return all intervals that
// precede its start
emit_preceding_intervals(item.agglomeration_start);
// Add the new item for the next loop
stack.push_back(&item);
}
// Intervals of the remaining intervals on the stack
emit_preceding_intervals(sequence.size());
}
double MinimizerMapper::get_log10_prob_of_disruption_in_interval(const vector<Minimizer>& minimizers,
const string& sequence, const string& quality_bytes,
const vector<size_t>::iterator& disrupt_begin, const vector<size_t>::iterator& disrupt_end,
size_t left, size_t right) {
#ifdef debug
cerr << "Compute log10 probability in interval " << left << "-" << right << endl;
#endif
if (left == right) {
// 0-length intervals need no disruption.
return 0;
}
// Start with the first column
double p = get_log10_prob_of_disruption_in_column(minimizers, sequence, quality_bytes, disrupt_begin, disrupt_end, left);
#ifdef debug
cerr << "\tlog10 probability at column " << left << ": " << p << endl;
#endif
for(size_t i = left + 1 ; i < right; i++) {
// OR up probability of all the other columns
double col_p = get_log10_prob_of_disruption_in_column(minimizers, sequence, quality_bytes, disrupt_begin, disrupt_end, i);
#ifdef debug
cerr << "\tlog10 probability at column " << i << ": " << col_p << endl;
#endif
p = add_log10(col_p, p);
#ifdef debug
cerr << "\tRunning total OR: " << p << endl;
#endif
}
// Make sure that we don't go above certainty when our bases are really bad
// and OR ~= sum assumption breaks down due to non-tiny probabilities.
p = std::min(p, 0.0);
// Return the result
return p;
}
double MinimizerMapper::get_log10_prob_of_disruption_in_column(const vector<Minimizer>& minimizers,
const string& sequence, const string& quality_bytes,
const vector<size_t>::iterator& disrupt_begin, const vector<size_t>::iterator& disrupt_end,
size_t index) {
#ifdef debug
cerr << "\tCompute log10 probability at column " << index << endl;
#endif
// Base cost is quality. Make sure to compute a non-integral answer.
double p = -(uint8_t)quality_bytes[index] / 10.0;
#ifdef debug
cerr << "\t\tBase log10 probability from quality: " << p << endl;
#endif
for (auto it = disrupt_begin; it != disrupt_end; ++it) {
// For each minimizer to disrupt
auto m = minimizers[*it];
#ifdef debug
cerr << "\t\tRelative rank " << (it - disrupt_begin) << " is minimizer " << m.value.key.decode(m.length) << endl;
#endif
if (!(m.forward_offset() <= index && index < m.forward_offset() + m.length)) {
// Index is out of range of the minimizer itself. We're in the flank.
#ifdef debug
cerr << "\t\t\tColumn " << index << " is in flank." << endl;
#endif
// How many new possible minimizers would an error here create in this agglomeration,
// to compete with its minimizer?
// No more than one per position in a minimizer sequence.
// No more than 1 per base from the start of the agglomeration to here, inclusive.
// No more than 1 per base from here to the last base of the agglomeration, inclusive.
size_t possible_minimizers = min((size_t) m.length,
min(index - m.agglomeration_start + 1,
(m.agglomeration_start + m.agglomeration_length) - index));
// Account for at least one of them beating the minimizer.
double any_beat_phred = phred_for_at_least_one(m.value.hash, possible_minimizers);
// Make sure to convert to log10 probability
double any_beat_log10_prob = -any_beat_phred / 10;
#ifdef debug
cerr << "\t\t\tBeat hash " << m.value.hash << " at least 1 time in " << possible_minimizers << " gives log10 probability: " << any_beat_log10_prob << endl;
#endif
p += any_beat_log10_prob;
// TODO: handle N somehow??? It can occur outside the minimizer itself, here in the flank.
}
#ifdef debug
cerr << "\t\t\tRunning AND log10 prob: " << p << endl;
#endif
}
return p;
}
//-----------------------------------------------------------------------------
void MinimizerMapper::attempt_rescue(const Alignment& aligned_read, Alignment& rescued_alignment, const std::vector<Minimizer>& minimizers, bool rescue_forward ) {
if (this->rescue_algorithm == rescue_none) { return; }
// We are traversing the same small subgraph repeatedly, so it's better to use a cache.
gbwtgraph::CachedGBWTGraph cached_graph(this->gbwt_graph);
// Find all nodes within a reasonable range from aligned_read.
std::unordered_set<id_t> rescue_nodes;
int64_t min_distance = max(0.0, fragment_length_distr.mean() - rescued_alignment.sequence().size() - rescue_subgraph_stdevs * fragment_length_distr.std_dev());
int64_t max_distance = fragment_length_distr.mean() + rescue_subgraph_stdevs * fragment_length_distr.std_dev();
distance_index.subgraph_in_range(aligned_read.path(), &cached_graph, min_distance, max_distance, rescue_nodes, rescue_forward);
// Remove node ids that do not exist in the GBWTGraph from the subgraph.
// We may be using the distance index of the original graph, and nodes
// not visited by any thread are missing from the GBWTGraph.
for (auto iter = rescue_nodes.begin(); iter != rescue_nodes.end(); ) {
if (!cached_graph.has_node(*iter)) {
iter = rescue_nodes.erase(iter);
} else {
++iter;
}
}
// Get rid of the old path.
rescued_alignment.clear_path();
// Find all seeds in the subgraph and try to get a full-length extension.
GaplessExtender::cluster_type seeds = this->seeds_in_subgraph(minimizers, rescue_nodes);
std::vector<GaplessExtension> extensions = this->extender.extend(seeds, rescued_alignment.sequence(), &cached_graph);
size_t best = extensions.size();
for (size_t i = 0; i < extensions.size(); i++) {
if (best >= extensions.size() || extensions[i].score > extensions[best].score) {
best = i;
}
}
// If we have a full-length extension, use it as the rescued alignment.
if (best < extensions.size() && extensions[best].full()) {
this->extension_to_alignment(extensions[best], rescued_alignment);
return;
}
// The haplotype-based algorithm is a special case.
if (this->rescue_algorithm == rescue_haplotypes) {
// Find and unfold the local haplotypes in the subgraph.
std::vector<std::vector<handle_t>> haplotype_paths;
bdsg::HashGraph align_graph;
this->extender.unfold_haplotypes(rescue_nodes, haplotype_paths, align_graph);
// Align to the subgraph.
this->get_regular_aligner()->align_xdrop(rescued_alignment, align_graph,
std::vector<MaximalExactMatch>(), false);
this->fix_dozeu_score(rescued_alignment, align_graph, std::vector<handle_t>());
// Get the corresponding alignment to the original graph.
this->extender.transform_alignment(rescued_alignment, haplotype_paths);
return;
}
// Use the best extension as a seed for dozeu.
// Also ensure that the entire extension is in the subgraph.
std::vector<MaximalExactMatch> dozeu_seed;
if (best < extensions.size()) {
const GaplessExtension& extension = extensions[best];
for (handle_t handle : extension.path) {
rescue_nodes.insert(cached_graph.get_id(handle));
}
dozeu_seed.emplace_back();
dozeu_seed.back().begin = rescued_alignment.sequence().begin() + extension.read_interval.first;
dozeu_seed.back().end = rescued_alignment.sequence().begin() + extension.read_interval.second;
nid_t id = cached_graph.get_id(extension.path.front());
bool is_reverse = cached_graph.get_is_reverse(extension.path.front());
gcsa::node_type node = gcsa::Node::encode(id, extension.offset, is_reverse);
dozeu_seed.back().nodes.push_back(node);
}
// GSSW and dozeu assume that the graph is a DAG.
std::vector<handle_t> topological_order = gbwtgraph::topological_order(cached_graph, rescue_nodes);
if (!topological_order.empty()) {
if (rescue_algorithm == rescue_dozeu) {
get_regular_aligner()->align_xdrop(rescued_alignment, cached_graph, topological_order,
dozeu_seed, false);
this->fix_dozeu_score(rescued_alignment, cached_graph, topological_order);
} else {
get_regular_aligner()->align(rescued_alignment, cached_graph, topological_order);
}
return;
}
// Build a subgraph overlay.
SubHandleGraph sub_graph(&cached_graph);
for (id_t id : rescue_nodes) {
sub_graph.add_handle(cached_graph.get_handle(id));
}
// Create an overlay where each strand is a separate node.
StrandSplitGraph split_graph(&sub_graph);
// Dagify the subgraph.
bdsg::HashGraph dagified;
std::unordered_map<id_t, id_t> dagify_trans =
algorithms::dagify(&split_graph, &dagified, rescued_alignment.sequence().size());
// Align to the subgraph.
// TODO: Map the seed to the dagified subgraph.
if (this->rescue_algorithm == rescue_dozeu) {
get_regular_aligner()->align_xdrop(rescued_alignment, dagified, std::vector<MaximalExactMatch>(), false);
this->fix_dozeu_score(rescued_alignment, dagified, std::vector<handle_t>());
} else if (this->rescue_algorithm == rescue_gssw) {
get_regular_aligner()->align(rescued_alignment, dagified, true);
}
// Map the alignment back to the original graph.
Path& path = *(rescued_alignment.mutable_path());
for (size_t i = 0; i < path.mapping_size(); i++) {
Position& pos = *(path.mutable_mapping(i)->mutable_position());
id_t id = dagify_trans[pos.node_id()];
handle_t handle = split_graph.get_underlying_handle(split_graph.get_handle(id));
pos.set_node_id(sub_graph.get_id(handle));
pos.set_is_reverse(sub_graph.get_is_reverse(handle));
}
}
GaplessExtender::cluster_type MinimizerMapper::seeds_in_subgraph(const std::vector<Minimizer>& minimizers,
const std::unordered_set<id_t>& subgraph) const {
std::vector<id_t> sorted_ids(subgraph.begin(), subgraph.end());
std::sort(sorted_ids.begin(), sorted_ids.end());
GaplessExtender::cluster_type result;
for (const Minimizer& minimizer : minimizers) {
gbwtgraph::hits_in_subgraph(minimizer.hits, minimizer.occs, sorted_ids, [&](pos_t pos, gbwtgraph::payload_type) {
if (minimizer.value.is_reverse) {
size_t node_length = this->gbwt_graph.get_length(this->gbwt_graph.get_handle(id(pos)));
pos = reverse_base_pos(pos, node_length);
}
result.insert(GaplessExtender::to_seed(pos, minimizer.value.offset));
});
}
return result;
}
void MinimizerMapper::fix_dozeu_score(Alignment& rescued_alignment, const HandleGraph& rescue_graph,
const std::vector<handle_t>& topological_order) const {
const Aligner* aligner = this->get_regular_aligner();
int32_t score = aligner->score_ungapped_alignment(rescued_alignment);
if (score > 0) {
rescued_alignment.set_score(score);
} else {
rescued_alignment.clear_path();
if (topological_order.empty()) {
aligner->align(rescued_alignment, rescue_graph, true);
} else {
aligner->align(rescued_alignment, rescue_graph, topological_order);
}
}
}
//-----------------------------------------------------------------------------
int64_t MinimizerMapper::distance_between(const Alignment& aln1, const Alignment& aln2) {
assert(aln1.path().mapping_size() != 0);
assert(aln2.path().mapping_size() != 0);
pos_t pos1 = initial_position(aln1.path());
pos_t pos2 = final_position(aln2.path());
int64_t min_dist = distance_index.min_distance(pos1, pos2);
return min_dist == -1 ? numeric_limits<int64_t>::max() : min_dist;
}
void MinimizerMapper::extension_to_alignment(const GaplessExtension& extension, Alignment& alignment) const {
*(alignment.mutable_path()) = extension.to_path(this->gbwt_graph, alignment.sequence());
alignment.set_score(extension.score);
double identity = 0.0;
if (!alignment.sequence().empty()) {
size_t len = alignment.sequence().length();
identity = (len - extension.mismatches()) / static_cast<double>(len);
}
alignment.set_identity(identity);
}
//-----------------------------------------------------------------------------
std::vector<MinimizerMapper::Minimizer> MinimizerMapper::find_minimizers(const std::string& sequence, Funnel& funnel) const {
if (this->track_provenance) {
// Start the minimizer finding stage
funnel.stage("minimizer");
}
std::vector<Minimizer> result;
double base_score = 1.0 + std::log(this->hard_hit_cap);
for (size_t i = 0; i < this->minimizer_indexes.size(); i++) {
// Get minimizers and their window agglomeration starts and lengths
vector<tuple<gbwtgraph::DefaultMinimizerIndex::minimizer_type, size_t, size_t>> current_minimizers =
minimizer_indexes[i]->minimizer_regions(sequence);
for (auto& m : current_minimizers) {
double score = 0.0;
auto hits = this->minimizer_indexes[i]->count_and_find(get<0>(m));
if (hits.first > 0) {
if (hits.first <= this->hard_hit_cap) {
score = base_score - std::log(hits.first);
} else {
score = 1.0;
}
}
result.push_back({ std::get<0>(m), std::get<1>(m), std::get<2>(m), hits.first, hits.second,
(int32_t) minimizer_indexes[i]->k(), (int32_t) minimizer_indexes[i]->w(), score });
}
}
std::sort(result.begin(), result.end());
if (this->track_provenance) {
// Record how many we found, as new lines.
funnel.introduce(result.size());
}
return result;
}
std::vector<MinimizerMapper::Seed> MinimizerMapper::find_seeds(const std::vector<Minimizer>& minimizers, const Alignment& aln, Funnel& funnel) const {
if (this->track_provenance) {
// Start the minimizer locating stage
funnel.stage("seed");
}
// One of the filters accepts minimizers until selected_score reaches target_score.
double base_target_score = 0.0;
for (const Minimizer& minimizer : minimizers) {
base_target_score += minimizer.score;
}
double target_score = (base_target_score * this->minimizer_score_fraction) + 0.000001;
double selected_score = 0.0;
// In order to consistently take either all or none of the minimizers in
// the read with a particular sequence, we track whether we took the
// previous one.
bool took_last = false;
// Select the minimizers we use for seeds.
size_t rejected_count = 0;
std::vector<Seed> seeds;
// Flag whether each minimizer in the read was located or not, for MAPQ capping.
// We ignore minimizers with no hits (count them as not located), because
// they would have to be created in the read no matter where we say it came
// from, and because adding more of them should lower the MAPQ cap, whereas
// locating more of the minimizers that are present and letting them pass
// to the enxt stage should raise the cap.
for (size_t i = 0; i < minimizers.size(); i++) {
if (this->track_provenance) {
// Say we're working on it
funnel.processing_input(i);
}
// Select the minimizer if it is informative enough or if the total score
// of the selected minimizers is not high enough.
const Minimizer& minimizer = minimizers[i];
#ifdef debug
std::cerr << "Minimizer " << i << " = " << minimizer.value.key.decode(minimizer.length)
<< " has " << minimizer.hits << " hits" << std::endl;
#endif
if (minimizer.hits == 0) {
// A minimizer with no hits can't go on.
took_last = false;
// We do not treat it as located for MAPQ capping purposes.
if (this->track_provenance) {
funnel.fail("any-hits", i);
}
} else if (minimizer.hits <= this->hit_cap ||
(minimizer.hits <= this->hard_hit_cap && selected_score + minimizer.score <= target_score) ||
(took_last && i > 0 && minimizer.value.key == minimizers[i - 1].value.key)) {
// We should keep this minimizer instance because it is
// sufficiently rare, or we want it to make target_score, or it is
// the same sequence as the previous minimizer which we also took.
// Locate the hits.
for (size_t j = 0; j < minimizer.hits; j++) {
pos_t hit = gbwtgraph::Position::decode(minimizer.occs[j].pos);
// Reverse the hits for a reverse minimizer
if (minimizer.value.is_reverse) {
size_t node_length = this->gbwt_graph.get_length(this->gbwt_graph.get_handle(id(hit)));
hit = reverse_base_pos(hit, node_length);
}
// Extract component id and offset in the root chain, if we have them for this seed.
// TODO: Get all the seed values here
tuple<bool, size_t, size_t, bool, size_t, size_t, size_t, size_t, bool> chain_info
(false, MIPayload::NO_VALUE, MIPayload::NO_VALUE, false, MIPayload::NO_VALUE, MIPayload::NO_VALUE, MIPayload::NO_VALUE, MIPayload::NO_VALUE, false );
if (minimizer.occs[j].payload != MIPayload::NO_CODE) {
chain_info = MIPayload::decode(minimizer.occs[j].payload);
}
seeds.push_back({ hit, i, std::get<0>(chain_info), std::get<1>(chain_info), std::get<2>(chain_info),
std::get<3>(chain_info), std::get<4>(chain_info), std::get<5>(chain_info), std::get<6>(chain_info), std::get<7>(chain_info), std::get<8>(chain_info) });
}
if (!(took_last && i > 0 && minimizer.value.key == minimizers[i - 1].value.key)) {
// We did not also take a previous identical-sequence minimizer, so count this one towards the score.
selected_score += minimizer.score;
}
// Remember that we took this minimizer
took_last = true;
if (this->track_provenance) {
// Record in the funnel that this minimizer gave rise to these seeds.
funnel.pass("any-hits", i);
funnel.pass("hard-hit-cap", i);
funnel.pass("hit-cap||score-fraction", i, selected_score / base_target_score);
funnel.expand(i, minimizer.hits);
}
} else if (minimizer.hits <= this->hard_hit_cap) {
// Passed hard hit cap but failed score fraction/normal hit cap
took_last = false;
rejected_count++;
if (this->track_provenance) {
funnel.pass("any-hits", i);
funnel.pass("hard-hit-cap", i);
funnel.fail("hit-cap||score-fraction", i, (selected_score + minimizer.score) / base_target_score);
}
//Stop looking for more minimizers once we fail the score fraction
target_score = selected_score;
} else {
// Failed hard hit cap
took_last = false;
rejected_count++;
if (this->track_provenance) {
funnel.pass("any-hits", i);
funnel.fail("hard-hit-cap", i);
}
}
if (this->track_provenance) {
// Say we're done with this input item
funnel.processed_input();
}
}
if (this->track_provenance && this->track_correctness) {
// Tag seeds with correctness based on proximity along paths to the input read's refpos
funnel.substage("correct");
if (this->path_graph == nullptr) {
cerr << "error[vg::MinimizerMapper] Cannot use track_correctness with no XG index" << endl;
exit(1);
}
if (aln.refpos_size() != 0) {
// Take the first refpos as the true position.
auto& true_pos = aln.refpos(0);
for (size_t i = 0; i < seeds.size(); i++) {
// Find every seed's reference positions. This maps from path name to pairs of offset and orientation.
auto offsets = algorithms::nearest_offsets_in_paths(this->path_graph, seeds[i].pos, 100);
for (auto& hit_pos : offsets[this->path_graph->get_path_handle(true_pos.name())]) {
// Look at all the ones on the path the read's true position is on.
if (abs((int64_t)hit_pos.first - (int64_t) true_pos.offset()) < 200) {
// Call this seed hit close enough to be correct
funnel.tag_correct(i);
}
}
}
}
}
#ifdef debug
std::cerr << "Found " << seeds.size() << " seeds from " << (minimizers.size() - rejected_count) << " minimizers, rejected " << rejected_count << std::endl;
#endif
return seeds;
}
//-----------------------------------------------------------------------------
void MinimizerMapper::score_cluster(Cluster& cluster, size_t i, const std::vector<Minimizer>& minimizers, const std::vector<Seed>& seeds, size_t seq_length, Funnel& funnel) const {
if (this->track_provenance) {
// Say we're making it
funnel.producing_output(i);
}
// Initialize the values.
cluster.score = 0.0;
cluster.coverage = 0.0;
cluster.present = SmallBitset(minimizers.size());
// Determine the minimizers that are present in the cluster.
for (auto hit_index : cluster.seeds) {
cluster.present.insert(seeds[hit_index].source);
#ifdef debug
cerr << "Minimizer " << seeds[hit_index].source << " is present in cluster " << i << endl;
#endif
}
// Compute the score and cluster coverage.
sdsl::bit_vector covered(seq_length, 0);
for (size_t j = 0; j < minimizers.size(); j++) {
if (cluster.present.contains(j)) {
const Minimizer& minimizer = minimizers[j];
cluster.score += minimizer.score;
// The offset of a reverse minimizer is the endpoint of the kmer
size_t start_offset = minimizer.forward_offset();
size_t k = minimizer.length;
// Set the k bits starting at start_offset.
covered.set_int(start_offset, sdsl::bits::lo_set[k], k);
}
}
// Count up the covered positions and turn it into a fraction.
cluster.coverage = sdsl::util::cnt_one_bits(covered) / static_cast<double>(seq_length);
if (this->track_provenance) {
// Record the cluster in the funnel as a group of the size of the number of items.
funnel.merge_group(cluster.seeds.begin(), cluster.seeds.end());
funnel.score(funnel.latest(), cluster.score);
// Say we made it.
funnel.produced_output();
}
}
//-----------------------------------------------------------------------------
int MinimizerMapper::score_extension_group(const Alignment& aln, const vector<GaplessExtension>& extended_seeds,
int gap_open_penalty, int gap_extend_penalty) {
if (extended_seeds.empty()) {
// TODO: We should never see an empty group of extensions
return 0;
} else if (extended_seeds.front().full()) {
// These are length matches. We already have the score.
int best_score = 0;
for (auto& extension : extended_seeds) {
best_score = max(best_score, extension.score);
}
return best_score;
} else {
// This is a collection of one or more non-full-length extended seeds.
if (aln.sequence().size() == 0) {
// No score here
return 0;
}
// We use a sweep line algorithm to find relevant points along the read: extension starts or ends.
// This records the last base to be covered by the current sweep line.
int64_t sweep_line = 0;
// This records the first base not covered by the last sweep line.
int64_t last_sweep_line = 0;
// And we track the next unentered gapless extension
size_t unentered = 0;
// Extensions we are in are in this min-heap of past-end position and gapless extension number.
vector<pair<size_t, size_t>> end_heap;
// The heap uses this comparator
auto min_heap_on_first = [](const pair<size_t, size_t>& a, const pair<size_t, size_t>& b) {
// Return true if a must come later in the heap than b
return a.first > b.first;
};
// We track the best score for a chain reaching the position before this one and ending in a gap.
// We never let it go below 0.
// Will be 0 when there's no gap that can be open
int best_gap_score = 0;
// We track the score for the best chain ending with each gapless extension
vector<int> best_chain_score(extended_seeds.size(), 0);
// And we're after the best score overall that we can reach when an extension ends
int best_past_ending_score_ever = 0;
// Overlaps are more complicated.
// We need a heap of all the extensions for which we have seen the
// start and that we can thus overlap.
// We filter things at the top of the heap if their past-end positions
// have occurred.
// So we store pairs of score we get backtracking to the current
// position, and past-end position for the thing we are backtracking
// from.
vector<pair<int, size_t>> overlap_heap;
// We can just use the standard max-heap comparator
// We encode the score relative to a counter that we increase by the
// gap extend every base we go through, so we don't need to update and
// re-sort the heap.
int overlap_score_offset = 0;
while(last_sweep_line <= aln.sequence().size()) {
// We are processed through the position before last_sweep_line.
// Find a place for sweep_line to go
// Find the next seed start
int64_t next_seed_start = numeric_limits<int64_t>::max();
if (unentered < extended_seeds.size()) {
next_seed_start = extended_seeds[unentered].read_interval.first;
}
// Find the next seed end
int64_t next_seed_end = numeric_limits<int64_t>::max();
if (!end_heap.empty()) {
next_seed_end = end_heap.front().first;
}
// Whichever is closer between those points and the end, do that.
sweep_line = min(min(next_seed_end, next_seed_start), (int64_t) aln.sequence().size());
// So now we're only interested in things that happen at sweep_line.
// Compute the distance from the previous sweep line position
// Make sure to account for last_sweep_line's semantics as the next unswept base.
int sweep_distance = sweep_line - last_sweep_line + 1;
// We need to track the score of the best thing that past-ended here
int best_past_ending_score_here = 0;
while(!end_heap.empty() && end_heap.front().first == sweep_line) {
// Find anything that past-ends here
size_t past_ending = end_heap.front().second;
// Mix it into the score
best_past_ending_score_here = std::max(best_past_ending_score_here, best_chain_score[past_ending]);
// Remove it from the end-tracking heap
std::pop_heap(end_heap.begin(), end_heap.end(), min_heap_on_first);
end_heap.pop_back();
}
// Mix that into the best score overall
best_past_ending_score_ever = std::max(best_past_ending_score_ever, best_past_ending_score_here);
if (sweep_line == aln.sequence().size()) {
// We don't need to think about gaps or backtracking anymore since everything has ended
break;
}
// Update the overlap score offset by removing some gap extends from it.
overlap_score_offset += sweep_distance * gap_extend_penalty;
// The best way to backtrack to here is whatever is on top of the heap, if anything, that doesn't past-end here.
int best_overlap_score = 0;
while (!overlap_heap.empty()) {
// While there is stuff on the heap
if (overlap_heap.front().second <= sweep_line) {
// We are already past this thing, so drop it
std::pop_heap(overlap_heap.begin(), overlap_heap.end());
overlap_heap.pop_back();
} else {
// This is at the top of the heap and we aren't past it
// Decode and use its score offset if we only backtrack to here.
best_overlap_score = overlap_heap.front().first + overlap_score_offset;
// Stop looking in the heap
break;
}
}
// The best way to end 1 before here in a gap is either:
if (best_gap_score != 0) {
// Best way to end 1 before our last sweep line position with a gap, plus distance times gap extend penalty
best_gap_score -= sweep_distance * gap_extend_penalty;
}
// Best way to end 1 before here with an actual extension, plus the gap open part of the gap open penalty.
// (Will never be taken over an actual adjacency)
best_gap_score = std::max(0, std::max(best_gap_score, best_past_ending_score_here - (gap_open_penalty - gap_extend_penalty)));
while (unentered < extended_seeds.size() && extended_seeds[unentered].read_interval.first == sweep_line) {
// For each thing that starts here
// Compute its chain score
best_chain_score[unentered] = std::max(best_overlap_score,
std::max(best_gap_score, best_past_ending_score_here)) + extended_seeds[unentered].score;
// Compute its backtrack-to-here score and add it to the backtracking heap
// We want how far we would have had to have backtracked to be
// able to preceed the base we are at now, where this thing
// starts.
size_t extension_length = extended_seeds[unentered].read_interval.second - extended_seeds[unentered].read_interval.first;
int raw_overlap_score = best_chain_score[unentered] - gap_open_penalty - gap_extend_penalty * extension_length;
int encoded_overlap_score = raw_overlap_score - overlap_score_offset;
// Stick it in the heap
overlap_heap.emplace_back(encoded_overlap_score, extended_seeds[unentered].read_interval.second);
std::push_heap(overlap_heap.begin(), overlap_heap.end());
// Add it to the end finding heap
end_heap.emplace_back(extended_seeds[unentered].read_interval.second, unentered);
std::push_heap(end_heap.begin(), end_heap.end(), min_heap_on_first);
// Advance and check the next thing to start
unentered++;
}
// Move last_sweep_line to sweep_line.
// We need to add 1 since last_sweep_line is the next *un*included base
last_sweep_line = sweep_line + 1;
}
// When we get here, we've seen the end of every extension and so we
// have the best score at the end of any of them.
return best_past_ending_score_ever;
}
}
std::vector<int> MinimizerMapper::score_extensions(const std::vector<std::vector<GaplessExtension>>& extensions, const Alignment& aln, Funnel& funnel) const {
// Extension scoring substage.
if (this->track_provenance) {
funnel.substage("score");
}
// We now estimate the best possible alignment score for each cluster.
std::vector<int> result(extensions.size(), 0);
for (size_t i = 0; i < extensions.size(); i++) {
if (this->track_provenance) {
funnel.producing_output(i);
}
result[i] = score_extension_group(aln, extensions[i], get_regular_aligner()->gap_open, get_regular_aligner()->gap_extension);
// Record the score with the funnel.
if (this->track_provenance) {
funnel.score(i, result[i]);
funnel.produced_output();
}
}
return result;
}
std::vector<int> MinimizerMapper::score_extensions(const std::vector<std::pair<std::vector<GaplessExtension>, size_t>>& extensions, const Alignment& aln, Funnel& funnel) const {
// Extension scoring substage.
if (this->track_provenance) {
funnel.substage("score");
}
// We now estimate the best possible alignment score for each cluster.
std::vector<int> result(extensions.size(), 0);
for (size_t i = 0; i < extensions.size(); i++) {
if (this->track_provenance) {
funnel.producing_output(i);
}
result[i] = score_extension_group(aln, extensions[i].first, get_regular_aligner()->gap_open, get_regular_aligner()->gap_extension);
// Record the score with the funnel.
if (this->track_provenance) {
funnel.score(i, result[i]);
funnel.produced_output();
}
}
return result;
}
//-----------------------------------------------------------------------------
void MinimizerMapper::find_optimal_tail_alignments(const Alignment& aln, const vector<GaplessExtension>& extended_seeds, Alignment& best, Alignment& second_best) const {
#ifdef debug
cerr << "Trying to find tail alignments for " << extended_seeds.size() << " extended seeds" << endl;
#endif
// Make paths for all the extensions
vector<Path> extension_paths;
vector<double> extension_path_scores;
extension_paths.reserve(extended_seeds.size());
extension_path_scores.reserve(extended_seeds.size());
for (auto& extended_seed : extended_seeds) {
// Compute the path for each extension
extension_paths.push_back(extended_seed.to_path(gbwt_graph, aln.sequence()));
// And the extension's score
extension_path_scores.push_back(get_regular_aligner()->score_partial_alignment(aln, gbwt_graph, extension_paths.back(),
aln.sequence().begin() + extended_seed.read_interval.first));
}
// We will keep the winning alignment here, in pieces
Path winning_left;
Path winning_middle;
Path winning_right;
size_t winning_score = 0;
Path second_left;
Path second_middle;
Path second_right;
size_t second_score = 0;
// Handle each extension in the set
process_until_threshold_b(extended_seeds, extension_path_scores,
extension_score_threshold, 1, max_local_extensions,
(function<double(size_t)>) [&](size_t extended_seed_num) {
// This extended seed looks good enough.
// TODO: We don't track this filter with the funnel because it
// operates within a single "item" (i.e. cluster/extension set).
// We track provenance at the item level, so throwing out wrong
// local alignments in a correct cluster would look like throwing
// out correct things.
// TODO: Revise how we track correctness and provenance to follow
// sub-cluster things.
// We start with the path in extension_paths[extended_seed_num],
// scored in extension_path_scores[extended_seed_num]
// We also have a left tail path and score
pair<Path, int64_t> left_tail_result {{}, 0};
// And a right tail path and score
pair<Path, int64_t> right_tail_result {{}, 0};
if (extended_seeds[extended_seed_num].read_interval.first != 0) {
// There is a left tail
// Get the forest of all left tail placements
auto forest = get_tail_forest(extended_seeds[extended_seed_num], aln.sequence().size(), true);
// Grab the part of the read sequence that comes before the extension
string before_sequence = aln.sequence().substr(0, extended_seeds[extended_seed_num].read_interval.first);
// Do right-pinned alignment
left_tail_result = std::move(get_best_alignment_against_any_tree(forest, before_sequence,
extended_seeds[extended_seed_num].starting_position(gbwt_graph), false));
}
if (extended_seeds[extended_seed_num].read_interval.second != aln.sequence().size()) {
// There is a right tail
// Get the forest of all right tail placements
auto forest = get_tail_forest(extended_seeds[extended_seed_num], aln.sequence().size(), false);
// Find the sequence
string trailing_sequence = aln.sequence().substr(extended_seeds[extended_seed_num].read_interval.second);
// Do left-pinned alignment
right_tail_result = std::move(get_best_alignment_against_any_tree(forest, trailing_sequence,
extended_seeds[extended_seed_num].tail_position(gbwt_graph), true));
}
// Compute total score
size_t total_score = extension_path_scores[extended_seed_num] + left_tail_result.second + right_tail_result.second;
//Get the node ids of the beginning and end of each alignment
id_t winning_start = winning_score == 0 ? 0 : (winning_left.mapping_size() == 0
? winning_middle.mapping(0).position().node_id()
: winning_left.mapping(0).position().node_id());
id_t current_start = left_tail_result.first.mapping_size() == 0
? extension_paths[extended_seed_num].mapping(0).position().node_id()
: left_tail_result.first.mapping(0).position().node_id();
id_t winning_end = winning_score == 0 ? 0 : (winning_right.mapping_size() == 0
? winning_middle.mapping(winning_middle.mapping_size() - 1).position().node_id()
: winning_right.mapping(winning_right.mapping_size()-1).position().node_id());
id_t current_end = right_tail_result.first.mapping_size() == 0
? extension_paths[extended_seed_num].mapping(extension_paths[extended_seed_num].mapping_size() - 1).position().node_id()
: right_tail_result.first.mapping(right_tail_result.first.mapping_size()-1).position().node_id();
//Is this left tail different from the currently winning left tail?
bool different_left = winning_start != current_start;
bool different_right = winning_end != current_end;
if (total_score > winning_score || winning_score == 0) {
// This is the new best alignment seen so far.
if (winning_score != 0 && different_left && different_right) {
//The previous best scoring alignment replaces the second best
second_score = winning_score;
second_left = std::move(winning_left);
second_middle = std::move(winning_middle);
second_right = std::move(winning_right);
}
// Save the score
winning_score = total_score;
// And the path parts
winning_left = std::move(left_tail_result.first);
winning_middle = std::move(extension_paths[extended_seed_num]);
winning_right = std::move(right_tail_result.first);
} else if ((total_score > second_score || second_score == 0) && different_left && different_right) {
// This is the new second best alignment seen so far and it is
// different from the best alignment.
// Save the score
second_score = total_score;
// And the path parts
second_left = std::move(left_tail_result.first);
second_middle = std::move(extension_paths[extended_seed_num]);
second_right = std::move(right_tail_result.first);
}
return true;
}, [&](size_t extended_seed_num) {
// This extended seed is good enough by its own score, but we have too many.
// Do nothing
}, [&](size_t extended_seed_num) {
// This extended seed isn't good enough by its own score.
// Do nothing
});
// Now we know the winning path and score. Move them over to out
best.set_score(winning_score);
second_best.set_score(second_score);
// Concatenate the paths. We know there must be at least an edit boundary
// between each part, because the maximal extension doesn't end in a
// mismatch or indel and eats all matches.
// We also don't need to worry about jumps that skip intervening sequence.
*best.mutable_path() = std::move(winning_left);
for (auto* to_append : {&winning_middle, &winning_right}) {
// For each path to append
for (auto& mapping : *to_append->mutable_mapping()) {
// For each mapping to append
if (mapping.position().offset() != 0 && best.path().mapping_size() > 0) {
// If we have a nonzero offset in our mapping, and we follow
// something, we must be continuing on from a previous mapping to
// the node.
assert(mapping.position().node_id() == best.path().mapping(best.path().mapping_size() - 1).position().node_id());
// Find that previous mapping
auto* prev_mapping = best.mutable_path()->mutable_mapping(best.path().mapping_size() - 1);
for (auto& edit : *mapping.mutable_edit()) {
// Move over all the edits in this mapping onto the end of that one.
*prev_mapping->add_edit() = std::move(edit);
}
} else {
// If we start at offset 0 or there's nothing before us, we need to just move the whole mapping
*best.mutable_path()->add_mapping() = std::move(mapping);
}
}
}
best.set_identity(identity(best.path()));
//Do the same for the second best
*second_best.mutable_path() = std::move(second_left);
for (auto* to_append : {&second_middle, &second_right}) {
// For each path to append
for (auto& mapping : *to_append->mutable_mapping()) {
// For each mapping to append
if (mapping.position().offset() != 0 && second_best.path().mapping_size() > 0) {
// If we have a nonzero offset in our mapping, and we follow
// something, we must be continuing on from a previous mapping to
// the node.
assert(mapping.position().node_id() == second_best.path().mapping(second_best.path().mapping_size() - 1).position().node_id());
// Find that previous mapping
auto* prev_mapping = second_best.mutable_path()->mutable_mapping(second_best.path().mapping_size() - 1);
for (auto& edit : *mapping.mutable_edit()) {
// Move over all the edits in this mapping onto the end of that one.
*prev_mapping->add_edit() = std::move(edit);
}
} else {
// If we start at offset 0 or there's nothing before us, we need to just move the whole mapping
*second_best.mutable_path()->add_mapping() = std::move(mapping);
}
}
}
// Compute the identity from the path.
second_best.set_identity(identity(second_best.path()));
}
pair<Path, size_t> MinimizerMapper::get_best_alignment_against_any_tree(const vector<TreeSubgraph>& trees,
const string& sequence, const Position& default_position, bool pin_left) const {
// We want the best alignment, to the base graph, done against any target path
Path best_path;
// And its score
int64_t best_score = 0;
if (!sequence.empty()) {
// We start out with the best alignment being a pure softclip.
// If we don't have any trees, or all trees are empty, or there's nothing beter, this is what we return.
Mapping* m = best_path.add_mapping();
Edit* e = m->add_edit();
e->set_from_length(0);
e->set_to_length(sequence.size());
e->set_sequence(sequence);
// Since the softclip consumes no graph, we place it on the node we are going to.
*m->mutable_position() = default_position;
#ifdef debug
cerr << "First best alignment: " << pb2json(best_path) << " score " << best_score << endl;
#endif
}
// We can align it once per target tree
for (auto& subgraph : trees) {
// For each tree we can map against, map pinning the correct edge of the sequence to the root.
if (subgraph.get_node_count() != 0) {
// This path has bases in it and could potentially be better than
// the default full-length softclip
// Do alignment to the subgraph with GSSWAligner.
Alignment current_alignment;
// If pinning right, we need to reverse the sequence, since we are
// always pinning left to the left edge of the tree subgraph.
current_alignment.set_sequence(pin_left ? sequence : reverse_complement(sequence));
#ifdef debug
cerr << "Align " << pb2json(current_alignment) << " pinned left";
#ifdef debug_dump_graph
cerr << " vs graph:" << endl;
subgraph.for_each_handle([&](const handle_t& here) {
cerr << subgraph.get_id(here) << " (" << subgraph.get_sequence(here) << "): " << endl;
subgraph.follow_edges(here, true, [&](const handle_t& there) {
cerr << "\t" << subgraph.get_id(there) << " (" << subgraph.get_sequence(there) << ") ->" << endl;
});
subgraph.follow_edges(here, false, [&](const handle_t& there) {
cerr << "\t-> " << subgraph.get_id(there) << " (" << subgraph.get_sequence(there) << ")" << endl;
});
});
#else
cerr << endl;
#endif
#endif
// X-drop align, accounting for full length bonus.
// We *always* do left-pinned alignment internally, since that's the shape of trees we get.
get_regular_aligner()->align_pinned(current_alignment, subgraph, true, true);
#ifdef debug
cerr << "\tScore: " << current_alignment.score() << endl;
#endif
if (current_alignment.score() > best_score) {
// This is a new best alignment.
best_path = current_alignment.path();
if (!pin_left) {
// Un-reverse it if we were pinning right
best_path = reverse_complement_path(best_path, [&](id_t node) {
return subgraph.get_length(subgraph.get_handle(node, false));
});
}
// Translate from subgraph into base graph and keep it.
best_path = subgraph.translate_down(best_path);
best_score = current_alignment.score();
#ifdef debug
cerr << "New best alignment is "
<< pb2json(best_path) << " score " << best_score << endl;
#endif
}
}
}
return make_pair(best_path, best_score);
}
vector<TreeSubgraph> MinimizerMapper::get_tail_forest(const GaplessExtension& extended_seed,
size_t read_length, bool left_tails) const {
// We will fill this in with all the trees we return
vector<TreeSubgraph> to_return;
// Now for this extension, walk the GBWT in the appropriate direction
#ifdef debug
cerr << "Look for " << (left_tails ? "left" : "right") << " tails from extension" << endl;
#endif
// TODO: Come up with a better way to do this with more accessors on the extension and less get_handle
// Get the Position reading out of the extension on the appropriate tail
Position from;
// And the length of that tail
size_t tail_length;
// And the GBWT search state we want to start with
const gbwt::SearchState* base_state = nullptr;
if (left_tails) {
// Look right from start
from = extended_seed.starting_position(gbwt_graph);
// And then flip to look the other way at the prev base
from = reverse(from, gbwt_graph.get_length(gbwt_graph.get_handle(from.node_id(), false)));
// Use the search state going backward
base_state = &extended_seed.state.backward;
tail_length = extended_seed.read_interval.first;
} else {
// Look right from end
from = extended_seed.tail_position(gbwt_graph);
// Use the search state going forward
base_state = &extended_seed.state.forward;
tail_length = read_length - extended_seed.read_interval.second;
}
if (tail_length == 0) {
// Don't go looking for places to put no tail.
return to_return;
}
// This is one tree that we are filling in
vector<pair<int64_t, handle_t>> tree;
// This is a stack of indexes at which we put parents in the tree
list<int64_t> parent_stack;
// Get the handle we are starting from
// TODO: is it cheaper to get this out of base_state?
handle_t start_handle = gbwt_graph.get_handle(from.node_id(), from.is_reverse());
// Decide if the start node will end up included in the tree, or if we cut it all off with the offset.
bool start_included = (from.offset() < gbwt_graph.get_length(start_handle));
// How long should we search? It should be the longest detectable gap plus the remaining sequence.
size_t search_limit = get_regular_aligner()->longest_detectable_gap(tail_length, read_length) + tail_length;
// Do a DFS over the haplotypes in the GBWT out to that distance.
dfs_gbwt(*base_state, from.offset(), search_limit, [&](const handle_t& entered) {
// Enter a new handle.
if (parent_stack.empty()) {
// This is the root of a new tree in the forrest
if (!tree.empty()) {
// Save the old tree and start a new one.
// We need to cut off from.offset() from the root, unless we would cut off the whole root.
// In that case, the GBWT DFS will have skipped the empty root entirely, so we cut off nothing.
to_return.emplace_back(&gbwt_graph, std::move(tree), start_included ? from.offset() : 0);
tree.clear();
}
// Add this to the tree with no parent
tree.emplace_back(-1, entered);
} else {
// Just say this is visitable from our parent.
tree.emplace_back(parent_stack.back(), entered);
}
// Record the parent index
parent_stack.push_back(tree.size() - 1);
}, [&]() {
// Exit the last visited handle. Pop off the stack.
parent_stack.pop_back();
});
if (!tree.empty()) {
// Now save the last tree
to_return.emplace_back(&gbwt_graph, std::move(tree), start_included ? from.offset() : 0);
tree.clear();
}
#ifdef debug
cerr << "Found " << to_return.size() << " trees" << endl;
#endif
// Now we have all the trees!
return to_return;
}
size_t MinimizerMapper::immutable_path_from_length(const ImmutablePath& path) {
size_t to_return = 0;
for (auto& m : path) {
// Sum up the from lengths of all the component Mappings
to_return += mapping_from_length(m);
}
return to_return;
}
Path MinimizerMapper::to_path(const ImmutablePath& path) {
Path to_return;
for (auto& m : path) {
// Copy all the Mappings into the Path.
*to_return.add_mapping() = m;
}
// Flip the order around to actual path order.
std::reverse(to_return.mutable_mapping()->begin(), to_return.mutable_mapping()->end());
// Return the completed path
return to_return;
}
void MinimizerMapper::dfs_gbwt(const Position& from, size_t walk_distance,
const function<void(const handle_t&)>& enter_handle, const function<void(void)> exit_handle) const {
// Get a handle to the node the from position is on, in the position's forward orientation
handle_t start_handle = gbwt_graph.get_handle(from.node_id(), from.is_reverse());
// Delegate to the handle-based version
dfs_gbwt(start_handle, from.offset(), walk_distance, enter_handle, exit_handle);
}
void MinimizerMapper::dfs_gbwt(handle_t from_handle, size_t from_offset, size_t walk_distance,
const function<void(const handle_t&)>& enter_handle, const function<void(void)> exit_handle) const {
// Turn from_handle into a SearchState for everything on it.
gbwt::SearchState start_state = gbwt_graph.get_state(from_handle);
// Delegate to the state-based version
dfs_gbwt(start_state, from_offset, walk_distance, enter_handle, exit_handle);
}
void MinimizerMapper::dfs_gbwt(const gbwt::SearchState& start_state, size_t from_offset, size_t walk_distance,
const function<void(const handle_t&)>& enter_handle, const function<void(void)> exit_handle) const {
// Holds the gbwt::SearchState we are at, and the distance we have consumed
using traversal_state_t = pair<gbwt::SearchState, size_t>;
if (start_state.empty()) {
// No haplotypes even visit the first node. Stop.
return;
}
// Get the handle we are starting on
handle_t from_handle = gbwt_graph.node_to_handle(start_state.node);
// The search state represents searching through the end of the node, so we have to consume that much search limit.
// Tack on how much search limit distance we consume by going to the end of
// the node. Our start position is a cut *between* bases, and we take everything after it.
// If the cut is at the offset of the whole length of the node, we take 0 bases.
// If it is at 0, we take all the bases in the node.
size_t distance_to_node_end = gbwt_graph.get_length(from_handle) - from_offset;
#ifdef debug
cerr << "DFS starting at offset " << from_offset << " on node of length "
<< gbwt_graph.get_length(from_handle) << " leaving " << distance_to_node_end << " bp" << endl;
#endif
// Have a recursive function that does the DFS. We fire the enter and exit
// callbacks, and the user can keep their own stack.
function<void(const gbwt::SearchState&, size_t, bool)> recursive_dfs = [&](const gbwt::SearchState& here_state,
size_t used_distance, bool hide_root) {
handle_t here_handle = gbwt_graph.node_to_handle(here_state.node);
if (!hide_root) {
// Enter this handle if there are any bases on it to visit
#ifdef debug
cerr << "Enter handle " << gbwt_graph.get_id(here_handle) << " " << gbwt_graph.get_is_reverse(here_handle) << endl;
#endif
enter_handle(here_handle);
}
// Up the used distance with our length
used_distance += gbwt_graph.get_length(here_handle);
if (used_distance < walk_distance) {
// If we haven't used up all our distance yet
gbwt_graph.follow_paths(here_state, [&](const gbwt::SearchState& there_state) -> bool {
// For each next state
// Otherwise, do it with the new distance value.
// Don't hide the root on any child subtrees; only the top root can need hiding.
recursive_dfs(there_state, used_distance, false);
return true;
});
}
if (!hide_root) {
// Exit this handle if we entered it
#ifdef debug
cerr << "Exit handle " << gbwt_graph.get_id(here_handle) << " " << gbwt_graph.get_is_reverse(here_handle) << endl;
#endif
exit_handle();
}
};
// Start the DFS with our stating node, consuming the distance from our
// offset to its end. Don't show the root state to the user if we don't
// actually visit any bases on that node.
recursive_dfs(start_state, distance_to_node_end, distance_to_node_end == 0);
}
}
|
#include "testing/testing.hpp"
#include "editor/config_loader.hpp"
#include "editor/editor_config.hpp"
#include "base/stl_helpers.hpp"
using namespace editor;
UNIT_TEST(EditorConfig_TypeDescription)
{
using EType = feature::Metadata::EType;
using Fields = editor::TypeAggregatedDescription::FeatureFields;
Fields const poi = {
feature::Metadata::FMD_OPEN_HOURS,
feature::Metadata::FMD_PHONE_NUMBER,
feature::Metadata::FMD_WEBSITE,
feature::Metadata::FMD_EMAIL,
feature::Metadata::FMD_LEVEL
};
pugi::xml_document doc;
ConfigLoader::LoadFromLocal(doc);
EditorConfig config;
config.SetConfig(doc);
{
editor::TypeAggregatedDescription desc;
TEST(!config.GetTypeDescription({"death-star"}, desc), ());
}
{
editor::TypeAggregatedDescription desc;
TEST(config.GetTypeDescription({"amenity-hunting_stand"}, desc), ());
TEST(desc.IsNameEditable(), ());
TEST(!desc.IsAddressEditable(), ());
TEST_EQUAL(desc.GetEditableFields(), Fields{EType::FMD_HEIGHT}, ());
}
{
editor::TypeAggregatedDescription desc;
TEST(config.GetTypeDescription({"shop-toys"}, desc), ());
TEST(desc.IsNameEditable(), ());
TEST(desc.IsAddressEditable(), ());
auto fields = poi;
fields.push_back(EType::FMD_INTERNET);
base::SortUnique(fields);
TEST_EQUAL(desc.GetEditableFields(), fields, ());
}
{
// Select amenity-bank because it goes first in config.
editor::TypeAggregatedDescription desc;
TEST(config.GetTypeDescription({"amenity-bar", "amenity-bank"}, desc), ());
TEST(desc.IsNameEditable(), ());
TEST(desc.IsAddressEditable(), ());
auto fields = poi;
fields.push_back(EType::FMD_OPERATOR);
base::SortUnique(fields);
TEST_EQUAL(desc.GetEditableFields(), fields, ());
}
{
// Testing type inheritance
editor::TypeAggregatedDescription desc;
TEST(config.GetTypeDescription({"amenity-place_of_worship-christian"}, desc), ());
TEST(desc.IsNameEditable(), ());
TEST_EQUAL(desc.GetEditableFields(), poi, ());
}
{
// Testing long type inheritance on a fake object
editor::TypeAggregatedDescription desc;
TEST(config.GetTypeDescription({"tourism-artwork-impresionism-monet"}, desc), ());
TEST(desc.IsNameEditable(), ());
TEST_EQUAL(desc.GetEditableFields(), Fields{}, ());
}
// TODO(mgsergio): Test case with priority="high" when there is one on editor.config.
}
UNIT_TEST(EditorConfig_GetTypesThatCanBeAdded)
{
pugi::xml_document doc;
ConfigLoader::LoadFromLocal(doc);
EditorConfig config;
config.SetConfig(doc);
auto const types = config.GetTypesThatCanBeAdded();
TEST(find(begin(types), end(types), "amenity-cafe") != end(types), ());
TEST(find(begin(types), end(types), "natural-peak") == end(types), ());
// Marked as "editable=no".
TEST(find(begin(types), end(types), "aeroway-airport") == end(types), ());
}
[editor][test] Fix test.
#include "testing/testing.hpp"
#include "editor/config_loader.hpp"
#include "editor/editor_config.hpp"
#include "base/stl_helpers.hpp"
using namespace editor;
UNIT_TEST(EditorConfig_TypeDescription)
{
using EType = feature::Metadata::EType;
using Fields = editor::TypeAggregatedDescription::FeatureFields;
Fields const poi = {
feature::Metadata::FMD_OPEN_HOURS,
feature::Metadata::FMD_PHONE_NUMBER,
feature::Metadata::FMD_WEBSITE,
feature::Metadata::FMD_EMAIL,
feature::Metadata::FMD_LEVEL
};
pugi::xml_document doc;
ConfigLoader::LoadFromLocal(doc);
EditorConfig config;
config.SetConfig(doc);
{
editor::TypeAggregatedDescription desc;
TEST(!config.GetTypeDescription({"death-star"}, desc), ());
}
{
editor::TypeAggregatedDescription desc;
TEST(config.GetTypeDescription({"amenity-hunting_stand"}, desc), ());
TEST(desc.IsNameEditable(), ());
TEST(!desc.IsAddressEditable(), ());
TEST_EQUAL(desc.GetEditableFields(), Fields{EType::FMD_HEIGHT}, ());
}
{
editor::TypeAggregatedDescription desc;
TEST(config.GetTypeDescription({"shop-toys"}, desc), ());
TEST(desc.IsNameEditable(), ());
TEST(desc.IsAddressEditable(), ());
auto fields = poi;
fields.push_back(EType::FMD_INTERNET);
base::SortUnique(fields);
TEST_EQUAL(desc.GetEditableFields(), fields, ());
}
{
// Select amenity-bank because it goes first in config.
editor::TypeAggregatedDescription desc;
TEST(config.GetTypeDescription({"amenity-bar", "amenity-bank"}, desc), ());
TEST(desc.IsNameEditable(), ());
TEST(desc.IsAddressEditable(), ());
auto fields = poi;
base::SortUnique(fields);
TEST_EQUAL(desc.GetEditableFields(), fields, ());
}
{
// Testing type inheritance
editor::TypeAggregatedDescription desc;
TEST(config.GetTypeDescription({"amenity-place_of_worship-christian"}, desc), ());
TEST(desc.IsNameEditable(), ());
TEST_EQUAL(desc.GetEditableFields(), poi, ());
}
{
// Testing long type inheritance on a fake object
editor::TypeAggregatedDescription desc;
TEST(config.GetTypeDescription({"tourism-artwork-impresionism-monet"}, desc), ());
TEST(desc.IsNameEditable(), ());
TEST_EQUAL(desc.GetEditableFields(), Fields{}, ());
}
// TODO(mgsergio): Test case with priority="high" when there is one on editor.config.
}
UNIT_TEST(EditorConfig_GetTypesThatCanBeAdded)
{
pugi::xml_document doc;
ConfigLoader::LoadFromLocal(doc);
EditorConfig config;
config.SetConfig(doc);
auto const types = config.GetTypesThatCanBeAdded();
TEST(find(begin(types), end(types), "amenity-cafe") != end(types), ());
TEST(find(begin(types), end(types), "natural-peak") == end(types), ());
// Marked as "editable=no".
TEST(find(begin(types), end(types), "aeroway-airport") == end(types), ());
}
|
/*************************************************************************/
/* multimesh_editor_plugin.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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. */
/*************************************************************************/
#include "multimesh_editor_plugin.h"
#include "scene/3d/mesh_instance.h"
#include "scene/gui/box_container.h"
#include "spatial_editor_plugin.h"
void MultiMeshEditor::_node_removed(Node *p_node) {
if (p_node == node) {
node = nullptr;
hide();
}
}
void MultiMeshEditor::_populate() {
if (!node) {
return;
}
Ref<Mesh> mesh;
if (mesh_source->get_text() == "") {
Ref<MultiMesh> multimesh;
multimesh = node->get_multimesh();
if (multimesh.is_null()) {
err_dialog->set_text(TTR("No mesh source specified (and no MultiMesh set in node)."));
err_dialog->popup_centered_minsize();
return;
}
if (multimesh->get_mesh().is_null()) {
err_dialog->set_text(TTR("No mesh source specified (and MultiMesh contains no Mesh)."));
err_dialog->popup_centered_minsize();
return;
}
mesh = multimesh->get_mesh();
} else {
Node *ms_node = node->get_node(mesh_source->get_text());
if (!ms_node) {
err_dialog->set_text(TTR("Mesh source is invalid (invalid path)."));
err_dialog->popup_centered_minsize();
return;
}
MeshInstance *ms_instance = Object::cast_to<MeshInstance>(ms_node);
if (!ms_instance) {
err_dialog->set_text(TTR("Mesh source is invalid (not a MeshInstance)."));
err_dialog->popup_centered_minsize();
return;
}
mesh = ms_instance->get_mesh();
if (mesh.is_null()) {
err_dialog->set_text(TTR("Mesh source is invalid (contains no Mesh resource)."));
err_dialog->popup_centered_minsize();
return;
}
}
if (surface_source->get_text() == "") {
err_dialog->set_text(TTR("No surface source specified."));
err_dialog->popup_centered_minsize();
return;
}
Node *ss_node = node->get_node(surface_source->get_text());
if (!ss_node) {
err_dialog->set_text(TTR("Surface source is invalid (invalid path)."));
err_dialog->popup_centered_minsize();
return;
}
GeometryInstance *ss_instance = Object::cast_to<MeshInstance>(ss_node);
if (!ss_instance) {
err_dialog->set_text(TTR("Surface source is invalid (no geometry)."));
err_dialog->popup_centered_minsize();
return;
}
Transform geom_xform = node->get_global_transform().affine_inverse() * ss_instance->get_global_transform();
PoolVector<Face3> geometry = ss_instance->get_faces(VisualInstance::FACES_SOLID);
if (geometry.size() == 0) {
err_dialog->set_text(TTR("Surface source is invalid (no faces)."));
err_dialog->popup_centered_minsize();
return;
}
//make all faces local
int gc = geometry.size();
PoolVector<Face3>::Write w = geometry.write();
for (int i = 0; i < gc; i++) {
for (int j = 0; j < 3; j++) {
w[i].vertex[j] = geom_xform.xform(w[i].vertex[j]);
}
}
w.release();
PoolVector<Face3> faces = geometry;
int facecount = faces.size();
ERR_FAIL_COND_MSG(!facecount, "Parent has no solid faces to populate.");
PoolVector<Face3>::Read r = faces.read();
float area_accum = 0;
Map<float, int> triangle_area_map;
for (int i = 0; i < facecount; i++) {
float area = r[i].get_area();
if (area < CMP_EPSILON) {
continue;
}
triangle_area_map[area_accum] = i;
area_accum += area;
}
ERR_FAIL_COND_MSG(triangle_area_map.size() == 0, "Couldn't map area.");
ERR_FAIL_COND_MSG(area_accum == 0, "Couldn't map area.");
Ref<MultiMesh> multimesh = memnew(MultiMesh);
multimesh->set_mesh(mesh);
int instance_count = populate_amount->get_value();
multimesh->set_transform_format(MultiMesh::TRANSFORM_3D);
multimesh->set_color_format(node->get_multimesh()->get_color_format());
multimesh->set_custom_data_format(node->get_multimesh()->get_custom_data_format());
multimesh->set_instance_count(instance_count);
float _tilt_random = populate_tilt_random->get_value();
float _rotate_random = populate_rotate_random->get_value();
float _scale_random = populate_scale_random->get_value();
float _scale = populate_scale->get_value();
int axis = populate_axis->get_selected();
Transform axis_xform;
if (axis == Vector3::AXIS_Z) {
axis_xform.rotate(Vector3(1, 0, 0), -Math_PI * 0.5);
}
if (axis == Vector3::AXIS_X) {
axis_xform.rotate(Vector3(0, 0, 1), -Math_PI * 0.5);
}
for (int i = 0; i < instance_count; i++) {
float areapos = Math::random(0.0f, area_accum);
Map<float, int>::Element *E = triangle_area_map.find_closest(areapos);
ERR_FAIL_COND(!E);
int index = E->get();
ERR_FAIL_INDEX(index, facecount);
// ok FINALLY get face
Face3 face = r[index];
//now compute some position inside the face...
Vector3 pos = face.get_random_point_inside();
Vector3 normal = face.get_plane().normal;
Vector3 op_axis = (face.vertex[0] - face.vertex[1]).normalized();
Transform xform;
xform.set_look_at(pos, pos + op_axis, normal);
xform = xform * axis_xform;
Basis post_xform;
post_xform.rotate(xform.basis.get_axis(1), -Math::random(-_rotate_random, _rotate_random) * Math_PI);
post_xform.rotate(xform.basis.get_axis(2), -Math::random(-_tilt_random, _tilt_random) * Math_PI);
post_xform.rotate(xform.basis.get_axis(0), -Math::random(-_tilt_random, _tilt_random) * Math_PI);
xform.basis = post_xform * xform.basis;
//xform.basis.orthonormalize();
xform.basis.scale(Vector3(1, 1, 1) * (_scale + Math::random(-_scale_random, _scale_random)));
multimesh->set_instance_transform(i, xform);
}
node->set_multimesh(multimesh);
}
void MultiMeshEditor::_browsed(const NodePath &p_path) {
NodePath path = node->get_path_to(get_node(p_path));
if (browsing_source) {
mesh_source->set_text(path);
} else {
surface_source->set_text(path);
}
}
void MultiMeshEditor::_menu_option(int p_option) {
switch (p_option) {
case MENU_OPTION_POPULATE: {
if (_last_pp_node != node) {
surface_source->set_text("..");
mesh_source->set_text("..");
populate_axis->select(1);
populate_rotate_random->set_value(0);
populate_tilt_random->set_value(0);
populate_scale_random->set_value(0);
populate_scale->set_value(1);
populate_amount->set_value(128);
_last_pp_node = node;
}
populate_dialog->popup_centered(Size2(250, 380));
} break;
}
}
void MultiMeshEditor::edit(MultiMeshInstance *p_multimesh) {
node = p_multimesh;
}
void MultiMeshEditor::_browse(bool p_source) {
browsing_source = p_source;
std->get_scene_tree()->set_marked(node, false);
std->popup_centered_ratio();
if (p_source) {
std->set_title(TTR("Select a Source Mesh:"));
} else {
std->set_title(TTR("Select a Target Surface:"));
}
}
void MultiMeshEditor::_bind_methods() {
ClassDB::bind_method("_menu_option", &MultiMeshEditor::_menu_option);
ClassDB::bind_method("_populate", &MultiMeshEditor::_populate);
ClassDB::bind_method("_browsed", &MultiMeshEditor::_browsed);
ClassDB::bind_method("_browse", &MultiMeshEditor::_browse);
}
MultiMeshEditor::MultiMeshEditor() {
options = memnew(MenuButton);
options->set_switch_on_hover(true);
SpatialEditor::get_singleton()->add_control_to_menu_panel(options);
options->set_text("MultiMesh");
options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("MultiMeshInstance", "EditorIcons"));
options->get_popup()->add_item(TTR("Populate Surface"));
options->get_popup()->connect("id_pressed", this, "_menu_option");
populate_dialog = memnew(ConfirmationDialog);
populate_dialog->set_title(TTR("Populate MultiMesh"));
add_child(populate_dialog);
VBoxContainer *vbc = memnew(VBoxContainer);
populate_dialog->add_child(vbc);
//populate_dialog->set_child_rect(vbc);
HBoxContainer *hbc = memnew(HBoxContainer);
surface_source = memnew(LineEdit);
hbc->add_child(surface_source);
surface_source->set_h_size_flags(SIZE_EXPAND_FILL);
Button *b = memnew(Button);
hbc->add_child(b);
b->set_text("..");
b->connect("pressed", this, "_browse", make_binds(false));
vbc->add_margin_child(TTR("Target Surface:"), hbc);
hbc = memnew(HBoxContainer);
mesh_source = memnew(LineEdit);
hbc->add_child(mesh_source);
mesh_source->set_h_size_flags(SIZE_EXPAND_FILL);
b = memnew(Button);
hbc->add_child(b);
b->set_text("..");
vbc->add_margin_child(TTR("Source Mesh:"), hbc);
b->connect("pressed", this, "_browse", make_binds(true));
populate_axis = memnew(OptionButton);
populate_axis->add_item(TTR("X-Axis"));
populate_axis->add_item(TTR("Y-Axis"));
populate_axis->add_item(TTR("Z-Axis"));
populate_axis->select(2);
vbc->add_margin_child(TTR("Mesh Up Axis:"), populate_axis);
populate_rotate_random = memnew(HSlider);
populate_rotate_random->set_max(1);
populate_rotate_random->set_step(0.01);
vbc->add_margin_child(TTR("Random Rotation:"), populate_rotate_random);
populate_tilt_random = memnew(HSlider);
populate_tilt_random->set_max(1);
populate_tilt_random->set_step(0.01);
vbc->add_margin_child(TTR("Random Tilt:"), populate_tilt_random);
populate_scale_random = memnew(SpinBox);
populate_scale_random->set_min(0);
populate_scale_random->set_max(1);
populate_scale_random->set_value(0);
populate_scale_random->set_step(0.01);
vbc->add_margin_child(TTR("Random Scale:"), populate_scale_random);
populate_scale = memnew(SpinBox);
populate_scale->set_min(0.001);
populate_scale->set_max(4096);
populate_scale->set_value(1);
populate_scale->set_step(0.01);
vbc->add_margin_child(TTR("Scale:"), populate_scale);
populate_amount = memnew(SpinBox);
populate_amount->set_anchor(MARGIN_RIGHT, ANCHOR_END);
populate_amount->set_begin(Point2(20, 232));
populate_amount->set_end(Point2(-5, 237));
populate_amount->set_min(1);
populate_amount->set_max(65536);
populate_amount->set_value(128);
vbc->add_margin_child(TTR("Amount:"), populate_amount);
populate_dialog->get_ok()->set_text(TTR("Populate"));
populate_dialog->get_ok()->connect("pressed", this, "_populate");
std = memnew(SceneTreeDialog);
populate_dialog->add_child(std);
std->connect("selected", this, "_browsed");
_last_pp_node = nullptr;
err_dialog = memnew(AcceptDialog);
add_child(err_dialog);
}
void MultiMeshEditorPlugin::edit(Object *p_object) {
multimesh_editor->edit(Object::cast_to<MultiMeshInstance>(p_object));
}
bool MultiMeshEditorPlugin::handles(Object *p_object) const {
return p_object->is_class("MultiMeshInstance");
}
void MultiMeshEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
multimesh_editor->options->show();
} else {
multimesh_editor->options->hide();
multimesh_editor->edit(nullptr);
}
}
MultiMeshEditorPlugin::MultiMeshEditorPlugin(EditorNode *p_node) {
editor = p_node;
multimesh_editor = memnew(MultiMeshEditor);
editor->get_viewport()->add_child(multimesh_editor);
multimesh_editor->options->hide();
}
MultiMeshEditorPlugin::~MultiMeshEditorPlugin() {
}
Fixed Populating MultimeshInstance Crash
When populating a MultimeshInstance (node), Godot would set the
new Multimesh's color and custom data format as the current node's
multimesh, which would cause a crash if node's multimesh is null.
Populate Function will now check if node has a multimesh or not, and
set the new multimesh with default (NONE) values if node's multimesh is
null.
Fixes Issue #61553
/*************************************************************************/
/* multimesh_editor_plugin.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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. */
/*************************************************************************/
#include "multimesh_editor_plugin.h"
#include "scene/3d/mesh_instance.h"
#include "scene/gui/box_container.h"
#include "spatial_editor_plugin.h"
void MultiMeshEditor::_node_removed(Node *p_node) {
if (p_node == node) {
node = nullptr;
hide();
}
}
void MultiMeshEditor::_populate() {
if (!node) {
return;
}
Ref<Mesh> mesh;
if (mesh_source->get_text() == "") {
Ref<MultiMesh> multimesh;
multimesh = node->get_multimesh();
if (multimesh.is_null()) {
err_dialog->set_text(TTR("No mesh source specified (and no MultiMesh set in node)."));
err_dialog->popup_centered_minsize();
return;
}
if (multimesh->get_mesh().is_null()) {
err_dialog->set_text(TTR("No mesh source specified (and MultiMesh contains no Mesh)."));
err_dialog->popup_centered_minsize();
return;
}
mesh = multimesh->get_mesh();
} else {
Node *ms_node = node->get_node(mesh_source->get_text());
if (!ms_node) {
err_dialog->set_text(TTR("Mesh source is invalid (invalid path)."));
err_dialog->popup_centered_minsize();
return;
}
MeshInstance *ms_instance = Object::cast_to<MeshInstance>(ms_node);
if (!ms_instance) {
err_dialog->set_text(TTR("Mesh source is invalid (not a MeshInstance)."));
err_dialog->popup_centered_minsize();
return;
}
mesh = ms_instance->get_mesh();
if (mesh.is_null()) {
err_dialog->set_text(TTR("Mesh source is invalid (contains no Mesh resource)."));
err_dialog->popup_centered_minsize();
return;
}
}
if (surface_source->get_text() == "") {
err_dialog->set_text(TTR("No surface source specified."));
err_dialog->popup_centered_minsize();
return;
}
Node *ss_node = node->get_node(surface_source->get_text());
if (!ss_node) {
err_dialog->set_text(TTR("Surface source is invalid (invalid path)."));
err_dialog->popup_centered_minsize();
return;
}
GeometryInstance *ss_instance = Object::cast_to<MeshInstance>(ss_node);
if (!ss_instance) {
err_dialog->set_text(TTR("Surface source is invalid (no geometry)."));
err_dialog->popup_centered_minsize();
return;
}
Transform geom_xform = node->get_global_transform().affine_inverse() * ss_instance->get_global_transform();
PoolVector<Face3> geometry = ss_instance->get_faces(VisualInstance::FACES_SOLID);
if (geometry.size() == 0) {
err_dialog->set_text(TTR("Surface source is invalid (no faces)."));
err_dialog->popup_centered_minsize();
return;
}
//make all faces local
int gc = geometry.size();
PoolVector<Face3>::Write w = geometry.write();
for (int i = 0; i < gc; i++) {
for (int j = 0; j < 3; j++) {
w[i].vertex[j] = geom_xform.xform(w[i].vertex[j]);
}
}
w.release();
PoolVector<Face3> faces = geometry;
int facecount = faces.size();
ERR_FAIL_COND_MSG(!facecount, "Parent has no solid faces to populate.");
PoolVector<Face3>::Read r = faces.read();
float area_accum = 0;
Map<float, int> triangle_area_map;
for (int i = 0; i < facecount; i++) {
float area = r[i].get_area();
if (area < CMP_EPSILON) {
continue;
}
triangle_area_map[area_accum] = i;
area_accum += area;
}
ERR_FAIL_COND_MSG(triangle_area_map.size() == 0, "Couldn't map area.");
ERR_FAIL_COND_MSG(area_accum == 0, "Couldn't map area.");
Ref<MultiMesh> multimesh = memnew(MultiMesh);
multimesh->set_mesh(mesh);
int instance_count = populate_amount->get_value();
multimesh->set_transform_format(MultiMesh::TRANSFORM_3D);
if (node->get_multimesh().is_null()) {
multimesh->set_color_format(MultiMesh::COLOR_NONE);
multimesh->set_custom_data_format(MultiMesh::CUSTOM_DATA_NONE);
} else {
multimesh->set_color_format(node->get_multimesh()->get_color_format());
multimesh->set_custom_data_format(node->get_multimesh()->get_custom_data_format());
}
multimesh->set_instance_count(instance_count);
float _tilt_random = populate_tilt_random->get_value();
float _rotate_random = populate_rotate_random->get_value();
float _scale_random = populate_scale_random->get_value();
float _scale = populate_scale->get_value();
int axis = populate_axis->get_selected();
Transform axis_xform;
if (axis == Vector3::AXIS_Z) {
axis_xform.rotate(Vector3(1, 0, 0), -Math_PI * 0.5);
}
if (axis == Vector3::AXIS_X) {
axis_xform.rotate(Vector3(0, 0, 1), -Math_PI * 0.5);
}
for (int i = 0; i < instance_count; i++) {
float areapos = Math::random(0.0f, area_accum);
Map<float, int>::Element *E = triangle_area_map.find_closest(areapos);
ERR_FAIL_COND(!E);
int index = E->get();
ERR_FAIL_INDEX(index, facecount);
// ok FINALLY get face
Face3 face = r[index];
//now compute some position inside the face...
Vector3 pos = face.get_random_point_inside();
Vector3 normal = face.get_plane().normal;
Vector3 op_axis = (face.vertex[0] - face.vertex[1]).normalized();
Transform xform;
xform.set_look_at(pos, pos + op_axis, normal);
xform = xform * axis_xform;
Basis post_xform;
post_xform.rotate(xform.basis.get_axis(1), -Math::random(-_rotate_random, _rotate_random) * Math_PI);
post_xform.rotate(xform.basis.get_axis(2), -Math::random(-_tilt_random, _tilt_random) * Math_PI);
post_xform.rotate(xform.basis.get_axis(0), -Math::random(-_tilt_random, _tilt_random) * Math_PI);
xform.basis = post_xform * xform.basis;
//xform.basis.orthonormalize();
xform.basis.scale(Vector3(1, 1, 1) * (_scale + Math::random(-_scale_random, _scale_random)));
multimesh->set_instance_transform(i, xform);
}
node->set_multimesh(multimesh);
}
void MultiMeshEditor::_browsed(const NodePath &p_path) {
NodePath path = node->get_path_to(get_node(p_path));
if (browsing_source) {
mesh_source->set_text(path);
} else {
surface_source->set_text(path);
}
}
void MultiMeshEditor::_menu_option(int p_option) {
switch (p_option) {
case MENU_OPTION_POPULATE: {
if (_last_pp_node != node) {
surface_source->set_text("..");
mesh_source->set_text("..");
populate_axis->select(1);
populate_rotate_random->set_value(0);
populate_tilt_random->set_value(0);
populate_scale_random->set_value(0);
populate_scale->set_value(1);
populate_amount->set_value(128);
_last_pp_node = node;
}
populate_dialog->popup_centered(Size2(250, 380));
} break;
}
}
void MultiMeshEditor::edit(MultiMeshInstance *p_multimesh) {
node = p_multimesh;
}
void MultiMeshEditor::_browse(bool p_source) {
browsing_source = p_source;
std->get_scene_tree()->set_marked(node, false);
std->popup_centered_ratio();
if (p_source) {
std->set_title(TTR("Select a Source Mesh:"));
} else {
std->set_title(TTR("Select a Target Surface:"));
}
}
void MultiMeshEditor::_bind_methods() {
ClassDB::bind_method("_menu_option", &MultiMeshEditor::_menu_option);
ClassDB::bind_method("_populate", &MultiMeshEditor::_populate);
ClassDB::bind_method("_browsed", &MultiMeshEditor::_browsed);
ClassDB::bind_method("_browse", &MultiMeshEditor::_browse);
}
MultiMeshEditor::MultiMeshEditor() {
options = memnew(MenuButton);
options->set_switch_on_hover(true);
SpatialEditor::get_singleton()->add_control_to_menu_panel(options);
options->set_text("MultiMesh");
options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("MultiMeshInstance", "EditorIcons"));
options->get_popup()->add_item(TTR("Populate Surface"));
options->get_popup()->connect("id_pressed", this, "_menu_option");
populate_dialog = memnew(ConfirmationDialog);
populate_dialog->set_title(TTR("Populate MultiMesh"));
add_child(populate_dialog);
VBoxContainer *vbc = memnew(VBoxContainer);
populate_dialog->add_child(vbc);
//populate_dialog->set_child_rect(vbc);
HBoxContainer *hbc = memnew(HBoxContainer);
surface_source = memnew(LineEdit);
hbc->add_child(surface_source);
surface_source->set_h_size_flags(SIZE_EXPAND_FILL);
Button *b = memnew(Button);
hbc->add_child(b);
b->set_text("..");
b->connect("pressed", this, "_browse", make_binds(false));
vbc->add_margin_child(TTR("Target Surface:"), hbc);
hbc = memnew(HBoxContainer);
mesh_source = memnew(LineEdit);
hbc->add_child(mesh_source);
mesh_source->set_h_size_flags(SIZE_EXPAND_FILL);
b = memnew(Button);
hbc->add_child(b);
b->set_text("..");
vbc->add_margin_child(TTR("Source Mesh:"), hbc);
b->connect("pressed", this, "_browse", make_binds(true));
populate_axis = memnew(OptionButton);
populate_axis->add_item(TTR("X-Axis"));
populate_axis->add_item(TTR("Y-Axis"));
populate_axis->add_item(TTR("Z-Axis"));
populate_axis->select(2);
vbc->add_margin_child(TTR("Mesh Up Axis:"), populate_axis);
populate_rotate_random = memnew(HSlider);
populate_rotate_random->set_max(1);
populate_rotate_random->set_step(0.01);
vbc->add_margin_child(TTR("Random Rotation:"), populate_rotate_random);
populate_tilt_random = memnew(HSlider);
populate_tilt_random->set_max(1);
populate_tilt_random->set_step(0.01);
vbc->add_margin_child(TTR("Random Tilt:"), populate_tilt_random);
populate_scale_random = memnew(SpinBox);
populate_scale_random->set_min(0);
populate_scale_random->set_max(1);
populate_scale_random->set_value(0);
populate_scale_random->set_step(0.01);
vbc->add_margin_child(TTR("Random Scale:"), populate_scale_random);
populate_scale = memnew(SpinBox);
populate_scale->set_min(0.001);
populate_scale->set_max(4096);
populate_scale->set_value(1);
populate_scale->set_step(0.01);
vbc->add_margin_child(TTR("Scale:"), populate_scale);
populate_amount = memnew(SpinBox);
populate_amount->set_anchor(MARGIN_RIGHT, ANCHOR_END);
populate_amount->set_begin(Point2(20, 232));
populate_amount->set_end(Point2(-5, 237));
populate_amount->set_min(1);
populate_amount->set_max(65536);
populate_amount->set_value(128);
vbc->add_margin_child(TTR("Amount:"), populate_amount);
populate_dialog->get_ok()->set_text(TTR("Populate"));
populate_dialog->get_ok()->connect("pressed", this, "_populate");
std = memnew(SceneTreeDialog);
populate_dialog->add_child(std);
std->connect("selected", this, "_browsed");
_last_pp_node = nullptr;
err_dialog = memnew(AcceptDialog);
add_child(err_dialog);
}
void MultiMeshEditorPlugin::edit(Object *p_object) {
multimesh_editor->edit(Object::cast_to<MultiMeshInstance>(p_object));
}
bool MultiMeshEditorPlugin::handles(Object *p_object) const {
return p_object->is_class("MultiMeshInstance");
}
void MultiMeshEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
multimesh_editor->options->show();
} else {
multimesh_editor->options->hide();
multimesh_editor->edit(nullptr);
}
}
MultiMeshEditorPlugin::MultiMeshEditorPlugin(EditorNode *p_node) {
editor = p_node;
multimesh_editor = memnew(MultiMeshEditor);
editor->get_viewport()->add_child(multimesh_editor);
multimesh_editor->options->hide();
}
MultiMeshEditorPlugin::~MultiMeshEditorPlugin() {
}
|
/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson
*
* Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/gui.hpp"
#include "guichan/basiccontainer.hpp"
#include "guichan/exception.hpp"
#include "guichan/focushandler.hpp"
#include "guichan/graphics.hpp"
#include "guichan/input.hpp"
#include "guichan/keyinput.hpp"
#include "guichan/keylistener.hpp"
#include "guichan/mouseinput.hpp"
#include "guichan/mouselistener.hpp"
#include "guichan/widget.hpp"
namespace gcn
{
Gui::Gui()
:mTop(NULL),
mGraphics(NULL),
mInput(NULL),
mTabbing(true),
mShiftPressed(false),
mMetaPressed(false),
mControlPressed(false),
mAltPressed(false),
mLastMousePressButton(0),
mLastMousePressTimeStamp(0),
mLastMouseX(0),
mLastMouseY(0),
mClickCount(0),
mLastMouseDragButton(0)
{
mFocusHandler = new FocusHandler();
}
Gui::~Gui()
{
if (Widget::widgetExists(mTop))
{
setTop(NULL);
}
delete mFocusHandler;
}
void Gui::setTop(Widget* top)
{
if (mTop != NULL)
{
mTop->_setFocusHandler(NULL);
}
if (top != NULL)
{
top->_setFocusHandler(mFocusHandler);
}
mTop = top;
}
Widget* Gui::getTop() const
{
return mTop;
}
void Gui::setGraphics(Graphics* graphics)
{
mGraphics = graphics;
}
Graphics* Gui::getGraphics() const
{
return mGraphics;
}
void Gui::setInput(Input* input)
{
mInput = input;
}
Input* Gui::getInput() const
{
return mInput;
}
void Gui::logic()
{
if (mTop == NULL)
{
throw GCN_EXCEPTION("No top widget set");
}
// Release of modal focus or modal mouse input focus might make it
// necessary to distribute mouse events.
handleModalFocusRelease();
handleModalMouseInputFocusRelease();
if (mInput != NULL)
{
mInput->_pollInput();
handleKeyInput();
handleMouseInput();
} // end if
mTop->logic();
}
void Gui::draw()
{
if (mTop == NULL)
{
throw GCN_EXCEPTION("No top widget set");
}
if (mGraphics == NULL)
{
throw GCN_EXCEPTION("No graphics set");
}
if (!mTop->isVisible())
{
return;
}
mGraphics->_beginDraw();
// If top has a border,
// draw it before drawing top
if (mTop->getBorderSize() > 0)
{
Rectangle rec = mTop->getDimension();
rec.x -= mTop->getBorderSize();
rec.y -= mTop->getBorderSize();
rec.width += 2 * mTop->getBorderSize();
rec.height += 2 * mTop->getBorderSize();
mGraphics->pushClipArea(rec);
mTop->drawBorder(mGraphics);
mGraphics->popClipArea();
}
mGraphics->pushClipArea(mTop->getDimension());
mTop->draw(mGraphics);
mGraphics->popClipArea();
mGraphics->_endDraw();
}
void Gui::focusNone()
{
mFocusHandler->focusNone();
}
void Gui::setTabbingEnabled(bool tabbing)
{
mTabbing = tabbing;
}
bool Gui::isTabbingEnabled()
{
return mTabbing;
}
void Gui::addGlobalKeyListener(KeyListener* keyListener)
{
mKeyListeners.push_back(keyListener);
}
void Gui::removeGlobalKeyListener(KeyListener* keyListener)
{
mKeyListeners.remove(keyListener);
}
void Gui::handleMouseInput()
{
while (!mInput->isMouseQueueEmpty())
{
MouseInput mouseInput = mInput->dequeueMouseInput();
// Save the current mouse state. It will be needed if modal focus
// changes or modal mouse input focus changes.
mLastMouseX = mouseInput.getX();
mLastMouseY = mouseInput.getY();
switch (mouseInput.getType())
{
case MouseInput::PRESSED:
handleMousePressed(mouseInput);
break;
case MouseInput::RELEASED:
handleMouseReleased(mouseInput);
break;
case MouseInput::MOVED:
handleMouseMoved(mouseInput);
break;
case MouseInput::WHEEL_MOVED_DOWN:
handleMouseWheelMovedDown(mouseInput);
break;
case MouseInput::WHEEL_MOVED_UP:
handleMouseWheelMovedUp(mouseInput);
break;
default:
throw GCN_EXCEPTION("Unknown mouse input type.");
break;
}
}
}
void Gui::handleKeyInput()
{
while (!mInput->isKeyQueueEmpty())
{
KeyInput keyInput = mInput->dequeueKeyInput();
// Save modifiers state
mShiftPressed = keyInput.isShiftPressed();
mMetaPressed = keyInput.isMetaPressed();
mControlPressed = keyInput.isControlPressed();
mAltPressed = keyInput.isAltPressed();
KeyEvent keyEventToGlobalKeyListeners(NULL,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
keyInput.getType(),
keyInput.isNumericPad(),
keyInput.getKey());
distributeKeyEventToGlobalKeyListeners(keyEventToGlobalKeyListeners);
// If a global key listener consumes the event it will not be
// sent further to the source of the event.
if (keyEventToGlobalKeyListeners.isConsumed())
{
continue;
}
bool keyEventConsumed = false;
// Send key inputs to the focused widgets
if (mFocusHandler->getFocused() != NULL)
{
KeyEvent keyEvent(getKeyEventSource(),
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
keyInput.getType(),
keyInput.isNumericPad(),
keyInput.getKey());
if (!mFocusHandler->getFocused()->isFocusable())
{
mFocusHandler->focusNone();
}
else
{
distributeKeyEvent(keyEvent);
}
keyEventConsumed = keyEvent.isConsumed();
}
// If the key event hasn't been consumed and
// tabbing is enable check for tab press and
// change focus.
if (!keyEventConsumed
&& mTabbing
&& keyInput.getKey().getValue() == Key::TAB
&& keyInput.getType() == KeyInput::PRESSED)
{
if (keyInput.isShiftPressed())
{
mFocusHandler->tabPrevious();
}
else
{
mFocusHandler->tabNext();
}
}
} // end while
}
void Gui::handleMouseMoved(const MouseInput& mouseInput)
{
// Check if the mouse leaves the application window.
if (mFocusHandler->getLastWidgetWithMouse() != NULL
&& (mouseInput.getX() < 0
|| mouseInput.getY() < 0
|| !mTop->getDimension().isPointInRect(mouseInput.getX(), mouseInput.getY()))
)
{
int lastWidgetWithMouseX, lastWidgetWithMouseY;
mFocusHandler->getLastWidgetWithMouse()->getAbsolutePosition(lastWidgetWithMouseX, lastWidgetWithMouseY);
MouseEvent mouseEvent(mFocusHandler->getLastWidgetWithMouse(),
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::EXITED,
mouseInput.getButton(),
mouseInput.getX() - lastWidgetWithMouseX,
mouseInput.getY() - lastWidgetWithMouseY,
mClickCount);
distributeMouseEvent(mouseEvent, true, true);
mFocusHandler->setLastWidgetWithMouse(NULL);
return;
}
Widget* sourceWidget = getMouseEventSource(mouseInput.getX(), mouseInput.getY());
if (sourceWidget != mFocusHandler->getLastWidgetWithMouse())
{
if (mFocusHandler->getLastWidgetWithMouse() != NULL)
{
int lastWidgetWithMouseX, lastWidgetWithMouseY;
mFocusHandler->getLastWidgetWithMouse()->getAbsolutePosition(lastWidgetWithMouseX, lastWidgetWithMouseY);
MouseEvent mouseEvent(mFocusHandler->getLastWidgetWithMouse(),
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::EXITED,
mouseInput.getButton(),
mouseInput.getX() - lastWidgetWithMouseX,
mouseInput.getY() - lastWidgetWithMouseY,
mClickCount);
distributeMouseEvent(mouseEvent, true, true);
mClickCount = 0;
mLastMousePressTimeStamp = 0;
}
int sourceWidgetX, sourceWidgetY;
sourceWidget->getAbsolutePosition(sourceWidgetX, sourceWidgetY);
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::ENTERED,
mouseInput.getButton(),
mouseInput.getX() - sourceWidgetX,
mouseInput.getY() - sourceWidgetY,
mClickCount);
distributeMouseEvent(mouseEvent, true, true);
mFocusHandler->setLastWidgetWithMouse(sourceWidget);
}
if (mFocusHandler->getDraggedWidget() != NULL)
{
int draggedWidgetX, draggedWidgetY;
mFocusHandler->getDraggedWidget()->getAbsolutePosition(draggedWidgetX, draggedWidgetY);
MouseEvent mouseEvent(mFocusHandler->getDraggedWidget(),
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::DRAGGED,
mLastMouseDragButton,
mouseInput.getX() - draggedWidgetX,
mouseInput.getY() - draggedWidgetY,
mClickCount);
distributeMouseEvent(mouseEvent);
}
else
{
int sourceWidgetX, sourceWidgetY;
sourceWidget->getAbsolutePosition(sourceWidgetX, sourceWidgetY);
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::MOVED,
mouseInput.getButton(),
mouseInput.getX() - sourceWidgetX,
mouseInput.getY() - sourceWidgetY,
mClickCount);
distributeMouseEvent(mouseEvent);
}
}
void Gui::handleMousePressed(const MouseInput& mouseInput)
{
Widget* sourceWidget = getMouseEventSource(mouseInput.getX(), mouseInput.getY());
if (mFocusHandler->getDraggedWidget() != NULL)
{
sourceWidget = mFocusHandler->getDraggedWidget();
}
int sourceWidgetX, sourceWidgetY;
sourceWidget->getAbsolutePosition(sourceWidgetX, sourceWidgetY);
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::PRESSED,
mouseInput.getButton(),
mouseInput.getX() - sourceWidgetX,
mouseInput.getY() - sourceWidgetY,
mClickCount);
distributeMouseEvent(mouseEvent);
mFocusHandler->setLastWidgetPressed(sourceWidget);
if (mFocusHandler->getModalFocused() != NULL
&& sourceWidget->hasModalFocus()
|| mFocusHandler->getModalFocused() == NULL)
{
sourceWidget->requestFocus();
}
mFocusHandler->setDraggedWidget(sourceWidget);
mLastMouseDragButton = mouseInput.getButton();
if (mLastMousePressTimeStamp < 300
&& mLastMousePressButton == mouseInput.getButton())
{
mClickCount++;
}
else
{
mClickCount = 0;
}
mLastMousePressButton = mouseInput.getButton();
mLastMousePressTimeStamp = mouseInput.getTimeStamp();
}
void Gui::handleMouseWheelMovedDown(const MouseInput& mouseInput)
{
Widget* sourceWidget = getMouseEventSource(mouseInput.getX(), mouseInput.getY());
if (mFocusHandler->getDraggedWidget() != NULL)
{
sourceWidget = mFocusHandler->getDraggedWidget();
}
int sourceWidgetX, sourceWidgetY;
sourceWidget->getAbsolutePosition(sourceWidgetX, sourceWidgetY);
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::WHEEL_MOVED_DOWN,
mouseInput.getButton(),
mouseInput.getX() - sourceWidgetX,
mouseInput.getY() - sourceWidgetY,
mClickCount);
distributeMouseEvent(mouseEvent);
}
void Gui::handleMouseWheelMovedUp(const MouseInput& mouseInput)
{
Widget* sourceWidget = getMouseEventSource(mouseInput.getX(), mouseInput.getY());
if (mFocusHandler->getDraggedWidget() != NULL)
{
sourceWidget = mFocusHandler->getDraggedWidget();
}
int sourceWidgetX, sourceWidgetY;
sourceWidget->getAbsolutePosition(sourceWidgetX, sourceWidgetY);
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::WHEEL_MOVED_UP,
mouseInput.getButton(),
mouseInput.getX() - sourceWidgetX,
mouseInput.getY() - sourceWidgetY,
mClickCount);
distributeMouseEvent(mouseEvent);
}
void Gui::handleMouseReleased(const MouseInput& mouseInput)
{
Widget* sourceWidget = getMouseEventSource(mouseInput.getX(), mouseInput.getY());
if (mFocusHandler->getDraggedWidget() != NULL)
{
if (sourceWidget != mFocusHandler->getLastWidgetPressed())
{
mFocusHandler->setLastWidgetPressed(NULL);
}
sourceWidget = mFocusHandler->getDraggedWidget();
}
int sourceWidgetX, sourceWidgetY;
sourceWidget->getAbsolutePosition(sourceWidgetX, sourceWidgetY);
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::RELEASED,
mouseInput.getButton(),
mouseInput.getX() - sourceWidgetX,
mouseInput.getY() - sourceWidgetY,
mClickCount);
distributeMouseEvent(mouseEvent);
if (mouseInput.getButton() == mLastMousePressButton
&& mFocusHandler->getLastWidgetPressed() == sourceWidget)
{
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::CLICKED,
mouseInput.getButton(),
mouseInput.getX() - sourceWidgetX,
mouseInput.getY() - sourceWidgetY,
mClickCount);
distributeMouseEvent(mouseEvent);
mFocusHandler->setLastWidgetPressed(NULL);
}
else
{
mLastMousePressButton = 0;
mClickCount = 0;
}
if (mFocusHandler->getDraggedWidget() != NULL)
{
mFocusHandler->setDraggedWidget(NULL);
}
}
void Gui::handleModalFocusRelease()
{
if (mFocusHandler->getLastWidgetWithModalFocus()
!= mFocusHandler->getModalFocused())
{
Widget* sourceWidget = getWidgetAt(mLastMouseX, mLastMouseY);
if (sourceWidget != mFocusHandler->getLastWidgetWithModalFocus()
&& mFocusHandler->getLastWidgetWithModalFocus() != NULL)
{
int sourceWidgetX, sourceWidgetY;
sourceWidget->getAbsolutePosition(sourceWidgetX, sourceWidgetY);
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::ENTERED,
mLastMousePressButton,
mLastMouseX,
mLastMouseY,
mClickCount);
distributeMouseEvent(mouseEvent);
}
mFocusHandler->setLastWidgetWithModalFocus(mFocusHandler->getModalFocused());
}
}
void Gui::handleModalMouseInputFocusRelease()
{
if (mFocusHandler->getLastWidgetWithModalMouseInputFocus()
!= mFocusHandler->getModalMouseInputFocused())
{
Widget* sourceWidget = getWidgetAt(mLastMouseX, mLastMouseY);
if (sourceWidget != mFocusHandler->getLastWidgetWithModalMouseInputFocus()
&& mFocusHandler->getLastWidgetWithModalMouseInputFocus() != NULL)
{
int sourceWidgetX, sourceWidgetY;
sourceWidget->getAbsolutePosition(sourceWidgetX, sourceWidgetY);
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::ENTERED,
mLastMousePressButton,
mLastMouseX,
mLastMouseY,
mClickCount);
distributeMouseEvent(mouseEvent);
}
mFocusHandler->setLastWidgetWithModalMouseInputFocus(mFocusHandler->getModalMouseInputFocused());
}
}
Widget* Gui::getWidgetAt(int x, int y)
{
// If the widget's parent has no child then we have found the widget..
Widget* parent = mTop;
Widget* child = mTop;
while (child != NULL)
{
Widget* swap = child;
int parentX, parentY;
parent->getAbsolutePosition(parentX, parentY);
child = parent->getWidgetAt(x - parentX, y - parentY);
parent = swap;
}
return parent;
}
Widget* Gui::getMouseEventSource(int x, int y)
{
Widget* widget = getWidgetAt(x, y);
if (mFocusHandler->getModalMouseInputFocused() != NULL
&& !widget->hasModalMouseInputFocus())
{
return mFocusHandler->getModalMouseInputFocused();
}
return widget;
}
Widget* Gui::getKeyEventSource()
{
Widget* widget = mFocusHandler->getFocused();
while (widget->_getInternalFocusHandler() != NULL
&& widget->_getInternalFocusHandler()->getFocused() != NULL)
{
widget = widget->_getInternalFocusHandler()->getFocused();
}
return widget;
}
void Gui::distributeMouseEvent(MouseEvent& mouseEvent,
bool force,
bool toSourceOnly)
{
Widget* parent = mouseEvent.getSource();
Widget* widget = mouseEvent.getSource();
if (mFocusHandler->getModalFocused() != NULL
&& !widget->hasModalFocus())
{
return;
}
if (mFocusHandler->getModalMouseInputFocused() != NULL
&& !widget->hasModalMouseInputFocus())
{
return;
}
while (parent != NULL)
{
// If the widget has been removed due to input
// cancel the distribution.
if (!Widget::widgetExists(widget))
{
break;
}
parent = (Widget*)widget->getParent();
if (widget->isEnabled() || force)
{
std::list<MouseListener*> mouseListeners = widget->_getMouseListeners();
// Send the event to all mouse listeners of the widget.
for (std::list<MouseListener*>::iterator it = mouseListeners.begin();
it != mouseListeners.end();
++it)
{
switch (mouseEvent.getType())
{
case MouseEvent::ENTERED:
(*it)->mouseEntered(mouseEvent);
break;
case MouseEvent::EXITED:
(*it)->mouseExited(mouseEvent);
break;
case MouseEvent::MOVED:
(*it)->mouseMoved(mouseEvent);
break;
case MouseEvent::PRESSED:
(*it)->mousePressed(mouseEvent);
break;
case MouseEvent::RELEASED:
(*it)->mouseReleased(mouseEvent);
break;
case MouseEvent::WHEEL_MOVED_UP:
(*it)->mouseWheelMovedUp(mouseEvent);
break;
case MouseEvent::WHEEL_MOVED_DOWN:
(*it)->mouseWheelMovedDown(mouseEvent);
break;
case MouseEvent::DRAGGED:
(*it)->mouseDragged(mouseEvent);
break;
case MouseEvent::CLICKED:
(*it)->mouseClicked(mouseEvent);
break;
default:
throw GCN_EXCEPTION("Unknown mouse event type.");
}
}
if (toSourceOnly)
{
break;
}
}
Widget* swap = widget;
widget = parent;
parent = (Widget*)swap->getParent();
// If a non modal focused widget has been reach
// and we have modal focus cancel the distribution.
if (mFocusHandler->getModalFocused() != NULL
&& !widget->hasModalFocus())
{
break;
}
// If a non modal mouse input focused widget has been reach
// and we have modal mouse input focus cancel the distribution.
if (mFocusHandler->getModalMouseInputFocused() != NULL
&& !widget->hasModalMouseInputFocus())
{
break;
}
}
}
void Gui::distributeKeyEvent(KeyEvent& keyEvent)
{
Widget* sourceWidget = keyEvent.getSource();
if (mFocusHandler->getModalFocused() != NULL
&& !sourceWidget->hasModalFocus())
{
return;
}
// If the widget has been removed due to input
// cancel the distribution.
if (!Widget::widgetExists(sourceWidget))
{
return;
}
if (sourceWidget->isEnabled())
{
std::list<KeyListener*> keyListeners = sourceWidget->_getKeyListeners();
// Send the event to all key listeners of the source widget.
for (std::list<KeyListener*>::iterator it = keyListeners.begin();
it != keyListeners.end();
++it)
{
switch (keyEvent.getType())
{
case KeyEvent::PRESSED:
(*it)->keyPressed(keyEvent);
break;
case KeyEvent::RELEASED:
(*it)->keyReleased(keyEvent);
break;
default:
throw GCN_EXCEPTION("Unknown key event type.");
}
}
}
}
void Gui::distributeKeyEventToGlobalKeyListeners(KeyEvent& keyEvent)
{
KeyListenerListIterator it;
for (it = mKeyListeners.begin(); it != mKeyListeners.end(); it++)
{
switch (keyEvent.getType())
{
case KeyEvent::PRESSED:
(*it)->keyPressed(keyEvent);
break;
case KeyEvent::RELEASED:
(*it)->keyReleased(keyEvent);
break;
default:
throw GCN_EXCEPTION("Unknown key event type.");
}
if (keyEvent.isConsumed())
{
break;
}
}
}
}
Issue 3 partially taken care of.
/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson
*
* Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/gui.hpp"
#include "guichan/basiccontainer.hpp"
#include "guichan/exception.hpp"
#include "guichan/focushandler.hpp"
#include "guichan/graphics.hpp"
#include "guichan/input.hpp"
#include "guichan/keyinput.hpp"
#include "guichan/keylistener.hpp"
#include "guichan/mouseinput.hpp"
#include "guichan/mouselistener.hpp"
#include "guichan/widget.hpp"
namespace gcn
{
Gui::Gui()
:mTop(NULL),
mGraphics(NULL),
mInput(NULL),
mTabbing(true),
mShiftPressed(false),
mMetaPressed(false),
mControlPressed(false),
mAltPressed(false),
mLastMousePressButton(0),
mLastMousePressTimeStamp(0),
mLastMouseX(0),
mLastMouseY(0),
mClickCount(1),
mLastMouseDragButton(0)
{
mFocusHandler = new FocusHandler();
}
Gui::~Gui()
{
if (Widget::widgetExists(mTop))
{
setTop(NULL);
}
delete mFocusHandler;
}
void Gui::setTop(Widget* top)
{
if (mTop != NULL)
{
mTop->_setFocusHandler(NULL);
}
if (top != NULL)
{
top->_setFocusHandler(mFocusHandler);
}
mTop = top;
}
Widget* Gui::getTop() const
{
return mTop;
}
void Gui::setGraphics(Graphics* graphics)
{
mGraphics = graphics;
}
Graphics* Gui::getGraphics() const
{
return mGraphics;
}
void Gui::setInput(Input* input)
{
mInput = input;
}
Input* Gui::getInput() const
{
return mInput;
}
void Gui::logic()
{
if (mTop == NULL)
{
throw GCN_EXCEPTION("No top widget set");
}
// Release of modal focus or modal mouse input focus might make it
// necessary to distribute mouse events.
handleModalFocusRelease();
handleModalMouseInputFocusRelease();
if (mInput != NULL)
{
mInput->_pollInput();
handleKeyInput();
handleMouseInput();
} // end if
mTop->logic();
}
void Gui::draw()
{
if (mTop == NULL)
{
throw GCN_EXCEPTION("No top widget set");
}
if (mGraphics == NULL)
{
throw GCN_EXCEPTION("No graphics set");
}
if (!mTop->isVisible())
{
return;
}
mGraphics->_beginDraw();
// If top has a border,
// draw it before drawing top
if (mTop->getBorderSize() > 0)
{
Rectangle rec = mTop->getDimension();
rec.x -= mTop->getBorderSize();
rec.y -= mTop->getBorderSize();
rec.width += 2 * mTop->getBorderSize();
rec.height += 2 * mTop->getBorderSize();
mGraphics->pushClipArea(rec);
mTop->drawBorder(mGraphics);
mGraphics->popClipArea();
}
mGraphics->pushClipArea(mTop->getDimension());
mTop->draw(mGraphics);
mGraphics->popClipArea();
mGraphics->_endDraw();
}
void Gui::focusNone()
{
mFocusHandler->focusNone();
}
void Gui::setTabbingEnabled(bool tabbing)
{
mTabbing = tabbing;
}
bool Gui::isTabbingEnabled()
{
return mTabbing;
}
void Gui::addGlobalKeyListener(KeyListener* keyListener)
{
mKeyListeners.push_back(keyListener);
}
void Gui::removeGlobalKeyListener(KeyListener* keyListener)
{
mKeyListeners.remove(keyListener);
}
void Gui::handleMouseInput()
{
while (!mInput->isMouseQueueEmpty())
{
MouseInput mouseInput = mInput->dequeueMouseInput();
// Save the current mouse state. It will be needed if modal focus
// changes or modal mouse input focus changes.
mLastMouseX = mouseInput.getX();
mLastMouseY = mouseInput.getY();
switch (mouseInput.getType())
{
case MouseInput::PRESSED:
handleMousePressed(mouseInput);
break;
case MouseInput::RELEASED:
handleMouseReleased(mouseInput);
break;
case MouseInput::MOVED:
handleMouseMoved(mouseInput);
break;
case MouseInput::WHEEL_MOVED_DOWN:
handleMouseWheelMovedDown(mouseInput);
break;
case MouseInput::WHEEL_MOVED_UP:
handleMouseWheelMovedUp(mouseInput);
break;
default:
throw GCN_EXCEPTION("Unknown mouse input type.");
break;
}
}
}
void Gui::handleKeyInput()
{
while (!mInput->isKeyQueueEmpty())
{
KeyInput keyInput = mInput->dequeueKeyInput();
// Save modifiers state
mShiftPressed = keyInput.isShiftPressed();
mMetaPressed = keyInput.isMetaPressed();
mControlPressed = keyInput.isControlPressed();
mAltPressed = keyInput.isAltPressed();
KeyEvent keyEventToGlobalKeyListeners(NULL,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
keyInput.getType(),
keyInput.isNumericPad(),
keyInput.getKey());
distributeKeyEventToGlobalKeyListeners(keyEventToGlobalKeyListeners);
// If a global key listener consumes the event it will not be
// sent further to the source of the event.
if (keyEventToGlobalKeyListeners.isConsumed())
{
continue;
}
bool keyEventConsumed = false;
// Send key inputs to the focused widgets
if (mFocusHandler->getFocused() != NULL)
{
KeyEvent keyEvent(getKeyEventSource(),
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
keyInput.getType(),
keyInput.isNumericPad(),
keyInput.getKey());
if (!mFocusHandler->getFocused()->isFocusable())
{
mFocusHandler->focusNone();
}
else
{
distributeKeyEvent(keyEvent);
}
keyEventConsumed = keyEvent.isConsumed();
}
// If the key event hasn't been consumed and
// tabbing is enable check for tab press and
// change focus.
if (!keyEventConsumed
&& mTabbing
&& keyInput.getKey().getValue() == Key::TAB
&& keyInput.getType() == KeyInput::PRESSED)
{
if (keyInput.isShiftPressed())
{
mFocusHandler->tabPrevious();
}
else
{
mFocusHandler->tabNext();
}
}
} // end while
}
void Gui::handleMouseMoved(const MouseInput& mouseInput)
{
// Check if the mouse leaves the application window.
if (mFocusHandler->getLastWidgetWithMouse() != NULL
&& (mouseInput.getX() < 0
|| mouseInput.getY() < 0
|| !mTop->getDimension().isPointInRect(mouseInput.getX(), mouseInput.getY()))
)
{
int lastWidgetWithMouseX, lastWidgetWithMouseY;
mFocusHandler->getLastWidgetWithMouse()->getAbsolutePosition(lastWidgetWithMouseX, lastWidgetWithMouseY);
MouseEvent mouseEvent(mFocusHandler->getLastWidgetWithMouse(),
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::EXITED,
mouseInput.getButton(),
mouseInput.getX() - lastWidgetWithMouseX,
mouseInput.getY() - lastWidgetWithMouseY,
mClickCount);
distributeMouseEvent(mouseEvent, true, true);
mFocusHandler->setLastWidgetWithMouse(NULL);
return;
}
Widget* sourceWidget = getMouseEventSource(mouseInput.getX(), mouseInput.getY());
if (sourceWidget != mFocusHandler->getLastWidgetWithMouse())
{
if (mFocusHandler->getLastWidgetWithMouse() != NULL)
{
int lastWidgetWithMouseX, lastWidgetWithMouseY;
mFocusHandler->getLastWidgetWithMouse()->getAbsolutePosition(lastWidgetWithMouseX, lastWidgetWithMouseY);
MouseEvent mouseEvent(mFocusHandler->getLastWidgetWithMouse(),
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::EXITED,
mouseInput.getButton(),
mouseInput.getX() - lastWidgetWithMouseX,
mouseInput.getY() - lastWidgetWithMouseY,
mClickCount);
distributeMouseEvent(mouseEvent, true, true);
mClickCount = 1;
mLastMousePressTimeStamp = 0;
}
int sourceWidgetX, sourceWidgetY;
sourceWidget->getAbsolutePosition(sourceWidgetX, sourceWidgetY);
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::ENTERED,
mouseInput.getButton(),
mouseInput.getX() - sourceWidgetX,
mouseInput.getY() - sourceWidgetY,
mClickCount);
distributeMouseEvent(mouseEvent, true, true);
mFocusHandler->setLastWidgetWithMouse(sourceWidget);
}
if (mFocusHandler->getDraggedWidget() != NULL)
{
int draggedWidgetX, draggedWidgetY;
mFocusHandler->getDraggedWidget()->getAbsolutePosition(draggedWidgetX, draggedWidgetY);
MouseEvent mouseEvent(mFocusHandler->getDraggedWidget(),
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::DRAGGED,
mLastMouseDragButton,
mouseInput.getX() - draggedWidgetX,
mouseInput.getY() - draggedWidgetY,
mClickCount);
distributeMouseEvent(mouseEvent);
}
else
{
int sourceWidgetX, sourceWidgetY;
sourceWidget->getAbsolutePosition(sourceWidgetX, sourceWidgetY);
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::MOVED,
mouseInput.getButton(),
mouseInput.getX() - sourceWidgetX,
mouseInput.getY() - sourceWidgetY,
mClickCount);
distributeMouseEvent(mouseEvent);
}
}
void Gui::handleMousePressed(const MouseInput& mouseInput)
{
Widget* sourceWidget = getMouseEventSource(mouseInput.getX(), mouseInput.getY());
if (mFocusHandler->getDraggedWidget() != NULL)
{
sourceWidget = mFocusHandler->getDraggedWidget();
}
int sourceWidgetX, sourceWidgetY;
sourceWidget->getAbsolutePosition(sourceWidgetX, sourceWidgetY);
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::PRESSED,
mouseInput.getButton(),
mouseInput.getX() - sourceWidgetX,
mouseInput.getY() - sourceWidgetY,
mClickCount);
distributeMouseEvent(mouseEvent);
mFocusHandler->setLastWidgetPressed(sourceWidget);
if (mFocusHandler->getModalFocused() != NULL
&& sourceWidget->hasModalFocus()
|| mFocusHandler->getModalFocused() == NULL)
{
sourceWidget->requestFocus();
}
mFocusHandler->setDraggedWidget(sourceWidget);
mLastMouseDragButton = mouseInput.getButton();
if (mLastMousePressTimeStamp < 300
&& mLastMousePressButton == mouseInput.getButton())
{
mClickCount++;
}
else
{
mClickCount = 1;
}
mLastMousePressButton = mouseInput.getButton();
mLastMousePressTimeStamp = mouseInput.getTimeStamp();
}
void Gui::handleMouseWheelMovedDown(const MouseInput& mouseInput)
{
Widget* sourceWidget = getMouseEventSource(mouseInput.getX(), mouseInput.getY());
if (mFocusHandler->getDraggedWidget() != NULL)
{
sourceWidget = mFocusHandler->getDraggedWidget();
}
int sourceWidgetX, sourceWidgetY;
sourceWidget->getAbsolutePosition(sourceWidgetX, sourceWidgetY);
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::WHEEL_MOVED_DOWN,
mouseInput.getButton(),
mouseInput.getX() - sourceWidgetX,
mouseInput.getY() - sourceWidgetY,
mClickCount);
distributeMouseEvent(mouseEvent);
}
void Gui::handleMouseWheelMovedUp(const MouseInput& mouseInput)
{
Widget* sourceWidget = getMouseEventSource(mouseInput.getX(), mouseInput.getY());
if (mFocusHandler->getDraggedWidget() != NULL)
{
sourceWidget = mFocusHandler->getDraggedWidget();
}
int sourceWidgetX, sourceWidgetY;
sourceWidget->getAbsolutePosition(sourceWidgetX, sourceWidgetY);
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::WHEEL_MOVED_UP,
mouseInput.getButton(),
mouseInput.getX() - sourceWidgetX,
mouseInput.getY() - sourceWidgetY,
mClickCount);
distributeMouseEvent(mouseEvent);
}
void Gui::handleMouseReleased(const MouseInput& mouseInput)
{
Widget* sourceWidget = getMouseEventSource(mouseInput.getX(), mouseInput.getY());
if (mFocusHandler->getDraggedWidget() != NULL)
{
if (sourceWidget != mFocusHandler->getLastWidgetPressed())
{
mFocusHandler->setLastWidgetPressed(NULL);
}
sourceWidget = mFocusHandler->getDraggedWidget();
}
int sourceWidgetX, sourceWidgetY;
sourceWidget->getAbsolutePosition(sourceWidgetX, sourceWidgetY);
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::RELEASED,
mouseInput.getButton(),
mouseInput.getX() - sourceWidgetX,
mouseInput.getY() - sourceWidgetY,
mClickCount);
distributeMouseEvent(mouseEvent);
if (mouseInput.getButton() == mLastMousePressButton
&& mFocusHandler->getLastWidgetPressed() == sourceWidget)
{
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::CLICKED,
mouseInput.getButton(),
mouseInput.getX() - sourceWidgetX,
mouseInput.getY() - sourceWidgetY,
mClickCount);
distributeMouseEvent(mouseEvent);
mFocusHandler->setLastWidgetPressed(NULL);
}
else
{
mLastMousePressButton = 0;
mClickCount = 0;
}
if (mFocusHandler->getDraggedWidget() != NULL)
{
mFocusHandler->setDraggedWidget(NULL);
}
}
void Gui::handleModalFocusRelease()
{
if (mFocusHandler->getLastWidgetWithModalFocus()
!= mFocusHandler->getModalFocused())
{
Widget* sourceWidget = getWidgetAt(mLastMouseX, mLastMouseY);
if (sourceWidget != mFocusHandler->getLastWidgetWithModalFocus()
&& mFocusHandler->getLastWidgetWithModalFocus() != NULL)
{
int sourceWidgetX, sourceWidgetY;
sourceWidget->getAbsolutePosition(sourceWidgetX, sourceWidgetY);
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::ENTERED,
mLastMousePressButton,
mLastMouseX,
mLastMouseY,
mClickCount);
distributeMouseEvent(mouseEvent);
}
mFocusHandler->setLastWidgetWithModalFocus(mFocusHandler->getModalFocused());
}
}
void Gui::handleModalMouseInputFocusRelease()
{
if (mFocusHandler->getLastWidgetWithModalMouseInputFocus()
!= mFocusHandler->getModalMouseInputFocused())
{
Widget* sourceWidget = getWidgetAt(mLastMouseX, mLastMouseY);
if (sourceWidget != mFocusHandler->getLastWidgetWithModalMouseInputFocus()
&& mFocusHandler->getLastWidgetWithModalMouseInputFocus() != NULL)
{
int sourceWidgetX, sourceWidgetY;
sourceWidget->getAbsolutePosition(sourceWidgetX, sourceWidgetY);
MouseEvent mouseEvent(sourceWidget,
mShiftPressed,
mControlPressed,
mAltPressed,
mMetaPressed,
MouseEvent::ENTERED,
mLastMousePressButton,
mLastMouseX,
mLastMouseY,
mClickCount);
distributeMouseEvent(mouseEvent);
}
mFocusHandler->setLastWidgetWithModalMouseInputFocus(mFocusHandler->getModalMouseInputFocused());
}
}
Widget* Gui::getWidgetAt(int x, int y)
{
// If the widget's parent has no child then we have found the widget..
Widget* parent = mTop;
Widget* child = mTop;
while (child != NULL)
{
Widget* swap = child;
int parentX, parentY;
parent->getAbsolutePosition(parentX, parentY);
child = parent->getWidgetAt(x - parentX, y - parentY);
parent = swap;
}
return parent;
}
Widget* Gui::getMouseEventSource(int x, int y)
{
Widget* widget = getWidgetAt(x, y);
if (mFocusHandler->getModalMouseInputFocused() != NULL
&& !widget->hasModalMouseInputFocus())
{
return mFocusHandler->getModalMouseInputFocused();
}
return widget;
}
Widget* Gui::getKeyEventSource()
{
Widget* widget = mFocusHandler->getFocused();
while (widget->_getInternalFocusHandler() != NULL
&& widget->_getInternalFocusHandler()->getFocused() != NULL)
{
widget = widget->_getInternalFocusHandler()->getFocused();
}
return widget;
}
void Gui::distributeMouseEvent(MouseEvent& mouseEvent,
bool force,
bool toSourceOnly)
{
Widget* parent = mouseEvent.getSource();
Widget* widget = mouseEvent.getSource();
if (mFocusHandler->getModalFocused() != NULL
&& !widget->hasModalFocus())
{
return;
}
if (mFocusHandler->getModalMouseInputFocused() != NULL
&& !widget->hasModalMouseInputFocus())
{
return;
}
while (parent != NULL)
{
// If the widget has been removed due to input
// cancel the distribution.
if (!Widget::widgetExists(widget))
{
break;
}
parent = (Widget*)widget->getParent();
if (widget->isEnabled() || force)
{
std::list<MouseListener*> mouseListeners = widget->_getMouseListeners();
// Send the event to all mouse listeners of the widget.
for (std::list<MouseListener*>::iterator it = mouseListeners.begin();
it != mouseListeners.end();
++it)
{
switch (mouseEvent.getType())
{
case MouseEvent::ENTERED:
(*it)->mouseEntered(mouseEvent);
break;
case MouseEvent::EXITED:
(*it)->mouseExited(mouseEvent);
break;
case MouseEvent::MOVED:
(*it)->mouseMoved(mouseEvent);
break;
case MouseEvent::PRESSED:
(*it)->mousePressed(mouseEvent);
break;
case MouseEvent::RELEASED:
(*it)->mouseReleased(mouseEvent);
break;
case MouseEvent::WHEEL_MOVED_UP:
(*it)->mouseWheelMovedUp(mouseEvent);
break;
case MouseEvent::WHEEL_MOVED_DOWN:
(*it)->mouseWheelMovedDown(mouseEvent);
break;
case MouseEvent::DRAGGED:
(*it)->mouseDragged(mouseEvent);
break;
case MouseEvent::CLICKED:
(*it)->mouseClicked(mouseEvent);
break;
default:
throw GCN_EXCEPTION("Unknown mouse event type.");
}
}
if (toSourceOnly)
{
break;
}
}
Widget* swap = widget;
widget = parent;
parent = (Widget*)swap->getParent();
// If a non modal focused widget has been reach
// and we have modal focus cancel the distribution.
if (mFocusHandler->getModalFocused() != NULL
&& !widget->hasModalFocus())
{
break;
}
// If a non modal mouse input focused widget has been reach
// and we have modal mouse input focus cancel the distribution.
if (mFocusHandler->getModalMouseInputFocused() != NULL
&& !widget->hasModalMouseInputFocus())
{
break;
}
}
}
void Gui::distributeKeyEvent(KeyEvent& keyEvent)
{
Widget* sourceWidget = keyEvent.getSource();
if (mFocusHandler->getModalFocused() != NULL
&& !sourceWidget->hasModalFocus())
{
return;
}
// If the widget has been removed due to input
// cancel the distribution.
if (!Widget::widgetExists(sourceWidget))
{
return;
}
if (sourceWidget->isEnabled())
{
std::list<KeyListener*> keyListeners = sourceWidget->_getKeyListeners();
// Send the event to all key listeners of the source widget.
for (std::list<KeyListener*>::iterator it = keyListeners.begin();
it != keyListeners.end();
++it)
{
switch (keyEvent.getType())
{
case KeyEvent::PRESSED:
(*it)->keyPressed(keyEvent);
break;
case KeyEvent::RELEASED:
(*it)->keyReleased(keyEvent);
break;
default:
throw GCN_EXCEPTION("Unknown key event type.");
}
}
}
}
void Gui::distributeKeyEventToGlobalKeyListeners(KeyEvent& keyEvent)
{
KeyListenerListIterator it;
for (it = mKeyListeners.begin(); it != mKeyListeners.end(); it++)
{
switch (keyEvent.getType())
{
case KeyEvent::PRESSED:
(*it)->keyPressed(keyEvent);
break;
case KeyEvent::RELEASED:
(*it)->keyReleased(keyEvent);
break;
default:
throw GCN_EXCEPTION("Unknown key event type.");
}
if (keyEvent.isConsumed())
{
break;
}
}
}
}
|
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dummyobject.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2007-06-26 16:04:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "precompiled_embeddedobj.hxx"
#ifndef _COM_SUN_STAR_EMBED_EMBEDSTATES_HPP_
#include <com/sun/star/embed/EmbedStates.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_EMBEDVERBS_HPP_
#include <com/sun/star/embed/EmbedVerbs.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_EMBEDUPDATEMODES_HPP_
#include <com/sun/star/embed/EmbedUpdateModes.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDCLIENT_HPP_
#include <com/sun/star/embed/XEmbeddedClient.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XINPLACECLIENT_HPP_
#include <com/sun/star/embed/XInplaceClient.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XWINDOWSUPPLIER_HPP_
#include <com/sun/star/embed/XWindowSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_STATECHANGEINPROGRESSEXCEPTION_HPP_
#include <com/sun/star/embed/StateChangeInProgressException.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_EMBEDSTATES_HPP_
#include <com/sun/star/embed/EmbedStates.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ASPECTS_HPP_
#include <com/sun/star/embed/Aspects.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_EMBEDMAPUNITS_HPP_
#include <com/sun/star/embed/EmbedMapUnits.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ENTRYINITMODES_HPP_
#include <com/sun/star/embed/EntryInitModes.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_NOVISUALAREASIZEEXCEPTION_HPP_
#include <com/sun/star/embed/NoVisualAreaSizeException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#include <cppuhelper/interfacecontainer.h>
#include <dummyobject.hxx>
using namespace ::com::sun::star;
//----------------------------------------------
void ODummyEmbeddedObject::CheckInit()
{
if ( m_bDisposed )
throw lang::DisposedException();
if ( m_nObjectState == -1 )
throw embed::WrongStateException( ::rtl::OUString::createFromAscii( "The object has no persistence!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
}
//----------------------------------------------
void ODummyEmbeddedObject::PostEvent_Impl( const ::rtl::OUString& aEventName,
const uno::Reference< uno::XInterface >& /*xSource*/ )
{
if ( m_pInterfaceContainer )
{
::cppu::OInterfaceContainerHelper* pIC = m_pInterfaceContainer->getContainer(
::getCppuType((const uno::Reference< document::XEventListener >*)0) );
if( pIC )
{
document::EventObject aEvent;
aEvent.EventName = aEventName;
aEvent.Source = uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >( this ) );
// For now all the events are sent as object events
// aEvent.Source = ( xSource.is() ? xSource
// : uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >( this ) ) );
::cppu::OInterfaceIteratorHelper aIt( *pIC );
while( aIt.hasMoreElements() )
{
try
{
((document::XEventListener *)aIt.next())->notifyEvent( aEvent );
}
catch( uno::RuntimeException& )
{
aIt.remove();
}
// the listener could dispose the object.
if ( m_bDisposed )
return;
}
}
}
}
//----------------------------------------------
ODummyEmbeddedObject::~ODummyEmbeddedObject()
{
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::changeState( sal_Int32 nNewState )
throw ( embed::UnreachableStateException,
embed::WrongStateException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
if ( nNewState == embed::EmbedStates::LOADED )
return;
throw embed::UnreachableStateException();
}
//----------------------------------------------
uno::Sequence< sal_Int32 > SAL_CALL ODummyEmbeddedObject::getReachableStates()
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
uno::Sequence< sal_Int32 > aResult( 1 );
aResult[0] = embed::EmbedStates::LOADED;
return aResult;
}
//----------------------------------------------
sal_Int32 SAL_CALL ODummyEmbeddedObject::getCurrentState()
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
return m_nObjectState;
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::doVerb( sal_Int32 )
throw ( lang::IllegalArgumentException,
embed::WrongStateException,
embed::UnreachableStateException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
// no supported verbs
}
//----------------------------------------------
uno::Sequence< embed::VerbDescriptor > SAL_CALL ODummyEmbeddedObject::getSupportedVerbs()
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
return uno::Sequence< embed::VerbDescriptor >();
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::setClientSite(
const uno::Reference< embed::XEmbeddedClient >& xClient )
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
m_xClientSite = xClient;
}
//----------------------------------------------
uno::Reference< embed::XEmbeddedClient > SAL_CALL ODummyEmbeddedObject::getClientSite()
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
return m_xClientSite;
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::update()
throw ( embed::WrongStateException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::setUpdateMode( sal_Int32 )
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
}
//----------------------------------------------
sal_Int64 SAL_CALL ODummyEmbeddedObject::getStatus( sal_Int64 )
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
return 0;
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::setContainerName( const ::rtl::OUString& )
throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::setVisualAreaSize( sal_Int64 nAspect, const awt::Size& aSize )
throw ( lang::IllegalArgumentException,
embed::WrongStateException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
OSL_ENSURE( nAspect != embed::Aspects::MSOLE_ICON, "For iconified objects no graphical replacement is required!\n" );
if ( nAspect == embed::Aspects::MSOLE_ICON )
// no representation can be retrieved
throw embed::WrongStateException( ::rtl::OUString::createFromAscii( "Illegal call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
m_nCachedAspect = nAspect;
m_aCachedSize = aSize;
m_bHasCachedSize = sal_True;
}
//----------------------------------------------
awt::Size SAL_CALL ODummyEmbeddedObject::getVisualAreaSize( sal_Int64 nAspect )
throw ( lang::IllegalArgumentException,
embed::WrongStateException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
OSL_ENSURE( nAspect != embed::Aspects::MSOLE_ICON, "For iconified objects no graphical replacement is required!\n" );
if ( nAspect == embed::Aspects::MSOLE_ICON )
// no representation can be retrieved
throw embed::WrongStateException( ::rtl::OUString::createFromAscii( "Illegal call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
if ( !m_bHasCachedSize || m_nCachedAspect != nAspect )
throw embed::NoVisualAreaSizeException(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "No size available!\n" ) ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
return m_aCachedSize;
}
//----------------------------------------------
sal_Int32 SAL_CALL ODummyEmbeddedObject::getMapUnit( sal_Int64 nAspect )
throw ( uno::Exception,
uno::RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
OSL_ENSURE( nAspect != embed::Aspects::MSOLE_ICON, "For iconified objects no graphical replacement is required!\n" );
if ( nAspect == embed::Aspects::MSOLE_ICON )
// no representation can be retrieved
throw embed::WrongStateException( ::rtl::OUString::createFromAscii( "Illegal call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
return embed::EmbedMapUnits::ONE_100TH_MM;
}
//----------------------------------------------
embed::VisualRepresentation SAL_CALL ODummyEmbeddedObject::getPreferredVisualRepresentation( sal_Int64 )
throw ( lang::IllegalArgumentException,
embed::WrongStateException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
// no representation can be retrieved
throw embed::WrongStateException( ::rtl::OUString::createFromAscii( "Illegal call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::setPersistentEntry(
const uno::Reference< embed::XStorage >& xStorage,
const ::rtl::OUString& sEntName,
sal_Int32 nEntryConnectionMode,
const uno::Sequence< beans::PropertyValue >& /* lArguments */,
const uno::Sequence< beans::PropertyValue >& /* lObjArgs */ )
throw ( lang::IllegalArgumentException,
embed::WrongStateException,
io::IOException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_bDisposed )
throw lang::DisposedException(); // TODO
if ( !xStorage.is() )
throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "No parent storage is provided!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ),
1 );
if ( !sEntName.getLength() )
throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "Empty element name is provided!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ),
2 );
if ( ( m_nObjectState != -1 || nEntryConnectionMode == embed::EntryInitModes::NO_INIT )
&& ( m_nObjectState == -1 || nEntryConnectionMode != embed::EntryInitModes::NO_INIT ) )
{
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "Can't change persistant representation of activated object!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
}
if ( m_bWaitSaveCompleted )
{
if ( nEntryConnectionMode == embed::EntryInitModes::NO_INIT )
saveCompleted( ( m_xParentStorage != xStorage || !m_aEntryName.equals( sEntName ) ) );
else
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "The object waits for saveCompleted() call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
}
if ( nEntryConnectionMode == embed::EntryInitModes::DEFAULT_INIT
|| nEntryConnectionMode == embed::EntryInitModes::NO_INIT )
{
if ( xStorage->hasByName( sEntName ) )
{
m_xParentStorage = xStorage;
m_aEntryName = sEntName;
m_nObjectState = embed::EmbedStates::LOADED;
}
else
throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "Wrong entry is provided!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ),
2 );
}
else
throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "Wrong connection mode is provided!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ),
3 );
}
//------------------------------------------------------
void SAL_CALL ODummyEmbeddedObject::storeToEntry( const uno::Reference< embed::XStorage >& xStorage,
const ::rtl::OUString& sEntName,
const uno::Sequence< beans::PropertyValue >& /* lArguments */,
const uno::Sequence< beans::PropertyValue >& /* lObjArgs */ )
throw ( lang::IllegalArgumentException,
embed::WrongStateException,
io::IOException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
if ( m_bWaitSaveCompleted )
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "The object waits for saveCompleted() call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
m_xParentStorage->copyElementTo( m_aEntryName, xStorage, sEntName );
}
//------------------------------------------------------
void SAL_CALL ODummyEmbeddedObject::storeAsEntry( const uno::Reference< embed::XStorage >& xStorage,
const ::rtl::OUString& sEntName,
const uno::Sequence< beans::PropertyValue >& /* lArguments */,
const uno::Sequence< beans::PropertyValue >& /* lObjArgs */ )
throw ( lang::IllegalArgumentException,
embed::WrongStateException,
io::IOException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
if ( m_bWaitSaveCompleted )
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "The object waits for saveCompleted() call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
PostEvent_Impl( ::rtl::OUString::createFromAscii( "OnSaveAs" ),
uno::Reference< uno::XInterface >( static_cast< cppu::OWeakObject* >( this ) ) );
m_xParentStorage->copyElementTo( m_aEntryName, xStorage, sEntName );
m_bWaitSaveCompleted = sal_True;
m_xNewParentStorage = xStorage;
m_aNewEntryName = sEntName;
}
//------------------------------------------------------
void SAL_CALL ODummyEmbeddedObject::saveCompleted( sal_Bool bUseNew )
throw ( embed::WrongStateException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
// it is allowed to call saveCompleted( false ) for nonstored objects
if ( !m_bWaitSaveCompleted && !bUseNew )
return;
OSL_ENSURE( m_bWaitSaveCompleted, "Unexpected saveCompleted() call!\n" );
if ( !m_bWaitSaveCompleted )
throw io::IOException(); // TODO: illegal call
OSL_ENSURE( m_xNewParentStorage.is() , "Internal object information is broken!\n" );
if ( !m_xNewParentStorage.is() )
throw uno::RuntimeException(); // TODO: broken internal information
if ( bUseNew )
{
m_xParentStorage = m_xNewParentStorage;
m_aEntryName = m_aNewEntryName;
PostEvent_Impl( ::rtl::OUString::createFromAscii( "OnSaveAsDone" ),
uno::Reference< uno::XInterface >( static_cast< cppu::OWeakObject* >( this ) ) );
}
m_xNewParentStorage = uno::Reference< embed::XStorage >();
m_aNewEntryName = ::rtl::OUString();
m_bWaitSaveCompleted = sal_False;
}
//------------------------------------------------------
sal_Bool SAL_CALL ODummyEmbeddedObject::hasEntry()
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
if ( m_bWaitSaveCompleted )
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "The object waits for saveCompleted() call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
if ( m_aEntryName.getLength() )
return sal_True;
return sal_False;
}
//------------------------------------------------------
::rtl::OUString SAL_CALL ODummyEmbeddedObject::getEntryName()
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
if ( m_bWaitSaveCompleted )
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "The object waits for saveCompleted() call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
return m_aEntryName;
}
//------------------------------------------------------
void SAL_CALL ODummyEmbeddedObject::storeOwn()
throw ( embed::WrongStateException,
io::IOException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
if ( m_bWaitSaveCompleted )
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "The object waits for saveCompleted() call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
// the object can not be activated or changed
return;
}
//------------------------------------------------------
sal_Bool SAL_CALL ODummyEmbeddedObject::isReadonly()
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
if ( m_bWaitSaveCompleted )
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "The object waits for saveCompleted() call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
// this object can not be changed
return sal_True;
}
//------------------------------------------------------
void SAL_CALL ODummyEmbeddedObject::reload(
const uno::Sequence< beans::PropertyValue >& /* lArguments */,
const uno::Sequence< beans::PropertyValue >& /* lObjArgs */ )
throw ( lang::IllegalArgumentException,
embed::WrongStateException,
io::IOException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
if ( m_bWaitSaveCompleted )
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "The object waits for saveCompleted() call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
// nothing to reload
}
//------------------------------------------------------
uno::Sequence< sal_Int8 > SAL_CALL ODummyEmbeddedObject::getClassID()
throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
// currently the class ID is empty
// TODO/LATER: should a special class ID be used in this case?
return uno::Sequence< sal_Int8 >();
}
//------------------------------------------------------
::rtl::OUString SAL_CALL ODummyEmbeddedObject::getClassName()
throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_bDisposed )
throw lang::DisposedException(); // TODO
return ::rtl::OUString();
}
//------------------------------------------------------
void SAL_CALL ODummyEmbeddedObject::setClassInfo(
const uno::Sequence< sal_Int8 >& /*aClassID*/, const ::rtl::OUString& /*aClassName*/ )
throw ( lang::NoSupportException,
uno::RuntimeException )
{
throw lang::NoSupportException();
}
//------------------------------------------------------
uno::Reference< util::XCloseable > SAL_CALL ODummyEmbeddedObject::getComponent()
throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
return uno::Reference< util::XCloseable >();
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::addStateChangeListener( const uno::Reference< embed::XStateChangeListener >& xListener )
throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_bDisposed )
return;
if ( !m_pInterfaceContainer )
m_pInterfaceContainer = new ::cppu::OMultiTypeInterfaceContainerHelper( m_aMutex );
m_pInterfaceContainer->addInterface( ::getCppuType( (const uno::Reference< embed::XStateChangeListener >*)0 ),
xListener );
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::removeStateChangeListener(
const uno::Reference< embed::XStateChangeListener >& xListener )
throw (uno::RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_pInterfaceContainer )
m_pInterfaceContainer->removeInterface( ::getCppuType( (const uno::Reference< embed::XStateChangeListener >*)0 ),
xListener );
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::close( sal_Bool bDeliverOwnership )
throw ( util::CloseVetoException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_bDisposed )
throw lang::DisposedException(); // TODO
uno::Reference< uno::XInterface > xSelfHold( static_cast< ::cppu::OWeakObject* >( this ) );
lang::EventObject aSource( static_cast< ::cppu::OWeakObject* >( this ) );
if ( m_pInterfaceContainer )
{
::cppu::OInterfaceContainerHelper* pContainer =
m_pInterfaceContainer->getContainer( ::getCppuType( ( const uno::Reference< util::XCloseListener >*) NULL ) );
if ( pContainer != NULL )
{
::cppu::OInterfaceIteratorHelper pIterator(*pContainer);
while (pIterator.hasMoreElements())
{
try
{
((util::XCloseListener*)pIterator.next())->queryClosing( aSource, bDeliverOwnership );
}
catch( uno::RuntimeException& )
{
pIterator.remove();
}
}
}
pContainer = m_pInterfaceContainer->getContainer(
::getCppuType( ( const uno::Reference< util::XCloseListener >*) NULL ) );
if ( pContainer != NULL )
{
::cppu::OInterfaceIteratorHelper pCloseIterator(*pContainer);
while (pCloseIterator.hasMoreElements())
{
try
{
((util::XCloseListener*)pCloseIterator.next())->notifyClosing( aSource );
}
catch( uno::RuntimeException& )
{
pCloseIterator.remove();
}
}
}
m_pInterfaceContainer->disposeAndClear( aSource );
}
m_bDisposed = sal_True; // the object is disposed now for outside
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::addCloseListener( const uno::Reference< util::XCloseListener >& xListener )
throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_bDisposed )
return;
if ( !m_pInterfaceContainer )
m_pInterfaceContainer = new ::cppu::OMultiTypeInterfaceContainerHelper( m_aMutex );
m_pInterfaceContainer->addInterface( ::getCppuType( (const uno::Reference< util::XCloseListener >*)0 ), xListener );
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::removeCloseListener( const uno::Reference< util::XCloseListener >& xListener )
throw (uno::RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_pInterfaceContainer )
m_pInterfaceContainer->removeInterface( ::getCppuType( (const uno::Reference< util::XCloseListener >*)0 ),
xListener );
}
//------------------------------------------------------
void SAL_CALL ODummyEmbeddedObject::addEventListener( const uno::Reference< document::XEventListener >& xListener )
throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_bDisposed )
return;
if ( !m_pInterfaceContainer )
m_pInterfaceContainer = new ::cppu::OMultiTypeInterfaceContainerHelper( m_aMutex );
m_pInterfaceContainer->addInterface( ::getCppuType( (const uno::Reference< document::XEventListener >*)0 ), xListener );
}
//------------------------------------------------------
void SAL_CALL ODummyEmbeddedObject::removeEventListener( const uno::Reference< document::XEventListener >& xListener )
throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_pInterfaceContainer )
m_pInterfaceContainer->removeInterface( ::getCppuType( (const uno::Reference< document::XEventListener >*)0 ),
xListener );
}
INTEGRATION: CWS changefileheader (1.2.26); FILE MERGED
2008/04/01 12:28:48 thb 1.2.26.2: #i85898# Stripping all external header guards
2008/03/31 13:33:17 rt 1.2.26.1: #i87441# Change license header to LPGL v3.
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dummyobject.cxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "precompiled_embeddedobj.hxx"
#include <com/sun/star/embed/EmbedStates.hpp>
#include <com/sun/star/embed/EmbedVerbs.hpp>
#include <com/sun/star/embed/EmbedUpdateModes.hpp>
#include <com/sun/star/embed/XEmbeddedClient.hpp>
#include <com/sun/star/embed/XInplaceClient.hpp>
#include <com/sun/star/embed/XWindowSupplier.hpp>
#include <com/sun/star/embed/StateChangeInProgressException.hpp>
#include <com/sun/star/embed/EmbedStates.hpp>
#include <com/sun/star/embed/Aspects.hpp>
#include <com/sun/star/embed/EmbedMapUnits.hpp>
#include <com/sun/star/embed/EntryInitModes.hpp>
#include <com/sun/star/embed/NoVisualAreaSizeException.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <cppuhelper/interfacecontainer.h>
#include <dummyobject.hxx>
using namespace ::com::sun::star;
//----------------------------------------------
void ODummyEmbeddedObject::CheckInit()
{
if ( m_bDisposed )
throw lang::DisposedException();
if ( m_nObjectState == -1 )
throw embed::WrongStateException( ::rtl::OUString::createFromAscii( "The object has no persistence!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
}
//----------------------------------------------
void ODummyEmbeddedObject::PostEvent_Impl( const ::rtl::OUString& aEventName,
const uno::Reference< uno::XInterface >& /*xSource*/ )
{
if ( m_pInterfaceContainer )
{
::cppu::OInterfaceContainerHelper* pIC = m_pInterfaceContainer->getContainer(
::getCppuType((const uno::Reference< document::XEventListener >*)0) );
if( pIC )
{
document::EventObject aEvent;
aEvent.EventName = aEventName;
aEvent.Source = uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >( this ) );
// For now all the events are sent as object events
// aEvent.Source = ( xSource.is() ? xSource
// : uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >( this ) ) );
::cppu::OInterfaceIteratorHelper aIt( *pIC );
while( aIt.hasMoreElements() )
{
try
{
((document::XEventListener *)aIt.next())->notifyEvent( aEvent );
}
catch( uno::RuntimeException& )
{
aIt.remove();
}
// the listener could dispose the object.
if ( m_bDisposed )
return;
}
}
}
}
//----------------------------------------------
ODummyEmbeddedObject::~ODummyEmbeddedObject()
{
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::changeState( sal_Int32 nNewState )
throw ( embed::UnreachableStateException,
embed::WrongStateException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
if ( nNewState == embed::EmbedStates::LOADED )
return;
throw embed::UnreachableStateException();
}
//----------------------------------------------
uno::Sequence< sal_Int32 > SAL_CALL ODummyEmbeddedObject::getReachableStates()
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
uno::Sequence< sal_Int32 > aResult( 1 );
aResult[0] = embed::EmbedStates::LOADED;
return aResult;
}
//----------------------------------------------
sal_Int32 SAL_CALL ODummyEmbeddedObject::getCurrentState()
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
return m_nObjectState;
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::doVerb( sal_Int32 )
throw ( lang::IllegalArgumentException,
embed::WrongStateException,
embed::UnreachableStateException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
// no supported verbs
}
//----------------------------------------------
uno::Sequence< embed::VerbDescriptor > SAL_CALL ODummyEmbeddedObject::getSupportedVerbs()
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
return uno::Sequence< embed::VerbDescriptor >();
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::setClientSite(
const uno::Reference< embed::XEmbeddedClient >& xClient )
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
m_xClientSite = xClient;
}
//----------------------------------------------
uno::Reference< embed::XEmbeddedClient > SAL_CALL ODummyEmbeddedObject::getClientSite()
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
return m_xClientSite;
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::update()
throw ( embed::WrongStateException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::setUpdateMode( sal_Int32 )
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
}
//----------------------------------------------
sal_Int64 SAL_CALL ODummyEmbeddedObject::getStatus( sal_Int64 )
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
return 0;
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::setContainerName( const ::rtl::OUString& )
throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::setVisualAreaSize( sal_Int64 nAspect, const awt::Size& aSize )
throw ( lang::IllegalArgumentException,
embed::WrongStateException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
OSL_ENSURE( nAspect != embed::Aspects::MSOLE_ICON, "For iconified objects no graphical replacement is required!\n" );
if ( nAspect == embed::Aspects::MSOLE_ICON )
// no representation can be retrieved
throw embed::WrongStateException( ::rtl::OUString::createFromAscii( "Illegal call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
m_nCachedAspect = nAspect;
m_aCachedSize = aSize;
m_bHasCachedSize = sal_True;
}
//----------------------------------------------
awt::Size SAL_CALL ODummyEmbeddedObject::getVisualAreaSize( sal_Int64 nAspect )
throw ( lang::IllegalArgumentException,
embed::WrongStateException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
OSL_ENSURE( nAspect != embed::Aspects::MSOLE_ICON, "For iconified objects no graphical replacement is required!\n" );
if ( nAspect == embed::Aspects::MSOLE_ICON )
// no representation can be retrieved
throw embed::WrongStateException( ::rtl::OUString::createFromAscii( "Illegal call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
if ( !m_bHasCachedSize || m_nCachedAspect != nAspect )
throw embed::NoVisualAreaSizeException(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "No size available!\n" ) ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
return m_aCachedSize;
}
//----------------------------------------------
sal_Int32 SAL_CALL ODummyEmbeddedObject::getMapUnit( sal_Int64 nAspect )
throw ( uno::Exception,
uno::RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
OSL_ENSURE( nAspect != embed::Aspects::MSOLE_ICON, "For iconified objects no graphical replacement is required!\n" );
if ( nAspect == embed::Aspects::MSOLE_ICON )
// no representation can be retrieved
throw embed::WrongStateException( ::rtl::OUString::createFromAscii( "Illegal call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
return embed::EmbedMapUnits::ONE_100TH_MM;
}
//----------------------------------------------
embed::VisualRepresentation SAL_CALL ODummyEmbeddedObject::getPreferredVisualRepresentation( sal_Int64 )
throw ( lang::IllegalArgumentException,
embed::WrongStateException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
// no representation can be retrieved
throw embed::WrongStateException( ::rtl::OUString::createFromAscii( "Illegal call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::setPersistentEntry(
const uno::Reference< embed::XStorage >& xStorage,
const ::rtl::OUString& sEntName,
sal_Int32 nEntryConnectionMode,
const uno::Sequence< beans::PropertyValue >& /* lArguments */,
const uno::Sequence< beans::PropertyValue >& /* lObjArgs */ )
throw ( lang::IllegalArgumentException,
embed::WrongStateException,
io::IOException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_bDisposed )
throw lang::DisposedException(); // TODO
if ( !xStorage.is() )
throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "No parent storage is provided!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ),
1 );
if ( !sEntName.getLength() )
throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "Empty element name is provided!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ),
2 );
if ( ( m_nObjectState != -1 || nEntryConnectionMode == embed::EntryInitModes::NO_INIT )
&& ( m_nObjectState == -1 || nEntryConnectionMode != embed::EntryInitModes::NO_INIT ) )
{
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "Can't change persistant representation of activated object!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
}
if ( m_bWaitSaveCompleted )
{
if ( nEntryConnectionMode == embed::EntryInitModes::NO_INIT )
saveCompleted( ( m_xParentStorage != xStorage || !m_aEntryName.equals( sEntName ) ) );
else
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "The object waits for saveCompleted() call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
}
if ( nEntryConnectionMode == embed::EntryInitModes::DEFAULT_INIT
|| nEntryConnectionMode == embed::EntryInitModes::NO_INIT )
{
if ( xStorage->hasByName( sEntName ) )
{
m_xParentStorage = xStorage;
m_aEntryName = sEntName;
m_nObjectState = embed::EmbedStates::LOADED;
}
else
throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "Wrong entry is provided!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ),
2 );
}
else
throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "Wrong connection mode is provided!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ),
3 );
}
//------------------------------------------------------
void SAL_CALL ODummyEmbeddedObject::storeToEntry( const uno::Reference< embed::XStorage >& xStorage,
const ::rtl::OUString& sEntName,
const uno::Sequence< beans::PropertyValue >& /* lArguments */,
const uno::Sequence< beans::PropertyValue >& /* lObjArgs */ )
throw ( lang::IllegalArgumentException,
embed::WrongStateException,
io::IOException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
if ( m_bWaitSaveCompleted )
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "The object waits for saveCompleted() call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
m_xParentStorage->copyElementTo( m_aEntryName, xStorage, sEntName );
}
//------------------------------------------------------
void SAL_CALL ODummyEmbeddedObject::storeAsEntry( const uno::Reference< embed::XStorage >& xStorage,
const ::rtl::OUString& sEntName,
const uno::Sequence< beans::PropertyValue >& /* lArguments */,
const uno::Sequence< beans::PropertyValue >& /* lObjArgs */ )
throw ( lang::IllegalArgumentException,
embed::WrongStateException,
io::IOException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
if ( m_bWaitSaveCompleted )
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "The object waits for saveCompleted() call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
PostEvent_Impl( ::rtl::OUString::createFromAscii( "OnSaveAs" ),
uno::Reference< uno::XInterface >( static_cast< cppu::OWeakObject* >( this ) ) );
m_xParentStorage->copyElementTo( m_aEntryName, xStorage, sEntName );
m_bWaitSaveCompleted = sal_True;
m_xNewParentStorage = xStorage;
m_aNewEntryName = sEntName;
}
//------------------------------------------------------
void SAL_CALL ODummyEmbeddedObject::saveCompleted( sal_Bool bUseNew )
throw ( embed::WrongStateException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
// it is allowed to call saveCompleted( false ) for nonstored objects
if ( !m_bWaitSaveCompleted && !bUseNew )
return;
OSL_ENSURE( m_bWaitSaveCompleted, "Unexpected saveCompleted() call!\n" );
if ( !m_bWaitSaveCompleted )
throw io::IOException(); // TODO: illegal call
OSL_ENSURE( m_xNewParentStorage.is() , "Internal object information is broken!\n" );
if ( !m_xNewParentStorage.is() )
throw uno::RuntimeException(); // TODO: broken internal information
if ( bUseNew )
{
m_xParentStorage = m_xNewParentStorage;
m_aEntryName = m_aNewEntryName;
PostEvent_Impl( ::rtl::OUString::createFromAscii( "OnSaveAsDone" ),
uno::Reference< uno::XInterface >( static_cast< cppu::OWeakObject* >( this ) ) );
}
m_xNewParentStorage = uno::Reference< embed::XStorage >();
m_aNewEntryName = ::rtl::OUString();
m_bWaitSaveCompleted = sal_False;
}
//------------------------------------------------------
sal_Bool SAL_CALL ODummyEmbeddedObject::hasEntry()
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
if ( m_bWaitSaveCompleted )
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "The object waits for saveCompleted() call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
if ( m_aEntryName.getLength() )
return sal_True;
return sal_False;
}
//------------------------------------------------------
::rtl::OUString SAL_CALL ODummyEmbeddedObject::getEntryName()
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
if ( m_bWaitSaveCompleted )
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "The object waits for saveCompleted() call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
return m_aEntryName;
}
//------------------------------------------------------
void SAL_CALL ODummyEmbeddedObject::storeOwn()
throw ( embed::WrongStateException,
io::IOException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
if ( m_bWaitSaveCompleted )
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "The object waits for saveCompleted() call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
// the object can not be activated or changed
return;
}
//------------------------------------------------------
sal_Bool SAL_CALL ODummyEmbeddedObject::isReadonly()
throw ( embed::WrongStateException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
if ( m_bWaitSaveCompleted )
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "The object waits for saveCompleted() call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
// this object can not be changed
return sal_True;
}
//------------------------------------------------------
void SAL_CALL ODummyEmbeddedObject::reload(
const uno::Sequence< beans::PropertyValue >& /* lArguments */,
const uno::Sequence< beans::PropertyValue >& /* lObjArgs */ )
throw ( lang::IllegalArgumentException,
embed::WrongStateException,
io::IOException,
uno::Exception,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
if ( m_bWaitSaveCompleted )
throw embed::WrongStateException(
::rtl::OUString::createFromAscii( "The object waits for saveCompleted() call!\n" ),
uno::Reference< uno::XInterface >( static_cast< ::cppu::OWeakObject* >(this) ) );
// nothing to reload
}
//------------------------------------------------------
uno::Sequence< sal_Int8 > SAL_CALL ODummyEmbeddedObject::getClassID()
throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
// currently the class ID is empty
// TODO/LATER: should a special class ID be used in this case?
return uno::Sequence< sal_Int8 >();
}
//------------------------------------------------------
::rtl::OUString SAL_CALL ODummyEmbeddedObject::getClassName()
throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_bDisposed )
throw lang::DisposedException(); // TODO
return ::rtl::OUString();
}
//------------------------------------------------------
void SAL_CALL ODummyEmbeddedObject::setClassInfo(
const uno::Sequence< sal_Int8 >& /*aClassID*/, const ::rtl::OUString& /*aClassName*/ )
throw ( lang::NoSupportException,
uno::RuntimeException )
{
throw lang::NoSupportException();
}
//------------------------------------------------------
uno::Reference< util::XCloseable > SAL_CALL ODummyEmbeddedObject::getComponent()
throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
CheckInit();
return uno::Reference< util::XCloseable >();
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::addStateChangeListener( const uno::Reference< embed::XStateChangeListener >& xListener )
throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_bDisposed )
return;
if ( !m_pInterfaceContainer )
m_pInterfaceContainer = new ::cppu::OMultiTypeInterfaceContainerHelper( m_aMutex );
m_pInterfaceContainer->addInterface( ::getCppuType( (const uno::Reference< embed::XStateChangeListener >*)0 ),
xListener );
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::removeStateChangeListener(
const uno::Reference< embed::XStateChangeListener >& xListener )
throw (uno::RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_pInterfaceContainer )
m_pInterfaceContainer->removeInterface( ::getCppuType( (const uno::Reference< embed::XStateChangeListener >*)0 ),
xListener );
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::close( sal_Bool bDeliverOwnership )
throw ( util::CloseVetoException,
uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_bDisposed )
throw lang::DisposedException(); // TODO
uno::Reference< uno::XInterface > xSelfHold( static_cast< ::cppu::OWeakObject* >( this ) );
lang::EventObject aSource( static_cast< ::cppu::OWeakObject* >( this ) );
if ( m_pInterfaceContainer )
{
::cppu::OInterfaceContainerHelper* pContainer =
m_pInterfaceContainer->getContainer( ::getCppuType( ( const uno::Reference< util::XCloseListener >*) NULL ) );
if ( pContainer != NULL )
{
::cppu::OInterfaceIteratorHelper pIterator(*pContainer);
while (pIterator.hasMoreElements())
{
try
{
((util::XCloseListener*)pIterator.next())->queryClosing( aSource, bDeliverOwnership );
}
catch( uno::RuntimeException& )
{
pIterator.remove();
}
}
}
pContainer = m_pInterfaceContainer->getContainer(
::getCppuType( ( const uno::Reference< util::XCloseListener >*) NULL ) );
if ( pContainer != NULL )
{
::cppu::OInterfaceIteratorHelper pCloseIterator(*pContainer);
while (pCloseIterator.hasMoreElements())
{
try
{
((util::XCloseListener*)pCloseIterator.next())->notifyClosing( aSource );
}
catch( uno::RuntimeException& )
{
pCloseIterator.remove();
}
}
}
m_pInterfaceContainer->disposeAndClear( aSource );
}
m_bDisposed = sal_True; // the object is disposed now for outside
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::addCloseListener( const uno::Reference< util::XCloseListener >& xListener )
throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_bDisposed )
return;
if ( !m_pInterfaceContainer )
m_pInterfaceContainer = new ::cppu::OMultiTypeInterfaceContainerHelper( m_aMutex );
m_pInterfaceContainer->addInterface( ::getCppuType( (const uno::Reference< util::XCloseListener >*)0 ), xListener );
}
//----------------------------------------------
void SAL_CALL ODummyEmbeddedObject::removeCloseListener( const uno::Reference< util::XCloseListener >& xListener )
throw (uno::RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_pInterfaceContainer )
m_pInterfaceContainer->removeInterface( ::getCppuType( (const uno::Reference< util::XCloseListener >*)0 ),
xListener );
}
//------------------------------------------------------
void SAL_CALL ODummyEmbeddedObject::addEventListener( const uno::Reference< document::XEventListener >& xListener )
throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_bDisposed )
return;
if ( !m_pInterfaceContainer )
m_pInterfaceContainer = new ::cppu::OMultiTypeInterfaceContainerHelper( m_aMutex );
m_pInterfaceContainer->addInterface( ::getCppuType( (const uno::Reference< document::XEventListener >*)0 ), xListener );
}
//------------------------------------------------------
void SAL_CALL ODummyEmbeddedObject::removeEventListener( const uno::Reference< document::XEventListener >& xListener )
throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( m_aMutex );
if ( m_pInterfaceContainer )
m_pInterfaceContainer->removeInterface( ::getCppuType( (const uno::Reference< document::XEventListener >*)0 ),
xListener );
}
|
/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005 darkbits Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/exception.hpp"
#include "guichan/focushandler.hpp"
#include "guichan/gui.hpp"
#include "guichan/key.hpp"
#include "config.hpp"
extern "C"
{
char* gcnGuichanVersion()
{
return PACKAGE_VERSION;
}
}
namespace gcn
{
Gui::Gui()
{
mTop = NULL;
mInput = NULL;
mGraphics = NULL;
mFocusHandler = new FocusHandler();
mTopHasMouse = false;
mTabbing = true;
} // end Gui
Gui::~Gui()
{
if (Widget::widgetExists(mTop))
{
setTop(NULL);
}
delete mFocusHandler;
} // end ~Gui
void Gui::setTop(Widget* top)
{
if (mTop)
{
mTop->_setFocusHandler(NULL);
}
if (top)
{
top->_setFocusHandler(mFocusHandler);
}
mTop = top;
} // end setTop
Widget* Gui::getTop() const
{
return mTop;
} // end getTop
void Gui::setGraphics(Graphics* graphics)
{
mGraphics = graphics;
} // end setGraphics
Graphics* Gui::getGraphics() const
{
return mGraphics;
} // end getGraphics
void Gui::setInput(Input* input)
{
mInput = input;
} // end setInput
Input* Gui::getInput() const
{
return mInput;
} // end getInput
void Gui::logic()
{
if (!mTop)
{
throw GCN_EXCEPTION("Gui::logic. No top widget set");
}
if(mInput)
{
mInput->_pollInput();
while (!mInput->isMouseQueueEmpty())
{
MouseInput mi = mInput->dequeueMouseInput();
// Send mouse input to every widget that has the mouse.
if (mi.x > 0 && mi.y > 0
&& mTop->getDimension().isPointInRect(mi.x, mi.y))
{
if (!mTop->hasMouse())
{
mTop->_mouseInMessage();
}
MouseInput mio = mi;
mio.x -= mTop->getX();
mio.y -= mTop->getY();
mTop->_mouseInputMessage(mio);
}
else if (mTop->hasMouse())
{
mTop->_mouseOutMessage();
}
Widget* f = mFocusHandler->getFocused();
Widget* d = mFocusHandler->getDragged();
// If the focused widget doesn't have the mouse,
// send the mouse input to the focused widget.
if (f != NULL && !f->hasMouse())
{
int xOffset, yOffset;
f->getAbsolutePosition(xOffset, yOffset);
MouseInput mio = mi;
mio.x -= xOffset;
mio.y -= yOffset;
f->_mouseInputMessage(mio);
}
// If the dragged widget is different from the focused
// widget, send the mouse input to the dragged widget.
if (d != NULL && d != f && !d->hasMouse())
{
int xOffset, yOffset;
d->getAbsolutePosition(xOffset, yOffset);
MouseInput mio = mi;
mio.x -= xOffset;
mio.y -= yOffset;
d->_mouseInputMessage(mio);
}
mFocusHandler->applyChanges();
} // end while
while (!mInput->isKeyQueueEmpty())
{
KeyInput ki = mInput->dequeueKeyInput();
if (mTabbing
&& ki.getKey().getValue() == Key::TAB
&& ki.getType() == KeyInput::PRESS)
{
if (ki.getKey().isShiftPressed())
{
mFocusHandler->tabPrevious();
}
else
{
mFocusHandler->tabNext();
}
}
else
{
// Send key inputs to the focused widgets
if (mFocusHandler->getFocused())
{
if (mFocusHandler->getFocused()->isFocusable())
{
mFocusHandler->getFocused()->_keyInputMessage(ki);
}
else
{
mFocusHandler->focusNone();
}
}
}
mFocusHandler->applyChanges();
} // end while
} // end if
mTop->logic();
} // end logic
void Gui::draw()
{
if (!mTop)
{
throw GCN_EXCEPTION("Gui::draw. No top widget set");
}
if (!mGraphics)
{
throw GCN_EXCEPTION("Gui::draw. No graphics set");
}
mGraphics->_beginDraw();
// If top has a border,
// draw it before drawing top
if (mTop->getBorderSize() > 0)
{
Rectangle rec = mTop->getDimension();
rec.x -= mTop->getBorderSize();
rec.y -= mTop->getBorderSize();
rec.width += 2 * mTop->getBorderSize();
rec.height += 2 * mTop->getBorderSize();
mGraphics->pushClipArea(rec);
mTop->drawBorder(mGraphics);
mGraphics->popClipArea();
}
mGraphics->pushClipArea(mTop->getDimension());
mTop->draw(mGraphics);
mGraphics->popClipArea();
mGraphics->_endDraw();
} // end draw
void Gui::focusNone()
{
mFocusHandler->focusNone();
}
void Gui::setTabbingEnabled(bool tabbing)
{
mTabbing = tabbing;
}
bool Gui::isTabbingEnabled()
{
return mTabbing;
}
} // end gcn
Moved gcnGuichanVersion to guichan.cpp.
/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005 darkbits Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/exception.hpp"
#include "guichan/focushandler.hpp"
#include "guichan/gui.hpp"
#include "guichan/key.hpp"
namespace gcn
{
Gui::Gui()
{
mTop = NULL;
mInput = NULL;
mGraphics = NULL;
mFocusHandler = new FocusHandler();
mTopHasMouse = false;
mTabbing = true;
} // end Gui
Gui::~Gui()
{
if (Widget::widgetExists(mTop))
{
setTop(NULL);
}
delete mFocusHandler;
} // end ~Gui
void Gui::setTop(Widget* top)
{
if (mTop)
{
mTop->_setFocusHandler(NULL);
}
if (top)
{
top->_setFocusHandler(mFocusHandler);
}
mTop = top;
} // end setTop
Widget* Gui::getTop() const
{
return mTop;
} // end getTop
void Gui::setGraphics(Graphics* graphics)
{
mGraphics = graphics;
} // end setGraphics
Graphics* Gui::getGraphics() const
{
return mGraphics;
} // end getGraphics
void Gui::setInput(Input* input)
{
mInput = input;
} // end setInput
Input* Gui::getInput() const
{
return mInput;
} // end getInput
void Gui::logic()
{
if (!mTop)
{
throw GCN_EXCEPTION("Gui::logic. No top widget set");
}
if(mInput)
{
mInput->_pollInput();
while (!mInput->isMouseQueueEmpty())
{
MouseInput mi = mInput->dequeueMouseInput();
// Send mouse input to every widget that has the mouse.
if (mi.x > 0 && mi.y > 0
&& mTop->getDimension().isPointInRect(mi.x, mi.y))
{
if (!mTop->hasMouse())
{
mTop->_mouseInMessage();
}
MouseInput mio = mi;
mio.x -= mTop->getX();
mio.y -= mTop->getY();
mTop->_mouseInputMessage(mio);
}
else if (mTop->hasMouse())
{
mTop->_mouseOutMessage();
}
Widget* f = mFocusHandler->getFocused();
Widget* d = mFocusHandler->getDragged();
// If the focused widget doesn't have the mouse,
// send the mouse input to the focused widget.
if (f != NULL && !f->hasMouse())
{
int xOffset, yOffset;
f->getAbsolutePosition(xOffset, yOffset);
MouseInput mio = mi;
mio.x -= xOffset;
mio.y -= yOffset;
f->_mouseInputMessage(mio);
}
// If the dragged widget is different from the focused
// widget, send the mouse input to the dragged widget.
if (d != NULL && d != f && !d->hasMouse())
{
int xOffset, yOffset;
d->getAbsolutePosition(xOffset, yOffset);
MouseInput mio = mi;
mio.x -= xOffset;
mio.y -= yOffset;
d->_mouseInputMessage(mio);
}
mFocusHandler->applyChanges();
} // end while
while (!mInput->isKeyQueueEmpty())
{
KeyInput ki = mInput->dequeueKeyInput();
if (mTabbing
&& ki.getKey().getValue() == Key::TAB
&& ki.getType() == KeyInput::PRESS)
{
if (ki.getKey().isShiftPressed())
{
mFocusHandler->tabPrevious();
}
else
{
mFocusHandler->tabNext();
}
}
else
{
// Send key inputs to the focused widgets
if (mFocusHandler->getFocused())
{
if (mFocusHandler->getFocused()->isFocusable())
{
mFocusHandler->getFocused()->_keyInputMessage(ki);
}
else
{
mFocusHandler->focusNone();
}
}
}
mFocusHandler->applyChanges();
} // end while
} // end if
mTop->logic();
} // end logic
void Gui::draw()
{
if (!mTop)
{
throw GCN_EXCEPTION("Gui::draw. No top widget set");
}
if (!mGraphics)
{
throw GCN_EXCEPTION("Gui::draw. No graphics set");
}
mGraphics->_beginDraw();
// If top has a border,
// draw it before drawing top
if (mTop->getBorderSize() > 0)
{
Rectangle rec = mTop->getDimension();
rec.x -= mTop->getBorderSize();
rec.y -= mTop->getBorderSize();
rec.width += 2 * mTop->getBorderSize();
rec.height += 2 * mTop->getBorderSize();
mGraphics->pushClipArea(rec);
mTop->drawBorder(mGraphics);
mGraphics->popClipArea();
}
mGraphics->pushClipArea(mTop->getDimension());
mTop->draw(mGraphics);
mGraphics->popClipArea();
mGraphics->_endDraw();
} // end draw
void Gui::focusNone()
{
mFocusHandler->focusNone();
}
void Gui::setTabbingEnabled(bool tabbing)
{
mTabbing = tabbing;
}
bool Gui::isTabbingEnabled()
{
return mTabbing;
}
} // end gcn
|
#include "Intake.h"
#include "Commands/IntakeBall.h"
#include "Commands/PushBall.h"
#include <math.h>
/**
* Subsystems namespace with implementation
* of Intake class.
*/
namespace subsystems
{
using IntakeBall = commands::IntakeBall;
using PushBall = commands::PushBall;
// Constructor:
Intake::Intake() : Subsystem("Intake")
{
roller_ = new CANTalon(1);
detector_ = new DigitalInput(2);
// Default values:
intake_speed_ = 1.0;
push_speed_ = -1.0;
state_ = State_t::OFF;
mode_ = Mode_t::VELOCITY;
max_velocity_ = 30;
allowed_error_ = 0.1;
}
// Destructor:
Intake::~Intake()
{
delete roller_;
delete detector_;
}
// Main functions:
void Intake::Initialize()
{
roller_->SetFeedbackDevice(CANTalon::QuadEncoder);
roller_->ConfigEncoderCodesPerRev(1024);
roller_->SetSensorDirection(false);
roller_->SelectProfileSlot(0);
roller_->SetVoltageRampRate(0.0);
roller_->SetCloseLoopRampRate(0.0);
// Configure max and min voltage outputs
roller_->ConfigNominalOutputVoltage(0.0, 0.0);
roller_->ConfigPeakOutputVoltage(12.0, -12.0);
}
bool Intake::CheckSwitch() const
{
return (detector_->Get());
}
void Intake::TakeBall(bool check)
{
if (CheckSwitch() && check)
Stop();
else
SetSpeed(intake_speed_);
}
void Intake::OutakeBall()
{
SetSpeed(push_speed_);
}
void Intake::SetSpeed(double speed)
{
if (mode_ == Mode_t::VELOCITY)
{
roller_->Set(max_velocity_ * speed);
}
else if (mode_ == Mode_t::VBUS)
{
roller_->Set(speed);
}
}
double Intake::GetSpeed() const
{
return roller_->Get();
}
void Intake::Stop()
{
SetSpeed(0.0);
}
void Intake::SetIntakeSpeed(double intake_speed)
{
intake_speed_ = intake_speed;
}
void Intake::SetPushSpeed(double push_speed)
{
push_speed_ = push_speed;
}
double Intake::GetIntakeSpeed() const
{
return intake_speed_;
}
double Intake::GetPushSpeed() const
{
return push_speed_;
}
// Error functions:
double Intake::GetErr() const
{
return roller_->GetSetpoint() - roller_->Get();
}
void Intake::SetAllowedError(double err)
{
allowed_error_ = err;
}
double Intake::GetAllowedError() const
{
return allowed_error_;
}
bool Intake::IsAllowable() const
{
return (fabs(GetErr()) > fabs(allowed_error_));
}
double Intake::GetMaxVelocity() const
{
return max_velocity_;
}
void Intake::SetMaxVelocity(double max_velocity)
{
max_velocity_ = max_velocity;
}
// State functions:
void Intake::SetState(State_t state)
{
state_ = state;
}
Intake::State_t Intake::GetState() const
{
return state_;
}
// Mode functions:
void Intake::SetMode(Mode_t mode)
{
mode_ = mode;
}
Intake::Mode_t Intake::GetMode() const
{
return mode_;
}
// Command functions:
IntakeBall* Intake::MakeIntakeBall()
{
return new IntakeBall(this);
}
PushBall* Intake::MakePushBall()
{
return new PushBall(this);
}
} // end namespace subsystems
Inconsequential format updates
#include "Intake.h"
#include "Commands/IntakeBall.h"
#include "Commands/PushBall.h"
#include <math.h>
/**
* Subsystems namespace with implementation
* of Intake class.
*/
namespace subsystems
{
using IntakeBall = commands::IntakeBall;
using PushBall = commands::PushBall;
// Constructor:
Intake::Intake() : Subsystem("Intake")
{
roller_ = new CANTalon(1);
detector_ = new DigitalInput(2);
// Default values:
intake_speed_ = 1.0;
push_speed_ = -1.0;
state_ = State_t::OFF;
mode_ = Mode_t::VELOCITY;
max_velocity_ = 30;
allowed_error_ = 0.1;
}
// Destructor:
Intake::~Intake()
{
delete roller_;
delete detector_;
}
// Main functions:
void Intake::Initialize()
{
roller_->SetFeedbackDevice(CANTalon::QuadEncoder);
roller_->ConfigEncoderCodesPerRev(1024);
roller_->SetSensorDirection(false);
roller_->SelectProfileSlot(0);
roller_->SetVoltageRampRate(0.0);
roller_->SetCloseLoopRampRate(0.0);
// Configure max and min voltage outputs
roller_->ConfigNominalOutputVoltage(0.0, 0.0);
roller_->ConfigPeakOutputVoltage(12.0, -12.0);
}
bool Intake::CheckSwitch() const
{
return (detector_->Get());
}
void Intake::TakeBall(bool check)
{
if (CheckSwitch() && check)
Stop();
else
SetSpeed(intake_speed_);
}
void Intake::OutakeBall()
{
SetSpeed(push_speed_);
}
void Intake::SetSpeed(double speed)
{
if (mode_ == Mode_t::VELOCITY)
{
roller_->Set(max_velocity_ * speed);
}
else if (mode_ == Mode_t::VBUS)
{
roller_->Set(speed);
}
}
double Intake::GetSpeed() const
{
return roller_->Get();
}
void Intake::Stop()
{
SetSpeed(0.0);
}
void Intake::SetIntakeSpeed(double intake_speed)
{
intake_speed_ = intake_speed;
}
void Intake::SetPushSpeed(double push_speed)
{
push_speed_ = push_speed;
}
double Intake::GetIntakeSpeed() const
{
return intake_speed_;
}
double Intake::GetPushSpeed() const
{
return push_speed_;
}
double Intake::GetMaxVelocity() const
{
return max_velocity_;
}
void Intake::SetMaxVelocity(double max_velocity)
{
max_velocity_ = max_velocity;
}
// Error functions:
double Intake::GetErr() const
{
return roller_->GetSetpoint() - roller_->Get();
}
void Intake::SetAllowedError(double err)
{
allowed_error_ = err;
}
double Intake::GetAllowedError() const
{
return allowed_error_;
}
bool Intake::IsAllowable() const
{
return (fabs(GetErr()) > fabs(allowed_error_));
}
// State functions:
void Intake::SetState(State_t state)
{
state_ = state;
}
Intake::State_t Intake::GetState() const
{
return state_;
}
// Control mode functions:
void Intake::SetMode(Mode_t mode)
{
if (mode_ != mode)
{
mode_ = mode;
if (mode_ == Mode_t::VELOCITY)
roller_->SetControlMode(CANTalon::ControlMode::kSpeed);
else if (mode_ == Mode_t::VBUS)
roller_->SetControlMode(CANTalon::ControlMode::kPercentVbus);
}
}
Intake::Mode_t Intake::GetMode() const
{
return mode_;
}
// Command functions:
IntakeBall* Intake::MakeIntakeBall()
{
return new IntakeBall(this);
}
PushBall* Intake::MakePushBall()
{
return new PushBall(this);
}
} // end namespace subsystems
|
/* Siconos-Kernel, Copyright INRIA 2005-2011.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a 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.
* Siconos 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 Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr
*/
#include "D1MinusLinear.hpp"
#include "Simulation.hpp"
#include "LagrangianLinearTIDS.hpp"
#include "LagrangianRheonomousR.hpp"
#include "LagrangianScleronomousR.hpp"
#include "NewtonImpactNSL.hpp"
#include "debug.h"
using namespace std;
using namespace RELATION;
struct D1MinusLinear::_NSLEffectOnFreeOutput : public SiconosVisitor
{
OneStepNSProblem *osnsp;
SP::UnitaryRelation UR;
_NSLEffectOnFreeOutput(OneStepNSProblem *p, SP::UnitaryRelation UR) : osnsp(p), UR(UR) {};
void visit(const NewtonImpactNSL& nslaw)
{
double e = nslaw.e();
Index subCoord(4);
subCoord[0] = 0;
subCoord[1] = UR->getNonSmoothLawSize();
subCoord[2] = 0;
subCoord[3] = subCoord[1];
subscal(e, *(UR->y_k(osnsp->levelMin())), *(UR->yp()), subCoord, false);
}
};
D1MinusLinear::D1MinusLinear(SP::DynamicalSystem newDS) :
OneStepIntegrator(OSI::D1MINUSLINEAR)
{
OSIDynamicalSystems->insert(newDS);
}
D1MinusLinear::D1MinusLinear(DynamicalSystemsSet& newDS): OneStepIntegrator(OSI::D1MINUSLINEAR, newDS) {}
void D1MinusLinear::initialize()
{
for (DSIterator it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it)
{
Type::Siconos dsType = Type::value(**it);
if (dsType != Type::LagrangianDS && dsType != Type::LagrangianLinearTIDS)
RuntimeException::selfThrow("D1MinusLinear::initialize - not implemented for Dynamical system type: " + dsType);
SP::LagrangianDS d = boost::static_pointer_cast<LagrangianDS> (*it);
d->computeMass();
}
}
double D1MinusLinear::computeResidu()
{
DEBUG_PRINT("\nCOMPUTERESIDU\n");
double t = simulationLink->nextTime(); // end of the time step
double told = simulationLink->startingTime(); // beginning of the time step
double h = simulationLink->timeStep(); // time step length
SP::OneStepNSProblems allOSNS = simulationLink->oneStepNSProblems(); // all OSNSP
SP::InteractionsSet allInteractions = simulationLink->model()->nonSmoothDynamicalSystem()->interactions(); // all Interactions
DEBUG_PRINTF("nextTime %f\n", t);
DEBUG_PRINTF("startingTime %f\n", told);
DEBUG_PRINTF("time step size %f\n", h);
DEBUG_PRINT("\nLEFT SIDE\n");
// -- LEFT SIDE --
// calculate acceleration without contact force
for (DSIterator it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it)
{
// type of the current DS
Type::Siconos dsType = Type::value(**it);
SP::LagrangianDS d = boost::static_pointer_cast<LagrangianDS> (*it);
SP::SiconosVector workFree = d->workFree(); // POINTER CONSTRUCTOR : contains acceleration without contact force
workFree->zero();
// get left state from memory
SP::SiconosVector qold = d->qMemory()->getSiconosVector(0);
SP::SiconosVector vold = d->velocityMemory()->getSiconosVector(0); // right limit
SP::SiconosMatrix Mold = d->mass();
DEBUG_EXPR(workFree->display());
DEBUG_EXPR(qold->display());
DEBUG_EXPR(vold->display());
DEBUG_EXPR(Mold->display());
// Lagrangian Nonlinear Systems
if (dsType == Type::LagrangianDS)
{
if (d->forces())
{
d->computeForces(told, qold, vold);
*workFree += *(d->forces());
}
}
// Lagrangian Linear Systems
else if (dsType == Type::LagrangianLinearTIDS)
{
SP::LagrangianLinearTIDS d = boost::static_pointer_cast<LagrangianLinearTIDS> (*it);
SP::SiconosMatrix C = d->C(); // constant dissipation
SP::SiconosMatrix K = d->K(); // constant stiffness
SP::SiconosVector Fext = d->fExt(); // time dependent force
if (K)
{
prod(*K, *qold, *workFree, false);
}
if (C)
{
prod(*C, *vold, *workFree, false);
}
*workFree *= -1.;
if (Fext)
{
d->computeFExt(told);
*workFree += *Fext;
}
}
Mold->PLUForwardBackwardInPlace(*workFree); // contains left (right limit) acceleration without contact force
DEBUG_EXPR(workFree->display());
}
// solve a LCP at acceleration level
if (!allOSNS->empty())
{
for (InteractionsIterator it = allInteractions->begin(); it != allInteractions->end(); it++)
{
(*it)->relation()->computeJach(told);
(*it)->relation()->computeJacg(told);
}
if (simulationLink->model()->nonSmoothDynamicalSystem()->topology()->hasChanged())
{
for (OSNSIterator itOsns = allOSNS->begin(); itOsns != allOSNS->end(); ++itOsns)
{
(*itOsns)->setHasBeUpdated(false);
}
}
if (!((*allOSNS)[SICONOS_OSNSP_TS_VELOCITY + 1]->interactions())->isEmpty())
{
(*allOSNS)[SICONOS_OSNSP_TS_VELOCITY + 1]->compute(told);
simulationLink->updateInput(2);
}
}
DEBUG_PRINT("\nADVANCE TO RIGHT SIDE\n");
// ADVANCE TO RIGHT
for (DSIterator it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it)
{
// type of the current DS
SP::LagrangianDS d = boost::static_pointer_cast<LagrangianDS> (*it);
SP::SiconosVector workFree = d->workFree(); // contains acceleration without contact force
// get left state from memory
SP::SiconosVector qold = d->qMemory()->getSiconosVector(0);
SP::SiconosVector vold = d->velocityMemory()->getSiconosVector(0); // right limit
SP::SiconosMatrix Mold = d->mass();
// initialize *it->residuFree and predicted right velocity (left limit)
SP::SiconosVector residuFree = (*it)->residuFree(); // POINTER CONSTRUCTOR : contains residu without nonsmooth effect
SP::SiconosVector v = d->velocity(); // POINTER CONSTRUCTOR : contains velocity v_{k+1}^- and not free velocity
residuFree->zero();
v->zero();
DEBUG_EXPR(workFree->display());
DEBUG_EXPR(qold->display());
DEBUG_EXPR(vold->display());
DEBUG_EXPR(Mold->display());
DEBUG_EXPR(residuFree->display());
DEBUG_EXPR(v->display());
if (d->p(2))
{
scal(-0.5 * h, *(d->p(2)), *residuFree, false);
scal(h, *(d->p(2)), *v, false);
DEBUG_EXPR(d->p(2)->display());
Mold->PLUForwardBackwardInPlace(*residuFree);
Mold->PLUForwardBackwardInPlace(*v);
}
DEBUG_EXPR(residuFree->display());
DEBUG_EXPR(v->display());
*residuFree -= 0.5 * h**workFree;
*v += h**workFree;
*v += *vold;
DEBUG_EXPR(residuFree->display());
DEBUG_EXPR(v->display());
SP::SiconosVector q = d->q(); // POINTER CONSTRUCTOR : contains position q_{k+1}
*q = *qold;
DEBUG_EXPR(q->display());
scal(0.5 * h, *vold + *v, *q, false);
DEBUG_EXPR(Mold->display());
DEBUG_EXPR(q->display());
}
DEBUG_PRINT("\nRIGHT SIDE\n");
// -- RIGHT SIDE --
// calculate acceleration without contact force
for (DSIterator it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it)
{
// type of the current DS
Type::Siconos dsType = Type::value(**it);
SP::LagrangianDS d = boost::static_pointer_cast<LagrangianDS> (*it);
SP::SiconosVector workFree = d->workFree(); // POINTER CONSTRUCTOR : contains acceleration without contact force
workFree->zero();
// get right state from memory
SP::SiconosVector q = d->q(); // contains position q_{k+1}
SP::SiconosVector v = d->velocity(); // contains velocity v_{k+1}^- and not free velocity
SP::SiconosMatrix M = d->mass(); // POINTER CONSTRUCTOR : contains mass matrix
DEBUG_EXPR(workFree->display());
DEBUG_EXPR(q->display());
DEBUG_EXPR(v->display());
DEBUG_EXPR(M->display());
// Lagrangian Nonlinear Systems
if (dsType == Type::LagrangianDS)
{
d->computeMass();
if (d->forces())
{
d->computeForces(t, q, v);
*workFree += *(d->forces());
}
}
// Lagrangian Linear Systems
else if (dsType == Type::LagrangianLinearTIDS)
{
SP::LagrangianLinearTIDS d = boost::static_pointer_cast<LagrangianLinearTIDS> (*it);
SP::SiconosMatrix C = d->C(); // constant dissipation
SP::SiconosMatrix K = d->K(); // constant stiffness
SP::SiconosVector Fext = d->fExt(); // time-dependent force
if (K)
{
prod(*K, *q, *workFree, false);
}
if (C)
{
prod(*C, *v, *workFree, false);
}
*workFree *= -1.;
if (Fext)
{
d->computeFExt(t);
*workFree += *Fext;
}
}
DEBUG_EXPR(M->display());
M->PLUForwardBackwardInPlace(*workFree); // contains right (left limit) acceleration without contact force
DEBUG_EXPR(workFree->display());
DEBUG_EXPR(q->display());
DEBUG_EXPR(v->display());
DEBUG_EXPR(M->display());
}
// solve a LCP at acceleration level only for contacts which have been active at the beginning of the time-step
if (!allOSNS->empty())
{
for (unsigned int level = simulationLink->levelMinForOutput(); level < simulationLink->levelMaxForOutput(); level++)
simulationLink->updateOutput(level);
// special update to consider only contacts which have been active at the beginning of the time-step
//
// Maurice Bremond: indices must be recomputed
// as we deal with dynamic graphs, vertices and edges are stored
// in lists for fast add/remove during updateIndexSet(i)
// we need indices of list elements to build the OSNS Matrix so we
// need an update if graph has changed
// this should be done in updateIndexSet(i) for all integrators only
// if a graph has changed
simulationLink->updateIndexSets();
//simulationLink->model()->nonSmoothDynamicalSystem()->topology()->indexSet(1)->update_vertices_indices();
//simulationLink->model()->nonSmoothDynamicalSystem()->topology()->indexSet(1)->update_edges_indices();
//simulationLink->model()->nonSmoothDynamicalSystem()->topology()->indexSet(2)->update_vertices_indices();
//simulationLink->model()->nonSmoothDynamicalSystem()->topology()->indexSet(2)->update_edges_indices();
for (InteractionsIterator it = allInteractions->begin(); it != allInteractions->end(); it++)
{
(*it)->relation()->computeJach(t);
(*it)->relation()->computeJacg(t);
}
if (simulationLink->model()->nonSmoothDynamicalSystem()->topology()->hasChanged())
{
for (OSNSIterator itOsns = allOSNS->begin(); itOsns != allOSNS->end(); ++itOsns)
{
(*itOsns)->setHasBeUpdated(false);
}
}
if (!((*allOSNS)[SICONOS_OSNSP_TS_VELOCITY + 1]->interactions())->isEmpty())
{
(*allOSNS)[SICONOS_OSNSP_TS_VELOCITY + 1]->compute(t);
simulationLink->updateInput(2);
}
}
DEBUG_PRINT("\nRESIDU\n");
// -- RESIDU --
for (DSIterator it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it)
{
// type of the current DS
SP::LagrangianDS d = boost::static_pointer_cast<LagrangianDS> (*it);
SP::SiconosVector workFree = d->workFree(); // contains acceleration without contact force
// get right state from memory
SP::SiconosMatrix M = d->mass();
// initialize *it->residuFree
SP::SiconosVector residuFree = (*it)->residuFree(); // POINTER CONSTRUCTOR : contains residu without nonsmooth effect
*residuFree -= 0.5 * h**workFree;
DEBUG_EXPR(workFree->display());
DEBUG_EXPR(M->display());
if (d->p(2))
{
SP::SiconosVector dummy(new SimpleVector(*(d->p(2)))); // value = contact force
M->PLUForwardBackwardInPlace(*dummy);
*residuFree -= 0.5 * h**dummy;
DEBUG_EXPR(d->p(2)->display());
}
*residuFree = prod(*M, *residuFree);
DEBUG_EXPR(residuFree->display());
}
return 0.; // there is no Newton iteration and the residuum is assumed to vanish
}
void D1MinusLinear::computeFreeState()
{
for (DSIterator it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it)
{
// Lagrangian Systems
SP::LagrangianDS d = boost::static_pointer_cast<LagrangianDS> (*it);
// get left state from memory
SP::SiconosVector vold = d->velocityMemory()->getSiconosVector(0); // right limit
// get right information
SP::SiconosMatrix M = d->mass();
SP::SiconosVector vfree = d->velocity(); // POINTER CONSTRUCTOR : contains free velocity
(*vfree) = *(d->residuFree());
M->PLUForwardBackwardInPlace(*vfree);
*vfree *= -1.;
*vfree += *vold;
}
}
void D1MinusLinear::computeFreeOutput(SP::UnitaryRelation UR, OneStepNSProblem* osnsp)
{
SP::OneStepNSProblems allOSNS = simulationLink->oneStepNSProblems(); // all OSNSP
// get relation and non smooth law information
RELATION::TYPES relationType = UR->getRelationType(); // relation
RELATION::SUBTYPES relationSubType = UR->getRelationSubType();
unsigned int relativePosition = UR->getRelativePosition();
unsigned int sizeY = UR->getNonSmoothLawSize(); // related NSL
Index coord(8);
coord[0] = relativePosition;
coord[1] = relativePosition + sizeY;
coord[2] = 0;
coord[3] = 0;
coord[4] = 0;
coord[5] = 0;
coord[6] = 0;
coord[7] = sizeY;
SP::SiconosMatrix C; // Jacobian of Relation with respect to degree of freedom
SP::SiconosVector Xfree; // free degree of freedom
SP::SiconosVector Yp = UR->yp(); // POINTER CONSTRUCTOR : contains output
// define Xfree for velocity and acceleration level
if (((*allOSNS)[SICONOS_OSNSP_TS_VELOCITY]).get() == osnsp)
{
Xfree = UR->workx();
}
else if (((*allOSNS)[SICONOS_OSNSP_TS_VELOCITY + 1]).get() == osnsp)
{
Xfree = UR->workFree();
}
else
RuntimeException::selfThrow("D1MinusLinear::computeFreeOutput - OSNSP neither on velocity nor on acceleration level.");
// calculate data of interaction
SP::Interaction mainInteraction = UR->interaction();
assert(mainInteraction);
assert(mainInteraction->relation());
// only Lagrangian Systems
if (relationType == Lagrangian)
{
// in Yp the linear part of velocity or acceleration relation will be saved
C = mainInteraction->relation()->C();
if (C)
{
assert(Xfree);
assert(Yp);
coord[3] = C->size(1);
coord[5] = C->size(1);
subprod(*C, *Xfree, *Yp, coord, true);
}
// in Yp corrections have to be added
SP::SiconosMatrix ID(new SimpleMatrix(sizeY, sizeY));
ID->eye();
Index xcoord(8);
xcoord[0] = 0;
xcoord[1] = sizeY;
xcoord[2] = 0;
xcoord[3] = sizeY;
xcoord[4] = 0;
xcoord[5] = sizeY;
xcoord[6] = 0;
xcoord[7] = sizeY;
if (relationSubType == RheonomousR) // explicit time dependence -> partial time derivative has to be added
{
if (((*allOSNS)[SICONOS_OSNSP_TS_VELOCITY]).get() == osnsp)
{
boost::static_pointer_cast<LagrangianRheonomousR>(UR->interaction()->relation())->computehDot(simulation()->getTkp1());
subprod(*ID, *(boost::static_pointer_cast<LagrangianRheonomousR>(UR->interaction()->relation())->hDot()), *Yp, xcoord, false);
}
else
RuntimeException::selfThrow("D1MinusLinear::computeFreeOutput is only implemented at velocity level for LagrangianRheonomousR.");
}
if (relationSubType == ScleronomousR) // acceleration term involving Hesse matrix of Relation with respect to degree is added
{
if (((*allOSNS)[SICONOS_OSNSP_TS_VELOCITY + 1]).get() == osnsp)
{
boost::static_pointer_cast<LagrangianScleronomousR>(UR->interaction()->relation())->computeNonLinearH2dot(simulation()->getTkp1());
subprod(*ID, *(boost::static_pointer_cast<LagrangianScleronomousR>(UR->interaction()->relation())->Nonlinearh2dot()), *Yp, xcoord, false);
}
}
if (((*allOSNS)[SICONOS_OSNSP_TS_VELOCITY]).get() == osnsp) // impact terms are added
{
SP::SiconosVisitor nslEffectOnFreeOutput(new _NSLEffectOnFreeOutput(osnsp, UR));
UR->interaction()->nonSmoothLaw()->accept(*nslEffectOnFreeOutput);
}
}
else
RuntimeException::selfThrow("D1MinusLinear::computeFreeOutput - not implemented for Relation of type " + relationType);
}
void D1MinusLinear::updateState(unsigned int level)
{
for (DSIterator it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it)
{
// Lagrangian Systems
SP::LagrangianDS d = boost::static_pointer_cast<LagrangianDS> (*it);
SP::SiconosMatrix M = d->mass();
SP::SiconosVector v = d->velocity(); // POINTER CONSTRUCTOR : contains new velocity
if (d->p(1))
{
SP::SiconosVector dummy(new SimpleVector(*(d->p(1)))); // value = nonsmooth impulse
M->PLUForwardBackwardInPlace(*dummy); // solution for its velocity equivalent
*v += *dummy; // add free velocity
DEBUG_PRINT("\nRIGHT IMPULSE\n");
DEBUG_PRINTF("%f\n", (*(d->p(1)))(0));
DEBUG_EXPR(throw(1));
}
}
}
void D1MinusLinear::insertDynamicalSystem(SP::DynamicalSystem ds)
{
OSIDynamicalSystems->insert(ds);
}
D1MinusLinear* D1MinusLinear::convert(OneStepIntegrator* osi)
{
return dynamic_cast<D1MinusLinear*>(osi);
}
reset lu decomposition for d1minuslinear
git-svn-id: de9bbed4c30e0eb58fe8e7d66f5c80b71699a07c@2922 bf01a9d7-0df3-0310-8ad4-b1c94d9ae2d5
/* Siconos-Kernel, Copyright INRIA 2005-2011.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a 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.
* Siconos 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 Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr
*/
#include "D1MinusLinear.hpp"
#include "Simulation.hpp"
#include "LagrangianLinearTIDS.hpp"
#include "LagrangianRheonomousR.hpp"
#include "LagrangianScleronomousR.hpp"
#include "NewtonImpactNSL.hpp"
#include "debug.h"
using namespace std;
using namespace RELATION;
struct D1MinusLinear::_NSLEffectOnFreeOutput : public SiconosVisitor
{
OneStepNSProblem *osnsp;
SP::UnitaryRelation UR;
_NSLEffectOnFreeOutput(OneStepNSProblem *p, SP::UnitaryRelation UR) : osnsp(p), UR(UR) {};
void visit(const NewtonImpactNSL& nslaw)
{
double e = nslaw.e();
Index subCoord(4);
subCoord[0] = 0;
subCoord[1] = UR->getNonSmoothLawSize();
subCoord[2] = 0;
subCoord[3] = subCoord[1];
subscal(e, *(UR->y_k(osnsp->levelMin())), *(UR->yp()), subCoord, false);
}
};
D1MinusLinear::D1MinusLinear(SP::DynamicalSystem newDS) :
OneStepIntegrator(OSI::D1MINUSLINEAR)
{
OSIDynamicalSystems->insert(newDS);
}
D1MinusLinear::D1MinusLinear(DynamicalSystemsSet& newDS): OneStepIntegrator(OSI::D1MINUSLINEAR, newDS) {}
void D1MinusLinear::initialize()
{
for (DSIterator it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it)
{
Type::Siconos dsType = Type::value(**it);
if (dsType != Type::LagrangianDS && dsType != Type::LagrangianLinearTIDS)
RuntimeException::selfThrow("D1MinusLinear::initialize - not implemented for Dynamical system type: " + dsType);
SP::LagrangianDS d = boost::static_pointer_cast<LagrangianDS> (*it);
d->computeMass();
}
}
double D1MinusLinear::computeResidu()
{
DEBUG_PRINT("\nCOMPUTERESIDU\n");
double t = simulationLink->nextTime(); // end of the time step
double told = simulationLink->startingTime(); // beginning of the time step
double h = simulationLink->timeStep(); // time step length
SP::OneStepNSProblems allOSNS = simulationLink->oneStepNSProblems(); // all OSNSP
SP::InteractionsSet allInteractions = simulationLink->model()->nonSmoothDynamicalSystem()->interactions(); // all Interactions
DEBUG_PRINTF("nextTime %f\n", t);
DEBUG_PRINTF("startingTime %f\n", told);
DEBUG_PRINTF("time step size %f\n", h);
DEBUG_PRINT("\nLEFT SIDE\n");
// -- LEFT SIDE --
// calculate acceleration without contact force
for (DSIterator it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it)
{
// type of the current DS
Type::Siconos dsType = Type::value(**it);
SP::LagrangianDS d = boost::static_pointer_cast<LagrangianDS> (*it);
SP::SiconosVector workFree = d->workFree(); // POINTER CONSTRUCTOR : contains acceleration without contact force
workFree->zero();
// get left state from memory
SP::SiconosVector qold = d->qMemory()->getSiconosVector(0);
SP::SiconosVector vold = d->velocityMemory()->getSiconosVector(0); // right limit
SP::SiconosMatrix Mold = d->mass();
DEBUG_EXPR(workFree->display());
DEBUG_EXPR(qold->display());
DEBUG_EXPR(vold->display());
DEBUG_EXPR(Mold->display());
// Lagrangian Nonlinear Systems
if (dsType == Type::LagrangianDS)
{
if (d->forces())
{
d->computeForces(told, qold, vold);
*workFree += *(d->forces());
}
}
// Lagrangian Linear Systems
else if (dsType == Type::LagrangianLinearTIDS)
{
SP::LagrangianLinearTIDS d = boost::static_pointer_cast<LagrangianLinearTIDS> (*it);
SP::SiconosMatrix C = d->C(); // constant dissipation
SP::SiconosMatrix K = d->K(); // constant stiffness
SP::SiconosVector Fext = d->fExt(); // time dependent force
if (K)
{
prod(*K, *qold, *workFree, false);
}
if (C)
{
prod(*C, *vold, *workFree, false);
}
*workFree *= -1.;
if (Fext)
{
d->computeFExt(told);
*workFree += *Fext;
}
}
Mold->PLUForwardBackwardInPlace(*workFree); // contains left (right limit) acceleration without contact force
DEBUG_EXPR(workFree->display());
}
// solve a LCP at acceleration level
if (!allOSNS->empty())
{
for (InteractionsIterator it = allInteractions->begin(); it != allInteractions->end(); it++)
{
(*it)->relation()->computeJach(told);
(*it)->relation()->computeJacg(told);
}
if (simulationLink->model()->nonSmoothDynamicalSystem()->topology()->hasChanged())
{
for (OSNSIterator itOsns = allOSNS->begin(); itOsns != allOSNS->end(); ++itOsns)
{
(*itOsns)->setHasBeUpdated(false);
}
}
if (!((*allOSNS)[SICONOS_OSNSP_TS_VELOCITY + 1]->interactions())->isEmpty())
{
(*allOSNS)[SICONOS_OSNSP_TS_VELOCITY + 1]->compute(told);
simulationLink->updateInput(2);
}
}
DEBUG_PRINT("\nADVANCE TO RIGHT SIDE\n");
// ADVANCE TO RIGHT
for (DSIterator it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it)
{
// type of the current DS
SP::LagrangianDS d = boost::static_pointer_cast<LagrangianDS> (*it);
SP::SiconosVector workFree = d->workFree(); // contains acceleration without contact force
// get left state from memory
SP::SiconosVector qold = d->qMemory()->getSiconosVector(0);
SP::SiconosVector vold = d->velocityMemory()->getSiconosVector(0); // right limit
SP::SiconosMatrix Mold = d->mass();
// initialize *it->residuFree and predicted right velocity (left limit)
SP::SiconosVector residuFree = (*it)->residuFree(); // POINTER CONSTRUCTOR : contains residu without nonsmooth effect
SP::SiconosVector v = d->velocity(); // POINTER CONSTRUCTOR : contains velocity v_{k+1}^- and not free velocity
residuFree->zero();
v->zero();
DEBUG_EXPR(workFree->display());
DEBUG_EXPR(qold->display());
DEBUG_EXPR(vold->display());
DEBUG_EXPR(Mold->display());
DEBUG_EXPR(residuFree->display());
DEBUG_EXPR(v->display());
if (d->p(2))
{
scal(-0.5 * h, *(d->p(2)), *residuFree, false);
scal(h, *(d->p(2)), *v, false);
DEBUG_EXPR(d->p(2)->display());
Mold->PLUForwardBackwardInPlace(*residuFree);
Mold->PLUForwardBackwardInPlace(*v);
}
DEBUG_EXPR(residuFree->display());
DEBUG_EXPR(v->display());
*residuFree -= 0.5 * h**workFree;
*v += h**workFree;
*v += *vold;
DEBUG_EXPR(residuFree->display());
DEBUG_EXPR(v->display());
SP::SiconosVector q = d->q(); // POINTER CONSTRUCTOR : contains position q_{k+1}
*q = *qold;
DEBUG_EXPR(q->display());
scal(0.5 * h, *vold + *v, *q, false);
DEBUG_EXPR(Mold->display());
DEBUG_EXPR(q->display());
}
DEBUG_PRINT("\nRIGHT SIDE\n");
// -- RIGHT SIDE --
// calculate acceleration without contact force
for (DSIterator it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it)
{
// type of the current DS
Type::Siconos dsType = Type::value(**it);
SP::LagrangianDS d = boost::static_pointer_cast<LagrangianDS> (*it);
SP::SiconosVector workFree = d->workFree(); // POINTER CONSTRUCTOR : contains acceleration without contact force
workFree->zero();
// get right state from memory
SP::SiconosVector q = d->q(); // contains position q_{k+1}
SP::SiconosVector v = d->velocity(); // contains velocity v_{k+1}^- and not free velocity
SP::SiconosMatrix M = d->mass(); // POINTER CONSTRUCTOR : contains mass matrix
DEBUG_EXPR(workFree->display());
DEBUG_EXPR(q->display());
DEBUG_EXPR(v->display());
DEBUG_EXPR(M->display());
// Lagrangian Nonlinear Systems
if (dsType == Type::LagrangianDS)
{
d->computeMass();
M->resetLU();
if (d->forces())
{
d->computeForces(t, q, v);
*workFree += *(d->forces());
}
}
// Lagrangian Linear Systems
else if (dsType == Type::LagrangianLinearTIDS)
{
SP::LagrangianLinearTIDS d = boost::static_pointer_cast<LagrangianLinearTIDS> (*it);
SP::SiconosMatrix C = d->C(); // constant dissipation
SP::SiconosMatrix K = d->K(); // constant stiffness
SP::SiconosVector Fext = d->fExt(); // time-dependent force
if (K)
{
prod(*K, *q, *workFree, false);
}
if (C)
{
prod(*C, *v, *workFree, false);
}
*workFree *= -1.;
if (Fext)
{
d->computeFExt(t);
*workFree += *Fext;
}
}
DEBUG_EXPR(M->display());
M->PLUForwardBackwardInPlace(*workFree); // contains right (left limit) acceleration without contact force
DEBUG_EXPR(workFree->display());
DEBUG_EXPR(q->display());
DEBUG_EXPR(v->display());
DEBUG_EXPR(M->display());
}
// solve a LCP at acceleration level only for contacts which have been active at the beginning of the time-step
if (!allOSNS->empty())
{
for (unsigned int level = simulationLink->levelMinForOutput(); level < simulationLink->levelMaxForOutput(); level++)
simulationLink->updateOutput(level);
// special update to consider only contacts which have been active at the beginning of the time-step
//
// Maurice Bremond: indices must be recomputed
// as we deal with dynamic graphs, vertices and edges are stored
// in lists for fast add/remove during updateIndexSet(i)
// we need indices of list elements to build the OSNS Matrix so we
// need an update if graph has changed
// this should be done in updateIndexSet(i) for all integrators only
// if a graph has changed
simulationLink->updateIndexSets();
//simulationLink->model()->nonSmoothDynamicalSystem()->topology()->indexSet(1)->update_vertices_indices();
//simulationLink->model()->nonSmoothDynamicalSystem()->topology()->indexSet(1)->update_edges_indices();
//simulationLink->model()->nonSmoothDynamicalSystem()->topology()->indexSet(2)->update_vertices_indices();
//simulationLink->model()->nonSmoothDynamicalSystem()->topology()->indexSet(2)->update_edges_indices();
for (InteractionsIterator it = allInteractions->begin(); it != allInteractions->end(); it++)
{
(*it)->relation()->computeJach(t);
(*it)->relation()->computeJacg(t);
}
if (simulationLink->model()->nonSmoothDynamicalSystem()->topology()->hasChanged())
{
for (OSNSIterator itOsns = allOSNS->begin(); itOsns != allOSNS->end(); ++itOsns)
{
(*itOsns)->setHasBeUpdated(false);
}
}
if (!((*allOSNS)[SICONOS_OSNSP_TS_VELOCITY + 1]->interactions())->isEmpty())
{
(*allOSNS)[SICONOS_OSNSP_TS_VELOCITY + 1]->compute(t);
simulationLink->updateInput(2);
}
}
DEBUG_PRINT("\nRESIDU\n");
// -- RESIDU --
for (DSIterator it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it)
{
// type of the current DS
SP::LagrangianDS d = boost::static_pointer_cast<LagrangianDS> (*it);
SP::SiconosVector workFree = d->workFree(); // contains acceleration without contact force
// get right state from memory
SP::SiconosMatrix M = d->mass();
// initialize *it->residuFree
SP::SiconosVector residuFree = (*it)->residuFree(); // POINTER CONSTRUCTOR : contains residu without nonsmooth effect
*residuFree -= 0.5 * h**workFree;
DEBUG_EXPR(workFree->display());
DEBUG_EXPR(M->display());
if (d->p(2))
{
SP::SiconosVector dummy(new SimpleVector(*(d->p(2)))); // value = contact force
M->PLUForwardBackwardInPlace(*dummy);
*residuFree -= 0.5 * h**dummy;
DEBUG_EXPR(d->p(2)->display());
}
*residuFree = prod(*M, *residuFree);
DEBUG_EXPR(residuFree->display());
}
return 0.; // there is no Newton iteration and the residuum is assumed to vanish
}
void D1MinusLinear::computeFreeState()
{
for (DSIterator it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it)
{
// Lagrangian Systems
SP::LagrangianDS d = boost::static_pointer_cast<LagrangianDS> (*it);
// get left state from memory
SP::SiconosVector vold = d->velocityMemory()->getSiconosVector(0); // right limit
// get right information
SP::SiconosMatrix M = d->mass();
SP::SiconosVector vfree = d->velocity(); // POINTER CONSTRUCTOR : contains free velocity
(*vfree) = *(d->residuFree());
M->PLUForwardBackwardInPlace(*vfree);
*vfree *= -1.;
*vfree += *vold;
}
}
void D1MinusLinear::computeFreeOutput(SP::UnitaryRelation UR, OneStepNSProblem* osnsp)
{
SP::OneStepNSProblems allOSNS = simulationLink->oneStepNSProblems(); // all OSNSP
// get relation and non smooth law information
RELATION::TYPES relationType = UR->getRelationType(); // relation
RELATION::SUBTYPES relationSubType = UR->getRelationSubType();
unsigned int relativePosition = UR->getRelativePosition();
unsigned int sizeY = UR->getNonSmoothLawSize(); // related NSL
Index coord(8);
coord[0] = relativePosition;
coord[1] = relativePosition + sizeY;
coord[2] = 0;
coord[3] = 0;
coord[4] = 0;
coord[5] = 0;
coord[6] = 0;
coord[7] = sizeY;
SP::SiconosMatrix C; // Jacobian of Relation with respect to degree of freedom
SP::SiconosVector Xfree; // free degree of freedom
SP::SiconosVector Yp = UR->yp(); // POINTER CONSTRUCTOR : contains output
// define Xfree for velocity and acceleration level
if (((*allOSNS)[SICONOS_OSNSP_TS_VELOCITY]).get() == osnsp)
{
Xfree = UR->workx();
}
else if (((*allOSNS)[SICONOS_OSNSP_TS_VELOCITY + 1]).get() == osnsp)
{
Xfree = UR->workFree();
}
else
RuntimeException::selfThrow("D1MinusLinear::computeFreeOutput - OSNSP neither on velocity nor on acceleration level.");
// calculate data of interaction
SP::Interaction mainInteraction = UR->interaction();
assert(mainInteraction);
assert(mainInteraction->relation());
// only Lagrangian Systems
if (relationType == Lagrangian)
{
// in Yp the linear part of velocity or acceleration relation will be saved
C = mainInteraction->relation()->C();
if (C)
{
assert(Xfree);
assert(Yp);
coord[3] = C->size(1);
coord[5] = C->size(1);
subprod(*C, *Xfree, *Yp, coord, true);
}
// in Yp corrections have to be added
SP::SiconosMatrix ID(new SimpleMatrix(sizeY, sizeY));
ID->eye();
Index xcoord(8);
xcoord[0] = 0;
xcoord[1] = sizeY;
xcoord[2] = 0;
xcoord[3] = sizeY;
xcoord[4] = 0;
xcoord[5] = sizeY;
xcoord[6] = 0;
xcoord[7] = sizeY;
if (relationSubType == RheonomousR) // explicit time dependence -> partial time derivative has to be added
{
if (((*allOSNS)[SICONOS_OSNSP_TS_VELOCITY]).get() == osnsp)
{
boost::static_pointer_cast<LagrangianRheonomousR>(UR->interaction()->relation())->computehDot(simulation()->getTkp1());
subprod(*ID, *(boost::static_pointer_cast<LagrangianRheonomousR>(UR->interaction()->relation())->hDot()), *Yp, xcoord, false);
}
else
RuntimeException::selfThrow("D1MinusLinear::computeFreeOutput is only implemented at velocity level for LagrangianRheonomousR.");
}
if (relationSubType == ScleronomousR) // acceleration term involving Hesse matrix of Relation with respect to degree is added
{
if (((*allOSNS)[SICONOS_OSNSP_TS_VELOCITY + 1]).get() == osnsp)
{
boost::static_pointer_cast<LagrangianScleronomousR>(UR->interaction()->relation())->computeNonLinearH2dot(simulation()->getTkp1());
subprod(*ID, *(boost::static_pointer_cast<LagrangianScleronomousR>(UR->interaction()->relation())->Nonlinearh2dot()), *Yp, xcoord, false);
}
}
if (((*allOSNS)[SICONOS_OSNSP_TS_VELOCITY]).get() == osnsp) // impact terms are added
{
SP::SiconosVisitor nslEffectOnFreeOutput(new _NSLEffectOnFreeOutput(osnsp, UR));
UR->interaction()->nonSmoothLaw()->accept(*nslEffectOnFreeOutput);
}
}
else
RuntimeException::selfThrow("D1MinusLinear::computeFreeOutput - not implemented for Relation of type " + relationType);
}
void D1MinusLinear::updateState(unsigned int level)
{
for (DSIterator it = OSIDynamicalSystems->begin(); it != OSIDynamicalSystems->end(); ++it)
{
// Lagrangian Systems
SP::LagrangianDS d = boost::static_pointer_cast<LagrangianDS> (*it);
SP::SiconosMatrix M = d->mass();
SP::SiconosVector v = d->velocity(); // POINTER CONSTRUCTOR : contains new velocity
if (d->p(1))
{
SP::SiconosVector dummy(new SimpleVector(*(d->p(1)))); // value = nonsmooth impulse
M->PLUForwardBackwardInPlace(*dummy); // solution for its velocity equivalent
*v += *dummy; // add free velocity
DEBUG_PRINT("\nRIGHT IMPULSE\n");
DEBUG_PRINTF("%f\n", (*(d->p(1)))(0));
//DEBUG_EXPR(throw(1));
}
}
}
void D1MinusLinear::insertDynamicalSystem(SP::DynamicalSystem ds)
{
OSIDynamicalSystems->insert(ds);
}
D1MinusLinear* D1MinusLinear::convert(OneStepIntegrator* osi)
{
return dynamic_cast<D1MinusLinear*>(osi);
}
|
// Copyright 2009 the V8 project authors. 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 Google Inc. 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
// 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 "v8.h"
#include "accessors.h"
#include "api.h"
#include "bootstrapper.h"
#include "codegen-inl.h"
#include "compilation-cache.h"
#include "debug.h"
#include "heap-profiler.h"
#include "global-handles.h"
#include "mark-compact.h"
#include "natives.h"
#include "scanner.h"
#include "scopeinfo.h"
#include "v8threads.h"
#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
#include "regexp-macro-assembler.h"
#endif
namespace v8 {
namespace internal {
String* Heap::hidden_symbol_;
Object* Heap::roots_[Heap::kRootListLength];
NewSpace Heap::new_space_;
OldSpace* Heap::old_pointer_space_ = NULL;
OldSpace* Heap::old_data_space_ = NULL;
OldSpace* Heap::code_space_ = NULL;
MapSpace* Heap::map_space_ = NULL;
CellSpace* Heap::cell_space_ = NULL;
LargeObjectSpace* Heap::lo_space_ = NULL;
static const int kMinimumPromotionLimit = 2*MB;
static const int kMinimumAllocationLimit = 8*MB;
int Heap::old_gen_promotion_limit_ = kMinimumPromotionLimit;
int Heap::old_gen_allocation_limit_ = kMinimumAllocationLimit;
int Heap::old_gen_exhausted_ = false;
int Heap::amount_of_external_allocated_memory_ = 0;
int Heap::amount_of_external_allocated_memory_at_last_global_gc_ = 0;
// semispace_size_ should be a power of 2 and old_generation_size_ should be
// a multiple of Page::kPageSize.
#if defined(ANDROID)
int Heap::semispace_size_ = 512*KB;
int Heap::old_generation_size_ = 128*MB;
int Heap::initial_semispace_size_ = 128*KB;
size_t Heap::code_range_size_ = 0;
#elif defined(V8_TARGET_ARCH_X64)
int Heap::semispace_size_ = 16*MB;
int Heap::old_generation_size_ = 1*GB;
int Heap::initial_semispace_size_ = 1*MB;
size_t Heap::code_range_size_ = 256*MB;
#else
int Heap::semispace_size_ = 8*MB;
int Heap::old_generation_size_ = 512*MB;
int Heap::initial_semispace_size_ = 512*KB;
size_t Heap::code_range_size_ = 0;
#endif
GCCallback Heap::global_gc_prologue_callback_ = NULL;
GCCallback Heap::global_gc_epilogue_callback_ = NULL;
// Variables set based on semispace_size_ and old_generation_size_ in
// ConfigureHeap.
int Heap::young_generation_size_ = 0; // Will be 2 * semispace_size_.
int Heap::survived_since_last_expansion_ = 0;
int Heap::external_allocation_limit_ = 0;
Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
int Heap::mc_count_ = 0;
int Heap::gc_count_ = 0;
int Heap::always_allocate_scope_depth_ = 0;
bool Heap::context_disposed_pending_ = false;
#ifdef DEBUG
bool Heap::allocation_allowed_ = true;
int Heap::allocation_timeout_ = 0;
bool Heap::disallow_allocation_failure_ = false;
#endif // DEBUG
int Heap::Capacity() {
if (!HasBeenSetup()) return 0;
return new_space_.Capacity() +
old_pointer_space_->Capacity() +
old_data_space_->Capacity() +
code_space_->Capacity() +
map_space_->Capacity() +
cell_space_->Capacity();
}
int Heap::Available() {
if (!HasBeenSetup()) return 0;
return new_space_.Available() +
old_pointer_space_->Available() +
old_data_space_->Available() +
code_space_->Available() +
map_space_->Available() +
cell_space_->Available();
}
bool Heap::HasBeenSetup() {
return old_pointer_space_ != NULL &&
old_data_space_ != NULL &&
code_space_ != NULL &&
map_space_ != NULL &&
cell_space_ != NULL &&
lo_space_ != NULL;
}
GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
// Is global GC requested?
if (space != NEW_SPACE || FLAG_gc_global) {
Counters::gc_compactor_caused_by_request.Increment();
return MARK_COMPACTOR;
}
// Is enough data promoted to justify a global GC?
if (OldGenerationPromotionLimitReached()) {
Counters::gc_compactor_caused_by_promoted_data.Increment();
return MARK_COMPACTOR;
}
// Have allocation in OLD and LO failed?
if (old_gen_exhausted_) {
Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
return MARK_COMPACTOR;
}
// Is there enough space left in OLD to guarantee that a scavenge can
// succeed?
//
// Note that MemoryAllocator->MaxAvailable() undercounts the memory available
// for object promotion. It counts only the bytes that the memory
// allocator has not yet allocated from the OS and assigned to any space,
// and does not count available bytes already in the old space or code
// space. Undercounting is safe---we may get an unrequested full GC when
// a scavenge would have succeeded.
if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
return MARK_COMPACTOR;
}
// Default
return SCAVENGER;
}
// TODO(1238405): Combine the infrastructure for --heap-stats and
// --log-gc to avoid the complicated preprocessor and flag testing.
#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
void Heap::ReportStatisticsBeforeGC() {
// Heap::ReportHeapStatistics will also log NewSpace statistics when
// compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
// following logic is used to avoid double logging.
#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
if (FLAG_heap_stats) {
ReportHeapStatistics("Before GC");
} else if (FLAG_log_gc) {
new_space_.ReportStatistics();
}
if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
#elif defined(DEBUG)
if (FLAG_heap_stats) {
new_space_.CollectStatistics();
ReportHeapStatistics("Before GC");
new_space_.ClearHistograms();
}
#elif defined(ENABLE_LOGGING_AND_PROFILING)
if (FLAG_log_gc) {
new_space_.CollectStatistics();
new_space_.ReportStatistics();
new_space_.ClearHistograms();
}
#endif
}
#if defined(ENABLE_LOGGING_AND_PROFILING)
void Heap::PrintShortHeapStatistics() {
if (!FLAG_trace_gc_verbose) return;
PrintF("Memory allocator, used: %8d, available: %8d\n",
MemoryAllocator::Size(), MemoryAllocator::Available());
PrintF("New space, used: %8d, available: %8d\n",
Heap::new_space_.Size(), new_space_.Available());
PrintF("Old pointers, used: %8d, available: %8d\n",
old_pointer_space_->Size(), old_pointer_space_->Available());
PrintF("Old data space, used: %8d, available: %8d\n",
old_data_space_->Size(), old_data_space_->Available());
PrintF("Code space, used: %8d, available: %8d\n",
code_space_->Size(), code_space_->Available());
PrintF("Map space, used: %8d, available: %8d\n",
map_space_->Size(), map_space_->Available());
PrintF("Large object space, used: %8d, avaialble: %8d\n",
lo_space_->Size(), lo_space_->Available());
}
#endif
// TODO(1238405): Combine the infrastructure for --heap-stats and
// --log-gc to avoid the complicated preprocessor and flag testing.
void Heap::ReportStatisticsAfterGC() {
// Similar to the before GC, we use some complicated logic to ensure that
// NewSpace statistics are logged exactly once when --log-gc is turned on.
#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
if (FLAG_heap_stats) {
new_space_.CollectStatistics();
ReportHeapStatistics("After GC");
} else if (FLAG_log_gc) {
new_space_.ReportStatistics();
}
#elif defined(DEBUG)
if (FLAG_heap_stats) ReportHeapStatistics("After GC");
#elif defined(ENABLE_LOGGING_AND_PROFILING)
if (FLAG_log_gc) new_space_.ReportStatistics();
#endif
}
#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
void Heap::GarbageCollectionPrologue() {
TranscendentalCache::Clear();
gc_count_++;
#ifdef DEBUG
ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
allow_allocation(false);
if (FLAG_verify_heap) {
Verify();
}
if (FLAG_gc_verbose) Print();
if (FLAG_print_rset) {
// Not all spaces have remembered set bits that we care about.
old_pointer_space_->PrintRSet();
map_space_->PrintRSet();
lo_space_->PrintRSet();
}
#endif
#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
ReportStatisticsBeforeGC();
#endif
}
int Heap::SizeOfObjects() {
int total = 0;
AllSpaces spaces;
while (Space* space = spaces.next()) {
total += space->Size();
}
return total;
}
void Heap::GarbageCollectionEpilogue() {
#ifdef DEBUG
allow_allocation(true);
ZapFromSpace();
if (FLAG_verify_heap) {
Verify();
}
if (FLAG_print_global_handles) GlobalHandles::Print();
if (FLAG_print_handles) PrintHandles();
if (FLAG_gc_verbose) Print();
if (FLAG_code_stats) ReportCodeStatistics("After GC");
#endif
Counters::alive_after_last_gc.Set(SizeOfObjects());
Counters::symbol_table_capacity.Set(symbol_table()->Capacity());
Counters::number_of_symbols.Set(symbol_table()->NumberOfElements());
#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
ReportStatisticsAfterGC();
#endif
#ifdef ENABLE_DEBUGGER_SUPPORT
Debug::AfterGarbageCollection();
#endif
}
void Heap::CollectAllGarbage(bool force_compaction) {
// Since we are ignoring the return value, the exact choice of space does
// not matter, so long as we do not specify NEW_SPACE, which would not
// cause a full GC.
MarkCompactCollector::SetForceCompaction(force_compaction);
CollectGarbage(0, OLD_POINTER_SPACE);
MarkCompactCollector::SetForceCompaction(false);
}
void Heap::CollectAllGarbageIfContextDisposed() {
// If the garbage collector interface is exposed through the global
// gc() function, we avoid being clever about forcing GCs when
// contexts are disposed and leave it to the embedder to make
// informed decisions about when to force a collection.
if (!FLAG_expose_gc && context_disposed_pending_) {
HistogramTimerScope scope(&Counters::gc_context);
CollectAllGarbage(false);
}
context_disposed_pending_ = false;
}
void Heap::NotifyContextDisposed() {
context_disposed_pending_ = true;
}
bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
// The VM is in the GC state until exiting this function.
VMState state(GC);
#ifdef DEBUG
// Reset the allocation timeout to the GC interval, but make sure to
// allow at least a few allocations after a collection. The reason
// for this is that we have a lot of allocation sequences and we
// assume that a garbage collection will allow the subsequent
// allocation attempts to go through.
allocation_timeout_ = Max(6, FLAG_gc_interval);
#endif
{ GCTracer tracer;
GarbageCollectionPrologue();
// The GC count was incremented in the prologue. Tell the tracer about
// it.
tracer.set_gc_count(gc_count_);
GarbageCollector collector = SelectGarbageCollector(space);
// Tell the tracer which collector we've selected.
tracer.set_collector(collector);
HistogramTimer* rate = (collector == SCAVENGER)
? &Counters::gc_scavenger
: &Counters::gc_compactor;
rate->Start();
PerformGarbageCollection(space, collector, &tracer);
rate->Stop();
GarbageCollectionEpilogue();
}
#ifdef ENABLE_LOGGING_AND_PROFILING
if (FLAG_log_gc) HeapProfiler::WriteSample();
#endif
switch (space) {
case NEW_SPACE:
return new_space_.Available() >= requested_size;
case OLD_POINTER_SPACE:
return old_pointer_space_->Available() >= requested_size;
case OLD_DATA_SPACE:
return old_data_space_->Available() >= requested_size;
case CODE_SPACE:
return code_space_->Available() >= requested_size;
case MAP_SPACE:
return map_space_->Available() >= requested_size;
case CELL_SPACE:
return cell_space_->Available() >= requested_size;
case LO_SPACE:
return lo_space_->Available() >= requested_size;
}
return false;
}
void Heap::PerformScavenge() {
GCTracer tracer;
PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
}
#ifdef DEBUG
// Helper class for verifying the symbol table.
class SymbolTableVerifier : public ObjectVisitor {
public:
SymbolTableVerifier() { }
void VisitPointers(Object** start, Object** end) {
// Visit all HeapObject pointers in [start, end).
for (Object** p = start; p < end; p++) {
if ((*p)->IsHeapObject()) {
// Check that the symbol is actually a symbol.
ASSERT((*p)->IsNull() || (*p)->IsUndefined() || (*p)->IsSymbol());
}
}
}
};
#endif // DEBUG
static void VerifySymbolTable() {
#ifdef DEBUG
SymbolTableVerifier verifier;
Heap::symbol_table()->IterateElements(&verifier);
#endif // DEBUG
}
void Heap::EnsureFromSpaceIsCommitted() {
if (new_space_.CommitFromSpaceIfNeeded()) return;
// Committing memory to from space failed.
// Try shrinking and try again.
Shrink();
if (new_space_.CommitFromSpaceIfNeeded()) return;
// Committing memory to from space failed again.
// Memory is exhausted and we will die.
V8::FatalProcessOutOfMemory("Committing semi space failed.");
}
void Heap::PerformGarbageCollection(AllocationSpace space,
GarbageCollector collector,
GCTracer* tracer) {
VerifySymbolTable();
if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
ASSERT(!allocation_allowed_);
global_gc_prologue_callback_();
}
EnsureFromSpaceIsCommitted();
if (collector == MARK_COMPACTOR) {
MarkCompact(tracer);
int old_gen_size = PromotedSpaceSize();
old_gen_promotion_limit_ =
old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
old_gen_allocation_limit_ =
old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 2);
old_gen_exhausted_ = false;
}
Scavenge();
Counters::objs_since_last_young.Set(0);
PostGarbageCollectionProcessing();
if (collector == MARK_COMPACTOR) {
// Register the amount of external allocated memory.
amount_of_external_allocated_memory_at_last_global_gc_ =
amount_of_external_allocated_memory_;
}
if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
ASSERT(!allocation_allowed_);
global_gc_epilogue_callback_();
}
VerifySymbolTable();
}
void Heap::PostGarbageCollectionProcessing() {
// Process weak handles post gc.
{
DisableAssertNoAllocation allow_allocation;
GlobalHandles::PostGarbageCollectionProcessing();
}
// Update relocatables.
Relocatable::PostGarbageCollectionProcessing();
}
void Heap::MarkCompact(GCTracer* tracer) {
gc_state_ = MARK_COMPACT;
mc_count_++;
tracer->set_full_gc_count(mc_count_);
LOG(ResourceEvent("markcompact", "begin"));
MarkCompactCollector::Prepare(tracer);
bool is_compacting = MarkCompactCollector::IsCompacting();
MarkCompactPrologue(is_compacting);
MarkCompactCollector::CollectGarbage();
MarkCompactEpilogue(is_compacting);
LOG(ResourceEvent("markcompact", "end"));
gc_state_ = NOT_IN_GC;
Shrink();
Counters::objs_since_last_full.Set(0);
context_disposed_pending_ = false;
}
void Heap::MarkCompactPrologue(bool is_compacting) {
// At any old GC clear the keyed lookup cache to enable collection of unused
// maps.
KeyedLookupCache::Clear();
ContextSlotCache::Clear();
DescriptorLookupCache::Clear();
CompilationCache::MarkCompactPrologue();
Top::MarkCompactPrologue(is_compacting);
ThreadManager::MarkCompactPrologue(is_compacting);
}
void Heap::MarkCompactEpilogue(bool is_compacting) {
Top::MarkCompactEpilogue(is_compacting);
ThreadManager::MarkCompactEpilogue(is_compacting);
}
Object* Heap::FindCodeObject(Address a) {
Object* obj = code_space_->FindObject(a);
if (obj->IsFailure()) {
obj = lo_space_->FindObject(a);
}
ASSERT(!obj->IsFailure());
return obj;
}
// Helper class for copying HeapObjects
class ScavengeVisitor: public ObjectVisitor {
public:
void VisitPointer(Object** p) { ScavengePointer(p); }
void VisitPointers(Object** start, Object** end) {
// Copy all HeapObject pointers in [start, end)
for (Object** p = start; p < end; p++) ScavengePointer(p);
}
private:
void ScavengePointer(Object** p) {
Object* object = *p;
if (!Heap::InNewSpace(object)) return;
Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
reinterpret_cast<HeapObject*>(object));
}
};
// A queue of pointers and maps of to-be-promoted objects during a
// scavenge collection.
class PromotionQueue {
public:
void Initialize(Address start_address) {
front_ = rear_ = reinterpret_cast<HeapObject**>(start_address);
}
bool is_empty() { return front_ <= rear_; }
void insert(HeapObject* object, Map* map) {
*(--rear_) = object;
*(--rear_) = map;
// Assert no overflow into live objects.
ASSERT(reinterpret_cast<Address>(rear_) >= Heap::new_space()->top());
}
void remove(HeapObject** object, Map** map) {
*object = *(--front_);
*map = Map::cast(*(--front_));
// Assert no underflow.
ASSERT(front_ >= rear_);
}
private:
// The front of the queue is higher in memory than the rear.
HeapObject** front_;
HeapObject** rear_;
};
// Shared state read by the scavenge collector and set by ScavengeObject.
static PromotionQueue promotion_queue;
#ifdef DEBUG
// Visitor class to verify pointers in code or data space do not point into
// new space.
class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
public:
void VisitPointers(Object** start, Object**end) {
for (Object** current = start; current < end; current++) {
if ((*current)->IsHeapObject()) {
ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
}
}
}
};
static void VerifyNonPointerSpacePointers() {
// Verify that there are no pointers to new space in spaces where we
// do not expect them.
VerifyNonPointerSpacePointersVisitor v;
HeapObjectIterator code_it(Heap::code_space());
while (code_it.has_next()) {
HeapObject* object = code_it.next();
object->Iterate(&v);
}
HeapObjectIterator data_it(Heap::old_data_space());
while (data_it.has_next()) data_it.next()->Iterate(&v);
}
#endif
void Heap::Scavenge() {
#ifdef DEBUG
if (FLAG_enable_slow_asserts) VerifyNonPointerSpacePointers();
#endif
gc_state_ = SCAVENGE;
// Implements Cheney's copying algorithm
LOG(ResourceEvent("scavenge", "begin"));
// Clear descriptor cache.
DescriptorLookupCache::Clear();
// Used for updating survived_since_last_expansion_ at function end.
int survived_watermark = PromotedSpaceSize();
if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
survived_since_last_expansion_ > new_space_.Capacity()) {
// Grow the size of new space if there is room to grow and enough
// data has survived scavenge since the last expansion.
new_space_.Grow();
survived_since_last_expansion_ = 0;
}
// Flip the semispaces. After flipping, to space is empty, from space has
// live objects.
new_space_.Flip();
new_space_.ResetAllocationInfo();
// We need to sweep newly copied objects which can be either in the
// to space or promoted to the old generation. For to-space
// objects, we treat the bottom of the to space as a queue. Newly
// copied and unswept objects lie between a 'front' mark and the
// allocation pointer.
//
// Promoted objects can go into various old-generation spaces, and
// can be allocated internally in the spaces (from the free list).
// We treat the top of the to space as a queue of addresses of
// promoted objects. The addresses of newly promoted and unswept
// objects lie between a 'front' mark and a 'rear' mark that is
// updated as a side effect of promoting an object.
//
// There is guaranteed to be enough room at the top of the to space
// for the addresses of promoted objects: every object promoted
// frees up its size in bytes from the top of the new space, and
// objects are at least one pointer in size.
Address new_space_front = new_space_.ToSpaceLow();
promotion_queue.Initialize(new_space_.ToSpaceHigh());
ScavengeVisitor scavenge_visitor;
// Copy roots.
IterateRoots(&scavenge_visitor);
// Copy objects reachable from weak pointers.
GlobalHandles::IterateWeakRoots(&scavenge_visitor);
// Copy objects reachable from the old generation. By definition,
// there are no intergenerational pointers in code or data spaces.
IterateRSet(old_pointer_space_, &ScavengePointer);
IterateRSet(map_space_, &ScavengePointer);
lo_space_->IterateRSet(&ScavengePointer);
// Copy objects reachable from cells by scavenging cell values directly.
HeapObjectIterator cell_iterator(cell_space_);
while (cell_iterator.has_next()) {
HeapObject* cell = cell_iterator.next();
if (cell->IsJSGlobalPropertyCell()) {
Address value_address =
reinterpret_cast<Address>(cell) +
(JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
}
}
do {
ASSERT(new_space_front <= new_space_.top());
// The addresses new_space_front and new_space_.top() define a
// queue of unprocessed copied objects. Process them until the
// queue is empty.
while (new_space_front < new_space_.top()) {
HeapObject* object = HeapObject::FromAddress(new_space_front);
object->Iterate(&scavenge_visitor);
new_space_front += object->Size();
}
// Promote and process all the to-be-promoted objects.
while (!promotion_queue.is_empty()) {
HeapObject* source;
Map* map;
promotion_queue.remove(&source, &map);
// Copy the from-space object to its new location (given by the
// forwarding address) and fix its map.
HeapObject* target = source->map_word().ToForwardingAddress();
CopyBlock(reinterpret_cast<Object**>(target->address()),
reinterpret_cast<Object**>(source->address()),
source->SizeFromMap(map));
target->set_map(map);
#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
// Update NewSpace stats if necessary.
RecordCopiedObject(target);
#endif
// Visit the newly copied object for pointers to new space.
target->Iterate(&scavenge_visitor);
UpdateRSet(target);
}
// Take another spin if there are now unswept objects in new space
// (there are currently no more unswept promoted objects).
} while (new_space_front < new_space_.top());
// Set age mark.
new_space_.set_age_mark(new_space_.top());
// Update how much has survived scavenge.
survived_since_last_expansion_ +=
(PromotedSpaceSize() - survived_watermark) + new_space_.Size();
LOG(ResourceEvent("scavenge", "end"));
gc_state_ = NOT_IN_GC;
}
void Heap::ClearRSetRange(Address start, int size_in_bytes) {
uint32_t start_bit;
Address start_word_address =
Page::ComputeRSetBitPosition(start, 0, &start_bit);
uint32_t end_bit;
Address end_word_address =
Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
0,
&end_bit);
// We want to clear the bits in the starting word starting with the
// first bit, and in the ending word up to and including the last
// bit. Build a pair of bitmasks to do that.
uint32_t start_bitmask = start_bit - 1;
uint32_t end_bitmask = ~((end_bit << 1) - 1);
// If the start address and end address are the same, we mask that
// word once, otherwise mask the starting and ending word
// separately and all the ones in between.
if (start_word_address == end_word_address) {
Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
} else {
Memory::uint32_at(start_word_address) &= start_bitmask;
Memory::uint32_at(end_word_address) &= end_bitmask;
start_word_address += kIntSize;
memset(start_word_address, 0, end_word_address - start_word_address);
}
}
class UpdateRSetVisitor: public ObjectVisitor {
public:
void VisitPointer(Object** p) {
UpdateRSet(p);
}
void VisitPointers(Object** start, Object** end) {
// Update a store into slots [start, end), used (a) to update remembered
// set when promoting a young object to old space or (b) to rebuild
// remembered sets after a mark-compact collection.
for (Object** p = start; p < end; p++) UpdateRSet(p);
}
private:
void UpdateRSet(Object** p) {
// The remembered set should not be set. It should be clear for objects
// newly copied to old space, and it is cleared before rebuilding in the
// mark-compact collector.
ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
if (Heap::InNewSpace(*p)) {
Page::SetRSet(reinterpret_cast<Address>(p), 0);
}
}
};
int Heap::UpdateRSet(HeapObject* obj) {
ASSERT(!InNewSpace(obj));
// Special handling of fixed arrays to iterate the body based on the start
// address and offset. Just iterating the pointers as in UpdateRSetVisitor
// will not work because Page::SetRSet needs to have the start of the
// object for large object pages.
if (obj->IsFixedArray()) {
FixedArray* array = FixedArray::cast(obj);
int length = array->length();
for (int i = 0; i < length; i++) {
int offset = FixedArray::kHeaderSize + i * kPointerSize;
ASSERT(!Page::IsRSetSet(obj->address(), offset));
if (Heap::InNewSpace(array->get(i))) {
Page::SetRSet(obj->address(), offset);
}
}
} else if (!obj->IsCode()) {
// Skip code object, we know it does not contain inter-generational
// pointers.
UpdateRSetVisitor v;
obj->Iterate(&v);
}
return obj->Size();
}
void Heap::RebuildRSets() {
// By definition, we do not care about remembered set bits in code,
// data, or cell spaces.
map_space_->ClearRSet();
RebuildRSets(map_space_);
old_pointer_space_->ClearRSet();
RebuildRSets(old_pointer_space_);
Heap::lo_space_->ClearRSet();
RebuildRSets(lo_space_);
}
void Heap::RebuildRSets(PagedSpace* space) {
HeapObjectIterator it(space);
while (it.has_next()) Heap::UpdateRSet(it.next());
}
void Heap::RebuildRSets(LargeObjectSpace* space) {
LargeObjectIterator it(space);
while (it.has_next()) Heap::UpdateRSet(it.next());
}
#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
void Heap::RecordCopiedObject(HeapObject* obj) {
bool should_record = false;
#ifdef DEBUG
should_record = FLAG_heap_stats;
#endif
#ifdef ENABLE_LOGGING_AND_PROFILING
should_record = should_record || FLAG_log_gc;
#endif
if (should_record) {
if (new_space_.Contains(obj)) {
new_space_.RecordAllocation(obj);
} else {
new_space_.RecordPromotion(obj);
}
}
}
#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
HeapObject* Heap::MigrateObject(HeapObject* source,
HeapObject* target,
int size) {
// Copy the content of source to target.
CopyBlock(reinterpret_cast<Object**>(target->address()),
reinterpret_cast<Object**>(source->address()),
size);
// Set the forwarding address.
source->set_map_word(MapWord::FromForwardingAddress(target));
#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
// Update NewSpace stats if necessary.
RecordCopiedObject(target);
#endif
return target;
}
static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
STATIC_ASSERT(kNotStringTag != 0 && kSymbolTag != 0);
ASSERT(object->map() == map);
InstanceType type = map->instance_type();
if ((type & kShortcutTypeMask) != kShortcutTypeTag) return false;
ASSERT(object->IsString() && !object->IsSymbol());
return ConsString::cast(object)->unchecked_second() == Heap::empty_string();
}
void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
ASSERT(InFromSpace(object));
MapWord first_word = object->map_word();
ASSERT(!first_word.IsForwardingAddress());
// Optimization: Bypass flattened ConsString objects.
if (IsShortcutCandidate(object, first_word.ToMap())) {
object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
*p = object;
// After patching *p we have to repeat the checks that object is in the
// active semispace of the young generation and not already copied.
if (!InNewSpace(object)) return;
first_word = object->map_word();
if (first_word.IsForwardingAddress()) {
*p = first_word.ToForwardingAddress();
return;
}
}
int object_size = object->SizeFromMap(first_word.ToMap());
// We rely on live objects in new space to be at least two pointers,
// so we can store the from-space address and map pointer of promoted
// objects in the to space.
ASSERT(object_size >= 2 * kPointerSize);
// If the object should be promoted, we try to copy it to old space.
if (ShouldBePromoted(object->address(), object_size)) {
Object* result;
if (object_size > MaxObjectSizeInPagedSpace()) {
result = lo_space_->AllocateRawFixedArray(object_size);
if (!result->IsFailure()) {
// Save the from-space object pointer and its map pointer at the
// top of the to space to be swept and copied later. Write the
// forwarding address over the map word of the from-space
// object.
HeapObject* target = HeapObject::cast(result);
promotion_queue.insert(object, first_word.ToMap());
object->set_map_word(MapWord::FromForwardingAddress(target));
// Give the space allocated for the result a proper map by
// treating it as a free list node (not linked into the free
// list).
FreeListNode* node = FreeListNode::FromAddress(target->address());
node->set_size(object_size);
*p = target;
return;
}
} else {
OldSpace* target_space = Heap::TargetSpace(object);
ASSERT(target_space == Heap::old_pointer_space_ ||
target_space == Heap::old_data_space_);
result = target_space->AllocateRaw(object_size);
if (!result->IsFailure()) {
HeapObject* target = HeapObject::cast(result);
if (target_space == Heap::old_pointer_space_) {
// Save the from-space object pointer and its map pointer at the
// top of the to space to be swept and copied later. Write the
// forwarding address over the map word of the from-space
// object.
promotion_queue.insert(object, first_word.ToMap());
object->set_map_word(MapWord::FromForwardingAddress(target));
// Give the space allocated for the result a proper map by
// treating it as a free list node (not linked into the free
// list).
FreeListNode* node = FreeListNode::FromAddress(target->address());
node->set_size(object_size);
*p = target;
} else {
// Objects promoted to the data space can be copied immediately
// and not revisited---we will never sweep that space for
// pointers and the copied objects do not contain pointers to
// new space objects.
*p = MigrateObject(object, target, object_size);
#ifdef DEBUG
VerifyNonPointerSpacePointersVisitor v;
(*p)->Iterate(&v);
#endif
}
return;
}
}
}
// The object should remain in new space or the old space allocation failed.
Object* result = new_space_.AllocateRaw(object_size);
// Failed allocation at this point is utterly unexpected.
ASSERT(!result->IsFailure());
*p = MigrateObject(object, HeapObject::cast(result), object_size);
}
void Heap::ScavengePointer(HeapObject** p) {
ScavengeObject(p, *p);
}
Object* Heap::AllocatePartialMap(InstanceType instance_type,
int instance_size) {
Object* result = AllocateRawMap();
if (result->IsFailure()) return result;
// Map::cast cannot be used due to uninitialized map field.
reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
reinterpret_cast<Map*>(result)->set_inobject_properties(0);
reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
return result;
}
Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
Object* result = AllocateRawMap();
if (result->IsFailure()) return result;
Map* map = reinterpret_cast<Map*>(result);
map->set_map(meta_map());
map->set_instance_type(instance_type);
map->set_prototype(null_value());
map->set_constructor(null_value());
map->set_instance_size(instance_size);
map->set_inobject_properties(0);
map->set_pre_allocated_property_fields(0);
map->set_instance_descriptors(empty_descriptor_array());
map->set_code_cache(empty_fixed_array());
map->set_unused_property_fields(0);
map->set_bit_field(0);
map->set_bit_field2(0);
return map;
}
const Heap::StringTypeTable Heap::string_type_table[] = {
#define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
{type, size, k##camel_name##MapRootIndex},
STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
#undef STRING_TYPE_ELEMENT
};
const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
#define CONSTANT_SYMBOL_ELEMENT(name, contents) \
{contents, k##name##RootIndex},
SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
#undef CONSTANT_SYMBOL_ELEMENT
};
const Heap::StructTable Heap::struct_table[] = {
#define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
{ NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
STRUCT_LIST(STRUCT_TABLE_ELEMENT)
#undef STRUCT_TABLE_ELEMENT
};
bool Heap::CreateInitialMaps() {
Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
if (obj->IsFailure()) return false;
// Map::cast cannot be used due to uninitialized map field.
Map* new_meta_map = reinterpret_cast<Map*>(obj);
set_meta_map(new_meta_map);
new_meta_map->set_map(new_meta_map);
obj = AllocatePartialMap(FIXED_ARRAY_TYPE, FixedArray::kHeaderSize);
if (obj->IsFailure()) return false;
set_fixed_array_map(Map::cast(obj));
obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
if (obj->IsFailure()) return false;
set_oddball_map(Map::cast(obj));
// Allocate the empty array
obj = AllocateEmptyFixedArray();
if (obj->IsFailure()) return false;
set_empty_fixed_array(FixedArray::cast(obj));
obj = Allocate(oddball_map(), OLD_DATA_SPACE);
if (obj->IsFailure()) return false;
set_null_value(obj);
// Allocate the empty descriptor array.
obj = AllocateEmptyFixedArray();
if (obj->IsFailure()) return false;
set_empty_descriptor_array(DescriptorArray::cast(obj));
// Fix the instance_descriptors for the existing maps.
meta_map()->set_instance_descriptors(empty_descriptor_array());
meta_map()->set_code_cache(empty_fixed_array());
fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
fixed_array_map()->set_code_cache(empty_fixed_array());
oddball_map()->set_instance_descriptors(empty_descriptor_array());
oddball_map()->set_code_cache(empty_fixed_array());
// Fix prototype object for existing maps.
meta_map()->set_prototype(null_value());
meta_map()->set_constructor(null_value());
fixed_array_map()->set_prototype(null_value());
fixed_array_map()->set_constructor(null_value());
oddball_map()->set_prototype(null_value());
oddball_map()->set_constructor(null_value());
obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
if (obj->IsFailure()) return false;
set_heap_number_map(Map::cast(obj));
obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
if (obj->IsFailure()) return false;
set_proxy_map(Map::cast(obj));
for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
const StringTypeTable& entry = string_type_table[i];
obj = AllocateMap(entry.type, entry.size);
if (obj->IsFailure()) return false;
roots_[entry.index] = Map::cast(obj);
}
obj = AllocateMap(SHORT_STRING_TYPE, SeqTwoByteString::kAlignedSize);
if (obj->IsFailure()) return false;
set_undetectable_short_string_map(Map::cast(obj));
Map::cast(obj)->set_is_undetectable();
obj = AllocateMap(MEDIUM_STRING_TYPE, SeqTwoByteString::kAlignedSize);
if (obj->IsFailure()) return false;
set_undetectable_medium_string_map(Map::cast(obj));
Map::cast(obj)->set_is_undetectable();
obj = AllocateMap(LONG_STRING_TYPE, SeqTwoByteString::kAlignedSize);
if (obj->IsFailure()) return false;
set_undetectable_long_string_map(Map::cast(obj));
Map::cast(obj)->set_is_undetectable();
obj = AllocateMap(SHORT_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
if (obj->IsFailure()) return false;
set_undetectable_short_ascii_string_map(Map::cast(obj));
Map::cast(obj)->set_is_undetectable();
obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
if (obj->IsFailure()) return false;
set_undetectable_medium_ascii_string_map(Map::cast(obj));
Map::cast(obj)->set_is_undetectable();
obj = AllocateMap(LONG_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
if (obj->IsFailure()) return false;
set_undetectable_long_ascii_string_map(Map::cast(obj));
Map::cast(obj)->set_is_undetectable();
obj = AllocateMap(BYTE_ARRAY_TYPE, ByteArray::kAlignedSize);
if (obj->IsFailure()) return false;
set_byte_array_map(Map::cast(obj));
obj = AllocateMap(PIXEL_ARRAY_TYPE, PixelArray::kAlignedSize);
if (obj->IsFailure()) return false;
set_pixel_array_map(Map::cast(obj));
obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
if (obj->IsFailure()) return false;
set_code_map(Map::cast(obj));
obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
JSGlobalPropertyCell::kSize);
if (obj->IsFailure()) return false;
set_global_property_cell_map(Map::cast(obj));
obj = AllocateMap(FILLER_TYPE, kPointerSize);
if (obj->IsFailure()) return false;
set_one_pointer_filler_map(Map::cast(obj));
obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
if (obj->IsFailure()) return false;
set_two_pointer_filler_map(Map::cast(obj));
for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
const StructTable& entry = struct_table[i];
obj = AllocateMap(entry.type, entry.size);
if (obj->IsFailure()) return false;
roots_[entry.index] = Map::cast(obj);
}
obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
if (obj->IsFailure()) return false;
set_hash_table_map(Map::cast(obj));
obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
if (obj->IsFailure()) return false;
set_context_map(Map::cast(obj));
obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
if (obj->IsFailure()) return false;
set_catch_context_map(Map::cast(obj));
obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
if (obj->IsFailure()) return false;
set_global_context_map(Map::cast(obj));
obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
if (obj->IsFailure()) return false;
set_boilerplate_function_map(Map::cast(obj));
obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
if (obj->IsFailure()) return false;
set_shared_function_info_map(Map::cast(obj));
ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
return true;
}
Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
// Statically ensure that it is safe to allocate heap numbers in paged
// spaces.
STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
// New space can't cope with forced allocation.
if (always_allocate()) space = OLD_DATA_SPACE;
Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
if (result->IsFailure()) return result;
HeapObject::cast(result)->set_map(heap_number_map());
HeapNumber::cast(result)->set_value(value);
return result;
}
Object* Heap::AllocateHeapNumber(double value) {
// Use general version, if we're forced to always allocate.
if (always_allocate()) return AllocateHeapNumber(value, TENURED);
// This version of AllocateHeapNumber is optimized for
// allocation in new space.
STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
if (result->IsFailure()) return result;
HeapObject::cast(result)->set_map(heap_number_map());
HeapNumber::cast(result)->set_value(value);
return result;
}
Object* Heap::AllocateJSGlobalPropertyCell(Object* value) {
Object* result = AllocateRawCell();
if (result->IsFailure()) return result;
HeapObject::cast(result)->set_map(global_property_cell_map());
JSGlobalPropertyCell::cast(result)->set_value(value);
return result;
}
Object* Heap::CreateOddball(Map* map,
const char* to_string,
Object* to_number) {
Object* result = Allocate(map, OLD_DATA_SPACE);
if (result->IsFailure()) return result;
return Oddball::cast(result)->Initialize(to_string, to_number);
}
bool Heap::CreateApiObjects() {
Object* obj;
obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
if (obj->IsFailure()) return false;
set_neander_map(Map::cast(obj));
obj = Heap::AllocateJSObjectFromMap(neander_map());
if (obj->IsFailure()) return false;
Object* elements = AllocateFixedArray(2);
if (elements->IsFailure()) return false;
FixedArray::cast(elements)->set(0, Smi::FromInt(0));
JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
set_message_listeners(JSObject::cast(obj));
return true;
}
void Heap::CreateCEntryStub() {
CEntryStub stub(1);
set_c_entry_code(*stub.GetCode());
}
#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
void Heap::CreateRegExpCEntryStub() {
RegExpCEntryStub stub;
set_re_c_entry_code(*stub.GetCode());
}
#endif
void Heap::CreateCEntryDebugBreakStub() {
CEntryDebugBreakStub stub;
set_c_entry_debug_break_code(*stub.GetCode());
}
void Heap::CreateJSEntryStub() {
JSEntryStub stub;
set_js_entry_code(*stub.GetCode());
}
void Heap::CreateJSConstructEntryStub() {
JSConstructEntryStub stub;
set_js_construct_entry_code(*stub.GetCode());
}
void Heap::CreateFixedStubs() {
// Here we create roots for fixed stubs. They are needed at GC
// for cooking and uncooking (check out frames.cc).
// The eliminates the need for doing dictionary lookup in the
// stub cache for these stubs.
HandleScope scope;
// gcc-4.4 has problem generating correct code of following snippet:
// { CEntryStub stub;
// c_entry_code_ = *stub.GetCode();
// }
// { CEntryDebugBreakStub stub;
// c_entry_debug_break_code_ = *stub.GetCode();
// }
// To workaround the problem, make separate functions without inlining.
Heap::CreateCEntryStub();
Heap::CreateCEntryDebugBreakStub();
Heap::CreateJSEntryStub();
Heap::CreateJSConstructEntryStub();
#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
Heap::CreateRegExpCEntryStub();
#endif
}
bool Heap::CreateInitialObjects() {
Object* obj;
// The -0 value must be set before NumberFromDouble works.
obj = AllocateHeapNumber(-0.0, TENURED);
if (obj->IsFailure()) return false;
set_minus_zero_value(obj);
ASSERT(signbit(minus_zero_value()->Number()) != 0);
obj = AllocateHeapNumber(OS::nan_value(), TENURED);
if (obj->IsFailure()) return false;
set_nan_value(obj);
obj = Allocate(oddball_map(), OLD_DATA_SPACE);
if (obj->IsFailure()) return false;
set_undefined_value(obj);
ASSERT(!InNewSpace(undefined_value()));
// Allocate initial symbol table.
obj = SymbolTable::Allocate(kInitialSymbolTableSize);
if (obj->IsFailure()) return false;
// Don't use set_symbol_table() due to asserts.
roots_[kSymbolTableRootIndex] = obj;
// Assign the print strings for oddballs after creating symboltable.
Object* symbol = LookupAsciiSymbol("undefined");
if (symbol->IsFailure()) return false;
Oddball::cast(undefined_value())->set_to_string(String::cast(symbol));
Oddball::cast(undefined_value())->set_to_number(nan_value());
// Assign the print strings for oddballs after creating symboltable.
symbol = LookupAsciiSymbol("null");
if (symbol->IsFailure()) return false;
Oddball::cast(null_value())->set_to_string(String::cast(symbol));
Oddball::cast(null_value())->set_to_number(Smi::FromInt(0));
// Allocate the null_value
obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
if (obj->IsFailure()) return false;
obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
if (obj->IsFailure()) return false;
set_true_value(obj);
obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
if (obj->IsFailure()) return false;
set_false_value(obj);
obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
if (obj->IsFailure()) return false;
set_the_hole_value(obj);
obj = CreateOddball(
oddball_map(), "no_interceptor_result_sentinel", Smi::FromInt(-2));
if (obj->IsFailure()) return false;
set_no_interceptor_result_sentinel(obj);
obj = CreateOddball(oddball_map(), "termination_exception", Smi::FromInt(-3));
if (obj->IsFailure()) return false;
set_termination_exception(obj);
// Allocate the empty string.
obj = AllocateRawAsciiString(0, TENURED);
if (obj->IsFailure()) return false;
set_empty_string(String::cast(obj));
for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
obj = LookupAsciiSymbol(constant_symbol_table[i].contents);
if (obj->IsFailure()) return false;
roots_[constant_symbol_table[i].index] = String::cast(obj);
}
// Allocate the hidden symbol which is used to identify the hidden properties
// in JSObjects. The hash code has a special value so that it will not match
// the empty string when searching for the property. It cannot be part of the
// loop above because it needs to be allocated manually with the special
// hash code in place. The hash code for the hidden_symbol is zero to ensure
// that it will always be at the first entry in property descriptors.
obj = AllocateSymbol(CStrVector(""), 0, String::kHashComputedMask);
if (obj->IsFailure()) return false;
hidden_symbol_ = String::cast(obj);
// Allocate the proxy for __proto__.
obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
if (obj->IsFailure()) return false;
set_prototype_accessors(Proxy::cast(obj));
// Allocate the code_stubs dictionary. The initial size is set to avoid
// expanding the dictionary during bootstrapping.
obj = NumberDictionary::Allocate(128);
if (obj->IsFailure()) return false;
set_code_stubs(NumberDictionary::cast(obj));
// Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
// is set to avoid expanding the dictionary during bootstrapping.
obj = NumberDictionary::Allocate(64);
if (obj->IsFailure()) return false;
set_non_monomorphic_cache(NumberDictionary::cast(obj));
CreateFixedStubs();
// Allocate the number->string conversion cache
obj = AllocateFixedArray(kNumberStringCacheSize * 2);
if (obj->IsFailure()) return false;
set_number_string_cache(FixedArray::cast(obj));
// Allocate cache for single character strings.
obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
if (obj->IsFailure()) return false;
set_single_character_string_cache(FixedArray::cast(obj));
// Allocate cache for external strings pointing to native source code.
obj = AllocateFixedArray(Natives::GetBuiltinsCount());
if (obj->IsFailure()) return false;
set_natives_source_cache(FixedArray::cast(obj));
// Handling of script id generation is in Factory::NewScript.
set_last_script_id(undefined_value());
// Initialize keyed lookup cache.
KeyedLookupCache::Clear();
// Initialize context slot cache.
ContextSlotCache::Clear();
// Initialize descriptor cache.
DescriptorLookupCache::Clear();
// Initialize compilation cache.
CompilationCache::Clear();
return true;
}
static inline int double_get_hash(double d) {
DoubleRepresentation rep(d);
return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
(Heap::kNumberStringCacheSize - 1));
}
static inline int smi_get_hash(Smi* smi) {
return (smi->value() & (Heap::kNumberStringCacheSize - 1));
}
Object* Heap::GetNumberStringCache(Object* number) {
int hash;
if (number->IsSmi()) {
hash = smi_get_hash(Smi::cast(number));
} else {
hash = double_get_hash(number->Number());
}
Object* key = number_string_cache()->get(hash * 2);
if (key == number) {
return String::cast(number_string_cache()->get(hash * 2 + 1));
} else if (key->IsHeapNumber() &&
number->IsHeapNumber() &&
key->Number() == number->Number()) {
return String::cast(number_string_cache()->get(hash * 2 + 1));
}
return undefined_value();
}
void Heap::SetNumberStringCache(Object* number, String* string) {
int hash;
if (number->IsSmi()) {
hash = smi_get_hash(Smi::cast(number));
number_string_cache()->set(hash * 2, number, SKIP_WRITE_BARRIER);
} else {
hash = double_get_hash(number->Number());
number_string_cache()->set(hash * 2, number);
}
number_string_cache()->set(hash * 2 + 1, string);
}
Object* Heap::SmiOrNumberFromDouble(double value,
bool new_object,
PretenureFlag pretenure) {
// We need to distinguish the minus zero value and this cannot be
// done after conversion to int. Doing this by comparing bit
// patterns is faster than using fpclassify() et al.
static const DoubleRepresentation plus_zero(0.0);
static const DoubleRepresentation minus_zero(-0.0);
static const DoubleRepresentation nan(OS::nan_value());
ASSERT(minus_zero_value() != NULL);
ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
DoubleRepresentation rep(value);
if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
if (rep.bits == minus_zero.bits) {
return new_object ? AllocateHeapNumber(-0.0, pretenure)
: minus_zero_value();
}
if (rep.bits == nan.bits) {
return new_object
? AllocateHeapNumber(OS::nan_value(), pretenure)
: nan_value();
}
// Try to represent the value as a tagged small integer.
int int_value = FastD2I(value);
if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
return Smi::FromInt(int_value);
}
// Materialize the value in the heap.
return AllocateHeapNumber(value, pretenure);
}
Object* Heap::NumberToString(Object* number) {
Object* cached = GetNumberStringCache(number);
if (cached != undefined_value()) {
return cached;
}
char arr[100];
Vector<char> buffer(arr, ARRAY_SIZE(arr));
const char* str;
if (number->IsSmi()) {
int num = Smi::cast(number)->value();
str = IntToCString(num, buffer);
} else {
double num = HeapNumber::cast(number)->value();
str = DoubleToCString(num, buffer);
}
Object* result = AllocateStringFromAscii(CStrVector(str));
if (!result->IsFailure()) {
SetNumberStringCache(number, String::cast(result));
}
return result;
}
Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
return SmiOrNumberFromDouble(value,
true /* number object must be new */,
pretenure);
}
Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
return SmiOrNumberFromDouble(value,
false /* use preallocated NaN, -0.0 */,
pretenure);
}
Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
// Statically ensure that it is safe to allocate proxies in paged spaces.
STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
Object* result = Allocate(proxy_map(), space);
if (result->IsFailure()) return result;
Proxy::cast(result)->set_proxy(proxy);
return result;
}
Object* Heap::AllocateSharedFunctionInfo(Object* name) {
Object* result = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
if (result->IsFailure()) return result;
SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
share->set_name(name);
Code* illegal = Builtins::builtin(Builtins::Illegal);
share->set_code(illegal);
Code* construct_stub = Builtins::builtin(Builtins::JSConstructStubGeneric);
share->set_construct_stub(construct_stub);
share->set_expected_nof_properties(0);
share->set_length(0);
share->set_formal_parameter_count(0);
share->set_instance_class_name(Object_symbol());
share->set_function_data(undefined_value());
share->set_script(undefined_value());
share->set_start_position_and_type(0);
share->set_debug_info(undefined_value());
share->set_inferred_name(empty_string());
share->set_compiler_hints(0);
share->set_this_property_assignments_count(0);
share->set_this_property_assignments(undefined_value());
return result;
}
Object* Heap::AllocateConsString(String* first, String* second) {
int first_length = first->length();
if (first_length == 0) return second;
int second_length = second->length();
if (second_length == 0) return first;
int length = first_length + second_length;
bool is_ascii = first->IsAsciiRepresentation()
&& second->IsAsciiRepresentation();
// Make sure that an out of memory exception is thrown if the length
// of the new cons string is too large to fit in a Smi.
if (length > Smi::kMaxValue || length < -0) {
Top::context()->mark_out_of_memory();
return Failure::OutOfMemoryException();
}
// If the resulting string is small make a flat string.
if (length < String::kMinNonFlatLength) {
ASSERT(first->IsFlat());
ASSERT(second->IsFlat());
if (is_ascii) {
Object* result = AllocateRawAsciiString(length);
if (result->IsFailure()) return result;
// Copy the characters into the new object.
char* dest = SeqAsciiString::cast(result)->GetChars();
// Copy first part.
char* src = SeqAsciiString::cast(first)->GetChars();
for (int i = 0; i < first_length; i++) *dest++ = src[i];
// Copy second part.
src = SeqAsciiString::cast(second)->GetChars();
for (int i = 0; i < second_length; i++) *dest++ = src[i];
return result;
} else {
Object* result = AllocateRawTwoByteString(length);
if (result->IsFailure()) return result;
// Copy the characters into the new object.
uc16* dest = SeqTwoByteString::cast(result)->GetChars();
String::WriteToFlat(first, dest, 0, first_length);
String::WriteToFlat(second, dest + first_length, 0, second_length);
return result;
}
}
Map* map;
if (length <= String::kMaxShortStringSize) {
map = is_ascii ? short_cons_ascii_string_map()
: short_cons_string_map();
} else if (length <= String::kMaxMediumStringSize) {
map = is_ascii ? medium_cons_ascii_string_map()
: medium_cons_string_map();
} else {
map = is_ascii ? long_cons_ascii_string_map()
: long_cons_string_map();
}
Object* result = Allocate(map, NEW_SPACE);
if (result->IsFailure()) return result;
ASSERT(InNewSpace(result));
ConsString* cons_string = ConsString::cast(result);
cons_string->set_first(first, SKIP_WRITE_BARRIER);
cons_string->set_second(second, SKIP_WRITE_BARRIER);
cons_string->set_length(length);
return result;
}
Object* Heap::AllocateSlicedString(String* buffer,
int start,
int end) {
int length = end - start;
// If the resulting string is small make a sub string.
if (length <= String::kMinNonFlatLength) {
return Heap::AllocateSubString(buffer, start, end);
}
Map* map;
if (length <= String::kMaxShortStringSize) {
map = buffer->IsAsciiRepresentation() ?
short_sliced_ascii_string_map() :
short_sliced_string_map();
} else if (length <= String::kMaxMediumStringSize) {
map = buffer->IsAsciiRepresentation() ?
medium_sliced_ascii_string_map() :
medium_sliced_string_map();
} else {
map = buffer->IsAsciiRepresentation() ?
long_sliced_ascii_string_map() :
long_sliced_string_map();
}
Object* result = Allocate(map, NEW_SPACE);
if (result->IsFailure()) return result;
SlicedString* sliced_string = SlicedString::cast(result);
sliced_string->set_buffer(buffer);
sliced_string->set_start(start);
sliced_string->set_length(length);
return result;
}
Object* Heap::AllocateSubString(String* buffer,
int start,
int end) {
int length = end - start;
if (length == 1) {
return Heap::LookupSingleCharacterStringFromCode(
buffer->Get(start));
}
// Make an attempt to flatten the buffer to reduce access time.
if (!buffer->IsFlat()) {
buffer->TryFlatten();
}
Object* result = buffer->IsAsciiRepresentation()
? AllocateRawAsciiString(length)
: AllocateRawTwoByteString(length);
if (result->IsFailure()) return result;
// Copy the characters into the new object.
String* string_result = String::cast(result);
StringHasher hasher(length);
int i = 0;
for (; i < length && hasher.is_array_index(); i++) {
uc32 c = buffer->Get(start + i);
hasher.AddCharacter(c);
string_result->Set(i, c);
}
for (; i < length; i++) {
uc32 c = buffer->Get(start + i);
hasher.AddCharacterNoIndex(c);
string_result->Set(i, c);
}
string_result->set_length_field(hasher.GetHashField());
return result;
}
Object* Heap::AllocateExternalStringFromAscii(
ExternalAsciiString::Resource* resource) {
Map* map;
int length = resource->length();
if (length <= String::kMaxShortStringSize) {
map = short_external_ascii_string_map();
} else if (length <= String::kMaxMediumStringSize) {
map = medium_external_ascii_string_map();
} else {
map = long_external_ascii_string_map();
}
Object* result = Allocate(map, NEW_SPACE);
if (result->IsFailure()) return result;
ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
external_string->set_length(length);
external_string->set_resource(resource);
return result;
}
Object* Heap::AllocateExternalStringFromTwoByte(
ExternalTwoByteString::Resource* resource) {
int length = resource->length();
Map* map = ExternalTwoByteString::StringMap(length);
Object* result = Allocate(map, NEW_SPACE);
if (result->IsFailure()) return result;
ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
external_string->set_length(length);
external_string->set_resource(resource);
return result;
}
Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
if (code <= String::kMaxAsciiCharCode) {
Object* value = Heap::single_character_string_cache()->get(code);
if (value != Heap::undefined_value()) return value;
char buffer[1];
buffer[0] = static_cast<char>(code);
Object* result = LookupSymbol(Vector<const char>(buffer, 1));
if (result->IsFailure()) return result;
Heap::single_character_string_cache()->set(code, result);
return result;
}
Object* result = Heap::AllocateRawTwoByteString(1);
if (result->IsFailure()) return result;
String* answer = String::cast(result);
answer->Set(0, code);
return answer;
}
Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
if (pretenure == NOT_TENURED) {
return AllocateByteArray(length);
}
int size = ByteArray::SizeFor(length);
AllocationSpace space =
size > MaxObjectSizeInPagedSpace() ? LO_SPACE : OLD_DATA_SPACE;
Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
if (result->IsFailure()) return result;
reinterpret_cast<Array*>(result)->set_map(byte_array_map());
reinterpret_cast<Array*>(result)->set_length(length);
return result;
}
Object* Heap::AllocateByteArray(int length) {
int size = ByteArray::SizeFor(length);
AllocationSpace space =
size > MaxObjectSizeInPagedSpace() ? LO_SPACE : NEW_SPACE;
// New space can't cope with forced allocation.
if (always_allocate()) space = LO_SPACE;
Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
if (result->IsFailure()) return result;
reinterpret_cast<Array*>(result)->set_map(byte_array_map());
reinterpret_cast<Array*>(result)->set_length(length);
return result;
}
void Heap::CreateFillerObjectAt(Address addr, int size) {
if (size == 0) return;
HeapObject* filler = HeapObject::FromAddress(addr);
if (size == kPointerSize) {
filler->set_map(Heap::one_pointer_filler_map());
} else {
filler->set_map(Heap::byte_array_map());
ByteArray::cast(filler)->set_length(ByteArray::LengthFor(size));
}
}
Object* Heap::AllocatePixelArray(int length,
uint8_t* external_pointer,
PretenureFlag pretenure) {
AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
// New space can't cope with forced allocation.
if (always_allocate()) space = OLD_DATA_SPACE;
Object* result = AllocateRaw(PixelArray::kAlignedSize, space, OLD_DATA_SPACE);
if (result->IsFailure()) return result;
reinterpret_cast<PixelArray*>(result)->set_map(pixel_array_map());
reinterpret_cast<PixelArray*>(result)->set_length(length);
reinterpret_cast<PixelArray*>(result)->set_external_pointer(external_pointer);
return result;
}
Object* Heap::CreateCode(const CodeDesc& desc,
ZoneScopeInfo* sinfo,
Code::Flags flags,
Handle<Object> self_reference) {
// Compute size
int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
int sinfo_size = 0;
if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
int obj_size = Code::SizeFor(body_size, sinfo_size);
ASSERT(IsAligned(obj_size, Code::kCodeAlignment));
Object* result;
if (obj_size > MaxObjectSizeInPagedSpace()) {
result = lo_space_->AllocateRawCode(obj_size);
} else {
result = code_space_->AllocateRaw(obj_size);
}
if (result->IsFailure()) return result;
// Initialize the object
HeapObject::cast(result)->set_map(code_map());
Code* code = Code::cast(result);
ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
code->set_instruction_size(desc.instr_size);
code->set_relocation_size(desc.reloc_size);
code->set_sinfo_size(sinfo_size);
code->set_flags(flags);
// Allow self references to created code object by patching the handle to
// point to the newly allocated Code object.
if (!self_reference.is_null()) {
*(self_reference.location()) = code;
}
// Migrate generated code.
// The generated code can contain Object** values (typically from handles)
// that are dereferenced during the copy to point directly to the actual heap
// objects. These pointers can include references to the code object itself,
// through the self_reference parameter.
code->CopyFrom(desc);
if (sinfo != NULL) sinfo->Serialize(code); // write scope info
#ifdef DEBUG
code->Verify();
#endif
return code;
}
Object* Heap::CopyCode(Code* code) {
// Allocate an object the same size as the code object.
int obj_size = code->Size();
Object* result;
if (obj_size > MaxObjectSizeInPagedSpace()) {
result = lo_space_->AllocateRawCode(obj_size);
} else {
result = code_space_->AllocateRaw(obj_size);
}
if (result->IsFailure()) return result;
// Copy code object.
Address old_addr = code->address();
Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
CopyBlock(reinterpret_cast<Object**>(new_addr),
reinterpret_cast<Object**>(old_addr),
obj_size);
// Relocate the copy.
Code* new_code = Code::cast(result);
ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
new_code->Relocate(new_addr - old_addr);
return new_code;
}
Object* Heap::Allocate(Map* map, AllocationSpace space) {
ASSERT(gc_state_ == NOT_IN_GC);
ASSERT(map->instance_type() != MAP_TYPE);
Object* result = AllocateRaw(map->instance_size(),
space,
TargetSpaceId(map->instance_type()));
if (result->IsFailure()) return result;
HeapObject::cast(result)->set_map(map);
return result;
}
Object* Heap::InitializeFunction(JSFunction* function,
SharedFunctionInfo* shared,
Object* prototype) {
ASSERT(!prototype->IsMap());
function->initialize_properties();
function->initialize_elements();
function->set_shared(shared);
function->set_prototype_or_initial_map(prototype);
function->set_context(undefined_value());
function->set_literals(empty_fixed_array(), SKIP_WRITE_BARRIER);
return function;
}
Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
// Allocate the prototype. Make sure to use the object function
// from the function's context, since the function can be from a
// different context.
JSFunction* object_function =
function->context()->global_context()->object_function();
Object* prototype = AllocateJSObject(object_function);
if (prototype->IsFailure()) return prototype;
// When creating the prototype for the function we must set its
// constructor to the function.
Object* result =
JSObject::cast(prototype)->SetProperty(constructor_symbol(),
function,
DONT_ENUM);
if (result->IsFailure()) return result;
return prototype;
}
Object* Heap::AllocateFunction(Map* function_map,
SharedFunctionInfo* shared,
Object* prototype) {
Object* result = Allocate(function_map, OLD_POINTER_SPACE);
if (result->IsFailure()) return result;
return InitializeFunction(JSFunction::cast(result), shared, prototype);
}
Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
// To get fast allocation and map sharing for arguments objects we
// allocate them based on an arguments boilerplate.
// This calls Copy directly rather than using Heap::AllocateRaw so we
// duplicate the check here.
ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
JSObject* boilerplate =
Top::context()->global_context()->arguments_boilerplate();
// Make the clone.
Map* map = boilerplate->map();
int object_size = map->instance_size();
Object* result = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
if (result->IsFailure()) return result;
// Copy the content. The arguments boilerplate doesn't have any
// fields that point to new space so it's safe to skip the write
// barrier here.
CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
reinterpret_cast<Object**>(boilerplate->address()),
object_size);
// Set the two properties.
JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
callee);
JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
Smi::FromInt(length),
SKIP_WRITE_BARRIER);
// Check the state of the object
ASSERT(JSObject::cast(result)->HasFastProperties());
ASSERT(JSObject::cast(result)->HasFastElements());
return result;
}
Object* Heap::AllocateInitialMap(JSFunction* fun) {
ASSERT(!fun->has_initial_map());
// First create a new map with the size and number of in-object properties
// suggested by the function.
int instance_size = fun->shared()->CalculateInstanceSize();
int in_object_properties = fun->shared()->CalculateInObjectProperties();
Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
if (map_obj->IsFailure()) return map_obj;
// Fetch or allocate prototype.
Object* prototype;
if (fun->has_instance_prototype()) {
prototype = fun->instance_prototype();
} else {
prototype = AllocateFunctionPrototype(fun);
if (prototype->IsFailure()) return prototype;
}
Map* map = Map::cast(map_obj);
map->set_inobject_properties(in_object_properties);
map->set_unused_property_fields(in_object_properties);
map->set_prototype(prototype);
// If the function has only simple this property assignments add field
// descriptors for these to the initial map as the object cannot be
// constructed without having these properties.
ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
if (fun->shared()->has_only_this_property_assignments() &&
fun->shared()->this_property_assignments_count() > 0) {
int count = fun->shared()->this_property_assignments_count();
if (count > in_object_properties) {
count = in_object_properties;
}
Object* descriptors_obj = DescriptorArray::Allocate(count);
if (descriptors_obj->IsFailure()) return descriptors_obj;
DescriptorArray* descriptors = DescriptorArray::cast(descriptors_obj);
for (int i = 0; i < count; i++) {
String* name = fun->shared()->GetThisPropertyAssignmentName(i);
ASSERT(name->IsSymbol());
FieldDescriptor field(name, i, NONE);
descriptors->Set(i, &field);
}
descriptors->Sort();
map->set_instance_descriptors(descriptors);
map->set_pre_allocated_property_fields(count);
map->set_unused_property_fields(in_object_properties - count);
}
return map;
}
void Heap::InitializeJSObjectFromMap(JSObject* obj,
FixedArray* properties,
Map* map) {
obj->set_properties(properties);
obj->initialize_elements();
// TODO(1240798): Initialize the object's body using valid initial values
// according to the object's initial map. For example, if the map's
// instance type is JS_ARRAY_TYPE, the length field should be initialized
// to a number (eg, Smi::FromInt(0)) and the elements initialized to a
// fixed array (eg, Heap::empty_fixed_array()). Currently, the object
// verification code has to cope with (temporarily) invalid objects. See
// for example, JSArray::JSArrayVerify).
obj->InitializeBody(map->instance_size());
}
Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
// JSFunctions should be allocated using AllocateFunction to be
// properly initialized.
ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
// Both types of globla objects should be allocated using
// AllocateGloblaObject to be properly initialized.
ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
// Allocate the backing storage for the properties.
int prop_size =
map->pre_allocated_property_fields() +
map->unused_property_fields() -
map->inobject_properties();
ASSERT(prop_size >= 0);
Object* properties = AllocateFixedArray(prop_size, pretenure);
if (properties->IsFailure()) return properties;
// Allocate the JSObject.
AllocationSpace space =
(pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
if (map->instance_size() > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
Object* obj = Allocate(map, space);
if (obj->IsFailure()) return obj;
// Initialize the JSObject.
InitializeJSObjectFromMap(JSObject::cast(obj),
FixedArray::cast(properties),
map);
return obj;
}
Object* Heap::AllocateJSObject(JSFunction* constructor,
PretenureFlag pretenure) {
// Allocate the initial map if absent.
if (!constructor->has_initial_map()) {
Object* initial_map = AllocateInitialMap(constructor);
if (initial_map->IsFailure()) return initial_map;
constructor->set_initial_map(Map::cast(initial_map));
Map::cast(initial_map)->set_constructor(constructor);
}
// Allocate the object based on the constructors initial map.
Object* result =
AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
// Make sure result is NOT a global object if valid.
ASSERT(result->IsFailure() || !result->IsGlobalObject());
return result;
}
Object* Heap::AllocateGlobalObject(JSFunction* constructor) {
ASSERT(constructor->has_initial_map());
Map* map = constructor->initial_map();
// Make sure no field properties are described in the initial map.
// This guarantees us that normalizing the properties does not
// require us to change property values to JSGlobalPropertyCells.
ASSERT(map->NextFreePropertyIndex() == 0);
// Make sure we don't have a ton of pre-allocated slots in the
// global objects. They will be unused once we normalize the object.
ASSERT(map->unused_property_fields() == 0);
ASSERT(map->inobject_properties() == 0);
// Initial size of the backing store to avoid resize of the storage during
// bootstrapping. The size differs between the JS global object ad the
// builtins object.
int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
// Allocate a dictionary object for backing storage.
Object* obj =
StringDictionary::Allocate(
map->NumberOfDescribedProperties() * 2 + initial_size);
if (obj->IsFailure()) return obj;
StringDictionary* dictionary = StringDictionary::cast(obj);
// The global object might be created from an object template with accessors.
// Fill these accessors into the dictionary.
DescriptorArray* descs = map->instance_descriptors();
for (int i = 0; i < descs->number_of_descriptors(); i++) {
PropertyDetails details = descs->GetDetails(i);
ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
PropertyDetails d =
PropertyDetails(details.attributes(), CALLBACKS, details.index());
Object* value = descs->GetCallbacksObject(i);
value = Heap::AllocateJSGlobalPropertyCell(value);
if (value->IsFailure()) return value;
Object* result = dictionary->Add(descs->GetKey(i), value, d);
if (result->IsFailure()) return result;
dictionary = StringDictionary::cast(result);
}
// Allocate the global object and initialize it with the backing store.
obj = Allocate(map, OLD_POINTER_SPACE);
if (obj->IsFailure()) return obj;
JSObject* global = JSObject::cast(obj);
InitializeJSObjectFromMap(global, dictionary, map);
// Create a new map for the global object.
obj = map->CopyDropDescriptors();
if (obj->IsFailure()) return obj;
Map* new_map = Map::cast(obj);
// Setup the global object as a normalized object.
global->set_map(new_map);
global->map()->set_instance_descriptors(Heap::empty_descriptor_array());
global->set_properties(dictionary);
// Make sure result is a global object with properties in dictionary.
ASSERT(global->IsGlobalObject());
ASSERT(!global->HasFastProperties());
return global;
}
Object* Heap::CopyJSObject(JSObject* source) {
// Never used to copy functions. If functions need to be copied we
// have to be careful to clear the literals array.
ASSERT(!source->IsJSFunction());
// Make the clone.
Map* map = source->map();
int object_size = map->instance_size();
Object* clone;
// If we're forced to always allocate, we use the general allocation
// functions which may leave us with an object in old space.
if (always_allocate()) {
clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
if (clone->IsFailure()) return clone;
Address clone_address = HeapObject::cast(clone)->address();
CopyBlock(reinterpret_cast<Object**>(clone_address),
reinterpret_cast<Object**>(source->address()),
object_size);
// Update write barrier for all fields that lie beyond the header.
for (int offset = JSObject::kHeaderSize;
offset < object_size;
offset += kPointerSize) {
RecordWrite(clone_address, offset);
}
} else {
clone = new_space_.AllocateRaw(object_size);
if (clone->IsFailure()) return clone;
ASSERT(Heap::InNewSpace(clone));
// Since we know the clone is allocated in new space, we can copy
// the contents without worrying about updating the write barrier.
CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
reinterpret_cast<Object**>(source->address()),
object_size);
}
FixedArray* elements = FixedArray::cast(source->elements());
FixedArray* properties = FixedArray::cast(source->properties());
// Update elements if necessary.
if (elements->length()> 0) {
Object* elem = CopyFixedArray(elements);
if (elem->IsFailure()) return elem;
JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
}
// Update properties if necessary.
if (properties->length() > 0) {
Object* prop = CopyFixedArray(properties);
if (prop->IsFailure()) return prop;
JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
}
// Return the new clone.
return clone;
}
Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
JSGlobalProxy* object) {
// Allocate initial map if absent.
if (!constructor->has_initial_map()) {
Object* initial_map = AllocateInitialMap(constructor);
if (initial_map->IsFailure()) return initial_map;
constructor->set_initial_map(Map::cast(initial_map));
Map::cast(initial_map)->set_constructor(constructor);
}
Map* map = constructor->initial_map();
// Check that the already allocated object has the same size as
// objects allocated using the constructor.
ASSERT(map->instance_size() == object->map()->instance_size());
// Allocate the backing storage for the properties.
int prop_size = map->unused_property_fields() - map->inobject_properties();
Object* properties = AllocateFixedArray(prop_size, TENURED);
if (properties->IsFailure()) return properties;
// Reset the map for the object.
object->set_map(constructor->initial_map());
// Reinitialize the object from the constructor map.
InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
return object;
}
Object* Heap::AllocateStringFromAscii(Vector<const char> string,
PretenureFlag pretenure) {
Object* result = AllocateRawAsciiString(string.length(), pretenure);
if (result->IsFailure()) return result;
// Copy the characters into the new object.
SeqAsciiString* string_result = SeqAsciiString::cast(result);
for (int i = 0; i < string.length(); i++) {
string_result->SeqAsciiStringSet(i, string[i]);
}
return result;
}
Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
PretenureFlag pretenure) {
// Count the number of characters in the UTF-8 string and check if
// it is an ASCII string.
Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
decoder->Reset(string.start(), string.length());
int chars = 0;
bool is_ascii = true;
while (decoder->has_more()) {
uc32 r = decoder->GetNext();
if (r > String::kMaxAsciiCharCode) is_ascii = false;
chars++;
}
// If the string is ascii, we do not need to convert the characters
// since UTF8 is backwards compatible with ascii.
if (is_ascii) return AllocateStringFromAscii(string, pretenure);
Object* result = AllocateRawTwoByteString(chars, pretenure);
if (result->IsFailure()) return result;
// Convert and copy the characters into the new object.
String* string_result = String::cast(result);
decoder->Reset(string.start(), string.length());
for (int i = 0; i < chars; i++) {
uc32 r = decoder->GetNext();
string_result->Set(i, r);
}
return result;
}
Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
PretenureFlag pretenure) {
// Check if the string is an ASCII string.
int i = 0;
while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
Object* result;
if (i == string.length()) { // It's an ASCII string.
result = AllocateRawAsciiString(string.length(), pretenure);
} else { // It's not an ASCII string.
result = AllocateRawTwoByteString(string.length(), pretenure);
}
if (result->IsFailure()) return result;
// Copy the characters into the new object, which may be either ASCII or
// UTF-16.
String* string_result = String::cast(result);
for (int i = 0; i < string.length(); i++) {
string_result->Set(i, string[i]);
}
return result;
}
Map* Heap::SymbolMapForString(String* string) {
// If the string is in new space it cannot be used as a symbol.
if (InNewSpace(string)) return NULL;
// Find the corresponding symbol map for strings.
Map* map = string->map();
if (map == short_ascii_string_map()) return short_ascii_symbol_map();
if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
if (map == long_ascii_string_map()) return long_ascii_symbol_map();
if (map == short_string_map()) return short_symbol_map();
if (map == medium_string_map()) return medium_symbol_map();
if (map == long_string_map()) return long_symbol_map();
if (map == short_cons_string_map()) return short_cons_symbol_map();
if (map == medium_cons_string_map()) return medium_cons_symbol_map();
if (map == long_cons_string_map()) return long_cons_symbol_map();
if (map == short_cons_ascii_string_map()) {
return short_cons_ascii_symbol_map();
}
if (map == medium_cons_ascii_string_map()) {
return medium_cons_ascii_symbol_map();
}
if (map == long_cons_ascii_string_map()) {
return long_cons_ascii_symbol_map();
}
if (map == short_sliced_string_map()) return short_sliced_symbol_map();
if (map == medium_sliced_string_map()) return medium_sliced_symbol_map();
if (map == long_sliced_string_map()) return long_sliced_symbol_map();
if (map == short_sliced_ascii_string_map()) {
return short_sliced_ascii_symbol_map();
}
if (map == medium_sliced_ascii_string_map()) {
return medium_sliced_ascii_symbol_map();
}
if (map == long_sliced_ascii_string_map()) {
return long_sliced_ascii_symbol_map();
}
if (map == short_external_string_map()) {
return short_external_symbol_map();
}
if (map == medium_external_string_map()) {
return medium_external_symbol_map();
}
if (map == long_external_string_map()) {
return long_external_symbol_map();
}
if (map == short_external_ascii_string_map()) {
return short_external_ascii_symbol_map();
}
if (map == medium_external_ascii_string_map()) {
return medium_external_ascii_symbol_map();
}
if (map == long_external_ascii_string_map()) {
return long_external_ascii_symbol_map();
}
// No match found.
return NULL;
}
Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
int chars,
uint32_t length_field) {
// Ensure the chars matches the number of characters in the buffer.
ASSERT(static_cast<unsigned>(chars) == buffer->Length());
// Determine whether the string is ascii.
bool is_ascii = true;
while (buffer->has_more() && is_ascii) {
if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
}
buffer->Rewind();
// Compute map and object size.
int size;
Map* map;
if (is_ascii) {
if (chars <= String::kMaxShortStringSize) {
map = short_ascii_symbol_map();
} else if (chars <= String::kMaxMediumStringSize) {
map = medium_ascii_symbol_map();
} else {
map = long_ascii_symbol_map();
}
size = SeqAsciiString::SizeFor(chars);
} else {
if (chars <= String::kMaxShortStringSize) {
map = short_symbol_map();
} else if (chars <= String::kMaxMediumStringSize) {
map = medium_symbol_map();
} else {
map = long_symbol_map();
}
size = SeqTwoByteString::SizeFor(chars);
}
// Allocate string.
AllocationSpace space =
(size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_DATA_SPACE;
Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
if (result->IsFailure()) return result;
reinterpret_cast<HeapObject*>(result)->set_map(map);
// The hash value contains the length of the string.
String* answer = String::cast(result);
answer->set_length_field(length_field);
ASSERT_EQ(size, answer->Size());
// Fill in the characters.
for (int i = 0; i < chars; i++) {
answer->Set(i, buffer->GetNext());
}
return answer;
}
Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
// New space can't cope with forced allocation.
if (always_allocate()) space = OLD_DATA_SPACE;
int size = SeqAsciiString::SizeFor(length);
Object* result = Failure::OutOfMemoryException();
if (space == NEW_SPACE) {
result = size <= kMaxObjectSizeInNewSpace
? new_space_.AllocateRaw(size)
: lo_space_->AllocateRaw(size);
} else {
if (size > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
result = AllocateRaw(size, space, OLD_DATA_SPACE);
}
if (result->IsFailure()) return result;
// Determine the map based on the string's length.
Map* map;
if (length <= String::kMaxShortStringSize) {
map = short_ascii_string_map();
} else if (length <= String::kMaxMediumStringSize) {
map = medium_ascii_string_map();
} else {
map = long_ascii_string_map();
}
// Partially initialize the object.
HeapObject::cast(result)->set_map(map);
String::cast(result)->set_length(length);
ASSERT_EQ(size, HeapObject::cast(result)->Size());
return result;
}
Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
// New space can't cope with forced allocation.
if (always_allocate()) space = OLD_DATA_SPACE;
int size = SeqTwoByteString::SizeFor(length);
Object* result = Failure::OutOfMemoryException();
if (space == NEW_SPACE) {
result = size <= kMaxObjectSizeInNewSpace
? new_space_.AllocateRaw(size)
: lo_space_->AllocateRaw(size);
} else {
if (size > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
result = AllocateRaw(size, space, OLD_DATA_SPACE);
}
if (result->IsFailure()) return result;
// Determine the map based on the string's length.
Map* map;
if (length <= String::kMaxShortStringSize) {
map = short_string_map();
} else if (length <= String::kMaxMediumStringSize) {
map = medium_string_map();
} else {
map = long_string_map();
}
// Partially initialize the object.
HeapObject::cast(result)->set_map(map);
String::cast(result)->set_length(length);
ASSERT_EQ(size, HeapObject::cast(result)->Size());
return result;
}
Object* Heap::AllocateEmptyFixedArray() {
int size = FixedArray::SizeFor(0);
Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
if (result->IsFailure()) return result;
// Initialize the object.
reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
reinterpret_cast<Array*>(result)->set_length(0);
return result;
}
Object* Heap::AllocateRawFixedArray(int length) {
// Use the general function if we're forced to always allocate.
if (always_allocate()) return AllocateFixedArray(length, TENURED);
// Allocate the raw data for a fixed array.
int size = FixedArray::SizeFor(length);
return size <= kMaxObjectSizeInNewSpace
? new_space_.AllocateRaw(size)
: lo_space_->AllocateRawFixedArray(size);
}
Object* Heap::CopyFixedArray(FixedArray* src) {
int len = src->length();
Object* obj = AllocateRawFixedArray(len);
if (obj->IsFailure()) return obj;
if (Heap::InNewSpace(obj)) {
HeapObject* dst = HeapObject::cast(obj);
CopyBlock(reinterpret_cast<Object**>(dst->address()),
reinterpret_cast<Object**>(src->address()),
FixedArray::SizeFor(len));
return obj;
}
HeapObject::cast(obj)->set_map(src->map());
FixedArray* result = FixedArray::cast(obj);
result->set_length(len);
// Copy the content
WriteBarrierMode mode = result->GetWriteBarrierMode();
for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
return result;
}
Object* Heap::AllocateFixedArray(int length) {
ASSERT(length >= 0);
if (length == 0) return empty_fixed_array();
Object* result = AllocateRawFixedArray(length);
if (!result->IsFailure()) {
// Initialize header.
reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
FixedArray* array = FixedArray::cast(result);
array->set_length(length);
Object* value = undefined_value();
// Initialize body.
for (int index = 0; index < length; index++) {
array->set(index, value, SKIP_WRITE_BARRIER);
}
}
return result;
}
Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
ASSERT(empty_fixed_array()->IsFixedArray());
if (length == 0) return empty_fixed_array();
// New space can't cope with forced allocation.
if (always_allocate()) pretenure = TENURED;
int size = FixedArray::SizeFor(length);
Object* result = Failure::OutOfMemoryException();
if (pretenure != TENURED) {
result = size <= kMaxObjectSizeInNewSpace
? new_space_.AllocateRaw(size)
: lo_space_->AllocateRawFixedArray(size);
}
if (result->IsFailure()) {
if (size > MaxObjectSizeInPagedSpace()) {
result = lo_space_->AllocateRawFixedArray(size);
} else {
AllocationSpace space =
(pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
result = AllocateRaw(size, space, OLD_POINTER_SPACE);
}
if (result->IsFailure()) return result;
}
// Initialize the object.
reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
FixedArray* array = FixedArray::cast(result);
array->set_length(length);
Object* value = undefined_value();
for (int index = 0; index < length; index++) {
array->set(index, value, SKIP_WRITE_BARRIER);
}
return array;
}
Object* Heap::AllocateFixedArrayWithHoles(int length) {
if (length == 0) return empty_fixed_array();
Object* result = AllocateRawFixedArray(length);
if (!result->IsFailure()) {
// Initialize header.
reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
FixedArray* array = FixedArray::cast(result);
array->set_length(length);
// Initialize body.
Object* value = the_hole_value();
for (int index = 0; index < length; index++) {
array->set(index, value, SKIP_WRITE_BARRIER);
}
}
return result;
}
Object* Heap::AllocateHashTable(int length) {
Object* result = Heap::AllocateFixedArray(length);
if (result->IsFailure()) return result;
reinterpret_cast<Array*>(result)->set_map(hash_table_map());
ASSERT(result->IsHashTable());
return result;
}
Object* Heap::AllocateGlobalContext() {
Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
if (result->IsFailure()) return result;
Context* context = reinterpret_cast<Context*>(result);
context->set_map(global_context_map());
ASSERT(context->IsGlobalContext());
ASSERT(result->IsContext());
return result;
}
Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
Object* result = Heap::AllocateFixedArray(length);
if (result->IsFailure()) return result;
Context* context = reinterpret_cast<Context*>(result);
context->set_map(context_map());
context->set_closure(function);
context->set_fcontext(context);
context->set_previous(NULL);
context->set_extension(NULL);
context->set_global(function->context()->global());
ASSERT(!context->IsGlobalContext());
ASSERT(context->is_function_context());
ASSERT(result->IsContext());
return result;
}
Object* Heap::AllocateWithContext(Context* previous,
JSObject* extension,
bool is_catch_context) {
Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
if (result->IsFailure()) return result;
Context* context = reinterpret_cast<Context*>(result);
context->set_map(is_catch_context ? catch_context_map() : context_map());
context->set_closure(previous->closure());
context->set_fcontext(previous->fcontext());
context->set_previous(previous);
context->set_extension(extension);
context->set_global(previous->global());
ASSERT(!context->IsGlobalContext());
ASSERT(!context->is_function_context());
ASSERT(result->IsContext());
return result;
}
Object* Heap::AllocateStruct(InstanceType type) {
Map* map;
switch (type) {
#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
STRUCT_LIST(MAKE_CASE)
#undef MAKE_CASE
default:
UNREACHABLE();
return Failure::InternalError();
}
int size = map->instance_size();
AllocationSpace space =
(size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_POINTER_SPACE;
Object* result = Heap::Allocate(map, space);
if (result->IsFailure()) return result;
Struct::cast(result)->InitializeBody(size);
return result;
}
bool Heap::IdleNotification() {
static const int kIdlesBeforeScavenge = 4;
static const int kIdlesBeforeMarkSweep = 7;
static const int kIdlesBeforeMarkCompact = 8;
static int number_idle_notifications = 0;
static int last_gc_count = gc_count_;
bool finished = false;
if (last_gc_count == gc_count_) {
number_idle_notifications++;
} else {
number_idle_notifications = 0;
last_gc_count = gc_count_;
}
if (number_idle_notifications == kIdlesBeforeScavenge) {
CollectGarbage(0, NEW_SPACE);
new_space_.Shrink();
last_gc_count = gc_count_;
} else if (number_idle_notifications == kIdlesBeforeMarkSweep) {
CollectAllGarbage(false);
new_space_.Shrink();
last_gc_count = gc_count_;
} else if (number_idle_notifications == kIdlesBeforeMarkCompact) {
CollectAllGarbage(true);
new_space_.Shrink();
last_gc_count = gc_count_;
number_idle_notifications = 0;
finished = true;
}
// Uncommit unused memory in new space.
Heap::UncommitFromSpace();
return finished;
}
#ifdef DEBUG
void Heap::Print() {
if (!HasBeenSetup()) return;
Top::PrintStack();
AllSpaces spaces;
while (Space* space = spaces.next()) space->Print();
}
void Heap::ReportCodeStatistics(const char* title) {
PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
PagedSpace::ResetCodeStatistics();
// We do not look for code in new space, map space, or old space. If code
// somehow ends up in those spaces, we would miss it here.
code_space_->CollectCodeStatistics();
lo_space_->CollectCodeStatistics();
PagedSpace::ReportCodeStatistics();
}
// This function expects that NewSpace's allocated objects histogram is
// populated (via a call to CollectStatistics or else as a side effect of a
// just-completed scavenge collection).
void Heap::ReportHeapStatistics(const char* title) {
USE(title);
PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
title, gc_count_);
PrintF("mark-compact GC : %d\n", mc_count_);
PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
PrintF("\n");
PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
GlobalHandles::PrintStats();
PrintF("\n");
PrintF("Heap statistics : ");
MemoryAllocator::ReportStatistics();
PrintF("To space : ");
new_space_.ReportStatistics();
PrintF("Old pointer space : ");
old_pointer_space_->ReportStatistics();
PrintF("Old data space : ");
old_data_space_->ReportStatistics();
PrintF("Code space : ");
code_space_->ReportStatistics();
PrintF("Map space : ");
map_space_->ReportStatistics();
PrintF("Cell space : ");
cell_space_->ReportStatistics();
PrintF("Large object space : ");
lo_space_->ReportStatistics();
PrintF(">>>>>> ========================================= >>>>>>\n");
}
#endif // DEBUG
bool Heap::Contains(HeapObject* value) {
return Contains(value->address());
}
bool Heap::Contains(Address addr) {
if (OS::IsOutsideAllocatedSpace(addr)) return false;
return HasBeenSetup() &&
(new_space_.ToSpaceContains(addr) ||
old_pointer_space_->Contains(addr) ||
old_data_space_->Contains(addr) ||
code_space_->Contains(addr) ||
map_space_->Contains(addr) ||
cell_space_->Contains(addr) ||
lo_space_->SlowContains(addr));
}
bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
return InSpace(value->address(), space);
}
bool Heap::InSpace(Address addr, AllocationSpace space) {
if (OS::IsOutsideAllocatedSpace(addr)) return false;
if (!HasBeenSetup()) return false;
switch (space) {
case NEW_SPACE:
return new_space_.ToSpaceContains(addr);
case OLD_POINTER_SPACE:
return old_pointer_space_->Contains(addr);
case OLD_DATA_SPACE:
return old_data_space_->Contains(addr);
case CODE_SPACE:
return code_space_->Contains(addr);
case MAP_SPACE:
return map_space_->Contains(addr);
case CELL_SPACE:
return cell_space_->Contains(addr);
case LO_SPACE:
return lo_space_->SlowContains(addr);
}
return false;
}
#ifdef DEBUG
void Heap::Verify() {
ASSERT(HasBeenSetup());
VerifyPointersVisitor visitor;
IterateRoots(&visitor);
new_space_.Verify();
VerifyPointersAndRSetVisitor rset_visitor;
old_pointer_space_->Verify(&rset_visitor);
map_space_->Verify(&rset_visitor);
VerifyPointersVisitor no_rset_visitor;
old_data_space_->Verify(&no_rset_visitor);
code_space_->Verify(&no_rset_visitor);
cell_space_->Verify(&no_rset_visitor);
lo_space_->Verify();
}
#endif // DEBUG
Object* Heap::LookupSymbol(Vector<const char> string) {
Object* symbol = NULL;
Object* new_table = symbol_table()->LookupSymbol(string, &symbol);
if (new_table->IsFailure()) return new_table;
// Can't use set_symbol_table because SymbolTable::cast knows that
// SymbolTable is a singleton and checks for identity.
roots_[kSymbolTableRootIndex] = new_table;
ASSERT(symbol != NULL);
return symbol;
}
Object* Heap::LookupSymbol(String* string) {
if (string->IsSymbol()) return string;
Object* symbol = NULL;
Object* new_table = symbol_table()->LookupString(string, &symbol);
if (new_table->IsFailure()) return new_table;
// Can't use set_symbol_table because SymbolTable::cast knows that
// SymbolTable is a singleton and checks for identity.
roots_[kSymbolTableRootIndex] = new_table;
ASSERT(symbol != NULL);
return symbol;
}
bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
if (string->IsSymbol()) {
*symbol = string;
return true;
}
return symbol_table()->LookupSymbolIfExists(string, symbol);
}
#ifdef DEBUG
void Heap::ZapFromSpace() {
ASSERT(reinterpret_cast<Object*>(kFromSpaceZapValue)->IsHeapObject());
for (Address a = new_space_.FromSpaceLow();
a < new_space_.FromSpaceHigh();
a += kPointerSize) {
Memory::Address_at(a) = kFromSpaceZapValue;
}
}
#endif // DEBUG
int Heap::IterateRSetRange(Address object_start,
Address object_end,
Address rset_start,
ObjectSlotCallback copy_object_func) {
Address object_address = object_start;
Address rset_address = rset_start;
int set_bits_count = 0;
// Loop over all the pointers in [object_start, object_end).
while (object_address < object_end) {
uint32_t rset_word = Memory::uint32_at(rset_address);
if (rset_word != 0) {
uint32_t result_rset = rset_word;
for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
// Do not dereference pointers at or past object_end.
if ((rset_word & bitmask) != 0 && object_address < object_end) {
Object** object_p = reinterpret_cast<Object**>(object_address);
if (Heap::InNewSpace(*object_p)) {
copy_object_func(reinterpret_cast<HeapObject**>(object_p));
}
// If this pointer does not need to be remembered anymore, clear
// the remembered set bit.
if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
set_bits_count++;
}
object_address += kPointerSize;
}
// Update the remembered set if it has changed.
if (result_rset != rset_word) {
Memory::uint32_at(rset_address) = result_rset;
}
} else {
// No bits in the word were set. This is the common case.
object_address += kPointerSize * kBitsPerInt;
}
rset_address += kIntSize;
}
return set_bits_count;
}
void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
ASSERT(Page::is_rset_in_use());
ASSERT(space == old_pointer_space_ || space == map_space_);
static void* paged_rset_histogram = StatsTable::CreateHistogram(
"V8.RSetPaged",
0,
Page::kObjectAreaSize / kPointerSize,
30);
PageIterator it(space, PageIterator::PAGES_IN_USE);
while (it.has_next()) {
Page* page = it.next();
int count = IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
page->RSetStart(), copy_object_func);
if (paged_rset_histogram != NULL) {
StatsTable::AddHistogramSample(paged_rset_histogram, count);
}
}
}
#ifdef DEBUG
#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
#else
#define SYNCHRONIZE_TAG(tag)
#endif
void Heap::IterateRoots(ObjectVisitor* v) {
IterateStrongRoots(v);
v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
SYNCHRONIZE_TAG("symbol_table");
}
void Heap::IterateStrongRoots(ObjectVisitor* v) {
v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
SYNCHRONIZE_TAG("strong_root_list");
v->VisitPointer(bit_cast<Object**, String**>(&hidden_symbol_));
SYNCHRONIZE_TAG("symbol");
Bootstrapper::Iterate(v);
SYNCHRONIZE_TAG("bootstrapper");
Top::Iterate(v);
SYNCHRONIZE_TAG("top");
Relocatable::Iterate(v);
SYNCHRONIZE_TAG("relocatable");
#ifdef ENABLE_DEBUGGER_SUPPORT
Debug::Iterate(v);
#endif
SYNCHRONIZE_TAG("debug");
CompilationCache::Iterate(v);
SYNCHRONIZE_TAG("compilationcache");
// Iterate over local handles in handle scopes.
HandleScopeImplementer::Iterate(v);
SYNCHRONIZE_TAG("handlescope");
// Iterate over the builtin code objects and code stubs in the heap. Note
// that it is not strictly necessary to iterate over code objects on
// scavenge collections. We still do it here because this same function
// is used by the mark-sweep collector and the deserializer.
Builtins::IterateBuiltins(v);
SYNCHRONIZE_TAG("builtins");
// Iterate over global handles.
GlobalHandles::IterateRoots(v);
SYNCHRONIZE_TAG("globalhandles");
// Iterate over pointers being held by inactive threads.
ThreadManager::Iterate(v);
SYNCHRONIZE_TAG("threadmanager");
}
#undef SYNCHRONIZE_TAG
// Flag is set when the heap has been configured. The heap can be repeatedly
// configured through the API until it is setup.
static bool heap_configured = false;
// TODO(1236194): Since the heap size is configurable on the command line
// and through the API, we should gracefully handle the case that the heap
// size is not big enough to fit all the initial objects.
bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
if (HasBeenSetup()) return false;
if (semispace_size > 0) semispace_size_ = semispace_size;
if (old_gen_size > 0) old_generation_size_ = old_gen_size;
// The new space size must be a power of two to support single-bit testing
// for containment.
semispace_size_ = RoundUpToPowerOf2(semispace_size_);
initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
young_generation_size_ = 2 * semispace_size_;
external_allocation_limit_ = 10 * semispace_size_;
// The old generation is paged.
old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
heap_configured = true;
return true;
}
bool Heap::ConfigureHeapDefault() {
return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
}
int Heap::PromotedSpaceSize() {
return old_pointer_space_->Size()
+ old_data_space_->Size()
+ code_space_->Size()
+ map_space_->Size()
+ cell_space_->Size()
+ lo_space_->Size();
}
int Heap::PromotedExternalMemorySize() {
if (amount_of_external_allocated_memory_
<= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
return amount_of_external_allocated_memory_
- amount_of_external_allocated_memory_at_last_global_gc_;
}
bool Heap::Setup(bool create_heap_objects) {
// Initialize heap spaces and initial maps and objects. Whenever something
// goes wrong, just return false. The caller should check the results and
// call Heap::TearDown() to release allocated memory.
//
// If the heap is not yet configured (eg, through the API), configure it.
// Configuration is based on the flags new-space-size (really the semispace
// size) and old-space-size if set or the initial values of semispace_size_
// and old_generation_size_ otherwise.
if (!heap_configured) {
if (!ConfigureHeapDefault()) return false;
}
// Setup memory allocator and reserve a chunk of memory for new
// space. The chunk is double the size of the new space to ensure
// that we can find a pair of semispaces that are contiguous and
// aligned to their size.
if (!MemoryAllocator::Setup(MaxCapacity())) return false;
void* chunk =
MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
if (chunk == NULL) return false;
// Align the pair of semispaces to their size, which must be a power
// of 2.
ASSERT(IsPowerOf2(young_generation_size_));
Address new_space_start =
RoundUp(reinterpret_cast<byte*>(chunk), young_generation_size_);
if (!new_space_.Setup(new_space_start, young_generation_size_)) return false;
// Initialize old pointer space.
old_pointer_space_ =
new OldSpace(old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
if (old_pointer_space_ == NULL) return false;
if (!old_pointer_space_->Setup(NULL, 0)) return false;
// Initialize old data space.
old_data_space_ =
new OldSpace(old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
if (old_data_space_ == NULL) return false;
if (!old_data_space_->Setup(NULL, 0)) return false;
// Initialize the code space, set its maximum capacity to the old
// generation size. It needs executable memory.
// On 64-bit platform(s), we put all code objects in a 2 GB range of
// virtual address space, so that they can call each other with near calls.
if (code_range_size_ > 0) {
if (!CodeRange::Setup(code_range_size_)) {
return false;
}
}
code_space_ =
new OldSpace(old_generation_size_, CODE_SPACE, EXECUTABLE);
if (code_space_ == NULL) return false;
if (!code_space_->Setup(NULL, 0)) return false;
// Initialize map space.
map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
if (map_space_ == NULL) return false;
if (!map_space_->Setup(NULL, 0)) return false;
// Initialize global property cell space.
cell_space_ = new CellSpace(old_generation_size_, CELL_SPACE);
if (cell_space_ == NULL) return false;
if (!cell_space_->Setup(NULL, 0)) return false;
// The large object code space may contain code or data. We set the memory
// to be non-executable here for safety, but this means we need to enable it
// explicitly when allocating large code objects.
lo_space_ = new LargeObjectSpace(LO_SPACE);
if (lo_space_ == NULL) return false;
if (!lo_space_->Setup()) return false;
if (create_heap_objects) {
// Create initial maps.
if (!CreateInitialMaps()) return false;
if (!CreateApiObjects()) return false;
// Create initial objects
if (!CreateInitialObjects()) return false;
}
LOG(IntEvent("heap-capacity", Capacity()));
LOG(IntEvent("heap-available", Available()));
return true;
}
void Heap::SetStackLimit(intptr_t limit) {
// On 64 bit machines, pointers are generally out of range of Smis. We write
// something that looks like an out of range Smi to the GC.
// Set up the special root array entry containing the stack guard.
// This is actually an address, but the tag makes the GC ignore it.
roots_[kStackLimitRootIndex] =
reinterpret_cast<Object*>((limit & ~kSmiTagMask) | kSmiTag);
}
void Heap::TearDown() {
GlobalHandles::TearDown();
new_space_.TearDown();
if (old_pointer_space_ != NULL) {
old_pointer_space_->TearDown();
delete old_pointer_space_;
old_pointer_space_ = NULL;
}
if (old_data_space_ != NULL) {
old_data_space_->TearDown();
delete old_data_space_;
old_data_space_ = NULL;
}
if (code_space_ != NULL) {
code_space_->TearDown();
delete code_space_;
code_space_ = NULL;
}
if (map_space_ != NULL) {
map_space_->TearDown();
delete map_space_;
map_space_ = NULL;
}
if (cell_space_ != NULL) {
cell_space_->TearDown();
delete cell_space_;
cell_space_ = NULL;
}
if (lo_space_ != NULL) {
lo_space_->TearDown();
delete lo_space_;
lo_space_ = NULL;
}
MemoryAllocator::TearDown();
}
void Heap::Shrink() {
// Try to shrink all paged spaces.
PagedSpaces spaces;
while (PagedSpace* space = spaces.next()) space->Shrink();
}
#ifdef ENABLE_HEAP_PROTECTION
void Heap::Protect() {
if (HasBeenSetup()) {
AllSpaces spaces;
while (Space* space = spaces.next()) space->Protect();
}
}
void Heap::Unprotect() {
if (HasBeenSetup()) {
AllSpaces spaces;
while (Space* space = spaces.next()) space->Unprotect();
}
}
#endif
#ifdef DEBUG
class PrintHandleVisitor: public ObjectVisitor {
public:
void VisitPointers(Object** start, Object** end) {
for (Object** p = start; p < end; p++)
PrintF(" handle %p to %p\n", p, *p);
}
};
void Heap::PrintHandles() {
PrintF("Handles:\n");
PrintHandleVisitor v;
HandleScopeImplementer::Iterate(&v);
}
#endif
Space* AllSpaces::next() {
switch (counter_++) {
case NEW_SPACE:
return Heap::new_space();
case OLD_POINTER_SPACE:
return Heap::old_pointer_space();
case OLD_DATA_SPACE:
return Heap::old_data_space();
case CODE_SPACE:
return Heap::code_space();
case MAP_SPACE:
return Heap::map_space();
case CELL_SPACE:
return Heap::cell_space();
case LO_SPACE:
return Heap::lo_space();
default:
return NULL;
}
}
PagedSpace* PagedSpaces::next() {
switch (counter_++) {
case OLD_POINTER_SPACE:
return Heap::old_pointer_space();
case OLD_DATA_SPACE:
return Heap::old_data_space();
case CODE_SPACE:
return Heap::code_space();
case MAP_SPACE:
return Heap::map_space();
case CELL_SPACE:
return Heap::cell_space();
default:
return NULL;
}
}
OldSpace* OldSpaces::next() {
switch (counter_++) {
case OLD_POINTER_SPACE:
return Heap::old_pointer_space();
case OLD_DATA_SPACE:
return Heap::old_data_space();
case CODE_SPACE:
return Heap::code_space();
default:
return NULL;
}
}
SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
}
SpaceIterator::~SpaceIterator() {
// Delete active iterator if any.
delete iterator_;
}
bool SpaceIterator::has_next() {
// Iterate until no more spaces.
return current_space_ != LAST_SPACE;
}
ObjectIterator* SpaceIterator::next() {
if (iterator_ != NULL) {
delete iterator_;
iterator_ = NULL;
// Move to the next space
current_space_++;
if (current_space_ > LAST_SPACE) {
return NULL;
}
}
// Return iterator for the new current space.
return CreateIterator();
}
// Create an iterator for the space to iterate.
ObjectIterator* SpaceIterator::CreateIterator() {
ASSERT(iterator_ == NULL);
switch (current_space_) {
case NEW_SPACE:
iterator_ = new SemiSpaceIterator(Heap::new_space());
break;
case OLD_POINTER_SPACE:
iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
break;
case OLD_DATA_SPACE:
iterator_ = new HeapObjectIterator(Heap::old_data_space());
break;
case CODE_SPACE:
iterator_ = new HeapObjectIterator(Heap::code_space());
break;
case MAP_SPACE:
iterator_ = new HeapObjectIterator(Heap::map_space());
break;
case CELL_SPACE:
iterator_ = new HeapObjectIterator(Heap::cell_space());
break;
case LO_SPACE:
iterator_ = new LargeObjectIterator(Heap::lo_space());
break;
}
// Return the newly allocated iterator;
ASSERT(iterator_ != NULL);
return iterator_;
}
HeapIterator::HeapIterator() {
Init();
}
HeapIterator::~HeapIterator() {
Shutdown();
}
void HeapIterator::Init() {
// Start the iteration.
space_iterator_ = new SpaceIterator();
object_iterator_ = space_iterator_->next();
}
void HeapIterator::Shutdown() {
// Make sure the last iterator is deallocated.
delete space_iterator_;
space_iterator_ = NULL;
object_iterator_ = NULL;
}
bool HeapIterator::has_next() {
// No iterator means we are done.
if (object_iterator_ == NULL) return false;
if (object_iterator_->has_next_object()) {
// If the current iterator has more objects we are fine.
return true;
} else {
// Go though the spaces looking for one that has objects.
while (space_iterator_->has_next()) {
object_iterator_ = space_iterator_->next();
if (object_iterator_->has_next_object()) {
return true;
}
}
}
// Done with the last space.
object_iterator_ = NULL;
return false;
}
HeapObject* HeapIterator::next() {
if (has_next()) {
return object_iterator_->next_object();
} else {
return NULL;
}
}
void HeapIterator::reset() {
// Restart the iterator.
Shutdown();
Init();
}
#ifdef DEBUG
static bool search_for_any_global;
static Object* search_target;
static bool found_target;
static List<Object*> object_stack(20);
// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
static const int kMarkTag = 2;
static void MarkObjectRecursively(Object** p);
class MarkObjectVisitor : public ObjectVisitor {
public:
void VisitPointers(Object** start, Object** end) {
// Copy all HeapObject pointers in [start, end)
for (Object** p = start; p < end; p++) {
if ((*p)->IsHeapObject())
MarkObjectRecursively(p);
}
}
};
static MarkObjectVisitor mark_visitor;
static void MarkObjectRecursively(Object** p) {
if (!(*p)->IsHeapObject()) return;
HeapObject* obj = HeapObject::cast(*p);
Object* map = obj->map();
if (!map->IsHeapObject()) return; // visited before
if (found_target) return; // stop if target found
object_stack.Add(obj);
if ((search_for_any_global && obj->IsJSGlobalObject()) ||
(!search_for_any_global && (obj == search_target))) {
found_target = true;
return;
}
// not visited yet
Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
Address map_addr = map_p->address();
obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
MarkObjectRecursively(&map);
obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
&mark_visitor);
if (!found_target) // don't pop if found the target
object_stack.RemoveLast();
}
static void UnmarkObjectRecursively(Object** p);
class UnmarkObjectVisitor : public ObjectVisitor {
public:
void VisitPointers(Object** start, Object** end) {
// Copy all HeapObject pointers in [start, end)
for (Object** p = start; p < end; p++) {
if ((*p)->IsHeapObject())
UnmarkObjectRecursively(p);
}
}
};
static UnmarkObjectVisitor unmark_visitor;
static void UnmarkObjectRecursively(Object** p) {
if (!(*p)->IsHeapObject()) return;
HeapObject* obj = HeapObject::cast(*p);
Object* map = obj->map();
if (map->IsHeapObject()) return; // unmarked already
Address map_addr = reinterpret_cast<Address>(map);
map_addr -= kMarkTag;
ASSERT_TAG_ALIGNED(map_addr);
HeapObject* map_p = HeapObject::FromAddress(map_addr);
obj->set_map(reinterpret_cast<Map*>(map_p));
UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
obj->IterateBody(Map::cast(map_p)->instance_type(),
obj->SizeFromMap(Map::cast(map_p)),
&unmark_visitor);
}
static void MarkRootObjectRecursively(Object** root) {
if (search_for_any_global) {
ASSERT(search_target == NULL);
} else {
ASSERT(search_target->IsHeapObject());
}
found_target = false;
object_stack.Clear();
MarkObjectRecursively(root);
UnmarkObjectRecursively(root);
if (found_target) {
PrintF("=====================================\n");
PrintF("==== Path to object ====\n");
PrintF("=====================================\n\n");
ASSERT(!object_stack.is_empty());
for (int i = 0; i < object_stack.length(); i++) {
if (i > 0) PrintF("\n |\n |\n V\n\n");
Object* obj = object_stack[i];
obj->Print();
}
PrintF("=====================================\n");
}
}
// Helper class for visiting HeapObjects recursively.
class MarkRootVisitor: public ObjectVisitor {
public:
void VisitPointers(Object** start, Object** end) {
// Visit all HeapObject pointers in [start, end)
for (Object** p = start; p < end; p++) {
if ((*p)->IsHeapObject())
MarkRootObjectRecursively(p);
}
}
};
// Triggers a depth-first traversal of reachable objects from roots
// and finds a path to a specific heap object and prints it.
void Heap::TracePathToObject() {
search_target = NULL;
search_for_any_global = false;
MarkRootVisitor root_visitor;
IterateRoots(&root_visitor);
}
// Triggers a depth-first traversal of reachable objects from roots
// and finds a path to any global object and prints it. Useful for
// determining the source for leaks of global objects.
void Heap::TracePathToGlobal() {
search_target = NULL;
search_for_any_global = true;
MarkRootVisitor root_visitor;
IterateRoots(&root_visitor);
}
#endif
GCTracer::GCTracer()
: start_time_(0.0),
start_size_(0.0),
gc_count_(0),
full_gc_count_(0),
is_compacting_(false),
marked_count_(0) {
// These two fields reflect the state of the previous full collection.
// Set them before they are changed by the collector.
previous_has_compacted_ = MarkCompactCollector::HasCompacted();
previous_marked_count_ = MarkCompactCollector::previous_marked_count();
if (!FLAG_trace_gc) return;
start_time_ = OS::TimeCurrentMillis();
start_size_ = SizeOfHeapObjects();
}
GCTracer::~GCTracer() {
if (!FLAG_trace_gc) return;
// Printf ONE line iff flag is set.
PrintF("%s %.1f -> %.1f MB, %d ms.\n",
CollectorString(),
start_size_, SizeOfHeapObjects(),
static_cast<int>(OS::TimeCurrentMillis() - start_time_));
#if defined(ENABLE_LOGGING_AND_PROFILING)
Heap::PrintShortHeapStatistics();
#endif
}
const char* GCTracer::CollectorString() {
switch (collector_) {
case SCAVENGER:
return "Scavenge";
case MARK_COMPACTOR:
return MarkCompactCollector::HasCompacted() ? "Mark-compact"
: "Mark-sweep";
}
return "Unknown GC";
}
int KeyedLookupCache::Hash(Map* map, String* name) {
// Uses only lower 32 bits if pointers are larger.
uintptr_t addr_hash =
static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> 2;
return (addr_hash ^ name->Hash()) % kLength;
}
int KeyedLookupCache::Lookup(Map* map, String* name) {
int index = Hash(map, name);
Key& key = keys_[index];
if ((key.map == map) && key.name->Equals(name)) {
return field_offsets_[index];
}
return -1;
}
void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
String* symbol;
if (Heap::LookupSymbolIfExists(name, &symbol)) {
int index = Hash(map, symbol);
Key& key = keys_[index];
key.map = map;
key.name = symbol;
field_offsets_[index] = field_offset;
}
}
void KeyedLookupCache::Clear() {
for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
}
KeyedLookupCache::Key KeyedLookupCache::keys_[KeyedLookupCache::kLength];
int KeyedLookupCache::field_offsets_[KeyedLookupCache::kLength];
void DescriptorLookupCache::Clear() {
for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
}
DescriptorLookupCache::Key
DescriptorLookupCache::keys_[DescriptorLookupCache::kLength];
int DescriptorLookupCache::results_[DescriptorLookupCache::kLength];
#ifdef DEBUG
bool Heap::GarbageCollectionGreedyCheck() {
ASSERT(FLAG_gc_greedy);
if (Bootstrapper::IsActive()) return true;
if (disallow_allocation_failure()) return true;
return CollectGarbage(0, NEW_SPACE);
}
#endif
TranscendentalCache::TranscendentalCache(TranscendentalCache::Type t)
: type_(t) {
uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
uint32_t in1 = 0xffffffffu; // generated by the FPU.
for (int i = 0; i < kCacheSize; i++) {
elements_[i].in[0] = in0;
elements_[i].in[1] = in1;
elements_[i].output = NULL;
}
}
TranscendentalCache* TranscendentalCache::caches_[kNumberOfCaches];
void TranscendentalCache::Clear() {
for (int i = 0; i < kNumberOfCaches; i++) {
if (caches_[i] != NULL) {
delete caches_[i];
caches_[i] = NULL;
}
}
}
} } // namespace v8::internal
Double the CodeRange on X64 to 512 MB.
Review URL: http://codereview.chromium.org/265006
git-svn-id: b158db1e4b4ab85d4c9e510fdef4b1e8c614b15b@3028 ce2b1a6d-e550-0410-aec6-3dcde31c8c00
// Copyright 2009 the V8 project authors. 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 Google Inc. 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
// 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 "v8.h"
#include "accessors.h"
#include "api.h"
#include "bootstrapper.h"
#include "codegen-inl.h"
#include "compilation-cache.h"
#include "debug.h"
#include "heap-profiler.h"
#include "global-handles.h"
#include "mark-compact.h"
#include "natives.h"
#include "scanner.h"
#include "scopeinfo.h"
#include "v8threads.h"
#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
#include "regexp-macro-assembler.h"
#endif
namespace v8 {
namespace internal {
String* Heap::hidden_symbol_;
Object* Heap::roots_[Heap::kRootListLength];
NewSpace Heap::new_space_;
OldSpace* Heap::old_pointer_space_ = NULL;
OldSpace* Heap::old_data_space_ = NULL;
OldSpace* Heap::code_space_ = NULL;
MapSpace* Heap::map_space_ = NULL;
CellSpace* Heap::cell_space_ = NULL;
LargeObjectSpace* Heap::lo_space_ = NULL;
static const int kMinimumPromotionLimit = 2*MB;
static const int kMinimumAllocationLimit = 8*MB;
int Heap::old_gen_promotion_limit_ = kMinimumPromotionLimit;
int Heap::old_gen_allocation_limit_ = kMinimumAllocationLimit;
int Heap::old_gen_exhausted_ = false;
int Heap::amount_of_external_allocated_memory_ = 0;
int Heap::amount_of_external_allocated_memory_at_last_global_gc_ = 0;
// semispace_size_ should be a power of 2 and old_generation_size_ should be
// a multiple of Page::kPageSize.
#if defined(ANDROID)
int Heap::semispace_size_ = 512*KB;
int Heap::old_generation_size_ = 128*MB;
int Heap::initial_semispace_size_ = 128*KB;
size_t Heap::code_range_size_ = 0;
#elif defined(V8_TARGET_ARCH_X64)
int Heap::semispace_size_ = 16*MB;
int Heap::old_generation_size_ = 1*GB;
int Heap::initial_semispace_size_ = 1*MB;
size_t Heap::code_range_size_ = 512*MB;
#else
int Heap::semispace_size_ = 8*MB;
int Heap::old_generation_size_ = 512*MB;
int Heap::initial_semispace_size_ = 512*KB;
size_t Heap::code_range_size_ = 0;
#endif
GCCallback Heap::global_gc_prologue_callback_ = NULL;
GCCallback Heap::global_gc_epilogue_callback_ = NULL;
// Variables set based on semispace_size_ and old_generation_size_ in
// ConfigureHeap.
int Heap::young_generation_size_ = 0; // Will be 2 * semispace_size_.
int Heap::survived_since_last_expansion_ = 0;
int Heap::external_allocation_limit_ = 0;
Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
int Heap::mc_count_ = 0;
int Heap::gc_count_ = 0;
int Heap::always_allocate_scope_depth_ = 0;
bool Heap::context_disposed_pending_ = false;
#ifdef DEBUG
bool Heap::allocation_allowed_ = true;
int Heap::allocation_timeout_ = 0;
bool Heap::disallow_allocation_failure_ = false;
#endif // DEBUG
int Heap::Capacity() {
if (!HasBeenSetup()) return 0;
return new_space_.Capacity() +
old_pointer_space_->Capacity() +
old_data_space_->Capacity() +
code_space_->Capacity() +
map_space_->Capacity() +
cell_space_->Capacity();
}
int Heap::Available() {
if (!HasBeenSetup()) return 0;
return new_space_.Available() +
old_pointer_space_->Available() +
old_data_space_->Available() +
code_space_->Available() +
map_space_->Available() +
cell_space_->Available();
}
bool Heap::HasBeenSetup() {
return old_pointer_space_ != NULL &&
old_data_space_ != NULL &&
code_space_ != NULL &&
map_space_ != NULL &&
cell_space_ != NULL &&
lo_space_ != NULL;
}
GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
// Is global GC requested?
if (space != NEW_SPACE || FLAG_gc_global) {
Counters::gc_compactor_caused_by_request.Increment();
return MARK_COMPACTOR;
}
// Is enough data promoted to justify a global GC?
if (OldGenerationPromotionLimitReached()) {
Counters::gc_compactor_caused_by_promoted_data.Increment();
return MARK_COMPACTOR;
}
// Have allocation in OLD and LO failed?
if (old_gen_exhausted_) {
Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
return MARK_COMPACTOR;
}
// Is there enough space left in OLD to guarantee that a scavenge can
// succeed?
//
// Note that MemoryAllocator->MaxAvailable() undercounts the memory available
// for object promotion. It counts only the bytes that the memory
// allocator has not yet allocated from the OS and assigned to any space,
// and does not count available bytes already in the old space or code
// space. Undercounting is safe---we may get an unrequested full GC when
// a scavenge would have succeeded.
if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
return MARK_COMPACTOR;
}
// Default
return SCAVENGER;
}
// TODO(1238405): Combine the infrastructure for --heap-stats and
// --log-gc to avoid the complicated preprocessor and flag testing.
#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
void Heap::ReportStatisticsBeforeGC() {
// Heap::ReportHeapStatistics will also log NewSpace statistics when
// compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
// following logic is used to avoid double logging.
#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
if (FLAG_heap_stats) {
ReportHeapStatistics("Before GC");
} else if (FLAG_log_gc) {
new_space_.ReportStatistics();
}
if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
#elif defined(DEBUG)
if (FLAG_heap_stats) {
new_space_.CollectStatistics();
ReportHeapStatistics("Before GC");
new_space_.ClearHistograms();
}
#elif defined(ENABLE_LOGGING_AND_PROFILING)
if (FLAG_log_gc) {
new_space_.CollectStatistics();
new_space_.ReportStatistics();
new_space_.ClearHistograms();
}
#endif
}
#if defined(ENABLE_LOGGING_AND_PROFILING)
void Heap::PrintShortHeapStatistics() {
if (!FLAG_trace_gc_verbose) return;
PrintF("Memory allocator, used: %8d, available: %8d\n",
MemoryAllocator::Size(), MemoryAllocator::Available());
PrintF("New space, used: %8d, available: %8d\n",
Heap::new_space_.Size(), new_space_.Available());
PrintF("Old pointers, used: %8d, available: %8d\n",
old_pointer_space_->Size(), old_pointer_space_->Available());
PrintF("Old data space, used: %8d, available: %8d\n",
old_data_space_->Size(), old_data_space_->Available());
PrintF("Code space, used: %8d, available: %8d\n",
code_space_->Size(), code_space_->Available());
PrintF("Map space, used: %8d, available: %8d\n",
map_space_->Size(), map_space_->Available());
PrintF("Large object space, used: %8d, avaialble: %8d\n",
lo_space_->Size(), lo_space_->Available());
}
#endif
// TODO(1238405): Combine the infrastructure for --heap-stats and
// --log-gc to avoid the complicated preprocessor and flag testing.
void Heap::ReportStatisticsAfterGC() {
// Similar to the before GC, we use some complicated logic to ensure that
// NewSpace statistics are logged exactly once when --log-gc is turned on.
#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
if (FLAG_heap_stats) {
new_space_.CollectStatistics();
ReportHeapStatistics("After GC");
} else if (FLAG_log_gc) {
new_space_.ReportStatistics();
}
#elif defined(DEBUG)
if (FLAG_heap_stats) ReportHeapStatistics("After GC");
#elif defined(ENABLE_LOGGING_AND_PROFILING)
if (FLAG_log_gc) new_space_.ReportStatistics();
#endif
}
#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
void Heap::GarbageCollectionPrologue() {
TranscendentalCache::Clear();
gc_count_++;
#ifdef DEBUG
ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
allow_allocation(false);
if (FLAG_verify_heap) {
Verify();
}
if (FLAG_gc_verbose) Print();
if (FLAG_print_rset) {
// Not all spaces have remembered set bits that we care about.
old_pointer_space_->PrintRSet();
map_space_->PrintRSet();
lo_space_->PrintRSet();
}
#endif
#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
ReportStatisticsBeforeGC();
#endif
}
int Heap::SizeOfObjects() {
int total = 0;
AllSpaces spaces;
while (Space* space = spaces.next()) {
total += space->Size();
}
return total;
}
void Heap::GarbageCollectionEpilogue() {
#ifdef DEBUG
allow_allocation(true);
ZapFromSpace();
if (FLAG_verify_heap) {
Verify();
}
if (FLAG_print_global_handles) GlobalHandles::Print();
if (FLAG_print_handles) PrintHandles();
if (FLAG_gc_verbose) Print();
if (FLAG_code_stats) ReportCodeStatistics("After GC");
#endif
Counters::alive_after_last_gc.Set(SizeOfObjects());
Counters::symbol_table_capacity.Set(symbol_table()->Capacity());
Counters::number_of_symbols.Set(symbol_table()->NumberOfElements());
#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
ReportStatisticsAfterGC();
#endif
#ifdef ENABLE_DEBUGGER_SUPPORT
Debug::AfterGarbageCollection();
#endif
}
void Heap::CollectAllGarbage(bool force_compaction) {
// Since we are ignoring the return value, the exact choice of space does
// not matter, so long as we do not specify NEW_SPACE, which would not
// cause a full GC.
MarkCompactCollector::SetForceCompaction(force_compaction);
CollectGarbage(0, OLD_POINTER_SPACE);
MarkCompactCollector::SetForceCompaction(false);
}
void Heap::CollectAllGarbageIfContextDisposed() {
// If the garbage collector interface is exposed through the global
// gc() function, we avoid being clever about forcing GCs when
// contexts are disposed and leave it to the embedder to make
// informed decisions about when to force a collection.
if (!FLAG_expose_gc && context_disposed_pending_) {
HistogramTimerScope scope(&Counters::gc_context);
CollectAllGarbage(false);
}
context_disposed_pending_ = false;
}
void Heap::NotifyContextDisposed() {
context_disposed_pending_ = true;
}
bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
// The VM is in the GC state until exiting this function.
VMState state(GC);
#ifdef DEBUG
// Reset the allocation timeout to the GC interval, but make sure to
// allow at least a few allocations after a collection. The reason
// for this is that we have a lot of allocation sequences and we
// assume that a garbage collection will allow the subsequent
// allocation attempts to go through.
allocation_timeout_ = Max(6, FLAG_gc_interval);
#endif
{ GCTracer tracer;
GarbageCollectionPrologue();
// The GC count was incremented in the prologue. Tell the tracer about
// it.
tracer.set_gc_count(gc_count_);
GarbageCollector collector = SelectGarbageCollector(space);
// Tell the tracer which collector we've selected.
tracer.set_collector(collector);
HistogramTimer* rate = (collector == SCAVENGER)
? &Counters::gc_scavenger
: &Counters::gc_compactor;
rate->Start();
PerformGarbageCollection(space, collector, &tracer);
rate->Stop();
GarbageCollectionEpilogue();
}
#ifdef ENABLE_LOGGING_AND_PROFILING
if (FLAG_log_gc) HeapProfiler::WriteSample();
#endif
switch (space) {
case NEW_SPACE:
return new_space_.Available() >= requested_size;
case OLD_POINTER_SPACE:
return old_pointer_space_->Available() >= requested_size;
case OLD_DATA_SPACE:
return old_data_space_->Available() >= requested_size;
case CODE_SPACE:
return code_space_->Available() >= requested_size;
case MAP_SPACE:
return map_space_->Available() >= requested_size;
case CELL_SPACE:
return cell_space_->Available() >= requested_size;
case LO_SPACE:
return lo_space_->Available() >= requested_size;
}
return false;
}
void Heap::PerformScavenge() {
GCTracer tracer;
PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
}
#ifdef DEBUG
// Helper class for verifying the symbol table.
class SymbolTableVerifier : public ObjectVisitor {
public:
SymbolTableVerifier() { }
void VisitPointers(Object** start, Object** end) {
// Visit all HeapObject pointers in [start, end).
for (Object** p = start; p < end; p++) {
if ((*p)->IsHeapObject()) {
// Check that the symbol is actually a symbol.
ASSERT((*p)->IsNull() || (*p)->IsUndefined() || (*p)->IsSymbol());
}
}
}
};
#endif // DEBUG
static void VerifySymbolTable() {
#ifdef DEBUG
SymbolTableVerifier verifier;
Heap::symbol_table()->IterateElements(&verifier);
#endif // DEBUG
}
void Heap::EnsureFromSpaceIsCommitted() {
if (new_space_.CommitFromSpaceIfNeeded()) return;
// Committing memory to from space failed.
// Try shrinking and try again.
Shrink();
if (new_space_.CommitFromSpaceIfNeeded()) return;
// Committing memory to from space failed again.
// Memory is exhausted and we will die.
V8::FatalProcessOutOfMemory("Committing semi space failed.");
}
void Heap::PerformGarbageCollection(AllocationSpace space,
GarbageCollector collector,
GCTracer* tracer) {
VerifySymbolTable();
if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
ASSERT(!allocation_allowed_);
global_gc_prologue_callback_();
}
EnsureFromSpaceIsCommitted();
if (collector == MARK_COMPACTOR) {
MarkCompact(tracer);
int old_gen_size = PromotedSpaceSize();
old_gen_promotion_limit_ =
old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
old_gen_allocation_limit_ =
old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 2);
old_gen_exhausted_ = false;
}
Scavenge();
Counters::objs_since_last_young.Set(0);
PostGarbageCollectionProcessing();
if (collector == MARK_COMPACTOR) {
// Register the amount of external allocated memory.
amount_of_external_allocated_memory_at_last_global_gc_ =
amount_of_external_allocated_memory_;
}
if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
ASSERT(!allocation_allowed_);
global_gc_epilogue_callback_();
}
VerifySymbolTable();
}
void Heap::PostGarbageCollectionProcessing() {
// Process weak handles post gc.
{
DisableAssertNoAllocation allow_allocation;
GlobalHandles::PostGarbageCollectionProcessing();
}
// Update relocatables.
Relocatable::PostGarbageCollectionProcessing();
}
void Heap::MarkCompact(GCTracer* tracer) {
gc_state_ = MARK_COMPACT;
mc_count_++;
tracer->set_full_gc_count(mc_count_);
LOG(ResourceEvent("markcompact", "begin"));
MarkCompactCollector::Prepare(tracer);
bool is_compacting = MarkCompactCollector::IsCompacting();
MarkCompactPrologue(is_compacting);
MarkCompactCollector::CollectGarbage();
MarkCompactEpilogue(is_compacting);
LOG(ResourceEvent("markcompact", "end"));
gc_state_ = NOT_IN_GC;
Shrink();
Counters::objs_since_last_full.Set(0);
context_disposed_pending_ = false;
}
void Heap::MarkCompactPrologue(bool is_compacting) {
// At any old GC clear the keyed lookup cache to enable collection of unused
// maps.
KeyedLookupCache::Clear();
ContextSlotCache::Clear();
DescriptorLookupCache::Clear();
CompilationCache::MarkCompactPrologue();
Top::MarkCompactPrologue(is_compacting);
ThreadManager::MarkCompactPrologue(is_compacting);
}
void Heap::MarkCompactEpilogue(bool is_compacting) {
Top::MarkCompactEpilogue(is_compacting);
ThreadManager::MarkCompactEpilogue(is_compacting);
}
Object* Heap::FindCodeObject(Address a) {
Object* obj = code_space_->FindObject(a);
if (obj->IsFailure()) {
obj = lo_space_->FindObject(a);
}
ASSERT(!obj->IsFailure());
return obj;
}
// Helper class for copying HeapObjects
class ScavengeVisitor: public ObjectVisitor {
public:
void VisitPointer(Object** p) { ScavengePointer(p); }
void VisitPointers(Object** start, Object** end) {
// Copy all HeapObject pointers in [start, end)
for (Object** p = start; p < end; p++) ScavengePointer(p);
}
private:
void ScavengePointer(Object** p) {
Object* object = *p;
if (!Heap::InNewSpace(object)) return;
Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
reinterpret_cast<HeapObject*>(object));
}
};
// A queue of pointers and maps of to-be-promoted objects during a
// scavenge collection.
class PromotionQueue {
public:
void Initialize(Address start_address) {
front_ = rear_ = reinterpret_cast<HeapObject**>(start_address);
}
bool is_empty() { return front_ <= rear_; }
void insert(HeapObject* object, Map* map) {
*(--rear_) = object;
*(--rear_) = map;
// Assert no overflow into live objects.
ASSERT(reinterpret_cast<Address>(rear_) >= Heap::new_space()->top());
}
void remove(HeapObject** object, Map** map) {
*object = *(--front_);
*map = Map::cast(*(--front_));
// Assert no underflow.
ASSERT(front_ >= rear_);
}
private:
// The front of the queue is higher in memory than the rear.
HeapObject** front_;
HeapObject** rear_;
};
// Shared state read by the scavenge collector and set by ScavengeObject.
static PromotionQueue promotion_queue;
#ifdef DEBUG
// Visitor class to verify pointers in code or data space do not point into
// new space.
class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
public:
void VisitPointers(Object** start, Object**end) {
for (Object** current = start; current < end; current++) {
if ((*current)->IsHeapObject()) {
ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
}
}
}
};
static void VerifyNonPointerSpacePointers() {
// Verify that there are no pointers to new space in spaces where we
// do not expect them.
VerifyNonPointerSpacePointersVisitor v;
HeapObjectIterator code_it(Heap::code_space());
while (code_it.has_next()) {
HeapObject* object = code_it.next();
object->Iterate(&v);
}
HeapObjectIterator data_it(Heap::old_data_space());
while (data_it.has_next()) data_it.next()->Iterate(&v);
}
#endif
void Heap::Scavenge() {
#ifdef DEBUG
if (FLAG_enable_slow_asserts) VerifyNonPointerSpacePointers();
#endif
gc_state_ = SCAVENGE;
// Implements Cheney's copying algorithm
LOG(ResourceEvent("scavenge", "begin"));
// Clear descriptor cache.
DescriptorLookupCache::Clear();
// Used for updating survived_since_last_expansion_ at function end.
int survived_watermark = PromotedSpaceSize();
if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
survived_since_last_expansion_ > new_space_.Capacity()) {
// Grow the size of new space if there is room to grow and enough
// data has survived scavenge since the last expansion.
new_space_.Grow();
survived_since_last_expansion_ = 0;
}
// Flip the semispaces. After flipping, to space is empty, from space has
// live objects.
new_space_.Flip();
new_space_.ResetAllocationInfo();
// We need to sweep newly copied objects which can be either in the
// to space or promoted to the old generation. For to-space
// objects, we treat the bottom of the to space as a queue. Newly
// copied and unswept objects lie between a 'front' mark and the
// allocation pointer.
//
// Promoted objects can go into various old-generation spaces, and
// can be allocated internally in the spaces (from the free list).
// We treat the top of the to space as a queue of addresses of
// promoted objects. The addresses of newly promoted and unswept
// objects lie between a 'front' mark and a 'rear' mark that is
// updated as a side effect of promoting an object.
//
// There is guaranteed to be enough room at the top of the to space
// for the addresses of promoted objects: every object promoted
// frees up its size in bytes from the top of the new space, and
// objects are at least one pointer in size.
Address new_space_front = new_space_.ToSpaceLow();
promotion_queue.Initialize(new_space_.ToSpaceHigh());
ScavengeVisitor scavenge_visitor;
// Copy roots.
IterateRoots(&scavenge_visitor);
// Copy objects reachable from weak pointers.
GlobalHandles::IterateWeakRoots(&scavenge_visitor);
// Copy objects reachable from the old generation. By definition,
// there are no intergenerational pointers in code or data spaces.
IterateRSet(old_pointer_space_, &ScavengePointer);
IterateRSet(map_space_, &ScavengePointer);
lo_space_->IterateRSet(&ScavengePointer);
// Copy objects reachable from cells by scavenging cell values directly.
HeapObjectIterator cell_iterator(cell_space_);
while (cell_iterator.has_next()) {
HeapObject* cell = cell_iterator.next();
if (cell->IsJSGlobalPropertyCell()) {
Address value_address =
reinterpret_cast<Address>(cell) +
(JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
}
}
do {
ASSERT(new_space_front <= new_space_.top());
// The addresses new_space_front and new_space_.top() define a
// queue of unprocessed copied objects. Process them until the
// queue is empty.
while (new_space_front < new_space_.top()) {
HeapObject* object = HeapObject::FromAddress(new_space_front);
object->Iterate(&scavenge_visitor);
new_space_front += object->Size();
}
// Promote and process all the to-be-promoted objects.
while (!promotion_queue.is_empty()) {
HeapObject* source;
Map* map;
promotion_queue.remove(&source, &map);
// Copy the from-space object to its new location (given by the
// forwarding address) and fix its map.
HeapObject* target = source->map_word().ToForwardingAddress();
CopyBlock(reinterpret_cast<Object**>(target->address()),
reinterpret_cast<Object**>(source->address()),
source->SizeFromMap(map));
target->set_map(map);
#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
// Update NewSpace stats if necessary.
RecordCopiedObject(target);
#endif
// Visit the newly copied object for pointers to new space.
target->Iterate(&scavenge_visitor);
UpdateRSet(target);
}
// Take another spin if there are now unswept objects in new space
// (there are currently no more unswept promoted objects).
} while (new_space_front < new_space_.top());
// Set age mark.
new_space_.set_age_mark(new_space_.top());
// Update how much has survived scavenge.
survived_since_last_expansion_ +=
(PromotedSpaceSize() - survived_watermark) + new_space_.Size();
LOG(ResourceEvent("scavenge", "end"));
gc_state_ = NOT_IN_GC;
}
void Heap::ClearRSetRange(Address start, int size_in_bytes) {
uint32_t start_bit;
Address start_word_address =
Page::ComputeRSetBitPosition(start, 0, &start_bit);
uint32_t end_bit;
Address end_word_address =
Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
0,
&end_bit);
// We want to clear the bits in the starting word starting with the
// first bit, and in the ending word up to and including the last
// bit. Build a pair of bitmasks to do that.
uint32_t start_bitmask = start_bit - 1;
uint32_t end_bitmask = ~((end_bit << 1) - 1);
// If the start address and end address are the same, we mask that
// word once, otherwise mask the starting and ending word
// separately and all the ones in between.
if (start_word_address == end_word_address) {
Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
} else {
Memory::uint32_at(start_word_address) &= start_bitmask;
Memory::uint32_at(end_word_address) &= end_bitmask;
start_word_address += kIntSize;
memset(start_word_address, 0, end_word_address - start_word_address);
}
}
class UpdateRSetVisitor: public ObjectVisitor {
public:
void VisitPointer(Object** p) {
UpdateRSet(p);
}
void VisitPointers(Object** start, Object** end) {
// Update a store into slots [start, end), used (a) to update remembered
// set when promoting a young object to old space or (b) to rebuild
// remembered sets after a mark-compact collection.
for (Object** p = start; p < end; p++) UpdateRSet(p);
}
private:
void UpdateRSet(Object** p) {
// The remembered set should not be set. It should be clear for objects
// newly copied to old space, and it is cleared before rebuilding in the
// mark-compact collector.
ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
if (Heap::InNewSpace(*p)) {
Page::SetRSet(reinterpret_cast<Address>(p), 0);
}
}
};
int Heap::UpdateRSet(HeapObject* obj) {
ASSERT(!InNewSpace(obj));
// Special handling of fixed arrays to iterate the body based on the start
// address and offset. Just iterating the pointers as in UpdateRSetVisitor
// will not work because Page::SetRSet needs to have the start of the
// object for large object pages.
if (obj->IsFixedArray()) {
FixedArray* array = FixedArray::cast(obj);
int length = array->length();
for (int i = 0; i < length; i++) {
int offset = FixedArray::kHeaderSize + i * kPointerSize;
ASSERT(!Page::IsRSetSet(obj->address(), offset));
if (Heap::InNewSpace(array->get(i))) {
Page::SetRSet(obj->address(), offset);
}
}
} else if (!obj->IsCode()) {
// Skip code object, we know it does not contain inter-generational
// pointers.
UpdateRSetVisitor v;
obj->Iterate(&v);
}
return obj->Size();
}
void Heap::RebuildRSets() {
// By definition, we do not care about remembered set bits in code,
// data, or cell spaces.
map_space_->ClearRSet();
RebuildRSets(map_space_);
old_pointer_space_->ClearRSet();
RebuildRSets(old_pointer_space_);
Heap::lo_space_->ClearRSet();
RebuildRSets(lo_space_);
}
void Heap::RebuildRSets(PagedSpace* space) {
HeapObjectIterator it(space);
while (it.has_next()) Heap::UpdateRSet(it.next());
}
void Heap::RebuildRSets(LargeObjectSpace* space) {
LargeObjectIterator it(space);
while (it.has_next()) Heap::UpdateRSet(it.next());
}
#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
void Heap::RecordCopiedObject(HeapObject* obj) {
bool should_record = false;
#ifdef DEBUG
should_record = FLAG_heap_stats;
#endif
#ifdef ENABLE_LOGGING_AND_PROFILING
should_record = should_record || FLAG_log_gc;
#endif
if (should_record) {
if (new_space_.Contains(obj)) {
new_space_.RecordAllocation(obj);
} else {
new_space_.RecordPromotion(obj);
}
}
}
#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
HeapObject* Heap::MigrateObject(HeapObject* source,
HeapObject* target,
int size) {
// Copy the content of source to target.
CopyBlock(reinterpret_cast<Object**>(target->address()),
reinterpret_cast<Object**>(source->address()),
size);
// Set the forwarding address.
source->set_map_word(MapWord::FromForwardingAddress(target));
#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
// Update NewSpace stats if necessary.
RecordCopiedObject(target);
#endif
return target;
}
static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
STATIC_ASSERT(kNotStringTag != 0 && kSymbolTag != 0);
ASSERT(object->map() == map);
InstanceType type = map->instance_type();
if ((type & kShortcutTypeMask) != kShortcutTypeTag) return false;
ASSERT(object->IsString() && !object->IsSymbol());
return ConsString::cast(object)->unchecked_second() == Heap::empty_string();
}
void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
ASSERT(InFromSpace(object));
MapWord first_word = object->map_word();
ASSERT(!first_word.IsForwardingAddress());
// Optimization: Bypass flattened ConsString objects.
if (IsShortcutCandidate(object, first_word.ToMap())) {
object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
*p = object;
// After patching *p we have to repeat the checks that object is in the
// active semispace of the young generation and not already copied.
if (!InNewSpace(object)) return;
first_word = object->map_word();
if (first_word.IsForwardingAddress()) {
*p = first_word.ToForwardingAddress();
return;
}
}
int object_size = object->SizeFromMap(first_word.ToMap());
// We rely on live objects in new space to be at least two pointers,
// so we can store the from-space address and map pointer of promoted
// objects in the to space.
ASSERT(object_size >= 2 * kPointerSize);
// If the object should be promoted, we try to copy it to old space.
if (ShouldBePromoted(object->address(), object_size)) {
Object* result;
if (object_size > MaxObjectSizeInPagedSpace()) {
result = lo_space_->AllocateRawFixedArray(object_size);
if (!result->IsFailure()) {
// Save the from-space object pointer and its map pointer at the
// top of the to space to be swept and copied later. Write the
// forwarding address over the map word of the from-space
// object.
HeapObject* target = HeapObject::cast(result);
promotion_queue.insert(object, first_word.ToMap());
object->set_map_word(MapWord::FromForwardingAddress(target));
// Give the space allocated for the result a proper map by
// treating it as a free list node (not linked into the free
// list).
FreeListNode* node = FreeListNode::FromAddress(target->address());
node->set_size(object_size);
*p = target;
return;
}
} else {
OldSpace* target_space = Heap::TargetSpace(object);
ASSERT(target_space == Heap::old_pointer_space_ ||
target_space == Heap::old_data_space_);
result = target_space->AllocateRaw(object_size);
if (!result->IsFailure()) {
HeapObject* target = HeapObject::cast(result);
if (target_space == Heap::old_pointer_space_) {
// Save the from-space object pointer and its map pointer at the
// top of the to space to be swept and copied later. Write the
// forwarding address over the map word of the from-space
// object.
promotion_queue.insert(object, first_word.ToMap());
object->set_map_word(MapWord::FromForwardingAddress(target));
// Give the space allocated for the result a proper map by
// treating it as a free list node (not linked into the free
// list).
FreeListNode* node = FreeListNode::FromAddress(target->address());
node->set_size(object_size);
*p = target;
} else {
// Objects promoted to the data space can be copied immediately
// and not revisited---we will never sweep that space for
// pointers and the copied objects do not contain pointers to
// new space objects.
*p = MigrateObject(object, target, object_size);
#ifdef DEBUG
VerifyNonPointerSpacePointersVisitor v;
(*p)->Iterate(&v);
#endif
}
return;
}
}
}
// The object should remain in new space or the old space allocation failed.
Object* result = new_space_.AllocateRaw(object_size);
// Failed allocation at this point is utterly unexpected.
ASSERT(!result->IsFailure());
*p = MigrateObject(object, HeapObject::cast(result), object_size);
}
void Heap::ScavengePointer(HeapObject** p) {
ScavengeObject(p, *p);
}
Object* Heap::AllocatePartialMap(InstanceType instance_type,
int instance_size) {
Object* result = AllocateRawMap();
if (result->IsFailure()) return result;
// Map::cast cannot be used due to uninitialized map field.
reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
reinterpret_cast<Map*>(result)->set_inobject_properties(0);
reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
return result;
}
Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
Object* result = AllocateRawMap();
if (result->IsFailure()) return result;
Map* map = reinterpret_cast<Map*>(result);
map->set_map(meta_map());
map->set_instance_type(instance_type);
map->set_prototype(null_value());
map->set_constructor(null_value());
map->set_instance_size(instance_size);
map->set_inobject_properties(0);
map->set_pre_allocated_property_fields(0);
map->set_instance_descriptors(empty_descriptor_array());
map->set_code_cache(empty_fixed_array());
map->set_unused_property_fields(0);
map->set_bit_field(0);
map->set_bit_field2(0);
return map;
}
const Heap::StringTypeTable Heap::string_type_table[] = {
#define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
{type, size, k##camel_name##MapRootIndex},
STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
#undef STRING_TYPE_ELEMENT
};
const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
#define CONSTANT_SYMBOL_ELEMENT(name, contents) \
{contents, k##name##RootIndex},
SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
#undef CONSTANT_SYMBOL_ELEMENT
};
const Heap::StructTable Heap::struct_table[] = {
#define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
{ NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
STRUCT_LIST(STRUCT_TABLE_ELEMENT)
#undef STRUCT_TABLE_ELEMENT
};
bool Heap::CreateInitialMaps() {
Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
if (obj->IsFailure()) return false;
// Map::cast cannot be used due to uninitialized map field.
Map* new_meta_map = reinterpret_cast<Map*>(obj);
set_meta_map(new_meta_map);
new_meta_map->set_map(new_meta_map);
obj = AllocatePartialMap(FIXED_ARRAY_TYPE, FixedArray::kHeaderSize);
if (obj->IsFailure()) return false;
set_fixed_array_map(Map::cast(obj));
obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
if (obj->IsFailure()) return false;
set_oddball_map(Map::cast(obj));
// Allocate the empty array
obj = AllocateEmptyFixedArray();
if (obj->IsFailure()) return false;
set_empty_fixed_array(FixedArray::cast(obj));
obj = Allocate(oddball_map(), OLD_DATA_SPACE);
if (obj->IsFailure()) return false;
set_null_value(obj);
// Allocate the empty descriptor array.
obj = AllocateEmptyFixedArray();
if (obj->IsFailure()) return false;
set_empty_descriptor_array(DescriptorArray::cast(obj));
// Fix the instance_descriptors for the existing maps.
meta_map()->set_instance_descriptors(empty_descriptor_array());
meta_map()->set_code_cache(empty_fixed_array());
fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
fixed_array_map()->set_code_cache(empty_fixed_array());
oddball_map()->set_instance_descriptors(empty_descriptor_array());
oddball_map()->set_code_cache(empty_fixed_array());
// Fix prototype object for existing maps.
meta_map()->set_prototype(null_value());
meta_map()->set_constructor(null_value());
fixed_array_map()->set_prototype(null_value());
fixed_array_map()->set_constructor(null_value());
oddball_map()->set_prototype(null_value());
oddball_map()->set_constructor(null_value());
obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
if (obj->IsFailure()) return false;
set_heap_number_map(Map::cast(obj));
obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
if (obj->IsFailure()) return false;
set_proxy_map(Map::cast(obj));
for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
const StringTypeTable& entry = string_type_table[i];
obj = AllocateMap(entry.type, entry.size);
if (obj->IsFailure()) return false;
roots_[entry.index] = Map::cast(obj);
}
obj = AllocateMap(SHORT_STRING_TYPE, SeqTwoByteString::kAlignedSize);
if (obj->IsFailure()) return false;
set_undetectable_short_string_map(Map::cast(obj));
Map::cast(obj)->set_is_undetectable();
obj = AllocateMap(MEDIUM_STRING_TYPE, SeqTwoByteString::kAlignedSize);
if (obj->IsFailure()) return false;
set_undetectable_medium_string_map(Map::cast(obj));
Map::cast(obj)->set_is_undetectable();
obj = AllocateMap(LONG_STRING_TYPE, SeqTwoByteString::kAlignedSize);
if (obj->IsFailure()) return false;
set_undetectable_long_string_map(Map::cast(obj));
Map::cast(obj)->set_is_undetectable();
obj = AllocateMap(SHORT_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
if (obj->IsFailure()) return false;
set_undetectable_short_ascii_string_map(Map::cast(obj));
Map::cast(obj)->set_is_undetectable();
obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
if (obj->IsFailure()) return false;
set_undetectable_medium_ascii_string_map(Map::cast(obj));
Map::cast(obj)->set_is_undetectable();
obj = AllocateMap(LONG_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
if (obj->IsFailure()) return false;
set_undetectable_long_ascii_string_map(Map::cast(obj));
Map::cast(obj)->set_is_undetectable();
obj = AllocateMap(BYTE_ARRAY_TYPE, ByteArray::kAlignedSize);
if (obj->IsFailure()) return false;
set_byte_array_map(Map::cast(obj));
obj = AllocateMap(PIXEL_ARRAY_TYPE, PixelArray::kAlignedSize);
if (obj->IsFailure()) return false;
set_pixel_array_map(Map::cast(obj));
obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
if (obj->IsFailure()) return false;
set_code_map(Map::cast(obj));
obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
JSGlobalPropertyCell::kSize);
if (obj->IsFailure()) return false;
set_global_property_cell_map(Map::cast(obj));
obj = AllocateMap(FILLER_TYPE, kPointerSize);
if (obj->IsFailure()) return false;
set_one_pointer_filler_map(Map::cast(obj));
obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
if (obj->IsFailure()) return false;
set_two_pointer_filler_map(Map::cast(obj));
for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
const StructTable& entry = struct_table[i];
obj = AllocateMap(entry.type, entry.size);
if (obj->IsFailure()) return false;
roots_[entry.index] = Map::cast(obj);
}
obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
if (obj->IsFailure()) return false;
set_hash_table_map(Map::cast(obj));
obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
if (obj->IsFailure()) return false;
set_context_map(Map::cast(obj));
obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
if (obj->IsFailure()) return false;
set_catch_context_map(Map::cast(obj));
obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
if (obj->IsFailure()) return false;
set_global_context_map(Map::cast(obj));
obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
if (obj->IsFailure()) return false;
set_boilerplate_function_map(Map::cast(obj));
obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
if (obj->IsFailure()) return false;
set_shared_function_info_map(Map::cast(obj));
ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
return true;
}
Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
// Statically ensure that it is safe to allocate heap numbers in paged
// spaces.
STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
// New space can't cope with forced allocation.
if (always_allocate()) space = OLD_DATA_SPACE;
Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
if (result->IsFailure()) return result;
HeapObject::cast(result)->set_map(heap_number_map());
HeapNumber::cast(result)->set_value(value);
return result;
}
Object* Heap::AllocateHeapNumber(double value) {
// Use general version, if we're forced to always allocate.
if (always_allocate()) return AllocateHeapNumber(value, TENURED);
// This version of AllocateHeapNumber is optimized for
// allocation in new space.
STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
if (result->IsFailure()) return result;
HeapObject::cast(result)->set_map(heap_number_map());
HeapNumber::cast(result)->set_value(value);
return result;
}
Object* Heap::AllocateJSGlobalPropertyCell(Object* value) {
Object* result = AllocateRawCell();
if (result->IsFailure()) return result;
HeapObject::cast(result)->set_map(global_property_cell_map());
JSGlobalPropertyCell::cast(result)->set_value(value);
return result;
}
Object* Heap::CreateOddball(Map* map,
const char* to_string,
Object* to_number) {
Object* result = Allocate(map, OLD_DATA_SPACE);
if (result->IsFailure()) return result;
return Oddball::cast(result)->Initialize(to_string, to_number);
}
bool Heap::CreateApiObjects() {
Object* obj;
obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
if (obj->IsFailure()) return false;
set_neander_map(Map::cast(obj));
obj = Heap::AllocateJSObjectFromMap(neander_map());
if (obj->IsFailure()) return false;
Object* elements = AllocateFixedArray(2);
if (elements->IsFailure()) return false;
FixedArray::cast(elements)->set(0, Smi::FromInt(0));
JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
set_message_listeners(JSObject::cast(obj));
return true;
}
void Heap::CreateCEntryStub() {
CEntryStub stub(1);
set_c_entry_code(*stub.GetCode());
}
#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
void Heap::CreateRegExpCEntryStub() {
RegExpCEntryStub stub;
set_re_c_entry_code(*stub.GetCode());
}
#endif
void Heap::CreateCEntryDebugBreakStub() {
CEntryDebugBreakStub stub;
set_c_entry_debug_break_code(*stub.GetCode());
}
void Heap::CreateJSEntryStub() {
JSEntryStub stub;
set_js_entry_code(*stub.GetCode());
}
void Heap::CreateJSConstructEntryStub() {
JSConstructEntryStub stub;
set_js_construct_entry_code(*stub.GetCode());
}
void Heap::CreateFixedStubs() {
// Here we create roots for fixed stubs. They are needed at GC
// for cooking and uncooking (check out frames.cc).
// The eliminates the need for doing dictionary lookup in the
// stub cache for these stubs.
HandleScope scope;
// gcc-4.4 has problem generating correct code of following snippet:
// { CEntryStub stub;
// c_entry_code_ = *stub.GetCode();
// }
// { CEntryDebugBreakStub stub;
// c_entry_debug_break_code_ = *stub.GetCode();
// }
// To workaround the problem, make separate functions without inlining.
Heap::CreateCEntryStub();
Heap::CreateCEntryDebugBreakStub();
Heap::CreateJSEntryStub();
Heap::CreateJSConstructEntryStub();
#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
Heap::CreateRegExpCEntryStub();
#endif
}
bool Heap::CreateInitialObjects() {
Object* obj;
// The -0 value must be set before NumberFromDouble works.
obj = AllocateHeapNumber(-0.0, TENURED);
if (obj->IsFailure()) return false;
set_minus_zero_value(obj);
ASSERT(signbit(minus_zero_value()->Number()) != 0);
obj = AllocateHeapNumber(OS::nan_value(), TENURED);
if (obj->IsFailure()) return false;
set_nan_value(obj);
obj = Allocate(oddball_map(), OLD_DATA_SPACE);
if (obj->IsFailure()) return false;
set_undefined_value(obj);
ASSERT(!InNewSpace(undefined_value()));
// Allocate initial symbol table.
obj = SymbolTable::Allocate(kInitialSymbolTableSize);
if (obj->IsFailure()) return false;
// Don't use set_symbol_table() due to asserts.
roots_[kSymbolTableRootIndex] = obj;
// Assign the print strings for oddballs after creating symboltable.
Object* symbol = LookupAsciiSymbol("undefined");
if (symbol->IsFailure()) return false;
Oddball::cast(undefined_value())->set_to_string(String::cast(symbol));
Oddball::cast(undefined_value())->set_to_number(nan_value());
// Assign the print strings for oddballs after creating symboltable.
symbol = LookupAsciiSymbol("null");
if (symbol->IsFailure()) return false;
Oddball::cast(null_value())->set_to_string(String::cast(symbol));
Oddball::cast(null_value())->set_to_number(Smi::FromInt(0));
// Allocate the null_value
obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
if (obj->IsFailure()) return false;
obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
if (obj->IsFailure()) return false;
set_true_value(obj);
obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
if (obj->IsFailure()) return false;
set_false_value(obj);
obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
if (obj->IsFailure()) return false;
set_the_hole_value(obj);
obj = CreateOddball(
oddball_map(), "no_interceptor_result_sentinel", Smi::FromInt(-2));
if (obj->IsFailure()) return false;
set_no_interceptor_result_sentinel(obj);
obj = CreateOddball(oddball_map(), "termination_exception", Smi::FromInt(-3));
if (obj->IsFailure()) return false;
set_termination_exception(obj);
// Allocate the empty string.
obj = AllocateRawAsciiString(0, TENURED);
if (obj->IsFailure()) return false;
set_empty_string(String::cast(obj));
for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
obj = LookupAsciiSymbol(constant_symbol_table[i].contents);
if (obj->IsFailure()) return false;
roots_[constant_symbol_table[i].index] = String::cast(obj);
}
// Allocate the hidden symbol which is used to identify the hidden properties
// in JSObjects. The hash code has a special value so that it will not match
// the empty string when searching for the property. It cannot be part of the
// loop above because it needs to be allocated manually with the special
// hash code in place. The hash code for the hidden_symbol is zero to ensure
// that it will always be at the first entry in property descriptors.
obj = AllocateSymbol(CStrVector(""), 0, String::kHashComputedMask);
if (obj->IsFailure()) return false;
hidden_symbol_ = String::cast(obj);
// Allocate the proxy for __proto__.
obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
if (obj->IsFailure()) return false;
set_prototype_accessors(Proxy::cast(obj));
// Allocate the code_stubs dictionary. The initial size is set to avoid
// expanding the dictionary during bootstrapping.
obj = NumberDictionary::Allocate(128);
if (obj->IsFailure()) return false;
set_code_stubs(NumberDictionary::cast(obj));
// Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
// is set to avoid expanding the dictionary during bootstrapping.
obj = NumberDictionary::Allocate(64);
if (obj->IsFailure()) return false;
set_non_monomorphic_cache(NumberDictionary::cast(obj));
CreateFixedStubs();
// Allocate the number->string conversion cache
obj = AllocateFixedArray(kNumberStringCacheSize * 2);
if (obj->IsFailure()) return false;
set_number_string_cache(FixedArray::cast(obj));
// Allocate cache for single character strings.
obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
if (obj->IsFailure()) return false;
set_single_character_string_cache(FixedArray::cast(obj));
// Allocate cache for external strings pointing to native source code.
obj = AllocateFixedArray(Natives::GetBuiltinsCount());
if (obj->IsFailure()) return false;
set_natives_source_cache(FixedArray::cast(obj));
// Handling of script id generation is in Factory::NewScript.
set_last_script_id(undefined_value());
// Initialize keyed lookup cache.
KeyedLookupCache::Clear();
// Initialize context slot cache.
ContextSlotCache::Clear();
// Initialize descriptor cache.
DescriptorLookupCache::Clear();
// Initialize compilation cache.
CompilationCache::Clear();
return true;
}
static inline int double_get_hash(double d) {
DoubleRepresentation rep(d);
return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
(Heap::kNumberStringCacheSize - 1));
}
static inline int smi_get_hash(Smi* smi) {
return (smi->value() & (Heap::kNumberStringCacheSize - 1));
}
Object* Heap::GetNumberStringCache(Object* number) {
int hash;
if (number->IsSmi()) {
hash = smi_get_hash(Smi::cast(number));
} else {
hash = double_get_hash(number->Number());
}
Object* key = number_string_cache()->get(hash * 2);
if (key == number) {
return String::cast(number_string_cache()->get(hash * 2 + 1));
} else if (key->IsHeapNumber() &&
number->IsHeapNumber() &&
key->Number() == number->Number()) {
return String::cast(number_string_cache()->get(hash * 2 + 1));
}
return undefined_value();
}
void Heap::SetNumberStringCache(Object* number, String* string) {
int hash;
if (number->IsSmi()) {
hash = smi_get_hash(Smi::cast(number));
number_string_cache()->set(hash * 2, number, SKIP_WRITE_BARRIER);
} else {
hash = double_get_hash(number->Number());
number_string_cache()->set(hash * 2, number);
}
number_string_cache()->set(hash * 2 + 1, string);
}
Object* Heap::SmiOrNumberFromDouble(double value,
bool new_object,
PretenureFlag pretenure) {
// We need to distinguish the minus zero value and this cannot be
// done after conversion to int. Doing this by comparing bit
// patterns is faster than using fpclassify() et al.
static const DoubleRepresentation plus_zero(0.0);
static const DoubleRepresentation minus_zero(-0.0);
static const DoubleRepresentation nan(OS::nan_value());
ASSERT(minus_zero_value() != NULL);
ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
DoubleRepresentation rep(value);
if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
if (rep.bits == minus_zero.bits) {
return new_object ? AllocateHeapNumber(-0.0, pretenure)
: minus_zero_value();
}
if (rep.bits == nan.bits) {
return new_object
? AllocateHeapNumber(OS::nan_value(), pretenure)
: nan_value();
}
// Try to represent the value as a tagged small integer.
int int_value = FastD2I(value);
if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
return Smi::FromInt(int_value);
}
// Materialize the value in the heap.
return AllocateHeapNumber(value, pretenure);
}
Object* Heap::NumberToString(Object* number) {
Object* cached = GetNumberStringCache(number);
if (cached != undefined_value()) {
return cached;
}
char arr[100];
Vector<char> buffer(arr, ARRAY_SIZE(arr));
const char* str;
if (number->IsSmi()) {
int num = Smi::cast(number)->value();
str = IntToCString(num, buffer);
} else {
double num = HeapNumber::cast(number)->value();
str = DoubleToCString(num, buffer);
}
Object* result = AllocateStringFromAscii(CStrVector(str));
if (!result->IsFailure()) {
SetNumberStringCache(number, String::cast(result));
}
return result;
}
Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
return SmiOrNumberFromDouble(value,
true /* number object must be new */,
pretenure);
}
Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
return SmiOrNumberFromDouble(value,
false /* use preallocated NaN, -0.0 */,
pretenure);
}
Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
// Statically ensure that it is safe to allocate proxies in paged spaces.
STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
Object* result = Allocate(proxy_map(), space);
if (result->IsFailure()) return result;
Proxy::cast(result)->set_proxy(proxy);
return result;
}
Object* Heap::AllocateSharedFunctionInfo(Object* name) {
Object* result = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
if (result->IsFailure()) return result;
SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
share->set_name(name);
Code* illegal = Builtins::builtin(Builtins::Illegal);
share->set_code(illegal);
Code* construct_stub = Builtins::builtin(Builtins::JSConstructStubGeneric);
share->set_construct_stub(construct_stub);
share->set_expected_nof_properties(0);
share->set_length(0);
share->set_formal_parameter_count(0);
share->set_instance_class_name(Object_symbol());
share->set_function_data(undefined_value());
share->set_script(undefined_value());
share->set_start_position_and_type(0);
share->set_debug_info(undefined_value());
share->set_inferred_name(empty_string());
share->set_compiler_hints(0);
share->set_this_property_assignments_count(0);
share->set_this_property_assignments(undefined_value());
return result;
}
Object* Heap::AllocateConsString(String* first, String* second) {
int first_length = first->length();
if (first_length == 0) return second;
int second_length = second->length();
if (second_length == 0) return first;
int length = first_length + second_length;
bool is_ascii = first->IsAsciiRepresentation()
&& second->IsAsciiRepresentation();
// Make sure that an out of memory exception is thrown if the length
// of the new cons string is too large to fit in a Smi.
if (length > Smi::kMaxValue || length < -0) {
Top::context()->mark_out_of_memory();
return Failure::OutOfMemoryException();
}
// If the resulting string is small make a flat string.
if (length < String::kMinNonFlatLength) {
ASSERT(first->IsFlat());
ASSERT(second->IsFlat());
if (is_ascii) {
Object* result = AllocateRawAsciiString(length);
if (result->IsFailure()) return result;
// Copy the characters into the new object.
char* dest = SeqAsciiString::cast(result)->GetChars();
// Copy first part.
char* src = SeqAsciiString::cast(first)->GetChars();
for (int i = 0; i < first_length; i++) *dest++ = src[i];
// Copy second part.
src = SeqAsciiString::cast(second)->GetChars();
for (int i = 0; i < second_length; i++) *dest++ = src[i];
return result;
} else {
Object* result = AllocateRawTwoByteString(length);
if (result->IsFailure()) return result;
// Copy the characters into the new object.
uc16* dest = SeqTwoByteString::cast(result)->GetChars();
String::WriteToFlat(first, dest, 0, first_length);
String::WriteToFlat(second, dest + first_length, 0, second_length);
return result;
}
}
Map* map;
if (length <= String::kMaxShortStringSize) {
map = is_ascii ? short_cons_ascii_string_map()
: short_cons_string_map();
} else if (length <= String::kMaxMediumStringSize) {
map = is_ascii ? medium_cons_ascii_string_map()
: medium_cons_string_map();
} else {
map = is_ascii ? long_cons_ascii_string_map()
: long_cons_string_map();
}
Object* result = Allocate(map, NEW_SPACE);
if (result->IsFailure()) return result;
ASSERT(InNewSpace(result));
ConsString* cons_string = ConsString::cast(result);
cons_string->set_first(first, SKIP_WRITE_BARRIER);
cons_string->set_second(second, SKIP_WRITE_BARRIER);
cons_string->set_length(length);
return result;
}
Object* Heap::AllocateSlicedString(String* buffer,
int start,
int end) {
int length = end - start;
// If the resulting string is small make a sub string.
if (length <= String::kMinNonFlatLength) {
return Heap::AllocateSubString(buffer, start, end);
}
Map* map;
if (length <= String::kMaxShortStringSize) {
map = buffer->IsAsciiRepresentation() ?
short_sliced_ascii_string_map() :
short_sliced_string_map();
} else if (length <= String::kMaxMediumStringSize) {
map = buffer->IsAsciiRepresentation() ?
medium_sliced_ascii_string_map() :
medium_sliced_string_map();
} else {
map = buffer->IsAsciiRepresentation() ?
long_sliced_ascii_string_map() :
long_sliced_string_map();
}
Object* result = Allocate(map, NEW_SPACE);
if (result->IsFailure()) return result;
SlicedString* sliced_string = SlicedString::cast(result);
sliced_string->set_buffer(buffer);
sliced_string->set_start(start);
sliced_string->set_length(length);
return result;
}
Object* Heap::AllocateSubString(String* buffer,
int start,
int end) {
int length = end - start;
if (length == 1) {
return Heap::LookupSingleCharacterStringFromCode(
buffer->Get(start));
}
// Make an attempt to flatten the buffer to reduce access time.
if (!buffer->IsFlat()) {
buffer->TryFlatten();
}
Object* result = buffer->IsAsciiRepresentation()
? AllocateRawAsciiString(length)
: AllocateRawTwoByteString(length);
if (result->IsFailure()) return result;
// Copy the characters into the new object.
String* string_result = String::cast(result);
StringHasher hasher(length);
int i = 0;
for (; i < length && hasher.is_array_index(); i++) {
uc32 c = buffer->Get(start + i);
hasher.AddCharacter(c);
string_result->Set(i, c);
}
for (; i < length; i++) {
uc32 c = buffer->Get(start + i);
hasher.AddCharacterNoIndex(c);
string_result->Set(i, c);
}
string_result->set_length_field(hasher.GetHashField());
return result;
}
Object* Heap::AllocateExternalStringFromAscii(
ExternalAsciiString::Resource* resource) {
Map* map;
int length = resource->length();
if (length <= String::kMaxShortStringSize) {
map = short_external_ascii_string_map();
} else if (length <= String::kMaxMediumStringSize) {
map = medium_external_ascii_string_map();
} else {
map = long_external_ascii_string_map();
}
Object* result = Allocate(map, NEW_SPACE);
if (result->IsFailure()) return result;
ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
external_string->set_length(length);
external_string->set_resource(resource);
return result;
}
Object* Heap::AllocateExternalStringFromTwoByte(
ExternalTwoByteString::Resource* resource) {
int length = resource->length();
Map* map = ExternalTwoByteString::StringMap(length);
Object* result = Allocate(map, NEW_SPACE);
if (result->IsFailure()) return result;
ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
external_string->set_length(length);
external_string->set_resource(resource);
return result;
}
Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
if (code <= String::kMaxAsciiCharCode) {
Object* value = Heap::single_character_string_cache()->get(code);
if (value != Heap::undefined_value()) return value;
char buffer[1];
buffer[0] = static_cast<char>(code);
Object* result = LookupSymbol(Vector<const char>(buffer, 1));
if (result->IsFailure()) return result;
Heap::single_character_string_cache()->set(code, result);
return result;
}
Object* result = Heap::AllocateRawTwoByteString(1);
if (result->IsFailure()) return result;
String* answer = String::cast(result);
answer->Set(0, code);
return answer;
}
Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
if (pretenure == NOT_TENURED) {
return AllocateByteArray(length);
}
int size = ByteArray::SizeFor(length);
AllocationSpace space =
size > MaxObjectSizeInPagedSpace() ? LO_SPACE : OLD_DATA_SPACE;
Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
if (result->IsFailure()) return result;
reinterpret_cast<Array*>(result)->set_map(byte_array_map());
reinterpret_cast<Array*>(result)->set_length(length);
return result;
}
Object* Heap::AllocateByteArray(int length) {
int size = ByteArray::SizeFor(length);
AllocationSpace space =
size > MaxObjectSizeInPagedSpace() ? LO_SPACE : NEW_SPACE;
// New space can't cope with forced allocation.
if (always_allocate()) space = LO_SPACE;
Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
if (result->IsFailure()) return result;
reinterpret_cast<Array*>(result)->set_map(byte_array_map());
reinterpret_cast<Array*>(result)->set_length(length);
return result;
}
void Heap::CreateFillerObjectAt(Address addr, int size) {
if (size == 0) return;
HeapObject* filler = HeapObject::FromAddress(addr);
if (size == kPointerSize) {
filler->set_map(Heap::one_pointer_filler_map());
} else {
filler->set_map(Heap::byte_array_map());
ByteArray::cast(filler)->set_length(ByteArray::LengthFor(size));
}
}
Object* Heap::AllocatePixelArray(int length,
uint8_t* external_pointer,
PretenureFlag pretenure) {
AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
// New space can't cope with forced allocation.
if (always_allocate()) space = OLD_DATA_SPACE;
Object* result = AllocateRaw(PixelArray::kAlignedSize, space, OLD_DATA_SPACE);
if (result->IsFailure()) return result;
reinterpret_cast<PixelArray*>(result)->set_map(pixel_array_map());
reinterpret_cast<PixelArray*>(result)->set_length(length);
reinterpret_cast<PixelArray*>(result)->set_external_pointer(external_pointer);
return result;
}
Object* Heap::CreateCode(const CodeDesc& desc,
ZoneScopeInfo* sinfo,
Code::Flags flags,
Handle<Object> self_reference) {
// Compute size
int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
int sinfo_size = 0;
if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
int obj_size = Code::SizeFor(body_size, sinfo_size);
ASSERT(IsAligned(obj_size, Code::kCodeAlignment));
Object* result;
if (obj_size > MaxObjectSizeInPagedSpace()) {
result = lo_space_->AllocateRawCode(obj_size);
} else {
result = code_space_->AllocateRaw(obj_size);
}
if (result->IsFailure()) return result;
// Initialize the object
HeapObject::cast(result)->set_map(code_map());
Code* code = Code::cast(result);
ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
code->set_instruction_size(desc.instr_size);
code->set_relocation_size(desc.reloc_size);
code->set_sinfo_size(sinfo_size);
code->set_flags(flags);
// Allow self references to created code object by patching the handle to
// point to the newly allocated Code object.
if (!self_reference.is_null()) {
*(self_reference.location()) = code;
}
// Migrate generated code.
// The generated code can contain Object** values (typically from handles)
// that are dereferenced during the copy to point directly to the actual heap
// objects. These pointers can include references to the code object itself,
// through the self_reference parameter.
code->CopyFrom(desc);
if (sinfo != NULL) sinfo->Serialize(code); // write scope info
#ifdef DEBUG
code->Verify();
#endif
return code;
}
Object* Heap::CopyCode(Code* code) {
// Allocate an object the same size as the code object.
int obj_size = code->Size();
Object* result;
if (obj_size > MaxObjectSizeInPagedSpace()) {
result = lo_space_->AllocateRawCode(obj_size);
} else {
result = code_space_->AllocateRaw(obj_size);
}
if (result->IsFailure()) return result;
// Copy code object.
Address old_addr = code->address();
Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
CopyBlock(reinterpret_cast<Object**>(new_addr),
reinterpret_cast<Object**>(old_addr),
obj_size);
// Relocate the copy.
Code* new_code = Code::cast(result);
ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
new_code->Relocate(new_addr - old_addr);
return new_code;
}
Object* Heap::Allocate(Map* map, AllocationSpace space) {
ASSERT(gc_state_ == NOT_IN_GC);
ASSERT(map->instance_type() != MAP_TYPE);
Object* result = AllocateRaw(map->instance_size(),
space,
TargetSpaceId(map->instance_type()));
if (result->IsFailure()) return result;
HeapObject::cast(result)->set_map(map);
return result;
}
Object* Heap::InitializeFunction(JSFunction* function,
SharedFunctionInfo* shared,
Object* prototype) {
ASSERT(!prototype->IsMap());
function->initialize_properties();
function->initialize_elements();
function->set_shared(shared);
function->set_prototype_or_initial_map(prototype);
function->set_context(undefined_value());
function->set_literals(empty_fixed_array(), SKIP_WRITE_BARRIER);
return function;
}
Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
// Allocate the prototype. Make sure to use the object function
// from the function's context, since the function can be from a
// different context.
JSFunction* object_function =
function->context()->global_context()->object_function();
Object* prototype = AllocateJSObject(object_function);
if (prototype->IsFailure()) return prototype;
// When creating the prototype for the function we must set its
// constructor to the function.
Object* result =
JSObject::cast(prototype)->SetProperty(constructor_symbol(),
function,
DONT_ENUM);
if (result->IsFailure()) return result;
return prototype;
}
Object* Heap::AllocateFunction(Map* function_map,
SharedFunctionInfo* shared,
Object* prototype) {
Object* result = Allocate(function_map, OLD_POINTER_SPACE);
if (result->IsFailure()) return result;
return InitializeFunction(JSFunction::cast(result), shared, prototype);
}
Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
// To get fast allocation and map sharing for arguments objects we
// allocate them based on an arguments boilerplate.
// This calls Copy directly rather than using Heap::AllocateRaw so we
// duplicate the check here.
ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
JSObject* boilerplate =
Top::context()->global_context()->arguments_boilerplate();
// Make the clone.
Map* map = boilerplate->map();
int object_size = map->instance_size();
Object* result = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
if (result->IsFailure()) return result;
// Copy the content. The arguments boilerplate doesn't have any
// fields that point to new space so it's safe to skip the write
// barrier here.
CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
reinterpret_cast<Object**>(boilerplate->address()),
object_size);
// Set the two properties.
JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
callee);
JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
Smi::FromInt(length),
SKIP_WRITE_BARRIER);
// Check the state of the object
ASSERT(JSObject::cast(result)->HasFastProperties());
ASSERT(JSObject::cast(result)->HasFastElements());
return result;
}
Object* Heap::AllocateInitialMap(JSFunction* fun) {
ASSERT(!fun->has_initial_map());
// First create a new map with the size and number of in-object properties
// suggested by the function.
int instance_size = fun->shared()->CalculateInstanceSize();
int in_object_properties = fun->shared()->CalculateInObjectProperties();
Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
if (map_obj->IsFailure()) return map_obj;
// Fetch or allocate prototype.
Object* prototype;
if (fun->has_instance_prototype()) {
prototype = fun->instance_prototype();
} else {
prototype = AllocateFunctionPrototype(fun);
if (prototype->IsFailure()) return prototype;
}
Map* map = Map::cast(map_obj);
map->set_inobject_properties(in_object_properties);
map->set_unused_property_fields(in_object_properties);
map->set_prototype(prototype);
// If the function has only simple this property assignments add field
// descriptors for these to the initial map as the object cannot be
// constructed without having these properties.
ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
if (fun->shared()->has_only_this_property_assignments() &&
fun->shared()->this_property_assignments_count() > 0) {
int count = fun->shared()->this_property_assignments_count();
if (count > in_object_properties) {
count = in_object_properties;
}
Object* descriptors_obj = DescriptorArray::Allocate(count);
if (descriptors_obj->IsFailure()) return descriptors_obj;
DescriptorArray* descriptors = DescriptorArray::cast(descriptors_obj);
for (int i = 0; i < count; i++) {
String* name = fun->shared()->GetThisPropertyAssignmentName(i);
ASSERT(name->IsSymbol());
FieldDescriptor field(name, i, NONE);
descriptors->Set(i, &field);
}
descriptors->Sort();
map->set_instance_descriptors(descriptors);
map->set_pre_allocated_property_fields(count);
map->set_unused_property_fields(in_object_properties - count);
}
return map;
}
void Heap::InitializeJSObjectFromMap(JSObject* obj,
FixedArray* properties,
Map* map) {
obj->set_properties(properties);
obj->initialize_elements();
// TODO(1240798): Initialize the object's body using valid initial values
// according to the object's initial map. For example, if the map's
// instance type is JS_ARRAY_TYPE, the length field should be initialized
// to a number (eg, Smi::FromInt(0)) and the elements initialized to a
// fixed array (eg, Heap::empty_fixed_array()). Currently, the object
// verification code has to cope with (temporarily) invalid objects. See
// for example, JSArray::JSArrayVerify).
obj->InitializeBody(map->instance_size());
}
Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
// JSFunctions should be allocated using AllocateFunction to be
// properly initialized.
ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
// Both types of globla objects should be allocated using
// AllocateGloblaObject to be properly initialized.
ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
// Allocate the backing storage for the properties.
int prop_size =
map->pre_allocated_property_fields() +
map->unused_property_fields() -
map->inobject_properties();
ASSERT(prop_size >= 0);
Object* properties = AllocateFixedArray(prop_size, pretenure);
if (properties->IsFailure()) return properties;
// Allocate the JSObject.
AllocationSpace space =
(pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
if (map->instance_size() > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
Object* obj = Allocate(map, space);
if (obj->IsFailure()) return obj;
// Initialize the JSObject.
InitializeJSObjectFromMap(JSObject::cast(obj),
FixedArray::cast(properties),
map);
return obj;
}
Object* Heap::AllocateJSObject(JSFunction* constructor,
PretenureFlag pretenure) {
// Allocate the initial map if absent.
if (!constructor->has_initial_map()) {
Object* initial_map = AllocateInitialMap(constructor);
if (initial_map->IsFailure()) return initial_map;
constructor->set_initial_map(Map::cast(initial_map));
Map::cast(initial_map)->set_constructor(constructor);
}
// Allocate the object based on the constructors initial map.
Object* result =
AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
// Make sure result is NOT a global object if valid.
ASSERT(result->IsFailure() || !result->IsGlobalObject());
return result;
}
Object* Heap::AllocateGlobalObject(JSFunction* constructor) {
ASSERT(constructor->has_initial_map());
Map* map = constructor->initial_map();
// Make sure no field properties are described in the initial map.
// This guarantees us that normalizing the properties does not
// require us to change property values to JSGlobalPropertyCells.
ASSERT(map->NextFreePropertyIndex() == 0);
// Make sure we don't have a ton of pre-allocated slots in the
// global objects. They will be unused once we normalize the object.
ASSERT(map->unused_property_fields() == 0);
ASSERT(map->inobject_properties() == 0);
// Initial size of the backing store to avoid resize of the storage during
// bootstrapping. The size differs between the JS global object ad the
// builtins object.
int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
// Allocate a dictionary object for backing storage.
Object* obj =
StringDictionary::Allocate(
map->NumberOfDescribedProperties() * 2 + initial_size);
if (obj->IsFailure()) return obj;
StringDictionary* dictionary = StringDictionary::cast(obj);
// The global object might be created from an object template with accessors.
// Fill these accessors into the dictionary.
DescriptorArray* descs = map->instance_descriptors();
for (int i = 0; i < descs->number_of_descriptors(); i++) {
PropertyDetails details = descs->GetDetails(i);
ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
PropertyDetails d =
PropertyDetails(details.attributes(), CALLBACKS, details.index());
Object* value = descs->GetCallbacksObject(i);
value = Heap::AllocateJSGlobalPropertyCell(value);
if (value->IsFailure()) return value;
Object* result = dictionary->Add(descs->GetKey(i), value, d);
if (result->IsFailure()) return result;
dictionary = StringDictionary::cast(result);
}
// Allocate the global object and initialize it with the backing store.
obj = Allocate(map, OLD_POINTER_SPACE);
if (obj->IsFailure()) return obj;
JSObject* global = JSObject::cast(obj);
InitializeJSObjectFromMap(global, dictionary, map);
// Create a new map for the global object.
obj = map->CopyDropDescriptors();
if (obj->IsFailure()) return obj;
Map* new_map = Map::cast(obj);
// Setup the global object as a normalized object.
global->set_map(new_map);
global->map()->set_instance_descriptors(Heap::empty_descriptor_array());
global->set_properties(dictionary);
// Make sure result is a global object with properties in dictionary.
ASSERT(global->IsGlobalObject());
ASSERT(!global->HasFastProperties());
return global;
}
Object* Heap::CopyJSObject(JSObject* source) {
// Never used to copy functions. If functions need to be copied we
// have to be careful to clear the literals array.
ASSERT(!source->IsJSFunction());
// Make the clone.
Map* map = source->map();
int object_size = map->instance_size();
Object* clone;
// If we're forced to always allocate, we use the general allocation
// functions which may leave us with an object in old space.
if (always_allocate()) {
clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
if (clone->IsFailure()) return clone;
Address clone_address = HeapObject::cast(clone)->address();
CopyBlock(reinterpret_cast<Object**>(clone_address),
reinterpret_cast<Object**>(source->address()),
object_size);
// Update write barrier for all fields that lie beyond the header.
for (int offset = JSObject::kHeaderSize;
offset < object_size;
offset += kPointerSize) {
RecordWrite(clone_address, offset);
}
} else {
clone = new_space_.AllocateRaw(object_size);
if (clone->IsFailure()) return clone;
ASSERT(Heap::InNewSpace(clone));
// Since we know the clone is allocated in new space, we can copy
// the contents without worrying about updating the write barrier.
CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
reinterpret_cast<Object**>(source->address()),
object_size);
}
FixedArray* elements = FixedArray::cast(source->elements());
FixedArray* properties = FixedArray::cast(source->properties());
// Update elements if necessary.
if (elements->length()> 0) {
Object* elem = CopyFixedArray(elements);
if (elem->IsFailure()) return elem;
JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
}
// Update properties if necessary.
if (properties->length() > 0) {
Object* prop = CopyFixedArray(properties);
if (prop->IsFailure()) return prop;
JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
}
// Return the new clone.
return clone;
}
Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
JSGlobalProxy* object) {
// Allocate initial map if absent.
if (!constructor->has_initial_map()) {
Object* initial_map = AllocateInitialMap(constructor);
if (initial_map->IsFailure()) return initial_map;
constructor->set_initial_map(Map::cast(initial_map));
Map::cast(initial_map)->set_constructor(constructor);
}
Map* map = constructor->initial_map();
// Check that the already allocated object has the same size as
// objects allocated using the constructor.
ASSERT(map->instance_size() == object->map()->instance_size());
// Allocate the backing storage for the properties.
int prop_size = map->unused_property_fields() - map->inobject_properties();
Object* properties = AllocateFixedArray(prop_size, TENURED);
if (properties->IsFailure()) return properties;
// Reset the map for the object.
object->set_map(constructor->initial_map());
// Reinitialize the object from the constructor map.
InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
return object;
}
Object* Heap::AllocateStringFromAscii(Vector<const char> string,
PretenureFlag pretenure) {
Object* result = AllocateRawAsciiString(string.length(), pretenure);
if (result->IsFailure()) return result;
// Copy the characters into the new object.
SeqAsciiString* string_result = SeqAsciiString::cast(result);
for (int i = 0; i < string.length(); i++) {
string_result->SeqAsciiStringSet(i, string[i]);
}
return result;
}
Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
PretenureFlag pretenure) {
// Count the number of characters in the UTF-8 string and check if
// it is an ASCII string.
Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
decoder->Reset(string.start(), string.length());
int chars = 0;
bool is_ascii = true;
while (decoder->has_more()) {
uc32 r = decoder->GetNext();
if (r > String::kMaxAsciiCharCode) is_ascii = false;
chars++;
}
// If the string is ascii, we do not need to convert the characters
// since UTF8 is backwards compatible with ascii.
if (is_ascii) return AllocateStringFromAscii(string, pretenure);
Object* result = AllocateRawTwoByteString(chars, pretenure);
if (result->IsFailure()) return result;
// Convert and copy the characters into the new object.
String* string_result = String::cast(result);
decoder->Reset(string.start(), string.length());
for (int i = 0; i < chars; i++) {
uc32 r = decoder->GetNext();
string_result->Set(i, r);
}
return result;
}
Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
PretenureFlag pretenure) {
// Check if the string is an ASCII string.
int i = 0;
while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
Object* result;
if (i == string.length()) { // It's an ASCII string.
result = AllocateRawAsciiString(string.length(), pretenure);
} else { // It's not an ASCII string.
result = AllocateRawTwoByteString(string.length(), pretenure);
}
if (result->IsFailure()) return result;
// Copy the characters into the new object, which may be either ASCII or
// UTF-16.
String* string_result = String::cast(result);
for (int i = 0; i < string.length(); i++) {
string_result->Set(i, string[i]);
}
return result;
}
Map* Heap::SymbolMapForString(String* string) {
// If the string is in new space it cannot be used as a symbol.
if (InNewSpace(string)) return NULL;
// Find the corresponding symbol map for strings.
Map* map = string->map();
if (map == short_ascii_string_map()) return short_ascii_symbol_map();
if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
if (map == long_ascii_string_map()) return long_ascii_symbol_map();
if (map == short_string_map()) return short_symbol_map();
if (map == medium_string_map()) return medium_symbol_map();
if (map == long_string_map()) return long_symbol_map();
if (map == short_cons_string_map()) return short_cons_symbol_map();
if (map == medium_cons_string_map()) return medium_cons_symbol_map();
if (map == long_cons_string_map()) return long_cons_symbol_map();
if (map == short_cons_ascii_string_map()) {
return short_cons_ascii_symbol_map();
}
if (map == medium_cons_ascii_string_map()) {
return medium_cons_ascii_symbol_map();
}
if (map == long_cons_ascii_string_map()) {
return long_cons_ascii_symbol_map();
}
if (map == short_sliced_string_map()) return short_sliced_symbol_map();
if (map == medium_sliced_string_map()) return medium_sliced_symbol_map();
if (map == long_sliced_string_map()) return long_sliced_symbol_map();
if (map == short_sliced_ascii_string_map()) {
return short_sliced_ascii_symbol_map();
}
if (map == medium_sliced_ascii_string_map()) {
return medium_sliced_ascii_symbol_map();
}
if (map == long_sliced_ascii_string_map()) {
return long_sliced_ascii_symbol_map();
}
if (map == short_external_string_map()) {
return short_external_symbol_map();
}
if (map == medium_external_string_map()) {
return medium_external_symbol_map();
}
if (map == long_external_string_map()) {
return long_external_symbol_map();
}
if (map == short_external_ascii_string_map()) {
return short_external_ascii_symbol_map();
}
if (map == medium_external_ascii_string_map()) {
return medium_external_ascii_symbol_map();
}
if (map == long_external_ascii_string_map()) {
return long_external_ascii_symbol_map();
}
// No match found.
return NULL;
}
Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
int chars,
uint32_t length_field) {
// Ensure the chars matches the number of characters in the buffer.
ASSERT(static_cast<unsigned>(chars) == buffer->Length());
// Determine whether the string is ascii.
bool is_ascii = true;
while (buffer->has_more() && is_ascii) {
if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
}
buffer->Rewind();
// Compute map and object size.
int size;
Map* map;
if (is_ascii) {
if (chars <= String::kMaxShortStringSize) {
map = short_ascii_symbol_map();
} else if (chars <= String::kMaxMediumStringSize) {
map = medium_ascii_symbol_map();
} else {
map = long_ascii_symbol_map();
}
size = SeqAsciiString::SizeFor(chars);
} else {
if (chars <= String::kMaxShortStringSize) {
map = short_symbol_map();
} else if (chars <= String::kMaxMediumStringSize) {
map = medium_symbol_map();
} else {
map = long_symbol_map();
}
size = SeqTwoByteString::SizeFor(chars);
}
// Allocate string.
AllocationSpace space =
(size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_DATA_SPACE;
Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
if (result->IsFailure()) return result;
reinterpret_cast<HeapObject*>(result)->set_map(map);
// The hash value contains the length of the string.
String* answer = String::cast(result);
answer->set_length_field(length_field);
ASSERT_EQ(size, answer->Size());
// Fill in the characters.
for (int i = 0; i < chars; i++) {
answer->Set(i, buffer->GetNext());
}
return answer;
}
Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
// New space can't cope with forced allocation.
if (always_allocate()) space = OLD_DATA_SPACE;
int size = SeqAsciiString::SizeFor(length);
Object* result = Failure::OutOfMemoryException();
if (space == NEW_SPACE) {
result = size <= kMaxObjectSizeInNewSpace
? new_space_.AllocateRaw(size)
: lo_space_->AllocateRaw(size);
} else {
if (size > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
result = AllocateRaw(size, space, OLD_DATA_SPACE);
}
if (result->IsFailure()) return result;
// Determine the map based on the string's length.
Map* map;
if (length <= String::kMaxShortStringSize) {
map = short_ascii_string_map();
} else if (length <= String::kMaxMediumStringSize) {
map = medium_ascii_string_map();
} else {
map = long_ascii_string_map();
}
// Partially initialize the object.
HeapObject::cast(result)->set_map(map);
String::cast(result)->set_length(length);
ASSERT_EQ(size, HeapObject::cast(result)->Size());
return result;
}
Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
// New space can't cope with forced allocation.
if (always_allocate()) space = OLD_DATA_SPACE;
int size = SeqTwoByteString::SizeFor(length);
Object* result = Failure::OutOfMemoryException();
if (space == NEW_SPACE) {
result = size <= kMaxObjectSizeInNewSpace
? new_space_.AllocateRaw(size)
: lo_space_->AllocateRaw(size);
} else {
if (size > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
result = AllocateRaw(size, space, OLD_DATA_SPACE);
}
if (result->IsFailure()) return result;
// Determine the map based on the string's length.
Map* map;
if (length <= String::kMaxShortStringSize) {
map = short_string_map();
} else if (length <= String::kMaxMediumStringSize) {
map = medium_string_map();
} else {
map = long_string_map();
}
// Partially initialize the object.
HeapObject::cast(result)->set_map(map);
String::cast(result)->set_length(length);
ASSERT_EQ(size, HeapObject::cast(result)->Size());
return result;
}
Object* Heap::AllocateEmptyFixedArray() {
int size = FixedArray::SizeFor(0);
Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
if (result->IsFailure()) return result;
// Initialize the object.
reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
reinterpret_cast<Array*>(result)->set_length(0);
return result;
}
Object* Heap::AllocateRawFixedArray(int length) {
// Use the general function if we're forced to always allocate.
if (always_allocate()) return AllocateFixedArray(length, TENURED);
// Allocate the raw data for a fixed array.
int size = FixedArray::SizeFor(length);
return size <= kMaxObjectSizeInNewSpace
? new_space_.AllocateRaw(size)
: lo_space_->AllocateRawFixedArray(size);
}
Object* Heap::CopyFixedArray(FixedArray* src) {
int len = src->length();
Object* obj = AllocateRawFixedArray(len);
if (obj->IsFailure()) return obj;
if (Heap::InNewSpace(obj)) {
HeapObject* dst = HeapObject::cast(obj);
CopyBlock(reinterpret_cast<Object**>(dst->address()),
reinterpret_cast<Object**>(src->address()),
FixedArray::SizeFor(len));
return obj;
}
HeapObject::cast(obj)->set_map(src->map());
FixedArray* result = FixedArray::cast(obj);
result->set_length(len);
// Copy the content
WriteBarrierMode mode = result->GetWriteBarrierMode();
for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
return result;
}
Object* Heap::AllocateFixedArray(int length) {
ASSERT(length >= 0);
if (length == 0) return empty_fixed_array();
Object* result = AllocateRawFixedArray(length);
if (!result->IsFailure()) {
// Initialize header.
reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
FixedArray* array = FixedArray::cast(result);
array->set_length(length);
Object* value = undefined_value();
// Initialize body.
for (int index = 0; index < length; index++) {
array->set(index, value, SKIP_WRITE_BARRIER);
}
}
return result;
}
Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
ASSERT(empty_fixed_array()->IsFixedArray());
if (length == 0) return empty_fixed_array();
// New space can't cope with forced allocation.
if (always_allocate()) pretenure = TENURED;
int size = FixedArray::SizeFor(length);
Object* result = Failure::OutOfMemoryException();
if (pretenure != TENURED) {
result = size <= kMaxObjectSizeInNewSpace
? new_space_.AllocateRaw(size)
: lo_space_->AllocateRawFixedArray(size);
}
if (result->IsFailure()) {
if (size > MaxObjectSizeInPagedSpace()) {
result = lo_space_->AllocateRawFixedArray(size);
} else {
AllocationSpace space =
(pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
result = AllocateRaw(size, space, OLD_POINTER_SPACE);
}
if (result->IsFailure()) return result;
}
// Initialize the object.
reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
FixedArray* array = FixedArray::cast(result);
array->set_length(length);
Object* value = undefined_value();
for (int index = 0; index < length; index++) {
array->set(index, value, SKIP_WRITE_BARRIER);
}
return array;
}
Object* Heap::AllocateFixedArrayWithHoles(int length) {
if (length == 0) return empty_fixed_array();
Object* result = AllocateRawFixedArray(length);
if (!result->IsFailure()) {
// Initialize header.
reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
FixedArray* array = FixedArray::cast(result);
array->set_length(length);
// Initialize body.
Object* value = the_hole_value();
for (int index = 0; index < length; index++) {
array->set(index, value, SKIP_WRITE_BARRIER);
}
}
return result;
}
Object* Heap::AllocateHashTable(int length) {
Object* result = Heap::AllocateFixedArray(length);
if (result->IsFailure()) return result;
reinterpret_cast<Array*>(result)->set_map(hash_table_map());
ASSERT(result->IsHashTable());
return result;
}
Object* Heap::AllocateGlobalContext() {
Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
if (result->IsFailure()) return result;
Context* context = reinterpret_cast<Context*>(result);
context->set_map(global_context_map());
ASSERT(context->IsGlobalContext());
ASSERT(result->IsContext());
return result;
}
Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
Object* result = Heap::AllocateFixedArray(length);
if (result->IsFailure()) return result;
Context* context = reinterpret_cast<Context*>(result);
context->set_map(context_map());
context->set_closure(function);
context->set_fcontext(context);
context->set_previous(NULL);
context->set_extension(NULL);
context->set_global(function->context()->global());
ASSERT(!context->IsGlobalContext());
ASSERT(context->is_function_context());
ASSERT(result->IsContext());
return result;
}
Object* Heap::AllocateWithContext(Context* previous,
JSObject* extension,
bool is_catch_context) {
Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
if (result->IsFailure()) return result;
Context* context = reinterpret_cast<Context*>(result);
context->set_map(is_catch_context ? catch_context_map() : context_map());
context->set_closure(previous->closure());
context->set_fcontext(previous->fcontext());
context->set_previous(previous);
context->set_extension(extension);
context->set_global(previous->global());
ASSERT(!context->IsGlobalContext());
ASSERT(!context->is_function_context());
ASSERT(result->IsContext());
return result;
}
Object* Heap::AllocateStruct(InstanceType type) {
Map* map;
switch (type) {
#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
STRUCT_LIST(MAKE_CASE)
#undef MAKE_CASE
default:
UNREACHABLE();
return Failure::InternalError();
}
int size = map->instance_size();
AllocationSpace space =
(size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_POINTER_SPACE;
Object* result = Heap::Allocate(map, space);
if (result->IsFailure()) return result;
Struct::cast(result)->InitializeBody(size);
return result;
}
bool Heap::IdleNotification() {
static const int kIdlesBeforeScavenge = 4;
static const int kIdlesBeforeMarkSweep = 7;
static const int kIdlesBeforeMarkCompact = 8;
static int number_idle_notifications = 0;
static int last_gc_count = gc_count_;
bool finished = false;
if (last_gc_count == gc_count_) {
number_idle_notifications++;
} else {
number_idle_notifications = 0;
last_gc_count = gc_count_;
}
if (number_idle_notifications == kIdlesBeforeScavenge) {
CollectGarbage(0, NEW_SPACE);
new_space_.Shrink();
last_gc_count = gc_count_;
} else if (number_idle_notifications == kIdlesBeforeMarkSweep) {
CollectAllGarbage(false);
new_space_.Shrink();
last_gc_count = gc_count_;
} else if (number_idle_notifications == kIdlesBeforeMarkCompact) {
CollectAllGarbage(true);
new_space_.Shrink();
last_gc_count = gc_count_;
number_idle_notifications = 0;
finished = true;
}
// Uncommit unused memory in new space.
Heap::UncommitFromSpace();
return finished;
}
#ifdef DEBUG
void Heap::Print() {
if (!HasBeenSetup()) return;
Top::PrintStack();
AllSpaces spaces;
while (Space* space = spaces.next()) space->Print();
}
void Heap::ReportCodeStatistics(const char* title) {
PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
PagedSpace::ResetCodeStatistics();
// We do not look for code in new space, map space, or old space. If code
// somehow ends up in those spaces, we would miss it here.
code_space_->CollectCodeStatistics();
lo_space_->CollectCodeStatistics();
PagedSpace::ReportCodeStatistics();
}
// This function expects that NewSpace's allocated objects histogram is
// populated (via a call to CollectStatistics or else as a side effect of a
// just-completed scavenge collection).
void Heap::ReportHeapStatistics(const char* title) {
USE(title);
PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
title, gc_count_);
PrintF("mark-compact GC : %d\n", mc_count_);
PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
PrintF("\n");
PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
GlobalHandles::PrintStats();
PrintF("\n");
PrintF("Heap statistics : ");
MemoryAllocator::ReportStatistics();
PrintF("To space : ");
new_space_.ReportStatistics();
PrintF("Old pointer space : ");
old_pointer_space_->ReportStatistics();
PrintF("Old data space : ");
old_data_space_->ReportStatistics();
PrintF("Code space : ");
code_space_->ReportStatistics();
PrintF("Map space : ");
map_space_->ReportStatistics();
PrintF("Cell space : ");
cell_space_->ReportStatistics();
PrintF("Large object space : ");
lo_space_->ReportStatistics();
PrintF(">>>>>> ========================================= >>>>>>\n");
}
#endif // DEBUG
bool Heap::Contains(HeapObject* value) {
return Contains(value->address());
}
bool Heap::Contains(Address addr) {
if (OS::IsOutsideAllocatedSpace(addr)) return false;
return HasBeenSetup() &&
(new_space_.ToSpaceContains(addr) ||
old_pointer_space_->Contains(addr) ||
old_data_space_->Contains(addr) ||
code_space_->Contains(addr) ||
map_space_->Contains(addr) ||
cell_space_->Contains(addr) ||
lo_space_->SlowContains(addr));
}
bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
return InSpace(value->address(), space);
}
bool Heap::InSpace(Address addr, AllocationSpace space) {
if (OS::IsOutsideAllocatedSpace(addr)) return false;
if (!HasBeenSetup()) return false;
switch (space) {
case NEW_SPACE:
return new_space_.ToSpaceContains(addr);
case OLD_POINTER_SPACE:
return old_pointer_space_->Contains(addr);
case OLD_DATA_SPACE:
return old_data_space_->Contains(addr);
case CODE_SPACE:
return code_space_->Contains(addr);
case MAP_SPACE:
return map_space_->Contains(addr);
case CELL_SPACE:
return cell_space_->Contains(addr);
case LO_SPACE:
return lo_space_->SlowContains(addr);
}
return false;
}
#ifdef DEBUG
void Heap::Verify() {
ASSERT(HasBeenSetup());
VerifyPointersVisitor visitor;
IterateRoots(&visitor);
new_space_.Verify();
VerifyPointersAndRSetVisitor rset_visitor;
old_pointer_space_->Verify(&rset_visitor);
map_space_->Verify(&rset_visitor);
VerifyPointersVisitor no_rset_visitor;
old_data_space_->Verify(&no_rset_visitor);
code_space_->Verify(&no_rset_visitor);
cell_space_->Verify(&no_rset_visitor);
lo_space_->Verify();
}
#endif // DEBUG
Object* Heap::LookupSymbol(Vector<const char> string) {
Object* symbol = NULL;
Object* new_table = symbol_table()->LookupSymbol(string, &symbol);
if (new_table->IsFailure()) return new_table;
// Can't use set_symbol_table because SymbolTable::cast knows that
// SymbolTable is a singleton and checks for identity.
roots_[kSymbolTableRootIndex] = new_table;
ASSERT(symbol != NULL);
return symbol;
}
Object* Heap::LookupSymbol(String* string) {
if (string->IsSymbol()) return string;
Object* symbol = NULL;
Object* new_table = symbol_table()->LookupString(string, &symbol);
if (new_table->IsFailure()) return new_table;
// Can't use set_symbol_table because SymbolTable::cast knows that
// SymbolTable is a singleton and checks for identity.
roots_[kSymbolTableRootIndex] = new_table;
ASSERT(symbol != NULL);
return symbol;
}
bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
if (string->IsSymbol()) {
*symbol = string;
return true;
}
return symbol_table()->LookupSymbolIfExists(string, symbol);
}
#ifdef DEBUG
void Heap::ZapFromSpace() {
ASSERT(reinterpret_cast<Object*>(kFromSpaceZapValue)->IsHeapObject());
for (Address a = new_space_.FromSpaceLow();
a < new_space_.FromSpaceHigh();
a += kPointerSize) {
Memory::Address_at(a) = kFromSpaceZapValue;
}
}
#endif // DEBUG
int Heap::IterateRSetRange(Address object_start,
Address object_end,
Address rset_start,
ObjectSlotCallback copy_object_func) {
Address object_address = object_start;
Address rset_address = rset_start;
int set_bits_count = 0;
// Loop over all the pointers in [object_start, object_end).
while (object_address < object_end) {
uint32_t rset_word = Memory::uint32_at(rset_address);
if (rset_word != 0) {
uint32_t result_rset = rset_word;
for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
// Do not dereference pointers at or past object_end.
if ((rset_word & bitmask) != 0 && object_address < object_end) {
Object** object_p = reinterpret_cast<Object**>(object_address);
if (Heap::InNewSpace(*object_p)) {
copy_object_func(reinterpret_cast<HeapObject**>(object_p));
}
// If this pointer does not need to be remembered anymore, clear
// the remembered set bit.
if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
set_bits_count++;
}
object_address += kPointerSize;
}
// Update the remembered set if it has changed.
if (result_rset != rset_word) {
Memory::uint32_at(rset_address) = result_rset;
}
} else {
// No bits in the word were set. This is the common case.
object_address += kPointerSize * kBitsPerInt;
}
rset_address += kIntSize;
}
return set_bits_count;
}
void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
ASSERT(Page::is_rset_in_use());
ASSERT(space == old_pointer_space_ || space == map_space_);
static void* paged_rset_histogram = StatsTable::CreateHistogram(
"V8.RSetPaged",
0,
Page::kObjectAreaSize / kPointerSize,
30);
PageIterator it(space, PageIterator::PAGES_IN_USE);
while (it.has_next()) {
Page* page = it.next();
int count = IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
page->RSetStart(), copy_object_func);
if (paged_rset_histogram != NULL) {
StatsTable::AddHistogramSample(paged_rset_histogram, count);
}
}
}
#ifdef DEBUG
#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
#else
#define SYNCHRONIZE_TAG(tag)
#endif
void Heap::IterateRoots(ObjectVisitor* v) {
IterateStrongRoots(v);
v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
SYNCHRONIZE_TAG("symbol_table");
}
void Heap::IterateStrongRoots(ObjectVisitor* v) {
v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
SYNCHRONIZE_TAG("strong_root_list");
v->VisitPointer(bit_cast<Object**, String**>(&hidden_symbol_));
SYNCHRONIZE_TAG("symbol");
Bootstrapper::Iterate(v);
SYNCHRONIZE_TAG("bootstrapper");
Top::Iterate(v);
SYNCHRONIZE_TAG("top");
Relocatable::Iterate(v);
SYNCHRONIZE_TAG("relocatable");
#ifdef ENABLE_DEBUGGER_SUPPORT
Debug::Iterate(v);
#endif
SYNCHRONIZE_TAG("debug");
CompilationCache::Iterate(v);
SYNCHRONIZE_TAG("compilationcache");
// Iterate over local handles in handle scopes.
HandleScopeImplementer::Iterate(v);
SYNCHRONIZE_TAG("handlescope");
// Iterate over the builtin code objects and code stubs in the heap. Note
// that it is not strictly necessary to iterate over code objects on
// scavenge collections. We still do it here because this same function
// is used by the mark-sweep collector and the deserializer.
Builtins::IterateBuiltins(v);
SYNCHRONIZE_TAG("builtins");
// Iterate over global handles.
GlobalHandles::IterateRoots(v);
SYNCHRONIZE_TAG("globalhandles");
// Iterate over pointers being held by inactive threads.
ThreadManager::Iterate(v);
SYNCHRONIZE_TAG("threadmanager");
}
#undef SYNCHRONIZE_TAG
// Flag is set when the heap has been configured. The heap can be repeatedly
// configured through the API until it is setup.
static bool heap_configured = false;
// TODO(1236194): Since the heap size is configurable on the command line
// and through the API, we should gracefully handle the case that the heap
// size is not big enough to fit all the initial objects.
bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
if (HasBeenSetup()) return false;
if (semispace_size > 0) semispace_size_ = semispace_size;
if (old_gen_size > 0) old_generation_size_ = old_gen_size;
// The new space size must be a power of two to support single-bit testing
// for containment.
semispace_size_ = RoundUpToPowerOf2(semispace_size_);
initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
young_generation_size_ = 2 * semispace_size_;
external_allocation_limit_ = 10 * semispace_size_;
// The old generation is paged.
old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
heap_configured = true;
return true;
}
bool Heap::ConfigureHeapDefault() {
return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
}
int Heap::PromotedSpaceSize() {
return old_pointer_space_->Size()
+ old_data_space_->Size()
+ code_space_->Size()
+ map_space_->Size()
+ cell_space_->Size()
+ lo_space_->Size();
}
int Heap::PromotedExternalMemorySize() {
if (amount_of_external_allocated_memory_
<= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
return amount_of_external_allocated_memory_
- amount_of_external_allocated_memory_at_last_global_gc_;
}
bool Heap::Setup(bool create_heap_objects) {
// Initialize heap spaces and initial maps and objects. Whenever something
// goes wrong, just return false. The caller should check the results and
// call Heap::TearDown() to release allocated memory.
//
// If the heap is not yet configured (eg, through the API), configure it.
// Configuration is based on the flags new-space-size (really the semispace
// size) and old-space-size if set or the initial values of semispace_size_
// and old_generation_size_ otherwise.
if (!heap_configured) {
if (!ConfigureHeapDefault()) return false;
}
// Setup memory allocator and reserve a chunk of memory for new
// space. The chunk is double the size of the new space to ensure
// that we can find a pair of semispaces that are contiguous and
// aligned to their size.
if (!MemoryAllocator::Setup(MaxCapacity())) return false;
void* chunk =
MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
if (chunk == NULL) return false;
// Align the pair of semispaces to their size, which must be a power
// of 2.
ASSERT(IsPowerOf2(young_generation_size_));
Address new_space_start =
RoundUp(reinterpret_cast<byte*>(chunk), young_generation_size_);
if (!new_space_.Setup(new_space_start, young_generation_size_)) return false;
// Initialize old pointer space.
old_pointer_space_ =
new OldSpace(old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
if (old_pointer_space_ == NULL) return false;
if (!old_pointer_space_->Setup(NULL, 0)) return false;
// Initialize old data space.
old_data_space_ =
new OldSpace(old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
if (old_data_space_ == NULL) return false;
if (!old_data_space_->Setup(NULL, 0)) return false;
// Initialize the code space, set its maximum capacity to the old
// generation size. It needs executable memory.
// On 64-bit platform(s), we put all code objects in a 2 GB range of
// virtual address space, so that they can call each other with near calls.
if (code_range_size_ > 0) {
if (!CodeRange::Setup(code_range_size_)) {
return false;
}
}
code_space_ =
new OldSpace(old_generation_size_, CODE_SPACE, EXECUTABLE);
if (code_space_ == NULL) return false;
if (!code_space_->Setup(NULL, 0)) return false;
// Initialize map space.
map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
if (map_space_ == NULL) return false;
if (!map_space_->Setup(NULL, 0)) return false;
// Initialize global property cell space.
cell_space_ = new CellSpace(old_generation_size_, CELL_SPACE);
if (cell_space_ == NULL) return false;
if (!cell_space_->Setup(NULL, 0)) return false;
// The large object code space may contain code or data. We set the memory
// to be non-executable here for safety, but this means we need to enable it
// explicitly when allocating large code objects.
lo_space_ = new LargeObjectSpace(LO_SPACE);
if (lo_space_ == NULL) return false;
if (!lo_space_->Setup()) return false;
if (create_heap_objects) {
// Create initial maps.
if (!CreateInitialMaps()) return false;
if (!CreateApiObjects()) return false;
// Create initial objects
if (!CreateInitialObjects()) return false;
}
LOG(IntEvent("heap-capacity", Capacity()));
LOG(IntEvent("heap-available", Available()));
return true;
}
void Heap::SetStackLimit(intptr_t limit) {
// On 64 bit machines, pointers are generally out of range of Smis. We write
// something that looks like an out of range Smi to the GC.
// Set up the special root array entry containing the stack guard.
// This is actually an address, but the tag makes the GC ignore it.
roots_[kStackLimitRootIndex] =
reinterpret_cast<Object*>((limit & ~kSmiTagMask) | kSmiTag);
}
void Heap::TearDown() {
GlobalHandles::TearDown();
new_space_.TearDown();
if (old_pointer_space_ != NULL) {
old_pointer_space_->TearDown();
delete old_pointer_space_;
old_pointer_space_ = NULL;
}
if (old_data_space_ != NULL) {
old_data_space_->TearDown();
delete old_data_space_;
old_data_space_ = NULL;
}
if (code_space_ != NULL) {
code_space_->TearDown();
delete code_space_;
code_space_ = NULL;
}
if (map_space_ != NULL) {
map_space_->TearDown();
delete map_space_;
map_space_ = NULL;
}
if (cell_space_ != NULL) {
cell_space_->TearDown();
delete cell_space_;
cell_space_ = NULL;
}
if (lo_space_ != NULL) {
lo_space_->TearDown();
delete lo_space_;
lo_space_ = NULL;
}
MemoryAllocator::TearDown();
}
void Heap::Shrink() {
// Try to shrink all paged spaces.
PagedSpaces spaces;
while (PagedSpace* space = spaces.next()) space->Shrink();
}
#ifdef ENABLE_HEAP_PROTECTION
void Heap::Protect() {
if (HasBeenSetup()) {
AllSpaces spaces;
while (Space* space = spaces.next()) space->Protect();
}
}
void Heap::Unprotect() {
if (HasBeenSetup()) {
AllSpaces spaces;
while (Space* space = spaces.next()) space->Unprotect();
}
}
#endif
#ifdef DEBUG
class PrintHandleVisitor: public ObjectVisitor {
public:
void VisitPointers(Object** start, Object** end) {
for (Object** p = start; p < end; p++)
PrintF(" handle %p to %p\n", p, *p);
}
};
void Heap::PrintHandles() {
PrintF("Handles:\n");
PrintHandleVisitor v;
HandleScopeImplementer::Iterate(&v);
}
#endif
Space* AllSpaces::next() {
switch (counter_++) {
case NEW_SPACE:
return Heap::new_space();
case OLD_POINTER_SPACE:
return Heap::old_pointer_space();
case OLD_DATA_SPACE:
return Heap::old_data_space();
case CODE_SPACE:
return Heap::code_space();
case MAP_SPACE:
return Heap::map_space();
case CELL_SPACE:
return Heap::cell_space();
case LO_SPACE:
return Heap::lo_space();
default:
return NULL;
}
}
PagedSpace* PagedSpaces::next() {
switch (counter_++) {
case OLD_POINTER_SPACE:
return Heap::old_pointer_space();
case OLD_DATA_SPACE:
return Heap::old_data_space();
case CODE_SPACE:
return Heap::code_space();
case MAP_SPACE:
return Heap::map_space();
case CELL_SPACE:
return Heap::cell_space();
default:
return NULL;
}
}
OldSpace* OldSpaces::next() {
switch (counter_++) {
case OLD_POINTER_SPACE:
return Heap::old_pointer_space();
case OLD_DATA_SPACE:
return Heap::old_data_space();
case CODE_SPACE:
return Heap::code_space();
default:
return NULL;
}
}
SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
}
SpaceIterator::~SpaceIterator() {
// Delete active iterator if any.
delete iterator_;
}
bool SpaceIterator::has_next() {
// Iterate until no more spaces.
return current_space_ != LAST_SPACE;
}
ObjectIterator* SpaceIterator::next() {
if (iterator_ != NULL) {
delete iterator_;
iterator_ = NULL;
// Move to the next space
current_space_++;
if (current_space_ > LAST_SPACE) {
return NULL;
}
}
// Return iterator for the new current space.
return CreateIterator();
}
// Create an iterator for the space to iterate.
ObjectIterator* SpaceIterator::CreateIterator() {
ASSERT(iterator_ == NULL);
switch (current_space_) {
case NEW_SPACE:
iterator_ = new SemiSpaceIterator(Heap::new_space());
break;
case OLD_POINTER_SPACE:
iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
break;
case OLD_DATA_SPACE:
iterator_ = new HeapObjectIterator(Heap::old_data_space());
break;
case CODE_SPACE:
iterator_ = new HeapObjectIterator(Heap::code_space());
break;
case MAP_SPACE:
iterator_ = new HeapObjectIterator(Heap::map_space());
break;
case CELL_SPACE:
iterator_ = new HeapObjectIterator(Heap::cell_space());
break;
case LO_SPACE:
iterator_ = new LargeObjectIterator(Heap::lo_space());
break;
}
// Return the newly allocated iterator;
ASSERT(iterator_ != NULL);
return iterator_;
}
HeapIterator::HeapIterator() {
Init();
}
HeapIterator::~HeapIterator() {
Shutdown();
}
void HeapIterator::Init() {
// Start the iteration.
space_iterator_ = new SpaceIterator();
object_iterator_ = space_iterator_->next();
}
void HeapIterator::Shutdown() {
// Make sure the last iterator is deallocated.
delete space_iterator_;
space_iterator_ = NULL;
object_iterator_ = NULL;
}
bool HeapIterator::has_next() {
// No iterator means we are done.
if (object_iterator_ == NULL) return false;
if (object_iterator_->has_next_object()) {
// If the current iterator has more objects we are fine.
return true;
} else {
// Go though the spaces looking for one that has objects.
while (space_iterator_->has_next()) {
object_iterator_ = space_iterator_->next();
if (object_iterator_->has_next_object()) {
return true;
}
}
}
// Done with the last space.
object_iterator_ = NULL;
return false;
}
HeapObject* HeapIterator::next() {
if (has_next()) {
return object_iterator_->next_object();
} else {
return NULL;
}
}
void HeapIterator::reset() {
// Restart the iterator.
Shutdown();
Init();
}
#ifdef DEBUG
static bool search_for_any_global;
static Object* search_target;
static bool found_target;
static List<Object*> object_stack(20);
// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
static const int kMarkTag = 2;
static void MarkObjectRecursively(Object** p);
class MarkObjectVisitor : public ObjectVisitor {
public:
void VisitPointers(Object** start, Object** end) {
// Copy all HeapObject pointers in [start, end)
for (Object** p = start; p < end; p++) {
if ((*p)->IsHeapObject())
MarkObjectRecursively(p);
}
}
};
static MarkObjectVisitor mark_visitor;
static void MarkObjectRecursively(Object** p) {
if (!(*p)->IsHeapObject()) return;
HeapObject* obj = HeapObject::cast(*p);
Object* map = obj->map();
if (!map->IsHeapObject()) return; // visited before
if (found_target) return; // stop if target found
object_stack.Add(obj);
if ((search_for_any_global && obj->IsJSGlobalObject()) ||
(!search_for_any_global && (obj == search_target))) {
found_target = true;
return;
}
// not visited yet
Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
Address map_addr = map_p->address();
obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
MarkObjectRecursively(&map);
obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
&mark_visitor);
if (!found_target) // don't pop if found the target
object_stack.RemoveLast();
}
static void UnmarkObjectRecursively(Object** p);
class UnmarkObjectVisitor : public ObjectVisitor {
public:
void VisitPointers(Object** start, Object** end) {
// Copy all HeapObject pointers in [start, end)
for (Object** p = start; p < end; p++) {
if ((*p)->IsHeapObject())
UnmarkObjectRecursively(p);
}
}
};
static UnmarkObjectVisitor unmark_visitor;
static void UnmarkObjectRecursively(Object** p) {
if (!(*p)->IsHeapObject()) return;
HeapObject* obj = HeapObject::cast(*p);
Object* map = obj->map();
if (map->IsHeapObject()) return; // unmarked already
Address map_addr = reinterpret_cast<Address>(map);
map_addr -= kMarkTag;
ASSERT_TAG_ALIGNED(map_addr);
HeapObject* map_p = HeapObject::FromAddress(map_addr);
obj->set_map(reinterpret_cast<Map*>(map_p));
UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
obj->IterateBody(Map::cast(map_p)->instance_type(),
obj->SizeFromMap(Map::cast(map_p)),
&unmark_visitor);
}
static void MarkRootObjectRecursively(Object** root) {
if (search_for_any_global) {
ASSERT(search_target == NULL);
} else {
ASSERT(search_target->IsHeapObject());
}
found_target = false;
object_stack.Clear();
MarkObjectRecursively(root);
UnmarkObjectRecursively(root);
if (found_target) {
PrintF("=====================================\n");
PrintF("==== Path to object ====\n");
PrintF("=====================================\n\n");
ASSERT(!object_stack.is_empty());
for (int i = 0; i < object_stack.length(); i++) {
if (i > 0) PrintF("\n |\n |\n V\n\n");
Object* obj = object_stack[i];
obj->Print();
}
PrintF("=====================================\n");
}
}
// Helper class for visiting HeapObjects recursively.
class MarkRootVisitor: public ObjectVisitor {
public:
void VisitPointers(Object** start, Object** end) {
// Visit all HeapObject pointers in [start, end)
for (Object** p = start; p < end; p++) {
if ((*p)->IsHeapObject())
MarkRootObjectRecursively(p);
}
}
};
// Triggers a depth-first traversal of reachable objects from roots
// and finds a path to a specific heap object and prints it.
void Heap::TracePathToObject() {
search_target = NULL;
search_for_any_global = false;
MarkRootVisitor root_visitor;
IterateRoots(&root_visitor);
}
// Triggers a depth-first traversal of reachable objects from roots
// and finds a path to any global object and prints it. Useful for
// determining the source for leaks of global objects.
void Heap::TracePathToGlobal() {
search_target = NULL;
search_for_any_global = true;
MarkRootVisitor root_visitor;
IterateRoots(&root_visitor);
}
#endif
GCTracer::GCTracer()
: start_time_(0.0),
start_size_(0.0),
gc_count_(0),
full_gc_count_(0),
is_compacting_(false),
marked_count_(0) {
// These two fields reflect the state of the previous full collection.
// Set them before they are changed by the collector.
previous_has_compacted_ = MarkCompactCollector::HasCompacted();
previous_marked_count_ = MarkCompactCollector::previous_marked_count();
if (!FLAG_trace_gc) return;
start_time_ = OS::TimeCurrentMillis();
start_size_ = SizeOfHeapObjects();
}
GCTracer::~GCTracer() {
if (!FLAG_trace_gc) return;
// Printf ONE line iff flag is set.
PrintF("%s %.1f -> %.1f MB, %d ms.\n",
CollectorString(),
start_size_, SizeOfHeapObjects(),
static_cast<int>(OS::TimeCurrentMillis() - start_time_));
#if defined(ENABLE_LOGGING_AND_PROFILING)
Heap::PrintShortHeapStatistics();
#endif
}
const char* GCTracer::CollectorString() {
switch (collector_) {
case SCAVENGER:
return "Scavenge";
case MARK_COMPACTOR:
return MarkCompactCollector::HasCompacted() ? "Mark-compact"
: "Mark-sweep";
}
return "Unknown GC";
}
int KeyedLookupCache::Hash(Map* map, String* name) {
// Uses only lower 32 bits if pointers are larger.
uintptr_t addr_hash =
static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> 2;
return (addr_hash ^ name->Hash()) % kLength;
}
int KeyedLookupCache::Lookup(Map* map, String* name) {
int index = Hash(map, name);
Key& key = keys_[index];
if ((key.map == map) && key.name->Equals(name)) {
return field_offsets_[index];
}
return -1;
}
void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
String* symbol;
if (Heap::LookupSymbolIfExists(name, &symbol)) {
int index = Hash(map, symbol);
Key& key = keys_[index];
key.map = map;
key.name = symbol;
field_offsets_[index] = field_offset;
}
}
void KeyedLookupCache::Clear() {
for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
}
KeyedLookupCache::Key KeyedLookupCache::keys_[KeyedLookupCache::kLength];
int KeyedLookupCache::field_offsets_[KeyedLookupCache::kLength];
void DescriptorLookupCache::Clear() {
for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
}
DescriptorLookupCache::Key
DescriptorLookupCache::keys_[DescriptorLookupCache::kLength];
int DescriptorLookupCache::results_[DescriptorLookupCache::kLength];
#ifdef DEBUG
bool Heap::GarbageCollectionGreedyCheck() {
ASSERT(FLAG_gc_greedy);
if (Bootstrapper::IsActive()) return true;
if (disallow_allocation_failure()) return true;
return CollectGarbage(0, NEW_SPACE);
}
#endif
TranscendentalCache::TranscendentalCache(TranscendentalCache::Type t)
: type_(t) {
uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
uint32_t in1 = 0xffffffffu; // generated by the FPU.
for (int i = 0; i < kCacheSize; i++) {
elements_[i].in[0] = in0;
elements_[i].in[1] = in1;
elements_[i].output = NULL;
}
}
TranscendentalCache* TranscendentalCache::caches_[kNumberOfCaches];
void TranscendentalCache::Clear() {
for (int i = 0; i < kNumberOfCaches; i++) {
if (caches_[i] != NULL) {
delete caches_[i];
caches_[i] = NULL;
}
}
}
} } // namespace v8::internal
|
/*
Q Light Controller
qlcfixturemode.cpp
Copyright (C) Heikki Junnila
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.
*/
#include <iostream>
#include <QString>
#include <QDebug>
#include <QVector>
#include <QtXml>
#include "qlcfixturemode.h"
#include "qlcfixturehead.h"
#include "qlcfixturedef.h"
#include "qlcchannel.h"
#include "qlcphysical.h"
QLCFixtureMode::QLCFixtureMode(QLCFixtureDef* fixtureDef)
: m_fixtureDef(fixtureDef)
{
Q_ASSERT(fixtureDef != NULL);
}
QLCFixtureMode::QLCFixtureMode(QLCFixtureDef* fixtureDef, const QLCFixtureMode* mode)
: m_fixtureDef(fixtureDef)
{
Q_ASSERT(fixtureDef != NULL);
Q_ASSERT(mode != NULL);
if (mode != NULL)
*this = *mode;
}
QLCFixtureMode::~QLCFixtureMode()
{
}
QLCFixtureMode& QLCFixtureMode::operator=(const QLCFixtureMode& mode)
{
if (this != &mode)
{
m_name = mode.m_name;
m_physical = mode.m_physical;
m_heads = mode.m_heads;
/* Clear the existing list of channels */
m_channels.clear();
Q_ASSERT(m_fixtureDef != NULL);
quint32 i = 0;
QVectorIterator <QLCChannel*> it(mode.m_channels);
while (it.hasNext() == true)
{
/* Since m_fixtureDef might not be the same as
mode.m_fixtureDef, we need to search for a
channel with the same name from m_fixtureDef and
not from mode.m_fixtureDef. If the channel in the
other mode is deleted, the one in this copied mode
will be invalid and we end up in a crash. */
QLCChannel* ch = it.next();
QLCChannel* actual = m_fixtureDef->channel(ch->name());
if (actual != NULL)
insertChannel(actual, i++);
else
qWarning() << Q_FUNC_INFO << "Unable to find channel"
<< ch->name() << "for mode"
<< m_name << "from its fixture definition";
}
}
return *this;
}
/****************************************************************************
* Name
****************************************************************************/
void QLCFixtureMode::setName(const QString &name)
{
m_name = name;
}
QString QLCFixtureMode::name() const
{
return m_name;
}
/*****************************************************************************
* Fixture definition
*****************************************************************************/
QLCFixtureDef* QLCFixtureMode::fixtureDef() const
{
return m_fixtureDef;
}
/****************************************************************************
* Channels
****************************************************************************/
bool QLCFixtureMode::insertChannel(QLCChannel* channel, quint32 index)
{
if (channel == NULL)
{
qWarning() << Q_FUNC_INFO << "Will not add a NULL channel to mode"
<< m_name;
return false;
}
Q_ASSERT(m_fixtureDef != NULL);
if (m_fixtureDef->channels().contains(channel) == true)
{
if (m_channels.contains(channel) == false)
{
if (index >= quint32(m_channels.size()))
m_channels.append(channel);
else
m_channels.insert(index, channel);
return true;
}
else
{
qWarning() << Q_FUNC_INFO << "Channel" << channel->name()
<< "is already a member of mode" << m_name;
return false;
}
}
else
{
qWarning() << Q_FUNC_INFO << "Will not add channel" << channel->name()
<< "to mode" << m_name
<< "because the channel does not belong to mode's"
<< "parent fixture definition.";
return false;
}
}
bool QLCFixtureMode::removeChannel(const QLCChannel* channel)
{
QMutableVectorIterator <QLCChannel*> it(m_channels);
while (it.hasNext() == true)
{
if (it.next() == channel)
{
/* Don't delete the channel since QLCFixtureModes
don't own them. QLCFixtureDefs do. */
it.remove();
return true;
}
}
return false;
}
void QLCFixtureMode::removeAllChannels()
{
m_channels.clear();
}
QLCChannel* QLCFixtureMode::channel(const QString& name) const
{
QVectorIterator <QLCChannel*> it(m_channels);
while (it.hasNext() == true)
{
QLCChannel* ch = it.next();
Q_ASSERT(ch != NULL);
if (ch->name() == name)
return ch;
}
return NULL;
}
QLCChannel* QLCFixtureMode::channel(quint32 ch) const
{
if (ch >= quint32(m_channels.size()))
return NULL;
else
return m_channels.at(ch);
}
QVector <QLCChannel*> QLCFixtureMode::channels() const
{
return m_channels;
}
quint32 QLCFixtureMode::channelNumber(QLCChannel* channel) const
{
if (channel == NULL)
return QLCChannel::invalid();
for (int i = 0; i < m_channels.size(); i++)
{
if (m_channels.at(i) == channel)
return i;
}
return QLCChannel::invalid();
}
/*****************************************************************************
* Heads
*****************************************************************************/
void QLCFixtureMode::insertHead(int index, const QLCFixtureHead& head)
{
if (index < 0 || index >= m_heads.size())
m_heads.append(head);
else
m_heads.insert(index, head);
}
void QLCFixtureMode::removeHead(int index)
{
if (index >= 0 && index < m_heads.size())
m_heads.remove(index);
}
void QLCFixtureMode::replaceHead(int index, const QLCFixtureHead& head)
{
if (index >= 0 && index < m_heads.size())
m_heads[index] = head;
}
QVector <QLCFixtureHead> const& QLCFixtureMode::heads() const
{
return m_heads;
}
int QLCFixtureMode::headForChannel(quint32 chnum) const
{
for (int i = 0; i < m_heads.size(); i++)
{
if (m_heads[i].channels().contains(chnum) == true)
return i;
}
return -1;
}
void QLCFixtureMode::cacheHeads()
{
for (int i = 0; i < m_heads.size(); i++)
{
QLCFixtureHead& head(m_heads[i]);
head.cacheChannels(this);
}
}
/****************************************************************************
* Physical
****************************************************************************/
void QLCFixtureMode::setPhysical(const QLCPhysical& physical)
{
m_physical = physical;
}
QLCPhysical QLCFixtureMode::physical() const
{
return m_physical;
}
/****************************************************************************
* Load & Save
****************************************************************************/
bool QLCFixtureMode::loadXML(const QDomElement& root)
{
if (root.tagName() != KXMLQLCFixtureMode)
{
qWarning() << Q_FUNC_INFO << "Mode tag not found";
return false;
}
/* Mode name */
QString str = root.attribute(KXMLQLCFixtureModeName);
if (str.isEmpty() == true)
{
qWarning() << Q_FUNC_INFO << "Mode has no name";
return false;
}
else
{
setName(str);
}
/* Subtags */
QDomNode node = root.firstChild();
while (node.isNull() == false)
{
QDomElement tag = node.toElement();
if (tag.tagName() == KXMLQLCFixtureModeChannel)
{
/* Channel */
Q_ASSERT(m_fixtureDef != NULL);
str = tag.attribute(KXMLQLCFixtureModeChannelNumber);
insertChannel(m_fixtureDef->channel(tag.text()),
str.toInt());
}
else if (tag.tagName() == KXMLQLCFixtureHead)
{
/* Head */
QLCFixtureHead head;
if (head.loadXML(tag) == true)
insertHead(-1, head);
}
else if (tag.tagName() == KXMLQLCPhysical)
{
/* Physical */
QLCPhysical physical;
physical.loadXML(tag);
setPhysical(physical);
}
else
{
qWarning() << Q_FUNC_INFO << "Unknown Fixture Mode tag:" << tag.tagName();
}
node = node.nextSibling();
}
// Cache all head channels
cacheHeads();
return true;
}
bool QLCFixtureMode::saveXML(QDomDocument* doc, QDomElement* root)
{
QDomElement tag;
QDomElement chtag;
QDomText text;
QString str;
int i = 0;
Q_ASSERT(doc != NULL);
Q_ASSERT(root != NULL);
/* Mode entry */
tag = doc->createElement(KXMLQLCFixtureMode);
tag.setAttribute(KXMLQLCFixtureModeName, m_name);
root->appendChild(tag);
m_physical.saveXML(doc, &tag);
/* Channels */
QVectorIterator <QLCChannel*> it(m_channels);
while (it.hasNext() == true)
{
chtag = doc->createElement(KXMLQLCFixtureModeChannel);
tag.appendChild(chtag);
str.setNum(i++);
chtag.setAttribute(KXMLQLCFixtureModeChannelNumber, str);
text = doc->createTextNode(it.next()->name());
chtag.appendChild(text);
}
/* Heads */
QVectorIterator <QLCFixtureHead> hit(m_heads);
while (hit.hasNext() == true)
hit.next().saveXML(doc, &tag);
return true;
}
qlcfixturemode::channel: less code, same effect
/*
Q Light Controller
qlcfixturemode.cpp
Copyright (C) Heikki Junnila
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.
*/
#include <iostream>
#include <QString>
#include <QDebug>
#include <QVector>
#include <QtXml>
#include "qlcfixturemode.h"
#include "qlcfixturehead.h"
#include "qlcfixturedef.h"
#include "qlcchannel.h"
#include "qlcphysical.h"
QLCFixtureMode::QLCFixtureMode(QLCFixtureDef* fixtureDef)
: m_fixtureDef(fixtureDef)
{
Q_ASSERT(fixtureDef != NULL);
}
QLCFixtureMode::QLCFixtureMode(QLCFixtureDef* fixtureDef, const QLCFixtureMode* mode)
: m_fixtureDef(fixtureDef)
{
Q_ASSERT(fixtureDef != NULL);
Q_ASSERT(mode != NULL);
if (mode != NULL)
*this = *mode;
}
QLCFixtureMode::~QLCFixtureMode()
{
}
QLCFixtureMode& QLCFixtureMode::operator=(const QLCFixtureMode& mode)
{
if (this != &mode)
{
m_name = mode.m_name;
m_physical = mode.m_physical;
m_heads = mode.m_heads;
/* Clear the existing list of channels */
m_channels.clear();
Q_ASSERT(m_fixtureDef != NULL);
quint32 i = 0;
QVectorIterator <QLCChannel*> it(mode.m_channels);
while (it.hasNext() == true)
{
/* Since m_fixtureDef might not be the same as
mode.m_fixtureDef, we need to search for a
channel with the same name from m_fixtureDef and
not from mode.m_fixtureDef. If the channel in the
other mode is deleted, the one in this copied mode
will be invalid and we end up in a crash. */
QLCChannel* ch = it.next();
QLCChannel* actual = m_fixtureDef->channel(ch->name());
if (actual != NULL)
insertChannel(actual, i++);
else
qWarning() << Q_FUNC_INFO << "Unable to find channel"
<< ch->name() << "for mode"
<< m_name << "from its fixture definition";
}
}
return *this;
}
/****************************************************************************
* Name
****************************************************************************/
void QLCFixtureMode::setName(const QString &name)
{
m_name = name;
}
QString QLCFixtureMode::name() const
{
return m_name;
}
/*****************************************************************************
* Fixture definition
*****************************************************************************/
QLCFixtureDef* QLCFixtureMode::fixtureDef() const
{
return m_fixtureDef;
}
/****************************************************************************
* Channels
****************************************************************************/
bool QLCFixtureMode::insertChannel(QLCChannel* channel, quint32 index)
{
if (channel == NULL)
{
qWarning() << Q_FUNC_INFO << "Will not add a NULL channel to mode"
<< m_name;
return false;
}
Q_ASSERT(m_fixtureDef != NULL);
if (m_fixtureDef->channels().contains(channel) == true)
{
if (m_channels.contains(channel) == false)
{
if (index >= quint32(m_channels.size()))
m_channels.append(channel);
else
m_channels.insert(index, channel);
return true;
}
else
{
qWarning() << Q_FUNC_INFO << "Channel" << channel->name()
<< "is already a member of mode" << m_name;
return false;
}
}
else
{
qWarning() << Q_FUNC_INFO << "Will not add channel" << channel->name()
<< "to mode" << m_name
<< "because the channel does not belong to mode's"
<< "parent fixture definition.";
return false;
}
}
bool QLCFixtureMode::removeChannel(const QLCChannel* channel)
{
QMutableVectorIterator <QLCChannel*> it(m_channels);
while (it.hasNext() == true)
{
if (it.next() == channel)
{
/* Don't delete the channel since QLCFixtureModes
don't own them. QLCFixtureDefs do. */
it.remove();
return true;
}
}
return false;
}
void QLCFixtureMode::removeAllChannels()
{
m_channels.clear();
}
QLCChannel* QLCFixtureMode::channel(const QString& name) const
{
QVectorIterator <QLCChannel*> it(m_channels);
while (it.hasNext() == true)
{
QLCChannel* ch = it.next();
Q_ASSERT(ch != NULL);
if (ch->name() == name)
return ch;
}
return NULL;
}
QLCChannel* QLCFixtureMode::channel(quint32 ch) const
{
return m_channels.value(ch, NULL);
}
QVector <QLCChannel*> QLCFixtureMode::channels() const
{
return m_channels;
}
quint32 QLCFixtureMode::channelNumber(QLCChannel* channel) const
{
if (channel == NULL)
return QLCChannel::invalid();
for (int i = 0; i < m_channels.size(); i++)
{
if (m_channels.at(i) == channel)
return i;
}
return QLCChannel::invalid();
}
/*****************************************************************************
* Heads
*****************************************************************************/
void QLCFixtureMode::insertHead(int index, const QLCFixtureHead& head)
{
if (index < 0 || index >= m_heads.size())
m_heads.append(head);
else
m_heads.insert(index, head);
}
void QLCFixtureMode::removeHead(int index)
{
if (index >= 0 && index < m_heads.size())
m_heads.remove(index);
}
void QLCFixtureMode::replaceHead(int index, const QLCFixtureHead& head)
{
if (index >= 0 && index < m_heads.size())
m_heads[index] = head;
}
QVector <QLCFixtureHead> const& QLCFixtureMode::heads() const
{
return m_heads;
}
int QLCFixtureMode::headForChannel(quint32 chnum) const
{
for (int i = 0; i < m_heads.size(); i++)
{
if (m_heads[i].channels().contains(chnum) == true)
return i;
}
return -1;
}
void QLCFixtureMode::cacheHeads()
{
for (int i = 0; i < m_heads.size(); i++)
{
QLCFixtureHead& head(m_heads[i]);
head.cacheChannels(this);
}
}
/****************************************************************************
* Physical
****************************************************************************/
void QLCFixtureMode::setPhysical(const QLCPhysical& physical)
{
m_physical = physical;
}
QLCPhysical QLCFixtureMode::physical() const
{
return m_physical;
}
/****************************************************************************
* Load & Save
****************************************************************************/
bool QLCFixtureMode::loadXML(const QDomElement& root)
{
if (root.tagName() != KXMLQLCFixtureMode)
{
qWarning() << Q_FUNC_INFO << "Mode tag not found";
return false;
}
/* Mode name */
QString str = root.attribute(KXMLQLCFixtureModeName);
if (str.isEmpty() == true)
{
qWarning() << Q_FUNC_INFO << "Mode has no name";
return false;
}
else
{
setName(str);
}
/* Subtags */
QDomNode node = root.firstChild();
while (node.isNull() == false)
{
QDomElement tag = node.toElement();
if (tag.tagName() == KXMLQLCFixtureModeChannel)
{
/* Channel */
Q_ASSERT(m_fixtureDef != NULL);
str = tag.attribute(KXMLQLCFixtureModeChannelNumber);
insertChannel(m_fixtureDef->channel(tag.text()),
str.toInt());
}
else if (tag.tagName() == KXMLQLCFixtureHead)
{
/* Head */
QLCFixtureHead head;
if (head.loadXML(tag) == true)
insertHead(-1, head);
}
else if (tag.tagName() == KXMLQLCPhysical)
{
/* Physical */
QLCPhysical physical;
physical.loadXML(tag);
setPhysical(physical);
}
else
{
qWarning() << Q_FUNC_INFO << "Unknown Fixture Mode tag:" << tag.tagName();
}
node = node.nextSibling();
}
// Cache all head channels
cacheHeads();
return true;
}
bool QLCFixtureMode::saveXML(QDomDocument* doc, QDomElement* root)
{
QDomElement tag;
QDomElement chtag;
QDomText text;
QString str;
int i = 0;
Q_ASSERT(doc != NULL);
Q_ASSERT(root != NULL);
/* Mode entry */
tag = doc->createElement(KXMLQLCFixtureMode);
tag.setAttribute(KXMLQLCFixtureModeName, m_name);
root->appendChild(tag);
m_physical.saveXML(doc, &tag);
/* Channels */
QVectorIterator <QLCChannel*> it(m_channels);
while (it.hasNext() == true)
{
chtag = doc->createElement(KXMLQLCFixtureModeChannel);
tag.appendChild(chtag);
str.setNum(i++);
chtag.setAttribute(KXMLQLCFixtureModeChannelNumber, str);
text = doc->createTextNode(it.next()->name());
chtag.appendChild(text);
}
/* Heads */
QVectorIterator <QLCFixtureHead> hit(m_heads);
while (hit.hasNext() == true)
hit.next().saveXML(doc, &tag);
return true;
}
|
#include <nan.h>
#include <fstream>
#include "hive.h"
using namespace v8;
static uv_key_t isolate_cache_key;
static uv_key_t context_cache_key;
static uv_once_t key_guard;
static std::ifstream f("node_modules/babel-core/browser.js");
static std::string babel(
(std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
// Initialize libuv thread-local cache keys.
static void create_keys() {
(void) uv_key_create(&isolate_cache_key);
(void) uv_key_create(&context_cache_key);
}
// Returns an Isolate* from the thread-local cache, if it exists.
// Otherwise, creates and caches a new Isolate* before returning.
static Isolate* get_isolate() {
Isolate* isolate = (Isolate *) uv_key_get(&isolate_cache_key);
if (isolate == NULL) {
isolate = Isolate::New();
uv_key_set(&isolate_cache_key, isolate);
}
return isolate;
}
// Returns a Persistent<Context>* from the thread-local cache, if it exists.
// Otherwise, creates a new Persistent<Context>* in the given isolate, and
// evaluates the Babel bootstrap script to prepare the context for file
// transformation.
static Persistent<Context>* get_context(Isolate* isolate) {
Persistent<Context>* context =
(Persistent<Context> *) uv_key_get(&context_cache_key);
if (context == NULL) {
Local<Context> ctx = Context::New(isolate);
context = new Persistent<Context>(isolate, ctx);
Context::Scope context_scope(ctx);
Local<Script> script = Script::Compile(
String::NewFromUtf8(isolate, babel.c_str()));
(void) script->Run();
uv_key_set(&context_cache_key, context);
}
return context;
}
// Transforms the given file contents in a new v8 isolate on Node's default
// libuv thread pool, returning the result of the transformation on the main
// event loop.
class HiveWorker : public NanAsyncWorker {
public:
HiveWorker(NanCallback* callback, std::string path, std::string script)
: NanAsyncWorker(callback), path(path), script(script) {}
~HiveWorker() {}
// Executed inside the worker-thread.
void Execute () {
(void) uv_once(&key_guard, create_keys);
Isolate* isolate = get_isolate();
Isolate::Scope isolate_scope(isolate);
NanLocker();
NanScope();
Persistent<Context>* context = get_context(isolate);
Context::Scope context_scope(Local<Context>::New(isolate, *context));
Local<Script> s = Script::Compile(NanNew<String>(script.c_str()));
Local<Value> result = s->Run();
res = result->IntegerValue();
NanUnlocker();
}
// Executed when the async work is complete, inside the main thread.
void HandleOKCallback () {
NanScope();
Local<Value> argv[] = {
NanNull(),
NanNew<Number>(res)
};
callback->Call(2, argv);
}
private:
std::string path;
std::string script;
int64_t res;
};
NAN_METHOD(Take) {
NanScope();
String::Utf8Value p(args[0]->ToString());
std::string path(*p);
String::Utf8Value s(args[1]->ToString());
std::string script(*s);
NanCallback *callback = new NanCallback(args[2].As<Function>());
NanAsyncQueueWorker(new HiveWorker(callback, path, script));
NanReturnUndefined();
}
Return string values from script eval
#include <nan.h>
#include <fstream>
#include "hive.h"
using namespace v8;
static uv_key_t isolate_cache_key;
static uv_key_t context_cache_key;
static uv_once_t key_guard;
static std::ifstream f("node_modules/babel-core/browser.js");
static std::string babel(
(std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
// Initialize libuv thread-local cache keys.
static void create_keys() {
(void) uv_key_create(&isolate_cache_key);
(void) uv_key_create(&context_cache_key);
}
// Returns an Isolate* from the thread-local cache, if it exists.
// Otherwise, creates and caches a new Isolate* before returning.
static Isolate* get_isolate() {
Isolate* isolate = (Isolate *) uv_key_get(&isolate_cache_key);
if (isolate == NULL) {
isolate = Isolate::New();
uv_key_set(&isolate_cache_key, isolate);
}
return isolate;
}
// Returns a Persistent<Context>* from the thread-local cache, if it exists.
// Otherwise, creates a new Persistent<Context>* in the given isolate, and
// evaluates the Babel bootstrap script to prepare the context for file
// transformation.
static Persistent<Context>* get_context(Isolate* isolate) {
Persistent<Context>* context =
(Persistent<Context> *) uv_key_get(&context_cache_key);
if (context == NULL) {
Local<Context> ctx = Context::New(isolate);
context = new Persistent<Context>(isolate, ctx);
Context::Scope context_scope(ctx);
Local<Script> script = Script::Compile(
String::NewFromUtf8(isolate, babel.c_str()));
(void) script->Run();
uv_key_set(&context_cache_key, context);
}
return context;
}
// Transforms the given file contents in a new v8 isolate on Node's default
// libuv thread pool, returning the result of the transformation on the main
// event loop.
class HiveWorker : public NanAsyncWorker {
public:
HiveWorker(NanCallback* callback, std::string path, std::string script)
: NanAsyncWorker(callback), path(path), script(script) {}
~HiveWorker() {}
// Executed inside the worker-thread.
void Execute () {
(void) uv_once(&key_guard, create_keys);
Isolate* isolate = get_isolate();
Isolate::Scope isolate_scope(isolate);
NanLocker();
NanScope();
Persistent<Context>* context = get_context(isolate);
Context::Scope context_scope(Local<Context>::New(isolate, *context));
Local<Script> s = Script::Compile(NanNew<String>(script.c_str()));
Local<String> result = s->Run()->ToString();
String::Utf8Value r(result);
res = std::string(*r);
NanUnlocker();
}
// Executed when the async work is complete, inside the main thread.
void HandleOKCallback () {
NanScope();
Local<Value> argv[] = {
NanNull(),
NanNew<String>(res.c_str())
};
callback->Call(2, argv);
}
private:
std::string path;
std::string script;
std::string res;
};
NAN_METHOD(Take) {
NanScope();
String::Utf8Value p(args[0]->ToString());
std::string path(*p);
String::Utf8Value s(args[1]->ToString());
std::string script(*s);
NanCallback *callback = new NanCallback(args[2].As<Function>());
NanAsyncQueueWorker(new HiveWorker(callback, path, script));
NanReturnUndefined();
}
|
#include "S2_Sprite.h"
#include "S2_Symbol.h"
#include "OBB.h"
#include "RenderFilter.h"
#include "FilterFactory.h"
namespace s2
{
Sprite::Sprite()
: m_sym(NULL)
, m_position(0, 0)
, m_angle(0)
, m_scale(1, 1)
, m_shear(0, 0)
, m_visible(true)
{
m_offset.MakeInvalid();
m_bounding = new OBB();
m_bounding_dirty = true;
m_shader.filter = FilterFactory::Instance()->Create(FM_NULL);
}
Sprite::Sprite(const Sprite& spr)
: m_sym(NULL)
, m_position(spr.m_position)
, m_angle(spr.m_angle)
, m_scale(spr.m_scale)
, m_shear(spr.m_shear)
, m_offset(spr.m_offset)
, m_color(spr.m_color)
, m_shader(spr.m_shader)
, m_camera(spr.m_camera)
, m_visible(spr.m_visible)
{
if (spr.m_sym) {
spr.m_sym->AddReference();
m_sym = spr.m_sym;
}
m_bounding = spr.m_bounding->Clone();
m_bounding_dirty = true;
FilterMode fm = FM_NULL;
if (spr.Shader().filter) {
fm = spr.Shader().filter->GetMode();
}
m_shader.filter = FilterFactory::Instance()->Create(fm);
}
Sprite::Sprite(Symbol* sym)
: m_sym(NULL)
, m_position(0, 0)
, m_angle(0)
, m_scale(1, 1)
, m_shear(0, 0)
, m_visible(true)
{
m_offset.MakeInvalid();
m_bounding = new OBB();
SetSymbol(sym);
m_shader.filter = FilterFactory::Instance()->Create(FM_NULL);
}
Sprite::~Sprite()
{
if (m_sym) {
m_sym->RemoveReference();
}
delete m_bounding;
delete m_shader.filter;
}
void Sprite::Translate(const sm::vec2& offset)
{
m_position += offset;
}
void Sprite::Rotate(float delta)
{
m_angle += delta;
}
void Sprite::SetSymbol(Symbol* sym)
{
cu::RefCountObjAssign(m_sym, sym);
UpdateBounding();
}
const BoundingBox* Sprite::GetBounding() const
{
if (m_bounding_dirty) {
UpdateBounding();
}
return m_bounding;
}
// todo: m_sym->GetBounding too slow, should be cached
void Sprite::UpdateBounding() const
{
if (!m_sym) {
return;
}
sm::rect rect = m_sym->GetBounding(this);
if (!m_offset.IsValid()) {
m_offset = rect.Center();
}
m_bounding_dirty = false;
m_bounding->Build(rect, m_position, m_angle, m_scale, m_shear, m_offset);
}
sm::vec2 Sprite::GetCenter() const
{
sm::vec2 center_offset = sm::rotate_vector(-m_offset, m_angle) + m_offset;
sm::vec2 center = m_position + center_offset;
return center;
}
void Sprite::SetPosition(const sm::vec2& pos)
{
m_position = pos;
// // immediately
// m_bounding->SetTransform(m_position, m_offset, m_angle);
// lazy
m_bounding_dirty = true;
}
void Sprite::SetAngle(float angle)
{
m_angle = angle;
// // immediately
// m_bounding->SetTransform(m_position, m_offset, m_angle);
// lazy
m_bounding_dirty = true;
}
void Sprite::SetScale(const sm::vec2& scale)
{
const sm::vec2& old_scale = m_scale;
if (old_scale.x != 0 && old_scale.y != 0) {
sm::vec2 dscale;
dscale.x = scale.x / m_scale.x;
dscale.y = scale.y / m_scale.y;
sm::vec2 old_offset = m_offset;
sm::vec2 new_offset(m_offset.x * dscale.x, m_offset.y * dscale.y);
m_offset = new_offset;
Translate(old_offset - new_offset);
}
m_scale = scale;
// lazy
m_bounding_dirty = true;
}
void Sprite::SetShear(const sm::vec2& shear)
{
sm::mat4 mat_old, mat_new;
mat_old.Shear(m_shear.x, m_shear.y);
mat_new.Shear(shear.x, shear.y);
sm::vec2 offset = mat_new * m_offset - mat_old * m_offset;
m_offset += offset;
Translate(-offset);
m_shear = shear;
// immediately
m_bounding->SetTransform(m_position, m_offset, m_angle);
// // lazy
// m_bounding_dirty = true;
}
void Sprite::SetOffset(const sm::vec2& offset)
{
// rotate + offset -> offset + rotate
sm::vec2 old_center = GetCenter();
m_offset = offset;
sm::vec2 new_center = GetCenter();
Translate(old_center - new_center);
// immediately
m_bounding->SetTransform(m_position, m_offset, m_angle);
// // lazy
// m_bounding_dirty = true;
}
sm::mat4 Sprite::GetTransMatrix() const
{
sm::vec2 center = GetCenter();
sm::mat4 mt;
mt.SetTransformation(center.x, center.y, m_angle,
m_scale.x, m_scale.y, 0, 0, m_shear.x, m_shear.y);
return mt;
}
sm::mat4 Sprite::GetTransInvMatrix() const
{
sm::mat4 mat;
mat.RotateZ(-m_angle);
mat.Shear(-m_shear.x, -m_shear.y);
mat.Translate(-m_position.x/m_scale.x, -m_position.y/m_scale.y, 0);
mat.Scale(1/m_scale.x, 1/m_scale.y, 1);
return mat;
}
}
[FIXED] spr set sym in ctor
Former-commit-id: 40c82bc906f3188b6af7d7871903cd3d8958731a
#include "S2_Sprite.h"
#include "S2_Symbol.h"
#include "OBB.h"
#include "RenderFilter.h"
#include "FilterFactory.h"
namespace s2
{
Sprite::Sprite()
: m_sym(NULL)
, m_position(0, 0)
, m_angle(0)
, m_scale(1, 1)
, m_shear(0, 0)
, m_visible(true)
{
m_offset.MakeInvalid();
m_bounding = new OBB();
m_bounding_dirty = true;
m_shader.filter = FilterFactory::Instance()->Create(FM_NULL);
}
Sprite::Sprite(const Sprite& spr)
: m_sym(NULL)
, m_position(spr.m_position)
, m_angle(spr.m_angle)
, m_scale(spr.m_scale)
, m_shear(spr.m_shear)
, m_offset(spr.m_offset)
, m_color(spr.m_color)
, m_shader(spr.m_shader)
, m_camera(spr.m_camera)
, m_visible(spr.m_visible)
{
if (spr.m_sym) {
spr.m_sym->AddReference();
m_sym = spr.m_sym;
}
m_bounding = spr.m_bounding->Clone();
m_bounding_dirty = true;
FilterMode fm = FM_NULL;
if (spr.Shader().filter) {
fm = spr.Shader().filter->GetMode();
}
m_shader.filter = FilterFactory::Instance()->Create(fm);
}
Sprite::Sprite(Symbol* sym)
: m_sym(NULL)
, m_position(0, 0)
, m_angle(0)
, m_scale(1, 1)
, m_shear(0, 0)
, m_visible(true)
{
cu::RefCountObjAssign(m_sym, sym);
m_offset.MakeInvalid();
m_bounding = new OBB();
m_bounding_dirty = true;
m_shader.filter = FilterFactory::Instance()->Create(FM_NULL);
}
Sprite::~Sprite()
{
if (m_sym) {
m_sym->RemoveReference();
}
delete m_bounding;
delete m_shader.filter;
}
void Sprite::Translate(const sm::vec2& offset)
{
m_position += offset;
}
void Sprite::Rotate(float delta)
{
m_angle += delta;
}
void Sprite::SetSymbol(Symbol* sym)
{
cu::RefCountObjAssign(m_sym, sym);
UpdateBounding();
}
const BoundingBox* Sprite::GetBounding() const
{
if (m_bounding_dirty) {
UpdateBounding();
}
return m_bounding;
}
// todo: m_sym->GetBounding too slow, should be cached
void Sprite::UpdateBounding() const
{
if (!m_sym) {
return;
}
sm::rect rect = m_sym->GetBounding(this);
if (!m_offset.IsValid()) {
m_offset = rect.Center();
}
m_bounding_dirty = false;
m_bounding->Build(rect, m_position, m_angle, m_scale, m_shear, m_offset);
}
sm::vec2 Sprite::GetCenter() const
{
sm::vec2 center_offset = sm::rotate_vector(-m_offset, m_angle) + m_offset;
sm::vec2 center = m_position + center_offset;
return center;
}
void Sprite::SetPosition(const sm::vec2& pos)
{
m_position = pos;
// // immediately
// m_bounding->SetTransform(m_position, m_offset, m_angle);
// lazy
m_bounding_dirty = true;
}
void Sprite::SetAngle(float angle)
{
m_angle = angle;
// // immediately
// m_bounding->SetTransform(m_position, m_offset, m_angle);
// lazy
m_bounding_dirty = true;
}
void Sprite::SetScale(const sm::vec2& scale)
{
const sm::vec2& old_scale = m_scale;
if (old_scale.x != 0 && old_scale.y != 0) {
sm::vec2 dscale;
dscale.x = scale.x / m_scale.x;
dscale.y = scale.y / m_scale.y;
sm::vec2 old_offset = m_offset;
sm::vec2 new_offset(m_offset.x * dscale.x, m_offset.y * dscale.y);
m_offset = new_offset;
Translate(old_offset - new_offset);
}
m_scale = scale;
// lazy
m_bounding_dirty = true;
}
void Sprite::SetShear(const sm::vec2& shear)
{
sm::mat4 mat_old, mat_new;
mat_old.Shear(m_shear.x, m_shear.y);
mat_new.Shear(shear.x, shear.y);
sm::vec2 offset = mat_new * m_offset - mat_old * m_offset;
m_offset += offset;
Translate(-offset);
m_shear = shear;
// immediately
m_bounding->SetTransform(m_position, m_offset, m_angle);
// // lazy
// m_bounding_dirty = true;
}
void Sprite::SetOffset(const sm::vec2& offset)
{
// rotate + offset -> offset + rotate
sm::vec2 old_center = GetCenter();
m_offset = offset;
sm::vec2 new_center = GetCenter();
Translate(old_center - new_center);
// immediately
m_bounding->SetTransform(m_position, m_offset, m_angle);
// // lazy
// m_bounding_dirty = true;
}
sm::mat4 Sprite::GetTransMatrix() const
{
sm::vec2 center = GetCenter();
sm::mat4 mt;
mt.SetTransformation(center.x, center.y, m_angle,
m_scale.x, m_scale.y, 0, 0, m_shear.x, m_shear.y);
return mt;
}
sm::mat4 Sprite::GetTransInvMatrix() const
{
sm::mat4 mat;
mat.RotateZ(-m_angle);
mat.Shear(-m_shear.x, -m_shear.y);
mat.Translate(-m_position.x/m_scale.x, -m_position.y/m_scale.y, 0);
mat.Scale(1/m_scale.x, 1/m_scale.y, 1);
return mat;
}
} |
// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI 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.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_UNITS_DURATION_HPP
#define IOX_HOOFS_UNITS_DURATION_HPP
#include "iceoryx_hoofs/cxx/expected.hpp"
#include "iceoryx_hoofs/platform/time.hpp" // required for QNX
#include <chrono>
#include <cmath>
#include <iostream>
#include <numeric>
namespace iox
{
namespace units
{
enum class TimeSpecReference
{
None,
Epoch,
Monotonic
};
class Duration;
inline namespace duration_literals
{
/// @brief Constructs a new Duration object from nanoseconds
constexpr Duration operator"" _ns(unsigned long long int) noexcept; // PRQA S 48
/// @brief Constructs a new Duration object from microseconds
constexpr Duration operator"" _us(unsigned long long int) noexcept; // PRQA S 48
/// @brief Constructs a new Duration object from milliseconds
constexpr Duration operator"" _ms(unsigned long long int) noexcept; // PRQA S 48
/// @brief Constructs a new Duration object from seconds
constexpr Duration operator"" _s(unsigned long long int) noexcept; // PRQA S 48
/// @brief Constructs a new Duration object from minutes
constexpr Duration operator"" _m(unsigned long long int) noexcept; // PRQA S 48
/// @brief Constructs a new Duration object from hours
constexpr Duration operator"" _h(unsigned long long int) noexcept; // PRQA S 48
/// @brief Constructs a new Duration object from days
constexpr Duration operator"" _d(unsigned long long int) noexcept; // PRQA S 48
} // namespace duration_literals
/// @code
/// #include <iostream>
/// // ...
/// using namespace units;
/// using namespace units::duration_literals;
/// auto someDays = 2 * 7_d + 5_ns;
/// auto someSeconds = 42_s + 500_ms;
/// std::cout << someDays << std::endl;
/// std::cout << someDays.nanoSeconds<uint64_t>() << " ns" << std::endl;
/// std::cout << someSeconds.milliSeconds<int64_t>() << " ms" << std::endl;
/// @endcode
class Duration
{
public:
// BEGIN CREATION FROM STATIC FUNCTIONS
/// @brief Constructs a new Duration object from nanoseconds
/// @tparam T is an integer type for the value
/// @param[in] value as nanoseconds
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
static constexpr Duration fromNanoseconds(const T value) noexcept;
/// @brief Constructs a new Duration object from microseconds
/// @tparam T is an integer type for the value
/// @param[in] value as microseconds
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
static constexpr Duration fromMicroseconds(const T value) noexcept;
/// @brief Constructs a new Duration object from milliseconds
/// @tparam T is an integer type for the value
/// @param[in] value as milliseconds
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
static constexpr Duration fromMilliseconds(const T value) noexcept;
/// @brief Constructs a new Duration object from seconds
/// @tparam T is an integer type for the value
/// @param[in] value as seconds
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
static constexpr Duration fromSeconds(const T value) noexcept;
/// @brief Constructs a new Duration object from minutes
/// @tparam T is an integer type for the value
/// @param[in] value as minutes
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
static constexpr Duration fromMinutes(const T value) noexcept;
/// @brief Constructs a new Duration object from hours
/// @tparam T is an integer type for the value
/// @param[in] value as hours
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
static constexpr Duration fromHours(const T value) noexcept;
/// @brief Constructs a new Duration object from days
/// @tparam T is an integer type for the value
/// @param[in] value as days
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
static constexpr Duration fromDays(const T value) noexcept;
/// @brief Constructs a new Duration object of maximum allowed length. Useful for functions which should have an
/// "infinite" timeout.
static constexpr Duration max() noexcept;
/// @brief Constructs a new Duration object with a duration of zero
static constexpr Duration zero() noexcept;
// END CREATION FROM STATIC FUNCTIONS
// BEGIN CONSTRUCTORS AND ASSIGNMENT
/// @brief Construct a Duration object from timeval
/// @param[in] value as timeval
constexpr explicit Duration(const struct timeval& value) noexcept;
/// @brief Construct a Duration object from timespec
/// @param[in] value as timespec
constexpr explicit Duration(const struct timespec& value) noexcept;
/// @brief Construct a Duration object from itimerspec
/// @param[in] value as itimerspec
/// @note only it_interval from the itimerspec is used
constexpr explicit Duration(const struct itimerspec& value) noexcept;
/// @brief Construct a Duration object from std::chrono::milliseconds
/// @param[in] value as milliseconds
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
constexpr explicit Duration(const std::chrono::milliseconds& value) noexcept;
/// @brief Construct a Duration object from std::chrono::nanoseconds
/// @param[in] value as nanoseconds
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
constexpr explicit Duration(const std::chrono::nanoseconds& value) noexcept;
/// @brief Assigns a std::chrono::milliseconds to an duration object
/// @param[in] rhs is the right hand side of the assignment
/// @return a reference to the Duration object with the assigned millisecond value
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
Duration& operator=(const std::chrono::milliseconds& rhs) noexcept;
// END CONSTRUCTORS AND ASSIGNMENT
// BEGIN COMPARISON
/// @brief Equal to operator
/// @param[in] rhs is the right hand side of the comparison
/// @return true if duration equal to rhs
constexpr bool operator==(const Duration& rhs) const noexcept;
/// @brief Not equal to operator
/// @param[in] rhs is the right hand side of the comparison
/// @return true if duration not equal to rhs
constexpr bool operator!=(const Duration& rhs) const noexcept;
/// @brief Less than operator
/// @param[in] rhs is the right hand side of the comparison
/// @return true if duration is less than rhs
constexpr bool operator<(const Duration& rhs) const noexcept;
/// @brief Less than or equal to operator
/// @param[in] rhs is the right hand side of the comparison
/// @return true if duration is less than or equal to rhs
constexpr bool operator<=(const Duration& rhs) const noexcept;
/// @brief Greater than operator
/// @param[in] rhs is the right hand side of the comparison
/// @return true if duration is greater than rhs
constexpr bool operator>(const Duration& rhs) const noexcept;
/// @brief Greater than or equal to operator
/// @param[in] rhs is the right hand side of the comparison
/// @return true if duration is greater than or equal to rhs
constexpr bool operator>=(const Duration& rhs) const noexcept;
// END COMPARISON
// BEGIN ARITHMETIC
/// @brief Creates Duration object by addition
/// @param[in] rhs is the second summand
/// @return a new Duration object
constexpr Duration operator+(const Duration& rhs) const noexcept;
/// @brief Creates Duration object by subtraction
/// @param[in] rhs is the subtrahend
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
constexpr Duration operator-(const Duration& rhs) const noexcept;
/// @brief Creates Duration object by multiplication
/// @tparam T is an arithmetic type for the multiplicator
/// @param[in] rhs is the multiplicator
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
/// @note A duration of 0 will always result in 0, no matter if multiplied with NaN or +Inf
/// @note There is no explicit division operator! This can be achieved by multiplication with the inverse of the
/// divisor.
/// @note Multiplication of a non-zero duration with NaN and +Inf results in a saturated max duration
template <typename T>
constexpr Duration operator*(const T& rhs) const noexcept;
// END ARITHMETIC
// BEGIN CONVERSION
/// @brief returns the duration in nanoseconds
/// @note If the duration in nanoseconds is larger than an uint64_t can represent, it will be clamped to the
/// uint64_t max value.
constexpr uint64_t toNanoseconds() const noexcept;
/// @brief returns the duration in microseconds
/// @note If the duration in microseconds is larger than an uint64_t can represent, it will be clamped to the
/// uint64_t max value.
/// @note The remaining nanoseconds are truncated, similar to the casting behavior of a float to an int.
constexpr uint64_t toMicroseconds() const noexcept;
/// @brief returns the duration in milliseconds
/// @note If the duration in milliseconds is larger than an uint64_t can represent, it will be clamped to the
/// uint64_t max value.
/// @note The remaining microseconds are truncated, similar to the casting behavior of a float to an int.
constexpr uint64_t toMilliseconds() const noexcept;
/// @brief returns the duration in seconds
/// @note The remaining milliseconds are truncated, similar to the casting behavior of a float to an int.
constexpr uint64_t toSeconds() const noexcept;
/// @brief returns the duration in minutes
/// @note The remaining seconds are truncated, similar to the casting behavior of a float to an int.
constexpr uint64_t toMinutes() const noexcept;
/// @brief returns the duration in hours
/// @note The remaining minutes are truncated, similar to the casting behavior of a float to an int.
constexpr uint64_t toHours() const noexcept;
/// @brief returns the duration in days
/// @note The remaining hours are truncated, similar to the casting behavior of a float to an int.
constexpr uint64_t toDays() const noexcept;
/// @brief converts duration in a timespec c struct
struct timespec timespec(const TimeSpecReference& reference = TimeSpecReference::None) const noexcept;
/// @brief converts duration in a timeval c struct
/// timeval::tv_sec = seconds since the Epoch (01.01.1970)
/// timeval::tv_usec = microseconds
constexpr operator struct timeval() const noexcept;
// END CONVERSION
friend constexpr Duration duration_literals::operator"" _ns(unsigned long long int) noexcept; // PRQA S 48
friend constexpr Duration duration_literals::operator"" _us(unsigned long long int) noexcept; // PRQA S 48
friend constexpr Duration duration_literals::operator"" _ms(unsigned long long int) noexcept; // PRQA S 48
friend constexpr Duration duration_literals::operator"" _s(unsigned long long int) noexcept; // PRQA S 48
friend constexpr Duration duration_literals::operator"" _m(unsigned long long int) noexcept; // PRQA S 48
friend constexpr Duration duration_literals::operator"" _h(unsigned long long int) noexcept; // PRQA S 48
friend constexpr Duration duration_literals::operator"" _d(unsigned long long int) noexcept; // PRQA S 48
template <typename T>
friend constexpr Duration operator*(const T& lhs, const Duration& rhs) noexcept;
friend std::ostream& operator<<(std::ostream& stream, const Duration& t) noexcept;
static constexpr uint32_t SECS_PER_MINUTE{60U};
static constexpr uint32_t SECS_PER_HOUR{3600U};
static constexpr uint32_t HOURS_PER_DAY{24U};
static constexpr uint32_t MILLISECS_PER_SEC{1000U};
static constexpr uint32_t MICROSECS_PER_SEC{MILLISECS_PER_SEC * 1000U};
static constexpr uint32_t NANOSECS_PER_MICROSEC{1000U};
static constexpr uint32_t NANOSECS_PER_MILLISEC{NANOSECS_PER_MICROSEC * 1000U};
static constexpr uint32_t NANOSECS_PER_SEC{NANOSECS_PER_MILLISEC * 1000U};
protected:
using Seconds_t = uint64_t;
using Nanoseconds_t = uint32_t;
/// @brief Constructs a Duration from seconds and nanoseconds
/// @param[in] seconds portion of the duration
/// @param[in] nanoseconds portion of the duration
/// @note this is protected to be able to use it in unit tests
constexpr Duration(const Seconds_t seconds, const Nanoseconds_t nanoseconds) noexcept;
/// @note this is factory method is necessary to build with msvc due to issues calling a protected constexpr ctor
/// from public methods
static constexpr Duration createDuration(const Seconds_t seconds, const Nanoseconds_t nanoseconds) noexcept;
private:
template <typename T, typename String>
static constexpr unsigned long long int positiveValueOrClampToZero(const T value, const String fromMethod) noexcept;
template <typename T>
constexpr Duration fromFloatingPointSeconds(const T floatingPointSeconds) const noexcept;
template <typename From, typename To>
constexpr bool wouldCastFromFloatingPointProbablyOverflow(const From floatingPoint) const noexcept;
template <typename T>
constexpr Duration multiplyWith(const std::enable_if_t<!std::is_floating_point<T>::value, T>& rhs) const noexcept;
template <typename T>
constexpr Duration multiplyWith(const std::enable_if_t<std::is_floating_point<T>::value, T>& rhs) const noexcept;
private:
Seconds_t m_seconds{0U};
Nanoseconds_t m_nanoseconds{0U};
};
/// @brief creates Duration object by multiplying object T with a duration
/// @tparam T is an arithmetic type for the multiplicator
/// @param[in] lhs is the multiplicator
/// @param[in] rhs is the multiplicant
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
constexpr Duration operator*(const T& lhs, const Duration& rhs) noexcept;
/// @brief stream operator for the Duration class
std::ostream& operator<<(std::ostream& stream, const Duration& t) noexcept;
} // namespace units
} // namespace iox
#include "iceoryx_hoofs/internal/units/duration.inl"
#endif // IOX_HOOFS_UNITS_DURATION_HPP
iox-#1078 Make duration_literals a non inlined namespace
Signed-off-by: Christian Eltzschig <b1c1d8736f20db3fb6c1c66bb1455ed43909f0d8@elchris.org>
// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI 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.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_UNITS_DURATION_HPP
#define IOX_HOOFS_UNITS_DURATION_HPP
#include "iceoryx_hoofs/cxx/expected.hpp"
#include "iceoryx_hoofs/platform/time.hpp" // required for QNX
#include <chrono>
#include <cmath>
#include <iostream>
#include <numeric>
namespace iox
{
namespace units
{
enum class TimeSpecReference
{
None,
Epoch,
Monotonic
};
class Duration;
namespace duration_literals
{
/// @brief Constructs a new Duration object from nanoseconds
constexpr Duration operator"" _ns(unsigned long long int) noexcept; // PRQA S 48
/// @brief Constructs a new Duration object from microseconds
constexpr Duration operator"" _us(unsigned long long int) noexcept; // PRQA S 48
/// @brief Constructs a new Duration object from milliseconds
constexpr Duration operator"" _ms(unsigned long long int) noexcept; // PRQA S 48
/// @brief Constructs a new Duration object from seconds
constexpr Duration operator"" _s(unsigned long long int) noexcept; // PRQA S 48
/// @brief Constructs a new Duration object from minutes
constexpr Duration operator"" _m(unsigned long long int) noexcept; // PRQA S 48
/// @brief Constructs a new Duration object from hours
constexpr Duration operator"" _h(unsigned long long int) noexcept; // PRQA S 48
/// @brief Constructs a new Duration object from days
constexpr Duration operator"" _d(unsigned long long int) noexcept; // PRQA S 48
} // namespace duration_literals
/// @code
/// #include <iostream>
/// // ...
/// using namespace units;
/// using namespace units::duration_literals;
/// auto someDays = 2 * 7_d + 5_ns;
/// auto someSeconds = 42_s + 500_ms;
/// std::cout << someDays << std::endl;
/// std::cout << someDays.nanoSeconds<uint64_t>() << " ns" << std::endl;
/// std::cout << someSeconds.milliSeconds<int64_t>() << " ms" << std::endl;
/// @endcode
class Duration
{
public:
// BEGIN CREATION FROM STATIC FUNCTIONS
/// @brief Constructs a new Duration object from nanoseconds
/// @tparam T is an integer type for the value
/// @param[in] value as nanoseconds
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
static constexpr Duration fromNanoseconds(const T value) noexcept;
/// @brief Constructs a new Duration object from microseconds
/// @tparam T is an integer type for the value
/// @param[in] value as microseconds
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
static constexpr Duration fromMicroseconds(const T value) noexcept;
/// @brief Constructs a new Duration object from milliseconds
/// @tparam T is an integer type for the value
/// @param[in] value as milliseconds
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
static constexpr Duration fromMilliseconds(const T value) noexcept;
/// @brief Constructs a new Duration object from seconds
/// @tparam T is an integer type for the value
/// @param[in] value as seconds
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
static constexpr Duration fromSeconds(const T value) noexcept;
/// @brief Constructs a new Duration object from minutes
/// @tparam T is an integer type for the value
/// @param[in] value as minutes
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
static constexpr Duration fromMinutes(const T value) noexcept;
/// @brief Constructs a new Duration object from hours
/// @tparam T is an integer type for the value
/// @param[in] value as hours
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
static constexpr Duration fromHours(const T value) noexcept;
/// @brief Constructs a new Duration object from days
/// @tparam T is an integer type for the value
/// @param[in] value as days
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
static constexpr Duration fromDays(const T value) noexcept;
/// @brief Constructs a new Duration object of maximum allowed length. Useful for functions which should have an
/// "infinite" timeout.
static constexpr Duration max() noexcept;
/// @brief Constructs a new Duration object with a duration of zero
static constexpr Duration zero() noexcept;
// END CREATION FROM STATIC FUNCTIONS
// BEGIN CONSTRUCTORS AND ASSIGNMENT
/// @brief Construct a Duration object from timeval
/// @param[in] value as timeval
constexpr explicit Duration(const struct timeval& value) noexcept;
/// @brief Construct a Duration object from timespec
/// @param[in] value as timespec
constexpr explicit Duration(const struct timespec& value) noexcept;
/// @brief Construct a Duration object from itimerspec
/// @param[in] value as itimerspec
/// @note only it_interval from the itimerspec is used
constexpr explicit Duration(const struct itimerspec& value) noexcept;
/// @brief Construct a Duration object from std::chrono::milliseconds
/// @param[in] value as milliseconds
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
constexpr explicit Duration(const std::chrono::milliseconds& value) noexcept;
/// @brief Construct a Duration object from std::chrono::nanoseconds
/// @param[in] value as nanoseconds
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
constexpr explicit Duration(const std::chrono::nanoseconds& value) noexcept;
/// @brief Assigns a std::chrono::milliseconds to an duration object
/// @param[in] rhs is the right hand side of the assignment
/// @return a reference to the Duration object with the assigned millisecond value
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
Duration& operator=(const std::chrono::milliseconds& rhs) noexcept;
// END CONSTRUCTORS AND ASSIGNMENT
// BEGIN COMPARISON
/// @brief Equal to operator
/// @param[in] rhs is the right hand side of the comparison
/// @return true if duration equal to rhs
constexpr bool operator==(const Duration& rhs) const noexcept;
/// @brief Not equal to operator
/// @param[in] rhs is the right hand side of the comparison
/// @return true if duration not equal to rhs
constexpr bool operator!=(const Duration& rhs) const noexcept;
/// @brief Less than operator
/// @param[in] rhs is the right hand side of the comparison
/// @return true if duration is less than rhs
constexpr bool operator<(const Duration& rhs) const noexcept;
/// @brief Less than or equal to operator
/// @param[in] rhs is the right hand side of the comparison
/// @return true if duration is less than or equal to rhs
constexpr bool operator<=(const Duration& rhs) const noexcept;
/// @brief Greater than operator
/// @param[in] rhs is the right hand side of the comparison
/// @return true if duration is greater than rhs
constexpr bool operator>(const Duration& rhs) const noexcept;
/// @brief Greater than or equal to operator
/// @param[in] rhs is the right hand side of the comparison
/// @return true if duration is greater than or equal to rhs
constexpr bool operator>=(const Duration& rhs) const noexcept;
// END COMPARISON
// BEGIN ARITHMETIC
/// @brief Creates Duration object by addition
/// @param[in] rhs is the second summand
/// @return a new Duration object
constexpr Duration operator+(const Duration& rhs) const noexcept;
/// @brief Creates Duration object by subtraction
/// @param[in] rhs is the subtrahend
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
constexpr Duration operator-(const Duration& rhs) const noexcept;
/// @brief Creates Duration object by multiplication
/// @tparam T is an arithmetic type for the multiplicator
/// @param[in] rhs is the multiplicator
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
/// @note A duration of 0 will always result in 0, no matter if multiplied with NaN or +Inf
/// @note There is no explicit division operator! This can be achieved by multiplication with the inverse of the
/// divisor.
/// @note Multiplication of a non-zero duration with NaN and +Inf results in a saturated max duration
template <typename T>
constexpr Duration operator*(const T& rhs) const noexcept;
// END ARITHMETIC
// BEGIN CONVERSION
/// @brief returns the duration in nanoseconds
/// @note If the duration in nanoseconds is larger than an uint64_t can represent, it will be clamped to the
/// uint64_t max value.
constexpr uint64_t toNanoseconds() const noexcept;
/// @brief returns the duration in microseconds
/// @note If the duration in microseconds is larger than an uint64_t can represent, it will be clamped to the
/// uint64_t max value.
/// @note The remaining nanoseconds are truncated, similar to the casting behavior of a float to an int.
constexpr uint64_t toMicroseconds() const noexcept;
/// @brief returns the duration in milliseconds
/// @note If the duration in milliseconds is larger than an uint64_t can represent, it will be clamped to the
/// uint64_t max value.
/// @note The remaining microseconds are truncated, similar to the casting behavior of a float to an int.
constexpr uint64_t toMilliseconds() const noexcept;
/// @brief returns the duration in seconds
/// @note The remaining milliseconds are truncated, similar to the casting behavior of a float to an int.
constexpr uint64_t toSeconds() const noexcept;
/// @brief returns the duration in minutes
/// @note The remaining seconds are truncated, similar to the casting behavior of a float to an int.
constexpr uint64_t toMinutes() const noexcept;
/// @brief returns the duration in hours
/// @note The remaining minutes are truncated, similar to the casting behavior of a float to an int.
constexpr uint64_t toHours() const noexcept;
/// @brief returns the duration in days
/// @note The remaining hours are truncated, similar to the casting behavior of a float to an int.
constexpr uint64_t toDays() const noexcept;
/// @brief converts duration in a timespec c struct
struct timespec timespec(const TimeSpecReference& reference = TimeSpecReference::None) const noexcept;
/// @brief converts duration in a timeval c struct
/// timeval::tv_sec = seconds since the Epoch (01.01.1970)
/// timeval::tv_usec = microseconds
constexpr operator struct timeval() const noexcept;
// END CONVERSION
friend constexpr Duration duration_literals::operator"" _ns(unsigned long long int) noexcept; // PRQA S 48
friend constexpr Duration duration_literals::operator"" _us(unsigned long long int) noexcept; // PRQA S 48
friend constexpr Duration duration_literals::operator"" _ms(unsigned long long int) noexcept; // PRQA S 48
friend constexpr Duration duration_literals::operator"" _s(unsigned long long int) noexcept; // PRQA S 48
friend constexpr Duration duration_literals::operator"" _m(unsigned long long int) noexcept; // PRQA S 48
friend constexpr Duration duration_literals::operator"" _h(unsigned long long int) noexcept; // PRQA S 48
friend constexpr Duration duration_literals::operator"" _d(unsigned long long int) noexcept; // PRQA S 48
template <typename T>
friend constexpr Duration operator*(const T& lhs, const Duration& rhs) noexcept;
friend std::ostream& operator<<(std::ostream& stream, const Duration& t) noexcept;
static constexpr uint32_t SECS_PER_MINUTE{60U};
static constexpr uint32_t SECS_PER_HOUR{3600U};
static constexpr uint32_t HOURS_PER_DAY{24U};
static constexpr uint32_t MILLISECS_PER_SEC{1000U};
static constexpr uint32_t MICROSECS_PER_SEC{MILLISECS_PER_SEC * 1000U};
static constexpr uint32_t NANOSECS_PER_MICROSEC{1000U};
static constexpr uint32_t NANOSECS_PER_MILLISEC{NANOSECS_PER_MICROSEC * 1000U};
static constexpr uint32_t NANOSECS_PER_SEC{NANOSECS_PER_MILLISEC * 1000U};
protected:
using Seconds_t = uint64_t;
using Nanoseconds_t = uint32_t;
/// @brief Constructs a Duration from seconds and nanoseconds
/// @param[in] seconds portion of the duration
/// @param[in] nanoseconds portion of the duration
/// @note this is protected to be able to use it in unit tests
constexpr Duration(const Seconds_t seconds, const Nanoseconds_t nanoseconds) noexcept;
/// @note this is factory method is necessary to build with msvc due to issues calling a protected constexpr ctor
/// from public methods
static constexpr Duration createDuration(const Seconds_t seconds, const Nanoseconds_t nanoseconds) noexcept;
private:
template <typename T, typename String>
static constexpr unsigned long long int positiveValueOrClampToZero(const T value, const String fromMethod) noexcept;
template <typename T>
constexpr Duration fromFloatingPointSeconds(const T floatingPointSeconds) const noexcept;
template <typename From, typename To>
constexpr bool wouldCastFromFloatingPointProbablyOverflow(const From floatingPoint) const noexcept;
template <typename T>
constexpr Duration multiplyWith(const std::enable_if_t<!std::is_floating_point<T>::value, T>& rhs) const noexcept;
template <typename T>
constexpr Duration multiplyWith(const std::enable_if_t<std::is_floating_point<T>::value, T>& rhs) const noexcept;
private:
Seconds_t m_seconds{0U};
Nanoseconds_t m_nanoseconds{0U};
};
/// @brief creates Duration object by multiplying object T with a duration
/// @tparam T is an arithmetic type for the multiplicator
/// @param[in] lhs is the multiplicator
/// @param[in] rhs is the multiplicant
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
constexpr Duration operator*(const T& lhs, const Duration& rhs) noexcept;
/// @brief stream operator for the Duration class
std::ostream& operator<<(std::ostream& stream, const Duration& t) noexcept;
} // namespace units
} // namespace iox
#include "iceoryx_hoofs/internal/units/duration.inl"
#endif // IOX_HOOFS_UNITS_DURATION_HPP
|
/*********************************************************************************
* Copyright (c) 2014 David D. Marshall <ddmarsha@calpoly.edu>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Rob McDonald -- based on piecewise_capped_surface_creator.hpp
********************************************************************************/
#ifndef eli_geom_surface_piecewise_multicap_surface_creator_hpp
#define eli_geom_surface_piecewise_multicap_surface_creator_hpp
#include <list>
#include <iterator>
#include "eli/code_eli.hpp"
#include "eli/constants/math.hpp"
#include "eli/util/tolerance.hpp"
#include "eli/geom/curve/bezier.hpp"
#include "eli/geom/curve/piecewise.hpp"
#include "eli/geom/surface/bezier.hpp"
#include "eli/geom/surface/piecewise.hpp"
#include "eli/geom/surface/piecewise_creator_base.hpp"
#include "eli/geom/surface/piecewise_connection_data.hpp"
namespace eli
{
namespace geom
{
namespace surface
{
template<typename data__, unsigned short dim__, typename tol__>
class piecewise_multicap_surface_creator : public piecewise_creator_base<data__, dim__, tol__>
{
public:
enum edge_cap_identifier
{
CAP_NONE,
CAP_UMIN,
CAP_UMAX,
CAP_VMIN,
CAP_VMAX
};
enum cap_type
{
FLAT,
ROUND,
EDGE,
SHARP
};
typedef piecewise_creator_base<data__, dim__, tol__> base_class_type;
typedef typename base_class_type::data_type data_type;
typedef typename base_class_type::point_type point_type;
typedef typename base_class_type::index_type index_type;
typedef typename base_class_type::tolerance_type tolerance_type;
typedef typename base_class_type::piecewise_surface_type piecewise_surface_type;
piecewise_multicap_surface_creator()
: piecewise_creator_base<data__, dim__, tol__>(0, 0), delta_param(1), edge_to_cap(CAP_NONE)
{
}
piecewise_multicap_surface_creator(const piecewise_surface_type &os, const data_type &dp, edge_cap_identifier ec)
: piecewise_creator_base<data__, dim__, tol__>(0, 0), orig_surface(os), delta_param(dp), edge_to_cap(ec)
{
}
piecewise_multicap_surface_creator(const piecewise_multicap_surface_creator<data_type, dim__, tolerance_type> & gs)
: piecewise_creator_base<data_type, dim__, tolerance_type>(gs), orig_surface(gs.orig_surface),
delta_param(gs.delta_param), edge_to_cap(gs.edge_to_cap)
{
}
virtual ~piecewise_multicap_surface_creator()
{
}
bool set_conditions(const piecewise_surface_type &os, const index_type & typ, const data_type &dp, edge_cap_identifier ec, const data_type &lf, const data_type &of, const data_type &sf, const bool &sc )
{
// all deltas are positive, even on the min edges
if (dp<=0)
return false;
cap_type = typ;
orig_surface = os;
edge_to_cap = ec;
delta_param = dp;
len_factor = lf;
off_factor = of;
str_factor = sf;
sweep_correct = sc;
return true;
}
virtual bool create(piecewise_surface_type &ps) const
{
typedef typename eli::geom::curve::piecewise<eli::geom::curve::bezier, data_type, dim__, tolerance_type> piecewise_curve_type;
typedef typename piecewise_curve_type::curve_type curve_type;
typedef typename piecewise_surface_type::surface_type surface_type;
tolerance_type tol;
piecewise_surface_type surface_copy( orig_surface );
// Ensure opposing surface faces have mid split and matching parameter splits
switch (edge_to_cap)
{
case (CAP_UMIN):
case (CAP_UMAX):
{
data_type vmin(surface_copy.get_v0()), vmax(surface_copy.get_vmax()), vsplit((vmin+vmax)/2);
// Make sure split exists.
surface_copy.split_v( vsplit );
piecewise_curve_type edge;
surface_copy.get_umin_bndy_curve( edge );
// make sure that the split location is different than the start/end location otherwise
// the edge is a point and no need to cap
if (tol.approximately_equal(edge.f(vmin), edge.f(vsplit)))
{
return false;
}
std::vector<data_type> pmap, rpmap, cmap;
// Get original parameter map
edge.get_pmap( pmap );
// Get reversed parameter map
edge.reverse();
edge.get_pmap( rpmap );
tolerance_type ttol;
// Comparison function for set_union.
auto comp = [&ttol](const data_type &x1, const data_type &x2)->bool
{
return ttol.approximately_less_than(x1, x2);
};
// Place union of pmap and omap into cmap.
std::set_union( pmap.begin(), pmap.end(), rpmap.begin(), rpmap.end(), std::back_inserter(cmap), comp );
for ( int i = 0; i < cmap.size(); i++ )
{
surface_copy.split_v( cmap[i] );
}
break;
}
case (CAP_VMIN):
case (CAP_VMAX):
{
data_type umin(surface_copy.get_u0()), umax(surface_copy.get_umax()), usplit((umin+umax)/2);
// Make sure split exists.
surface_copy.split_u( usplit );
piecewise_curve_type edge;
surface_copy.get_vmin_bndy_curve( edge );
// make sure that the split location is different than the start/end location otherwise
// the edge is a point and no need to cap
if (tol.approximately_equal(edge.f(umin), edge.f(usplit)))
{
return false;
}
std::vector<data_type> pmap, rpmap, cmap;
// Get original parameter map
edge.get_pmap( pmap );
// Get reversed parameter map
edge.reverse();
edge.get_pmap( rpmap );
tolerance_type ttol;
// Comparison function for set_union.
auto comp = [&ttol](const data_type &x1, const data_type &x2)->bool
{
return ttol.approximately_less_than(x1, x2);
};
// Place union of pmap and omap into cmap.
std::set_union( pmap.begin(), pmap.end(), rpmap.begin(), rpmap.end(), std::back_inserter(cmap), comp );
for ( int i = 0; i < cmap.size(); i++ )
{
surface_copy.split_u( cmap[i] );
}
break;
}
default:
{
// must not want any edge capped
assert(edge_to_cap==CAP_NONE);
return false;
}
}
// Ensure opposing surface faces have matching order
switch (edge_to_cap)
{
case (CAP_UMIN):
case (CAP_UMAX):
{
piecewise_curve_type edge;
surface_copy.get_umin_bndy_curve( edge );
std::vector<index_type> ord;
edge.degrees( std::back_inserter( ord ) );
index_type n = ord.size();
for ( index_type i = 0; i < n/2; i++ )
{
index_type j = n-i-1;
ord[i] = std::max( ord[i], ord[j] );
ord[j] = ord[i];
}
surface_copy.promote_v_to( ord );
break;
}
case (CAP_VMIN):
case (CAP_VMAX):
{
piecewise_curve_type edge;
surface_copy.get_vmin_bndy_curve( edge );
std::vector<index_type> ord;
edge.degrees( std::back_inserter( ord ) );
index_type n = ord.size();
for ( index_type i = 0; i < n/2; i++ )
{
index_type j = n-i-1;
ord[i] = std::max( ord[i], ord[j] );
ord[j] = ord[i];
}
surface_copy.promote_u_to( ord );
break;
}
default:
{
// must not want any edge capped
assert(edge_to_cap==CAP_NONE);
return false;
}
}
// extract the curve corresponding to the edge of surface wanting to cap
piecewise_curve_type edge, ndelta;
switch (edge_to_cap)
{
case (CAP_UMIN):
{
surface_copy.get_umin_bndy_curve( edge );
surface_copy.get_umin_ndelta_pcurve( ndelta );
break;
}
case (CAP_UMAX):
{
surface_copy.get_umax_bndy_curve( edge );
surface_copy.get_umax_ndelta_pcurve( ndelta );
break;
}
case (CAP_VMIN):
{
surface_copy.get_vmin_bndy_curve( edge );
surface_copy.get_vmin_ndelta_pcurve( ndelta );
break;
}
case (CAP_VMAX):
{
surface_copy.get_vmax_bndy_curve( edge );
surface_copy.get_vmax_ndelta_pcurve( ndelta );
break;
}
default:
{
// must not want any edge capped
assert(edge_to_cap==CAP_NONE);
return false;
}
}
data_type tsplit( ( edge.get_t0() + edge.get_tmax() ) * 0.5 );
// split the curve at the mid-parameter location and reverse the second piece's parameterization
piecewise_curve_type first_half, second_half;
edge.split(first_half, second_half, tsplit);
second_half.reverse();
second_half.set_t0(first_half.get_t0());
// Split the ndelta pseudocurve. Since this isn't really a curve, it only works because the split
// point already exists and this becomes reordering and manipulating of existing values, and should
// not change any values of control points.
piecewise_curve_type nd_first_half, nd_second_half;
ndelta.split(nd_first_half, nd_second_half, tsplit);
nd_second_half.reverse();
nd_second_half.set_t0(nd_first_half.get_t0());
std::vector<data_type> pmap, dvcap, ducap(2);
// Get edge parameter map
first_half.get_pmap( pmap );
dvcap.resize( pmap.size() - 1 );
for ( int i = 0; i < pmap.size() - 1; i++ )
{
dvcap[i] = pmap[ i + 1 ] - pmap[ i ];
}
ducap[0] = delta_param;
ducap[1] = delta_param;
// create surface connecting two edges with param spacing of 2*delta_param and points for other two edges
// cap u-direction goes from second_half curve to first_half curve
// cap v-direction follows first_half direction
piecewise_surface_type cap;
{
cap.init_uv( ducap.begin(), ducap.end(), dvcap.begin(), dvcap.end(), 0.0, pmap[0] );
int nseg = first_half.number_segments();
// Vector along upper curve in average 'forward' direction
point_type fwd;
if ( sweep_correct )
{
fwd = ( first_half.f( tsplit ) - first_half.f( first_half.get_t0() ) );
data_type fwdlen = fwd.norm();
if ( tol.approximately_equal( fwdlen, 0.0 ) )
{
fwd << 0, 0, 0;
}
else
{
fwd = fwd / fwdlen;
}
}
for ( int i = 0; i < nseg; i++ )
{
curve_type cfirst, clast;
curve_type ndfirst, ndlast;
first_half.get( cfirst, i );
second_half.get( clast, i );
nd_first_half.get( ndfirst, i );
nd_second_half.get( ndlast, i );
int deg = cfirst.degree();
surface_type s1, s2;
switch( cap_type ){
case FLAT:
{
s1.resize( 1, deg );
s2.resize( 1, deg );
for ( int j = 0; j <= deg; j++ )
{
point_type pup, psplit, pdn;
pup = clast.get_control_point( j );
pdn = cfirst.get_control_point( j );
psplit = ( pup + pdn ) * 0.5;
// Build linear upper side curve
s1.set_control_point( pup, 0, j );
s1.set_control_point( psplit, 1, j );
// Build linear lower side curve
s2.set_control_point( psplit, 0, j );
s2.set_control_point( pdn, 1, j );
}
}
break;
case ROUND:
{
s1.resize( 3, deg );
s2.resize( 3, deg );
for ( int j = 0; j <= deg; j++ )
{
point_type pup, psplit, pdn;
point_type tanup, tandn;
pup = clast.get_control_point( j );
pdn = cfirst.get_control_point( j );
tanup = ndlast.get_control_point( j );
tandn = ndfirst.get_control_point( j );
data_type ksweep = 1.0;
if ( sweep_correct )
{
point_type avetan = ( tanup + tandn ) * 0.5;
ksweep = 1.0 / sin( acos( avetan.dot( fwd ) ) );
if ( tol.approximately_equal( ksweep, 0.0) )
{
ksweep = 1.0;
}
}
// Displacement vector
point_type disp = pup - pdn;
// Chord of circle to construct
data_type circ_chord = disp.norm();
if ( tol.approximately_equal( circ_chord, 0.0 ) )
{
disp << 0, 0, 0;
}
else
{
disp = disp/circ_chord;
}
// Find angles between tangents and displacement
data_type dottanup = disp.dot( tanup );
data_type thetaup = acos( dottanup );
data_type dottandn = disp.dot( tandn );
data_type thetadn = acos( dottandn );
// Find circular arc to include
data_type theta = eli::constants::math<data__>::pi() + thetadn - thetaup;
if ( tol.approximately_equal( theta, 0) ) // Make flat panel avoid division by zero.
{
psplit = ( pup + pdn ) * 0.5;
// Build cubic upper side curve
s1.set_control_point( pup, 0, j );
s1.set_control_point( ( 2 * pup + psplit ) / 3, 1, j );
s1.set_control_point( ( pup + 2 * psplit ) / 3, 2, j );
s1.set_control_point( psplit, 3, j );
// Build cubic lower side curve
s2.set_control_point( psplit, 0, j );
s2.set_control_point( ( pdn + 2 * psplit ) / 3, 1, j );
s2.set_control_point( ( 2 * pdn + psplit ) / 3, 2, j );
s2.set_control_point( pdn, 3, j );
}
else
{
// Find radius from chord length.
data_type radius = circ_chord / ( 2.0 * sin( theta / 2.0 ) );
// Distance to quad Bezier construction point.
data_type b = radius * tan( theta / 4.0 );
// Extrapolated tip up/down points.
point_type ptup, ptdn;
ptup = pup + tanup * b * len_factor * ksweep;
ptdn = pdn + tandn * b * len_factor * ksweep;
// Displacement vector at extrapolated tip
point_type dispt = ptup - ptdn;
// Point on center of circle.
psplit = ( ptup + ptdn ) * 0.5 + dispt * off_factor;
// Fraction of radius to place cubic control point
data_type f = (4.0/3.0) * tan(theta / 8.0);
// Build cubic upper side curve
s1.set_control_point( pup, 0, j );
s1.set_control_point( pup + tanup * radius * f * len_factor * ksweep, 1, j );
s1.set_control_point( psplit + disp * radius * f, 2, j );
s1.set_control_point( psplit, 3, j );
// Build cubic lower side curve
s2.set_control_point( psplit, 0, j );
s2.set_control_point( psplit - disp * radius * f, 1, j );
s2.set_control_point( pdn + tandn * radius * f * len_factor * ksweep, 2, j );
s2.set_control_point( pdn, 3, j );
}
}
break;
case EDGE:
{
s1.resize( 1, deg );
s2.resize( 1, deg );
for ( int j = 0; j <= deg; j++ )
{
point_type pup, psplit, pdn;
point_type tanup, tandn;
pup = clast.get_control_point( j );
pdn = cfirst.get_control_point( j );
tanup = ndlast.get_control_point( j );
tandn = ndfirst.get_control_point( j );
data_type ksweep = 1.0;
if ( sweep_correct )
{
point_type avetan = ( tanup + tandn ) * 0.5;
ksweep = 1.0 / sin( acos( avetan.dot( fwd ) ) );
if ( tol.approximately_equal( ksweep, 0.0) )
{
ksweep = 1.0;
}
}
// Displacement vector
point_type disp = pup - pdn;
// Chord of circle to construct
data_type circ_chord = disp.norm();
if ( tol.approximately_equal( circ_chord, 0.0 ) )
{
disp << 0, 0, 0;
}
else
{
disp = disp/circ_chord;
}
// Extrapolated tip up/down points.
point_type ptup, ptdn;
ptup = pup + tanup * circ_chord * len_factor * ksweep * 0.5;
ptdn = pdn + tandn * circ_chord * len_factor * ksweep * 0.5;
// Displacement vector at extrapolated tip
point_type dispt = ptup - ptdn;
psplit = ( ptup + ptdn ) * 0.5 + dispt * off_factor;
// Build linear upper side curve
s1.set_control_point( pup, 0, j );
s1.set_control_point( psplit, 1, j );
// Build linear lower side curve
s2.set_control_point( psplit, 0, j );
s2.set_control_point( pdn, 1, j );
}
}
break;
case SHARP:
{
s1.resize( 2, deg );
s2.resize( 2, deg );
for ( int j = 0; j <= deg; j++ )
{
point_type pup, psplit, pdn;
point_type tanup, tandn;
pup = clast.get_control_point( j );
pdn = cfirst.get_control_point( j );
tanup = ndlast.get_control_point( j );
tandn = ndfirst.get_control_point( j );
data_type ksweep = 1.0;
if ( sweep_correct )
{
point_type avetan = ( tanup + tandn ) * 0.5;
ksweep = 1.0 / sin( acos( avetan.dot( fwd ) ) );
if ( tol.approximately_equal( ksweep, 0.0) )
{
ksweep = 1.0;
}
}
// Displacement vector
point_type disp = pup - pdn;
// Chord of circle to construct
data_type circ_chord = disp.norm();
if ( tol.approximately_equal( circ_chord, 0.0 ) )
{
disp << 0, 0, 0;
}
else
{
disp = disp/circ_chord;
}
// Extrapolated tip up/down points.
point_type ptup, ptdn;
ptup = pup + tanup * circ_chord * len_factor * ksweep * 0.5;
ptdn = pdn + tandn * circ_chord * len_factor * ksweep * 0.5;
// Displacement vector at extrapolated tip
point_type dispt = ptup - ptdn;
psplit = ( ptup + ptdn ) * 0.5 + dispt * off_factor;
// Upper/lower control point.
point_type pupcp, pdncp;
pupcp = pup + tanup * circ_chord * len_factor * ksweep * 0.5 * str_factor;
pdncp = pdn + tandn * circ_chord * len_factor * ksweep * 0.5 * str_factor;
// Build linear upper side curve
s1.set_control_point( pup, 0, j );
s1.set_control_point( pupcp, 1, j );
s1.set_control_point( psplit, 2, j );
// Build linear lower side curve
s2.set_control_point( psplit, 0, j );
s2.set_control_point( pdncp, 1, j );
s2.set_control_point( pdn, 2, j );
}
}
break;
}
}
cap.set( s1, 0, i );
cap.set( s2, 1, i );
}
}
// split the cap surface at mid point
cap.split_u(surface_copy.get_u0()-delta_param);
// resize output surface to needed size
data_type u0, v0;
std::vector<data_type> ucap_param, vcap_param, uparam, vparam, du, dv;
index_type i, j, icap_mid, umin_offset(0), vmin_offset(0);
surface_copy.get_pmap_u(uparam);
cap.get_pmap_uv(ucap_param, vcap_param);
// NOTE: This assumes that there are same number of patches on both sides of split
icap_mid=ucap_param.size()/2;
switch (edge_to_cap)
{
case (CAP_UMIN):
{
// establish the new u and v parameterization of surface
const index_type nucap_patch(icap_mid), nvcap_patch(cap.number_v_patches());
u0=ucap_param[icap_mid];
du.resize(uparam.size()-1+nucap_patch);
for (i=icap_mid; i<static_cast<index_type>(ucap_param.size())-1; ++i)
{
du[i-icap_mid]=ucap_param[i+1]-ucap_param[i];
}
for (i=0; i<static_cast<index_type>(uparam.size())-1; ++i)
{
du[i+nucap_patch]=uparam[i+1]-uparam[i];
}
// set the new v-parameterization
vparam.resize(2*vcap_param.size()-1);
data_type vmid(vcap_param[vcap_param.size()-1]);
for (j=0; j<static_cast<index_type>(vcap_param.size()); ++j)
{
vparam[j]=vcap_param[j];
vparam[vparam.size()-1-j]=2*vmid-vparam[j];
}
// set the v-parameters
v0=vparam[0];
dv.resize(vparam.size()-1);
for (j=0; j<static_cast<index_type>(dv.size()); ++j)
{
dv[j]=vparam[j+1]-vparam[j];
}
// split a copy original surface at any new v-coordinate locations
piecewise_surface_type orig_copy(surface_copy);
typename piecewise_surface_type::surface_type patch;
for (j=0; j<static_cast<index_type>(vparam.size()); ++j)
{
orig_copy.split_v(vparam[j]);
}
assert(orig_copy.number_v_patches()==(static_cast<index_type>(vparam.size())-1));
// resize the output surface
ps.init_uv(du.begin(), du.end(), dv.begin(), dv.end(), u0, v0);
umin_offset=nucap_patch;
// add first half of cap surfaces
for (i=0; i<nucap_patch; ++i)
{
for (j=0; j<nvcap_patch; ++j)
{
cap.get(patch, i + nucap_patch, j);
ps.set(patch, i, j);
}
}
// reverse the cap so that the second half
cap.reverse_u();
cap.reverse_v();
// add second half of cap surfaces
for (i=0; i<nucap_patch; ++i)
{
for (j=nvcap_patch; j<static_cast<index_type>(dv.size()); ++j)
{
cap.get(patch, i + nucap_patch, j-nvcap_patch);
ps.set(patch, i, j);
}
}
// add non-cap surfaces
for (i=0; i<orig_copy.number_u_patches(); ++i)
{
for (j=0; j<orig_copy.number_v_patches(); ++j)
{
orig_copy.get(patch, i, j);
ps.set(patch, i+umin_offset, j+vmin_offset);
}
}
break;
}
case (CAP_UMAX):
{
// need to reverse u-direction
cap.reverse_u();
// establish the new u and v parameterization of surface
const index_type nucap_patch(icap_mid), nu_patch(uparam.size()-1), nvcap_patch(cap.number_v_patches());
u0=uparam[0];
du.resize(uparam.size()-1+nucap_patch);
for (i=0; i<static_cast<index_type>(uparam.size())-1; ++i)
{
du[i]=uparam[i+1]-uparam[i];
}
for (i=nu_patch; i<static_cast<index_type>(du.size()); ++i)
{
du[i]=ucap_param[(i-nu_patch)+1]-ucap_param[i-nu_patch];
}
// set the new v-parameterization
vparam.resize(2*vcap_param.size()-1);
data_type vmid(vcap_param[vcap_param.size()-1]);
for (j=0; j<static_cast<index_type>(vcap_param.size()); ++j)
{
vparam[j]=vcap_param[j];
vparam[vparam.size()-1-j]=2*vmid-vparam[j];
}
// set the v-parameters
v0=vparam[0];
dv.resize(vparam.size()-1);
for (j=0; j<static_cast<index_type>(dv.size()); ++j)
{
dv[j]=vparam[j+1]-vparam[j];
}
// split a copy original surface at any new v-coordinate locations
piecewise_surface_type orig_copy(surface_copy);
typename piecewise_surface_type::surface_type patch;
for (j=0; j<static_cast<index_type>(vparam.size()); ++j)
{
orig_copy.split_v(vparam[j]);
}
assert(orig_copy.number_v_patches()==(static_cast<index_type>(vparam.size())-1));
// resize the output surface
ps.init_uv(du.begin(), du.end(), dv.begin(), dv.end(), u0, v0);
// add first half of cap surfaces
for (i=0; i<nucap_patch; ++i)
{
for (j=0; j<nvcap_patch; ++j)
{
cap.get(patch, i, j);
ps.set(patch, i + nu_patch, j);
}
}
// reverse the cap so that the second half
cap.reverse_u();
cap.reverse_v();
// add second half of cap surfaces
for (i=0; i<nucap_patch; ++i)
{
for (j=nvcap_patch; j<static_cast<index_type>(dv.size()); ++j)
{
cap.get(patch, i, j-nvcap_patch);
ps.set(patch, i + nu_patch, j);
}
}
// add non-cap surfaces
for (i=0; i<orig_copy.number_u_patches(); ++i)
{
for (j=0; j<orig_copy.number_v_patches(); ++j)
{
orig_copy.get(patch, i, j);
ps.set(patch, i+umin_offset, j+vmin_offset);
}
}
break;
}
case (CAP_VMIN):
{
assert(false);
return false;
break;
}
case (CAP_VMAX):
{
assert(false);
return false;
break;
}
default:
{
// must not want any edge capped
assert(edge_to_cap==CAP_NONE);
return false;
}
}
return true;
}
private:
piecewise_surface_type orig_surface;
data_type delta_param;
edge_cap_identifier edge_to_cap;
data_type len_factor;
data_type off_factor;
data_type str_factor;
bool sweep_correct;
index_type cap_type;
};
}
}
}
#endif
Protect piecewise capped creator from empty surfaces.
/*********************************************************************************
* Copyright (c) 2014 David D. Marshall <ddmarsha@calpoly.edu>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Rob McDonald -- based on piecewise_capped_surface_creator.hpp
********************************************************************************/
#ifndef eli_geom_surface_piecewise_multicap_surface_creator_hpp
#define eli_geom_surface_piecewise_multicap_surface_creator_hpp
#include <list>
#include <iterator>
#include "eli/code_eli.hpp"
#include "eli/constants/math.hpp"
#include "eli/util/tolerance.hpp"
#include "eli/geom/curve/bezier.hpp"
#include "eli/geom/curve/piecewise.hpp"
#include "eli/geom/surface/bezier.hpp"
#include "eli/geom/surface/piecewise.hpp"
#include "eli/geom/surface/piecewise_creator_base.hpp"
#include "eli/geom/surface/piecewise_connection_data.hpp"
namespace eli
{
namespace geom
{
namespace surface
{
template<typename data__, unsigned short dim__, typename tol__>
class piecewise_multicap_surface_creator : public piecewise_creator_base<data__, dim__, tol__>
{
public:
enum edge_cap_identifier
{
CAP_NONE,
CAP_UMIN,
CAP_UMAX,
CAP_VMIN,
CAP_VMAX
};
enum cap_type
{
FLAT,
ROUND,
EDGE,
SHARP
};
typedef piecewise_creator_base<data__, dim__, tol__> base_class_type;
typedef typename base_class_type::data_type data_type;
typedef typename base_class_type::point_type point_type;
typedef typename base_class_type::index_type index_type;
typedef typename base_class_type::tolerance_type tolerance_type;
typedef typename base_class_type::piecewise_surface_type piecewise_surface_type;
piecewise_multicap_surface_creator()
: piecewise_creator_base<data__, dim__, tol__>(0, 0), delta_param(1), edge_to_cap(CAP_NONE)
{
}
piecewise_multicap_surface_creator(const piecewise_surface_type &os, const data_type &dp, edge_cap_identifier ec)
: piecewise_creator_base<data__, dim__, tol__>(0, 0), orig_surface(os), delta_param(dp), edge_to_cap(ec)
{
}
piecewise_multicap_surface_creator(const piecewise_multicap_surface_creator<data_type, dim__, tolerance_type> & gs)
: piecewise_creator_base<data_type, dim__, tolerance_type>(gs), orig_surface(gs.orig_surface),
delta_param(gs.delta_param), edge_to_cap(gs.edge_to_cap)
{
}
virtual ~piecewise_multicap_surface_creator()
{
}
bool set_conditions(const piecewise_surface_type &os, const index_type & typ, const data_type &dp, edge_cap_identifier ec, const data_type &lf, const data_type &of, const data_type &sf, const bool &sc )
{
// all deltas are positive, even on the min edges
if (dp<=0)
return false;
cap_type = typ;
orig_surface = os;
edge_to_cap = ec;
delta_param = dp;
len_factor = lf;
off_factor = of;
str_factor = sf;
sweep_correct = sc;
if ( orig_surface.number_u_patches() == 0 || orig_surface.number_v_patches() == 0 )
{
return false;
}
return true;
}
virtual bool create(piecewise_surface_type &ps) const
{
typedef typename eli::geom::curve::piecewise<eli::geom::curve::bezier, data_type, dim__, tolerance_type> piecewise_curve_type;
typedef typename piecewise_curve_type::curve_type curve_type;
typedef typename piecewise_surface_type::surface_type surface_type;
tolerance_type tol;
piecewise_surface_type surface_copy( orig_surface );
// Ensure opposing surface faces have mid split and matching parameter splits
switch (edge_to_cap)
{
case (CAP_UMIN):
case (CAP_UMAX):
{
data_type vmin(surface_copy.get_v0()), vmax(surface_copy.get_vmax()), vsplit((vmin+vmax)/2);
// Make sure split exists.
surface_copy.split_v( vsplit );
piecewise_curve_type edge;
surface_copy.get_umin_bndy_curve( edge );
// make sure that the split location is different than the start/end location otherwise
// the edge is a point and no need to cap
if (tol.approximately_equal(edge.f(vmin), edge.f(vsplit)))
{
return false;
}
std::vector<data_type> pmap, rpmap, cmap;
// Get original parameter map
edge.get_pmap( pmap );
// Get reversed parameter map
edge.reverse();
edge.get_pmap( rpmap );
tolerance_type ttol;
// Comparison function for set_union.
auto comp = [&ttol](const data_type &x1, const data_type &x2)->bool
{
return ttol.approximately_less_than(x1, x2);
};
// Place union of pmap and omap into cmap.
std::set_union( pmap.begin(), pmap.end(), rpmap.begin(), rpmap.end(), std::back_inserter(cmap), comp );
for ( int i = 0; i < cmap.size(); i++ )
{
surface_copy.split_v( cmap[i] );
}
break;
}
case (CAP_VMIN):
case (CAP_VMAX):
{
data_type umin(surface_copy.get_u0()), umax(surface_copy.get_umax()), usplit((umin+umax)/2);
// Make sure split exists.
surface_copy.split_u( usplit );
piecewise_curve_type edge;
surface_copy.get_vmin_bndy_curve( edge );
// make sure that the split location is different than the start/end location otherwise
// the edge is a point and no need to cap
if (tol.approximately_equal(edge.f(umin), edge.f(usplit)))
{
return false;
}
std::vector<data_type> pmap, rpmap, cmap;
// Get original parameter map
edge.get_pmap( pmap );
// Get reversed parameter map
edge.reverse();
edge.get_pmap( rpmap );
tolerance_type ttol;
// Comparison function for set_union.
auto comp = [&ttol](const data_type &x1, const data_type &x2)->bool
{
return ttol.approximately_less_than(x1, x2);
};
// Place union of pmap and omap into cmap.
std::set_union( pmap.begin(), pmap.end(), rpmap.begin(), rpmap.end(), std::back_inserter(cmap), comp );
for ( int i = 0; i < cmap.size(); i++ )
{
surface_copy.split_u( cmap[i] );
}
break;
}
default:
{
// must not want any edge capped
assert(edge_to_cap==CAP_NONE);
return false;
}
}
// Ensure opposing surface faces have matching order
switch (edge_to_cap)
{
case (CAP_UMIN):
case (CAP_UMAX):
{
piecewise_curve_type edge;
surface_copy.get_umin_bndy_curve( edge );
std::vector<index_type> ord;
edge.degrees( std::back_inserter( ord ) );
index_type n = ord.size();
for ( index_type i = 0; i < n/2; i++ )
{
index_type j = n-i-1;
ord[i] = std::max( ord[i], ord[j] );
ord[j] = ord[i];
}
surface_copy.promote_v_to( ord );
break;
}
case (CAP_VMIN):
case (CAP_VMAX):
{
piecewise_curve_type edge;
surface_copy.get_vmin_bndy_curve( edge );
std::vector<index_type> ord;
edge.degrees( std::back_inserter( ord ) );
index_type n = ord.size();
for ( index_type i = 0; i < n/2; i++ )
{
index_type j = n-i-1;
ord[i] = std::max( ord[i], ord[j] );
ord[j] = ord[i];
}
surface_copy.promote_u_to( ord );
break;
}
default:
{
// must not want any edge capped
assert(edge_to_cap==CAP_NONE);
return false;
}
}
// extract the curve corresponding to the edge of surface wanting to cap
piecewise_curve_type edge, ndelta;
switch (edge_to_cap)
{
case (CAP_UMIN):
{
surface_copy.get_umin_bndy_curve( edge );
surface_copy.get_umin_ndelta_pcurve( ndelta );
break;
}
case (CAP_UMAX):
{
surface_copy.get_umax_bndy_curve( edge );
surface_copy.get_umax_ndelta_pcurve( ndelta );
break;
}
case (CAP_VMIN):
{
surface_copy.get_vmin_bndy_curve( edge );
surface_copy.get_vmin_ndelta_pcurve( ndelta );
break;
}
case (CAP_VMAX):
{
surface_copy.get_vmax_bndy_curve( edge );
surface_copy.get_vmax_ndelta_pcurve( ndelta );
break;
}
default:
{
// must not want any edge capped
assert(edge_to_cap==CAP_NONE);
return false;
}
}
data_type tsplit( ( edge.get_t0() + edge.get_tmax() ) * 0.5 );
// split the curve at the mid-parameter location and reverse the second piece's parameterization
piecewise_curve_type first_half, second_half;
edge.split(first_half, second_half, tsplit);
second_half.reverse();
second_half.set_t0(first_half.get_t0());
// Split the ndelta pseudocurve. Since this isn't really a curve, it only works because the split
// point already exists and this becomes reordering and manipulating of existing values, and should
// not change any values of control points.
piecewise_curve_type nd_first_half, nd_second_half;
ndelta.split(nd_first_half, nd_second_half, tsplit);
nd_second_half.reverse();
nd_second_half.set_t0(nd_first_half.get_t0());
std::vector<data_type> pmap, dvcap, ducap(2);
// Get edge parameter map
first_half.get_pmap( pmap );
dvcap.resize( pmap.size() - 1 );
for ( int i = 0; i < pmap.size() - 1; i++ )
{
dvcap[i] = pmap[ i + 1 ] - pmap[ i ];
}
ducap[0] = delta_param;
ducap[1] = delta_param;
// create surface connecting two edges with param spacing of 2*delta_param and points for other two edges
// cap u-direction goes from second_half curve to first_half curve
// cap v-direction follows first_half direction
piecewise_surface_type cap;
{
cap.init_uv( ducap.begin(), ducap.end(), dvcap.begin(), dvcap.end(), 0.0, pmap[0] );
int nseg = first_half.number_segments();
// Vector along upper curve in average 'forward' direction
point_type fwd;
if ( sweep_correct )
{
fwd = ( first_half.f( tsplit ) - first_half.f( first_half.get_t0() ) );
data_type fwdlen = fwd.norm();
if ( tol.approximately_equal( fwdlen, 0.0 ) )
{
fwd << 0, 0, 0;
}
else
{
fwd = fwd / fwdlen;
}
}
for ( int i = 0; i < nseg; i++ )
{
curve_type cfirst, clast;
curve_type ndfirst, ndlast;
first_half.get( cfirst, i );
second_half.get( clast, i );
nd_first_half.get( ndfirst, i );
nd_second_half.get( ndlast, i );
int deg = cfirst.degree();
surface_type s1, s2;
switch( cap_type ){
case FLAT:
{
s1.resize( 1, deg );
s2.resize( 1, deg );
for ( int j = 0; j <= deg; j++ )
{
point_type pup, psplit, pdn;
pup = clast.get_control_point( j );
pdn = cfirst.get_control_point( j );
psplit = ( pup + pdn ) * 0.5;
// Build linear upper side curve
s1.set_control_point( pup, 0, j );
s1.set_control_point( psplit, 1, j );
// Build linear lower side curve
s2.set_control_point( psplit, 0, j );
s2.set_control_point( pdn, 1, j );
}
}
break;
case ROUND:
{
s1.resize( 3, deg );
s2.resize( 3, deg );
for ( int j = 0; j <= deg; j++ )
{
point_type pup, psplit, pdn;
point_type tanup, tandn;
pup = clast.get_control_point( j );
pdn = cfirst.get_control_point( j );
tanup = ndlast.get_control_point( j );
tandn = ndfirst.get_control_point( j );
data_type ksweep = 1.0;
if ( sweep_correct )
{
point_type avetan = ( tanup + tandn ) * 0.5;
ksweep = 1.0 / sin( acos( avetan.dot( fwd ) ) );
if ( tol.approximately_equal( ksweep, 0.0) )
{
ksweep = 1.0;
}
}
// Displacement vector
point_type disp = pup - pdn;
// Chord of circle to construct
data_type circ_chord = disp.norm();
if ( tol.approximately_equal( circ_chord, 0.0 ) )
{
disp << 0, 0, 0;
}
else
{
disp = disp/circ_chord;
}
// Find angles between tangents and displacement
data_type dottanup = disp.dot( tanup );
data_type thetaup = acos( dottanup );
data_type dottandn = disp.dot( tandn );
data_type thetadn = acos( dottandn );
// Find circular arc to include
data_type theta = eli::constants::math<data__>::pi() + thetadn - thetaup;
if ( tol.approximately_equal( theta, 0) ) // Make flat panel avoid division by zero.
{
psplit = ( pup + pdn ) * 0.5;
// Build cubic upper side curve
s1.set_control_point( pup, 0, j );
s1.set_control_point( ( 2 * pup + psplit ) / 3, 1, j );
s1.set_control_point( ( pup + 2 * psplit ) / 3, 2, j );
s1.set_control_point( psplit, 3, j );
// Build cubic lower side curve
s2.set_control_point( psplit, 0, j );
s2.set_control_point( ( pdn + 2 * psplit ) / 3, 1, j );
s2.set_control_point( ( 2 * pdn + psplit ) / 3, 2, j );
s2.set_control_point( pdn, 3, j );
}
else
{
// Find radius from chord length.
data_type radius = circ_chord / ( 2.0 * sin( theta / 2.0 ) );
// Distance to quad Bezier construction point.
data_type b = radius * tan( theta / 4.0 );
// Extrapolated tip up/down points.
point_type ptup, ptdn;
ptup = pup + tanup * b * len_factor * ksweep;
ptdn = pdn + tandn * b * len_factor * ksweep;
// Displacement vector at extrapolated tip
point_type dispt = ptup - ptdn;
// Point on center of circle.
psplit = ( ptup + ptdn ) * 0.5 + dispt * off_factor;
// Fraction of radius to place cubic control point
data_type f = (4.0/3.0) * tan(theta / 8.0);
// Build cubic upper side curve
s1.set_control_point( pup, 0, j );
s1.set_control_point( pup + tanup * radius * f * len_factor * ksweep, 1, j );
s1.set_control_point( psplit + disp * radius * f, 2, j );
s1.set_control_point( psplit, 3, j );
// Build cubic lower side curve
s2.set_control_point( psplit, 0, j );
s2.set_control_point( psplit - disp * radius * f, 1, j );
s2.set_control_point( pdn + tandn * radius * f * len_factor * ksweep, 2, j );
s2.set_control_point( pdn, 3, j );
}
}
break;
case EDGE:
{
s1.resize( 1, deg );
s2.resize( 1, deg );
for ( int j = 0; j <= deg; j++ )
{
point_type pup, psplit, pdn;
point_type tanup, tandn;
pup = clast.get_control_point( j );
pdn = cfirst.get_control_point( j );
tanup = ndlast.get_control_point( j );
tandn = ndfirst.get_control_point( j );
data_type ksweep = 1.0;
if ( sweep_correct )
{
point_type avetan = ( tanup + tandn ) * 0.5;
ksweep = 1.0 / sin( acos( avetan.dot( fwd ) ) );
if ( tol.approximately_equal( ksweep, 0.0) )
{
ksweep = 1.0;
}
}
// Displacement vector
point_type disp = pup - pdn;
// Chord of circle to construct
data_type circ_chord = disp.norm();
if ( tol.approximately_equal( circ_chord, 0.0 ) )
{
disp << 0, 0, 0;
}
else
{
disp = disp/circ_chord;
}
// Extrapolated tip up/down points.
point_type ptup, ptdn;
ptup = pup + tanup * circ_chord * len_factor * ksweep * 0.5;
ptdn = pdn + tandn * circ_chord * len_factor * ksweep * 0.5;
// Displacement vector at extrapolated tip
point_type dispt = ptup - ptdn;
psplit = ( ptup + ptdn ) * 0.5 + dispt * off_factor;
// Build linear upper side curve
s1.set_control_point( pup, 0, j );
s1.set_control_point( psplit, 1, j );
// Build linear lower side curve
s2.set_control_point( psplit, 0, j );
s2.set_control_point( pdn, 1, j );
}
}
break;
case SHARP:
{
s1.resize( 2, deg );
s2.resize( 2, deg );
for ( int j = 0; j <= deg; j++ )
{
point_type pup, psplit, pdn;
point_type tanup, tandn;
pup = clast.get_control_point( j );
pdn = cfirst.get_control_point( j );
tanup = ndlast.get_control_point( j );
tandn = ndfirst.get_control_point( j );
data_type ksweep = 1.0;
if ( sweep_correct )
{
point_type avetan = ( tanup + tandn ) * 0.5;
ksweep = 1.0 / sin( acos( avetan.dot( fwd ) ) );
if ( tol.approximately_equal( ksweep, 0.0) )
{
ksweep = 1.0;
}
}
// Displacement vector
point_type disp = pup - pdn;
// Chord of circle to construct
data_type circ_chord = disp.norm();
if ( tol.approximately_equal( circ_chord, 0.0 ) )
{
disp << 0, 0, 0;
}
else
{
disp = disp/circ_chord;
}
// Extrapolated tip up/down points.
point_type ptup, ptdn;
ptup = pup + tanup * circ_chord * len_factor * ksweep * 0.5;
ptdn = pdn + tandn * circ_chord * len_factor * ksweep * 0.5;
// Displacement vector at extrapolated tip
point_type dispt = ptup - ptdn;
psplit = ( ptup + ptdn ) * 0.5 + dispt * off_factor;
// Upper/lower control point.
point_type pupcp, pdncp;
pupcp = pup + tanup * circ_chord * len_factor * ksweep * 0.5 * str_factor;
pdncp = pdn + tandn * circ_chord * len_factor * ksweep * 0.5 * str_factor;
// Build linear upper side curve
s1.set_control_point( pup, 0, j );
s1.set_control_point( pupcp, 1, j );
s1.set_control_point( psplit, 2, j );
// Build linear lower side curve
s2.set_control_point( psplit, 0, j );
s2.set_control_point( pdncp, 1, j );
s2.set_control_point( pdn, 2, j );
}
}
break;
}
}
cap.set( s1, 0, i );
cap.set( s2, 1, i );
}
}
// split the cap surface at mid point
cap.split_u(surface_copy.get_u0()-delta_param);
// resize output surface to needed size
data_type u0, v0;
std::vector<data_type> ucap_param, vcap_param, uparam, vparam, du, dv;
index_type i, j, icap_mid, umin_offset(0), vmin_offset(0);
surface_copy.get_pmap_u(uparam);
cap.get_pmap_uv(ucap_param, vcap_param);
// NOTE: This assumes that there are same number of patches on both sides of split
icap_mid=ucap_param.size()/2;
switch (edge_to_cap)
{
case (CAP_UMIN):
{
// establish the new u and v parameterization of surface
const index_type nucap_patch(icap_mid), nvcap_patch(cap.number_v_patches());
u0=ucap_param[icap_mid];
du.resize(uparam.size()-1+nucap_patch);
for (i=icap_mid; i<static_cast<index_type>(ucap_param.size())-1; ++i)
{
du[i-icap_mid]=ucap_param[i+1]-ucap_param[i];
}
for (i=0; i<static_cast<index_type>(uparam.size())-1; ++i)
{
du[i+nucap_patch]=uparam[i+1]-uparam[i];
}
// set the new v-parameterization
vparam.resize(2*vcap_param.size()-1);
data_type vmid(vcap_param[vcap_param.size()-1]);
for (j=0; j<static_cast<index_type>(vcap_param.size()); ++j)
{
vparam[j]=vcap_param[j];
vparam[vparam.size()-1-j]=2*vmid-vparam[j];
}
// set the v-parameters
v0=vparam[0];
dv.resize(vparam.size()-1);
for (j=0; j<static_cast<index_type>(dv.size()); ++j)
{
dv[j]=vparam[j+1]-vparam[j];
}
// split a copy original surface at any new v-coordinate locations
piecewise_surface_type orig_copy(surface_copy);
typename piecewise_surface_type::surface_type patch;
for (j=0; j<static_cast<index_type>(vparam.size()); ++j)
{
orig_copy.split_v(vparam[j]);
}
assert(orig_copy.number_v_patches()==(static_cast<index_type>(vparam.size())-1));
// resize the output surface
ps.init_uv(du.begin(), du.end(), dv.begin(), dv.end(), u0, v0);
umin_offset=nucap_patch;
// add first half of cap surfaces
for (i=0; i<nucap_patch; ++i)
{
for (j=0; j<nvcap_patch; ++j)
{
cap.get(patch, i + nucap_patch, j);
ps.set(patch, i, j);
}
}
// reverse the cap so that the second half
cap.reverse_u();
cap.reverse_v();
// add second half of cap surfaces
for (i=0; i<nucap_patch; ++i)
{
for (j=nvcap_patch; j<static_cast<index_type>(dv.size()); ++j)
{
cap.get(patch, i + nucap_patch, j-nvcap_patch);
ps.set(patch, i, j);
}
}
// add non-cap surfaces
for (i=0; i<orig_copy.number_u_patches(); ++i)
{
for (j=0; j<orig_copy.number_v_patches(); ++j)
{
orig_copy.get(patch, i, j);
ps.set(patch, i+umin_offset, j+vmin_offset);
}
}
break;
}
case (CAP_UMAX):
{
// need to reverse u-direction
cap.reverse_u();
// establish the new u and v parameterization of surface
const index_type nucap_patch(icap_mid), nu_patch(uparam.size()-1), nvcap_patch(cap.number_v_patches());
u0=uparam[0];
du.resize(uparam.size()-1+nucap_patch);
for (i=0; i<static_cast<index_type>(uparam.size())-1; ++i)
{
du[i]=uparam[i+1]-uparam[i];
}
for (i=nu_patch; i<static_cast<index_type>(du.size()); ++i)
{
du[i]=ucap_param[(i-nu_patch)+1]-ucap_param[i-nu_patch];
}
// set the new v-parameterization
vparam.resize(2*vcap_param.size()-1);
data_type vmid(vcap_param[vcap_param.size()-1]);
for (j=0; j<static_cast<index_type>(vcap_param.size()); ++j)
{
vparam[j]=vcap_param[j];
vparam[vparam.size()-1-j]=2*vmid-vparam[j];
}
// set the v-parameters
v0=vparam[0];
dv.resize(vparam.size()-1);
for (j=0; j<static_cast<index_type>(dv.size()); ++j)
{
dv[j]=vparam[j+1]-vparam[j];
}
// split a copy original surface at any new v-coordinate locations
piecewise_surface_type orig_copy(surface_copy);
typename piecewise_surface_type::surface_type patch;
for (j=0; j<static_cast<index_type>(vparam.size()); ++j)
{
orig_copy.split_v(vparam[j]);
}
assert(orig_copy.number_v_patches()==(static_cast<index_type>(vparam.size())-1));
// resize the output surface
ps.init_uv(du.begin(), du.end(), dv.begin(), dv.end(), u0, v0);
// add first half of cap surfaces
for (i=0; i<nucap_patch; ++i)
{
for (j=0; j<nvcap_patch; ++j)
{
cap.get(patch, i, j);
ps.set(patch, i + nu_patch, j);
}
}
// reverse the cap so that the second half
cap.reverse_u();
cap.reverse_v();
// add second half of cap surfaces
for (i=0; i<nucap_patch; ++i)
{
for (j=nvcap_patch; j<static_cast<index_type>(dv.size()); ++j)
{
cap.get(patch, i, j-nvcap_patch);
ps.set(patch, i + nu_patch, j);
}
}
// add non-cap surfaces
for (i=0; i<orig_copy.number_u_patches(); ++i)
{
for (j=0; j<orig_copy.number_v_patches(); ++j)
{
orig_copy.get(patch, i, j);
ps.set(patch, i+umin_offset, j+vmin_offset);
}
}
break;
}
case (CAP_VMIN):
{
assert(false);
return false;
break;
}
case (CAP_VMAX):
{
assert(false);
return false;
break;
}
default:
{
// must not want any edge capped
assert(edge_to_cap==CAP_NONE);
return false;
}
}
return true;
}
private:
piecewise_surface_type orig_surface;
data_type delta_param;
edge_cap_identifier edge_to_cap;
data_type len_factor;
data_type off_factor;
data_type str_factor;
bool sweep_correct;
index_type cap_type;
};
}
}
}
#endif
|
/*************************************************************************
*
* $RCSfile: sdpage2.cxx,v $
*
* $Revision: 1.26 $
*
* last change: $Author: kz $ $Date: 2005-07-14 10:43:59 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser Generals l Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SFXDOCFILE_HXX //autogen
#include <sfx2/docfile.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _OUTLINER_HXX
#include <svx/outliner.hxx>
#endif
#ifndef _SVXLINK_HXX
#include <svx/linkmgr.hxx>
#endif
#ifndef _SVDOTEXT_HXX //autogen
#include <svx/svdotext.hxx>
#endif
#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _OUTLOBJ_HXX //autogen
#include <svx/outlobj.hxx>
#endif
#include <svtools/urihelper.hxx>
#ifndef _SVX_XMLCNITM_HXX
#include <svx/xmlcnitm.hxx>
#endif
#ifndef _SVDITER_HXX
#include <svx/svditer.hxx>
#endif
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#include "sdresid.hxx"
#include "sdpage.hxx"
#include "glob.hxx"
#include "glob.hrc"
#include "drawdoc.hxx"
#include "stlpool.hxx"
//#include "sdiocmpt.hxx"
#include "pglink.hxx"
//#include "strmname.h"
#include "anminfo.hxx"
#ifdef MAC
#include "::ui:inc:strings.hrc"
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "::ui:inc:DrawDocShell.hxx"
#endif
#else
#ifdef UNX
#include "../ui/inc/strings.hrc"
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "../ui/inc/DrawDocShell.hxx"
#endif
#else
#include "..\ui\inc\cfgids.hxx"
#include "..\ui\inc\strings.hrc"
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "..\ui\inc\DrawDocShell.hxx"
#endif
#endif
#endif
// #90477#
#ifndef _TOOLS_TENCCVT_HXX
#include <tools/tenccvt.hxx>
#endif
using namespace ::sd;
using namespace ::com::sun::star;
/*************************************************************************
|*
|* SetPresentationLayout, setzt: Layoutnamen, Masterpage-Verknpfung und
|* Vorlagen fuer Praesentationsobjekte
|*
|* Vorraussetzungen: - Die Seite muss bereits das richtige Model kennen!
|* - Die entsprechende Masterpage muss bereits im Model sein.
|* - Die entsprechenden StyleSheets muessen bereits im
|* im StyleSheetPool sein.
|*
|* bReplaceStyleSheets = TRUE : Benannte StyleSheets werden ausgetauscht
|* FALSE: Alle StyleSheets werden neu zugewiesen
|*
|* bSetMasterPage = TRUE : MasterPage suchen und zuweisen
|*
|* bReverseOrder = FALSE: MasterPages von vorn nach hinten suchen
|* TRUE : MasterPages von hinten nach vorn suchen (fuer Undo-Action)
|*
\************************************************************************/
void SdPage::SetPresentationLayout(const String& rLayoutName,
BOOL bReplaceStyleSheets,
BOOL bSetMasterPage,
BOOL bReverseOrder)
{
/*********************************************************************
|* Layoutname der Seite
\********************************************************************/
String aOldLayoutName(aLayoutName); // merken
aLayoutName = rLayoutName;
aLayoutName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( SD_LT_SEPARATOR ));
aLayoutName += String(SdResId(STR_LAYOUT_OUTLINE));
/*********************************************************************
|* ggf. Masterpage suchen und setzen
\********************************************************************/
if (bSetMasterPage && !IsMasterPage())
{
SdPage* pMaster;
SdPage* pFoundMaster = 0;
USHORT nMaster = 0;
USHORT nMasterCount = pModel->GetMasterPageCount();
if( !bReverseOrder )
{
for ( nMaster = 0; nMaster < nMasterCount; nMaster++ )
{
pMaster = static_cast<SdPage*>(pModel->GetMasterPage(nMaster));
if (pMaster->GetPageKind() == ePageKind && pMaster->GetLayoutName() == aLayoutName)
{
pFoundMaster = pMaster;
break;
}
}
}
else
{
for ( nMaster = nMasterCount; nMaster > 0; nMaster-- )
{
pMaster = static_cast<SdPage*>(pModel->GetMasterPage(nMaster - 1));
if (pMaster->GetPageKind() == ePageKind && pMaster->GetLayoutName() == aLayoutName)
{
pFoundMaster = pMaster;
break;
}
}
}
DBG_ASSERT(pFoundMaster, "Masterpage for presentation layout not found!");
// this should never happen, but we play failsafe here
if( pFoundMaster == 0 )
pFoundMaster = static_cast< SdDrawDocument *>(pModel)->GetSdPage( 0, ePageKind );
if( pFoundMaster )
TRG_SetMasterPage(*pFoundMaster);
}
/*********************************************************************
|* Vorlagen fuer Praesentationsobjekte
\********************************************************************/
// Listen mit:
// - Vorlagenzeigern fuer Gliederungstextobjekt (alte und neue Vorlagen)
// -Replacedaten fuer OutlinerParaObject
List aOutlineStyles;
List aOldOutlineStyles;
List aReplList;
BOOL bListsFilled = FALSE;
ULONG nObjCount = GetObjCount();
for (ULONG nObj = 0; nObj < nObjCount; nObj++)
{
SdrTextObj* pObj = (SdrTextObj*) GetObj(nObj);
if (pObj->GetObjInventor() == SdrInventor &&
pObj->GetObjIdentifier() == OBJ_OUTLINETEXT)
{
if (!bListsFilled || !bReplaceStyleSheets)
{
String aFullName;
String aOldFullName;
SfxStyleSheetBase* pSheet = NULL;
SfxStyleSheetBasePool* pStShPool = pModel->GetStyleSheetPool();
for (USHORT i = 1; i < 10; i++)
{
aFullName = aLayoutName;
aOldFullName = aOldLayoutName;
aFullName += sal_Unicode( ' ' );
aFullName += String::CreateFromInt32( (sal_Int32)i );
aOldFullName += sal_Unicode( ' ' );
aOldFullName += String::CreateFromInt32( (sal_Int32)i );
pSheet = pStShPool->Find(aOldFullName, SD_LT_FAMILY);
DBG_ASSERT(pSheet, "alte Gliederungsvorlage nicht gefunden");
aOldOutlineStyles.Insert(pSheet, LIST_APPEND);
pSheet = pStShPool->Find(aFullName, SD_LT_FAMILY);
DBG_ASSERT(pSheet, "neue Gliederungsvorlage nicht gefunden");
aOutlineStyles.Insert(pSheet, LIST_APPEND);
if (bReplaceStyleSheets && pSheet)
{
// Replace anstatt Set
StyleReplaceData* pReplData = new StyleReplaceData;
pReplData->nNewFamily = pSheet->GetFamily();
pReplData->nFamily = pSheet->GetFamily();
pReplData->aNewName = aFullName;
pReplData->aName = aOldFullName;
aReplList.Insert(pReplData, LIST_APPEND);
}
else
{
OutlinerParaObject* pOPO = ((SdrTextObj*)pObj)->GetOutlinerParaObject();
if( pOPO )
pOPO->SetStyleSheets( i, aFullName, SD_LT_FAMILY );
}
}
bListsFilled = TRUE;
}
SfxStyleSheet* pSheet = (SfxStyleSheet*)aOutlineStyles.First();
SfxStyleSheet* pOldSheet = (SfxStyleSheet*)aOldOutlineStyles.First();
while (pSheet)
{
if (pSheet != pOldSheet)
{
pObj->EndListening(*pOldSheet);
if (!pObj->IsListening(*pSheet))
pObj->StartListening(*pSheet);
}
pSheet = (SfxStyleSheet*)aOutlineStyles.Next();
pOldSheet = (SfxStyleSheet*)aOldOutlineStyles.Next();
}
OutlinerParaObject* pOPO = ((SdrTextObj*)pObj)->GetOutlinerParaObject();
if ( bReplaceStyleSheets && pOPO )
{
StyleReplaceData* pReplData = (StyleReplaceData*) aReplList.First();
while( pReplData )
{
pOPO->ChangeStyleSheets( pReplData->aName, pReplData->nFamily, pReplData->aNewName, pReplData->nNewFamily );
pReplData = (StyleReplaceData*) aReplList.Next();
}
}
}
else if (pObj->GetObjInventor() == SdrInventor &&
pObj->GetObjIdentifier() == OBJ_TITLETEXT)
{
// PresObjKind nicht ueber GetPresObjKind() holen, da dort nur
// die PresObjListe beruecksichtigt wird. Es sollen aber alle
// "Titelobjekte" hier beruecksichtigt werden (Paste aus Clipboard usw.)
SfxStyleSheet* pSheet = GetStyleSheetForPresObj(PRESOBJ_TITLE);
if (pSheet)
pObj->SetStyleSheet(pSheet, TRUE);
}
else
{
SfxStyleSheet* pSheet = GetStyleSheetForPresObj(GetPresObjKind(pObj));
if (pSheet)
pObj->SetStyleSheet(pSheet, TRUE);
}
}
for (ULONG i = 0; i < aReplList.Count(); i++)
{
delete (StyleReplaceData*) aReplList.GetObject(i);
}
}
/*************************************************************************
|*
|* das Gliederungstextobjekt bei den Vorlagen fuer die Gliederungsebenen
|* abmelden
|*
\************************************************************************/
void SdPage::EndListenOutlineText()
{
SdrObject* pOutlineTextObj = GetPresObj(PRESOBJ_OUTLINE);
if (pOutlineTextObj)
{
SdStyleSheetPool* pSPool = (SdStyleSheetPool*)pModel->GetStyleSheetPool();
DBG_ASSERT(pSPool, "StyleSheetPool nicht gefunden");
String aTrueLayoutName(aLayoutName);
aTrueLayoutName.Erase( aTrueLayoutName.SearchAscii( SD_LT_SEPARATOR ));
List* pOutlineStyles = pSPool->CreateOutlineSheetList(aTrueLayoutName);
for (SfxStyleSheet* pSheet = (SfxStyleSheet*)pOutlineStyles->First();
pSheet;
pSheet = (SfxStyleSheet*)pOutlineStyles->Next())
{
pOutlineTextObj->EndListening(*pSheet);
}
delete pOutlineStyles;
}
}
/*************************************************************************
|*
|* Neues Model setzen
|*
\************************************************************************/
void SdPage::SetModel(SdrModel* pNewModel)
{
DisconnectLink();
// Model umsetzen
FmFormPage::SetModel(pNewModel);
ConnectLink();
}
/*************************************************************************
|*
|* Ist die Seite read-only?
|*
\************************************************************************/
FASTBOOL SdPage::IsReadOnly() const
{
BOOL bReadOnly = FALSE;
if (pPageLink)
{
// Seite ist gelinkt
// bReadOnly = TRUE wuerde dazu fuehren, dass diese Seite nicht
// bearbeitet werden kann. Dieser Effekt ist jedoch z.Z. nicht
// gewuenscht, daher auskommentiert:
// bReadOnly = TRUE;
}
return (bReadOnly);
}
/*************************************************************************
|*
|* Beim LinkManager anmelden
|*
\************************************************************************/
void SdPage::ConnectLink()
{
SvxLinkManager* pLinkManager = pModel!=NULL ? pModel->GetLinkManager() : NULL;
if (pLinkManager && !pPageLink && aFileName.Len() && aBookmarkName.Len() &&
ePageKind==PK_STANDARD && !IsMasterPage() &&
( (SdDrawDocument*) pModel)->IsNewOrLoadCompleted())
{
/**********************************************************************
* Anmelden
* Nur Standardseiten duerfen gelinkt sein
**********************************************************************/
::sd::DrawDocShell* pDocSh = ((SdDrawDocument*) pModel)->GetDocSh();
if (!pDocSh || pDocSh->GetMedium()->GetOrigURL() != aFileName)
{
// Keine Links auf Dokument-eigene Seiten!
pPageLink = new SdPageLink(this, aFileName, aBookmarkName);
String aFilterName(SdResId(STR_IMPRESS));
pLinkManager->InsertFileLink(*pPageLink, OBJECT_CLIENT_FILE,
aFileName, &aFilterName, &aBookmarkName);
pPageLink->Connect();
}
}
}
/*************************************************************************
|*
|* Beim LinkManager abmelden
|*
\************************************************************************/
void SdPage::DisconnectLink()
{
SvxLinkManager* pLinkManager = pModel!=NULL ? pModel->GetLinkManager() : NULL;
if (pLinkManager && pPageLink)
{
/**********************************************************************
* Abmelden
* (Bei Remove wird *pGraphicLink implizit deleted)
**********************************************************************/
pLinkManager->Remove(pPageLink);
pPageLink=NULL;
}
}
/*************************************************************************
|*
|* Copy-Ctor
|*
\************************************************************************/
SdPage::SdPage(const SdPage& rSrcPage) :
FmFormPage(rSrcPage),
mpItems(NULL)
{
ePageKind = rSrcPage.ePageKind;
eAutoLayout = rSrcPage.eAutoLayout;
bOwnArrangement = FALSE;
PresentationObjectList::const_iterator aIter( rSrcPage.maPresObjList.begin() );
const PresentationObjectList::const_iterator aEnd( rSrcPage.maPresObjList.end() );
for(; aIter != aEnd; aIter++)
{
InsertPresObj(GetObj((*aIter).mpObject->GetOrdNum()), (*aIter).meKind);
}
bSelected = FALSE;
mnTransitionType = rSrcPage.mnTransitionType;
mnTransitionSubtype = rSrcPage.mnTransitionSubtype;
mbTransitionDirection = rSrcPage.mbTransitionDirection;
mnTransitionFadeColor = rSrcPage.mnTransitionFadeColor;
mfTransitionDuration = rSrcPage.mfTransitionDuration;
ePresChange = rSrcPage.ePresChange;
nTime = rSrcPage.nTime;
bSoundOn = rSrcPage.bSoundOn;
bExcluded = rSrcPage.bExcluded;
aLayoutName = rSrcPage.aLayoutName;
aSoundFile = rSrcPage.aSoundFile;
aCreatedPageName = String();
aFileName = rSrcPage.aFileName;
aBookmarkName = rSrcPage.aBookmarkName;
bScaleObjects = rSrcPage.bScaleObjects;
bBackgroundFullSize = rSrcPage.bBackgroundFullSize;
eCharSet = rSrcPage.eCharSet;
nPaperBin = rSrcPage.nPaperBin;
eOrientation = rSrcPage.eOrientation;
// header footer
setHeaderFooterSettings( rSrcPage.getHeaderFooterSettings() );
pPageLink = NULL; // Wird beim Einfuegen ueber ConnectLink() gesetzt
}
/*************************************************************************
|*
|* Clone
|*
\************************************************************************/
SdrPage* SdPage::Clone() const
{
SdPage* pPage = new SdPage(*this);
cloneAnimations( *pPage );
return pPage;
}
/*************************************************************************
|*
|* GetTextStyleSheetForObject
|*
\************************************************************************/
SfxStyleSheet* SdPage::GetTextStyleSheetForObject( SdrObject* pObj ) const
{
const PresObjKind eKind = ((SdPage*)this)->GetPresObjKind(pObj);
if( eKind != PRESOBJ_NONE )
{
return ((SdPage*)this)->GetStyleSheetForPresObj(eKind);
}
return FmFormPage::GetTextStyleSheetForObject( pObj );
}
SfxItemSet* SdPage::getOrCreateItems()
{
if( mpItems == NULL )
mpItems = new SfxItemSet( pModel->GetItemPool(), SDRATTR_XMLATTRIBUTES, SDRATTR_XMLATTRIBUTES );
return mpItems;
}
sal_Bool SdPage::setAlienAttributes( const com::sun::star::uno::Any& rAttributes )
{
SfxItemSet* pSet = getOrCreateItems();
SvXMLAttrContainerItem aAlienAttributes( SDRATTR_XMLATTRIBUTES );
if( aAlienAttributes.PutValue( rAttributes, 0 ) )
{
pSet->Put( aAlienAttributes );
return sal_True;
}
return sal_False;
}
void SdPage::getAlienAttributes( com::sun::star::uno::Any& rAttributes )
{
const SfxPoolItem* pItem;
if( (mpItems == NULL) || ( SFX_ITEM_SET != mpItems->GetItemState( SDRATTR_XMLATTRIBUTES, sal_False, &pItem ) ) )
{
SvXMLAttrContainerItem aAlienAttributes;
aAlienAttributes.QueryValue( rAttributes, 0 );
}
else
{
((SvXMLAttrContainerItem*)pItem)->QueryValue( rAttributes, 0 );
}
}
sal_Int16 SdPage::getTransitionType (void) const
{
return mnTransitionType;
}
void SdPage::setTransitionType( sal_Int16 nTransitionType )
{
mnTransitionType = nTransitionType;
ActionChanged();
}
sal_Int16 SdPage::getTransitionSubtype (void) const
{
return mnTransitionSubtype;
}
void SdPage::setTransitionSubtype ( sal_Int16 nTransitionSubtype )
{
mnTransitionSubtype = nTransitionSubtype;
ActionChanged();
}
sal_Bool SdPage::getTransitionDirection (void) const
{
return mbTransitionDirection;
}
void SdPage::setTransitionDirection ( sal_Bool bTransitionbDirection )
{
mbTransitionDirection = bTransitionbDirection;
ActionChanged();
}
sal_Int32 SdPage::getTransitionFadeColor (void) const
{
return mnTransitionFadeColor;
}
void SdPage::setTransitionFadeColor ( sal_Int32 nTransitionFadeColor )
{
mnTransitionFadeColor = nTransitionFadeColor;
ActionChanged();
}
double SdPage::getTransitionDuration (void) const
{
return mfTransitionDuration;
}
void SdPage::setTransitionDuration ( double fTranstionDuration )
{
mfTransitionDuration = fTranstionDuration;
ActionChanged();
}
INTEGRATION: CWS ooo19126 (1.26.60); FILE MERGED
2005/09/05 13:20:21 rt 1.26.60.1: #i54170# Change license header: remove SISSL
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sdpage2.cxx,v $
*
* $Revision: 1.27 $
*
* last change: $Author: rt $ $Date: 2005-09-09 03:14:10 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SFXDOCFILE_HXX //autogen
#include <sfx2/docfile.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _OUTLINER_HXX
#include <svx/outliner.hxx>
#endif
#ifndef _SVXLINK_HXX
#include <svx/linkmgr.hxx>
#endif
#ifndef _SVDOTEXT_HXX //autogen
#include <svx/svdotext.hxx>
#endif
#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _OUTLOBJ_HXX //autogen
#include <svx/outlobj.hxx>
#endif
#include <svtools/urihelper.hxx>
#ifndef _SVX_XMLCNITM_HXX
#include <svx/xmlcnitm.hxx>
#endif
#ifndef _SVDITER_HXX
#include <svx/svditer.hxx>
#endif
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#include "sdresid.hxx"
#include "sdpage.hxx"
#include "glob.hxx"
#include "glob.hrc"
#include "drawdoc.hxx"
#include "stlpool.hxx"
//#include "sdiocmpt.hxx"
#include "pglink.hxx"
//#include "strmname.h"
#include "anminfo.hxx"
#ifdef MAC
#include "::ui:inc:strings.hrc"
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "::ui:inc:DrawDocShell.hxx"
#endif
#else
#ifdef UNX
#include "../ui/inc/strings.hrc"
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "../ui/inc/DrawDocShell.hxx"
#endif
#else
#include "..\ui\inc\cfgids.hxx"
#include "..\ui\inc\strings.hrc"
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "..\ui\inc\DrawDocShell.hxx"
#endif
#endif
#endif
// #90477#
#ifndef _TOOLS_TENCCVT_HXX
#include <tools/tenccvt.hxx>
#endif
using namespace ::sd;
using namespace ::com::sun::star;
/*************************************************************************
|*
|* SetPresentationLayout, setzt: Layoutnamen, Masterpage-Verknpfung und
|* Vorlagen fuer Praesentationsobjekte
|*
|* Vorraussetzungen: - Die Seite muss bereits das richtige Model kennen!
|* - Die entsprechende Masterpage muss bereits im Model sein.
|* - Die entsprechenden StyleSheets muessen bereits im
|* im StyleSheetPool sein.
|*
|* bReplaceStyleSheets = TRUE : Benannte StyleSheets werden ausgetauscht
|* FALSE: Alle StyleSheets werden neu zugewiesen
|*
|* bSetMasterPage = TRUE : MasterPage suchen und zuweisen
|*
|* bReverseOrder = FALSE: MasterPages von vorn nach hinten suchen
|* TRUE : MasterPages von hinten nach vorn suchen (fuer Undo-Action)
|*
\************************************************************************/
void SdPage::SetPresentationLayout(const String& rLayoutName,
BOOL bReplaceStyleSheets,
BOOL bSetMasterPage,
BOOL bReverseOrder)
{
/*********************************************************************
|* Layoutname der Seite
\********************************************************************/
String aOldLayoutName(aLayoutName); // merken
aLayoutName = rLayoutName;
aLayoutName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( SD_LT_SEPARATOR ));
aLayoutName += String(SdResId(STR_LAYOUT_OUTLINE));
/*********************************************************************
|* ggf. Masterpage suchen und setzen
\********************************************************************/
if (bSetMasterPage && !IsMasterPage())
{
SdPage* pMaster;
SdPage* pFoundMaster = 0;
USHORT nMaster = 0;
USHORT nMasterCount = pModel->GetMasterPageCount();
if( !bReverseOrder )
{
for ( nMaster = 0; nMaster < nMasterCount; nMaster++ )
{
pMaster = static_cast<SdPage*>(pModel->GetMasterPage(nMaster));
if (pMaster->GetPageKind() == ePageKind && pMaster->GetLayoutName() == aLayoutName)
{
pFoundMaster = pMaster;
break;
}
}
}
else
{
for ( nMaster = nMasterCount; nMaster > 0; nMaster-- )
{
pMaster = static_cast<SdPage*>(pModel->GetMasterPage(nMaster - 1));
if (pMaster->GetPageKind() == ePageKind && pMaster->GetLayoutName() == aLayoutName)
{
pFoundMaster = pMaster;
break;
}
}
}
DBG_ASSERT(pFoundMaster, "Masterpage for presentation layout not found!");
// this should never happen, but we play failsafe here
if( pFoundMaster == 0 )
pFoundMaster = static_cast< SdDrawDocument *>(pModel)->GetSdPage( 0, ePageKind );
if( pFoundMaster )
TRG_SetMasterPage(*pFoundMaster);
}
/*********************************************************************
|* Vorlagen fuer Praesentationsobjekte
\********************************************************************/
// Listen mit:
// - Vorlagenzeigern fuer Gliederungstextobjekt (alte und neue Vorlagen)
// -Replacedaten fuer OutlinerParaObject
List aOutlineStyles;
List aOldOutlineStyles;
List aReplList;
BOOL bListsFilled = FALSE;
ULONG nObjCount = GetObjCount();
for (ULONG nObj = 0; nObj < nObjCount; nObj++)
{
SdrTextObj* pObj = (SdrTextObj*) GetObj(nObj);
if (pObj->GetObjInventor() == SdrInventor &&
pObj->GetObjIdentifier() == OBJ_OUTLINETEXT)
{
if (!bListsFilled || !bReplaceStyleSheets)
{
String aFullName;
String aOldFullName;
SfxStyleSheetBase* pSheet = NULL;
SfxStyleSheetBasePool* pStShPool = pModel->GetStyleSheetPool();
for (USHORT i = 1; i < 10; i++)
{
aFullName = aLayoutName;
aOldFullName = aOldLayoutName;
aFullName += sal_Unicode( ' ' );
aFullName += String::CreateFromInt32( (sal_Int32)i );
aOldFullName += sal_Unicode( ' ' );
aOldFullName += String::CreateFromInt32( (sal_Int32)i );
pSheet = pStShPool->Find(aOldFullName, SD_LT_FAMILY);
DBG_ASSERT(pSheet, "alte Gliederungsvorlage nicht gefunden");
aOldOutlineStyles.Insert(pSheet, LIST_APPEND);
pSheet = pStShPool->Find(aFullName, SD_LT_FAMILY);
DBG_ASSERT(pSheet, "neue Gliederungsvorlage nicht gefunden");
aOutlineStyles.Insert(pSheet, LIST_APPEND);
if (bReplaceStyleSheets && pSheet)
{
// Replace anstatt Set
StyleReplaceData* pReplData = new StyleReplaceData;
pReplData->nNewFamily = pSheet->GetFamily();
pReplData->nFamily = pSheet->GetFamily();
pReplData->aNewName = aFullName;
pReplData->aName = aOldFullName;
aReplList.Insert(pReplData, LIST_APPEND);
}
else
{
OutlinerParaObject* pOPO = ((SdrTextObj*)pObj)->GetOutlinerParaObject();
if( pOPO )
pOPO->SetStyleSheets( i, aFullName, SD_LT_FAMILY );
}
}
bListsFilled = TRUE;
}
SfxStyleSheet* pSheet = (SfxStyleSheet*)aOutlineStyles.First();
SfxStyleSheet* pOldSheet = (SfxStyleSheet*)aOldOutlineStyles.First();
while (pSheet)
{
if (pSheet != pOldSheet)
{
pObj->EndListening(*pOldSheet);
if (!pObj->IsListening(*pSheet))
pObj->StartListening(*pSheet);
}
pSheet = (SfxStyleSheet*)aOutlineStyles.Next();
pOldSheet = (SfxStyleSheet*)aOldOutlineStyles.Next();
}
OutlinerParaObject* pOPO = ((SdrTextObj*)pObj)->GetOutlinerParaObject();
if ( bReplaceStyleSheets && pOPO )
{
StyleReplaceData* pReplData = (StyleReplaceData*) aReplList.First();
while( pReplData )
{
pOPO->ChangeStyleSheets( pReplData->aName, pReplData->nFamily, pReplData->aNewName, pReplData->nNewFamily );
pReplData = (StyleReplaceData*) aReplList.Next();
}
}
}
else if (pObj->GetObjInventor() == SdrInventor &&
pObj->GetObjIdentifier() == OBJ_TITLETEXT)
{
// PresObjKind nicht ueber GetPresObjKind() holen, da dort nur
// die PresObjListe beruecksichtigt wird. Es sollen aber alle
// "Titelobjekte" hier beruecksichtigt werden (Paste aus Clipboard usw.)
SfxStyleSheet* pSheet = GetStyleSheetForPresObj(PRESOBJ_TITLE);
if (pSheet)
pObj->SetStyleSheet(pSheet, TRUE);
}
else
{
SfxStyleSheet* pSheet = GetStyleSheetForPresObj(GetPresObjKind(pObj));
if (pSheet)
pObj->SetStyleSheet(pSheet, TRUE);
}
}
for (ULONG i = 0; i < aReplList.Count(); i++)
{
delete (StyleReplaceData*) aReplList.GetObject(i);
}
}
/*************************************************************************
|*
|* das Gliederungstextobjekt bei den Vorlagen fuer die Gliederungsebenen
|* abmelden
|*
\************************************************************************/
void SdPage::EndListenOutlineText()
{
SdrObject* pOutlineTextObj = GetPresObj(PRESOBJ_OUTLINE);
if (pOutlineTextObj)
{
SdStyleSheetPool* pSPool = (SdStyleSheetPool*)pModel->GetStyleSheetPool();
DBG_ASSERT(pSPool, "StyleSheetPool nicht gefunden");
String aTrueLayoutName(aLayoutName);
aTrueLayoutName.Erase( aTrueLayoutName.SearchAscii( SD_LT_SEPARATOR ));
List* pOutlineStyles = pSPool->CreateOutlineSheetList(aTrueLayoutName);
for (SfxStyleSheet* pSheet = (SfxStyleSheet*)pOutlineStyles->First();
pSheet;
pSheet = (SfxStyleSheet*)pOutlineStyles->Next())
{
pOutlineTextObj->EndListening(*pSheet);
}
delete pOutlineStyles;
}
}
/*************************************************************************
|*
|* Neues Model setzen
|*
\************************************************************************/
void SdPage::SetModel(SdrModel* pNewModel)
{
DisconnectLink();
// Model umsetzen
FmFormPage::SetModel(pNewModel);
ConnectLink();
}
/*************************************************************************
|*
|* Ist die Seite read-only?
|*
\************************************************************************/
FASTBOOL SdPage::IsReadOnly() const
{
BOOL bReadOnly = FALSE;
if (pPageLink)
{
// Seite ist gelinkt
// bReadOnly = TRUE wuerde dazu fuehren, dass diese Seite nicht
// bearbeitet werden kann. Dieser Effekt ist jedoch z.Z. nicht
// gewuenscht, daher auskommentiert:
// bReadOnly = TRUE;
}
return (bReadOnly);
}
/*************************************************************************
|*
|* Beim LinkManager anmelden
|*
\************************************************************************/
void SdPage::ConnectLink()
{
SvxLinkManager* pLinkManager = pModel!=NULL ? pModel->GetLinkManager() : NULL;
if (pLinkManager && !pPageLink && aFileName.Len() && aBookmarkName.Len() &&
ePageKind==PK_STANDARD && !IsMasterPage() &&
( (SdDrawDocument*) pModel)->IsNewOrLoadCompleted())
{
/**********************************************************************
* Anmelden
* Nur Standardseiten duerfen gelinkt sein
**********************************************************************/
::sd::DrawDocShell* pDocSh = ((SdDrawDocument*) pModel)->GetDocSh();
if (!pDocSh || pDocSh->GetMedium()->GetOrigURL() != aFileName)
{
// Keine Links auf Dokument-eigene Seiten!
pPageLink = new SdPageLink(this, aFileName, aBookmarkName);
String aFilterName(SdResId(STR_IMPRESS));
pLinkManager->InsertFileLink(*pPageLink, OBJECT_CLIENT_FILE,
aFileName, &aFilterName, &aBookmarkName);
pPageLink->Connect();
}
}
}
/*************************************************************************
|*
|* Beim LinkManager abmelden
|*
\************************************************************************/
void SdPage::DisconnectLink()
{
SvxLinkManager* pLinkManager = pModel!=NULL ? pModel->GetLinkManager() : NULL;
if (pLinkManager && pPageLink)
{
/**********************************************************************
* Abmelden
* (Bei Remove wird *pGraphicLink implizit deleted)
**********************************************************************/
pLinkManager->Remove(pPageLink);
pPageLink=NULL;
}
}
/*************************************************************************
|*
|* Copy-Ctor
|*
\************************************************************************/
SdPage::SdPage(const SdPage& rSrcPage) :
FmFormPage(rSrcPage),
mpItems(NULL)
{
ePageKind = rSrcPage.ePageKind;
eAutoLayout = rSrcPage.eAutoLayout;
bOwnArrangement = FALSE;
PresentationObjectList::const_iterator aIter( rSrcPage.maPresObjList.begin() );
const PresentationObjectList::const_iterator aEnd( rSrcPage.maPresObjList.end() );
for(; aIter != aEnd; aIter++)
{
InsertPresObj(GetObj((*aIter).mpObject->GetOrdNum()), (*aIter).meKind);
}
bSelected = FALSE;
mnTransitionType = rSrcPage.mnTransitionType;
mnTransitionSubtype = rSrcPage.mnTransitionSubtype;
mbTransitionDirection = rSrcPage.mbTransitionDirection;
mnTransitionFadeColor = rSrcPage.mnTransitionFadeColor;
mfTransitionDuration = rSrcPage.mfTransitionDuration;
ePresChange = rSrcPage.ePresChange;
nTime = rSrcPage.nTime;
bSoundOn = rSrcPage.bSoundOn;
bExcluded = rSrcPage.bExcluded;
aLayoutName = rSrcPage.aLayoutName;
aSoundFile = rSrcPage.aSoundFile;
aCreatedPageName = String();
aFileName = rSrcPage.aFileName;
aBookmarkName = rSrcPage.aBookmarkName;
bScaleObjects = rSrcPage.bScaleObjects;
bBackgroundFullSize = rSrcPage.bBackgroundFullSize;
eCharSet = rSrcPage.eCharSet;
nPaperBin = rSrcPage.nPaperBin;
eOrientation = rSrcPage.eOrientation;
// header footer
setHeaderFooterSettings( rSrcPage.getHeaderFooterSettings() );
pPageLink = NULL; // Wird beim Einfuegen ueber ConnectLink() gesetzt
}
/*************************************************************************
|*
|* Clone
|*
\************************************************************************/
SdrPage* SdPage::Clone() const
{
SdPage* pPage = new SdPage(*this);
cloneAnimations( *pPage );
return pPage;
}
/*************************************************************************
|*
|* GetTextStyleSheetForObject
|*
\************************************************************************/
SfxStyleSheet* SdPage::GetTextStyleSheetForObject( SdrObject* pObj ) const
{
const PresObjKind eKind = ((SdPage*)this)->GetPresObjKind(pObj);
if( eKind != PRESOBJ_NONE )
{
return ((SdPage*)this)->GetStyleSheetForPresObj(eKind);
}
return FmFormPage::GetTextStyleSheetForObject( pObj );
}
SfxItemSet* SdPage::getOrCreateItems()
{
if( mpItems == NULL )
mpItems = new SfxItemSet( pModel->GetItemPool(), SDRATTR_XMLATTRIBUTES, SDRATTR_XMLATTRIBUTES );
return mpItems;
}
sal_Bool SdPage::setAlienAttributes( const com::sun::star::uno::Any& rAttributes )
{
SfxItemSet* pSet = getOrCreateItems();
SvXMLAttrContainerItem aAlienAttributes( SDRATTR_XMLATTRIBUTES );
if( aAlienAttributes.PutValue( rAttributes, 0 ) )
{
pSet->Put( aAlienAttributes );
return sal_True;
}
return sal_False;
}
void SdPage::getAlienAttributes( com::sun::star::uno::Any& rAttributes )
{
const SfxPoolItem* pItem;
if( (mpItems == NULL) || ( SFX_ITEM_SET != mpItems->GetItemState( SDRATTR_XMLATTRIBUTES, sal_False, &pItem ) ) )
{
SvXMLAttrContainerItem aAlienAttributes;
aAlienAttributes.QueryValue( rAttributes, 0 );
}
else
{
((SvXMLAttrContainerItem*)pItem)->QueryValue( rAttributes, 0 );
}
}
sal_Int16 SdPage::getTransitionType (void) const
{
return mnTransitionType;
}
void SdPage::setTransitionType( sal_Int16 nTransitionType )
{
mnTransitionType = nTransitionType;
ActionChanged();
}
sal_Int16 SdPage::getTransitionSubtype (void) const
{
return mnTransitionSubtype;
}
void SdPage::setTransitionSubtype ( sal_Int16 nTransitionSubtype )
{
mnTransitionSubtype = nTransitionSubtype;
ActionChanged();
}
sal_Bool SdPage::getTransitionDirection (void) const
{
return mbTransitionDirection;
}
void SdPage::setTransitionDirection ( sal_Bool bTransitionbDirection )
{
mbTransitionDirection = bTransitionbDirection;
ActionChanged();
}
sal_Int32 SdPage::getTransitionFadeColor (void) const
{
return mnTransitionFadeColor;
}
void SdPage::setTransitionFadeColor ( sal_Int32 nTransitionFadeColor )
{
mnTransitionFadeColor = nTransitionFadeColor;
ActionChanged();
}
double SdPage::getTransitionDuration (void) const
{
return mfTransitionDuration;
}
void SdPage::setTransitionDuration ( double fTranstionDuration )
{
mfTransitionDuration = fTranstionDuration;
ActionChanged();
}
|
/*************************************************************************
*
* $RCSfile: sdmod.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: ka $ $Date: 2002-12-11 14:54:56 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SVTOOLS_LANGUAGEOPTIONS_HXX
#include <svtools/languageoptions.hxx>
#endif
#ifndef _UNOTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _SV_VIRDEV_HXX
#include <vcl/virdev.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SV_STATUS_HXX //autogen
#include <vcl/status.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXMSG_HXX //autogen
#include <sfx2/msg.hxx>
#endif
#ifndef _SFXOBJFACE_HXX //autogen
#include <sfx2/objface.hxx>
#endif
#ifndef _SFX_PRINTER_HXX
#include <sfx2/printer.hxx>
#endif
#ifndef _SVX_PSZCTRL_HXX //autogen
#include <svx/pszctrl.hxx>
#endif
#ifndef _SVX_ZOOMCTRL_HXX //autogen
#include <svx/zoomctrl.hxx>
#endif
#ifndef _SVX_MODCTRL_HXX //autogen
#include <svx/modctrl.hxx>
#endif
#ifndef _ZFORLIST_HXX
#include <svtools/zforlist.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _EHDL_HXX
#include <svtools/ehdl.hxx>
#endif
#define ITEMID_SEARCH SID_SEARCH_ITEM
#include <svx/svxids.hrc>
#include <offmgr/ofaids.hrc>
#include <svx/srchitem.hxx>
#pragma hdrstop
#define _SD_DLL // fuer SD_MOD()
#include "sderror.hxx"
#include "sdmod.hxx"
#include "sddll.hxx"
#include "sdresid.hxx"
#include "optsitem.hxx"
#include "docshell.hxx"
#include "drawdoc.hxx"
#include "app.hrc"
#include "glob.hrc"
#include "strings.hrc"
#include "res_bmp.hrc"
#include "cfgids.hxx"
TYPEINIT1( SdModuleDummy, SfxModule );
TYPEINIT1( SdModule, SdModuleDummy );
#define SdModule
#include "sdslots.hxx"
SFX_IMPL_INTERFACE(SdModule, SfxModule, SdResId(STR_APPLICATIONOBJECTBAR))
{
SFX_STATUSBAR_REGISTRATION(RID_DRAW_STATUSBAR);
}
SFX_IMPL_MODULE_DLL(Sd)
/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/
SdModule::SdModule(SvFactory* pDrawObjFact, SvFactory* pGraphicObjFact)
: SdModuleDummy(SFX_APP()->CreateResManager("sd"), FALSE,
pDrawObjFact, pGraphicObjFact),
bWaterCan(FALSE),
pTransferClip(NULL),
pTransferDrag(NULL),
pTransferSelection(NULL),
pImpressOptions(NULL),
pDrawOptions(NULL),
pSearchItem(NULL),
pNumberFormatter( NULL )
{
SetName( UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "StarDraw" ) ) ); // Nicht uebersetzen!
pSearchItem = new SvxSearchItem(ITEMID_SEARCH);
pSearchItem->SetAppFlag(SVX_SEARCHAPP_DRAW);
StartListening( *SFX_APP() );
mpErrorHdl = new SfxErrorHandler( RID_SD_ERRHDL,
ERRCODE_AREA_SD,
ERRCODE_AREA_SD_END,
GetResMgr() );
mpRefDevice = new VirtualDevice;
mpRefDevice->SetMapMode( MAP_100TH_MM );
}
/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
SdModule::~SdModule()
{
delete pSearchItem;
if( pNumberFormatter )
delete pNumberFormatter;
delete mpErrorHdl;
delete static_cast< VirtualDevice* >( mpRefDevice );
}
/*************************************************************************
|*
|* Statusbar erzeugen
|*
\************************************************************************/
#define AUTOSIZE_WIDTH 180
#define TEXT_WIDTH(s) rStatusBar.GetTextWidth((s))
void SdModule::FillStatusBar(StatusBar& rStatusBar)
{
// Hinweis
rStatusBar.InsertItem( SID_CONTEXT, TEXT_WIDTH( String().Fill( 30, 'x' ) ), // vorher 52
SIB_IN | SIB_LEFT | SIB_AUTOSIZE );
// Groesse und Position
rStatusBar.InsertItem( SID_ATTR_SIZE, SvxPosSizeStatusBarControl::GetDefItemWidth(rStatusBar), // vorher 42
SIB_IN | SIB_USERDRAW );
// SIB_AUTOSIZE | SIB_LEFT | SIB_OWNERDRAW );
// Massstab
rStatusBar.InsertItem( SID_ATTR_ZOOM, SvxZoomStatusBarControl::GetDefItemWidth(rStatusBar), SIB_IN | SIB_CENTER );
/*
// Einfuege- / Uberschreibmodus
rStatusBar.InsertItem( SID_ATTR_INSERT, TEXT_WIDTH( "EINFG" ),
SIB_IN | SIB_CENTER );
// Selektionsmodus
rStatusBar.InsertItem( SID_STATUS_SELMODE, TEXT_WIDTH( "ERG" ),
SIB_IN | SIB_CENTER );
*/
// Dokument geaendert
rStatusBar.InsertItem( SID_DOC_MODIFIED, SvxModifyControl::GetDefItemWidth(rStatusBar) );
// Seite
rStatusBar.InsertItem( SID_STATUS_PAGE, TEXT_WIDTH( String().Fill( 24, 'X' ) ),
SIB_IN | SIB_LEFT );
// Praesentationslayout
rStatusBar.InsertItem( SID_STATUS_LAYOUT, TEXT_WIDTH( String().Fill( 10, 'X' ) ),
SIB_IN | SIB_LEFT | SIB_AUTOSIZE );
}
/*************************************************************************
|*
|* Modul laden (nur Attrappe fuer das Linken der DLL)
|*
\************************************************************************/
SfxModule* SdModuleDummy::Load()
{
return (NULL);
}
/*************************************************************************
|*
|* Modul laden
|*
\************************************************************************/
SfxModule* SdModule::Load()
{
return (this);
}
/*************************************************************************
|*
|* get notifications
|*
\************************************************************************/
void SdModule::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
if( rHint.ISA( SfxSimpleHint ) &&
( (SfxSimpleHint&) rHint ).GetId() == SFX_HINT_DEINITIALIZING )
{
delete pImpressOptions, pImpressOptions = NULL;
delete pDrawOptions, pDrawOptions = NULL;
}
}
/*************************************************************************
|*
|* Modul freigeben
|*
\************************************************************************/
void SdModule::Free()
{
}
/*************************************************************************
|*
|* Optionen zurueckgeben
|*
\************************************************************************/
SdOptions* SdModule::GetSdOptions(DocumentType eDocType)
{
SdOptions* pOptions = NULL;
if (eDocType == DOCUMENT_TYPE_DRAW)
{
if (!pDrawOptions)
pDrawOptions = new SdOptions( SDCFG_DRAW );
pOptions = pDrawOptions;
}
else if (eDocType == DOCUMENT_TYPE_IMPRESS)
{
if (!pImpressOptions)
pImpressOptions = new SdOptions( SDCFG_IMPRESS );
pOptions = pImpressOptions;
}
if( pOptions )
{
UINT16 nMetric = pOptions->GetMetric();
SdDrawDocShell* pDocSh = PTR_CAST( SdDrawDocShell, SfxObjectShell::Current() );
SdDrawDocument* pDoc = NULL;
if (pDocSh)
pDoc = pDocSh->GetDoc();
if( nMetric != 0xffff && pDoc && eDocType == pDoc->GetDocumentType() )
PutItem( SfxUInt16Item( SID_ATTR_METRIC, nMetric ) );
}
return(pOptions);
}
/*************************************************************************
|*
|* Optionen-Stream fuer interne Options oeffnen und zurueckgeben;
|* falls der Stream zum Lesen geoeffnet wird, aber noch nicht
|* angelegt wurde, wird ein 'leeres' RefObject zurueckgegeben
|*
\************************************************************************/
SvStorageStreamRef SdModule::GetOptionStream( const String& rOptionName,
SdOptionStreamMode eMode )
{
SdDrawDocShell* pDocSh = PTR_CAST( SdDrawDocShell, SfxObjectShell::Current() );
SvStorageStreamRef xStm;
if( pDocSh )
{
DocumentType eType = pDocSh->GetDoc()->GetDocumentType();
String aStmName;
if( !xOptionStorage.Is() )
{
INetURLObject aURL( SvtPathOptions().GetUserConfigPath() );
aURL.Append( UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "drawing.cfg" ) ) );
SvStream* pStm = ::utl::UcbStreamHelper::CreateStream( aURL.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READWRITE );
if( pStm )
xOptionStorage = new SvStorage( pStm, TRUE );
}
if( DOCUMENT_TYPE_DRAW == eType )
aStmName.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "Draw_" ) );
else
aStmName.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "Impress_" ) );
aStmName += rOptionName;
if( SD_OPTION_STORE == eMode || xOptionStorage->IsContained( aStmName ) )
xStm = xOptionStorage->OpenStream( aStmName );
}
return xStm;
}
/*************************************************************************
|*
\************************************************************************/
SvNumberFormatter* SdModule::GetNumberFormatter()
{
if( !pNumberFormatter )
pNumberFormatter = new SvNumberFormatter( ::comphelper::getProcessServiceFactory(), LANGUAGE_SYSTEM );
return pNumberFormatter;
}
/*************************************************************************
|*
\************************************************************************/
OutputDevice* SdModule::GetRefDevice( SdDrawDocShell& rDocShell )
{
return( IsPrinterRefDevice() ? rDocShell.GetPrinter( sal_True ) : mpRefDevice );
}
/*************************************************************************
|*
\************************************************************************/
sal_Bool SdModule::IsPrinterRefDevice() const
{
return sal_True;
}
/*************************************************************************
|*
\************************************************************************/
::com::sun::star::text::WritingMode SdModule::GetDefaultWritingMode() const
{
/*
const SvtLanguageOptions aLanguageOptions;
return( aLanguageOptions.IsCTLFontEnabled() ?
::com::sun::star::text::WritingMode_RL_TB :
::com::sun::star::text::WritingMode_LR_TB );
*/
return ::com::sun::star::text::WritingMode_LR_TB;
}
INTEGRATION: CWS draw9 (1.18.84); FILE MERGED
2003/04/04 13:40:33 af 1.18.84.1: #108104# Renamed ref device to mpVirtualRefDevice.
/*************************************************************************
*
* $RCSfile: sdmod.cxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: rt $ $Date: 2003-04-24 14:37:04 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SVTOOLS_LANGUAGEOPTIONS_HXX
#include <svtools/languageoptions.hxx>
#endif
#ifndef _UNOTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _SV_VIRDEV_HXX
#include <vcl/virdev.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SV_STATUS_HXX //autogen
#include <vcl/status.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXMSG_HXX //autogen
#include <sfx2/msg.hxx>
#endif
#ifndef _SFXOBJFACE_HXX //autogen
#include <sfx2/objface.hxx>
#endif
#ifndef _SFX_PRINTER_HXX
#include <sfx2/printer.hxx>
#endif
#ifndef _SVX_PSZCTRL_HXX //autogen
#include <svx/pszctrl.hxx>
#endif
#ifndef _SVX_ZOOMCTRL_HXX //autogen
#include <svx/zoomctrl.hxx>
#endif
#ifndef _SVX_MODCTRL_HXX //autogen
#include <svx/modctrl.hxx>
#endif
#ifndef _ZFORLIST_HXX
#include <svtools/zforlist.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _EHDL_HXX
#include <svtools/ehdl.hxx>
#endif
#define ITEMID_SEARCH SID_SEARCH_ITEM
#include <svx/svxids.hrc>
#include <offmgr/ofaids.hrc>
#include <svx/srchitem.hxx>
#pragma hdrstop
#define _SD_DLL // fuer SD_MOD()
#include "sderror.hxx"
#include "sdmod.hxx"
#include "sddll.hxx"
#include "sdresid.hxx"
#include "optsitem.hxx"
#include "docshell.hxx"
#include "drawdoc.hxx"
#include "app.hrc"
#include "glob.hrc"
#include "strings.hrc"
#include "res_bmp.hrc"
#include "cfgids.hxx"
TYPEINIT1( SdModuleDummy, SfxModule );
TYPEINIT1( SdModule, SdModuleDummy );
#define SdModule
#include "sdslots.hxx"
SFX_IMPL_INTERFACE(SdModule, SfxModule, SdResId(STR_APPLICATIONOBJECTBAR))
{
SFX_STATUSBAR_REGISTRATION(RID_DRAW_STATUSBAR);
}
SFX_IMPL_MODULE_DLL(Sd)
/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/
SdModule::SdModule(SvFactory* pDrawObjFact, SvFactory* pGraphicObjFact)
: SdModuleDummy(SFX_APP()->CreateResManager("sd"), FALSE,
pDrawObjFact, pGraphicObjFact),
bWaterCan(FALSE),
pTransferClip(NULL),
pTransferDrag(NULL),
pTransferSelection(NULL),
pImpressOptions(NULL),
pDrawOptions(NULL),
pSearchItem(NULL),
pNumberFormatter( NULL )
{
SetName( UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "StarDraw" ) ) ); // Nicht uebersetzen!
pSearchItem = new SvxSearchItem(ITEMID_SEARCH);
pSearchItem->SetAppFlag(SVX_SEARCHAPP_DRAW);
StartListening( *SFX_APP() );
mpErrorHdl = new SfxErrorHandler( RID_SD_ERRHDL,
ERRCODE_AREA_SD,
ERRCODE_AREA_SD_END,
GetResMgr() );
mpVirtualRefDevice = new VirtualDevice;
mpVirtualRefDevice->SetMapMode( MAP_100TH_MM );
}
/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
SdModule::~SdModule()
{
delete pSearchItem;
if( pNumberFormatter )
delete pNumberFormatter;
delete mpErrorHdl;
delete static_cast< VirtualDevice* >( mpVirtualRefDevice );
}
/*************************************************************************
|*
|* Statusbar erzeugen
|*
\************************************************************************/
#define AUTOSIZE_WIDTH 180
#define TEXT_WIDTH(s) rStatusBar.GetTextWidth((s))
void SdModule::FillStatusBar(StatusBar& rStatusBar)
{
// Hinweis
rStatusBar.InsertItem( SID_CONTEXT, TEXT_WIDTH( String().Fill( 30, 'x' ) ), // vorher 52
SIB_IN | SIB_LEFT | SIB_AUTOSIZE );
// Groesse und Position
rStatusBar.InsertItem( SID_ATTR_SIZE, SvxPosSizeStatusBarControl::GetDefItemWidth(rStatusBar), // vorher 42
SIB_IN | SIB_USERDRAW );
// SIB_AUTOSIZE | SIB_LEFT | SIB_OWNERDRAW );
// Massstab
rStatusBar.InsertItem( SID_ATTR_ZOOM, SvxZoomStatusBarControl::GetDefItemWidth(rStatusBar), SIB_IN | SIB_CENTER );
/*
// Einfuege- / Uberschreibmodus
rStatusBar.InsertItem( SID_ATTR_INSERT, TEXT_WIDTH( "EINFG" ),
SIB_IN | SIB_CENTER );
// Selektionsmodus
rStatusBar.InsertItem( SID_STATUS_SELMODE, TEXT_WIDTH( "ERG" ),
SIB_IN | SIB_CENTER );
*/
// Dokument geaendert
rStatusBar.InsertItem( SID_DOC_MODIFIED, SvxModifyControl::GetDefItemWidth(rStatusBar) );
// Seite
rStatusBar.InsertItem( SID_STATUS_PAGE, TEXT_WIDTH( String().Fill( 24, 'X' ) ),
SIB_IN | SIB_LEFT );
// Praesentationslayout
rStatusBar.InsertItem( SID_STATUS_LAYOUT, TEXT_WIDTH( String().Fill( 10, 'X' ) ),
SIB_IN | SIB_LEFT | SIB_AUTOSIZE );
}
/*************************************************************************
|*
|* Modul laden (nur Attrappe fuer das Linken der DLL)
|*
\************************************************************************/
SfxModule* SdModuleDummy::Load()
{
return (NULL);
}
/*************************************************************************
|*
|* Modul laden
|*
\************************************************************************/
SfxModule* SdModule::Load()
{
return (this);
}
/*************************************************************************
|*
|* get notifications
|*
\************************************************************************/
void SdModule::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
if( rHint.ISA( SfxSimpleHint ) &&
( (SfxSimpleHint&) rHint ).GetId() == SFX_HINT_DEINITIALIZING )
{
delete pImpressOptions, pImpressOptions = NULL;
delete pDrawOptions, pDrawOptions = NULL;
}
}
/*************************************************************************
|*
|* Modul freigeben
|*
\************************************************************************/
void SdModule::Free()
{
}
/*************************************************************************
|*
|* Optionen zurueckgeben
|*
\************************************************************************/
SdOptions* SdModule::GetSdOptions(DocumentType eDocType)
{
SdOptions* pOptions = NULL;
if (eDocType == DOCUMENT_TYPE_DRAW)
{
if (!pDrawOptions)
pDrawOptions = new SdOptions( SDCFG_DRAW );
pOptions = pDrawOptions;
}
else if (eDocType == DOCUMENT_TYPE_IMPRESS)
{
if (!pImpressOptions)
pImpressOptions = new SdOptions( SDCFG_IMPRESS );
pOptions = pImpressOptions;
}
if( pOptions )
{
UINT16 nMetric = pOptions->GetMetric();
SdDrawDocShell* pDocSh = PTR_CAST( SdDrawDocShell, SfxObjectShell::Current() );
SdDrawDocument* pDoc = NULL;
if (pDocSh)
pDoc = pDocSh->GetDoc();
if( nMetric != 0xffff && pDoc && eDocType == pDoc->GetDocumentType() )
PutItem( SfxUInt16Item( SID_ATTR_METRIC, nMetric ) );
}
return(pOptions);
}
/*************************************************************************
|*
|* Optionen-Stream fuer interne Options oeffnen und zurueckgeben;
|* falls der Stream zum Lesen geoeffnet wird, aber noch nicht
|* angelegt wurde, wird ein 'leeres' RefObject zurueckgegeben
|*
\************************************************************************/
SvStorageStreamRef SdModule::GetOptionStream( const String& rOptionName,
SdOptionStreamMode eMode )
{
SdDrawDocShell* pDocSh = PTR_CAST( SdDrawDocShell, SfxObjectShell::Current() );
SvStorageStreamRef xStm;
if( pDocSh )
{
DocumentType eType = pDocSh->GetDoc()->GetDocumentType();
String aStmName;
if( !xOptionStorage.Is() )
{
INetURLObject aURL( SvtPathOptions().GetUserConfigPath() );
aURL.Append( UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "drawing.cfg" ) ) );
SvStream* pStm = ::utl::UcbStreamHelper::CreateStream( aURL.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READWRITE );
if( pStm )
xOptionStorage = new SvStorage( pStm, TRUE );
}
if( DOCUMENT_TYPE_DRAW == eType )
aStmName.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "Draw_" ) );
else
aStmName.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "Impress_" ) );
aStmName += rOptionName;
if( SD_OPTION_STORE == eMode || xOptionStorage->IsContained( aStmName ) )
xStm = xOptionStorage->OpenStream( aStmName );
}
return xStm;
}
/*************************************************************************
|*
\************************************************************************/
SvNumberFormatter* SdModule::GetNumberFormatter()
{
if( !pNumberFormatter )
pNumberFormatter = new SvNumberFormatter( ::comphelper::getProcessServiceFactory(), LANGUAGE_SYSTEM );
return pNumberFormatter;
}
/*************************************************************************
|*
\************************************************************************/
OutputDevice* SdModule::GetVirtualRefDevice (void)
{
return mpVirtualRefDevice;
}
/** This method is deprecated and only an alias to
<member>GetVirtualRefDevice()</member>. The given argument is ignored.
*/
OutputDevice* SdModule::GetRefDevice (SdDrawDocShell& rDocShell)
{
return GetVirtualRefDevice();
}
/*************************************************************************
|*
\************************************************************************/
::com::sun::star::text::WritingMode SdModule::GetDefaultWritingMode() const
{
/*
const SvtLanguageOptions aLanguageOptions;
return( aLanguageOptions.IsCTLFontEnabled() ?
::com::sun::star::text::WritingMode_RL_TB :
::com::sun::star::text::WritingMode_LR_TB );
*/
return ::com::sun::star::text::WritingMode_LR_TB;
}
|
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
// Boost
#include <boost/make_shared.hpp>
// StdAir
#include <stdair/basic/BasChronometer.hpp>
#include <stdair/basic/BasFileMgr.hpp>
#include <stdair/bom/BomManager.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/factory/FacBomManager.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/STDAIR_Service.hpp>
// TravelCCM
#include <travelccm/factory/FacTRAVELCCMServiceContext.hpp>
#include <travelccm/command/ChoiceManager.hpp>
#include <travelccm/service/TRAVELCCM_ServiceContext.hpp>
#include <travelccm/TRAVELCCM_Service.hpp>
namespace TRAVELCCM {
// ////////////////////////////////////////////////////////////////////
TRAVELCCM_Service::TRAVELCCM_Service() : _travelccmServiceContext (NULL) {
assert (false);
}
// ////////////////////////////////////////////////////////////////////
TRAVELCCM_Service::TRAVELCCM_Service (const TRAVELCCM_Service& iService)
: _travelccmServiceContext (NULL) {
assert (false);
}
// ////////////////////////////////////////////////////////////////////
TRAVELCCM_Service::TRAVELCCM_Service (const stdair::BasLogParams& iLogParams,
const stdair::BasDBParams& iDBParams)
: _travelccmServiceContext (NULL) {
// Initialise the STDAIR service handler
stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
initStdAirService (iLogParams, iDBParams);
// Initialise the service context
initServiceContext();
// Add the StdAir service context to the AIRINV service context
// \note AIRINV owns the STDAIR service resources here.
const bool ownStdairService = true;
addStdAirService (lSTDAIR_Service_ptr, ownStdairService);
// Initialise the (remaining of the) context
initTravelCCMService();
}
// ////////////////////////////////////////////////////////////////////
TRAVELCCM_Service::TRAVELCCM_Service (const stdair::BasLogParams& iLogParams)
: _travelccmServiceContext (NULL) {
// Initialise the STDAIR service handler
stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
initStdAirService (iLogParams);
// Initialise the service context
initServiceContext();
// Add the StdAir service context to the AIRINV service context
// \note AIRINV owns the STDAIR service resources here.
const bool ownStdairService = true;
addStdAirService (lSTDAIR_Service_ptr, ownStdairService);
// Initialise the (remaining of the) context
initTravelCCMService();
}
// ////////////////////////////////////////////////////////////////////
TRAVELCCM_Service::
TRAVELCCM_Service (stdair::STDAIR_ServicePtr_T ioSTDAIR_Service_ptr)
: _travelccmServiceContext (NULL) {
// Initialise the service context
initServiceContext();
// Store the STDAIR service object within the (AIRINV) service context
// \note AirInv does not own the STDAIR service resources here.
const bool doesNotOwnStdairService = false;
addStdAirService (ioSTDAIR_Service_ptr, doesNotOwnStdairService);
// Initialise the (remaining of the) context
initTravelCCMService();
}
// ////////////////////////////////////////////////////////////////////
void TRAVELCCM_Service::finalise () {
// ////////////////////////////////////////////////////////////////////
TRAVELCCM_Service::~TRAVELCCM_Service() {
// Delete/Clean all the objects from memory
finalise();
}
// ////////////////////////////////////////////////////////////////////
void TRAVELCCM_Service::finalise() {
assert (_travelccmServiceContext != NULL);
// Reset the (Boost.)Smart pointer pointing on the STDAIR_Service object.
_travelccmServiceContext->reset();
}
// ////////////////////////////////////////////////////////////////////
void TRAVELCCM_Service::initServiceContext() {
// Initialise the context
TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
FacTRAVELCCMServiceContext::instance().create();
_travelccmServiceContext = &lTRAVELCCM_ServiceContext;
}
// ////////////////////////////////////////////////////////////////////
void TRAVELCCM_Service::
addStdAirService (stdair::STDAIR_ServicePtr_T ioSTDAIR_Service_ptr,
const bool iOwnStdairService) {
// Retrieve the Travelccm service context
assert (_travelccmServiceContext != NULL);
TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
*_travelccmServiceContext;
// Store the STDAIR service object within the (TRAVELCCM) service context
lTRAVELCCM_ServiceContext.setSTDAIR_Service (ioSTDAIR_Service_ptr,
iOwnStdairService);
}
// ////////////////////////////////////////////////////////////////////
stdair::STDAIR_ServicePtr_T TRAVELCCM_Service::
initStdAirService (const stdair::BasLogParams& iLogParams,
const stdair::BasDBParams& iDBParams) {
/**
* Initialise the STDAIR service handler.
*
* \note The track on the object memory is kept thanks to the Boost
* Smart Pointers component.
*/
stdair::STDAIR_ServicePtr_T oSTDAIR_Service_ptr =
boost::make_shared<stdair::STDAIR_Service> (iLogParams, iDBParams);
assert (oSTDAIR_Service_ptr != NULL);
return oSTDAIR_Service_ptr;
}
// ////////////////////////////////////////////////////////////////////
stdair::STDAIR_ServicePtr_T TRAVELCCM_Service::
initStdAirService (const stdair::BasLogParams& iLogParams) {
/**
* Initialise the STDAIR service handler.
*
* \note The track on the object memory is kept thanks to the Boost
* Smart Pointers component.
*/
stdair::STDAIR_ServicePtr_T oSTDAIR_Service_ptr =
boost::make_shared<stdair::STDAIR_Service> (iLogParams);
assert (oSTDAIR_Service_ptr != NULL);
return oSTDAIR_Service_ptr;
}
// ////////////////////////////////////////////////////////////////////
void TRAVELCCM_Service::initTravelCCMService() {
// Do nothing at this stage. A sample BOM tree may be built by
// calling the buildSampleBom() method
}
// //////////////////////////////////////////////////////////////////////
void TRAVELCCM_Service::buildSampleBom() {
// Retrieve the TRAVELCCM service context
if (_travelccmServiceContext == NULL) {
throw stdair::NonInitialisedServiceException ("The Travelccm service has "
"not been initialised");
}
assert (_travelccmServiceContext != NULL);
TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
*_travelccmServiceContext;
// Retrieve the STDAIR service object from the (TRAVELCCM) service context
stdair::STDAIR_Service& lSTDAIR_Service =
lTRAVELCCM_ServiceContext.getSTDAIR_Service();
// Delegate the BOM building to the dedicated service
lSTDAIR_Service.buildSampleBom();
}
// //////////////////////////////////////////////////////////////////////
void TRAVELCCM_Service::
buildSampleTravelSolutions (stdair::TravelSolutionList_T& ioTSList) {
// Retrieve the TRAVELCCM service context
if (_travelccmServiceContext == NULL) {
throw stdair::NonInitialisedServiceException ("The Travelccm service has "
"not been initialised");
}
assert (_travelccmServiceContext != NULL);
TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
*_travelccmServiceContext;
// Retrieve the STDAIR service object from the (TRAVELCCM) service context
stdair::STDAIR_Service& lSTDAIR_Service =
lTRAVELCCM_ServiceContext.getSTDAIR_Service();
// Delegate the BOM building to the dedicated service
lSTDAIR_Service.buildSampleTravelSolutions (ioTSList);
}
// //////////////////////////////////////////////////////////////////////
stdair::BookingRequestStruct TRAVELCCM_Service::
buildSampleBookingRequest (const bool isForCRS) {
// Retrieve the TRAVELCCM service context
if (_travelccmServiceContext == NULL) {
throw stdair::NonInitialisedServiceException ("The Travelccm service has "
"not been initialised");
}
assert (_travelccmServiceContext != NULL);
TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
*_travelccmServiceContext;
// Retrieve the STDAIR service object from the (TRAVELCCM) service context
stdair::STDAIR_Service& lSTDAIR_Service =
lTRAVELCCM_ServiceContext.getSTDAIR_Service();
// Delegate the BOM building to the dedicated service
return lSTDAIR_Service.buildSampleBookingRequest (isForCRS);
}
// //////////////////////////////////////////////////////////////////////
std::string TRAVELCCM_Service::csvDisplay() const {
// Retrieve the TRAVELCCM service context
if (_travelccmServiceContext == NULL) {
throw stdair::NonInitialisedServiceException ("The TravelccmMaster service"
" has not been initialised");
}
assert (_travelccmServiceContext != NULL);
TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
*_travelccmServiceContext;
// Retrieve the STDAIR service object from the (TRAVELCCM) service context
stdair::STDAIR_Service& lSTDAIR_Service =
lTRAVELCCM_ServiceContext.getSTDAIR_Service();
// Delegate the BOM building to the dedicated service
return lSTDAIR_Service.csvDisplay();
}
// //////////////////////////////////////////////////////////////////////
std::string TRAVELCCM_Service::
csvDisplay (const stdair::TravelSolutionList_T& iTravelSolutionList) const {
// Retrieve the TRAVELCCM service context
if (_travelccmServiceContext == NULL) {
throw stdair::NonInitialisedServiceException ("The TravelccmMaster service"
" has not been initialised");
}
assert (_travelccmServiceContext != NULL);
TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
*_travelccmServiceContext;
// Retrieve the STDAIR service object from the (TRAVELCCM) service context
stdair::STDAIR_Service& lSTDAIR_Service =
lTRAVELCCM_ServiceContext.getSTDAIR_Service();
// Delegate the BOM building to the dedicated service
return lSTDAIR_Service.csvDisplay (iTravelSolutionList);
}
// ////////////////////////////////////////////////////////////////////
const stdair::TravelSolutionStruct* TRAVELCCM_Service::
chooseTravelSolution (stdair::TravelSolutionList_T& ioTravelSolutionList,
const stdair::BookingRequestStruct& iBookingRequest) {
const stdair::TravelSolutionStruct* oTravelSolution_ptr =
ChoiceManager::chooseTravelSolution (ioTravelSolutionList,
iBookingRequest);
return oTravelSolution_ptr;
}
}
[TravelCCM] [Dev] Fixed a merge problem.
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
// Boost
#include <boost/make_shared.hpp>
// StdAir
#include <stdair/basic/BasChronometer.hpp>
#include <stdair/basic/BasFileMgr.hpp>
#include <stdair/bom/BomManager.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/factory/FacBomManager.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/STDAIR_Service.hpp>
// TravelCCM
#include <travelccm/factory/FacTRAVELCCMServiceContext.hpp>
#include <travelccm/command/ChoiceManager.hpp>
#include <travelccm/service/TRAVELCCM_ServiceContext.hpp>
#include <travelccm/TRAVELCCM_Service.hpp>
namespace TRAVELCCM {
// ////////////////////////////////////////////////////////////////////
TRAVELCCM_Service::TRAVELCCM_Service() : _travelccmServiceContext (NULL) {
assert (false);
}
// ////////////////////////////////////////////////////////////////////
TRAVELCCM_Service::TRAVELCCM_Service (const TRAVELCCM_Service& iService)
: _travelccmServiceContext (NULL) {
assert (false);
}
// ////////////////////////////////////////////////////////////////////
TRAVELCCM_Service::TRAVELCCM_Service (const stdair::BasLogParams& iLogParams,
const stdair::BasDBParams& iDBParams)
: _travelccmServiceContext (NULL) {
// Initialise the STDAIR service handler
stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
initStdAirService (iLogParams, iDBParams);
// Initialise the service context
initServiceContext();
// Add the StdAir service context to the AIRINV service context
// \note AIRINV owns the STDAIR service resources here.
const bool ownStdairService = true;
addStdAirService (lSTDAIR_Service_ptr, ownStdairService);
// Initialise the (remaining of the) context
initTravelCCMService();
}
// ////////////////////////////////////////////////////////////////////
TRAVELCCM_Service::TRAVELCCM_Service (const stdair::BasLogParams& iLogParams)
: _travelccmServiceContext (NULL) {
// Initialise the STDAIR service handler
stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
initStdAirService (iLogParams);
// Initialise the service context
initServiceContext();
// Add the StdAir service context to the AIRINV service context
// \note AIRINV owns the STDAIR service resources here.
const bool ownStdairService = true;
addStdAirService (lSTDAIR_Service_ptr, ownStdairService);
// Initialise the (remaining of the) context
initTravelCCMService();
}
// ////////////////////////////////////////////////////////////////////
TRAVELCCM_Service::
TRAVELCCM_Service (stdair::STDAIR_ServicePtr_T ioSTDAIR_Service_ptr)
: _travelccmServiceContext (NULL) {
// Initialise the service context
initServiceContext();
// Store the STDAIR service object within the (AIRINV) service context
// \note AirInv does not own the STDAIR service resources here.
const bool doesNotOwnStdairService = false;
addStdAirService (ioSTDAIR_Service_ptr, doesNotOwnStdairService);
// Initialise the (remaining of the) context
initTravelCCMService();
}
// ////////////////////////////////////////////////////////////////////
TRAVELCCM_Service::~TRAVELCCM_Service() {
// Delete/Clean all the objects from memory
finalise();
}
// ////////////////////////////////////////////////////////////////////
void TRAVELCCM_Service::finalise() {
assert (_travelccmServiceContext != NULL);
// Reset the (Boost.)Smart pointer pointing on the STDAIR_Service object.
_travelccmServiceContext->reset();
}
// ////////////////////////////////////////////////////////////////////
void TRAVELCCM_Service::initServiceContext() {
// Initialise the context
TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
FacTRAVELCCMServiceContext::instance().create();
_travelccmServiceContext = &lTRAVELCCM_ServiceContext;
}
// ////////////////////////////////////////////////////////////////////
void TRAVELCCM_Service::
addStdAirService (stdair::STDAIR_ServicePtr_T ioSTDAIR_Service_ptr,
const bool iOwnStdairService) {
// Retrieve the Travelccm service context
assert (_travelccmServiceContext != NULL);
TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
*_travelccmServiceContext;
// Store the STDAIR service object within the (TRAVELCCM) service context
lTRAVELCCM_ServiceContext.setSTDAIR_Service (ioSTDAIR_Service_ptr,
iOwnStdairService);
}
// ////////////////////////////////////////////////////////////////////
stdair::STDAIR_ServicePtr_T TRAVELCCM_Service::
initStdAirService (const stdair::BasLogParams& iLogParams,
const stdair::BasDBParams& iDBParams) {
/**
* Initialise the STDAIR service handler.
*
* \note The track on the object memory is kept thanks to the Boost
* Smart Pointers component.
*/
stdair::STDAIR_ServicePtr_T oSTDAIR_Service_ptr =
boost::make_shared<stdair::STDAIR_Service> (iLogParams, iDBParams);
assert (oSTDAIR_Service_ptr != NULL);
return oSTDAIR_Service_ptr;
}
// ////////////////////////////////////////////////////////////////////
stdair::STDAIR_ServicePtr_T TRAVELCCM_Service::
initStdAirService (const stdair::BasLogParams& iLogParams) {
/**
* Initialise the STDAIR service handler.
*
* \note The track on the object memory is kept thanks to the Boost
* Smart Pointers component.
*/
stdair::STDAIR_ServicePtr_T oSTDAIR_Service_ptr =
boost::make_shared<stdair::STDAIR_Service> (iLogParams);
assert (oSTDAIR_Service_ptr != NULL);
return oSTDAIR_Service_ptr;
}
// ////////////////////////////////////////////////////////////////////
void TRAVELCCM_Service::initTravelCCMService() {
// Do nothing at this stage. A sample BOM tree may be built by
// calling the buildSampleBom() method
}
// //////////////////////////////////////////////////////////////////////
void TRAVELCCM_Service::buildSampleBom() {
// Retrieve the TRAVELCCM service context
if (_travelccmServiceContext == NULL) {
throw stdair::NonInitialisedServiceException ("The Travelccm service has "
"not been initialised");
}
assert (_travelccmServiceContext != NULL);
TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
*_travelccmServiceContext;
// Retrieve the STDAIR service object from the (TRAVELCCM) service context
stdair::STDAIR_Service& lSTDAIR_Service =
lTRAVELCCM_ServiceContext.getSTDAIR_Service();
// Delegate the BOM building to the dedicated service
lSTDAIR_Service.buildSampleBom();
}
// //////////////////////////////////////////////////////////////////////
void TRAVELCCM_Service::
buildSampleTravelSolutions (stdair::TravelSolutionList_T& ioTSList) {
// Retrieve the TRAVELCCM service context
if (_travelccmServiceContext == NULL) {
throw stdair::NonInitialisedServiceException ("The Travelccm service has "
"not been initialised");
}
assert (_travelccmServiceContext != NULL);
TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
*_travelccmServiceContext;
// Retrieve the STDAIR service object from the (TRAVELCCM) service context
stdair::STDAIR_Service& lSTDAIR_Service =
lTRAVELCCM_ServiceContext.getSTDAIR_Service();
// Delegate the BOM building to the dedicated service
lSTDAIR_Service.buildSampleTravelSolutions (ioTSList);
}
// //////////////////////////////////////////////////////////////////////
stdair::BookingRequestStruct TRAVELCCM_Service::
buildSampleBookingRequest (const bool isForCRS) {
// Retrieve the TRAVELCCM service context
if (_travelccmServiceContext == NULL) {
throw stdair::NonInitialisedServiceException ("The Travelccm service has "
"not been initialised");
}
assert (_travelccmServiceContext != NULL);
TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
*_travelccmServiceContext;
// Retrieve the STDAIR service object from the (TRAVELCCM) service context
stdair::STDAIR_Service& lSTDAIR_Service =
lTRAVELCCM_ServiceContext.getSTDAIR_Service();
// Delegate the BOM building to the dedicated service
return lSTDAIR_Service.buildSampleBookingRequest (isForCRS);
}
// //////////////////////////////////////////////////////////////////////
std::string TRAVELCCM_Service::csvDisplay() const {
// Retrieve the TRAVELCCM service context
if (_travelccmServiceContext == NULL) {
throw stdair::NonInitialisedServiceException ("The TravelccmMaster service"
" has not been initialised");
}
assert (_travelccmServiceContext != NULL);
TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
*_travelccmServiceContext;
// Retrieve the STDAIR service object from the (TRAVELCCM) service context
stdair::STDAIR_Service& lSTDAIR_Service =
lTRAVELCCM_ServiceContext.getSTDAIR_Service();
// Delegate the BOM building to the dedicated service
return lSTDAIR_Service.csvDisplay();
}
// //////////////////////////////////////////////////////////////////////
std::string TRAVELCCM_Service::
csvDisplay (const stdair::TravelSolutionList_T& iTravelSolutionList) const {
// Retrieve the TRAVELCCM service context
if (_travelccmServiceContext == NULL) {
throw stdair::NonInitialisedServiceException ("The TravelccmMaster service"
" has not been initialised");
}
assert (_travelccmServiceContext != NULL);
TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
*_travelccmServiceContext;
// Retrieve the STDAIR service object from the (TRAVELCCM) service context
stdair::STDAIR_Service& lSTDAIR_Service =
lTRAVELCCM_ServiceContext.getSTDAIR_Service();
// Delegate the BOM building to the dedicated service
return lSTDAIR_Service.csvDisplay (iTravelSolutionList);
}
// ////////////////////////////////////////////////////////////////////
const stdair::TravelSolutionStruct* TRAVELCCM_Service::
chooseTravelSolution (stdair::TravelSolutionList_T& ioTravelSolutionList,
const stdair::BookingRequestStruct& iBookingRequest) {
const stdair::TravelSolutionStruct* oTravelSolution_ptr =
ChoiceManager::chooseTravelSolution (ioTravelSolutionList,
iBookingRequest);
return oTravelSolution_ptr;
}
}
|
/// \file RPageStorageDaos.cxx
/// \ingroup NTuple ROOT7
/// \author Javier Lopez-Gomez <j.lopez@cern.ch>
/// \date 2020-11-03
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include <ROOT/RCluster.hxx>
#include <ROOT/RClusterPool.hxx>
#include <ROOT/RField.hxx>
#include <ROOT/RLogger.hxx>
#include <ROOT/RNTupleDescriptor.hxx>
#include <ROOT/RNTupleModel.hxx>
#include <ROOT/RNTupleUtil.hxx>
#include <ROOT/RNTupleZip.hxx>
#include <ROOT/RPage.hxx>
#include <ROOT/RPageAllocator.hxx>
#include <ROOT/RPagePool.hxx>
#include <ROOT/RDaos.hxx>
#include <ROOT/RPageStorageDaos.hxx>
#include <RVersion.h>
#include <TError.h>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <utility>
#include <regex>
namespace {
struct RDaosURI {
/// \brief UUID of the DAOS pool
std::string fPoolUuid;
/// \brief Ranks of the service replicas, separated by `_`
std::string fSvcReplicas;
/// \brief UUID of the container for this RNTuple
std::string fContainerUuid;
};
/**
\brief Parse a DAOS RNTuple URI of the form 'daos://pool-uuid:svc_replicas/container_uuid'.
*/
RDaosURI ParseDaosURI(std::string_view uri)
{
std::regex re("daos://([[:xdigit:]-]+):([[:digit:]_]+)/([[:xdigit:]-]+)");
std::cmatch m;
if (!std::regex_match(uri.data(), m, re))
throw ROOT::Experimental::RException(R__FAIL("Invalid DAOS pool URI."));
return { m[1], m[2], m[3] };
}
/// \brief Some random distribution/attribute key. TODO: apply recommended schema, i.e.
/// an OID for each cluster + a dkey for each page.
static constexpr std::uint64_t kDistributionKey = 0x5a3c69f0cafe4a11;
static constexpr std::uint64_t kAttributeKey = 0x4243544b5344422d;
static constexpr daos_obj_id_t kOidAnchor{std::uint64_t(-1), 0};
static constexpr daos_obj_id_t kOidHeader{std::uint64_t(-2), 0};
static constexpr daos_obj_id_t kOidFooter{std::uint64_t(-3), 0};
static constexpr daos_oclass_id_t kCidMetadata = OC_SX;
} // namespace
////////////////////////////////////////////////////////////////////////////////
std::uint32_t
ROOT::Experimental::Detail::RDaosNTupleAnchor::Serialize(void *buffer) const
{
using namespace ROOT::Experimental::Internal::RNTupleSerialization;
if (buffer != nullptr) {
auto bytes = reinterpret_cast<unsigned char *>(buffer);
bytes += SerializeUInt32(fVersion, bytes);
bytes += SerializeUInt32(fNBytesHeader, bytes);
bytes += SerializeUInt32(fLenHeader, bytes);
bytes += SerializeUInt32(fNBytesFooter, bytes);
bytes += SerializeUInt32(fLenFooter, bytes);
bytes += SerializeString(fObjClass, bytes);
}
return SerializeString(fObjClass, nullptr) + 20;
}
std::uint32_t
ROOT::Experimental::Detail::RDaosNTupleAnchor::Deserialize(const void *buffer)
{
using namespace ROOT::Experimental::Internal::RNTupleSerialization;
auto bytes = reinterpret_cast<const unsigned char *>(buffer);
bytes += DeserializeUInt32(bytes, &fVersion);
bytes += DeserializeUInt32(bytes, &fNBytesHeader);
bytes += DeserializeUInt32(bytes, &fLenHeader);
bytes += DeserializeUInt32(bytes, &fNBytesFooter);
bytes += DeserializeUInt32(bytes, &fLenFooter);
bytes += DeserializeString(bytes, &fObjClass);
return SerializeString(fObjClass, nullptr) + 20;
}
std::uint32_t
ROOT::Experimental::Detail::RDaosNTupleAnchor::GetSize()
{
return RDaosNTupleAnchor().Serialize(nullptr)
+ ROOT::Experimental::Detail::RDaosObject::ObjClassId::kOCNameMaxLength;
}
////////////////////////////////////////////////////////////////////////////////
ROOT::Experimental::Detail::RPageSinkDaos::RPageSinkDaos(std::string_view ntupleName, std::string_view uri,
const RNTupleWriteOptions &options)
: RPageSink(ntupleName, options)
, fPageAllocator(std::make_unique<RPageAllocatorHeap>())
, fURI(uri)
{
R__LOG_WARNING(NTupleLog()) << "The DAOS backend is experimental and still under development. " <<
"Do not store real data with this version of RNTuple!";
fCompressor = std::make_unique<RNTupleCompressor>();
EnableDefaultMetrics("RPageSinkDaos");
}
ROOT::Experimental::Detail::RPageSinkDaos::~RPageSinkDaos() = default;
void ROOT::Experimental::Detail::RPageSinkDaos::CreateImpl(const RNTupleModel & /* model */)
{
auto opts = dynamic_cast<RNTupleWriteOptionsDaos *>(fOptions.get());
fNTupleAnchor.fObjClass = opts ? opts->GetObjectClass() : RNTupleWriteOptionsDaos().GetObjectClass();
auto oclass = RDaosObject::ObjClassId(fNTupleAnchor.fObjClass);
if (oclass.IsUnknown())
throw ROOT::Experimental::RException(R__FAIL("Unknown object class " + fNTupleAnchor.fObjClass));
auto args = ParseDaosURI(fURI);
auto pool = std::make_shared<RDaosPool>(args.fPoolUuid, args.fSvcReplicas);
fDaosContainer = std::make_unique<RDaosContainer>(pool, args.fContainerUuid, /*create =*/ true);
fDaosContainer->SetDefaultObjectClass(oclass);
const auto &descriptor = fDescriptorBuilder.GetDescriptor();
auto szHeader = descriptor.GetHeaderSize();
auto buffer = std::make_unique<unsigned char[]>(szHeader);
descriptor.SerializeHeader(buffer.get());
auto zipBuffer = std::make_unique<unsigned char[]>(szHeader);
auto szZipHeader = fCompressor->Zip(buffer.get(), szHeader, GetWriteOptions().GetCompression(),
[&zipBuffer](const void *b, size_t n, size_t o){ memcpy(zipBuffer.get() + o, b, n); } );
WriteNTupleHeader(zipBuffer.get(), szZipHeader, szHeader);
}
ROOT::Experimental::RClusterDescriptor::RLocator
ROOT::Experimental::Detail::RPageSinkDaos::CommitPageImpl(ColumnHandle_t columnHandle, const RPage &page)
{
auto element = columnHandle.fColumn->GetElement();
RPageStorage::RSealedPage sealedPage;
{
RNTupleAtomicTimer timer(fCounters->fTimeWallZip, fCounters->fTimeCpuZip);
sealedPage = SealPage(page, *element, GetWriteOptions().GetCompression());
}
fCounters->fSzZip.Add(page.GetNBytes());
return CommitSealedPageImpl(columnHandle.fId, sealedPage);
}
ROOT::Experimental::RClusterDescriptor::RLocator
ROOT::Experimental::Detail::RPageSinkDaos::CommitSealedPageImpl(
DescriptorId_t /*columnId*/, const RPageStorage::RSealedPage &sealedPage)
{
auto offsetData = fOid.fetch_add(1);
{
RNTupleAtomicTimer timer(fCounters->fTimeWallWrite, fCounters->fTimeCpuWrite);
fDaosContainer->WriteSingleAkey(sealedPage.fBuffer, sealedPage.fSize,
{offsetData, 0}, kDistributionKey, kAttributeKey);
}
RClusterDescriptor::RLocator result;
result.fPosition = offsetData;
result.fBytesOnStorage = sealedPage.fSize;
fCounters->fNPageCommitted.Inc();
fCounters->fSzWritePayload.Add(sealedPage.fSize);
fNBytesCurrentCluster += sealedPage.fSize;
return result;
}
std::uint64_t
ROOT::Experimental::Detail::RPageSinkDaos::CommitClusterImpl(ROOT::Experimental::NTupleSize_t /* nEntries */)
{
auto result = fNBytesCurrentCluster;
fNBytesCurrentCluster = 0;
return result;
}
void ROOT::Experimental::Detail::RPageSinkDaos::CommitDatasetImpl()
{
const auto &descriptor = fDescriptorBuilder.GetDescriptor();
auto szFooter = descriptor.GetFooterSize();
auto buffer = std::make_unique<unsigned char []>(szFooter);
descriptor.SerializeFooter(buffer.get());
auto zipBuffer = std::make_unique<unsigned char []>(szFooter);
auto szZipFooter = fCompressor->Zip(buffer.get(), szFooter, GetWriteOptions().GetCompression(),
[&zipBuffer](const void *b, size_t n, size_t o){ memcpy(zipBuffer.get() + o, b, n); } );
WriteNTupleFooter(zipBuffer.get(), szZipFooter, szFooter);
WriteNTupleAnchor();
}
void ROOT::Experimental::Detail::RPageSinkDaos::WriteNTupleHeader(
const void *data, size_t nbytes, size_t lenHeader)
{
fDaosContainer->WriteSingleAkey(data, nbytes, kOidHeader, kDistributionKey,
kAttributeKey, kCidMetadata);
fNTupleAnchor.fLenHeader = lenHeader;
fNTupleAnchor.fNBytesHeader = nbytes;
}
void ROOT::Experimental::Detail::RPageSinkDaos::WriteNTupleFooter(
const void *data, size_t nbytes, size_t lenFooter)
{
fDaosContainer->WriteSingleAkey(data, nbytes, kOidFooter, kDistributionKey,
kAttributeKey, kCidMetadata);
fNTupleAnchor.fLenFooter = lenFooter;
fNTupleAnchor.fNBytesFooter = nbytes;
}
void ROOT::Experimental::Detail::RPageSinkDaos::WriteNTupleAnchor() {
const auto ntplSize = RDaosNTupleAnchor::GetSize();
auto buffer = std::make_unique<unsigned char[]>(ntplSize);
fNTupleAnchor.Serialize(buffer.get());
fDaosContainer->WriteSingleAkey(buffer.get(), ntplSize, kOidAnchor, kDistributionKey,
kAttributeKey, kCidMetadata);
}
ROOT::Experimental::Detail::RPage
ROOT::Experimental::Detail::RPageSinkDaos::ReservePage(ColumnHandle_t columnHandle, std::size_t nElements)
{
if (nElements == 0)
throw RException(R__FAIL("invalid call: request empty page"));
auto elementSize = columnHandle.fColumn->GetElement()->GetSize();
return fPageAllocator->NewPage(columnHandle.fId, elementSize, nElements);
}
void ROOT::Experimental::Detail::RPageSinkDaos::ReleasePage(RPage &page)
{
fPageAllocator->DeletePage(page);
}
////////////////////////////////////////////////////////////////////////////////
ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageAllocatorDaos::NewPage(
ColumnId_t columnId, void *mem, std::size_t elementSize, std::size_t nElements)
{
RPage newPage(columnId, mem, elementSize, nElements);
newPage.GrowUnchecked(nElements);
return newPage;
}
void ROOT::Experimental::Detail::RPageAllocatorDaos::DeletePage(const RPage& page)
{
if (page.IsNull())
return;
delete[] reinterpret_cast<unsigned char *>(page.GetBuffer());
}
////////////////////////////////////////////////////////////////////////////////
ROOT::Experimental::Detail::RPageSourceDaos::RPageSourceDaos(std::string_view ntupleName, std::string_view uri,
const RNTupleReadOptions &options)
: RPageSource(ntupleName, options)
, fPageAllocator(std::make_unique<RPageAllocatorDaos>())
, fPagePool(std::make_shared<RPagePool>())
, fURI(uri)
, fClusterPool(std::make_unique<RClusterPool>(*this))
{
fDecompressor = std::make_unique<RNTupleDecompressor>();
EnableDefaultMetrics("RPageSourceDaos");
auto args = ParseDaosURI(uri);
auto pool = std::make_shared<RDaosPool>(args.fPoolUuid, args.fSvcReplicas);
fDaosContainer = std::make_unique<RDaosContainer>(pool, args.fContainerUuid);
}
ROOT::Experimental::Detail::RPageSourceDaos::~RPageSourceDaos() = default;
ROOT::Experimental::RNTupleDescriptor ROOT::Experimental::Detail::RPageSourceDaos::AttachImpl()
{
RNTupleDescriptorBuilder descBuilder;
RDaosNTupleAnchor ntpl;
const auto ntplSize = RDaosNTupleAnchor::GetSize();
auto buffer = std::make_unique<unsigned char[]>(ntplSize);
fDaosContainer->ReadSingleAkey(buffer.get(), ntplSize, kOidAnchor, kDistributionKey,
kAttributeKey, kCidMetadata);
ntpl.Deserialize(buffer.get());
auto oclass = RDaosObject::ObjClassId(ntpl.fObjClass);
if (oclass.IsUnknown())
throw ROOT::Experimental::RException(R__FAIL("Unknown object class " + ntpl.fObjClass));
fDaosContainer->SetDefaultObjectClass(oclass);
buffer = std::make_unique<unsigned char[]>(ntpl.fLenHeader);
auto zipBuffer = std::make_unique<unsigned char[]>(ntpl.fNBytesHeader);
fDaosContainer->ReadSingleAkey(zipBuffer.get(), ntpl.fNBytesHeader, kOidHeader, kDistributionKey,
kAttributeKey, kCidMetadata);
fDecompressor->Unzip(zipBuffer.get(), ntpl.fNBytesHeader, ntpl.fLenHeader, buffer.get());
descBuilder.SetFromHeader(buffer.get());
buffer = std::make_unique<unsigned char[]>(ntpl.fLenFooter);
zipBuffer = std::make_unique<unsigned char[]>(ntpl.fNBytesFooter);
fDaosContainer->ReadSingleAkey(zipBuffer.get(), ntpl.fNBytesFooter, kOidFooter, kDistributionKey,
kAttributeKey, kCidMetadata);
fDecompressor->Unzip(zipBuffer.get(), ntpl.fNBytesFooter, ntpl.fLenFooter, buffer.get());
descBuilder.AddClustersFromFooter(buffer.get());
return descBuilder.MoveDescriptor();
}
std::string ROOT::Experimental::Detail::RPageSourceDaos::GetObjectClass() const
{
return fDaosContainer->GetDefaultObjectClass().ToString();
}
void ROOT::Experimental::Detail::RPageSourceDaos::LoadSealedPage(
DescriptorId_t columnId, const RClusterIndex &clusterIndex, RSealedPage &sealedPage)
{
const auto clusterId = clusterIndex.GetClusterId();
const auto &clusterDescriptor = fDescriptor.GetClusterDescriptor(clusterId);
auto pageInfo = clusterDescriptor.GetPageRange(columnId).Find(clusterIndex.GetIndex());
const auto bytesOnStorage = pageInfo.fLocator.fBytesOnStorage;
sealedPage.fSize = bytesOnStorage;
sealedPage.fNElements = pageInfo.fNElements;
if (sealedPage.fBuffer) {
fDaosContainer->ReadSingleAkey(const_cast<void *>(sealedPage.fBuffer), bytesOnStorage,
{static_cast<decltype(daos_obj_id_t::lo)>(pageInfo.fLocator.fPosition), 0},
kDistributionKey, kAttributeKey);
}
}
ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceDaos::PopulatePageFromCluster(
ColumnHandle_t columnHandle, const RClusterDescriptor &clusterDescriptor, ClusterSize_t::ValueType idxInCluster)
{
const auto columnId = columnHandle.fId;
const auto clusterId = clusterDescriptor.GetId();
auto pageInfo = clusterDescriptor.GetPageRange(columnId).Find(idxInCluster);
const auto element = columnHandle.fColumn->GetElement();
const auto elementSize = element->GetSize();
const auto bytesOnStorage = pageInfo.fLocator.fBytesOnStorage;
const void *sealedPageBuffer = nullptr; // points either to directReadBuffer or to a read-only page in the cluster
std::unique_ptr<unsigned char []> directReadBuffer; // only used if cluster pool is turned off
if (fOptions.GetClusterCache() == RNTupleReadOptions::EClusterCache::kOff) {
directReadBuffer = std::make_unique<unsigned char[]>(bytesOnStorage);
fDaosContainer->ReadSingleAkey(directReadBuffer.get(), bytesOnStorage,
{static_cast<decltype(daos_obj_id_t::lo)>(pageInfo.fLocator.fPosition), 0},
kDistributionKey, kAttributeKey);
fCounters->fNPageLoaded.Inc();
fCounters->fNRead.Inc();
fCounters->fSzReadPayload.Add(bytesOnStorage);
sealedPageBuffer = directReadBuffer.get();
} else {
if (!fCurrentCluster || (fCurrentCluster->GetId() != clusterId) || !fCurrentCluster->ContainsColumn(columnId))
fCurrentCluster = fClusterPool->GetCluster(clusterId, fActiveColumns);
R__ASSERT(fCurrentCluster->ContainsColumn(columnId));
auto cachedPage = fPagePool->GetPage(columnId, RClusterIndex(clusterId, idxInCluster));
if (!cachedPage.IsNull())
return cachedPage;
ROnDiskPage::Key key(columnId, pageInfo.fPageNo);
auto onDiskPage = fCurrentCluster->GetOnDiskPage(key);
R__ASSERT(onDiskPage && (bytesOnStorage == onDiskPage->GetSize()));
sealedPageBuffer = onDiskPage->GetAddress();
}
std::unique_ptr<unsigned char []> pageBuffer;
{
RNTupleAtomicTimer timer(fCounters->fTimeWallUnzip, fCounters->fTimeCpuUnzip);
pageBuffer = UnsealPage({sealedPageBuffer, bytesOnStorage, pageInfo.fNElements}, *element);
fCounters->fSzUnzip.Add(elementSize * pageInfo.fNElements);
}
const auto indexOffset = clusterDescriptor.GetColumnRange(columnId).fFirstElementIndex;
auto newPage = fPageAllocator->NewPage(columnId, pageBuffer.release(), elementSize, pageInfo.fNElements);
newPage.SetWindow(indexOffset + pageInfo.fFirstInPage, RPage::RClusterInfo(clusterId, indexOffset));
fPagePool->RegisterPage(newPage,
RPageDeleter([](const RPage &page, void * /*userData*/)
{
RPageAllocatorDaos::DeletePage(page);
}, nullptr));
fCounters->fNPagePopulated.Inc();
return newPage;
}
ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceDaos::PopulatePage(
ColumnHandle_t columnHandle, NTupleSize_t globalIndex)
{
const auto columnId = columnHandle.fId;
auto cachedPage = fPagePool->GetPage(columnId, globalIndex);
if (!cachedPage.IsNull())
return cachedPage;
const auto clusterId = fDescriptor.FindClusterId(columnId, globalIndex);
R__ASSERT(clusterId != kInvalidDescriptorId);
const auto &clusterDescriptor = fDescriptor.GetClusterDescriptor(clusterId);
const auto selfOffset = clusterDescriptor.GetColumnRange(columnId).fFirstElementIndex;
R__ASSERT(selfOffset <= globalIndex);
return PopulatePageFromCluster(columnHandle, clusterDescriptor, globalIndex - selfOffset);
}
ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceDaos::PopulatePage(
ColumnHandle_t columnHandle, const RClusterIndex &clusterIndex)
{
const auto clusterId = clusterIndex.GetClusterId();
const auto idxInCluster = clusterIndex.GetIndex();
const auto columnId = columnHandle.fId;
auto cachedPage = fPagePool->GetPage(columnId, clusterIndex);
if (!cachedPage.IsNull())
return cachedPage;
R__ASSERT(clusterId != kInvalidDescriptorId);
const auto &clusterDescriptor = fDescriptor.GetClusterDescriptor(clusterId);
return PopulatePageFromCluster(columnHandle, clusterDescriptor, idxInCluster);
}
void ROOT::Experimental::Detail::RPageSourceDaos::ReleasePage(RPage &page)
{
fPagePool->ReturnPage(page);
}
std::unique_ptr<ROOT::Experimental::Detail::RPageSource> ROOT::Experimental::Detail::RPageSourceDaos::Clone() const
{
auto clone = new RPageSourceDaos(fNTupleName, fURI, fOptions);
return std::unique_ptr<RPageSourceDaos>(clone);
}
std::unique_ptr<ROOT::Experimental::Detail::RCluster>
ROOT::Experimental::Detail::RPageSourceDaos::LoadCluster(DescriptorId_t clusterId, const ColumnSet_t &columns)
{
fCounters->fNClusterLoaded.Inc();
const auto &clusterDesc = GetDescriptor().GetClusterDescriptor(clusterId);
auto clusterLocator = clusterDesc.GetLocator();
struct RDaosSealedPageLocator {
RDaosSealedPageLocator() = default;
RDaosSealedPageLocator(DescriptorId_t c, NTupleSize_t p, std::uint64_t o, std::uint64_t s, std::size_t b)
: fColumnId(c), fPageNo(p), fObjectId(o), fSize(s), fBufPos(b) {}
DescriptorId_t fColumnId = 0;
NTupleSize_t fPageNo = 0;
std::uint64_t fObjectId = 0;
std::uint64_t fSize = 0;
std::size_t fBufPos = 0;
};
// Collect the page necessary page meta-data and sum up the total size of the compressed and packed pages
std::vector<RDaosSealedPageLocator> onDiskPages;
std::size_t szPayload = 0;
for (auto columnId : columns) {
const auto &pageRange = clusterDesc.GetPageRange(columnId);
NTupleSize_t pageNo = 0;
for (const auto &pageInfo : pageRange.fPageInfos) {
const auto &pageLocator = pageInfo.fLocator;
onDiskPages.emplace_back(RDaosSealedPageLocator(
columnId, pageNo, pageLocator.fPosition, pageLocator.fBytesOnStorage, szPayload));
szPayload += pageLocator.fBytesOnStorage;
++pageNo;
}
}
// Prepare the input vector for the RDaosContainer::ReadV() call
std::vector<RDaosContainer::RWOperation> readRequests;
auto buffer = new unsigned char[szPayload];
for (auto &s : onDiskPages) {
std::vector<d_iov_t> iovs(1);
d_iov_set(&iovs[0], buffer + s.fBufPos, s.fSize);
readRequests.emplace_back(daos_obj_id_t{s.fObjectId, 0},
kDistributionKey, kAttributeKey, iovs);
}
fCounters->fSzReadPayload.Add(szPayload);
// Register the on disk pages in a page map
auto pageMap = std::make_unique<ROnDiskPageMapHeap>(std::unique_ptr<unsigned char []>(buffer));
for (const auto &s : onDiskPages) {
ROnDiskPage::Key key(s.fColumnId, s.fPageNo);
pageMap->Register(key, ROnDiskPage(buffer + s.fBufPos, s.fSize));
}
fCounters->fNPageLoaded.Add(onDiskPages.size());
{
RNTupleAtomicTimer timer(fCounters->fTimeWallRead, fCounters->fTimeCpuRead);
fDaosContainer->ReadV(readRequests);
}
fCounters->fNReadV.Inc();
fCounters->fNRead.Add(readRequests.size());
auto cluster = std::make_unique<RCluster>(clusterId);
cluster->Adopt(std::move(pageMap));
for (auto colId : columns)
cluster->SetColumnAvailable(colId);
return cluster;
}
void ROOT::Experimental::Detail::RPageSourceDaos::UnzipClusterImpl(RCluster *cluster)
{
RNTupleAtomicTimer timer(fCounters->fTimeWallUnzip, fCounters->fTimeCpuUnzip);
fTaskScheduler->Reset();
const auto clusterId = cluster->GetId();
const auto &clusterDescriptor = fDescriptor.GetClusterDescriptor(clusterId);
std::vector<std::unique_ptr<RColumnElementBase>> allElements;
const auto &columnsInCluster = cluster->GetAvailColumns();
for (const auto columnId : columnsInCluster) {
const auto &columnDesc = fDescriptor.GetColumnDescriptor(columnId);
allElements.emplace_back(RColumnElementBase::Generate(columnDesc.GetModel().GetType()));
const auto &pageRange = clusterDescriptor.GetPageRange(columnId);
std::uint64_t pageNo = 0;
std::uint64_t firstInPage = 0;
for (const auto &pi : pageRange.fPageInfos) {
ROnDiskPage::Key key(columnId, pageNo);
auto onDiskPage = cluster->GetOnDiskPage(key);
R__ASSERT(onDiskPage && (onDiskPage->GetSize() == pi.fLocator.fBytesOnStorage));
auto taskFunc =
[this, columnId, clusterId, firstInPage, onDiskPage,
element = allElements.back().get(),
nElements = pi.fNElements,
indexOffset = clusterDescriptor.GetColumnRange(columnId).fFirstElementIndex
] () {
auto pageBuffer = UnsealPage({onDiskPage->GetAddress(), onDiskPage->GetSize(), nElements}, *element);
fCounters->fSzUnzip.Add(element->GetSize() * nElements);
auto newPage = fPageAllocator->NewPage(columnId, pageBuffer.release(), element->GetSize(), nElements);
newPage.SetWindow(indexOffset + firstInPage, RPage::RClusterInfo(clusterId, indexOffset));
fPagePool->PreloadPage(newPage,
RPageDeleter([](const RPage &page, void * /*userData*/)
{
RPageAllocatorDaos::DeletePage(page);
}, nullptr));
};
fTaskScheduler->AddTask(taskFunc);
firstInPage += pi.fNElements;
pageNo++;
} // for all pages in column
} // for all columns in cluster
fCounters->fNPagePopulated.Add(cluster->GetNOnDiskPages());
fTaskScheduler->Wait();
}
[ntuple] More concise implementation of RPageSinkDaos::CommitSealedPageImpl
/// \file RPageStorageDaos.cxx
/// \ingroup NTuple ROOT7
/// \author Javier Lopez-Gomez <j.lopez@cern.ch>
/// \date 2020-11-03
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include <ROOT/RCluster.hxx>
#include <ROOT/RClusterPool.hxx>
#include <ROOT/RField.hxx>
#include <ROOT/RLogger.hxx>
#include <ROOT/RNTupleDescriptor.hxx>
#include <ROOT/RNTupleModel.hxx>
#include <ROOT/RNTupleUtil.hxx>
#include <ROOT/RNTupleZip.hxx>
#include <ROOT/RPage.hxx>
#include <ROOT/RPageAllocator.hxx>
#include <ROOT/RPagePool.hxx>
#include <ROOT/RDaos.hxx>
#include <ROOT/RPageStorageDaos.hxx>
#include <RVersion.h>
#include <TError.h>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <utility>
#include <regex>
namespace {
struct RDaosURI {
/// \brief UUID of the DAOS pool
std::string fPoolUuid;
/// \brief Ranks of the service replicas, separated by `_`
std::string fSvcReplicas;
/// \brief UUID of the container for this RNTuple
std::string fContainerUuid;
};
/**
\brief Parse a DAOS RNTuple URI of the form 'daos://pool-uuid:svc_replicas/container_uuid'.
*/
RDaosURI ParseDaosURI(std::string_view uri)
{
std::regex re("daos://([[:xdigit:]-]+):([[:digit:]_]+)/([[:xdigit:]-]+)");
std::cmatch m;
if (!std::regex_match(uri.data(), m, re))
throw ROOT::Experimental::RException(R__FAIL("Invalid DAOS pool URI."));
return { m[1], m[2], m[3] };
}
/// \brief Some random distribution/attribute key. TODO: apply recommended schema, i.e.
/// an OID for each cluster + a dkey for each page.
static constexpr std::uint64_t kDistributionKey = 0x5a3c69f0cafe4a11;
static constexpr std::uint64_t kAttributeKey = 0x4243544b5344422d;
static constexpr daos_obj_id_t kOidAnchor{std::uint64_t(-1), 0};
static constexpr daos_obj_id_t kOidHeader{std::uint64_t(-2), 0};
static constexpr daos_obj_id_t kOidFooter{std::uint64_t(-3), 0};
static constexpr daos_oclass_id_t kCidMetadata = OC_SX;
} // namespace
////////////////////////////////////////////////////////////////////////////////
std::uint32_t
ROOT::Experimental::Detail::RDaosNTupleAnchor::Serialize(void *buffer) const
{
using namespace ROOT::Experimental::Internal::RNTupleSerialization;
if (buffer != nullptr) {
auto bytes = reinterpret_cast<unsigned char *>(buffer);
bytes += SerializeUInt32(fVersion, bytes);
bytes += SerializeUInt32(fNBytesHeader, bytes);
bytes += SerializeUInt32(fLenHeader, bytes);
bytes += SerializeUInt32(fNBytesFooter, bytes);
bytes += SerializeUInt32(fLenFooter, bytes);
bytes += SerializeString(fObjClass, bytes);
}
return SerializeString(fObjClass, nullptr) + 20;
}
std::uint32_t
ROOT::Experimental::Detail::RDaosNTupleAnchor::Deserialize(const void *buffer)
{
using namespace ROOT::Experimental::Internal::RNTupleSerialization;
auto bytes = reinterpret_cast<const unsigned char *>(buffer);
bytes += DeserializeUInt32(bytes, &fVersion);
bytes += DeserializeUInt32(bytes, &fNBytesHeader);
bytes += DeserializeUInt32(bytes, &fLenHeader);
bytes += DeserializeUInt32(bytes, &fNBytesFooter);
bytes += DeserializeUInt32(bytes, &fLenFooter);
bytes += DeserializeString(bytes, &fObjClass);
return SerializeString(fObjClass, nullptr) + 20;
}
std::uint32_t
ROOT::Experimental::Detail::RDaosNTupleAnchor::GetSize()
{
return RDaosNTupleAnchor().Serialize(nullptr)
+ ROOT::Experimental::Detail::RDaosObject::ObjClassId::kOCNameMaxLength;
}
////////////////////////////////////////////////////////////////////////////////
ROOT::Experimental::Detail::RPageSinkDaos::RPageSinkDaos(std::string_view ntupleName, std::string_view uri,
const RNTupleWriteOptions &options)
: RPageSink(ntupleName, options)
, fPageAllocator(std::make_unique<RPageAllocatorHeap>())
, fURI(uri)
{
R__LOG_WARNING(NTupleLog()) << "The DAOS backend is experimental and still under development. " <<
"Do not store real data with this version of RNTuple!";
fCompressor = std::make_unique<RNTupleCompressor>();
EnableDefaultMetrics("RPageSinkDaos");
}
ROOT::Experimental::Detail::RPageSinkDaos::~RPageSinkDaos() = default;
void ROOT::Experimental::Detail::RPageSinkDaos::CreateImpl(const RNTupleModel & /* model */)
{
auto opts = dynamic_cast<RNTupleWriteOptionsDaos *>(fOptions.get());
fNTupleAnchor.fObjClass = opts ? opts->GetObjectClass() : RNTupleWriteOptionsDaos().GetObjectClass();
auto oclass = RDaosObject::ObjClassId(fNTupleAnchor.fObjClass);
if (oclass.IsUnknown())
throw ROOT::Experimental::RException(R__FAIL("Unknown object class " + fNTupleAnchor.fObjClass));
auto args = ParseDaosURI(fURI);
auto pool = std::make_shared<RDaosPool>(args.fPoolUuid, args.fSvcReplicas);
fDaosContainer = std::make_unique<RDaosContainer>(pool, args.fContainerUuid, /*create =*/ true);
fDaosContainer->SetDefaultObjectClass(oclass);
const auto &descriptor = fDescriptorBuilder.GetDescriptor();
auto szHeader = descriptor.GetHeaderSize();
auto buffer = std::make_unique<unsigned char[]>(szHeader);
descriptor.SerializeHeader(buffer.get());
auto zipBuffer = std::make_unique<unsigned char[]>(szHeader);
auto szZipHeader = fCompressor->Zip(buffer.get(), szHeader, GetWriteOptions().GetCompression(),
[&zipBuffer](const void *b, size_t n, size_t o){ memcpy(zipBuffer.get() + o, b, n); } );
WriteNTupleHeader(zipBuffer.get(), szZipHeader, szHeader);
}
ROOT::Experimental::RClusterDescriptor::RLocator
ROOT::Experimental::Detail::RPageSinkDaos::CommitPageImpl(ColumnHandle_t columnHandle, const RPage &page)
{
auto element = columnHandle.fColumn->GetElement();
RPageStorage::RSealedPage sealedPage;
{
RNTupleAtomicTimer timer(fCounters->fTimeWallZip, fCounters->fTimeCpuZip);
sealedPage = SealPage(page, *element, GetWriteOptions().GetCompression());
}
fCounters->fSzZip.Add(page.GetNBytes());
return CommitSealedPageImpl(columnHandle.fId, sealedPage);
}
ROOT::Experimental::RClusterDescriptor::RLocator
ROOT::Experimental::Detail::RPageSinkDaos::CommitSealedPageImpl(
DescriptorId_t /*columnId*/, const RPageStorage::RSealedPage &sealedPage)
{
auto offsetData = fOid.fetch_add(1);
{
RNTupleAtomicTimer timer(fCounters->fTimeWallWrite, fCounters->fTimeCpuWrite);
fDaosContainer->WriteSingleAkey(sealedPage.fBuffer, sealedPage.fSize,
{offsetData, 0}, kDistributionKey, kAttributeKey);
}
RClusterDescriptor::RLocator result;
result.fPosition = offsetData;
result.fBytesOnStorage = sealedPage.fSize;
fCounters->fNPageCommitted.Inc();
fCounters->fSzWritePayload.Add(sealedPage.fSize);
fNBytesCurrentCluster += sealedPage.fSize;
return result;
}
std::uint64_t
ROOT::Experimental::Detail::RPageSinkDaos::CommitClusterImpl(ROOT::Experimental::NTupleSize_t /* nEntries */)
{
return std::exchange(fNBytesCurrentCluster, 0);
}
void ROOT::Experimental::Detail::RPageSinkDaos::CommitDatasetImpl()
{
const auto &descriptor = fDescriptorBuilder.GetDescriptor();
auto szFooter = descriptor.GetFooterSize();
auto buffer = std::make_unique<unsigned char []>(szFooter);
descriptor.SerializeFooter(buffer.get());
auto zipBuffer = std::make_unique<unsigned char []>(szFooter);
auto szZipFooter = fCompressor->Zip(buffer.get(), szFooter, GetWriteOptions().GetCompression(),
[&zipBuffer](const void *b, size_t n, size_t o){ memcpy(zipBuffer.get() + o, b, n); } );
WriteNTupleFooter(zipBuffer.get(), szZipFooter, szFooter);
WriteNTupleAnchor();
}
void ROOT::Experimental::Detail::RPageSinkDaos::WriteNTupleHeader(
const void *data, size_t nbytes, size_t lenHeader)
{
fDaosContainer->WriteSingleAkey(data, nbytes, kOidHeader, kDistributionKey,
kAttributeKey, kCidMetadata);
fNTupleAnchor.fLenHeader = lenHeader;
fNTupleAnchor.fNBytesHeader = nbytes;
}
void ROOT::Experimental::Detail::RPageSinkDaos::WriteNTupleFooter(
const void *data, size_t nbytes, size_t lenFooter)
{
fDaosContainer->WriteSingleAkey(data, nbytes, kOidFooter, kDistributionKey,
kAttributeKey, kCidMetadata);
fNTupleAnchor.fLenFooter = lenFooter;
fNTupleAnchor.fNBytesFooter = nbytes;
}
void ROOT::Experimental::Detail::RPageSinkDaos::WriteNTupleAnchor() {
const auto ntplSize = RDaosNTupleAnchor::GetSize();
auto buffer = std::make_unique<unsigned char[]>(ntplSize);
fNTupleAnchor.Serialize(buffer.get());
fDaosContainer->WriteSingleAkey(buffer.get(), ntplSize, kOidAnchor, kDistributionKey,
kAttributeKey, kCidMetadata);
}
ROOT::Experimental::Detail::RPage
ROOT::Experimental::Detail::RPageSinkDaos::ReservePage(ColumnHandle_t columnHandle, std::size_t nElements)
{
if (nElements == 0)
throw RException(R__FAIL("invalid call: request empty page"));
auto elementSize = columnHandle.fColumn->GetElement()->GetSize();
return fPageAllocator->NewPage(columnHandle.fId, elementSize, nElements);
}
void ROOT::Experimental::Detail::RPageSinkDaos::ReleasePage(RPage &page)
{
fPageAllocator->DeletePage(page);
}
////////////////////////////////////////////////////////////////////////////////
ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageAllocatorDaos::NewPage(
ColumnId_t columnId, void *mem, std::size_t elementSize, std::size_t nElements)
{
RPage newPage(columnId, mem, elementSize, nElements);
newPage.GrowUnchecked(nElements);
return newPage;
}
void ROOT::Experimental::Detail::RPageAllocatorDaos::DeletePage(const RPage& page)
{
if (page.IsNull())
return;
delete[] reinterpret_cast<unsigned char *>(page.GetBuffer());
}
////////////////////////////////////////////////////////////////////////////////
ROOT::Experimental::Detail::RPageSourceDaos::RPageSourceDaos(std::string_view ntupleName, std::string_view uri,
const RNTupleReadOptions &options)
: RPageSource(ntupleName, options)
, fPageAllocator(std::make_unique<RPageAllocatorDaos>())
, fPagePool(std::make_shared<RPagePool>())
, fURI(uri)
, fClusterPool(std::make_unique<RClusterPool>(*this))
{
fDecompressor = std::make_unique<RNTupleDecompressor>();
EnableDefaultMetrics("RPageSourceDaos");
auto args = ParseDaosURI(uri);
auto pool = std::make_shared<RDaosPool>(args.fPoolUuid, args.fSvcReplicas);
fDaosContainer = std::make_unique<RDaosContainer>(pool, args.fContainerUuid);
}
ROOT::Experimental::Detail::RPageSourceDaos::~RPageSourceDaos() = default;
ROOT::Experimental::RNTupleDescriptor ROOT::Experimental::Detail::RPageSourceDaos::AttachImpl()
{
RNTupleDescriptorBuilder descBuilder;
RDaosNTupleAnchor ntpl;
const auto ntplSize = RDaosNTupleAnchor::GetSize();
auto buffer = std::make_unique<unsigned char[]>(ntplSize);
fDaosContainer->ReadSingleAkey(buffer.get(), ntplSize, kOidAnchor, kDistributionKey,
kAttributeKey, kCidMetadata);
ntpl.Deserialize(buffer.get());
auto oclass = RDaosObject::ObjClassId(ntpl.fObjClass);
if (oclass.IsUnknown())
throw ROOT::Experimental::RException(R__FAIL("Unknown object class " + ntpl.fObjClass));
fDaosContainer->SetDefaultObjectClass(oclass);
buffer = std::make_unique<unsigned char[]>(ntpl.fLenHeader);
auto zipBuffer = std::make_unique<unsigned char[]>(ntpl.fNBytesHeader);
fDaosContainer->ReadSingleAkey(zipBuffer.get(), ntpl.fNBytesHeader, kOidHeader, kDistributionKey,
kAttributeKey, kCidMetadata);
fDecompressor->Unzip(zipBuffer.get(), ntpl.fNBytesHeader, ntpl.fLenHeader, buffer.get());
descBuilder.SetFromHeader(buffer.get());
buffer = std::make_unique<unsigned char[]>(ntpl.fLenFooter);
zipBuffer = std::make_unique<unsigned char[]>(ntpl.fNBytesFooter);
fDaosContainer->ReadSingleAkey(zipBuffer.get(), ntpl.fNBytesFooter, kOidFooter, kDistributionKey,
kAttributeKey, kCidMetadata);
fDecompressor->Unzip(zipBuffer.get(), ntpl.fNBytesFooter, ntpl.fLenFooter, buffer.get());
descBuilder.AddClustersFromFooter(buffer.get());
return descBuilder.MoveDescriptor();
}
std::string ROOT::Experimental::Detail::RPageSourceDaos::GetObjectClass() const
{
return fDaosContainer->GetDefaultObjectClass().ToString();
}
void ROOT::Experimental::Detail::RPageSourceDaos::LoadSealedPage(
DescriptorId_t columnId, const RClusterIndex &clusterIndex, RSealedPage &sealedPage)
{
const auto clusterId = clusterIndex.GetClusterId();
const auto &clusterDescriptor = fDescriptor.GetClusterDescriptor(clusterId);
auto pageInfo = clusterDescriptor.GetPageRange(columnId).Find(clusterIndex.GetIndex());
const auto bytesOnStorage = pageInfo.fLocator.fBytesOnStorage;
sealedPage.fSize = bytesOnStorage;
sealedPage.fNElements = pageInfo.fNElements;
if (sealedPage.fBuffer) {
fDaosContainer->ReadSingleAkey(const_cast<void *>(sealedPage.fBuffer), bytesOnStorage,
{static_cast<decltype(daos_obj_id_t::lo)>(pageInfo.fLocator.fPosition), 0},
kDistributionKey, kAttributeKey);
}
}
ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceDaos::PopulatePageFromCluster(
ColumnHandle_t columnHandle, const RClusterDescriptor &clusterDescriptor, ClusterSize_t::ValueType idxInCluster)
{
const auto columnId = columnHandle.fId;
const auto clusterId = clusterDescriptor.GetId();
auto pageInfo = clusterDescriptor.GetPageRange(columnId).Find(idxInCluster);
const auto element = columnHandle.fColumn->GetElement();
const auto elementSize = element->GetSize();
const auto bytesOnStorage = pageInfo.fLocator.fBytesOnStorage;
const void *sealedPageBuffer = nullptr; // points either to directReadBuffer or to a read-only page in the cluster
std::unique_ptr<unsigned char []> directReadBuffer; // only used if cluster pool is turned off
if (fOptions.GetClusterCache() == RNTupleReadOptions::EClusterCache::kOff) {
directReadBuffer = std::make_unique<unsigned char[]>(bytesOnStorage);
fDaosContainer->ReadSingleAkey(directReadBuffer.get(), bytesOnStorage,
{static_cast<decltype(daos_obj_id_t::lo)>(pageInfo.fLocator.fPosition), 0},
kDistributionKey, kAttributeKey);
fCounters->fNPageLoaded.Inc();
fCounters->fNRead.Inc();
fCounters->fSzReadPayload.Add(bytesOnStorage);
sealedPageBuffer = directReadBuffer.get();
} else {
if (!fCurrentCluster || (fCurrentCluster->GetId() != clusterId) || !fCurrentCluster->ContainsColumn(columnId))
fCurrentCluster = fClusterPool->GetCluster(clusterId, fActiveColumns);
R__ASSERT(fCurrentCluster->ContainsColumn(columnId));
auto cachedPage = fPagePool->GetPage(columnId, RClusterIndex(clusterId, idxInCluster));
if (!cachedPage.IsNull())
return cachedPage;
ROnDiskPage::Key key(columnId, pageInfo.fPageNo);
auto onDiskPage = fCurrentCluster->GetOnDiskPage(key);
R__ASSERT(onDiskPage && (bytesOnStorage == onDiskPage->GetSize()));
sealedPageBuffer = onDiskPage->GetAddress();
}
std::unique_ptr<unsigned char []> pageBuffer;
{
RNTupleAtomicTimer timer(fCounters->fTimeWallUnzip, fCounters->fTimeCpuUnzip);
pageBuffer = UnsealPage({sealedPageBuffer, bytesOnStorage, pageInfo.fNElements}, *element);
fCounters->fSzUnzip.Add(elementSize * pageInfo.fNElements);
}
const auto indexOffset = clusterDescriptor.GetColumnRange(columnId).fFirstElementIndex;
auto newPage = fPageAllocator->NewPage(columnId, pageBuffer.release(), elementSize, pageInfo.fNElements);
newPage.SetWindow(indexOffset + pageInfo.fFirstInPage, RPage::RClusterInfo(clusterId, indexOffset));
fPagePool->RegisterPage(newPage,
RPageDeleter([](const RPage &page, void * /*userData*/)
{
RPageAllocatorDaos::DeletePage(page);
}, nullptr));
fCounters->fNPagePopulated.Inc();
return newPage;
}
ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceDaos::PopulatePage(
ColumnHandle_t columnHandle, NTupleSize_t globalIndex)
{
const auto columnId = columnHandle.fId;
auto cachedPage = fPagePool->GetPage(columnId, globalIndex);
if (!cachedPage.IsNull())
return cachedPage;
const auto clusterId = fDescriptor.FindClusterId(columnId, globalIndex);
R__ASSERT(clusterId != kInvalidDescriptorId);
const auto &clusterDescriptor = fDescriptor.GetClusterDescriptor(clusterId);
const auto selfOffset = clusterDescriptor.GetColumnRange(columnId).fFirstElementIndex;
R__ASSERT(selfOffset <= globalIndex);
return PopulatePageFromCluster(columnHandle, clusterDescriptor, globalIndex - selfOffset);
}
ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceDaos::PopulatePage(
ColumnHandle_t columnHandle, const RClusterIndex &clusterIndex)
{
const auto clusterId = clusterIndex.GetClusterId();
const auto idxInCluster = clusterIndex.GetIndex();
const auto columnId = columnHandle.fId;
auto cachedPage = fPagePool->GetPage(columnId, clusterIndex);
if (!cachedPage.IsNull())
return cachedPage;
R__ASSERT(clusterId != kInvalidDescriptorId);
const auto &clusterDescriptor = fDescriptor.GetClusterDescriptor(clusterId);
return PopulatePageFromCluster(columnHandle, clusterDescriptor, idxInCluster);
}
void ROOT::Experimental::Detail::RPageSourceDaos::ReleasePage(RPage &page)
{
fPagePool->ReturnPage(page);
}
std::unique_ptr<ROOT::Experimental::Detail::RPageSource> ROOT::Experimental::Detail::RPageSourceDaos::Clone() const
{
auto clone = new RPageSourceDaos(fNTupleName, fURI, fOptions);
return std::unique_ptr<RPageSourceDaos>(clone);
}
std::unique_ptr<ROOT::Experimental::Detail::RCluster>
ROOT::Experimental::Detail::RPageSourceDaos::LoadCluster(DescriptorId_t clusterId, const ColumnSet_t &columns)
{
fCounters->fNClusterLoaded.Inc();
const auto &clusterDesc = GetDescriptor().GetClusterDescriptor(clusterId);
auto clusterLocator = clusterDesc.GetLocator();
struct RDaosSealedPageLocator {
RDaosSealedPageLocator() = default;
RDaosSealedPageLocator(DescriptorId_t c, NTupleSize_t p, std::uint64_t o, std::uint64_t s, std::size_t b)
: fColumnId(c), fPageNo(p), fObjectId(o), fSize(s), fBufPos(b) {}
DescriptorId_t fColumnId = 0;
NTupleSize_t fPageNo = 0;
std::uint64_t fObjectId = 0;
std::uint64_t fSize = 0;
std::size_t fBufPos = 0;
};
// Collect the page necessary page meta-data and sum up the total size of the compressed and packed pages
std::vector<RDaosSealedPageLocator> onDiskPages;
std::size_t szPayload = 0;
for (auto columnId : columns) {
const auto &pageRange = clusterDesc.GetPageRange(columnId);
NTupleSize_t pageNo = 0;
for (const auto &pageInfo : pageRange.fPageInfos) {
const auto &pageLocator = pageInfo.fLocator;
onDiskPages.emplace_back(RDaosSealedPageLocator(
columnId, pageNo, pageLocator.fPosition, pageLocator.fBytesOnStorage, szPayload));
szPayload += pageLocator.fBytesOnStorage;
++pageNo;
}
}
// Prepare the input vector for the RDaosContainer::ReadV() call
std::vector<RDaosContainer::RWOperation> readRequests;
auto buffer = new unsigned char[szPayload];
for (auto &s : onDiskPages) {
std::vector<d_iov_t> iovs(1);
d_iov_set(&iovs[0], buffer + s.fBufPos, s.fSize);
readRequests.emplace_back(daos_obj_id_t{s.fObjectId, 0},
kDistributionKey, kAttributeKey, iovs);
}
fCounters->fSzReadPayload.Add(szPayload);
// Register the on disk pages in a page map
auto pageMap = std::make_unique<ROnDiskPageMapHeap>(std::unique_ptr<unsigned char []>(buffer));
for (const auto &s : onDiskPages) {
ROnDiskPage::Key key(s.fColumnId, s.fPageNo);
pageMap->Register(key, ROnDiskPage(buffer + s.fBufPos, s.fSize));
}
fCounters->fNPageLoaded.Add(onDiskPages.size());
{
RNTupleAtomicTimer timer(fCounters->fTimeWallRead, fCounters->fTimeCpuRead);
fDaosContainer->ReadV(readRequests);
}
fCounters->fNReadV.Inc();
fCounters->fNRead.Add(readRequests.size());
auto cluster = std::make_unique<RCluster>(clusterId);
cluster->Adopt(std::move(pageMap));
for (auto colId : columns)
cluster->SetColumnAvailable(colId);
return cluster;
}
void ROOT::Experimental::Detail::RPageSourceDaos::UnzipClusterImpl(RCluster *cluster)
{
RNTupleAtomicTimer timer(fCounters->fTimeWallUnzip, fCounters->fTimeCpuUnzip);
fTaskScheduler->Reset();
const auto clusterId = cluster->GetId();
const auto &clusterDescriptor = fDescriptor.GetClusterDescriptor(clusterId);
std::vector<std::unique_ptr<RColumnElementBase>> allElements;
const auto &columnsInCluster = cluster->GetAvailColumns();
for (const auto columnId : columnsInCluster) {
const auto &columnDesc = fDescriptor.GetColumnDescriptor(columnId);
allElements.emplace_back(RColumnElementBase::Generate(columnDesc.GetModel().GetType()));
const auto &pageRange = clusterDescriptor.GetPageRange(columnId);
std::uint64_t pageNo = 0;
std::uint64_t firstInPage = 0;
for (const auto &pi : pageRange.fPageInfos) {
ROnDiskPage::Key key(columnId, pageNo);
auto onDiskPage = cluster->GetOnDiskPage(key);
R__ASSERT(onDiskPage && (onDiskPage->GetSize() == pi.fLocator.fBytesOnStorage));
auto taskFunc =
[this, columnId, clusterId, firstInPage, onDiskPage,
element = allElements.back().get(),
nElements = pi.fNElements,
indexOffset = clusterDescriptor.GetColumnRange(columnId).fFirstElementIndex
] () {
auto pageBuffer = UnsealPage({onDiskPage->GetAddress(), onDiskPage->GetSize(), nElements}, *element);
fCounters->fSzUnzip.Add(element->GetSize() * nElements);
auto newPage = fPageAllocator->NewPage(columnId, pageBuffer.release(), element->GetSize(), nElements);
newPage.SetWindow(indexOffset + firstInPage, RPage::RClusterInfo(clusterId, indexOffset));
fPagePool->PreloadPage(newPage,
RPageDeleter([](const RPage &page, void * /*userData*/)
{
RPageAllocatorDaos::DeletePage(page);
}, nullptr));
};
fTaskScheduler->AddTask(taskFunc);
firstInPage += pi.fNElements;
pageNo++;
} // for all pages in column
} // for all columns in cluster
fCounters->fNPagePopulated.Add(cluster->GetNOnDiskPages());
fTaskScheduler->Wait();
}
|
/////////////////////////////////////////////////////////////////////////
//
// 'Limit Example' RooStats tutorial macro #101
// author: Kyle Cranmer
// date June. 2009
//
// This tutorial shows an example of creating a simple
// model for a number counting experiment with uncertainty
// on both the background rate and signal efficeincy. We then
// use a Confidence Interval Calculator to set a limit on the signal.
//
//
/////////////////////////////////////////////////////////////////////////
#ifndef __CINT__
#include "RooGlobalFunc.h"
#endif
#include "RooProfileLL.h"
#include "RooAbsPdf.h"
#include "RooStats/HypoTestResult.h"
#include "RooRealVar.h"
#include "RooPlot.h"
#include "RooDataSet.h"
#include "RooTreeDataStore.h"
#include "TTree.h"
#include "TCanvas.h"
#include "TLine.h"
#include "TStopwatch.h"
#include "RooStats/ProfileLikelihoodCalculator.h"
#include "RooStats/MCMCCalculator.h"
#include "RooStats/UniformProposal.h"
#include "RooStats/FeldmanCousins.h"
#include "RooStats/NumberCountingPdfFactory.h"
#include "RooStats/ConfInterval.h"
#include "RooStats/PointSetInterval.h"
#include "RooStats/LikelihoodInterval.h"
#include "RooStats/LikelihoodIntervalPlot.h"
#include "RooStats/RooStatsUtils.h"
// use this order for safety on library loading
using namespace RooFit ;
using namespace RooStats ;
void rs101_limitexample()
{
/////////////////////////////////////////
// An example of setting a limit in a number counting experiment with uncertainty on background and signal
/////////////////////////////////////////
// to time the macro
TStopwatch t;
t.Start();
/////////////////////////////////////////
// The Model building stage
/////////////////////////////////////////
RooWorkspace* wspace = new RooWorkspace();
wspace->factory("Poisson::countingModel(obs[150,0,300], sum(s[50,0,120]*ratioSigEff[1.,0,2.],b[100,0,300]*ratioBkgEff[1.,0.,2.]))"); // counting model
wspace->factory("Gaussian::sigConstraint(ratioSigEff,1,0.05)"); // 5% signal efficiency uncertainty
wspace->factory("Gaussian::bkgConstraint(ratioBkgEff,1,0.1)"); // 10% background efficiency uncertainty
wspace->factory("PROD::modelWithConstraints(countingModel,sigConstraint,bkgConstraint)"); // product of terms
wspace->Print();
RooAbsPdf* modelWithConstraints = wspace->pdf("modelWithConstraints"); // get the model
RooRealVar* obs = wspace->var("obs"); // get the observable
RooRealVar* s = wspace->var("s"); // get the signal we care about
RooRealVar* b = wspace->var("b"); // get the background and set it to a constant. Uncertainty included in ratioBkgEff
b->setConstant();
RooRealVar* ratioSigEff = wspace->var("ratioSigEff"); // get uncertaint parameter to constrain
RooRealVar* ratioBkgEff = wspace->var("ratioBkgEff"); // get uncertaint parameter to constrain
RooArgSet constrainedParams(*ratioSigEff, *ratioBkgEff); // need to constrain these in the fit (should change default behavior)
// Create an example dataset with 160 observed events
obs->setVal(160.);
RooDataSet* data = new RooDataSet("exampleData", "exampleData", RooArgSet(*obs));
data->add(*obs);
RooArgSet all(*s, *ratioBkgEff, *ratioSigEff);
// not necessary
modelWithConstraints->fitTo(*data, RooFit::Constrain(RooArgSet(*ratioSigEff, *ratioBkgEff)));
// Now let's make some confidence intervals for s, our parameter of interest
RooArgSet paramOfInterest(*s);
// First, let's use a Calculator based on the Profile Likelihood Ratio
ProfileLikelihoodCalculator plc(*data, *modelWithConstraints, paramOfInterest);
plc.SetTestSize(.1);
ConfInterval* lrint = plc.GetInterval(); // that was easy.
// Second, use a Calculator based on the Feldman Cousins technique
FeldmanCousins fc;
fc.SetPdf(*modelWithConstraints);
fc.SetData(*data);
fc.SetParameters( paramOfInterest );
fc.UseAdaptiveSampling(true);
fc.FluctuateNumDataEntries(false); // number counting analysis: dataset always has 1 entry with N events observed
fc.SetNBins(100); // number of points to test per parameter
fc.SetTestSize(.1);
// fc.SaveBeltToFile(true); // optional
ConfInterval* fcint = NULL;
fcint = fc.GetInterval(); // that was easy.
// Third, use a Calculator based on Markov Chain monte carlo
UniformProposal up;
MCMCCalculator mc;
mc.SetPdf(*modelWithConstraints);
mc.SetData(*data);
mc.SetParameters(paramOfInterest);
mc.SetProposalFunction(up);
mc.SetNumIters(100000); // steps in the chain
mc.SetTestSize(.1); // 90% CL
mc.SetNumBins(50); // used in posterior histogram
mc.SetNumBurnInSteps(40); // ignore first steps in chain due to "burn in"
ConfInterval* mcmcint = NULL;
mcmcint = mc.GetInterval();
// Let's make a plot
TCanvas* dataCanvas = new TCanvas("dataCanvas");
dataCanvas->Divide(2,1);
dataCanvas->cd(1);
LikelihoodIntervalPlot plotInt((LikelihoodInterval*)lrint);
plotInt.SetTitle("Profile Likelihood Ratio and Posterior for S");
plotInt.Draw();
// draw posterior
TH1* posterior = ((MCMCInterval*)mcmcint)->GetPosteriorHist();
posterior->Scale(1/posterior->GetBinContent(posterior->GetMaximumBin())); // scale so highest bin has y=1.
posterior->Draw("same");
// Get Lower and Upper limits from Profile Calculator
cout << "Profile lower limit on s = " << ((LikelihoodInterval*) lrint)->LowerLimit(*s) << endl;
cout << "Profile upper limit on s = " << ((LikelihoodInterval*) lrint)->UpperLimit(*s) << endl;
// Get Lower and Upper limits from FeldmanCousins with profile construction
if (fcint != NULL) {
double fcul = ((PointSetInterval*) fcint)->UpperLimit(*s);
double fcll = ((PointSetInterval*) fcint)->LowerLimit(*s);
cout << "FC lower limit on s = " << fcll << endl;
cout << "FC upper limit on s = " << fcul << endl;
TLine* fcllLine = new TLine(fcll, 0, fcll, 1);
TLine* fculLine = new TLine(fcul, 0, fcul, 1);
fcllLine->SetLineColor(kRed);
fculLine->SetLineColor(kRed);
fcllLine->Draw("same");
fculLine->Draw("same");
dataCanvas->Update();
}
// Get Lower and Upper limits from MCMC
double mcul = ((MCMCInterval*) mcmcint)->UpperLimit(*s);
double mcll = ((MCMCInterval*) mcmcint)->LowerLimit(*s);
cout << "MCMC lower limit on s = " << mcll << endl;
cout << "MCMC upper limit on s = " << mcul << endl;
TLine* mcllLine = new TLine(mcll, 0, mcll, 1);
TLine* mculLine = new TLine(mcul, 0, mcul, 1);
mcllLine->SetLineColor(kMagenta);
mculLine->SetLineColor(kMagenta);
mcllLine->Draw("same");
mculLine->Draw("same");
dataCanvas->Update();
// 3-d plot of the parameter points
dataCanvas->cd(2);
// also plot the points in the markov chain
TTree& chain = ((RooTreeDataStore*) ((MCMCInterval*)mcmcint)->GetChain()->GetAsConstDataSet())->tree();
chain.SetMarkerStyle(6);
chain.SetMarkerColor(kRed);
chain.Draw("s:ratioSigEff:ratioBkgEff","w","box"); // 3-d box proporional to posterior
// the points used in the profile construction
TTree& parameterScan = ((RooTreeDataStore*) fc.GetPointsToScan()->store())->tree();
parameterScan.SetMarkerStyle(24);
parameterScan.Draw("s:ratioSigEff:ratioBkgEff","","same");
delete wspace;
delete lrint;
if (fcint != NULL) delete fcint;
delete data;
/// print timing info
t.Stop();
t.Print();
}
new attempt to fic tutorial
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@30497 27541ba8-7e3a-0410-8455-c3a389f83636
/////////////////////////////////////////////////////////////////////////
//
// 'Limit Example' RooStats tutorial macro #101
// author: Kyle Cranmer
// date June. 2009
//
// This tutorial shows an example of creating a simple
// model for a number counting experiment with uncertainty
// on both the background rate and signal efficeincy. We then
// use a Confidence Interval Calculator to set a limit on the signal.
//
//
/////////////////////////////////////////////////////////////////////////
#ifndef __CINT__
#include "RooGlobalFunc.h"
#endif
#include "RooProfileLL.h"
#include "RooAbsPdf.h"
#include "RooStats/HypoTestResult.h"
#include "RooRealVar.h"
#include "RooPlot.h"
#include "RooDataSet.h"
#include "RooTreeDataStore.h"
#include "TTree.h"
#include "TCanvas.h"
#include "TLine.h"
#include "TStopwatch.h"
#include "RooStats/ProfileLikelihoodCalculator.h"
#include "RooStats/MCMCCalculator.h"
#include "RooStats/UniformProposal.h"
#include "RooStats/FeldmanCousins.h"
#include "RooStats/NumberCountingPdfFactory.h"
#include "RooStats/ConfInterval.h"
#include "RooStats/PointSetInterval.h"
#include "RooStats/LikelihoodInterval.h"
#include "RooStats/LikelihoodIntervalPlot.h"
#include "RooStats/RooStatsUtils.h"
// use this order for safety on library loading
using namespace RooFit ;
using namespace RooStats ;
void rs101_limitexample()
{
/////////////////////////////////////////
// An example of setting a limit in a number counting experiment with uncertainty on background and signal
/////////////////////////////////////////
// to time the macro
TStopwatch t;
t.Start();
/////////////////////////////////////////
// The Model building stage
/////////////////////////////////////////
RooWorkspace* wspace = new RooWorkspace();
wspace->factory("Poisson::countingModel(obs[150,0,300], sum(s[50,0,120]*ratioSigEff[1.,0,2.],b[100,0,300]*ratioBkgEff[1.,0.,2.]))"); // counting model
wspace->factory("Gaussian::sigConstraint(ratioSigEff,1,0.05)"); // 5% signal efficiency uncertainty
wspace->factory("Gaussian::bkgConstraint(ratioBkgEff,1,0.1)"); // 10% background efficiency uncertainty
wspace->factory("PROD::modelWithConstraints(countingModel,sigConstraint,bkgConstraint)"); // product of terms
wspace->Print();
RooAbsPdf* modelWithConstraints = wspace->pdf("modelWithConstraints"); // get the model
RooRealVar* obs = wspace->var("obs"); // get the observable
RooRealVar* s = wspace->var("s"); // get the signal we care about
RooRealVar* b = wspace->var("b"); // get the background and set it to a constant. Uncertainty included in ratioBkgEff
b->setConstant();
RooRealVar* ratioSigEff = wspace->var("ratioSigEff"); // get uncertaint parameter to constrain
RooRealVar* ratioBkgEff = wspace->var("ratioBkgEff"); // get uncertaint parameter to constrain
RooArgSet constrainedParams(*ratioSigEff, *ratioBkgEff); // need to constrain these in the fit (should change default behavior)
// Create an example dataset with 160 observed events
obs->setVal(160.);
RooDataSet* data = new RooDataSet("exampleData", "exampleData", RooArgSet(*obs));
data->add(*obs);
RooArgSet all(*s, *ratioBkgEff, *ratioSigEff);
// not necessary
modelWithConstraints->fitTo(*data, RooFit::Constrain(RooArgSet(*ratioSigEff, *ratioBkgEff)));
// Now let's make some confidence intervals for s, our parameter of interest
RooArgSet paramOfInterest(*s);
// First, let's use a Calculator based on the Profile Likelihood Ratio
ProfileLikelihoodCalculator plc(*data, *modelWithConstraints, paramOfInterest);
plc.SetTestSize(.1);
ConfInterval* lrint = plc.GetInterval(); // that was easy.
// Second, use a Calculator based on the Feldman Cousins technique
FeldmanCousins fc;
fc.SetPdf(*modelWithConstraints);
fc.SetData(*data);
fc.SetParameters( paramOfInterest );
fc.UseAdaptiveSampling(true);
fc.FluctuateNumDataEntries(false); // number counting analysis: dataset always has 1 entry with N events observed
fc.SetNBins(100); // number of points to test per parameter
fc.SetTestSize(.1);
// fc.SaveBeltToFile(true); // optional
ConfInterval* fcint = NULL;
fcint = fc.GetInterval(); // that was easy.
// Third, use a Calculator based on Markov Chain monte carlo
UniformProposal up;
MCMCCalculator mc;
mc.SetPdf(*modelWithConstraints);
mc.SetData(*data);
mc.SetParameters(paramOfInterest);
mc.SetProposalFunction(up);
mc.SetNumIters(100000); // steps in the chain
mc.SetTestSize(.1); // 90% CL
mc.SetNumBins(50); // used in posterior histogram
mc.SetNumBurnInSteps(40); // ignore first steps in chain due to "burn in"
ConfInterval* mcmcint = NULL;
mcmcint = mc.GetInterval();
// Let's make a plot
TCanvas* dataCanvas = new TCanvas("dataCanvas");
dataCanvas->Divide(2,1);
dataCanvas->cd(1);
LikelihoodIntervalPlot plotInt((LikelihoodInterval*)lrint);
plotInt.SetTitle("Profile Likelihood Ratio and Posterior for S");
plotInt.Draw();
// draw posterior
TH1* posterior = ((MCMCInterval*)mcmcint)->GetPosteriorHist();
posterior->Scale(1/posterior->GetBinContent(posterior->GetMaximumBin())); // scale so highest bin has y=1.
posterior->Draw("same");
// Get Lower and Upper limits from Profile Calculator
cout << "Profile lower limit on s = " << ((LikelihoodInterval*) lrint)->LowerLimit(*s) << endl;
cout << "Profile upper limit on s = " << ((LikelihoodInterval*) lrint)->UpperLimit(*s) << endl;
// Get Lower and Upper limits from FeldmanCousins with profile construction
if (fcint != NULL) {
double fcul = ((PointSetInterval*) fcint)->UpperLimit(*s);
double fcll = ((PointSetInterval*) fcint)->LowerLimit(*s);
cout << "FC lower limit on s = " << fcll << endl;
cout << "FC upper limit on s = " << fcul << endl;
TLine* fcllLine = new TLine(fcll, 0, fcll, 1);
TLine* fculLine = new TLine(fcul, 0, fcul, 1);
fcllLine->SetLineColor(kRed);
fculLine->SetLineColor(kRed);
fcllLine->Draw("same");
fculLine->Draw("same");
dataCanvas->Update();
}
// Get Lower and Upper limits from MCMC
double mcul = ((MCMCInterval*) mcmcint)->UpperLimit(*s);
double mcll = ((MCMCInterval*) mcmcint)->LowerLimit(*s);
cout << "MCMC lower limit on s = " << mcll << endl;
cout << "MCMC upper limit on s = " << mcul << endl;
TLine* mcllLine = new TLine(mcll, 0, mcll, 1);
TLine* mculLine = new TLine(mcul, 0, mcul, 1);
mcllLine->SetLineColor(kMagenta);
mculLine->SetLineColor(kMagenta);
mcllLine->Draw("same");
mculLine->Draw("same");
dataCanvas->Update();
// 3-d plot of the parameter points
dataCanvas->cd(2);
// also plot the points in the markov chain
TTree& chain = ((RooTreeDataStore*) ((MCMCInterval*)mcmcint)->GetChainAsDataSet()->store())->tree();
chain.SetMarkerStyle(6);
chain.SetMarkerColor(kRed);
chain.Draw("s:ratioSigEff:ratioBkgEff","w","box"); // 3-d box proporional to posterior
// the points used in the profile construction
TTree& parameterScan = ((RooTreeDataStore*) fc.GetPointsToScan()->store())->tree();
parameterScan.SetMarkerStyle(24);
parameterScan.Draw("s:ratioSigEff:ratioBkgEff","","same");
delete wspace;
delete lrint;
if (fcint != NULL) delete fcint;
delete data;
/// print timing info
t.Stop();
t.Print();
}
// int main() {
// rs101_limitexample();
// }
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkDemandDrivenPipeline.cxx
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.
=========================================================================*/
#include "vtkDemandDrivenPipeline.h"
#include "vtkAlgorithm.h"
#include "vtkAlgorithmOutput.h"
#include "vtkCellData.h"
#include "vtkCommand.h"
#include "vtkDataObject.h"
#include "vtkDataSet.h"
#include "vtkGarbageCollector.h"
#include "vtkHierarchicalBoxDataSet.h"
#include "vtkHierarchicalDataSet.h"
#include "vtkInformation.h"
#include "vtkInformationIntegerKey.h"
#include "vtkInformationKeyVectorKey.h"
#include "vtkInformationRequestKey.h"
#include "vtkInformationUnsignedLongKey.h"
#include "vtkInformationVector.h"
#include "vtkInstantiator.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkImageData.h"
#include "vtkPolyData.h"
#include "vtkRectilinearGrid.h"
#include "vtkStructuredGrid.h"
#include "vtkStructuredPoints.h"
#include "vtkUnstructuredGrid.h"
#include <vtkstd/vector>
vtkCxxRevisionMacro(vtkDemandDrivenPipeline, "1.38");
vtkStandardNewMacro(vtkDemandDrivenPipeline);
vtkInformationKeyMacro(vtkDemandDrivenPipeline, DATA_NOT_GENERATED, Integer);
vtkInformationKeyMacro(vtkDemandDrivenPipeline, PIPELINE_MODIFIED_TIME, UnsignedLong);
vtkInformationKeyMacro(vtkDemandDrivenPipeline, RELEASE_DATA, Integer);
vtkInformationKeyMacro(vtkDemandDrivenPipeline, REQUEST_DATA, Request);
vtkInformationKeyMacro(vtkDemandDrivenPipeline, REQUEST_DATA_NOT_GENERATED, Integer);
vtkInformationKeyMacro(vtkDemandDrivenPipeline, REQUEST_DATA_OBJECT, Request);
vtkInformationKeyMacro(vtkDemandDrivenPipeline, REQUEST_INFORMATION, Request);
vtkInformationKeyMacro(vtkDemandDrivenPipeline, REQUEST_PIPELINE_MODIFIED_TIME, Request);
//----------------------------------------------------------------------------
vtkDemandDrivenPipeline::vtkDemandDrivenPipeline()
{
this->MTimeRequest = 0;
this->InfoRequest = 0;
this->DataObjectRequest = 0;
this->DataRequest = 0;
}
//----------------------------------------------------------------------------
vtkDemandDrivenPipeline::~vtkDemandDrivenPipeline()
{
if (this->MTimeRequest)
{
this->MTimeRequest->Delete();
}
if (this->InfoRequest)
{
this->InfoRequest->Delete();
}
if (this->DataObjectRequest)
{
this->DataObjectRequest->Delete();
}
if (this->DataRequest)
{
this->DataRequest->Delete();
}
}
//----------------------------------------------------------------------------
void vtkDemandDrivenPipeline::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "PipelineMTime: " << this->PipelineMTime << "\n";
}
unsigned long vtkDemandDrivenPipeline::ComputePipelineMTime(int forward, vtkInformation *request,
vtkInformationVector **inInfoVec)
{
// The pipeline's MTime starts with this algorithm's MTime.
// Invoke the request on the algorithm.
this->PipelineMTime = this->Algorithm->ComputePipelineMTime(request);
// We want the maximum PipelineMTime of all inputs.
if (forward)
{
for(int i=0; i < this->Algorithm->GetNumberOfInputPorts(); ++i)
{
for(int j=0; j < inInfoVec[i]->GetNumberOfInformationObjects(); ++j)
{
vtkInformation* info = inInfoVec[i]->GetInformationObject(j);
// call ComputePipelineMTime on the input
vtkExecutive* e;
int producerPort;
info->Get(vtkExecutive::PRODUCER(),e,producerPort);
if(e)
{
unsigned long mtime = e->ComputePipelineMTime(1,request,e->GetInputInformation());
if(mtime > this->PipelineMTime)
{
this->PipelineMTime = mtime;
}
}
}
}
}
return this->PipelineMTime;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::ProcessRequest(vtkInformation* request,
int forward,
vtkInformationVector** inInfoVec,
vtkInformationVector* outInfoVec)
{
// The algorithm should not invoke anything on the executive.
if(!this->CheckAlgorithm("ProcessRequest", request))
{
return 0;
}
if(this->Algorithm && request->Has(REQUEST_DATA_OBJECT()))
{
// if we are up to date then short circuit
if (this->PipelineMTime < this->DataObjectTime.GetMTime())
{
return 1;
}
// Update inputs first if they are out of date
if(forward && !this->ForwardUpstream(request))
{
return 0;
}
// Make sure our output data type is up-to-date.
int result = 1;
if(this->PipelineMTime > this->DataObjectTime.GetMTime())
{
// Request data type from the algorithm.
result = this->ExecuteDataObject(request,inInfoVec,outInfoVec);
// Make sure the data object exists for all output ports.
for(int i=0;
result && i < outInfoVec->GetNumberOfInformationObjects(); ++i)
{
vtkInformation* info = outInfoVec->GetInformationObject(i);
if(!info->Get(vtkDataObject::DATA_OBJECT()))
{
result = 0;
}
}
if(result)
{
// Data object is now up to date.
this->DataObjectTime.Modified();
}
}
return result;
}
if(this->Algorithm && request->Has(REQUEST_INFORMATION()))
{
// if we are up to date then short circuit
if (this->PipelineMTime < this->InformationTime.GetMTime())
{
return 1;
}
// Update inputs first.
if(forward && !this->ForwardUpstream(request))
{
return 0;
}
// Make sure our output information is up-to-date.
int result = 1;
if(this->PipelineMTime > this->InformationTime.GetMTime())
{
// Make sure input types are valid before algorithm does anything.
if(!this->InputCountIsValid(inInfoVec) ||
!this->InputTypeIsValid(inInfoVec))
{
return 0;
}
// Request information from the algorithm.
result = this->ExecuteInformation(request,inInfoVec,outInfoVec);
// Information is now up to date.
this->InformationTime.Modified();
}
return result;
}
if(this->Algorithm && request->Has(REQUEST_DATA()))
{
// Get the output port from which the request was made.
int outputPort = -1;
if(request->Has(FROM_OUTPUT_PORT()))
{
outputPort = request->Get(FROM_OUTPUT_PORT());
}
// Make sure our outputs are up-to-date.
int result = 1;
if(this->NeedToExecuteData(outputPort,inInfoVec,outInfoVec))
{
// Update inputs first.
if(forward && !this->ForwardUpstream(request))
{
return 0;
}
// Make sure inputs are valid before algorithm does anything.
if(!this->InputCountIsValid(inInfoVec) ||
!this->InputTypeIsValid(inInfoVec) ||
!this->InputFieldsAreValid(inInfoVec))
{
return 0;
}
// Request data from the algorithm.
result = this->ExecuteData(request,inInfoVec,outInfoVec);
// Data are now up to date.
this->DataTime.Modified();
// Some filters may modify themselves while processing
// REQUEST_DATA. Since we mark the filter execution end time
// here this behavior does not cause re-execution, so it should
// be allowed. The filter is now considered up-to-date.
// However, we must prevent the REQUEST_DATA_OBJECT and
// REQUEST_INFORMATION passes from re-running, so mark them
// up-do-date also. It is up to the filter to not modify itself
// in a way that would change the result of any pass.
this->InformationTime.Modified();
this->DataObjectTime.Modified();
}
return result;
}
// Let the superclass handle other requests.
return this->Superclass::ProcessRequest(request, forward,
inInfoVec, outInfoVec);
}
//----------------------------------------------------------------------------
void vtkDemandDrivenPipeline::ResetPipelineInformation(int,
vtkInformation* info)
{
info->Remove(RELEASE_DATA());
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::Update()
{
return this->Superclass::Update();
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::Update(int port)
{
if(!this->UpdateInformation())
{
return 0;
}
if(port >= -1 && port < this->Algorithm->GetNumberOfOutputPorts())
{
return this->UpdateData(port);
}
else
{
return 1;
}
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::UpdatePipelineMTime()
{
// The algorithm should not invoke anything on the executive.
if(!this->CheckAlgorithm("UpdatePipelineMTime", 0))
{
return 0;
}
this->ComputePipelineMTime(1,0,this->GetInputInformation());
return 1;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::UpdateDataObject()
{
// The algorithm should not invoke anything on the executive.
if(!this->CheckAlgorithm("UpdateDataObject", 0))
{
return 0;
}
// Update the pipeline mtime first.
if(!this->UpdatePipelineMTime())
{
return 0;
}
// Setup the request for data object creation.
if (!this->DataObjectRequest)
{
this->DataObjectRequest = vtkInformation::New();
this->DataObjectRequest->Set(REQUEST_DATA_OBJECT());
// The request is forwarded upstream through the pipeline.
this->DataObjectRequest->Set(vtkExecutive::FORWARD_DIRECTION(), vtkExecutive::RequestUpstream);
// Algorithms process this request after it is forwarded.
this->DataObjectRequest->Set(vtkExecutive::ALGORITHM_AFTER_FORWARD(), 1);
}
// Send the request.
return this->ProcessRequest(this->DataObjectRequest,1,this->GetInputInformation(),
this->GetOutputInformation());
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::UpdateInformation()
{
// The algorithm should not invoke anything on the executive.
if(!this->CheckAlgorithm("UpdateInformation", 0))
{
return 0;
}
// Do the data-object creation pass before the information pass.
if(!this->UpdateDataObject())
{
return 0;
}
// Setup the request for information.
if (!this->InfoRequest)
{
this->InfoRequest = vtkInformation::New();
this->InfoRequest->Set(REQUEST_INFORMATION());
// The request is forwarded upstream through the pipeline.
this->InfoRequest->Set(vtkExecutive::FORWARD_DIRECTION(), vtkExecutive::RequestUpstream);
// Algorithms process this request after it is forwarded.
this->InfoRequest->Set(vtkExecutive::ALGORITHM_AFTER_FORWARD(), 1);
}
// Send the request.
return this->ProcessRequest(this->InfoRequest,1,this->GetInputInformation(),
this->GetOutputInformation());
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::UpdateData(int outputPort)
{
// The algorithm should not invoke anything on the executive.
if(!this->CheckAlgorithm("UpdateData", 0))
{
return 0;
}
// Range check.
if(outputPort < -1 ||
outputPort >= this->Algorithm->GetNumberOfOutputPorts())
{
vtkErrorMacro("UpdateData given output port index "
<< outputPort << " on an algorithm with "
<< this->Algorithm->GetNumberOfOutputPorts()
<< " output ports.");
return 0;
}
// Setup the request for data.
if (!this->DataRequest)
{
this->DataRequest = vtkInformation::New();
this->DataRequest->Set(REQUEST_DATA());
// The request is forwarded upstream through the pipeline.
this->DataRequest->Set(vtkExecutive::FORWARD_DIRECTION(), vtkExecutive::RequestUpstream);
// Algorithms process this request after it is forwarded.
this->DataRequest->Set(vtkExecutive::ALGORITHM_AFTER_FORWARD(), 1);
}
// Send the request.
this->DataRequest->Set(FROM_OUTPUT_PORT(), outputPort);
return this->ProcessRequest(this->DataRequest,1,this->GetInputInformation(),
this->GetOutputInformation());
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::ExecuteDataObject(vtkInformation* request,
vtkInformationVector** inInfo,
vtkInformationVector* outInfo)
{
// Invoke the request on the algorithm.
int result = this->CallAlgorithm(request, vtkExecutive::RequestDownstream,
inInfo, outInfo);
// Make sure a valid data object exists for all output ports.
for(int i=0; result && i < this->Algorithm->GetNumberOfOutputPorts(); ++i)
{
result = this->CheckDataObject(i, outInfo);
}
return result;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::ExecuteInformation
(vtkInformation* request,
vtkInformationVector** inInfoVec,
vtkInformationVector* outInfoVec)
{
// Give each output data object a chance to set default values in
// its pipeline information. Provide the first input's information
// to each output.
vtkInformation* inInfo = 0;
if(this->GetNumberOfInputPorts() > 0)
{
inInfo = inInfoVec[0]->GetInformationObject(0);
}
for(int i=0; i < this->Algorithm->GetNumberOfOutputPorts(); ++i)
{
vtkInformation* outInfo = outInfoVec->GetInformationObject(i);
if(vtkDataObject* outData = outInfo->Get(vtkDataObject::DATA_OBJECT()))
{
outData->CopyInformationToPipeline(request, inInfo);
}
}
// Invoke the request on the algorithm.
return this->CallAlgorithm(request, vtkExecutive::RequestDownstream,
inInfoVec, outInfoVec);
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::ExecuteData(vtkInformation* request,
vtkInformationVector** inInfo,
vtkInformationVector* outInfo)
{
this->ExecuteDataStart(request, inInfo, outInfo);
// Invoke the request on the algorithm.
int result = this->CallAlgorithm(request, vtkExecutive::RequestDownstream,
inInfo, outInfo);
this->ExecuteDataEnd(request, inInfo, outInfo);
return result;
}
//----------------------------------------------------------------------------
void vtkDemandDrivenPipeline::ExecuteDataStart(vtkInformation* request,
vtkInformationVector** inInfo,
vtkInformationVector* outputs)
{
// Ask the algorithm to mark outputs that it will not generate.
request->Remove(REQUEST_DATA());
request->Set(REQUEST_DATA_NOT_GENERATED(), 1);
this->CallAlgorithm(request, vtkExecutive::RequestDownstream,
inInfo, outputs);
request->Remove(REQUEST_DATA_NOT_GENERATED());
request->Set(REQUEST_DATA());
// Prepare outputs that will be generated to receive new data.
for(int i=0; i < outputs->GetNumberOfInformationObjects(); ++i)
{
vtkInformation* outInfo = outputs->GetInformationObject(i);
vtkDataObject* data = outInfo->Get(vtkDataObject::DATA_OBJECT());
if(data && !outInfo->Get(DATA_NOT_GENERATED()))
{
data->PrepareForNewData();
data->CopyInformationFromPipeline(request);
}
}
// Tell observers the algorithm is about to execute.
this->Algorithm->InvokeEvent(vtkCommand::StartEvent,NULL);
// The algorithm has not yet made any progress.
this->Algorithm->SetAbortExecute(0);
this->Algorithm->UpdateProgress(0.0);
}
//----------------------------------------------------------------------------
void vtkDemandDrivenPipeline::ExecuteDataEnd(vtkInformation* request,
vtkInformationVector** inInfoVec,
vtkInformationVector* outputs)
{
// The algorithm has either finished or aborted.
if(!this->Algorithm->GetAbortExecute())
{
this->Algorithm->UpdateProgress(1.0);
}
// Tell observers the algorithm is done executing.
this->Algorithm->InvokeEvent(vtkCommand::EndEvent,NULL);
// Tell outputs they have been generated.
this->MarkOutputsGenerated(request,inInfoVec,outputs);
// Remove any not-generated mark.
int i, j;
for(i=0; i < outputs->GetNumberOfInformationObjects(); ++i)
{
vtkInformation* outInfo = outputs->GetInformationObject(i);
outInfo->Remove(DATA_NOT_GENERATED());
}
// Release input data if requested.
for(i=0; i < this->Algorithm->GetNumberOfInputPorts(); ++i)
{
for(j=0; j < inInfoVec[i]->GetNumberOfInformationObjects(); ++j)
{
vtkInformation* inInfo = inInfoVec[i]->GetInformationObject(j);
vtkDataObject* dataObject = inInfo->Get(vtkDataObject::DATA_OBJECT());
if(dataObject && (dataObject->GetGlobalReleaseDataFlag() ||
inInfo->Get(RELEASE_DATA())))
{
dataObject->ReleaseData();
}
}
}
}
//----------------------------------------------------------------------------
void vtkDemandDrivenPipeline::MarkOutputsGenerated
(vtkInformation*,
vtkInformationVector** /* inInfoVec */,
vtkInformationVector* outputs)
{
// Tell all generated outputs that they have been generated.
for(int i=0; i < outputs->GetNumberOfInformationObjects(); ++i)
{
vtkInformation* outInfo = outputs->GetInformationObject(i);
vtkDataObject* data = outInfo->Get(vtkDataObject::DATA_OBJECT());
if(data && !outInfo->Get(DATA_NOT_GENERATED()))
{
data->DataHasBeenGenerated();
}
}
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::CheckDataObject(int port,
vtkInformationVector* outInfoVec)
{
// Check that the given output port has a valid data object.
vtkInformation* outInfo = outInfoVec->GetInformationObject(port);
vtkDataObject* data = outInfo->Get(vtkDataObject::DATA_OBJECT());
vtkInformation* portInfo = this->Algorithm->GetOutputPortInformation(port);
if(const char* dt = portInfo->Get(vtkDataObject::DATA_TYPE_NAME()))
{
// The output port specifies a data type. Make sure the data
// object exists and is of the right type.
if(!data || !data->IsA(dt))
{
// Try to create an instance of the correct type.
data = this->NewDataObject(dt);
this->SetOutputData(port, data, outInfo);
if(data)
{
data->FastDelete();
}
}
if(!data)
{
// The algorithm has a bug and did not create the data object.
vtkErrorMacro("Algorithm " << this->Algorithm->GetClassName() << "("
<< this->Algorithm
<< ") did not create output for port " << port
<< " when asked by REQUEST_DATA_OBJECT and does not"
<< " specify a concrete DATA_TYPE_NAME.");
return 0;
}
return 1;
}
else if(data)
{
// The algorithm did not specify its output data type. Just assume
// the data object is of the correct type.
return 1;
}
else
{
// The algorithm did not specify its output data type and no
// object exists.
vtkErrorMacro("Algorithm " << this->Algorithm->GetClassName() << "("
<< this->Algorithm
<< ") did not create output for port " << port
<< " when asked by REQUEST_DATA_OBJECT and does not"
<< " specify any DATA_TYPE_NAME.");
return 0;
}
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputCountIsValid
(vtkInformationVector **inInfoVec)
{
// Check the number of connections for each port.
int result = 1;
for(int p=0; p < this->Algorithm->GetNumberOfInputPorts(); ++p)
{
if(!this->InputCountIsValid(p,inInfoVec))
{
result = 0;
}
}
return result;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputCountIsValid
(int port, vtkInformationVector **inInfoVec)
{
// Get the number of connections for this port.
if (!inInfoVec[port])
{
return 0;
}
int connections = inInfoVec[port]->GetNumberOfInformationObjects();
// If the input port is optional, there may be less than one connection.
if(!this->InputIsOptional(port) && (connections < 1))
{
vtkErrorMacro("Input port " << port << " of algorithm "
<< this->Algorithm->GetClassName()
<< "(" << this->Algorithm << ") has " << connections
<< " connections but is not optional.");
return 0;
}
// If the input port is repeatable, there may be more than one connection.
if(!this->InputIsRepeatable(port) && (connections > 1))
{
vtkErrorMacro("Input port " << port << " of algorithm "
<< this->Algorithm->GetClassName()
<< "(" << this->Algorithm << ") has " << connections
<< " connections but is not repeatable.");
return 0;
}
return 1;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputTypeIsValid
(vtkInformationVector **inInfoVec)
{
// Check the connection types for each port.
int result = 1;
for(int p=0; p < this->Algorithm->GetNumberOfInputPorts(); ++p)
{
if(!this->InputTypeIsValid(p, inInfoVec))
{
result = 0;
}
}
return result;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputTypeIsValid
(int port, vtkInformationVector **inInfoVec)
{
// Check the type of each connection on this port.
int result = 1;
if (!inInfoVec[port])
{
return 0;
}
for(int i=0; i < inInfoVec[port]->GetNumberOfInformationObjects(); ++i)
{
if(!this->InputTypeIsValid(port, i, inInfoVec))
{
result = 0;
}
}
return result;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputTypeIsValid
(int port, int index, vtkInformationVector **inInfoVec)
{
if (!inInfoVec[port])
{
return 0;
}
vtkInformation* info = this->Algorithm->GetInputPortInformation(port);
vtkDataObject* input = this->GetInputData(port, index, inInfoVec);
// Enforce required type, if any.
if(const char* dt = info->Get(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE()))
{
// The input cannot be NULL unless the port is optional.
if(!input && !info->Get(vtkAlgorithm::INPUT_IS_OPTIONAL()))
{
vtkErrorMacro("Input for connection index " << index
<< " on input port index " << port
<< " for algorithm " << this->Algorithm->GetClassName()
<< "(" << this->Algorithm << ") is NULL, but a " << dt
<< " is required.");
return 0;
}
// The input must be of required type or NULL.
if(input && !input->IsA(dt))
{
vtkErrorMacro("Input for connection index " << index
<< " on input port index " << port
<< " for algorithm " << this->Algorithm->GetClassName()
<< "(" << this->Algorithm << ") is of type "
<< input->GetClassName() << ", but a " << dt
<< " is required.");
return 0;
}
}
return 1;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputFieldsAreValid
(vtkInformationVector **inInfoVec)
{
// Check the fields for each port.
int result = 1;
for(int p=0; p < this->Algorithm->GetNumberOfInputPorts(); ++p)
{
if(!this->InputFieldsAreValid(p,inInfoVec))
{
result = 0;
}
}
return result;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputFieldsAreValid
(int port, vtkInformationVector **inInfoVec)
{
// Check the fields for each connection on this port.
if (!inInfoVec[port])
{
return 0;
}
int result = 1;
for(int i=0; i < inInfoVec[port]->GetNumberOfInformationObjects(); ++i)
{
if(!this->InputFieldsAreValid(port, i, inInfoVec))
{
result = 0;
}
}
return result;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputFieldsAreValid
(int port, int index, vtkInformationVector **inInfoVec)
{
vtkInformation* info = this->Algorithm->GetInputPortInformation(port);
vtkInformationVector* fields =
info->Get(vtkAlgorithm::INPUT_REQUIRED_FIELDS());
// If there are no required fields, there is nothing to check.
if(!fields)
{
return 1;
}
vtkDataObject* input = this->GetInputData(port, index, inInfoVec);
// NULL inputs do not have to have the proper fields.
if(!input)
{
return 1;
}
// Check availability of each required field.
int result = 1;
for(int i=0; i < fields->GetNumberOfInformationObjects(); ++i)
{
vtkInformation* field = fields->GetInformationObject(i);
// Decide which kinds of fields to check.
int checkPoints = 1;
int checkCells = 1;
int checkFields = 1;
if(field->Has(vtkDataObject::FIELD_ASSOCIATION()))
{
switch(field->Get(vtkDataObject::FIELD_ASSOCIATION()))
{
case vtkDataObject::FIELD_ASSOCIATION_POINTS:
checkCells = 0; checkFields = 0; break;
case vtkDataObject::FIELD_ASSOCIATION_CELLS:
checkPoints = 0; checkFields = 0; break;
case vtkDataObject::FIELD_ASSOCIATION_NONE:
checkPoints = 0; checkCells = 0; break;
}
}
// Point and cell data arrays only exist in vtkDataSet instances.
vtkDataSet* dataSet = vtkDataSet::SafeDownCast(input);
// Look for a point data, cell data, or field data array matching
// the requirements.
if(!(checkPoints && dataSet && dataSet->GetPointData() &&
this->DataSetAttributeExists(dataSet->GetPointData(), field)) &&
!(checkCells && dataSet && dataSet->GetCellData() &&
this->DataSetAttributeExists(dataSet->GetCellData(), field)) &&
!(checkFields && input && input->GetFieldData() &&
this->FieldArrayExists(input->GetFieldData(), field)))
{
/* TODO: Construct more descriptive error message from field
requirements. */
vtkErrorMacro("Required field not found in input.");
result = 0;
}
}
return result;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::DataSetAttributeExists(vtkDataSetAttributes* dsa,
vtkInformation* field)
{
if(field->Has(vtkDataObject::FIELD_ATTRIBUTE_TYPE()))
{
// A specific attribute must match the requirements.
int attrType = field->Get(vtkDataObject::FIELD_ATTRIBUTE_TYPE());
return this->ArrayIsValid(dsa->GetAttribute(attrType), field);
}
else
{
// Search for an array matching the requirements.
return this->FieldArrayExists(dsa, field);
}
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::FieldArrayExists(vtkFieldData* data,
vtkInformation* field)
{
// Search the field data instance for an array matching the requirements.
for(int a=0; a < data->GetNumberOfArrays(); ++a)
{
if(this->ArrayIsValid(data->GetArray(a), field))
{
return 1;
}
}
return 0;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::ArrayIsValid(vtkDataArray* array,
vtkInformation* field)
{
// Enforce existence of the array.
if(!array)
{
return 0;
}
// Enforce name of the array. This should really only be used for
// field data (not point or cell data).
if(const char* name = field->Get(vtkDataObject::FIELD_NAME()))
{
if(!array->GetName() || (strcmp(name, array->GetName()) != 0))
{
return 0;
}
}
// Enforce component type for the array.
if(field->Has(vtkDataObject::FIELD_ARRAY_TYPE()))
{
int arrayType = field->Get(vtkDataObject::FIELD_ARRAY_TYPE());
if(array->GetDataType() != arrayType)
{
return 0;
}
}
// Enforce number of components for the array.
if(field->Has(vtkDataObject::FIELD_NUMBER_OF_COMPONENTS()))
{
int arrayNumComponents =
field->Get(vtkDataObject::FIELD_NUMBER_OF_COMPONENTS());
if(array->GetNumberOfComponents() != arrayNumComponents)
{
return 0;
}
}
// Enforce number of tuples. This should really only be used for
// field data (not point or cell data).
if(field->Has(vtkDataObject::FIELD_NUMBER_OF_TUPLES()))
{
int arrayNumTuples = field->Get(vtkDataObject::FIELD_NUMBER_OF_TUPLES());
if(array->GetNumberOfTuples() != arrayNumTuples)
{
return 0;
}
}
return 1;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputIsOptional(int port)
{
if(vtkInformation* info = this->Algorithm->GetInputPortInformation(port))
{
return info->Get(vtkAlgorithm::INPUT_IS_OPTIONAL());
}
return 0;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputIsRepeatable(int port)
{
if(vtkInformation* info = this->Algorithm->GetInputPortInformation(port))
{
return info->Get(vtkAlgorithm::INPUT_IS_REPEATABLE());
}
return 0;
}
//----------------------------------------------------------------------------
vtkDataObject* vtkDemandDrivenPipeline::NewDataObject(const char* type)
{
// Check for some standard types and then try the instantiator.
if(strcmp(type, "vtkImageData") == 0)
{
return vtkImageData::New();
}
else if(strcmp(type, "vtkPolyData") == 0)
{
return vtkPolyData::New();
}
else if(strcmp(type, "vtkRectilinearGrid") == 0)
{
return vtkRectilinearGrid::New();
}
else if(strcmp(type, "vtkStructuredGrid") == 0)
{
return vtkStructuredGrid::New();
}
else if(strcmp(type, "vtkStructuredPoints") == 0)
{
return vtkStructuredPoints::New();
}
else if(strcmp(type, "vtkUnstructuredGrid") == 0)
{
return vtkUnstructuredGrid::New();
}
else if(strcmp(type, "vtkHierarchicalDataSet") == 0)
{
return vtkHierarchicalDataSet::New();
}
else if(strcmp(type, "vtkHierarchicalBoxDataSet") == 0)
{
return vtkHierarchicalBoxDataSet::New();
}
else if(vtkObject* obj = vtkInstantiator::CreateInstance(type))
{
vtkDataObject* data = vtkDataObject::SafeDownCast(obj);
if(!data)
{
obj->Delete();
}
return data;
}
else
{
return 0;
}
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline
::NeedToExecuteData(int outputPort,
vtkInformationVector** inInfoVec,
vtkInformationVector* outInfoVec)
{
// If the filter parameters or input have been modified since the
// last execution then we must execute. This is a shortcut for most
// filters since all outputs will have the same UpdateTime. This
// also handles the case in which there are no outputs.
if(this->PipelineMTime > this->DataTime.GetMTime())
{
return 1;
}
if(outputPort >= 0)
{
// If the output on the port making the request is out-of-date
// then we must execute.
vtkInformation* info = outInfoVec->GetInformationObject(outputPort);
vtkDataObject* data = info->Get(vtkDataObject::DATA_OBJECT());
if(!data || this->PipelineMTime > data->GetUpdateTime())
{
return 1;
}
}
else
{
// No port is specified. Check all ports.
for(int i=0; i < this->Algorithm->GetNumberOfOutputPorts(); ++i)
{
if(this->NeedToExecuteData(i,inInfoVec,outInfoVec))
{
return 1;
}
}
}
// We do not need to execute.
return 0;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::SetReleaseDataFlag(int port, int n)
{
if(!this->OutputPortIndexInRange(port, "set release data flag on"))
{
return 0;
}
vtkInformation* info = this->GetOutputInformation(port);
if(this->GetReleaseDataFlag(port) != n)
{
info->Set(RELEASE_DATA(), n);
return 1;
}
return 0;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::GetReleaseDataFlag(int port)
{
if(!this->OutputPortIndexInRange(port, "get release data flag from"))
{
return 0;
}
vtkInformation* info = this->GetOutputInformation(port);
if(!info->Has(RELEASE_DATA()))
{
info->Set(RELEASE_DATA(), 0);
}
return info->Get(RELEASE_DATA());
}
BUG:Added vtkHyperOctree to NewDataObject, it should fix all the HyperOctree tests that fail, such as linux static, thanks Berk
/*=========================================================================
Program: Visualization Toolkit
Module: vtkDemandDrivenPipeline.cxx
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.
=========================================================================*/
#include "vtkDemandDrivenPipeline.h"
#include "vtkAlgorithm.h"
#include "vtkAlgorithmOutput.h"
#include "vtkCellData.h"
#include "vtkCommand.h"
#include "vtkDataObject.h"
#include "vtkDataSet.h"
#include "vtkGarbageCollector.h"
#include "vtkHierarchicalBoxDataSet.h"
#include "vtkHierarchicalDataSet.h"
#include "vtkInformation.h"
#include "vtkInformationIntegerKey.h"
#include "vtkInformationKeyVectorKey.h"
#include "vtkInformationRequestKey.h"
#include "vtkInformationUnsignedLongKey.h"
#include "vtkInformationVector.h"
#include "vtkInstantiator.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkImageData.h"
#include "vtkPolyData.h"
#include "vtkRectilinearGrid.h"
#include "vtkStructuredGrid.h"
#include "vtkStructuredPoints.h"
#include "vtkUnstructuredGrid.h"
#include "vtkHyperOctree.h"
#include <vtkstd/vector>
vtkCxxRevisionMacro(vtkDemandDrivenPipeline, "1.39");
vtkStandardNewMacro(vtkDemandDrivenPipeline);
vtkInformationKeyMacro(vtkDemandDrivenPipeline, DATA_NOT_GENERATED, Integer);
vtkInformationKeyMacro(vtkDemandDrivenPipeline, PIPELINE_MODIFIED_TIME, UnsignedLong);
vtkInformationKeyMacro(vtkDemandDrivenPipeline, RELEASE_DATA, Integer);
vtkInformationKeyMacro(vtkDemandDrivenPipeline, REQUEST_DATA, Request);
vtkInformationKeyMacro(vtkDemandDrivenPipeline, REQUEST_DATA_NOT_GENERATED, Integer);
vtkInformationKeyMacro(vtkDemandDrivenPipeline, REQUEST_DATA_OBJECT, Request);
vtkInformationKeyMacro(vtkDemandDrivenPipeline, REQUEST_INFORMATION, Request);
vtkInformationKeyMacro(vtkDemandDrivenPipeline, REQUEST_PIPELINE_MODIFIED_TIME, Request);
//----------------------------------------------------------------------------
vtkDemandDrivenPipeline::vtkDemandDrivenPipeline()
{
this->MTimeRequest = 0;
this->InfoRequest = 0;
this->DataObjectRequest = 0;
this->DataRequest = 0;
}
//----------------------------------------------------------------------------
vtkDemandDrivenPipeline::~vtkDemandDrivenPipeline()
{
if (this->MTimeRequest)
{
this->MTimeRequest->Delete();
}
if (this->InfoRequest)
{
this->InfoRequest->Delete();
}
if (this->DataObjectRequest)
{
this->DataObjectRequest->Delete();
}
if (this->DataRequest)
{
this->DataRequest->Delete();
}
}
//----------------------------------------------------------------------------
void vtkDemandDrivenPipeline::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "PipelineMTime: " << this->PipelineMTime << "\n";
}
unsigned long vtkDemandDrivenPipeline::ComputePipelineMTime(int forward, vtkInformation *request,
vtkInformationVector **inInfoVec)
{
// The pipeline's MTime starts with this algorithm's MTime.
// Invoke the request on the algorithm.
this->PipelineMTime = this->Algorithm->ComputePipelineMTime(request);
// We want the maximum PipelineMTime of all inputs.
if (forward)
{
for(int i=0; i < this->Algorithm->GetNumberOfInputPorts(); ++i)
{
for(int j=0; j < inInfoVec[i]->GetNumberOfInformationObjects(); ++j)
{
vtkInformation* info = inInfoVec[i]->GetInformationObject(j);
// call ComputePipelineMTime on the input
vtkExecutive* e;
int producerPort;
info->Get(vtkExecutive::PRODUCER(),e,producerPort);
if(e)
{
unsigned long mtime = e->ComputePipelineMTime(1,request,e->GetInputInformation());
if(mtime > this->PipelineMTime)
{
this->PipelineMTime = mtime;
}
}
}
}
}
return this->PipelineMTime;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::ProcessRequest(vtkInformation* request,
int forward,
vtkInformationVector** inInfoVec,
vtkInformationVector* outInfoVec)
{
// The algorithm should not invoke anything on the executive.
if(!this->CheckAlgorithm("ProcessRequest", request))
{
return 0;
}
if(this->Algorithm && request->Has(REQUEST_DATA_OBJECT()))
{
// if we are up to date then short circuit
if (this->PipelineMTime < this->DataObjectTime.GetMTime())
{
return 1;
}
// Update inputs first if they are out of date
if(forward && !this->ForwardUpstream(request))
{
return 0;
}
// Make sure our output data type is up-to-date.
int result = 1;
if(this->PipelineMTime > this->DataObjectTime.GetMTime())
{
// Request data type from the algorithm.
result = this->ExecuteDataObject(request,inInfoVec,outInfoVec);
// Make sure the data object exists for all output ports.
for(int i=0;
result && i < outInfoVec->GetNumberOfInformationObjects(); ++i)
{
vtkInformation* info = outInfoVec->GetInformationObject(i);
if(!info->Get(vtkDataObject::DATA_OBJECT()))
{
result = 0;
}
}
if(result)
{
// Data object is now up to date.
this->DataObjectTime.Modified();
}
}
return result;
}
if(this->Algorithm && request->Has(REQUEST_INFORMATION()))
{
// if we are up to date then short circuit
if (this->PipelineMTime < this->InformationTime.GetMTime())
{
return 1;
}
// Update inputs first.
if(forward && !this->ForwardUpstream(request))
{
return 0;
}
// Make sure our output information is up-to-date.
int result = 1;
if(this->PipelineMTime > this->InformationTime.GetMTime())
{
// Make sure input types are valid before algorithm does anything.
if(!this->InputCountIsValid(inInfoVec) ||
!this->InputTypeIsValid(inInfoVec))
{
return 0;
}
// Request information from the algorithm.
result = this->ExecuteInformation(request,inInfoVec,outInfoVec);
// Information is now up to date.
this->InformationTime.Modified();
}
return result;
}
if(this->Algorithm && request->Has(REQUEST_DATA()))
{
// Get the output port from which the request was made.
int outputPort = -1;
if(request->Has(FROM_OUTPUT_PORT()))
{
outputPort = request->Get(FROM_OUTPUT_PORT());
}
// Make sure our outputs are up-to-date.
int result = 1;
if(this->NeedToExecuteData(outputPort,inInfoVec,outInfoVec))
{
// Update inputs first.
if(forward && !this->ForwardUpstream(request))
{
return 0;
}
// Make sure inputs are valid before algorithm does anything.
if(!this->InputCountIsValid(inInfoVec) ||
!this->InputTypeIsValid(inInfoVec) ||
!this->InputFieldsAreValid(inInfoVec))
{
return 0;
}
// Request data from the algorithm.
result = this->ExecuteData(request,inInfoVec,outInfoVec);
// Data are now up to date.
this->DataTime.Modified();
// Some filters may modify themselves while processing
// REQUEST_DATA. Since we mark the filter execution end time
// here this behavior does not cause re-execution, so it should
// be allowed. The filter is now considered up-to-date.
// However, we must prevent the REQUEST_DATA_OBJECT and
// REQUEST_INFORMATION passes from re-running, so mark them
// up-do-date also. It is up to the filter to not modify itself
// in a way that would change the result of any pass.
this->InformationTime.Modified();
this->DataObjectTime.Modified();
}
return result;
}
// Let the superclass handle other requests.
return this->Superclass::ProcessRequest(request, forward,
inInfoVec, outInfoVec);
}
//----------------------------------------------------------------------------
void vtkDemandDrivenPipeline::ResetPipelineInformation(int,
vtkInformation* info)
{
info->Remove(RELEASE_DATA());
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::Update()
{
return this->Superclass::Update();
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::Update(int port)
{
if(!this->UpdateInformation())
{
return 0;
}
if(port >= -1 && port < this->Algorithm->GetNumberOfOutputPorts())
{
return this->UpdateData(port);
}
else
{
return 1;
}
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::UpdatePipelineMTime()
{
// The algorithm should not invoke anything on the executive.
if(!this->CheckAlgorithm("UpdatePipelineMTime", 0))
{
return 0;
}
this->ComputePipelineMTime(1,0,this->GetInputInformation());
return 1;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::UpdateDataObject()
{
// The algorithm should not invoke anything on the executive.
if(!this->CheckAlgorithm("UpdateDataObject", 0))
{
return 0;
}
// Update the pipeline mtime first.
if(!this->UpdatePipelineMTime())
{
return 0;
}
// Setup the request for data object creation.
if (!this->DataObjectRequest)
{
this->DataObjectRequest = vtkInformation::New();
this->DataObjectRequest->Set(REQUEST_DATA_OBJECT());
// The request is forwarded upstream through the pipeline.
this->DataObjectRequest->Set(vtkExecutive::FORWARD_DIRECTION(), vtkExecutive::RequestUpstream);
// Algorithms process this request after it is forwarded.
this->DataObjectRequest->Set(vtkExecutive::ALGORITHM_AFTER_FORWARD(), 1);
}
// Send the request.
return this->ProcessRequest(this->DataObjectRequest,1,this->GetInputInformation(),
this->GetOutputInformation());
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::UpdateInformation()
{
// The algorithm should not invoke anything on the executive.
if(!this->CheckAlgorithm("UpdateInformation", 0))
{
return 0;
}
// Do the data-object creation pass before the information pass.
if(!this->UpdateDataObject())
{
return 0;
}
// Setup the request for information.
if (!this->InfoRequest)
{
this->InfoRequest = vtkInformation::New();
this->InfoRequest->Set(REQUEST_INFORMATION());
// The request is forwarded upstream through the pipeline.
this->InfoRequest->Set(vtkExecutive::FORWARD_DIRECTION(), vtkExecutive::RequestUpstream);
// Algorithms process this request after it is forwarded.
this->InfoRequest->Set(vtkExecutive::ALGORITHM_AFTER_FORWARD(), 1);
}
// Send the request.
return this->ProcessRequest(this->InfoRequest,1,this->GetInputInformation(),
this->GetOutputInformation());
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::UpdateData(int outputPort)
{
// The algorithm should not invoke anything on the executive.
if(!this->CheckAlgorithm("UpdateData", 0))
{
return 0;
}
// Range check.
if(outputPort < -1 ||
outputPort >= this->Algorithm->GetNumberOfOutputPorts())
{
vtkErrorMacro("UpdateData given output port index "
<< outputPort << " on an algorithm with "
<< this->Algorithm->GetNumberOfOutputPorts()
<< " output ports.");
return 0;
}
// Setup the request for data.
if (!this->DataRequest)
{
this->DataRequest = vtkInformation::New();
this->DataRequest->Set(REQUEST_DATA());
// The request is forwarded upstream through the pipeline.
this->DataRequest->Set(vtkExecutive::FORWARD_DIRECTION(), vtkExecutive::RequestUpstream);
// Algorithms process this request after it is forwarded.
this->DataRequest->Set(vtkExecutive::ALGORITHM_AFTER_FORWARD(), 1);
}
// Send the request.
this->DataRequest->Set(FROM_OUTPUT_PORT(), outputPort);
return this->ProcessRequest(this->DataRequest,1,this->GetInputInformation(),
this->GetOutputInformation());
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::ExecuteDataObject(vtkInformation* request,
vtkInformationVector** inInfo,
vtkInformationVector* outInfo)
{
// Invoke the request on the algorithm.
int result = this->CallAlgorithm(request, vtkExecutive::RequestDownstream,
inInfo, outInfo);
// Make sure a valid data object exists for all output ports.
for(int i=0; result && i < this->Algorithm->GetNumberOfOutputPorts(); ++i)
{
result = this->CheckDataObject(i, outInfo);
}
return result;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::ExecuteInformation
(vtkInformation* request,
vtkInformationVector** inInfoVec,
vtkInformationVector* outInfoVec)
{
// Give each output data object a chance to set default values in
// its pipeline information. Provide the first input's information
// to each output.
vtkInformation* inInfo = 0;
if(this->GetNumberOfInputPorts() > 0)
{
inInfo = inInfoVec[0]->GetInformationObject(0);
}
for(int i=0; i < this->Algorithm->GetNumberOfOutputPorts(); ++i)
{
vtkInformation* outInfo = outInfoVec->GetInformationObject(i);
if(vtkDataObject* outData = outInfo->Get(vtkDataObject::DATA_OBJECT()))
{
outData->CopyInformationToPipeline(request, inInfo);
}
}
// Invoke the request on the algorithm.
return this->CallAlgorithm(request, vtkExecutive::RequestDownstream,
inInfoVec, outInfoVec);
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::ExecuteData(vtkInformation* request,
vtkInformationVector** inInfo,
vtkInformationVector* outInfo)
{
this->ExecuteDataStart(request, inInfo, outInfo);
// Invoke the request on the algorithm.
int result = this->CallAlgorithm(request, vtkExecutive::RequestDownstream,
inInfo, outInfo);
this->ExecuteDataEnd(request, inInfo, outInfo);
return result;
}
//----------------------------------------------------------------------------
void vtkDemandDrivenPipeline::ExecuteDataStart(vtkInformation* request,
vtkInformationVector** inInfo,
vtkInformationVector* outputs)
{
// Ask the algorithm to mark outputs that it will not generate.
request->Remove(REQUEST_DATA());
request->Set(REQUEST_DATA_NOT_GENERATED(), 1);
this->CallAlgorithm(request, vtkExecutive::RequestDownstream,
inInfo, outputs);
request->Remove(REQUEST_DATA_NOT_GENERATED());
request->Set(REQUEST_DATA());
// Prepare outputs that will be generated to receive new data.
for(int i=0; i < outputs->GetNumberOfInformationObjects(); ++i)
{
vtkInformation* outInfo = outputs->GetInformationObject(i);
vtkDataObject* data = outInfo->Get(vtkDataObject::DATA_OBJECT());
if(data && !outInfo->Get(DATA_NOT_GENERATED()))
{
data->PrepareForNewData();
data->CopyInformationFromPipeline(request);
}
}
// Tell observers the algorithm is about to execute.
this->Algorithm->InvokeEvent(vtkCommand::StartEvent,NULL);
// The algorithm has not yet made any progress.
this->Algorithm->SetAbortExecute(0);
this->Algorithm->UpdateProgress(0.0);
}
//----------------------------------------------------------------------------
void vtkDemandDrivenPipeline::ExecuteDataEnd(vtkInformation* request,
vtkInformationVector** inInfoVec,
vtkInformationVector* outputs)
{
// The algorithm has either finished or aborted.
if(!this->Algorithm->GetAbortExecute())
{
this->Algorithm->UpdateProgress(1.0);
}
// Tell observers the algorithm is done executing.
this->Algorithm->InvokeEvent(vtkCommand::EndEvent,NULL);
// Tell outputs they have been generated.
this->MarkOutputsGenerated(request,inInfoVec,outputs);
// Remove any not-generated mark.
int i, j;
for(i=0; i < outputs->GetNumberOfInformationObjects(); ++i)
{
vtkInformation* outInfo = outputs->GetInformationObject(i);
outInfo->Remove(DATA_NOT_GENERATED());
}
// Release input data if requested.
for(i=0; i < this->Algorithm->GetNumberOfInputPorts(); ++i)
{
for(j=0; j < inInfoVec[i]->GetNumberOfInformationObjects(); ++j)
{
vtkInformation* inInfo = inInfoVec[i]->GetInformationObject(j);
vtkDataObject* dataObject = inInfo->Get(vtkDataObject::DATA_OBJECT());
if(dataObject && (dataObject->GetGlobalReleaseDataFlag() ||
inInfo->Get(RELEASE_DATA())))
{
dataObject->ReleaseData();
}
}
}
}
//----------------------------------------------------------------------------
void vtkDemandDrivenPipeline::MarkOutputsGenerated
(vtkInformation*,
vtkInformationVector** /* inInfoVec */,
vtkInformationVector* outputs)
{
// Tell all generated outputs that they have been generated.
for(int i=0; i < outputs->GetNumberOfInformationObjects(); ++i)
{
vtkInformation* outInfo = outputs->GetInformationObject(i);
vtkDataObject* data = outInfo->Get(vtkDataObject::DATA_OBJECT());
if(data && !outInfo->Get(DATA_NOT_GENERATED()))
{
data->DataHasBeenGenerated();
}
}
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::CheckDataObject(int port,
vtkInformationVector* outInfoVec)
{
// Check that the given output port has a valid data object.
vtkInformation* outInfo = outInfoVec->GetInformationObject(port);
vtkDataObject* data = outInfo->Get(vtkDataObject::DATA_OBJECT());
vtkInformation* portInfo = this->Algorithm->GetOutputPortInformation(port);
if(const char* dt = portInfo->Get(vtkDataObject::DATA_TYPE_NAME()))
{
// The output port specifies a data type. Make sure the data
// object exists and is of the right type.
if(!data || !data->IsA(dt))
{
// Try to create an instance of the correct type.
data = this->NewDataObject(dt);
this->SetOutputData(port, data, outInfo);
if(data)
{
data->FastDelete();
}
}
if(!data)
{
// The algorithm has a bug and did not create the data object.
vtkErrorMacro("Algorithm " << this->Algorithm->GetClassName() << "("
<< this->Algorithm
<< ") did not create output for port " << port
<< " when asked by REQUEST_DATA_OBJECT and does not"
<< " specify a concrete DATA_TYPE_NAME.");
return 0;
}
return 1;
}
else if(data)
{
// The algorithm did not specify its output data type. Just assume
// the data object is of the correct type.
return 1;
}
else
{
// The algorithm did not specify its output data type and no
// object exists.
vtkErrorMacro("Algorithm " << this->Algorithm->GetClassName() << "("
<< this->Algorithm
<< ") did not create output for port " << port
<< " when asked by REQUEST_DATA_OBJECT and does not"
<< " specify any DATA_TYPE_NAME.");
return 0;
}
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputCountIsValid
(vtkInformationVector **inInfoVec)
{
// Check the number of connections for each port.
int result = 1;
for(int p=0; p < this->Algorithm->GetNumberOfInputPorts(); ++p)
{
if(!this->InputCountIsValid(p,inInfoVec))
{
result = 0;
}
}
return result;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputCountIsValid
(int port, vtkInformationVector **inInfoVec)
{
// Get the number of connections for this port.
if (!inInfoVec[port])
{
return 0;
}
int connections = inInfoVec[port]->GetNumberOfInformationObjects();
// If the input port is optional, there may be less than one connection.
if(!this->InputIsOptional(port) && (connections < 1))
{
vtkErrorMacro("Input port " << port << " of algorithm "
<< this->Algorithm->GetClassName()
<< "(" << this->Algorithm << ") has " << connections
<< " connections but is not optional.");
return 0;
}
// If the input port is repeatable, there may be more than one connection.
if(!this->InputIsRepeatable(port) && (connections > 1))
{
vtkErrorMacro("Input port " << port << " of algorithm "
<< this->Algorithm->GetClassName()
<< "(" << this->Algorithm << ") has " << connections
<< " connections but is not repeatable.");
return 0;
}
return 1;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputTypeIsValid
(vtkInformationVector **inInfoVec)
{
// Check the connection types for each port.
int result = 1;
for(int p=0; p < this->Algorithm->GetNumberOfInputPorts(); ++p)
{
if(!this->InputTypeIsValid(p, inInfoVec))
{
result = 0;
}
}
return result;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputTypeIsValid
(int port, vtkInformationVector **inInfoVec)
{
// Check the type of each connection on this port.
int result = 1;
if (!inInfoVec[port])
{
return 0;
}
for(int i=0; i < inInfoVec[port]->GetNumberOfInformationObjects(); ++i)
{
if(!this->InputTypeIsValid(port, i, inInfoVec))
{
result = 0;
}
}
return result;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputTypeIsValid
(int port, int index, vtkInformationVector **inInfoVec)
{
if (!inInfoVec[port])
{
return 0;
}
vtkInformation* info = this->Algorithm->GetInputPortInformation(port);
vtkDataObject* input = this->GetInputData(port, index, inInfoVec);
// Enforce required type, if any.
if(const char* dt = info->Get(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE()))
{
// The input cannot be NULL unless the port is optional.
if(!input && !info->Get(vtkAlgorithm::INPUT_IS_OPTIONAL()))
{
vtkErrorMacro("Input for connection index " << index
<< " on input port index " << port
<< " for algorithm " << this->Algorithm->GetClassName()
<< "(" << this->Algorithm << ") is NULL, but a " << dt
<< " is required.");
return 0;
}
// The input must be of required type or NULL.
if(input && !input->IsA(dt))
{
vtkErrorMacro("Input for connection index " << index
<< " on input port index " << port
<< " for algorithm " << this->Algorithm->GetClassName()
<< "(" << this->Algorithm << ") is of type "
<< input->GetClassName() << ", but a " << dt
<< " is required.");
return 0;
}
}
return 1;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputFieldsAreValid
(vtkInformationVector **inInfoVec)
{
// Check the fields for each port.
int result = 1;
for(int p=0; p < this->Algorithm->GetNumberOfInputPorts(); ++p)
{
if(!this->InputFieldsAreValid(p,inInfoVec))
{
result = 0;
}
}
return result;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputFieldsAreValid
(int port, vtkInformationVector **inInfoVec)
{
// Check the fields for each connection on this port.
if (!inInfoVec[port])
{
return 0;
}
int result = 1;
for(int i=0; i < inInfoVec[port]->GetNumberOfInformationObjects(); ++i)
{
if(!this->InputFieldsAreValid(port, i, inInfoVec))
{
result = 0;
}
}
return result;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputFieldsAreValid
(int port, int index, vtkInformationVector **inInfoVec)
{
vtkInformation* info = this->Algorithm->GetInputPortInformation(port);
vtkInformationVector* fields =
info->Get(vtkAlgorithm::INPUT_REQUIRED_FIELDS());
// If there are no required fields, there is nothing to check.
if(!fields)
{
return 1;
}
vtkDataObject* input = this->GetInputData(port, index, inInfoVec);
// NULL inputs do not have to have the proper fields.
if(!input)
{
return 1;
}
// Check availability of each required field.
int result = 1;
for(int i=0; i < fields->GetNumberOfInformationObjects(); ++i)
{
vtkInformation* field = fields->GetInformationObject(i);
// Decide which kinds of fields to check.
int checkPoints = 1;
int checkCells = 1;
int checkFields = 1;
if(field->Has(vtkDataObject::FIELD_ASSOCIATION()))
{
switch(field->Get(vtkDataObject::FIELD_ASSOCIATION()))
{
case vtkDataObject::FIELD_ASSOCIATION_POINTS:
checkCells = 0; checkFields = 0; break;
case vtkDataObject::FIELD_ASSOCIATION_CELLS:
checkPoints = 0; checkFields = 0; break;
case vtkDataObject::FIELD_ASSOCIATION_NONE:
checkPoints = 0; checkCells = 0; break;
}
}
// Point and cell data arrays only exist in vtkDataSet instances.
vtkDataSet* dataSet = vtkDataSet::SafeDownCast(input);
// Look for a point data, cell data, or field data array matching
// the requirements.
if(!(checkPoints && dataSet && dataSet->GetPointData() &&
this->DataSetAttributeExists(dataSet->GetPointData(), field)) &&
!(checkCells && dataSet && dataSet->GetCellData() &&
this->DataSetAttributeExists(dataSet->GetCellData(), field)) &&
!(checkFields && input && input->GetFieldData() &&
this->FieldArrayExists(input->GetFieldData(), field)))
{
/* TODO: Construct more descriptive error message from field
requirements. */
vtkErrorMacro("Required field not found in input.");
result = 0;
}
}
return result;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::DataSetAttributeExists(vtkDataSetAttributes* dsa,
vtkInformation* field)
{
if(field->Has(vtkDataObject::FIELD_ATTRIBUTE_TYPE()))
{
// A specific attribute must match the requirements.
int attrType = field->Get(vtkDataObject::FIELD_ATTRIBUTE_TYPE());
return this->ArrayIsValid(dsa->GetAttribute(attrType), field);
}
else
{
// Search for an array matching the requirements.
return this->FieldArrayExists(dsa, field);
}
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::FieldArrayExists(vtkFieldData* data,
vtkInformation* field)
{
// Search the field data instance for an array matching the requirements.
for(int a=0; a < data->GetNumberOfArrays(); ++a)
{
if(this->ArrayIsValid(data->GetArray(a), field))
{
return 1;
}
}
return 0;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::ArrayIsValid(vtkDataArray* array,
vtkInformation* field)
{
// Enforce existence of the array.
if(!array)
{
return 0;
}
// Enforce name of the array. This should really only be used for
// field data (not point or cell data).
if(const char* name = field->Get(vtkDataObject::FIELD_NAME()))
{
if(!array->GetName() || (strcmp(name, array->GetName()) != 0))
{
return 0;
}
}
// Enforce component type for the array.
if(field->Has(vtkDataObject::FIELD_ARRAY_TYPE()))
{
int arrayType = field->Get(vtkDataObject::FIELD_ARRAY_TYPE());
if(array->GetDataType() != arrayType)
{
return 0;
}
}
// Enforce number of components for the array.
if(field->Has(vtkDataObject::FIELD_NUMBER_OF_COMPONENTS()))
{
int arrayNumComponents =
field->Get(vtkDataObject::FIELD_NUMBER_OF_COMPONENTS());
if(array->GetNumberOfComponents() != arrayNumComponents)
{
return 0;
}
}
// Enforce number of tuples. This should really only be used for
// field data (not point or cell data).
if(field->Has(vtkDataObject::FIELD_NUMBER_OF_TUPLES()))
{
int arrayNumTuples = field->Get(vtkDataObject::FIELD_NUMBER_OF_TUPLES());
if(array->GetNumberOfTuples() != arrayNumTuples)
{
return 0;
}
}
return 1;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputIsOptional(int port)
{
if(vtkInformation* info = this->Algorithm->GetInputPortInformation(port))
{
return info->Get(vtkAlgorithm::INPUT_IS_OPTIONAL());
}
return 0;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::InputIsRepeatable(int port)
{
if(vtkInformation* info = this->Algorithm->GetInputPortInformation(port))
{
return info->Get(vtkAlgorithm::INPUT_IS_REPEATABLE());
}
return 0;
}
//----------------------------------------------------------------------------
vtkDataObject* vtkDemandDrivenPipeline::NewDataObject(const char* type)
{
// Check for some standard types and then try the instantiator.
if(strcmp(type, "vtkImageData") == 0)
{
return vtkImageData::New();
}
else if(strcmp(type, "vtkPolyData") == 0)
{
return vtkPolyData::New();
}
else if(strcmp(type, "vtkRectilinearGrid") == 0)
{
return vtkRectilinearGrid::New();
}
else if(strcmp(type, "vtkStructuredGrid") == 0)
{
return vtkStructuredGrid::New();
}
else if(strcmp(type, "vtkStructuredPoints") == 0)
{
return vtkStructuredPoints::New();
}
else if(strcmp(type, "vtkUnstructuredGrid") == 0)
{
return vtkUnstructuredGrid::New();
}
else if(strcmp(type, "vtkHierarchicalDataSet") == 0)
{
return vtkHierarchicalDataSet::New();
}
else if(strcmp(type, "vtkHierarchicalBoxDataSet") == 0)
{
return vtkHierarchicalBoxDataSet::New();
}
else if(strcmp(type, "vtkHyperOctree") == 0)
{
return vtkHyperOctree::New();
}
else if(vtkObject* obj = vtkInstantiator::CreateInstance(type))
{
vtkDataObject* data = vtkDataObject::SafeDownCast(obj);
if(!data)
{
obj->Delete();
}
return data;
}
else
{
return 0;
}
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline
::NeedToExecuteData(int outputPort,
vtkInformationVector** inInfoVec,
vtkInformationVector* outInfoVec)
{
// If the filter parameters or input have been modified since the
// last execution then we must execute. This is a shortcut for most
// filters since all outputs will have the same UpdateTime. This
// also handles the case in which there are no outputs.
if(this->PipelineMTime > this->DataTime.GetMTime())
{
return 1;
}
if(outputPort >= 0)
{
// If the output on the port making the request is out-of-date
// then we must execute.
vtkInformation* info = outInfoVec->GetInformationObject(outputPort);
vtkDataObject* data = info->Get(vtkDataObject::DATA_OBJECT());
if(!data || this->PipelineMTime > data->GetUpdateTime())
{
return 1;
}
}
else
{
// No port is specified. Check all ports.
for(int i=0; i < this->Algorithm->GetNumberOfOutputPorts(); ++i)
{
if(this->NeedToExecuteData(i,inInfoVec,outInfoVec))
{
return 1;
}
}
}
// We do not need to execute.
return 0;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::SetReleaseDataFlag(int port, int n)
{
if(!this->OutputPortIndexInRange(port, "set release data flag on"))
{
return 0;
}
vtkInformation* info = this->GetOutputInformation(port);
if(this->GetReleaseDataFlag(port) != n)
{
info->Set(RELEASE_DATA(), n);
return 1;
}
return 0;
}
//----------------------------------------------------------------------------
int vtkDemandDrivenPipeline::GetReleaseDataFlag(int port)
{
if(!this->OutputPortIndexInRange(port, "get release data flag from"))
{
return 0;
}
vtkInformation* info = this->GetOutputInformation(port);
if(!info->Has(RELEASE_DATA()))
{
info->Set(RELEASE_DATA(), 0);
}
return info->Get(RELEASE_DATA());
}
|
#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include <sstream>
#include <iomanip>
#include <stdio.h>
typedef enum {
INSTALL,
DELETE
} Mode;
int main(int argc, char **argv) {
if(!platformInit()) {
return 0;
}
bool ninjhax = platformIsNinjhax();
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL;
bool exit = false;
bool netInstall = false;
u64 freeSpace = fsGetFreeSpace(destination);
auto onLoop = [&]() {
if(ninjhax && inputIsPressed(BUTTON_SELECT)) {
exit = true;
return true;
}
bool breakLoop = false;
if(inputIsPressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fsGetFreeSpace(destination);
if(mode == DELETE) {
breakLoop = true;
}
}
if(inputIsPressed(BUTTON_R)) {
if(mode == INSTALL) {
mode = DELETE;
} else {
mode = INSTALL;
}
breakLoop = true;
}
if(inputIsPressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
std::stringstream stream;
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
stream << "Y - Receive an app over the network" << "\n";
if(ninjhax) {
stream << "SELECT - Exit to launcher" << "\n";
}
std::string str = stream.str();
screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);
return breakLoop;
};
auto onProgress = [&](int progress) {
uiDisplayProgress(TOP_SCREEN, "Installing", "Press B to cancel.", true, progress);
inputPoll();
return !inputIsPressed(BUTTON_B);
};
while(platformIsRunning()) {
std::string targetInstall;
App targetDelete;
if(mode == INSTALL) {
uiSelectFile(&targetInstall, "sdmc:", extensions, [&](bool inRoot) {
return onLoop();
}, [&](std::string path, bool &updateList) {
if(uiPrompt(TOP_SCREEN, "Install the selected title?", true)) {
AppResult ret = appInstallFile(destination, path, onProgress);
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE) {
uiSelectApp(&targetDelete, destination, onLoop, [&](App app, bool &updateList) {
if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true)) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult ret = appDelete(app);
std::stringstream resultMsg;
resultMsg << "Delete ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
}
if(netInstall && !exit) {
netInstall = false;
screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);
RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);
if(file.fd == NULL) {
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
std::stringstream resultMsg;
if(mode == INSTALL) {
resultMsg << "Install ";
} else if(mode == DELETE) {
resultMsg << "Delete ";
}
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
fclose(file.fd);
continue;
}
if(exit) {
break;
}
}
platformCleanup();
return 0;
}
Allow deleting CIA files and installing/deleting all CIA files in a directory at once.
#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include <stdio.h>
#include <sstream>
#include <iomanip>
#include <sys/dirent.h>
typedef enum {
INSTALL_CIA,
DELETE_CIA,
DELETE_TITLE
} Mode;
int main(int argc, char **argv) {
if(!platformInit()) {
return 0;
}
bool ninjhax = platformIsNinjhax();
/* if(ninjhax) {
consoleInit(GFX_BOTTOM, NULL);
consoleClear();
AcquireResult result = platformAcquireServices();
if(result != ACQUIRE_SUCCESS) {
//std::stringstream errorStream;
//errorStream << "Failed to acquire services." << "\n";
//errorStream << platformGetAcquireResultString(result) << "\n";
//uiPrompt(TOP_SCREEN, errorStream.str(), false);
while(true) {
inputPoll();
if(inputIsPressed(BUTTON_START)) {
break;
}
}
platformCleanup();
return 0;
}
} */
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL_CIA;
bool exit = false;
bool netInstall = false;
u64 freeSpace = fsGetFreeSpace(destination);
auto onLoop = [&]() {
if(ninjhax && inputIsPressed(BUTTON_SELECT)) {
exit = true;
return true;
}
bool breakLoop = false;
if(inputIsPressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fsGetFreeSpace(destination);
if(mode == DELETE_TITLE) {
breakLoop = true;
}
}
if(inputIsPressed(BUTTON_R)) {
if(mode == INSTALL_CIA) {
mode = DELETE_CIA;
} else if(mode == DELETE_CIA) {
mode = DELETE_TITLE;
} else {
mode = INSTALL_CIA;
}
breakLoop = true;
}
if(inputIsPressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
std::stringstream stream;
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : "Delete Title") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
if(mode == INSTALL_CIA) {
stream << "X - Install all CIAs in the current directory" << "\n";
} else if(mode == DELETE_CIA) {
stream << "X - Delete all CIAs in the current directory" << "\n";
}
stream << "Y - Receive an app over the network" << "\n";
if(ninjhax) {
stream << "SELECT - Exit to launcher" << "\n";
}
std::string str = stream.str();
screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);
return breakLoop;
};
auto onProgress = [&](int progress) {
uiDisplayProgress(TOP_SCREEN, "Installing", "Press B to cancel.", true, progress);
inputPoll();
return !inputIsPressed(BUTTON_B);
};
while(platformIsRunning()) {
std::string fileTarget;
App appTarget;
if(mode == INSTALL_CIA) {
uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
if(inputIsPressed(BUTTON_X)) {
if(uiPrompt(TOP_SCREEN, "Install all CIAs in the current directory?", true)) {
bool failed = false;
std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
std::string path = (*it).path;
std::string fileName = (*it).name;
if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
AppResult ret = appInstallFile(destination, path, onProgress);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install failed!" << "\n";
resultMsg << fileName << "\n";
resultMsg << appGetResultString(ret) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
failed = true;
break;
}
}
}
if(!failed) {
uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
}
freeSpace = fsGetFreeSpace(destination);
}
}
return onLoop();
}, [&](const std::string path, bool &updateList) {
if(uiPrompt(TOP_SCREEN, "Install the selected CIA?", true)) {
AppResult ret = appInstallFile(destination, path, onProgress);
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE_CIA) {
uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
if(inputIsPressed(BUTTON_X)) {
if(uiPrompt(TOP_SCREEN, "Delete all CIAs in the current directory?", true)) {
updateList = true;
bool failed = false;
std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
std::string path = (*it).path;
std::string fileName = (*it).name;
if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
if(!fsDelete(path)) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << fileName << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
failed = true;
break;
}
}
}
if(!failed) {
uiPrompt(TOP_SCREEN, "Delete succeeded!\n", false);
}
freeSpace = fsGetFreeSpace(destination);
}
}
return onLoop();
}, [&](const std::string path, bool &updateList) {
if(uiPrompt(TOP_SCREEN, "Delete the selected CIA?", true)) {
updateList = true;
std::stringstream resultMsg;
resultMsg << "Delete ";
if(fsDelete(path)) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE_TITLE) {
uiSelectApp(&appTarget, destination, [&](bool &updateList) {
return onLoop();
}, [&](App app, bool &updateList) {
if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true)) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult ret = appDelete(app);
std::stringstream resultMsg;
resultMsg << "Delete ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
}
if(netInstall && !exit) {
netInstall = false;
screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);
RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);
if(file.fd == NULL) {
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
fclose(file.fd);
continue;
}
if(exit) {
break;
}
}
platformCleanup();
return 0;
}
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "warnings_guard_ne_locks.h"
#include <ne_uri.h>
#include "rtl/ustring.hxx"
#include "osl/time.h"
#include "osl/thread.hxx"
#include "salhelper/thread.hxx"
#include "NeonSession.hxx"
#include "NeonLockStore.hxx"
using namespace webdav_ucp;
namespace webdav_ucp {
class TickerThread : public salhelper::Thread
{
bool m_bFinish;
NeonLockStore & m_rLockStore;
public:
TickerThread( NeonLockStore & rLockStore )
: Thread( "NeonTickerThread" ), m_bFinish( false ),
m_rLockStore( rLockStore ) {}
void finish() { m_bFinish = true; }
private:
virtual void execute();
};
} // namespace webdav_ucp
// -------------------------------------------------------------------
void TickerThread::execute()
{
OSL_TRACE( "TickerThread: start." );
// we have to go through the loop more often to be able to finish ~quickly
const int nNth = 25;
int nCount = nNth;
while ( !m_bFinish )
{
if ( nCount-- <= 0 )
{
m_rLockStore.refreshLocks();
nCount = nNth;
}
TimeValue aTV;
aTV.Seconds = 0;
aTV.Nanosec = 1000000000 / nNth;
osl::Thread::wait( aTV );
}
OSL_TRACE( "TickerThread: stop." );
}
// -------------------------------------------------------------------
NeonLockStore::NeonLockStore()
: m_pNeonLockStore( ne_lockstore_create() )
{
OSL_ENSURE( m_pNeonLockStore, "Unable to create neon lock store!" );
}
// -------------------------------------------------------------------
NeonLockStore::~NeonLockStore()
{
stopTicker();
// release active locks, if any.
OSL_ENSURE( m_aLockInfoMap.empty(),
"NeonLockStore::~NeonLockStore - Releasing active locks!" );
LockInfoMap::const_iterator it( m_aLockInfoMap.begin() );
const LockInfoMap::const_iterator end( m_aLockInfoMap.end() );
while ( it != end )
{
NeonLock * pLock = (*it).first;
(*it).second.xSession->UNLOCK( pLock );
ne_lockstore_remove( m_pNeonLockStore, pLock );
ne_lock_destroy( pLock );
++it;
}
ne_lockstore_destroy( m_pNeonLockStore );
}
// -------------------------------------------------------------------
void NeonLockStore::startTicker()
{
osl::MutexGuard aGuard( m_aMutex );
if ( !m_pTickerThread.is() )
{
m_pTickerThread = new TickerThread( *this );
m_pTickerThread->launch();
}
}
// -------------------------------------------------------------------
void NeonLockStore::stopTicker()
{
osl::MutexGuard aGuard( m_aMutex );
if ( m_pTickerThread.is() )
{
m_pTickerThread->finish();
m_pTickerThread->join();
m_pTickerThread.clear();
}
}
// -------------------------------------------------------------------
void NeonLockStore::registerSession( HttpSession * pHttpSession )
{
osl::MutexGuard aGuard( m_aMutex );
ne_lockstore_register( m_pNeonLockStore, pHttpSession );
}
// -------------------------------------------------------------------
NeonLock * NeonLockStore::findByUri( rtl::OUString const & rUri )
{
osl::MutexGuard aGuard( m_aMutex );
ne_uri aUri;
ne_uri_parse( rtl::OUStringToOString(
rUri, RTL_TEXTENCODING_UTF8 ).getStr(), &aUri );
return ne_lockstore_findbyuri( m_pNeonLockStore, &aUri );
}
// -------------------------------------------------------------------
void NeonLockStore::addLock( NeonLock * pLock,
rtl::Reference< NeonSession > const & xSession,
sal_Int32 nLastChanceToSendRefreshRequest )
{
osl::MutexGuard aGuard( m_aMutex );
ne_lockstore_add( m_pNeonLockStore, pLock );
m_aLockInfoMap[ pLock ]
= LockInfo( xSession, nLastChanceToSendRefreshRequest );
startTicker();
}
// -------------------------------------------------------------------
void NeonLockStore::updateLock( NeonLock * pLock,
sal_Int32 nLastChanceToSendRefreshRequest )
{
osl::MutexGuard aGuard( m_aMutex );
LockInfoMap::iterator it( m_aLockInfoMap.find( pLock ) );
OSL_ENSURE( it != m_aLockInfoMap.end(),
"NeonLockStore::updateLock: lock not found!" );
if ( it != m_aLockInfoMap.end() )
{
(*it).second.nLastChanceToSendRefreshRequest
= nLastChanceToSendRefreshRequest;
}
}
// -------------------------------------------------------------------
void NeonLockStore::removeLock( NeonLock * pLock )
{
osl::MutexGuard aGuard( m_aMutex );
m_aLockInfoMap.erase( pLock );
ne_lockstore_remove( m_pNeonLockStore, pLock );
if ( m_aLockInfoMap.empty() )
stopTicker();
}
// -------------------------------------------------------------------
void NeonLockStore::refreshLocks()
{
osl::MutexGuard aGuard( m_aMutex );
LockInfoMap::iterator it( m_aLockInfoMap.begin() );
const LockInfoMap::const_iterator end( m_aLockInfoMap.end() );
while ( it != end )
{
LockInfo & rInfo = (*it).second;
if ( rInfo.nLastChanceToSendRefreshRequest != -1 )
{
// 30 seconds or less remaining until lock expires?
TimeValue t1;
osl_getSystemTime( &t1 );
if ( rInfo.nLastChanceToSendRefreshRequest - 30
<= sal_Int32( t1.Seconds ) )
{
// refresh the lock.
sal_Int32 nlastChanceToSendRefreshRequest = -1;
if ( rInfo.xSession->LOCK(
(*it).first,
/* out param */ nlastChanceToSendRefreshRequest ) )
{
rInfo.nLastChanceToSendRefreshRequest
= nlastChanceToSendRefreshRequest;
}
else
{
// refresh failed. stop auto-refresh.
rInfo.nLastChanceToSendRefreshRequest = -1;
}
}
}
++it;
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
fix msvc2005 build
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "warnings_guard_ne_locks.h"
#include <ne_uri.h>
#include "rtl/ustring.hxx"
#include "osl/time.h"
#include "osl/thread.hxx"
#include "salhelper/thread.hxx"
#include "NeonSession.hxx"
#include "NeonLockStore.hxx"
using namespace webdav_ucp;
namespace webdav_ucp {
class TickerThread : public salhelper::Thread
{
bool m_bFinish;
NeonLockStore & m_rLockStore;
public:
TickerThread( NeonLockStore & rLockStore )
: Thread( "NeonTickerThread" ), m_bFinish( false ),
m_rLockStore( rLockStore ) {}
void finish() { m_bFinish = true; }
private:
virtual void execute();
};
} // namespace webdav_ucp
// -------------------------------------------------------------------
void TickerThread::execute()
{
OSL_TRACE( "TickerThread: start." );
// we have to go through the loop more often to be able to finish ~quickly
const int nNth = 25;
int nCount = nNth;
while ( !m_bFinish )
{
if ( nCount-- <= 0 )
{
m_rLockStore.refreshLocks();
nCount = nNth;
}
TimeValue aTV;
aTV.Seconds = 0;
aTV.Nanosec = 1000000000 / nNth;
salhelper::Thread::wait( aTV );
}
OSL_TRACE( "TickerThread: stop." );
}
// -------------------------------------------------------------------
NeonLockStore::NeonLockStore()
: m_pNeonLockStore( ne_lockstore_create() )
{
OSL_ENSURE( m_pNeonLockStore, "Unable to create neon lock store!" );
}
// -------------------------------------------------------------------
NeonLockStore::~NeonLockStore()
{
stopTicker();
// release active locks, if any.
OSL_ENSURE( m_aLockInfoMap.empty(),
"NeonLockStore::~NeonLockStore - Releasing active locks!" );
LockInfoMap::const_iterator it( m_aLockInfoMap.begin() );
const LockInfoMap::const_iterator end( m_aLockInfoMap.end() );
while ( it != end )
{
NeonLock * pLock = (*it).first;
(*it).second.xSession->UNLOCK( pLock );
ne_lockstore_remove( m_pNeonLockStore, pLock );
ne_lock_destroy( pLock );
++it;
}
ne_lockstore_destroy( m_pNeonLockStore );
}
// -------------------------------------------------------------------
void NeonLockStore::startTicker()
{
osl::MutexGuard aGuard( m_aMutex );
if ( !m_pTickerThread.is() )
{
m_pTickerThread = new TickerThread( *this );
m_pTickerThread->launch();
}
}
// -------------------------------------------------------------------
void NeonLockStore::stopTicker()
{
osl::MutexGuard aGuard( m_aMutex );
if ( m_pTickerThread.is() )
{
m_pTickerThread->finish();
m_pTickerThread->join();
m_pTickerThread.clear();
}
}
// -------------------------------------------------------------------
void NeonLockStore::registerSession( HttpSession * pHttpSession )
{
osl::MutexGuard aGuard( m_aMutex );
ne_lockstore_register( m_pNeonLockStore, pHttpSession );
}
// -------------------------------------------------------------------
NeonLock * NeonLockStore::findByUri( rtl::OUString const & rUri )
{
osl::MutexGuard aGuard( m_aMutex );
ne_uri aUri;
ne_uri_parse( rtl::OUStringToOString(
rUri, RTL_TEXTENCODING_UTF8 ).getStr(), &aUri );
return ne_lockstore_findbyuri( m_pNeonLockStore, &aUri );
}
// -------------------------------------------------------------------
void NeonLockStore::addLock( NeonLock * pLock,
rtl::Reference< NeonSession > const & xSession,
sal_Int32 nLastChanceToSendRefreshRequest )
{
osl::MutexGuard aGuard( m_aMutex );
ne_lockstore_add( m_pNeonLockStore, pLock );
m_aLockInfoMap[ pLock ]
= LockInfo( xSession, nLastChanceToSendRefreshRequest );
startTicker();
}
// -------------------------------------------------------------------
void NeonLockStore::updateLock( NeonLock * pLock,
sal_Int32 nLastChanceToSendRefreshRequest )
{
osl::MutexGuard aGuard( m_aMutex );
LockInfoMap::iterator it( m_aLockInfoMap.find( pLock ) );
OSL_ENSURE( it != m_aLockInfoMap.end(),
"NeonLockStore::updateLock: lock not found!" );
if ( it != m_aLockInfoMap.end() )
{
(*it).second.nLastChanceToSendRefreshRequest
= nLastChanceToSendRefreshRequest;
}
}
// -------------------------------------------------------------------
void NeonLockStore::removeLock( NeonLock * pLock )
{
osl::MutexGuard aGuard( m_aMutex );
m_aLockInfoMap.erase( pLock );
ne_lockstore_remove( m_pNeonLockStore, pLock );
if ( m_aLockInfoMap.empty() )
stopTicker();
}
// -------------------------------------------------------------------
void NeonLockStore::refreshLocks()
{
osl::MutexGuard aGuard( m_aMutex );
LockInfoMap::iterator it( m_aLockInfoMap.begin() );
const LockInfoMap::const_iterator end( m_aLockInfoMap.end() );
while ( it != end )
{
LockInfo & rInfo = (*it).second;
if ( rInfo.nLastChanceToSendRefreshRequest != -1 )
{
// 30 seconds or less remaining until lock expires?
TimeValue t1;
osl_getSystemTime( &t1 );
if ( rInfo.nLastChanceToSendRefreshRequest - 30
<= sal_Int32( t1.Seconds ) )
{
// refresh the lock.
sal_Int32 nlastChanceToSendRefreshRequest = -1;
if ( rInfo.xSession->LOCK(
(*it).first,
/* out param */ nlastChanceToSendRefreshRequest ) )
{
rInfo.nLastChanceToSendRefreshRequest
= nlastChanceToSendRefreshRequest;
}
else
{
// refresh failed. stop auto-refresh.
rInfo.nLastChanceToSendRefreshRequest = -1;
}
}
}
++it;
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2001 - 2014 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
#include <deal.II/base/std_cxx11/array.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/grid/tria.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/grid/tria_boundary.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/lac/sparsity_pattern.h>
#include <deal.II/lac/sparsity_tools.h>
#include <deal.II/lac/compressed_sparsity_pattern.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_accessor.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/fe/fe_nothing.h>
#include <deal.II/fe/mapping_q1.h>
#include <deal.II/fe/mapping_q.h>
#include <deal.II/fe/fe_values.h>
#include <deal.II/hp/mapping_collection.h>
#include <deal.II/multigrid/mg_dof_handler.h>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <cmath>
#include <numeric>
#include <list>
#include <set>
DEAL_II_NAMESPACE_OPEN
namespace GridTools
{
// This anonymous namespace contains utility functions to extract the
// triangulation from any container such as DoFHandler
// and the like
namespace
{
template<int dim, int spacedim>
const Triangulation<dim, spacedim> &
get_tria(const Triangulation<dim, spacedim> &tria)
{
return tria;
}
template<int dim, int spacedim>
const Triangulation<dim, spacedim> &
get_tria(const parallel::distributed::Triangulation<dim, spacedim> &tria)
{
return tria;
}
template<int dim, template<int, int> class Container, int spacedim>
const Triangulation<dim,spacedim> &
get_tria(const Container<dim,spacedim> &container)
{
return container.get_tria();
}
template<int dim, int spacedim>
Triangulation<dim, spacedim> &
get_tria(Triangulation<dim, spacedim> &tria)
{
return tria;
}
template<int dim, int spacedim>
Triangulation<dim, spacedim> &
get_tria(parallel::distributed::Triangulation<dim, spacedim> &tria)
{
return tria;
}
template<int dim, template<int, int> class Container, int spacedim>
const Triangulation<dim,spacedim> &
get_tria(Container<dim,spacedim> &container)
{
return container.get_tria();
}
}
template <int dim, int spacedim>
double
diameter (const Triangulation<dim, spacedim> &tria)
{
// we can't deal with distributed meshes
// since we don't have all vertices
// locally. there is one exception,
// however: if the mesh has never been
// refined. the way to test this is not to
// ask tria.n_levels()==1, since this is
// something that can happen on one
// processor without being true on
// all. however, we can ask for the global
// number of active cells and use that
#ifdef DEAL_II_WITH_P4EST
if (const parallel::distributed::Triangulation<dim,spacedim> *p_tria
= dynamic_cast<const parallel::distributed::Triangulation<dim,spacedim>*>(&tria))
Assert (p_tria->n_global_active_cells() == tria.n_cells(0),
ExcNotImplemented());
#endif
// the algorithm used simply
// traverses all cells and picks
// out the boundary vertices. it
// may or may not be faster to
// simply get all vectors, don't
// mark boundary vertices, and
// compute the distances thereof,
// but at least as the mesh is
// refined, it seems better to
// first mark boundary nodes, as
// marking is O(N) in the number of
// cells/vertices, while computing
// the maximal distance is O(N*N)
const std::vector<Point<spacedim> > &vertices = tria.get_vertices ();
std::vector<bool> boundary_vertices (vertices.size(), false);
typename Triangulation<dim,spacedim>::active_cell_iterator
cell = tria.begin_active();
const typename Triangulation<dim,spacedim>::active_cell_iterator
endc = tria.end();
for (; cell!=endc; ++cell)
for (unsigned int face=0; face<GeometryInfo<dim>::faces_per_cell; ++face)
if (cell->face(face)->at_boundary ())
for (unsigned int i=0; i<GeometryInfo<dim>::vertices_per_face; ++i)
boundary_vertices[cell->face(face)->vertex_index(i)] = true;
// now traverse the list of
// boundary vertices and check
// distances. since distances are
// symmetric, we only have to check
// one half
double max_distance_sqr = 0;
std::vector<bool>::const_iterator pi = boundary_vertices.begin();
const unsigned int N = boundary_vertices.size();
for (unsigned int i=0; i<N; ++i, ++pi)
{
std::vector<bool>::const_iterator pj = pi+1;
for (unsigned int j=i+1; j<N; ++j, ++pj)
if ((*pi==true) && (*pj==true) &&
((vertices[i]-vertices[j]).square() > max_distance_sqr))
max_distance_sqr = (vertices[i]-vertices[j]).square();
};
return std::sqrt(max_distance_sqr);
}
template <int dim, int spacedim>
double
volume (const Triangulation<dim, spacedim> &triangulation,
const Mapping<dim,spacedim> &mapping)
{
// get the degree of the mapping if possible. if not, just assume 1
const unsigned int mapping_degree
= (dynamic_cast<const MappingQ<dim,spacedim>*>(&mapping) != 0 ?
dynamic_cast<const MappingQ<dim,spacedim>*>(&mapping)->get_degree() :
1);
// then initialize an appropriate quadrature formula
const QGauss<dim> quadrature_formula (mapping_degree + 1);
const unsigned int n_q_points = quadrature_formula.size();
// we really want the JxW values from the FEValues object, but it
// wants a finite element. create a cheap element as a dummy
// element
FE_Nothing<dim,spacedim> dummy_fe;
FEValues<dim,spacedim> fe_values (mapping, dummy_fe, quadrature_formula,
update_JxW_values);
typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active(),
endc = triangulation.end();
double local_volume = 0;
// compute the integral quantities by quadrature
for (; cell!=endc; ++cell)
if (cell->is_locally_owned())
{
fe_values.reinit (cell);
for (unsigned int q=0; q<n_q_points; ++q)
local_volume += fe_values.JxW(q);
}
double global_volume = 0;
#ifdef DEAL_II_WITH_MPI
if (const parallel::distributed::Triangulation<dim,spacedim> *p_tria
= dynamic_cast<const parallel::distributed::Triangulation<dim,spacedim>*>(&triangulation))
global_volume = Utilities::MPI::sum (local_volume, p_tria->get_communicator());
else
global_volume = local_volume;
#else
global_volume = local_volume;
#endif
return global_volume;
}
template <>
double
cell_measure<3>(const std::vector<Point<3> > &all_vertices,
const unsigned int (&vertex_indices)[GeometryInfo<3>::vertices_per_cell])
{
// note that this is the
// cell_measure based on the new
// deal.II numbering. When called
// from inside GridReordering make
// sure that you reorder the
// vertex_indices before
const double x[8] = { all_vertices[vertex_indices[0]](0),
all_vertices[vertex_indices[1]](0),
all_vertices[vertex_indices[2]](0),
all_vertices[vertex_indices[3]](0),
all_vertices[vertex_indices[4]](0),
all_vertices[vertex_indices[5]](0),
all_vertices[vertex_indices[6]](0),
all_vertices[vertex_indices[7]](0)
};
const double y[8] = { all_vertices[vertex_indices[0]](1),
all_vertices[vertex_indices[1]](1),
all_vertices[vertex_indices[2]](1),
all_vertices[vertex_indices[3]](1),
all_vertices[vertex_indices[4]](1),
all_vertices[vertex_indices[5]](1),
all_vertices[vertex_indices[6]](1),
all_vertices[vertex_indices[7]](1)
};
const double z[8] = { all_vertices[vertex_indices[0]](2),
all_vertices[vertex_indices[1]](2),
all_vertices[vertex_indices[2]](2),
all_vertices[vertex_indices[3]](2),
all_vertices[vertex_indices[4]](2),
all_vertices[vertex_indices[5]](2),
all_vertices[vertex_indices[6]](2),
all_vertices[vertex_indices[7]](2)
};
/*
This is the same Maple script as in the barycenter method above
except of that here the shape functions tphi[0]-tphi[7] are ordered
according to the lexicographic numbering.
x := array(0..7):
y := array(0..7):
z := array(0..7):
tphi[0] := (1-xi)*(1-eta)*(1-zeta):
tphi[1] := xi*(1-eta)*(1-zeta):
tphi[2] := (1-xi)* eta*(1-zeta):
tphi[3] := xi* eta*(1-zeta):
tphi[4] := (1-xi)*(1-eta)*zeta:
tphi[5] := xi*(1-eta)*zeta:
tphi[6] := (1-xi)* eta*zeta:
tphi[7] := xi* eta*zeta:
x_real := sum(x[s]*tphi[s], s=0..7):
y_real := sum(y[s]*tphi[s], s=0..7):
z_real := sum(z[s]*tphi[s], s=0..7):
with (linalg):
J := matrix(3,3, [[diff(x_real, xi), diff(x_real, eta), diff(x_real, zeta)],
[diff(y_real, xi), diff(y_real, eta), diff(y_real, zeta)],
[diff(z_real, xi), diff(z_real, eta), diff(z_real, zeta)]]):
detJ := det (J):
measure := simplify ( int ( int ( int (detJ, xi=0..1), eta=0..1), zeta=0..1)):
readlib(C):
C(measure, optimized);
The C code produced by this maple script is further optimized by
hand. In particular, division by 12 is performed only once, not
hundred of times.
*/
const double t3 = y[3]*x[2];
const double t5 = z[1]*x[5];
const double t9 = z[3]*x[2];
const double t11 = x[1]*y[0];
const double t14 = x[4]*y[0];
const double t18 = x[5]*y[7];
const double t20 = y[1]*x[3];
const double t22 = y[5]*x[4];
const double t26 = z[7]*x[6];
const double t28 = x[0]*y[4];
const double t34 = z[3]*x[1]*y[2]+t3*z[1]-t5*y[7]+y[7]*x[4]*z[6]+t9*y[6]-t11*z[4]-t5*y[3]-t14*z[2]+z[1]*x[4]*y[0]-t18*z[3]+t20*z[0]-t22*z[0]-y[0]*x[5]*z[4]-t26*y[3]+t28*z[2]-t9*y[1]-y[1]*x[4]*z[0]-t11*z[5];
const double t37 = y[1]*x[0];
const double t44 = x[1]*y[5];
const double t46 = z[1]*x[0];
const double t49 = x[0]*y[2];
const double t52 = y[5]*x[7];
const double t54 = x[3]*y[7];
const double t56 = x[2]*z[0];
const double t58 = x[3]*y[2];
const double t64 = -x[6]*y[4]*z[2]-t37*z[2]+t18*z[6]-x[3]*y[6]*z[2]+t11*z[2]+t5*y[0]+t44*z[4]-t46*y[4]-t20*z[7]-t49*z[6]-t22*z[1]+t52*z[3]-t54*z[2]-t56*y[4]-t58*z[0]+y[1]*x[2]*z[0]+t9*y[7]+t37*z[4];
const double t66 = x[1]*y[7];
const double t68 = y[0]*x[6];
const double t70 = x[7]*y[6];
const double t73 = z[5]*x[4];
const double t76 = x[6]*y[7];
const double t90 = x[4]*z[0];
const double t92 = x[1]*y[3];
const double t95 = -t66*z[3]-t68*z[2]-t70*z[2]+t26*y[5]-t73*y[6]-t14*z[6]+t76*z[2]-t3*z[6]+x[6]*y[2]*z[4]-z[3]*x[6]*y[2]+t26*y[4]-t44*z[3]-x[1]*y[2]*z[0]+x[5]*y[6]*z[4]+t54*z[5]+t90*y[2]-t92*z[2]+t46*y[2];
const double t102 = x[2]*y[0];
const double t107 = y[3]*x[7];
const double t114 = x[0]*y[6];
const double t125 = y[0]*x[3]*z[2]-z[7]*x[5]*y[6]-x[2]*y[6]*z[4]+t102*z[6]-t52*z[6]+x[2]*y[4]*z[6]-t107*z[5]-t54*z[6]+t58*z[6]-x[7]*y[4]*z[6]+t37*z[5]-t114*z[4]+t102*z[4]-z[1]*x[2]*y[0]+t28*z[6]-y[5]*x[6]*z[4]-z[5]*x[1]*y[4]-t73*y[7];
const double t129 = z[0]*x[6];
const double t133 = y[1]*x[7];
const double t145 = y[1]*x[5];
const double t156 = t90*y[6]-t129*y[4]+z[7]*x[2]*y[6]-t133*z[5]+x[5]*y[3]*z[7]-t26*y[2]-t70*z[3]+t46*y[3]+z[5]*x[7]*y[4]+z[7]*x[3]*y[6]-t49*z[4]+t145*z[7]-x[2]*y[7]*z[6]+t70*z[5]+t66*z[5]-z[7]*x[4]*y[6]+t18*z[4]+x[1]*y[4]*z[0];
const double t160 = x[5]*y[4];
const double t165 = z[1]*x[7];
const double t178 = z[1]*x[3];
const double t181 = t107*z[6]+t22*z[7]+t76*z[3]+t160*z[1]-x[4]*y[2]*z[6]+t70*z[4]+t165*y[5]+x[7]*y[2]*z[6]-t76*z[5]-t76*z[4]+t133*z[3]-t58*z[1]+y[5]*x[0]*z[4]+t114*z[2]-t3*z[7]+t20*z[2]+t178*y[7]+t129*y[2];
const double t207 = t92*z[7]+t22*z[6]+z[3]*x[0]*y[2]-x[0]*y[3]*z[2]-z[3]*x[7]*y[2]-t165*y[3]-t9*y[0]+t58*z[7]+y[3]*x[6]*z[2]+t107*z[2]+t73*y[0]-x[3]*y[5]*z[7]+t3*z[0]-t56*y[6]-z[5]*x[0]*y[4]+t73*y[1]-t160*z[6]+t160*z[0];
const double t228 = -t44*z[7]+z[5]*x[6]*y[4]-t52*z[4]-t145*z[4]+t68*z[4]+t92*z[5]-t92*z[0]+t11*z[3]+t44*z[0]+t178*y[5]-t46*y[5]-t178*y[0]-t145*z[0]-t20*z[5]-t37*z[3]-t160*z[7]+t145*z[3]+x[4]*y[6]*z[2];
return (t34+t64+t95+t125+t156+t181+t207+t228)/12.;
}
template <>
double
cell_measure(const std::vector<Point<2> > &all_vertices,
const unsigned int (&vertex_indices) [GeometryInfo<2>::vertices_per_cell])
{
/*
Get the computation of the measure by this little Maple script. We
use the blinear mapping of the unit quad to the real quad. However,
every transformation mapping the unit faces to straight lines should
do.
Remember that the area of the quad is given by
\int_K 1 dx dy = \int_{\hat K} |det J| d(xi) d(eta)
# x and y are arrays holding the x- and y-values of the four vertices
# of this cell in real space.
x := array(0..3);
y := array(0..3);
z := array(0..3);
tphi[0] := (1-xi)*(1-eta):
tphi[1] := xi*(1-eta):
tphi[2] := (1-xi)*eta:
tphi[3] := xi*eta:
x_real := sum(x[s]*tphi[s], s=0..3):
y_real := sum(y[s]*tphi[s], s=0..3):
z_real := sum(z[s]*tphi[s], s=0..3):
Jxi := <diff(x_real,xi) | diff(y_real,xi) | diff(z_real,xi)>;
Jeta := <diff(x_real,eta)| diff(y_real,eta)| diff(z_real,eta)>;
with(VectorCalculus):
J := CrossProduct(Jxi, Jeta);
detJ := sqrt(J[1]^2 + J[2]^2 +J[3]^2);
# measure := evalf (Int (Int (detJ, xi=0..1, method = _NCrule ) , eta=0..1, method = _NCrule ) ):
# readlib(C):
# C(measure, optimized);
additional optimizaton: divide by 2 only one time
*/
const double x[4] = { all_vertices[vertex_indices[0]](0),
all_vertices[vertex_indices[1]](0),
all_vertices[vertex_indices[2]](0),
all_vertices[vertex_indices[3]](0)
};
const double y[4] = { all_vertices[vertex_indices[0]](1),
all_vertices[vertex_indices[1]](1),
all_vertices[vertex_indices[2]](1),
all_vertices[vertex_indices[3]](1)
};
return (-x[1]*y[0]+x[1]*y[3]+y[0]*x[2]+x[0]*y[1]-x[0]*y[2]-y[1]*x[3]-x[2]*y[3]+x[3]*y[2])/2;
}
template <int dim>
double
cell_measure(const std::vector<Point<dim> > &,
const unsigned int ( &) [GeometryInfo<dim>::vertices_per_cell])
{
Assert(false, ExcNotImplemented());
return 0.;
}
template <int dim, int spacedim>
void
delete_unused_vertices (std::vector<Point<spacedim> > &vertices,
std::vector<CellData<dim> > &cells,
SubCellData &subcelldata)
{
// first check which vertices are
// actually used
std::vector<bool> vertex_used (vertices.size(), false);
for (unsigned int c=0; c<cells.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
vertex_used[cells[c].vertices[v]] = true;
// then renumber the vertices that
// are actually used in the same
// order as they were beforehand
const unsigned int invalid_vertex = numbers::invalid_unsigned_int;
std::vector<unsigned int> new_vertex_numbers (vertices.size(), invalid_vertex);
unsigned int next_free_number = 0;
for (unsigned int i=0; i<vertices.size(); ++i)
if (vertex_used[i] == true)
{
new_vertex_numbers[i] = next_free_number;
++next_free_number;
};
// next replace old vertex numbers
// by the new ones
for (unsigned int c=0; c<cells.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
cells[c].vertices[v] = new_vertex_numbers[cells[c].vertices[v]];
// same for boundary data
for (unsigned int c=0; c<subcelldata.boundary_lines.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<1>::vertices_per_cell; ++v)
subcelldata.boundary_lines[c].vertices[v]
= new_vertex_numbers[subcelldata.boundary_lines[c].vertices[v]];
for (unsigned int c=0; c<subcelldata.boundary_quads.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<2>::vertices_per_cell; ++v)
subcelldata.boundary_quads[c].vertices[v]
= new_vertex_numbers[subcelldata.boundary_quads[c].vertices[v]];
// finally copy over the vertices
// which we really need to a new
// array and replace the old one by
// the new one
std::vector<Point<spacedim> > tmp;
tmp.reserve (std::count(vertex_used.begin(), vertex_used.end(), true));
for (unsigned int v=0; v<vertices.size(); ++v)
if (vertex_used[v] == true)
tmp.push_back (vertices[v]);
swap (vertices, tmp);
}
template <int dim, int spacedim>
void
delete_duplicated_vertices (std::vector<Point<spacedim> > &vertices,
std::vector<CellData<dim> > &cells,
SubCellData &subcelldata,
std::vector<unsigned int> &considered_vertices,
double tol)
{
// create a vector of vertex
// indices. initialize it to the identity,
// later on change that if necessary.
std::vector<unsigned int> new_vertex_numbers(vertices.size());
for (unsigned int i=0; i<vertices.size(); ++i)
new_vertex_numbers[i]=i;
// if the considered_vertices vector is
// empty, consider all vertices
if (considered_vertices.size()==0)
considered_vertices=new_vertex_numbers;
// now loop over all vertices to be
// considered and try to find an identical
// one
for (unsigned int i=0; i<considered_vertices.size(); ++i)
{
if (new_vertex_numbers[considered_vertices[i]]!=considered_vertices[i])
// this vertex has been identified with
// another one already, skip it in the
// test
continue;
// this vertex is not identified with
// another one so far. search in the list
// of remaining vertices. if a duplicate
// vertex is found, set the new vertex
// index for that vertex to this vertex'
// index.
for (unsigned int j=i+1; j<considered_vertices.size(); ++j)
{
bool equal=true;
for (unsigned int d=0; d<spacedim; ++d)
equal &= (fabs(vertices[considered_vertices[j]](d)-vertices[considered_vertices[i]](d))<tol);
if (equal)
{
new_vertex_numbers[considered_vertices[j]]=considered_vertices[i];
// we do not suppose, that there might be another duplicate
// vertex, so break here
break;
}
}
}
// now we got a renumbering list. simply
// renumber all vertices (non-duplicate
// vertices get renumbered to themselves, so
// nothing bad happens). after that, the
// duplicate vertices will be unused, so call
// delete_unused_vertices() to do that part
// of the job.
for (unsigned int c=0; c<cells.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
cells[c].vertices[v]=new_vertex_numbers[cells[c].vertices[v]];
delete_unused_vertices(vertices,cells,subcelldata);
}
// define some transformations in an anonymous namespace
namespace
{
template <int spacedim>
class ShiftPoint
{
public:
ShiftPoint (const Point<spacedim> &shift)
:
shift(shift)
{}
Point<spacedim> operator() (const Point<spacedim> p) const
{
return p+shift;
}
private:
const Point<spacedim> shift;
};
// the following class is only
// needed in 2d, so avoid trouble
// with compilers warning otherwise
class Rotate2d
{
public:
Rotate2d (const double angle)
:
angle(angle)
{}
Point<2> operator() (const Point<2> &p) const
{
return Point<2> (std::cos(angle)*p(0) - std::sin(angle) * p(1),
std::sin(angle)*p(0) + std::cos(angle) * p(1));
}
private:
const double angle;
};
template <int spacedim>
class ScalePoint
{
public:
ScalePoint (const double factor)
:
factor(factor)
{}
Point<spacedim> operator() (const Point<spacedim> p) const
{
return p*factor;
}
private:
const double factor;
};
}
template <int dim, int spacedim>
void
shift (const Point<spacedim> &shift_vector,
Triangulation<dim, spacedim> &triangulation)
{
transform (ShiftPoint<spacedim>(shift_vector), triangulation);
}
void
rotate (const double angle,
Triangulation<2> &triangulation)
{
transform (Rotate2d(angle), triangulation);
}
template <int dim, int spacedim>
void
scale (const double scaling_factor,
Triangulation<dim, spacedim> &triangulation)
{
Assert (scaling_factor>0, ExcScalingFactorNotPositive (scaling_factor));
transform (ScalePoint<spacedim>(scaling_factor), triangulation);
}
template <int dim>
void
laplace_transform (const std::map<unsigned int,Point<dim> > &new_points,
Triangulation<dim> &triangulation,
const Function<dim> *coefficient)
{
//TODO: Move implementation of this function into the current
// namespace
GridGenerator::laplace_transformation(triangulation, new_points, coefficient);
}
/**
* Distort a triangulation in
* some random way.
*/
template <int dim, int spacedim>
void
distort_random (const double factor,
Triangulation<dim,spacedim> &triangulation,
const bool keep_boundary)
{
// if spacedim>dim we need to make sure that we perturb
// points but keep them on
// the manifold. however, this isn't implemented right now
Assert (spacedim == dim, ExcNotImplemented());
// find the smallest length of the
// lines adjacent to the
// vertex. take the initial value
// to be larger than anything that
// might be found: the diameter of
// the triangulation, here
// estimated by adding up the
// diameters of the coarse grid
// cells.
double almost_infinite_length = 0;
for (typename Triangulation<dim,spacedim>::cell_iterator
cell=triangulation.begin(0); cell!=triangulation.end(0); ++cell)
almost_infinite_length += cell->diameter();
std::vector<double> minimal_length (triangulation.n_vertices(),
almost_infinite_length);
// also note if a vertex is at the boundary
std::vector<bool> at_boundary (triangulation.n_vertices(), false);
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell=triangulation.begin_active(); cell!=triangulation.end(); ++cell)
if (cell->is_locally_owned())
{
if (dim>1)
{
for (unsigned int i=0; i<GeometryInfo<dim>::lines_per_cell; ++i)
{
const typename Triangulation<dim,spacedim>::line_iterator line
= cell->line(i);
if (keep_boundary && line->at_boundary())
{
at_boundary[line->vertex_index(0)] = true;
at_boundary[line->vertex_index(1)] = true;
}
minimal_length[line->vertex_index(0)]
= std::min(line->diameter(),
minimal_length[line->vertex_index(0)]);
minimal_length[line->vertex_index(1)]
= std::min(line->diameter(),
minimal_length[line->vertex_index(1)]);
}
}
else //dim==1
{
if (keep_boundary)
for (unsigned int vertex=0; vertex<2; ++vertex)
if (cell->at_boundary(vertex) == true)
at_boundary[cell->vertex_index(vertex)] = true;
minimal_length[cell->vertex_index(0)]
= std::min(cell->diameter(),
minimal_length[cell->vertex_index(0)]);
minimal_length[cell->vertex_index(1)]
= std::min(cell->diameter(),
minimal_length[cell->vertex_index(1)]);
}
}
// If the triangulation is distributed, we need to
// exchange the moved vertices across mpi processes
if (parallel::distributed::Triangulation< dim, spacedim > *distributed_triangulation
= dynamic_cast<parallel::distributed::Triangulation<dim,spacedim>*> (&triangulation))
{
// create a random number generator for the interval [-1,1]. we use
// this to make sure the distribution we get is repeatable, i.e.,
// if you call the function twice on the same mesh, then you will
// get the same mesh. this would not be the case if you used
// the rand() function, which carries around some internal state
boost::random::mt19937 rng;
boost::random::uniform_real_distribution<> uniform_distribution(-1,1);
const std::vector<bool> locally_owned_vertices = get_locally_owned_vertices(triangulation);
std::vector<bool> vertex_moved (triangulation.n_vertices(), false);
// Next move vertices on locally owned cells
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell=triangulation.begin_active(); cell!=triangulation.end(); ++cell)
if (cell->is_locally_owned())
{
for (unsigned int vertex_no=0; vertex_no<GeometryInfo<dim>::vertices_per_cell;
++vertex_no)
{
const unsigned global_vertex_no = cell->vertex_index(vertex_no);
// ignore this vertex if we shall keep the boundary and
// this vertex *is* at the boundary, if it is already moved
// or if another process moves this vertex
if ((keep_boundary && at_boundary[global_vertex_no])
|| vertex_moved[global_vertex_no]
|| !locally_owned_vertices[global_vertex_no])
continue;
// first compute a random shift vector
Point<spacedim> shift_vector;
for (unsigned int d=0; d<spacedim; ++d)
shift_vector(d) = uniform_distribution(rng);
shift_vector *= factor * minimal_length[global_vertex_no] /
std::sqrt(shift_vector.square());
// finally move the vertex
cell->vertex(vertex_no) += shift_vector;
vertex_moved[global_vertex_no] = true;
}
}
#if DEAL_II_USE_P4EST
distributed_triangulation
->communicate_locally_moved_vertices(locally_owned_vertices);
#else
Assert (false, ExcInternalError());
#endif
}
else
// if this is a sequential triangulation, we could in principle
// use the algorithm above, but we'll use an algorithm that we used
// before the parallel::distributed::Triangulation was introduced
// in order to preserve backward compatibility
{
// loop over all vertices and compute their new locations
const unsigned int n_vertices = triangulation.n_vertices();
std::vector<Point<spacedim> > new_vertex_locations (n_vertices);
const std::vector<Point<spacedim> > &old_vertex_locations
= triangulation.get_vertices();
for (unsigned int vertex=0; vertex<n_vertices; ++vertex)
{
// ignore this vertex if we will keep the boundary and
// this vertex *is* at the boundary
if (keep_boundary && at_boundary[vertex])
new_vertex_locations[vertex] = old_vertex_locations[vertex];
else
{
// compute a random shift vector
Point<spacedim> shift_vector;
for (unsigned int d=0; d<spacedim; ++d)
shift_vector(d) = std::rand()*2.0/RAND_MAX-1;
shift_vector *= factor * minimal_length[vertex] /
std::sqrt(shift_vector.square());
// record new vertex location
new_vertex_locations[vertex] = old_vertex_locations[vertex] + shift_vector;
}
}
// now do the actual move of the vertices
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell=triangulation.begin_active(); cell!=triangulation.end(); ++cell)
for (unsigned int vertex_no=0;
vertex_no<GeometryInfo<dim>::vertices_per_cell; ++vertex_no)
cell->vertex(vertex_no) = new_vertex_locations[cell->vertex_index(vertex_no)];
}
// Correct hanging nodes if necessary
if (dim>=2)
{
// We do the same as in GridTools::transform
//
// exclude hanging nodes at the boundaries of artificial cells:
// these may belong to ghost cells for which we know the exact
// location of vertices, whereas the artificial cell may or may
// not be further refined, and so we cannot know whether
// the location of the hanging node is correct or not
typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active(),
endc = triangulation.end();
for (; cell!=endc; ++cell)
if (!cell->is_artificial())
for (unsigned int face=0;
face<GeometryInfo<dim>::faces_per_cell; ++face)
if (cell->face(face)->has_children() &&
!cell->face(face)->at_boundary())
{
// this face has hanging nodes
if (dim==2)
cell->face(face)->child(0)->vertex(1)
= (cell->face(face)->vertex(0) +
cell->face(face)->vertex(1)) / 2;
else if (dim==3)
{
cell->face(face)->child(0)->vertex(1)
= .5*(cell->face(face)->vertex(0)
+cell->face(face)->vertex(1));
cell->face(face)->child(0)->vertex(2)
= .5*(cell->face(face)->vertex(0)
+cell->face(face)->vertex(2));
cell->face(face)->child(1)->vertex(3)
= .5*(cell->face(face)->vertex(1)
+cell->face(face)->vertex(3));
cell->face(face)->child(2)->vertex(3)
= .5*(cell->face(face)->vertex(2)
+cell->face(face)->vertex(3));
// center of the face
cell->face(face)->child(0)->vertex(3)
= .25*(cell->face(face)->vertex(0)
+cell->face(face)->vertex(1)
+cell->face(face)->vertex(2)
+cell->face(face)->vertex(3));
}
}
}
}
template <int dim, template <int, int> class Container, int spacedim>
unsigned int
find_closest_vertex (const Container<dim,spacedim> &container,
const Point<spacedim> &p)
{
// first get the underlying
// triangulation from the
// container and determine vertices
// and used vertices
const Triangulation<dim, spacedim> &tria = get_tria(container);
const std::vector< Point<spacedim> > &vertices = tria.get_vertices();
const std::vector< bool > &used = tria.get_used_vertices();
// At the beginning, the first
// used vertex is the closest one
std::vector<bool>::const_iterator first =
std::find(used.begin(), used.end(), true);
// Assert that at least one vertex
// is actually used
Assert(first != used.end(), ExcInternalError());
unsigned int best_vertex = std::distance(used.begin(), first);
double best_dist = (p - vertices[best_vertex]).square();
// For all remaining vertices, test
// whether they are any closer
for (unsigned int j = best_vertex+1; j < vertices.size(); j++)
if (used[j])
{
double dist = (p - vertices[j]).square();
if (dist < best_dist)
{
best_vertex = j;
best_dist = dist;
}
}
return best_vertex;
}
template<int dim, template<int, int> class Container, int spacedim>
std::vector<typename Container<dim,spacedim>::active_cell_iterator>
find_cells_adjacent_to_vertex(const Container<dim,spacedim> &container,
const unsigned int vertex)
{
// make sure that the given vertex is
// an active vertex of the underlying
// triangulation
Assert(vertex < get_tria(container).n_vertices(),
ExcIndexRange(0,get_tria(container).n_vertices(),vertex));
Assert(get_tria(container).get_used_vertices()[vertex],
ExcVertexNotUsed(vertex));
// use a set instead of a vector
// to ensure that cells are inserted only
// once
std::set<typename Container<dim,spacedim>::active_cell_iterator> adjacent_cells;
typename Container<dim,spacedim>::active_cell_iterator
cell = container.begin_active(),
endc = container.end();
// go through all active cells and look if the vertex is part of that cell
//
// in 1d, this is all we need to care about. in 2d/3d we also need to worry
// that the vertex might be a hanging node on a face or edge of a cell; in
// this case, we would want to add those cells as well on whose faces the
// vertex is located but for which it is not a vertex itself.
//
// getting this right is a lot simpler in 2d than in 3d. in 2d, a hanging
// node can only be in the middle of a face and we can query the neighboring
// cell from the current cell. on the other hand, in 3d a hanging node
// vertex can also be on an edge but there can be many other cells on
// this edge and we can not access them from the cell we are currently
// on.
//
// so, in the 3d case, if we run the algorithm as in 2d, we catch all
// those cells for which the vertex we seek is on a *subface*, but we
// miss the case of cells for which the vertex we seek is on a
// sub-edge for which there is no corresponding sub-face (because the
// immediate neighbor behind this face is not refined), see for example
// the bits/find_cells_adjacent_to_vertex_6 testcase. thus, if we
// haven't yet found the vertex for the current cell we also need to
// look at the mid-points of edges
//
// as a final note, deciding whether a neighbor is actually coarser is
// simple in the case of isotropic refinement (we just need to look at
// the level of the current and the neighboring cell). however, this
// isn't so simple if we have used anisotropic refinement since then
// the level of a cell is not indicative of whether it is coarser or
// not than the current cell. ultimately, we want to add all cells on
// which the vertex is, independent of whether they are coarser or
// finer and so in the 2d case below we simply add *any* *active* neighbor.
// in the worst case, we add cells multiple times to the adjacent_cells
// list, but std::set throws out those cells already entered
for (; cell != endc; ++cell)
{
for (unsigned int v = 0; v < GeometryInfo<dim>::vertices_per_cell; v++)
if (cell->vertex_index(v) == vertex)
{
// OK, we found a cell that contains
// the given vertex. We add it
// to the list.
adjacent_cells.insert(cell);
// as explained above, in 2+d we need to check whether
// this vertex is on a face behind which there is a
// (possibly) coarser neighbor. if this is the case,
// then we need to also add this neighbor
if (dim >= 2)
for (unsigned int vface = 0; vface < dim; vface++)
{
const unsigned int face =
GeometryInfo<dim>::vertex_to_face[v][vface];
if (!cell->at_boundary(face)
&&
cell->neighbor(face)->active())
{
// there is a (possibly) coarser cell behind a
// face to which the vertex belongs. the
// vertex we are looking at is then either a
// vertex of that coarser neighbor, or it is a
// hanging node on one of the faces of that
// cell. in either case, it is adjacent to the
// vertex, so add it to the list as well (if
// the cell was already in the list then the
// std::set makes sure that we get it only
// once)
adjacent_cells.insert (cell->neighbor(face));
}
}
// in any case, we have found a cell, so go to the next cell
goto next_cell;
}
// in 3d also loop over the edges
if (dim >= 3)
{
for (unsigned int e=0; e<GeometryInfo<dim>::lines_per_cell; ++e)
if (cell->line(e)->has_children())
// the only place where this vertex could have been
// hiding is on the mid-edge point of the edge we
// are looking at
if (cell->line(e)->child(0)->vertex_index(1) == vertex)
{
adjacent_cells.insert(cell);
// jump out of this tangle of nested loops
goto next_cell;
}
}
// in more than 3d we would probably have to do the same as
// above also for even lower-dimensional objects
Assert (dim <= 3, ExcNotImplemented());
// move on to the next cell if we have found the
// vertex on the current one
next_cell:
;
}
// if this was an active vertex then there needs to have been
// at least one cell to which it is adjacent!
Assert (adjacent_cells.size() > 0, ExcInternalError());
// return the result as a vector, rather than the set we built above
return
std::vector<typename Container<dim,spacedim>::active_cell_iterator>
(adjacent_cells.begin(), adjacent_cells.end());
}
namespace
{
template <int dim, template<int, int> class Container, int spacedim>
void find_active_cell_around_point_internal(const Container<dim,spacedim> &container,
std::set<typename Container<dim,spacedim>::active_cell_iterator> &searched_cells,
std::set<typename Container<dim,spacedim>::active_cell_iterator> &adjacent_cells)
{
typedef typename Container<dim,spacedim>::active_cell_iterator cell_iterator;
// update the searched cells
searched_cells.insert(adjacent_cells.begin(), adjacent_cells.end());
// now we to collect all neighbors
// of the cells in adjacent_cells we
// have not yet searched.
std::set<cell_iterator> adjacent_cells_new;
typename std::set<cell_iterator>::const_iterator
cell = adjacent_cells.begin(),
endc = adjacent_cells.end();
for (; cell != endc; ++cell)
{
std::vector<cell_iterator> active_neighbors;
get_active_neighbors<Container<dim, spacedim> >(*cell, active_neighbors);
for (unsigned int i=0; i<active_neighbors.size(); ++i)
if (searched_cells.find(active_neighbors[i]) == searched_cells.end())
adjacent_cells_new.insert(active_neighbors[i]);
}
adjacent_cells.clear();
adjacent_cells.insert(adjacent_cells_new.begin(), adjacent_cells_new.end());
if (adjacent_cells.size() == 0)
{
// we haven't found any other cell that would be a
// neighbor of a previously found cell, but we know
// that we haven't checked all cells yet. that means
// that the domain is disconnected. in that case,
// choose the first previously untouched cell we
// can find
cell_iterator it = container.begin_active();
for ( ; it!=container.end(); ++it)
if (searched_cells.find(it) == searched_cells.end())
{
adjacent_cells.insert(it);
break;
}
}
}
}
template <int dim, template<int, int> class Container, int spacedim>
typename Container<dim,spacedim>::active_cell_iterator
find_active_cell_around_point (const Container<dim,spacedim> &container,
const Point<spacedim> &p)
{
return
find_active_cell_around_point<dim,Container,spacedim>
(StaticMappingQ1<dim,spacedim>::mapping,
container, p).first;
}
template <int dim, template <int, int> class Container, int spacedim>
std::pair<typename Container<dim,spacedim>::active_cell_iterator, Point<dim> >
find_active_cell_around_point (const Mapping<dim,spacedim> &mapping,
const Container<dim,spacedim> &container,
const Point<spacedim> &p)
{
typedef typename Container<dim,spacedim>::active_cell_iterator active_cell_iterator;
// The best distance is set to the
// maximum allowable distance from
// the unit cell; we assume a
// max. deviation of 1e-10
double best_distance = 1e-10;
int best_level = -1;
std::pair<active_cell_iterator, Point<dim> > best_cell;
// Find closest vertex and determine
// all adjacent cells
std::vector<active_cell_iterator> adjacent_cells_tmp
= find_cells_adjacent_to_vertex(container,
find_closest_vertex(container, p));
// Make sure that we have found
// at least one cell adjacent to vertex.
Assert(adjacent_cells_tmp.size()>0, ExcInternalError());
// Copy all the cells into a std::set
std::set<active_cell_iterator> adjacent_cells (adjacent_cells_tmp.begin(),
adjacent_cells_tmp.end());
std::set<active_cell_iterator> searched_cells;
// Determine the maximal number of cells
// in the grid.
// As long as we have not found
// the cell and have not searched
// every cell in the triangulation,
// we keep on looking.
const unsigned int n_active_cells = get_tria(container).n_active_cells();
bool found = false;
unsigned int cells_searched = 0;
while (!found && cells_searched < n_active_cells)
{
typename std::set<active_cell_iterator>::const_iterator
cell = adjacent_cells.begin(),
endc = adjacent_cells.end();
for (; cell != endc; ++cell)
{
try
{
const Point<dim> p_cell = mapping.transform_real_to_unit_cell(*cell, p);
// calculate the infinity norm of
// the distance vector to the unit cell.
const double dist = GeometryInfo<dim>::distance_to_unit_cell(p_cell);
// We compare if the point is inside the
// unit cell (or at least not too far
// outside). If it is, it is also checked
// that the cell has a more refined state
if ((dist < best_distance)
||
((dist == best_distance)
&&
((*cell)->level() > best_level)))
{
found = true;
best_distance = dist;
best_level = (*cell)->level();
best_cell = std::make_pair(*cell, p_cell);
}
}
catch (typename MappingQ1<dim,spacedim>::ExcTransformationFailed &)
{
// ok, the transformation
// failed presumably
// because the point we
// are looking for lies
// outside the current
// cell. this means that
// the current cell can't
// be the cell around the
// point, so just ignore
// this cell and move on
// to the next
}
}
// update the number of cells searched
cells_searched += adjacent_cells.size();
// if we have not found the cell in
// question and have not yet searched every
// cell, we expand our search to
// all the not already searched neighbors of
// the cells in adjacent_cells. This is
// what find_active_cell_around_point_internal
// is for.
if (!found && cells_searched < n_active_cells)
{
find_active_cell_around_point_internal<dim,Container,spacedim>
(container, searched_cells, adjacent_cells);
}
}
AssertThrow (best_cell.first.state() == IteratorState::valid,
ExcPointNotFound<spacedim>(p));
return best_cell;
}
template <int dim, int spacedim>
std::pair<typename hp::DoFHandler<dim,spacedim>::active_cell_iterator, Point<dim> >
find_active_cell_around_point (const hp::MappingCollection<dim,spacedim> &mapping,
const hp::DoFHandler<dim,spacedim> &container,
const Point<spacedim> &p)
{
Assert ((mapping.size() == 1) ||
(mapping.size() == container.get_fe().size()),
ExcMessage ("Mapping collection needs to have either size 1 "
"or size equal to the number of elements in "
"the FECollection."));
typedef typename hp::DoFHandler<dim,spacedim>::active_cell_iterator cell_iterator;
std::pair<cell_iterator, Point<dim> > best_cell;
//If we have only one element in the MappingCollection,
//we use find_active_cell_around_point using only one
//mapping.
if (mapping.size() == 1)
best_cell = find_active_cell_around_point(mapping[0], container, p);
else
{
// The best distance is set to the
// maximum allowable distance from
// the unit cell; we assume a
// max. deviation of 1e-10
double best_distance = 1e-10;
int best_level = -1;
// Find closest vertex and determine
// all adjacent cells
unsigned int vertex = find_closest_vertex(container, p);
std::vector<cell_iterator> adjacent_cells_tmp =
find_cells_adjacent_to_vertex(container, vertex);
// Make sure that we have found
// at least one cell adjacent to vertex.
Assert(adjacent_cells_tmp.size()>0, ExcInternalError());
// Copy all the cells into a std::set
std::set<cell_iterator> adjacent_cells(adjacent_cells_tmp.begin(), adjacent_cells_tmp.end());
std::set<cell_iterator> searched_cells;
// Determine the maximal number of cells
// in the grid.
// As long as we have not found
// the cell and have not searched
// every cell in the triangulation,
// we keep on looking.
const unsigned int n_cells =get_tria(container).n_cells();
bool found = false;
unsigned int cells_searched = 0;
while (!found && cells_searched < n_cells)
{
typename std::set<cell_iterator>::const_iterator
cell = adjacent_cells.begin(),
endc = adjacent_cells.end();
for (; cell != endc; ++cell)
{
try
{
const Point<dim> p_cell = mapping[(*cell)->active_fe_index()].transform_real_to_unit_cell(*cell, p);
// calculate the infinity norm of
// the distance vector to the unit cell.
const double dist = GeometryInfo<dim>::distance_to_unit_cell(p_cell);
// We compare if the point is inside the
// unit cell (or at least not too far
// outside). If it is, it is also checked
// that the cell has a more refined state
if (dist < best_distance ||
(dist == best_distance && (*cell)->level() > best_level))
{
found = true;
best_distance = dist;
best_level = (*cell)->level();
best_cell = std::make_pair(*cell, p_cell);
}
}
catch (typename MappingQ1<dim,spacedim>::ExcTransformationFailed &)
{
// ok, the transformation
// failed presumably
// because the point we
// are looking for lies
// outside the current
// cell. this means that
// the current cell can't
// be the cell around the
// point, so just ignore
// this cell and move on
// to the next
}
}
//udpate the number of cells searched
cells_searched += adjacent_cells.size();
// if we have not found the cell in
// question and have not yet searched every
// cell, we expand our search to
// all the not already searched neighbors of
// the cells in adjacent_cells.
if (!found && cells_searched < n_cells)
{
find_active_cell_around_point_internal<dim,hp::DoFHandler,spacedim>
(container, searched_cells, adjacent_cells);
}
}
}
AssertThrow (best_cell.first.state() == IteratorState::valid,
ExcPointNotFound<spacedim>(p));
return best_cell;
}
template <int dim, int spacedim>
void
get_face_connectivity_of_cells (const Triangulation<dim,spacedim> &triangulation,
SparsityPattern &cell_connectivity)
{
// as built in this function, we
// only consider face neighbors,
// which leads to a fixed number of
// entries per row (don't forget
// that each cell couples with
// itself, and that neighbors can
// be refined)
cell_connectivity.reinit (triangulation.n_active_cells(),
triangulation.n_active_cells(),
GeometryInfo<dim>::faces_per_cell
* GeometryInfo<dim>::max_children_per_face
+
1);
// create a map pair<lvl,idx> -> SparsityPattern index
// TODO: we are no longer using user_indices for this because we can get
// pointer/index clashes when saving/restoring them. The following approach
// works, but this map can get quite big. Not sure about more efficient solutions.
std::map< std::pair<unsigned int,unsigned int>, unsigned int >
indexmap;
unsigned int index = 0;
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell, ++index)
indexmap[std::pair<unsigned int,unsigned int>(cell->level(),cell->index())] = index;
// next loop over all cells and
// their neighbors to build the
// sparsity pattern. note that it's
// a bit hard to enter all the
// connections when a neighbor has
// children since we would need to
// find out which of its children
// is adjacent to the current
// cell. this problem can be
// omitted if we only do something
// if the neighbor has no children
// -- in that case it is either on
// the same or a coarser level than
// we are. in return, we have to
// add entries in both directions
// for both cells
index = 0;
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell, ++index)
{
cell_connectivity.add (index, index);
for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)
if ((cell->at_boundary(f) == false)
&&
(cell->neighbor(f)->has_children() == false))
{
unsigned int other_index = indexmap.find(
std::pair<unsigned int,unsigned int>(cell->neighbor(f)->level(),cell->neighbor(f)->index()))->second;
cell_connectivity.add (index, other_index);
cell_connectivity.add (other_index, index);
}
}
// now compress the so-built connectivity pattern
cell_connectivity.compress ();
}
template <int dim, int spacedim>
void
partition_triangulation (const unsigned int n_partitions,
Triangulation<dim,spacedim> &triangulation)
{
Assert ((dynamic_cast<parallel::distributed::Triangulation<dim,spacedim>*>
(&triangulation)
== 0),
ExcMessage ("Objects of type parallel::distributed::Triangulation "
"are already partitioned implicitly and can not be "
"partitioned again explicitly."));
Assert (n_partitions > 0, ExcInvalidNumberOfPartitions(n_partitions));
// check for an easy return
if (n_partitions == 1)
{
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell)
cell->set_subdomain_id (0);
return;
}
// we decompose the domain by first
// generating the connection graph of all
// cells with their neighbors, and then
// passing this graph off to METIS.
// finally defer to the other function for
// partitioning and assigning subdomain ids
SparsityPattern cell_connectivity;
get_face_connectivity_of_cells (triangulation, cell_connectivity);
partition_triangulation (n_partitions,
cell_connectivity,
triangulation);
}
template <int dim, int spacedim>
void
partition_triangulation (const unsigned int n_partitions,
const SparsityPattern &cell_connection_graph,
Triangulation<dim,spacedim> &triangulation)
{
Assert ((dynamic_cast<parallel::distributed::Triangulation<dim,spacedim>*>
(&triangulation)
== 0),
ExcMessage ("Objects of type parallel::distributed::Triangulation "
"are already partitioned implicitly and can not be "
"partitioned again explicitly."));
Assert (n_partitions > 0, ExcInvalidNumberOfPartitions(n_partitions));
Assert (cell_connection_graph.n_rows() == triangulation.n_active_cells(),
ExcMessage ("Connectivity graph has wrong size"));
Assert (cell_connection_graph.n_cols() == triangulation.n_active_cells(),
ExcMessage ("Connectivity graph has wrong size"));
// check for an easy return
if (n_partitions == 1)
{
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell)
cell->set_subdomain_id (0);
return;
}
// partition this connection graph and get
// back a vector of indices, one per degree
// of freedom (which is associated with a
// cell)
std::vector<unsigned int> partition_indices (triangulation.n_active_cells());
SparsityTools::partition (cell_connection_graph, n_partitions, partition_indices);
// finally loop over all cells and set the
// subdomain ids
unsigned int index = 0;
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell, ++index)
cell->set_subdomain_id (partition_indices[index]);
}
template <int dim, int spacedim>
void
get_subdomain_association (const Triangulation<dim, spacedim> &triangulation,
std::vector<types::subdomain_id> &subdomain)
{
Assert (subdomain.size() == triangulation.n_active_cells(),
ExcDimensionMismatch (subdomain.size(),
triangulation.n_active_cells()));
unsigned int index = 0;
for (typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell!=triangulation.end(); ++cell, ++index)
subdomain[index] = cell->subdomain_id();
Assert (index == subdomain.size(), ExcInternalError());
}
template <int dim, int spacedim>
unsigned int
count_cells_with_subdomain_association (const Triangulation<dim, spacedim> &triangulation,
const types::subdomain_id subdomain)
{
unsigned int count = 0;
for (typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell!=triangulation.end(); ++cell)
if (cell->subdomain_id() == subdomain)
++count;
return count;
}
template <int dim, int spacedim>
std::vector<bool>
get_locally_owned_vertices (const Triangulation<dim,spacedim> &triangulation)
{
// start with all vertices
std::vector<bool> locally_owned_vertices = triangulation.get_used_vertices();
// if the triangulation is distributed, eliminate those that
// are owned by other processors -- either because the vertex is
// on an artificial cell, or because it is on a ghost cell with
// a smaller subdomain
if (const parallel::distributed::Triangulation<dim,spacedim> *tr
= dynamic_cast<const parallel::distributed::Triangulation<dim,spacedim> *>
(&triangulation))
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell)
if (cell->is_artificial()
||
(cell->is_ghost() &&
(cell->subdomain_id() < tr->locally_owned_subdomain())))
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
locally_owned_vertices[cell->vertex_index(v)] = false;
return locally_owned_vertices;
}
template <typename Container>
std::list<std::pair<typename Container::cell_iterator,
typename Container::cell_iterator> >
get_finest_common_cells (const Container &mesh_1,
const Container &mesh_2)
{
Assert (have_same_coarse_mesh (mesh_1, mesh_2),
ExcMessage ("The two containers must be represent triangulations that "
"have the same coarse meshes"));
// the algorithm goes as follows:
// first, we fill a list with pairs
// of iterators common to the two
// meshes on the coarsest
// level. then we traverse the
// list; each time, we find a pair
// of iterators for which both
// correspond to non-active cells,
// we delete this item and push the
// pairs of iterators to their
// children to the back. if these
// again both correspond to
// non-active cells, we will get to
// the later on for further
// consideration
typedef
std::list<std::pair<typename Container::cell_iterator,
typename Container::cell_iterator> >
CellList;
CellList cell_list;
// first push the coarse level cells
typename Container::cell_iterator
cell_1 = mesh_1.begin(0),
cell_2 = mesh_2.begin(0);
for (; cell_1 != mesh_1.end(0); ++cell_1, ++cell_2)
cell_list.push_back (std::make_pair (cell_1, cell_2));
// then traverse list as described
// above
typename CellList::iterator cell_pair = cell_list.begin();
while (cell_pair != cell_list.end())
{
// if both cells in this pair
// have children, then erase
// this element and push their
// children instead
if (cell_pair->first->has_children()
&&
cell_pair->second->has_children())
{
Assert(cell_pair->first->refinement_case()==
cell_pair->second->refinement_case(), ExcNotImplemented());
for (unsigned int c=0; c<cell_pair->first->n_children(); ++c)
cell_list.push_back (std::make_pair (cell_pair->first->child(c),
cell_pair->second->child(c)));
// erasing an iterator
// keeps other iterators
// valid, so already
// advance the present
// iterator by one and then
// delete the element we've
// visited before
const typename CellList::iterator previous_cell_pair = cell_pair;
++cell_pair;
cell_list.erase (previous_cell_pair);
}
else
// both cells are active, do
// nothing
++cell_pair;
}
// just to make sure everything is ok,
// validate that all pairs have at least one
// active iterator or have different
// refinement_cases
for (cell_pair = cell_list.begin(); cell_pair != cell_list.end(); ++cell_pair)
Assert (cell_pair->first->active()
||
cell_pair->second->active()
||
(cell_pair->first->refinement_case()
!= cell_pair->second->refinement_case()),
ExcInternalError());
return cell_list;
}
template <int dim, int spacedim>
bool
have_same_coarse_mesh (const Triangulation<dim, spacedim> &mesh_1,
const Triangulation<dim, spacedim> &mesh_2)
{
// make sure the two meshes have
// the same number of coarse cells
if (mesh_1.n_cells (0) != mesh_2.n_cells (0))
return false;
// if so, also make sure they have
// the same vertices on the cells
// of the coarse mesh
typename Triangulation<dim, spacedim>::cell_iterator
cell_1 = mesh_1.begin(0),
cell_2 = mesh_2.begin(0),
endc = mesh_1.end(0);
for (; cell_1!=endc; ++cell_1, ++cell_2)
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
if (cell_1->vertex(v) != cell_2->vertex(v))
return false;
// if we've gotten through all
// this, then the meshes really
// seem to have a common coarse
// mesh
return true;
}
template <typename Container>
bool
have_same_coarse_mesh (const Container &mesh_1,
const Container &mesh_2)
{
return have_same_coarse_mesh (get_tria(mesh_1),
get_tria(mesh_2));
}
template <int dim, int spacedim>
double
minimal_cell_diameter (const Triangulation<dim, spacedim> &triangulation)
{
double min_diameter = triangulation.begin_active()->diameter();
for (typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active(); cell != triangulation.end();
++cell)
min_diameter = std::min (min_diameter,
cell->diameter());
return min_diameter;
}
template <int dim, int spacedim>
double
maximal_cell_diameter (const Triangulation<dim, spacedim> &triangulation)
{
double max_diameter = triangulation.begin_active()->diameter();
for (typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active(); cell != triangulation.end();
++cell)
max_diameter = std::max (max_diameter,
cell->diameter());
return max_diameter;
}
template <int dim, int spacedim>
void
create_union_triangulation (const Triangulation<dim, spacedim> &triangulation_1,
const Triangulation<dim, spacedim> &triangulation_2,
Triangulation<dim, spacedim> &result)
{
// this function is deprecated. call the function that replaced it
GridGenerator::create_union_triangulation (triangulation_1, triangulation_2, result);
}
namespace internal
{
namespace FixUpDistortedChildCells
{
// compute the mean square
// deviation of the alternating
// forms of the children of the
// given object from that of
// the object itself. for
// objects with
// structdim==spacedim, the
// alternating form is the
// determinant of the jacobian,
// whereas for faces with
// structdim==spacedim-1, the
// alternating form is the
// (signed and scaled) normal
// vector
//
// this average square
// deviation is computed for an
// object where the center node
// has been replaced by the
// second argument to this
// function
template <typename Iterator, int spacedim>
double
objective_function (const Iterator &object,
const Point<spacedim> &object_mid_point)
{
const unsigned int structdim = Iterator::AccessorType::structure_dimension;
Assert (spacedim == Iterator::AccessorType::dimension,
ExcInternalError());
// everything below is wrong
// if not for the following
// condition
Assert (object->refinement_case() == RefinementCase<structdim>::isotropic_refinement,
ExcNotImplemented());
// first calculate the
// average alternating form
// for the parent cell/face
Point<spacedim> parent_vertices
[GeometryInfo<structdim>::vertices_per_cell];
Tensor<spacedim-structdim,spacedim> parent_alternating_forms
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
parent_vertices[i] = object->vertex(i);
GeometryInfo<structdim>::alternating_form_at_vertices (parent_vertices,
parent_alternating_forms);
const Tensor<spacedim-structdim,spacedim>
average_parent_alternating_form
= std::accumulate (&parent_alternating_forms[0],
&parent_alternating_forms[GeometryInfo<structdim>::vertices_per_cell],
Tensor<spacedim-structdim,spacedim>());
// now do the same
// computation for the
// children where we use the
// given location for the
// object mid point instead of
// the one the triangulation
// currently reports
Point<spacedim> child_vertices
[GeometryInfo<structdim>::max_children_per_cell]
[GeometryInfo<structdim>::vertices_per_cell];
Tensor<spacedim-structdim,spacedim> child_alternating_forms
[GeometryInfo<structdim>::max_children_per_cell]
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
child_vertices[c][i] = object->child(c)->vertex(i);
// replace mid-object
// vertex. note that for
// child i, the mid-object
// vertex happens to have the
// number
// max_children_per_cell-i
for (unsigned int c=0; c<object->n_children(); ++c)
child_vertices[c][GeometryInfo<structdim>::max_children_per_cell-c-1]
= object_mid_point;
for (unsigned int c=0; c<object->n_children(); ++c)
GeometryInfo<structdim>::alternating_form_at_vertices (child_vertices[c],
child_alternating_forms[c]);
// on a uniformly refined
// hypercube object, the child
// alternating forms should
// all be smaller by a factor
// of 2^structdim than the
// ones of the parent. as a
// consequence, we'll use the
// squared deviation from
// this ideal value as an
// objective function
double objective = 0;
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
objective += (child_alternating_forms[c][i] -
average_parent_alternating_form/std::pow(2.,1.*structdim))
.norm_square();
return objective;
}
/**
* Return the location of the midpoint
* of the 'f'th face (vertex) of this 1d
* object.
*/
template <typename Iterator>
Point<Iterator::AccessorType::space_dimension>
get_face_midpoint (const Iterator &object,
const unsigned int f,
dealii::internal::int2type<1>)
{
return object->vertex(f);
}
/**
* Return the location of the midpoint
* of the 'f'th face (line) of this 2d
* object.
*/
template <typename Iterator>
Point<Iterator::AccessorType::space_dimension>
get_face_midpoint (const Iterator &object,
const unsigned int f,
dealii::internal::int2type<2>)
{
return object->line(f)->center();
}
/**
* Return the location of the midpoint
* of the 'f'th face (quad) of this 3d
* object.
*/
template <typename Iterator>
Point<Iterator::AccessorType::space_dimension>
get_face_midpoint (const Iterator &object,
const unsigned int f,
dealii::internal::int2type<3>)
{
return object->face(f)->center();
}
/**
* Compute the minimal diameter of an
* object by looking for the minimal
* distance between the mid-points of
* its faces. This minimal diameter is
* used to determine the step length
* for our grid cell improvement
* algorithm, and it should be small
* enough that the point moves around
* within the cell even if it is highly
* elongated -- thus, the diameter of
* the object is not a good measure,
* while the minimal diameter is. Note
* that the algorithm below works for
* both cells that are long rectangles
* with parallel sides where the
* nearest distance is between opposite
* edges as well as highly slanted
* parallelograms where the shortest
* distance is between neighboring
* edges.
*/
template <typename Iterator>
double
minimal_diameter (const Iterator &object)
{
const unsigned int
structdim = Iterator::AccessorType::structure_dimension;
double diameter = object->diameter();
for (unsigned int f=0;
f<GeometryInfo<structdim>::faces_per_cell;
++f)
for (unsigned int e=f+1;
e<GeometryInfo<structdim>::faces_per_cell;
++e)
diameter = std::min (diameter,
get_face_midpoint
(object, f,
dealii::internal::int2type<structdim>())
.distance (get_face_midpoint
(object,
e,
dealii::internal::int2type<structdim>())));
return diameter;
}
/**
* Try to fix up a single cell. Return
* whether we succeeded with this.
*
* The second argument indicates
* whether we need to respect the
* manifold/boundary on which this
* object lies when moving around its
* mid-point.
*/
template <typename Iterator>
bool
fix_up_object (const Iterator &object,
const bool respect_manifold)
{
const Boundary<Iterator::AccessorType::dimension,
Iterator::AccessorType::space_dimension>
*manifold = (respect_manifold ?
&object->get_boundary() :
0);
const unsigned int structdim = Iterator::AccessorType::structure_dimension;
const unsigned int spacedim = Iterator::AccessorType::space_dimension;
// right now we can only deal
// with cells that have been
// refined isotropically
// because that is the only
// case where we have a cell
// mid-point that can be moved
// around without having to
// consider boundary
// information
Assert (object->has_children(), ExcInternalError());
Assert (object->refinement_case() == RefinementCase<structdim>::isotropic_refinement,
ExcNotImplemented());
// get the current location of
// the object mid-vertex:
Point<spacedim> object_mid_point
= object->child(0)->vertex (GeometryInfo<structdim>::max_children_per_cell-1);
// now do a few steepest descent
// steps to reduce the objective
// function. compute the diameter in
// the helper function above
unsigned int iteration = 0;
const double diameter = minimal_diameter (object);
// current value of objective
// function and initial delta
double current_value = objective_function (object, object_mid_point);
double initial_delta = 0;
do
{
// choose a step length
// that is initially 1/4
// of the child objects'
// diameter, and a sequence
// whose sum does not
// converge (to avoid
// premature termination of
// the iteration)
const double step_length = diameter / 4 / (iteration + 1);
// compute the objective
// function's derivative using a
// two-sided difference formula
// with eps=step_length/10
Tensor<1,spacedim> gradient;
for (unsigned int d=0; d<spacedim; ++d)
{
const double eps = step_length/10;
Point<spacedim> h;
h[d] = eps/2;
if (respect_manifold == false)
gradient[d]
= ((objective_function (object, object_mid_point + h)
-
objective_function (object, object_mid_point - h))
/
eps);
else
gradient[d]
= ((objective_function (object,
manifold->project_to_surface(object,
object_mid_point + h))
-
objective_function (object,
manifold->project_to_surface(object,
object_mid_point - h)))
/
eps);
}
// sometimes, the
// (unprojected) gradient
// is perpendicular to
// the manifold, but we
// can't go there if
// respect_manifold==true. in
// that case, gradient=0,
// and we simply need to
// quite the loop here
if (gradient.norm() == 0)
break;
// so we need to go in
// direction -gradient. the
// optimal value of the
// objective function is
// zero, so assuming that
// the model is quadratic
// we would have to go
// -2*val/||gradient|| in
// this direction, make
// sure we go at most
// step_length into this
// direction
object_mid_point -= std::min(2 * current_value / (gradient*gradient),
step_length / gradient.norm()) *
gradient;
if (respect_manifold == true)
object_mid_point = manifold->project_to_surface(object,
object_mid_point);
// compute current value of the
// objective function
const double previous_value = current_value;
current_value = objective_function (object, object_mid_point);
if (iteration == 0)
initial_delta = (previous_value - current_value);
// stop if we aren't moving much
// any more
if ((iteration >= 1) &&
((previous_value - current_value < 0)
||
(std::fabs (previous_value - current_value)
<
0.001 * initial_delta)))
break;
++iteration;
}
while (iteration < 20);
// verify that the new
// location is indeed better
// than the one before. check
// this by comparing whether
// the minimum value of the
// products of parent and
// child alternating forms is
// positive. for cells this
// means that the
// determinants have the same
// sign, for faces that the
// face normals of parent and
// children point in the same
// general direction
double old_min_product, new_min_product;
Point<spacedim> parent_vertices
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
parent_vertices[i] = object->vertex(i);
Tensor<spacedim-structdim,spacedim> parent_alternating_forms
[GeometryInfo<structdim>::vertices_per_cell];
GeometryInfo<structdim>::alternating_form_at_vertices (parent_vertices,
parent_alternating_forms);
Point<spacedim> child_vertices
[GeometryInfo<structdim>::max_children_per_cell]
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
child_vertices[c][i] = object->child(c)->vertex(i);
Tensor<spacedim-structdim,spacedim> child_alternating_forms
[GeometryInfo<structdim>::max_children_per_cell]
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int c=0; c<object->n_children(); ++c)
GeometryInfo<structdim>::alternating_form_at_vertices (child_vertices[c],
child_alternating_forms[c]);
old_min_product = child_alternating_forms[0][0] * parent_alternating_forms[0];
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
for (unsigned int j=0; j<GeometryInfo<structdim>::vertices_per_cell; ++j)
old_min_product = std::min (old_min_product,
child_alternating_forms[c][i] *
parent_alternating_forms[j]);
// for the new minimum value,
// replace mid-object
// vertex. note that for child
// i, the mid-object vertex
// happens to have the number
// max_children_per_cell-i
for (unsigned int c=0; c<object->n_children(); ++c)
child_vertices[c][GeometryInfo<structdim>::max_children_per_cell-c-1]
= object_mid_point;
for (unsigned int c=0; c<object->n_children(); ++c)
GeometryInfo<structdim>::alternating_form_at_vertices (child_vertices[c],
child_alternating_forms[c]);
new_min_product = child_alternating_forms[0][0] * parent_alternating_forms[0];
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
for (unsigned int j=0; j<GeometryInfo<structdim>::vertices_per_cell; ++j)
new_min_product = std::min (new_min_product,
child_alternating_forms[c][i] *
parent_alternating_forms[j]);
// if new minimum value is
// better than before, then set the
// new mid point. otherwise
// return this object as one of
// those that can't apparently
// be fixed
if (new_min_product >= old_min_product)
object->child(0)->vertex (GeometryInfo<structdim>::max_children_per_cell-1)
= object_mid_point;
// return whether after this
// operation we have an object that
// is well oriented
return (std::max (new_min_product, old_min_product) > 0);
}
void fix_up_faces (const dealii::Triangulation<1,1>::cell_iterator &,
dealii::internal::int2type<1>,
dealii::internal::int2type<1>)
{
// nothing to do for the faces of
// cells in 1d
}
// possibly fix up the faces of
// a cell by moving around its
// mid-points
template <int structdim, int spacedim>
void fix_up_faces (const typename dealii::Triangulation<structdim,spacedim>::cell_iterator &cell,
dealii::internal::int2type<structdim>,
dealii::internal::int2type<spacedim>)
{
// see if we first can fix up
// some of the faces of this
// object. we can mess with
// faces if and only if it is
// not at the boundary (since
// otherwise the location of
// the face mid-point has been
// determined by the boundary
// object) and if the
// neighboring cell is not even
// more refined than we are
// (since in that case the
// sub-faces have themselves
// children that we can't move
// around any more). however,
// the latter case shouldn't
// happen anyway: if the
// current face is distorted
// but the neighbor is even
// more refined, then the face
// had been deformed before
// already, and had been
// ignored at the time; we
// should then also be able to
// ignore it this time as well
for (unsigned int f=0; f<GeometryInfo<structdim>::faces_per_cell; ++f)
{
Assert (cell->face(f)->has_children(), ExcInternalError());
Assert (cell->face(f)->refinement_case() ==
RefinementCase<structdim-1>::isotropic_refinement,
ExcInternalError());
bool subface_is_more_refined = false;
for (unsigned int g=0; g<GeometryInfo<structdim>::max_children_per_face; ++g)
if (cell->face(f)->child(g)->has_children())
{
subface_is_more_refined = true;
break;
}
if (subface_is_more_refined == true)
continue;
// so, now we finally know
// that we can do something
// about this face
fix_up_object (cell->face(f), cell->at_boundary(f));
}
}
} /* namespace FixUpDistortedChildCells */
} /* namespace internal */
template <int dim, int spacedim>
typename Triangulation<dim,spacedim>::DistortedCellList
fix_up_distorted_child_cells (const typename Triangulation<dim,spacedim>::DistortedCellList &distorted_cells,
Triangulation<dim,spacedim> &/*triangulation*/)
{
typename Triangulation<dim,spacedim>::DistortedCellList unfixable_subset;
// loop over all cells that we have
// to fix up
for (typename std::list<typename Triangulation<dim,spacedim>::cell_iterator>::const_iterator
cell_ptr = distorted_cells.distorted_cells.begin();
cell_ptr != distorted_cells.distorted_cells.end(); ++cell_ptr)
{
const typename Triangulation<dim,spacedim>::cell_iterator
cell = *cell_ptr;
internal::FixUpDistortedChildCells
::fix_up_faces (cell,
dealii::internal::int2type<dim>(),
dealii::internal::int2type<spacedim>());
// fix up the object. we need to
// respect the manifold if the cell is
// embedded in a higher dimensional
// space; otherwise, like a hex in 3d,
// every point within the cell interior
// is fair game
if (! internal::FixUpDistortedChildCells::fix_up_object (cell,
(dim < spacedim)))
unfixable_subset.distorted_cells.push_back (cell);
}
return unfixable_subset;
}
template <class Container>
std::vector<typename Container::active_cell_iterator>
get_patch_around_cell(const typename Container::active_cell_iterator &cell)
{
Assert (cell->is_locally_owned(),
ExcMessage ("This function only makes sense if the cell for "
"which you are asking for a patch, is locally "
"owned."));
std::vector<typename Container::active_cell_iterator> patch;
patch.push_back (cell);
for (unsigned int face_number=0; face_number<GeometryInfo<Container::dimension>::faces_per_cell; ++face_number)
if (cell->face(face_number)->at_boundary()==false)
{
if (cell->neighbor(face_number)->has_children() == false)
patch.push_back (cell->neighbor(face_number));
else
// the neighbor is refined. in 2d/3d, we can simply ask for the children
// of the neighbor because they can not be further refined and,
// consequently, the children is active
if (Container::dimension > 1)
{
for (unsigned int subface=0; subface<cell->face(face_number)->n_children(); ++subface)
patch.push_back (cell->neighbor_child_on_subface (face_number, subface));
}
else
{
// in 1d, we need to work a bit harder: iterate until we find
// the child by going from cell to child to child etc
typename Container::cell_iterator neighbor
= cell->neighbor (face_number);
while (neighbor->has_children())
neighbor = neighbor->child(1-face_number);
Assert (neighbor->neighbor(1-face_number) == cell, ExcInternalError());
patch.push_back (neighbor);
}
}
return patch;
}
template <template <int,int> class Container, int dim, int spacedim>
#ifndef _MSC_VER
std::map<typename Container<dim-1,spacedim>::cell_iterator,
typename Container<dim,spacedim>::face_iterator>
#else
typename ExtractBoundaryMesh<Container,dim,spacedim>::return_type
#endif
extract_boundary_mesh (const Container<dim,spacedim> &volume_mesh,
Container<dim-1,spacedim> &surface_mesh,
const std::set<types::boundary_id> &boundary_ids)
{
// this function is deprecated. call the one that replaced it
return GridGenerator::extract_boundary_mesh (volume_mesh, surface_mesh, boundary_ids);
}
/*
* Internally used in orthogonal_equality
*
* An orthogonal equality test for points:
*
* point1 and point2 are considered equal, if
* (point1 + offset) - point2
* is parallel to the unit vector in <direction>
*/
template<int spacedim>
inline bool orthogonal_equality (const dealii::Point<spacedim> &point1,
const dealii::Point<spacedim> &point2,
const int direction,
const dealii::Tensor<1,spacedim> &offset)
{
Assert (0<=direction && direction<spacedim,
ExcIndexRange (direction, 0, spacedim));
for (int i = 0; i < spacedim; ++i)
{
// Only compare coordinate-components != direction:
if (i == direction)
continue;
if (fabs(point1(i) + offset[i] - point2(i)) > 1.e-10)
return false;
}
return true;
}
/*
* Internally used in orthogonal_equality
*
* A lookup table to transform vertex matchings to orientation flags of
* the form (face_orientation, face_flip, face_rotation)
*
* See the comment on the next function as well as the detailed
* documentation of make_periodicity_constraints and
* collect_periodic_faces for details
*/
template<int dim> struct OrientationLookupTable {};
template<> struct OrientationLookupTable<1>
{
typedef std_cxx11::array<unsigned int, GeometryInfo<1>::vertices_per_face> MATCH_T;
static inline std::bitset<3> lookup (const MATCH_T &)
{
// The 1D case is trivial
return 4; // [true ,false,false]
}
};
template<> struct OrientationLookupTable<2>
{
typedef std_cxx11::array<unsigned int, GeometryInfo<2>::vertices_per_face> MATCH_T;
static inline std::bitset<3> lookup (const MATCH_T &matching)
{
// In 2D matching faces (=lines) results in two cases: Either
// they are aligned or flipped. We store this "line_flip"
// property somewhat sloppy as "face_flip"
// (always: face_orientation = true, face_rotation = false)
static const MATCH_T m_tff = {{ 0 , 1 }};
if (matching == m_tff) return 1; // [true ,false,false]
static const MATCH_T m_ttf = {{ 1 , 0 }};
if (matching == m_ttf) return 3; // [true ,true ,false]
AssertThrow(false, ExcInternalError());
// what follows is dead code, but it avoids warnings about the lack
// of a return value
return 0;
}
};
template<> struct OrientationLookupTable<3>
{
typedef std_cxx11::array<unsigned int, GeometryInfo<3>::vertices_per_face> MATCH_T;
static inline std::bitset<3> lookup (const MATCH_T &matching)
{
// The full fledged 3D case. *Yay*
// See the documentation in include/deal.II/base/geometry_info.h
// as well as the actual implementation in source/grid/tria.cc
// for more details...
static const MATCH_T m_tff = {{ 0 , 1 , 2 , 3 }};
if (matching == m_tff) return 1; // [true ,false,false]
static const MATCH_T m_tft = {{ 1 , 3 , 0 , 2 }};
if (matching == m_tft) return 5; // [true ,false,true ]
static const MATCH_T m_ttf = {{ 3 , 2 , 1 , 0 }};
if (matching == m_ttf) return 3; // [true ,true ,false]
static const MATCH_T m_ttt = {{ 2 , 0 , 3 , 1 }};
if (matching == m_ttt) return 7; // [true ,true ,true ]
static const MATCH_T m_fff = {{ 0 , 2 , 1 , 3 }};
if (matching == m_fff) return 0; // [false,false,false]
static const MATCH_T m_fft = {{ 2 , 3 , 0 , 1 }};
if (matching == m_fft) return 4; // [false,false,true ]
static const MATCH_T m_ftf = {{ 3 , 1 , 2 , 0 }};
if (matching == m_ftf) return 2; // [false,true ,false]
static const MATCH_T m_ftt = {{ 1 , 0 , 3 , 2 }};
if (matching == m_ftt) return 6; // [false,true ,true ]
AssertThrow(false, ExcInternalError());
// what follows is dead code, but it avoids warnings about the lack
// of a return value
return 0;
}
};
template<typename FaceIterator>
inline bool
orthogonal_equality (std::bitset<3> &orientation,
const FaceIterator &face1,
const FaceIterator &face2,
const int direction,
const dealii::Tensor<1,FaceIterator::AccessorType::space_dimension> &offset)
{
static const int dim = FaceIterator::AccessorType::dimension;
// Do a full matching of the face vertices:
std_cxx11::
array<unsigned int, GeometryInfo<dim>::vertices_per_face> matching;
std::set<unsigned int> face2_vertices;
for (unsigned int i = 0; i < GeometryInfo<dim>::vertices_per_face; ++i)
face2_vertices.insert(i);
for (unsigned int i = 0; i < GeometryInfo<dim>::vertices_per_face; ++i)
{
for (std::set<unsigned int>::iterator it = face2_vertices.begin();
it != face2_vertices.end();
it++)
{
if (orthogonal_equality(face1->vertex(i),face2->vertex(*it),
direction, offset))
{
matching[i] = *it;
face2_vertices.erase(it);
break; // jump out of the innermost loop
}
}
}
// And finally, a lookup to determine the ordering bitmask:
if (face2_vertices.empty())
orientation = OrientationLookupTable<dim>::lookup(matching);
return face2_vertices.empty();
}
template<typename FaceIterator>
inline bool
orthogonal_equality (const FaceIterator &face1,
const FaceIterator &face2,
const int direction,
const dealii::Tensor<1,FaceIterator::AccessorType::space_dimension> &offset)
{
// Call the function above with a dummy orientation array
std::bitset<3> dummy;
return orthogonal_equality (dummy, face1, face2, direction, offset);
}
/*
* Internally used in collect_periodic_faces
*/
template<typename CellIterator>
void
match_periodic_face_pairs
(std::set<std::pair<CellIterator, unsigned int> > &pairs1,
std::set<std::pair<typename identity<CellIterator>::type, unsigned int> > &pairs2,
const int direction,
std::vector<PeriodicFacePair<CellIterator> > &matched_pairs,
const dealii::Tensor<1,CellIterator::AccessorType::space_dimension> &offset)
{
static const int space_dim = CellIterator::AccessorType::space_dimension;
Assert (0<=direction && direction<space_dim,
ExcIndexRange (direction, 0, space_dim));
Assert (pairs1.size() == pairs2.size(),
ExcMessage ("Unmatched faces on periodic boundaries"));
unsigned int n_matches = 0;
// Match with a complexity of O(n^2). This could be improved...
std::bitset<3> orientation;
typedef typename std::set
<std::pair<CellIterator, unsigned int> >::const_iterator PairIterator;
for (PairIterator it1 = pairs1.begin(); it1 != pairs1.end(); ++it1)
{
for (PairIterator it2 = pairs2.begin(); it2 != pairs2.end(); ++it2)
{
const CellIterator cell1 = it1->first;
const CellIterator cell2 = it2->first;
const unsigned int face_idx1 = it1->second;
const unsigned int face_idx2 = it2->second;
if (GridTools::orthogonal_equality(orientation,
cell1->face(face_idx1),
cell2->face(face_idx2),
direction, offset))
{
// We have a match, so insert the matching pairs and
// remove the matched cell in pairs2 to speed up the
// matching:
const PeriodicFacePair<CellIterator> matched_face
= {{cell1, cell2},{face_idx1, face_idx2}, orientation};
matched_pairs.push_back(matched_face);
pairs2.erase(it2);
++n_matches;
break;
}
}
}
//Assure that all faces are matched
AssertThrow (n_matches == pairs1.size() && pairs2.size() == 0,
ExcMessage ("Unmatched faces on periodic boundaries"));
}
template<typename CONTAINER>
void
collect_periodic_faces
(const CONTAINER &container,
const types::boundary_id b_id1,
const types::boundary_id b_id2,
const int direction,
std::vector<PeriodicFacePair<typename CONTAINER::cell_iterator> > &matched_pairs,
const dealii::Tensor<1,CONTAINER::space_dimension> &offset)
{
static const int dim = CONTAINER::dimension;
static const int space_dim = CONTAINER::space_dimension;
Assert (0<=direction && direction<space_dim,
ExcIndexRange (direction, 0, space_dim));
// Loop over all cells on the highest level and collect all boundary
// faces belonging to b_id1 and b_id2:
std::set<std::pair<typename CONTAINER::cell_iterator, unsigned int> > pairs1;
std::set<std::pair<typename CONTAINER::cell_iterator, unsigned int> > pairs2;
for (typename CONTAINER::cell_iterator cell = container.begin(0);
cell != container.end(0); ++cell)
{
for (unsigned int i = 0; i < GeometryInfo<dim>::faces_per_cell; ++i)
{
const typename CONTAINER::face_iterator face = cell->face(i);
if (face->at_boundary() && face->boundary_indicator() == b_id1)
{
const std::pair<typename CONTAINER::cell_iterator, unsigned int> pair1
= std::make_pair(cell, i);
pairs1.insert(pair1);
}
if (face->at_boundary() && face->boundary_indicator() == b_id2)
{
const std::pair<typename CONTAINER::cell_iterator, unsigned int> pair2
= std::make_pair(cell, i);
pairs2.insert(pair2);
}
}
}
Assert (pairs1.size() == pairs2.size(),
ExcMessage ("Unmatched faces on periodic boundaries"));
// and call match_periodic_face_pairs that does the actual matching:
match_periodic_face_pairs(pairs1, pairs2, direction, matched_pairs, offset);
}
template<typename CONTAINER>
void
collect_periodic_faces
(const CONTAINER &container,
const types::boundary_id b_id,
const int direction,
std::vector<PeriodicFacePair<typename CONTAINER::cell_iterator> > &matched_pairs,
const dealii::Tensor<1,CONTAINER::space_dimension> &offset)
{
static const int dim = CONTAINER::dimension;
static const int space_dim = CONTAINER::space_dimension;
Assert (0<=direction && direction<space_dim,
ExcIndexRange (direction, 0, space_dim));
Assert(dim == space_dim,
ExcNotImplemented());
// Loop over all cells on the highest level and collect all boundary
// faces 2*direction and 2*direction*1:
std::set<std::pair<typename CONTAINER::cell_iterator, unsigned int> > pairs1;
std::set<std::pair<typename CONTAINER::cell_iterator, unsigned int> > pairs2;
for (typename CONTAINER::cell_iterator cell = container.begin(0);
cell != container.end(0); ++cell)
{
const typename CONTAINER::face_iterator face_1 = cell->face(2*direction);
const typename CONTAINER::face_iterator face_2 = cell->face(2*direction+1);
if (face_1->at_boundary() && face_1->boundary_indicator() == b_id)
{
const std::pair<typename CONTAINER::cell_iterator, unsigned int> pair1
= std::make_pair(cell, 2*direction);
pairs1.insert(pair1);
}
if (face_2->at_boundary() && face_2->boundary_indicator() == b_id)
{
const std::pair<typename CONTAINER::cell_iterator, unsigned int> pair2
= std::make_pair(cell, 2*direction+1);
pairs2.insert(pair2);
}
}
Assert (pairs1.size() == pairs2.size(),
ExcMessage ("Unmatched faces on periodic boundaries"));
#ifdef DEBUG
const unsigned int size_old = matched_pairs.size();
#endif
// and call match_periodic_face_pairs that does the actual matching:
match_periodic_face_pairs(pairs1, pairs2, direction, matched_pairs, offset);
#ifdef DEBUG
//check for standard orientation
const unsigned int size_new = matched_pairs.size();
for (unsigned int i = size_old; i < size_new; ++i)
{
Assert(matched_pairs[i].orientation == 1,
ExcMessage("Found a face match with non standard orientation. "
"This function is only suitable for meshes with cells "
"in default orientation"));
}
#endif
}
} /* namespace GridTools */
// explicit instantiations
#include "grid_tools.inst"
DEAL_II_NAMESPACE_CLOSE
Fix the previous commit so that it doesn't produce a warning.
// ---------------------------------------------------------------------
//
// Copyright (C) 2001 - 2014 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
#include <deal.II/base/std_cxx11/array.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/grid/tria.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/grid/tria_boundary.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/lac/sparsity_pattern.h>
#include <deal.II/lac/sparsity_tools.h>
#include <deal.II/lac/compressed_sparsity_pattern.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_accessor.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/fe/fe_nothing.h>
#include <deal.II/fe/mapping_q1.h>
#include <deal.II/fe/mapping_q.h>
#include <deal.II/fe/fe_values.h>
#include <deal.II/hp/mapping_collection.h>
#include <deal.II/multigrid/mg_dof_handler.h>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <cmath>
#include <numeric>
#include <list>
#include <set>
DEAL_II_NAMESPACE_OPEN
namespace GridTools
{
// This anonymous namespace contains utility functions to extract the
// triangulation from any container such as DoFHandler
// and the like
namespace
{
template<int dim, int spacedim>
const Triangulation<dim, spacedim> &
get_tria(const Triangulation<dim, spacedim> &tria)
{
return tria;
}
template<int dim, int spacedim>
const Triangulation<dim, spacedim> &
get_tria(const parallel::distributed::Triangulation<dim, spacedim> &tria)
{
return tria;
}
template<int dim, template<int, int> class Container, int spacedim>
const Triangulation<dim,spacedim> &
get_tria(const Container<dim,spacedim> &container)
{
return container.get_tria();
}
template<int dim, int spacedim>
Triangulation<dim, spacedim> &
get_tria(Triangulation<dim, spacedim> &tria)
{
return tria;
}
template<int dim, int spacedim>
Triangulation<dim, spacedim> &
get_tria(parallel::distributed::Triangulation<dim, spacedim> &tria)
{
return tria;
}
template<int dim, template<int, int> class Container, int spacedim>
const Triangulation<dim,spacedim> &
get_tria(Container<dim,spacedim> &container)
{
return container.get_tria();
}
}
template <int dim, int spacedim>
double
diameter (const Triangulation<dim, spacedim> &tria)
{
// we can't deal with distributed meshes
// since we don't have all vertices
// locally. there is one exception,
// however: if the mesh has never been
// refined. the way to test this is not to
// ask tria.n_levels()==1, since this is
// something that can happen on one
// processor without being true on
// all. however, we can ask for the global
// number of active cells and use that
#ifdef DEAL_II_WITH_P4EST
if (const parallel::distributed::Triangulation<dim,spacedim> *p_tria
= dynamic_cast<const parallel::distributed::Triangulation<dim,spacedim>*>(&tria))
Assert (p_tria->n_global_active_cells() == tria.n_cells(0),
ExcNotImplemented());
#endif
// the algorithm used simply
// traverses all cells and picks
// out the boundary vertices. it
// may or may not be faster to
// simply get all vectors, don't
// mark boundary vertices, and
// compute the distances thereof,
// but at least as the mesh is
// refined, it seems better to
// first mark boundary nodes, as
// marking is O(N) in the number of
// cells/vertices, while computing
// the maximal distance is O(N*N)
const std::vector<Point<spacedim> > &vertices = tria.get_vertices ();
std::vector<bool> boundary_vertices (vertices.size(), false);
typename Triangulation<dim,spacedim>::active_cell_iterator
cell = tria.begin_active();
const typename Triangulation<dim,spacedim>::active_cell_iterator
endc = tria.end();
for (; cell!=endc; ++cell)
for (unsigned int face=0; face<GeometryInfo<dim>::faces_per_cell; ++face)
if (cell->face(face)->at_boundary ())
for (unsigned int i=0; i<GeometryInfo<dim>::vertices_per_face; ++i)
boundary_vertices[cell->face(face)->vertex_index(i)] = true;
// now traverse the list of
// boundary vertices and check
// distances. since distances are
// symmetric, we only have to check
// one half
double max_distance_sqr = 0;
std::vector<bool>::const_iterator pi = boundary_vertices.begin();
const unsigned int N = boundary_vertices.size();
for (unsigned int i=0; i<N; ++i, ++pi)
{
std::vector<bool>::const_iterator pj = pi+1;
for (unsigned int j=i+1; j<N; ++j, ++pj)
if ((*pi==true) && (*pj==true) &&
((vertices[i]-vertices[j]).square() > max_distance_sqr))
max_distance_sqr = (vertices[i]-vertices[j]).square();
};
return std::sqrt(max_distance_sqr);
}
template <int dim, int spacedim>
double
volume (const Triangulation<dim, spacedim> &triangulation,
const Mapping<dim,spacedim> &mapping)
{
// get the degree of the mapping if possible. if not, just assume 1
const unsigned int mapping_degree
= (dynamic_cast<const MappingQ<dim,spacedim>*>(&mapping) != 0 ?
dynamic_cast<const MappingQ<dim,spacedim>*>(&mapping)->get_degree() :
1);
// then initialize an appropriate quadrature formula
const QGauss<dim> quadrature_formula (mapping_degree + 1);
const unsigned int n_q_points = quadrature_formula.size();
// we really want the JxW values from the FEValues object, but it
// wants a finite element. create a cheap element as a dummy
// element
FE_Nothing<dim,spacedim> dummy_fe;
FEValues<dim,spacedim> fe_values (mapping, dummy_fe, quadrature_formula,
update_JxW_values);
typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active(),
endc = triangulation.end();
double local_volume = 0;
// compute the integral quantities by quadrature
for (; cell!=endc; ++cell)
if (cell->is_locally_owned())
{
fe_values.reinit (cell);
for (unsigned int q=0; q<n_q_points; ++q)
local_volume += fe_values.JxW(q);
}
double global_volume = 0;
#ifdef DEAL_II_WITH_MPI
if (const parallel::distributed::Triangulation<dim,spacedim> *p_tria
= dynamic_cast<const parallel::distributed::Triangulation<dim,spacedim>*>(&triangulation))
global_volume = Utilities::MPI::sum (local_volume, p_tria->get_communicator());
else
global_volume = local_volume;
#else
global_volume = local_volume;
#endif
return global_volume;
}
template <>
double
cell_measure<3>(const std::vector<Point<3> > &all_vertices,
const unsigned int (&vertex_indices)[GeometryInfo<3>::vertices_per_cell])
{
// note that this is the
// cell_measure based on the new
// deal.II numbering. When called
// from inside GridReordering make
// sure that you reorder the
// vertex_indices before
const double x[8] = { all_vertices[vertex_indices[0]](0),
all_vertices[vertex_indices[1]](0),
all_vertices[vertex_indices[2]](0),
all_vertices[vertex_indices[3]](0),
all_vertices[vertex_indices[4]](0),
all_vertices[vertex_indices[5]](0),
all_vertices[vertex_indices[6]](0),
all_vertices[vertex_indices[7]](0)
};
const double y[8] = { all_vertices[vertex_indices[0]](1),
all_vertices[vertex_indices[1]](1),
all_vertices[vertex_indices[2]](1),
all_vertices[vertex_indices[3]](1),
all_vertices[vertex_indices[4]](1),
all_vertices[vertex_indices[5]](1),
all_vertices[vertex_indices[6]](1),
all_vertices[vertex_indices[7]](1)
};
const double z[8] = { all_vertices[vertex_indices[0]](2),
all_vertices[vertex_indices[1]](2),
all_vertices[vertex_indices[2]](2),
all_vertices[vertex_indices[3]](2),
all_vertices[vertex_indices[4]](2),
all_vertices[vertex_indices[5]](2),
all_vertices[vertex_indices[6]](2),
all_vertices[vertex_indices[7]](2)
};
/*
This is the same Maple script as in the barycenter method above
except of that here the shape functions tphi[0]-tphi[7] are ordered
according to the lexicographic numbering.
x := array(0..7):
y := array(0..7):
z := array(0..7):
tphi[0] := (1-xi)*(1-eta)*(1-zeta):
tphi[1] := xi*(1-eta)*(1-zeta):
tphi[2] := (1-xi)* eta*(1-zeta):
tphi[3] := xi* eta*(1-zeta):
tphi[4] := (1-xi)*(1-eta)*zeta:
tphi[5] := xi*(1-eta)*zeta:
tphi[6] := (1-xi)* eta*zeta:
tphi[7] := xi* eta*zeta:
x_real := sum(x[s]*tphi[s], s=0..7):
y_real := sum(y[s]*tphi[s], s=0..7):
z_real := sum(z[s]*tphi[s], s=0..7):
with (linalg):
J := matrix(3,3, [[diff(x_real, xi), diff(x_real, eta), diff(x_real, zeta)],
[diff(y_real, xi), diff(y_real, eta), diff(y_real, zeta)],
[diff(z_real, xi), diff(z_real, eta), diff(z_real, zeta)]]):
detJ := det (J):
measure := simplify ( int ( int ( int (detJ, xi=0..1), eta=0..1), zeta=0..1)):
readlib(C):
C(measure, optimized);
The C code produced by this maple script is further optimized by
hand. In particular, division by 12 is performed only once, not
hundred of times.
*/
const double t3 = y[3]*x[2];
const double t5 = z[1]*x[5];
const double t9 = z[3]*x[2];
const double t11 = x[1]*y[0];
const double t14 = x[4]*y[0];
const double t18 = x[5]*y[7];
const double t20 = y[1]*x[3];
const double t22 = y[5]*x[4];
const double t26 = z[7]*x[6];
const double t28 = x[0]*y[4];
const double t34 = z[3]*x[1]*y[2]+t3*z[1]-t5*y[7]+y[7]*x[4]*z[6]+t9*y[6]-t11*z[4]-t5*y[3]-t14*z[2]+z[1]*x[4]*y[0]-t18*z[3]+t20*z[0]-t22*z[0]-y[0]*x[5]*z[4]-t26*y[3]+t28*z[2]-t9*y[1]-y[1]*x[4]*z[0]-t11*z[5];
const double t37 = y[1]*x[0];
const double t44 = x[1]*y[5];
const double t46 = z[1]*x[0];
const double t49 = x[0]*y[2];
const double t52 = y[5]*x[7];
const double t54 = x[3]*y[7];
const double t56 = x[2]*z[0];
const double t58 = x[3]*y[2];
const double t64 = -x[6]*y[4]*z[2]-t37*z[2]+t18*z[6]-x[3]*y[6]*z[2]+t11*z[2]+t5*y[0]+t44*z[4]-t46*y[4]-t20*z[7]-t49*z[6]-t22*z[1]+t52*z[3]-t54*z[2]-t56*y[4]-t58*z[0]+y[1]*x[2]*z[0]+t9*y[7]+t37*z[4];
const double t66 = x[1]*y[7];
const double t68 = y[0]*x[6];
const double t70 = x[7]*y[6];
const double t73 = z[5]*x[4];
const double t76 = x[6]*y[7];
const double t90 = x[4]*z[0];
const double t92 = x[1]*y[3];
const double t95 = -t66*z[3]-t68*z[2]-t70*z[2]+t26*y[5]-t73*y[6]-t14*z[6]+t76*z[2]-t3*z[6]+x[6]*y[2]*z[4]-z[3]*x[6]*y[2]+t26*y[4]-t44*z[3]-x[1]*y[2]*z[0]+x[5]*y[6]*z[4]+t54*z[5]+t90*y[2]-t92*z[2]+t46*y[2];
const double t102 = x[2]*y[0];
const double t107 = y[3]*x[7];
const double t114 = x[0]*y[6];
const double t125 = y[0]*x[3]*z[2]-z[7]*x[5]*y[6]-x[2]*y[6]*z[4]+t102*z[6]-t52*z[6]+x[2]*y[4]*z[6]-t107*z[5]-t54*z[6]+t58*z[6]-x[7]*y[4]*z[6]+t37*z[5]-t114*z[4]+t102*z[4]-z[1]*x[2]*y[0]+t28*z[6]-y[5]*x[6]*z[4]-z[5]*x[1]*y[4]-t73*y[7];
const double t129 = z[0]*x[6];
const double t133 = y[1]*x[7];
const double t145 = y[1]*x[5];
const double t156 = t90*y[6]-t129*y[4]+z[7]*x[2]*y[6]-t133*z[5]+x[5]*y[3]*z[7]-t26*y[2]-t70*z[3]+t46*y[3]+z[5]*x[7]*y[4]+z[7]*x[3]*y[6]-t49*z[4]+t145*z[7]-x[2]*y[7]*z[6]+t70*z[5]+t66*z[5]-z[7]*x[4]*y[6]+t18*z[4]+x[1]*y[4]*z[0];
const double t160 = x[5]*y[4];
const double t165 = z[1]*x[7];
const double t178 = z[1]*x[3];
const double t181 = t107*z[6]+t22*z[7]+t76*z[3]+t160*z[1]-x[4]*y[2]*z[6]+t70*z[4]+t165*y[5]+x[7]*y[2]*z[6]-t76*z[5]-t76*z[4]+t133*z[3]-t58*z[1]+y[5]*x[0]*z[4]+t114*z[2]-t3*z[7]+t20*z[2]+t178*y[7]+t129*y[2];
const double t207 = t92*z[7]+t22*z[6]+z[3]*x[0]*y[2]-x[0]*y[3]*z[2]-z[3]*x[7]*y[2]-t165*y[3]-t9*y[0]+t58*z[7]+y[3]*x[6]*z[2]+t107*z[2]+t73*y[0]-x[3]*y[5]*z[7]+t3*z[0]-t56*y[6]-z[5]*x[0]*y[4]+t73*y[1]-t160*z[6]+t160*z[0];
const double t228 = -t44*z[7]+z[5]*x[6]*y[4]-t52*z[4]-t145*z[4]+t68*z[4]+t92*z[5]-t92*z[0]+t11*z[3]+t44*z[0]+t178*y[5]-t46*y[5]-t178*y[0]-t145*z[0]-t20*z[5]-t37*z[3]-t160*z[7]+t145*z[3]+x[4]*y[6]*z[2];
return (t34+t64+t95+t125+t156+t181+t207+t228)/12.;
}
template <>
double
cell_measure(const std::vector<Point<2> > &all_vertices,
const unsigned int (&vertex_indices) [GeometryInfo<2>::vertices_per_cell])
{
/*
Get the computation of the measure by this little Maple script. We
use the blinear mapping of the unit quad to the real quad. However,
every transformation mapping the unit faces to straight lines should
do.
Remember that the area of the quad is given by
\int_K 1 dx dy = \int_{\hat K} |det J| d(xi) d(eta)
# x and y are arrays holding the x- and y-values of the four vertices
# of this cell in real space.
x := array(0..3);
y := array(0..3);
z := array(0..3);
tphi[0] := (1-xi)*(1-eta):
tphi[1] := xi*(1-eta):
tphi[2] := (1-xi)*eta:
tphi[3] := xi*eta:
x_real := sum(x[s]*tphi[s], s=0..3):
y_real := sum(y[s]*tphi[s], s=0..3):
z_real := sum(z[s]*tphi[s], s=0..3):
Jxi := <diff(x_real,xi) | diff(y_real,xi) | diff(z_real,xi)>;
Jeta := <diff(x_real,eta)| diff(y_real,eta)| diff(z_real,eta)>;
with(VectorCalculus):
J := CrossProduct(Jxi, Jeta);
detJ := sqrt(J[1]^2 + J[2]^2 +J[3]^2);
# measure := evalf (Int (Int (detJ, xi=0..1, method = _NCrule ) , eta=0..1, method = _NCrule ) ):
# readlib(C):
# C(measure, optimized);
additional optimizaton: divide by 2 only one time
*/
const double x[4] = { all_vertices[vertex_indices[0]](0),
all_vertices[vertex_indices[1]](0),
all_vertices[vertex_indices[2]](0),
all_vertices[vertex_indices[3]](0)
};
const double y[4] = { all_vertices[vertex_indices[0]](1),
all_vertices[vertex_indices[1]](1),
all_vertices[vertex_indices[2]](1),
all_vertices[vertex_indices[3]](1)
};
return (-x[1]*y[0]+x[1]*y[3]+y[0]*x[2]+x[0]*y[1]-x[0]*y[2]-y[1]*x[3]-x[2]*y[3]+x[3]*y[2])/2;
}
template <int dim>
double
cell_measure(const std::vector<Point<dim> > &,
const unsigned int ( &) [GeometryInfo<dim>::vertices_per_cell])
{
Assert(false, ExcNotImplemented());
return 0.;
}
template <int dim, int spacedim>
void
delete_unused_vertices (std::vector<Point<spacedim> > &vertices,
std::vector<CellData<dim> > &cells,
SubCellData &subcelldata)
{
// first check which vertices are
// actually used
std::vector<bool> vertex_used (vertices.size(), false);
for (unsigned int c=0; c<cells.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
vertex_used[cells[c].vertices[v]] = true;
// then renumber the vertices that
// are actually used in the same
// order as they were beforehand
const unsigned int invalid_vertex = numbers::invalid_unsigned_int;
std::vector<unsigned int> new_vertex_numbers (vertices.size(), invalid_vertex);
unsigned int next_free_number = 0;
for (unsigned int i=0; i<vertices.size(); ++i)
if (vertex_used[i] == true)
{
new_vertex_numbers[i] = next_free_number;
++next_free_number;
};
// next replace old vertex numbers
// by the new ones
for (unsigned int c=0; c<cells.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
cells[c].vertices[v] = new_vertex_numbers[cells[c].vertices[v]];
// same for boundary data
for (unsigned int c=0; c<subcelldata.boundary_lines.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<1>::vertices_per_cell; ++v)
subcelldata.boundary_lines[c].vertices[v]
= new_vertex_numbers[subcelldata.boundary_lines[c].vertices[v]];
for (unsigned int c=0; c<subcelldata.boundary_quads.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<2>::vertices_per_cell; ++v)
subcelldata.boundary_quads[c].vertices[v]
= new_vertex_numbers[subcelldata.boundary_quads[c].vertices[v]];
// finally copy over the vertices
// which we really need to a new
// array and replace the old one by
// the new one
std::vector<Point<spacedim> > tmp;
tmp.reserve (std::count(vertex_used.begin(), vertex_used.end(), true));
for (unsigned int v=0; v<vertices.size(); ++v)
if (vertex_used[v] == true)
tmp.push_back (vertices[v]);
swap (vertices, tmp);
}
template <int dim, int spacedim>
void
delete_duplicated_vertices (std::vector<Point<spacedim> > &vertices,
std::vector<CellData<dim> > &cells,
SubCellData &subcelldata,
std::vector<unsigned int> &considered_vertices,
double tol)
{
// create a vector of vertex
// indices. initialize it to the identity,
// later on change that if necessary.
std::vector<unsigned int> new_vertex_numbers(vertices.size());
for (unsigned int i=0; i<vertices.size(); ++i)
new_vertex_numbers[i]=i;
// if the considered_vertices vector is
// empty, consider all vertices
if (considered_vertices.size()==0)
considered_vertices=new_vertex_numbers;
// now loop over all vertices to be
// considered and try to find an identical
// one
for (unsigned int i=0; i<considered_vertices.size(); ++i)
{
if (new_vertex_numbers[considered_vertices[i]]!=considered_vertices[i])
// this vertex has been identified with
// another one already, skip it in the
// test
continue;
// this vertex is not identified with
// another one so far. search in the list
// of remaining vertices. if a duplicate
// vertex is found, set the new vertex
// index for that vertex to this vertex'
// index.
for (unsigned int j=i+1; j<considered_vertices.size(); ++j)
{
bool equal=true;
for (unsigned int d=0; d<spacedim; ++d)
equal &= (fabs(vertices[considered_vertices[j]](d)-vertices[considered_vertices[i]](d))<tol);
if (equal)
{
new_vertex_numbers[considered_vertices[j]]=considered_vertices[i];
// we do not suppose, that there might be another duplicate
// vertex, so break here
break;
}
}
}
// now we got a renumbering list. simply
// renumber all vertices (non-duplicate
// vertices get renumbered to themselves, so
// nothing bad happens). after that, the
// duplicate vertices will be unused, so call
// delete_unused_vertices() to do that part
// of the job.
for (unsigned int c=0; c<cells.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
cells[c].vertices[v]=new_vertex_numbers[cells[c].vertices[v]];
delete_unused_vertices(vertices,cells,subcelldata);
}
// define some transformations in an anonymous namespace
namespace
{
template <int spacedim>
class ShiftPoint
{
public:
ShiftPoint (const Point<spacedim> &shift)
:
shift(shift)
{}
Point<spacedim> operator() (const Point<spacedim> p) const
{
return p+shift;
}
private:
const Point<spacedim> shift;
};
// the following class is only
// needed in 2d, so avoid trouble
// with compilers warning otherwise
class Rotate2d
{
public:
Rotate2d (const double angle)
:
angle(angle)
{}
Point<2> operator() (const Point<2> &p) const
{
return Point<2> (std::cos(angle)*p(0) - std::sin(angle) * p(1),
std::sin(angle)*p(0) + std::cos(angle) * p(1));
}
private:
const double angle;
};
template <int spacedim>
class ScalePoint
{
public:
ScalePoint (const double factor)
:
factor(factor)
{}
Point<spacedim> operator() (const Point<spacedim> p) const
{
return p*factor;
}
private:
const double factor;
};
}
template <int dim, int spacedim>
void
shift (const Point<spacedim> &shift_vector,
Triangulation<dim, spacedim> &triangulation)
{
transform (ShiftPoint<spacedim>(shift_vector), triangulation);
}
void
rotate (const double angle,
Triangulation<2> &triangulation)
{
transform (Rotate2d(angle), triangulation);
}
template <int dim, int spacedim>
void
scale (const double scaling_factor,
Triangulation<dim, spacedim> &triangulation)
{
Assert (scaling_factor>0, ExcScalingFactorNotPositive (scaling_factor));
transform (ScalePoint<spacedim>(scaling_factor), triangulation);
}
template <int dim>
void
laplace_transform (const std::map<unsigned int,Point<dim> > &new_points,
Triangulation<dim> &triangulation,
const Function<dim> *coefficient)
{
//TODO: Move implementation of this function into the current
// namespace
GridGenerator::laplace_transformation(triangulation, new_points, coefficient);
}
/**
* Distort a triangulation in
* some random way.
*/
template <int dim, int spacedim>
void
distort_random (const double factor,
Triangulation<dim,spacedim> &triangulation,
const bool keep_boundary)
{
// if spacedim>dim we need to make sure that we perturb
// points but keep them on
// the manifold. however, this isn't implemented right now
Assert (spacedim == dim, ExcNotImplemented());
// find the smallest length of the
// lines adjacent to the
// vertex. take the initial value
// to be larger than anything that
// might be found: the diameter of
// the triangulation, here
// estimated by adding up the
// diameters of the coarse grid
// cells.
double almost_infinite_length = 0;
for (typename Triangulation<dim,spacedim>::cell_iterator
cell=triangulation.begin(0); cell!=triangulation.end(0); ++cell)
almost_infinite_length += cell->diameter();
std::vector<double> minimal_length (triangulation.n_vertices(),
almost_infinite_length);
// also note if a vertex is at the boundary
std::vector<bool> at_boundary (triangulation.n_vertices(), false);
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell=triangulation.begin_active(); cell!=triangulation.end(); ++cell)
if (cell->is_locally_owned())
{
if (dim>1)
{
for (unsigned int i=0; i<GeometryInfo<dim>::lines_per_cell; ++i)
{
const typename Triangulation<dim,spacedim>::line_iterator line
= cell->line(i);
if (keep_boundary && line->at_boundary())
{
at_boundary[line->vertex_index(0)] = true;
at_boundary[line->vertex_index(1)] = true;
}
minimal_length[line->vertex_index(0)]
= std::min(line->diameter(),
minimal_length[line->vertex_index(0)]);
minimal_length[line->vertex_index(1)]
= std::min(line->diameter(),
minimal_length[line->vertex_index(1)]);
}
}
else //dim==1
{
if (keep_boundary)
for (unsigned int vertex=0; vertex<2; ++vertex)
if (cell->at_boundary(vertex) == true)
at_boundary[cell->vertex_index(vertex)] = true;
minimal_length[cell->vertex_index(0)]
= std::min(cell->diameter(),
minimal_length[cell->vertex_index(0)]);
minimal_length[cell->vertex_index(1)]
= std::min(cell->diameter(),
minimal_length[cell->vertex_index(1)]);
}
}
// If the triangulation is distributed, we need to
// exchange the moved vertices across mpi processes
if (parallel::distributed::Triangulation< dim, spacedim > *distributed_triangulation
= dynamic_cast<parallel::distributed::Triangulation<dim,spacedim>*> (&triangulation))
{
// create a random number generator for the interval [-1,1]. we use
// this to make sure the distribution we get is repeatable, i.e.,
// if you call the function twice on the same mesh, then you will
// get the same mesh. this would not be the case if you used
// the rand() function, which carries around some internal state
boost::random::mt19937 rng;
boost::random::uniform_real_distribution<> uniform_distribution(-1,1);
const std::vector<bool> locally_owned_vertices = get_locally_owned_vertices(triangulation);
std::vector<bool> vertex_moved (triangulation.n_vertices(), false);
// Next move vertices on locally owned cells
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell=triangulation.begin_active(); cell!=triangulation.end(); ++cell)
if (cell->is_locally_owned())
{
for (unsigned int vertex_no=0; vertex_no<GeometryInfo<dim>::vertices_per_cell;
++vertex_no)
{
const unsigned global_vertex_no = cell->vertex_index(vertex_no);
// ignore this vertex if we shall keep the boundary and
// this vertex *is* at the boundary, if it is already moved
// or if another process moves this vertex
if ((keep_boundary && at_boundary[global_vertex_no])
|| vertex_moved[global_vertex_no]
|| !locally_owned_vertices[global_vertex_no])
continue;
// first compute a random shift vector
Point<spacedim> shift_vector;
for (unsigned int d=0; d<spacedim; ++d)
shift_vector(d) = uniform_distribution(rng);
shift_vector *= factor * minimal_length[global_vertex_no] /
std::sqrt(shift_vector.square());
// finally move the vertex
cell->vertex(vertex_no) += shift_vector;
vertex_moved[global_vertex_no] = true;
}
}
#ifdef DEAL_II_USE_P4EST
distributed_triangulation
->communicate_locally_moved_vertices(locally_owned_vertices);
#else
Assert (false, ExcInternalError());
#endif
}
else
// if this is a sequential triangulation, we could in principle
// use the algorithm above, but we'll use an algorithm that we used
// before the parallel::distributed::Triangulation was introduced
// in order to preserve backward compatibility
{
// loop over all vertices and compute their new locations
const unsigned int n_vertices = triangulation.n_vertices();
std::vector<Point<spacedim> > new_vertex_locations (n_vertices);
const std::vector<Point<spacedim> > &old_vertex_locations
= triangulation.get_vertices();
for (unsigned int vertex=0; vertex<n_vertices; ++vertex)
{
// ignore this vertex if we will keep the boundary and
// this vertex *is* at the boundary
if (keep_boundary && at_boundary[vertex])
new_vertex_locations[vertex] = old_vertex_locations[vertex];
else
{
// compute a random shift vector
Point<spacedim> shift_vector;
for (unsigned int d=0; d<spacedim; ++d)
shift_vector(d) = std::rand()*2.0/RAND_MAX-1;
shift_vector *= factor * minimal_length[vertex] /
std::sqrt(shift_vector.square());
// record new vertex location
new_vertex_locations[vertex] = old_vertex_locations[vertex] + shift_vector;
}
}
// now do the actual move of the vertices
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell=triangulation.begin_active(); cell!=triangulation.end(); ++cell)
for (unsigned int vertex_no=0;
vertex_no<GeometryInfo<dim>::vertices_per_cell; ++vertex_no)
cell->vertex(vertex_no) = new_vertex_locations[cell->vertex_index(vertex_no)];
}
// Correct hanging nodes if necessary
if (dim>=2)
{
// We do the same as in GridTools::transform
//
// exclude hanging nodes at the boundaries of artificial cells:
// these may belong to ghost cells for which we know the exact
// location of vertices, whereas the artificial cell may or may
// not be further refined, and so we cannot know whether
// the location of the hanging node is correct or not
typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active(),
endc = triangulation.end();
for (; cell!=endc; ++cell)
if (!cell->is_artificial())
for (unsigned int face=0;
face<GeometryInfo<dim>::faces_per_cell; ++face)
if (cell->face(face)->has_children() &&
!cell->face(face)->at_boundary())
{
// this face has hanging nodes
if (dim==2)
cell->face(face)->child(0)->vertex(1)
= (cell->face(face)->vertex(0) +
cell->face(face)->vertex(1)) / 2;
else if (dim==3)
{
cell->face(face)->child(0)->vertex(1)
= .5*(cell->face(face)->vertex(0)
+cell->face(face)->vertex(1));
cell->face(face)->child(0)->vertex(2)
= .5*(cell->face(face)->vertex(0)
+cell->face(face)->vertex(2));
cell->face(face)->child(1)->vertex(3)
= .5*(cell->face(face)->vertex(1)
+cell->face(face)->vertex(3));
cell->face(face)->child(2)->vertex(3)
= .5*(cell->face(face)->vertex(2)
+cell->face(face)->vertex(3));
// center of the face
cell->face(face)->child(0)->vertex(3)
= .25*(cell->face(face)->vertex(0)
+cell->face(face)->vertex(1)
+cell->face(face)->vertex(2)
+cell->face(face)->vertex(3));
}
}
}
}
template <int dim, template <int, int> class Container, int spacedim>
unsigned int
find_closest_vertex (const Container<dim,spacedim> &container,
const Point<spacedim> &p)
{
// first get the underlying
// triangulation from the
// container and determine vertices
// and used vertices
const Triangulation<dim, spacedim> &tria = get_tria(container);
const std::vector< Point<spacedim> > &vertices = tria.get_vertices();
const std::vector< bool > &used = tria.get_used_vertices();
// At the beginning, the first
// used vertex is the closest one
std::vector<bool>::const_iterator first =
std::find(used.begin(), used.end(), true);
// Assert that at least one vertex
// is actually used
Assert(first != used.end(), ExcInternalError());
unsigned int best_vertex = std::distance(used.begin(), first);
double best_dist = (p - vertices[best_vertex]).square();
// For all remaining vertices, test
// whether they are any closer
for (unsigned int j = best_vertex+1; j < vertices.size(); j++)
if (used[j])
{
double dist = (p - vertices[j]).square();
if (dist < best_dist)
{
best_vertex = j;
best_dist = dist;
}
}
return best_vertex;
}
template<int dim, template<int, int> class Container, int spacedim>
std::vector<typename Container<dim,spacedim>::active_cell_iterator>
find_cells_adjacent_to_vertex(const Container<dim,spacedim> &container,
const unsigned int vertex)
{
// make sure that the given vertex is
// an active vertex of the underlying
// triangulation
Assert(vertex < get_tria(container).n_vertices(),
ExcIndexRange(0,get_tria(container).n_vertices(),vertex));
Assert(get_tria(container).get_used_vertices()[vertex],
ExcVertexNotUsed(vertex));
// use a set instead of a vector
// to ensure that cells are inserted only
// once
std::set<typename Container<dim,spacedim>::active_cell_iterator> adjacent_cells;
typename Container<dim,spacedim>::active_cell_iterator
cell = container.begin_active(),
endc = container.end();
// go through all active cells and look if the vertex is part of that cell
//
// in 1d, this is all we need to care about. in 2d/3d we also need to worry
// that the vertex might be a hanging node on a face or edge of a cell; in
// this case, we would want to add those cells as well on whose faces the
// vertex is located but for which it is not a vertex itself.
//
// getting this right is a lot simpler in 2d than in 3d. in 2d, a hanging
// node can only be in the middle of a face and we can query the neighboring
// cell from the current cell. on the other hand, in 3d a hanging node
// vertex can also be on an edge but there can be many other cells on
// this edge and we can not access them from the cell we are currently
// on.
//
// so, in the 3d case, if we run the algorithm as in 2d, we catch all
// those cells for which the vertex we seek is on a *subface*, but we
// miss the case of cells for which the vertex we seek is on a
// sub-edge for which there is no corresponding sub-face (because the
// immediate neighbor behind this face is not refined), see for example
// the bits/find_cells_adjacent_to_vertex_6 testcase. thus, if we
// haven't yet found the vertex for the current cell we also need to
// look at the mid-points of edges
//
// as a final note, deciding whether a neighbor is actually coarser is
// simple in the case of isotropic refinement (we just need to look at
// the level of the current and the neighboring cell). however, this
// isn't so simple if we have used anisotropic refinement since then
// the level of a cell is not indicative of whether it is coarser or
// not than the current cell. ultimately, we want to add all cells on
// which the vertex is, independent of whether they are coarser or
// finer and so in the 2d case below we simply add *any* *active* neighbor.
// in the worst case, we add cells multiple times to the adjacent_cells
// list, but std::set throws out those cells already entered
for (; cell != endc; ++cell)
{
for (unsigned int v = 0; v < GeometryInfo<dim>::vertices_per_cell; v++)
if (cell->vertex_index(v) == vertex)
{
// OK, we found a cell that contains
// the given vertex. We add it
// to the list.
adjacent_cells.insert(cell);
// as explained above, in 2+d we need to check whether
// this vertex is on a face behind which there is a
// (possibly) coarser neighbor. if this is the case,
// then we need to also add this neighbor
if (dim >= 2)
for (unsigned int vface = 0; vface < dim; vface++)
{
const unsigned int face =
GeometryInfo<dim>::vertex_to_face[v][vface];
if (!cell->at_boundary(face)
&&
cell->neighbor(face)->active())
{
// there is a (possibly) coarser cell behind a
// face to which the vertex belongs. the
// vertex we are looking at is then either a
// vertex of that coarser neighbor, or it is a
// hanging node on one of the faces of that
// cell. in either case, it is adjacent to the
// vertex, so add it to the list as well (if
// the cell was already in the list then the
// std::set makes sure that we get it only
// once)
adjacent_cells.insert (cell->neighbor(face));
}
}
// in any case, we have found a cell, so go to the next cell
goto next_cell;
}
// in 3d also loop over the edges
if (dim >= 3)
{
for (unsigned int e=0; e<GeometryInfo<dim>::lines_per_cell; ++e)
if (cell->line(e)->has_children())
// the only place where this vertex could have been
// hiding is on the mid-edge point of the edge we
// are looking at
if (cell->line(e)->child(0)->vertex_index(1) == vertex)
{
adjacent_cells.insert(cell);
// jump out of this tangle of nested loops
goto next_cell;
}
}
// in more than 3d we would probably have to do the same as
// above also for even lower-dimensional objects
Assert (dim <= 3, ExcNotImplemented());
// move on to the next cell if we have found the
// vertex on the current one
next_cell:
;
}
// if this was an active vertex then there needs to have been
// at least one cell to which it is adjacent!
Assert (adjacent_cells.size() > 0, ExcInternalError());
// return the result as a vector, rather than the set we built above
return
std::vector<typename Container<dim,spacedim>::active_cell_iterator>
(adjacent_cells.begin(), adjacent_cells.end());
}
namespace
{
template <int dim, template<int, int> class Container, int spacedim>
void find_active_cell_around_point_internal(const Container<dim,spacedim> &container,
std::set<typename Container<dim,spacedim>::active_cell_iterator> &searched_cells,
std::set<typename Container<dim,spacedim>::active_cell_iterator> &adjacent_cells)
{
typedef typename Container<dim,spacedim>::active_cell_iterator cell_iterator;
// update the searched cells
searched_cells.insert(adjacent_cells.begin(), adjacent_cells.end());
// now we to collect all neighbors
// of the cells in adjacent_cells we
// have not yet searched.
std::set<cell_iterator> adjacent_cells_new;
typename std::set<cell_iterator>::const_iterator
cell = adjacent_cells.begin(),
endc = adjacent_cells.end();
for (; cell != endc; ++cell)
{
std::vector<cell_iterator> active_neighbors;
get_active_neighbors<Container<dim, spacedim> >(*cell, active_neighbors);
for (unsigned int i=0; i<active_neighbors.size(); ++i)
if (searched_cells.find(active_neighbors[i]) == searched_cells.end())
adjacent_cells_new.insert(active_neighbors[i]);
}
adjacent_cells.clear();
adjacent_cells.insert(adjacent_cells_new.begin(), adjacent_cells_new.end());
if (adjacent_cells.size() == 0)
{
// we haven't found any other cell that would be a
// neighbor of a previously found cell, but we know
// that we haven't checked all cells yet. that means
// that the domain is disconnected. in that case,
// choose the first previously untouched cell we
// can find
cell_iterator it = container.begin_active();
for ( ; it!=container.end(); ++it)
if (searched_cells.find(it) == searched_cells.end())
{
adjacent_cells.insert(it);
break;
}
}
}
}
template <int dim, template<int, int> class Container, int spacedim>
typename Container<dim,spacedim>::active_cell_iterator
find_active_cell_around_point (const Container<dim,spacedim> &container,
const Point<spacedim> &p)
{
return
find_active_cell_around_point<dim,Container,spacedim>
(StaticMappingQ1<dim,spacedim>::mapping,
container, p).first;
}
template <int dim, template <int, int> class Container, int spacedim>
std::pair<typename Container<dim,spacedim>::active_cell_iterator, Point<dim> >
find_active_cell_around_point (const Mapping<dim,spacedim> &mapping,
const Container<dim,spacedim> &container,
const Point<spacedim> &p)
{
typedef typename Container<dim,spacedim>::active_cell_iterator active_cell_iterator;
// The best distance is set to the
// maximum allowable distance from
// the unit cell; we assume a
// max. deviation of 1e-10
double best_distance = 1e-10;
int best_level = -1;
std::pair<active_cell_iterator, Point<dim> > best_cell;
// Find closest vertex and determine
// all adjacent cells
std::vector<active_cell_iterator> adjacent_cells_tmp
= find_cells_adjacent_to_vertex(container,
find_closest_vertex(container, p));
// Make sure that we have found
// at least one cell adjacent to vertex.
Assert(adjacent_cells_tmp.size()>0, ExcInternalError());
// Copy all the cells into a std::set
std::set<active_cell_iterator> adjacent_cells (adjacent_cells_tmp.begin(),
adjacent_cells_tmp.end());
std::set<active_cell_iterator> searched_cells;
// Determine the maximal number of cells
// in the grid.
// As long as we have not found
// the cell and have not searched
// every cell in the triangulation,
// we keep on looking.
const unsigned int n_active_cells = get_tria(container).n_active_cells();
bool found = false;
unsigned int cells_searched = 0;
while (!found && cells_searched < n_active_cells)
{
typename std::set<active_cell_iterator>::const_iterator
cell = adjacent_cells.begin(),
endc = adjacent_cells.end();
for (; cell != endc; ++cell)
{
try
{
const Point<dim> p_cell = mapping.transform_real_to_unit_cell(*cell, p);
// calculate the infinity norm of
// the distance vector to the unit cell.
const double dist = GeometryInfo<dim>::distance_to_unit_cell(p_cell);
// We compare if the point is inside the
// unit cell (or at least not too far
// outside). If it is, it is also checked
// that the cell has a more refined state
if ((dist < best_distance)
||
((dist == best_distance)
&&
((*cell)->level() > best_level)))
{
found = true;
best_distance = dist;
best_level = (*cell)->level();
best_cell = std::make_pair(*cell, p_cell);
}
}
catch (typename MappingQ1<dim,spacedim>::ExcTransformationFailed &)
{
// ok, the transformation
// failed presumably
// because the point we
// are looking for lies
// outside the current
// cell. this means that
// the current cell can't
// be the cell around the
// point, so just ignore
// this cell and move on
// to the next
}
}
// update the number of cells searched
cells_searched += adjacent_cells.size();
// if we have not found the cell in
// question and have not yet searched every
// cell, we expand our search to
// all the not already searched neighbors of
// the cells in adjacent_cells. This is
// what find_active_cell_around_point_internal
// is for.
if (!found && cells_searched < n_active_cells)
{
find_active_cell_around_point_internal<dim,Container,spacedim>
(container, searched_cells, adjacent_cells);
}
}
AssertThrow (best_cell.first.state() == IteratorState::valid,
ExcPointNotFound<spacedim>(p));
return best_cell;
}
template <int dim, int spacedim>
std::pair<typename hp::DoFHandler<dim,spacedim>::active_cell_iterator, Point<dim> >
find_active_cell_around_point (const hp::MappingCollection<dim,spacedim> &mapping,
const hp::DoFHandler<dim,spacedim> &container,
const Point<spacedim> &p)
{
Assert ((mapping.size() == 1) ||
(mapping.size() == container.get_fe().size()),
ExcMessage ("Mapping collection needs to have either size 1 "
"or size equal to the number of elements in "
"the FECollection."));
typedef typename hp::DoFHandler<dim,spacedim>::active_cell_iterator cell_iterator;
std::pair<cell_iterator, Point<dim> > best_cell;
//If we have only one element in the MappingCollection,
//we use find_active_cell_around_point using only one
//mapping.
if (mapping.size() == 1)
best_cell = find_active_cell_around_point(mapping[0], container, p);
else
{
// The best distance is set to the
// maximum allowable distance from
// the unit cell; we assume a
// max. deviation of 1e-10
double best_distance = 1e-10;
int best_level = -1;
// Find closest vertex and determine
// all adjacent cells
unsigned int vertex = find_closest_vertex(container, p);
std::vector<cell_iterator> adjacent_cells_tmp =
find_cells_adjacent_to_vertex(container, vertex);
// Make sure that we have found
// at least one cell adjacent to vertex.
Assert(adjacent_cells_tmp.size()>0, ExcInternalError());
// Copy all the cells into a std::set
std::set<cell_iterator> adjacent_cells(adjacent_cells_tmp.begin(), adjacent_cells_tmp.end());
std::set<cell_iterator> searched_cells;
// Determine the maximal number of cells
// in the grid.
// As long as we have not found
// the cell and have not searched
// every cell in the triangulation,
// we keep on looking.
const unsigned int n_cells =get_tria(container).n_cells();
bool found = false;
unsigned int cells_searched = 0;
while (!found && cells_searched < n_cells)
{
typename std::set<cell_iterator>::const_iterator
cell = adjacent_cells.begin(),
endc = adjacent_cells.end();
for (; cell != endc; ++cell)
{
try
{
const Point<dim> p_cell = mapping[(*cell)->active_fe_index()].transform_real_to_unit_cell(*cell, p);
// calculate the infinity norm of
// the distance vector to the unit cell.
const double dist = GeometryInfo<dim>::distance_to_unit_cell(p_cell);
// We compare if the point is inside the
// unit cell (or at least not too far
// outside). If it is, it is also checked
// that the cell has a more refined state
if (dist < best_distance ||
(dist == best_distance && (*cell)->level() > best_level))
{
found = true;
best_distance = dist;
best_level = (*cell)->level();
best_cell = std::make_pair(*cell, p_cell);
}
}
catch (typename MappingQ1<dim,spacedim>::ExcTransformationFailed &)
{
// ok, the transformation
// failed presumably
// because the point we
// are looking for lies
// outside the current
// cell. this means that
// the current cell can't
// be the cell around the
// point, so just ignore
// this cell and move on
// to the next
}
}
//udpate the number of cells searched
cells_searched += adjacent_cells.size();
// if we have not found the cell in
// question and have not yet searched every
// cell, we expand our search to
// all the not already searched neighbors of
// the cells in adjacent_cells.
if (!found && cells_searched < n_cells)
{
find_active_cell_around_point_internal<dim,hp::DoFHandler,spacedim>
(container, searched_cells, adjacent_cells);
}
}
}
AssertThrow (best_cell.first.state() == IteratorState::valid,
ExcPointNotFound<spacedim>(p));
return best_cell;
}
template <int dim, int spacedim>
void
get_face_connectivity_of_cells (const Triangulation<dim,spacedim> &triangulation,
SparsityPattern &cell_connectivity)
{
// as built in this function, we
// only consider face neighbors,
// which leads to a fixed number of
// entries per row (don't forget
// that each cell couples with
// itself, and that neighbors can
// be refined)
cell_connectivity.reinit (triangulation.n_active_cells(),
triangulation.n_active_cells(),
GeometryInfo<dim>::faces_per_cell
* GeometryInfo<dim>::max_children_per_face
+
1);
// create a map pair<lvl,idx> -> SparsityPattern index
// TODO: we are no longer using user_indices for this because we can get
// pointer/index clashes when saving/restoring them. The following approach
// works, but this map can get quite big. Not sure about more efficient solutions.
std::map< std::pair<unsigned int,unsigned int>, unsigned int >
indexmap;
unsigned int index = 0;
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell, ++index)
indexmap[std::pair<unsigned int,unsigned int>(cell->level(),cell->index())] = index;
// next loop over all cells and
// their neighbors to build the
// sparsity pattern. note that it's
// a bit hard to enter all the
// connections when a neighbor has
// children since we would need to
// find out which of its children
// is adjacent to the current
// cell. this problem can be
// omitted if we only do something
// if the neighbor has no children
// -- in that case it is either on
// the same or a coarser level than
// we are. in return, we have to
// add entries in both directions
// for both cells
index = 0;
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell, ++index)
{
cell_connectivity.add (index, index);
for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)
if ((cell->at_boundary(f) == false)
&&
(cell->neighbor(f)->has_children() == false))
{
unsigned int other_index = indexmap.find(
std::pair<unsigned int,unsigned int>(cell->neighbor(f)->level(),cell->neighbor(f)->index()))->second;
cell_connectivity.add (index, other_index);
cell_connectivity.add (other_index, index);
}
}
// now compress the so-built connectivity pattern
cell_connectivity.compress ();
}
template <int dim, int spacedim>
void
partition_triangulation (const unsigned int n_partitions,
Triangulation<dim,spacedim> &triangulation)
{
Assert ((dynamic_cast<parallel::distributed::Triangulation<dim,spacedim>*>
(&triangulation)
== 0),
ExcMessage ("Objects of type parallel::distributed::Triangulation "
"are already partitioned implicitly and can not be "
"partitioned again explicitly."));
Assert (n_partitions > 0, ExcInvalidNumberOfPartitions(n_partitions));
// check for an easy return
if (n_partitions == 1)
{
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell)
cell->set_subdomain_id (0);
return;
}
// we decompose the domain by first
// generating the connection graph of all
// cells with their neighbors, and then
// passing this graph off to METIS.
// finally defer to the other function for
// partitioning and assigning subdomain ids
SparsityPattern cell_connectivity;
get_face_connectivity_of_cells (triangulation, cell_connectivity);
partition_triangulation (n_partitions,
cell_connectivity,
triangulation);
}
template <int dim, int spacedim>
void
partition_triangulation (const unsigned int n_partitions,
const SparsityPattern &cell_connection_graph,
Triangulation<dim,spacedim> &triangulation)
{
Assert ((dynamic_cast<parallel::distributed::Triangulation<dim,spacedim>*>
(&triangulation)
== 0),
ExcMessage ("Objects of type parallel::distributed::Triangulation "
"are already partitioned implicitly and can not be "
"partitioned again explicitly."));
Assert (n_partitions > 0, ExcInvalidNumberOfPartitions(n_partitions));
Assert (cell_connection_graph.n_rows() == triangulation.n_active_cells(),
ExcMessage ("Connectivity graph has wrong size"));
Assert (cell_connection_graph.n_cols() == triangulation.n_active_cells(),
ExcMessage ("Connectivity graph has wrong size"));
// check for an easy return
if (n_partitions == 1)
{
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell)
cell->set_subdomain_id (0);
return;
}
// partition this connection graph and get
// back a vector of indices, one per degree
// of freedom (which is associated with a
// cell)
std::vector<unsigned int> partition_indices (triangulation.n_active_cells());
SparsityTools::partition (cell_connection_graph, n_partitions, partition_indices);
// finally loop over all cells and set the
// subdomain ids
unsigned int index = 0;
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell, ++index)
cell->set_subdomain_id (partition_indices[index]);
}
template <int dim, int spacedim>
void
get_subdomain_association (const Triangulation<dim, spacedim> &triangulation,
std::vector<types::subdomain_id> &subdomain)
{
Assert (subdomain.size() == triangulation.n_active_cells(),
ExcDimensionMismatch (subdomain.size(),
triangulation.n_active_cells()));
unsigned int index = 0;
for (typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell!=triangulation.end(); ++cell, ++index)
subdomain[index] = cell->subdomain_id();
Assert (index == subdomain.size(), ExcInternalError());
}
template <int dim, int spacedim>
unsigned int
count_cells_with_subdomain_association (const Triangulation<dim, spacedim> &triangulation,
const types::subdomain_id subdomain)
{
unsigned int count = 0;
for (typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell!=triangulation.end(); ++cell)
if (cell->subdomain_id() == subdomain)
++count;
return count;
}
template <int dim, int spacedim>
std::vector<bool>
get_locally_owned_vertices (const Triangulation<dim,spacedim> &triangulation)
{
// start with all vertices
std::vector<bool> locally_owned_vertices = triangulation.get_used_vertices();
// if the triangulation is distributed, eliminate those that
// are owned by other processors -- either because the vertex is
// on an artificial cell, or because it is on a ghost cell with
// a smaller subdomain
if (const parallel::distributed::Triangulation<dim,spacedim> *tr
= dynamic_cast<const parallel::distributed::Triangulation<dim,spacedim> *>
(&triangulation))
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell)
if (cell->is_artificial()
||
(cell->is_ghost() &&
(cell->subdomain_id() < tr->locally_owned_subdomain())))
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
locally_owned_vertices[cell->vertex_index(v)] = false;
return locally_owned_vertices;
}
template <typename Container>
std::list<std::pair<typename Container::cell_iterator,
typename Container::cell_iterator> >
get_finest_common_cells (const Container &mesh_1,
const Container &mesh_2)
{
Assert (have_same_coarse_mesh (mesh_1, mesh_2),
ExcMessage ("The two containers must be represent triangulations that "
"have the same coarse meshes"));
// the algorithm goes as follows:
// first, we fill a list with pairs
// of iterators common to the two
// meshes on the coarsest
// level. then we traverse the
// list; each time, we find a pair
// of iterators for which both
// correspond to non-active cells,
// we delete this item and push the
// pairs of iterators to their
// children to the back. if these
// again both correspond to
// non-active cells, we will get to
// the later on for further
// consideration
typedef
std::list<std::pair<typename Container::cell_iterator,
typename Container::cell_iterator> >
CellList;
CellList cell_list;
// first push the coarse level cells
typename Container::cell_iterator
cell_1 = mesh_1.begin(0),
cell_2 = mesh_2.begin(0);
for (; cell_1 != mesh_1.end(0); ++cell_1, ++cell_2)
cell_list.push_back (std::make_pair (cell_1, cell_2));
// then traverse list as described
// above
typename CellList::iterator cell_pair = cell_list.begin();
while (cell_pair != cell_list.end())
{
// if both cells in this pair
// have children, then erase
// this element and push their
// children instead
if (cell_pair->first->has_children()
&&
cell_pair->second->has_children())
{
Assert(cell_pair->first->refinement_case()==
cell_pair->second->refinement_case(), ExcNotImplemented());
for (unsigned int c=0; c<cell_pair->first->n_children(); ++c)
cell_list.push_back (std::make_pair (cell_pair->first->child(c),
cell_pair->second->child(c)));
// erasing an iterator
// keeps other iterators
// valid, so already
// advance the present
// iterator by one and then
// delete the element we've
// visited before
const typename CellList::iterator previous_cell_pair = cell_pair;
++cell_pair;
cell_list.erase (previous_cell_pair);
}
else
// both cells are active, do
// nothing
++cell_pair;
}
// just to make sure everything is ok,
// validate that all pairs have at least one
// active iterator or have different
// refinement_cases
for (cell_pair = cell_list.begin(); cell_pair != cell_list.end(); ++cell_pair)
Assert (cell_pair->first->active()
||
cell_pair->second->active()
||
(cell_pair->first->refinement_case()
!= cell_pair->second->refinement_case()),
ExcInternalError());
return cell_list;
}
template <int dim, int spacedim>
bool
have_same_coarse_mesh (const Triangulation<dim, spacedim> &mesh_1,
const Triangulation<dim, spacedim> &mesh_2)
{
// make sure the two meshes have
// the same number of coarse cells
if (mesh_1.n_cells (0) != mesh_2.n_cells (0))
return false;
// if so, also make sure they have
// the same vertices on the cells
// of the coarse mesh
typename Triangulation<dim, spacedim>::cell_iterator
cell_1 = mesh_1.begin(0),
cell_2 = mesh_2.begin(0),
endc = mesh_1.end(0);
for (; cell_1!=endc; ++cell_1, ++cell_2)
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
if (cell_1->vertex(v) != cell_2->vertex(v))
return false;
// if we've gotten through all
// this, then the meshes really
// seem to have a common coarse
// mesh
return true;
}
template <typename Container>
bool
have_same_coarse_mesh (const Container &mesh_1,
const Container &mesh_2)
{
return have_same_coarse_mesh (get_tria(mesh_1),
get_tria(mesh_2));
}
template <int dim, int spacedim>
double
minimal_cell_diameter (const Triangulation<dim, spacedim> &triangulation)
{
double min_diameter = triangulation.begin_active()->diameter();
for (typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active(); cell != triangulation.end();
++cell)
min_diameter = std::min (min_diameter,
cell->diameter());
return min_diameter;
}
template <int dim, int spacedim>
double
maximal_cell_diameter (const Triangulation<dim, spacedim> &triangulation)
{
double max_diameter = triangulation.begin_active()->diameter();
for (typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active(); cell != triangulation.end();
++cell)
max_diameter = std::max (max_diameter,
cell->diameter());
return max_diameter;
}
template <int dim, int spacedim>
void
create_union_triangulation (const Triangulation<dim, spacedim> &triangulation_1,
const Triangulation<dim, spacedim> &triangulation_2,
Triangulation<dim, spacedim> &result)
{
// this function is deprecated. call the function that replaced it
GridGenerator::create_union_triangulation (triangulation_1, triangulation_2, result);
}
namespace internal
{
namespace FixUpDistortedChildCells
{
// compute the mean square
// deviation of the alternating
// forms of the children of the
// given object from that of
// the object itself. for
// objects with
// structdim==spacedim, the
// alternating form is the
// determinant of the jacobian,
// whereas for faces with
// structdim==spacedim-1, the
// alternating form is the
// (signed and scaled) normal
// vector
//
// this average square
// deviation is computed for an
// object where the center node
// has been replaced by the
// second argument to this
// function
template <typename Iterator, int spacedim>
double
objective_function (const Iterator &object,
const Point<spacedim> &object_mid_point)
{
const unsigned int structdim = Iterator::AccessorType::structure_dimension;
Assert (spacedim == Iterator::AccessorType::dimension,
ExcInternalError());
// everything below is wrong
// if not for the following
// condition
Assert (object->refinement_case() == RefinementCase<structdim>::isotropic_refinement,
ExcNotImplemented());
// first calculate the
// average alternating form
// for the parent cell/face
Point<spacedim> parent_vertices
[GeometryInfo<structdim>::vertices_per_cell];
Tensor<spacedim-structdim,spacedim> parent_alternating_forms
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
parent_vertices[i] = object->vertex(i);
GeometryInfo<structdim>::alternating_form_at_vertices (parent_vertices,
parent_alternating_forms);
const Tensor<spacedim-structdim,spacedim>
average_parent_alternating_form
= std::accumulate (&parent_alternating_forms[0],
&parent_alternating_forms[GeometryInfo<structdim>::vertices_per_cell],
Tensor<spacedim-structdim,spacedim>());
// now do the same
// computation for the
// children where we use the
// given location for the
// object mid point instead of
// the one the triangulation
// currently reports
Point<spacedim> child_vertices
[GeometryInfo<structdim>::max_children_per_cell]
[GeometryInfo<structdim>::vertices_per_cell];
Tensor<spacedim-structdim,spacedim> child_alternating_forms
[GeometryInfo<structdim>::max_children_per_cell]
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
child_vertices[c][i] = object->child(c)->vertex(i);
// replace mid-object
// vertex. note that for
// child i, the mid-object
// vertex happens to have the
// number
// max_children_per_cell-i
for (unsigned int c=0; c<object->n_children(); ++c)
child_vertices[c][GeometryInfo<structdim>::max_children_per_cell-c-1]
= object_mid_point;
for (unsigned int c=0; c<object->n_children(); ++c)
GeometryInfo<structdim>::alternating_form_at_vertices (child_vertices[c],
child_alternating_forms[c]);
// on a uniformly refined
// hypercube object, the child
// alternating forms should
// all be smaller by a factor
// of 2^structdim than the
// ones of the parent. as a
// consequence, we'll use the
// squared deviation from
// this ideal value as an
// objective function
double objective = 0;
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
objective += (child_alternating_forms[c][i] -
average_parent_alternating_form/std::pow(2.,1.*structdim))
.norm_square();
return objective;
}
/**
* Return the location of the midpoint
* of the 'f'th face (vertex) of this 1d
* object.
*/
template <typename Iterator>
Point<Iterator::AccessorType::space_dimension>
get_face_midpoint (const Iterator &object,
const unsigned int f,
dealii::internal::int2type<1>)
{
return object->vertex(f);
}
/**
* Return the location of the midpoint
* of the 'f'th face (line) of this 2d
* object.
*/
template <typename Iterator>
Point<Iterator::AccessorType::space_dimension>
get_face_midpoint (const Iterator &object,
const unsigned int f,
dealii::internal::int2type<2>)
{
return object->line(f)->center();
}
/**
* Return the location of the midpoint
* of the 'f'th face (quad) of this 3d
* object.
*/
template <typename Iterator>
Point<Iterator::AccessorType::space_dimension>
get_face_midpoint (const Iterator &object,
const unsigned int f,
dealii::internal::int2type<3>)
{
return object->face(f)->center();
}
/**
* Compute the minimal diameter of an
* object by looking for the minimal
* distance between the mid-points of
* its faces. This minimal diameter is
* used to determine the step length
* for our grid cell improvement
* algorithm, and it should be small
* enough that the point moves around
* within the cell even if it is highly
* elongated -- thus, the diameter of
* the object is not a good measure,
* while the minimal diameter is. Note
* that the algorithm below works for
* both cells that are long rectangles
* with parallel sides where the
* nearest distance is between opposite
* edges as well as highly slanted
* parallelograms where the shortest
* distance is between neighboring
* edges.
*/
template <typename Iterator>
double
minimal_diameter (const Iterator &object)
{
const unsigned int
structdim = Iterator::AccessorType::structure_dimension;
double diameter = object->diameter();
for (unsigned int f=0;
f<GeometryInfo<structdim>::faces_per_cell;
++f)
for (unsigned int e=f+1;
e<GeometryInfo<structdim>::faces_per_cell;
++e)
diameter = std::min (diameter,
get_face_midpoint
(object, f,
dealii::internal::int2type<structdim>())
.distance (get_face_midpoint
(object,
e,
dealii::internal::int2type<structdim>())));
return diameter;
}
/**
* Try to fix up a single cell. Return
* whether we succeeded with this.
*
* The second argument indicates
* whether we need to respect the
* manifold/boundary on which this
* object lies when moving around its
* mid-point.
*/
template <typename Iterator>
bool
fix_up_object (const Iterator &object,
const bool respect_manifold)
{
const Boundary<Iterator::AccessorType::dimension,
Iterator::AccessorType::space_dimension>
*manifold = (respect_manifold ?
&object->get_boundary() :
0);
const unsigned int structdim = Iterator::AccessorType::structure_dimension;
const unsigned int spacedim = Iterator::AccessorType::space_dimension;
// right now we can only deal
// with cells that have been
// refined isotropically
// because that is the only
// case where we have a cell
// mid-point that can be moved
// around without having to
// consider boundary
// information
Assert (object->has_children(), ExcInternalError());
Assert (object->refinement_case() == RefinementCase<structdim>::isotropic_refinement,
ExcNotImplemented());
// get the current location of
// the object mid-vertex:
Point<spacedim> object_mid_point
= object->child(0)->vertex (GeometryInfo<structdim>::max_children_per_cell-1);
// now do a few steepest descent
// steps to reduce the objective
// function. compute the diameter in
// the helper function above
unsigned int iteration = 0;
const double diameter = minimal_diameter (object);
// current value of objective
// function and initial delta
double current_value = objective_function (object, object_mid_point);
double initial_delta = 0;
do
{
// choose a step length
// that is initially 1/4
// of the child objects'
// diameter, and a sequence
// whose sum does not
// converge (to avoid
// premature termination of
// the iteration)
const double step_length = diameter / 4 / (iteration + 1);
// compute the objective
// function's derivative using a
// two-sided difference formula
// with eps=step_length/10
Tensor<1,spacedim> gradient;
for (unsigned int d=0; d<spacedim; ++d)
{
const double eps = step_length/10;
Point<spacedim> h;
h[d] = eps/2;
if (respect_manifold == false)
gradient[d]
= ((objective_function (object, object_mid_point + h)
-
objective_function (object, object_mid_point - h))
/
eps);
else
gradient[d]
= ((objective_function (object,
manifold->project_to_surface(object,
object_mid_point + h))
-
objective_function (object,
manifold->project_to_surface(object,
object_mid_point - h)))
/
eps);
}
// sometimes, the
// (unprojected) gradient
// is perpendicular to
// the manifold, but we
// can't go there if
// respect_manifold==true. in
// that case, gradient=0,
// and we simply need to
// quite the loop here
if (gradient.norm() == 0)
break;
// so we need to go in
// direction -gradient. the
// optimal value of the
// objective function is
// zero, so assuming that
// the model is quadratic
// we would have to go
// -2*val/||gradient|| in
// this direction, make
// sure we go at most
// step_length into this
// direction
object_mid_point -= std::min(2 * current_value / (gradient*gradient),
step_length / gradient.norm()) *
gradient;
if (respect_manifold == true)
object_mid_point = manifold->project_to_surface(object,
object_mid_point);
// compute current value of the
// objective function
const double previous_value = current_value;
current_value = objective_function (object, object_mid_point);
if (iteration == 0)
initial_delta = (previous_value - current_value);
// stop if we aren't moving much
// any more
if ((iteration >= 1) &&
((previous_value - current_value < 0)
||
(std::fabs (previous_value - current_value)
<
0.001 * initial_delta)))
break;
++iteration;
}
while (iteration < 20);
// verify that the new
// location is indeed better
// than the one before. check
// this by comparing whether
// the minimum value of the
// products of parent and
// child alternating forms is
// positive. for cells this
// means that the
// determinants have the same
// sign, for faces that the
// face normals of parent and
// children point in the same
// general direction
double old_min_product, new_min_product;
Point<spacedim> parent_vertices
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
parent_vertices[i] = object->vertex(i);
Tensor<spacedim-structdim,spacedim> parent_alternating_forms
[GeometryInfo<structdim>::vertices_per_cell];
GeometryInfo<structdim>::alternating_form_at_vertices (parent_vertices,
parent_alternating_forms);
Point<spacedim> child_vertices
[GeometryInfo<structdim>::max_children_per_cell]
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
child_vertices[c][i] = object->child(c)->vertex(i);
Tensor<spacedim-structdim,spacedim> child_alternating_forms
[GeometryInfo<structdim>::max_children_per_cell]
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int c=0; c<object->n_children(); ++c)
GeometryInfo<structdim>::alternating_form_at_vertices (child_vertices[c],
child_alternating_forms[c]);
old_min_product = child_alternating_forms[0][0] * parent_alternating_forms[0];
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
for (unsigned int j=0; j<GeometryInfo<structdim>::vertices_per_cell; ++j)
old_min_product = std::min (old_min_product,
child_alternating_forms[c][i] *
parent_alternating_forms[j]);
// for the new minimum value,
// replace mid-object
// vertex. note that for child
// i, the mid-object vertex
// happens to have the number
// max_children_per_cell-i
for (unsigned int c=0; c<object->n_children(); ++c)
child_vertices[c][GeometryInfo<structdim>::max_children_per_cell-c-1]
= object_mid_point;
for (unsigned int c=0; c<object->n_children(); ++c)
GeometryInfo<structdim>::alternating_form_at_vertices (child_vertices[c],
child_alternating_forms[c]);
new_min_product = child_alternating_forms[0][0] * parent_alternating_forms[0];
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
for (unsigned int j=0; j<GeometryInfo<structdim>::vertices_per_cell; ++j)
new_min_product = std::min (new_min_product,
child_alternating_forms[c][i] *
parent_alternating_forms[j]);
// if new minimum value is
// better than before, then set the
// new mid point. otherwise
// return this object as one of
// those that can't apparently
// be fixed
if (new_min_product >= old_min_product)
object->child(0)->vertex (GeometryInfo<structdim>::max_children_per_cell-1)
= object_mid_point;
// return whether after this
// operation we have an object that
// is well oriented
return (std::max (new_min_product, old_min_product) > 0);
}
void fix_up_faces (const dealii::Triangulation<1,1>::cell_iterator &,
dealii::internal::int2type<1>,
dealii::internal::int2type<1>)
{
// nothing to do for the faces of
// cells in 1d
}
// possibly fix up the faces of
// a cell by moving around its
// mid-points
template <int structdim, int spacedim>
void fix_up_faces (const typename dealii::Triangulation<structdim,spacedim>::cell_iterator &cell,
dealii::internal::int2type<structdim>,
dealii::internal::int2type<spacedim>)
{
// see if we first can fix up
// some of the faces of this
// object. we can mess with
// faces if and only if it is
// not at the boundary (since
// otherwise the location of
// the face mid-point has been
// determined by the boundary
// object) and if the
// neighboring cell is not even
// more refined than we are
// (since in that case the
// sub-faces have themselves
// children that we can't move
// around any more). however,
// the latter case shouldn't
// happen anyway: if the
// current face is distorted
// but the neighbor is even
// more refined, then the face
// had been deformed before
// already, and had been
// ignored at the time; we
// should then also be able to
// ignore it this time as well
for (unsigned int f=0; f<GeometryInfo<structdim>::faces_per_cell; ++f)
{
Assert (cell->face(f)->has_children(), ExcInternalError());
Assert (cell->face(f)->refinement_case() ==
RefinementCase<structdim-1>::isotropic_refinement,
ExcInternalError());
bool subface_is_more_refined = false;
for (unsigned int g=0; g<GeometryInfo<structdim>::max_children_per_face; ++g)
if (cell->face(f)->child(g)->has_children())
{
subface_is_more_refined = true;
break;
}
if (subface_is_more_refined == true)
continue;
// so, now we finally know
// that we can do something
// about this face
fix_up_object (cell->face(f), cell->at_boundary(f));
}
}
} /* namespace FixUpDistortedChildCells */
} /* namespace internal */
template <int dim, int spacedim>
typename Triangulation<dim,spacedim>::DistortedCellList
fix_up_distorted_child_cells (const typename Triangulation<dim,spacedim>::DistortedCellList &distorted_cells,
Triangulation<dim,spacedim> &/*triangulation*/)
{
typename Triangulation<dim,spacedim>::DistortedCellList unfixable_subset;
// loop over all cells that we have
// to fix up
for (typename std::list<typename Triangulation<dim,spacedim>::cell_iterator>::const_iterator
cell_ptr = distorted_cells.distorted_cells.begin();
cell_ptr != distorted_cells.distorted_cells.end(); ++cell_ptr)
{
const typename Triangulation<dim,spacedim>::cell_iterator
cell = *cell_ptr;
internal::FixUpDistortedChildCells
::fix_up_faces (cell,
dealii::internal::int2type<dim>(),
dealii::internal::int2type<spacedim>());
// fix up the object. we need to
// respect the manifold if the cell is
// embedded in a higher dimensional
// space; otherwise, like a hex in 3d,
// every point within the cell interior
// is fair game
if (! internal::FixUpDistortedChildCells::fix_up_object (cell,
(dim < spacedim)))
unfixable_subset.distorted_cells.push_back (cell);
}
return unfixable_subset;
}
template <class Container>
std::vector<typename Container::active_cell_iterator>
get_patch_around_cell(const typename Container::active_cell_iterator &cell)
{
Assert (cell->is_locally_owned(),
ExcMessage ("This function only makes sense if the cell for "
"which you are asking for a patch, is locally "
"owned."));
std::vector<typename Container::active_cell_iterator> patch;
patch.push_back (cell);
for (unsigned int face_number=0; face_number<GeometryInfo<Container::dimension>::faces_per_cell; ++face_number)
if (cell->face(face_number)->at_boundary()==false)
{
if (cell->neighbor(face_number)->has_children() == false)
patch.push_back (cell->neighbor(face_number));
else
// the neighbor is refined. in 2d/3d, we can simply ask for the children
// of the neighbor because they can not be further refined and,
// consequently, the children is active
if (Container::dimension > 1)
{
for (unsigned int subface=0; subface<cell->face(face_number)->n_children(); ++subface)
patch.push_back (cell->neighbor_child_on_subface (face_number, subface));
}
else
{
// in 1d, we need to work a bit harder: iterate until we find
// the child by going from cell to child to child etc
typename Container::cell_iterator neighbor
= cell->neighbor (face_number);
while (neighbor->has_children())
neighbor = neighbor->child(1-face_number);
Assert (neighbor->neighbor(1-face_number) == cell, ExcInternalError());
patch.push_back (neighbor);
}
}
return patch;
}
template <template <int,int> class Container, int dim, int spacedim>
#ifndef _MSC_VER
std::map<typename Container<dim-1,spacedim>::cell_iterator,
typename Container<dim,spacedim>::face_iterator>
#else
typename ExtractBoundaryMesh<Container,dim,spacedim>::return_type
#endif
extract_boundary_mesh (const Container<dim,spacedim> &volume_mesh,
Container<dim-1,spacedim> &surface_mesh,
const std::set<types::boundary_id> &boundary_ids)
{
// this function is deprecated. call the one that replaced it
return GridGenerator::extract_boundary_mesh (volume_mesh, surface_mesh, boundary_ids);
}
/*
* Internally used in orthogonal_equality
*
* An orthogonal equality test for points:
*
* point1 and point2 are considered equal, if
* (point1 + offset) - point2
* is parallel to the unit vector in <direction>
*/
template<int spacedim>
inline bool orthogonal_equality (const dealii::Point<spacedim> &point1,
const dealii::Point<spacedim> &point2,
const int direction,
const dealii::Tensor<1,spacedim> &offset)
{
Assert (0<=direction && direction<spacedim,
ExcIndexRange (direction, 0, spacedim));
for (int i = 0; i < spacedim; ++i)
{
// Only compare coordinate-components != direction:
if (i == direction)
continue;
if (fabs(point1(i) + offset[i] - point2(i)) > 1.e-10)
return false;
}
return true;
}
/*
* Internally used in orthogonal_equality
*
* A lookup table to transform vertex matchings to orientation flags of
* the form (face_orientation, face_flip, face_rotation)
*
* See the comment on the next function as well as the detailed
* documentation of make_periodicity_constraints and
* collect_periodic_faces for details
*/
template<int dim> struct OrientationLookupTable {};
template<> struct OrientationLookupTable<1>
{
typedef std_cxx11::array<unsigned int, GeometryInfo<1>::vertices_per_face> MATCH_T;
static inline std::bitset<3> lookup (const MATCH_T &)
{
// The 1D case is trivial
return 4; // [true ,false,false]
}
};
template<> struct OrientationLookupTable<2>
{
typedef std_cxx11::array<unsigned int, GeometryInfo<2>::vertices_per_face> MATCH_T;
static inline std::bitset<3> lookup (const MATCH_T &matching)
{
// In 2D matching faces (=lines) results in two cases: Either
// they are aligned or flipped. We store this "line_flip"
// property somewhat sloppy as "face_flip"
// (always: face_orientation = true, face_rotation = false)
static const MATCH_T m_tff = {{ 0 , 1 }};
if (matching == m_tff) return 1; // [true ,false,false]
static const MATCH_T m_ttf = {{ 1 , 0 }};
if (matching == m_ttf) return 3; // [true ,true ,false]
AssertThrow(false, ExcInternalError());
// what follows is dead code, but it avoids warnings about the lack
// of a return value
return 0;
}
};
template<> struct OrientationLookupTable<3>
{
typedef std_cxx11::array<unsigned int, GeometryInfo<3>::vertices_per_face> MATCH_T;
static inline std::bitset<3> lookup (const MATCH_T &matching)
{
// The full fledged 3D case. *Yay*
// See the documentation in include/deal.II/base/geometry_info.h
// as well as the actual implementation in source/grid/tria.cc
// for more details...
static const MATCH_T m_tff = {{ 0 , 1 , 2 , 3 }};
if (matching == m_tff) return 1; // [true ,false,false]
static const MATCH_T m_tft = {{ 1 , 3 , 0 , 2 }};
if (matching == m_tft) return 5; // [true ,false,true ]
static const MATCH_T m_ttf = {{ 3 , 2 , 1 , 0 }};
if (matching == m_ttf) return 3; // [true ,true ,false]
static const MATCH_T m_ttt = {{ 2 , 0 , 3 , 1 }};
if (matching == m_ttt) return 7; // [true ,true ,true ]
static const MATCH_T m_fff = {{ 0 , 2 , 1 , 3 }};
if (matching == m_fff) return 0; // [false,false,false]
static const MATCH_T m_fft = {{ 2 , 3 , 0 , 1 }};
if (matching == m_fft) return 4; // [false,false,true ]
static const MATCH_T m_ftf = {{ 3 , 1 , 2 , 0 }};
if (matching == m_ftf) return 2; // [false,true ,false]
static const MATCH_T m_ftt = {{ 1 , 0 , 3 , 2 }};
if (matching == m_ftt) return 6; // [false,true ,true ]
AssertThrow(false, ExcInternalError());
// what follows is dead code, but it avoids warnings about the lack
// of a return value
return 0;
}
};
template<typename FaceIterator>
inline bool
orthogonal_equality (std::bitset<3> &orientation,
const FaceIterator &face1,
const FaceIterator &face2,
const int direction,
const dealii::Tensor<1,FaceIterator::AccessorType::space_dimension> &offset)
{
static const int dim = FaceIterator::AccessorType::dimension;
// Do a full matching of the face vertices:
std_cxx11::
array<unsigned int, GeometryInfo<dim>::vertices_per_face> matching;
std::set<unsigned int> face2_vertices;
for (unsigned int i = 0; i < GeometryInfo<dim>::vertices_per_face; ++i)
face2_vertices.insert(i);
for (unsigned int i = 0; i < GeometryInfo<dim>::vertices_per_face; ++i)
{
for (std::set<unsigned int>::iterator it = face2_vertices.begin();
it != face2_vertices.end();
it++)
{
if (orthogonal_equality(face1->vertex(i),face2->vertex(*it),
direction, offset))
{
matching[i] = *it;
face2_vertices.erase(it);
break; // jump out of the innermost loop
}
}
}
// And finally, a lookup to determine the ordering bitmask:
if (face2_vertices.empty())
orientation = OrientationLookupTable<dim>::lookup(matching);
return face2_vertices.empty();
}
template<typename FaceIterator>
inline bool
orthogonal_equality (const FaceIterator &face1,
const FaceIterator &face2,
const int direction,
const dealii::Tensor<1,FaceIterator::AccessorType::space_dimension> &offset)
{
// Call the function above with a dummy orientation array
std::bitset<3> dummy;
return orthogonal_equality (dummy, face1, face2, direction, offset);
}
/*
* Internally used in collect_periodic_faces
*/
template<typename CellIterator>
void
match_periodic_face_pairs
(std::set<std::pair<CellIterator, unsigned int> > &pairs1,
std::set<std::pair<typename identity<CellIterator>::type, unsigned int> > &pairs2,
const int direction,
std::vector<PeriodicFacePair<CellIterator> > &matched_pairs,
const dealii::Tensor<1,CellIterator::AccessorType::space_dimension> &offset)
{
static const int space_dim = CellIterator::AccessorType::space_dimension;
Assert (0<=direction && direction<space_dim,
ExcIndexRange (direction, 0, space_dim));
Assert (pairs1.size() == pairs2.size(),
ExcMessage ("Unmatched faces on periodic boundaries"));
unsigned int n_matches = 0;
// Match with a complexity of O(n^2). This could be improved...
std::bitset<3> orientation;
typedef typename std::set
<std::pair<CellIterator, unsigned int> >::const_iterator PairIterator;
for (PairIterator it1 = pairs1.begin(); it1 != pairs1.end(); ++it1)
{
for (PairIterator it2 = pairs2.begin(); it2 != pairs2.end(); ++it2)
{
const CellIterator cell1 = it1->first;
const CellIterator cell2 = it2->first;
const unsigned int face_idx1 = it1->second;
const unsigned int face_idx2 = it2->second;
if (GridTools::orthogonal_equality(orientation,
cell1->face(face_idx1),
cell2->face(face_idx2),
direction, offset))
{
// We have a match, so insert the matching pairs and
// remove the matched cell in pairs2 to speed up the
// matching:
const PeriodicFacePair<CellIterator> matched_face
= {{cell1, cell2},{face_idx1, face_idx2}, orientation};
matched_pairs.push_back(matched_face);
pairs2.erase(it2);
++n_matches;
break;
}
}
}
//Assure that all faces are matched
AssertThrow (n_matches == pairs1.size() && pairs2.size() == 0,
ExcMessage ("Unmatched faces on periodic boundaries"));
}
template<typename CONTAINER>
void
collect_periodic_faces
(const CONTAINER &container,
const types::boundary_id b_id1,
const types::boundary_id b_id2,
const int direction,
std::vector<PeriodicFacePair<typename CONTAINER::cell_iterator> > &matched_pairs,
const dealii::Tensor<1,CONTAINER::space_dimension> &offset)
{
static const int dim = CONTAINER::dimension;
static const int space_dim = CONTAINER::space_dimension;
Assert (0<=direction && direction<space_dim,
ExcIndexRange (direction, 0, space_dim));
// Loop over all cells on the highest level and collect all boundary
// faces belonging to b_id1 and b_id2:
std::set<std::pair<typename CONTAINER::cell_iterator, unsigned int> > pairs1;
std::set<std::pair<typename CONTAINER::cell_iterator, unsigned int> > pairs2;
for (typename CONTAINER::cell_iterator cell = container.begin(0);
cell != container.end(0); ++cell)
{
for (unsigned int i = 0; i < GeometryInfo<dim>::faces_per_cell; ++i)
{
const typename CONTAINER::face_iterator face = cell->face(i);
if (face->at_boundary() && face->boundary_indicator() == b_id1)
{
const std::pair<typename CONTAINER::cell_iterator, unsigned int> pair1
= std::make_pair(cell, i);
pairs1.insert(pair1);
}
if (face->at_boundary() && face->boundary_indicator() == b_id2)
{
const std::pair<typename CONTAINER::cell_iterator, unsigned int> pair2
= std::make_pair(cell, i);
pairs2.insert(pair2);
}
}
}
Assert (pairs1.size() == pairs2.size(),
ExcMessage ("Unmatched faces on periodic boundaries"));
// and call match_periodic_face_pairs that does the actual matching:
match_periodic_face_pairs(pairs1, pairs2, direction, matched_pairs, offset);
}
template<typename CONTAINER>
void
collect_periodic_faces
(const CONTAINER &container,
const types::boundary_id b_id,
const int direction,
std::vector<PeriodicFacePair<typename CONTAINER::cell_iterator> > &matched_pairs,
const dealii::Tensor<1,CONTAINER::space_dimension> &offset)
{
static const int dim = CONTAINER::dimension;
static const int space_dim = CONTAINER::space_dimension;
Assert (0<=direction && direction<space_dim,
ExcIndexRange (direction, 0, space_dim));
Assert(dim == space_dim,
ExcNotImplemented());
// Loop over all cells on the highest level and collect all boundary
// faces 2*direction and 2*direction*1:
std::set<std::pair<typename CONTAINER::cell_iterator, unsigned int> > pairs1;
std::set<std::pair<typename CONTAINER::cell_iterator, unsigned int> > pairs2;
for (typename CONTAINER::cell_iterator cell = container.begin(0);
cell != container.end(0); ++cell)
{
const typename CONTAINER::face_iterator face_1 = cell->face(2*direction);
const typename CONTAINER::face_iterator face_2 = cell->face(2*direction+1);
if (face_1->at_boundary() && face_1->boundary_indicator() == b_id)
{
const std::pair<typename CONTAINER::cell_iterator, unsigned int> pair1
= std::make_pair(cell, 2*direction);
pairs1.insert(pair1);
}
if (face_2->at_boundary() && face_2->boundary_indicator() == b_id)
{
const std::pair<typename CONTAINER::cell_iterator, unsigned int> pair2
= std::make_pair(cell, 2*direction+1);
pairs2.insert(pair2);
}
}
Assert (pairs1.size() == pairs2.size(),
ExcMessage ("Unmatched faces on periodic boundaries"));
#ifdef DEBUG
const unsigned int size_old = matched_pairs.size();
#endif
// and call match_periodic_face_pairs that does the actual matching:
match_periodic_face_pairs(pairs1, pairs2, direction, matched_pairs, offset);
#ifdef DEBUG
//check for standard orientation
const unsigned int size_new = matched_pairs.size();
for (unsigned int i = size_old; i < size_new; ++i)
{
Assert(matched_pairs[i].orientation == 1,
ExcMessage("Found a face match with non standard orientation. "
"This function is only suitable for meshes with cells "
"in default orientation"));
}
#endif
}
} /* namespace GridTools */
// explicit instantiations
#include "grid_tools.inst"
DEAL_II_NAMESPACE_CLOSE
|
/* http.cc
Mathieu Stefani, 13 August 2015
Http layer implementation
*/
#include <cstring>
#include <iostream>
#include <stdexcept>
#include "common.h"
#include "http.h"
#include "net.h"
#include "peer.h"
using namespace std;
namespace Net {
namespace Http {
static constexpr char CR = 0xD;
static constexpr char LF = 0xA;
static constexpr char CRLF[] = {CR, LF};
namespace Private {
Parser::Buffer::Buffer()
: len(0)
{
memset(data, sizeof data, 0);
}
void
Parser::Buffer::reset() {
memset(data, sizeof data, 0);
len = 0;
}
bool
Parser::Cursor::advance(size_t count)
{
if (value + count >= sizeof (buff.data)) {
//parser->raise("Early EOF");
}
// Allowed to advance one past the end
else if (value + count > buff.len) {
return false;
}
value += count;
return true;
}
bool
Parser::Cursor::eol() const {
return buff.data[value] == CR && next() == LF;
}
int
Parser::Cursor::next() const {
if (value + 1 >= sizeof (buff.data)) {
//parser->raise("Early EOF");
}
else if (value + 1 >= buff.len) {
return Eof;
}
return buff.data[value + 1];
}
char
Parser::Cursor::current() const {
return buff.data[value];
}
const char *
Parser::Cursor::offset() const {
return buff.data + value;
}
const char *
Parser::Cursor::offset(size_t off) const {
return buff.data + off;
}
size_t
Parser::Cursor::diff(size_t other) const {
return value - other;
}
size_t
Parser::Cursor::diff(const Cursor& other) const {
return value - other.value;
}
size_t
Parser::Cursor::remaining() const {
// assert(val <= buff.len);
return buff.len - value;
}
void
Parser::Cursor::reset() {
value = 0;
}
void
Parser::Step::raise(const char* msg, Code code /* = Code::Bad_Request */) {
throw HttpError(code, msg);
}
Parser::State
Parser::RequestLineStep::apply(Cursor& cursor) {
Cursor::Revert revert(cursor);
auto tryMatch = [&](const char* const str) {
const size_t len = std::strlen(str);
if (strncmp(cursor.offset(), str, len) == 0) {
cursor.advance(len - 1);
return true;
}
return false;
};
// Method
if (tryMatch("OPTIONS")) {
request->method = Method::Options;
}
else if (tryMatch("GET")) {
request->method = Method::Get;
}
else if (tryMatch("POST")) {
request->method = Method::Post;
}
else if (tryMatch("HEAD")) {
request->method = Method::Head;
}
else if (tryMatch("PUT")) {
request->method = Method::Put;
}
else if (tryMatch("DELETE")) {
request->method = Method::Delete;
}
else {
raise("Unknown HTTP request method");
}
auto n = cursor.next();
if (n == Cursor::Eof) return State::Again;
else if (n != ' ') raise("Malformed HTTP request after Method, expected SP");
if (!cursor.advance(2)) return State::Again;
size_t start = cursor;
while ((n = cursor.next()) != Cursor::Eof && n != ' ') {
if (!cursor.advance(1)) return State::Again;
}
request->resource = std::string(cursor.offset(start), cursor.diff(start) + 1);
if ((n = cursor.next()) == Cursor::Eof) return State::Again;
if (n != ' ')
raise("Malformed HTTP request after Request-URI");
// SP
if (!cursor.advance(2)) return State::Again;
// HTTP-Version
start = cursor;
while (!cursor.eol())
if (!cursor.advance(1)) return State::Again;
const size_t diff = cursor.diff(start);
if (strncmp(cursor.offset(start), "HTTP/1.0", diff) == 0) {
request->version = Version::Http10;
}
else if (strncmp(cursor.offset(start), "HTTP/1.1", diff) == 0) {
request->version = Version::Http11;
}
else {
raise("Encountered invalid HTTP version");
}
if (!cursor.advance(2)) return State::Again;
revert.ignore();
return State::Next;
}
Parser::State
Parser::HeadersStep::apply(Cursor& cursor) {
Cursor::Revert revert(cursor);
while (!cursor.eol()) {
Cursor::Revert headerRevert(cursor);
// Read the header name
size_t start = cursor;
while (cursor.current() != ':')
if (!cursor.advance(1)) return State::Again;
// Skip the ':'
if (!cursor.advance(1)) return State::Again;
std::string name = std::string(cursor.offset(start), cursor.diff(start) - 1);
// Ignore spaces
while (cursor.current() == ' ')
if (!cursor.advance(1)) return State::Again;
// Read the header value
start = cursor;
while (!cursor.eol()) {
if (!cursor.advance(1)) return State::Again;
}
if (HeaderRegistry::isRegistered(name)) {
std::shared_ptr<Header> header = HeaderRegistry::makeHeader(name);
header->parseRaw(cursor.offset(start), cursor.diff(start));
request->headers.add(header);
}
// CRLF
if (!cursor.advance(2)) return State::Again;
headerRevert.ignore();
}
revert.ignore();
return Parser::State::Next;
}
Parser::State
Parser::BodyStep::apply(Cursor& cursor) {
auto cl = request->headers.tryGet<ContentLength>();
if (!cl) return Parser::State::Done;
auto contentLength = cl->value();
// We already started to read some bytes but we got an incomplete payload
if (bytesRead > 0) {
// How many bytes do we still need to read ?
const size_t remaining = contentLength - bytesRead;
auto start = cursor;
// Could be refactored in a single function / lambda but I'm too lazy
// for that right now
if (!cursor.advance(remaining)) {
const size_t available = cursor.remaining();
request->body.append(cursor.offset(start), available);
bytesRead += available;
cursor.advance(available);
return State::Again;
}
else {
request->body.append(cursor.offset(), cursor.diff(start));
}
}
// This is the first time we are reading the payload
else {
if (!cursor.advance(2)) return State::Again;
request->body.reserve(contentLength);
auto start = cursor;
// We have an incomplete body, read what we can
if (!cursor.advance(contentLength)) {
const size_t available = cursor.remaining();
request->body.append(cursor.offset(start), available);
bytesRead += available;
cursor.advance(available);
return State::Again;
}
request->body.append(cursor.offset(start), cursor.diff(start));
}
bytesRead = 0;
return Parser::State::Done;
}
Parser::State
Parser::parse() {
State state = State::Again;
do {
Step *step = allSteps[currentStep].get();
state = step->apply(cursor);
if (state == State::Next) {
++currentStep;
}
} while (state == State::Next);
// Should be either Again or Done
return state;
}
bool
Parser::feed(const char* data, size_t len) {
if (len + buffer.len >= sizeof (buffer.data)) {
return false;
}
memcpy(buffer.data + buffer.len, data, len);
buffer.len += len;
return true;
}
void
Parser::reset() {
buffer.reset();
cursor.reset();
currentStep = 0;
request.headers.clear();
request.body.clear();
request.resource.clear();
}
ssize_t
Writer::writeRaw(const void* data, size_t len) {
buf = static_cast<char *>(memcpy(buf, data, len));
buf += len;
return 0;
}
ssize_t
Writer::writeString(const char* str) {
const size_t len = std::strlen(str);
return writeRaw(str, std::strlen(str));
}
ssize_t
Writer::writeHeader(const char* name, const char* value) {
writeString(name);
writeChar(':');
writeString(value);
writeRaw(CRLF, 2);
return 0;
}
} // namespace Private
const char* methodString(Method method)
{
switch (method) {
#define METHOD(name, str) \
case Method::name: \
return str;
HTTP_METHODS
#undef METHOD
}
unreachable();
}
const char* codeString(Code code)
{
switch (code) {
#define CODE(_, name, str) \
case Code::name: \
return str;
STATUS_CODES
#undef CODE
}
return "";
}
HttpError::HttpError(Code code, std::string reason)
: code_(static_cast<int>(code))
, reason_(std::move(reason))
{ }
HttpError::HttpError(int code, std::string reason)
: code_(code)
, reason_(std::move(reason))
{ }
Message::Message()
: version(Version::Http11)
{ }
Request::Request()
: Message()
{ }
Response::Response(int code, std::string body)
{
this->body = std::move(body);
code_ = code;
}
Response::Response(Code code, std::string body)
: Message()
{
this->body = std::move(body);
code_ = static_cast<int>(code);
}
void
Response::writeTo(Tcp::Peer& peer)
{
int fd = peer.fd();
char buffer[Const::MaxBuffer];
std::memset(buffer, 0, Const::MaxBuffer);
Private::Writer fmt(buffer, sizeof buffer);
fmt.writeString("HTTP/1.1 ");
fmt.writeInt(code_);
fmt.writeChar(' ');
fmt.writeString(codeString(static_cast<Code>(code_)));
fmt.writeRaw(CRLF, 2);
for (const auto& header: headers.list()) {
std::ostringstream oss;
header->write(oss);
std::string str = oss.str();
fmt.writeRaw(str.c_str(), str.size());
fmt.writeRaw(CRLF, 2);
}
fmt.writeHeader("Content-Length", body.size());
fmt.writeRaw(CRLF, 2);
fmt.writeString(body.c_str());
const size_t len = fmt.cursor() - buffer;
ssize_t bytes = send(fd, buffer, len, 0);
}
void
Handler::onInput(const char* buffer, size_t len, Tcp::Peer& peer) {
auto& parser = getParser(peer);
if (!parser.feed(buffer, len)) {
cout << "Could not feed parser bro" << endl;
}
else {
try {
auto state = parser.parse();
if (state == Private::Parser::State::Done) {
onRequest(parser.request, peer);
parser.reset();
}
} catch (const HttpError &err) {
Response response(err.code(), err.reason());
response.writeTo(peer);
}
catch (const std::exception& e) {
Response response(Code::Internal_Server_Error, e.what());
response.writeTo(peer);
}
}
}
void
Handler::onOutput() {
}
void
Handler::onConnection(Tcp::Peer& peer) {
peer.setData(std::make_shared<Private::Parser>());
}
void
Handler::onDisconnection(Tcp::Peer& peer) {
}
Private::Parser&
Handler::getParser(Tcp::Peer& peer) {
auto data = peer.data();
return *std::static_pointer_cast<Private::Parser>(data);
}
Endpoint::Endpoint()
{ }
Endpoint::Endpoint(const Net::Address& addr)
: listener(addr)
{ }
void
Endpoint::setHandler(const std::shared_ptr<Handler>& handler) {
handler_ = handler;
}
void
Endpoint::serve()
{
if (!handler_)
throw std::runtime_error("Must call setHandler() prior to serve()");
listener.init(8, Tcp::Options::InstallSignalHandler);
listener.setHandler(handler_);
if (listener.bind()) {
const auto& addr = listener.address();
cout << "Now listening on " << "http://" + addr.host() << ":" << addr.port() << endl;
listener.run();
}
}
} // namespace Http
} // namespace Net
The default handler now returns an HTTP 500 when an exception occurs
/* http.cc
Mathieu Stefani, 13 August 2015
Http layer implementation
*/
#include <cstring>
#include <iostream>
#include <stdexcept>
#include "common.h"
#include "http.h"
#include "net.h"
#include "peer.h"
using namespace std;
namespace Net {
namespace Http {
static constexpr char CR = 0xD;
static constexpr char LF = 0xA;
static constexpr char CRLF[] = {CR, LF};
namespace Private {
Parser::Buffer::Buffer()
: len(0)
{
memset(data, sizeof data, 0);
}
void
Parser::Buffer::reset() {
memset(data, sizeof data, 0);
len = 0;
}
bool
Parser::Cursor::advance(size_t count)
{
if (value + count >= sizeof (buff.data)) {
//parser->raise("Early EOF");
}
// Allowed to advance one past the end
else if (value + count > buff.len) {
return false;
}
value += count;
return true;
}
bool
Parser::Cursor::eol() const {
return buff.data[value] == CR && next() == LF;
}
int
Parser::Cursor::next() const {
if (value + 1 >= sizeof (buff.data)) {
//parser->raise("Early EOF");
}
else if (value + 1 >= buff.len) {
return Eof;
}
return buff.data[value + 1];
}
char
Parser::Cursor::current() const {
return buff.data[value];
}
const char *
Parser::Cursor::offset() const {
return buff.data + value;
}
const char *
Parser::Cursor::offset(size_t off) const {
return buff.data + off;
}
size_t
Parser::Cursor::diff(size_t other) const {
return value - other;
}
size_t
Parser::Cursor::diff(const Cursor& other) const {
return value - other.value;
}
size_t
Parser::Cursor::remaining() const {
// assert(val <= buff.len);
return buff.len - value;
}
void
Parser::Cursor::reset() {
value = 0;
}
void
Parser::Step::raise(const char* msg, Code code /* = Code::Bad_Request */) {
throw HttpError(code, msg);
}
Parser::State
Parser::RequestLineStep::apply(Cursor& cursor) {
Cursor::Revert revert(cursor);
auto tryMatch = [&](const char* const str) {
const size_t len = std::strlen(str);
if (strncmp(cursor.offset(), str, len) == 0) {
cursor.advance(len - 1);
return true;
}
return false;
};
// Method
if (tryMatch("OPTIONS")) {
request->method = Method::Options;
}
else if (tryMatch("GET")) {
request->method = Method::Get;
}
else if (tryMatch("POST")) {
request->method = Method::Post;
}
else if (tryMatch("HEAD")) {
request->method = Method::Head;
}
else if (tryMatch("PUT")) {
request->method = Method::Put;
}
else if (tryMatch("DELETE")) {
request->method = Method::Delete;
}
else {
raise("Unknown HTTP request method");
}
auto n = cursor.next();
if (n == Cursor::Eof) return State::Again;
else if (n != ' ') raise("Malformed HTTP request after Method, expected SP");
if (!cursor.advance(2)) return State::Again;
size_t start = cursor;
while ((n = cursor.next()) != Cursor::Eof && n != ' ') {
if (!cursor.advance(1)) return State::Again;
}
request->resource = std::string(cursor.offset(start), cursor.diff(start) + 1);
if ((n = cursor.next()) == Cursor::Eof) return State::Again;
if (n != ' ')
raise("Malformed HTTP request after Request-URI");
// SP
if (!cursor.advance(2)) return State::Again;
// HTTP-Version
start = cursor;
while (!cursor.eol())
if (!cursor.advance(1)) return State::Again;
const size_t diff = cursor.diff(start);
if (strncmp(cursor.offset(start), "HTTP/1.0", diff) == 0) {
request->version = Version::Http10;
}
else if (strncmp(cursor.offset(start), "HTTP/1.1", diff) == 0) {
request->version = Version::Http11;
}
else {
raise("Encountered invalid HTTP version");
}
if (!cursor.advance(2)) return State::Again;
revert.ignore();
return State::Next;
}
Parser::State
Parser::HeadersStep::apply(Cursor& cursor) {
Cursor::Revert revert(cursor);
while (!cursor.eol()) {
Cursor::Revert headerRevert(cursor);
// Read the header name
size_t start = cursor;
while (cursor.current() != ':')
if (!cursor.advance(1)) return State::Again;
// Skip the ':'
if (!cursor.advance(1)) return State::Again;
std::string name = std::string(cursor.offset(start), cursor.diff(start) - 1);
// Ignore spaces
while (cursor.current() == ' ')
if (!cursor.advance(1)) return State::Again;
// Read the header value
start = cursor;
while (!cursor.eol()) {
if (!cursor.advance(1)) return State::Again;
}
if (HeaderRegistry::isRegistered(name)) {
std::shared_ptr<Header> header = HeaderRegistry::makeHeader(name);
header->parseRaw(cursor.offset(start), cursor.diff(start));
request->headers.add(header);
}
// CRLF
if (!cursor.advance(2)) return State::Again;
headerRevert.ignore();
}
revert.ignore();
return Parser::State::Next;
}
Parser::State
Parser::BodyStep::apply(Cursor& cursor) {
auto cl = request->headers.tryGet<ContentLength>();
if (!cl) return Parser::State::Done;
auto contentLength = cl->value();
// We already started to read some bytes but we got an incomplete payload
if (bytesRead > 0) {
// How many bytes do we still need to read ?
const size_t remaining = contentLength - bytesRead;
auto start = cursor;
// Could be refactored in a single function / lambda but I'm too lazy
// for that right now
if (!cursor.advance(remaining)) {
const size_t available = cursor.remaining();
request->body.append(cursor.offset(start), available);
bytesRead += available;
cursor.advance(available);
return State::Again;
}
else {
request->body.append(cursor.offset(), cursor.diff(start));
}
}
// This is the first time we are reading the payload
else {
if (!cursor.advance(2)) return State::Again;
request->body.reserve(contentLength);
auto start = cursor;
// We have an incomplete body, read what we can
if (!cursor.advance(contentLength)) {
const size_t available = cursor.remaining();
request->body.append(cursor.offset(start), available);
bytesRead += available;
cursor.advance(available);
return State::Again;
}
request->body.append(cursor.offset(start), cursor.diff(start));
}
bytesRead = 0;
return Parser::State::Done;
}
Parser::State
Parser::parse() {
State state = State::Again;
do {
Step *step = allSteps[currentStep].get();
state = step->apply(cursor);
if (state == State::Next) {
++currentStep;
}
} while (state == State::Next);
// Should be either Again or Done
return state;
}
bool
Parser::feed(const char* data, size_t len) {
if (len + buffer.len >= sizeof (buffer.data)) {
return false;
}
memcpy(buffer.data + buffer.len, data, len);
buffer.len += len;
return true;
}
void
Parser::reset() {
buffer.reset();
cursor.reset();
currentStep = 0;
request.headers.clear();
request.body.clear();
request.resource.clear();
}
ssize_t
Writer::writeRaw(const void* data, size_t len) {
buf = static_cast<char *>(memcpy(buf, data, len));
buf += len;
return 0;
}
ssize_t
Writer::writeString(const char* str) {
const size_t len = std::strlen(str);
return writeRaw(str, std::strlen(str));
}
ssize_t
Writer::writeHeader(const char* name, const char* value) {
writeString(name);
writeChar(':');
writeString(value);
writeRaw(CRLF, 2);
return 0;
}
} // namespace Private
const char* methodString(Method method)
{
switch (method) {
#define METHOD(name, str) \
case Method::name: \
return str;
HTTP_METHODS
#undef METHOD
}
unreachable();
}
const char* codeString(Code code)
{
switch (code) {
#define CODE(_, name, str) \
case Code::name: \
return str;
STATUS_CODES
#undef CODE
}
return "";
}
HttpError::HttpError(Code code, std::string reason)
: code_(static_cast<int>(code))
, reason_(std::move(reason))
{ }
HttpError::HttpError(int code, std::string reason)
: code_(code)
, reason_(std::move(reason))
{ }
Message::Message()
: version(Version::Http11)
{ }
Request::Request()
: Message()
{ }
Response::Response(int code, std::string body)
{
this->body = std::move(body);
code_ = code;
}
Response::Response(Code code, std::string body)
: Message()
{
this->body = std::move(body);
code_ = static_cast<int>(code);
}
void
Response::writeTo(Tcp::Peer& peer)
{
int fd = peer.fd();
char buffer[Const::MaxBuffer];
std::memset(buffer, 0, Const::MaxBuffer);
Private::Writer fmt(buffer, sizeof buffer);
fmt.writeString("HTTP/1.1 ");
fmt.writeInt(code_);
fmt.writeChar(' ');
fmt.writeString(codeString(static_cast<Code>(code_)));
fmt.writeRaw(CRLF, 2);
for (const auto& header: headers.list()) {
std::ostringstream oss;
header->write(oss);
std::string str = oss.str();
fmt.writeRaw(str.c_str(), str.size());
fmt.writeRaw(CRLF, 2);
}
fmt.writeHeader("Content-Length", body.size());
fmt.writeRaw(CRLF, 2);
fmt.writeString(body.c_str());
const size_t len = fmt.cursor() - buffer;
ssize_t bytes = send(fd, buffer, len, 0);
}
void
Handler::onInput(const char* buffer, size_t len, Tcp::Peer& peer) {
try {
auto& parser = getParser(peer);
if (!parser.feed(buffer, len)) {
throw HttpError(Code::Request_Entity_Too_Large, "Request exceeded maximum buffer size");
}
auto state = parser.parse();
if (state == Private::Parser::State::Done) {
onRequest(parser.request, peer);
parser.reset();
}
} catch (const HttpError &err) {
Response response(err.code(), err.reason());
response.writeTo(peer);
}
catch (const std::exception& e) {
Response response(Code::Internal_Server_Error, e.what());
response.writeTo(peer);
}
}
void
Handler::onOutput() {
}
void
Handler::onConnection(Tcp::Peer& peer) {
peer.setData(std::make_shared<Private::Parser>());
}
void
Handler::onDisconnection(Tcp::Peer& peer) {
}
Private::Parser&
Handler::getParser(Tcp::Peer& peer) {
auto data = peer.data();
return *std::static_pointer_cast<Private::Parser>(data);
}
Endpoint::Endpoint()
{ }
Endpoint::Endpoint(const Net::Address& addr)
: listener(addr)
{ }
void
Endpoint::setHandler(const std::shared_ptr<Handler>& handler) {
handler_ = handler;
}
void
Endpoint::serve()
{
if (!handler_)
throw std::runtime_error("Must call setHandler() prior to serve()");
listener.init(8, Tcp::Options::InstallSignalHandler);
listener.setHandler(handler_);
if (listener.bind()) {
const auto& addr = listener.address();
cout << "Now listening on " << "http://" + addr.host() << ":" << addr.port() << endl;
listener.run();
}
}
} // namespace Http
} // namespace Net
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2001 - 2015 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
#include <deal.II/base/std_cxx11/array.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/thread_management.h>
#include <deal.II/lac/vector.h>
#include <deal.II/lac/vector_memory.h>
#include <deal.II/lac/filtered_matrix.h>
#include <deal.II/lac/precondition.h>
#include <deal.II/lac/solver_cg.h>
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/dynamic_sparsity_pattern.h>
#include <deal.II/lac/constraint_matrix.h>
#include <deal.II/lac/sparsity_pattern.h>
#include <deal.II/lac/sparsity_tools.h>
#include <deal.II/grid/tria.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/grid/tria_boundary.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_accessor.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/fe/fe_nothing.h>
#include <deal.II/fe/mapping_q1.h>
#include <deal.II/fe/mapping_q.h>
#include <deal.II/fe/fe_values.h>
#include <deal.II/hp/mapping_collection.h>
#include <deal.II/numerics/matrix_tools.h>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <cmath>
#include <numeric>
#include <list>
#include <set>
DEAL_II_NAMESPACE_OPEN
namespace GridTools
{
// This anonymous namespace contains utility functions to extract the
// triangulation from any container such as DoFHandler
// and the like
namespace
{
template<int dim, int spacedim>
const Triangulation<dim, spacedim> &
get_tria(const Triangulation<dim, spacedim> &tria)
{
return tria;
}
template<int dim, int spacedim>
const Triangulation<dim, spacedim> &
get_tria(const parallel::distributed::Triangulation<dim, spacedim> &tria)
{
return tria;
}
template<int dim, template<int, int> class Container, int spacedim>
const Triangulation<dim,spacedim> &
get_tria(const Container<dim,spacedim> &container)
{
return container.get_tria();
}
template<int dim, int spacedim>
Triangulation<dim, spacedim> &
get_tria(Triangulation<dim, spacedim> &tria)
{
return tria;
}
template<int dim, int spacedim>
Triangulation<dim, spacedim> &
get_tria(parallel::distributed::Triangulation<dim, spacedim> &tria)
{
return tria;
}
template<int dim, template<int, int> class Container, int spacedim>
const Triangulation<dim,spacedim> &
get_tria(Container<dim,spacedim> &container)
{
return container.get_tria();
}
}
template <int dim, int spacedim>
double
diameter (const Triangulation<dim, spacedim> &tria)
{
// we can't deal with distributed meshes
// since we don't have all vertices
// locally. there is one exception,
// however: if the mesh has never been
// refined. the way to test this is not to
// ask tria.n_levels()==1, since this is
// something that can happen on one
// processor without being true on
// all. however, we can ask for the global
// number of active cells and use that
#ifdef DEAL_II_WITH_P4EST
if (const parallel::distributed::Triangulation<dim,spacedim> *p_tria
= dynamic_cast<const parallel::distributed::Triangulation<dim,spacedim>*>(&tria))
Assert (p_tria->n_global_active_cells() == tria.n_cells(0),
ExcNotImplemented());
#endif
// the algorithm used simply
// traverses all cells and picks
// out the boundary vertices. it
// may or may not be faster to
// simply get all vectors, don't
// mark boundary vertices, and
// compute the distances thereof,
// but at least as the mesh is
// refined, it seems better to
// first mark boundary nodes, as
// marking is O(N) in the number of
// cells/vertices, while computing
// the maximal distance is O(N*N)
const std::vector<Point<spacedim> > &vertices = tria.get_vertices ();
std::vector<bool> boundary_vertices (vertices.size(), false);
typename Triangulation<dim,spacedim>::active_cell_iterator
cell = tria.begin_active();
const typename Triangulation<dim,spacedim>::active_cell_iterator
endc = tria.end();
for (; cell!=endc; ++cell)
for (unsigned int face=0; face<GeometryInfo<dim>::faces_per_cell; ++face)
if (cell->face(face)->at_boundary ())
for (unsigned int i=0; i<GeometryInfo<dim>::vertices_per_face; ++i)
boundary_vertices[cell->face(face)->vertex_index(i)] = true;
// now traverse the list of
// boundary vertices and check
// distances. since distances are
// symmetric, we only have to check
// one half
double max_distance_sqr = 0;
std::vector<bool>::const_iterator pi = boundary_vertices.begin();
const unsigned int N = boundary_vertices.size();
for (unsigned int i=0; i<N; ++i, ++pi)
{
std::vector<bool>::const_iterator pj = pi+1;
for (unsigned int j=i+1; j<N; ++j, ++pj)
if ((*pi==true) && (*pj==true) &&
((vertices[i]-vertices[j]).norm_square() > max_distance_sqr))
max_distance_sqr = (vertices[i]-vertices[j]).norm_square();
};
return std::sqrt(max_distance_sqr);
}
template <int dim, int spacedim>
double
volume (const Triangulation<dim, spacedim> &triangulation,
const Mapping<dim,spacedim> &mapping)
{
// get the degree of the mapping if possible. if not, just assume 1
const unsigned int mapping_degree
= (dynamic_cast<const MappingQ<dim,spacedim>*>(&mapping) != 0 ?
dynamic_cast<const MappingQ<dim,spacedim>*>(&mapping)->get_degree() :
1);
// then initialize an appropriate quadrature formula
const QGauss<dim> quadrature_formula (mapping_degree + 1);
const unsigned int n_q_points = quadrature_formula.size();
// we really want the JxW values from the FEValues object, but it
// wants a finite element. create a cheap element as a dummy
// element
FE_Nothing<dim,spacedim> dummy_fe;
FEValues<dim,spacedim> fe_values (mapping, dummy_fe, quadrature_formula,
update_JxW_values);
typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active(),
endc = triangulation.end();
double local_volume = 0;
// compute the integral quantities by quadrature
for (; cell!=endc; ++cell)
if (cell->is_locally_owned())
{
fe_values.reinit (cell);
for (unsigned int q=0; q<n_q_points; ++q)
local_volume += fe_values.JxW(q);
}
double global_volume = 0;
#ifdef DEAL_II_WITH_MPI
if (const parallel::distributed::Triangulation<dim,spacedim> *p_tria
= dynamic_cast<const parallel::distributed::Triangulation<dim,spacedim>*>(&triangulation))
global_volume = Utilities::MPI::sum (local_volume, p_tria->get_communicator());
else
global_volume = local_volume;
#else
global_volume = local_volume;
#endif
return global_volume;
}
template <>
double
cell_measure<3>(const std::vector<Point<3> > &all_vertices,
const unsigned int (&vertex_indices)[GeometryInfo<3>::vertices_per_cell])
{
// note that this is the
// cell_measure based on the new
// deal.II numbering. When called
// from inside GridReordering make
// sure that you reorder the
// vertex_indices before
const double x[8] = { all_vertices[vertex_indices[0]](0),
all_vertices[vertex_indices[1]](0),
all_vertices[vertex_indices[2]](0),
all_vertices[vertex_indices[3]](0),
all_vertices[vertex_indices[4]](0),
all_vertices[vertex_indices[5]](0),
all_vertices[vertex_indices[6]](0),
all_vertices[vertex_indices[7]](0)
};
const double y[8] = { all_vertices[vertex_indices[0]](1),
all_vertices[vertex_indices[1]](1),
all_vertices[vertex_indices[2]](1),
all_vertices[vertex_indices[3]](1),
all_vertices[vertex_indices[4]](1),
all_vertices[vertex_indices[5]](1),
all_vertices[vertex_indices[6]](1),
all_vertices[vertex_indices[7]](1)
};
const double z[8] = { all_vertices[vertex_indices[0]](2),
all_vertices[vertex_indices[1]](2),
all_vertices[vertex_indices[2]](2),
all_vertices[vertex_indices[3]](2),
all_vertices[vertex_indices[4]](2),
all_vertices[vertex_indices[5]](2),
all_vertices[vertex_indices[6]](2),
all_vertices[vertex_indices[7]](2)
};
/*
This is the same Maple script as in the barycenter method above
except of that here the shape functions tphi[0]-tphi[7] are ordered
according to the lexicographic numbering.
x := array(0..7):
y := array(0..7):
z := array(0..7):
tphi[0] := (1-xi)*(1-eta)*(1-zeta):
tphi[1] := xi*(1-eta)*(1-zeta):
tphi[2] := (1-xi)* eta*(1-zeta):
tphi[3] := xi* eta*(1-zeta):
tphi[4] := (1-xi)*(1-eta)*zeta:
tphi[5] := xi*(1-eta)*zeta:
tphi[6] := (1-xi)* eta*zeta:
tphi[7] := xi* eta*zeta:
x_real := sum(x[s]*tphi[s], s=0..7):
y_real := sum(y[s]*tphi[s], s=0..7):
z_real := sum(z[s]*tphi[s], s=0..7):
with (linalg):
J := matrix(3,3, [[diff(x_real, xi), diff(x_real, eta), diff(x_real, zeta)],
[diff(y_real, xi), diff(y_real, eta), diff(y_real, zeta)],
[diff(z_real, xi), diff(z_real, eta), diff(z_real, zeta)]]):
detJ := det (J):
measure := simplify ( int ( int ( int (detJ, xi=0..1), eta=0..1), zeta=0..1)):
readlib(C):
C(measure, optimized);
The C code produced by this maple script is further optimized by
hand. In particular, division by 12 is performed only once, not
hundred of times.
*/
const double t3 = y[3]*x[2];
const double t5 = z[1]*x[5];
const double t9 = z[3]*x[2];
const double t11 = x[1]*y[0];
const double t14 = x[4]*y[0];
const double t18 = x[5]*y[7];
const double t20 = y[1]*x[3];
const double t22 = y[5]*x[4];
const double t26 = z[7]*x[6];
const double t28 = x[0]*y[4];
const double t34 = z[3]*x[1]*y[2]+t3*z[1]-t5*y[7]+y[7]*x[4]*z[6]+t9*y[6]-t11*z[4]-t5*y[3]-t14*z[2]+z[1]*x[4]*y[0]-t18*z[3]+t20*z[0]-t22*z[0]-y[0]*x[5]*z[4]-t26*y[3]+t28*z[2]-t9*y[1]-y[1]*x[4]*z[0]-t11*z[5];
const double t37 = y[1]*x[0];
const double t44 = x[1]*y[5];
const double t46 = z[1]*x[0];
const double t49 = x[0]*y[2];
const double t52 = y[5]*x[7];
const double t54 = x[3]*y[7];
const double t56 = x[2]*z[0];
const double t58 = x[3]*y[2];
const double t64 = -x[6]*y[4]*z[2]-t37*z[2]+t18*z[6]-x[3]*y[6]*z[2]+t11*z[2]+t5*y[0]+t44*z[4]-t46*y[4]-t20*z[7]-t49*z[6]-t22*z[1]+t52*z[3]-t54*z[2]-t56*y[4]-t58*z[0]+y[1]*x[2]*z[0]+t9*y[7]+t37*z[4];
const double t66 = x[1]*y[7];
const double t68 = y[0]*x[6];
const double t70 = x[7]*y[6];
const double t73 = z[5]*x[4];
const double t76 = x[6]*y[7];
const double t90 = x[4]*z[0];
const double t92 = x[1]*y[3];
const double t95 = -t66*z[3]-t68*z[2]-t70*z[2]+t26*y[5]-t73*y[6]-t14*z[6]+t76*z[2]-t3*z[6]+x[6]*y[2]*z[4]-z[3]*x[6]*y[2]+t26*y[4]-t44*z[3]-x[1]*y[2]*z[0]+x[5]*y[6]*z[4]+t54*z[5]+t90*y[2]-t92*z[2]+t46*y[2];
const double t102 = x[2]*y[0];
const double t107 = y[3]*x[7];
const double t114 = x[0]*y[6];
const double t125 = y[0]*x[3]*z[2]-z[7]*x[5]*y[6]-x[2]*y[6]*z[4]+t102*z[6]-t52*z[6]+x[2]*y[4]*z[6]-t107*z[5]-t54*z[6]+t58*z[6]-x[7]*y[4]*z[6]+t37*z[5]-t114*z[4]+t102*z[4]-z[1]*x[2]*y[0]+t28*z[6]-y[5]*x[6]*z[4]-z[5]*x[1]*y[4]-t73*y[7];
const double t129 = z[0]*x[6];
const double t133 = y[1]*x[7];
const double t145 = y[1]*x[5];
const double t156 = t90*y[6]-t129*y[4]+z[7]*x[2]*y[6]-t133*z[5]+x[5]*y[3]*z[7]-t26*y[2]-t70*z[3]+t46*y[3]+z[5]*x[7]*y[4]+z[7]*x[3]*y[6]-t49*z[4]+t145*z[7]-x[2]*y[7]*z[6]+t70*z[5]+t66*z[5]-z[7]*x[4]*y[6]+t18*z[4]+x[1]*y[4]*z[0];
const double t160 = x[5]*y[4];
const double t165 = z[1]*x[7];
const double t178 = z[1]*x[3];
const double t181 = t107*z[6]+t22*z[7]+t76*z[3]+t160*z[1]-x[4]*y[2]*z[6]+t70*z[4]+t165*y[5]+x[7]*y[2]*z[6]-t76*z[5]-t76*z[4]+t133*z[3]-t58*z[1]+y[5]*x[0]*z[4]+t114*z[2]-t3*z[7]+t20*z[2]+t178*y[7]+t129*y[2];
const double t207 = t92*z[7]+t22*z[6]+z[3]*x[0]*y[2]-x[0]*y[3]*z[2]-z[3]*x[7]*y[2]-t165*y[3]-t9*y[0]+t58*z[7]+y[3]*x[6]*z[2]+t107*z[2]+t73*y[0]-x[3]*y[5]*z[7]+t3*z[0]-t56*y[6]-z[5]*x[0]*y[4]+t73*y[1]-t160*z[6]+t160*z[0];
const double t228 = -t44*z[7]+z[5]*x[6]*y[4]-t52*z[4]-t145*z[4]+t68*z[4]+t92*z[5]-t92*z[0]+t11*z[3]+t44*z[0]+t178*y[5]-t46*y[5]-t178*y[0]-t145*z[0]-t20*z[5]-t37*z[3]-t160*z[7]+t145*z[3]+x[4]*y[6]*z[2];
return (t34+t64+t95+t125+t156+t181+t207+t228)/12.;
}
template <>
double
cell_measure(const std::vector<Point<2> > &all_vertices,
const unsigned int (&vertex_indices) [GeometryInfo<2>::vertices_per_cell])
{
/*
Get the computation of the measure by this little Maple script. We
use the blinear mapping of the unit quad to the real quad. However,
every transformation mapping the unit faces to straight lines should
do.
Remember that the area of the quad is given by
\int_K 1 dx dy = \int_{\hat K} |det J| d(xi) d(eta)
# x and y are arrays holding the x- and y-values of the four vertices
# of this cell in real space.
x := array(0..3);
y := array(0..3);
z := array(0..3);
tphi[0] := (1-xi)*(1-eta):
tphi[1] := xi*(1-eta):
tphi[2] := (1-xi)*eta:
tphi[3] := xi*eta:
x_real := sum(x[s]*tphi[s], s=0..3):
y_real := sum(y[s]*tphi[s], s=0..3):
z_real := sum(z[s]*tphi[s], s=0..3):
Jxi := <diff(x_real,xi) | diff(y_real,xi) | diff(z_real,xi)>;
Jeta := <diff(x_real,eta)| diff(y_real,eta)| diff(z_real,eta)>;
with(VectorCalculus):
J := CrossProduct(Jxi, Jeta);
detJ := sqrt(J[1]^2 + J[2]^2 +J[3]^2);
# measure := evalf (Int (Int (detJ, xi=0..1, method = _NCrule ) , eta=0..1, method = _NCrule ) ):
# readlib(C):
# C(measure, optimized);
additional optimizaton: divide by 2 only one time
*/
const double x[4] = { all_vertices[vertex_indices[0]](0),
all_vertices[vertex_indices[1]](0),
all_vertices[vertex_indices[2]](0),
all_vertices[vertex_indices[3]](0)
};
const double y[4] = { all_vertices[vertex_indices[0]](1),
all_vertices[vertex_indices[1]](1),
all_vertices[vertex_indices[2]](1),
all_vertices[vertex_indices[3]](1)
};
return (-x[1]*y[0]+x[1]*y[3]+y[0]*x[2]+x[0]*y[1]-x[0]*y[2]-y[1]*x[3]-x[2]*y[3]+x[3]*y[2])/2;
}
template <int dim>
double
cell_measure(const std::vector<Point<dim> > &,
const unsigned int ( &) [GeometryInfo<dim>::vertices_per_cell])
{
Assert(false, ExcNotImplemented());
return 0.;
}
template <int dim, int spacedim>
void
delete_unused_vertices (std::vector<Point<spacedim> > &vertices,
std::vector<CellData<dim> > &cells,
SubCellData &subcelldata)
{
// first check which vertices are
// actually used
std::vector<bool> vertex_used (vertices.size(), false);
for (unsigned int c=0; c<cells.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
vertex_used[cells[c].vertices[v]] = true;
// then renumber the vertices that
// are actually used in the same
// order as they were beforehand
const unsigned int invalid_vertex = numbers::invalid_unsigned_int;
std::vector<unsigned int> new_vertex_numbers (vertices.size(), invalid_vertex);
unsigned int next_free_number = 0;
for (unsigned int i=0; i<vertices.size(); ++i)
if (vertex_used[i] == true)
{
new_vertex_numbers[i] = next_free_number;
++next_free_number;
};
// next replace old vertex numbers
// by the new ones
for (unsigned int c=0; c<cells.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
cells[c].vertices[v] = new_vertex_numbers[cells[c].vertices[v]];
// same for boundary data
for (unsigned int c=0; c<subcelldata.boundary_lines.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<1>::vertices_per_cell; ++v)
subcelldata.boundary_lines[c].vertices[v]
= new_vertex_numbers[subcelldata.boundary_lines[c].vertices[v]];
for (unsigned int c=0; c<subcelldata.boundary_quads.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<2>::vertices_per_cell; ++v)
subcelldata.boundary_quads[c].vertices[v]
= new_vertex_numbers[subcelldata.boundary_quads[c].vertices[v]];
// finally copy over the vertices
// which we really need to a new
// array and replace the old one by
// the new one
std::vector<Point<spacedim> > tmp;
tmp.reserve (std::count(vertex_used.begin(), vertex_used.end(), true));
for (unsigned int v=0; v<vertices.size(); ++v)
if (vertex_used[v] == true)
tmp.push_back (vertices[v]);
swap (vertices, tmp);
}
template <int dim, int spacedim>
void
delete_duplicated_vertices (std::vector<Point<spacedim> > &vertices,
std::vector<CellData<dim> > &cells,
SubCellData &subcelldata,
std::vector<unsigned int> &considered_vertices,
double tol)
{
// create a vector of vertex
// indices. initialize it to the identity,
// later on change that if necessary.
std::vector<unsigned int> new_vertex_numbers(vertices.size());
for (unsigned int i=0; i<vertices.size(); ++i)
new_vertex_numbers[i]=i;
// if the considered_vertices vector is
// empty, consider all vertices
if (considered_vertices.size()==0)
considered_vertices=new_vertex_numbers;
// now loop over all vertices to be
// considered and try to find an identical
// one
for (unsigned int i=0; i<considered_vertices.size(); ++i)
{
if (new_vertex_numbers[considered_vertices[i]]!=considered_vertices[i])
// this vertex has been identified with
// another one already, skip it in the
// test
continue;
// this vertex is not identified with
// another one so far. search in the list
// of remaining vertices. if a duplicate
// vertex is found, set the new vertex
// index for that vertex to this vertex'
// index.
for (unsigned int j=i+1; j<considered_vertices.size(); ++j)
{
bool equal=true;
for (unsigned int d=0; d<spacedim; ++d)
equal &= (fabs(vertices[considered_vertices[j]](d)-vertices[considered_vertices[i]](d))<tol);
if (equal)
{
new_vertex_numbers[considered_vertices[j]]=considered_vertices[i];
// we do not suppose, that there might be another duplicate
// vertex, so break here
break;
}
}
}
// now we got a renumbering list. simply
// renumber all vertices (non-duplicate
// vertices get renumbered to themselves, so
// nothing bad happens). after that, the
// duplicate vertices will be unused, so call
// delete_unused_vertices() to do that part
// of the job.
for (unsigned int c=0; c<cells.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
cells[c].vertices[v]=new_vertex_numbers[cells[c].vertices[v]];
delete_unused_vertices(vertices,cells,subcelldata);
}
// define some transformations in an anonymous namespace
namespace
{
template <int spacedim>
class Shift
{
public:
Shift (const Tensor<1,spacedim> &shift)
:
shift(shift)
{}
Point<spacedim> operator() (const Point<spacedim> p) const
{
return p+shift;
}
private:
const Tensor<1,spacedim> shift;
};
// the following class is only
// needed in 2d, so avoid trouble
// with compilers warning otherwise
class Rotate2d
{
public:
Rotate2d (const double angle)
:
angle(angle)
{}
Point<2> operator() (const Point<2> &p) const
{
return Point<2> (std::cos(angle)*p(0) - std::sin(angle) * p(1),
std::sin(angle)*p(0) + std::cos(angle) * p(1));
}
private:
const double angle;
};
template <int spacedim>
class Scale
{
public:
Scale (const double factor)
:
factor(factor)
{}
Point<spacedim> operator() (const Point<spacedim> p) const
{
return p*factor;
}
private:
const double factor;
};
}
template <int dim, int spacedim>
void
shift (const Tensor<1,spacedim> &shift_vector,
Triangulation<dim, spacedim> &triangulation)
{
transform (Shift<spacedim>(shift_vector), triangulation);
}
void
rotate (const double angle,
Triangulation<2> &triangulation)
{
transform (Rotate2d(angle), triangulation);
}
template <int dim, int spacedim>
void
scale (const double scaling_factor,
Triangulation<dim, spacedim> &triangulation)
{
Assert (scaling_factor>0, ExcScalingFactorNotPositive (scaling_factor));
transform (Scale<spacedim>(scaling_factor), triangulation);
}
namespace
{
/**
* Solve the Laplace equation for the @p laplace_transform function for one
* of the @p dim space dimensions. Factorized into a function of its own
* in order to allow parallel execution.
*/
void laplace_solve (const SparseMatrix<double> &S,
const std::map<unsigned int,double> &m,
Vector<double> &u)
{
const unsigned int n_dofs=S.n();
FilteredMatrix<Vector<double> > SF (S);
PreconditionJacobi<SparseMatrix<double> > prec;
prec.initialize(S, 1.2);
FilteredMatrix<Vector<double> > PF (prec);
SolverControl control (n_dofs, 1.e-10, false, false);
GrowingVectorMemory<Vector<double> > mem;
SolverCG<Vector<double> > solver (control, mem);
Vector<double> f(n_dofs);
SF.add_constraints(m);
SF.apply_constraints (f, true);
solver.solve(SF, u, f, PF);
}
}
// Implementation for 1D only
template <>
void laplace_transform (const std::map<unsigned int,Point<1> > &,
Triangulation<1> &,
const Function<1> *)
{
Assert(false, ExcNotImplemented());
}
// Implementation for dimensions except 1
template <int dim>
void
laplace_transform (const std::map<unsigned int,Point<dim> > &new_points,
Triangulation<dim> &triangulation,
const Function<dim> *coefficient)
{
// first provide everything that is
// needed for solving a Laplace
// equation.
MappingQ1<dim> mapping_q1;
FE_Q<dim> q1(1);
DoFHandler<dim> dof_handler(triangulation);
dof_handler.distribute_dofs(q1);
DynamicSparsityPattern dsp (dof_handler.n_dofs (),
dof_handler.n_dofs ());
DoFTools::make_sparsity_pattern (dof_handler, dsp);
dsp.compress ();
SparsityPattern sparsity_pattern;
sparsity_pattern.copy_from (dsp);
sparsity_pattern.compress ();
SparseMatrix<double> S(sparsity_pattern);
QGauss<dim> quadrature(4);
MatrixCreator::create_laplace_matrix(mapping_q1, dof_handler, quadrature, S,coefficient);
// set up the boundary values for
// the laplace problem
std::vector<std::map<unsigned int,double> > m(dim);
typename std::map<unsigned int,Point<dim> >::const_iterator map_end=new_points.end();
// fill these maps using the data
// given by new_points
typename DoFHandler<dim>::cell_iterator cell=dof_handler.begin_active(),
endc=dof_handler.end();
for (; cell!=endc; ++cell)
{
for (unsigned int face_no=0; face_no<GeometryInfo<dim>::faces_per_cell; ++face_no)
{
const typename DoFHandler<dim>::face_iterator face=cell->face(face_no);
// loop over all vertices of the cell and see if it is listed in the map
// given as first argument of the function
for (unsigned int vertex_no=0;
vertex_no<GeometryInfo<dim>::vertices_per_face; ++vertex_no)
{
const unsigned int vertex_index=face->vertex_index(vertex_no);
const typename std::map<unsigned int,Point<dim> >::const_iterator map_iter
= new_points.find(vertex_index);
if (map_iter!=map_end)
for (unsigned int i=0; i<dim; ++i)
m[i].insert(std::pair<unsigned int,double> (
face->vertex_dof_index(vertex_no, 0), map_iter->second(i)));
}
}
}
// solve the dim problems with
// different right hand sides.
Vector<double> us[dim];
for (unsigned int i=0; i<dim; ++i)
us[i].reinit (dof_handler.n_dofs());
// solve linear systems in parallel
Threads::TaskGroup<> tasks;
for (unsigned int i=0; i<dim; ++i)
tasks += Threads::new_task (&laplace_solve,
S, m[i], us[i]);
tasks.join_all ();
// change the coordinates of the
// points of the triangulation
// according to the computed values
for (cell=dof_handler.begin_active(); cell!=endc; ++cell)
for (unsigned int vertex_no=0;
vertex_no<GeometryInfo<dim>::vertices_per_cell; ++vertex_no)
{
Point<dim> &v=cell->vertex(vertex_no);
const unsigned int dof_index=cell->vertex_dof_index(vertex_no, 0);
for (unsigned int i=0; i<dim; ++i)
v(i)=us[i](dof_index);
}
}
template <int dim, int spacedim>
std::map<unsigned int, Point<spacedim> >
get_all_vertices_at_boundary (const Triangulation<dim, spacedim> &tria)
{
std::map<unsigned int, Point<spacedim> > vertex_map;
typename Triangulation<dim,spacedim>::active_cell_iterator
cell = tria.begin_active(),
endc = tria.end();
for (; cell!=endc; ++cell)
{
for (unsigned int i=0; i<GeometryInfo<dim>::faces_per_cell; ++i)
{
const typename Triangulation<dim, spacedim>::face_iterator &face
= cell->face(i);
if (face->at_boundary())
{
for (unsigned j = 0; j < GeometryInfo<dim>::vertices_per_face; ++j)
{
const Point<spacedim> &vertex = face->vertex(j);
const unsigned int vertex_index = face->vertex_index(j);
vertex_map[vertex_index] = vertex;
}
}
}
}
return vertex_map;
}
/**
* Distort a triangulation in
* some random way.
*/
template <int dim, int spacedim>
void
distort_random (const double factor,
Triangulation<dim,spacedim> &triangulation,
const bool keep_boundary)
{
// if spacedim>dim we need to make sure that we perturb
// points but keep them on
// the manifold. however, this isn't implemented right now
Assert (spacedim == dim, ExcNotImplemented());
// find the smallest length of the
// lines adjacent to the
// vertex. take the initial value
// to be larger than anything that
// might be found: the diameter of
// the triangulation, here
// estimated by adding up the
// diameters of the coarse grid
// cells.
double almost_infinite_length = 0;
for (typename Triangulation<dim,spacedim>::cell_iterator
cell=triangulation.begin(0); cell!=triangulation.end(0); ++cell)
almost_infinite_length += cell->diameter();
std::vector<double> minimal_length (triangulation.n_vertices(),
almost_infinite_length);
// also note if a vertex is at the boundary
std::vector<bool> at_boundary (triangulation.n_vertices(), false);
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell=triangulation.begin_active(); cell!=triangulation.end(); ++cell)
if (cell->is_locally_owned())
{
if (dim>1)
{
for (unsigned int i=0; i<GeometryInfo<dim>::lines_per_cell; ++i)
{
const typename Triangulation<dim,spacedim>::line_iterator line
= cell->line(i);
if (keep_boundary && line->at_boundary())
{
at_boundary[line->vertex_index(0)] = true;
at_boundary[line->vertex_index(1)] = true;
}
minimal_length[line->vertex_index(0)]
= std::min(line->diameter(),
minimal_length[line->vertex_index(0)]);
minimal_length[line->vertex_index(1)]
= std::min(line->diameter(),
minimal_length[line->vertex_index(1)]);
}
}
else //dim==1
{
if (keep_boundary)
for (unsigned int vertex=0; vertex<2; ++vertex)
if (cell->at_boundary(vertex) == true)
at_boundary[cell->vertex_index(vertex)] = true;
minimal_length[cell->vertex_index(0)]
= std::min(cell->diameter(),
minimal_length[cell->vertex_index(0)]);
minimal_length[cell->vertex_index(1)]
= std::min(cell->diameter(),
minimal_length[cell->vertex_index(1)]);
}
}
// If the triangulation is distributed, we need to
// exchange the moved vertices across mpi processes
if (parallel::distributed::Triangulation< dim, spacedim > *distributed_triangulation
= dynamic_cast<parallel::distributed::Triangulation<dim,spacedim>*> (&triangulation))
{
// create a random number generator for the interval [-1,1]. we use
// this to make sure the distribution we get is repeatable, i.e.,
// if you call the function twice on the same mesh, then you will
// get the same mesh. this would not be the case if you used
// the rand() function, which carries around some internal state
boost::random::mt19937 rng;
boost::random::uniform_real_distribution<> uniform_distribution(-1,1);
const std::vector<bool> locally_owned_vertices = get_locally_owned_vertices(triangulation);
std::vector<bool> vertex_moved (triangulation.n_vertices(), false);
// Next move vertices on locally owned cells
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell=triangulation.begin_active(); cell!=triangulation.end(); ++cell)
if (cell->is_locally_owned())
{
for (unsigned int vertex_no=0; vertex_no<GeometryInfo<dim>::vertices_per_cell;
++vertex_no)
{
const unsigned global_vertex_no = cell->vertex_index(vertex_no);
// ignore this vertex if we shall keep the boundary and
// this vertex *is* at the boundary, if it is already moved
// or if another process moves this vertex
if ((keep_boundary && at_boundary[global_vertex_no])
|| vertex_moved[global_vertex_no]
|| !locally_owned_vertices[global_vertex_no])
continue;
// first compute a random shift vector
Point<spacedim> shift_vector;
for (unsigned int d=0; d<spacedim; ++d)
shift_vector(d) = uniform_distribution(rng);
shift_vector *= factor * minimal_length[global_vertex_no] /
std::sqrt(shift_vector.square());
// finally move the vertex
cell->vertex(vertex_no) += shift_vector;
vertex_moved[global_vertex_no] = true;
}
}
#ifdef DEAL_II_WITH_P4EST
distributed_triangulation
->communicate_locally_moved_vertices(locally_owned_vertices);
#else
(void)distributed_triangulation;
Assert (false, ExcInternalError());
#endif
}
else
// if this is a sequential triangulation, we could in principle
// use the algorithm above, but we'll use an algorithm that we used
// before the parallel::distributed::Triangulation was introduced
// in order to preserve backward compatibility
{
// loop over all vertices and compute their new locations
const unsigned int n_vertices = triangulation.n_vertices();
std::vector<Point<spacedim> > new_vertex_locations (n_vertices);
const std::vector<Point<spacedim> > &old_vertex_locations
= triangulation.get_vertices();
for (unsigned int vertex=0; vertex<n_vertices; ++vertex)
{
// ignore this vertex if we will keep the boundary and
// this vertex *is* at the boundary
if (keep_boundary && at_boundary[vertex])
new_vertex_locations[vertex] = old_vertex_locations[vertex];
else
{
// compute a random shift vector
Point<spacedim> shift_vector;
for (unsigned int d=0; d<spacedim; ++d)
shift_vector(d) = std::rand()*2.0/RAND_MAX-1;
shift_vector *= factor * minimal_length[vertex] /
std::sqrt(shift_vector.square());
// record new vertex location
new_vertex_locations[vertex] = old_vertex_locations[vertex] + shift_vector;
}
}
// now do the actual move of the vertices
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell=triangulation.begin_active(); cell!=triangulation.end(); ++cell)
for (unsigned int vertex_no=0;
vertex_no<GeometryInfo<dim>::vertices_per_cell; ++vertex_no)
cell->vertex(vertex_no) = new_vertex_locations[cell->vertex_index(vertex_no)];
}
// Correct hanging nodes if necessary
if (dim>=2)
{
// We do the same as in GridTools::transform
//
// exclude hanging nodes at the boundaries of artificial cells:
// these may belong to ghost cells for which we know the exact
// location of vertices, whereas the artificial cell may or may
// not be further refined, and so we cannot know whether
// the location of the hanging node is correct or not
typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active(),
endc = triangulation.end();
for (; cell!=endc; ++cell)
if (!cell->is_artificial())
for (unsigned int face=0;
face<GeometryInfo<dim>::faces_per_cell; ++face)
if (cell->face(face)->has_children() &&
!cell->face(face)->at_boundary())
{
// this face has hanging nodes
if (dim==2)
cell->face(face)->child(0)->vertex(1)
= (cell->face(face)->vertex(0) +
cell->face(face)->vertex(1)) / 2;
else if (dim==3)
{
cell->face(face)->child(0)->vertex(1)
= .5*(cell->face(face)->vertex(0)
+cell->face(face)->vertex(1));
cell->face(face)->child(0)->vertex(2)
= .5*(cell->face(face)->vertex(0)
+cell->face(face)->vertex(2));
cell->face(face)->child(1)->vertex(3)
= .5*(cell->face(face)->vertex(1)
+cell->face(face)->vertex(3));
cell->face(face)->child(2)->vertex(3)
= .5*(cell->face(face)->vertex(2)
+cell->face(face)->vertex(3));
// center of the face
cell->face(face)->child(0)->vertex(3)
= .25*(cell->face(face)->vertex(0)
+cell->face(face)->vertex(1)
+cell->face(face)->vertex(2)
+cell->face(face)->vertex(3));
}
}
}
}
template <int dim, template <int, int> class Container, int spacedim>
unsigned int
find_closest_vertex (const Container<dim,spacedim> &container,
const Point<spacedim> &p)
{
// first get the underlying
// triangulation from the
// container and determine vertices
// and used vertices
const Triangulation<dim, spacedim> &tria = get_tria(container);
const std::vector< Point<spacedim> > &vertices = tria.get_vertices();
const std::vector< bool > &used = tria.get_used_vertices();
// At the beginning, the first
// used vertex is the closest one
std::vector<bool>::const_iterator first =
std::find(used.begin(), used.end(), true);
// Assert that at least one vertex
// is actually used
Assert(first != used.end(), ExcInternalError());
unsigned int best_vertex = std::distance(used.begin(), first);
double best_dist = (p - vertices[best_vertex]).norm_square();
// For all remaining vertices, test
// whether they are any closer
for (unsigned int j = best_vertex+1; j < vertices.size(); j++)
if (used[j])
{
double dist = (p - vertices[j]).norm_square();
if (dist < best_dist)
{
best_vertex = j;
best_dist = dist;
}
}
return best_vertex;
}
template<int dim, template<int, int> class Container, int spacedim>
#ifndef _MSC_VER
std::vector<typename Container<dim, spacedim>::active_cell_iterator>
#else
std::vector<typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type>
#endif
find_cells_adjacent_to_vertex(const Container<dim,spacedim> &container,
const unsigned int vertex)
{
// make sure that the given vertex is
// an active vertex of the underlying
// triangulation
Assert(vertex < get_tria(container).n_vertices(),
ExcIndexRange(0,get_tria(container).n_vertices(),vertex));
Assert(get_tria(container).get_used_vertices()[vertex],
ExcVertexNotUsed(vertex));
// use a set instead of a vector
// to ensure that cells are inserted only
// once
std::set<typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type> adjacent_cells;
typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type
cell = container.begin_active(),
endc = container.end();
// go through all active cells and look if the vertex is part of that cell
//
// in 1d, this is all we need to care about. in 2d/3d we also need to worry
// that the vertex might be a hanging node on a face or edge of a cell; in
// this case, we would want to add those cells as well on whose faces the
// vertex is located but for which it is not a vertex itself.
//
// getting this right is a lot simpler in 2d than in 3d. in 2d, a hanging
// node can only be in the middle of a face and we can query the neighboring
// cell from the current cell. on the other hand, in 3d a hanging node
// vertex can also be on an edge but there can be many other cells on
// this edge and we can not access them from the cell we are currently
// on.
//
// so, in the 3d case, if we run the algorithm as in 2d, we catch all
// those cells for which the vertex we seek is on a *subface*, but we
// miss the case of cells for which the vertex we seek is on a
// sub-edge for which there is no corresponding sub-face (because the
// immediate neighbor behind this face is not refined), see for example
// the bits/find_cells_adjacent_to_vertex_6 testcase. thus, if we
// haven't yet found the vertex for the current cell we also need to
// look at the mid-points of edges
//
// as a final note, deciding whether a neighbor is actually coarser is
// simple in the case of isotropic refinement (we just need to look at
// the level of the current and the neighboring cell). however, this
// isn't so simple if we have used anisotropic refinement since then
// the level of a cell is not indicative of whether it is coarser or
// not than the current cell. ultimately, we want to add all cells on
// which the vertex is, independent of whether they are coarser or
// finer and so in the 2d case below we simply add *any* *active* neighbor.
// in the worst case, we add cells multiple times to the adjacent_cells
// list, but std::set throws out those cells already entered
for (; cell != endc; ++cell)
{
for (unsigned int v = 0; v < GeometryInfo<dim>::vertices_per_cell; v++)
if (cell->vertex_index(v) == vertex)
{
// OK, we found a cell that contains
// the given vertex. We add it
// to the list.
adjacent_cells.insert(cell);
// as explained above, in 2+d we need to check whether
// this vertex is on a face behind which there is a
// (possibly) coarser neighbor. if this is the case,
// then we need to also add this neighbor
if (dim >= 2)
for (unsigned int vface = 0; vface < dim; vface++)
{
const unsigned int face =
GeometryInfo<dim>::vertex_to_face[v][vface];
if (!cell->at_boundary(face)
&&
cell->neighbor(face)->active())
{
// there is a (possibly) coarser cell behind a
// face to which the vertex belongs. the
// vertex we are looking at is then either a
// vertex of that coarser neighbor, or it is a
// hanging node on one of the faces of that
// cell. in either case, it is adjacent to the
// vertex, so add it to the list as well (if
// the cell was already in the list then the
// std::set makes sure that we get it only
// once)
adjacent_cells.insert (cell->neighbor(face));
}
}
// in any case, we have found a cell, so go to the next cell
goto next_cell;
}
// in 3d also loop over the edges
if (dim >= 3)
{
for (unsigned int e=0; e<GeometryInfo<dim>::lines_per_cell; ++e)
if (cell->line(e)->has_children())
// the only place where this vertex could have been
// hiding is on the mid-edge point of the edge we
// are looking at
if (cell->line(e)->child(0)->vertex_index(1) == vertex)
{
adjacent_cells.insert(cell);
// jump out of this tangle of nested loops
goto next_cell;
}
}
// in more than 3d we would probably have to do the same as
// above also for even lower-dimensional objects
Assert (dim <= 3, ExcNotImplemented());
// move on to the next cell if we have found the
// vertex on the current one
next_cell:
;
}
// if this was an active vertex then there needs to have been
// at least one cell to which it is adjacent!
Assert (adjacent_cells.size() > 0, ExcInternalError());
// return the result as a vector, rather than the set we built above
return
std::vector<typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type>
(adjacent_cells.begin(), adjacent_cells.end());
}
namespace
{
template <int dim, template<int, int> class Container, int spacedim>
void find_active_cell_around_point_internal(const Container<dim,spacedim> &container,
#ifndef _MSC_VER
std::set<typename Container<dim, spacedim>::active_cell_iterator> &searched_cells,
std::set<typename Container<dim, spacedim>::active_cell_iterator> &adjacent_cells)
#else
std::set<typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type> &searched_cells,
std::set<typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type> &adjacent_cells)
#endif
{
#ifndef _MSC_VER
typedef typename Container<dim, spacedim>::active_cell_iterator cell_iterator;
#else
typedef typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type cell_iterator;
#endif
// update the searched cells
searched_cells.insert(adjacent_cells.begin(), adjacent_cells.end());
// now we to collect all neighbors
// of the cells in adjacent_cells we
// have not yet searched.
std::set<cell_iterator> adjacent_cells_new;
typename std::set<cell_iterator>::const_iterator
cell = adjacent_cells.begin(),
endc = adjacent_cells.end();
for (; cell != endc; ++cell)
{
std::vector<cell_iterator> active_neighbors;
get_active_neighbors<Container<dim, spacedim> >(*cell, active_neighbors);
for (unsigned int i=0; i<active_neighbors.size(); ++i)
if (searched_cells.find(active_neighbors[i]) == searched_cells.end())
adjacent_cells_new.insert(active_neighbors[i]);
}
adjacent_cells.clear();
adjacent_cells.insert(adjacent_cells_new.begin(), adjacent_cells_new.end());
if (adjacent_cells.size() == 0)
{
// we haven't found any other cell that would be a
// neighbor of a previously found cell, but we know
// that we haven't checked all cells yet. that means
// that the domain is disconnected. in that case,
// choose the first previously untouched cell we
// can find
cell_iterator it = container.begin_active();
for ( ; it!=container.end(); ++it)
if (searched_cells.find(it) == searched_cells.end())
{
adjacent_cells.insert(it);
break;
}
}
}
}
template <int dim, template<int, int> class Container, int spacedim>
#ifndef _MSC_VER
typename Container<dim, spacedim>::active_cell_iterator
#else
typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type
#endif
find_active_cell_around_point (const Container<dim,spacedim> &container,
const Point<spacedim> &p)
{
return
find_active_cell_around_point<dim,Container,spacedim>
(StaticMappingQ1<dim,spacedim>::mapping,
container, p).first;
}
template <int dim, template <int, int> class Container, int spacedim>
#ifndef _MSC_VER
std::pair<typename Container<dim, spacedim>::active_cell_iterator, Point<dim> >
#else
std::pair<typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type, Point<dim> >
#endif
find_active_cell_around_point (const Mapping<dim,spacedim> &mapping,
const Container<dim,spacedim> &container,
const Point<spacedim> &p)
{
typedef typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type active_cell_iterator;
// The best distance is set to the
// maximum allowable distance from
// the unit cell; we assume a
// max. deviation of 1e-10
double best_distance = 1e-10;
int best_level = -1;
std::pair<active_cell_iterator, Point<dim> > best_cell;
// Find closest vertex and determine
// all adjacent cells
std::vector<active_cell_iterator> adjacent_cells_tmp
= find_cells_adjacent_to_vertex(container,
find_closest_vertex(container, p));
// Make sure that we have found
// at least one cell adjacent to vertex.
Assert(adjacent_cells_tmp.size()>0, ExcInternalError());
// Copy all the cells into a std::set
std::set<active_cell_iterator> adjacent_cells (adjacent_cells_tmp.begin(),
adjacent_cells_tmp.end());
std::set<active_cell_iterator> searched_cells;
// Determine the maximal number of cells
// in the grid.
// As long as we have not found
// the cell and have not searched
// every cell in the triangulation,
// we keep on looking.
const unsigned int n_active_cells = get_tria(container).n_active_cells();
bool found = false;
unsigned int cells_searched = 0;
while (!found && cells_searched < n_active_cells)
{
typename std::set<active_cell_iterator>::const_iterator
cell = adjacent_cells.begin(),
endc = adjacent_cells.end();
for (; cell != endc; ++cell)
{
try
{
const Point<dim> p_cell = mapping.transform_real_to_unit_cell(*cell, p);
// calculate the infinity norm of
// the distance vector to the unit cell.
const double dist = GeometryInfo<dim>::distance_to_unit_cell(p_cell);
// We compare if the point is inside the
// unit cell (or at least not too far
// outside). If it is, it is also checked
// that the cell has a more refined state
if ((dist < best_distance)
||
((dist == best_distance)
&&
((*cell)->level() > best_level)))
{
found = true;
best_distance = dist;
best_level = (*cell)->level();
best_cell = std::make_pair(*cell, p_cell);
}
}
catch (typename MappingQ1<dim,spacedim>::ExcTransformationFailed &)
{
// ok, the transformation
// failed presumably
// because the point we
// are looking for lies
// outside the current
// cell. this means that
// the current cell can't
// be the cell around the
// point, so just ignore
// this cell and move on
// to the next
}
}
// update the number of cells searched
cells_searched += adjacent_cells.size();
// if we have not found the cell in
// question and have not yet searched every
// cell, we expand our search to
// all the not already searched neighbors of
// the cells in adjacent_cells. This is
// what find_active_cell_around_point_internal
// is for.
if (!found && cells_searched < n_active_cells)
{
find_active_cell_around_point_internal<dim,Container,spacedim>
(container, searched_cells, adjacent_cells);
}
}
AssertThrow (best_cell.first.state() == IteratorState::valid,
ExcPointNotFound<spacedim>(p));
return best_cell;
}
template <int dim, int spacedim>
std::pair<typename hp::DoFHandler<dim,spacedim>::active_cell_iterator, Point<dim> >
find_active_cell_around_point (const hp::MappingCollection<dim,spacedim> &mapping,
const hp::DoFHandler<dim,spacedim> &container,
const Point<spacedim> &p)
{
Assert ((mapping.size() == 1) ||
(mapping.size() == container.get_fe().size()),
ExcMessage ("Mapping collection needs to have either size 1 "
"or size equal to the number of elements in "
"the FECollection."));
typedef typename hp::DoFHandler<dim,spacedim>::active_cell_iterator cell_iterator;
std::pair<cell_iterator, Point<dim> > best_cell;
//If we have only one element in the MappingCollection,
//we use find_active_cell_around_point using only one
//mapping.
if (mapping.size() == 1)
best_cell = find_active_cell_around_point(mapping[0], container, p);
else
{
// The best distance is set to the
// maximum allowable distance from
// the unit cell; we assume a
// max. deviation of 1e-10
double best_distance = 1e-10;
int best_level = -1;
// Find closest vertex and determine
// all adjacent cells
unsigned int vertex = find_closest_vertex(container, p);
std::vector<cell_iterator> adjacent_cells_tmp =
find_cells_adjacent_to_vertex(container, vertex);
// Make sure that we have found
// at least one cell adjacent to vertex.
Assert(adjacent_cells_tmp.size()>0, ExcInternalError());
// Copy all the cells into a std::set
std::set<cell_iterator> adjacent_cells(adjacent_cells_tmp.begin(), adjacent_cells_tmp.end());
std::set<cell_iterator> searched_cells;
// Determine the maximal number of cells
// in the grid.
// As long as we have not found
// the cell and have not searched
// every cell in the triangulation,
// we keep on looking.
const unsigned int n_cells =get_tria(container).n_cells();
bool found = false;
unsigned int cells_searched = 0;
while (!found && cells_searched < n_cells)
{
typename std::set<cell_iterator>::const_iterator
cell = adjacent_cells.begin(),
endc = adjacent_cells.end();
for (; cell != endc; ++cell)
{
try
{
const Point<dim> p_cell = mapping[(*cell)->active_fe_index()].transform_real_to_unit_cell(*cell, p);
// calculate the infinity norm of
// the distance vector to the unit cell.
const double dist = GeometryInfo<dim>::distance_to_unit_cell(p_cell);
// We compare if the point is inside the
// unit cell (or at least not too far
// outside). If it is, it is also checked
// that the cell has a more refined state
if (dist < best_distance ||
(dist == best_distance && (*cell)->level() > best_level))
{
found = true;
best_distance = dist;
best_level = (*cell)->level();
best_cell = std::make_pair(*cell, p_cell);
}
}
catch (typename MappingQ1<dim,spacedim>::ExcTransformationFailed &)
{
// ok, the transformation
// failed presumably
// because the point we
// are looking for lies
// outside the current
// cell. this means that
// the current cell can't
// be the cell around the
// point, so just ignore
// this cell and move on
// to the next
}
}
//udpate the number of cells searched
cells_searched += adjacent_cells.size();
// if we have not found the cell in
// question and have not yet searched every
// cell, we expand our search to
// all the not already searched neighbors of
// the cells in adjacent_cells.
if (!found && cells_searched < n_cells)
{
find_active_cell_around_point_internal<dim,hp::DoFHandler,spacedim>
(container, searched_cells, adjacent_cells);
}
}
}
AssertThrow (best_cell.first.state() == IteratorState::valid,
ExcPointNotFound<spacedim>(p));
return best_cell;
}
template <int dim, int spacedim>
void
get_face_connectivity_of_cells (const Triangulation<dim,spacedim> &triangulation,
DynamicSparsityPattern &cell_connectivity)
{
cell_connectivity.reinit (triangulation.n_active_cells(),
triangulation.n_active_cells());
// create a map pair<lvl,idx> -> SparsityPattern index
// TODO: we are no longer using user_indices for this because we can get
// pointer/index clashes when saving/restoring them. The following approach
// works, but this map can get quite big. Not sure about more efficient solutions.
std::map< std::pair<unsigned int,unsigned int>, unsigned int >
indexmap;
unsigned int index = 0;
for (typename dealii::internal::ActiveCellIterator<dim, spacedim, Triangulation<dim, spacedim> >::type
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell, ++index)
indexmap[std::pair<unsigned int,unsigned int>(cell->level(),cell->index())] = index;
// next loop over all cells and their neighbors to build the sparsity
// pattern. note that it's a bit hard to enter all the connections when a
// neighbor has children since we would need to find out which of its
// children is adjacent to the current cell. this problem can be omitted
// if we only do something if the neighbor has no children -- in that case
// it is either on the same or a coarser level than we are. in return, we
// have to add entries in both directions for both cells
index = 0;
for (typename dealii::internal::ActiveCellIterator<dim, spacedim, Triangulation<dim, spacedim> >::type
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell, ++index)
{
cell_connectivity.add (index, index);
for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)
if ((cell->at_boundary(f) == false)
&&
(cell->neighbor(f)->has_children() == false))
{
unsigned int other_index = indexmap.find(
std::pair<unsigned int,unsigned int>(cell->neighbor(f)->level(),cell->neighbor(f)->index()))->second;
cell_connectivity.add (index, other_index);
cell_connectivity.add (other_index, index);
}
}
}
template <int dim, int spacedim>
void
get_face_connectivity_of_cells (const Triangulation<dim,spacedim> &triangulation,
SparsityPattern &cell_connectivity)
{
DynamicSparsityPattern dsp;
get_face_connectivity_of_cells(triangulation, dsp);
cell_connectivity.copy_from(dsp);
}
template <int dim, int spacedim>
void
get_vertex_connectivity_of_cells (const Triangulation<dim,spacedim> &triangulation,
DynamicSparsityPattern &cell_connectivity)
{
std::vector<std::vector<unsigned int> > vertex_to_cell(triangulation.n_vertices());
unsigned int index = 0;
for (typename Triangulation<dim,spacedim>::active_cell_iterator cell=
triangulation.begin_active(); cell != triangulation.end(); ++cell, ++index)
{
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
vertex_to_cell[cell->vertex_index(v)].push_back(index);
}
cell_connectivity.reinit (triangulation.n_active_cells(),
triangulation.n_active_cells());
index = 0;
for (typename Triangulation<dim,spacedim>::active_cell_iterator cell=
triangulation.begin_active(); cell != triangulation.end(); ++cell, ++index)
{
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
for (unsigned int n=0; n<vertex_to_cell[cell->vertex_index(v)].size(); ++n)
cell_connectivity.add(index, vertex_to_cell[cell->vertex_index(v)][n]);
}
}
template <int dim, int spacedim>
void
partition_triangulation (const unsigned int n_partitions,
Triangulation<dim,spacedim> &triangulation)
{
Assert ((dynamic_cast<parallel::distributed::Triangulation<dim,spacedim>*>
(&triangulation)
== 0),
ExcMessage ("Objects of type parallel::distributed::Triangulation "
"are already partitioned implicitly and can not be "
"partitioned again explicitly."));
Assert (n_partitions > 0, ExcInvalidNumberOfPartitions(n_partitions));
// check for an easy return
if (n_partitions == 1)
{
for (typename dealii::internal::ActiveCellIterator<dim, spacedim, Triangulation<dim, spacedim> >::type
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell)
cell->set_subdomain_id (0);
return;
}
// we decompose the domain by first
// generating the connection graph of all
// cells with their neighbors, and then
// passing this graph off to METIS.
// finally defer to the other function for
// partitioning and assigning subdomain ids
SparsityPattern cell_connectivity;
get_face_connectivity_of_cells (triangulation, cell_connectivity);
partition_triangulation (n_partitions,
cell_connectivity,
triangulation);
}
template <int dim, int spacedim>
void
partition_triangulation (const unsigned int n_partitions,
const SparsityPattern &cell_connection_graph,
Triangulation<dim,spacedim> &triangulation)
{
Assert ((dynamic_cast<parallel::distributed::Triangulation<dim,spacedim>*>
(&triangulation)
== 0),
ExcMessage ("Objects of type parallel::distributed::Triangulation "
"are already partitioned implicitly and can not be "
"partitioned again explicitly."));
Assert (n_partitions > 0, ExcInvalidNumberOfPartitions(n_partitions));
Assert (cell_connection_graph.n_rows() == triangulation.n_active_cells(),
ExcMessage ("Connectivity graph has wrong size"));
Assert (cell_connection_graph.n_cols() == triangulation.n_active_cells(),
ExcMessage ("Connectivity graph has wrong size"));
// check for an easy return
if (n_partitions == 1)
{
for (typename dealii::internal::ActiveCellIterator<dim, spacedim, Triangulation<dim, spacedim> >::type
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell)
cell->set_subdomain_id (0);
return;
}
// partition this connection graph and get
// back a vector of indices, one per degree
// of freedom (which is associated with a
// cell)
std::vector<unsigned int> partition_indices (triangulation.n_active_cells());
SparsityTools::partition (cell_connection_graph, n_partitions, partition_indices);
// finally loop over all cells and set the
// subdomain ids
unsigned int index = 0;
for (typename dealii::internal::ActiveCellIterator<dim, spacedim, Triangulation<dim, spacedim> >::type
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell, ++index)
cell->set_subdomain_id (partition_indices[index]);
}
template <int dim, int spacedim>
void
get_subdomain_association (const Triangulation<dim, spacedim> &triangulation,
std::vector<types::subdomain_id> &subdomain)
{
Assert (subdomain.size() == triangulation.n_active_cells(),
ExcDimensionMismatch (subdomain.size(),
triangulation.n_active_cells()));
unsigned int index = 0;
for (typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell!=triangulation.end(); ++cell, ++index)
subdomain[index] = cell->subdomain_id();
Assert (index == subdomain.size(), ExcInternalError());
}
template <int dim, int spacedim>
unsigned int
count_cells_with_subdomain_association (const Triangulation<dim, spacedim> &triangulation,
const types::subdomain_id subdomain)
{
unsigned int count = 0;
for (typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell!=triangulation.end(); ++cell)
if (cell->subdomain_id() == subdomain)
++count;
return count;
}
template <int dim, int spacedim>
std::vector<bool>
get_locally_owned_vertices (const Triangulation<dim,spacedim> &triangulation)
{
// start with all vertices
std::vector<bool> locally_owned_vertices = triangulation.get_used_vertices();
// if the triangulation is distributed, eliminate those that
// are owned by other processors -- either because the vertex is
// on an artificial cell, or because it is on a ghost cell with
// a smaller subdomain
if (const parallel::distributed::Triangulation<dim,spacedim> *tr
= dynamic_cast<const parallel::distributed::Triangulation<dim,spacedim> *>
(&triangulation))
for (typename dealii::internal::ActiveCellIterator<dim, spacedim, Triangulation<dim, spacedim> >::type
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell)
if (cell->is_artificial()
||
(cell->is_ghost() &&
(cell->subdomain_id() < tr->locally_owned_subdomain())))
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
locally_owned_vertices[cell->vertex_index(v)] = false;
return locally_owned_vertices;
}
template <typename Container>
std::list<std::pair<typename Container::cell_iterator,
typename Container::cell_iterator> >
get_finest_common_cells (const Container &mesh_1,
const Container &mesh_2)
{
Assert (have_same_coarse_mesh (mesh_1, mesh_2),
ExcMessage ("The two containers must be represent triangulations that "
"have the same coarse meshes"));
// the algorithm goes as follows:
// first, we fill a list with pairs
// of iterators common to the two
// meshes on the coarsest
// level. then we traverse the
// list; each time, we find a pair
// of iterators for which both
// correspond to non-active cells,
// we delete this item and push the
// pairs of iterators to their
// children to the back. if these
// again both correspond to
// non-active cells, we will get to
// the later on for further
// consideration
typedef
std::list<std::pair<typename Container::cell_iterator,
typename Container::cell_iterator> >
CellList;
CellList cell_list;
// first push the coarse level cells
typename Container::cell_iterator
cell_1 = mesh_1.begin(0),
cell_2 = mesh_2.begin(0);
for (; cell_1 != mesh_1.end(0); ++cell_1, ++cell_2)
cell_list.push_back (std::make_pair (cell_1, cell_2));
// then traverse list as described
// above
typename CellList::iterator cell_pair = cell_list.begin();
while (cell_pair != cell_list.end())
{
// if both cells in this pair
// have children, then erase
// this element and push their
// children instead
if (cell_pair->first->has_children()
&&
cell_pair->second->has_children())
{
Assert(cell_pair->first->refinement_case()==
cell_pair->second->refinement_case(), ExcNotImplemented());
for (unsigned int c=0; c<cell_pair->first->n_children(); ++c)
cell_list.push_back (std::make_pair (cell_pair->first->child(c),
cell_pair->second->child(c)));
// erasing an iterator
// keeps other iterators
// valid, so already
// advance the present
// iterator by one and then
// delete the element we've
// visited before
const typename CellList::iterator previous_cell_pair = cell_pair;
++cell_pair;
cell_list.erase (previous_cell_pair);
}
else
// both cells are active, do
// nothing
++cell_pair;
}
// just to make sure everything is ok,
// validate that all pairs have at least one
// active iterator or have different
// refinement_cases
for (cell_pair = cell_list.begin(); cell_pair != cell_list.end(); ++cell_pair)
Assert (cell_pair->first->active()
||
cell_pair->second->active()
||
(cell_pair->first->refinement_case()
!= cell_pair->second->refinement_case()),
ExcInternalError());
return cell_list;
}
template <int dim, int spacedim>
bool
have_same_coarse_mesh (const Triangulation<dim, spacedim> &mesh_1,
const Triangulation<dim, spacedim> &mesh_2)
{
// make sure the two meshes have
// the same number of coarse cells
if (mesh_1.n_cells (0) != mesh_2.n_cells (0))
return false;
// if so, also make sure they have
// the same vertices on the cells
// of the coarse mesh
typename Triangulation<dim, spacedim>::cell_iterator
cell_1 = mesh_1.begin(0),
cell_2 = mesh_2.begin(0),
endc = mesh_1.end(0);
for (; cell_1!=endc; ++cell_1, ++cell_2)
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
if (cell_1->vertex(v) != cell_2->vertex(v))
return false;
// if we've gotten through all
// this, then the meshes really
// seem to have a common coarse
// mesh
return true;
}
template <typename Container>
bool
have_same_coarse_mesh (const Container &mesh_1,
const Container &mesh_2)
{
return have_same_coarse_mesh (get_tria(mesh_1),
get_tria(mesh_2));
}
template <int dim, int spacedim>
double
minimal_cell_diameter (const Triangulation<dim, spacedim> &triangulation)
{
double min_diameter = triangulation.begin_active()->diameter();
for (typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active(); cell != triangulation.end();
++cell)
min_diameter = std::min (min_diameter,
cell->diameter());
return min_diameter;
}
template <int dim, int spacedim>
double
maximal_cell_diameter (const Triangulation<dim, spacedim> &triangulation)
{
double max_diameter = triangulation.begin_active()->diameter();
for (typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active(); cell != triangulation.end();
++cell)
max_diameter = std::max (max_diameter,
cell->diameter());
return max_diameter;
}
namespace internal
{
namespace FixUpDistortedChildCells
{
// compute the mean square
// deviation of the alternating
// forms of the children of the
// given object from that of
// the object itself. for
// objects with
// structdim==spacedim, the
// alternating form is the
// determinant of the jacobian,
// whereas for faces with
// structdim==spacedim-1, the
// alternating form is the
// (signed and scaled) normal
// vector
//
// this average square
// deviation is computed for an
// object where the center node
// has been replaced by the
// second argument to this
// function
template <typename Iterator, int spacedim>
double
objective_function (const Iterator &object,
const Point<spacedim> &object_mid_point)
{
const unsigned int structdim = Iterator::AccessorType::structure_dimension;
Assert (spacedim == Iterator::AccessorType::dimension,
ExcInternalError());
// everything below is wrong
// if not for the following
// condition
Assert (object->refinement_case() == RefinementCase<structdim>::isotropic_refinement,
ExcNotImplemented());
// first calculate the
// average alternating form
// for the parent cell/face
Point<spacedim> parent_vertices
[GeometryInfo<structdim>::vertices_per_cell];
Tensor<spacedim-structdim,spacedim> parent_alternating_forms
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
parent_vertices[i] = object->vertex(i);
GeometryInfo<structdim>::alternating_form_at_vertices (parent_vertices,
parent_alternating_forms);
const Tensor<spacedim-structdim,spacedim>
average_parent_alternating_form
= std::accumulate (&parent_alternating_forms[0],
&parent_alternating_forms[GeometryInfo<structdim>::vertices_per_cell],
Tensor<spacedim-structdim,spacedim>());
// now do the same
// computation for the
// children where we use the
// given location for the
// object mid point instead of
// the one the triangulation
// currently reports
Point<spacedim> child_vertices
[GeometryInfo<structdim>::max_children_per_cell]
[GeometryInfo<structdim>::vertices_per_cell];
Tensor<spacedim-structdim,spacedim> child_alternating_forms
[GeometryInfo<structdim>::max_children_per_cell]
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
child_vertices[c][i] = object->child(c)->vertex(i);
// replace mid-object
// vertex. note that for
// child i, the mid-object
// vertex happens to have the
// number
// max_children_per_cell-i
for (unsigned int c=0; c<object->n_children(); ++c)
child_vertices[c][GeometryInfo<structdim>::max_children_per_cell-c-1]
= object_mid_point;
for (unsigned int c=0; c<object->n_children(); ++c)
GeometryInfo<structdim>::alternating_form_at_vertices (child_vertices[c],
child_alternating_forms[c]);
// on a uniformly refined
// hypercube object, the child
// alternating forms should
// all be smaller by a factor
// of 2^structdim than the
// ones of the parent. as a
// consequence, we'll use the
// squared deviation from
// this ideal value as an
// objective function
double objective = 0;
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
objective += (child_alternating_forms[c][i] -
average_parent_alternating_form/std::pow(2.,1.*structdim))
.norm_square();
return objective;
}
/**
* Return the location of the midpoint
* of the 'f'th face (vertex) of this 1d
* object.
*/
template <typename Iterator>
Point<Iterator::AccessorType::space_dimension>
get_face_midpoint (const Iterator &object,
const unsigned int f,
dealii::internal::int2type<1>)
{
return object->vertex(f);
}
/**
* Return the location of the midpoint
* of the 'f'th face (line) of this 2d
* object.
*/
template <typename Iterator>
Point<Iterator::AccessorType::space_dimension>
get_face_midpoint (const Iterator &object,
const unsigned int f,
dealii::internal::int2type<2>)
{
return object->line(f)->center();
}
/**
* Return the location of the midpoint
* of the 'f'th face (quad) of this 3d
* object.
*/
template <typename Iterator>
Point<Iterator::AccessorType::space_dimension>
get_face_midpoint (const Iterator &object,
const unsigned int f,
dealii::internal::int2type<3>)
{
return object->face(f)->center();
}
/**
* Compute the minimal diameter of an
* object by looking for the minimal
* distance between the mid-points of
* its faces. This minimal diameter is
* used to determine the step length
* for our grid cell improvement
* algorithm, and it should be small
* enough that the point moves around
* within the cell even if it is highly
* elongated -- thus, the diameter of
* the object is not a good measure,
* while the minimal diameter is. Note
* that the algorithm below works for
* both cells that are long rectangles
* with parallel sides where the
* nearest distance is between opposite
* edges as well as highly slanted
* parallelograms where the shortest
* distance is between neighboring
* edges.
*/
template <typename Iterator>
double
minimal_diameter (const Iterator &object)
{
const unsigned int
structdim = Iterator::AccessorType::structure_dimension;
double diameter = object->diameter();
for (unsigned int f=0;
f<GeometryInfo<structdim>::faces_per_cell;
++f)
for (unsigned int e=f+1;
e<GeometryInfo<structdim>::faces_per_cell;
++e)
diameter = std::min (diameter,
get_face_midpoint
(object, f,
dealii::internal::int2type<structdim>())
.distance (get_face_midpoint
(object,
e,
dealii::internal::int2type<structdim>())));
return diameter;
}
/**
* Try to fix up a single cell. Return
* whether we succeeded with this.
*
* The second argument indicates
* whether we need to respect the
* manifold/boundary on which this
* object lies when moving around its
* mid-point.
*/
template <typename Iterator>
bool
fix_up_object (const Iterator &object,
const bool respect_manifold)
{
const Boundary<Iterator::AccessorType::dimension,
Iterator::AccessorType::space_dimension>
*manifold = (respect_manifold ?
&object->get_boundary() :
0);
const unsigned int structdim = Iterator::AccessorType::structure_dimension;
const unsigned int spacedim = Iterator::AccessorType::space_dimension;
// right now we can only deal
// with cells that have been
// refined isotropically
// because that is the only
// case where we have a cell
// mid-point that can be moved
// around without having to
// consider boundary
// information
Assert (object->has_children(), ExcInternalError());
Assert (object->refinement_case() == RefinementCase<structdim>::isotropic_refinement,
ExcNotImplemented());
// get the current location of
// the object mid-vertex:
Point<spacedim> object_mid_point
= object->child(0)->vertex (GeometryInfo<structdim>::max_children_per_cell-1);
// now do a few steepest descent
// steps to reduce the objective
// function. compute the diameter in
// the helper function above
unsigned int iteration = 0;
const double diameter = minimal_diameter (object);
// current value of objective
// function and initial delta
double current_value = objective_function (object, object_mid_point);
double initial_delta = 0;
do
{
// choose a step length
// that is initially 1/4
// of the child objects'
// diameter, and a sequence
// whose sum does not
// converge (to avoid
// premature termination of
// the iteration)
const double step_length = diameter / 4 / (iteration + 1);
// compute the objective
// function's derivative using a
// two-sided difference formula
// with eps=step_length/10
Tensor<1,spacedim> gradient;
for (unsigned int d=0; d<spacedim; ++d)
{
const double eps = step_length/10;
Tensor<1,spacedim> h;
h[d] = eps/2;
if (respect_manifold == false)
gradient[d]
= ((objective_function (object, object_mid_point + h)
-
objective_function (object, object_mid_point - h))
/
eps);
else
gradient[d]
= ((objective_function (object,
manifold->project_to_surface(object,
object_mid_point + h))
-
objective_function (object,
manifold->project_to_surface(object,
object_mid_point - h)))
/
eps);
}
// sometimes, the
// (unprojected) gradient
// is perpendicular to
// the manifold, but we
// can't go there if
// respect_manifold==true. in
// that case, gradient=0,
// and we simply need to
// quite the loop here
if (gradient.norm() == 0)
break;
// so we need to go in
// direction -gradient. the
// optimal value of the
// objective function is
// zero, so assuming that
// the model is quadratic
// we would have to go
// -2*val/||gradient|| in
// this direction, make
// sure we go at most
// step_length into this
// direction
object_mid_point -= std::min(2 * current_value / (gradient*gradient),
step_length / gradient.norm()) *
gradient;
if (respect_manifold == true)
object_mid_point = manifold->project_to_surface(object,
object_mid_point);
// compute current value of the
// objective function
const double previous_value = current_value;
current_value = objective_function (object, object_mid_point);
if (iteration == 0)
initial_delta = (previous_value - current_value);
// stop if we aren't moving much
// any more
if ((iteration >= 1) &&
((previous_value - current_value < 0)
||
(std::fabs (previous_value - current_value)
<
0.001 * initial_delta)))
break;
++iteration;
}
while (iteration < 20);
// verify that the new
// location is indeed better
// than the one before. check
// this by comparing whether
// the minimum value of the
// products of parent and
// child alternating forms is
// positive. for cells this
// means that the
// determinants have the same
// sign, for faces that the
// face normals of parent and
// children point in the same
// general direction
double old_min_product, new_min_product;
Point<spacedim> parent_vertices
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
parent_vertices[i] = object->vertex(i);
Tensor<spacedim-structdim,spacedim> parent_alternating_forms
[GeometryInfo<structdim>::vertices_per_cell];
GeometryInfo<structdim>::alternating_form_at_vertices (parent_vertices,
parent_alternating_forms);
Point<spacedim> child_vertices
[GeometryInfo<structdim>::max_children_per_cell]
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
child_vertices[c][i] = object->child(c)->vertex(i);
Tensor<spacedim-structdim,spacedim> child_alternating_forms
[GeometryInfo<structdim>::max_children_per_cell]
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int c=0; c<object->n_children(); ++c)
GeometryInfo<structdim>::alternating_form_at_vertices (child_vertices[c],
child_alternating_forms[c]);
old_min_product = child_alternating_forms[0][0] * parent_alternating_forms[0];
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
for (unsigned int j=0; j<GeometryInfo<structdim>::vertices_per_cell; ++j)
old_min_product = std::min (old_min_product,
child_alternating_forms[c][i] *
parent_alternating_forms[j]);
// for the new minimum value,
// replace mid-object
// vertex. note that for child
// i, the mid-object vertex
// happens to have the number
// max_children_per_cell-i
for (unsigned int c=0; c<object->n_children(); ++c)
child_vertices[c][GeometryInfo<structdim>::max_children_per_cell-c-1]
= object_mid_point;
for (unsigned int c=0; c<object->n_children(); ++c)
GeometryInfo<structdim>::alternating_form_at_vertices (child_vertices[c],
child_alternating_forms[c]);
new_min_product = child_alternating_forms[0][0] * parent_alternating_forms[0];
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
for (unsigned int j=0; j<GeometryInfo<structdim>::vertices_per_cell; ++j)
new_min_product = std::min (new_min_product,
child_alternating_forms[c][i] *
parent_alternating_forms[j]);
// if new minimum value is
// better than before, then set the
// new mid point. otherwise
// return this object as one of
// those that can't apparently
// be fixed
if (new_min_product >= old_min_product)
object->child(0)->vertex (GeometryInfo<structdim>::max_children_per_cell-1)
= object_mid_point;
// return whether after this
// operation we have an object that
// is well oriented
return (std::max (new_min_product, old_min_product) > 0);
}
void fix_up_faces (const dealii::Triangulation<1,1>::cell_iterator &,
dealii::internal::int2type<1>,
dealii::internal::int2type<1>)
{
// nothing to do for the faces of
// cells in 1d
}
// possibly fix up the faces of
// a cell by moving around its
// mid-points
template <int structdim, int spacedim>
void fix_up_faces (const typename dealii::Triangulation<structdim,spacedim>::cell_iterator &cell,
dealii::internal::int2type<structdim>,
dealii::internal::int2type<spacedim>)
{
// see if we first can fix up
// some of the faces of this
// object. we can mess with
// faces if and only if it is
// not at the boundary (since
// otherwise the location of
// the face mid-point has been
// determined by the boundary
// object) and if the
// neighboring cell is not even
// more refined than we are
// (since in that case the
// sub-faces have themselves
// children that we can't move
// around any more). however,
// the latter case shouldn't
// happen anyway: if the
// current face is distorted
// but the neighbor is even
// more refined, then the face
// had been deformed before
// already, and had been
// ignored at the time; we
// should then also be able to
// ignore it this time as well
for (unsigned int f=0; f<GeometryInfo<structdim>::faces_per_cell; ++f)
{
Assert (cell->face(f)->has_children(), ExcInternalError());
Assert (cell->face(f)->refinement_case() ==
RefinementCase<structdim-1>::isotropic_refinement,
ExcInternalError());
bool subface_is_more_refined = false;
for (unsigned int g=0; g<GeometryInfo<structdim>::max_children_per_face; ++g)
if (cell->face(f)->child(g)->has_children())
{
subface_is_more_refined = true;
break;
}
if (subface_is_more_refined == true)
continue;
// so, now we finally know
// that we can do something
// about this face
fix_up_object (cell->face(f), cell->at_boundary(f));
}
}
} /* namespace FixUpDistortedChildCells */
} /* namespace internal */
template <int dim, int spacedim>
typename Triangulation<dim,spacedim>::DistortedCellList
fix_up_distorted_child_cells (const typename Triangulation<dim,spacedim>::DistortedCellList &distorted_cells,
Triangulation<dim,spacedim> &/*triangulation*/)
{
typename Triangulation<dim,spacedim>::DistortedCellList unfixable_subset;
// loop over all cells that we have
// to fix up
for (typename std::list<typename Triangulation<dim,spacedim>::cell_iterator>::const_iterator
cell_ptr = distorted_cells.distorted_cells.begin();
cell_ptr != distorted_cells.distorted_cells.end(); ++cell_ptr)
{
const typename Triangulation<dim,spacedim>::cell_iterator
cell = *cell_ptr;
internal::FixUpDistortedChildCells
::fix_up_faces (cell,
dealii::internal::int2type<dim>(),
dealii::internal::int2type<spacedim>());
// fix up the object. we need to
// respect the manifold if the cell is
// embedded in a higher dimensional
// space; otherwise, like a hex in 3d,
// every point within the cell interior
// is fair game
if (! internal::FixUpDistortedChildCells::fix_up_object (cell,
(dim < spacedim)))
unfixable_subset.distorted_cells.push_back (cell);
}
return unfixable_subset;
}
template <class Container>
std::vector<typename Container::active_cell_iterator>
get_patch_around_cell(const typename Container::active_cell_iterator &cell)
{
Assert (cell->is_locally_owned(),
ExcMessage ("This function only makes sense if the cell for "
"which you are asking for a patch, is locally "
"owned."));
std::vector<typename Container::active_cell_iterator> patch;
patch.push_back (cell);
for (unsigned int face_number=0; face_number<GeometryInfo<Container::dimension>::faces_per_cell; ++face_number)
if (cell->face(face_number)->at_boundary()==false)
{
if (cell->neighbor(face_number)->has_children() == false)
patch.push_back (cell->neighbor(face_number));
else
// the neighbor is refined. in 2d/3d, we can simply ask for the children
// of the neighbor because they can not be further refined and,
// consequently, the children is active
if (Container::dimension > 1)
{
for (unsigned int subface=0; subface<cell->face(face_number)->n_children(); ++subface)
patch.push_back (cell->neighbor_child_on_subface (face_number, subface));
}
else
{
// in 1d, we need to work a bit harder: iterate until we find
// the child by going from cell to child to child etc
typename Container::cell_iterator neighbor
= cell->neighbor (face_number);
while (neighbor->has_children())
neighbor = neighbor->child(1-face_number);
Assert (neighbor->neighbor(1-face_number) == cell, ExcInternalError());
patch.push_back (neighbor);
}
}
return patch;
}
/*
* Internally used in orthogonal_equality
*
* An orthogonal equality test for points:
*
* point1 and point2 are considered equal, if
* matrix.(point1 + offset) - point2
* is parallel to the unit vector in <direction>
*/
template<int spacedim>
inline bool orthogonal_equality (const Point<spacedim> &point1,
const Point<spacedim> &point2,
const int direction,
const Tensor<1,spacedim> &offset,
const FullMatrix<double> &matrix)
{
Assert (0<=direction && direction<spacedim,
ExcIndexRange (direction, 0, spacedim));
Assert(matrix.m() == matrix.n(), ExcInternalError());
Point<spacedim> distance;
if (matrix.m() == spacedim)
for (int i = 0; i < spacedim; ++i)
for (int j = 0; j < spacedim; ++j)
distance(i) = matrix(i,j) * point1(j);
else
distance = point1;
distance += offset - point2;
for (int i = 0; i < spacedim; ++i)
{
// Only compare coordinate-components != direction:
if (i == direction)
continue;
if (fabs(distance(i)) > 1.e-10)
return false;
}
return true;
}
/*
* Internally used in orthogonal_equality
*
* A lookup table to transform vertex matchings to orientation flags of
* the form (face_orientation, face_flip, face_rotation)
*
* See the comment on the next function as well as the detailed
* documentation of make_periodicity_constraints and
* collect_periodic_faces for details
*/
template<int dim> struct OrientationLookupTable {};
template<> struct OrientationLookupTable<1>
{
typedef std_cxx11::array<unsigned int, GeometryInfo<1>::vertices_per_face> MATCH_T;
static inline std::bitset<3> lookup (const MATCH_T &)
{
// The 1D case is trivial
return 4; // [true ,false,false]
}
};
template<> struct OrientationLookupTable<2>
{
typedef std_cxx11::array<unsigned int, GeometryInfo<2>::vertices_per_face> MATCH_T;
static inline std::bitset<3> lookup (const MATCH_T &matching)
{
// In 2D matching faces (=lines) results in two cases: Either
// they are aligned or flipped. We store this "line_flip"
// property somewhat sloppy as "face_flip"
// (always: face_orientation = true, face_rotation = false)
static const MATCH_T m_tff = {{ 0 , 1 }};
if (matching == m_tff) return 1; // [true ,false,false]
static const MATCH_T m_ttf = {{ 1 , 0 }};
if (matching == m_ttf) return 3; // [true ,true ,false]
AssertThrow(false, ExcInternalError());
// what follows is dead code, but it avoids warnings about the lack
// of a return value
return 0;
}
};
template<> struct OrientationLookupTable<3>
{
typedef std_cxx11::array<unsigned int, GeometryInfo<3>::vertices_per_face> MATCH_T;
static inline std::bitset<3> lookup (const MATCH_T &matching)
{
// The full fledged 3D case. *Yay*
// See the documentation in include/deal.II/base/geometry_info.h
// as well as the actual implementation in source/grid/tria.cc
// for more details...
static const MATCH_T m_tff = {{ 0 , 1 , 2 , 3 }};
if (matching == m_tff) return 1; // [true ,false,false]
static const MATCH_T m_tft = {{ 1 , 3 , 0 , 2 }};
if (matching == m_tft) return 5; // [true ,false,true ]
static const MATCH_T m_ttf = {{ 3 , 2 , 1 , 0 }};
if (matching == m_ttf) return 3; // [true ,true ,false]
static const MATCH_T m_ttt = {{ 2 , 0 , 3 , 1 }};
if (matching == m_ttt) return 7; // [true ,true ,true ]
static const MATCH_T m_fff = {{ 0 , 2 , 1 , 3 }};
if (matching == m_fff) return 0; // [false,false,false]
static const MATCH_T m_fft = {{ 2 , 3 , 0 , 1 }};
if (matching == m_fft) return 4; // [false,false,true ]
static const MATCH_T m_ftf = {{ 3 , 1 , 2 , 0 }};
if (matching == m_ftf) return 2; // [false,true ,false]
static const MATCH_T m_ftt = {{ 1 , 0 , 3 , 2 }};
if (matching == m_ftt) return 6; // [false,true ,true ]
AssertThrow(false, ExcInternalError());
// what follows is dead code, but it avoids warnings about the lack
// of a return value
return 0;
}
};
template<typename FaceIterator>
inline bool
orthogonal_equality (std::bitset<3> &orientation,
const FaceIterator &face1,
const FaceIterator &face2,
const int direction,
const Tensor<1,FaceIterator::AccessorType::space_dimension> &offset,
const FullMatrix<double> &matrix)
{
Assert(matrix.m() == matrix.n(),
ExcMessage("The supplied matrix must be a square matrix"));
static const int dim = FaceIterator::AccessorType::dimension;
// Do a full matching of the face vertices:
std_cxx11::
array<unsigned int, GeometryInfo<dim>::vertices_per_face> matching;
std::set<unsigned int> face2_vertices;
for (unsigned int i = 0; i < GeometryInfo<dim>::vertices_per_face; ++i)
face2_vertices.insert(i);
for (unsigned int i = 0; i < GeometryInfo<dim>::vertices_per_face; ++i)
{
for (std::set<unsigned int>::iterator it = face2_vertices.begin();
it != face2_vertices.end();
it++)
{
if (orthogonal_equality(face1->vertex(i),face2->vertex(*it),
direction, offset, matrix))
{
matching[i] = *it;
face2_vertices.erase(it);
break; // jump out of the innermost loop
}
}
}
// And finally, a lookup to determine the ordering bitmask:
if (face2_vertices.empty())
orientation = OrientationLookupTable<dim>::lookup(matching);
return face2_vertices.empty();
}
template<typename FaceIterator>
inline bool
orthogonal_equality (const FaceIterator &face1,
const FaceIterator &face2,
const int direction,
const Tensor<1,FaceIterator::AccessorType::space_dimension> &offset,
const FullMatrix<double> &matrix)
{
// Call the function above with a dummy orientation array
std::bitset<3> dummy;
return orthogonal_equality (dummy, face1, face2, direction, offset, matrix);
}
/*
* Internally used in collect_periodic_faces
*/
template<typename CellIterator>
void
match_periodic_face_pairs
(std::set<std::pair<CellIterator, unsigned int> > &pairs1,
std::set<std::pair<typename identity<CellIterator>::type, unsigned int> > &pairs2,
const int direction,
std::vector<PeriodicFacePair<CellIterator> > &matched_pairs,
const dealii::Tensor<1,CellIterator::AccessorType::space_dimension> &offset,
const FullMatrix<double> &matrix,
const std::vector<unsigned int> &first_vector_components)
{
static const int space_dim = CellIterator::AccessorType::space_dimension;
(void)space_dim;
Assert (0<=direction && direction<space_dim,
ExcIndexRange (direction, 0, space_dim));
Assert (pairs1.size() == pairs2.size(),
ExcMessage ("Unmatched faces on periodic boundaries"));
unsigned int n_matches = 0;
// Match with a complexity of O(n^2). This could be improved...
std::bitset<3> orientation;
typedef typename std::set
<std::pair<CellIterator, unsigned int> >::const_iterator PairIterator;
for (PairIterator it1 = pairs1.begin(); it1 != pairs1.end(); ++it1)
{
for (PairIterator it2 = pairs2.begin(); it2 != pairs2.end(); ++it2)
{
const CellIterator cell1 = it1->first;
const CellIterator cell2 = it2->first;
const unsigned int face_idx1 = it1->second;
const unsigned int face_idx2 = it2->second;
if (GridTools::orthogonal_equality(orientation,
cell1->face(face_idx1),
cell2->face(face_idx2),
direction, offset,
matrix))
{
// We have a match, so insert the matching pairs and
// remove the matched cell in pairs2 to speed up the
// matching:
const PeriodicFacePair<CellIterator> matched_face =
{
{cell1, cell2},
{face_idx1, face_idx2},
orientation,
matrix,
first_vector_components
};
matched_pairs.push_back(matched_face);
pairs2.erase(it2);
++n_matches;
break;
}
}
}
//Assure that all faces are matched
AssertThrow (n_matches == pairs1.size() && pairs2.size() == 0,
ExcMessage ("Unmatched faces on periodic boundaries"));
}
template<typename CONTAINER>
void
collect_periodic_faces
(const CONTAINER &container,
const types::boundary_id b_id1,
const types::boundary_id b_id2,
const int direction,
std::vector<PeriodicFacePair<typename CONTAINER::cell_iterator> > &matched_pairs,
const Tensor<1,CONTAINER::space_dimension> &offset,
const FullMatrix<double> &matrix,
const std::vector<unsigned int> &first_vector_components)
{
static const int dim = CONTAINER::dimension;
static const int space_dim = CONTAINER::space_dimension;
(void)dim;
(void)space_dim;
Assert (0<=direction && direction<space_dim,
ExcIndexRange (direction, 0, space_dim));
// Loop over all cells on the highest level and collect all boundary
// faces belonging to b_id1 and b_id2:
std::set<std::pair<typename CONTAINER::cell_iterator, unsigned int> > pairs1;
std::set<std::pair<typename CONTAINER::cell_iterator, unsigned int> > pairs2;
for (typename CONTAINER::cell_iterator cell = container.begin(0);
cell != container.end(0); ++cell)
{
for (unsigned int i = 0; i < GeometryInfo<dim>::faces_per_cell; ++i)
{
const typename CONTAINER::face_iterator face = cell->face(i);
if (face->at_boundary() && face->boundary_id() == b_id1)
{
const std::pair<typename CONTAINER::cell_iterator, unsigned int> pair1
= std::make_pair(cell, i);
pairs1.insert(pair1);
}
if (face->at_boundary() && face->boundary_id() == b_id2)
{
const std::pair<typename CONTAINER::cell_iterator, unsigned int> pair2
= std::make_pair(cell, i);
pairs2.insert(pair2);
}
}
}
Assert (pairs1.size() == pairs2.size(),
ExcMessage ("Unmatched faces on periodic boundaries"));
// and call match_periodic_face_pairs that does the actual matching:
match_periodic_face_pairs(pairs1, pairs2, direction, matched_pairs,
offset, matrix, first_vector_components);
}
template<typename CONTAINER>
void
collect_periodic_faces
(const CONTAINER &container,
const types::boundary_id b_id,
const int direction,
std::vector<PeriodicFacePair<typename CONTAINER::cell_iterator> > &matched_pairs,
const Tensor<1,CONTAINER::space_dimension> &offset,
const FullMatrix<double> &matrix,
const std::vector<unsigned int> &first_vector_components)
{
static const int dim = CONTAINER::dimension;
static const int space_dim = CONTAINER::space_dimension;
(void)dim;
(void)space_dim;
Assert (0<=direction && direction<space_dim,
ExcIndexRange (direction, 0, space_dim));
Assert(dim == space_dim,
ExcNotImplemented());
// Loop over all cells on the highest level and collect all boundary
// faces 2*direction and 2*direction*1:
std::set<std::pair<typename CONTAINER::cell_iterator, unsigned int> > pairs1;
std::set<std::pair<typename CONTAINER::cell_iterator, unsigned int> > pairs2;
for (typename CONTAINER::cell_iterator cell = container.begin(0);
cell != container.end(0); ++cell)
{
const typename CONTAINER::face_iterator face_1 = cell->face(2*direction);
const typename CONTAINER::face_iterator face_2 = cell->face(2*direction+1);
if (face_1->at_boundary() && face_1->boundary_id() == b_id)
{
const std::pair<typename CONTAINER::cell_iterator, unsigned int> pair1
= std::make_pair(cell, 2*direction);
pairs1.insert(pair1);
}
if (face_2->at_boundary() && face_2->boundary_id() == b_id)
{
const std::pair<typename CONTAINER::cell_iterator, unsigned int> pair2
= std::make_pair(cell, 2*direction+1);
pairs2.insert(pair2);
}
}
Assert (pairs1.size() == pairs2.size(),
ExcMessage ("Unmatched faces on periodic boundaries"));
#ifdef DEBUG
const unsigned int size_old = matched_pairs.size();
#endif
// and call match_periodic_face_pairs that does the actual matching:
match_periodic_face_pairs(pairs1, pairs2, direction, matched_pairs,
offset, matrix, first_vector_components);
#ifdef DEBUG
//check for standard orientation
const unsigned int size_new = matched_pairs.size();
for (unsigned int i = size_old; i < size_new; ++i)
{
Assert(matched_pairs[i].orientation == 1,
ExcMessage("Found a face match with non standard orientation. "
"This function is only suitable for meshes with cells "
"in default orientation"));
}
#endif
}
template <int dim, int spacedim>
void copy_boundary_to_manifold_id(Triangulation<dim, spacedim> &tria,
const bool reset_boundary_ids)
{
typename Triangulation<dim,spacedim>::active_cell_iterator
cell=tria.begin_active(), endc=tria.end();
for (; cell != endc; ++cell)
for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)
if (cell->face(f)->at_boundary())
{
cell->face(f)->set_manifold_id
(static_cast<types::manifold_id>(cell->face(f)->boundary_id()));
if (reset_boundary_ids == true)
cell->face(f)->set_boundary_id(0);
}
}
template <int dim, int spacedim>
void copy_material_to_manifold_id(Triangulation<dim, spacedim> &tria,
const bool compute_face_ids)
{
typename Triangulation<dim,spacedim>::active_cell_iterator
cell=tria.begin_active(), endc=tria.end();
for (; cell != endc; ++cell)
{
cell->set_manifold_id(cell->material_id());
if (compute_face_ids == true)
{
for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)
{
if (cell->neighbor(f) != endc)
cell->face(f)->set_manifold_id
(std::min(cell->material_id(),
cell->neighbor(f)->material_id()));
else
cell->face(f)->set_manifold_id(cell->material_id());
}
}
}
}
} /* namespace GridTools */
// explicit instantiations
#include "grid_tools.inst"
DEAL_II_NAMESPACE_CLOSE
Replace a double loop over cells and indices by a single loop and the use of cell->active_cell_index().
// ---------------------------------------------------------------------
//
// Copyright (C) 2001 - 2015 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
#include <deal.II/base/std_cxx11/array.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/thread_management.h>
#include <deal.II/lac/vector.h>
#include <deal.II/lac/vector_memory.h>
#include <deal.II/lac/filtered_matrix.h>
#include <deal.II/lac/precondition.h>
#include <deal.II/lac/solver_cg.h>
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/dynamic_sparsity_pattern.h>
#include <deal.II/lac/constraint_matrix.h>
#include <deal.II/lac/sparsity_pattern.h>
#include <deal.II/lac/sparsity_tools.h>
#include <deal.II/grid/tria.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/grid/tria_boundary.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_accessor.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/fe/fe_nothing.h>
#include <deal.II/fe/mapping_q1.h>
#include <deal.II/fe/mapping_q.h>
#include <deal.II/fe/fe_values.h>
#include <deal.II/hp/mapping_collection.h>
#include <deal.II/numerics/matrix_tools.h>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <cmath>
#include <numeric>
#include <list>
#include <set>
DEAL_II_NAMESPACE_OPEN
namespace GridTools
{
// This anonymous namespace contains utility functions to extract the
// triangulation from any container such as DoFHandler
// and the like
namespace
{
template<int dim, int spacedim>
const Triangulation<dim, spacedim> &
get_tria(const Triangulation<dim, spacedim> &tria)
{
return tria;
}
template<int dim, int spacedim>
const Triangulation<dim, spacedim> &
get_tria(const parallel::distributed::Triangulation<dim, spacedim> &tria)
{
return tria;
}
template<int dim, template<int, int> class Container, int spacedim>
const Triangulation<dim,spacedim> &
get_tria(const Container<dim,spacedim> &container)
{
return container.get_tria();
}
template<int dim, int spacedim>
Triangulation<dim, spacedim> &
get_tria(Triangulation<dim, spacedim> &tria)
{
return tria;
}
template<int dim, int spacedim>
Triangulation<dim, spacedim> &
get_tria(parallel::distributed::Triangulation<dim, spacedim> &tria)
{
return tria;
}
template<int dim, template<int, int> class Container, int spacedim>
const Triangulation<dim,spacedim> &
get_tria(Container<dim,spacedim> &container)
{
return container.get_tria();
}
}
template <int dim, int spacedim>
double
diameter (const Triangulation<dim, spacedim> &tria)
{
// we can't deal with distributed meshes
// since we don't have all vertices
// locally. there is one exception,
// however: if the mesh has never been
// refined. the way to test this is not to
// ask tria.n_levels()==1, since this is
// something that can happen on one
// processor without being true on
// all. however, we can ask for the global
// number of active cells and use that
#ifdef DEAL_II_WITH_P4EST
if (const parallel::distributed::Triangulation<dim,spacedim> *p_tria
= dynamic_cast<const parallel::distributed::Triangulation<dim,spacedim>*>(&tria))
Assert (p_tria->n_global_active_cells() == tria.n_cells(0),
ExcNotImplemented());
#endif
// the algorithm used simply
// traverses all cells and picks
// out the boundary vertices. it
// may or may not be faster to
// simply get all vectors, don't
// mark boundary vertices, and
// compute the distances thereof,
// but at least as the mesh is
// refined, it seems better to
// first mark boundary nodes, as
// marking is O(N) in the number of
// cells/vertices, while computing
// the maximal distance is O(N*N)
const std::vector<Point<spacedim> > &vertices = tria.get_vertices ();
std::vector<bool> boundary_vertices (vertices.size(), false);
typename Triangulation<dim,spacedim>::active_cell_iterator
cell = tria.begin_active();
const typename Triangulation<dim,spacedim>::active_cell_iterator
endc = tria.end();
for (; cell!=endc; ++cell)
for (unsigned int face=0; face<GeometryInfo<dim>::faces_per_cell; ++face)
if (cell->face(face)->at_boundary ())
for (unsigned int i=0; i<GeometryInfo<dim>::vertices_per_face; ++i)
boundary_vertices[cell->face(face)->vertex_index(i)] = true;
// now traverse the list of
// boundary vertices and check
// distances. since distances are
// symmetric, we only have to check
// one half
double max_distance_sqr = 0;
std::vector<bool>::const_iterator pi = boundary_vertices.begin();
const unsigned int N = boundary_vertices.size();
for (unsigned int i=0; i<N; ++i, ++pi)
{
std::vector<bool>::const_iterator pj = pi+1;
for (unsigned int j=i+1; j<N; ++j, ++pj)
if ((*pi==true) && (*pj==true) &&
((vertices[i]-vertices[j]).norm_square() > max_distance_sqr))
max_distance_sqr = (vertices[i]-vertices[j]).norm_square();
};
return std::sqrt(max_distance_sqr);
}
template <int dim, int spacedim>
double
volume (const Triangulation<dim, spacedim> &triangulation,
const Mapping<dim,spacedim> &mapping)
{
// get the degree of the mapping if possible. if not, just assume 1
const unsigned int mapping_degree
= (dynamic_cast<const MappingQ<dim,spacedim>*>(&mapping) != 0 ?
dynamic_cast<const MappingQ<dim,spacedim>*>(&mapping)->get_degree() :
1);
// then initialize an appropriate quadrature formula
const QGauss<dim> quadrature_formula (mapping_degree + 1);
const unsigned int n_q_points = quadrature_formula.size();
// we really want the JxW values from the FEValues object, but it
// wants a finite element. create a cheap element as a dummy
// element
FE_Nothing<dim,spacedim> dummy_fe;
FEValues<dim,spacedim> fe_values (mapping, dummy_fe, quadrature_formula,
update_JxW_values);
typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active(),
endc = triangulation.end();
double local_volume = 0;
// compute the integral quantities by quadrature
for (; cell!=endc; ++cell)
if (cell->is_locally_owned())
{
fe_values.reinit (cell);
for (unsigned int q=0; q<n_q_points; ++q)
local_volume += fe_values.JxW(q);
}
double global_volume = 0;
#ifdef DEAL_II_WITH_MPI
if (const parallel::distributed::Triangulation<dim,spacedim> *p_tria
= dynamic_cast<const parallel::distributed::Triangulation<dim,spacedim>*>(&triangulation))
global_volume = Utilities::MPI::sum (local_volume, p_tria->get_communicator());
else
global_volume = local_volume;
#else
global_volume = local_volume;
#endif
return global_volume;
}
template <>
double
cell_measure<3>(const std::vector<Point<3> > &all_vertices,
const unsigned int (&vertex_indices)[GeometryInfo<3>::vertices_per_cell])
{
// note that this is the
// cell_measure based on the new
// deal.II numbering. When called
// from inside GridReordering make
// sure that you reorder the
// vertex_indices before
const double x[8] = { all_vertices[vertex_indices[0]](0),
all_vertices[vertex_indices[1]](0),
all_vertices[vertex_indices[2]](0),
all_vertices[vertex_indices[3]](0),
all_vertices[vertex_indices[4]](0),
all_vertices[vertex_indices[5]](0),
all_vertices[vertex_indices[6]](0),
all_vertices[vertex_indices[7]](0)
};
const double y[8] = { all_vertices[vertex_indices[0]](1),
all_vertices[vertex_indices[1]](1),
all_vertices[vertex_indices[2]](1),
all_vertices[vertex_indices[3]](1),
all_vertices[vertex_indices[4]](1),
all_vertices[vertex_indices[5]](1),
all_vertices[vertex_indices[6]](1),
all_vertices[vertex_indices[7]](1)
};
const double z[8] = { all_vertices[vertex_indices[0]](2),
all_vertices[vertex_indices[1]](2),
all_vertices[vertex_indices[2]](2),
all_vertices[vertex_indices[3]](2),
all_vertices[vertex_indices[4]](2),
all_vertices[vertex_indices[5]](2),
all_vertices[vertex_indices[6]](2),
all_vertices[vertex_indices[7]](2)
};
/*
This is the same Maple script as in the barycenter method above
except of that here the shape functions tphi[0]-tphi[7] are ordered
according to the lexicographic numbering.
x := array(0..7):
y := array(0..7):
z := array(0..7):
tphi[0] := (1-xi)*(1-eta)*(1-zeta):
tphi[1] := xi*(1-eta)*(1-zeta):
tphi[2] := (1-xi)* eta*(1-zeta):
tphi[3] := xi* eta*(1-zeta):
tphi[4] := (1-xi)*(1-eta)*zeta:
tphi[5] := xi*(1-eta)*zeta:
tphi[6] := (1-xi)* eta*zeta:
tphi[7] := xi* eta*zeta:
x_real := sum(x[s]*tphi[s], s=0..7):
y_real := sum(y[s]*tphi[s], s=0..7):
z_real := sum(z[s]*tphi[s], s=0..7):
with (linalg):
J := matrix(3,3, [[diff(x_real, xi), diff(x_real, eta), diff(x_real, zeta)],
[diff(y_real, xi), diff(y_real, eta), diff(y_real, zeta)],
[diff(z_real, xi), diff(z_real, eta), diff(z_real, zeta)]]):
detJ := det (J):
measure := simplify ( int ( int ( int (detJ, xi=0..1), eta=0..1), zeta=0..1)):
readlib(C):
C(measure, optimized);
The C code produced by this maple script is further optimized by
hand. In particular, division by 12 is performed only once, not
hundred of times.
*/
const double t3 = y[3]*x[2];
const double t5 = z[1]*x[5];
const double t9 = z[3]*x[2];
const double t11 = x[1]*y[0];
const double t14 = x[4]*y[0];
const double t18 = x[5]*y[7];
const double t20 = y[1]*x[3];
const double t22 = y[5]*x[4];
const double t26 = z[7]*x[6];
const double t28 = x[0]*y[4];
const double t34 = z[3]*x[1]*y[2]+t3*z[1]-t5*y[7]+y[7]*x[4]*z[6]+t9*y[6]-t11*z[4]-t5*y[3]-t14*z[2]+z[1]*x[4]*y[0]-t18*z[3]+t20*z[0]-t22*z[0]-y[0]*x[5]*z[4]-t26*y[3]+t28*z[2]-t9*y[1]-y[1]*x[4]*z[0]-t11*z[5];
const double t37 = y[1]*x[0];
const double t44 = x[1]*y[5];
const double t46 = z[1]*x[0];
const double t49 = x[0]*y[2];
const double t52 = y[5]*x[7];
const double t54 = x[3]*y[7];
const double t56 = x[2]*z[0];
const double t58 = x[3]*y[2];
const double t64 = -x[6]*y[4]*z[2]-t37*z[2]+t18*z[6]-x[3]*y[6]*z[2]+t11*z[2]+t5*y[0]+t44*z[4]-t46*y[4]-t20*z[7]-t49*z[6]-t22*z[1]+t52*z[3]-t54*z[2]-t56*y[4]-t58*z[0]+y[1]*x[2]*z[0]+t9*y[7]+t37*z[4];
const double t66 = x[1]*y[7];
const double t68 = y[0]*x[6];
const double t70 = x[7]*y[6];
const double t73 = z[5]*x[4];
const double t76 = x[6]*y[7];
const double t90 = x[4]*z[0];
const double t92 = x[1]*y[3];
const double t95 = -t66*z[3]-t68*z[2]-t70*z[2]+t26*y[5]-t73*y[6]-t14*z[6]+t76*z[2]-t3*z[6]+x[6]*y[2]*z[4]-z[3]*x[6]*y[2]+t26*y[4]-t44*z[3]-x[1]*y[2]*z[0]+x[5]*y[6]*z[4]+t54*z[5]+t90*y[2]-t92*z[2]+t46*y[2];
const double t102 = x[2]*y[0];
const double t107 = y[3]*x[7];
const double t114 = x[0]*y[6];
const double t125 = y[0]*x[3]*z[2]-z[7]*x[5]*y[6]-x[2]*y[6]*z[4]+t102*z[6]-t52*z[6]+x[2]*y[4]*z[6]-t107*z[5]-t54*z[6]+t58*z[6]-x[7]*y[4]*z[6]+t37*z[5]-t114*z[4]+t102*z[4]-z[1]*x[2]*y[0]+t28*z[6]-y[5]*x[6]*z[4]-z[5]*x[1]*y[4]-t73*y[7];
const double t129 = z[0]*x[6];
const double t133 = y[1]*x[7];
const double t145 = y[1]*x[5];
const double t156 = t90*y[6]-t129*y[4]+z[7]*x[2]*y[6]-t133*z[5]+x[5]*y[3]*z[7]-t26*y[2]-t70*z[3]+t46*y[3]+z[5]*x[7]*y[4]+z[7]*x[3]*y[6]-t49*z[4]+t145*z[7]-x[2]*y[7]*z[6]+t70*z[5]+t66*z[5]-z[7]*x[4]*y[6]+t18*z[4]+x[1]*y[4]*z[0];
const double t160 = x[5]*y[4];
const double t165 = z[1]*x[7];
const double t178 = z[1]*x[3];
const double t181 = t107*z[6]+t22*z[7]+t76*z[3]+t160*z[1]-x[4]*y[2]*z[6]+t70*z[4]+t165*y[5]+x[7]*y[2]*z[6]-t76*z[5]-t76*z[4]+t133*z[3]-t58*z[1]+y[5]*x[0]*z[4]+t114*z[2]-t3*z[7]+t20*z[2]+t178*y[7]+t129*y[2];
const double t207 = t92*z[7]+t22*z[6]+z[3]*x[0]*y[2]-x[0]*y[3]*z[2]-z[3]*x[7]*y[2]-t165*y[3]-t9*y[0]+t58*z[7]+y[3]*x[6]*z[2]+t107*z[2]+t73*y[0]-x[3]*y[5]*z[7]+t3*z[0]-t56*y[6]-z[5]*x[0]*y[4]+t73*y[1]-t160*z[6]+t160*z[0];
const double t228 = -t44*z[7]+z[5]*x[6]*y[4]-t52*z[4]-t145*z[4]+t68*z[4]+t92*z[5]-t92*z[0]+t11*z[3]+t44*z[0]+t178*y[5]-t46*y[5]-t178*y[0]-t145*z[0]-t20*z[5]-t37*z[3]-t160*z[7]+t145*z[3]+x[4]*y[6]*z[2];
return (t34+t64+t95+t125+t156+t181+t207+t228)/12.;
}
template <>
double
cell_measure(const std::vector<Point<2> > &all_vertices,
const unsigned int (&vertex_indices) [GeometryInfo<2>::vertices_per_cell])
{
/*
Get the computation of the measure by this little Maple script. We
use the blinear mapping of the unit quad to the real quad. However,
every transformation mapping the unit faces to straight lines should
do.
Remember that the area of the quad is given by
\int_K 1 dx dy = \int_{\hat K} |det J| d(xi) d(eta)
# x and y are arrays holding the x- and y-values of the four vertices
# of this cell in real space.
x := array(0..3);
y := array(0..3);
z := array(0..3);
tphi[0] := (1-xi)*(1-eta):
tphi[1] := xi*(1-eta):
tphi[2] := (1-xi)*eta:
tphi[3] := xi*eta:
x_real := sum(x[s]*tphi[s], s=0..3):
y_real := sum(y[s]*tphi[s], s=0..3):
z_real := sum(z[s]*tphi[s], s=0..3):
Jxi := <diff(x_real,xi) | diff(y_real,xi) | diff(z_real,xi)>;
Jeta := <diff(x_real,eta)| diff(y_real,eta)| diff(z_real,eta)>;
with(VectorCalculus):
J := CrossProduct(Jxi, Jeta);
detJ := sqrt(J[1]^2 + J[2]^2 +J[3]^2);
# measure := evalf (Int (Int (detJ, xi=0..1, method = _NCrule ) , eta=0..1, method = _NCrule ) ):
# readlib(C):
# C(measure, optimized);
additional optimizaton: divide by 2 only one time
*/
const double x[4] = { all_vertices[vertex_indices[0]](0),
all_vertices[vertex_indices[1]](0),
all_vertices[vertex_indices[2]](0),
all_vertices[vertex_indices[3]](0)
};
const double y[4] = { all_vertices[vertex_indices[0]](1),
all_vertices[vertex_indices[1]](1),
all_vertices[vertex_indices[2]](1),
all_vertices[vertex_indices[3]](1)
};
return (-x[1]*y[0]+x[1]*y[3]+y[0]*x[2]+x[0]*y[1]-x[0]*y[2]-y[1]*x[3]-x[2]*y[3]+x[3]*y[2])/2;
}
template <int dim>
double
cell_measure(const std::vector<Point<dim> > &,
const unsigned int ( &) [GeometryInfo<dim>::vertices_per_cell])
{
Assert(false, ExcNotImplemented());
return 0.;
}
template <int dim, int spacedim>
void
delete_unused_vertices (std::vector<Point<spacedim> > &vertices,
std::vector<CellData<dim> > &cells,
SubCellData &subcelldata)
{
// first check which vertices are
// actually used
std::vector<bool> vertex_used (vertices.size(), false);
for (unsigned int c=0; c<cells.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
vertex_used[cells[c].vertices[v]] = true;
// then renumber the vertices that
// are actually used in the same
// order as they were beforehand
const unsigned int invalid_vertex = numbers::invalid_unsigned_int;
std::vector<unsigned int> new_vertex_numbers (vertices.size(), invalid_vertex);
unsigned int next_free_number = 0;
for (unsigned int i=0; i<vertices.size(); ++i)
if (vertex_used[i] == true)
{
new_vertex_numbers[i] = next_free_number;
++next_free_number;
};
// next replace old vertex numbers
// by the new ones
for (unsigned int c=0; c<cells.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
cells[c].vertices[v] = new_vertex_numbers[cells[c].vertices[v]];
// same for boundary data
for (unsigned int c=0; c<subcelldata.boundary_lines.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<1>::vertices_per_cell; ++v)
subcelldata.boundary_lines[c].vertices[v]
= new_vertex_numbers[subcelldata.boundary_lines[c].vertices[v]];
for (unsigned int c=0; c<subcelldata.boundary_quads.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<2>::vertices_per_cell; ++v)
subcelldata.boundary_quads[c].vertices[v]
= new_vertex_numbers[subcelldata.boundary_quads[c].vertices[v]];
// finally copy over the vertices
// which we really need to a new
// array and replace the old one by
// the new one
std::vector<Point<spacedim> > tmp;
tmp.reserve (std::count(vertex_used.begin(), vertex_used.end(), true));
for (unsigned int v=0; v<vertices.size(); ++v)
if (vertex_used[v] == true)
tmp.push_back (vertices[v]);
swap (vertices, tmp);
}
template <int dim, int spacedim>
void
delete_duplicated_vertices (std::vector<Point<spacedim> > &vertices,
std::vector<CellData<dim> > &cells,
SubCellData &subcelldata,
std::vector<unsigned int> &considered_vertices,
double tol)
{
// create a vector of vertex
// indices. initialize it to the identity,
// later on change that if necessary.
std::vector<unsigned int> new_vertex_numbers(vertices.size());
for (unsigned int i=0; i<vertices.size(); ++i)
new_vertex_numbers[i]=i;
// if the considered_vertices vector is
// empty, consider all vertices
if (considered_vertices.size()==0)
considered_vertices=new_vertex_numbers;
// now loop over all vertices to be
// considered and try to find an identical
// one
for (unsigned int i=0; i<considered_vertices.size(); ++i)
{
if (new_vertex_numbers[considered_vertices[i]]!=considered_vertices[i])
// this vertex has been identified with
// another one already, skip it in the
// test
continue;
// this vertex is not identified with
// another one so far. search in the list
// of remaining vertices. if a duplicate
// vertex is found, set the new vertex
// index for that vertex to this vertex'
// index.
for (unsigned int j=i+1; j<considered_vertices.size(); ++j)
{
bool equal=true;
for (unsigned int d=0; d<spacedim; ++d)
equal &= (fabs(vertices[considered_vertices[j]](d)-vertices[considered_vertices[i]](d))<tol);
if (equal)
{
new_vertex_numbers[considered_vertices[j]]=considered_vertices[i];
// we do not suppose, that there might be another duplicate
// vertex, so break here
break;
}
}
}
// now we got a renumbering list. simply
// renumber all vertices (non-duplicate
// vertices get renumbered to themselves, so
// nothing bad happens). after that, the
// duplicate vertices will be unused, so call
// delete_unused_vertices() to do that part
// of the job.
for (unsigned int c=0; c<cells.size(); ++c)
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
cells[c].vertices[v]=new_vertex_numbers[cells[c].vertices[v]];
delete_unused_vertices(vertices,cells,subcelldata);
}
// define some transformations in an anonymous namespace
namespace
{
template <int spacedim>
class Shift
{
public:
Shift (const Tensor<1,spacedim> &shift)
:
shift(shift)
{}
Point<spacedim> operator() (const Point<spacedim> p) const
{
return p+shift;
}
private:
const Tensor<1,spacedim> shift;
};
// the following class is only
// needed in 2d, so avoid trouble
// with compilers warning otherwise
class Rotate2d
{
public:
Rotate2d (const double angle)
:
angle(angle)
{}
Point<2> operator() (const Point<2> &p) const
{
return Point<2> (std::cos(angle)*p(0) - std::sin(angle) * p(1),
std::sin(angle)*p(0) + std::cos(angle) * p(1));
}
private:
const double angle;
};
template <int spacedim>
class Scale
{
public:
Scale (const double factor)
:
factor(factor)
{}
Point<spacedim> operator() (const Point<spacedim> p) const
{
return p*factor;
}
private:
const double factor;
};
}
template <int dim, int spacedim>
void
shift (const Tensor<1,spacedim> &shift_vector,
Triangulation<dim, spacedim> &triangulation)
{
transform (Shift<spacedim>(shift_vector), triangulation);
}
void
rotate (const double angle,
Triangulation<2> &triangulation)
{
transform (Rotate2d(angle), triangulation);
}
template <int dim, int spacedim>
void
scale (const double scaling_factor,
Triangulation<dim, spacedim> &triangulation)
{
Assert (scaling_factor>0, ExcScalingFactorNotPositive (scaling_factor));
transform (Scale<spacedim>(scaling_factor), triangulation);
}
namespace
{
/**
* Solve the Laplace equation for the @p laplace_transform function for one
* of the @p dim space dimensions. Factorized into a function of its own
* in order to allow parallel execution.
*/
void laplace_solve (const SparseMatrix<double> &S,
const std::map<unsigned int,double> &m,
Vector<double> &u)
{
const unsigned int n_dofs=S.n();
FilteredMatrix<Vector<double> > SF (S);
PreconditionJacobi<SparseMatrix<double> > prec;
prec.initialize(S, 1.2);
FilteredMatrix<Vector<double> > PF (prec);
SolverControl control (n_dofs, 1.e-10, false, false);
GrowingVectorMemory<Vector<double> > mem;
SolverCG<Vector<double> > solver (control, mem);
Vector<double> f(n_dofs);
SF.add_constraints(m);
SF.apply_constraints (f, true);
solver.solve(SF, u, f, PF);
}
}
// Implementation for 1D only
template <>
void laplace_transform (const std::map<unsigned int,Point<1> > &,
Triangulation<1> &,
const Function<1> *)
{
Assert(false, ExcNotImplemented());
}
// Implementation for dimensions except 1
template <int dim>
void
laplace_transform (const std::map<unsigned int,Point<dim> > &new_points,
Triangulation<dim> &triangulation,
const Function<dim> *coefficient)
{
// first provide everything that is
// needed for solving a Laplace
// equation.
MappingQ1<dim> mapping_q1;
FE_Q<dim> q1(1);
DoFHandler<dim> dof_handler(triangulation);
dof_handler.distribute_dofs(q1);
DynamicSparsityPattern dsp (dof_handler.n_dofs (),
dof_handler.n_dofs ());
DoFTools::make_sparsity_pattern (dof_handler, dsp);
dsp.compress ();
SparsityPattern sparsity_pattern;
sparsity_pattern.copy_from (dsp);
sparsity_pattern.compress ();
SparseMatrix<double> S(sparsity_pattern);
QGauss<dim> quadrature(4);
MatrixCreator::create_laplace_matrix(mapping_q1, dof_handler, quadrature, S,coefficient);
// set up the boundary values for
// the laplace problem
std::vector<std::map<unsigned int,double> > m(dim);
typename std::map<unsigned int,Point<dim> >::const_iterator map_end=new_points.end();
// fill these maps using the data
// given by new_points
typename DoFHandler<dim>::cell_iterator cell=dof_handler.begin_active(),
endc=dof_handler.end();
for (; cell!=endc; ++cell)
{
for (unsigned int face_no=0; face_no<GeometryInfo<dim>::faces_per_cell; ++face_no)
{
const typename DoFHandler<dim>::face_iterator face=cell->face(face_no);
// loop over all vertices of the cell and see if it is listed in the map
// given as first argument of the function
for (unsigned int vertex_no=0;
vertex_no<GeometryInfo<dim>::vertices_per_face; ++vertex_no)
{
const unsigned int vertex_index=face->vertex_index(vertex_no);
const typename std::map<unsigned int,Point<dim> >::const_iterator map_iter
= new_points.find(vertex_index);
if (map_iter!=map_end)
for (unsigned int i=0; i<dim; ++i)
m[i].insert(std::pair<unsigned int,double> (
face->vertex_dof_index(vertex_no, 0), map_iter->second(i)));
}
}
}
// solve the dim problems with
// different right hand sides.
Vector<double> us[dim];
for (unsigned int i=0; i<dim; ++i)
us[i].reinit (dof_handler.n_dofs());
// solve linear systems in parallel
Threads::TaskGroup<> tasks;
for (unsigned int i=0; i<dim; ++i)
tasks += Threads::new_task (&laplace_solve,
S, m[i], us[i]);
tasks.join_all ();
// change the coordinates of the
// points of the triangulation
// according to the computed values
for (cell=dof_handler.begin_active(); cell!=endc; ++cell)
for (unsigned int vertex_no=0;
vertex_no<GeometryInfo<dim>::vertices_per_cell; ++vertex_no)
{
Point<dim> &v=cell->vertex(vertex_no);
const unsigned int dof_index=cell->vertex_dof_index(vertex_no, 0);
for (unsigned int i=0; i<dim; ++i)
v(i)=us[i](dof_index);
}
}
template <int dim, int spacedim>
std::map<unsigned int, Point<spacedim> >
get_all_vertices_at_boundary (const Triangulation<dim, spacedim> &tria)
{
std::map<unsigned int, Point<spacedim> > vertex_map;
typename Triangulation<dim,spacedim>::active_cell_iterator
cell = tria.begin_active(),
endc = tria.end();
for (; cell!=endc; ++cell)
{
for (unsigned int i=0; i<GeometryInfo<dim>::faces_per_cell; ++i)
{
const typename Triangulation<dim, spacedim>::face_iterator &face
= cell->face(i);
if (face->at_boundary())
{
for (unsigned j = 0; j < GeometryInfo<dim>::vertices_per_face; ++j)
{
const Point<spacedim> &vertex = face->vertex(j);
const unsigned int vertex_index = face->vertex_index(j);
vertex_map[vertex_index] = vertex;
}
}
}
}
return vertex_map;
}
/**
* Distort a triangulation in
* some random way.
*/
template <int dim, int spacedim>
void
distort_random (const double factor,
Triangulation<dim,spacedim> &triangulation,
const bool keep_boundary)
{
// if spacedim>dim we need to make sure that we perturb
// points but keep them on
// the manifold. however, this isn't implemented right now
Assert (spacedim == dim, ExcNotImplemented());
// find the smallest length of the
// lines adjacent to the
// vertex. take the initial value
// to be larger than anything that
// might be found: the diameter of
// the triangulation, here
// estimated by adding up the
// diameters of the coarse grid
// cells.
double almost_infinite_length = 0;
for (typename Triangulation<dim,spacedim>::cell_iterator
cell=triangulation.begin(0); cell!=triangulation.end(0); ++cell)
almost_infinite_length += cell->diameter();
std::vector<double> minimal_length (triangulation.n_vertices(),
almost_infinite_length);
// also note if a vertex is at the boundary
std::vector<bool> at_boundary (triangulation.n_vertices(), false);
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell=triangulation.begin_active(); cell!=triangulation.end(); ++cell)
if (cell->is_locally_owned())
{
if (dim>1)
{
for (unsigned int i=0; i<GeometryInfo<dim>::lines_per_cell; ++i)
{
const typename Triangulation<dim,spacedim>::line_iterator line
= cell->line(i);
if (keep_boundary && line->at_boundary())
{
at_boundary[line->vertex_index(0)] = true;
at_boundary[line->vertex_index(1)] = true;
}
minimal_length[line->vertex_index(0)]
= std::min(line->diameter(),
minimal_length[line->vertex_index(0)]);
minimal_length[line->vertex_index(1)]
= std::min(line->diameter(),
minimal_length[line->vertex_index(1)]);
}
}
else //dim==1
{
if (keep_boundary)
for (unsigned int vertex=0; vertex<2; ++vertex)
if (cell->at_boundary(vertex) == true)
at_boundary[cell->vertex_index(vertex)] = true;
minimal_length[cell->vertex_index(0)]
= std::min(cell->diameter(),
minimal_length[cell->vertex_index(0)]);
minimal_length[cell->vertex_index(1)]
= std::min(cell->diameter(),
minimal_length[cell->vertex_index(1)]);
}
}
// If the triangulation is distributed, we need to
// exchange the moved vertices across mpi processes
if (parallel::distributed::Triangulation< dim, spacedim > *distributed_triangulation
= dynamic_cast<parallel::distributed::Triangulation<dim,spacedim>*> (&triangulation))
{
// create a random number generator for the interval [-1,1]. we use
// this to make sure the distribution we get is repeatable, i.e.,
// if you call the function twice on the same mesh, then you will
// get the same mesh. this would not be the case if you used
// the rand() function, which carries around some internal state
boost::random::mt19937 rng;
boost::random::uniform_real_distribution<> uniform_distribution(-1,1);
const std::vector<bool> locally_owned_vertices = get_locally_owned_vertices(triangulation);
std::vector<bool> vertex_moved (triangulation.n_vertices(), false);
// Next move vertices on locally owned cells
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell=triangulation.begin_active(); cell!=triangulation.end(); ++cell)
if (cell->is_locally_owned())
{
for (unsigned int vertex_no=0; vertex_no<GeometryInfo<dim>::vertices_per_cell;
++vertex_no)
{
const unsigned global_vertex_no = cell->vertex_index(vertex_no);
// ignore this vertex if we shall keep the boundary and
// this vertex *is* at the boundary, if it is already moved
// or if another process moves this vertex
if ((keep_boundary && at_boundary[global_vertex_no])
|| vertex_moved[global_vertex_no]
|| !locally_owned_vertices[global_vertex_no])
continue;
// first compute a random shift vector
Point<spacedim> shift_vector;
for (unsigned int d=0; d<spacedim; ++d)
shift_vector(d) = uniform_distribution(rng);
shift_vector *= factor * minimal_length[global_vertex_no] /
std::sqrt(shift_vector.square());
// finally move the vertex
cell->vertex(vertex_no) += shift_vector;
vertex_moved[global_vertex_no] = true;
}
}
#ifdef DEAL_II_WITH_P4EST
distributed_triangulation
->communicate_locally_moved_vertices(locally_owned_vertices);
#else
(void)distributed_triangulation;
Assert (false, ExcInternalError());
#endif
}
else
// if this is a sequential triangulation, we could in principle
// use the algorithm above, but we'll use an algorithm that we used
// before the parallel::distributed::Triangulation was introduced
// in order to preserve backward compatibility
{
// loop over all vertices and compute their new locations
const unsigned int n_vertices = triangulation.n_vertices();
std::vector<Point<spacedim> > new_vertex_locations (n_vertices);
const std::vector<Point<spacedim> > &old_vertex_locations
= triangulation.get_vertices();
for (unsigned int vertex=0; vertex<n_vertices; ++vertex)
{
// ignore this vertex if we will keep the boundary and
// this vertex *is* at the boundary
if (keep_boundary && at_boundary[vertex])
new_vertex_locations[vertex] = old_vertex_locations[vertex];
else
{
// compute a random shift vector
Point<spacedim> shift_vector;
for (unsigned int d=0; d<spacedim; ++d)
shift_vector(d) = std::rand()*2.0/RAND_MAX-1;
shift_vector *= factor * minimal_length[vertex] /
std::sqrt(shift_vector.square());
// record new vertex location
new_vertex_locations[vertex] = old_vertex_locations[vertex] + shift_vector;
}
}
// now do the actual move of the vertices
for (typename Triangulation<dim,spacedim>::active_cell_iterator
cell=triangulation.begin_active(); cell!=triangulation.end(); ++cell)
for (unsigned int vertex_no=0;
vertex_no<GeometryInfo<dim>::vertices_per_cell; ++vertex_no)
cell->vertex(vertex_no) = new_vertex_locations[cell->vertex_index(vertex_no)];
}
// Correct hanging nodes if necessary
if (dim>=2)
{
// We do the same as in GridTools::transform
//
// exclude hanging nodes at the boundaries of artificial cells:
// these may belong to ghost cells for which we know the exact
// location of vertices, whereas the artificial cell may or may
// not be further refined, and so we cannot know whether
// the location of the hanging node is correct or not
typename Triangulation<dim,spacedim>::active_cell_iterator
cell = triangulation.begin_active(),
endc = triangulation.end();
for (; cell!=endc; ++cell)
if (!cell->is_artificial())
for (unsigned int face=0;
face<GeometryInfo<dim>::faces_per_cell; ++face)
if (cell->face(face)->has_children() &&
!cell->face(face)->at_boundary())
{
// this face has hanging nodes
if (dim==2)
cell->face(face)->child(0)->vertex(1)
= (cell->face(face)->vertex(0) +
cell->face(face)->vertex(1)) / 2;
else if (dim==3)
{
cell->face(face)->child(0)->vertex(1)
= .5*(cell->face(face)->vertex(0)
+cell->face(face)->vertex(1));
cell->face(face)->child(0)->vertex(2)
= .5*(cell->face(face)->vertex(0)
+cell->face(face)->vertex(2));
cell->face(face)->child(1)->vertex(3)
= .5*(cell->face(face)->vertex(1)
+cell->face(face)->vertex(3));
cell->face(face)->child(2)->vertex(3)
= .5*(cell->face(face)->vertex(2)
+cell->face(face)->vertex(3));
// center of the face
cell->face(face)->child(0)->vertex(3)
= .25*(cell->face(face)->vertex(0)
+cell->face(face)->vertex(1)
+cell->face(face)->vertex(2)
+cell->face(face)->vertex(3));
}
}
}
}
template <int dim, template <int, int> class Container, int spacedim>
unsigned int
find_closest_vertex (const Container<dim,spacedim> &container,
const Point<spacedim> &p)
{
// first get the underlying
// triangulation from the
// container and determine vertices
// and used vertices
const Triangulation<dim, spacedim> &tria = get_tria(container);
const std::vector< Point<spacedim> > &vertices = tria.get_vertices();
const std::vector< bool > &used = tria.get_used_vertices();
// At the beginning, the first
// used vertex is the closest one
std::vector<bool>::const_iterator first =
std::find(used.begin(), used.end(), true);
// Assert that at least one vertex
// is actually used
Assert(first != used.end(), ExcInternalError());
unsigned int best_vertex = std::distance(used.begin(), first);
double best_dist = (p - vertices[best_vertex]).norm_square();
// For all remaining vertices, test
// whether they are any closer
for (unsigned int j = best_vertex+1; j < vertices.size(); j++)
if (used[j])
{
double dist = (p - vertices[j]).norm_square();
if (dist < best_dist)
{
best_vertex = j;
best_dist = dist;
}
}
return best_vertex;
}
template<int dim, template<int, int> class Container, int spacedim>
#ifndef _MSC_VER
std::vector<typename Container<dim, spacedim>::active_cell_iterator>
#else
std::vector<typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type>
#endif
find_cells_adjacent_to_vertex(const Container<dim,spacedim> &container,
const unsigned int vertex)
{
// make sure that the given vertex is
// an active vertex of the underlying
// triangulation
Assert(vertex < get_tria(container).n_vertices(),
ExcIndexRange(0,get_tria(container).n_vertices(),vertex));
Assert(get_tria(container).get_used_vertices()[vertex],
ExcVertexNotUsed(vertex));
// use a set instead of a vector
// to ensure that cells are inserted only
// once
std::set<typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type> adjacent_cells;
typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type
cell = container.begin_active(),
endc = container.end();
// go through all active cells and look if the vertex is part of that cell
//
// in 1d, this is all we need to care about. in 2d/3d we also need to worry
// that the vertex might be a hanging node on a face or edge of a cell; in
// this case, we would want to add those cells as well on whose faces the
// vertex is located but for which it is not a vertex itself.
//
// getting this right is a lot simpler in 2d than in 3d. in 2d, a hanging
// node can only be in the middle of a face and we can query the neighboring
// cell from the current cell. on the other hand, in 3d a hanging node
// vertex can also be on an edge but there can be many other cells on
// this edge and we can not access them from the cell we are currently
// on.
//
// so, in the 3d case, if we run the algorithm as in 2d, we catch all
// those cells for which the vertex we seek is on a *subface*, but we
// miss the case of cells for which the vertex we seek is on a
// sub-edge for which there is no corresponding sub-face (because the
// immediate neighbor behind this face is not refined), see for example
// the bits/find_cells_adjacent_to_vertex_6 testcase. thus, if we
// haven't yet found the vertex for the current cell we also need to
// look at the mid-points of edges
//
// as a final note, deciding whether a neighbor is actually coarser is
// simple in the case of isotropic refinement (we just need to look at
// the level of the current and the neighboring cell). however, this
// isn't so simple if we have used anisotropic refinement since then
// the level of a cell is not indicative of whether it is coarser or
// not than the current cell. ultimately, we want to add all cells on
// which the vertex is, independent of whether they are coarser or
// finer and so in the 2d case below we simply add *any* *active* neighbor.
// in the worst case, we add cells multiple times to the adjacent_cells
// list, but std::set throws out those cells already entered
for (; cell != endc; ++cell)
{
for (unsigned int v = 0; v < GeometryInfo<dim>::vertices_per_cell; v++)
if (cell->vertex_index(v) == vertex)
{
// OK, we found a cell that contains
// the given vertex. We add it
// to the list.
adjacent_cells.insert(cell);
// as explained above, in 2+d we need to check whether
// this vertex is on a face behind which there is a
// (possibly) coarser neighbor. if this is the case,
// then we need to also add this neighbor
if (dim >= 2)
for (unsigned int vface = 0; vface < dim; vface++)
{
const unsigned int face =
GeometryInfo<dim>::vertex_to_face[v][vface];
if (!cell->at_boundary(face)
&&
cell->neighbor(face)->active())
{
// there is a (possibly) coarser cell behind a
// face to which the vertex belongs. the
// vertex we are looking at is then either a
// vertex of that coarser neighbor, or it is a
// hanging node on one of the faces of that
// cell. in either case, it is adjacent to the
// vertex, so add it to the list as well (if
// the cell was already in the list then the
// std::set makes sure that we get it only
// once)
adjacent_cells.insert (cell->neighbor(face));
}
}
// in any case, we have found a cell, so go to the next cell
goto next_cell;
}
// in 3d also loop over the edges
if (dim >= 3)
{
for (unsigned int e=0; e<GeometryInfo<dim>::lines_per_cell; ++e)
if (cell->line(e)->has_children())
// the only place where this vertex could have been
// hiding is on the mid-edge point of the edge we
// are looking at
if (cell->line(e)->child(0)->vertex_index(1) == vertex)
{
adjacent_cells.insert(cell);
// jump out of this tangle of nested loops
goto next_cell;
}
}
// in more than 3d we would probably have to do the same as
// above also for even lower-dimensional objects
Assert (dim <= 3, ExcNotImplemented());
// move on to the next cell if we have found the
// vertex on the current one
next_cell:
;
}
// if this was an active vertex then there needs to have been
// at least one cell to which it is adjacent!
Assert (adjacent_cells.size() > 0, ExcInternalError());
// return the result as a vector, rather than the set we built above
return
std::vector<typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type>
(adjacent_cells.begin(), adjacent_cells.end());
}
namespace
{
template <int dim, template<int, int> class Container, int spacedim>
void find_active_cell_around_point_internal(const Container<dim,spacedim> &container,
#ifndef _MSC_VER
std::set<typename Container<dim, spacedim>::active_cell_iterator> &searched_cells,
std::set<typename Container<dim, spacedim>::active_cell_iterator> &adjacent_cells)
#else
std::set<typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type> &searched_cells,
std::set<typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type> &adjacent_cells)
#endif
{
#ifndef _MSC_VER
typedef typename Container<dim, spacedim>::active_cell_iterator cell_iterator;
#else
typedef typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type cell_iterator;
#endif
// update the searched cells
searched_cells.insert(adjacent_cells.begin(), adjacent_cells.end());
// now we to collect all neighbors
// of the cells in adjacent_cells we
// have not yet searched.
std::set<cell_iterator> adjacent_cells_new;
typename std::set<cell_iterator>::const_iterator
cell = adjacent_cells.begin(),
endc = adjacent_cells.end();
for (; cell != endc; ++cell)
{
std::vector<cell_iterator> active_neighbors;
get_active_neighbors<Container<dim, spacedim> >(*cell, active_neighbors);
for (unsigned int i=0; i<active_neighbors.size(); ++i)
if (searched_cells.find(active_neighbors[i]) == searched_cells.end())
adjacent_cells_new.insert(active_neighbors[i]);
}
adjacent_cells.clear();
adjacent_cells.insert(adjacent_cells_new.begin(), adjacent_cells_new.end());
if (adjacent_cells.size() == 0)
{
// we haven't found any other cell that would be a
// neighbor of a previously found cell, but we know
// that we haven't checked all cells yet. that means
// that the domain is disconnected. in that case,
// choose the first previously untouched cell we
// can find
cell_iterator it = container.begin_active();
for ( ; it!=container.end(); ++it)
if (searched_cells.find(it) == searched_cells.end())
{
adjacent_cells.insert(it);
break;
}
}
}
}
template <int dim, template<int, int> class Container, int spacedim>
#ifndef _MSC_VER
typename Container<dim, spacedim>::active_cell_iterator
#else
typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type
#endif
find_active_cell_around_point (const Container<dim,spacedim> &container,
const Point<spacedim> &p)
{
return
find_active_cell_around_point<dim,Container,spacedim>
(StaticMappingQ1<dim,spacedim>::mapping,
container, p).first;
}
template <int dim, template <int, int> class Container, int spacedim>
#ifndef _MSC_VER
std::pair<typename Container<dim, spacedim>::active_cell_iterator, Point<dim> >
#else
std::pair<typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type, Point<dim> >
#endif
find_active_cell_around_point (const Mapping<dim,spacedim> &mapping,
const Container<dim,spacedim> &container,
const Point<spacedim> &p)
{
typedef typename dealii::internal::ActiveCellIterator<dim, spacedim, Container<dim, spacedim> >::type active_cell_iterator;
// The best distance is set to the
// maximum allowable distance from
// the unit cell; we assume a
// max. deviation of 1e-10
double best_distance = 1e-10;
int best_level = -1;
std::pair<active_cell_iterator, Point<dim> > best_cell;
// Find closest vertex and determine
// all adjacent cells
std::vector<active_cell_iterator> adjacent_cells_tmp
= find_cells_adjacent_to_vertex(container,
find_closest_vertex(container, p));
// Make sure that we have found
// at least one cell adjacent to vertex.
Assert(adjacent_cells_tmp.size()>0, ExcInternalError());
// Copy all the cells into a std::set
std::set<active_cell_iterator> adjacent_cells (adjacent_cells_tmp.begin(),
adjacent_cells_tmp.end());
std::set<active_cell_iterator> searched_cells;
// Determine the maximal number of cells
// in the grid.
// As long as we have not found
// the cell and have not searched
// every cell in the triangulation,
// we keep on looking.
const unsigned int n_active_cells = get_tria(container).n_active_cells();
bool found = false;
unsigned int cells_searched = 0;
while (!found && cells_searched < n_active_cells)
{
typename std::set<active_cell_iterator>::const_iterator
cell = adjacent_cells.begin(),
endc = adjacent_cells.end();
for (; cell != endc; ++cell)
{
try
{
const Point<dim> p_cell = mapping.transform_real_to_unit_cell(*cell, p);
// calculate the infinity norm of
// the distance vector to the unit cell.
const double dist = GeometryInfo<dim>::distance_to_unit_cell(p_cell);
// We compare if the point is inside the
// unit cell (or at least not too far
// outside). If it is, it is also checked
// that the cell has a more refined state
if ((dist < best_distance)
||
((dist == best_distance)
&&
((*cell)->level() > best_level)))
{
found = true;
best_distance = dist;
best_level = (*cell)->level();
best_cell = std::make_pair(*cell, p_cell);
}
}
catch (typename MappingQ1<dim,spacedim>::ExcTransformationFailed &)
{
// ok, the transformation
// failed presumably
// because the point we
// are looking for lies
// outside the current
// cell. this means that
// the current cell can't
// be the cell around the
// point, so just ignore
// this cell and move on
// to the next
}
}
// update the number of cells searched
cells_searched += adjacent_cells.size();
// if we have not found the cell in
// question and have not yet searched every
// cell, we expand our search to
// all the not already searched neighbors of
// the cells in adjacent_cells. This is
// what find_active_cell_around_point_internal
// is for.
if (!found && cells_searched < n_active_cells)
{
find_active_cell_around_point_internal<dim,Container,spacedim>
(container, searched_cells, adjacent_cells);
}
}
AssertThrow (best_cell.first.state() == IteratorState::valid,
ExcPointNotFound<spacedim>(p));
return best_cell;
}
template <int dim, int spacedim>
std::pair<typename hp::DoFHandler<dim,spacedim>::active_cell_iterator, Point<dim> >
find_active_cell_around_point (const hp::MappingCollection<dim,spacedim> &mapping,
const hp::DoFHandler<dim,spacedim> &container,
const Point<spacedim> &p)
{
Assert ((mapping.size() == 1) ||
(mapping.size() == container.get_fe().size()),
ExcMessage ("Mapping collection needs to have either size 1 "
"or size equal to the number of elements in "
"the FECollection."));
typedef typename hp::DoFHandler<dim,spacedim>::active_cell_iterator cell_iterator;
std::pair<cell_iterator, Point<dim> > best_cell;
//If we have only one element in the MappingCollection,
//we use find_active_cell_around_point using only one
//mapping.
if (mapping.size() == 1)
best_cell = find_active_cell_around_point(mapping[0], container, p);
else
{
// The best distance is set to the
// maximum allowable distance from
// the unit cell; we assume a
// max. deviation of 1e-10
double best_distance = 1e-10;
int best_level = -1;
// Find closest vertex and determine
// all adjacent cells
unsigned int vertex = find_closest_vertex(container, p);
std::vector<cell_iterator> adjacent_cells_tmp =
find_cells_adjacent_to_vertex(container, vertex);
// Make sure that we have found
// at least one cell adjacent to vertex.
Assert(adjacent_cells_tmp.size()>0, ExcInternalError());
// Copy all the cells into a std::set
std::set<cell_iterator> adjacent_cells(adjacent_cells_tmp.begin(), adjacent_cells_tmp.end());
std::set<cell_iterator> searched_cells;
// Determine the maximal number of cells
// in the grid.
// As long as we have not found
// the cell and have not searched
// every cell in the triangulation,
// we keep on looking.
const unsigned int n_cells =get_tria(container).n_cells();
bool found = false;
unsigned int cells_searched = 0;
while (!found && cells_searched < n_cells)
{
typename std::set<cell_iterator>::const_iterator
cell = adjacent_cells.begin(),
endc = adjacent_cells.end();
for (; cell != endc; ++cell)
{
try
{
const Point<dim> p_cell = mapping[(*cell)->active_fe_index()].transform_real_to_unit_cell(*cell, p);
// calculate the infinity norm of
// the distance vector to the unit cell.
const double dist = GeometryInfo<dim>::distance_to_unit_cell(p_cell);
// We compare if the point is inside the
// unit cell (or at least not too far
// outside). If it is, it is also checked
// that the cell has a more refined state
if (dist < best_distance ||
(dist == best_distance && (*cell)->level() > best_level))
{
found = true;
best_distance = dist;
best_level = (*cell)->level();
best_cell = std::make_pair(*cell, p_cell);
}
}
catch (typename MappingQ1<dim,spacedim>::ExcTransformationFailed &)
{
// ok, the transformation
// failed presumably
// because the point we
// are looking for lies
// outside the current
// cell. this means that
// the current cell can't
// be the cell around the
// point, so just ignore
// this cell and move on
// to the next
}
}
//udpate the number of cells searched
cells_searched += adjacent_cells.size();
// if we have not found the cell in
// question and have not yet searched every
// cell, we expand our search to
// all the not already searched neighbors of
// the cells in adjacent_cells.
if (!found && cells_searched < n_cells)
{
find_active_cell_around_point_internal<dim,hp::DoFHandler,spacedim>
(container, searched_cells, adjacent_cells);
}
}
}
AssertThrow (best_cell.first.state() == IteratorState::valid,
ExcPointNotFound<spacedim>(p));
return best_cell;
}
template <int dim, int spacedim>
void
get_face_connectivity_of_cells (const Triangulation<dim,spacedim> &triangulation,
DynamicSparsityPattern &cell_connectivity)
{
cell_connectivity.reinit (triangulation.n_active_cells(),
triangulation.n_active_cells());
// create a map pair<lvl,idx> -> SparsityPattern index
// TODO: we are no longer using user_indices for this because we can get
// pointer/index clashes when saving/restoring them. The following approach
// works, but this map can get quite big. Not sure about more efficient solutions.
std::map< std::pair<unsigned int,unsigned int>, unsigned int >
indexmap;
for (typename dealii::internal::ActiveCellIterator<dim, spacedim, Triangulation<dim, spacedim> >::type
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell)
indexmap[std::pair<unsigned int,unsigned int>(cell->level(),cell->index())] = cell->active_cell_index();
// next loop over all cells and their neighbors to build the sparsity
// pattern. note that it's a bit hard to enter all the connections when a
// neighbor has children since we would need to find out which of its
// children is adjacent to the current cell. this problem can be omitted
// if we only do something if the neighbor has no children -- in that case
// it is either on the same or a coarser level than we are. in return, we
// have to add entries in both directions for both cells
for (typename dealii::internal::ActiveCellIterator<dim, spacedim, Triangulation<dim, spacedim> >::type
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell)
{
const unsigned int index = cell->active_cell_index();
cell_connectivity.add (index, index);
for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)
if ((cell->at_boundary(f) == false)
&&
(cell->neighbor(f)->has_children() == false))
{
unsigned int other_index = indexmap.find(
std::pair<unsigned int,unsigned int>(cell->neighbor(f)->level(),cell->neighbor(f)->index()))->second;
cell_connectivity.add (index, other_index);
cell_connectivity.add (other_index, index);
}
}
}
template <int dim, int spacedim>
void
get_face_connectivity_of_cells (const Triangulation<dim,spacedim> &triangulation,
SparsityPattern &cell_connectivity)
{
DynamicSparsityPattern dsp;
get_face_connectivity_of_cells(triangulation, dsp);
cell_connectivity.copy_from(dsp);
}
template <int dim, int spacedim>
void
get_vertex_connectivity_of_cells (const Triangulation<dim,spacedim> &triangulation,
DynamicSparsityPattern &cell_connectivity)
{
std::vector<std::vector<unsigned int> > vertex_to_cell(triangulation.n_vertices());
for (typename Triangulation<dim,spacedim>::active_cell_iterator cell=
triangulation.begin_active(); cell != triangulation.end(); ++cell)
{
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
vertex_to_cell[cell->vertex_index(v)].push_back(cell->active_cell_index());
}
cell_connectivity.reinit (triangulation.n_active_cells(),
triangulation.n_active_cells());
for (typename Triangulation<dim,spacedim>::active_cell_iterator cell=
triangulation.begin_active(); cell != triangulation.end(); ++cell)
{
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
for (unsigned int n=0; n<vertex_to_cell[cell->vertex_index(v)].size(); ++n)
cell_connectivity.add(cell->active_cell_index(), vertex_to_cell[cell->vertex_index(v)][n]);
}
}
template <int dim, int spacedim>
void
partition_triangulation (const unsigned int n_partitions,
Triangulation<dim,spacedim> &triangulation)
{
Assert ((dynamic_cast<parallel::distributed::Triangulation<dim,spacedim>*>
(&triangulation)
== 0),
ExcMessage ("Objects of type parallel::distributed::Triangulation "
"are already partitioned implicitly and can not be "
"partitioned again explicitly."));
Assert (n_partitions > 0, ExcInvalidNumberOfPartitions(n_partitions));
// check for an easy return
if (n_partitions == 1)
{
for (typename dealii::internal::ActiveCellIterator<dim, spacedim, Triangulation<dim, spacedim> >::type
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell)
cell->set_subdomain_id (0);
return;
}
// we decompose the domain by first
// generating the connection graph of all
// cells with their neighbors, and then
// passing this graph off to METIS.
// finally defer to the other function for
// partitioning and assigning subdomain ids
SparsityPattern cell_connectivity;
get_face_connectivity_of_cells (triangulation, cell_connectivity);
partition_triangulation (n_partitions,
cell_connectivity,
triangulation);
}
template <int dim, int spacedim>
void
partition_triangulation (const unsigned int n_partitions,
const SparsityPattern &cell_connection_graph,
Triangulation<dim,spacedim> &triangulation)
{
Assert ((dynamic_cast<parallel::distributed::Triangulation<dim,spacedim>*>
(&triangulation)
== 0),
ExcMessage ("Objects of type parallel::distributed::Triangulation "
"are already partitioned implicitly and can not be "
"partitioned again explicitly."));
Assert (n_partitions > 0, ExcInvalidNumberOfPartitions(n_partitions));
Assert (cell_connection_graph.n_rows() == triangulation.n_active_cells(),
ExcMessage ("Connectivity graph has wrong size"));
Assert (cell_connection_graph.n_cols() == triangulation.n_active_cells(),
ExcMessage ("Connectivity graph has wrong size"));
// check for an easy return
if (n_partitions == 1)
{
for (typename dealii::internal::ActiveCellIterator<dim, spacedim, Triangulation<dim, spacedim> >::type
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell)
cell->set_subdomain_id (0);
return;
}
// partition this connection graph and get
// back a vector of indices, one per degree
// of freedom (which is associated with a
// cell)
std::vector<unsigned int> partition_indices (triangulation.n_active_cells());
SparsityTools::partition (cell_connection_graph, n_partitions, partition_indices);
// finally loop over all cells and set the
// subdomain ids
for (typename dealii::internal::ActiveCellIterator<dim, spacedim, Triangulation<dim, spacedim> >::type
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell)
cell->set_subdomain_id (partition_indices[cell->active_cell_index()]);
}
template <int dim, int spacedim>
void
get_subdomain_association (const Triangulation<dim, spacedim> &triangulation,
std::vector<types::subdomain_id> &subdomain)
{
Assert (subdomain.size() == triangulation.n_active_cells(),
ExcDimensionMismatch (subdomain.size(),
triangulation.n_active_cells()));
for (typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active(); cell!=triangulation.end(); ++cell)
subdomain[cell->active_cell_index()] = cell->subdomain_id();
}
template <int dim, int spacedim>
unsigned int
count_cells_with_subdomain_association (const Triangulation<dim, spacedim> &triangulation,
const types::subdomain_id subdomain)
{
unsigned int count = 0;
for (typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active();
cell!=triangulation.end(); ++cell)
if (cell->subdomain_id() == subdomain)
++count;
return count;
}
template <int dim, int spacedim>
std::vector<bool>
get_locally_owned_vertices (const Triangulation<dim,spacedim> &triangulation)
{
// start with all vertices
std::vector<bool> locally_owned_vertices = triangulation.get_used_vertices();
// if the triangulation is distributed, eliminate those that
// are owned by other processors -- either because the vertex is
// on an artificial cell, or because it is on a ghost cell with
// a smaller subdomain
if (const parallel::distributed::Triangulation<dim,spacedim> *tr
= dynamic_cast<const parallel::distributed::Triangulation<dim,spacedim> *>
(&triangulation))
for (typename dealii::internal::ActiveCellIterator<dim, spacedim, Triangulation<dim, spacedim> >::type
cell = triangulation.begin_active();
cell != triangulation.end(); ++cell)
if (cell->is_artificial()
||
(cell->is_ghost() &&
(cell->subdomain_id() < tr->locally_owned_subdomain())))
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
locally_owned_vertices[cell->vertex_index(v)] = false;
return locally_owned_vertices;
}
template <typename Container>
std::list<std::pair<typename Container::cell_iterator,
typename Container::cell_iterator> >
get_finest_common_cells (const Container &mesh_1,
const Container &mesh_2)
{
Assert (have_same_coarse_mesh (mesh_1, mesh_2),
ExcMessage ("The two containers must be represent triangulations that "
"have the same coarse meshes"));
// the algorithm goes as follows:
// first, we fill a list with pairs
// of iterators common to the two
// meshes on the coarsest
// level. then we traverse the
// list; each time, we find a pair
// of iterators for which both
// correspond to non-active cells,
// we delete this item and push the
// pairs of iterators to their
// children to the back. if these
// again both correspond to
// non-active cells, we will get to
// the later on for further
// consideration
typedef
std::list<std::pair<typename Container::cell_iterator,
typename Container::cell_iterator> >
CellList;
CellList cell_list;
// first push the coarse level cells
typename Container::cell_iterator
cell_1 = mesh_1.begin(0),
cell_2 = mesh_2.begin(0);
for (; cell_1 != mesh_1.end(0); ++cell_1, ++cell_2)
cell_list.push_back (std::make_pair (cell_1, cell_2));
// then traverse list as described
// above
typename CellList::iterator cell_pair = cell_list.begin();
while (cell_pair != cell_list.end())
{
// if both cells in this pair
// have children, then erase
// this element and push their
// children instead
if (cell_pair->first->has_children()
&&
cell_pair->second->has_children())
{
Assert(cell_pair->first->refinement_case()==
cell_pair->second->refinement_case(), ExcNotImplemented());
for (unsigned int c=0; c<cell_pair->first->n_children(); ++c)
cell_list.push_back (std::make_pair (cell_pair->first->child(c),
cell_pair->second->child(c)));
// erasing an iterator
// keeps other iterators
// valid, so already
// advance the present
// iterator by one and then
// delete the element we've
// visited before
const typename CellList::iterator previous_cell_pair = cell_pair;
++cell_pair;
cell_list.erase (previous_cell_pair);
}
else
// both cells are active, do
// nothing
++cell_pair;
}
// just to make sure everything is ok,
// validate that all pairs have at least one
// active iterator or have different
// refinement_cases
for (cell_pair = cell_list.begin(); cell_pair != cell_list.end(); ++cell_pair)
Assert (cell_pair->first->active()
||
cell_pair->second->active()
||
(cell_pair->first->refinement_case()
!= cell_pair->second->refinement_case()),
ExcInternalError());
return cell_list;
}
template <int dim, int spacedim>
bool
have_same_coarse_mesh (const Triangulation<dim, spacedim> &mesh_1,
const Triangulation<dim, spacedim> &mesh_2)
{
// make sure the two meshes have
// the same number of coarse cells
if (mesh_1.n_cells (0) != mesh_2.n_cells (0))
return false;
// if so, also make sure they have
// the same vertices on the cells
// of the coarse mesh
typename Triangulation<dim, spacedim>::cell_iterator
cell_1 = mesh_1.begin(0),
cell_2 = mesh_2.begin(0),
endc = mesh_1.end(0);
for (; cell_1!=endc; ++cell_1, ++cell_2)
for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)
if (cell_1->vertex(v) != cell_2->vertex(v))
return false;
// if we've gotten through all
// this, then the meshes really
// seem to have a common coarse
// mesh
return true;
}
template <typename Container>
bool
have_same_coarse_mesh (const Container &mesh_1,
const Container &mesh_2)
{
return have_same_coarse_mesh (get_tria(mesh_1),
get_tria(mesh_2));
}
template <int dim, int spacedim>
double
minimal_cell_diameter (const Triangulation<dim, spacedim> &triangulation)
{
double min_diameter = triangulation.begin_active()->diameter();
for (typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active(); cell != triangulation.end();
++cell)
min_diameter = std::min (min_diameter,
cell->diameter());
return min_diameter;
}
template <int dim, int spacedim>
double
maximal_cell_diameter (const Triangulation<dim, spacedim> &triangulation)
{
double max_diameter = triangulation.begin_active()->diameter();
for (typename Triangulation<dim, spacedim>::active_cell_iterator
cell = triangulation.begin_active(); cell != triangulation.end();
++cell)
max_diameter = std::max (max_diameter,
cell->diameter());
return max_diameter;
}
namespace internal
{
namespace FixUpDistortedChildCells
{
// compute the mean square
// deviation of the alternating
// forms of the children of the
// given object from that of
// the object itself. for
// objects with
// structdim==spacedim, the
// alternating form is the
// determinant of the jacobian,
// whereas for faces with
// structdim==spacedim-1, the
// alternating form is the
// (signed and scaled) normal
// vector
//
// this average square
// deviation is computed for an
// object where the center node
// has been replaced by the
// second argument to this
// function
template <typename Iterator, int spacedim>
double
objective_function (const Iterator &object,
const Point<spacedim> &object_mid_point)
{
const unsigned int structdim = Iterator::AccessorType::structure_dimension;
Assert (spacedim == Iterator::AccessorType::dimension,
ExcInternalError());
// everything below is wrong
// if not for the following
// condition
Assert (object->refinement_case() == RefinementCase<structdim>::isotropic_refinement,
ExcNotImplemented());
// first calculate the
// average alternating form
// for the parent cell/face
Point<spacedim> parent_vertices
[GeometryInfo<structdim>::vertices_per_cell];
Tensor<spacedim-structdim,spacedim> parent_alternating_forms
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
parent_vertices[i] = object->vertex(i);
GeometryInfo<structdim>::alternating_form_at_vertices (parent_vertices,
parent_alternating_forms);
const Tensor<spacedim-structdim,spacedim>
average_parent_alternating_form
= std::accumulate (&parent_alternating_forms[0],
&parent_alternating_forms[GeometryInfo<structdim>::vertices_per_cell],
Tensor<spacedim-structdim,spacedim>());
// now do the same
// computation for the
// children where we use the
// given location for the
// object mid point instead of
// the one the triangulation
// currently reports
Point<spacedim> child_vertices
[GeometryInfo<structdim>::max_children_per_cell]
[GeometryInfo<structdim>::vertices_per_cell];
Tensor<spacedim-structdim,spacedim> child_alternating_forms
[GeometryInfo<structdim>::max_children_per_cell]
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
child_vertices[c][i] = object->child(c)->vertex(i);
// replace mid-object
// vertex. note that for
// child i, the mid-object
// vertex happens to have the
// number
// max_children_per_cell-i
for (unsigned int c=0; c<object->n_children(); ++c)
child_vertices[c][GeometryInfo<structdim>::max_children_per_cell-c-1]
= object_mid_point;
for (unsigned int c=0; c<object->n_children(); ++c)
GeometryInfo<structdim>::alternating_form_at_vertices (child_vertices[c],
child_alternating_forms[c]);
// on a uniformly refined
// hypercube object, the child
// alternating forms should
// all be smaller by a factor
// of 2^structdim than the
// ones of the parent. as a
// consequence, we'll use the
// squared deviation from
// this ideal value as an
// objective function
double objective = 0;
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
objective += (child_alternating_forms[c][i] -
average_parent_alternating_form/std::pow(2.,1.*structdim))
.norm_square();
return objective;
}
/**
* Return the location of the midpoint
* of the 'f'th face (vertex) of this 1d
* object.
*/
template <typename Iterator>
Point<Iterator::AccessorType::space_dimension>
get_face_midpoint (const Iterator &object,
const unsigned int f,
dealii::internal::int2type<1>)
{
return object->vertex(f);
}
/**
* Return the location of the midpoint
* of the 'f'th face (line) of this 2d
* object.
*/
template <typename Iterator>
Point<Iterator::AccessorType::space_dimension>
get_face_midpoint (const Iterator &object,
const unsigned int f,
dealii::internal::int2type<2>)
{
return object->line(f)->center();
}
/**
* Return the location of the midpoint
* of the 'f'th face (quad) of this 3d
* object.
*/
template <typename Iterator>
Point<Iterator::AccessorType::space_dimension>
get_face_midpoint (const Iterator &object,
const unsigned int f,
dealii::internal::int2type<3>)
{
return object->face(f)->center();
}
/**
* Compute the minimal diameter of an
* object by looking for the minimal
* distance between the mid-points of
* its faces. This minimal diameter is
* used to determine the step length
* for our grid cell improvement
* algorithm, and it should be small
* enough that the point moves around
* within the cell even if it is highly
* elongated -- thus, the diameter of
* the object is not a good measure,
* while the minimal diameter is. Note
* that the algorithm below works for
* both cells that are long rectangles
* with parallel sides where the
* nearest distance is between opposite
* edges as well as highly slanted
* parallelograms where the shortest
* distance is between neighboring
* edges.
*/
template <typename Iterator>
double
minimal_diameter (const Iterator &object)
{
const unsigned int
structdim = Iterator::AccessorType::structure_dimension;
double diameter = object->diameter();
for (unsigned int f=0;
f<GeometryInfo<structdim>::faces_per_cell;
++f)
for (unsigned int e=f+1;
e<GeometryInfo<structdim>::faces_per_cell;
++e)
diameter = std::min (diameter,
get_face_midpoint
(object, f,
dealii::internal::int2type<structdim>())
.distance (get_face_midpoint
(object,
e,
dealii::internal::int2type<structdim>())));
return diameter;
}
/**
* Try to fix up a single cell. Return
* whether we succeeded with this.
*
* The second argument indicates
* whether we need to respect the
* manifold/boundary on which this
* object lies when moving around its
* mid-point.
*/
template <typename Iterator>
bool
fix_up_object (const Iterator &object,
const bool respect_manifold)
{
const Boundary<Iterator::AccessorType::dimension,
Iterator::AccessorType::space_dimension>
*manifold = (respect_manifold ?
&object->get_boundary() :
0);
const unsigned int structdim = Iterator::AccessorType::structure_dimension;
const unsigned int spacedim = Iterator::AccessorType::space_dimension;
// right now we can only deal
// with cells that have been
// refined isotropically
// because that is the only
// case where we have a cell
// mid-point that can be moved
// around without having to
// consider boundary
// information
Assert (object->has_children(), ExcInternalError());
Assert (object->refinement_case() == RefinementCase<structdim>::isotropic_refinement,
ExcNotImplemented());
// get the current location of
// the object mid-vertex:
Point<spacedim> object_mid_point
= object->child(0)->vertex (GeometryInfo<structdim>::max_children_per_cell-1);
// now do a few steepest descent
// steps to reduce the objective
// function. compute the diameter in
// the helper function above
unsigned int iteration = 0;
const double diameter = minimal_diameter (object);
// current value of objective
// function and initial delta
double current_value = objective_function (object, object_mid_point);
double initial_delta = 0;
do
{
// choose a step length
// that is initially 1/4
// of the child objects'
// diameter, and a sequence
// whose sum does not
// converge (to avoid
// premature termination of
// the iteration)
const double step_length = diameter / 4 / (iteration + 1);
// compute the objective
// function's derivative using a
// two-sided difference formula
// with eps=step_length/10
Tensor<1,spacedim> gradient;
for (unsigned int d=0; d<spacedim; ++d)
{
const double eps = step_length/10;
Tensor<1,spacedim> h;
h[d] = eps/2;
if (respect_manifold == false)
gradient[d]
= ((objective_function (object, object_mid_point + h)
-
objective_function (object, object_mid_point - h))
/
eps);
else
gradient[d]
= ((objective_function (object,
manifold->project_to_surface(object,
object_mid_point + h))
-
objective_function (object,
manifold->project_to_surface(object,
object_mid_point - h)))
/
eps);
}
// sometimes, the
// (unprojected) gradient
// is perpendicular to
// the manifold, but we
// can't go there if
// respect_manifold==true. in
// that case, gradient=0,
// and we simply need to
// quite the loop here
if (gradient.norm() == 0)
break;
// so we need to go in
// direction -gradient. the
// optimal value of the
// objective function is
// zero, so assuming that
// the model is quadratic
// we would have to go
// -2*val/||gradient|| in
// this direction, make
// sure we go at most
// step_length into this
// direction
object_mid_point -= std::min(2 * current_value / (gradient*gradient),
step_length / gradient.norm()) *
gradient;
if (respect_manifold == true)
object_mid_point = manifold->project_to_surface(object,
object_mid_point);
// compute current value of the
// objective function
const double previous_value = current_value;
current_value = objective_function (object, object_mid_point);
if (iteration == 0)
initial_delta = (previous_value - current_value);
// stop if we aren't moving much
// any more
if ((iteration >= 1) &&
((previous_value - current_value < 0)
||
(std::fabs (previous_value - current_value)
<
0.001 * initial_delta)))
break;
++iteration;
}
while (iteration < 20);
// verify that the new
// location is indeed better
// than the one before. check
// this by comparing whether
// the minimum value of the
// products of parent and
// child alternating forms is
// positive. for cells this
// means that the
// determinants have the same
// sign, for faces that the
// face normals of parent and
// children point in the same
// general direction
double old_min_product, new_min_product;
Point<spacedim> parent_vertices
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
parent_vertices[i] = object->vertex(i);
Tensor<spacedim-structdim,spacedim> parent_alternating_forms
[GeometryInfo<structdim>::vertices_per_cell];
GeometryInfo<structdim>::alternating_form_at_vertices (parent_vertices,
parent_alternating_forms);
Point<spacedim> child_vertices
[GeometryInfo<structdim>::max_children_per_cell]
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
child_vertices[c][i] = object->child(c)->vertex(i);
Tensor<spacedim-structdim,spacedim> child_alternating_forms
[GeometryInfo<structdim>::max_children_per_cell]
[GeometryInfo<structdim>::vertices_per_cell];
for (unsigned int c=0; c<object->n_children(); ++c)
GeometryInfo<structdim>::alternating_form_at_vertices (child_vertices[c],
child_alternating_forms[c]);
old_min_product = child_alternating_forms[0][0] * parent_alternating_forms[0];
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
for (unsigned int j=0; j<GeometryInfo<structdim>::vertices_per_cell; ++j)
old_min_product = std::min (old_min_product,
child_alternating_forms[c][i] *
parent_alternating_forms[j]);
// for the new minimum value,
// replace mid-object
// vertex. note that for child
// i, the mid-object vertex
// happens to have the number
// max_children_per_cell-i
for (unsigned int c=0; c<object->n_children(); ++c)
child_vertices[c][GeometryInfo<structdim>::max_children_per_cell-c-1]
= object_mid_point;
for (unsigned int c=0; c<object->n_children(); ++c)
GeometryInfo<structdim>::alternating_form_at_vertices (child_vertices[c],
child_alternating_forms[c]);
new_min_product = child_alternating_forms[0][0] * parent_alternating_forms[0];
for (unsigned int c=0; c<object->n_children(); ++c)
for (unsigned int i=0; i<GeometryInfo<structdim>::vertices_per_cell; ++i)
for (unsigned int j=0; j<GeometryInfo<structdim>::vertices_per_cell; ++j)
new_min_product = std::min (new_min_product,
child_alternating_forms[c][i] *
parent_alternating_forms[j]);
// if new minimum value is
// better than before, then set the
// new mid point. otherwise
// return this object as one of
// those that can't apparently
// be fixed
if (new_min_product >= old_min_product)
object->child(0)->vertex (GeometryInfo<structdim>::max_children_per_cell-1)
= object_mid_point;
// return whether after this
// operation we have an object that
// is well oriented
return (std::max (new_min_product, old_min_product) > 0);
}
void fix_up_faces (const dealii::Triangulation<1,1>::cell_iterator &,
dealii::internal::int2type<1>,
dealii::internal::int2type<1>)
{
// nothing to do for the faces of
// cells in 1d
}
// possibly fix up the faces of
// a cell by moving around its
// mid-points
template <int structdim, int spacedim>
void fix_up_faces (const typename dealii::Triangulation<structdim,spacedim>::cell_iterator &cell,
dealii::internal::int2type<structdim>,
dealii::internal::int2type<spacedim>)
{
// see if we first can fix up
// some of the faces of this
// object. we can mess with
// faces if and only if it is
// not at the boundary (since
// otherwise the location of
// the face mid-point has been
// determined by the boundary
// object) and if the
// neighboring cell is not even
// more refined than we are
// (since in that case the
// sub-faces have themselves
// children that we can't move
// around any more). however,
// the latter case shouldn't
// happen anyway: if the
// current face is distorted
// but the neighbor is even
// more refined, then the face
// had been deformed before
// already, and had been
// ignored at the time; we
// should then also be able to
// ignore it this time as well
for (unsigned int f=0; f<GeometryInfo<structdim>::faces_per_cell; ++f)
{
Assert (cell->face(f)->has_children(), ExcInternalError());
Assert (cell->face(f)->refinement_case() ==
RefinementCase<structdim-1>::isotropic_refinement,
ExcInternalError());
bool subface_is_more_refined = false;
for (unsigned int g=0; g<GeometryInfo<structdim>::max_children_per_face; ++g)
if (cell->face(f)->child(g)->has_children())
{
subface_is_more_refined = true;
break;
}
if (subface_is_more_refined == true)
continue;
// so, now we finally know
// that we can do something
// about this face
fix_up_object (cell->face(f), cell->at_boundary(f));
}
}
} /* namespace FixUpDistortedChildCells */
} /* namespace internal */
template <int dim, int spacedim>
typename Triangulation<dim,spacedim>::DistortedCellList
fix_up_distorted_child_cells (const typename Triangulation<dim,spacedim>::DistortedCellList &distorted_cells,
Triangulation<dim,spacedim> &/*triangulation*/)
{
typename Triangulation<dim,spacedim>::DistortedCellList unfixable_subset;
// loop over all cells that we have
// to fix up
for (typename std::list<typename Triangulation<dim,spacedim>::cell_iterator>::const_iterator
cell_ptr = distorted_cells.distorted_cells.begin();
cell_ptr != distorted_cells.distorted_cells.end(); ++cell_ptr)
{
const typename Triangulation<dim,spacedim>::cell_iterator
cell = *cell_ptr;
internal::FixUpDistortedChildCells
::fix_up_faces (cell,
dealii::internal::int2type<dim>(),
dealii::internal::int2type<spacedim>());
// fix up the object. we need to
// respect the manifold if the cell is
// embedded in a higher dimensional
// space; otherwise, like a hex in 3d,
// every point within the cell interior
// is fair game
if (! internal::FixUpDistortedChildCells::fix_up_object (cell,
(dim < spacedim)))
unfixable_subset.distorted_cells.push_back (cell);
}
return unfixable_subset;
}
template <class Container>
std::vector<typename Container::active_cell_iterator>
get_patch_around_cell(const typename Container::active_cell_iterator &cell)
{
Assert (cell->is_locally_owned(),
ExcMessage ("This function only makes sense if the cell for "
"which you are asking for a patch, is locally "
"owned."));
std::vector<typename Container::active_cell_iterator> patch;
patch.push_back (cell);
for (unsigned int face_number=0; face_number<GeometryInfo<Container::dimension>::faces_per_cell; ++face_number)
if (cell->face(face_number)->at_boundary()==false)
{
if (cell->neighbor(face_number)->has_children() == false)
patch.push_back (cell->neighbor(face_number));
else
// the neighbor is refined. in 2d/3d, we can simply ask for the children
// of the neighbor because they can not be further refined and,
// consequently, the children is active
if (Container::dimension > 1)
{
for (unsigned int subface=0; subface<cell->face(face_number)->n_children(); ++subface)
patch.push_back (cell->neighbor_child_on_subface (face_number, subface));
}
else
{
// in 1d, we need to work a bit harder: iterate until we find
// the child by going from cell to child to child etc
typename Container::cell_iterator neighbor
= cell->neighbor (face_number);
while (neighbor->has_children())
neighbor = neighbor->child(1-face_number);
Assert (neighbor->neighbor(1-face_number) == cell, ExcInternalError());
patch.push_back (neighbor);
}
}
return patch;
}
/*
* Internally used in orthogonal_equality
*
* An orthogonal equality test for points:
*
* point1 and point2 are considered equal, if
* matrix.(point1 + offset) - point2
* is parallel to the unit vector in <direction>
*/
template<int spacedim>
inline bool orthogonal_equality (const Point<spacedim> &point1,
const Point<spacedim> &point2,
const int direction,
const Tensor<1,spacedim> &offset,
const FullMatrix<double> &matrix)
{
Assert (0<=direction && direction<spacedim,
ExcIndexRange (direction, 0, spacedim));
Assert(matrix.m() == matrix.n(), ExcInternalError());
Point<spacedim> distance;
if (matrix.m() == spacedim)
for (int i = 0; i < spacedim; ++i)
for (int j = 0; j < spacedim; ++j)
distance(i) = matrix(i,j) * point1(j);
else
distance = point1;
distance += offset - point2;
for (int i = 0; i < spacedim; ++i)
{
// Only compare coordinate-components != direction:
if (i == direction)
continue;
if (fabs(distance(i)) > 1.e-10)
return false;
}
return true;
}
/*
* Internally used in orthogonal_equality
*
* A lookup table to transform vertex matchings to orientation flags of
* the form (face_orientation, face_flip, face_rotation)
*
* See the comment on the next function as well as the detailed
* documentation of make_periodicity_constraints and
* collect_periodic_faces for details
*/
template<int dim> struct OrientationLookupTable {};
template<> struct OrientationLookupTable<1>
{
typedef std_cxx11::array<unsigned int, GeometryInfo<1>::vertices_per_face> MATCH_T;
static inline std::bitset<3> lookup (const MATCH_T &)
{
// The 1D case is trivial
return 4; // [true ,false,false]
}
};
template<> struct OrientationLookupTable<2>
{
typedef std_cxx11::array<unsigned int, GeometryInfo<2>::vertices_per_face> MATCH_T;
static inline std::bitset<3> lookup (const MATCH_T &matching)
{
// In 2D matching faces (=lines) results in two cases: Either
// they are aligned or flipped. We store this "line_flip"
// property somewhat sloppy as "face_flip"
// (always: face_orientation = true, face_rotation = false)
static const MATCH_T m_tff = {{ 0 , 1 }};
if (matching == m_tff) return 1; // [true ,false,false]
static const MATCH_T m_ttf = {{ 1 , 0 }};
if (matching == m_ttf) return 3; // [true ,true ,false]
AssertThrow(false, ExcInternalError());
// what follows is dead code, but it avoids warnings about the lack
// of a return value
return 0;
}
};
template<> struct OrientationLookupTable<3>
{
typedef std_cxx11::array<unsigned int, GeometryInfo<3>::vertices_per_face> MATCH_T;
static inline std::bitset<3> lookup (const MATCH_T &matching)
{
// The full fledged 3D case. *Yay*
// See the documentation in include/deal.II/base/geometry_info.h
// as well as the actual implementation in source/grid/tria.cc
// for more details...
static const MATCH_T m_tff = {{ 0 , 1 , 2 , 3 }};
if (matching == m_tff) return 1; // [true ,false,false]
static const MATCH_T m_tft = {{ 1 , 3 , 0 , 2 }};
if (matching == m_tft) return 5; // [true ,false,true ]
static const MATCH_T m_ttf = {{ 3 , 2 , 1 , 0 }};
if (matching == m_ttf) return 3; // [true ,true ,false]
static const MATCH_T m_ttt = {{ 2 , 0 , 3 , 1 }};
if (matching == m_ttt) return 7; // [true ,true ,true ]
static const MATCH_T m_fff = {{ 0 , 2 , 1 , 3 }};
if (matching == m_fff) return 0; // [false,false,false]
static const MATCH_T m_fft = {{ 2 , 3 , 0 , 1 }};
if (matching == m_fft) return 4; // [false,false,true ]
static const MATCH_T m_ftf = {{ 3 , 1 , 2 , 0 }};
if (matching == m_ftf) return 2; // [false,true ,false]
static const MATCH_T m_ftt = {{ 1 , 0 , 3 , 2 }};
if (matching == m_ftt) return 6; // [false,true ,true ]
AssertThrow(false, ExcInternalError());
// what follows is dead code, but it avoids warnings about the lack
// of a return value
return 0;
}
};
template<typename FaceIterator>
inline bool
orthogonal_equality (std::bitset<3> &orientation,
const FaceIterator &face1,
const FaceIterator &face2,
const int direction,
const Tensor<1,FaceIterator::AccessorType::space_dimension> &offset,
const FullMatrix<double> &matrix)
{
Assert(matrix.m() == matrix.n(),
ExcMessage("The supplied matrix must be a square matrix"));
static const int dim = FaceIterator::AccessorType::dimension;
// Do a full matching of the face vertices:
std_cxx11::
array<unsigned int, GeometryInfo<dim>::vertices_per_face> matching;
std::set<unsigned int> face2_vertices;
for (unsigned int i = 0; i < GeometryInfo<dim>::vertices_per_face; ++i)
face2_vertices.insert(i);
for (unsigned int i = 0; i < GeometryInfo<dim>::vertices_per_face; ++i)
{
for (std::set<unsigned int>::iterator it = face2_vertices.begin();
it != face2_vertices.end();
it++)
{
if (orthogonal_equality(face1->vertex(i),face2->vertex(*it),
direction, offset, matrix))
{
matching[i] = *it;
face2_vertices.erase(it);
break; // jump out of the innermost loop
}
}
}
// And finally, a lookup to determine the ordering bitmask:
if (face2_vertices.empty())
orientation = OrientationLookupTable<dim>::lookup(matching);
return face2_vertices.empty();
}
template<typename FaceIterator>
inline bool
orthogonal_equality (const FaceIterator &face1,
const FaceIterator &face2,
const int direction,
const Tensor<1,FaceIterator::AccessorType::space_dimension> &offset,
const FullMatrix<double> &matrix)
{
// Call the function above with a dummy orientation array
std::bitset<3> dummy;
return orthogonal_equality (dummy, face1, face2, direction, offset, matrix);
}
/*
* Internally used in collect_periodic_faces
*/
template<typename CellIterator>
void
match_periodic_face_pairs
(std::set<std::pair<CellIterator, unsigned int> > &pairs1,
std::set<std::pair<typename identity<CellIterator>::type, unsigned int> > &pairs2,
const int direction,
std::vector<PeriodicFacePair<CellIterator> > &matched_pairs,
const dealii::Tensor<1,CellIterator::AccessorType::space_dimension> &offset,
const FullMatrix<double> &matrix,
const std::vector<unsigned int> &first_vector_components)
{
static const int space_dim = CellIterator::AccessorType::space_dimension;
(void)space_dim;
Assert (0<=direction && direction<space_dim,
ExcIndexRange (direction, 0, space_dim));
Assert (pairs1.size() == pairs2.size(),
ExcMessage ("Unmatched faces on periodic boundaries"));
unsigned int n_matches = 0;
// Match with a complexity of O(n^2). This could be improved...
std::bitset<3> orientation;
typedef typename std::set
<std::pair<CellIterator, unsigned int> >::const_iterator PairIterator;
for (PairIterator it1 = pairs1.begin(); it1 != pairs1.end(); ++it1)
{
for (PairIterator it2 = pairs2.begin(); it2 != pairs2.end(); ++it2)
{
const CellIterator cell1 = it1->first;
const CellIterator cell2 = it2->first;
const unsigned int face_idx1 = it1->second;
const unsigned int face_idx2 = it2->second;
if (GridTools::orthogonal_equality(orientation,
cell1->face(face_idx1),
cell2->face(face_idx2),
direction, offset,
matrix))
{
// We have a match, so insert the matching pairs and
// remove the matched cell in pairs2 to speed up the
// matching:
const PeriodicFacePair<CellIterator> matched_face =
{
{cell1, cell2},
{face_idx1, face_idx2},
orientation,
matrix,
first_vector_components
};
matched_pairs.push_back(matched_face);
pairs2.erase(it2);
++n_matches;
break;
}
}
}
//Assure that all faces are matched
AssertThrow (n_matches == pairs1.size() && pairs2.size() == 0,
ExcMessage ("Unmatched faces on periodic boundaries"));
}
template<typename CONTAINER>
void
collect_periodic_faces
(const CONTAINER &container,
const types::boundary_id b_id1,
const types::boundary_id b_id2,
const int direction,
std::vector<PeriodicFacePair<typename CONTAINER::cell_iterator> > &matched_pairs,
const Tensor<1,CONTAINER::space_dimension> &offset,
const FullMatrix<double> &matrix,
const std::vector<unsigned int> &first_vector_components)
{
static const int dim = CONTAINER::dimension;
static const int space_dim = CONTAINER::space_dimension;
(void)dim;
(void)space_dim;
Assert (0<=direction && direction<space_dim,
ExcIndexRange (direction, 0, space_dim));
// Loop over all cells on the highest level and collect all boundary
// faces belonging to b_id1 and b_id2:
std::set<std::pair<typename CONTAINER::cell_iterator, unsigned int> > pairs1;
std::set<std::pair<typename CONTAINER::cell_iterator, unsigned int> > pairs2;
for (typename CONTAINER::cell_iterator cell = container.begin(0);
cell != container.end(0); ++cell)
{
for (unsigned int i = 0; i < GeometryInfo<dim>::faces_per_cell; ++i)
{
const typename CONTAINER::face_iterator face = cell->face(i);
if (face->at_boundary() && face->boundary_id() == b_id1)
{
const std::pair<typename CONTAINER::cell_iterator, unsigned int> pair1
= std::make_pair(cell, i);
pairs1.insert(pair1);
}
if (face->at_boundary() && face->boundary_id() == b_id2)
{
const std::pair<typename CONTAINER::cell_iterator, unsigned int> pair2
= std::make_pair(cell, i);
pairs2.insert(pair2);
}
}
}
Assert (pairs1.size() == pairs2.size(),
ExcMessage ("Unmatched faces on periodic boundaries"));
// and call match_periodic_face_pairs that does the actual matching:
match_periodic_face_pairs(pairs1, pairs2, direction, matched_pairs,
offset, matrix, first_vector_components);
}
template<typename CONTAINER>
void
collect_periodic_faces
(const CONTAINER &container,
const types::boundary_id b_id,
const int direction,
std::vector<PeriodicFacePair<typename CONTAINER::cell_iterator> > &matched_pairs,
const Tensor<1,CONTAINER::space_dimension> &offset,
const FullMatrix<double> &matrix,
const std::vector<unsigned int> &first_vector_components)
{
static const int dim = CONTAINER::dimension;
static const int space_dim = CONTAINER::space_dimension;
(void)dim;
(void)space_dim;
Assert (0<=direction && direction<space_dim,
ExcIndexRange (direction, 0, space_dim));
Assert(dim == space_dim,
ExcNotImplemented());
// Loop over all cells on the highest level and collect all boundary
// faces 2*direction and 2*direction*1:
std::set<std::pair<typename CONTAINER::cell_iterator, unsigned int> > pairs1;
std::set<std::pair<typename CONTAINER::cell_iterator, unsigned int> > pairs2;
for (typename CONTAINER::cell_iterator cell = container.begin(0);
cell != container.end(0); ++cell)
{
const typename CONTAINER::face_iterator face_1 = cell->face(2*direction);
const typename CONTAINER::face_iterator face_2 = cell->face(2*direction+1);
if (face_1->at_boundary() && face_1->boundary_id() == b_id)
{
const std::pair<typename CONTAINER::cell_iterator, unsigned int> pair1
= std::make_pair(cell, 2*direction);
pairs1.insert(pair1);
}
if (face_2->at_boundary() && face_2->boundary_id() == b_id)
{
const std::pair<typename CONTAINER::cell_iterator, unsigned int> pair2
= std::make_pair(cell, 2*direction+1);
pairs2.insert(pair2);
}
}
Assert (pairs1.size() == pairs2.size(),
ExcMessage ("Unmatched faces on periodic boundaries"));
#ifdef DEBUG
const unsigned int size_old = matched_pairs.size();
#endif
// and call match_periodic_face_pairs that does the actual matching:
match_periodic_face_pairs(pairs1, pairs2, direction, matched_pairs,
offset, matrix, first_vector_components);
#ifdef DEBUG
//check for standard orientation
const unsigned int size_new = matched_pairs.size();
for (unsigned int i = size_old; i < size_new; ++i)
{
Assert(matched_pairs[i].orientation == 1,
ExcMessage("Found a face match with non standard orientation. "
"This function is only suitable for meshes with cells "
"in default orientation"));
}
#endif
}
template <int dim, int spacedim>
void copy_boundary_to_manifold_id(Triangulation<dim, spacedim> &tria,
const bool reset_boundary_ids)
{
typename Triangulation<dim,spacedim>::active_cell_iterator
cell=tria.begin_active(), endc=tria.end();
for (; cell != endc; ++cell)
for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)
if (cell->face(f)->at_boundary())
{
cell->face(f)->set_manifold_id
(static_cast<types::manifold_id>(cell->face(f)->boundary_id()));
if (reset_boundary_ids == true)
cell->face(f)->set_boundary_id(0);
}
}
template <int dim, int spacedim>
void copy_material_to_manifold_id(Triangulation<dim, spacedim> &tria,
const bool compute_face_ids)
{
typename Triangulation<dim,spacedim>::active_cell_iterator
cell=tria.begin_active(), endc=tria.end();
for (; cell != endc; ++cell)
{
cell->set_manifold_id(cell->material_id());
if (compute_face_ids == true)
{
for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)
{
if (cell->neighbor(f) != endc)
cell->face(f)->set_manifold_id
(std::min(cell->material_id(),
cell->neighbor(f)->material_id()));
else
cell->face(f)->set_manifold_id(cell->material_id());
}
}
}
}
} /* namespace GridTools */
// explicit instantiations
#include "grid_tools.inst"
DEAL_II_NAMESPACE_CLOSE
|
#include "./MainWindow.h"
#include "../Search.h"
#include "../Processer.h"
#include <iostream>
#include <gdkmm/rgba.h>
#include <gtk/gtk.h>
#include "SettingsWindow.h"
#include <gdkmm/pixbuf.h>
#include <gtkmm/icontheme.h>
using namespace std;
MainWindow::MainWindow(Logic& logic)
: mLogic(logic)
{
//Load settings
mIgnoreClipboardChange = !mLogic.mTranslateClipboardAtStart;
// Sets the border width of the window.
this->set_border_width(10);
this->set_default_size(mLogic.mSizeX, mLogic.mSizeY);
this->move(mLogic.mPositionX, mLogic.mPositionY);
this->set_keep_above(mLogic.mAlwaysOnTop);
this->set_title("Dictionary");
//Icons
Glib::RefPtr<Gdk::Pixbuf> imagePlus
= Gdk::Pixbuf::create_from_file("./share/icons/ic_add_black_24dp_1x.png");
imagePlus->get_height();
Gtk::IconTheme::add_builtin_icon("custom_icon_add", 4, imagePlus);
Glib::RefPtr<Gdk::Pixbuf> imageSettings
= Gdk::Pixbuf::create_from_file("./share/icons/ic_settings_black_24dp_1x.png");
imageSettings->get_height();
Gtk::IconTheme::add_builtin_icon("custom_icon_settings", 4, imageSettings);
//--------------------------------------------------------------------------
// settings button clicked shows settings window
mSettingsButton.set_image_from_icon_name("custom_icon_settings");
mSettingsButton.signal_clicked().connect([this](){
if(mSettingsWindow)
return;
mSettingsWindow.reset(new SettingsWindow(mLogic));
this->set_keep_above(false);
mSettingsWindow->show();
//refresh on settings closed
mSettingsWindow->signal_hide().connect([this](){
// delete mSettingsWindow;
mSettingsWindow.reset(); //destructor is called
this->executeSearch(mWordInput.get_text());
this->set_keep_above(mLogic.mAlwaysOnTop);
});
});
//--------------------------------------------------------------------------
// Add word button
mAddWordButton.set_image_from_icon_name("custom_icon_add");
mAddWordButton.signal_clicked().connect([this]() {
string leastKnownWord = "";
//find word with lowest number of translations
auto leastKnown = min_element(mTranslationResult.begin(),
mTranslationResult.end(), [](auto &a, auto &b) {
return a.second.size() < b.second.size();
});
if(leastKnown != mTranslationResult.end()){
std::cout<<"leastKnown->first = "<<leastKnown->first<<std::endl;
leastKnownWord = leastKnown->first;
}
mNewWordWindow.reset(new NewWordWindow(mLogic, leastKnownWord));
this->set_keep_above(false);
mNewWordWindow->show();
mNewWordWindow->set_transient_for(*this);
mNewWordWindow->set_keep_above(true);
mNewWordWindow->signal_hide().connect([this]() {
mNewWordWindow.reset();
this->executeSearch(mWordInput.get_text());
this->set_keep_above(mLogic.mAlwaysOnTop);
});
});
//Grid
add(mGrid);
mGrid.set_column_spacing(5);
//Grid - first row
mGrid.add(mWordInput);
mGrid.add(mAddWordButton);
mGrid.add(mSettingsButton);
//scrolling area for results
mGrid.attach(mScrollForResults, 0,2,3,1);
mScrollForResults.set_hexpand();
mScrollForResults.set_policy(Gtk::PolicyType::POLICY_AUTOMATIC,
Gtk::PolicyType::POLICY_ALWAYS);
mScrollForResults.add(mTreeView);
mScrollForResults.set_margin_top(10);
mScrollForResults.set_min_content_width(400);
mScrollForResults.set_min_content_height(200);
//--------------------------------------------------------------------------
//results treeView
mRefListStore = Gtk::ListStore::create(mColumns);
mTreeView.set_model(mRefListStore);
mTreeView.set_hexpand();
mTreeView.set_vexpand();
//Word Culumn
{
mTreeView.append_column("Word", mColumns.mGerman);
Gtk::TreeViewColumn *pColumn = mTreeView.get_column(0);
pColumn->set_sizing(Gtk::TreeViewColumnSizing::TREE_VIEW_COLUMN_AUTOSIZE);
Gdk::Color col("#ffaa00");
static_cast<Gtk::CellRendererText *>(pColumn->get_first_cell())
->property_foreground_gdk()
.set_value(col);
}
//Match Culumn
{
mTreeView.append_column("Match", mColumns.mGerman_found);
Gtk::TreeViewColumn *pColumn = mTreeView.get_column(1);
pColumn->set_sizing(Gtk::TreeViewColumnSizing::TREE_VIEW_COLUMN_AUTOSIZE);
pColumn->set_cell_data_func(
*pColumn->get_first_cell(),
[this](Gtk::CellRenderer *renderer,
const Gtk::TreeModel::iterator &iter)
{
Gtk::TreeModel::Row row = *iter;
Gdk::Color col("#ff0000");
auto score = row[this->mColumns.mScore];
if(score < 0)
score = 0;
if(score > 4)
score = 4;
switch (score)
{
//TODO add more colors
case 0:
col.set("#40B640");
break;
case 1:
col.set("#82B640");
break;
case 2:
col.set("#AFB640");
break;
case 3:
col.set("#B67E40");
break;
case 4:
col.set("#B64640");
break;
default:
break;
}
static_cast<Gtk::CellRendererText *>(renderer)
->property_foreground_gdk()
.set_value(col);
});
}
//Translation Culumn
{
mTreeView.append_column("Translation", mColumns.mEnglish);
Gtk::TreeViewColumn* pColumn = mTreeView.get_column(2);
pColumn->set_sizing(Gtk::TreeViewColumnSizing::TREE_VIEW_COLUMN_AUTOSIZE);
static_cast<Gtk::CellRendererText *>(pColumn->get_first_cell())
->property_wrap_mode().set_value(Pango::WRAP_WORD_CHAR);
}
// mTreeView.append_column("Score", mColumns.mScore);
//deal with resizing
this->signal_check_resize().connect([this]()
{
#ifdef _WIN32
const int padding_for_wrap_def = 160;
#else
const int padding_for_wrap_def = 30;
#endif
//calculate remaining size
Gtk::TreeViewColumn* pColumn = mTreeView.get_column(2);
auto width = this->get_allocated_width()
- mTreeView.get_column(0)->get_width()
- mTreeView.get_column(1)->get_width()-padding_for_wrap_def;
//minimum reasonable size for column
if(width < 150)
width = 150;
static_cast<Gtk::CellRendererText *>(pColumn->get_first_cell())
->property_wrap_width().set_value(width);
//debounce
static auto oldsize = 0;
if(oldsize != width)
{
oldsize = width;
//trigger redraw of mTreeView
unique_lock<mutex> guard{this->mSearchMutex};
this->mRedrawNeeded = true;
}
});
// mWordInput.set_text("Put here text to translation...");
mWordInput.set_text("Das ist einee CKatze Katzeee abbestellt begeststellenai...");
mWordInput.set_hexpand();
this->show_all_children();
//make pulse called repeatedly every 100ms
sigc::slot<bool> my_slot = sigc::bind(
sigc::mem_fun(*this, &MainWindow::pulse), 0);
mPulseConnection = Glib::signal_timeout().connect(my_slot, 150);
}
//------------------------------------------------------------------------------
MainWindow::~MainWindow()
{
// present refreshes window position
this->present();
//saves data to logic, this is then saved to json config file
this->get_position(mLogic.mPositionX, mLogic.mPositionY);
this->get_size(mLogic.mSizeX, mLogic.mSizeY);
}
//-----------------------------------------------------------------------------------
bool MainWindow::pulse(int num)
{
ignore_arg(num);
//check if text has changed
Glib::ustring tmp = mWordInput.get_text();
if( mOldTextInEntry != tmp)
{
mOldTextInEntry = tmp;
std::cout << "changed..." << std::endl;
//todo max size of the text
executeSearch(tmp);
}
Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
refClipboard->request_text(
sigc::mem_fun(*this, &MainWindow::on_clipboard_received) );
unique_lock<mutex> guard{mSearchMutex};
if(mNewTranslationAvailable || mRedrawNeeded)
{
mRefListStore->clear();
//for all words, push results to ListStore
for(auto &&w : mTranslationWords)
{
auto &rr = mTranslationResult[w];
bool first = true;
for(auto &&r : rr)
{
Gtk::TreeModel::iterator iter = mRefListStore->append();
Gtk::TreeModel::Row row = *iter;
if (first)
row[mColumns.mGerman] = w;
first = false;
row[mColumns.mGerman_found] = r.match;
row[mColumns.mEnglish] = r.words;
row[mColumns.mScore] = r.score;
}
//if no match found, still display atleast the word
if (first){
Gtk::TreeModel::iterator iter = mRefListStore->append();
(*iter)[mColumns.mGerman] = w;
}
}
mNewTranslationAvailable = false;
mRedrawNeeded = false;
}
return true;
}
//------------------------------------------------------------------------------
void MainWindow::executeSearch(Glib::ustring text)
{
unique_lock<mutex> guard{mSearchMutex};
mWaitingToTranslate = text;
if(!mSearchInProgress)
{
mSearchInProgress = true;
guard.unlock();
std::thread thread {&MainWindow::searchThread, this};
thread.detach();
}
}
//------------------------------------------------------------------------------
void MainWindow::searchThread()
{
string text;
unique_lock<mutex> guard(mSearchMutex);
while(true)
{
//load string and set it to empty
text = mWaitingToTranslate;
mWaitingToTranslate = "";
guard.unlock();
//translate, during translation can Pulse add new string to translate
int numthreads = std::thread::hardware_concurrency();
numthreads = (numthreads > 1) ? numthreads : 1;
std::vector<string> words = Processer::splitToWords(text.c_str());
workerResult results = _search(mLogic.mDicts, numthreads, words, false);
cout << "results are here" << endl;
// for(auto &&w : words)
// {
// auto &rr = results[w];
// cout << w << endl;
// for(auto &&r : rr)
// {
// cout << " " << r.score << ":" << r.match << " -" << r.words
// << endl;
// }
// }
//lock and test if there is another string to translate
guard.lock();
mTranslationResult = results;
mTranslationWords = words;
mNewTranslationAvailable = true;
if(mWaitingToTranslate == "")
break;
}
cout<<"Finish"<<endl;
mSearchInProgress = false;
}
//------------------------------------------------------------------------------
void MainWindow::on_clipboard_received(const Glib::ustring &data)
{
// check if new text is in the clipboard
Glib::ustring text = data;
if (text.size() > 256)
text = text.substr(0, 256);
if(mOldClipboard != text)
{
mOldClipboard = text;
if(!mIgnoreClipboardChange)
{
std::cout << "Clipboard changed..." << std::endl;
mWordInput.set_text(text);
// we do not need to execute search, since pulse does that for us
// when text is changed.
}
mIgnoreClipboardChange = false;
}
}
//------------------------------------------------------------------------------
glitches with resizing fixed
#include "./MainWindow.h"
#include "../Search.h"
#include "../Processer.h"
#include <iostream>
#include <gdkmm/rgba.h>
#include <gtk/gtk.h>
#include "SettingsWindow.h"
#include <gdkmm/pixbuf.h>
#include <gtkmm/icontheme.h>
using namespace std;
MainWindow::MainWindow(Logic& logic)
: mLogic(logic)
{
//Load settings
mIgnoreClipboardChange = !mLogic.mTranslateClipboardAtStart;
// Sets the border width of the window.
this->set_border_width(10);
this->set_default_size(mLogic.mSizeX, mLogic.mSizeY);
this->move(mLogic.mPositionX, mLogic.mPositionY);
this->set_keep_above(mLogic.mAlwaysOnTop);
this->set_title("Dictionary");
//Icons
Glib::RefPtr<Gdk::Pixbuf> imagePlus
= Gdk::Pixbuf::create_from_file("./share/icons/ic_add_black_24dp_1x.png");
imagePlus->get_height();
Gtk::IconTheme::add_builtin_icon("custom_icon_add", 4, imagePlus);
Glib::RefPtr<Gdk::Pixbuf> imageSettings
= Gdk::Pixbuf::create_from_file("./share/icons/ic_settings_black_24dp_1x.png");
imageSettings->get_height();
Gtk::IconTheme::add_builtin_icon("custom_icon_settings", 4, imageSettings);
//--------------------------------------------------------------------------
// settings button clicked shows settings window
mSettingsButton.set_image_from_icon_name("custom_icon_settings");
mSettingsButton.signal_clicked().connect([this](){
if(mSettingsWindow)
return;
mSettingsWindow.reset(new SettingsWindow(mLogic));
this->set_keep_above(false);
mSettingsWindow->show();
//refresh on settings closed
mSettingsWindow->signal_hide().connect([this](){
// delete mSettingsWindow;
mSettingsWindow.reset(); //destructor is called
this->executeSearch(mWordInput.get_text());
this->set_keep_above(mLogic.mAlwaysOnTop);
});
});
//--------------------------------------------------------------------------
// Add word button
mAddWordButton.set_image_from_icon_name("custom_icon_add");
mAddWordButton.signal_clicked().connect([this]() {
string leastKnownWord = "";
//find word with lowest number of translations
auto leastKnown = min_element(mTranslationResult.begin(),
mTranslationResult.end(), [](auto &a, auto &b) {
return a.second.size() < b.second.size();
});
if(leastKnown != mTranslationResult.end()){
std::cout<<"leastKnown->first = "<<leastKnown->first<<std::endl;
leastKnownWord = leastKnown->first;
}
mNewWordWindow.reset(new NewWordWindow(mLogic, leastKnownWord));
this->set_keep_above(false);
mNewWordWindow->show();
mNewWordWindow->set_transient_for(*this);
mNewWordWindow->set_keep_above(true);
mNewWordWindow->signal_hide().connect([this]() {
mNewWordWindow.reset();
this->executeSearch(mWordInput.get_text());
this->set_keep_above(mLogic.mAlwaysOnTop);
});
});
//Grid
add(mGrid);
mGrid.set_column_spacing(5);
//Grid - first row
mGrid.add(mWordInput);
mGrid.add(mAddWordButton);
mGrid.add(mSettingsButton);
//scrolling area for results
mGrid.attach(mScrollForResults, 0,2,3,1);
mScrollForResults.set_hexpand();
mScrollForResults.set_policy(Gtk::PolicyType::POLICY_AUTOMATIC,
Gtk::PolicyType::POLICY_ALWAYS);
mScrollForResults.add(mTreeView);
mScrollForResults.set_margin_top(10);
mScrollForResults.set_min_content_width(400);
mScrollForResults.set_min_content_height(200);
//--------------------------------------------------------------------------
//results treeView
mRefListStore = Gtk::ListStore::create(mColumns);
mTreeView.set_model(mRefListStore);
mTreeView.set_hexpand();
mTreeView.set_vexpand();
//Word Culumn
{
mTreeView.append_column("Word", mColumns.mGerman);
Gtk::TreeViewColumn *pColumn = mTreeView.get_column(0);
// pColumn->set_sizing(Gtk::TreeViewColumnSizing::TREE_VIEW_COLUMN_AUTOSIZE);
// neccessary to prevent glitches
pColumn->set_sizing(Gtk::TreeViewColumnSizing::TREE_VIEW_COLUMN_GROW_ONLY);
Gdk::Color col("#ffaa00");
static_cast<Gtk::CellRendererText *>(pColumn->get_first_cell())
->property_foreground_gdk()
.set_value(col);
}
//Match Culumn
{
mTreeView.append_column("Match", mColumns.mGerman_found);
Gtk::TreeViewColumn *pColumn = mTreeView.get_column(1);
pColumn->set_sizing(Gtk::TreeViewColumnSizing::TREE_VIEW_COLUMN_AUTOSIZE);
pColumn->set_cell_data_func(
*pColumn->get_first_cell(),
[this](Gtk::CellRenderer *renderer,
const Gtk::TreeModel::iterator &iter)
{
Gtk::TreeModel::Row row = *iter;
Gdk::Color col("#ff0000");
auto score = row[this->mColumns.mScore];
if(score < 0)
score = 0;
if(score > 4)
score = 4;
switch (score)
{
//TODO add more colors
case 0:
col.set("#40B640");
break;
case 1:
col.set("#82B640");
break;
case 2:
col.set("#AFB640");
break;
case 3:
col.set("#B67E40");
break;
case 4:
col.set("#B64640");
break;
default:
break;
}
static_cast<Gtk::CellRendererText *>(renderer)
->property_foreground_gdk()
.set_value(col);
});
}
//Translation Culumn
{
mTreeView.append_column("Translation", mColumns.mEnglish);
Gtk::TreeViewColumn* pColumn = mTreeView.get_column(2);
pColumn->set_sizing(Gtk::TreeViewColumnSizing::TREE_VIEW_COLUMN_AUTOSIZE);
static_cast<Gtk::CellRendererText *>(pColumn->get_first_cell())
->property_wrap_mode().set_value(Pango::WRAP_WORD_CHAR);
}
// mTreeView.append_column("Score", mColumns.mScore);
//deal with resizing
this->signal_check_resize().connect([this]()
{
#ifdef _WIN32
const int padding_for_wrap_def = 160;
#else
const int padding_for_wrap_def = 30;
#endif
//calculate remaining size
Gtk::TreeViewColumn* pColumn = mTreeView.get_column(2);
auto width = this->get_allocated_width()
- mTreeView.get_column(0)->get_width()
- mTreeView.get_column(1)->get_width()-padding_for_wrap_def;
//minimum reasonable size for column
if(width < 150)
width = 150;
static_cast<Gtk::CellRendererText *>(pColumn->get_first_cell())
->property_wrap_width().set_value(width);
//debounce
static auto oldsize = 0;
if(oldsize != width)
{
oldsize = width;
//trigger redraw of mTreeView
unique_lock<mutex> guard{this->mSearchMutex};
this->mRedrawNeeded = true;
}
});
// mWordInput.set_text("Put here text to translation...");
mWordInput.set_text("Das ist einee CKatze Katzeee abbestellt begeststellenai...");
mWordInput.set_hexpand();
this->show_all_children();
//make pulse called repeatedly every 100ms
sigc::slot<bool> my_slot = sigc::bind(
sigc::mem_fun(*this, &MainWindow::pulse), 0);
mPulseConnection = Glib::signal_timeout().connect(my_slot, 150);
}
//------------------------------------------------------------------------------
MainWindow::~MainWindow()
{
// present refreshes window position
this->present();
//saves data to logic, this is then saved to json config file
this->get_position(mLogic.mPositionX, mLogic.mPositionY);
this->get_size(mLogic.mSizeX, mLogic.mSizeY);
}
//-----------------------------------------------------------------------------------
bool MainWindow::pulse(int num)
{
ignore_arg(num);
//check if text has changed
Glib::ustring tmp = mWordInput.get_text();
if( mOldTextInEntry != tmp)
{
mOldTextInEntry = tmp;
std::cout << "changed..." << std::endl;
//todo max size of the text
executeSearch(tmp);
}
Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
refClipboard->request_text(
sigc::mem_fun(*this, &MainWindow::on_clipboard_received) );
// If there is new translation, fill the treeview with new data
unique_lock<mutex> guard{mSearchMutex};
if(mNewTranslationAvailable || mRedrawNeeded)
{
mRefListStore->clear();
//for all words, push results to ListStore
for(auto &&w : mTranslationWords)
{
auto &rr = mTranslationResult[w];
bool first = true;
for(auto &&r : rr)
{
Gtk::TreeModel::iterator iter = mRefListStore->append();
Gtk::TreeModel::Row row = *iter;
if (first)
row[mColumns.mGerman] = w;
first = false;
row[mColumns.mGerman_found] = r.match;
row[mColumns.mEnglish] = r.words;
row[mColumns.mScore] = r.score;
}
//if no match found, still display atleast the word
if (first){
Gtk::TreeModel::iterator iter = mRefListStore->append();
(*iter)[mColumns.mGerman] = w;
}
}
//shrink culumns to fit the size
this->mTreeView.columns_autosize();
mNewTranslationAvailable = false;
mRedrawNeeded = false;
}
return true;
}
//------------------------------------------------------------------------------
void MainWindow::executeSearch(Glib::ustring text)
{
unique_lock<mutex> guard{mSearchMutex};
mWaitingToTranslate = text;
if(!mSearchInProgress)
{
mSearchInProgress = true;
guard.unlock();
std::thread thread {&MainWindow::searchThread, this};
thread.detach();
}
}
//------------------------------------------------------------------------------
void MainWindow::searchThread()
{
string text;
unique_lock<mutex> guard(mSearchMutex);
while(true)
{
//load string and set it to empty
text = mWaitingToTranslate;
mWaitingToTranslate = "";
guard.unlock();
//translate, during translation can Pulse add new string to translate
int numthreads = std::thread::hardware_concurrency();
numthreads = (numthreads > 1) ? numthreads : 1;
std::vector<string> words = Processer::splitToWords(text.c_str());
workerResult results = _search(mLogic.mDicts, numthreads, words, false);
cout << "results are here" << endl;
// for(auto &&w : words)
// {
// auto &rr = results[w];
// cout << w << endl;
// for(auto &&r : rr)
// {
// cout << " " << r.score << ":" << r.match << " -" << r.words
// << endl;
// }
// }
//lock and test if there is another string to translate
guard.lock();
mTranslationResult = results;
mTranslationWords = words;
mNewTranslationAvailable = true;
if(mWaitingToTranslate == "")
break;
}
cout<<"Finish"<<endl;
mSearchInProgress = false;
}
//------------------------------------------------------------------------------
void MainWindow::on_clipboard_received(const Glib::ustring &data)
{
// check if new text is in the clipboard
Glib::ustring text = data;
if (text.size() > 256)
text = text.substr(0, 256);
if(mOldClipboard != text)
{
mOldClipboard = text;
if(!mIgnoreClipboardChange)
{
std::cout << "Clipboard changed..." << std::endl;
mWordInput.set_text(text);
// we do not need to execute search, since pulse does that for us
// when text is changed.
}
mIgnoreClipboardChange = false;
}
}
//------------------------------------------------------------------------------
|
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include <Include/PlatformDefinitions.hpp>
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <iostream>
#endif
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/sax/SAXException.hpp>
#include <Include/XalanAutoPtr.hpp>
#include <XalanTransformer/XalanTransformer.hpp>
//#define XALAN_VQ_SPECIAL_TRACE
#if defined(XALAN_VQ_SPECIAL_TRACE)
#include "C:/Program Files/Rational/Quantify/pure.h"
#endif
#if !defined (XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::endl;
#endif
void
Usage()
{
cerr << endl
<< "Xalan version 1.3"
<< endl
<< "Usage: Xalan [options] source stylesheet"
<< endl
<< "Options:"
<< endl
<< " -a Use xml-stylesheet PI, not the 'stylesheet' argument"
<< endl
<< " -o filename Write output to the specified file."
<< endl
<< " -p name expression Sets a stylesheet parameter."
<< endl
<< " -v Validates source documents."
<< endl
<< " -? Display this message."
<< endl;
}
class Params
{
public:
Params(unsigned long maxParams) :
m_validate(false),
m_useStylesheetPI(false),
m_inFileName(0),
m_xslFileName(0),
m_outFileName(0),
m_params(),
m_maxParams(maxParams),
m_currentParam(0)
{
}
bool
addParam(
const char* name,
const char* expression)
{
if (m_currentParam == m_maxParams)
{
return false;
}
else
{
// Allocate memory if necessary...
if (m_params.get() == 0)
{
m_params.reset(new ParamPair[m_maxParams]);
}
assert(m_params.get() != 0);
m_params[m_currentParam].m_name = name;
m_params[m_currentParam].m_expression = expression;
++m_currentParam;
return true;
}
};
void
setParams(XalanTransformer& theTransformer)
{
theTransformer.setUseValidation(m_validate);
for(unsigned long i = 0; i < m_currentParam; ++i)
{
theTransformer.setStylesheetParam(
m_params[i].m_name,
m_params[i].m_expression);
}
}
bool m_validate;
bool m_useStylesheetPI;
const char* m_inFileName;
const char* m_xslFileName;
const char* m_outFileName;
private:
struct ParamPair
{
ParamPair() :
m_name(0),
m_expression(0)
{
}
const char* m_name;
const char* m_expression;
};
XalanArrayAutoPtr<ParamPair> m_params;
const unsigned long m_maxParams;
unsigned long m_currentParam;
};
bool
getArgs(
int argc,
const char* argv[],
Params& params)
{
#if defined(XALAN_STRICT_ANSI_HEADERS)
using std::strlen;
#endif
bool fSuccess = true;
for (int i = 1; i < argc && fSuccess == true; ++i)
{
if (argv[i][0] == '-')
{
if (strlen(argv[i]) != 2)
{
fSuccess = false;
}
else if (params.m_inFileName != 0 || params.m_xslFileName != 0)
{
fSuccess = false;
}
else if (argv[i][1] == 'a')
{
params.m_useStylesheetPI = true;
}
else if (argv[i][1] == 'o')
{
++i;
if(i < argc && argv[i][0] != '-' &&
strlen(argv[i]) != 0)
{
params.m_outFileName = argv[i];
}
else
{
fSuccess = false;
}
}
else if (argv[i][1] == 'p')
{
++i;
if(i >= argc || argv[i][0] == '-')
{
fSuccess = false;
}
else
{
const char* const name = argv[i];
++i;
// Don't check for '-' here, since that might
// be a valid character in a parameter value.
if(i >= argc)
{
fSuccess = false;
}
else
{
const char* const value = argv[i];
if (params.addParam(name, value) == false)
{
cerr << "Maximum numbers of stylesheets params has been exceeded!" << endl;
fSuccess = false;
}
}
}
}
else if (argv[i][1] == 'v')
{
params.m_validate = true;
}
}
else if (params.m_inFileName == 0 &&
strlen(argv[i]) != 0)
{
params.m_inFileName = argv[i];
if (strlen(params.m_inFileName) == 0)
{
fSuccess = false;
}
}
else if (params.m_xslFileName == 0 &&
strlen(argv[i]) != 0 &&
params.m_useStylesheetPI == false)
{
params.m_xslFileName = argv[i];
if (strlen(params.m_xslFileName) == 0)
{
fSuccess = false;
}
}
else
{
fSuccess = false;
}
}
if (fSuccess == true && params.m_inFileName == 0)
{
return false;
}
else if (params.m_xslFileName == 0 && params.m_useStylesheetPI == false)
{
return false;
}
else
{
return fSuccess;
}
}
int
xsltMain(
int argc,
const char* argv[])
{
int theResult = -1;
// Set the maximum number of params as half of argc - 1.
// It's actually argc - 2, but that could get us into negative
// numbers, so don't bother. Also, always add 1, in case
// (argc - 1) / 2 is 0.
Params theParams((argc - 1) / 2 + 1);
if (getArgs(argc, argv, theParams) == false)
{
Usage();
}
else
{
// Call the static initializer for Xerces...
XMLPlatformUtils::Initialize();
// Initialize Xalan...
XalanTransformer::initialize();
{
// Create a XalanTransformer instance...
XalanTransformer theTransformer;
// Set any options...
theParams.setParams(theTransformer);
if (theParams.m_outFileName != 0)
{
theResult = theTransformer.transform(
theParams.m_inFileName,
theParams.m_xslFileName,
theParams.m_outFileName);
}
else
{
theResult = theTransformer.transform(
theParams.m_inFileName,
theParams.m_xslFileName,
cout);
}
if (theResult != 0)
{
cerr << theTransformer.getLastError() << endl;
}
}
// Terminate Xalan...
XalanTransformer::terminate();
// Terminate Xerces...
XMLPlatformUtils::Terminate();
}
return theResult;
}
int
main(
int argc,
const char* argv[])
{
#if !defined(XALAN_USE_ICU) && !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
#if defined(XALAN_VQ_SPECIAL_TRACE)
QuantifyStopRecordingData();
#endif
if (argc < 2)
{
Usage();
return -1;
}
else
{
return xsltMain(argc, argv);
}
}
Removed unnecessary include.
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include <Include/PlatformDefinitions.hpp>
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <iostream>
#endif
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
#include <xercesc/util/PlatformUtils.hpp>
#include <Include/XalanAutoPtr.hpp>
#include <XalanTransformer/XalanTransformer.hpp>
//#define XALAN_VQ_SPECIAL_TRACE
#if defined(XALAN_VQ_SPECIAL_TRACE)
#include "C:/Program Files/Rational/Quantify/pure.h"
#endif
#if !defined (XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::endl;
#endif
void
Usage()
{
cerr << endl
<< "Xalan version 1.3"
<< endl
<< "Usage: Xalan [options] source stylesheet"
<< endl
<< "Options:"
<< endl
<< " -a Use xml-stylesheet PI, not the 'stylesheet' argument"
<< endl
<< " -o filename Write output to the specified file."
<< endl
<< " -p name expression Sets a stylesheet parameter."
<< endl
<< " -v Validates source documents."
<< endl
<< " -? Display this message."
<< endl;
}
class Params
{
public:
Params(unsigned long maxParams) :
m_validate(false),
m_useStylesheetPI(false),
m_inFileName(0),
m_xslFileName(0),
m_outFileName(0),
m_params(),
m_maxParams(maxParams),
m_currentParam(0)
{
}
bool
addParam(
const char* name,
const char* expression)
{
if (m_currentParam == m_maxParams)
{
return false;
}
else
{
// Allocate memory if necessary...
if (m_params.get() == 0)
{
m_params.reset(new ParamPair[m_maxParams]);
}
assert(m_params.get() != 0);
m_params[m_currentParam].m_name = name;
m_params[m_currentParam].m_expression = expression;
++m_currentParam;
return true;
}
};
void
setParams(XalanTransformer& theTransformer)
{
theTransformer.setUseValidation(m_validate);
for(unsigned long i = 0; i < m_currentParam; ++i)
{
theTransformer.setStylesheetParam(
m_params[i].m_name,
m_params[i].m_expression);
}
}
bool m_validate;
bool m_useStylesheetPI;
const char* m_inFileName;
const char* m_xslFileName;
const char* m_outFileName;
private:
struct ParamPair
{
ParamPair() :
m_name(0),
m_expression(0)
{
}
const char* m_name;
const char* m_expression;
};
XalanArrayAutoPtr<ParamPair> m_params;
const unsigned long m_maxParams;
unsigned long m_currentParam;
};
bool
getArgs(
int argc,
const char* argv[],
Params& params)
{
#if defined(XALAN_STRICT_ANSI_HEADERS)
using std::strlen;
#endif
bool fSuccess = true;
for (int i = 1; i < argc && fSuccess == true; ++i)
{
if (argv[i][0] == '-')
{
if (strlen(argv[i]) != 2)
{
fSuccess = false;
}
else if (params.m_inFileName != 0 || params.m_xslFileName != 0)
{
fSuccess = false;
}
else if (argv[i][1] == 'a')
{
params.m_useStylesheetPI = true;
}
else if (argv[i][1] == 'o')
{
++i;
if(i < argc && argv[i][0] != '-' &&
strlen(argv[i]) != 0)
{
params.m_outFileName = argv[i];
}
else
{
fSuccess = false;
}
}
else if (argv[i][1] == 'p')
{
++i;
if(i >= argc || argv[i][0] == '-')
{
fSuccess = false;
}
else
{
const char* const name = argv[i];
++i;
// Don't check for '-' here, since that might
// be a valid character in a parameter value.
if(i >= argc)
{
fSuccess = false;
}
else
{
const char* const value = argv[i];
if (params.addParam(name, value) == false)
{
cerr << "Maximum numbers of stylesheets params has been exceeded!" << endl;
fSuccess = false;
}
}
}
}
else if (argv[i][1] == 'v')
{
params.m_validate = true;
}
}
else if (params.m_inFileName == 0 &&
strlen(argv[i]) != 0)
{
params.m_inFileName = argv[i];
if (strlen(params.m_inFileName) == 0)
{
fSuccess = false;
}
}
else if (params.m_xslFileName == 0 &&
strlen(argv[i]) != 0 &&
params.m_useStylesheetPI == false)
{
params.m_xslFileName = argv[i];
if (strlen(params.m_xslFileName) == 0)
{
fSuccess = false;
}
}
else
{
fSuccess = false;
}
}
if (fSuccess == true && params.m_inFileName == 0)
{
return false;
}
else if (params.m_xslFileName == 0 && params.m_useStylesheetPI == false)
{
return false;
}
else
{
return fSuccess;
}
}
int
xsltMain(
int argc,
const char* argv[])
{
int theResult = -1;
// Set the maximum number of params as half of argc - 1.
// It's actually argc - 2, but that could get us into negative
// numbers, so don't bother. Also, always add 1, in case
// (argc - 1) / 2 is 0.
Params theParams((argc - 1) / 2 + 1);
if (getArgs(argc, argv, theParams) == false)
{
Usage();
}
else
{
// Call the static initializer for Xerces...
XMLPlatformUtils::Initialize();
// Initialize Xalan...
XalanTransformer::initialize();
{
// Create a XalanTransformer instance...
XalanTransformer theTransformer;
// Set any options...
theParams.setParams(theTransformer);
if (theParams.m_outFileName != 0)
{
theResult = theTransformer.transform(
theParams.m_inFileName,
theParams.m_xslFileName,
theParams.m_outFileName);
}
else
{
theResult = theTransformer.transform(
theParams.m_inFileName,
theParams.m_xslFileName,
cout);
}
if (theResult != 0)
{
cerr << theTransformer.getLastError() << endl;
}
}
// Terminate Xalan...
XalanTransformer::terminate();
// Terminate Xerces...
XMLPlatformUtils::Terminate();
}
return theResult;
}
int
main(
int argc,
const char* argv[])
{
#if !defined(XALAN_USE_ICU) && !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
#if defined(XALAN_VQ_SPECIAL_TRACE)
QuantifyStopRecordingData();
#endif
if (argc < 2)
{
Usage();
return -1;
}
else
{
return xsltMain(argc, argv);
}
}
|
#include "gtest/gtest.h"
#include "test_utils/test_utils.hpp"
#include "cpputil/math_utils.hpp"
#include "Models/ChisqModel.hpp"
#include "Models/PosteriorSamplers/IndependentMvnVarSampler.hpp"
#include "Models/StateSpace/MultivariateStateSpaceModel.hpp"
#include "Models/StateSpace/StateModels/LocalLevelStateModel.hpp"
#include "Models/StateSpace/PosteriorSamplers/SharedLocalLevelPosteriorSampler.hpp"
#include "Models/StateSpace/PosteriorSamplers/MultivariateStateSpaceModelSampler.hpp"
#include "distributions.hpp"
#include "LinAlg/Array.hpp"
namespace {
using namespace BOOM;
using std::endl;
using std::cout;
class MultivariateStateSpaceModelTest : public ::testing::Test {
protected:
MultivariateStateSpaceModelTest()
: sigma_obs_(.25) {
GlobalRng::rng.seed(8675310);
}
// Generate fake parameters, simulate the state, and simulate observed data.
// Args:
// time_dimension: The number of time points to simulate.
// ydim: The dimension of the response to simulate.
// nfactors: The number of factors in the state.
void McmcSetup(int time_dimension, int ydim, int nfactors) {
if (nfactors >= ydim) {
report_error("The number of factors should be less than ydim.");
}
Vector state = rnorm_vector(nfactors, 0, 1);
state_.resize(nfactors, time_dimension);
observed_data_.resize(time_dimension, ydim);
observation_coefficients_.resize(ydim, nfactors);
observation_coefficients_.randomize();
innovation_sigsq_ = Vector(nfactors);
innovation_sigsq_.randomize();
innovation_sigsq_ *= innovation_sigsq_;
Vector innovation_sd = sqrt(innovation_sigsq_);
for (int i = 0; i < observation_coefficients_.nrow(); ++i) {
for (int j = i; j < observation_coefficients_.ncol(); ++j) {
observation_coefficients_(i, j) = 0.0;
}
if (i < observation_coefficients_.ncol()) {
observation_coefficients_(i, i) = 1.0;
}
}
for (int i = 0; i < time_dimension; ++i) {
state += rnorm_vector(nfactors, 0, 1) * innovation_sd;
state_.col(i) = state;
observed_data_.row(i) = observation_coefficients_ * state
+ rnorm_vector(ydim, 0, sigma_obs_);
}
}
Matrix observed_data_;
Matrix state_;
Matrix observation_coefficients_;
Vector innovation_sigsq_;
double sigma_obs_;
};
//===========================================================================
TEST_F(MultivariateStateSpaceModelTest, EmptyTest) {}
//===========================================================================
TEST_F(MultivariateStateSpaceModelTest, ConstructorTest) {
MultivariateStateSpaceModel model(3);
}
//===========================================================================
TEST_F(MultivariateStateSpaceModelTest, BaseClassTest) {
MultivariateStateSpaceModel model(3);
IndependentMvnModel *obs = model.observation_model();
EXPECT_TRUE(obs != nullptr);
EXPECT_EQ(obs->dim(), 3);
EXPECT_EQ(0, model.number_of_state_models());
EXPECT_EQ(0, model.state_dimension());
EXPECT_EQ(0, model.time_dimension());
}
//===========================================================================
TEST_F(MultivariateStateSpaceModelTest, ModelMatricesTest) {
int ydim = 3;
int nfactors = 2;
int time_dimension = 10;
McmcSetup(time_dimension, ydim, nfactors);
MultivariateStateSpaceModel model(ydim);
for (int i = 0; i < time_dimension; ++i) {
NEW(PartiallyObservedVectorData, data_point)(observed_data_.row(i));
model.add_data(data_point);
}
NEW(SharedLocalLevelStateModel, state_model)(nfactors, &model);
model.add_shared_state(state_model);
Selector fully_observed(ydim, true);
EXPECT_EQ(model.observation_coefficients(0, fully_observed)->nrow(), ydim);
EXPECT_EQ(model.observation_coefficients(0, fully_observed)->ncol(),
nfactors);
}
//===========================================================================
// TODO: move this to a function that depends on ydim. Test with ydim == 2 to
// catch the low-dimensional update.
TEST_F(MultivariateStateSpaceModelTest, DrawHighDimensionalStateTest) {
int time_dimension = 100;
int ydim = 3;
int nfactors = 2;
int niter = 200;
McmcSetup(time_dimension, ydim, nfactors);
NEW(MultivariateStateSpaceModel, model)(ydim);
cout << "raw data: " << endl;
for (int i = 0; i < observed_data_.nrow(); ++i) {
NEW(PartiallyObservedVectorData, data_point)(observed_data_.row(i));
model->add_data(data_point);
}
NEW(SharedLocalLevelStateModel, state_model)(nfactors, model.get());
// Initial state mean and variance.
Vector initial_state_mean(2, 0.0);
SpdMatrix initial_state_variance(2, 1.0);
state_model->set_initial_state_mean(initial_state_mean);
state_model->set_initial_state_variance(initial_state_variance);
// Prior distribution and posterior sampler.
std::vector<Ptr<GammaModelBase>> innovation_precision_priors;
for (int i = 0; i < nfactors; ++i) {
innovation_precision_priors.push_back(
new ChisqModel(1, sqrt(innovation_sigsq_[i])));
}
Matrix observation_coefficient_prior_mean(nfactors, ydim, 0.0);
NEW(SharedLocalLevelPosteriorSampler, state_model_sampler)(
state_model.get(),
innovation_precision_priors,
observation_coefficient_prior_mean,
1.0);
state_model->set_method(state_model_sampler);
// Done configuring, so add the state model.
for (int i = 0; i < nfactors; ++i) {
state_model->innovation_model(i)->set_sigsq(innovation_sigsq_[i]);
}
state_model->coefficient_model()->set_Beta(
observation_coefficients_.transpose());
model->add_shared_state(state_model);
// Check that the model matrices are as expected.
int time_index = 2;
Matrix transition = model->state_transition_matrix(time_index)->dense();
EXPECT_TRUE(MatrixEquals(transition, SpdMatrix(2, 1.0)));
state_model->coefficient_model()->set_Beta(observation_coefficients_.transpose());
Matrix observation_coefficients = model->observation_coefficients(
time_index, Selector(ydim, true))->dense();
EXPECT_EQ(observation_coefficients.nrow(), observation_coefficients_.nrow());
EXPECT_EQ(observation_coefficients.ncol(), observation_coefficients_.ncol());
EXPECT_TRUE(MatrixEquals(observation_coefficients_, observation_coefficients))
<< endl << "correct observation matrix: " << endl
<< observation_coefficients_ << endl
<< "what the model has: " << endl
<< observation_coefficients;
// Need a prior for the observation model.
std::vector<Ptr<GammaModelBase>> observation_model_priors;
for (int i = 0; i < ydim; ++i) {
observation_model_priors.push_back(new GammaModel(1, 1));
}
NEW(IndependentMvnVarSampler, observation_model_sampler)(
model->observation_model(),
observation_model_priors);
model->observation_model()->set_method(observation_model_sampler);
model->observation_model()->set_sigsq(Vector(ydim, square(sigma_obs_)));
// Set the global sampler for the model.
NEW(MultivariateStateSpaceModelSampler, sampler)(model.get());
model->set_method(sampler);
Array state_draws({niter, model->state_dimension(), model->time_dimension()});
for (int i = 0; i < niter; ++i) {
model->sample_posterior();
state_draws.slice(i, -1, -1) = model->state();
}
auto status = CheckMcmcMatrix(state_draws.slice(-1, 0, -1).to_matrix(),
state_.row(0), .95, true, "factor1.txt");
EXPECT_TRUE(status.ok) << status.error_message();
// The imputed values of the state should fall within the range of the data
// at time t.
EXPECT_EQ("",
CheckWithinRage(state_draws.slice(-1, 0, -1).to_matrix(),
Vector(state_.row(0)) - 10 * sigma_obs_,
Vector(state_.row(0)) + 10 * sigma_obs_));
EXPECT_EQ("",
CheckWithinRage(state_draws.slice(-1, 1, -1).to_matrix(),
Vector(state_.row(1)) - 10 * sigma_obs_,
Vector(state_.row(1)) + 10 * sigma_obs_));
auto status2 = CheckMcmcMatrix(state_draws.slice(-1, 1, -1).to_matrix(),
state_.row(1), .95, true, "factor2.txt");
EXPECT_TRUE(status2.ok) << status2.error_message();
}
} // namespace
Tweak to multivariate_test for new RNG.
#include "gtest/gtest.h"
#include "test_utils/test_utils.hpp"
#include "cpputil/math_utils.hpp"
#include "Models/ChisqModel.hpp"
#include "Models/PosteriorSamplers/IndependentMvnVarSampler.hpp"
#include "Models/StateSpace/MultivariateStateSpaceModel.hpp"
#include "Models/StateSpace/StateModels/LocalLevelStateModel.hpp"
#include "Models/StateSpace/PosteriorSamplers/SharedLocalLevelPosteriorSampler.hpp"
#include "Models/StateSpace/PosteriorSamplers/MultivariateStateSpaceModelSampler.hpp"
#include "distributions.hpp"
#include "LinAlg/Array.hpp"
namespace {
using namespace BOOM;
using std::endl;
using std::cout;
class MultivariateStateSpaceModelTest : public ::testing::Test {
protected:
MultivariateStateSpaceModelTest()
: sigma_obs_(.25) {
GlobalRng::rng.seed(8675310);
}
// Generate fake parameters, simulate the state, and simulate observed data.
// Args:
// time_dimension: The number of time points to simulate.
// ydim: The dimension of the response to simulate.
// nfactors: The number of factors in the state.
void McmcSetup(int time_dimension, int ydim, int nfactors) {
if (nfactors >= ydim) {
report_error("The number of factors should be less than ydim.");
}
Vector state = rnorm_vector(nfactors, 0, 1);
state_.resize(nfactors, time_dimension);
observed_data_.resize(time_dimension, ydim);
observation_coefficients_.resize(ydim, nfactors);
observation_coefficients_.randomize();
innovation_sigsq_ = Vector(nfactors);
innovation_sigsq_.randomize();
innovation_sigsq_ *= innovation_sigsq_;
Vector innovation_sd = sqrt(innovation_sigsq_);
for (int i = 0; i < observation_coefficients_.nrow(); ++i) {
for (int j = i; j < observation_coefficients_.ncol(); ++j) {
observation_coefficients_(i, j) = 0.0;
}
if (i < observation_coefficients_.ncol()) {
observation_coefficients_(i, i) = 1.0;
}
}
for (int i = 0; i < time_dimension; ++i) {
state += rnorm_vector(nfactors, 0, 1) * innovation_sd;
state_.col(i) = state;
observed_data_.row(i) = observation_coefficients_ * state
+ rnorm_vector(ydim, 0, sigma_obs_);
}
}
Matrix observed_data_;
Matrix state_;
Matrix observation_coefficients_;
Vector innovation_sigsq_;
double sigma_obs_;
};
//===========================================================================
TEST_F(MultivariateStateSpaceModelTest, EmptyTest) {}
//===========================================================================
TEST_F(MultivariateStateSpaceModelTest, ConstructorTest) {
MultivariateStateSpaceModel model(3);
}
//===========================================================================
TEST_F(MultivariateStateSpaceModelTest, BaseClassTest) {
MultivariateStateSpaceModel model(3);
IndependentMvnModel *obs = model.observation_model();
EXPECT_TRUE(obs != nullptr);
EXPECT_EQ(obs->dim(), 3);
EXPECT_EQ(0, model.number_of_state_models());
EXPECT_EQ(0, model.state_dimension());
EXPECT_EQ(0, model.time_dimension());
}
//===========================================================================
TEST_F(MultivariateStateSpaceModelTest, ModelMatricesTest) {
int ydim = 3;
int nfactors = 2;
int time_dimension = 10;
McmcSetup(time_dimension, ydim, nfactors);
MultivariateStateSpaceModel model(ydim);
for (int i = 0; i < time_dimension; ++i) {
NEW(PartiallyObservedVectorData, data_point)(observed_data_.row(i));
model.add_data(data_point);
}
NEW(SharedLocalLevelStateModel, state_model)(nfactors, &model);
model.add_shared_state(state_model);
Selector fully_observed(ydim, true);
EXPECT_EQ(model.observation_coefficients(0, fully_observed)->nrow(), ydim);
EXPECT_EQ(model.observation_coefficients(0, fully_observed)->ncol(),
nfactors);
}
//===========================================================================
// TODO: move this to a function that depends on ydim. Test with ydim == 2 to
// catch the low-dimensional update.
TEST_F(MultivariateStateSpaceModelTest, DrawHighDimensionalStateTest) {
int time_dimension = 100;
int ydim = 3;
int nfactors = 2;
int niter = 200;
McmcSetup(time_dimension, ydim, nfactors);
NEW(MultivariateStateSpaceModel, model)(ydim);
cout << "raw data: " << endl;
for (int i = 0; i < observed_data_.nrow(); ++i) {
NEW(PartiallyObservedVectorData, data_point)(observed_data_.row(i));
model->add_data(data_point);
}
NEW(SharedLocalLevelStateModel, state_model)(nfactors, model.get());
// Initial state mean and variance.
Vector initial_state_mean(2, 0.0);
SpdMatrix initial_state_variance(2, 1.0);
state_model->set_initial_state_mean(initial_state_mean);
state_model->set_initial_state_variance(initial_state_variance);
// Prior distribution and posterior sampler.
std::vector<Ptr<GammaModelBase>> innovation_precision_priors;
for (int i = 0; i < nfactors; ++i) {
innovation_precision_priors.push_back(
new ChisqModel(1, sqrt(innovation_sigsq_[i])));
}
Matrix observation_coefficient_prior_mean(nfactors, ydim, 0.0);
NEW(SharedLocalLevelPosteriorSampler, state_model_sampler)(
state_model.get(),
innovation_precision_priors,
observation_coefficient_prior_mean,
1.0);
state_model->set_method(state_model_sampler);
// Done configuring, so add the state model.
for (int i = 0; i < nfactors; ++i) {
state_model->innovation_model(i)->set_sigsq(innovation_sigsq_[i]);
}
state_model->coefficient_model()->set_Beta(
observation_coefficients_.transpose());
model->add_shared_state(state_model);
// Check that the model matrices are as expected.
int time_index = 2;
Matrix transition = model->state_transition_matrix(time_index)->dense();
EXPECT_TRUE(MatrixEquals(transition, SpdMatrix(2, 1.0)));
state_model->coefficient_model()->set_Beta(observation_coefficients_.transpose());
Matrix observation_coefficients = model->observation_coefficients(
time_index, Selector(ydim, true))->dense();
EXPECT_EQ(observation_coefficients.nrow(), observation_coefficients_.nrow());
EXPECT_EQ(observation_coefficients.ncol(), observation_coefficients_.ncol());
EXPECT_TRUE(MatrixEquals(observation_coefficients_, observation_coefficients))
<< endl << "correct observation matrix: " << endl
<< observation_coefficients_ << endl
<< "what the model has: " << endl
<< observation_coefficients;
// Need a prior for the observation model.
std::vector<Ptr<GammaModelBase>> observation_model_priors;
for (int i = 0; i < ydim; ++i) {
observation_model_priors.push_back(new GammaModel(1, 1));
}
NEW(IndependentMvnVarSampler, observation_model_sampler)(
model->observation_model(),
observation_model_priors);
model->observation_model()->set_method(observation_model_sampler);
model->observation_model()->set_sigsq(Vector(ydim, square(sigma_obs_)));
// Set the global sampler for the model.
NEW(MultivariateStateSpaceModelSampler, sampler)(model.get());
model->set_method(sampler);
Array state_draws({niter, model->state_dimension(), model->time_dimension()});
for (int i = 0; i < niter; ++i) {
model->sample_posterior();
state_draws.slice(i, -1, -1) = model->state();
}
auto status = CheckMcmcMatrix(state_draws.slice(-1, 0, -1).to_matrix(),
state_.row(0), .95, true, "factor1.txt");
EXPECT_TRUE(status.ok) << status;
EXPECT_EQ("", CheckStochasticProcess(
state_draws.slice(-1, 0, -1).to_matrix(),
Vector(state_.row(0)),
.95, .10, "factor1.txt"));
// The explained variance ratio had to be adjusted for this test, but by
// visual inspection it looks fine.
EXPECT_EQ("", CheckStochasticProcess(
state_draws.slice(-1, 1, -1).to_matrix(),
Vector(state_.row(1)),
.95, .50, "factor2.txt"));
}
} // namespace
|
// Copyright (c) 2014, NVIDIA CORPORATION. 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.
#pragma once
#include <stddef.h> // XXX instead of <cstddef> to WAR clang issue
#include <type_traits>
#include <utility> // <utility> declares std::tuple_element et al. for us
// allow the user to define an annotation to apply to these functions
// by default, it attempts to be constexpr
#ifndef __TUPLE_ANNOTATION
# if __cplusplus <= 201103L
# define __TUPLE_ANNOTATION
# else
# define __TUPLE_ANNOTATION constexpr
# endif
# define __TUPLE_ANNOTATION_NEEDS_UNDEF
#endif
// define the incantation to silence nvcc errors concerning __host__ __device__ functions
#if defined(__CUDACC__) && !(defined(__CUDA__) && defined(__clang__))
#define __TUPLE_EXEC_CHECK_DISABLE \
#pragma nv_exec_check_disable
#else
#define __TUPLE_EXEC_CHECK_DISABLE
#endif
// allow the user to define a namespace for these functions
#ifndef __TUPLE_NAMESPACE
#define __TUPLE_NAMESPACE std
#define __TUPLE_NAMESPACE_NEEDS_UNDEF
#endif
namespace __TUPLE_NAMESPACE
{
template<class... Types> class tuple;
} // end namespace
// specializations of stuff in std come before their use
namespace std
{
template<size_t i>
struct tuple_element<i, __TUPLE_NAMESPACE::tuple<>> {};
template<class Type1, class... Types>
struct tuple_element<0, __TUPLE_NAMESPACE::tuple<Type1,Types...>>
{
using type = Type1;
};
template<size_t i, class Type1, class... Types>
struct tuple_element<i, __TUPLE_NAMESPACE::tuple<Type1,Types...>>
{
using type = typename tuple_element<i - 1, __TUPLE_NAMESPACE::tuple<Types...>>::type;
};
template<class... Types>
struct tuple_size<__TUPLE_NAMESPACE::tuple<Types...>>
: std::integral_constant<size_t, sizeof...(Types)>
{};
} // end std
namespace __TUPLE_NAMESPACE
{
namespace detail
{
// define variadic "and" operator
template <typename... Conditions>
struct tuple_and;
template<>
struct tuple_and<>
: public std::true_type
{
};
template <typename Condition, typename... Conditions>
struct tuple_and<Condition, Conditions...>
: public std::integral_constant<
bool,
Condition::value && tuple_and<Conditions...>::value>
{
};
// XXX this implementation is based on Howard Hinnant's "tuple leaf" construction in libcxx
// define index sequence in case it is missing
// prefix this stuff with "tuple" to avoid collisions with other implementations
template<size_t... I> struct tuple_index_sequence {};
template<size_t Start, typename Indices, size_t End>
struct tuple_make_index_sequence_impl;
template<size_t Start, size_t... Indices, size_t End>
struct tuple_make_index_sequence_impl<
Start,
tuple_index_sequence<Indices...>,
End
>
{
typedef typename tuple_make_index_sequence_impl<
Start + 1,
tuple_index_sequence<Indices..., Start>,
End
>::type type;
};
template<size_t End, size_t... Indices>
struct tuple_make_index_sequence_impl<End, tuple_index_sequence<Indices...>, End>
{
typedef tuple_index_sequence<Indices...> type;
};
template<size_t N>
using tuple_make_index_sequence = typename tuple_make_index_sequence_impl<0, tuple_index_sequence<>, N>::type;
template<class T>
struct tuple_use_empty_base_class_optimization
: std::integral_constant<
bool,
std::is_empty<T>::value
#if __cplusplus >= 201402L
&& !std::is_final<T>::value
#endif
>
{};
template<class T, bool = tuple_use_empty_base_class_optimization<T>::value>
class tuple_leaf_base
{
public:
__TUPLE_EXEC_CHECK_DISABLE
__TUPLE_ANNOTATION
tuple_leaf_base() = default;
__TUPLE_EXEC_CHECK_DISABLE
template<class U>
__TUPLE_ANNOTATION
tuple_leaf_base(U&& arg) : val_(std::forward<U>(arg)) {}
__TUPLE_ANNOTATION
const T& const_get() const
{
return val_;
}
__TUPLE_ANNOTATION
T& mutable_get()
{
return val_;
}
private:
T val_;
};
template<class T>
class tuple_leaf_base<T,true> : public T
{
public:
__TUPLE_ANNOTATION
tuple_leaf_base() = default;
template<class U>
__TUPLE_ANNOTATION
tuple_leaf_base(U&& arg) : T(std::forward<U>(arg)) {}
__TUPLE_ANNOTATION
const T& const_get() const
{
return *this;
}
__TUPLE_ANNOTATION
T& mutable_get()
{
return *this;
}
};
template<size_t I, class T>
class tuple_leaf : public tuple_leaf_base<T>
{
private:
using super_t = tuple_leaf_base<T>;
public:
__TUPLE_ANNOTATION
tuple_leaf() = default;
template<class U,
class = typename std::enable_if<
std::is_constructible<T,U>::value
>::type>
__TUPLE_ANNOTATION
tuple_leaf(U&& arg) : super_t(std::forward<U>(arg)) {}
__TUPLE_ANNOTATION
tuple_leaf(const tuple_leaf& other) : super_t(other.const_get()) {}
__TUPLE_ANNOTATION
tuple_leaf(tuple_leaf&& other) : super_t(std::forward<T>(other.mutable_get())) {}
template<class U,
class = typename std::enable_if<
std::is_constructible<T,U>::value
>::type>
__TUPLE_ANNOTATION
tuple_leaf(const tuple_leaf<I,U>& other) : super_t(other.const_get()) {}
__TUPLE_EXEC_CHECK_DISABLE
template<class U,
class = typename std::enable_if<
std::is_assignable<T,U>::value
>::type>
__TUPLE_ANNOTATION
tuple_leaf& operator=(const tuple_leaf<I,U>& other)
{
this->mutable_get() = other.const_get();
return *this;
}
__TUPLE_EXEC_CHECK_DISABLE
__TUPLE_ANNOTATION
tuple_leaf& operator=(const tuple_leaf& other)
{
this->mutable_get() = other.const_get();
return *this;
}
__TUPLE_EXEC_CHECK_DISABLE
__TUPLE_ANNOTATION
tuple_leaf& operator=(tuple_leaf&& other)
{
this->mutable_get() = std::forward<T>(other.mutable_get());
return *this;
}
__TUPLE_EXEC_CHECK_DISABLE
template<class U,
class = typename std::enable_if<
std::is_assignable<T,U&&>::value
>::type>
__TUPLE_ANNOTATION
tuple_leaf& operator=(tuple_leaf<I,U>&& other)
{
this->mutable_get() = std::forward<U>(other.mutable_get());
return *this;
}
__TUPLE_EXEC_CHECK_DISABLE
__TUPLE_ANNOTATION
int swap(tuple_leaf& other)
{
using std::swap;
swap(this->mutable_get(), other.mutable_get());
return 0;
}
};
template<class... Args>
struct tuple_type_list {};
template<size_t i, class... Args>
struct tuple_type_at_impl;
template<size_t i, class Arg0, class... Args>
struct tuple_type_at_impl<i, Arg0, Args...>
{
using type = typename tuple_type_at_impl<i-1, Args...>::type;
};
template<class Arg0, class... Args>
struct tuple_type_at_impl<0, Arg0,Args...>
{
using type = Arg0;
};
template<size_t i, class... Args>
using tuple_type_at = typename tuple_type_at_impl<i,Args...>::type;
template<class IndexSequence, class... Args>
class tuple_base;
template<size_t... I, class... Types>
class tuple_base<tuple_index_sequence<I...>, Types...>
: public tuple_leaf<I,Types>...
{
public:
using leaf_types = tuple_type_list<tuple_leaf<I,Types>...>;
__TUPLE_ANNOTATION
tuple_base() = default;
__TUPLE_ANNOTATION
tuple_base(const Types&... args)
: tuple_leaf<I,Types>(args)...
{}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
tuple_and<
std::is_constructible<Types,UTypes&&>...
>::value
>::type>
__TUPLE_ANNOTATION
explicit tuple_base(UTypes&&... args)
: tuple_leaf<I,Types>(std::forward<UTypes>(args))...
{}
__TUPLE_ANNOTATION
tuple_base(const tuple_base& other)
: tuple_leaf<I,Types>(other.template const_leaf<I>())...
{}
__TUPLE_ANNOTATION
tuple_base(tuple_base&& other)
: tuple_leaf<I,Types>(std::move(other.template mutable_leaf<I>()))...
{}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
tuple_and<
std::is_constructible<Types,const UTypes&>...
>::value
>::type>
__TUPLE_ANNOTATION
tuple_base(const tuple_base<tuple_index_sequence<I...>,UTypes...>& other)
: tuple_leaf<I,Types>(other.template const_leaf<I>())...
{}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
tuple_and<
std::is_constructible<Types,const UTypes&>...
>::value
>::type>
__TUPLE_ANNOTATION
tuple_base(const std::tuple<UTypes...>& other)
: tuple_base{std::get<I>(other)...}
{}
__TUPLE_ANNOTATION
tuple_base& operator=(const tuple_base& other)
{
swallow((mutable_leaf<I>() = other.template const_leaf<I>())...);
return *this;
}
__TUPLE_ANNOTATION
tuple_base& operator=(tuple_base&& other)
{
swallow((mutable_leaf<I>() = std::move(other.template mutable_leaf<I>()))...);
return *this;
}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
tuple_and<
std::is_assignable<Types,const UTypes&>...
>::value
>::type>
__TUPLE_ANNOTATION
tuple_base& operator=(const tuple_base<tuple_index_sequence<I...>,UTypes...>& other)
{
swallow((mutable_leaf<I>() = other.template const_leaf<I>())...);
return *this;
}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
tuple_and<
std::is_assignable<Types,UTypes&&>...
>::value
>::type>
__TUPLE_ANNOTATION
tuple_base& operator=(tuple_base<tuple_index_sequence<I...>,UTypes...>&& other)
{
swallow((mutable_leaf<I>() = std::move(other.template mutable_leaf<I>()))...);
return *this;
}
template<class UType1, class UType2,
class = typename std::enable_if<
(sizeof...(Types) == 2) &&
tuple_and<
std::is_assignable<tuple_type_at< 0,Types...>,const UType1&>,
std::is_assignable<tuple_type_at<sizeof...(Types) == 2 ? 1 : 0,Types...>,const UType2&>
>::value
>::type>
__TUPLE_ANNOTATION
tuple_base& operator=(const std::pair<UType1,UType2>& p)
{
mutable_get<0>() = p.first;
mutable_get<1>() = p.second;
return *this;
}
template<class UType1, class UType2,
class = typename std::enable_if<
(sizeof...(Types) == 2) &&
tuple_and<
std::is_assignable<tuple_type_at< 0,Types...>,UType1&&>,
std::is_assignable<tuple_type_at<sizeof...(Types) == 2 ? 1 : 0,Types...>,UType2&&>
>::value
>::type>
__TUPLE_ANNOTATION
tuple_base& operator=(std::pair<UType1,UType2>&& p)
{
mutable_get<0>() = std::move(p.first);
mutable_get<1>() = std::move(p.second);
return *this;
}
template<size_t i>
__TUPLE_ANNOTATION
const tuple_leaf<i,tuple_type_at<i,Types...>>& const_leaf() const
{
return *this;
}
template<size_t i>
__TUPLE_ANNOTATION
tuple_leaf<i,tuple_type_at<i,Types...>>& mutable_leaf()
{
return *this;
}
template<size_t i>
__TUPLE_ANNOTATION
tuple_leaf<i,tuple_type_at<i,Types...>>&& move_leaf() &&
{
return std::move(*this);
}
__TUPLE_ANNOTATION
void swap(tuple_base& other)
{
swallow(tuple_leaf<I,Types>::swap(other)...);
}
template<size_t i>
__TUPLE_ANNOTATION
const tuple_type_at<i,Types...>& const_get() const
{
return const_leaf<i>().const_get();
}
template<size_t i>
__TUPLE_ANNOTATION
tuple_type_at<i,Types...>& mutable_get()
{
return mutable_leaf<i>().mutable_get();
}
// enable conversion to Tuple-like things
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
tuple_and<
std::is_constructible<Types,const UTypes&>...
>::value
>::type>
__TUPLE_ANNOTATION
operator std::tuple<UTypes...> () const
{
return std::tuple<UTypes...>(const_get<I>()...);
}
private:
template<class... Args>
__TUPLE_ANNOTATION
static void swallow(Args&&...) {}
};
} // end detail
} // end namespace
// implement std::get()
namespace std
{
template<size_t i, class... UTypes>
__TUPLE_ANNOTATION
typename std::tuple_element<i, __TUPLE_NAMESPACE::tuple<UTypes...>>::type &
get(__TUPLE_NAMESPACE::tuple<UTypes...>& t)
{
return t.template mutable_get<i>();
}
template<size_t i, class... UTypes>
__TUPLE_ANNOTATION
const typename std::tuple_element<i, __TUPLE_NAMESPACE::tuple<UTypes...>>::type &
get(const __TUPLE_NAMESPACE::tuple<UTypes...>& t)
{
return t.template const_get<i>();
}
template<size_t i, class... UTypes>
__TUPLE_ANNOTATION
typename std::tuple_element<i, __TUPLE_NAMESPACE::tuple<UTypes...>>::type &&
get(__TUPLE_NAMESPACE::tuple<UTypes...>&& t)
{
using type = typename std::tuple_element<i, __TUPLE_NAMESPACE::tuple<UTypes...>>::type;
auto&& leaf = static_cast<__TUPLE_NAMESPACE::detail::tuple_leaf<i,type>&&>(t.base());
return static_cast<type&&>(leaf.mutable_get());
}
} // end std
namespace __TUPLE_NAMESPACE
{
template<class... Types>
class tuple
{
private:
using base_type = detail::tuple_base<detail::tuple_make_index_sequence<sizeof...(Types)>, Types...>;
base_type base_;
__TUPLE_ANNOTATION
base_type& base()
{
return base_;
}
__TUPLE_ANNOTATION
const base_type& base() const
{
return base_;
}
public:
__TUPLE_ANNOTATION
tuple() : base_{} {};
__TUPLE_ANNOTATION
explicit tuple(const Types&... args)
: base_{args...}
{}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
detail::tuple_and<
std::is_constructible<Types,UTypes&&>...
>::value
>::type>
__TUPLE_ANNOTATION
explicit tuple(UTypes&&... args)
: base_{std::forward<UTypes>(args)...}
{}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
detail::tuple_and<
std::is_constructible<Types,const UTypes&>...
>::value
>::type>
__TUPLE_ANNOTATION
tuple(const tuple<UTypes...>& other)
: base_{other.base()}
{}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
detail::tuple_and<
std::is_constructible<Types,UTypes&&>...
>::value
>::type>
__TUPLE_ANNOTATION
tuple(tuple<UTypes...>&& other)
: base_{std::move(other.base())}
{}
template<class UType1, class UType2,
class = typename std::enable_if<
(sizeof...(Types) == 2) &&
detail::tuple_and<
std::is_constructible<detail::tuple_type_at< 0,Types...>,const UType1&>,
std::is_constructible<detail::tuple_type_at<sizeof...(Types) == 2 ? 1 : 0,Types...>,const UType2&>
>::value
>::type>
__TUPLE_ANNOTATION
tuple(const std::pair<UType1,UType2>& p)
: base_{p.first, p.second}
{}
template<class UType1, class UType2,
class = typename std::enable_if<
(sizeof...(Types) == 2) &&
detail::tuple_and<
std::is_constructible<detail::tuple_type_at< 0,Types...>,UType1&&>,
std::is_constructible<detail::tuple_type_at<sizeof...(Types) == 2 ? 1 : 0,Types...>,UType2&&>
>::value
>::type>
__TUPLE_ANNOTATION
tuple(std::pair<UType1,UType2>&& p)
: base_{std::move(p.first), std::move(p.second)}
{}
__TUPLE_ANNOTATION
tuple(const tuple& other)
: base_{other.base()}
{}
__TUPLE_ANNOTATION
tuple(tuple&& other)
: base_{std::move(other.base())}
{}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
detail::tuple_and<
std::is_constructible<Types,const UTypes&>...
>::value
>::type>
__TUPLE_ANNOTATION
tuple(const std::tuple<UTypes...>& other)
: base_{other}
{}
__TUPLE_ANNOTATION
tuple& operator=(const tuple& other)
{
base().operator=(other.base());
return *this;
}
__TUPLE_ANNOTATION
tuple& operator=(tuple&& other)
{
base().operator=(std::move(other.base()));
return *this;
}
// XXX needs enable_if
template<class... UTypes>
__TUPLE_ANNOTATION
tuple& operator=(const tuple<UTypes...>& other)
{
base().operator=(other.base());
return *this;
}
// XXX needs enable_if
template<class... UTypes>
__TUPLE_ANNOTATION
tuple& operator=(tuple<UTypes...>&& other)
{
base().operator=(other.base());
return *this;
}
template<class UType1, class UType2,
class = typename std::enable_if<
(sizeof...(Types) == 2) &&
detail::tuple_and<
std::is_assignable<detail::tuple_type_at< 0,Types...>,const UType1&>,
std::is_assignable<detail::tuple_type_at<sizeof...(Types) == 2 ? 1 : 0,Types...>,const UType2&>
>::value
>::type>
__TUPLE_ANNOTATION
tuple& operator=(const std::pair<UType1,UType2>& p)
{
base().operator=(p);
return *this;
}
template<class UType1, class UType2,
class = typename std::enable_if<
(sizeof...(Types) == 2) &&
detail::tuple_and<
std::is_assignable<detail::tuple_type_at< 0,Types...>,UType1&&>,
std::is_assignable<detail::tuple_type_at<sizeof...(Types) == 2 ? 1 : 0,Types...>,UType2&&>
>::value
>::type>
__TUPLE_ANNOTATION
tuple& operator=(std::pair<UType1,UType2>&& p)
{
base().operator=(std::move(p));
return *this;
}
__TUPLE_ANNOTATION
void swap(tuple& other)
{
base().swap(other.base());
}
// enable conversion to Tuple-like things
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
detail::tuple_and<
std::is_constructible<Types,const UTypes&>...
>::value
>::type>
__TUPLE_ANNOTATION
operator std::tuple<UTypes...> () const
{
return static_cast<std::tuple<UTypes...>>(base());
}
private:
template<class... UTypes>
friend class tuple;
template<size_t i>
__TUPLE_ANNOTATION
const typename std::tuple_element<i,tuple>::type& const_get() const
{
return base().template const_get<i>();
}
template<size_t i>
__TUPLE_ANNOTATION
typename std::tuple_element<i,tuple>::type& mutable_get()
{
return base().template mutable_get<i>();
}
public:
template<size_t i, class... UTypes>
friend __TUPLE_ANNOTATION
typename std::tuple_element<i, __TUPLE_NAMESPACE::tuple<UTypes...>>::type &
std::get(__TUPLE_NAMESPACE::tuple<UTypes...>& t);
template<size_t i, class... UTypes>
friend __TUPLE_ANNOTATION
const typename std::tuple_element<i, __TUPLE_NAMESPACE::tuple<UTypes...>>::type &
std::get(const __TUPLE_NAMESPACE::tuple<UTypes...>& t);
template<size_t i, class... UTypes>
friend __TUPLE_ANNOTATION
typename std::tuple_element<i, __TUPLE_NAMESPACE::tuple<UTypes...>>::type &&
std::get(__TUPLE_NAMESPACE::tuple<UTypes...>&& t);
};
template<>
class tuple<>
{
public:
__TUPLE_ANNOTATION
void swap(tuple&){}
};
template<class... Types>
__TUPLE_ANNOTATION
void swap(tuple<Types...>& a, tuple<Types...>& b)
{
a.swap(b);
}
template<class... Types>
__TUPLE_ANNOTATION
tuple<typename std::decay<Types>::type...> make_tuple(Types&&... args)
{
return tuple<typename std::decay<Types>::type...>(std::forward<Types>(args)...);
}
template<class... Types>
__TUPLE_ANNOTATION
tuple<Types&...> tie(Types&... args)
{
return tuple<Types&...>(args...);
}
template<class... Args>
__TUPLE_ANNOTATION
__TUPLE_NAMESPACE::tuple<Args&&...> forward_as_tuple(Args&&... args)
{
return __TUPLE_NAMESPACE::tuple<Args&&...>(std::forward<Args>(args)...);
}
namespace detail
{
struct tuple_ignore_t
{
template<class T>
__TUPLE_ANNOTATION
const tuple_ignore_t operator=(T&&) const
{
return *this;
}
};
} // end detail
constexpr detail::tuple_ignore_t ignore{};
namespace detail
{
template<size_t I, class T, class... Types>
struct tuple_find_exactly_one_impl;
template<size_t I, class T, class U, class... Types>
struct tuple_find_exactly_one_impl<I,T,U,Types...> : tuple_find_exactly_one_impl<I+1, T, Types...> {};
template<size_t I, class T, class... Types>
struct tuple_find_exactly_one_impl<I,T,T,Types...> : std::integral_constant<size_t, I>
{
static_assert(tuple_find_exactly_one_impl<I,T,Types...>::value == -1, "type can only occur once in type list");
};
template<size_t I, class T>
struct tuple_find_exactly_one_impl<I,T> : std::integral_constant<int, -1> {};
template<class T, class... Types>
struct tuple_find_exactly_one : tuple_find_exactly_one_impl<0,T,Types...>
{
static_assert(int(tuple_find_exactly_one::value) != -1, "type not found in type list");
};
} // end detail
} // end namespace
// implement std::get()
namespace std
{
template<class T, class... Types>
__TUPLE_ANNOTATION
T& get(__TUPLE_NAMESPACE::tuple<Types...>& t)
{
return std::get<__TUPLE_NAMESPACE::detail::tuple_find_exactly_one<T,Types...>::value>(t);
}
template<class T, class... Types>
__TUPLE_ANNOTATION
const T& get(const __TUPLE_NAMESPACE::tuple<Types...>& t)
{
return std::get<__TUPLE_NAMESPACE::detail::tuple_find_exactly_one<T,Types...>::value>(t);
}
template<class T, class... Types>
__TUPLE_ANNOTATION
T&& get(__TUPLE_NAMESPACE::tuple<Types...>&& t)
{
return std::get<__TUPLE_NAMESPACE::detail::tuple_find_exactly_one<T,Types...>::value>(std::move(t));
}
} // end std
// implement relational operators
namespace __TUPLE_NAMESPACE
{
namespace detail
{
__TUPLE_ANNOTATION
inline bool tuple_all()
{
return true;
}
__TUPLE_ANNOTATION
inline bool tuple_all(bool t)
{
return t;
}
template<typename... Bools>
__TUPLE_ANNOTATION
bool tuple_all(bool t, Bools... ts)
{
return t && detail::tuple_all(ts...);
}
} // end detail
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool operator==(const tuple<TTypes...>& t, const tuple<UTypes...>& u);
namespace detail
{
template<class... TTypes, class... UTypes, size_t... I>
__TUPLE_ANNOTATION
bool tuple_eq(const tuple<TTypes...>& t, const tuple<UTypes...>& u, detail::tuple_index_sequence<I...>)
{
return detail::tuple_all((std::get<I>(t) == std::get<I>(u))...);
}
} // end detail
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool operator==(const tuple<TTypes...>& t, const tuple<UTypes...>& u)
{
return detail::tuple_eq(t, u, detail::tuple_make_index_sequence<sizeof...(TTypes)>{});
}
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool operator<(const tuple<TTypes...>& t, const tuple<UTypes...>& u);
namespace detail
{
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool tuple_lt(const tuple<TTypes...>& t, const tuple<UTypes...>& u, tuple_index_sequence<>)
{
return false;
}
template<size_t I, class... TTypes, class... UTypes, size_t... Is>
__TUPLE_ANNOTATION
bool tuple_lt(const tuple<TTypes...>& t, const tuple<UTypes...>& u, tuple_index_sequence<I, Is...>)
{
return ( std::get<I>(t) < std::get<I>(u)
|| (!(std::get<I>(u) < std::get<I>(t))
&& detail::tuple_lt(t, u, typename tuple_make_index_sequence_impl<I+1, tuple_index_sequence<>, sizeof...(TTypes)>::type{})));
}
} // end detail
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool operator<(const tuple<TTypes...>& t, const tuple<UTypes...>& u)
{
return detail::tuple_lt(t, u, detail::tuple_make_index_sequence<sizeof...(TTypes)>{});
}
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool operator!=(const tuple<TTypes...>& t, const tuple<UTypes...>& u)
{
return !(t == u);
}
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool operator>(const tuple<TTypes...>& t, const tuple<UTypes...>& u)
{
return u < t;
}
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool operator<=(const tuple<TTypes...>& t, const tuple<UTypes...>& u)
{
return !(u < t);
}
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool operator>=(const tuple<TTypes...>& t, const tuple<UTypes...>& u)
{
return !(t < u);
}
} // end namespace
#ifdef __TUPLE_ANNOTATION_NEEDS_UNDEF
#undef __TUPLE_ANNOTATION
#undef __TUPLE_ANNOTATION_NEEDS_UNDEF
#endif
#ifdef __TUPLE_NAMESPACE_NEEDS_UNDEF
#undef __TUPLE_NAMESPACE
#undef __TUPLE_NAMESPACE_NEEDS_UNDEF
#endif
#undef __TUPLE_EXEC_CHECK_DISABLE
Update to latest tuple code
// Copyright (c) 2014, NVIDIA CORPORATION. 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.
#pragma once
#include <stddef.h> // XXX instead of <cstddef> to WAR clang issue
#include <type_traits>
#include <utility> // <utility> declares std::tuple_element et al. for us
// allow the user to define an annotation to apply to these functions
// by default, it attempts to be constexpr
#ifndef __TUPLE_ANNOTATION
# if __cplusplus <= 201103L
# define __TUPLE_ANNOTATION
# else
# define __TUPLE_ANNOTATION constexpr
# endif
# define __TUPLE_ANNOTATION_NEEDS_UNDEF
#endif
// define the incantation to silence nvcc errors concerning __host__ __device__ functions
#if defined(__CUDACC__) && !(defined(__CUDA__) && defined(__clang__))
#define __TUPLE_EXEC_CHECK_DISABLE \
#pragma nv_exec_check_disable
#else
#define __TUPLE_EXEC_CHECK_DISABLE
#endif
// allow the user to define a namespace for these functions
#ifndef __TUPLE_NAMESPACE
#define __TUPLE_NAMESPACE std
#define __TUPLE_NAMESPACE_NEEDS_UNDEF
#endif
namespace __TUPLE_NAMESPACE
{
template<class... Types> class tuple;
} // end namespace
// specializations of stuff in std come before their use
namespace std
{
template<size_t i>
struct tuple_element<i, __TUPLE_NAMESPACE::tuple<>> {};
template<class Type1, class... Types>
struct tuple_element<0, __TUPLE_NAMESPACE::tuple<Type1,Types...>>
{
using type = Type1;
};
template<size_t i, class Type1, class... Types>
struct tuple_element<i, __TUPLE_NAMESPACE::tuple<Type1,Types...>>
{
using type = typename tuple_element<i - 1, __TUPLE_NAMESPACE::tuple<Types...>>::type;
};
template<class... Types>
struct tuple_size<__TUPLE_NAMESPACE::tuple<Types...>>
: std::integral_constant<size_t, sizeof...(Types)>
{};
} // end std
namespace __TUPLE_NAMESPACE
{
namespace detail
{
// define variadic "and" operator
template <typename... Conditions>
struct tuple_and;
template<>
struct tuple_and<>
: public std::true_type
{
};
template <typename Condition, typename... Conditions>
struct tuple_and<Condition, Conditions...>
: public std::integral_constant<
bool,
Condition::value && tuple_and<Conditions...>::value>
{
};
// XXX this implementation is based on Howard Hinnant's "tuple leaf" construction in libcxx
// define index sequence in case it is missing
// prefix this stuff with "tuple" to avoid collisions with other implementations
template<size_t... I> struct tuple_index_sequence {};
template<size_t Start, typename Indices, size_t End>
struct tuple_make_index_sequence_impl;
template<size_t Start, size_t... Indices, size_t End>
struct tuple_make_index_sequence_impl<
Start,
tuple_index_sequence<Indices...>,
End
>
{
typedef typename tuple_make_index_sequence_impl<
Start + 1,
tuple_index_sequence<Indices..., Start>,
End
>::type type;
};
template<size_t End, size_t... Indices>
struct tuple_make_index_sequence_impl<End, tuple_index_sequence<Indices...>, End>
{
typedef tuple_index_sequence<Indices...> type;
};
template<size_t N>
using tuple_make_index_sequence = typename tuple_make_index_sequence_impl<0, tuple_index_sequence<>, N>::type;
template<class T>
struct tuple_use_empty_base_class_optimization
: std::integral_constant<
bool,
std::is_empty<T>::value
#if __cplusplus >= 201402L
&& !std::is_final<T>::value
#endif
>
{};
template<class T, bool = tuple_use_empty_base_class_optimization<T>::value>
class tuple_leaf_base
{
public:
__TUPLE_EXEC_CHECK_DISABLE
__TUPLE_ANNOTATION
tuple_leaf_base() = default;
__TUPLE_EXEC_CHECK_DISABLE
template<class U>
__TUPLE_ANNOTATION
tuple_leaf_base(U&& arg) : val_(std::forward<U>(arg)) {}
__TUPLE_ANNOTATION
const T& const_get() const
{
return val_;
}
__TUPLE_ANNOTATION
T& mutable_get()
{
return val_;
}
private:
T val_;
};
template<class T>
class tuple_leaf_base<T,true> : public T
{
public:
__TUPLE_ANNOTATION
tuple_leaf_base() = default;
template<class U>
__TUPLE_ANNOTATION
tuple_leaf_base(U&& arg) : T(std::forward<U>(arg)) {}
__TUPLE_ANNOTATION
const T& const_get() const
{
return *this;
}
__TUPLE_ANNOTATION
T& mutable_get()
{
return *this;
}
};
template<size_t I, class T>
class tuple_leaf : public tuple_leaf_base<T>
{
private:
using super_t = tuple_leaf_base<T>;
public:
__TUPLE_ANNOTATION
tuple_leaf() = default;
template<class U,
class = typename std::enable_if<
std::is_constructible<T,U>::value
>::type>
__TUPLE_ANNOTATION
tuple_leaf(U&& arg) : super_t(std::forward<U>(arg)) {}
__TUPLE_ANNOTATION
tuple_leaf(const tuple_leaf& other) : super_t(other.const_get()) {}
__TUPLE_ANNOTATION
tuple_leaf(tuple_leaf&& other) : super_t(std::forward<T>(other.mutable_get())) {}
template<class U,
class = typename std::enable_if<
std::is_constructible<T,const U&>::value
>::type>
__TUPLE_ANNOTATION
tuple_leaf(const tuple_leaf<I,U>& other) : super_t(other.const_get()) {}
// converting move-constructor
// note the use of std::forward<U> here to allow construction of T from U&&
template<class U,
class = typename std::enable_if<
std::is_constructible<T,U&&>::value
>::type>
__TUPLE_ANNOTATION
tuple_leaf(tuple_leaf<I,U>&& other) : super_t(std::forward<U>(other.mutable_get())) {}
__TUPLE_EXEC_CHECK_DISABLE
template<class U,
class = typename std::enable_if<
std::is_assignable<T,U>::value
>::type>
__TUPLE_ANNOTATION
tuple_leaf& operator=(const tuple_leaf<I,U>& other)
{
this->mutable_get() = other.const_get();
return *this;
}
__TUPLE_EXEC_CHECK_DISABLE
__TUPLE_ANNOTATION
tuple_leaf& operator=(const tuple_leaf& other)
{
this->mutable_get() = other.const_get();
return *this;
}
__TUPLE_EXEC_CHECK_DISABLE
__TUPLE_ANNOTATION
tuple_leaf& operator=(tuple_leaf&& other)
{
this->mutable_get() = std::forward<T>(other.mutable_get());
return *this;
}
__TUPLE_EXEC_CHECK_DISABLE
template<class U,
class = typename std::enable_if<
std::is_assignable<T,U&&>::value
>::type>
__TUPLE_ANNOTATION
tuple_leaf& operator=(tuple_leaf<I,U>&& other)
{
this->mutable_get() = std::forward<U>(other.mutable_get());
return *this;
}
__TUPLE_EXEC_CHECK_DISABLE
__TUPLE_ANNOTATION
int swap(tuple_leaf& other)
{
using std::swap;
swap(this->mutable_get(), other.mutable_get());
return 0;
}
};
template<class... Args>
struct tuple_type_list {};
template<size_t i, class... Args>
struct tuple_type_at_impl;
template<size_t i, class Arg0, class... Args>
struct tuple_type_at_impl<i, Arg0, Args...>
{
using type = typename tuple_type_at_impl<i-1, Args...>::type;
};
template<class Arg0, class... Args>
struct tuple_type_at_impl<0, Arg0,Args...>
{
using type = Arg0;
};
template<size_t i, class... Args>
using tuple_type_at = typename tuple_type_at_impl<i,Args...>::type;
template<class IndexSequence, class... Args>
class tuple_base;
template<size_t... I, class... Types>
class tuple_base<tuple_index_sequence<I...>, Types...>
: public tuple_leaf<I,Types>...
{
public:
using leaf_types = tuple_type_list<tuple_leaf<I,Types>...>;
__TUPLE_ANNOTATION
tuple_base() = default;
__TUPLE_ANNOTATION
tuple_base(const Types&... args)
: tuple_leaf<I,Types>(args)...
{}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
tuple_and<
std::is_constructible<Types,UTypes&&>...
>::value
>::type>
__TUPLE_ANNOTATION
explicit tuple_base(UTypes&&... args)
: tuple_leaf<I,Types>(std::forward<UTypes>(args))...
{}
__TUPLE_ANNOTATION
tuple_base(const tuple_base& other)
: tuple_leaf<I,Types>(other.template const_leaf<I>())...
{}
__TUPLE_ANNOTATION
tuple_base(tuple_base&& other)
: tuple_leaf<I,Types>(std::move(other.template mutable_leaf<I>()))...
{}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
tuple_and<
std::is_constructible<Types,const UTypes&>...
>::value
>::type>
__TUPLE_ANNOTATION
tuple_base(const tuple_base<tuple_index_sequence<I...>,UTypes...>& other)
: tuple_leaf<I,Types>(other.template const_leaf<I>())...
{}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
tuple_and<
std::is_constructible<Types,UTypes&&>...
>::value
>::type>
__TUPLE_ANNOTATION
tuple_base(tuple_base<tuple_index_sequence<I...>,UTypes...>&& other)
: tuple_leaf<I,Types>(std::move(other.template mutable_leaf<I>()))...
{}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
tuple_and<
std::is_constructible<Types,const UTypes&>...
>::value
>::type>
__TUPLE_ANNOTATION
tuple_base(const std::tuple<UTypes...>& other)
: tuple_base{std::get<I>(other)...}
{}
__TUPLE_ANNOTATION
tuple_base& operator=(const tuple_base& other)
{
swallow((mutable_leaf<I>() = other.template const_leaf<I>())...);
return *this;
}
__TUPLE_ANNOTATION
tuple_base& operator=(tuple_base&& other)
{
swallow((mutable_leaf<I>() = std::move(other.template mutable_leaf<I>()))...);
return *this;
}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
tuple_and<
std::is_assignable<Types,const UTypes&>...
>::value
>::type>
__TUPLE_ANNOTATION
tuple_base& operator=(const tuple_base<tuple_index_sequence<I...>,UTypes...>& other)
{
swallow((mutable_leaf<I>() = other.template const_leaf<I>())...);
return *this;
}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
tuple_and<
std::is_assignable<Types,UTypes&&>...
>::value
>::type>
__TUPLE_ANNOTATION
tuple_base& operator=(tuple_base<tuple_index_sequence<I...>,UTypes...>&& other)
{
swallow((mutable_leaf<I>() = std::move(other.template mutable_leaf<I>()))...);
return *this;
}
template<class UType1, class UType2,
class = typename std::enable_if<
(sizeof...(Types) == 2) &&
tuple_and<
std::is_assignable<tuple_type_at< 0,Types...>,const UType1&>,
std::is_assignable<tuple_type_at<sizeof...(Types) == 2 ? 1 : 0,Types...>,const UType2&>
>::value
>::type>
__TUPLE_ANNOTATION
tuple_base& operator=(const std::pair<UType1,UType2>& p)
{
mutable_get<0>() = p.first;
mutable_get<1>() = p.second;
return *this;
}
template<class UType1, class UType2,
class = typename std::enable_if<
(sizeof...(Types) == 2) &&
tuple_and<
std::is_assignable<tuple_type_at< 0,Types...>,UType1&&>,
std::is_assignable<tuple_type_at<sizeof...(Types) == 2 ? 1 : 0,Types...>,UType2&&>
>::value
>::type>
__TUPLE_ANNOTATION
tuple_base& operator=(std::pair<UType1,UType2>&& p)
{
mutable_get<0>() = std::move(p.first);
mutable_get<1>() = std::move(p.second);
return *this;
}
template<size_t i>
__TUPLE_ANNOTATION
const tuple_leaf<i,tuple_type_at<i,Types...>>& const_leaf() const
{
return *this;
}
template<size_t i>
__TUPLE_ANNOTATION
tuple_leaf<i,tuple_type_at<i,Types...>>& mutable_leaf()
{
return *this;
}
template<size_t i>
__TUPLE_ANNOTATION
tuple_leaf<i,tuple_type_at<i,Types...>>&& move_leaf() &&
{
return std::move(*this);
}
__TUPLE_ANNOTATION
void swap(tuple_base& other)
{
swallow(tuple_leaf<I,Types>::swap(other)...);
}
template<size_t i>
__TUPLE_ANNOTATION
const tuple_type_at<i,Types...>& const_get() const
{
return const_leaf<i>().const_get();
}
template<size_t i>
__TUPLE_ANNOTATION
tuple_type_at<i,Types...>& mutable_get()
{
return mutable_leaf<i>().mutable_get();
}
// enable conversion to Tuple-like things
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
tuple_and<
std::is_constructible<Types,const UTypes&>...
>::value
>::type>
__TUPLE_ANNOTATION
operator std::tuple<UTypes...> () const
{
return std::tuple<UTypes...>(const_get<I>()...);
}
private:
template<class... Args>
__TUPLE_ANNOTATION
static void swallow(Args&&...) {}
};
} // end detail
} // end namespace
// implement std::get()
namespace std
{
template<size_t i, class... UTypes>
__TUPLE_ANNOTATION
typename std::tuple_element<i, __TUPLE_NAMESPACE::tuple<UTypes...>>::type &
get(__TUPLE_NAMESPACE::tuple<UTypes...>& t)
{
return t.template mutable_get<i>();
}
template<size_t i, class... UTypes>
__TUPLE_ANNOTATION
const typename std::tuple_element<i, __TUPLE_NAMESPACE::tuple<UTypes...>>::type &
get(const __TUPLE_NAMESPACE::tuple<UTypes...>& t)
{
return t.template const_get<i>();
}
template<size_t i, class... UTypes>
__TUPLE_ANNOTATION
typename std::tuple_element<i, __TUPLE_NAMESPACE::tuple<UTypes...>>::type &&
get(__TUPLE_NAMESPACE::tuple<UTypes...>&& t)
{
using type = typename std::tuple_element<i, __TUPLE_NAMESPACE::tuple<UTypes...>>::type;
auto&& leaf = static_cast<__TUPLE_NAMESPACE::detail::tuple_leaf<i,type>&&>(t.base());
return static_cast<type&&>(leaf.mutable_get());
}
} // end std
namespace __TUPLE_NAMESPACE
{
template<class... Types>
class tuple
{
private:
using base_type = detail::tuple_base<detail::tuple_make_index_sequence<sizeof...(Types)>, Types...>;
base_type base_;
__TUPLE_ANNOTATION
base_type& base()
{
return base_;
}
__TUPLE_ANNOTATION
const base_type& base() const
{
return base_;
}
public:
__TUPLE_ANNOTATION
tuple() : base_{} {};
__TUPLE_ANNOTATION
explicit tuple(const Types&... args)
: base_{args...}
{}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
detail::tuple_and<
std::is_constructible<Types,UTypes&&>...
>::value
>::type>
__TUPLE_ANNOTATION
explicit tuple(UTypes&&... args)
: base_{std::forward<UTypes>(args)...}
{}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
detail::tuple_and<
std::is_constructible<Types,const UTypes&>...
>::value
>::type>
__TUPLE_ANNOTATION
tuple(const tuple<UTypes...>& other)
: base_{other.base()}
{}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
detail::tuple_and<
std::is_constructible<Types,UTypes&&>...
>::value
>::type>
__TUPLE_ANNOTATION
tuple(tuple<UTypes...>&& other)
: base_{std::move(other.base())}
{}
template<class UType1, class UType2,
class = typename std::enable_if<
(sizeof...(Types) == 2) &&
detail::tuple_and<
std::is_constructible<detail::tuple_type_at< 0,Types...>,const UType1&>,
std::is_constructible<detail::tuple_type_at<sizeof...(Types) == 2 ? 1 : 0,Types...>,const UType2&>
>::value
>::type>
__TUPLE_ANNOTATION
tuple(const std::pair<UType1,UType2>& p)
: base_{p.first, p.second}
{}
template<class UType1, class UType2,
class = typename std::enable_if<
(sizeof...(Types) == 2) &&
detail::tuple_and<
std::is_constructible<detail::tuple_type_at< 0,Types...>,UType1&&>,
std::is_constructible<detail::tuple_type_at<sizeof...(Types) == 2 ? 1 : 0,Types...>,UType2&&>
>::value
>::type>
__TUPLE_ANNOTATION
tuple(std::pair<UType1,UType2>&& p)
: base_{std::move(p.first), std::move(p.second)}
{}
__TUPLE_ANNOTATION
tuple(const tuple& other)
: base_{other.base()}
{}
__TUPLE_ANNOTATION
tuple(tuple&& other)
: base_{std::move(other.base())}
{}
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
detail::tuple_and<
std::is_constructible<Types,const UTypes&>...
>::value
>::type>
__TUPLE_ANNOTATION
tuple(const std::tuple<UTypes...>& other)
: base_{other}
{}
__TUPLE_ANNOTATION
tuple& operator=(const tuple& other)
{
base().operator=(other.base());
return *this;
}
__TUPLE_ANNOTATION
tuple& operator=(tuple&& other)
{
base().operator=(std::move(other.base()));
return *this;
}
// XXX needs enable_if
template<class... UTypes>
__TUPLE_ANNOTATION
tuple& operator=(const tuple<UTypes...>& other)
{
base().operator=(other.base());
return *this;
}
// XXX needs enable_if
template<class... UTypes>
__TUPLE_ANNOTATION
tuple& operator=(tuple<UTypes...>&& other)
{
base().operator=(other.base());
return *this;
}
template<class UType1, class UType2,
class = typename std::enable_if<
(sizeof...(Types) == 2) &&
detail::tuple_and<
std::is_assignable<detail::tuple_type_at< 0,Types...>,const UType1&>,
std::is_assignable<detail::tuple_type_at<sizeof...(Types) == 2 ? 1 : 0,Types...>,const UType2&>
>::value
>::type>
__TUPLE_ANNOTATION
tuple& operator=(const std::pair<UType1,UType2>& p)
{
base().operator=(p);
return *this;
}
template<class UType1, class UType2,
class = typename std::enable_if<
(sizeof...(Types) == 2) &&
detail::tuple_and<
std::is_assignable<detail::tuple_type_at< 0,Types...>,UType1&&>,
std::is_assignable<detail::tuple_type_at<sizeof...(Types) == 2 ? 1 : 0,Types...>,UType2&&>
>::value
>::type>
__TUPLE_ANNOTATION
tuple& operator=(std::pair<UType1,UType2>&& p)
{
base().operator=(std::move(p));
return *this;
}
__TUPLE_ANNOTATION
void swap(tuple& other)
{
base().swap(other.base());
}
// enable conversion to Tuple-like things
template<class... UTypes,
class = typename std::enable_if<
(sizeof...(Types) == sizeof...(UTypes)) &&
detail::tuple_and<
std::is_constructible<Types,const UTypes&>...
>::value
>::type>
__TUPLE_ANNOTATION
operator std::tuple<UTypes...> () const
{
return static_cast<std::tuple<UTypes...>>(base());
}
private:
template<class... UTypes>
friend class tuple;
template<size_t i>
__TUPLE_ANNOTATION
const typename std::tuple_element<i,tuple>::type& const_get() const
{
return base().template const_get<i>();
}
template<size_t i>
__TUPLE_ANNOTATION
typename std::tuple_element<i,tuple>::type& mutable_get()
{
return base().template mutable_get<i>();
}
public:
template<size_t i, class... UTypes>
friend __TUPLE_ANNOTATION
typename std::tuple_element<i, __TUPLE_NAMESPACE::tuple<UTypes...>>::type &
std::get(__TUPLE_NAMESPACE::tuple<UTypes...>& t);
template<size_t i, class... UTypes>
friend __TUPLE_ANNOTATION
const typename std::tuple_element<i, __TUPLE_NAMESPACE::tuple<UTypes...>>::type &
std::get(const __TUPLE_NAMESPACE::tuple<UTypes...>& t);
template<size_t i, class... UTypes>
friend __TUPLE_ANNOTATION
typename std::tuple_element<i, __TUPLE_NAMESPACE::tuple<UTypes...>>::type &&
std::get(__TUPLE_NAMESPACE::tuple<UTypes...>&& t);
};
template<>
class tuple<>
{
public:
__TUPLE_ANNOTATION
void swap(tuple&){}
};
template<class... Types>
__TUPLE_ANNOTATION
void swap(tuple<Types...>& a, tuple<Types...>& b)
{
a.swap(b);
}
template<class... Types>
__TUPLE_ANNOTATION
tuple<typename std::decay<Types>::type...> make_tuple(Types&&... args)
{
return tuple<typename std::decay<Types>::type...>(std::forward<Types>(args)...);
}
template<class... Types>
__TUPLE_ANNOTATION
tuple<Types&...> tie(Types&... args)
{
return tuple<Types&...>(args...);
}
template<class... Args>
__TUPLE_ANNOTATION
__TUPLE_NAMESPACE::tuple<Args&&...> forward_as_tuple(Args&&... args)
{
return __TUPLE_NAMESPACE::tuple<Args&&...>(std::forward<Args>(args)...);
}
namespace detail
{
struct tuple_ignore_t
{
template<class T>
__TUPLE_ANNOTATION
const tuple_ignore_t operator=(T&&) const
{
return *this;
}
};
} // end detail
constexpr detail::tuple_ignore_t ignore{};
namespace detail
{
template<size_t I, class T, class... Types>
struct tuple_find_exactly_one_impl;
template<size_t I, class T, class U, class... Types>
struct tuple_find_exactly_one_impl<I,T,U,Types...> : tuple_find_exactly_one_impl<I+1, T, Types...> {};
template<size_t I, class T, class... Types>
struct tuple_find_exactly_one_impl<I,T,T,Types...> : std::integral_constant<size_t, I>
{
static_assert(tuple_find_exactly_one_impl<I,T,Types...>::value == -1, "type can only occur once in type list");
};
template<size_t I, class T>
struct tuple_find_exactly_one_impl<I,T> : std::integral_constant<int, -1> {};
template<class T, class... Types>
struct tuple_find_exactly_one : tuple_find_exactly_one_impl<0,T,Types...>
{
static_assert(int(tuple_find_exactly_one::value) != -1, "type not found in type list");
};
} // end detail
} // end namespace
// implement std::get()
namespace std
{
template<class T, class... Types>
__TUPLE_ANNOTATION
T& get(__TUPLE_NAMESPACE::tuple<Types...>& t)
{
return std::get<__TUPLE_NAMESPACE::detail::tuple_find_exactly_one<T,Types...>::value>(t);
}
template<class T, class... Types>
__TUPLE_ANNOTATION
const T& get(const __TUPLE_NAMESPACE::tuple<Types...>& t)
{
return std::get<__TUPLE_NAMESPACE::detail::tuple_find_exactly_one<T,Types...>::value>(t);
}
template<class T, class... Types>
__TUPLE_ANNOTATION
T&& get(__TUPLE_NAMESPACE::tuple<Types...>&& t)
{
return std::get<__TUPLE_NAMESPACE::detail::tuple_find_exactly_one<T,Types...>::value>(std::move(t));
}
} // end std
// implement relational operators
namespace __TUPLE_NAMESPACE
{
namespace detail
{
__TUPLE_ANNOTATION
inline bool tuple_all()
{
return true;
}
__TUPLE_ANNOTATION
inline bool tuple_all(bool t)
{
return t;
}
template<typename... Bools>
__TUPLE_ANNOTATION
bool tuple_all(bool t, Bools... ts)
{
return t && detail::tuple_all(ts...);
}
} // end detail
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool operator==(const tuple<TTypes...>& t, const tuple<UTypes...>& u);
namespace detail
{
template<class... TTypes, class... UTypes, size_t... I>
__TUPLE_ANNOTATION
bool tuple_eq(const tuple<TTypes...>& t, const tuple<UTypes...>& u, detail::tuple_index_sequence<I...>)
{
return detail::tuple_all((std::get<I>(t) == std::get<I>(u))...);
}
} // end detail
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool operator==(const tuple<TTypes...>& t, const tuple<UTypes...>& u)
{
return detail::tuple_eq(t, u, detail::tuple_make_index_sequence<sizeof...(TTypes)>{});
}
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool operator<(const tuple<TTypes...>& t, const tuple<UTypes...>& u);
namespace detail
{
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool tuple_lt(const tuple<TTypes...>& t, const tuple<UTypes...>& u, tuple_index_sequence<>)
{
return false;
}
template<size_t I, class... TTypes, class... UTypes, size_t... Is>
__TUPLE_ANNOTATION
bool tuple_lt(const tuple<TTypes...>& t, const tuple<UTypes...>& u, tuple_index_sequence<I, Is...>)
{
return ( std::get<I>(t) < std::get<I>(u)
|| (!(std::get<I>(u) < std::get<I>(t))
&& detail::tuple_lt(t, u, typename tuple_make_index_sequence_impl<I+1, tuple_index_sequence<>, sizeof...(TTypes)>::type{})));
}
} // end detail
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool operator<(const tuple<TTypes...>& t, const tuple<UTypes...>& u)
{
return detail::tuple_lt(t, u, detail::tuple_make_index_sequence<sizeof...(TTypes)>{});
}
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool operator!=(const tuple<TTypes...>& t, const tuple<UTypes...>& u)
{
return !(t == u);
}
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool operator>(const tuple<TTypes...>& t, const tuple<UTypes...>& u)
{
return u < t;
}
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool operator<=(const tuple<TTypes...>& t, const tuple<UTypes...>& u)
{
return !(u < t);
}
template<class... TTypes, class... UTypes>
__TUPLE_ANNOTATION
bool operator>=(const tuple<TTypes...>& t, const tuple<UTypes...>& u)
{
return !(t < u);
}
} // end namespace
#ifdef __TUPLE_ANNOTATION_NEEDS_UNDEF
#undef __TUPLE_ANNOTATION
#undef __TUPLE_ANNOTATION_NEEDS_UNDEF
#endif
#ifdef __TUPLE_NAMESPACE_NEEDS_UNDEF
#undef __TUPLE_NAMESPACE
#undef __TUPLE_NAMESPACE_NEEDS_UNDEF
#endif
#undef __TUPLE_EXEC_CHECK_DISABLE
|
delete
|
/*
This file is part of Akregator.
Copyright (C) 2004 Stanislav Karchebny <Stanislav.Karchebny@kdemail.net>
2004 Sashmit Bhaduri <smt@vfemail.net>
2005 Frank Osterfeld <osterfeld@kde.org>
This program 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.
This program 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 program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "mainwidget.h"
#include "actionmanagerimpl.h"
#include "addfeeddialog.h"
#include "articlelistview.h"
#include "articleviewer.h"
#include "articlejobs.h"
#include "akregatorconfig.h"
#include "akregator_part.h"
#include "browserframe.h"
#include "createfeedcommand.h"
#include "createfoldercommand.h"
#include "deletesubscriptioncommand.h"
#include "editsubscriptioncommand.h"
#include "expireitemscommand.h"
#include "feed.h"
#include "feedlist.h"
#include "feedpropertiesdialog.h"
#include "fetchqueue.h"
#include "folder.h"
#include "framemanager.h"
#include "kernel.h"
#include "notificationmanager.h"
#include "openurlrequest.h"
#include "progressmanager.h"
#include "searchbar.h"
#include "selectioncontroller.h"
//#include "speechclient.h"
#include "subscriptionlistjobs.h"
#include "subscriptionlistmodel.h"
#include "subscriptionlistview.h"
#include "tabwidget.h"
#include "treenode.h"
#include "treenodevisitor.h"
#include "types.h"
#include <solid/networking.h>
#include <kaction.h>
#include <kdialog.h>
#include <KDebug>
#include <kfiledialog.h>
#include <kfileitem.h>
#include <kiconloader.h>
#include <kinputdialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <krandom.h>
#include <kshell.h>
#include <kstandarddirs.h>
#include <ktoggleaction.h>
#include <ktoolinvocation.h>
#include <kurl.h>
#include <QClipboard>
#include <QPixmap>
#include <QSplitter>
#include <QTextDocument>
#include <QDomDocument>
#include <QTimer>
#include <algorithm>
#include <memory>
#include <cassert>
using namespace Akregator;
using namespace Solid;
Akregator::MainWidget::~MainWidget()
{
// if m_shuttingDown is false, slotOnShutdown was not called. That
// means that not the whole app is shutdown, only the part. So it
// should be no risk to do the cleanups now
if (!m_shuttingDown)
slotOnShutdown();
}
Akregator::MainWidget::MainWidget( Part *part, QWidget *parent, ActionManagerImpl* actionManager, const char *name)
: QWidget(parent),
m_feedList( 0 ),
m_viewMode(NormalView),
m_actionManager(actionManager),
m_feedListManagementInterface( new FeedListManagementImpl )
{
setObjectName(name);
FeedListManagementInterface::setInstance( m_feedListManagementInterface );
m_actionManager->initMainWidget(this);
m_actionManager->initFrameManager(Kernel::self()->frameManager());
m_part = part;
m_shuttingDown = false;
m_displayingAboutPage = false;
setFocusPolicy(Qt::StrongFocus);
QVBoxLayout *lt = new QVBoxLayout( this );
lt->setMargin(0);
m_horizontalSplitter = new QSplitter(Qt::Horizontal, this);
m_horizontalSplitter->setOpaqueResize(true);
lt->addWidget(m_horizontalSplitter);
connect(Kernel::self()->fetchQueue(), SIGNAL(fetched(Akregator::Feed*)),
this, SLOT(slotFeedFetched(Akregator::Feed*)));
connect(Kernel::self()->fetchQueue(), SIGNAL(signalStarted()),
this, SLOT(slotFetchingStarted()));
connect(Kernel::self()->fetchQueue(), SIGNAL(signalStopped()),
this, SLOT(slotFetchingStopped()));
m_feedListView = new SubscriptionListView( m_horizontalSplitter );
m_feedListView->setObjectName( "feedtree" );
m_actionManager->initSubscriptionListView( m_feedListView );
connect(m_feedListView, SIGNAL(signalContextMenu(K3ListView*, Akregator::TreeNode*, const QPoint&)),
this, SLOT(slotFeedTreeContextMenu(K3ListView*, Akregator::TreeNode*, const QPoint&)));
connect(m_feedListView, SIGNAL(signalDropped (KUrl::List &, Akregator::TreeNode*,
Akregator::Folder*)),
this, SLOT(slotFeedUrlDropped (KUrl::List &,
Akregator::TreeNode*, Akregator::Folder*)));
m_tabWidget = new TabWidget(m_horizontalSplitter);
m_actionManager->initTabWidget(m_tabWidget);
connect( m_part, SIGNAL(signalSettingsChanged()),
m_tabWidget, SLOT(slotSettingsChanged()));
connect( m_tabWidget, SIGNAL(signalCurrentFrameChanged(int)),
Kernel::self()->frameManager(), SLOT(slotChangeFrame(int)));
connect( m_tabWidget, SIGNAL(signalRemoveFrameRequest(int)),
Kernel::self()->frameManager(), SLOT(slotRemoveFrame(int)));
connect( m_tabWidget, SIGNAL(signalOpenUrlRequest(Akregator::OpenUrlRequest&)),
Kernel::self()->frameManager(), SLOT(slotOpenUrlRequest(Akregator::OpenUrlRequest&)));
connect( Kernel::self()->frameManager(), SIGNAL(signalFrameAdded(Akregator::Frame*)),
m_tabWidget, SLOT(slotAddFrame(Akregator::Frame*)));
connect( Kernel::self()->frameManager(), SIGNAL(signalSelectFrame(int)),
m_tabWidget, SLOT(slotSelectFrame(int)) );
connect( Kernel::self()->frameManager(), SIGNAL(signalFrameRemoved(int)),
m_tabWidget, SLOT(slotRemoveFrame(int)));
connect( Kernel::self()->frameManager(), SIGNAL(signalRequestNewFrame(int&)),
this, SLOT( slotRequestNewFrame(int&) ) );
m_tabWidget->setWhatsThis( i18n("You can view multiple articles in several open tabs."));
m_mainTab = new QWidget(this);
m_mainTab->setObjectName("Article Tab");
m_mainTab->setWhatsThis( i18n("Articles list."));
QVBoxLayout *mainTabLayout = new QVBoxLayout( m_mainTab);
mainTabLayout->setMargin(0);
m_searchBar = new SearchBar(m_mainTab);
if ( !Settings::showQuickFilter() )
m_searchBar->hide();
mainTabLayout->addWidget(m_searchBar);
m_articleSplitter = new QSplitter(Qt::Vertical, m_mainTab);
m_articleSplitter->setObjectName("panner2");
m_articleListView = new ArticleListView( m_articleSplitter );
m_selectionController = new SelectionController( this );
m_selectionController->setArticleLister( m_articleListView );
m_selectionController->setFeedSelector( m_feedListView );
connect(m_searchBar, SIGNAL( signalSearch( std::vector<boost::shared_ptr<const Akregator::Filters::AbstractMatcher> > ) ),
m_selectionController, SLOT( setFilters( std::vector<boost::shared_ptr<const Akregator::Filters::AbstractMatcher> > ) ) );
FolderExpansionHandler* expansionHandler = new FolderExpansionHandler( this );
connect( m_feedListView, SIGNAL( expanded( QModelIndex ) ), expansionHandler, SLOT( itemExpanded( QModelIndex ) ) );
connect( m_feedListView, SIGNAL( collapsed( QModelIndex ) ), expansionHandler, SLOT( itemCollapsed( QModelIndex ) ) );
m_selectionController->setFolderExpansionHandler( expansionHandler );
connect( m_selectionController, SIGNAL( currentSubscriptionChanged( Akregator::TreeNode* ) ),
this, SLOT( slotNodeSelected( Akregator::TreeNode* ) ) );
connect( m_selectionController, SIGNAL( currentArticleChanged( Akregator::Article ) ),
this, SLOT( slotArticleSelected( Akregator::Article ) ) );
connect( m_selectionController, SIGNAL( articleDoubleClicked( Akregator::Article ) ),
this, SLOT( slotOpenArticleInBrowser( Akregator::Article )) );
m_actionManager->initArticleListView(m_articleListView);
connect( m_articleListView, SIGNAL(signalMouseButtonPressed(int, KUrl )),
this, SLOT(slotMouseButtonPressed(int, KUrl )));
connect( m_part, SIGNAL(signalSettingsChanged()),
m_articleListView, SLOT(slotPaletteOrFontChanged()));
m_articleViewer = new ArticleViewer(m_articleSplitter);
m_actionManager->initArticleViewer(m_articleViewer);
m_articleListView->setFocusProxy(m_articleViewer);
connect( m_articleViewer, SIGNAL(signalOpenUrlRequest(Akregator::OpenUrlRequest& )),
Kernel::self()->frameManager(), SLOT(slotOpenUrlRequest( Akregator::OpenUrlRequest& )) );
connect( m_articleViewer->part()->browserExtension(), SIGNAL(mouseOverInfo( KFileItem )),
this, SLOT(slotMouseOverInfo( KFileItem )) );
connect( m_part, SIGNAL(signalSettingsChanged()),
m_articleViewer, SLOT(slotPaletteOrFontChanged()));
connect(m_searchBar, SIGNAL( signalSearch( std::vector<boost::shared_ptr<const Akregator::Filters::AbstractMatcher> > ) ),
m_articleViewer, SLOT( setFilters( std::vector<boost::shared_ptr<const Akregator::Filters::AbstractMatcher> > ) ) );
m_articleViewer->part()->widget()->setWhatsThis( i18n("Browsing area."));
mainTabLayout->addWidget( m_articleSplitter );
m_mainFrame = new MainFrame(this, m_part, m_mainTab, i18n("Articles"));
Kernel::self()->frameManager()->slotAddFrame(m_mainFrame);
const QList<int> sp1sizes = Settings::splitter1Sizes();
if ( sp1sizes.count() >= m_horizontalSplitter->count() )
m_horizontalSplitter->setSizes( sp1sizes );
const QList<int> sp2sizes = Settings::splitter2Sizes();
if ( sp2sizes.count() >= m_articleSplitter->count() )
m_articleSplitter->setSizes( sp2sizes );
KConfigGroup conf(Settings::self()->config(), "General");
if(!conf.readEntry("Disable Introduction", false))
{
m_articleListView->hide();
m_searchBar->hide();
m_articleViewer->displayAboutPage();
m_mainFrame->slotSetTitle(i18n("About"));
m_displayingAboutPage = true;
}
m_fetchTimer = new QTimer(this);
connect( m_fetchTimer, SIGNAL(timeout()),
this, SLOT(slotDoIntervalFetches()) );
m_fetchTimer->start(1000*60);
// delete expired articles once per hour
m_expiryTimer = new QTimer(this);
connect(m_expiryTimer, SIGNAL(timeout()),
this, SLOT(slotDeleteExpiredArticles()) );
m_expiryTimer->start(3600*1000);
m_markReadTimer = new QTimer(this);
m_markReadTimer->setSingleShot(true);
connect(m_markReadTimer, SIGNAL(timeout()), this, SLOT(slotSetCurrentArticleReadDelayed()) );
setFeedList( new FeedList( Kernel::self()->storage() ) );
switch (Settings::viewMode())
{
case CombinedView:
slotCombinedView();
break;
case WidescreenView:
slotWidescreenView();
break;
default:
slotNormalView();
}
if ( !Settings::resetQuickFilterOnNodeChange() )
{
m_searchBar->slotSetStatus( Settings::statusFilter() );
m_searchBar->slotSetText( Settings::textFilter() );
}
}
void Akregator::MainWidget::slotOnShutdown()
{
m_shuttingDown = true;
Kernel::self()->fetchQueue()->slotAbort();
setFeedList( 0 );
delete m_feedListManagementInterface;
delete m_feedListView; // call delete here, so that the header settings will get saved
delete m_articleListView; // same for this one
// close all pageviewers in a controlled way
// fixes bug 91660, at least when no part loading data
m_tabWidget->setCurrentIndex(m_tabWidget->count()-1); // select last page
while (m_tabWidget->count() > 1) // remove frames until only the main frame remains
m_tabWidget->slotRemoveCurrentFrame();
delete m_mainTab;
delete m_mainFrame;
Settings::self()->writeConfig();
}
void Akregator::MainWidget::saveSettings()
{
const QList<int> spl1 = m_horizontalSplitter->sizes();
if ( std::count( spl1.begin(), spl1.end(), 0 ) == 0 )
Settings::setSplitter1Sizes( spl1 );
const QList<int> spl2 = m_articleSplitter->sizes();
if ( std::count( spl2.begin(), spl2.end(), 0 ) == 0 )
Settings::setSplitter2Sizes( spl2 );
Settings::setViewMode( m_viewMode );
Settings::self()->writeConfig();
}
void Akregator::MainWidget::slotRequestNewFrame(int& frameId)
{
BrowserFrame* frame = new BrowserFrame(m_tabWidget);
connect( m_part, SIGNAL(signalSettingsChanged()), frame, SLOT(slotPaletteOrFontChanged()));
Kernel::self()->frameManager()->slotAddFrame(frame);
frameId = frame->id();
}
void Akregator::MainWidget::setTabIcon(const QPixmap& icon)
{
ArticleViewer* s = dynamic_cast<ArticleViewer*>(sender());
if (s)
{
m_tabWidget->setTabIcon(m_tabWidget->indexOf(s->part()->widget()), icon);
}
}
void Akregator::MainWidget::sendArticle(bool attach)
{
QByteArray text;
QString title;
Frame* frame = Kernel::self()->frameManager()->currentFrame();
if (frame && frame->id() > 0) { // are we in some other tab than the articlelist?
text = frame->url().prettyUrl().toLatin1();
title = frame->title();
}
else { // nah, we're in articlelist..
const Article article = m_selectionController->currentArticle();
if(!article.isNull()) {
text = article.link().prettyUrl().toLatin1();
title = article.title();
}
}
if(text.isEmpty() || text.isNull())
return;
if(attach)
{
KToolInvocation::invokeMailer(QString(),
QString(),
QString(),
title,
QString(),
QString(),
QStringList(text),
text);
}
else
{
KToolInvocation::invokeMailer(QString(),
QString(),
QString(),
title,
text,
QString(),
QStringList(),
text);
}
}
bool Akregator::MainWidget::importFeeds(const QDomDocument& doc)
{
std::auto_ptr<FeedList> feedList( new FeedList( Kernel::self()->storage() ) );
const bool parsed = feedList->readFromOpml(doc);
// FIXME: parsing error, print some message
if (!parsed)
return false;
QString title = !feedList->title().isEmpty() ? feedList->title() : i18n("Imported Folder");
bool ok;
title = KInputDialog::getText( i18n("Add Imported Folder"),
i18n("Imported folder name:"),
title,
&ok,
this );
if (!ok)
return false;
Folder* fg = new Folder(title);
m_feedList->rootNode()->appendChild(fg);
m_feedList->append(feedList.get(), fg);
return true;
}
void Akregator::MainWidget::setFeedList( FeedList* list )
{
if ( list == m_feedList )
return;
FeedList* const oldList = m_feedList;
m_feedList = list;
if ( m_feedList )
{
connect( m_feedList->rootNode(), SIGNAL( signalChanged( Akregator::TreeNode* ) ),
this, SLOT( slotSetTotalUnread() ) );
slotSetTotalUnread();
}
m_feedListManagementInterface->setFeedList( m_feedList );
Kernel::self()->setFeedList( m_feedList);
ProgressManager::self()->setFeedList( m_feedList );
m_selectionController->setFeedList( m_feedList );
kDebug() << "new feed list is %p old one: %p" << m_feedList.data() << oldList;
if ( oldList ) {
oldList->disconnect( this );
oldList->rootNode()->disconnect( this );
}
delete oldList;
slotDeleteExpiredArticles();
}
bool Akregator::MainWidget::loadFeeds(const QDomDocument& doc, Folder* parent)
{
assert( m_feedList );
std::auto_ptr<FeedList> feedList( new FeedList( Kernel::self()->storage() ) );
if ( !feedList->readFromOpml( doc ) )
return false;
m_feedListView->setUpdatesEnabled( false );
if ( !parent )
setFeedList( feedList.release() );
else
m_feedList->append( feedList.release(), parent );
m_feedListView->setUpdatesEnabled( true );
m_feedListView->triggerUpdate();
return true;
}
void Akregator::MainWidget::deleteExpiredArticles( FeedList* list )
{
if ( !list )
return;
ExpireItemsCommand* cmd = new ExpireItemsCommand( this );
cmd->setParentWidget( this );
cmd->setFeedList( list );
cmd->setFeeds( list->feedIds() );
cmd->start();
}
void Akregator::MainWidget::slotDeleteExpiredArticles()
{
deleteExpiredArticles( m_feedList );
}
QDomDocument Akregator::MainWidget::feedListToOPML()
{
return m_feedList->toOpml();
}
void Akregator::MainWidget::addFeedToGroup(const QString& url, const QString& groupName)
{
// Locate the group.
QList<const TreeNode *> namedGroups = m_feedList->findByTitle( groupName );
Folder* group = 0;
foreach( const TreeNode * candidate, namedGroups ) {
if ( candidate->isGroup() ) {
group = const_cast<Folder*>( static_cast<const Folder*>( candidate ) );
break;
}
}
if (!group)
{
Folder* g = new Folder( groupName );
m_feedList->rootNode()->appendChild(g);
group = g;
}
// Invoke the Add Feed dialog with url filled in.
addFeed(url, 0, group, true);
}
void Akregator::MainWidget::slotNormalView()
{
if (m_viewMode == NormalView)
return;
if (m_viewMode == CombinedView)
{
m_articleListView->show();
const Article article = m_selectionController->currentArticle();
if (!article.isNull())
m_articleViewer->showArticle(article);
else
m_articleViewer->slotShowSummary( m_selectionController->selectedSubscription() );
}
m_articleSplitter->setOrientation(Qt::Vertical);
m_viewMode = NormalView;
Settings::setViewMode( m_viewMode );
}
void Akregator::MainWidget::slotWidescreenView()
{
if (m_viewMode == WidescreenView)
return;
if (m_viewMode == CombinedView)
{
m_articleListView->show();
Article article = m_selectionController->currentArticle();
if (!article.isNull())
m_articleViewer->showArticle(article);
else
m_articleViewer->slotShowSummary( m_selectionController->selectedSubscription() );
}
m_articleSplitter->setOrientation(Qt::Horizontal);
m_viewMode = WidescreenView;
Settings::setViewMode( m_viewMode );
}
void Akregator::MainWidget::slotCombinedView()
{
if (m_viewMode == CombinedView)
return;
m_articleListView->slotClear();
m_articleListView->hide();
m_viewMode = CombinedView;
Settings::setViewMode( m_viewMode );
}
void Akregator::MainWidget::slotFeedTreeContextMenu(K3ListView*, TreeNode* /*node*/, const QPoint& /*p*/)
{
m_tabWidget->setCurrentWidget( m_mainFrame );
}
void Akregator::MainWidget::slotMoveCurrentNodeUp()
{
TreeNode* current = m_selectionController->selectedSubscription();
if (!current)
return;
TreeNode* prev = current->prevSibling();
Folder* parent = current->parent();
if (!prev || !parent)
return;
parent->removeChild(prev);
parent->insertChild(prev, current);
m_feedListView->ensureNodeVisible(current);
}
void Akregator::MainWidget::slotMoveCurrentNodeDown()
{
TreeNode* current = m_selectionController->selectedSubscription();
if (!current)
return;
TreeNode* next = current->nextSibling();
Folder* parent = current->parent();
if (!next || !parent)
return;
parent->removeChild(current);
parent->insertChild(current, next);
m_feedListView->ensureNodeVisible(current);
}
void Akregator::MainWidget::slotMoveCurrentNodeLeft()
{
TreeNode* current = m_selectionController->selectedSubscription();
if (!current || !current->parent() || !current->parent()->parent())
return;
Folder* parent = current->parent();
Folder* grandparent = current->parent()->parent();
parent->removeChild(current);
grandparent->insertChild(current, parent);
m_feedListView->ensureNodeVisible(current);
}
void Akregator::MainWidget::slotMoveCurrentNodeRight()
{
TreeNode* current = m_selectionController->selectedSubscription();
if (!current || !current->parent())
return;
TreeNode* prev = current->prevSibling();
if ( prev && prev->isGroup() )
{
Folder* fg = static_cast<Folder*>(prev);
current->parent()->removeChild(current);
fg->appendChild(current);
m_feedListView->ensureNodeVisible(current);
}
}
void Akregator::MainWidget::slotNodeSelected(TreeNode* node)
{
m_markReadTimer->stop();
if (m_displayingAboutPage)
{
m_mainFrame->slotSetTitle(i18n("Articles"));
if (m_viewMode != CombinedView)
m_articleListView->show();
if (Settings::showQuickFilter())
m_searchBar->show();
m_displayingAboutPage = false;
}
m_tabWidget->setCurrentWidget( m_mainFrame );
if ( Settings::resetQuickFilterOnNodeChange() )
m_searchBar->slotClearSearch();
if (m_viewMode == CombinedView)
{
m_articleViewer->showNode(node);
}
else
{
m_articleViewer->slotShowSummary(node);
}
if (node)
m_mainFrame->setWindowTitle(node->title());
m_actionManager->slotNodeSelected(node);
}
void Akregator::MainWidget::slotFeedAdd()
{
Folder* group = 0;
if ( !m_selectionController->selectedSubscription() )
group = m_feedList->rootNode(); // all feeds
else
{
if ( m_selectionController->selectedSubscription()->isGroup())
group = static_cast<Folder*>( m_selectionController->selectedSubscription() );
else
group= m_selectionController->selectedSubscription()->parent();
}
TreeNode* const lastChild = !group->children().isEmpty() ? group->children().last() : 0;
addFeed(QString::null, lastChild, group, false); //krazy:exclude=nullstrassign for old broken gcc
}
void Akregator::MainWidget::addFeed(const QString& url, TreeNode *after, Folder* parent, bool autoExec)
{
CreateFeedCommand* cmd( new CreateFeedCommand( this ) );
cmd->setParentWidget( this );
cmd->setPosition( parent, after );
cmd->setRootFolder( m_feedList->rootNode() );
cmd->setAutoExecute( autoExec );
cmd->setUrl( url );
cmd->setSubscriptionListView( m_feedListView );
cmd->start();
}
void Akregator::MainWidget::slotFeedAddGroup()
{
CreateFolderCommand* cmd = new CreateFolderCommand( this );
cmd->setParentWidget( this );
cmd->setSelectedSubscription( m_selectionController->selectedSubscription() );
cmd->setRootFolder( m_feedList->rootNode() );
cmd->setSubscriptionListView( m_feedListView );
cmd->start();
}
void Akregator::MainWidget::slotFeedRemove()
{
TreeNode* selectedNode = m_selectionController->selectedSubscription();
// don't delete root element! (safety valve)
if (!selectedNode || selectedNode == m_feedList->rootNode())
return;
DeleteSubscriptionCommand* cmd = new DeleteSubscriptionCommand( this );
cmd->setParentWidget( this );
cmd->setSubscription( m_feedList, selectedNode->id() );
cmd->start();
}
void Akregator::MainWidget::slotFeedModify()
{
TreeNode* const node = m_selectionController->selectedSubscription();
if ( !node )
return;
EditSubscriptionCommand* cmd = new EditSubscriptionCommand( this );
cmd->setParentWidget( this );
cmd->setSubscription( m_feedList, node->id() );
cmd->setSubscriptionListView( m_feedListView );
cmd->start();
}
void Akregator::MainWidget::slotNextUnreadArticle()
{
if (m_viewMode == CombinedView)
m_feedListView->slotNextUnreadFeed();
TreeNode* sel = m_selectionController->selectedSubscription();
if (sel && sel->unread() > 0)
m_articleListView->slotNextUnreadArticle();
else
m_feedListView->slotNextUnreadFeed();
}
void Akregator::MainWidget::slotPrevUnreadArticle()
{
if (m_viewMode == CombinedView)
m_feedListView->slotPrevUnreadFeed();
TreeNode* sel = m_selectionController->selectedSubscription();
if (sel && sel->unread() > 0)
m_articleListView->slotPreviousUnreadArticle();
else
m_feedListView->slotPrevUnreadFeed();
}
void Akregator::MainWidget::slotMarkAllFeedsRead()
{
m_feedList->rootNode()->slotMarkAllArticlesAsRead();
}
void Akregator::MainWidget::slotMarkAllRead()
{
if(!m_selectionController->selectedSubscription())
return;
m_selectionController->selectedSubscription()->slotMarkAllArticlesAsRead();
}
void Akregator::MainWidget::slotSetTotalUnread()
{
emit signalUnreadCountChanged( m_feedList ? m_feedList->rootNode()->unread() : 0 );
}
void Akregator::MainWidget::slotDoIntervalFetches()
{
if ( !m_feedList )
return;
const Networking::Status status = Solid::Networking::status();
if ( status != Networking::Connected && status != Networking::Unknown )
return;
m_feedList->rootNode()->slotAddToFetchQueue(Kernel::self()->fetchQueue(), true);
}
void Akregator::MainWidget::slotFetchCurrentFeed()
{
if ( !m_selectionController->selectedSubscription() )
return;
m_selectionController->selectedSubscription()->slotAddToFetchQueue(Kernel::self()->fetchQueue());
}
void Akregator::MainWidget::slotFetchAllFeeds()
{
m_feedList->rootNode()->slotAddToFetchQueue(Kernel::self()->fetchQueue());
}
void Akregator::MainWidget::slotFetchingStarted()
{
m_mainFrame->slotSetState(Frame::Started);
m_actionManager->action("feed_stop")->setEnabled(true);
m_mainFrame->slotSetStatusText(i18n("Fetching Feeds..."));
}
void Akregator::MainWidget::slotFetchingStopped()
{
m_mainFrame->slotSetState(Frame::Completed);
m_actionManager->action("feed_stop")->setEnabled(false);
m_mainFrame->slotSetStatusText(QString());
}
void Akregator::MainWidget::slotFeedFetched(Feed *feed)
{
// iterate through the articles (once again) to do notifications properly
if (feed->articles().count() > 0)
{
QList<Article> articles = feed->articles();
QList<Article>::ConstIterator it;
QList<Article>::ConstIterator end = articles.end();
for (it = articles.begin(); it != end; ++it)
{
if ((*it).status()==Akregator::New && ((*it).feed()->useNotification() || Settings::useNotifications()))
{
NotificationManager::self()->slotNotifyArticle(*it);
}
}
}
}
void Akregator::MainWidget::slotArticleSelected(const Akregator::Article& article)
{
if (m_viewMode == CombinedView)
return;
m_markReadTimer->stop();
assert( article.isNull() || article.feed() );
KToggleAction* const maai = qobject_cast<KToggleAction*>( m_actionManager->action( "article_set_status_important" ) );
assert( maai );
maai->setChecked( article.keep() );
m_articleViewer->showArticle( article );
if ( article.isNull() || article.status() == Akregator::Read )
return;
if ( !Settings::useMarkReadDelay() )
return;
const int delay = Settings::markReadDelay();
if ( delay > 0 )
{
m_markReadTimer->start( delay * 1000 );
}
else
{
Akregator::ArticleModifyJob* job = new Akregator::ArticleModifyJob;
const Akregator::ArticleId aid = { article.feed()->xmlUrl(), article.guid() };
job->setStatus( aid, Akregator::Read );
job->start();
}
}
void Akregator::MainWidget::slotMouseButtonPressed(int button, const KUrl& url)
{
if (button != Qt::MidButton)
return;
if (!url.isValid())
return;
OpenUrlRequest req(url);
switch (Settings::mMBBehaviour())
{
case Settings::EnumMMBBehaviour::OpenInExternalBrowser:
req.setOptions(OpenUrlRequest::ExternalBrowser);
break;
case Settings::EnumMMBBehaviour::OpenInBackground:
req.setOptions(OpenUrlRequest::NewTab);
req.setOpenInBackground(true);
break;
default:
req.setOptions(OpenUrlRequest::NewTab);
req.setOpenInBackground(false);
}
Kernel::self()->frameManager()->slotOpenUrlRequest(req);
}
void Akregator::MainWidget::slotOpenHomepage()
{
Feed* feed = dynamic_cast<Feed *>( m_selectionController->selectedSubscription() );
if (!feed)
return;
KUrl url(feed->htmlUrl());
if (url.isValid())
{
OpenUrlRequest req(feed->htmlUrl());
req.setOptions(OpenUrlRequest::ExternalBrowser);
Kernel::self()->frameManager()->slotOpenUrlRequest(req);
}
}
void Akregator::MainWidget::slotOpenCurrentArticleInBrowser()
{
slotOpenArticleInBrowser( m_selectionController->currentArticle() );
}
void Akregator::MainWidget::slotOpenArticleInBrowser(const Akregator::Article& article)
{
if (!article.isNull() && article.link().isValid())
{
OpenUrlRequest req(article.link());
req.setOptions(OpenUrlRequest::ExternalBrowser);
Kernel::self()->frameManager()->slotOpenUrlRequest(req);
}
}
void Akregator::MainWidget::slotOpenCurrentArticle()
{
Article article = m_selectionController->currentArticle();
if ( article.isNull() )
return;
const KUrl url = article.link();
if ( !url.isValid() )
return;
OpenUrlRequest req( url );
req.setOptions( OpenUrlRequest::NewTab );
// TODO: (re-)add a setting for foreground/background
// and use it here
//req.setOpenInBackground( true );
Kernel::self()->frameManager()->slotOpenUrlRequest( req );
}
void Akregator::MainWidget::slotCopyLinkAddress()
{
const Article article = m_selectionController->currentArticle();
if(article.isNull())
return;
QString link;
if (article.link().isValid())
{
link = article.link().url();
QClipboard *cb = QApplication::clipboard();
cb->setText(link, QClipboard::Clipboard);
// don't set url to selection as it's a no-no according to a fd.o spec
//cb->setText(link, QClipboard::Selection);
}
}
void Akregator::MainWidget::slotFeedUrlDropped(KUrl::List &urls, TreeNode* after, Folder* parent)
{
Q_FOREACH ( const KUrl& i, urls )
addFeed( i.prettyUrl(), after, parent, false );
}
void Akregator::MainWidget::slotToggleShowQuickFilter()
{
if ( Settings::showQuickFilter() )
{
Settings::setShowQuickFilter(false);
m_searchBar->slotClearSearch();
m_searchBar->hide();
}
else
{
Settings::setShowQuickFilter(true);
if (!m_displayingAboutPage)
m_searchBar->show();
}
}
void Akregator::MainWidget::slotArticleDelete()
{
if ( m_viewMode == CombinedView )
return;
QList<Article> articles = m_selectionController->selectedArticles();
QString msg;
switch (articles.count())
{
case 0:
return;
case 1:
msg = i18n("<qt>Are you sure you want to delete article <b>%1</b>?</qt>", Qt::escape(articles.first().title()));
break;
default:
msg = i18n("<qt>Are you sure you want to delete the %1 selected articles?</qt>", articles.count());
}
if ( KMessageBox::warningContinueCancel( this,
msg, i18n( "Delete Article" ),
KStandardGuiItem::del(),
KStandardGuiItem::cancel(),
"Disable delete article confirmation" ) != KMessageBox::Continue )
return;
TreeNode* const selected = m_selectionController->selectedSubscription();
if ( selected )
selected->setNotificationMode( false );
Akregator::ArticleDeleteJob* job = new Akregator::ArticleDeleteJob;
Q_FOREACH( const Akregator::Article i, articles )
{
Feed* const feed = i.feed();
assert( feed );
const Akregator::ArticleId aid = { feed->xmlUrl(), i.guid() };
job->appendArticleId( aid );
}
job->start();
if ( selected )
selected->setNotificationMode( true );
}
void Akregator::MainWidget::slotArticleToggleKeepFlag( bool )
{
const QList<Article> articles = m_selectionController->selectedArticles();
if (articles.isEmpty())
return;
bool allFlagsSet = true;
Q_FOREACH ( const Akregator::Article i, articles )
{
allFlagsSet = allFlagsSet && i.keep();
if ( !allFlagsSet )
break;
}
Akregator::ArticleModifyJob* job = new Akregator::ArticleModifyJob;
Q_FOREACH ( const Akregator::Article i, articles )
{
const Akregator::ArticleId aid = { i.feed()->xmlUrl(), i.guid() };
job->setKeep( aid, !allFlagsSet );
}
job->start();
}
namespace {
void setSelectedArticleStatus( const Akregator::AbstractSelectionController* controller, int status )
{
const QList<Akregator::Article> articles = controller->selectedArticles();
if (articles.isEmpty())
return;
Akregator::ArticleModifyJob* job = new Akregator::ArticleModifyJob;
Q_FOREACH ( const Akregator::Article i, articles )
{
const Akregator::ArticleId aid = { i.feed()->xmlUrl(), i.guid() };
job->setStatus( aid, status );
}
job->start();
}
}
void Akregator::MainWidget::slotSetSelectedArticleRead()
{
::setSelectedArticleStatus( m_selectionController, Akregator::Read );
}
void Akregator::MainWidget::slotTextToSpeechRequest()
{
if (Kernel::self()->frameManager()->currentFrame() == m_mainFrame)
{
if (m_viewMode != CombinedView)
{
// in non-combined view, read selected articles
#ifdef __GNUC__
#warning "kde4:readd speechclient";
#endif
//SpeechClient::self()->slotSpeak(m_selectionController->selectedArticles());
// TODO: if article viewer has a selection, read only the selected text?
}
else
{
if (m_selectionController->selectedSubscription())
{
//TODO: read articles in current node, respecting quick filter!
}
}
}
else
{
// TODO: read selected page viewer
}
}
void Akregator::MainWidget::slotSetSelectedArticleUnread()
{
::setSelectedArticleStatus( m_selectionController, Akregator::Unread );
}
void Akregator::MainWidget::slotSetSelectedArticleNew()
{
::setSelectedArticleStatus( m_selectionController, Akregator::New );
}
void Akregator::MainWidget::slotSetCurrentArticleReadDelayed()
{
const Article article = m_selectionController->currentArticle();
if (article.isNull())
return;
Akregator::ArticleModifyJob* const job = new Akregator::ArticleModifyJob;
const Akregator::ArticleId aid = { article.feed()->xmlUrl(), article.guid() };
job->setStatus( aid, Akregator::Read );
job->start();
}
void Akregator::MainWidget::slotMouseOverInfo(const KFileItem& kifi)
{
m_mainFrame->slotSetStatusText( kifi.isNull() ? QString() : kifi.url().prettyUrl() );
}
void Akregator::MainWidget::readProperties(const KConfigGroup &config)
{
if ( !Settings::resetQuickFilterOnNodeChange() )
{
// read filter settings
m_searchBar->slotSetText(config.readEntry("searchLine"));
m_searchBar->slotSetStatus(config.readEntry("searchCombo").toInt());
}
}
void Akregator::MainWidget::saveProperties(KConfigGroup & config)
{
// save filter settings
config.writeEntry("searchLine", m_searchBar->text());
config.writeEntry("searchCombo", m_searchBar->status());
}
#include "mainwidget.moc"
in combined view mode, return here
svn path=/branches/KDE/4.1/kdepim/; revision=876233
/*
This file is part of Akregator.
Copyright (C) 2004 Stanislav Karchebny <Stanislav.Karchebny@kdemail.net>
2004 Sashmit Bhaduri <smt@vfemail.net>
2005 Frank Osterfeld <osterfeld@kde.org>
This program 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.
This program 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 program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "mainwidget.h"
#include "actionmanagerimpl.h"
#include "addfeeddialog.h"
#include "articlelistview.h"
#include "articleviewer.h"
#include "articlejobs.h"
#include "akregatorconfig.h"
#include "akregator_part.h"
#include "browserframe.h"
#include "createfeedcommand.h"
#include "createfoldercommand.h"
#include "deletesubscriptioncommand.h"
#include "editsubscriptioncommand.h"
#include "expireitemscommand.h"
#include "feed.h"
#include "feedlist.h"
#include "feedpropertiesdialog.h"
#include "fetchqueue.h"
#include "folder.h"
#include "framemanager.h"
#include "kernel.h"
#include "notificationmanager.h"
#include "openurlrequest.h"
#include "progressmanager.h"
#include "searchbar.h"
#include "selectioncontroller.h"
//#include "speechclient.h"
#include "subscriptionlistjobs.h"
#include "subscriptionlistmodel.h"
#include "subscriptionlistview.h"
#include "tabwidget.h"
#include "treenode.h"
#include "treenodevisitor.h"
#include "types.h"
#include <solid/networking.h>
#include <kaction.h>
#include <kdialog.h>
#include <KDebug>
#include <kfiledialog.h>
#include <kfileitem.h>
#include <kiconloader.h>
#include <kinputdialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <krandom.h>
#include <kshell.h>
#include <kstandarddirs.h>
#include <ktoggleaction.h>
#include <ktoolinvocation.h>
#include <kurl.h>
#include <QClipboard>
#include <QPixmap>
#include <QSplitter>
#include <QTextDocument>
#include <QDomDocument>
#include <QTimer>
#include <algorithm>
#include <memory>
#include <cassert>
using namespace Akregator;
using namespace Solid;
Akregator::MainWidget::~MainWidget()
{
// if m_shuttingDown is false, slotOnShutdown was not called. That
// means that not the whole app is shutdown, only the part. So it
// should be no risk to do the cleanups now
if (!m_shuttingDown)
slotOnShutdown();
}
Akregator::MainWidget::MainWidget( Part *part, QWidget *parent, ActionManagerImpl* actionManager, const char *name)
: QWidget(parent),
m_feedList( 0 ),
m_viewMode(NormalView),
m_actionManager(actionManager),
m_feedListManagementInterface( new FeedListManagementImpl )
{
setObjectName(name);
FeedListManagementInterface::setInstance( m_feedListManagementInterface );
m_actionManager->initMainWidget(this);
m_actionManager->initFrameManager(Kernel::self()->frameManager());
m_part = part;
m_shuttingDown = false;
m_displayingAboutPage = false;
setFocusPolicy(Qt::StrongFocus);
QVBoxLayout *lt = new QVBoxLayout( this );
lt->setMargin(0);
m_horizontalSplitter = new QSplitter(Qt::Horizontal, this);
m_horizontalSplitter->setOpaqueResize(true);
lt->addWidget(m_horizontalSplitter);
connect(Kernel::self()->fetchQueue(), SIGNAL(fetched(Akregator::Feed*)),
this, SLOT(slotFeedFetched(Akregator::Feed*)));
connect(Kernel::self()->fetchQueue(), SIGNAL(signalStarted()),
this, SLOT(slotFetchingStarted()));
connect(Kernel::self()->fetchQueue(), SIGNAL(signalStopped()),
this, SLOT(slotFetchingStopped()));
m_feedListView = new SubscriptionListView( m_horizontalSplitter );
m_feedListView->setObjectName( "feedtree" );
m_actionManager->initSubscriptionListView( m_feedListView );
connect(m_feedListView, SIGNAL(signalContextMenu(K3ListView*, Akregator::TreeNode*, const QPoint&)),
this, SLOT(slotFeedTreeContextMenu(K3ListView*, Akregator::TreeNode*, const QPoint&)));
connect(m_feedListView, SIGNAL(signalDropped (KUrl::List &, Akregator::TreeNode*,
Akregator::Folder*)),
this, SLOT(slotFeedUrlDropped (KUrl::List &,
Akregator::TreeNode*, Akregator::Folder*)));
m_tabWidget = new TabWidget(m_horizontalSplitter);
m_actionManager->initTabWidget(m_tabWidget);
connect( m_part, SIGNAL(signalSettingsChanged()),
m_tabWidget, SLOT(slotSettingsChanged()));
connect( m_tabWidget, SIGNAL(signalCurrentFrameChanged(int)),
Kernel::self()->frameManager(), SLOT(slotChangeFrame(int)));
connect( m_tabWidget, SIGNAL(signalRemoveFrameRequest(int)),
Kernel::self()->frameManager(), SLOT(slotRemoveFrame(int)));
connect( m_tabWidget, SIGNAL(signalOpenUrlRequest(Akregator::OpenUrlRequest&)),
Kernel::self()->frameManager(), SLOT(slotOpenUrlRequest(Akregator::OpenUrlRequest&)));
connect( Kernel::self()->frameManager(), SIGNAL(signalFrameAdded(Akregator::Frame*)),
m_tabWidget, SLOT(slotAddFrame(Akregator::Frame*)));
connect( Kernel::self()->frameManager(), SIGNAL(signalSelectFrame(int)),
m_tabWidget, SLOT(slotSelectFrame(int)) );
connect( Kernel::self()->frameManager(), SIGNAL(signalFrameRemoved(int)),
m_tabWidget, SLOT(slotRemoveFrame(int)));
connect( Kernel::self()->frameManager(), SIGNAL(signalRequestNewFrame(int&)),
this, SLOT( slotRequestNewFrame(int&) ) );
m_tabWidget->setWhatsThis( i18n("You can view multiple articles in several open tabs."));
m_mainTab = new QWidget(this);
m_mainTab->setObjectName("Article Tab");
m_mainTab->setWhatsThis( i18n("Articles list."));
QVBoxLayout *mainTabLayout = new QVBoxLayout( m_mainTab);
mainTabLayout->setMargin(0);
m_searchBar = new SearchBar(m_mainTab);
if ( !Settings::showQuickFilter() )
m_searchBar->hide();
mainTabLayout->addWidget(m_searchBar);
m_articleSplitter = new QSplitter(Qt::Vertical, m_mainTab);
m_articleSplitter->setObjectName("panner2");
m_articleListView = new ArticleListView( m_articleSplitter );
m_selectionController = new SelectionController( this );
m_selectionController->setArticleLister( m_articleListView );
m_selectionController->setFeedSelector( m_feedListView );
connect(m_searchBar, SIGNAL( signalSearch( std::vector<boost::shared_ptr<const Akregator::Filters::AbstractMatcher> > ) ),
m_selectionController, SLOT( setFilters( std::vector<boost::shared_ptr<const Akregator::Filters::AbstractMatcher> > ) ) );
FolderExpansionHandler* expansionHandler = new FolderExpansionHandler( this );
connect( m_feedListView, SIGNAL( expanded( QModelIndex ) ), expansionHandler, SLOT( itemExpanded( QModelIndex ) ) );
connect( m_feedListView, SIGNAL( collapsed( QModelIndex ) ), expansionHandler, SLOT( itemCollapsed( QModelIndex ) ) );
m_selectionController->setFolderExpansionHandler( expansionHandler );
connect( m_selectionController, SIGNAL( currentSubscriptionChanged( Akregator::TreeNode* ) ),
this, SLOT( slotNodeSelected( Akregator::TreeNode* ) ) );
connect( m_selectionController, SIGNAL( currentArticleChanged( Akregator::Article ) ),
this, SLOT( slotArticleSelected( Akregator::Article ) ) );
connect( m_selectionController, SIGNAL( articleDoubleClicked( Akregator::Article ) ),
this, SLOT( slotOpenArticleInBrowser( Akregator::Article )) );
m_actionManager->initArticleListView(m_articleListView);
connect( m_articleListView, SIGNAL(signalMouseButtonPressed(int, KUrl )),
this, SLOT(slotMouseButtonPressed(int, KUrl )));
connect( m_part, SIGNAL(signalSettingsChanged()),
m_articleListView, SLOT(slotPaletteOrFontChanged()));
m_articleViewer = new ArticleViewer(m_articleSplitter);
m_actionManager->initArticleViewer(m_articleViewer);
m_articleListView->setFocusProxy(m_articleViewer);
connect( m_articleViewer, SIGNAL(signalOpenUrlRequest(Akregator::OpenUrlRequest& )),
Kernel::self()->frameManager(), SLOT(slotOpenUrlRequest( Akregator::OpenUrlRequest& )) );
connect( m_articleViewer->part()->browserExtension(), SIGNAL(mouseOverInfo( KFileItem )),
this, SLOT(slotMouseOverInfo( KFileItem )) );
connect( m_part, SIGNAL(signalSettingsChanged()),
m_articleViewer, SLOT(slotPaletteOrFontChanged()));
connect(m_searchBar, SIGNAL( signalSearch( std::vector<boost::shared_ptr<const Akregator::Filters::AbstractMatcher> > ) ),
m_articleViewer, SLOT( setFilters( std::vector<boost::shared_ptr<const Akregator::Filters::AbstractMatcher> > ) ) );
m_articleViewer->part()->widget()->setWhatsThis( i18n("Browsing area."));
mainTabLayout->addWidget( m_articleSplitter );
m_mainFrame = new MainFrame(this, m_part, m_mainTab, i18n("Articles"));
Kernel::self()->frameManager()->slotAddFrame(m_mainFrame);
const QList<int> sp1sizes = Settings::splitter1Sizes();
if ( sp1sizes.count() >= m_horizontalSplitter->count() )
m_horizontalSplitter->setSizes( sp1sizes );
const QList<int> sp2sizes = Settings::splitter2Sizes();
if ( sp2sizes.count() >= m_articleSplitter->count() )
m_articleSplitter->setSizes( sp2sizes );
KConfigGroup conf(Settings::self()->config(), "General");
if(!conf.readEntry("Disable Introduction", false))
{
m_articleListView->hide();
m_searchBar->hide();
m_articleViewer->displayAboutPage();
m_mainFrame->slotSetTitle(i18n("About"));
m_displayingAboutPage = true;
}
m_fetchTimer = new QTimer(this);
connect( m_fetchTimer, SIGNAL(timeout()),
this, SLOT(slotDoIntervalFetches()) );
m_fetchTimer->start(1000*60);
// delete expired articles once per hour
m_expiryTimer = new QTimer(this);
connect(m_expiryTimer, SIGNAL(timeout()),
this, SLOT(slotDeleteExpiredArticles()) );
m_expiryTimer->start(3600*1000);
m_markReadTimer = new QTimer(this);
m_markReadTimer->setSingleShot(true);
connect(m_markReadTimer, SIGNAL(timeout()), this, SLOT(slotSetCurrentArticleReadDelayed()) );
setFeedList( new FeedList( Kernel::self()->storage() ) );
switch (Settings::viewMode())
{
case CombinedView:
slotCombinedView();
break;
case WidescreenView:
slotWidescreenView();
break;
default:
slotNormalView();
}
if ( !Settings::resetQuickFilterOnNodeChange() )
{
m_searchBar->slotSetStatus( Settings::statusFilter() );
m_searchBar->slotSetText( Settings::textFilter() );
}
}
void Akregator::MainWidget::slotOnShutdown()
{
m_shuttingDown = true;
Kernel::self()->fetchQueue()->slotAbort();
setFeedList( 0 );
delete m_feedListManagementInterface;
delete m_feedListView; // call delete here, so that the header settings will get saved
delete m_articleListView; // same for this one
// close all pageviewers in a controlled way
// fixes bug 91660, at least when no part loading data
m_tabWidget->setCurrentIndex(m_tabWidget->count()-1); // select last page
while (m_tabWidget->count() > 1) // remove frames until only the main frame remains
m_tabWidget->slotRemoveCurrentFrame();
delete m_mainTab;
delete m_mainFrame;
Settings::self()->writeConfig();
}
void Akregator::MainWidget::saveSettings()
{
const QList<int> spl1 = m_horizontalSplitter->sizes();
if ( std::count( spl1.begin(), spl1.end(), 0 ) == 0 )
Settings::setSplitter1Sizes( spl1 );
const QList<int> spl2 = m_articleSplitter->sizes();
if ( std::count( spl2.begin(), spl2.end(), 0 ) == 0 )
Settings::setSplitter2Sizes( spl2 );
Settings::setViewMode( m_viewMode );
Settings::self()->writeConfig();
}
void Akregator::MainWidget::slotRequestNewFrame(int& frameId)
{
BrowserFrame* frame = new BrowserFrame(m_tabWidget);
connect( m_part, SIGNAL(signalSettingsChanged()), frame, SLOT(slotPaletteOrFontChanged()));
Kernel::self()->frameManager()->slotAddFrame(frame);
frameId = frame->id();
}
void Akregator::MainWidget::setTabIcon(const QPixmap& icon)
{
ArticleViewer* s = dynamic_cast<ArticleViewer*>(sender());
if (s)
{
m_tabWidget->setTabIcon(m_tabWidget->indexOf(s->part()->widget()), icon);
}
}
void Akregator::MainWidget::sendArticle(bool attach)
{
QByteArray text;
QString title;
Frame* frame = Kernel::self()->frameManager()->currentFrame();
if (frame && frame->id() > 0) { // are we in some other tab than the articlelist?
text = frame->url().prettyUrl().toLatin1();
title = frame->title();
}
else { // nah, we're in articlelist..
const Article article = m_selectionController->currentArticle();
if(!article.isNull()) {
text = article.link().prettyUrl().toLatin1();
title = article.title();
}
}
if(text.isEmpty() || text.isNull())
return;
if(attach)
{
KToolInvocation::invokeMailer(QString(),
QString(),
QString(),
title,
QString(),
QString(),
QStringList(text),
text);
}
else
{
KToolInvocation::invokeMailer(QString(),
QString(),
QString(),
title,
text,
QString(),
QStringList(),
text);
}
}
bool Akregator::MainWidget::importFeeds(const QDomDocument& doc)
{
std::auto_ptr<FeedList> feedList( new FeedList( Kernel::self()->storage() ) );
const bool parsed = feedList->readFromOpml(doc);
// FIXME: parsing error, print some message
if (!parsed)
return false;
QString title = !feedList->title().isEmpty() ? feedList->title() : i18n("Imported Folder");
bool ok;
title = KInputDialog::getText( i18n("Add Imported Folder"),
i18n("Imported folder name:"),
title,
&ok,
this );
if (!ok)
return false;
Folder* fg = new Folder(title);
m_feedList->rootNode()->appendChild(fg);
m_feedList->append(feedList.get(), fg);
return true;
}
void Akregator::MainWidget::setFeedList( FeedList* list )
{
if ( list == m_feedList )
return;
FeedList* const oldList = m_feedList;
m_feedList = list;
if ( m_feedList )
{
connect( m_feedList->rootNode(), SIGNAL( signalChanged( Akregator::TreeNode* ) ),
this, SLOT( slotSetTotalUnread() ) );
slotSetTotalUnread();
}
m_feedListManagementInterface->setFeedList( m_feedList );
Kernel::self()->setFeedList( m_feedList);
ProgressManager::self()->setFeedList( m_feedList );
m_selectionController->setFeedList( m_feedList );
kDebug() << "new feed list is %p old one: %p" << m_feedList.data() << oldList;
if ( oldList ) {
oldList->disconnect( this );
oldList->rootNode()->disconnect( this );
}
delete oldList;
slotDeleteExpiredArticles();
}
bool Akregator::MainWidget::loadFeeds(const QDomDocument& doc, Folder* parent)
{
assert( m_feedList );
std::auto_ptr<FeedList> feedList( new FeedList( Kernel::self()->storage() ) );
if ( !feedList->readFromOpml( doc ) )
return false;
m_feedListView->setUpdatesEnabled( false );
if ( !parent )
setFeedList( feedList.release() );
else
m_feedList->append( feedList.release(), parent );
m_feedListView->setUpdatesEnabled( true );
m_feedListView->triggerUpdate();
return true;
}
void Akregator::MainWidget::deleteExpiredArticles( FeedList* list )
{
if ( !list )
return;
ExpireItemsCommand* cmd = new ExpireItemsCommand( this );
cmd->setParentWidget( this );
cmd->setFeedList( list );
cmd->setFeeds( list->feedIds() );
cmd->start();
}
void Akregator::MainWidget::slotDeleteExpiredArticles()
{
deleteExpiredArticles( m_feedList );
}
QDomDocument Akregator::MainWidget::feedListToOPML()
{
return m_feedList->toOpml();
}
void Akregator::MainWidget::addFeedToGroup(const QString& url, const QString& groupName)
{
// Locate the group.
QList<const TreeNode *> namedGroups = m_feedList->findByTitle( groupName );
Folder* group = 0;
foreach( const TreeNode * candidate, namedGroups ) {
if ( candidate->isGroup() ) {
group = const_cast<Folder*>( static_cast<const Folder*>( candidate ) );
break;
}
}
if (!group)
{
Folder* g = new Folder( groupName );
m_feedList->rootNode()->appendChild(g);
group = g;
}
// Invoke the Add Feed dialog with url filled in.
addFeed(url, 0, group, true);
}
void Akregator::MainWidget::slotNormalView()
{
if (m_viewMode == NormalView)
return;
if (m_viewMode == CombinedView)
{
m_articleListView->show();
const Article article = m_selectionController->currentArticle();
if (!article.isNull())
m_articleViewer->showArticle(article);
else
m_articleViewer->slotShowSummary( m_selectionController->selectedSubscription() );
}
m_articleSplitter->setOrientation(Qt::Vertical);
m_viewMode = NormalView;
Settings::setViewMode( m_viewMode );
}
void Akregator::MainWidget::slotWidescreenView()
{
if (m_viewMode == WidescreenView)
return;
if (m_viewMode == CombinedView)
{
m_articleListView->show();
Article article = m_selectionController->currentArticle();
if (!article.isNull())
m_articleViewer->showArticle(article);
else
m_articleViewer->slotShowSummary( m_selectionController->selectedSubscription() );
}
m_articleSplitter->setOrientation(Qt::Horizontal);
m_viewMode = WidescreenView;
Settings::setViewMode( m_viewMode );
}
void Akregator::MainWidget::slotCombinedView()
{
if (m_viewMode == CombinedView)
return;
m_articleListView->slotClear();
m_articleListView->hide();
m_viewMode = CombinedView;
Settings::setViewMode( m_viewMode );
}
void Akregator::MainWidget::slotFeedTreeContextMenu(K3ListView*, TreeNode* /*node*/, const QPoint& /*p*/)
{
m_tabWidget->setCurrentWidget( m_mainFrame );
}
void Akregator::MainWidget::slotMoveCurrentNodeUp()
{
TreeNode* current = m_selectionController->selectedSubscription();
if (!current)
return;
TreeNode* prev = current->prevSibling();
Folder* parent = current->parent();
if (!prev || !parent)
return;
parent->removeChild(prev);
parent->insertChild(prev, current);
m_feedListView->ensureNodeVisible(current);
}
void Akregator::MainWidget::slotMoveCurrentNodeDown()
{
TreeNode* current = m_selectionController->selectedSubscription();
if (!current)
return;
TreeNode* next = current->nextSibling();
Folder* parent = current->parent();
if (!next || !parent)
return;
parent->removeChild(current);
parent->insertChild(current, next);
m_feedListView->ensureNodeVisible(current);
}
void Akregator::MainWidget::slotMoveCurrentNodeLeft()
{
TreeNode* current = m_selectionController->selectedSubscription();
if (!current || !current->parent() || !current->parent()->parent())
return;
Folder* parent = current->parent();
Folder* grandparent = current->parent()->parent();
parent->removeChild(current);
grandparent->insertChild(current, parent);
m_feedListView->ensureNodeVisible(current);
}
void Akregator::MainWidget::slotMoveCurrentNodeRight()
{
TreeNode* current = m_selectionController->selectedSubscription();
if (!current || !current->parent())
return;
TreeNode* prev = current->prevSibling();
if ( prev && prev->isGroup() )
{
Folder* fg = static_cast<Folder*>(prev);
current->parent()->removeChild(current);
fg->appendChild(current);
m_feedListView->ensureNodeVisible(current);
}
}
void Akregator::MainWidget::slotNodeSelected(TreeNode* node)
{
m_markReadTimer->stop();
if (m_displayingAboutPage)
{
m_mainFrame->slotSetTitle(i18n("Articles"));
if (m_viewMode != CombinedView)
m_articleListView->show();
if (Settings::showQuickFilter())
m_searchBar->show();
m_displayingAboutPage = false;
}
m_tabWidget->setCurrentWidget( m_mainFrame );
if ( Settings::resetQuickFilterOnNodeChange() )
m_searchBar->slotClearSearch();
if (m_viewMode == CombinedView)
{
m_articleViewer->showNode(node);
}
else
{
m_articleViewer->slotShowSummary(node);
}
if (node)
m_mainFrame->setWindowTitle(node->title());
m_actionManager->slotNodeSelected(node);
}
void Akregator::MainWidget::slotFeedAdd()
{
Folder* group = 0;
if ( !m_selectionController->selectedSubscription() )
group = m_feedList->rootNode(); // all feeds
else
{
if ( m_selectionController->selectedSubscription()->isGroup())
group = static_cast<Folder*>( m_selectionController->selectedSubscription() );
else
group= m_selectionController->selectedSubscription()->parent();
}
TreeNode* const lastChild = !group->children().isEmpty() ? group->children().last() : 0;
addFeed(QString::null, lastChild, group, false); //krazy:exclude=nullstrassign for old broken gcc
}
void Akregator::MainWidget::addFeed(const QString& url, TreeNode *after, Folder* parent, bool autoExec)
{
CreateFeedCommand* cmd( new CreateFeedCommand( this ) );
cmd->setParentWidget( this );
cmd->setPosition( parent, after );
cmd->setRootFolder( m_feedList->rootNode() );
cmd->setAutoExecute( autoExec );
cmd->setUrl( url );
cmd->setSubscriptionListView( m_feedListView );
cmd->start();
}
void Akregator::MainWidget::slotFeedAddGroup()
{
CreateFolderCommand* cmd = new CreateFolderCommand( this );
cmd->setParentWidget( this );
cmd->setSelectedSubscription( m_selectionController->selectedSubscription() );
cmd->setRootFolder( m_feedList->rootNode() );
cmd->setSubscriptionListView( m_feedListView );
cmd->start();
}
void Akregator::MainWidget::slotFeedRemove()
{
TreeNode* selectedNode = m_selectionController->selectedSubscription();
// don't delete root element! (safety valve)
if (!selectedNode || selectedNode == m_feedList->rootNode())
return;
DeleteSubscriptionCommand* cmd = new DeleteSubscriptionCommand( this );
cmd->setParentWidget( this );
cmd->setSubscription( m_feedList, selectedNode->id() );
cmd->start();
}
void Akregator::MainWidget::slotFeedModify()
{
TreeNode* const node = m_selectionController->selectedSubscription();
if ( !node )
return;
EditSubscriptionCommand* cmd = new EditSubscriptionCommand( this );
cmd->setParentWidget( this );
cmd->setSubscription( m_feedList, node->id() );
cmd->setSubscriptionListView( m_feedListView );
cmd->start();
}
void Akregator::MainWidget::slotNextUnreadArticle()
{
if (m_viewMode == CombinedView)
{
m_feedListView->slotNextUnreadFeed();
return;
}
TreeNode* sel = m_selectionController->selectedSubscription();
if (sel && sel->unread() > 0)
m_articleListView->slotNextUnreadArticle();
else
m_feedListView->slotNextUnreadFeed();
}
void Akregator::MainWidget::slotPrevUnreadArticle()
{
if (m_viewMode == CombinedView)
{
m_feedListView->slotPrevUnreadFeed();
return;
}
TreeNode* sel = m_selectionController->selectedSubscription();
if (sel && sel->unread() > 0)
m_articleListView->slotPreviousUnreadArticle();
else
m_feedListView->slotPrevUnreadFeed();
}
void Akregator::MainWidget::slotMarkAllFeedsRead()
{
m_feedList->rootNode()->slotMarkAllArticlesAsRead();
}
void Akregator::MainWidget::slotMarkAllRead()
{
if(!m_selectionController->selectedSubscription())
return;
m_selectionController->selectedSubscription()->slotMarkAllArticlesAsRead();
}
void Akregator::MainWidget::slotSetTotalUnread()
{
emit signalUnreadCountChanged( m_feedList ? m_feedList->rootNode()->unread() : 0 );
}
void Akregator::MainWidget::slotDoIntervalFetches()
{
if ( !m_feedList )
return;
const Networking::Status status = Solid::Networking::status();
if ( status != Networking::Connected && status != Networking::Unknown )
return;
m_feedList->rootNode()->slotAddToFetchQueue(Kernel::self()->fetchQueue(), true);
}
void Akregator::MainWidget::slotFetchCurrentFeed()
{
if ( !m_selectionController->selectedSubscription() )
return;
m_selectionController->selectedSubscription()->slotAddToFetchQueue(Kernel::self()->fetchQueue());
}
void Akregator::MainWidget::slotFetchAllFeeds()
{
m_feedList->rootNode()->slotAddToFetchQueue(Kernel::self()->fetchQueue());
}
void Akregator::MainWidget::slotFetchingStarted()
{
m_mainFrame->slotSetState(Frame::Started);
m_actionManager->action("feed_stop")->setEnabled(true);
m_mainFrame->slotSetStatusText(i18n("Fetching Feeds..."));
}
void Akregator::MainWidget::slotFetchingStopped()
{
m_mainFrame->slotSetState(Frame::Completed);
m_actionManager->action("feed_stop")->setEnabled(false);
m_mainFrame->slotSetStatusText(QString());
}
void Akregator::MainWidget::slotFeedFetched(Feed *feed)
{
// iterate through the articles (once again) to do notifications properly
if (feed->articles().count() > 0)
{
QList<Article> articles = feed->articles();
QList<Article>::ConstIterator it;
QList<Article>::ConstIterator end = articles.end();
for (it = articles.begin(); it != end; ++it)
{
if ((*it).status()==Akregator::New && ((*it).feed()->useNotification() || Settings::useNotifications()))
{
NotificationManager::self()->slotNotifyArticle(*it);
}
}
}
}
void Akregator::MainWidget::slotArticleSelected(const Akregator::Article& article)
{
if (m_viewMode == CombinedView)
return;
m_markReadTimer->stop();
assert( article.isNull() || article.feed() );
KToggleAction* const maai = qobject_cast<KToggleAction*>( m_actionManager->action( "article_set_status_important" ) );
assert( maai );
maai->setChecked( article.keep() );
m_articleViewer->showArticle( article );
if ( article.isNull() || article.status() == Akregator::Read )
return;
if ( !Settings::useMarkReadDelay() )
return;
const int delay = Settings::markReadDelay();
if ( delay > 0 )
{
m_markReadTimer->start( delay * 1000 );
}
else
{
Akregator::ArticleModifyJob* job = new Akregator::ArticleModifyJob;
const Akregator::ArticleId aid = { article.feed()->xmlUrl(), article.guid() };
job->setStatus( aid, Akregator::Read );
job->start();
}
}
void Akregator::MainWidget::slotMouseButtonPressed(int button, const KUrl& url)
{
if (button != Qt::MidButton)
return;
if (!url.isValid())
return;
OpenUrlRequest req(url);
switch (Settings::mMBBehaviour())
{
case Settings::EnumMMBBehaviour::OpenInExternalBrowser:
req.setOptions(OpenUrlRequest::ExternalBrowser);
break;
case Settings::EnumMMBBehaviour::OpenInBackground:
req.setOptions(OpenUrlRequest::NewTab);
req.setOpenInBackground(true);
break;
default:
req.setOptions(OpenUrlRequest::NewTab);
req.setOpenInBackground(false);
}
Kernel::self()->frameManager()->slotOpenUrlRequest(req);
}
void Akregator::MainWidget::slotOpenHomepage()
{
Feed* feed = dynamic_cast<Feed *>( m_selectionController->selectedSubscription() );
if (!feed)
return;
KUrl url(feed->htmlUrl());
if (url.isValid())
{
OpenUrlRequest req(feed->htmlUrl());
req.setOptions(OpenUrlRequest::ExternalBrowser);
Kernel::self()->frameManager()->slotOpenUrlRequest(req);
}
}
void Akregator::MainWidget::slotOpenCurrentArticleInBrowser()
{
slotOpenArticleInBrowser( m_selectionController->currentArticle() );
}
void Akregator::MainWidget::slotOpenArticleInBrowser(const Akregator::Article& article)
{
if (!article.isNull() && article.link().isValid())
{
OpenUrlRequest req(article.link());
req.setOptions(OpenUrlRequest::ExternalBrowser);
Kernel::self()->frameManager()->slotOpenUrlRequest(req);
}
}
void Akregator::MainWidget::slotOpenCurrentArticle()
{
Article article = m_selectionController->currentArticle();
if ( article.isNull() )
return;
const KUrl url = article.link();
if ( !url.isValid() )
return;
OpenUrlRequest req( url );
req.setOptions( OpenUrlRequest::NewTab );
// TODO: (re-)add a setting for foreground/background
// and use it here
//req.setOpenInBackground( true );
Kernel::self()->frameManager()->slotOpenUrlRequest( req );
}
void Akregator::MainWidget::slotCopyLinkAddress()
{
const Article article = m_selectionController->currentArticle();
if(article.isNull())
return;
QString link;
if (article.link().isValid())
{
link = article.link().url();
QClipboard *cb = QApplication::clipboard();
cb->setText(link, QClipboard::Clipboard);
// don't set url to selection as it's a no-no according to a fd.o spec
//cb->setText(link, QClipboard::Selection);
}
}
void Akregator::MainWidget::slotFeedUrlDropped(KUrl::List &urls, TreeNode* after, Folder* parent)
{
Q_FOREACH ( const KUrl& i, urls )
addFeed( i.prettyUrl(), after, parent, false );
}
void Akregator::MainWidget::slotToggleShowQuickFilter()
{
if ( Settings::showQuickFilter() )
{
Settings::setShowQuickFilter(false);
m_searchBar->slotClearSearch();
m_searchBar->hide();
}
else
{
Settings::setShowQuickFilter(true);
if (!m_displayingAboutPage)
m_searchBar->show();
}
}
void Akregator::MainWidget::slotArticleDelete()
{
if ( m_viewMode == CombinedView )
return;
QList<Article> articles = m_selectionController->selectedArticles();
QString msg;
switch (articles.count())
{
case 0:
return;
case 1:
msg = i18n("<qt>Are you sure you want to delete article <b>%1</b>?</qt>", Qt::escape(articles.first().title()));
break;
default:
msg = i18n("<qt>Are you sure you want to delete the %1 selected articles?</qt>", articles.count());
}
if ( KMessageBox::warningContinueCancel( this,
msg, i18n( "Delete Article" ),
KStandardGuiItem::del(),
KStandardGuiItem::cancel(),
"Disable delete article confirmation" ) != KMessageBox::Continue )
return;
TreeNode* const selected = m_selectionController->selectedSubscription();
if ( selected )
selected->setNotificationMode( false );
Akregator::ArticleDeleteJob* job = new Akregator::ArticleDeleteJob;
Q_FOREACH( const Akregator::Article i, articles )
{
Feed* const feed = i.feed();
assert( feed );
const Akregator::ArticleId aid = { feed->xmlUrl(), i.guid() };
job->appendArticleId( aid );
}
job->start();
if ( selected )
selected->setNotificationMode( true );
}
void Akregator::MainWidget::slotArticleToggleKeepFlag( bool )
{
const QList<Article> articles = m_selectionController->selectedArticles();
if (articles.isEmpty())
return;
bool allFlagsSet = true;
Q_FOREACH ( const Akregator::Article i, articles )
{
allFlagsSet = allFlagsSet && i.keep();
if ( !allFlagsSet )
break;
}
Akregator::ArticleModifyJob* job = new Akregator::ArticleModifyJob;
Q_FOREACH ( const Akregator::Article i, articles )
{
const Akregator::ArticleId aid = { i.feed()->xmlUrl(), i.guid() };
job->setKeep( aid, !allFlagsSet );
}
job->start();
}
namespace {
void setSelectedArticleStatus( const Akregator::AbstractSelectionController* controller, int status )
{
const QList<Akregator::Article> articles = controller->selectedArticles();
if (articles.isEmpty())
return;
Akregator::ArticleModifyJob* job = new Akregator::ArticleModifyJob;
Q_FOREACH ( const Akregator::Article i, articles )
{
const Akregator::ArticleId aid = { i.feed()->xmlUrl(), i.guid() };
job->setStatus( aid, status );
}
job->start();
}
}
void Akregator::MainWidget::slotSetSelectedArticleRead()
{
::setSelectedArticleStatus( m_selectionController, Akregator::Read );
}
void Akregator::MainWidget::slotTextToSpeechRequest()
{
if (Kernel::self()->frameManager()->currentFrame() == m_mainFrame)
{
if (m_viewMode != CombinedView)
{
// in non-combined view, read selected articles
#ifdef __GNUC__
#warning "kde4:readd speechclient";
#endif
//SpeechClient::self()->slotSpeak(m_selectionController->selectedArticles());
// TODO: if article viewer has a selection, read only the selected text?
}
else
{
if (m_selectionController->selectedSubscription())
{
//TODO: read articles in current node, respecting quick filter!
}
}
}
else
{
// TODO: read selected page viewer
}
}
void Akregator::MainWidget::slotSetSelectedArticleUnread()
{
::setSelectedArticleStatus( m_selectionController, Akregator::Unread );
}
void Akregator::MainWidget::slotSetSelectedArticleNew()
{
::setSelectedArticleStatus( m_selectionController, Akregator::New );
}
void Akregator::MainWidget::slotSetCurrentArticleReadDelayed()
{
const Article article = m_selectionController->currentArticle();
if (article.isNull())
return;
Akregator::ArticleModifyJob* const job = new Akregator::ArticleModifyJob;
const Akregator::ArticleId aid = { article.feed()->xmlUrl(), article.guid() };
job->setStatus( aid, Akregator::Read );
job->start();
}
void Akregator::MainWidget::slotMouseOverInfo(const KFileItem& kifi)
{
m_mainFrame->slotSetStatusText( kifi.isNull() ? QString() : kifi.url().prettyUrl() );
}
void Akregator::MainWidget::readProperties(const KConfigGroup &config)
{
if ( !Settings::resetQuickFilterOnNodeChange() )
{
// read filter settings
m_searchBar->slotSetText(config.readEntry("searchLine"));
m_searchBar->slotSetStatus(config.readEntry("searchCombo").toInt());
}
}
void Akregator::MainWidget::saveProperties(KConfigGroup & config)
{
// save filter settings
config.writeEntry("searchLine", m_searchBar->text());
config.writeEntry("searchCombo", m_searchBar->status());
}
#include "mainwidget.moc"
|
//===-- WebAssemblyMCTargetDesc.cpp - WebAssembly Target Descriptions -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file provides WebAssembly-specific target descriptions.
///
//===----------------------------------------------------------------------===//
#include "WebAssemblyMCTargetDesc.h"
#include "InstPrinter/WebAssemblyInstPrinter.h"
#include "WebAssemblyMCAsmInfo.h"
#include "WebAssemblyTargetStreamer.h"
#include "llvm/MC/MCCodeGenInfo.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;
#define DEBUG_TYPE "wasm-mc-target-desc"
#define GET_INSTRINFO_MC_DESC
#include "WebAssemblyGenInstrInfo.inc"
#define GET_SUBTARGETINFO_MC_DESC
#include "WebAssemblyGenSubtargetInfo.inc"
#define GET_REGINFO_MC_DESC
#include "WebAssemblyGenRegisterInfo.inc"
static MCAsmInfo *createMCAsmInfo(const MCRegisterInfo & /*MRI*/,
const Triple &TT) {
return new WebAssemblyMCAsmInfo(TT);
}
static MCInstrInfo *createMCInstrInfo() {
MCInstrInfo *X = new MCInstrInfo();
InitWebAssemblyMCInstrInfo(X);
return X;
}
static MCInstPrinter *createMCInstPrinter(const Triple & /*T*/,
unsigned SyntaxVariant,
const MCAsmInfo &MAI,
const MCInstrInfo &MII,
const MCRegisterInfo &MRI) {
assert(SyntaxVariant == 0);
return new WebAssemblyInstPrinter(MAI, MII, MRI);
}
static MCCodeEmitter *createCodeEmitter(const MCInstrInfo &MCII,
const MCRegisterInfo & /*MRI*/,
MCContext &Ctx) {
return createWebAssemblyMCCodeEmitter(MCII, Ctx);
}
static MCAsmBackend *createAsmBackend(const Target & /*T*/,
const MCRegisterInfo & /*MRI*/,
const Triple &TT, StringRef /*CPU*/) {
return createWebAssemblyAsmBackend(TT);
}
static MCSubtargetInfo *createMCSubtargetInfo(const Triple &TT, StringRef CPU,
StringRef FS) {
return createWebAssemblyMCSubtargetInfoImpl(TT, CPU, FS);
}
static MCTargetStreamer *
createObjectTargetStreamer(MCStreamer &S, const MCSubtargetInfo & /*STI*/) {
return new WebAssemblyTargetELFStreamer(S);
}
static MCTargetStreamer *createAsmTargetStreamer(MCStreamer &S,
formatted_raw_ostream &OS,
MCInstPrinter * /*InstPrint*/,
bool /*isVerboseAsm*/) {
return new WebAssemblyTargetAsmStreamer(S, OS);
}
// Force static initialization.
extern "C" void LLVMInitializeWebAssemblyTargetMC() {
for (Target *T : {&TheWebAssemblyTarget32, &TheWebAssemblyTarget64}) {
// Register the MC asm info.
RegisterMCAsmInfoFn X(*T, createMCAsmInfo);
// Register the MC instruction info.
TargetRegistry::RegisterMCInstrInfo(*T, createMCInstrInfo);
// Register the MCInstPrinter.
TargetRegistry::RegisterMCInstPrinter(*T, createMCInstPrinter);
// Register the MC code emitter.
TargetRegistry::RegisterMCCodeEmitter(*T, createCodeEmitter);
// Register the ASM Backend.
TargetRegistry::RegisterMCAsmBackend(*T, createAsmBackend);
// Register the MC subtarget info.
TargetRegistry::RegisterMCSubtargetInfo(*T, createMCSubtargetInfo);
// Register the object target streamer.
TargetRegistry::RegisterObjectTargetStreamer(*T,
createObjectTargetStreamer);
// Register the asm target streamer.
TargetRegistry::RegisterAsmTargetStreamer(*T, createAsmTargetStreamer);
}
}
[WebAsssembly] Register the MC register info.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@257525 91177308-0d34-0410-b5e6-96231b3b80d8
//===-- WebAssemblyMCTargetDesc.cpp - WebAssembly Target Descriptions -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file provides WebAssembly-specific target descriptions.
///
//===----------------------------------------------------------------------===//
#include "WebAssemblyMCTargetDesc.h"
#include "InstPrinter/WebAssemblyInstPrinter.h"
#include "WebAssemblyMCAsmInfo.h"
#include "WebAssemblyTargetStreamer.h"
#include "llvm/MC/MCCodeGenInfo.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;
#define DEBUG_TYPE "wasm-mc-target-desc"
#define GET_INSTRINFO_MC_DESC
#include "WebAssemblyGenInstrInfo.inc"
#define GET_SUBTARGETINFO_MC_DESC
#include "WebAssemblyGenSubtargetInfo.inc"
#define GET_REGINFO_MC_DESC
#include "WebAssemblyGenRegisterInfo.inc"
static MCAsmInfo *createMCAsmInfo(const MCRegisterInfo & /*MRI*/,
const Triple &TT) {
return new WebAssemblyMCAsmInfo(TT);
}
static MCInstrInfo *createMCInstrInfo() {
MCInstrInfo *X = new MCInstrInfo();
InitWebAssemblyMCInstrInfo(X);
return X;
}
static MCRegisterInfo *createMCRegisterInfo(const Triple & /*T*/) {
MCRegisterInfo *X = new MCRegisterInfo();
InitWebAssemblyMCRegisterInfo(X, 0);
return X;
}
static MCInstPrinter *createMCInstPrinter(const Triple & /*T*/,
unsigned SyntaxVariant,
const MCAsmInfo &MAI,
const MCInstrInfo &MII,
const MCRegisterInfo &MRI) {
assert(SyntaxVariant == 0);
return new WebAssemblyInstPrinter(MAI, MII, MRI);
}
static MCCodeEmitter *createCodeEmitter(const MCInstrInfo &MCII,
const MCRegisterInfo & /*MRI*/,
MCContext &Ctx) {
return createWebAssemblyMCCodeEmitter(MCII, Ctx);
}
static MCAsmBackend *createAsmBackend(const Target & /*T*/,
const MCRegisterInfo & /*MRI*/,
const Triple &TT, StringRef /*CPU*/) {
return createWebAssemblyAsmBackend(TT);
}
static MCSubtargetInfo *createMCSubtargetInfo(const Triple &TT, StringRef CPU,
StringRef FS) {
return createWebAssemblyMCSubtargetInfoImpl(TT, CPU, FS);
}
static MCTargetStreamer *
createObjectTargetStreamer(MCStreamer &S, const MCSubtargetInfo & /*STI*/) {
return new WebAssemblyTargetELFStreamer(S);
}
static MCTargetStreamer *createAsmTargetStreamer(MCStreamer &S,
formatted_raw_ostream &OS,
MCInstPrinter * /*InstPrint*/,
bool /*isVerboseAsm*/) {
return new WebAssemblyTargetAsmStreamer(S, OS);
}
// Force static initialization.
extern "C" void LLVMInitializeWebAssemblyTargetMC() {
for (Target *T : {&TheWebAssemblyTarget32, &TheWebAssemblyTarget64}) {
// Register the MC asm info.
RegisterMCAsmInfoFn X(*T, createMCAsmInfo);
// Register the MC instruction info.
TargetRegistry::RegisterMCInstrInfo(*T, createMCInstrInfo);
// Register the MC register info.
TargetRegistry::RegisterMCRegInfo(*T, createMCRegisterInfo);
// Register the MCInstPrinter.
TargetRegistry::RegisterMCInstPrinter(*T, createMCInstPrinter);
// Register the MC code emitter.
TargetRegistry::RegisterMCCodeEmitter(*T, createCodeEmitter);
// Register the ASM Backend.
TargetRegistry::RegisterMCAsmBackend(*T, createAsmBackend);
// Register the MC subtarget info.
TargetRegistry::RegisterMCSubtargetInfo(*T, createMCSubtargetInfo);
// Register the object target streamer.
TargetRegistry::RegisterObjectTargetStreamer(*T,
createObjectTargetStreamer);
// Register the asm target streamer.
TargetRegistry::RegisterAsmTargetStreamer(*T, createAsmTargetStreamer);
}
}
|
// Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
// File: BlockFix_UnionFaces.cxx
// Created: Tue Dec 7 17:15:42 2004
// Author: Pavel DURANDIN
#include <BlockFix_UnionFaces.hxx>
#include <Basics_OCCTVersion.hxx>
#include <ShapeAnalysis_WireOrder.hxx>
#include <ShapeAnalysis_Edge.hxx>
#include <ShapeBuild_Edge.hxx>
#include <ShapeBuild_ReShape.hxx>
#include <ShapeExtend_WireData.hxx>
#include <ShapeExtend_CompositeSurface.hxx>
#include <ShapeFix_Face.hxx>
#include <ShapeFix_ComposeShell.hxx>
#include <ShapeFix_SequenceOfWireSegment.hxx>
#include <ShapeFix_WireSegment.hxx>
#include <ShapeFix_Wire.hxx>
#include <ShapeFix_Edge.hxx>
#if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
#include <IntPatch_ImpImpIntersection.hxx>
#else
#include <IntPatch_TheIIIntOfIntersection.hxx>
#endif
#include <BRep_Tool.hxx>
#include <BRep_Builder.hxx>
#include <BRepTools.hxx>
#include <BRepTopAdaptor_TopolTool.hxx>
#include <TopExp.hxx>
#include <TopExp_Explorer.hxx>
#include <TopTools_SequenceOfShape.hxx>
#include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
#include <TopTools_ListOfShape.hxx>
#include <TopTools_ListIteratorOfListOfShape.hxx>
#include <TopTools_MapOfShape.hxx>
#include <TopTools_MapIteratorOfMapOfShape.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Wire.hxx>
#include <TopoDS_Face.hxx>
#include <TopoDS_Solid.hxx>
#include <TopoDS_Vertex.hxx>
#include <TopoDS_Shell.hxx>
#include <TopoDS_Iterator.hxx>
#include <TopoDS_Shape.hxx>
#include <TColGeom_HArray2OfSurface.hxx>
#include <GeomAdaptor_HSurface.hxx>
#include <GeomLib_IsPlanarSurface.hxx>
#include <Geom_Surface.hxx>
#include <Geom_Plane.hxx>
#include <Geom_OffsetSurface.hxx>
#include <Geom_SphericalSurface.hxx>
#include <Geom_CylindricalSurface.hxx>
#include <Geom_SurfaceOfRevolution.hxx>
#include <Geom_SurfaceOfLinearExtrusion.hxx>
#include <Geom_RectangularTrimmedSurface.hxx>
#include <Geom_Curve.hxx>
#include <Geom_Line.hxx>
#include <Geom_Circle.hxx>
#include <Geom2d_Line.hxx>
#include <gp_XY.hxx>
#include <gp_Pnt2d.hxx>
#include <Standard_Failure.hxx>
#include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
//=======================================================================
//function : BlockFix_UnionFaces
//purpose :
//=======================================================================
BlockFix_UnionFaces::BlockFix_UnionFaces()
: myTolerance(Precision::Confusion()),
myOptimumNbFaces(6)
{
}
//=======================================================================
//function : GetTolerance
//purpose :
//=======================================================================
Standard_Real& BlockFix_UnionFaces::GetTolerance()
{
return myTolerance;
}
//=======================================================================
//function : GetOptimumNbFaces
//purpose :
//=======================================================================
Standard_Integer& BlockFix_UnionFaces::GetOptimumNbFaces()
{
return myOptimumNbFaces;
}
//=======================================================================
//function : AddOrdinaryEdges
//purpose : auxilary
// adds edges from the shape to the sequence
// seams and equal edges are dropped
// Returns true if one of original edges dropped
//=======================================================================
static Standard_Boolean AddOrdinaryEdges(TopTools_SequenceOfShape& edges,
const TopoDS_Shape aShape,
Standard_Integer& anIndex)
{
//map of edges
TopTools_MapOfShape aNewEdges;
//add edges without seams
for(TopExp_Explorer exp(aShape,TopAbs_EDGE); exp.More(); exp.Next()) {
TopoDS_Shape edge = exp.Current();
if(aNewEdges.Contains(edge))
aNewEdges.Remove(edge);
else
aNewEdges.Add(edge);
}
Standard_Boolean isDropped = Standard_False;
//merge edges and drop seams
for(Standard_Integer i = 1; i <= edges.Length(); i++) {
TopoDS_Shape current = edges(i);
if(aNewEdges.Contains(current)) {
aNewEdges.Remove(current);
edges.Remove(i);
i--;
if(!isDropped) {
isDropped = Standard_True;
anIndex = i;
}
}
}
//add edges to the sequemce
for(TopTools_MapIteratorOfMapOfShape anIter(aNewEdges); anIter.More(); anIter.Next())
edges.Append(anIter.Key());
return isDropped;
}
//=======================================================================
//function : ClearRts
//purpose : auxilary
//=======================================================================
static Handle(Geom_Surface) ClearRts(const Handle(Geom_Surface)& aSurface)
{
if(aSurface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
Handle(Geom_RectangularTrimmedSurface) rts =
Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurface);
return rts->BasisSurface();
}
return aSurface;
}
//=======================================================================
//function : IsFacesOfSameSolids
//purpose : auxilary
//=======================================================================
static Standard_Boolean IsFacesOfSameSolids
(const TopoDS_Face &theFace1,
const TopoDS_Face &theFace2,
const TopTools_IndexedDataMapOfShapeListOfShape &theMapFaceSolids)
{
Standard_Boolean isSame = Standard_False;
if (theMapFaceSolids.Contains(theFace1) &&
theMapFaceSolids.Contains(theFace2)) {
const TopTools_ListOfShape& aList1 = theMapFaceSolids.FindFromKey(theFace1);
const TopTools_ListOfShape& aList2 = theMapFaceSolids.FindFromKey(theFace2);
if (aList1.Extent() == aList2.Extent()) {
TopTools_ListIteratorOfListOfShape anIter1(aList1);
isSame = Standard_True;
for (; anIter1.More(); anIter1.Next()) {
const TopoDS_Shape &aSolid1 = anIter1.Value();
TopTools_ListIteratorOfListOfShape anIter2(aList2);
for (; anIter2.More(); anIter2.Next()) {
if (aSolid1.IsSame(anIter2.Value())) {
// Same solid is detected. Break the loop
break;
}
}
if (!anIter2.More()) {
// No same solid is detected. Break the loop.
isSame = Standard_False;
break;
}
}
}
}
return isSame;
}
//=======================================================================
//function : IsEdgeValidToMerge
//purpose : Edge is valid if it is not seam or if it is a seam and the face
// has another seam edge.
//=======================================================================
static Standard_Boolean IsEdgeValidToMerge(const TopoDS_Edge &theEdge,
const TopoDS_Face &theFace)
{
Standard_Boolean isValid = Standard_True;
if (BRep_Tool::IsClosed(theEdge, theFace)) {
// This is a seam edge. Check if there are another seam edges on the face.
TopExp_Explorer anExp(theFace, TopAbs_EDGE);
for (; anExp.More(); anExp.Next()) {
const TopoDS_Shape &aShEdge = anExp.Current();
// Skip same edge.
if (theEdge.IsSame(aShEdge)) {
continue;
}
// Check if this edge is a seam.
TopoDS_Edge anEdge = TopoDS::Edge(aShEdge);
if (BRep_Tool::IsClosed(anEdge, theFace)) {
isValid = Standard_False;
break;
}
}
}
return isValid;
}
//=======================================================================
//function : Perform
//purpose :
//=======================================================================
TopoDS_Shape BlockFix_UnionFaces::Perform(const TopoDS_Shape& Shape)
{
Handle(ShapeBuild_ReShape) myContext = new ShapeBuild_ReShape;
TopoDS_Shape aResShape = myContext->Apply(Shape);
// Fill Map of faces as keys and list of solids or shells as items.
TopTools_IndexedDataMapOfShapeListOfShape aMapFaceSoOrSh;
TopAbs_ShapeEnum aType = Shape.ShapeType();
if (aType != TopAbs_SHELL) {
aType = TopAbs_SOLID;
}
TopExp::MapShapesAndAncestors
(Shape, TopAbs_FACE, aType, aMapFaceSoOrSh);
// processing each solid
TopExp_Explorer exps;
for (exps.Init(Shape, aType); exps.More(); exps.Next()) {
TopoDS_Shape aSoOrSh = exps.Current();
// creating map of edge faces
TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
TopExp::MapShapesAndAncestors(aSoOrSh, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
// map of processed shapes
TopTools_MapOfShape aProcessed;
Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
Standard_Integer NbModif = 0;
Standard_Boolean hasFailed = Standard_False;
Standard_Real tol = Min(Max(Precision::Confusion(), myTolerance/10.), 0.1);
// count faces
int nbf = 0;
TopExp_Explorer exp;
TopTools_MapOfShape mapF;
for (exp.Init(aSoOrSh, TopAbs_FACE); exp.More(); exp.Next()) {
if (mapF.Add(exp.Current()))
nbf++;
}
bool doUnion = ((myOptimumNbFaces == 0) ||
((myOptimumNbFaces > 0) && (nbf > myOptimumNbFaces)));
// processing each face
mapF.Clear();
for (exp.Init(aSoOrSh, TopAbs_FACE); exp.More() && doUnion; exp.Next()) {
TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
if (aProcessed.Contains(aFace))
continue;
Standard_Integer dummy;
TopTools_SequenceOfShape edges;
AddOrdinaryEdges(edges,aFace,dummy);
TopTools_SequenceOfShape faces;
faces.Append(aFace);
//surface and location to construct result
TopLoc_Location aBaseLocation;
Handle(Geom_Surface) aBaseSurface = BRep_Tool::Surface(aFace,aBaseLocation);
aBaseSurface = ClearRts(aBaseSurface);
// find adjacent faces to union
Standard_Integer i;
for (i = 1; i <= edges.Length(); i++) {
TopoDS_Edge edge = TopoDS::Edge(edges(i));
if (BRep_Tool::Degenerated(edge) || !IsEdgeValidToMerge(edge, aFace))
continue;
const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
TopTools_ListIteratorOfListOfShape anIter(aList);
for (; anIter.More(); anIter.Next()) {
TopoDS_Face anCheckedFace = TopoDS::Face(anIter.Value().Oriented(TopAbs_FORWARD));
if (anCheckedFace.IsSame(aFace))
continue;
if (aProcessed.Contains(anCheckedFace))
continue;
if (!IsEdgeValidToMerge(edge, anCheckedFace)) {
// Skip seam edge.
continue;
}
// Check if faces belong to same solids.
if (!IsFacesOfSameSolids(aFace, anCheckedFace, aMapFaceSoOrSh)) {
continue;
}
if (IsSameDomain(aFace,anCheckedFace)) {
if (aList.Extent() != 2) {
// non mainfold case is not processed
continue;
}
// replacing pcurves
TopoDS_Face aMockUpFace;
BRep_Builder B;
B.MakeFace(aMockUpFace,aBaseSurface,aBaseLocation,0.);
MovePCurves(aMockUpFace,anCheckedFace);
if (AddOrdinaryEdges(edges,aMockUpFace,dummy)) {
// sequence edges is modified
i = dummy;
}
faces.Append(anCheckedFace);
aProcessed.Add(anCheckedFace);
break;
}
}
}
// all faces collected in the sequence. Perform union of faces
if (faces.Length() > 1) {
NbModif++;
TopoDS_Face aResult;
BRep_Builder B;
B.MakeFace(aResult,aBaseSurface,aBaseLocation,0);
Standard_Integer nbWires = 0;
// connecting wires
while (edges.Length()>0) {
Standard_Boolean isEdge3d = Standard_False;
nbWires++;
TopTools_MapOfShape aVertices;
TopoDS_Wire aWire;
B.MakeWire(aWire);
TopoDS_Edge anEdge = TopoDS::Edge(edges(1));
edges.Remove(1);
isEdge3d |= !BRep_Tool::Degenerated(anEdge);
B.Add(aWire,anEdge);
TopoDS_Vertex V1,V2;
TopExp::Vertices(anEdge,V1,V2);
aVertices.Add(V1);
aVertices.Add(V2);
Standard_Boolean isNewFound = Standard_False;
do {
isNewFound = Standard_False;
for(Standard_Integer j = 1; j <= edges.Length(); j++) {
anEdge = TopoDS::Edge(edges(j));
TopExp::Vertices(anEdge,V1,V2);
if(aVertices.Contains(V1) || aVertices.Contains(V2)) {
isEdge3d |= !BRep_Tool::Degenerated(anEdge);
aVertices.Add(V1);
aVertices.Add(V2);
B.Add(aWire,anEdge);
edges.Remove(j);
j--;
isNewFound = Standard_True;
}
}
} while (isNewFound);
// sorting any type of edges
aWire = TopoDS::Wire(aContext->Apply(aWire));
TopoDS_Face tmpF = TopoDS::Face(aContext->Apply(faces(1).Oriented(TopAbs_FORWARD)));
Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(aWire,tmpF,Precision::Confusion());
sfw->FixReorder();
Standard_Boolean isDegRemoved = Standard_False;
if(!sfw->StatusReorder ( ShapeExtend_FAIL )) {
// clear degenerated edges if at least one with 3d curve exist
if(isEdge3d) {
Handle(ShapeExtend_WireData) sewd = sfw->WireData();
for(Standard_Integer j = 1; j<=sewd->NbEdges();j++) {
TopoDS_Edge E = sewd->Edge(j);
if(BRep_Tool::Degenerated(E)) {
sewd->Remove(j);
isDegRemoved = Standard_True;
j--;
}
}
}
sfw->FixShifted();
if(isDegRemoved)
sfw->FixDegenerated();
}
TopoDS_Wire aWireFixed = sfw->Wire();
aContext->Replace(aWire,aWireFixed);
// add resulting wire
if(isEdge3d) {
B.Add(aResult,aWireFixed);
}
else {
// sorting edges
Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
Standard_Integer nbEdges = sbwd->NbEdges();
// sort degenerated edges and create one edge instead of several ones
ShapeAnalysis_WireOrder sawo(Standard_False, 0);
ShapeAnalysis_Edge sae;
Standard_Integer aLastEdge = nbEdges;
for(Standard_Integer j = 1; j <= nbEdges; j++) {
Standard_Real f,l;
//smh protection on NULL pcurve
Handle(Geom2d_Curve) c2d;
if(!sae.PCurve(sbwd->Edge(j),tmpF,c2d,f,l)) {
aLastEdge--;
continue;
}
sawo.Add(c2d->Value(f).XY(),c2d->Value(l).XY());
}
sawo.Perform();
// constructind one degenerative edge
gp_XY aStart, anEnd, tmp;
Standard_Integer nbFirst = sawo.Ordered(1);
TopoDS_Edge anOrigE = TopoDS::Edge(sbwd->Edge(nbFirst).Oriented(TopAbs_FORWARD));
ShapeBuild_Edge sbe;
TopoDS_Vertex aDummyV;
TopoDS_Edge E = sbe.CopyReplaceVertices(anOrigE,aDummyV,aDummyV);
sawo.XY(nbFirst,aStart,tmp);
sawo.XY(sawo.Ordered(aLastEdge),tmp,anEnd);
gp_XY aVec = anEnd-aStart;
Handle(Geom2d_Line) aLine = new Geom2d_Line(aStart,gp_Dir2d(anEnd-aStart));
B.UpdateEdge(E,aLine,tmpF,0.);
B.Range(E,tmpF,0.,aVec.Modulus());
Handle(Geom_Curve) C3d;
B.UpdateEdge(E,C3d,0.);
B.Degenerated(E,Standard_True);
TopoDS_Wire aW;
B.MakeWire(aW);
B.Add(aW,E);
B.Add(aResult,aW);
}
}
// perform substitution of face
aContext->Replace(aContext->Apply(aFace),aResult);
ShapeFix_Face sff (aResult);
//Intializing by tolerances
sff.SetPrecision(myTolerance);
sff.SetMinTolerance(tol);
sff.SetMaxTolerance(Max(1.,myTolerance*1000.));
//Setting modes
sff.FixOrientationMode() = 0;
//sff.FixWireMode() = 0;
sff.SetContext(aContext);
// Applying the fixes
sff.Perform();
if(sff.Status(ShapeExtend_FAIL))
hasFailed = Standard_True;
// breaking down to several faces
TopoDS_Shape theResult = aContext->Apply(aResult);
for (TopExp_Explorer aFaceExp (theResult,TopAbs_FACE); aFaceExp.More(); aFaceExp.Next()) {
TopoDS_Face aCurrent = TopoDS::Face(aFaceExp.Current().Oriented(TopAbs_FORWARD));
Handle(TColGeom_HArray2OfSurface) grid = new TColGeom_HArray2OfSurface ( 1, 1, 1, 1 );
grid->SetValue ( 1, 1, aBaseSurface );
Handle(ShapeExtend_CompositeSurface) G = new ShapeExtend_CompositeSurface ( grid );
ShapeFix_ComposeShell CompShell;
CompShell.Init ( G, aBaseLocation, aCurrent, ::Precision::Confusion() );//myPrecision
CompShell.SetContext( aContext );
TopTools_SequenceOfShape parts;
ShapeFix_SequenceOfWireSegment wires;
for(TopExp_Explorer W_Exp(aCurrent,TopAbs_WIRE);W_Exp.More();W_Exp.Next()) {
Handle(ShapeExtend_WireData) sbwd =
new ShapeExtend_WireData ( TopoDS::Wire(W_Exp.Current() ));
ShapeFix_WireSegment seg ( sbwd, TopAbs_REVERSED );
wires.Append(seg);
}
CompShell.DispatchWires ( parts,wires );
for (Standard_Integer j=1; j <= parts.Length(); j++ ) {
ShapeFix_Face aFixOrient(TopoDS::Face(parts(j)));
aFixOrient.SetContext(aContext);
aFixOrient.FixOrientation();
}
TopoDS_Shape CompRes;
if ( faces.Length() !=1 ) {
TopoDS_Shell S;
B.MakeShell ( S );
for ( i=1; i <= parts.Length(); i++ )
B.Add ( S, parts(i) );
CompRes = S;
}
else CompRes = parts(1);
aContext->Replace(aCurrent,CompRes);
}
// remove the remaining faces
for(i = 2; i <= faces.Length(); i++)
aContext->Remove(faces(i));
}
} // end processing each face
//TopoDS_Shape aResult = Shape;
if (NbModif > 0 && !hasFailed) {
TopoDS_Shape aResult = aContext->Apply(aSoOrSh);
ShapeFix_Edge sfe;
for (exp.Init(aResult,TopAbs_EDGE); exp.More(); exp.Next()) {
TopoDS_Edge E = TopoDS::Edge(exp.Current());
sfe.FixVertexTolerance (E);
// ptv add fix same parameter
sfe.FixSameParameter(E, myTolerance);
}
myContext->Replace(aSoOrSh, aResult);
}
//else
{
for (exp.Init(aSoOrSh, TopAbs_FACE); exp.More(); exp.Next()) {
TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire;
sfw->SetContext(myContext);
sfw->SetPrecision(myTolerance);
sfw->SetMinTolerance(myTolerance);
sfw->SetMaxTolerance(Max(1.,myTolerance*1000.));
sfw->SetFace(aFace);
for (TopoDS_Iterator iter (aFace,Standard_False); iter.More(); iter.Next()) {
TopoDS_Wire wire = TopoDS::Wire(iter.Value());
sfw->Load(wire);
sfw->FixReorder();
sfw->FixShifted();
}
}
}
} // end processing each solid
aResShape = myContext->Apply(Shape);
return aResShape;
}
//=======================================================================
//function : IsSameDomain
//purpose :
//=======================================================================
bool getCylinder (Handle(Geom_Surface)& theInSurface, gp_Cylinder& theOutCylinder)
{
bool isCylinder = false;
if (theInSurface->IsKind(STANDARD_TYPE(Geom_CylindricalSurface))) {
Handle(Geom_CylindricalSurface) aGC = Handle(Geom_CylindricalSurface)::DownCast(theInSurface);
theOutCylinder = aGC->Cylinder();
isCylinder = true;
}
else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfRevolution))) {
Handle(Geom_SurfaceOfRevolution) aRS =
Handle(Geom_SurfaceOfRevolution)::DownCast(theInSurface);
Handle(Geom_Curve) aBasis = aRS->BasisCurve();
if (aBasis->IsKind(STANDARD_TYPE(Geom_Line))) {
Handle(Geom_Line) aBasisLine = Handle(Geom_Line)::DownCast(aBasis);
gp_Dir aDir = aRS->Direction();
gp_Dir aBasisDir = aBasisLine->Position().Direction();
if (aBasisDir.IsParallel(aDir, Precision::Confusion())) {
// basis line is parallel to the revolution axis: it is a cylinder
gp_Pnt aLoc = aRS->Location();
Standard_Real aR = aBasisLine->Lin().Distance(aLoc);
gp_Ax3 aCylAx (aLoc, aDir);
theOutCylinder = gp_Cylinder(aCylAx, aR);
isCylinder = true;
}
}
}
else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfLinearExtrusion))) {
Handle(Geom_SurfaceOfLinearExtrusion) aLES =
Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(theInSurface);
Handle(Geom_Curve) aBasis = aLES->BasisCurve();
if (aBasis->IsKind(STANDARD_TYPE(Geom_Circle))) {
Handle(Geom_Circle) aBasisCircle = Handle(Geom_Circle)::DownCast(aBasis);
gp_Dir aDir = aLES->Direction();
gp_Dir aBasisDir = aBasisCircle->Position().Direction();
if (aBasisDir.IsParallel(aDir, Precision::Confusion())) {
// basis circle is normal to the extrusion axis: it is a cylinder
gp_Pnt aLoc = aBasisCircle->Location();
Standard_Real aR = aBasisCircle->Radius();
gp_Ax3 aCylAx (aLoc, aDir);
theOutCylinder = gp_Cylinder(aCylAx, aR);
isCylinder = true;
}
}
}
else {
}
return isCylinder;
}
Standard_Boolean BlockFix_UnionFaces::IsSameDomain(const TopoDS_Face& aFace,
const TopoDS_Face& aCheckedFace) const
{
//checking the same handles
TopLoc_Location L1, L2;
Handle(Geom_Surface) S1, S2;
S1 = BRep_Tool::Surface(aFace,L1);
S2 = BRep_Tool::Surface(aCheckedFace,L2);
if (S1 == S2 && L1 == L2)
return true;
// planar and cylindrical cases (IMP 20052)
Standard_Real aPrec = Precision::Confusion();
S1 = BRep_Tool::Surface(aFace);
S2 = BRep_Tool::Surface(aCheckedFace);
S1 = ClearRts(S1);
S2 = ClearRts(S2);
//Handle(Geom_OffsetSurface) aGOFS1, aGOFS2;
//aGOFS1 = Handle(Geom_OffsetSurface)::DownCast(S1);
//aGOFS2 = Handle(Geom_OffsetSurface)::DownCast(S2);
//if (!aGOFS1.IsNull()) S1 = aGOFS1->BasisSurface();
//if (!aGOFS2.IsNull()) S2 = aGOFS2->BasisSurface();
// case of two elementary surfaces: use OCCT tool
// elementary surfaces: ConicalSurface, CylindricalSurface,
// Plane, SphericalSurface and ToroidalSurface
if (S1->IsKind(STANDARD_TYPE(Geom_ElementarySurface)) &&
S2->IsKind(STANDARD_TYPE(Geom_ElementarySurface)))
{
Handle(GeomAdaptor_HSurface) aGA1 = new GeomAdaptor_HSurface(S1);
Handle(GeomAdaptor_HSurface) aGA2 = new GeomAdaptor_HSurface(S2);
Handle(BRepTopAdaptor_TopolTool) aTT1 = new BRepTopAdaptor_TopolTool();
Handle(BRepTopAdaptor_TopolTool) aTT2 = new BRepTopAdaptor_TopolTool();
try {
#if OCC_VERSION_LARGE > 0x06010000
OCC_CATCH_SIGNALS;
#endif
#if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
IntPatch_ImpImpIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
#else
IntPatch_TheIIIntOfIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
#endif
if (!anIIInt.IsDone() || anIIInt.IsEmpty())
return false;
return anIIInt.TangentFaces();
}
catch (Standard_Failure) {
return false;
}
}
// case of two planar surfaces:
// all kinds of surfaces checked, including b-spline and bezier
GeomLib_IsPlanarSurface aPlanarityChecker1 (S1, aPrec);
if (aPlanarityChecker1.IsPlanar()) {
GeomLib_IsPlanarSurface aPlanarityChecker2 (S2, aPrec);
if (aPlanarityChecker2.IsPlanar()) {
gp_Pln aPln1 = aPlanarityChecker1.Plan();
gp_Pln aPln2 = aPlanarityChecker2.Plan();
if (aPln1.Position().Direction().IsParallel(aPln2.Position().Direction(), aPrec) &&
aPln1.Distance(aPln2) < aPrec) {
return true;
}
}
}
// case of two cylindrical surfaces, at least one of which is a swept surface
// swept surfaces: SurfaceOfLinearExtrusion, SurfaceOfRevolution
if ((S1->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
S1->IsKind(STANDARD_TYPE(Geom_SweptSurface))) &&
(S2->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
S2->IsKind(STANDARD_TYPE(Geom_SweptSurface))))
{
gp_Cylinder aCyl1, aCyl2;
if (getCylinder(S1, aCyl1) && getCylinder(S2, aCyl2)) {
if (fabs(aCyl1.Radius() - aCyl2.Radius()) < aPrec) {
gp_Dir aDir1 = aCyl1.Position().Direction();
gp_Dir aDir2 = aCyl2.Position().Direction();
if (aDir1.IsParallel(aDir2, aPrec)) {
gp_Pnt aLoc1 = aCyl1.Location();
gp_Pnt aLoc2 = aCyl2.Location();
gp_Vec aVec12 (aLoc1, aLoc2);
if (aVec12.SquareMagnitude() < aPrec*aPrec ||
aVec12.IsParallel(aDir1, aPrec)) {
return true;
}
}
}
}
}
return false;
}
//=======================================================================
//function : MovePCurves
//purpose :
//=======================================================================
void BlockFix_UnionFaces::MovePCurves(TopoDS_Face& aTarget,
const TopoDS_Face& aSource) const
{
BRep_Builder B;
for(TopExp_Explorer wexp(aSource,TopAbs_WIRE);wexp.More();wexp.Next()) {
Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(TopoDS::Wire(wexp.Current()),
aTarget, Precision::Confusion());
sfw->FixReorder();
Standard_Boolean isReoredFailed = sfw->StatusReorder ( ShapeExtend_FAIL );
sfw->FixEdgeCurves();
if(isReoredFailed)
continue;
sfw->FixShifted();
sfw->FixDegenerated();
// remove degenerated edges from not degenerated points
ShapeAnalysis_Edge sae;
Handle(ShapeExtend_WireData) sewd = sfw->WireData();
for(Standard_Integer i = 1; i<=sewd->NbEdges();i++) {
TopoDS_Edge E = sewd->Edge(i);
if(BRep_Tool::Degenerated(E)&&!sae.HasPCurve(E,aTarget)) {
sewd->Remove(i);
i--;
}
}
TopoDS_Wire ResWire = sfw->Wire();
B.Add(aTarget,ResWire);
}
}
0022495: [CEA 1058] Shape invalide after UnionFaces
// Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
// File: BlockFix_UnionFaces.cxx
// Created: Tue Dec 7 17:15:42 2004
// Author: Pavel DURANDIN
#include <BlockFix_UnionFaces.hxx>
#include <Basics_OCCTVersion.hxx>
#include <ShapeAnalysis_WireOrder.hxx>
#include <ShapeAnalysis_Edge.hxx>
#include <ShapeBuild_Edge.hxx>
#include <ShapeBuild_ReShape.hxx>
#include <ShapeExtend_WireData.hxx>
#include <ShapeExtend_CompositeSurface.hxx>
#include <ShapeFix_Face.hxx>
#include <ShapeFix_ComposeShell.hxx>
#include <ShapeFix_SequenceOfWireSegment.hxx>
#include <ShapeFix_WireSegment.hxx>
#include <ShapeFix_Wire.hxx>
#include <ShapeFix_Edge.hxx>
#if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
#include <IntPatch_ImpImpIntersection.hxx>
#else
#include <IntPatch_TheIIIntOfIntersection.hxx>
#endif
#include <BRep_Tool.hxx>
#include <BRep_Builder.hxx>
#include <BRepTools.hxx>
#include <BRepTopAdaptor_TopolTool.hxx>
#include <TopExp.hxx>
#include <TopExp_Explorer.hxx>
#include <TopTools_SequenceOfShape.hxx>
#include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
#include <TopTools_ListOfShape.hxx>
#include <TopTools_ListIteratorOfListOfShape.hxx>
#include <TopTools_MapOfShape.hxx>
#include <TopTools_MapIteratorOfMapOfShape.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Wire.hxx>
#include <TopoDS_Face.hxx>
#include <TopoDS_Solid.hxx>
#include <TopoDS_Vertex.hxx>
#include <TopoDS_Shell.hxx>
#include <TopoDS_Iterator.hxx>
#include <TopoDS_Shape.hxx>
#include <TColGeom_HArray2OfSurface.hxx>
#include <GeomAdaptor_HSurface.hxx>
#include <GeomLib_IsPlanarSurface.hxx>
#include <Geom_Surface.hxx>
#include <Geom_Plane.hxx>
#include <Geom_OffsetSurface.hxx>
#include <Geom_SphericalSurface.hxx>
#include <Geom_CylindricalSurface.hxx>
#include <Geom_SurfaceOfRevolution.hxx>
#include <Geom_SurfaceOfLinearExtrusion.hxx>
#include <Geom_RectangularTrimmedSurface.hxx>
#include <Geom_Curve.hxx>
#include <Geom_Line.hxx>
#include <Geom_Circle.hxx>
#include <Geom2d_Line.hxx>
#include <gp_XY.hxx>
#include <gp_Pnt2d.hxx>
#include <Standard_Failure.hxx>
#include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
//=======================================================================
//function : BlockFix_UnionFaces
//purpose :
//=======================================================================
BlockFix_UnionFaces::BlockFix_UnionFaces()
: myTolerance(Precision::Confusion()),
myOptimumNbFaces(6)
{
}
//=======================================================================
//function : GetTolerance
//purpose :
//=======================================================================
Standard_Real& BlockFix_UnionFaces::GetTolerance()
{
return myTolerance;
}
//=======================================================================
//function : GetOptimumNbFaces
//purpose :
//=======================================================================
Standard_Integer& BlockFix_UnionFaces::GetOptimumNbFaces()
{
return myOptimumNbFaces;
}
//=======================================================================
//function : AddOrdinaryEdges
//purpose : auxilary
// adds edges from the shape to the sequence
// seams and equal edges are dropped
// Returns true if one of original edges dropped
//=======================================================================
static Standard_Boolean AddOrdinaryEdges(TopTools_SequenceOfShape& edges,
const TopoDS_Shape aShape,
Standard_Integer& anIndex)
{
//map of edges
TopTools_MapOfShape aNewEdges;
//add edges without seams
for(TopExp_Explorer exp(aShape,TopAbs_EDGE); exp.More(); exp.Next()) {
TopoDS_Shape edge = exp.Current();
if(aNewEdges.Contains(edge))
aNewEdges.Remove(edge);
else
aNewEdges.Add(edge);
}
Standard_Boolean isDropped = Standard_False;
//merge edges and drop seams
for(Standard_Integer i = 1; i <= edges.Length(); i++) {
TopoDS_Shape current = edges(i);
if(aNewEdges.Contains(current)) {
aNewEdges.Remove(current);
edges.Remove(i);
i--;
if(!isDropped) {
isDropped = Standard_True;
anIndex = i;
}
}
}
//add edges to the sequemce
for(TopTools_MapIteratorOfMapOfShape anIter(aNewEdges); anIter.More(); anIter.Next())
edges.Append(anIter.Key());
return isDropped;
}
//=======================================================================
//function : ClearRts
//purpose : auxilary
//=======================================================================
static Handle(Geom_Surface) ClearRts(const Handle(Geom_Surface)& aSurface)
{
if(aSurface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
Handle(Geom_RectangularTrimmedSurface) rts =
Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurface);
return rts->BasisSurface();
}
return aSurface;
}
//=======================================================================
//function : IsFacesOfSameSolids
//purpose : auxilary
//=======================================================================
static Standard_Boolean IsFacesOfSameSolids
(const TopoDS_Face &theFace1,
const TopoDS_Face &theFace2,
const TopTools_IndexedDataMapOfShapeListOfShape &theMapFaceSolids)
{
Standard_Boolean isSame = Standard_False;
if (theMapFaceSolids.Contains(theFace1) &&
theMapFaceSolids.Contains(theFace2)) {
const TopTools_ListOfShape& aList1 = theMapFaceSolids.FindFromKey(theFace1);
const TopTools_ListOfShape& aList2 = theMapFaceSolids.FindFromKey(theFace2);
if (aList1.Extent() == aList2.Extent()) {
TopTools_ListIteratorOfListOfShape anIter1(aList1);
isSame = Standard_True;
for (; anIter1.More(); anIter1.Next()) {
const TopoDS_Shape &aSolid1 = anIter1.Value();
TopTools_ListIteratorOfListOfShape anIter2(aList2);
for (; anIter2.More(); anIter2.Next()) {
if (aSolid1.IsSame(anIter2.Value())) {
// Same solid is detected. Break the loop
break;
}
}
if (!anIter2.More()) {
// No same solid is detected. Break the loop.
isSame = Standard_False;
break;
}
}
}
}
return isSame;
}
//=======================================================================
//function : IsEdgeValidToMerge
//purpose : Edge is valid if it is not seam or if it is a seam and the face
// has another seam edge.
//=======================================================================
static Standard_Boolean IsEdgeValidToMerge(const TopoDS_Edge &theEdge,
const TopoDS_Face &theFace)
{
Standard_Boolean isValid = Standard_True;
if (BRep_Tool::IsClosed(theEdge, theFace)) {
// This is a seam edge. Check if there are another seam edges on the face.
TopExp_Explorer anExp(theFace, TopAbs_EDGE);
for (; anExp.More(); anExp.Next()) {
const TopoDS_Shape &aShEdge = anExp.Current();
// Skip same edge.
if (theEdge.IsSame(aShEdge)) {
continue;
}
// Check if this edge is a seam.
TopoDS_Edge anEdge = TopoDS::Edge(aShEdge);
if (BRep_Tool::IsClosed(anEdge, theFace)) {
isValid = Standard_False;
break;
}
}
}
return isValid;
}
//=======================================================================
//function : Perform
//purpose :
//=======================================================================
TopoDS_Shape BlockFix_UnionFaces::Perform(const TopoDS_Shape& Shape)
{
// Fill Map of faces as keys and list of solids or shells as items.
TopTools_IndexedDataMapOfShapeListOfShape aMapFaceSoOrSh;
TopAbs_ShapeEnum aType = Shape.ShapeType();
if (aType != TopAbs_SHELL) {
aType = TopAbs_SOLID;
}
TopExp::MapShapesAndAncestors
(Shape, TopAbs_FACE, aType, aMapFaceSoOrSh);
// processing each solid
Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
TopTools_MapOfShape aProcessed;
TopExp_Explorer exps;
for (exps.Init(Shape, aType); exps.More(); exps.Next()) {
TopoDS_Shape aSoOrSh = exps.Current();
// creating map of edge faces
TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
TopExp::MapShapesAndAncestors(aSoOrSh, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
Standard_Integer NbModif = 0;
Standard_Boolean hasFailed = Standard_False;
Standard_Real tol = Min(Max(Precision::Confusion(), myTolerance/10.), 0.1);
// count faces
int nbf = 0;
TopExp_Explorer exp;
TopTools_MapOfShape mapF;
for (exp.Init(aSoOrSh, TopAbs_FACE); exp.More(); exp.Next()) {
if (mapF.Add(exp.Current()))
nbf++;
}
bool doUnion = ((myOptimumNbFaces == 0) ||
((myOptimumNbFaces > 0) && (nbf > myOptimumNbFaces)));
// processing each face
mapF.Clear();
for (exp.Init(aSoOrSh, TopAbs_FACE); exp.More() && doUnion; exp.Next()) {
TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
if (aProcessed.Contains(aFace)) {
continue;
}
Standard_Integer dummy;
TopTools_SequenceOfShape edges;
AddOrdinaryEdges(edges,aFace,dummy);
TopTools_SequenceOfShape faces;
faces.Append(aFace);
//surface and location to construct result
TopLoc_Location aBaseLocation;
Handle(Geom_Surface) aBaseSurface = BRep_Tool::Surface(aFace,aBaseLocation);
aBaseSurface = ClearRts(aBaseSurface);
aBaseSurface = Handle(Geom_Surface)::DownCast(aBaseSurface->Copy());
// find adjacent faces to union
Standard_Integer i;
for (i = 1; i <= edges.Length(); i++) {
TopoDS_Edge edge = TopoDS::Edge(edges(i));
if (BRep_Tool::Degenerated(edge) || !IsEdgeValidToMerge(edge, aFace))
continue;
const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
TopTools_ListIteratorOfListOfShape anIter(aList);
for (; anIter.More(); anIter.Next()) {
TopoDS_Face anCheckedFace = TopoDS::Face(anIter.Value().Oriented(TopAbs_FORWARD));
if (anCheckedFace.IsSame(aFace))
continue;
if (aProcessed.Contains(anCheckedFace))
continue;
if (!IsEdgeValidToMerge(edge, anCheckedFace)) {
// Skip seam edge.
continue;
}
// Check if faces belong to same solids.
if (!IsFacesOfSameSolids(aFace, anCheckedFace, aMapFaceSoOrSh)) {
continue;
}
if (IsSameDomain(aFace,anCheckedFace)) {
if (aList.Extent() != 2) {
// non mainfold case is not processed
continue;
}
// replacing pcurves
TopoDS_Face aMockUpFace;
BRep_Builder B;
B.MakeFace(aMockUpFace,aBaseSurface,aBaseLocation,0.);
MovePCurves(aMockUpFace,anCheckedFace);
if (AddOrdinaryEdges(edges,aMockUpFace,dummy)) {
// sequence edges is modified
i = dummy;
}
faces.Append(anCheckedFace);
aProcessed.Add(anCheckedFace);
break;
}
}
}
// all faces collected in the sequence. Perform union of faces
if (faces.Length() > 1) {
NbModif++;
TopoDS_Face aResult;
BRep_Builder B;
B.MakeFace(aResult,aBaseSurface,aBaseLocation,0);
Standard_Integer nbWires = 0;
// connecting wires
while (edges.Length()>0) {
Standard_Boolean isEdge3d = Standard_False;
nbWires++;
TopTools_MapOfShape aVertices;
TopoDS_Wire aWire;
B.MakeWire(aWire);
TopoDS_Edge anEdge = TopoDS::Edge(edges(1));
edges.Remove(1);
isEdge3d |= !BRep_Tool::Degenerated(anEdge);
B.Add(aWire,anEdge);
TopoDS_Vertex V1,V2;
TopExp::Vertices(anEdge,V1,V2);
aVertices.Add(V1);
aVertices.Add(V2);
Standard_Boolean isNewFound = Standard_False;
do {
isNewFound = Standard_False;
for(Standard_Integer j = 1; j <= edges.Length(); j++) {
anEdge = TopoDS::Edge(edges(j));
TopExp::Vertices(anEdge,V1,V2);
if(aVertices.Contains(V1) || aVertices.Contains(V2)) {
isEdge3d |= !BRep_Tool::Degenerated(anEdge);
aVertices.Add(V1);
aVertices.Add(V2);
B.Add(aWire,anEdge);
edges.Remove(j);
j--;
isNewFound = Standard_True;
}
}
} while (isNewFound);
// sorting any type of edges
aWire = TopoDS::Wire(aContext->Apply(aWire));
Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(aWire,aResult,Precision::Confusion());
sfw->FixReorder();
Standard_Boolean isDegRemoved = Standard_False;
if(!sfw->StatusReorder ( ShapeExtend_FAIL )) {
// clear degenerated edges if at least one with 3d curve exist
if(isEdge3d) {
Handle(ShapeExtend_WireData) sewd = sfw->WireData();
for(Standard_Integer j = 1; j<=sewd->NbEdges();j++) {
TopoDS_Edge E = sewd->Edge(j);
if(BRep_Tool::Degenerated(E)) {
sewd->Remove(j);
isDegRemoved = Standard_True;
j--;
}
}
}
sfw->FixShifted();
if(isDegRemoved)
sfw->FixDegenerated();
}
TopoDS_Wire aWireFixed = sfw->Wire();
aContext->Replace(aWire,aWireFixed);
// add resulting wire
if(isEdge3d) {
B.Add(aResult,aWireFixed);
}
else {
// sorting edges
Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
Standard_Integer nbEdges = sbwd->NbEdges();
// sort degenerated edges and create one edge instead of several ones
ShapeAnalysis_WireOrder sawo(Standard_False, 0);
ShapeAnalysis_Edge sae;
Standard_Integer aLastEdge = nbEdges;
for(Standard_Integer j = 1; j <= nbEdges; j++) {
Standard_Real f,l;
//smh protection on NULL pcurve
Handle(Geom2d_Curve) c2d;
if(!sae.PCurve(sbwd->Edge(j),aResult,c2d,f,l)) {
aLastEdge--;
continue;
}
sawo.Add(c2d->Value(f).XY(),c2d->Value(l).XY());
}
sawo.Perform();
// constructind one degenerative edge
gp_XY aStart, anEnd, tmp;
Standard_Integer nbFirst = sawo.Ordered(1);
TopoDS_Edge anOrigE = TopoDS::Edge(sbwd->Edge(nbFirst).Oriented(TopAbs_FORWARD));
ShapeBuild_Edge sbe;
TopoDS_Vertex aDummyV;
TopoDS_Edge E = sbe.CopyReplaceVertices(anOrigE,aDummyV,aDummyV);
sawo.XY(nbFirst,aStart,tmp);
sawo.XY(sawo.Ordered(aLastEdge),tmp,anEnd);
gp_XY aVec = anEnd-aStart;
Handle(Geom2d_Line) aLine = new Geom2d_Line(aStart,gp_Dir2d(anEnd-aStart));
B.UpdateEdge(E,aLine,aResult,0.);
B.Range(E,aResult,0.,aVec.Modulus());
Handle(Geom_Curve) C3d;
B.UpdateEdge(E,C3d,0.);
B.Degenerated(E,Standard_True);
TopoDS_Wire aW;
B.MakeWire(aW);
B.Add(aW,E);
B.Add(aResult,aW);
}
}
// perform substitution of face
aContext->Replace(aContext->Apply(aFace),aResult);
ShapeFix_Face sff (aResult);
//Intializing by tolerances
sff.SetPrecision(myTolerance);
sff.SetMinTolerance(tol);
sff.SetMaxTolerance(Max(1.,myTolerance*1000.));
//Setting modes
sff.FixOrientationMode() = 0;
//sff.FixWireMode() = 0;
sff.SetContext(aContext);
// Applying the fixes
sff.Perform();
if(sff.Status(ShapeExtend_FAIL))
hasFailed = Standard_True;
// breaking down to several faces
TopoDS_Shape theResult = aContext->Apply(aResult);
for (TopExp_Explorer aFaceExp (theResult,TopAbs_FACE); aFaceExp.More(); aFaceExp.Next()) {
TopoDS_Face aCurrent = TopoDS::Face(aFaceExp.Current().Oriented(TopAbs_FORWARD));
Handle(TColGeom_HArray2OfSurface) grid = new TColGeom_HArray2OfSurface ( 1, 1, 1, 1 );
grid->SetValue ( 1, 1, aBaseSurface );
Handle(ShapeExtend_CompositeSurface) G = new ShapeExtend_CompositeSurface ( grid );
ShapeFix_ComposeShell CompShell;
CompShell.Init ( G, aBaseLocation, aCurrent, ::Precision::Confusion() );//myPrecision
CompShell.SetContext( aContext );
TopTools_SequenceOfShape parts;
ShapeFix_SequenceOfWireSegment wires;
for(TopExp_Explorer W_Exp(aCurrent,TopAbs_WIRE);W_Exp.More();W_Exp.Next()) {
Handle(ShapeExtend_WireData) sbwd =
new ShapeExtend_WireData ( TopoDS::Wire(W_Exp.Current() ));
ShapeFix_WireSegment seg ( sbwd, TopAbs_REVERSED );
wires.Append(seg);
}
CompShell.DispatchWires ( parts,wires );
for (Standard_Integer j=1; j <= parts.Length(); j++ ) {
ShapeFix_Face aFixOrient(TopoDS::Face(parts(j)));
aFixOrient.SetContext(aContext);
aFixOrient.FixOrientation();
}
TopoDS_Shape CompRes;
if ( faces.Length() !=1 ) {
TopoDS_Shell S;
B.MakeShell ( S );
for ( i=1; i <= parts.Length(); i++ )
B.Add ( S, parts(i) );
CompRes = S;
}
else CompRes = parts(1);
aContext->Replace(aCurrent,CompRes);
}
// remove the remaining faces
for(i = 2; i <= faces.Length(); i++)
aContext->Remove(faces(i));
}
} // end processing each face
//TopoDS_Shape aResult = Shape;
if (NbModif > 0 && !hasFailed) {
TopoDS_Shape aResult = aContext->Apply(aSoOrSh);
ShapeFix_Edge sfe;
for (exp.Init(aResult,TopAbs_EDGE); exp.More(); exp.Next()) {
TopoDS_Edge E = TopoDS::Edge(exp.Current());
sfe.FixVertexTolerance (E);
// ptv add fix same parameter
sfe.FixSameParameter(E, myTolerance);
}
}
for (exp.Init(aSoOrSh, TopAbs_FACE); exp.More(); exp.Next()) {
TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire;
sfw->SetContext(aContext);
sfw->SetPrecision(myTolerance);
sfw->SetMinTolerance(myTolerance);
sfw->SetMaxTolerance(Max(1.,myTolerance*1000.));
sfw->SetFace(aFace);
for (TopoDS_Iterator iter (aFace,Standard_False); iter.More(); iter.Next()) {
TopoDS_Wire wire = TopoDS::Wire(iter.Value());
sfw->Load(wire);
sfw->FixReorder();
sfw->FixShifted();
}
}
} // end processing each solid
const TopoDS_Shape aResShape = aContext->Apply(Shape);
return aResShape;
}
//=======================================================================
//function : IsSameDomain
//purpose :
//=======================================================================
bool getCylinder (Handle(Geom_Surface)& theInSurface, gp_Cylinder& theOutCylinder)
{
bool isCylinder = false;
if (theInSurface->IsKind(STANDARD_TYPE(Geom_CylindricalSurface))) {
Handle(Geom_CylindricalSurface) aGC = Handle(Geom_CylindricalSurface)::DownCast(theInSurface);
theOutCylinder = aGC->Cylinder();
isCylinder = true;
}
else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfRevolution))) {
Handle(Geom_SurfaceOfRevolution) aRS =
Handle(Geom_SurfaceOfRevolution)::DownCast(theInSurface);
Handle(Geom_Curve) aBasis = aRS->BasisCurve();
if (aBasis->IsKind(STANDARD_TYPE(Geom_Line))) {
Handle(Geom_Line) aBasisLine = Handle(Geom_Line)::DownCast(aBasis);
gp_Dir aDir = aRS->Direction();
gp_Dir aBasisDir = aBasisLine->Position().Direction();
if (aBasisDir.IsParallel(aDir, Precision::Confusion())) {
// basis line is parallel to the revolution axis: it is a cylinder
gp_Pnt aLoc = aRS->Location();
Standard_Real aR = aBasisLine->Lin().Distance(aLoc);
gp_Ax3 aCylAx (aLoc, aDir);
theOutCylinder = gp_Cylinder(aCylAx, aR);
isCylinder = true;
}
}
}
else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfLinearExtrusion))) {
Handle(Geom_SurfaceOfLinearExtrusion) aLES =
Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(theInSurface);
Handle(Geom_Curve) aBasis = aLES->BasisCurve();
if (aBasis->IsKind(STANDARD_TYPE(Geom_Circle))) {
Handle(Geom_Circle) aBasisCircle = Handle(Geom_Circle)::DownCast(aBasis);
gp_Dir aDir = aLES->Direction();
gp_Dir aBasisDir = aBasisCircle->Position().Direction();
if (aBasisDir.IsParallel(aDir, Precision::Confusion())) {
// basis circle is normal to the extrusion axis: it is a cylinder
gp_Pnt aLoc = aBasisCircle->Location();
Standard_Real aR = aBasisCircle->Radius();
gp_Ax3 aCylAx (aLoc, aDir);
theOutCylinder = gp_Cylinder(aCylAx, aR);
isCylinder = true;
}
}
}
else {
}
return isCylinder;
}
Standard_Boolean BlockFix_UnionFaces::IsSameDomain(const TopoDS_Face& aFace,
const TopoDS_Face& aCheckedFace) const
{
//checking the same handles
TopLoc_Location L1, L2;
Handle(Geom_Surface) S1, S2;
S1 = BRep_Tool::Surface(aFace,L1);
S2 = BRep_Tool::Surface(aCheckedFace,L2);
if (S1 == S2 && L1 == L2)
return true;
// planar and cylindrical cases (IMP 20052)
Standard_Real aPrec = Precision::Confusion();
S1 = BRep_Tool::Surface(aFace);
S2 = BRep_Tool::Surface(aCheckedFace);
S1 = ClearRts(S1);
S2 = ClearRts(S2);
//Handle(Geom_OffsetSurface) aGOFS1, aGOFS2;
//aGOFS1 = Handle(Geom_OffsetSurface)::DownCast(S1);
//aGOFS2 = Handle(Geom_OffsetSurface)::DownCast(S2);
//if (!aGOFS1.IsNull()) S1 = aGOFS1->BasisSurface();
//if (!aGOFS2.IsNull()) S2 = aGOFS2->BasisSurface();
// case of two elementary surfaces: use OCCT tool
// elementary surfaces: ConicalSurface, CylindricalSurface,
// Plane, SphericalSurface and ToroidalSurface
if (S1->IsKind(STANDARD_TYPE(Geom_ElementarySurface)) &&
S2->IsKind(STANDARD_TYPE(Geom_ElementarySurface)))
{
Handle(GeomAdaptor_HSurface) aGA1 = new GeomAdaptor_HSurface(S1);
Handle(GeomAdaptor_HSurface) aGA2 = new GeomAdaptor_HSurface(S2);
Handle(BRepTopAdaptor_TopolTool) aTT1 = new BRepTopAdaptor_TopolTool();
Handle(BRepTopAdaptor_TopolTool) aTT2 = new BRepTopAdaptor_TopolTool();
try {
#if OCC_VERSION_LARGE > 0x06010000
OCC_CATCH_SIGNALS;
#endif
#if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
IntPatch_ImpImpIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
#else
IntPatch_TheIIIntOfIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
#endif
if (!anIIInt.IsDone() || anIIInt.IsEmpty())
return false;
return anIIInt.TangentFaces();
}
catch (Standard_Failure) {
return false;
}
}
// case of two planar surfaces:
// all kinds of surfaces checked, including b-spline and bezier
GeomLib_IsPlanarSurface aPlanarityChecker1 (S1, aPrec);
if (aPlanarityChecker1.IsPlanar()) {
GeomLib_IsPlanarSurface aPlanarityChecker2 (S2, aPrec);
if (aPlanarityChecker2.IsPlanar()) {
gp_Pln aPln1 = aPlanarityChecker1.Plan();
gp_Pln aPln2 = aPlanarityChecker2.Plan();
if (aPln1.Position().Direction().IsParallel(aPln2.Position().Direction(), aPrec) &&
aPln1.Distance(aPln2) < aPrec) {
return true;
}
}
}
// case of two cylindrical surfaces, at least one of which is a swept surface
// swept surfaces: SurfaceOfLinearExtrusion, SurfaceOfRevolution
if ((S1->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
S1->IsKind(STANDARD_TYPE(Geom_SweptSurface))) &&
(S2->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
S2->IsKind(STANDARD_TYPE(Geom_SweptSurface))))
{
gp_Cylinder aCyl1, aCyl2;
if (getCylinder(S1, aCyl1) && getCylinder(S2, aCyl2)) {
if (fabs(aCyl1.Radius() - aCyl2.Radius()) < aPrec) {
gp_Dir aDir1 = aCyl1.Position().Direction();
gp_Dir aDir2 = aCyl2.Position().Direction();
if (aDir1.IsParallel(aDir2, aPrec)) {
gp_Pnt aLoc1 = aCyl1.Location();
gp_Pnt aLoc2 = aCyl2.Location();
gp_Vec aVec12 (aLoc1, aLoc2);
if (aVec12.SquareMagnitude() < aPrec*aPrec ||
aVec12.IsParallel(aDir1, aPrec)) {
return true;
}
}
}
}
}
return false;
}
//=======================================================================
//function : MovePCurves
//purpose :
//=======================================================================
void BlockFix_UnionFaces::MovePCurves(TopoDS_Face& aTarget,
const TopoDS_Face& aSource) const
{
BRep_Builder B;
for(TopExp_Explorer wexp(aSource,TopAbs_WIRE);wexp.More();wexp.Next()) {
Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(TopoDS::Wire(wexp.Current()),
aTarget, Precision::Confusion());
sfw->FixReorder();
Standard_Boolean isReoredFailed = sfw->StatusReorder ( ShapeExtend_FAIL );
sfw->FixEdgeCurves();
if(isReoredFailed)
continue;
sfw->FixShifted();
sfw->FixDegenerated();
// remove degenerated edges from not degenerated points
ShapeAnalysis_Edge sae;
Handle(ShapeExtend_WireData) sewd = sfw->WireData();
for(Standard_Integer i = 1; i<=sewd->NbEdges();i++) {
TopoDS_Edge E = sewd->Edge(i);
if(BRep_Tool::Degenerated(E)&&!sae.HasPCurve(E,aTarget)) {
sewd->Remove(i);
i--;
}
}
TopoDS_Wire ResWire = sfw->Wire();
B.Add(aTarget,ResWire);
}
}
|
#include <fcntl.h>
extern "C" {
#include "signconf/signconf_task.h"
#include "shared/file.h"
#include "shared/duration.h"
}
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include "xmlext-pb/xmlext-rd.h"
#include "xmlext-pb/xmlext-wr.h"
#include "signconf/signconf.pb.h"
#include "policy/kasp.pb.h"
#include "keystate/keystate.pb.h"
static const char *module_str = "signconf_task";
void WriteSignConf(const std::string &path, ::ods::signconf::SignerConfigurationDocument *doc)
{
write_pb_message_to_xml_file(doc,path.c_str());
}
/*
* ForEvery zone Z in zonelist do
* if flag signerConfNeedsWriting is set then
* Assign the data from the zone and associated policy to the signer configuration object
* Write signer configuration XML file at the correct location taken from zonedata signerconfiguration field in the zone
*/
void
perform_signconf(int sockfd, engineconfig_type *config)
{
char buf[ODS_SE_MAXLINE];
const char *policyfile = config->policy_filename;
const char *datastore = config->datastore;
int fd;
GOOGLE_PROTOBUF_VERIFY_VERSION;
// Read the zonelist and policies in from the same directory as
// the database, use serialized protocolbuffer for now, but switch
// to using database table ASAP.
bool bFailedToLoad = false;
::ods::kasp::KaspDocument *kaspDoc = new ::ods::kasp::KaspDocument;
{
std::string policypb(datastore);
policypb += ".policy.pb";
int fd = open(policypb.c_str(),O_RDONLY);
if (kaspDoc->ParseFromFileDescriptor(fd)) {
ods_log_debug("[%s] policies have been loaded",
module_str);
} else {
ods_log_error("[%s] policies could not be loaded from \"%s\"",
module_str,policypb.c_str());
bFailedToLoad = true;
}
close(fd);
}
::ods::keystate::KeyStateDocument *keystateDoc =
new ::ods::keystate::KeyStateDocument;
{
std::string keystatepb(datastore);
keystatepb += ".keystate.pb";
int fd = open(keystatepb.c_str(),O_RDONLY);
if (keystateDoc->ParseFromFileDescriptor(fd)) {
ods_log_debug("[%s] keystates have been loaded",
module_str);
} else {
ods_log_error("[%s] keystates could not be loaded from \"%s\"",
module_str,keystatepb.c_str());
bFailedToLoad = true;
}
close(fd);
}
if (bFailedToLoad) {
delete kaspDoc;
delete keystateDoc;
ods_log_error("[%s] unable to continue",
module_str);
return ;
}
// Go through all the zones and run the enforcer for every one of them.
for (int i=0; i<keystateDoc->zones_size(); ++i) {
const ::ods::keystate::EnforcerZone &ks_zone = keystateDoc->zones(i);
if (!ks_zone.signconf_needs_writing())
continue;
const ::ods::kasp::KASP &
kasp = kaspDoc->kasp();
//printf("%s\n",zone.name().c_str());
const ::ods::kasp::Policy *policy = NULL;
for (int p=0; p<kasp.policies_size(); ++p) {
// lookup the policy associated with this zone
// printf("%s\n",kasp.policies(p).name().c_str());
if (kasp.policies(p).name() == ks_zone.policy()) {
policy = &kasp.policies(p);
ods_log_debug("[%s] policy %s found for zone %s",
module_str,policy->name().c_str(),
ks_zone.name().c_str());
break;
}
}
if (policy == NULL) {
ods_log_error("[%s] policy %s could not be found for zone %s",
module_str,ks_zone.policy().c_str(),
ks_zone.name().c_str());
ods_log_error("[%s] unable to enforce zone %s",
module_str,ks_zone.name().c_str());
continue;
}
::ods::signconf::SignerConfigurationDocument *doc = new ::ods::signconf::SignerConfigurationDocument;
::ods::signconf::Zone *sc_zone = doc->mutable_signerconfiguration()->mutable_zone();
sc_zone->set_name(ks_zone.name());
// Get the Signatures parameters straight from the policy.
::ods::signconf::Signatures *sc_sigs = sc_zone->mutable_signatures();
const ::ods::kasp::Signatures &kp_sigs = policy->signatures();
sc_sigs->set_resign( kp_sigs.resign() );
sc_sigs->set_refresh( kp_sigs.refresh() );
sc_sigs->set_valdefault( kp_sigs.valdefault() );
sc_sigs->set_valdenial( kp_sigs.valdenial() );
sc_sigs->set_jitter( kp_sigs.jitter() );
sc_sigs->set_inceptionoffset( kp_sigs.inceptionoffset() );
// Get the Denial parameters straight from the policy
::ods::signconf::Denial *sc_denial = sc_zone->mutable_denial();
const ::ods::kasp::Denial &kp_denial = policy->denial();
if (kp_denial.has_nsec() && kp_denial.has_nsec3()) {
ods_log_error("[%s] policy %s contains both NSEC and NSEC3 in Denial for zone %s",
module_str,ks_zone.policy().c_str(),
ks_zone.name().c_str());
// skip to the next zone.
continue;
} else {
if (!kp_denial.has_nsec() && !kp_denial.has_nsec3()) {
ods_log_error("[%s] policy %s does not contains NSEC or NSEC3 in Denial for zone %s",
module_str,ks_zone.policy().c_str(),
ks_zone.name().c_str());
// skip to the next zone.
continue;
} else {
// NSEC
if(!kp_denial.has_nsec())
sc_denial->clear_nsec();
else
sc_denial->mutable_nsec();
// NSEC3
if (!kp_denial.has_nsec3())
sc_denial->clear_nsec3();
else {
::ods::signconf::NSEC3 *sc_nsec3 = sc_denial->mutable_nsec3();
const ::ods::kasp::NSEC3 &kp_nsec3 = kp_denial.nsec3();
if (kp_nsec3.has_optout())
sc_nsec3->set_optout( kp_nsec3.optout() );
else
sc_nsec3->clear_optout();
sc_nsec3->set_algorithm( kp_nsec3.algorithm() );
sc_nsec3->set_iterations( kp_nsec3.iterations() );
sc_nsec3->set_salt( kp_nsec3.salt() );
}
}
}
// Get the Keys from the zone data and add them to the signer
// configuration
::ods::signconf::Keys *sc_keys = sc_zone->mutable_keys();
sc_keys->set_ttl( policy->keys().ttl() );
for (int k=0; k<ks_zone.keys_size(); ++k) {
const ::ods::keystate::KeyData &ks_key = ks_zone.keys(k);
::ods::signconf::Key* sc_key = sc_keys->add_keys();
// TODO: is this correct ?
if (ks_key.role() == ::ods::keystate::ZSK)
sc_key->set_flags( 256 ); // ZSK
else
sc_key->set_flags( 257 ); // KSK,CSK
sc_key->set_algorithm( ks_key.algorithm() );
sc_key->set_locator( ks_key.locator() );
sc_key->set_ksk( ks_key.role() == ::ods::keystate::KSK || ks_key.role() == ::ods::keystate::CSK );
sc_key->set_zsk( ks_key.role() == ::ods::keystate::ZSK || ks_key.role() == ::ods::keystate::CSK );
sc_key->set_publish( ks_key.publish() );
// The deactivate flag was intended to allow smooth key rollover.
// With the deactivate flag present a normal rollover would be
// performed where signatures would be replaced immmediately.
// With deactivate flag not present a smooth rollover would be
// performed where signatures that had not yet passed there refresh
// timestamp could be recycled and gradually replaced with
// new signatures.
// sc_key->set_deactivate( !ks_key.active() );
}
const ::ods::kasp::Zone &kp_zone = policy->zone();
sc_zone->set_ttl( kp_zone.ttl() );
sc_zone->set_min( kp_zone.min() );
sc_zone->set_serial( (::ods::signconf::serial) kp_zone.serial() );
if (policy->audit_size() > 0)
sc_zone->set_audit(true);
else
sc_zone->clear_audit();
WriteSignConf(ks_zone.signconf_path(), doc);
delete doc;
}
delete kaspDoc;
delete keystateDoc;
}
static task_type *
signconf_task_perform(task_type *task)
{
perform_signconf(-1,(engineconfig_type *)task->context);
task_cleanup(task);
return NULL;
}
task_type *
signconf_task(engineconfig_type *config, const char *what, const char * who)
{
task_id what_id = task_register(what,
"signconf_task_perform",
signconf_task_perform);
return task_create(what_id, time_now(), who, (void*)config);
}
Turn off signconf_needs_writing flag after writing the signer configuration to disk.
#include <fcntl.h>
extern "C" {
#include "signconf/signconf_task.h"
#include "shared/file.h"
#include "shared/duration.h"
}
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include "xmlext-pb/xmlext-rd.h"
#include "xmlext-pb/xmlext-wr.h"
#include "signconf/signconf.pb.h"
#include "policy/kasp.pb.h"
#include "keystate/keystate.pb.h"
static const char *module_str = "signconf_task";
void WriteSignConf(const std::string &path,
::ods::signconf::SignerConfigurationDocument *doc)
{
write_pb_message_to_xml_file(doc,path.c_str());
}
/*
* ForEvery zone Z in zonelist do
* if flag signerConfNeedsWriting is set then
* Assign the data from the zone and associated policy to the signer
* configuration object
* Write signer configuration XML file at the correct location taken
* from zonedata signerconfiguration field in the zone
*/
void
perform_signconf(int sockfd, engineconfig_type *config)
{
char buf[ODS_SE_MAXLINE];
const char *policyfile = config->policy_filename;
const char *datastore = config->datastore;
int fd;
GOOGLE_PROTOBUF_VERIFY_VERSION;
// Read the zonelist and policies in from the same directory as
// the database, use serialized protocolbuffer for now, but switch
// to using database table ASAP.
bool bFailedToLoad = false;
::ods::kasp::KaspDocument *kaspDoc = new ::ods::kasp::KaspDocument;
{
std::string policypb(datastore);
policypb += ".policy.pb";
int fd = open(policypb.c_str(),O_RDONLY);
if (kaspDoc->ParseFromFileDescriptor(fd)) {
ods_log_debug("[%s] policies have been loaded",
module_str);
} else {
ods_log_error("[%s] policies could not be loaded from \"%s\"",
module_str,policypb.c_str());
bFailedToLoad = true;
}
close(fd);
}
::ods::keystate::KeyStateDocument *keystateDoc =
new ::ods::keystate::KeyStateDocument;
{
std::string keystatepb(datastore);
keystatepb += ".keystate.pb";
int fd = open(keystatepb.c_str(),O_RDONLY);
if (keystateDoc->ParseFromFileDescriptor(fd)) {
ods_log_debug("[%s] keystates have been loaded",
module_str);
} else {
ods_log_error("[%s] keystates could not be loaded from \"%s\"",
module_str,keystatepb.c_str());
bFailedToLoad = true;
}
close(fd);
}
if (bFailedToLoad) {
delete kaspDoc;
delete keystateDoc;
ods_log_error("[%s] unable to continue",
module_str);
return ;
}
// Go through all the zones and write signer configuration when required.
for (int i=0; i<keystateDoc->zones_size(); ++i) {
::ods::keystate::EnforcerZone *ks_zone = keystateDoc->mutable_zones(i);
if (!ks_zone->signconf_needs_writing())
continue;
const ::ods::kasp::KASP &
kasp = kaspDoc->kasp();
//printf("%s\n",zone.name().c_str());
const ::ods::kasp::Policy *policy = NULL;
for (int p=0; p<kasp.policies_size(); ++p) {
// lookup the policy associated with this zone
// printf("%s\n",kasp.policies(p).name().c_str());
if (kasp.policies(p).name() == ks_zone->policy()) {
policy = &kasp.policies(p);
ods_log_debug("[%s] policy %s found for zone %s",
module_str,policy->name().c_str(),
ks_zone->name().c_str());
break;
}
}
if (policy == NULL) {
ods_log_error("[%s] policy %s could not be found for zone %s",
module_str,ks_zone->policy().c_str(),
ks_zone->name().c_str());
ods_log_error("[%s] unable to enforce zone %s",
module_str,ks_zone->name().c_str());
continue;
}
::ods::signconf::SignerConfigurationDocument *doc = new ::ods::signconf::SignerConfigurationDocument;
::ods::signconf::Zone *sc_zone = doc->mutable_signerconfiguration()->mutable_zone();
sc_zone->set_name(ks_zone->name());
// Get the Signatures parameters straight from the policy.
::ods::signconf::Signatures *sc_sigs = sc_zone->mutable_signatures();
const ::ods::kasp::Signatures &kp_sigs = policy->signatures();
sc_sigs->set_resign( kp_sigs.resign() );
sc_sigs->set_refresh( kp_sigs.refresh() );
sc_sigs->set_valdefault( kp_sigs.valdefault() );
sc_sigs->set_valdenial( kp_sigs.valdenial() );
sc_sigs->set_jitter( kp_sigs.jitter() );
sc_sigs->set_inceptionoffset( kp_sigs.inceptionoffset() );
// Get the Denial parameters straight from the policy
::ods::signconf::Denial *sc_denial = sc_zone->mutable_denial();
const ::ods::kasp::Denial &kp_denial = policy->denial();
if (kp_denial.has_nsec() && kp_denial.has_nsec3()) {
ods_log_error("[%s] policy %s contains both NSEC and NSEC3 in Denial for zone %s",
module_str,ks_zone->policy().c_str(),
ks_zone->name().c_str());
// skip to the next zone.
continue;
} else {
if (!kp_denial.has_nsec() && !kp_denial.has_nsec3()) {
ods_log_error("[%s] policy %s does not contains NSEC or NSEC3 in Denial for zone %s",
module_str,ks_zone->policy().c_str(),
ks_zone->name().c_str());
// skip to the next zone.
continue;
} else {
// NSEC
if(!kp_denial.has_nsec())
sc_denial->clear_nsec();
else
sc_denial->mutable_nsec();
// NSEC3
if (!kp_denial.has_nsec3())
sc_denial->clear_nsec3();
else {
::ods::signconf::NSEC3 *sc_nsec3 = sc_denial->mutable_nsec3();
const ::ods::kasp::NSEC3 &kp_nsec3 = kp_denial.nsec3();
if (kp_nsec3.has_optout())
sc_nsec3->set_optout( kp_nsec3.optout() );
else
sc_nsec3->clear_optout();
sc_nsec3->set_algorithm( kp_nsec3.algorithm() );
sc_nsec3->set_iterations( kp_nsec3.iterations() );
sc_nsec3->set_salt( kp_nsec3.salt() );
}
}
}
// Get the Keys from the zone data and add them to the signer
// configuration
::ods::signconf::Keys *sc_keys = sc_zone->mutable_keys();
sc_keys->set_ttl( policy->keys().ttl() );
for (int k=0; k<ks_zone->keys_size(); ++k) {
const ::ods::keystate::KeyData &ks_key = ks_zone->keys(k);
::ods::signconf::Key* sc_key = sc_keys->add_keys();
// TODO: is this correct ?
if (ks_key.role() == ::ods::keystate::ZSK)
sc_key->set_flags( 256 ); // ZSK
else
sc_key->set_flags( 257 ); // KSK,CSK
sc_key->set_algorithm( ks_key.algorithm() );
sc_key->set_locator( ks_key.locator() );
sc_key->set_ksk( ks_key.role() == ::ods::keystate::KSK || ks_key.role() == ::ods::keystate::CSK );
sc_key->set_zsk( ks_key.role() == ::ods::keystate::ZSK || ks_key.role() == ::ods::keystate::CSK );
sc_key->set_publish( ks_key.publish() );
// The deactivate flag was intended to allow smooth key rollover.
// With the deactivate flag present a normal rollover would be
// performed where signatures would be replaced immmediately.
// With deactivate flag not present a smooth rollover would be
// performed where signatures that had not yet passed there refresh
// timestamp could be recycled and gradually replaced with
// new signatures.
// sc_key->set_deactivate( !ks_key.active() );
}
const ::ods::kasp::Zone &kp_zone = policy->zone();
sc_zone->set_ttl( kp_zone.ttl() );
sc_zone->set_min( kp_zone.min() );
sc_zone->set_serial( (::ods::signconf::serial) kp_zone.serial() );
if (policy->audit_size() > 0)
sc_zone->set_audit(true);
else
sc_zone->clear_audit();
WriteSignConf(ks_zone->signconf_path(), doc);
ks_zone->set_signconf_needs_writing(false);
delete doc;
}
// Persist the keystate zones back to disk as they may have
// been changed while writing the signer configurations
if (keystateDoc->IsInitialized()) {
std::string datapath(datastore);
datapath += ".keystate.pb";
int fd = open(datapath.c_str(),O_WRONLY|O_CREAT, 0644);
if (keystateDoc->SerializeToFileDescriptor(fd)) {
ods_log_debug("[%s] key states have been updated",
module_str);
(void)snprintf(buf, ODS_SE_MAXLINE,
"update of key states completed.\n");
ods_writen(sockfd, buf, strlen(buf));
} else {
(void)snprintf(buf, ODS_SE_MAXLINE,
"error: key states file could not be written.\n");
ods_writen(sockfd, buf, strlen(buf));
}
close(fd);
} else {
(void)snprintf(buf, ODS_SE_MAXLINE,
"error: a message in the key states is missing "
"mandatory information.\n");
ods_writen(sockfd, buf, strlen(buf));
}
delete kaspDoc;
delete keystateDoc;
}
static task_type *
signconf_task_perform(task_type *task)
{
perform_signconf(-1,(engineconfig_type *)task->context);
task_cleanup(task);
return NULL;
}
task_type *
signconf_task(engineconfig_type *config, const char *what, const char * who)
{
task_id what_id = task_register(what,
"signconf_task_perform",
signconf_task_perform);
return task_create(what_id, time_now(), who, (void*)config);
}
|
/*
Q Light Controller - Unit tests
qlcchannel_test.cpp
Copyright (C) Heikki Junnila
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
Version 2 as published by the Free Software Foundation.
This program 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. The license is
in the file "COPYING".
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,$
*/
#include <QPointer>
#include <QtTest>
#include <QtXml>
#include "qlcchannel_test.h"
#include "qlccapability.h"
#include "qlcchannel.h"
void QLCChannel_Test::groupList()
{
QStringList list(QLCChannel::groupList());
QVERIFY(list.size() == 12);
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Beam)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Colour)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Effect)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Gobo)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Intensity)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Maintenance)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::NoGroup)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Pan)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Prism)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Shutter)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Speed)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Tilt)));
}
void QLCChannel_Test::name()
{
/* Verify that a name can be set & get for the channel */
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->name().isEmpty());
channel->setName("Channel");
QVERIFY(channel->name() == "Channel");
delete channel;
}
void QLCChannel_Test::group()
{
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->group() == QLCChannel::Intensity);
channel->setGroup(QLCChannel::Beam);
QVERIFY(channel->group() == QLCChannel::Beam);
channel->setGroup(QLCChannel::Group(31337));
QVERIFY(channel->group() == QLCChannel::Group(31337));
delete channel;
}
void QLCChannel_Test::controlByte()
{
QCOMPARE(int(QLCChannel::MSB), 0);
QCOMPARE(int(QLCChannel::LSB), 1);
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->controlByte() == QLCChannel::MSB);
channel->setControlByte(QLCChannel::LSB);
QVERIFY(channel->controlByte() == QLCChannel::LSB);
delete channel;
}
void QLCChannel_Test::colourList()
{
QStringList list(QLCChannel::colourList());
QVERIFY(list.size() == 7);
QVERIFY(list.contains(QLCChannel::colourToString(QLCChannel::NoColour)));
QVERIFY(list.contains(QLCChannel::colourToString(QLCChannel::Red)));
QVERIFY(list.contains(QLCChannel::colourToString(QLCChannel::Green)));
QVERIFY(list.contains(QLCChannel::colourToString(QLCChannel::Blue)));
QVERIFY(list.contains(QLCChannel::colourToString(QLCChannel::Cyan)));
QVERIFY(list.contains(QLCChannel::colourToString(QLCChannel::Magenta)));
QVERIFY(list.contains(QLCChannel::colourToString(QLCChannel::Yellow)));
}
void QLCChannel_Test::colour()
{
QCOMPARE(int(QLCChannel::NoColour), 0);
QCOMPARE(int(QLCChannel::Red), 0xFF0000);
QCOMPARE(int(QLCChannel::Green), 0x00FF00);
QCOMPARE(int(QLCChannel::Blue), 0x0000FF);
QCOMPARE(int(QLCChannel::Cyan), 0x00FFFF);
QCOMPARE(int(QLCChannel::Magenta), 0xFF00FF);
QCOMPARE(int(QLCChannel::Yellow), 0xFFFF00);
QLCChannel* channel = new QLCChannel();
QCOMPARE(channel->colour(), QLCChannel::NoColour);
channel->setColour(QLCChannel::Green);
QCOMPARE(channel->colour(), QLCChannel::Green);
channel->setColour(QLCChannel::Magenta);
QCOMPARE(channel->colour(), QLCChannel::Magenta);
channel->setColour(QLCChannel::NoColour);
QCOMPARE(channel->colour(), QLCChannel::NoColour);
}
void QLCChannel_Test::searchCapabilityByValue()
{
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->capabilities().size() == 0);
QLCCapability* cap1 = new QLCCapability(0, 9, "0-9");
QVERIFY(channel->addCapability(cap1) == true);
QVERIFY(channel->capabilities().size() == 1);
QLCCapability* cap2 = new QLCCapability(10, 19, "10-19");
QVERIFY(channel->addCapability(cap2) == true);
QVERIFY(channel->capabilities().size() == 2);
QLCCapability* cap3 = new QLCCapability(20, 29, "20-29");
QVERIFY(channel->addCapability(cap3) == true);
QVERIFY(channel->capabilities().size() == 3);
QVERIFY(channel->searchCapability(0) == cap1);
QVERIFY(channel->searchCapability(1) == cap1);
QVERIFY(channel->searchCapability(2) == cap1);
QVERIFY(channel->searchCapability(3) == cap1);
QVERIFY(channel->searchCapability(4) == cap1);
QVERIFY(channel->searchCapability(5) == cap1);
QVERIFY(channel->searchCapability(6) == cap1);
QVERIFY(channel->searchCapability(7) == cap1);
QVERIFY(channel->searchCapability(8) == cap1);
QVERIFY(channel->searchCapability(9) == cap1);
QVERIFY(channel->searchCapability(10) == cap2);
QVERIFY(channel->searchCapability(11) == cap2);
QVERIFY(channel->searchCapability(12) == cap2);
QVERIFY(channel->searchCapability(13) == cap2);
QVERIFY(channel->searchCapability(14) == cap2);
QVERIFY(channel->searchCapability(15) == cap2);
QVERIFY(channel->searchCapability(16) == cap2);
QVERIFY(channel->searchCapability(17) == cap2);
QVERIFY(channel->searchCapability(18) == cap2);
QVERIFY(channel->searchCapability(19) == cap2);
QVERIFY(channel->searchCapability(30) == NULL);
delete channel;
}
void QLCChannel_Test::searchCapabilityByName()
{
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->capabilities().size() == 0);
QLCCapability* cap1 = new QLCCapability(0, 9, "0-9");
QVERIFY(channel->addCapability(cap1) == true);
QLCCapability* cap2 = new QLCCapability(10, 19, "10-19");
QVERIFY(channel->addCapability(cap2) == true);
QLCCapability* cap3 = new QLCCapability(20, 29, "20-29");
QVERIFY(channel->addCapability(cap3) == true);
QVERIFY(channel->searchCapability("0-9") == cap1);
QVERIFY(channel->searchCapability("10-19") == cap2);
QVERIFY(channel->searchCapability("20-29") == cap3);
QVERIFY(channel->searchCapability("foo") == NULL);
delete channel;
}
void QLCChannel_Test::addCapability()
{
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->capabilities().size() == 0);
QLCCapability* cap1 = new QLCCapability(15, 19, "15-19");
QVERIFY(channel->addCapability(cap1) == true);
QVERIFY(channel->capabilities().size() == 1);
QVERIFY(channel->capabilities()[0] == cap1);
QLCCapability* cap2 = new QLCCapability(0, 9, "0-9");
QVERIFY(channel->addCapability(cap2) == true);
QVERIFY(channel->capabilities().size() == 2);
QVERIFY(channel->capabilities()[0] == cap1);
QVERIFY(channel->capabilities()[1] == cap2);
/* Completely overlapping with cap2 */
QLCCapability* cap3 = new QLCCapability(5, 6, "5-6");
QVERIFY(channel->addCapability(cap3) == false);
delete cap3;
cap3 = NULL;
/* Partially overlapping from low-end with cap1 */
QLCCapability* cap4 = new QLCCapability(19, 25, "19-25");
QVERIFY(channel->addCapability(cap4) == false);
delete cap4;
cap4 = NULL;
/* Partially overlapping from high end with cap1 */
QLCCapability* cap5 = new QLCCapability(10, 15, "10-15");
QVERIFY(channel->addCapability(cap5) == false);
delete cap5;
cap5 = NULL;
/* Partially overlapping with two ranges at both ends (cap1 & cap2) */
QLCCapability* cap6 = new QLCCapability(8, 16, "8-16");
QVERIFY(channel->addCapability(cap6) == false);
delete cap6;
cap6 = NULL;
/* Completely containing cap1 */
QLCCapability* cap7 = new QLCCapability(14, 20, "14-20");
QVERIFY(channel->addCapability(cap7) == false);
delete cap7;
cap7 = NULL;
/* Non-overlapping, between cap1 & cap2*/
QLCCapability* cap8 = new QLCCapability(10, 14, "10-14");
QVERIFY(channel->addCapability(cap8) == true);
/* Don't delete cap8 because it's now a member of the channel and gets
deleted from the channel's destructor. */
delete channel;
}
void QLCChannel_Test::removeCapability()
{
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->capabilities().size() == 0);
QLCCapability* cap1 = new QLCCapability(10, 20, "10-20");
QVERIFY(channel->addCapability(cap1) == true);
QVERIFY(channel->capabilities().size() == 1);
QLCCapability* cap2 = new QLCCapability(0, 9, "0-9");
QVERIFY(channel->addCapability(cap2) == true);
QVERIFY(channel->capabilities().size() == 2);
QVERIFY(channel->removeCapability(cap2) == true);
QVERIFY(channel->capabilities().size() == 1);
/* cap2 is deleted by QLCChannel::removeCapability() */
QVERIFY(channel->removeCapability(cap2) == false);
QVERIFY(channel->capabilities().size() == 1);
QVERIFY(channel->removeCapability(cap1) == true);
QVERIFY(channel->capabilities().size() == 0);
/* cap1 is deleted by QLCChannel::removeCapability() */
delete channel;
}
void QLCChannel_Test::sortCapabilities()
{
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->capabilities().size() == 0);
QLCCapability* cap1 = new QLCCapability(10, 19, "10-19");
QVERIFY(channel->addCapability(cap1) == true);
QLCCapability* cap2 = new QLCCapability(50, 59, "50-59");
QVERIFY(channel->addCapability(cap2) == true);
QLCCapability* cap3 = new QLCCapability(40, 49, "40-49");
QVERIFY(channel->addCapability(cap3) == true);
QLCCapability* cap4 = new QLCCapability(0, 9, "0-9");
QVERIFY(channel->addCapability(cap4) == true);
QLCCapability* cap5 = new QLCCapability(200, 209, "200-209");
QVERIFY(channel->addCapability(cap5) == true);
QLCCapability* cap6 = new QLCCapability(30, 39, "30-39");
QVERIFY(channel->addCapability(cap6) == true);
QLCCapability* cap7 = new QLCCapability(26, 29, "26-29");
QVERIFY(channel->addCapability(cap7) == true);
QLCCapability* cap8 = new QLCCapability(20, 25, "20-25");
QVERIFY(channel->addCapability(cap8) == true);
QList <QLCCapability*> orig(channel->capabilities());
QVERIFY(orig.at(0) == cap1);
QVERIFY(orig.at(1) == cap2);
QVERIFY(orig.at(2) == cap3);
QVERIFY(orig.at(3) == cap4);
QVERIFY(orig.at(4) == cap5);
QVERIFY(orig.at(5) == cap6);
QVERIFY(orig.at(6) == cap7);
QVERIFY(orig.at(7) == cap8);
channel->sortCapabilities();
QList <QLCCapability*> sorted(channel->capabilities());
QVERIFY(sorted.at(0) == cap4);
QVERIFY(sorted.at(1) == cap1);
QVERIFY(sorted.at(2) == cap8);
QVERIFY(sorted.at(3) == cap7);
QVERIFY(sorted.at(4) == cap6);
QVERIFY(sorted.at(5) == cap3);
QVERIFY(sorted.at(6) == cap2);
QVERIFY(sorted.at(7) == cap5);
delete channel;
}
void QLCChannel_Test::copy()
{
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->capabilities().size() == 0);
channel->setName("Foobar");
channel->setGroup(QLCChannel::Tilt);
channel->setControlByte(QLCChannel::ControlByte(3));
channel->setColour(QLCChannel::Yellow);
QLCCapability* cap1 = new QLCCapability(10, 19, "10-19");
QVERIFY(channel->addCapability(cap1) == true);
QLCCapability* cap2 = new QLCCapability(50, 59, "50-59");
QVERIFY(channel->addCapability(cap2) == true);
QLCCapability* cap3 = new QLCCapability(40, 49, "40-49");
QVERIFY(channel->addCapability(cap3) == true);
QLCCapability* cap4 = new QLCCapability(0, 9, "0-9");
QVERIFY(channel->addCapability(cap4) == true);
QLCCapability* cap5 = new QLCCapability(200, 209, "200-209");
QVERIFY(channel->addCapability(cap5) == true);
QLCCapability* cap6 = new QLCCapability(30, 39, "30-39");
QVERIFY(channel->addCapability(cap6) == true);
QLCCapability* cap7 = new QLCCapability(26, 29, "26-29");
QVERIFY(channel->addCapability(cap7) == true);
QLCCapability* cap8 = new QLCCapability(20, 25, "20-25");
QVERIFY(channel->addCapability(cap8) == true);
/* Create a copy of the original channel */
QLCChannel* copy = new QLCChannel(channel);
QVERIFY(copy->name() == "Foobar");
QVERIFY(copy->group() == QLCChannel::Tilt);
QVERIFY(copy->controlByte() == QLCChannel::ControlByte(3));
QVERIFY(copy->colour() == QLCChannel::Yellow);
/* Verify that the capabilities in the copied channel are also
copies i.e. their pointers are not the same as the originals. */
QList <QLCCapability*> caps(copy->capabilities());
QVERIFY(caps.size() == 8);
QVERIFY(caps.at(0) != cap1);
QVERIFY(caps.at(0)->name() == cap1->name());
QVERIFY(caps.at(0)->min() == cap1->min());
QVERIFY(caps.at(0)->max() == cap1->max());
QVERIFY(caps.at(1) != cap2);
QVERIFY(caps.at(1)->name() == cap2->name());
QVERIFY(caps.at(1)->min() == cap2->min());
QVERIFY(caps.at(1)->max() == cap2->max());
QVERIFY(caps.at(2) != cap3);
QVERIFY(caps.at(2)->name() == cap3->name());
QVERIFY(caps.at(2)->min() == cap3->min());
QVERIFY(caps.at(2)->max() == cap3->max());
QVERIFY(caps.at(3) != cap4);
QVERIFY(caps.at(3)->name() == cap4->name());
QVERIFY(caps.at(3)->min() == cap4->min());
QVERIFY(caps.at(3)->max() == cap4->max());
QVERIFY(caps.at(4) != cap5);
QVERIFY(caps.at(4)->name() == cap5->name());
QVERIFY(caps.at(4)->min() == cap5->min());
QVERIFY(caps.at(4)->max() == cap5->max());
QVERIFY(caps.at(5) != cap6);
QVERIFY(caps.at(5)->name() == cap6->name());
QVERIFY(caps.at(5)->min() == cap6->min());
QVERIFY(caps.at(5)->max() == cap6->max());
QVERIFY(caps.at(6) != cap7);
QVERIFY(caps.at(6)->name() == cap7->name());
QVERIFY(caps.at(6)->min() == cap7->min());
QVERIFY(caps.at(6)->max() == cap7->max());
QVERIFY(caps.at(7) != cap8);
QVERIFY(caps.at(7)->name() == cap8->name());
QVERIFY(caps.at(7)->min() == cap8->min());
QVERIFY(caps.at(7)->max() == cap8->max());
}
void QLCChannel_Test::load()
{
QDomDocument doc;
QDomElement root = doc.createElement("Channel");
root.setAttribute("Name", "Channel1");
doc.appendChild(root);
QDomElement group = doc.createElement("Group");
root.appendChild(group);
group.setAttribute("Byte", 1);
QDomText groupName = doc.createTextNode("Tilt");
group.appendChild(groupName);
QDomElement colour = doc.createElement("Colour");
QDomText colourText = doc.createTextNode(QLCChannel::colourToString(QLCChannel::Cyan));
colour.appendChild(colourText);
root.appendChild(colour);
QDomElement cap1 = doc.createElement("Capability");
root.appendChild(cap1);
cap1.setAttribute("Min", 0);
cap1.setAttribute("Max", 10);
QDomText cap1name = doc.createTextNode("Cap1");
cap1.appendChild(cap1name);
/* Overlaps with cap1, shouldn't appear in the channel */
QDomElement cap2 = doc.createElement("Capability");
root.appendChild(cap2);
cap2.setAttribute("Min", 5);
cap2.setAttribute("Max", 15);
QDomText cap2name = doc.createTextNode("Cap2");
cap2.appendChild(cap2name);
QDomElement cap3 = doc.createElement("Capability");
root.appendChild(cap3);
cap3.setAttribute("Min", 11);
cap3.setAttribute("Max", 20);
QDomText cap3name = doc.createTextNode("Cap3");
cap3.appendChild(cap3name);
/* Invalid capability tag, shouldn't appear in the channel, since it
is not recognized by the channel. */
QDomElement cap4 = doc.createElement("apability");
root.appendChild(cap4);
cap4.setAttribute("Min", 21);
cap4.setAttribute("Max", 30);
QDomText cap4name = doc.createTextNode("Cap4");
cap4.appendChild(cap4name);
/* Missing minimum value, shouldn't appear in the channel, because
loadXML() fails. */
QDomElement cap5 = doc.createElement("Capability");
root.appendChild(cap5);
cap5.setAttribute("Max", 30);
QDomText cap5name = doc.createTextNode("Cap5");
cap5.appendChild(cap5name);
QLCChannel ch;
QVERIFY(ch.loadXML(root) == true);
qDebug() << int(ch.colour());
QVERIFY(ch.name() == "Channel1");
QVERIFY(ch.group() == QLCChannel::Tilt);
QVERIFY(ch.controlByte() == QLCChannel::LSB);
QVERIFY(ch.colour() == QLCChannel::Cyan);
QVERIFY(ch.capabilities().size() == 2);
QVERIFY(ch.capabilities()[0]->name() == "Cap1");
QVERIFY(ch.capabilities()[1]->name() == "Cap3");
}
void QLCChannel_Test::loadWrongRoot()
{
QDomDocument doc;
QDomElement root = doc.createElement("Chanel");
root.setAttribute("Name", "Channel1");
doc.appendChild(root);
QDomElement group = doc.createElement("Group");
root.appendChild(group);
group.setAttribute("Byte", 1);
QDomText groupName = doc.createTextNode("Tilt");
group.appendChild(groupName);
QDomElement cap1 = doc.createElement("Capability");
root.appendChild(cap1);
cap1.setAttribute("Min", 0);
cap1.setAttribute("Max", 10);
QDomText cap1name = doc.createTextNode("Cap1");
cap1.appendChild(cap1name);
/* Overlaps with cap1, shouldn't appear in the channel */
QDomElement cap2 = doc.createElement("Capability");
root.appendChild(cap2);
cap2.setAttribute("Min", 5);
cap2.setAttribute("Max", 15);
QDomText cap2name = doc.createTextNode("Cap2");
cap2.appendChild(cap2name);
QDomElement cap3 = doc.createElement("Capability");
root.appendChild(cap3);
cap3.setAttribute("Min", 11);
cap3.setAttribute("Max", 20);
QDomText cap3name = doc.createTextNode("Cap3");
cap3.appendChild(cap3name);
QLCChannel ch;
QVERIFY(ch.loadXML(root) == false);
QVERIFY(ch.name().isEmpty());
QVERIFY(ch.group() == QLCChannel::Intensity);
QVERIFY(ch.controlByte() == QLCChannel::MSB);
QVERIFY(ch.capabilities().size() == 0);
}
void QLCChannel_Test::save()
{
QLCChannel* channel = new QLCChannel();
channel->setName("Foobar");
channel->setGroup(QLCChannel::Shutter);
channel->setControlByte(QLCChannel::LSB);
QLCCapability* cap1 = new QLCCapability(0, 9, "One");
QVERIFY(channel->addCapability(cap1) == true);
QLCCapability* cap2 = new QLCCapability(10, 19, "Two");
QVERIFY(channel->addCapability(cap2) == true);
QLCCapability* cap3 = new QLCCapability(20, 29, "Three");
QVERIFY(channel->addCapability(cap3) == true);
QLCCapability* cap4 = new QLCCapability(30, 39, "Four");
QVERIFY(channel->addCapability(cap4) == true);
QDomDocument doc;
QDomElement root = doc.createElement("TestRoot");
QVERIFY(channel->saveXML(&doc, &root) == true);
QVERIFY(root.firstChild().toElement().tagName() == "Channel");
QVERIFY(root.firstChild().toElement().attribute("Name") == "Foobar");
bool group = false;
bool capOne = false, capTwo = false, capThree = false, capFour = false;
QDomNode node = root.firstChild().firstChild();
while (node.isNull() == false)
{
QDomElement e = node.toElement();
if (e.tagName() == "Group")
{
group = true;
QVERIFY(e.attribute("Byte") == "1");
QVERIFY(e.text() == "Shutter");
}
else if (e.tagName() == "Capability")
{
if (e.text() == "One" && capOne == false)
capOne = true;
else if (e.text() == "Two" && capTwo == false)
capTwo = true;
else if (e.text() == "Three" && capThree == false)
capThree = true;
else if (e.text() == "Four" && capFour == false)
capFour = true;
else
QFAIL("Same capability saved multiple times");
}
else
{
QFAIL(QString("Unexpected tag: %1").arg(e.tagName())
.toAscii());
}
node = node.nextSibling();
}
QVERIFY(group == true);
QVERIFY(capOne == true);
QVERIFY(capTwo == true);
QVERIFY(capThree == true);
QVERIFY(capFour == true);
delete channel;
}
QTEST_APPLESS_MAIN(QLCChannel_Test)
Fixed QLCChannel tests for 4.1.2 release
/*
Q Light Controller - Unit tests
qlcchannel_test.cpp
Copyright (C) Heikki Junnila
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
Version 2 as published by the Free Software Foundation.
This program 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. The license is
in the file "COPYING".
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,$
*/
#include <QPointer>
#include <QtTest>
#include <QtXml>
#include "qlcchannel_test.h"
#include "qlccapability.h"
#include "qlcchannel.h"
void QLCChannel_Test::groupList()
{
QStringList list(QLCChannel::groupList());
QVERIFY(list.size() == 12);
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Beam)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Colour)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Effect)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Gobo)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Intensity)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Maintenance)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::NoGroup)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Pan)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Prism)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Shutter)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Speed)));
QVERIFY(list.contains(QLCChannel::groupToString(QLCChannel::Tilt)));
}
void QLCChannel_Test::name()
{
/* Verify that a name can be set & get for the channel */
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->name().isEmpty());
channel->setName("Channel");
QVERIFY(channel->name() == "Channel");
delete channel;
}
void QLCChannel_Test::group()
{
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->group() == QLCChannel::Intensity);
channel->setGroup(QLCChannel::Beam);
QVERIFY(channel->group() == QLCChannel::Beam);
channel->setGroup(QLCChannel::Group(31337));
QVERIFY(channel->group() == QLCChannel::Group(31337));
delete channel;
}
void QLCChannel_Test::controlByte()
{
QCOMPARE(int(QLCChannel::MSB), 0);
QCOMPARE(int(QLCChannel::LSB), 1);
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->controlByte() == QLCChannel::MSB);
channel->setControlByte(QLCChannel::LSB);
QVERIFY(channel->controlByte() == QLCChannel::LSB);
delete channel;
}
void QLCChannel_Test::colourList()
{
QStringList list(QLCChannel::colourList());
QVERIFY(list.size() == 8);
QVERIFY(list.contains(QLCChannel::colourToString(QLCChannel::NoColour)));
QVERIFY(list.contains(QLCChannel::colourToString(QLCChannel::Red)));
QVERIFY(list.contains(QLCChannel::colourToString(QLCChannel::Green)));
QVERIFY(list.contains(QLCChannel::colourToString(QLCChannel::Blue)));
QVERIFY(list.contains(QLCChannel::colourToString(QLCChannel::Cyan)));
QVERIFY(list.contains(QLCChannel::colourToString(QLCChannel::Magenta)));
QVERIFY(list.contains(QLCChannel::colourToString(QLCChannel::Yellow)));
QVERIFY(list.contains(QLCChannel::colourToString(QLCChannel::White)));
}
void QLCChannel_Test::colour()
{
QCOMPARE(int(QLCChannel::NoColour), 0);
QCOMPARE(int(QLCChannel::Red), 0xFF0000);
QCOMPARE(int(QLCChannel::Green), 0x00FF00);
QCOMPARE(int(QLCChannel::Blue), 0x0000FF);
QCOMPARE(int(QLCChannel::Cyan), 0x00FFFF);
QCOMPARE(int(QLCChannel::Magenta), 0xFF00FF);
QCOMPARE(int(QLCChannel::Yellow), 0xFFFF00);
QLCChannel* channel = new QLCChannel();
QCOMPARE(channel->colour(), QLCChannel::NoColour);
channel->setColour(QLCChannel::Green);
QCOMPARE(channel->colour(), QLCChannel::Green);
channel->setColour(QLCChannel::Magenta);
QCOMPARE(channel->colour(), QLCChannel::Magenta);
channel->setColour(QLCChannel::NoColour);
QCOMPARE(channel->colour(), QLCChannel::NoColour);
}
void QLCChannel_Test::searchCapabilityByValue()
{
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->capabilities().size() == 0);
QLCCapability* cap1 = new QLCCapability(0, 9, "0-9");
QVERIFY(channel->addCapability(cap1) == true);
QVERIFY(channel->capabilities().size() == 1);
QLCCapability* cap2 = new QLCCapability(10, 19, "10-19");
QVERIFY(channel->addCapability(cap2) == true);
QVERIFY(channel->capabilities().size() == 2);
QLCCapability* cap3 = new QLCCapability(20, 29, "20-29");
QVERIFY(channel->addCapability(cap3) == true);
QVERIFY(channel->capabilities().size() == 3);
QVERIFY(channel->searchCapability(0) == cap1);
QVERIFY(channel->searchCapability(1) == cap1);
QVERIFY(channel->searchCapability(2) == cap1);
QVERIFY(channel->searchCapability(3) == cap1);
QVERIFY(channel->searchCapability(4) == cap1);
QVERIFY(channel->searchCapability(5) == cap1);
QVERIFY(channel->searchCapability(6) == cap1);
QVERIFY(channel->searchCapability(7) == cap1);
QVERIFY(channel->searchCapability(8) == cap1);
QVERIFY(channel->searchCapability(9) == cap1);
QVERIFY(channel->searchCapability(10) == cap2);
QVERIFY(channel->searchCapability(11) == cap2);
QVERIFY(channel->searchCapability(12) == cap2);
QVERIFY(channel->searchCapability(13) == cap2);
QVERIFY(channel->searchCapability(14) == cap2);
QVERIFY(channel->searchCapability(15) == cap2);
QVERIFY(channel->searchCapability(16) == cap2);
QVERIFY(channel->searchCapability(17) == cap2);
QVERIFY(channel->searchCapability(18) == cap2);
QVERIFY(channel->searchCapability(19) == cap2);
QVERIFY(channel->searchCapability(30) == NULL);
delete channel;
}
void QLCChannel_Test::searchCapabilityByName()
{
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->capabilities().size() == 0);
QLCCapability* cap1 = new QLCCapability(0, 9, "0-9");
QVERIFY(channel->addCapability(cap1) == true);
QLCCapability* cap2 = new QLCCapability(10, 19, "10-19");
QVERIFY(channel->addCapability(cap2) == true);
QLCCapability* cap3 = new QLCCapability(20, 29, "20-29");
QVERIFY(channel->addCapability(cap3) == true);
QVERIFY(channel->searchCapability("0-9") == cap1);
QVERIFY(channel->searchCapability("10-19") == cap2);
QVERIFY(channel->searchCapability("20-29") == cap3);
QVERIFY(channel->searchCapability("foo") == NULL);
delete channel;
}
void QLCChannel_Test::addCapability()
{
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->capabilities().size() == 0);
QLCCapability* cap1 = new QLCCapability(15, 19, "15-19");
QVERIFY(channel->addCapability(cap1) == true);
QVERIFY(channel->capabilities().size() == 1);
QVERIFY(channel->capabilities()[0] == cap1);
QLCCapability* cap2 = new QLCCapability(0, 9, "0-9");
QVERIFY(channel->addCapability(cap2) == true);
QVERIFY(channel->capabilities().size() == 2);
QVERIFY(channel->capabilities()[0] == cap1);
QVERIFY(channel->capabilities()[1] == cap2);
/* Completely overlapping with cap2 */
QLCCapability* cap3 = new QLCCapability(5, 6, "5-6");
QVERIFY(channel->addCapability(cap3) == false);
delete cap3;
cap3 = NULL;
/* Partially overlapping from low-end with cap1 */
QLCCapability* cap4 = new QLCCapability(19, 25, "19-25");
QVERIFY(channel->addCapability(cap4) == false);
delete cap4;
cap4 = NULL;
/* Partially overlapping from high end with cap1 */
QLCCapability* cap5 = new QLCCapability(10, 15, "10-15");
QVERIFY(channel->addCapability(cap5) == false);
delete cap5;
cap5 = NULL;
/* Partially overlapping with two ranges at both ends (cap1 & cap2) */
QLCCapability* cap6 = new QLCCapability(8, 16, "8-16");
QVERIFY(channel->addCapability(cap6) == false);
delete cap6;
cap6 = NULL;
/* Completely containing cap1 */
QLCCapability* cap7 = new QLCCapability(14, 20, "14-20");
QVERIFY(channel->addCapability(cap7) == false);
delete cap7;
cap7 = NULL;
/* Non-overlapping, between cap1 & cap2*/
QLCCapability* cap8 = new QLCCapability(10, 14, "10-14");
QVERIFY(channel->addCapability(cap8) == true);
/* Don't delete cap8 because it's now a member of the channel and gets
deleted from the channel's destructor. */
delete channel;
}
void QLCChannel_Test::removeCapability()
{
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->capabilities().size() == 0);
QLCCapability* cap1 = new QLCCapability(10, 20, "10-20");
QVERIFY(channel->addCapability(cap1) == true);
QVERIFY(channel->capabilities().size() == 1);
QLCCapability* cap2 = new QLCCapability(0, 9, "0-9");
QVERIFY(channel->addCapability(cap2) == true);
QVERIFY(channel->capabilities().size() == 2);
QVERIFY(channel->removeCapability(cap2) == true);
QVERIFY(channel->capabilities().size() == 1);
/* cap2 is deleted by QLCChannel::removeCapability() */
QVERIFY(channel->removeCapability(cap2) == false);
QVERIFY(channel->capabilities().size() == 1);
QVERIFY(channel->removeCapability(cap1) == true);
QVERIFY(channel->capabilities().size() == 0);
/* cap1 is deleted by QLCChannel::removeCapability() */
delete channel;
}
void QLCChannel_Test::sortCapabilities()
{
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->capabilities().size() == 0);
QLCCapability* cap1 = new QLCCapability(10, 19, "10-19");
QVERIFY(channel->addCapability(cap1) == true);
QLCCapability* cap2 = new QLCCapability(50, 59, "50-59");
QVERIFY(channel->addCapability(cap2) == true);
QLCCapability* cap3 = new QLCCapability(40, 49, "40-49");
QVERIFY(channel->addCapability(cap3) == true);
QLCCapability* cap4 = new QLCCapability(0, 9, "0-9");
QVERIFY(channel->addCapability(cap4) == true);
QLCCapability* cap5 = new QLCCapability(200, 209, "200-209");
QVERIFY(channel->addCapability(cap5) == true);
QLCCapability* cap6 = new QLCCapability(30, 39, "30-39");
QVERIFY(channel->addCapability(cap6) == true);
QLCCapability* cap7 = new QLCCapability(26, 29, "26-29");
QVERIFY(channel->addCapability(cap7) == true);
QLCCapability* cap8 = new QLCCapability(20, 25, "20-25");
QVERIFY(channel->addCapability(cap8) == true);
QList <QLCCapability*> orig(channel->capabilities());
QVERIFY(orig.at(0) == cap1);
QVERIFY(orig.at(1) == cap2);
QVERIFY(orig.at(2) == cap3);
QVERIFY(orig.at(3) == cap4);
QVERIFY(orig.at(4) == cap5);
QVERIFY(orig.at(5) == cap6);
QVERIFY(orig.at(6) == cap7);
QVERIFY(orig.at(7) == cap8);
channel->sortCapabilities();
QList <QLCCapability*> sorted(channel->capabilities());
QVERIFY(sorted.at(0) == cap4);
QVERIFY(sorted.at(1) == cap1);
QVERIFY(sorted.at(2) == cap8);
QVERIFY(sorted.at(3) == cap7);
QVERIFY(sorted.at(4) == cap6);
QVERIFY(sorted.at(5) == cap3);
QVERIFY(sorted.at(6) == cap2);
QVERIFY(sorted.at(7) == cap5);
delete channel;
}
void QLCChannel_Test::copy()
{
QLCChannel* channel = new QLCChannel();
QVERIFY(channel->capabilities().size() == 0);
channel->setName("Foobar");
channel->setGroup(QLCChannel::Tilt);
channel->setControlByte(QLCChannel::ControlByte(3));
channel->setColour(QLCChannel::Yellow);
QLCCapability* cap1 = new QLCCapability(10, 19, "10-19");
QVERIFY(channel->addCapability(cap1) == true);
QLCCapability* cap2 = new QLCCapability(50, 59, "50-59");
QVERIFY(channel->addCapability(cap2) == true);
QLCCapability* cap3 = new QLCCapability(40, 49, "40-49");
QVERIFY(channel->addCapability(cap3) == true);
QLCCapability* cap4 = new QLCCapability(0, 9, "0-9");
QVERIFY(channel->addCapability(cap4) == true);
QLCCapability* cap5 = new QLCCapability(200, 209, "200-209");
QVERIFY(channel->addCapability(cap5) == true);
QLCCapability* cap6 = new QLCCapability(30, 39, "30-39");
QVERIFY(channel->addCapability(cap6) == true);
QLCCapability* cap7 = new QLCCapability(26, 29, "26-29");
QVERIFY(channel->addCapability(cap7) == true);
QLCCapability* cap8 = new QLCCapability(20, 25, "20-25");
QVERIFY(channel->addCapability(cap8) == true);
/* Create a copy of the original channel */
QLCChannel* copy = new QLCChannel(channel);
QVERIFY(copy->name() == "Foobar");
QVERIFY(copy->group() == QLCChannel::Tilt);
QVERIFY(copy->controlByte() == QLCChannel::ControlByte(3));
QVERIFY(copy->colour() == QLCChannel::Yellow);
/* Verify that the capabilities in the copied channel are also
copies i.e. their pointers are not the same as the originals. */
QList <QLCCapability*> caps(copy->capabilities());
QVERIFY(caps.size() == 8);
QVERIFY(caps.at(0) != cap1);
QVERIFY(caps.at(0)->name() == cap1->name());
QVERIFY(caps.at(0)->min() == cap1->min());
QVERIFY(caps.at(0)->max() == cap1->max());
QVERIFY(caps.at(1) != cap2);
QVERIFY(caps.at(1)->name() == cap2->name());
QVERIFY(caps.at(1)->min() == cap2->min());
QVERIFY(caps.at(1)->max() == cap2->max());
QVERIFY(caps.at(2) != cap3);
QVERIFY(caps.at(2)->name() == cap3->name());
QVERIFY(caps.at(2)->min() == cap3->min());
QVERIFY(caps.at(2)->max() == cap3->max());
QVERIFY(caps.at(3) != cap4);
QVERIFY(caps.at(3)->name() == cap4->name());
QVERIFY(caps.at(3)->min() == cap4->min());
QVERIFY(caps.at(3)->max() == cap4->max());
QVERIFY(caps.at(4) != cap5);
QVERIFY(caps.at(4)->name() == cap5->name());
QVERIFY(caps.at(4)->min() == cap5->min());
QVERIFY(caps.at(4)->max() == cap5->max());
QVERIFY(caps.at(5) != cap6);
QVERIFY(caps.at(5)->name() == cap6->name());
QVERIFY(caps.at(5)->min() == cap6->min());
QVERIFY(caps.at(5)->max() == cap6->max());
QVERIFY(caps.at(6) != cap7);
QVERIFY(caps.at(6)->name() == cap7->name());
QVERIFY(caps.at(6)->min() == cap7->min());
QVERIFY(caps.at(6)->max() == cap7->max());
QVERIFY(caps.at(7) != cap8);
QVERIFY(caps.at(7)->name() == cap8->name());
QVERIFY(caps.at(7)->min() == cap8->min());
QVERIFY(caps.at(7)->max() == cap8->max());
}
void QLCChannel_Test::load()
{
QDomDocument doc;
QDomElement root = doc.createElement("Channel");
root.setAttribute("Name", "Channel1");
doc.appendChild(root);
QDomElement group = doc.createElement("Group");
root.appendChild(group);
group.setAttribute("Byte", 1);
QDomText groupName = doc.createTextNode("Tilt");
group.appendChild(groupName);
QDomElement colour = doc.createElement("Colour");
QDomText colourText = doc.createTextNode(QLCChannel::colourToString(QLCChannel::Cyan));
colour.appendChild(colourText);
root.appendChild(colour);
QDomElement cap1 = doc.createElement("Capability");
root.appendChild(cap1);
cap1.setAttribute("Min", 0);
cap1.setAttribute("Max", 10);
QDomText cap1name = doc.createTextNode("Cap1");
cap1.appendChild(cap1name);
/* Overlaps with cap1, shouldn't appear in the channel */
QDomElement cap2 = doc.createElement("Capability");
root.appendChild(cap2);
cap2.setAttribute("Min", 5);
cap2.setAttribute("Max", 15);
QDomText cap2name = doc.createTextNode("Cap2");
cap2.appendChild(cap2name);
QDomElement cap3 = doc.createElement("Capability");
root.appendChild(cap3);
cap3.setAttribute("Min", 11);
cap3.setAttribute("Max", 20);
QDomText cap3name = doc.createTextNode("Cap3");
cap3.appendChild(cap3name);
/* Invalid capability tag, shouldn't appear in the channel, since it
is not recognized by the channel. */
QDomElement cap4 = doc.createElement("apability");
root.appendChild(cap4);
cap4.setAttribute("Min", 21);
cap4.setAttribute("Max", 30);
QDomText cap4name = doc.createTextNode("Cap4");
cap4.appendChild(cap4name);
/* Missing minimum value, shouldn't appear in the channel, because
loadXML() fails. */
QDomElement cap5 = doc.createElement("Capability");
root.appendChild(cap5);
cap5.setAttribute("Max", 30);
QDomText cap5name = doc.createTextNode("Cap5");
cap5.appendChild(cap5name);
QLCChannel ch;
QVERIFY(ch.loadXML(root) == true);
qDebug() << int(ch.colour());
QVERIFY(ch.name() == "Channel1");
QVERIFY(ch.group() == QLCChannel::Tilt);
QVERIFY(ch.controlByte() == QLCChannel::LSB);
QVERIFY(ch.colour() == QLCChannel::Cyan);
QVERIFY(ch.capabilities().size() == 2);
QVERIFY(ch.capabilities()[0]->name() == "Cap1");
QVERIFY(ch.capabilities()[1]->name() == "Cap3");
}
void QLCChannel_Test::loadWrongRoot()
{
QDomDocument doc;
QDomElement root = doc.createElement("Chanel");
root.setAttribute("Name", "Channel1");
doc.appendChild(root);
QDomElement group = doc.createElement("Group");
root.appendChild(group);
group.setAttribute("Byte", 1);
QDomText groupName = doc.createTextNode("Tilt");
group.appendChild(groupName);
QDomElement cap1 = doc.createElement("Capability");
root.appendChild(cap1);
cap1.setAttribute("Min", 0);
cap1.setAttribute("Max", 10);
QDomText cap1name = doc.createTextNode("Cap1");
cap1.appendChild(cap1name);
/* Overlaps with cap1, shouldn't appear in the channel */
QDomElement cap2 = doc.createElement("Capability");
root.appendChild(cap2);
cap2.setAttribute("Min", 5);
cap2.setAttribute("Max", 15);
QDomText cap2name = doc.createTextNode("Cap2");
cap2.appendChild(cap2name);
QDomElement cap3 = doc.createElement("Capability");
root.appendChild(cap3);
cap3.setAttribute("Min", 11);
cap3.setAttribute("Max", 20);
QDomText cap3name = doc.createTextNode("Cap3");
cap3.appendChild(cap3name);
QLCChannel ch;
QVERIFY(ch.loadXML(root) == false);
QVERIFY(ch.name().isEmpty());
QVERIFY(ch.group() == QLCChannel::Intensity);
QVERIFY(ch.controlByte() == QLCChannel::MSB);
QVERIFY(ch.capabilities().size() == 0);
}
void QLCChannel_Test::save()
{
QLCChannel* channel = new QLCChannel();
channel->setName("Foobar");
channel->setGroup(QLCChannel::Shutter);
channel->setControlByte(QLCChannel::LSB);
QLCCapability* cap1 = new QLCCapability(0, 9, "One");
QVERIFY(channel->addCapability(cap1) == true);
QLCCapability* cap2 = new QLCCapability(10, 19, "Two");
QVERIFY(channel->addCapability(cap2) == true);
QLCCapability* cap3 = new QLCCapability(20, 29, "Three");
QVERIFY(channel->addCapability(cap3) == true);
QLCCapability* cap4 = new QLCCapability(30, 39, "Four");
QVERIFY(channel->addCapability(cap4) == true);
QDomDocument doc;
QDomElement root = doc.createElement("TestRoot");
QVERIFY(channel->saveXML(&doc, &root) == true);
QVERIFY(root.firstChild().toElement().tagName() == "Channel");
QVERIFY(root.firstChild().toElement().attribute("Name") == "Foobar");
bool group = false;
bool capOne = false, capTwo = false, capThree = false, capFour = false;
QDomNode node = root.firstChild().firstChild();
while (node.isNull() == false)
{
QDomElement e = node.toElement();
if (e.tagName() == "Group")
{
group = true;
QVERIFY(e.attribute("Byte") == "1");
QVERIFY(e.text() == "Shutter");
}
else if (e.tagName() == "Capability")
{
if (e.text() == "One" && capOne == false)
capOne = true;
else if (e.text() == "Two" && capTwo == false)
capTwo = true;
else if (e.text() == "Three" && capThree == false)
capThree = true;
else if (e.text() == "Four" && capFour == false)
capFour = true;
else
QFAIL("Same capability saved multiple times");
}
else
{
QFAIL(QString("Unexpected tag: %1").arg(e.tagName())
.toAscii());
}
node = node.nextSibling();
}
QVERIFY(group == true);
QVERIFY(capOne == true);
QVERIFY(capTwo == true);
QVERIFY(capThree == true);
QVERIFY(capFour == true);
delete channel;
}
QTEST_APPLESS_MAIN(QLCChannel_Test)
|
#include "util/bitmap.h"
#include "mugen/mugen_menu.h"
#include <fstream>
#include <iostream>
#include <algorithm>
#include <cctype>
#include <string>
#include <cstring>
#include <vector>
#include <ostream>
#include <sstream>
#include <iostream>
#include "mugen_stage.h"
#include "init.h"
#include "resource.h"
#include "util/funcs.h"
#include "util/file-system.h"
#include "util/timedifference.h"
#include "game/console.h"
#include "object/animation.h"
#include "object/object.h"
#include "object/character.h"
#include "object/object_attack.h"
#include "object/player.h"
#include "globals.h"
#include "factory/font_render.h"
#include "menu/menu_option.h"
#include "menu/menu_global.h"
#include "menu/option_quit.h"
#include "menu/option_dummy.h"
#include "gui/keyinput_manager.h"
#include "gui/keys.h"
#include "mugen_animation.h"
#include "mugen_background.h"
#include "character.h"
#include "mugen_item.h"
#include "mugen_item_content.h"
#include "mugen_section.h"
#include "mugen_sound.h"
#include "mugen_reader.h"
#include "mugen_sprite.h"
#include "mugen_util.h"
#include "mugen_font.h"
#include "mugen_storyboard.h"
#include "mugen/option_versus.h"
#include "ast/all.h"
#include "parser/all.h"
namespace PaintownUtil = ::Util;
using namespace std;
static const int DEFAULT_WIDTH = 320;
static const int DEFAULT_HEIGHT = 240;
static const int DEFAULT_SCREEN_X_AXIS = 160;
static const int DEFAULT_SCREEN_Y_AXIS = 0;
MugenCharacterSelect::MugenCharacterSelect(const unsigned long int &ticker, std::vector<MugenFont *> &fonts):
cellBackgroundBitmap(0),
cellRandomBitmap(0),
selectTicker(ticker),
fonts(fonts),
characterList(0){
}
MugenCharacterSelect::~MugenCharacterSelect(){
/*if (cellBackgroundBitmap){
delete cellBackgroundBitmap;
}
if (cellRandomBitmap){
delete cellRandomBitmap;
}
if (p1Cursor.active){
delete p1Cursor.active;
}
if (p1Cursor.done){
delete p1Cursor.done;
}
if (p2Cursor.active){
delete p2Cursor.active;
}
if (p2Cursor.done){
delete p2Cursor.done;
}*/
if (background){
delete background;
}
for (std::vector< std::vector< MugenCell *> >::iterator i = cells.begin(); i != cells.end(); ++i){
std::vector< MugenCell *> &row = *i;
for (std::vector< MugenCell *>::iterator c = row.begin(); c != row.end(); ++c){
MugenCell *cell = *c;
if (cell) delete cell;
}
}
// Characters
for (std::vector< Mugen::Character *>::iterator c = characters.begin(); c != characters.end(); ++c){
if (*c) delete (*c);
}
// STages
for (std::vector< MugenStage *>::iterator i = stages.begin(); i != stages.end(); ++i){
if (*i) delete (*i);
}
// Delete character select list struct
if (characterList){
delete characterList;
}
}
void MugenCharacterSelect::load(const std::string &selectFile, const std::vector<Ast::Section*> & sections, MugenSprites & sprites){
#if 0
/* Extract info for our first section of our select screen */
for( ; index < collection.size(); ++index ){
std::string head = collection[index]->getHeader();
Mugen::Util::fixCase(head);
if( head == "select info" ){
while( collection[index]->hasItems() ){
MugenItemContent *content = collection[index]->getNext();
const MugenItem *item = content->getNext();
std::string itemhead = item->query();
Mugen::Util::removeSpaces(itemhead);
Mugen::Util::fixCase(itemhead);
Global::debug(1) << "Got itemhead: '" << itemhead << "'" << endl;
if ( itemhead == "fadein.time" ){
int time;
*content->getNext() >> time;
fader.setFadeInTime(time);
} else if ( itemhead == "fadein.color" ){
int r,g,b;
*content->getNext() >> r;
*content->getNext() >> g;
*content->getNext() >> b;
fader.setFadeInColor(Bitmap::makeColor(r,g,b));
} else if ( itemhead == "fadeout.time" ){
int time;
*content->getNext() >> time;
fader.setFadeOutTime(time);
} else if ( itemhead == "fadeout.color" ){
int r,g,b;
*content->getNext() >> r;
*content->getNext() >> g;
*content->getNext() >> b;
fader.setFadeOutColor(Bitmap::makeColor(r,g,b));
} else if ( itemhead == "rows" ){
*content->getNext() >> rows;
} else if ( itemhead == "columns" ){
*content->getNext() >> columns;
} else if ( itemhead == "wrapping"){
*content->getNext() >> wrapping;
} else if ( itemhead == "pos" ){
*content->getNext() >> position.x;
*content->getNext() >> position.y;
} else if ( itemhead == "showemptyboxes" ){
*content->getNext() >> showEmptyBoxes;
} else if ( itemhead == "moveoveremptyboxes" ){
*content->getNext() >> moveOverEmptyBoxes;
} else if ( itemhead == "cell.size" ){
*content->getNext() >> cellSize.x;
*content->getNext() >> cellSize.y;
} else if ( itemhead == "cell.spacing" ){
*content->getNext() >> cellSpacing;
} else if ( itemhead == "cell.bg.spr" ){
int group, sprite;
*content->getNext() >> group;
*content->getNext() >> sprite;
cellBackgroundSprite = sprites[group][sprite];
cellBackgroundSprite->load();
cellBackgroundBitmap = cellBackgroundSprite->getBitmap();//= new Bitmap(Bitmap::memoryPCX((unsigned char*) cellBackgroundSprite->pcx, cellBackgroundSprite->newlength, true));
} else if ( itemhead == "cell.random.spr" ){
int group, sprite;
*content->getNext() >> group;
*content->getNext() >> sprite;
cellRandomSprite = sprites[group][sprite];
cellRandomSprite->load();
cellRandomBitmap = cellRandomSprite->getBitmap();// = new Bitmap(Bitmap::memoryPCX((unsigned char*) cellRandomSprite->pcx, cellRandomSprite->newlength, true));
} else if ( itemhead == "cell.random.switchtime" ){
*content->getNext() >> cellRandomSwitchTime;
} else if ( itemhead == "p1.cursor.startcell" ){
*content->getNext() >> p1Cursor.cursor.x;
*content->getNext() >> p1Cursor.cursor.y;
p1Cursor.start.x = p1Cursor.cursor.x;
p1Cursor.start.y = p1Cursor.cursor.y;
} else if ( itemhead == "p1.cursor.active.spr"){
int group, sprite;
*content->getNext() >> group;
*content->getNext() >> sprite;
p1Cursor.cursorActiveSprite = sprites[group][sprite];
p1Cursor.cursorActiveSprite->load();
p1Cursor.active = p1Cursor.cursorActiveSprite->getBitmap();//new Bitmap(Bitmap::memoryPCX((unsigned char*) p1Cursor.cursorActiveSprite->pcx, p1Cursor.cursorActiveSprite->newlength, true));
} else if ( itemhead == "p1.cursor.done.spr"){
int group, sprite;
*content->getNext() >> group;
*content->getNext() >> sprite;
p1Cursor.cursorDoneSprite = sprites[group][sprite];
p1Cursor.cursorDoneSprite->load();
p1Cursor.done = p1Cursor.cursorDoneSprite->getBitmap();//new Bitmap(Bitmap::memoryPCX((unsigned char*) p1Cursor.cursorDoneSprite->pcx, p1Cursor.cursorDoneSprite->newlength, true));
}
else if ( itemhead == "p1.cursor.move.snd" ){ /* nothing */ }
else if ( itemhead == "p1.cursor.done.snd"){ /* nothing */ }
else if ( itemhead == "p1.random.move.snd"){ /* nothing */ }
else if ( itemhead == "p2.cursor.startcell"){
*content->getNext() >> p2Cursor.cursor.x;
*content->getNext() >> p2Cursor.cursor.y;
p2Cursor.start.x = p2Cursor.cursor.x;
p2Cursor.start.y = p2Cursor.cursor.y;
} if ( itemhead == "p2.cursor.active.spr"){
int group, sprite;
*content->getNext() >> group;
*content->getNext() >> sprite;
p2Cursor.cursorActiveSprite = sprites[group][sprite];
p2Cursor.cursorActiveSprite->load();
p2Cursor.active = p2Cursor.cursorActiveSprite->getBitmap();//new Bitmap(Bitmap::memoryPCX((unsigned char*) p2Cursor.cursorActiveSprite->pcx, p2Cursor.cursorActiveSprite->newlength, true));
} else if ( itemhead == "p2.cursor.done.spr"){
int group, sprite;
*content->getNext() >> group;
*content->getNext() >> sprite;
p2Cursor.cursorDoneSprite = sprites[group][sprite];
p2Cursor.cursorDoneSprite->load();
p2Cursor.done = p2Cursor.cursorDoneSprite->getBitmap();// = new Bitmap(Bitmap::memoryPCX((unsigned char*) p2Cursor.cursorDoneSprite->pcx, p2Cursor.cursorDoneSprite->newlength, true));
} else if ( itemhead == "p2.cursor.blink"){
*content->getNext() >> p2Cursor.blink;
p2Cursor.blinkCounter = 0;
}
else if ( itemhead == "p2.cursor.move.snd"){ /* nothing */ }
else if ( itemhead == "p2.cursor.done.snd"){ /* nothing */ }
else if ( itemhead == "p2.random.move.snd"){ /* nothing */ }
else if ( itemhead == "stage.move.snd"){ /* nothing */ }
else if ( itemhead == "stage.done.snd"){ /* nothing */ }
else if ( itemhead == "cancel.snd"){ /* nothing */ }
else if ( itemhead == "portrait.offset"){
*content->getNext() >> portraitOffset.x;
*content->getNext() >> portraitOffset.y;
} else if ( itemhead == "portrait.scale"){
*content->getNext() >> portraitScale.x;
*content->getNext() >> portraitScale.y;
} else if ( itemhead == "title.offset"){
*content->getNext() >> titleOffset.x;
*content->getNext() >> titleOffset.y;
} else if ( itemhead == "title.font"){
*content->getNext() >> titleFont.index;
*content->getNext() >> titleFont.bank;
*content->getNext() >> titleFont.position;
} else if ( itemhead == "p1.face.offset"){
*content->getNext() >> p1Cursor.faceOffset.x;
*content->getNext() >> p1Cursor.faceOffset.y;
} else if ( itemhead == "p1.face.scale"){
*content->getNext() >> p1Cursor.faceScalex;
*content->getNext() >> p1Cursor.faceScaley;
} else if ( itemhead == "p1.face.facing"){
*content->getNext() >> p1Cursor.facing;
} else if ( itemhead == "p2.face.offset"){
*content->getNext() >> p2Cursor.faceOffset.x;
*content->getNext() >> p2Cursor.faceOffset.y;
} else if ( itemhead == "p2.face.scale"){
*content->getNext() >> p2Cursor.faceScalex;
*content->getNext() >> p2Cursor.faceScaley;
} else if ( itemhead == "p2.face.facing"){
*content->getNext() >> p2Cursor.facing;
} else if ( itemhead == "p1.name.offset"){
*content->getNext() >> p1Cursor.nameOffset.x;
*content->getNext() >> p1Cursor.nameOffset.y;
} else if ( itemhead == "p1.name.font"){
*content->getNext() >> p1Cursor.nameFont.index;
*content->getNext() >> p1Cursor.nameFont.bank;
*content->getNext() >> p1Cursor.nameFont.position;
} else if ( itemhead == "p2.name.offset"){
*content->getNext() >> p2Cursor.nameOffset.x;
*content->getNext() >> p2Cursor.nameOffset.y;
} else if ( itemhead == "p2.name.font"){
*content->getNext() >> p2Cursor.nameFont.index;
*content->getNext() >> p2Cursor.nameFont.bank;
*content->getNext() >> p2Cursor.nameFont.position;
} else if ( itemhead == "stage.pos"){
*content->getNext() >> stageInfo.stagePosition.x;
*content->getNext() >> stageInfo.stagePosition.y;
} else if ( itemhead == "stage.active.font"){
*content->getNext() >> stageInfo.stageActiveFont.index;
*content->getNext() >> stageInfo.stageActiveFont.bank;
*content->getNext() >> stageInfo.stageActiveFont.position;
} else if ( itemhead == "stage.active2.font"){
*content->getNext() >> stageInfo.stageActiveFont2.index;
*content->getNext() >> stageInfo.stageActiveFont2.bank;
*content->getNext() >> stageInfo.stageActiveFont2.position;
} else if ( itemhead == "stage.done.font"){
*content->getNext() >> stageInfo.stageDoneFont.index;
*content->getNext() >> stageInfo.stageDoneFont.bank;
*content->getNext() >> stageInfo.stageDoneFont.position;
} else if ( itemhead.find("teammenu")!=std::string::npos ){ /* Ignore for now */ }
//else throw MugenException( "Unhandled option in Select Info Section: " + itemhead );
}
}
else if( head == "selectbgdef" ){
// Background management
/* FIXME!!!! use collectBackgroundStuff() */
/*
MugenBackgroundManager *manager = new MugenBackgroundManager(Mugen::Util::getFileDir( selectFile ),collection, index,selectTicker,&sprites);
background = manager;
Global::debug(1) << "Got background: '" << manager->getName() << "'" << endl;
*/
}
else {
// Done collecting
index--;
break;
}
}
#endif
fonts = fonts;
// Set up cell table
Mugen::Point currentPosition;
currentPosition.y = position.y;
for (int row = 0; row < rows; ++row){
currentPosition.x = position.x;
std::vector< MugenCell *> cellRow;
for (int column = 0; column < columns; ++column){
MugenCell *cell = new MugenCell;
cell->position.x = currentPosition.x;
cell->position.y = currentPosition.y;
cell->character = 0;
cell->random = false;
cell->empty = true;
cellRow.push_back(cell);
currentPosition.x += cellSize.x + cellSpacing;
}
cells.push_back(cellRow);
currentPosition.y += cellSize.y + cellSpacing;
}
// Now load up our characters
loadCharacters(selectFile);
// Set stage info
stageInfo.selected = false;
stageInfo.altCounter = 0;
// Set up the animations for those that have action numbers assigned (not -1 )
// Also do their preload
if (background) background->preload(DEFAULT_SCREEN_X_AXIS, DEFAULT_SCREEN_Y_AXIS );
}
MugenSelectedChars *MugenCharacterSelect::run(const std::string &title, const int players, const bool selectStage, Bitmap *work){
Bitmap workArea(DEFAULT_WIDTH,DEFAULT_HEIGHT);
bool done = false;
// Set the fade state
fader.setState(FADEIN);
double runCounter = 0;
Global::speed_counter = 0;
Global::second_counter = 0;
int game_time = 100;
// Set player 1 and 2 cursors
p1Cursor.selecting = true;
p1Cursor.cursor.x = p1Cursor.start.x;
p1Cursor.cursor.y = p1Cursor.start.y;
p2Cursor.selecting = true;
p2Cursor.cursor.x = p2Cursor.start.x;
p2Cursor.cursor.y = p2Cursor.start.y;
// Stage list
stageInfo.selected = false;
stageInfo.altCounter = 0;
std::vector< MugenStage *> stageSelections;
unsigned int random = Util::rnd(0,stages.size()-1);
stageSelections.push_back(stages[random]);
for (std::vector<MugenStage *>::iterator i = stages.begin(); i != stages.end(); ++i){
stageSelections.push_back(*i);
}
unsigned int currentStage = 0;
if (characterList){
delete characterList;
}
characterList = new MugenSelectedChars();
characterList->selectedStage = 0;
while ( ! done && fader.getState() != RUNFADE ){
bool draw = false;
keyInputManager::update();
if ( Global::speed_counter > 0 ){
draw = true;
runCounter += Global::speed_counter * Global::LOGIC_MULTIPLIER;
while ( runCounter >= 1.0 ){
runCounter -= 1;
// Keys
if (fader.getState() == NOFADE){
if ( keyInputManager::keyState(keys::UP, true ) ||
/* for vi people like me */
keyInputManager::keyState('k', true )){
movePlayer1Cursor(-1,0);
}
if ( keyInputManager::keyState(keys::DOWN, true ) ||
/* for vi people like me */
keyInputManager::keyState('j', true )){
movePlayer1Cursor(1,0);
}
if ( keyInputManager::keyState(keys::LEFT, true) ||
keyInputManager::keyState('h', true)){
if (p1Cursor.selecting){
movePlayer1Cursor(0,-1);
} else {
if (selectStage && !stageInfo.selected){
if (currentStage > 0){
currentStage--;
} else {
currentStage = stageSelections.size() -1;
}
}
}
}
if ( keyInputManager::keyState(keys::RIGHT, true )||
keyInputManager::keyState('l', true )){
if (p1Cursor.selecting){
movePlayer1Cursor(0,1);
} else {
if (selectStage && !stageInfo.selected){
if (currentStage < stageSelections.size()-1){
currentStage++;
} else {
currentStage = 0;
}
}
}
}
if ( keyInputManager::keyState(keys::ENTER, true ) ){
if (!cells[p1Cursor.cursor.x][p1Cursor.cursor.y]->empty && p1Cursor.selecting){
p1Cursor.selecting = false;
characterList->team1.push_back(cells[p1Cursor.cursor.x][p1Cursor.cursor.y]->character);
} else if (!p1Cursor.selecting && selectStage && !stageInfo.selected){
stageInfo.selected = true;
characterList->selectedStage = stageSelections[currentStage];
}
}
if ( keyInputManager::keyState(keys::ESC, true ) ){
done = true;
fader.setState(FADEOUT);
}
}
// Fader
fader.act();
// Backgrounds
background->logic( 0, 0, 0, 0 );
// Check status
if (players == 2){
if (!p1Cursor.selecting && !p2Cursor.selecting && stageInfo.selected){
done = true;
fader.setState(FADEOUT);
}
} else if (players == 1){
if (!p1Cursor.selecting && ((selectStage && stageInfo.selected) || !selectStage)){
done = true;
fader.setState(FADEOUT);
}
}
}
Global::speed_counter = 0;
}
while ( Global::second_counter > 0 ){
game_time--;
Global::second_counter--;
if ( game_time < 0 ){
game_time = 0;
}
}
if ( draw ){
// backgrounds
background->renderBack(0,0,DEFAULT_WIDTH,DEFAULT_HEIGHT,&workArea);
// Stuff
drawCursors(players, &workArea);
// Draw title
MugenFont *font = fonts[titleFont.index-1];
font->render(titleOffset.x, titleOffset.y, titleFont.position, titleFont.bank, workArea, title);
// Draw stage
if (selectStage && (!p1Cursor.selecting || !p2Cursor.selecting)){
std::string stageName = "Stage";
if (currentStage == 0){
stageName += ": Random";
} else {
std::stringstream s;
s << " " << currentStage << ": " << stageSelections[currentStage]->getName();
stageName += s.str();
}
if (!stageInfo.selected){
if (stageInfo.altCounter % 2 == 0){
// reuse Font
font = fonts[stageInfo.stageActiveFont.index-1];
font->render(stageInfo.stagePosition.x, stageInfo.stagePosition.y, stageInfo.stageActiveFont.position, stageInfo.stageActiveFont.bank, workArea, stageName);
} else {
// reuse Font
font = fonts[stageInfo.stageActiveFont2.index-1];
font->render(stageInfo.stagePosition.x, stageInfo.stagePosition.y, stageInfo.stageActiveFont2.position, stageInfo.stageActiveFont2.bank, workArea, stageName);
}
stageInfo.altCounter++;
if (stageInfo.altCounter == 10){
stageInfo.altCounter = 0;
}
} else {
// Done selecting
// reuse Font
font = fonts[stageInfo.stageDoneFont.index-1];
font->render(stageInfo.stagePosition.x, stageInfo.stagePosition.y, stageInfo.stageDoneFont.position, stageInfo.stageDoneFont.bank, workArea, stageName);
}
}
// Foregrounds
background->renderFront(0,0,DEFAULT_WIDTH,DEFAULT_HEIGHT,&workArea);
// Do fades
fader.draw(&workArea);
// Finally render to screen
workArea.Stretch(*work);
work->BlitToScreen();
}
while ( Global::speed_counter < 1 ){
Util::rest( 1 );
keyInputManager::update();
}
}
if (selectStage && !stageInfo.selected)return 0;
return characterList;
}
void MugenCharacterSelect::drawCursors(const int players, Bitmap *work){
Mugen::Point currentPosition;
currentPosition.y = position.y;
for (int row = 0; row < rows; ++row){
currentPosition.x = position.x;
for (int column = 0; column < columns; ++column){
MugenCell *cell = cells[row][column];
if (!cell->empty){
if (!cell->random){
cell->character->renderSprite(cell->position.x,cell->position.y,9000,0,work);
cellBackgroundBitmap->draw(currentPosition.x,currentPosition.y,*work);
} else {
cellRandomBitmap->draw(cell->position.x,cell->position.y,*work);
cellBackgroundBitmap->draw(currentPosition.x,currentPosition.y,*work);
}
} else if (showEmptyBoxes){
cellBackgroundBitmap->draw(currentPosition.x,currentPosition.y,*work);
}
currentPosition.x += cellSize.x + cellSpacing;
}
currentPosition.y += cellSize.y + cellSpacing;
}
// Player cursors player 1
if (p1Cursor.selecting){
p1Cursor.active->draw(cells[p1Cursor.cursor.x][p1Cursor.cursor.y]->position.x,cells[p1Cursor.cursor.x][p1Cursor.cursor.y]->position.y,*work);
} else {
p1Cursor.done->draw(cells[p1Cursor.cursor.x][p1Cursor.cursor.y]->position.x,cells[p1Cursor.cursor.x][p1Cursor.cursor.y]->position.y,*work);
}
if ( !cells[p1Cursor.cursor.x][p1Cursor.cursor.y]->empty ){
MugenCell *cell = cells[p1Cursor.cursor.x][p1Cursor.cursor.y];
if (!cell->empty){
if (!cell->random){
// Portrait
cell->character->renderSprite(p1Cursor.faceOffset.x,p1Cursor.faceOffset.y,9000,1,work,p1Cursor.facing, p1Cursor.faceScalex,p1Cursor.faceScaley);
// Name
MugenFont *font = fonts[p1Cursor.nameFont.index-1];
font->render(p1Cursor.nameOffset.x, p1Cursor.nameOffset.y, p1Cursor.nameFont.position, p1Cursor.nameFont.bank, *work, cell->character->getName());
} else {
}
}
}
// Player cursors player 2
if (players > 1){
if (p2Cursor.blink && ((p1Cursor.cursor.x == p2Cursor.cursor.x) && (p1Cursor.cursor.y == p2Cursor.cursor.y))){
if (p2Cursor.blinkCounter % 2 == 0){
if (p2Cursor.selecting){
p2Cursor.active->draw(cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->position.x,cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->position.y,*work);
} else {
p2Cursor.done->draw(cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->position.x,cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->position.y,*work);
}
}
p2Cursor.blinkCounter++;
if (p2Cursor.blinkCounter == 10){
p2Cursor.blinkCounter = 0;
}
} else {
if (p2Cursor.selecting){
p2Cursor.active->draw(cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->position.x,cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->position.y,*work);
} else {
p2Cursor.done->draw(cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->position.x,cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->position.y,*work);
}
}
if ( !cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->empty ){
MugenCell *cell = cells[p2Cursor.cursor.x][p2Cursor.cursor.y];
if (!cell->empty){
if (!cell->random){
// Portrait
cell->character->renderSprite(p2Cursor.faceOffset.x,p2Cursor.faceOffset.y,9000,1,work,p2Cursor.facing, p2Cursor.faceScalex,p2Cursor.faceScaley);
// Name
MugenFont *font = fonts[p2Cursor.nameFont.index-1];
font->render(p2Cursor.nameOffset.x, p2Cursor.nameOffset.y, p2Cursor.nameFont.position, p2Cursor.nameFont.bank, *work, cell->character->getName());
} else {
}
}
}
}
}
void MugenCharacterSelect::movePlayer1Cursor(int x, int y){
if (!p1Cursor.selecting){
return;
}
if (x > 0){
if (moveOverEmptyBoxes){
p1Cursor.cursor.x += x;
if (wrapping && p1Cursor.cursor.x >= rows){
p1Cursor.cursor.x = 0;
} else if (p1Cursor.cursor.x >= rows) {
p1Cursor.cursor.x = rows-1;
}
}
else {
int curx = p1Cursor.cursor.x;
while (!cells[curx][p1Cursor.cursor.y]->empty){
curx+=x;
if (wrapping && curx >= rows){
curx = 0;
} else if (curx >= rows) {
curx = p1Cursor.cursor.x;
}
if (curx == p1Cursor.cursor.x){
break;
}
}
if (!cells[curx][p1Cursor.cursor.y]->empty)p1Cursor.cursor.x = curx;
}
} else if (x < 0){
if (moveOverEmptyBoxes){
p1Cursor.cursor.x += x;
if (wrapping && p1Cursor.cursor.x < 0){
p1Cursor.cursor.x = rows-1;
} else if (p1Cursor.cursor.x < 0) {
p1Cursor.cursor.x = 0;
}
}
else {
int curx = p1Cursor.cursor.x;
while (!cells[curx][p1Cursor.cursor.y]->empty){
curx+=x;
if (wrapping && curx < 0){
curx = rows-1;
} else if (curx < 0) {
curx = p1Cursor.cursor.x;
}
if (curx == p1Cursor.cursor.x){
break;
}
}
if (!cells[curx][p1Cursor.cursor.y]->empty)p1Cursor.cursor.x = curx;
}
}
if (y > 0){
if (moveOverEmptyBoxes){
p1Cursor.cursor.y += y;
if (wrapping && p1Cursor.cursor.y >= columns){
p1Cursor.cursor.y = 0;
} else if (p1Cursor.cursor.y >= columns) {
p1Cursor.cursor.y = columns-1;
}
}
else {
int cury = p1Cursor.cursor.y;
while (!cells[p1Cursor.cursor.x][cury]->empty){
cury+=y;
if (wrapping && cury >= columns){
cury = 0;
} else if (cury >= columns) {
cury = p1Cursor.cursor.y;
}
if (cury == p1Cursor.cursor.y){
break;
}
}
if (!cells[p1Cursor.cursor.x][cury]->empty)p1Cursor.cursor.y = cury;
}
} else if (y < 0){
if (moveOverEmptyBoxes){
p1Cursor.cursor.y += y;
if (wrapping && p1Cursor.cursor.y < 0){
p1Cursor.cursor.y = columns-1;
} else if (p1Cursor.cursor.y < 0) {
p1Cursor.cursor.y = 0;
}
}
else {
int cury = p1Cursor.cursor.y;
while (!cells[p1Cursor.cursor.x][cury]->empty){
cury+=y;
if (wrapping && cury < 0){
cury = columns-1;
} else if (cury < 0) {
cury = p1Cursor.cursor.y;
}
if (cury == p1Cursor.cursor.y){
break;
}
}
if (!cells[p1Cursor.cursor.x][cury]->empty)p1Cursor.cursor.y = cury;
}
}
}
void MugenCharacterSelect::movePlayer2Cursor(int x, int y){
if (!p2Cursor.selecting){
return;
}
if (x > 0){
if (moveOverEmptyBoxes){
p2Cursor.cursor.x += x;
if (wrapping && p2Cursor.cursor.x >= rows){
p2Cursor.cursor.x = 0;
} else if (p2Cursor.cursor.x >= rows) {
p2Cursor.cursor.x = rows-1;
}
}
else {
int curx = p2Cursor.cursor.x;
while (!cells[curx][p2Cursor.cursor.y]->empty){
curx+=x;
if (wrapping && curx >= rows){
curx = 0;
} else if (curx >= rows) {
curx = p2Cursor.cursor.x;
}
if (curx == p2Cursor.cursor.x){
break;
}
}
if (!cells[curx][p2Cursor.cursor.y]->empty)p2Cursor.cursor.x = curx;
}
} else if (x < 0){
if (moveOverEmptyBoxes){
p2Cursor.cursor.x += x;
if (wrapping && p2Cursor.cursor.x < 0){
p2Cursor.cursor.x = rows-1;
} else if (p2Cursor.cursor.x < 0) {
p2Cursor.cursor.x = 0;
}
}
else {
int curx = p2Cursor.cursor.x;
while (!cells[curx][p2Cursor.cursor.y]->empty){
curx+=x;
if (wrapping && curx < 0){
curx = rows-1;
} else if (curx < 0) {
curx = p2Cursor.cursor.x;
}
if (curx == p2Cursor.cursor.x){
break;
}
}
if (!cells[curx][p2Cursor.cursor.y]->empty)p2Cursor.cursor.x = curx;
}
}
if (y > 0){
if (moveOverEmptyBoxes){
p2Cursor.cursor.y += y;
if (wrapping && p2Cursor.cursor.y >= columns){
p2Cursor.cursor.y = 0;
} else if (p2Cursor.cursor.y >= columns) {
p2Cursor.cursor.y = columns-1;
}
}
else {
int cury = p2Cursor.cursor.y;
while (!cells[p2Cursor.cursor.x][cury]->empty){
cury+=y;
if (wrapping && cury >= columns){
cury = 0;
} else if (cury >= columns) {
cury = p2Cursor.cursor.y;
}
if (cury == p2Cursor.cursor.y){
break;
}
}
if (!cells[p1Cursor.cursor.x][cury]->empty)p2Cursor.cursor.y = cury;
}
} else if (y < 0){
if (moveOverEmptyBoxes){
p2Cursor.cursor.y += y;
if (wrapping && p2Cursor.cursor.y < 0){
p2Cursor.cursor.y = columns-1;
} else if (p2Cursor.cursor.y < 0) {
p2Cursor.cursor.y = 0;
}
}
else {
int cury = p2Cursor.cursor.y;
while (!cells[p2Cursor.cursor.x][cury]->empty){
cury+=y;
if (wrapping && cury < 0){
cury = columns-1;
} else if (cury < 0) {
cury = p2Cursor.cursor.y;
}
if (cury == p2Cursor.cursor.y){
break;
}
}
if (!cells[p1Cursor.cursor.x][cury]->empty)p2Cursor.cursor.y = cury;
}
}
}
void MugenCharacterSelect::loadCharacters(const std::string &selectFile) throw (MugenException){
std::string dir = Mugen::Util::getFileDir(selectFile);
std::string file = Mugen::Util::stripDir(selectFile);
/* FIXME!! Replace with peg parser */
MugenReader reader( Mugen::Util::getCorrectFileLocation(dir,file) );
std::vector< MugenSection * > collection;
collection = reader.getCollection();
std::vector< std::string > stageNames;
/* Extract info for our first section of our menu */
for( unsigned int i = 0; i < collection.size(); ++i ){
std::string head = collection[i]->getHeader();
Mugen::Util::fixCase(head);
if( head == "characters" ){
int row = 0;
int column = 0;
while( collection[i]->hasItems() ){
MugenItemContent *content = collection[i]->getNext();
const MugenItem *item = content->getNext();
std::string itemhead = item->query();
Mugen::Util::removeSpaces(itemhead);
if (itemhead=="random"){
// set random flag
cells[row][column]->random = true;
cells[row][column]->empty = false;
} else {
// Get character
Mugen::Character *character = new Mugen::Character(itemhead);
try{
character->load();
} catch (const MugenException & ex){
throw ex;
}
characters.push_back(character);
Global::debug(1) << "Got character: " << character->getName() << endl;
// set cell
cells[row][column]->character = character;
cells[row][column]->empty = false;
if (content->hasItems()){
// Next item will be a stage lets add it to the list of stages
std::string temp;
*content->getNext() >> temp;
stageNames.push_back(temp);
Global::debug(1) << "Got stage: " << temp << endl;
}
// Need to add in other options and assign their respective stages to them....
}
column++;
if (column >=columns){
column = 0;
row++;
// Have we met our quota?
if (row >= rows){
// can't add any more characters... breakage
break;
}
}
}
}
else if( head == "extrastages" ){
while( collection[i]->hasItems() ){
MugenItemContent *content = collection[i]->getNext();
const MugenItem *item = content->getNext();
std::string itemhead = item->query();
Mugen::Util::removeSpaces(itemhead);
// Next item will be a stage lets add it to the list of stages
stageNames.push_back(itemhead);
Global::debug(1) << "Got stage: " << itemhead << endl;
}
}
else if( head == "options" ){ /* ignore for now */}
else throw MugenException("Unhandled Section in '" + selectFile + "': " + head, __FILE__, __LINE__);
}
// Prepare stages
for (std::vector<std::string>::iterator i = stageNames.begin(); i != stageNames.end(); ++i){
MugenStage *stage = new MugenStage(*i);
// No need to load them.... Load only when using the stage...
/*try{
stage->load();
} catch (MugenException &ex){
throw MugenException(ex);
}*/
stages.push_back(stage);
}
}
MugenMenu::MugenMenu(const std::string &filename):
optionLocation(0),
location(filename),
spriteFile(""),
soundFile(""),
logoFile(""),
introFile(""),
selectFile(""),
fightFile(""),
windowVisibleItems(0),
showBoxCursor(false),
ticker(0),
background(0),
logo(0),
intro(0),
characterSelect(0){
}
static vector<Ast::Section*> collectSelectStuff(Ast::AstParse::section_iterator & iterator, Ast::AstParse::section_iterator end){
Ast::AstParse::section_iterator last = iterator;
vector<Ast::Section*> stuff;
Ast::Section * section = *iterator;
std::string head = section->getName();
/* better to do case insensitive regex matching rather than
* screw up the original string
*/
stuff.push_back(section);
iterator++;
while (true){
if (iterator == end){
break;
}
section = *iterator;
string sectionName = section->getName();
Mugen::Util::fixCase(sectionName);
// Global::debug(2, __FILE__) << "Match '" << (prefix + name + ".*") << "' against '" << sectionName << "'" << endl;
if (PaintownUtil::matchRegex(sectionName, "select")){
stuff.push_back(section);
} else {
break;
}
last = iterator;
iterator++;
}
iterator = last;
return stuff;
}
void MugenMenu::loadData() throw (MugenException){
// Lets look for our def since some people think that all file systems are case insensitive
std::string baseDir = Filesystem::find("mugen/data/" + Mugen::Util::getFileDir(location));
const std::string ourDefFile = Mugen::Util::fixFileName( baseDir, Mugen::Util::stripDir(location) );
// get real basedir
//baseDir = Mugen::Util::getFileDir( ourDefFile );
Global::debug(1) << baseDir << endl;
if (ourDefFile.empty()){
throw MugenException( "Cannot locate menu definition file for: " + location );
}
TimeDifference diff;
diff.startTime();
Ast::AstParse parsed((list<Ast::Section*>*) Mugen::Def::main(ourDefFile));
diff.endTime();
Global::debug(1) << "Parsed mugen file " + ourDefFile + " in" + diff.printTime("") << endl;
/*
MugenReader reader( ourDefFile );
std::vector< MugenSection * > collection;
collection = reader.getCollection();
*/
for (Ast::AstParse::section_iterator section_it = parsed.getSections()->begin(); section_it != parsed.getSections()->end(); section_it++){
Ast::Section * section = *section_it;
std::string head = section->getName();
/* this should really be head = Mugen::Util::fixCase(head) */
Mugen::Util::fixCase(head);
if (head == "info"){
class InfoWalker: public Ast::Walker{
public:
InfoWalker(MugenMenu & menu):
menu(menu){
}
MugenMenu & menu;
virtual void onAttributeSimple(const Ast::AttributeSimple & simple){
if (simple == "name"){
menu.setName(simple.valueAsString());
Global::debug(1) << "Read name '" << menu.getName() << "'" << endl;
} else if (simple == "author"){
string temp;
simple >> temp;
Global::debug(1) << "Made by: '" << temp << "'" << endl;
} else {
throw MugenException("Unhandled option in Info Section: " + simple.toString(), __FILE__, __LINE__);
}
}
};
InfoWalker walker(*this);
section->walk(walker);
} else if (head == "files"){
class FileWalker: public Ast::Walker{
public:
FileWalker(MugenMenu & menu, const string & baseDir):
menu(menu),
baseDir(baseDir){
}
MugenMenu & menu;
const string & baseDir;
virtual void onAttributeSimple(const Ast::AttributeSimple & simple){
if (simple == "spr"){
simple >> menu.spriteFile;
Global::debug(1) << "Got Sprite File: '" << menu.spriteFile << "'" << endl;
Mugen::Util::readSprites(Mugen::Util::getCorrectFileLocation(baseDir, menu.spriteFile), "", menu.sprites);
} else if (simple == "snd"){
simple >> menu.soundFile;
Global::debug(1) << "Got Sound File: '" << menu.soundFile << "'" << endl;
} else if (simple == "logo.storyboard"){
try{
simple >> menu.logoFile;
try{
Global::debug(1) << "Logo file " << baseDir << "/" << menu.logoFile << endl;
menu.logo = new MugenStoryboard(Mugen::Util::getCorrectFileLocation(baseDir, menu.logoFile));
menu.logo->load();
Global::debug(1) << "Got Logo Storyboard File: '" << menu.logoFile << "'" << endl;
} catch (const MugenException &ex){
throw MugenException( "Error loading logo storyboard: " + ex.getReason(), __FILE__, __LINE__);
}
} catch (const Ast::Exception & e){
}
} else if (simple == "intro.storyboard"){
try{
simple >> menu.introFile;
try{
Global::debug(1) << "Intro file " << baseDir << "/" << menu.introFile << endl;
menu.intro = new MugenStoryboard(Mugen::Util::getCorrectFileLocation(baseDir, menu.logoFile));
menu.intro->load();
Global::debug(1) << "Got Intro Storyboard File: '" << menu.introFile << "'" << endl;
} catch (const MugenException &ex){
throw MugenException( "Error loading intro storyboard: " + ex.getReason(), __FILE__, __LINE__);
}
} catch (const Ast::Exception & e){
}
} else if (simple == "select"){
simple >> menu.selectFile;
Global::debug(1) << "Got Select File: '" << menu.selectFile << "'" << endl;
} else if (simple == "fight"){
simple >> menu.fightFile;
Global::debug(1) << "Got Fight File: '" << menu.fightFile << "'" << endl;
} else if (PaintownUtil::matchRegex(simple.idString(), "^font")){
string temp;
simple >> temp;
menu.fonts.push_back(new MugenFont(Mugen::Util::getCorrectFileLocation(baseDir, temp)));
Global::debug(1) << "Got Font File: '" << temp << "'" << endl;
} else {
throw MugenException("Unhandled option in Files Section: " + simple.toString(), __FILE__, __LINE__ );
}
}
};
FileWalker walker(*this, baseDir);
section->walk(walker);
} else if (head == "music"){
/* FIXME! parse music here */
} else if (head == "title info"){
class TitleInfoWalker: public Ast::Walker{
public:
TitleInfoWalker(MugenMenu & menu):
menu(menu){
}
MugenMenu & menu;
virtual void onAttributeSimple(const Ast::AttributeSimple & simple){
if (simple == "fadein.time"){
int time;
simple >> time;
menu.fader.setFadeInTime(time);
} else if (simple == "fadein.color"){
int r,g,b;
simple >> r >> g >> b;
menu.fader.setFadeInColor(Bitmap::makeColor(r,g,b));
} else if (simple == "fadeout.time"){
int time;
simple >> time;
menu.fader.setFadeOutTime(time);
} else if (simple == "fadeout.color"){
int r,g,b;
simple >> r >> g >> b;
menu.fader.setFadeOutColor(Bitmap::makeColor(r,g,b));
} else if (simple == "menu.pos"){
simple >> menu.position.x;
simple >> menu.position.y;
} else if (simple == "menu.item.font"){
simple >> menu.fontItem.index;
simple >> menu.fontItem.bank;
simple >> menu.fontItem.position;
} else if (simple == "menu.item.active.font"){
simple >> menu.fontActive.index;
simple >> menu.fontActive.bank;
simple >> menu.fontActive.position;
} else if (simple == "menu.item.spacing"){
simple >> menu.fontSpacing.x;
simple >> menu.fontSpacing.y;
} else if (simple == "menu.itemname.arcade"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.versus"){
try{
menu.addOption(new MugenOptionVersus(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.teamarcade"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.teamversus"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.teamcoop"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.survival"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.survivalcoop"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.training"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.watch"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.options"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.exit"){
try{
menu.addOption(new OptionQuit(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.window.margins.x"){
simple >> menu.windowMarginX.x;
simple >> menu.windowMarginX.y;
} else if (simple == "menu.window.margins.y"){
simple >> menu.windowMarginY.x;
simple >> menu.windowMarginY.y;
} else if (simple == "menu.window.visibleitems"){
simple >> menu.windowVisibleItems;
} else if (simple == "menu.boxcursor.visible"){
simple >> menu.showBoxCursor;
} else if (simple == "menu.boxcursor.coords"){
simple >> menu.boxCursorCoords.x1;
simple >> menu.boxCursorCoords.y1;
simple >> menu.boxCursorCoords.x2;
simple >> menu.boxCursorCoords.y2;
menu.boxCursorCoords.alpha = 128;
menu.boxCursorCoords.alphaMove = -6;
} else if (simple == "cursor.move.snd"){
/* FIXME! parse cursor.move.snd */
} else if (simple == "cursor.done.snd"){
/* FIXME! parse cursor.done.snd */
} else if (simple == "cancel.snd"){
/* FIXME! parse cancel.snd */
} else {
throw MugenException("Unhandled option in Info Section: " + simple.toString(), __FILE__, __LINE__);
}
}
};
TitleInfoWalker walker(*this);
section->walk(walker);
} else if (PaintownUtil::matchRegex(head, "^titlebgdef")){
vector<Ast::Section*> backgroundStuff = Mugen::Util::collectBackgroundStuff(section_it, parsed.getSections()->end());
MugenBackgroundManager *manager = new MugenBackgroundManager(baseDir, backgroundStuff, ticker, &sprites);
background = manager;
Global::debug(1) << "Got background: '" << manager->getName() << "'" << endl;
} else if (head == "select info"){
// Pass off to selectInfo
characterSelect = new MugenCharacterSelect(ticker, fonts);
characterSelect->load(baseDir + selectFile, collectSelectStuff(section_it, parsed.getSections()->end()), sprites);
} else if (head == "selectbgdef" ){ /* Ignore for now */ }
else if (head.find("selectbg") != std::string::npos ){ /* Ignore for now */ }
else if (head == "vs screen" ){ /* Ignore for now */ }
else if (head == "versusbgdef" ){ /* Ignore for now */ }
else if (head.find("versusbg" ) != std::string::npos ){ /* Ignore for now */ }
else if (head == "demo mode" ){ /* Ignore for now */ }
else if (head == "continue screen" ){ /* Ignore for now */ }
else if (head == "game over screen" ){ /* Ignore for now */ }
else if (head == "win screen" ){ /* Ignore for now */ }
else if (head == "default ending" ){ /* Ignore for now */ }
else if (head == "end credits" ){ /* Ignore for now */ }
else if (head == "survival results screen" ){ /* Ignore for now */ }
else if (head == "option info" ){ /* Ignore for now */ }
else if (head == "optionbgdef" ){ /* Ignore for now */ }
else if (head.find("optionbg") != std::string::npos ){ /* Ignore for now */ }
else if (head == "music" ){ /* Ignore for now */ }
else if (head.find("begin action") != std::string::npos ){ /* Ignore for now */ }
else {
throw MugenException("Unhandled Section in '" + ourDefFile + "': " + head, __FILE__, __LINE__ );
}
}
/* Set up the animations for those that have action numbers assigned (not -1 )
* Also do their preload
*/
if (background){
background->preload(DEFAULT_SCREEN_X_AXIS, DEFAULT_SCREEN_Y_AXIS );
}
}
MugenMenu::~MugenMenu(){
// cleanup
cleanup();
}
void MugenMenu::run() throw (ReturnException) {
Bitmap workArea(DEFAULT_WIDTH,DEFAULT_HEIGHT);
bool done = false;
bool endGame = false;
if ( menuOptions.empty() ){
return;
}
selectedOption = menuOptions.begin();
optionLocation = 0;
menuOptions.front()->setState(MenuOption::Selected);
/*
if ( !music.empty() ){
MenuGlobals::setMusic(music);
}
if ( !selectSound.empty() ){
MenuGlobals::setSelectSound(selectSound);
}
*/
// Set the fade state
fader.setState(FADEIN);
// Do we have logos or intros?
// Logo run it no repeat
if (logo){
logo->run( work,false);
}
// Intro run it no repeat
if (intro){
intro->run( work,false);
}
double runCounter = 0;
while( ! endGame ){
Global::speed_counter = 0;
Global::second_counter = 0;
int game_time = 100;
while ( ! done && (*selectedOption)->getState() != MenuOption::Run && fader.getState() != RUNFADE ){
bool draw = false;
keyInputManager::update();
if ( Global::speed_counter > 0 ){
draw = true;
runCounter += Global::speed_counter * Global::LOGIC_MULTIPLIER;
while ( runCounter >= 1.0 ){
ticker++;
runCounter -= 1;
// Keys
if (fader.getState() == NOFADE){
if ( keyInputManager::keyState(keys::UP, true ) ||
/* for vi people like me */
keyInputManager::keyState('k', true )){
(*selectedOption)->setState(MenuOption::Deselected);
if ( selectedOption > menuOptions.begin() ){
selectedOption--;
optionLocation--;
} else {
selectedOption = menuOptions.end() -1;
optionLocation = menuOptions.size() -1;
}
(*selectedOption)->setState(MenuOption::Selected);
//if(menuOptions.size() > 1)MenuGlobals::playSelectSound();
}
if ( keyInputManager::keyState(keys::DOWN, true ) ||
/* for vi people like me */
keyInputManager::keyState('j', true )){
(*selectedOption)->setState(MenuOption::Deselected);
if ( selectedOption < menuOptions.begin()+menuOptions.size()-1 ){
selectedOption++;
optionLocation++;
} else {
selectedOption = menuOptions.begin();
optionLocation = 0;
}
(*selectedOption)->setState(MenuOption::Selected);
//if(menuOptions.size() > 1)MenuGlobals::playSelectSound();
}
if ( keyInputManager::keyState(keys::LEFT, true) ||
keyInputManager::keyState('h', true)){
if ( (*selectedOption)->leftKey()){
/* ??? */
}
}
if ( keyInputManager::keyState(keys::RIGHT, true )||
keyInputManager::keyState('l', true )){
if ( (*selectedOption)->rightKey()){
/* ??? */
}
}
if ( keyInputManager::keyState(keys::ENTER, true ) ){
if((*selectedOption)->isRunnable())(*selectedOption)->setState( MenuOption::Run );
// Set the fade state
fader.setState(FADEOUT);
}
if ( keyInputManager::keyState(keys::ESC, true ) ){
endGame = done = true;
// Set the fade state
fader.setState(FADEOUT);
(*selectedOption)->setState(MenuOption::Deselected);
throw ReturnException();
}
}
// Fader
fader.act();
// Options
for( vector< MenuOption *>::iterator b = menuOptions.begin(); b != menuOptions.end(); ++b ){
(*b)->logic();
}
// Backgrounds
background->logic( 0, 0, 0, 0 );
}
Global::speed_counter = 0;
}
while ( Global::second_counter > 0 ){
game_time--;
Global::second_counter--;
if ( game_time < 0 ){
game_time = 0;
}
}
if ( draw ){
// backgrounds
background->renderBack(0,0,DEFAULT_WIDTH,DEFAULT_HEIGHT,&workArea);
// Draw any misc stuff in the background of the menu of selected object
(*selectedOption)->drawBelow(work);
// Draw text
renderText(&workArea);
// Foregrounds
background->renderFront(0,0,DEFAULT_WIDTH,DEFAULT_HEIGHT,&workArea);
// Draw any misc stuff in the foreground of the menu of selected object
(*selectedOption)->drawAbove(work);
// Do fades
fader.draw(&workArea);
// Finally render to screen
workArea.Stretch(*work);
work->BlitToScreen();
}
while ( Global::speed_counter < 1 ){
Util::rest( 1 );
keyInputManager::update();
}
}
// do we got an option to run, lets do it
if ((*selectedOption)->getState() == MenuOption::Run){
try{
/*if (backSound != ""){
Sound * ok = Resource::getSound(okSound);
ok->play();
}*/
(*selectedOption)->run(endGame);
if (!endGame){
//characterSelect->run((*selectedOption)->getText(), 1, true, work);
}
} catch ( const ReturnException & re ){
}
// Reset it's state
(*selectedOption)->setState(MenuOption::Selected);
/*if ( !music.empty() ){
MenuGlobals::setMusic(music);
}
if ( !selectSound.empty() ){
MenuGlobals::setSelectSound(selectSound);
}*/
// reset the fade state
fader.setState(FADEIN);
}
/*
if (!music.empty()){
if(MenuGlobals::currentMusic() != music){
MenuGlobals::popMusic();
}
}
if (!selectSound.empty()){
if(MenuGlobals::currentSelectSound() != selectSound){
MenuGlobals::popSelectSound();
}
}
*/
if (endGame){
// Deselect selected entry
(*selectedOption)->setState(MenuOption::Deselected);
/*if (backSound != ""){
Sound * back = Resource::getSound(backSound);
back->play();
}*/
}
}
}
void MugenMenu::cleanup(){
//Backgrounds
if (background) delete background;
// Character select
if (characterSelect) delete characterSelect;
// Get rid of sprites
cleanupSprites();
}
void MugenMenu::cleanupSprites(){
// Get rid of sprites
for( std::map< unsigned int, std::map< unsigned int, MugenSprite * > >::iterator i = sprites.begin() ; i != sprites.end() ; ++i ){
for( std::map< unsigned int, MugenSprite * >::iterator j = i->second.begin() ; j != i->second.end() ; ++j ){
if( j->second )delete j->second;
}
}
}
// Draw text
void MugenMenu::renderText(Bitmap *bmp){
int xplacement = position.x;
int yplacement = position.y;
int visibleCounter = 0;
int offset = optionLocation >= windowVisibleItems ? optionLocation - windowVisibleItems + 1 : 0;
for( std::vector <MenuOption *>::iterator i = menuOptions.begin() + offset; i != menuOptions.end(); ++i){
MenuOption *option = *i;
if (option->getState() == MenuOption::Selected){
MugenFont *font = fonts[fontActive.index-1];
if(showBoxCursor){
boxCursorCoords.alpha += boxCursorCoords.alphaMove;
if (boxCursorCoords.alpha <= 0){
boxCursorCoords.alpha = 0;
boxCursorCoords.alphaMove = 6;
}
else if (boxCursorCoords.alpha >= 128){
boxCursorCoords.alpha = 128;
boxCursorCoords.alphaMove = -6;
}
Bitmap::drawingMode(Bitmap::MODE_TRANS);
Bitmap::transBlender(0,0,0,boxCursorCoords.alpha);
bmp->rectangleFill(xplacement + boxCursorCoords.x1, yplacement + boxCursorCoords.y1, xplacement + boxCursorCoords.x2,yplacement + boxCursorCoords.y2,Bitmap::makeColor(255,255,255));
Bitmap::drawingMode(Bitmap::MODE_SOLID);
}
font->render(xplacement, yplacement, fontActive.position, fontActive.bank, *bmp, option->getText());
xplacement += fontSpacing.x;
yplacement += fontSpacing.y;
} else {
MugenFont *font = fonts[fontItem.index-1];
font->render(xplacement, yplacement, fontItem.position, fontItem.bank, *bmp, option->getText());
xplacement += fontSpacing.x;
yplacement += fontSpacing.y;
}
// Visible counter
visibleCounter++;
if (visibleCounter >= windowVisibleItems)break;
}
}
pass selectbg stuff to the background manager
#include "util/bitmap.h"
#include "mugen/mugen_menu.h"
#include <fstream>
#include <iostream>
#include <algorithm>
#include <cctype>
#include <string>
#include <cstring>
#include <vector>
#include <ostream>
#include <sstream>
#include <iostream>
#include "mugen_stage.h"
#include "init.h"
#include "resource.h"
#include "util/funcs.h"
#include "util/file-system.h"
#include "util/timedifference.h"
#include "game/console.h"
#include "object/animation.h"
#include "object/object.h"
#include "object/character.h"
#include "object/object_attack.h"
#include "object/player.h"
#include "globals.h"
#include "factory/font_render.h"
#include "menu/menu_option.h"
#include "menu/menu_global.h"
#include "menu/option_quit.h"
#include "menu/option_dummy.h"
#include "gui/keyinput_manager.h"
#include "gui/keys.h"
#include "mugen_animation.h"
#include "mugen_background.h"
#include "character.h"
#include "mugen_item.h"
#include "mugen_item_content.h"
#include "mugen_section.h"
#include "mugen_sound.h"
#include "mugen_reader.h"
#include "mugen_sprite.h"
#include "mugen_util.h"
#include "mugen_font.h"
#include "mugen_storyboard.h"
#include "mugen/option_versus.h"
#include "ast/all.h"
#include "parser/all.h"
namespace PaintownUtil = ::Util;
using namespace std;
static const int DEFAULT_WIDTH = 320;
static const int DEFAULT_HEIGHT = 240;
static const int DEFAULT_SCREEN_X_AXIS = 160;
static const int DEFAULT_SCREEN_Y_AXIS = 0;
MugenCharacterSelect::MugenCharacterSelect(const unsigned long int &ticker, std::vector<MugenFont *> &fonts):
cellBackgroundBitmap(0),
cellRandomBitmap(0),
selectTicker(ticker),
fonts(fonts),
characterList(0){
}
MugenCharacterSelect::~MugenCharacterSelect(){
/*if (cellBackgroundBitmap){
delete cellBackgroundBitmap;
}
if (cellRandomBitmap){
delete cellRandomBitmap;
}
if (p1Cursor.active){
delete p1Cursor.active;
}
if (p1Cursor.done){
delete p1Cursor.done;
}
if (p2Cursor.active){
delete p2Cursor.active;
}
if (p2Cursor.done){
delete p2Cursor.done;
}*/
if (background){
delete background;
}
for (std::vector< std::vector< MugenCell *> >::iterator i = cells.begin(); i != cells.end(); ++i){
std::vector< MugenCell *> &row = *i;
for (std::vector< MugenCell *>::iterator c = row.begin(); c != row.end(); ++c){
MugenCell *cell = *c;
if (cell) delete cell;
}
}
// Characters
for (std::vector< Mugen::Character *>::iterator c = characters.begin(); c != characters.end(); ++c){
if (*c) delete (*c);
}
// STages
for (std::vector< MugenStage *>::iterator i = stages.begin(); i != stages.end(); ++i){
if (*i) delete (*i);
}
// Delete character select list struct
if (characterList){
delete characterList;
}
}
void MugenCharacterSelect::load(const std::string &selectFile, const std::vector<Ast::Section*> & sections, MugenSprites & sprites){
for (vector<Ast::Section*>::const_iterator it = sections.begin(); it != sections.end(); it++){
Ast::Section * section = *it;
std::string head = section->getName();
/* this should really be head = Mugen::Util::fixCase(head) */
Mugen::Util::fixCase(head);
if (head == "select info"){
#if 0
while( collection[index]->hasItems() ){
MugenItemContent *content = collection[index]->getNext();
const MugenItem *item = content->getNext();
std::string itemhead = item->query();
Mugen::Util::removeSpaces(itemhead);
Mugen::Util::fixCase(itemhead);
Global::debug(1) << "Got itemhead: '" << itemhead << "'" << endl;
if ( itemhead == "fadein.time" ){
int time;
*content->getNext() >> time;
fader.setFadeInTime(time);
} else if ( itemhead == "fadein.color" ){
int r,g,b;
*content->getNext() >> r;
*content->getNext() >> g;
*content->getNext() >> b;
fader.setFadeInColor(Bitmap::makeColor(r,g,b));
} else if ( itemhead == "fadeout.time" ){
int time;
*content->getNext() >> time;
fader.setFadeOutTime(time);
} else if ( itemhead == "fadeout.color" ){
int r,g,b;
*content->getNext() >> r;
*content->getNext() >> g;
*content->getNext() >> b;
fader.setFadeOutColor(Bitmap::makeColor(r,g,b));
} else if ( itemhead == "rows" ){
*content->getNext() >> rows;
} else if ( itemhead == "columns" ){
*content->getNext() >> columns;
} else if ( itemhead == "wrapping"){
*content->getNext() >> wrapping;
} else if ( itemhead == "pos" ){
*content->getNext() >> position.x;
*content->getNext() >> position.y;
} else if ( itemhead == "showemptyboxes" ){
*content->getNext() >> showEmptyBoxes;
} else if ( itemhead == "moveoveremptyboxes" ){
*content->getNext() >> moveOverEmptyBoxes;
} else if ( itemhead == "cell.size" ){
*content->getNext() >> cellSize.x;
*content->getNext() >> cellSize.y;
} else if ( itemhead == "cell.spacing" ){
*content->getNext() >> cellSpacing;
} else if ( itemhead == "cell.bg.spr" ){
int group, sprite;
*content->getNext() >> group;
*content->getNext() >> sprite;
cellBackgroundSprite = sprites[group][sprite];
cellBackgroundSprite->load();
cellBackgroundBitmap = cellBackgroundSprite->getBitmap();//= new Bitmap(Bitmap::memoryPCX((unsigned char*) cellBackgroundSprite->pcx, cellBackgroundSprite->newlength, true));
} else if ( itemhead == "cell.random.spr" ){
int group, sprite;
*content->getNext() >> group;
*content->getNext() >> sprite;
cellRandomSprite = sprites[group][sprite];
cellRandomSprite->load();
cellRandomBitmap = cellRandomSprite->getBitmap();// = new Bitmap(Bitmap::memoryPCX((unsigned char*) cellRandomSprite->pcx, cellRandomSprite->newlength, true));
} else if ( itemhead == "cell.random.switchtime" ){
*content->getNext() >> cellRandomSwitchTime;
} else if ( itemhead == "p1.cursor.startcell" ){
*content->getNext() >> p1Cursor.cursor.x;
*content->getNext() >> p1Cursor.cursor.y;
p1Cursor.start.x = p1Cursor.cursor.x;
p1Cursor.start.y = p1Cursor.cursor.y;
} else if ( itemhead == "p1.cursor.active.spr"){
int group, sprite;
*content->getNext() >> group;
*content->getNext() >> sprite;
p1Cursor.cursorActiveSprite = sprites[group][sprite];
p1Cursor.cursorActiveSprite->load();
p1Cursor.active = p1Cursor.cursorActiveSprite->getBitmap();//new Bitmap(Bitmap::memoryPCX((unsigned char*) p1Cursor.cursorActiveSprite->pcx, p1Cursor.cursorActiveSprite->newlength, true));
} else if ( itemhead == "p1.cursor.done.spr"){
int group, sprite;
*content->getNext() >> group;
*content->getNext() >> sprite;
p1Cursor.cursorDoneSprite = sprites[group][sprite];
p1Cursor.cursorDoneSprite->load();
p1Cursor.done = p1Cursor.cursorDoneSprite->getBitmap();//new Bitmap(Bitmap::memoryPCX((unsigned char*) p1Cursor.cursorDoneSprite->pcx, p1Cursor.cursorDoneSprite->newlength, true));
}
else if ( itemhead == "p1.cursor.move.snd" ){ /* nothing */ }
else if ( itemhead == "p1.cursor.done.snd"){ /* nothing */ }
else if ( itemhead == "p1.random.move.snd"){ /* nothing */ }
else if ( itemhead == "p2.cursor.startcell"){
*content->getNext() >> p2Cursor.cursor.x;
*content->getNext() >> p2Cursor.cursor.y;
p2Cursor.start.x = p2Cursor.cursor.x;
p2Cursor.start.y = p2Cursor.cursor.y;
} if ( itemhead == "p2.cursor.active.spr"){
int group, sprite;
*content->getNext() >> group;
*content->getNext() >> sprite;
p2Cursor.cursorActiveSprite = sprites[group][sprite];
p2Cursor.cursorActiveSprite->load();
p2Cursor.active = p2Cursor.cursorActiveSprite->getBitmap();//new Bitmap(Bitmap::memoryPCX((unsigned char*) p2Cursor.cursorActiveSprite->pcx, p2Cursor.cursorActiveSprite->newlength, true));
} else if ( itemhead == "p2.cursor.done.spr"){
int group, sprite;
*content->getNext() >> group;
*content->getNext() >> sprite;
p2Cursor.cursorDoneSprite = sprites[group][sprite];
p2Cursor.cursorDoneSprite->load();
p2Cursor.done = p2Cursor.cursorDoneSprite->getBitmap();// = new Bitmap(Bitmap::memoryPCX((unsigned char*) p2Cursor.cursorDoneSprite->pcx, p2Cursor.cursorDoneSprite->newlength, true));
} else if ( itemhead == "p2.cursor.blink"){
*content->getNext() >> p2Cursor.blink;
p2Cursor.blinkCounter = 0;
}
else if ( itemhead == "p2.cursor.move.snd"){ /* nothing */ }
else if ( itemhead == "p2.cursor.done.snd"){ /* nothing */ }
else if ( itemhead == "p2.random.move.snd"){ /* nothing */ }
else if ( itemhead == "stage.move.snd"){ /* nothing */ }
else if ( itemhead == "stage.done.snd"){ /* nothing */ }
else if ( itemhead == "cancel.snd"){ /* nothing */ }
else if ( itemhead == "portrait.offset"){
*content->getNext() >> portraitOffset.x;
*content->getNext() >> portraitOffset.y;
} else if ( itemhead == "portrait.scale"){
*content->getNext() >> portraitScale.x;
*content->getNext() >> portraitScale.y;
} else if ( itemhead == "title.offset"){
*content->getNext() >> titleOffset.x;
*content->getNext() >> titleOffset.y;
} else if ( itemhead == "title.font"){
*content->getNext() >> titleFont.index;
*content->getNext() >> titleFont.bank;
*content->getNext() >> titleFont.position;
} else if ( itemhead == "p1.face.offset"){
*content->getNext() >> p1Cursor.faceOffset.x;
*content->getNext() >> p1Cursor.faceOffset.y;
} else if ( itemhead == "p1.face.scale"){
*content->getNext() >> p1Cursor.faceScalex;
*content->getNext() >> p1Cursor.faceScaley;
} else if ( itemhead == "p1.face.facing"){
*content->getNext() >> p1Cursor.facing;
} else if ( itemhead == "p2.face.offset"){
*content->getNext() >> p2Cursor.faceOffset.x;
*content->getNext() >> p2Cursor.faceOffset.y;
} else if ( itemhead == "p2.face.scale"){
*content->getNext() >> p2Cursor.faceScalex;
*content->getNext() >> p2Cursor.faceScaley;
} else if ( itemhead == "p2.face.facing"){
*content->getNext() >> p2Cursor.facing;
} else if ( itemhead == "p1.name.offset"){
*content->getNext() >> p1Cursor.nameOffset.x;
*content->getNext() >> p1Cursor.nameOffset.y;
} else if ( itemhead == "p1.name.font"){
*content->getNext() >> p1Cursor.nameFont.index;
*content->getNext() >> p1Cursor.nameFont.bank;
*content->getNext() >> p1Cursor.nameFont.position;
} else if ( itemhead == "p2.name.offset"){
*content->getNext() >> p2Cursor.nameOffset.x;
*content->getNext() >> p2Cursor.nameOffset.y;
} else if ( itemhead == "p2.name.font"){
*content->getNext() >> p2Cursor.nameFont.index;
*content->getNext() >> p2Cursor.nameFont.bank;
*content->getNext() >> p2Cursor.nameFont.position;
} else if ( itemhead == "stage.pos"){
*content->getNext() >> stageInfo.stagePosition.x;
*content->getNext() >> stageInfo.stagePosition.y;
} else if ( itemhead == "stage.active.font"){
*content->getNext() >> stageInfo.stageActiveFont.index;
*content->getNext() >> stageInfo.stageActiveFont.bank;
*content->getNext() >> stageInfo.stageActiveFont.position;
} else if ( itemhead == "stage.active2.font"){
*content->getNext() >> stageInfo.stageActiveFont2.index;
*content->getNext() >> stageInfo.stageActiveFont2.bank;
*content->getNext() >> stageInfo.stageActiveFont2.position;
} else if ( itemhead == "stage.done.font"){
*content->getNext() >> stageInfo.stageDoneFont.index;
*content->getNext() >> stageInfo.stageDoneFont.bank;
*content->getNext() >> stageInfo.stageDoneFont.position;
} else if ( itemhead.find("teammenu")!=std::string::npos ){ /* Ignore for now */ }
//else throw MugenException( "Unhandled option in Select Info Section: " + itemhead );
}
#endif
} else if (head == "selectbgdef"){
/* Background management */
MugenBackgroundManager *manager = new MugenBackgroundManager(Mugen::Util::getFileDir(selectFile), sections, selectTicker, &sprites, "selectbg");
background = manager;
Global::debug(1) << "Got background: '" << manager->getName() << "'" << endl;
}
}
fonts = fonts;
// Set up cell table
Mugen::Point currentPosition;
currentPosition.y = position.y;
for (int row = 0; row < rows; ++row){
currentPosition.x = position.x;
std::vector< MugenCell *> cellRow;
for (int column = 0; column < columns; ++column){
MugenCell *cell = new MugenCell;
cell->position.x = currentPosition.x;
cell->position.y = currentPosition.y;
cell->character = 0;
cell->random = false;
cell->empty = true;
cellRow.push_back(cell);
currentPosition.x += cellSize.x + cellSpacing;
}
cells.push_back(cellRow);
currentPosition.y += cellSize.y + cellSpacing;
}
// Now load up our characters
loadCharacters(selectFile);
// Set stage info
stageInfo.selected = false;
stageInfo.altCounter = 0;
// Set up the animations for those that have action numbers assigned (not -1 )
// Also do their preload
if (background) background->preload(DEFAULT_SCREEN_X_AXIS, DEFAULT_SCREEN_Y_AXIS );
}
MugenSelectedChars *MugenCharacterSelect::run(const std::string &title, const int players, const bool selectStage, Bitmap *work){
Bitmap workArea(DEFAULT_WIDTH,DEFAULT_HEIGHT);
bool done = false;
// Set the fade state
fader.setState(FADEIN);
double runCounter = 0;
Global::speed_counter = 0;
Global::second_counter = 0;
int game_time = 100;
// Set player 1 and 2 cursors
p1Cursor.selecting = true;
p1Cursor.cursor.x = p1Cursor.start.x;
p1Cursor.cursor.y = p1Cursor.start.y;
p2Cursor.selecting = true;
p2Cursor.cursor.x = p2Cursor.start.x;
p2Cursor.cursor.y = p2Cursor.start.y;
// Stage list
stageInfo.selected = false;
stageInfo.altCounter = 0;
std::vector< MugenStage *> stageSelections;
unsigned int random = Util::rnd(0,stages.size()-1);
stageSelections.push_back(stages[random]);
for (std::vector<MugenStage *>::iterator i = stages.begin(); i != stages.end(); ++i){
stageSelections.push_back(*i);
}
unsigned int currentStage = 0;
if (characterList){
delete characterList;
}
characterList = new MugenSelectedChars();
characterList->selectedStage = 0;
while ( ! done && fader.getState() != RUNFADE ){
bool draw = false;
keyInputManager::update();
if ( Global::speed_counter > 0 ){
draw = true;
runCounter += Global::speed_counter * Global::LOGIC_MULTIPLIER;
while ( runCounter >= 1.0 ){
runCounter -= 1;
// Keys
if (fader.getState() == NOFADE){
if ( keyInputManager::keyState(keys::UP, true ) ||
/* for vi people like me */
keyInputManager::keyState('k', true )){
movePlayer1Cursor(-1,0);
}
if ( keyInputManager::keyState(keys::DOWN, true ) ||
/* for vi people like me */
keyInputManager::keyState('j', true )){
movePlayer1Cursor(1,0);
}
if ( keyInputManager::keyState(keys::LEFT, true) ||
keyInputManager::keyState('h', true)){
if (p1Cursor.selecting){
movePlayer1Cursor(0,-1);
} else {
if (selectStage && !stageInfo.selected){
if (currentStage > 0){
currentStage--;
} else {
currentStage = stageSelections.size() -1;
}
}
}
}
if ( keyInputManager::keyState(keys::RIGHT, true )||
keyInputManager::keyState('l', true )){
if (p1Cursor.selecting){
movePlayer1Cursor(0,1);
} else {
if (selectStage && !stageInfo.selected){
if (currentStage < stageSelections.size()-1){
currentStage++;
} else {
currentStage = 0;
}
}
}
}
if ( keyInputManager::keyState(keys::ENTER, true ) ){
if (!cells[p1Cursor.cursor.x][p1Cursor.cursor.y]->empty && p1Cursor.selecting){
p1Cursor.selecting = false;
characterList->team1.push_back(cells[p1Cursor.cursor.x][p1Cursor.cursor.y]->character);
} else if (!p1Cursor.selecting && selectStage && !stageInfo.selected){
stageInfo.selected = true;
characterList->selectedStage = stageSelections[currentStage];
}
}
if ( keyInputManager::keyState(keys::ESC, true ) ){
done = true;
fader.setState(FADEOUT);
}
}
// Fader
fader.act();
// Backgrounds
background->logic( 0, 0, 0, 0 );
// Check status
if (players == 2){
if (!p1Cursor.selecting && !p2Cursor.selecting && stageInfo.selected){
done = true;
fader.setState(FADEOUT);
}
} else if (players == 1){
if (!p1Cursor.selecting && ((selectStage && stageInfo.selected) || !selectStage)){
done = true;
fader.setState(FADEOUT);
}
}
}
Global::speed_counter = 0;
}
while ( Global::second_counter > 0 ){
game_time--;
Global::second_counter--;
if ( game_time < 0 ){
game_time = 0;
}
}
if ( draw ){
// backgrounds
background->renderBack(0,0,DEFAULT_WIDTH,DEFAULT_HEIGHT,&workArea);
// Stuff
drawCursors(players, &workArea);
// Draw title
MugenFont *font = fonts[titleFont.index-1];
font->render(titleOffset.x, titleOffset.y, titleFont.position, titleFont.bank, workArea, title);
// Draw stage
if (selectStage && (!p1Cursor.selecting || !p2Cursor.selecting)){
std::string stageName = "Stage";
if (currentStage == 0){
stageName += ": Random";
} else {
std::stringstream s;
s << " " << currentStage << ": " << stageSelections[currentStage]->getName();
stageName += s.str();
}
if (!stageInfo.selected){
if (stageInfo.altCounter % 2 == 0){
// reuse Font
font = fonts[stageInfo.stageActiveFont.index-1];
font->render(stageInfo.stagePosition.x, stageInfo.stagePosition.y, stageInfo.stageActiveFont.position, stageInfo.stageActiveFont.bank, workArea, stageName);
} else {
// reuse Font
font = fonts[stageInfo.stageActiveFont2.index-1];
font->render(stageInfo.stagePosition.x, stageInfo.stagePosition.y, stageInfo.stageActiveFont2.position, stageInfo.stageActiveFont2.bank, workArea, stageName);
}
stageInfo.altCounter++;
if (stageInfo.altCounter == 10){
stageInfo.altCounter = 0;
}
} else {
// Done selecting
// reuse Font
font = fonts[stageInfo.stageDoneFont.index-1];
font->render(stageInfo.stagePosition.x, stageInfo.stagePosition.y, stageInfo.stageDoneFont.position, stageInfo.stageDoneFont.bank, workArea, stageName);
}
}
// Foregrounds
background->renderFront(0,0,DEFAULT_WIDTH,DEFAULT_HEIGHT,&workArea);
// Do fades
fader.draw(&workArea);
// Finally render to screen
workArea.Stretch(*work);
work->BlitToScreen();
}
while ( Global::speed_counter < 1 ){
Util::rest( 1 );
keyInputManager::update();
}
}
if (selectStage && !stageInfo.selected)return 0;
return characterList;
}
void MugenCharacterSelect::drawCursors(const int players, Bitmap *work){
Mugen::Point currentPosition;
currentPosition.y = position.y;
for (int row = 0; row < rows; ++row){
currentPosition.x = position.x;
for (int column = 0; column < columns; ++column){
MugenCell *cell = cells[row][column];
if (!cell->empty){
if (!cell->random){
cell->character->renderSprite(cell->position.x,cell->position.y,9000,0,work);
cellBackgroundBitmap->draw(currentPosition.x,currentPosition.y,*work);
} else {
cellRandomBitmap->draw(cell->position.x,cell->position.y,*work);
cellBackgroundBitmap->draw(currentPosition.x,currentPosition.y,*work);
}
} else if (showEmptyBoxes){
cellBackgroundBitmap->draw(currentPosition.x,currentPosition.y,*work);
}
currentPosition.x += cellSize.x + cellSpacing;
}
currentPosition.y += cellSize.y + cellSpacing;
}
// Player cursors player 1
if (p1Cursor.selecting){
p1Cursor.active->draw(cells[p1Cursor.cursor.x][p1Cursor.cursor.y]->position.x,cells[p1Cursor.cursor.x][p1Cursor.cursor.y]->position.y,*work);
} else {
p1Cursor.done->draw(cells[p1Cursor.cursor.x][p1Cursor.cursor.y]->position.x,cells[p1Cursor.cursor.x][p1Cursor.cursor.y]->position.y,*work);
}
if ( !cells[p1Cursor.cursor.x][p1Cursor.cursor.y]->empty ){
MugenCell *cell = cells[p1Cursor.cursor.x][p1Cursor.cursor.y];
if (!cell->empty){
if (!cell->random){
// Portrait
cell->character->renderSprite(p1Cursor.faceOffset.x,p1Cursor.faceOffset.y,9000,1,work,p1Cursor.facing, p1Cursor.faceScalex,p1Cursor.faceScaley);
// Name
MugenFont *font = fonts[p1Cursor.nameFont.index-1];
font->render(p1Cursor.nameOffset.x, p1Cursor.nameOffset.y, p1Cursor.nameFont.position, p1Cursor.nameFont.bank, *work, cell->character->getName());
} else {
}
}
}
// Player cursors player 2
if (players > 1){
if (p2Cursor.blink && ((p1Cursor.cursor.x == p2Cursor.cursor.x) && (p1Cursor.cursor.y == p2Cursor.cursor.y))){
if (p2Cursor.blinkCounter % 2 == 0){
if (p2Cursor.selecting){
p2Cursor.active->draw(cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->position.x,cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->position.y,*work);
} else {
p2Cursor.done->draw(cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->position.x,cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->position.y,*work);
}
}
p2Cursor.blinkCounter++;
if (p2Cursor.blinkCounter == 10){
p2Cursor.blinkCounter = 0;
}
} else {
if (p2Cursor.selecting){
p2Cursor.active->draw(cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->position.x,cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->position.y,*work);
} else {
p2Cursor.done->draw(cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->position.x,cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->position.y,*work);
}
}
if ( !cells[p2Cursor.cursor.x][p2Cursor.cursor.y]->empty ){
MugenCell *cell = cells[p2Cursor.cursor.x][p2Cursor.cursor.y];
if (!cell->empty){
if (!cell->random){
// Portrait
cell->character->renderSprite(p2Cursor.faceOffset.x,p2Cursor.faceOffset.y,9000,1,work,p2Cursor.facing, p2Cursor.faceScalex,p2Cursor.faceScaley);
// Name
MugenFont *font = fonts[p2Cursor.nameFont.index-1];
font->render(p2Cursor.nameOffset.x, p2Cursor.nameOffset.y, p2Cursor.nameFont.position, p2Cursor.nameFont.bank, *work, cell->character->getName());
} else {
}
}
}
}
}
void MugenCharacterSelect::movePlayer1Cursor(int x, int y){
if (!p1Cursor.selecting){
return;
}
if (x > 0){
if (moveOverEmptyBoxes){
p1Cursor.cursor.x += x;
if (wrapping && p1Cursor.cursor.x >= rows){
p1Cursor.cursor.x = 0;
} else if (p1Cursor.cursor.x >= rows) {
p1Cursor.cursor.x = rows-1;
}
}
else {
int curx = p1Cursor.cursor.x;
while (!cells[curx][p1Cursor.cursor.y]->empty){
curx+=x;
if (wrapping && curx >= rows){
curx = 0;
} else if (curx >= rows) {
curx = p1Cursor.cursor.x;
}
if (curx == p1Cursor.cursor.x){
break;
}
}
if (!cells[curx][p1Cursor.cursor.y]->empty)p1Cursor.cursor.x = curx;
}
} else if (x < 0){
if (moveOverEmptyBoxes){
p1Cursor.cursor.x += x;
if (wrapping && p1Cursor.cursor.x < 0){
p1Cursor.cursor.x = rows-1;
} else if (p1Cursor.cursor.x < 0) {
p1Cursor.cursor.x = 0;
}
}
else {
int curx = p1Cursor.cursor.x;
while (!cells[curx][p1Cursor.cursor.y]->empty){
curx+=x;
if (wrapping && curx < 0){
curx = rows-1;
} else if (curx < 0) {
curx = p1Cursor.cursor.x;
}
if (curx == p1Cursor.cursor.x){
break;
}
}
if (!cells[curx][p1Cursor.cursor.y]->empty)p1Cursor.cursor.x = curx;
}
}
if (y > 0){
if (moveOverEmptyBoxes){
p1Cursor.cursor.y += y;
if (wrapping && p1Cursor.cursor.y >= columns){
p1Cursor.cursor.y = 0;
} else if (p1Cursor.cursor.y >= columns) {
p1Cursor.cursor.y = columns-1;
}
}
else {
int cury = p1Cursor.cursor.y;
while (!cells[p1Cursor.cursor.x][cury]->empty){
cury+=y;
if (wrapping && cury >= columns){
cury = 0;
} else if (cury >= columns) {
cury = p1Cursor.cursor.y;
}
if (cury == p1Cursor.cursor.y){
break;
}
}
if (!cells[p1Cursor.cursor.x][cury]->empty)p1Cursor.cursor.y = cury;
}
} else if (y < 0){
if (moveOverEmptyBoxes){
p1Cursor.cursor.y += y;
if (wrapping && p1Cursor.cursor.y < 0){
p1Cursor.cursor.y = columns-1;
} else if (p1Cursor.cursor.y < 0) {
p1Cursor.cursor.y = 0;
}
}
else {
int cury = p1Cursor.cursor.y;
while (!cells[p1Cursor.cursor.x][cury]->empty){
cury+=y;
if (wrapping && cury < 0){
cury = columns-1;
} else if (cury < 0) {
cury = p1Cursor.cursor.y;
}
if (cury == p1Cursor.cursor.y){
break;
}
}
if (!cells[p1Cursor.cursor.x][cury]->empty)p1Cursor.cursor.y = cury;
}
}
}
void MugenCharacterSelect::movePlayer2Cursor(int x, int y){
if (!p2Cursor.selecting){
return;
}
if (x > 0){
if (moveOverEmptyBoxes){
p2Cursor.cursor.x += x;
if (wrapping && p2Cursor.cursor.x >= rows){
p2Cursor.cursor.x = 0;
} else if (p2Cursor.cursor.x >= rows) {
p2Cursor.cursor.x = rows-1;
}
}
else {
int curx = p2Cursor.cursor.x;
while (!cells[curx][p2Cursor.cursor.y]->empty){
curx+=x;
if (wrapping && curx >= rows){
curx = 0;
} else if (curx >= rows) {
curx = p2Cursor.cursor.x;
}
if (curx == p2Cursor.cursor.x){
break;
}
}
if (!cells[curx][p2Cursor.cursor.y]->empty)p2Cursor.cursor.x = curx;
}
} else if (x < 0){
if (moveOverEmptyBoxes){
p2Cursor.cursor.x += x;
if (wrapping && p2Cursor.cursor.x < 0){
p2Cursor.cursor.x = rows-1;
} else if (p2Cursor.cursor.x < 0) {
p2Cursor.cursor.x = 0;
}
}
else {
int curx = p2Cursor.cursor.x;
while (!cells[curx][p2Cursor.cursor.y]->empty){
curx+=x;
if (wrapping && curx < 0){
curx = rows-1;
} else if (curx < 0) {
curx = p2Cursor.cursor.x;
}
if (curx == p2Cursor.cursor.x){
break;
}
}
if (!cells[curx][p2Cursor.cursor.y]->empty)p2Cursor.cursor.x = curx;
}
}
if (y > 0){
if (moveOverEmptyBoxes){
p2Cursor.cursor.y += y;
if (wrapping && p2Cursor.cursor.y >= columns){
p2Cursor.cursor.y = 0;
} else if (p2Cursor.cursor.y >= columns) {
p2Cursor.cursor.y = columns-1;
}
}
else {
int cury = p2Cursor.cursor.y;
while (!cells[p2Cursor.cursor.x][cury]->empty){
cury+=y;
if (wrapping && cury >= columns){
cury = 0;
} else if (cury >= columns) {
cury = p2Cursor.cursor.y;
}
if (cury == p2Cursor.cursor.y){
break;
}
}
if (!cells[p1Cursor.cursor.x][cury]->empty)p2Cursor.cursor.y = cury;
}
} else if (y < 0){
if (moveOverEmptyBoxes){
p2Cursor.cursor.y += y;
if (wrapping && p2Cursor.cursor.y < 0){
p2Cursor.cursor.y = columns-1;
} else if (p2Cursor.cursor.y < 0) {
p2Cursor.cursor.y = 0;
}
}
else {
int cury = p2Cursor.cursor.y;
while (!cells[p2Cursor.cursor.x][cury]->empty){
cury+=y;
if (wrapping && cury < 0){
cury = columns-1;
} else if (cury < 0) {
cury = p2Cursor.cursor.y;
}
if (cury == p2Cursor.cursor.y){
break;
}
}
if (!cells[p1Cursor.cursor.x][cury]->empty)p2Cursor.cursor.y = cury;
}
}
}
void MugenCharacterSelect::loadCharacters(const std::string &selectFile) throw (MugenException){
std::string dir = Mugen::Util::getFileDir(selectFile);
std::string file = Mugen::Util::stripDir(selectFile);
/* FIXME!! Replace with peg parser */
MugenReader reader( Mugen::Util::getCorrectFileLocation(dir,file) );
std::vector< MugenSection * > collection;
collection = reader.getCollection();
std::vector< std::string > stageNames;
/* Extract info for our first section of our menu */
for( unsigned int i = 0; i < collection.size(); ++i ){
std::string head = collection[i]->getHeader();
Mugen::Util::fixCase(head);
if( head == "characters" ){
int row = 0;
int column = 0;
while( collection[i]->hasItems() ){
MugenItemContent *content = collection[i]->getNext();
const MugenItem *item = content->getNext();
std::string itemhead = item->query();
Mugen::Util::removeSpaces(itemhead);
if (itemhead=="random"){
// set random flag
cells[row][column]->random = true;
cells[row][column]->empty = false;
} else {
// Get character
Mugen::Character *character = new Mugen::Character(itemhead);
try{
character->load();
} catch (const MugenException & ex){
throw ex;
}
characters.push_back(character);
Global::debug(1) << "Got character: " << character->getName() << endl;
// set cell
cells[row][column]->character = character;
cells[row][column]->empty = false;
if (content->hasItems()){
// Next item will be a stage lets add it to the list of stages
std::string temp;
*content->getNext() >> temp;
stageNames.push_back(temp);
Global::debug(1) << "Got stage: " << temp << endl;
}
// Need to add in other options and assign their respective stages to them....
}
column++;
if (column >=columns){
column = 0;
row++;
// Have we met our quota?
if (row >= rows){
// can't add any more characters... breakage
break;
}
}
}
}
else if( head == "extrastages" ){
while( collection[i]->hasItems() ){
MugenItemContent *content = collection[i]->getNext();
const MugenItem *item = content->getNext();
std::string itemhead = item->query();
Mugen::Util::removeSpaces(itemhead);
// Next item will be a stage lets add it to the list of stages
stageNames.push_back(itemhead);
Global::debug(1) << "Got stage: " << itemhead << endl;
}
}
else if( head == "options" ){ /* ignore for now */}
else throw MugenException("Unhandled Section in '" + selectFile + "': " + head, __FILE__, __LINE__);
}
// Prepare stages
for (std::vector<std::string>::iterator i = stageNames.begin(); i != stageNames.end(); ++i){
MugenStage *stage = new MugenStage(*i);
// No need to load them.... Load only when using the stage...
/*try{
stage->load();
} catch (MugenException &ex){
throw MugenException(ex);
}*/
stages.push_back(stage);
}
}
MugenMenu::MugenMenu(const std::string &filename):
optionLocation(0),
location(filename),
spriteFile(""),
soundFile(""),
logoFile(""),
introFile(""),
selectFile(""),
fightFile(""),
windowVisibleItems(0),
showBoxCursor(false),
ticker(0),
background(0),
logo(0),
intro(0),
characterSelect(0){
}
static vector<Ast::Section*> collectSelectStuff(Ast::AstParse::section_iterator & iterator, Ast::AstParse::section_iterator end){
Ast::AstParse::section_iterator last = iterator;
vector<Ast::Section*> stuff;
Ast::Section * section = *iterator;
std::string head = section->getName();
/* better to do case insensitive regex matching rather than
* screw up the original string
*/
stuff.push_back(section);
iterator++;
while (true){
if (iterator == end){
break;
}
section = *iterator;
string sectionName = section->getName();
Mugen::Util::fixCase(sectionName);
// Global::debug(2, __FILE__) << "Match '" << (prefix + name + ".*") << "' against '" << sectionName << "'" << endl;
if (PaintownUtil::matchRegex(sectionName, "select")){
stuff.push_back(section);
} else {
break;
}
last = iterator;
iterator++;
}
iterator = last;
return stuff;
}
void MugenMenu::loadData() throw (MugenException){
// Lets look for our def since some people think that all file systems are case insensitive
std::string baseDir = Filesystem::find("mugen/data/" + Mugen::Util::getFileDir(location));
const std::string ourDefFile = Mugen::Util::fixFileName( baseDir, Mugen::Util::stripDir(location) );
// get real basedir
//baseDir = Mugen::Util::getFileDir( ourDefFile );
Global::debug(1) << baseDir << endl;
if (ourDefFile.empty()){
throw MugenException( "Cannot locate menu definition file for: " + location );
}
TimeDifference diff;
diff.startTime();
Ast::AstParse parsed((list<Ast::Section*>*) Mugen::Def::main(ourDefFile));
diff.endTime();
Global::debug(1) << "Parsed mugen file " + ourDefFile + " in" + diff.printTime("") << endl;
/*
MugenReader reader( ourDefFile );
std::vector< MugenSection * > collection;
collection = reader.getCollection();
*/
for (Ast::AstParse::section_iterator section_it = parsed.getSections()->begin(); section_it != parsed.getSections()->end(); section_it++){
Ast::Section * section = *section_it;
std::string head = section->getName();
/* this should really be head = Mugen::Util::fixCase(head) */
Mugen::Util::fixCase(head);
if (head == "info"){
class InfoWalker: public Ast::Walker{
public:
InfoWalker(MugenMenu & menu):
menu(menu){
}
MugenMenu & menu;
virtual void onAttributeSimple(const Ast::AttributeSimple & simple){
if (simple == "name"){
menu.setName(simple.valueAsString());
Global::debug(1) << "Read name '" << menu.getName() << "'" << endl;
} else if (simple == "author"){
string temp;
simple >> temp;
Global::debug(1) << "Made by: '" << temp << "'" << endl;
} else {
throw MugenException("Unhandled option in Info Section: " + simple.toString(), __FILE__, __LINE__);
}
}
};
InfoWalker walker(*this);
section->walk(walker);
} else if (head == "files"){
class FileWalker: public Ast::Walker{
public:
FileWalker(MugenMenu & menu, const string & baseDir):
menu(menu),
baseDir(baseDir){
}
MugenMenu & menu;
const string & baseDir;
virtual void onAttributeSimple(const Ast::AttributeSimple & simple){
if (simple == "spr"){
simple >> menu.spriteFile;
Global::debug(1) << "Got Sprite File: '" << menu.spriteFile << "'" << endl;
Mugen::Util::readSprites(Mugen::Util::getCorrectFileLocation(baseDir, menu.spriteFile), "", menu.sprites);
} else if (simple == "snd"){
simple >> menu.soundFile;
Global::debug(1) << "Got Sound File: '" << menu.soundFile << "'" << endl;
} else if (simple == "logo.storyboard"){
try{
simple >> menu.logoFile;
try{
Global::debug(1) << "Logo file " << baseDir << "/" << menu.logoFile << endl;
menu.logo = new MugenStoryboard(Mugen::Util::getCorrectFileLocation(baseDir, menu.logoFile));
menu.logo->load();
Global::debug(1) << "Got Logo Storyboard File: '" << menu.logoFile << "'" << endl;
} catch (const MugenException &ex){
throw MugenException( "Error loading logo storyboard: " + ex.getReason(), __FILE__, __LINE__);
}
} catch (const Ast::Exception & e){
}
} else if (simple == "intro.storyboard"){
try{
simple >> menu.introFile;
try{
Global::debug(1) << "Intro file " << baseDir << "/" << menu.introFile << endl;
menu.intro = new MugenStoryboard(Mugen::Util::getCorrectFileLocation(baseDir, menu.logoFile));
menu.intro->load();
Global::debug(1) << "Got Intro Storyboard File: '" << menu.introFile << "'" << endl;
} catch (const MugenException &ex){
throw MugenException( "Error loading intro storyboard: " + ex.getReason(), __FILE__, __LINE__);
}
} catch (const Ast::Exception & e){
}
} else if (simple == "select"){
simple >> menu.selectFile;
Global::debug(1) << "Got Select File: '" << menu.selectFile << "'" << endl;
} else if (simple == "fight"){
simple >> menu.fightFile;
Global::debug(1) << "Got Fight File: '" << menu.fightFile << "'" << endl;
} else if (PaintownUtil::matchRegex(simple.idString(), "^font")){
string temp;
simple >> temp;
menu.fonts.push_back(new MugenFont(Mugen::Util::getCorrectFileLocation(baseDir, temp)));
Global::debug(1) << "Got Font File: '" << temp << "'" << endl;
} else {
throw MugenException("Unhandled option in Files Section: " + simple.toString(), __FILE__, __LINE__ );
}
}
};
FileWalker walker(*this, baseDir);
section->walk(walker);
} else if (head == "music"){
/* FIXME! parse music here */
} else if (head == "title info"){
class TitleInfoWalker: public Ast::Walker{
public:
TitleInfoWalker(MugenMenu & menu):
menu(menu){
}
MugenMenu & menu;
virtual void onAttributeSimple(const Ast::AttributeSimple & simple){
if (simple == "fadein.time"){
int time;
simple >> time;
menu.fader.setFadeInTime(time);
} else if (simple == "fadein.color"){
int r,g,b;
simple >> r >> g >> b;
menu.fader.setFadeInColor(Bitmap::makeColor(r,g,b));
} else if (simple == "fadeout.time"){
int time;
simple >> time;
menu.fader.setFadeOutTime(time);
} else if (simple == "fadeout.color"){
int r,g,b;
simple >> r >> g >> b;
menu.fader.setFadeOutColor(Bitmap::makeColor(r,g,b));
} else if (simple == "menu.pos"){
simple >> menu.position.x;
simple >> menu.position.y;
} else if (simple == "menu.item.font"){
simple >> menu.fontItem.index;
simple >> menu.fontItem.bank;
simple >> menu.fontItem.position;
} else if (simple == "menu.item.active.font"){
simple >> menu.fontActive.index;
simple >> menu.fontActive.bank;
simple >> menu.fontActive.position;
} else if (simple == "menu.item.spacing"){
simple >> menu.fontSpacing.x;
simple >> menu.fontSpacing.y;
} else if (simple == "menu.itemname.arcade"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.versus"){
try{
menu.addOption(new MugenOptionVersus(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.teamarcade"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.teamversus"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.teamcoop"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.survival"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.survivalcoop"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.training"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.watch"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.options"){
try{
menu.addOption(new OptionDummy(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.itemname.exit"){
try{
menu.addOption(new OptionQuit(simple.valueAsString()));
} catch (const Ast::Exception & e){
}
} else if (simple == "menu.window.margins.x"){
simple >> menu.windowMarginX.x;
simple >> menu.windowMarginX.y;
} else if (simple == "menu.window.margins.y"){
simple >> menu.windowMarginY.x;
simple >> menu.windowMarginY.y;
} else if (simple == "menu.window.visibleitems"){
simple >> menu.windowVisibleItems;
} else if (simple == "menu.boxcursor.visible"){
simple >> menu.showBoxCursor;
} else if (simple == "menu.boxcursor.coords"){
simple >> menu.boxCursorCoords.x1;
simple >> menu.boxCursorCoords.y1;
simple >> menu.boxCursorCoords.x2;
simple >> menu.boxCursorCoords.y2;
menu.boxCursorCoords.alpha = 128;
menu.boxCursorCoords.alphaMove = -6;
} else if (simple == "cursor.move.snd"){
/* FIXME! parse cursor.move.snd */
} else if (simple == "cursor.done.snd"){
/* FIXME! parse cursor.done.snd */
} else if (simple == "cancel.snd"){
/* FIXME! parse cancel.snd */
} else {
throw MugenException("Unhandled option in Info Section: " + simple.toString(), __FILE__, __LINE__);
}
}
};
TitleInfoWalker walker(*this);
section->walk(walker);
} else if (PaintownUtil::matchRegex(head, "^titlebgdef")){
vector<Ast::Section*> backgroundStuff = Mugen::Util::collectBackgroundStuff(section_it, parsed.getSections()->end());
MugenBackgroundManager *manager = new MugenBackgroundManager(baseDir, backgroundStuff, ticker, &sprites);
background = manager;
Global::debug(1) << "Got background: '" << manager->getName() << "'" << endl;
} else if (head == "select info"){
// Pass off to selectInfo
characterSelect = new MugenCharacterSelect(ticker, fonts);
characterSelect->load(baseDir + selectFile, collectSelectStuff(section_it, parsed.getSections()->end()), sprites);
} else if (head == "selectbgdef" ){ /* Ignore for now */ }
else if (head.find("selectbg") != std::string::npos ){ /* Ignore for now */ }
else if (head == "vs screen" ){ /* Ignore for now */ }
else if (head == "versusbgdef" ){ /* Ignore for now */ }
else if (head.find("versusbg" ) != std::string::npos ){ /* Ignore for now */ }
else if (head == "demo mode" ){ /* Ignore for now */ }
else if (head == "continue screen" ){ /* Ignore for now */ }
else if (head == "game over screen" ){ /* Ignore for now */ }
else if (head == "win screen" ){ /* Ignore for now */ }
else if (head == "default ending" ){ /* Ignore for now */ }
else if (head == "end credits" ){ /* Ignore for now */ }
else if (head == "survival results screen" ){ /* Ignore for now */ }
else if (head == "option info" ){ /* Ignore for now */ }
else if (head == "optionbgdef" ){ /* Ignore for now */ }
else if (head.find("optionbg") != std::string::npos ){ /* Ignore for now */ }
else if (head == "music" ){ /* Ignore for now */ }
else if (head.find("begin action") != std::string::npos ){ /* Ignore for now */ }
else {
throw MugenException("Unhandled Section in '" + ourDefFile + "': " + head, __FILE__, __LINE__ );
}
}
/* Set up the animations for those that have action numbers assigned (not -1 )
* Also do their preload
*/
if (background){
background->preload(DEFAULT_SCREEN_X_AXIS, DEFAULT_SCREEN_Y_AXIS );
}
}
MugenMenu::~MugenMenu(){
// cleanup
cleanup();
}
void MugenMenu::run() throw (ReturnException) {
Bitmap workArea(DEFAULT_WIDTH,DEFAULT_HEIGHT);
bool done = false;
bool endGame = false;
if ( menuOptions.empty() ){
return;
}
selectedOption = menuOptions.begin();
optionLocation = 0;
menuOptions.front()->setState(MenuOption::Selected);
/*
if ( !music.empty() ){
MenuGlobals::setMusic(music);
}
if ( !selectSound.empty() ){
MenuGlobals::setSelectSound(selectSound);
}
*/
// Set the fade state
fader.setState(FADEIN);
// Do we have logos or intros?
// Logo run it no repeat
if (logo){
logo->run( work,false);
}
// Intro run it no repeat
if (intro){
intro->run( work,false);
}
double runCounter = 0;
while( ! endGame ){
Global::speed_counter = 0;
Global::second_counter = 0;
int game_time = 100;
while ( ! done && (*selectedOption)->getState() != MenuOption::Run && fader.getState() != RUNFADE ){
bool draw = false;
keyInputManager::update();
if ( Global::speed_counter > 0 ){
draw = true;
runCounter += Global::speed_counter * Global::LOGIC_MULTIPLIER;
while ( runCounter >= 1.0 ){
ticker++;
runCounter -= 1;
// Keys
if (fader.getState() == NOFADE){
if ( keyInputManager::keyState(keys::UP, true ) ||
/* for vi people like me */
keyInputManager::keyState('k', true )){
(*selectedOption)->setState(MenuOption::Deselected);
if ( selectedOption > menuOptions.begin() ){
selectedOption--;
optionLocation--;
} else {
selectedOption = menuOptions.end() -1;
optionLocation = menuOptions.size() -1;
}
(*selectedOption)->setState(MenuOption::Selected);
//if(menuOptions.size() > 1)MenuGlobals::playSelectSound();
}
if ( keyInputManager::keyState(keys::DOWN, true ) ||
/* for vi people like me */
keyInputManager::keyState('j', true )){
(*selectedOption)->setState(MenuOption::Deselected);
if ( selectedOption < menuOptions.begin()+menuOptions.size()-1 ){
selectedOption++;
optionLocation++;
} else {
selectedOption = menuOptions.begin();
optionLocation = 0;
}
(*selectedOption)->setState(MenuOption::Selected);
//if(menuOptions.size() > 1)MenuGlobals::playSelectSound();
}
if ( keyInputManager::keyState(keys::LEFT, true) ||
keyInputManager::keyState('h', true)){
if ( (*selectedOption)->leftKey()){
/* ??? */
}
}
if ( keyInputManager::keyState(keys::RIGHT, true )||
keyInputManager::keyState('l', true )){
if ( (*selectedOption)->rightKey()){
/* ??? */
}
}
if ( keyInputManager::keyState(keys::ENTER, true ) ){
if((*selectedOption)->isRunnable())(*selectedOption)->setState( MenuOption::Run );
// Set the fade state
fader.setState(FADEOUT);
}
if ( keyInputManager::keyState(keys::ESC, true ) ){
endGame = done = true;
// Set the fade state
fader.setState(FADEOUT);
(*selectedOption)->setState(MenuOption::Deselected);
throw ReturnException();
}
}
// Fader
fader.act();
// Options
for( vector< MenuOption *>::iterator b = menuOptions.begin(); b != menuOptions.end(); ++b ){
(*b)->logic();
}
// Backgrounds
background->logic( 0, 0, 0, 0 );
}
Global::speed_counter = 0;
}
while ( Global::second_counter > 0 ){
game_time--;
Global::second_counter--;
if ( game_time < 0 ){
game_time = 0;
}
}
if ( draw ){
// backgrounds
background->renderBack(0,0,DEFAULT_WIDTH,DEFAULT_HEIGHT,&workArea);
// Draw any misc stuff in the background of the menu of selected object
(*selectedOption)->drawBelow(work);
// Draw text
renderText(&workArea);
// Foregrounds
background->renderFront(0,0,DEFAULT_WIDTH,DEFAULT_HEIGHT,&workArea);
// Draw any misc stuff in the foreground of the menu of selected object
(*selectedOption)->drawAbove(work);
// Do fades
fader.draw(&workArea);
// Finally render to screen
workArea.Stretch(*work);
work->BlitToScreen();
}
while ( Global::speed_counter < 1 ){
Util::rest( 1 );
keyInputManager::update();
}
}
// do we got an option to run, lets do it
if ((*selectedOption)->getState() == MenuOption::Run){
try{
/*if (backSound != ""){
Sound * ok = Resource::getSound(okSound);
ok->play();
}*/
(*selectedOption)->run(endGame);
if (!endGame){
//characterSelect->run((*selectedOption)->getText(), 1, true, work);
}
} catch ( const ReturnException & re ){
}
// Reset it's state
(*selectedOption)->setState(MenuOption::Selected);
/*if ( !music.empty() ){
MenuGlobals::setMusic(music);
}
if ( !selectSound.empty() ){
MenuGlobals::setSelectSound(selectSound);
}*/
// reset the fade state
fader.setState(FADEIN);
}
/*
if (!music.empty()){
if(MenuGlobals::currentMusic() != music){
MenuGlobals::popMusic();
}
}
if (!selectSound.empty()){
if(MenuGlobals::currentSelectSound() != selectSound){
MenuGlobals::popSelectSound();
}
}
*/
if (endGame){
// Deselect selected entry
(*selectedOption)->setState(MenuOption::Deselected);
/*if (backSound != ""){
Sound * back = Resource::getSound(backSound);
back->play();
}*/
}
}
}
void MugenMenu::cleanup(){
//Backgrounds
if (background) delete background;
// Character select
if (characterSelect) delete characterSelect;
// Get rid of sprites
cleanupSprites();
}
void MugenMenu::cleanupSprites(){
// Get rid of sprites
for( std::map< unsigned int, std::map< unsigned int, MugenSprite * > >::iterator i = sprites.begin() ; i != sprites.end() ; ++i ){
for( std::map< unsigned int, MugenSprite * >::iterator j = i->second.begin() ; j != i->second.end() ; ++j ){
if( j->second )delete j->second;
}
}
}
// Draw text
void MugenMenu::renderText(Bitmap *bmp){
int xplacement = position.x;
int yplacement = position.y;
int visibleCounter = 0;
int offset = optionLocation >= windowVisibleItems ? optionLocation - windowVisibleItems + 1 : 0;
for( std::vector <MenuOption *>::iterator i = menuOptions.begin() + offset; i != menuOptions.end(); ++i){
MenuOption *option = *i;
if (option->getState() == MenuOption::Selected){
MugenFont *font = fonts[fontActive.index-1];
if(showBoxCursor){
boxCursorCoords.alpha += boxCursorCoords.alphaMove;
if (boxCursorCoords.alpha <= 0){
boxCursorCoords.alpha = 0;
boxCursorCoords.alphaMove = 6;
}
else if (boxCursorCoords.alpha >= 128){
boxCursorCoords.alpha = 128;
boxCursorCoords.alphaMove = -6;
}
Bitmap::drawingMode(Bitmap::MODE_TRANS);
Bitmap::transBlender(0,0,0,boxCursorCoords.alpha);
bmp->rectangleFill(xplacement + boxCursorCoords.x1, yplacement + boxCursorCoords.y1, xplacement + boxCursorCoords.x2,yplacement + boxCursorCoords.y2,Bitmap::makeColor(255,255,255));
Bitmap::drawingMode(Bitmap::MODE_SOLID);
}
font->render(xplacement, yplacement, fontActive.position, fontActive.bank, *bmp, option->getText());
xplacement += fontSpacing.x;
yplacement += fontSpacing.y;
} else {
MugenFont *font = fonts[fontItem.index-1];
font->render(xplacement, yplacement, fontItem.position, fontItem.bank, *bmp, option->getText());
xplacement += fontSpacing.x;
yplacement += fontSpacing.y;
}
// Visible counter
visibleCounter++;
if (visibleCounter >= windowVisibleItems)break;
}
}
|
/*------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2016 The Khronos Group Inc.
* Copyright (c) 2016 Samsung Electronics 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.
*
*//*!
* \file
* \brief Instanced Draw Tests
*//*--------------------------------------------------------------------*/
#include "vktDrawInstancedTests.hpp"
#include "deSharedPtr.hpp"
#include "rrRenderer.hpp"
#include "tcuImageCompare.hpp"
#include "tcuRGBA.hpp"
#include "tcuTextureUtil.hpp"
#include "vkImageUtil.hpp"
#include "vkPrograms.hpp"
#include "vktDrawBufferObjectUtil.hpp"
#include "vktDrawCreateInfoUtil.hpp"
#include "vktDrawImageObjectUtil.hpp"
#include "vktDrawTestCaseUtil.hpp"
namespace vkt
{
namespace Draw
{
namespace
{
static const int QUAD_GRID_SIZE = 8;
static const int WIDTH = 128;
static const int HEIGHT = 128;
struct TestParams
{
enum DrawFunction
{
FUNCTION_DRAW = 0,
FUNCTION_DRAW_INDEXED,
FUNCTION_DRAW_INDIRECT,
FUNCTION_DRAW_INDEXED_INDIRECT,
FUNTION_LAST
};
DrawFunction function;
vk::VkPrimitiveTopology topology;
};
struct VertexPositionAndColor
{
VertexPositionAndColor (tcu::Vec4 position_, tcu::Vec4 color_)
: position (position_)
, color (color_)
{
}
tcu::Vec4 position;
tcu::Vec4 color;
};
std::ostream & operator<<(std::ostream & str, TestParams const & v)
{
std::ostringstream string;
switch (v.function)
{
case TestParams::FUNCTION_DRAW:
string << "draw";
break;
case TestParams::FUNCTION_DRAW_INDEXED:
string << "draw_indexed";
break;
case TestParams::FUNCTION_DRAW_INDIRECT:
string << "draw_indirect";
break;
case TestParams::FUNCTION_DRAW_INDEXED_INDIRECT:
string << "draw_indexed_indirect";
break;
default:
DE_ASSERT(false);
}
string << "_" << de::toString(v.topology);
return str << string.str();
}
rr::PrimitiveType mapVkPrimitiveTopology (vk::VkPrimitiveTopology primitiveTopology)
{
switch (primitiveTopology)
{
case vk::VK_PRIMITIVE_TOPOLOGY_POINT_LIST: return rr::PRIMITIVETYPE_POINTS;
case vk::VK_PRIMITIVE_TOPOLOGY_LINE_LIST: return rr::PRIMITIVETYPE_LINES;
case vk::VK_PRIMITIVE_TOPOLOGY_LINE_STRIP: return rr::PRIMITIVETYPE_LINE_STRIP;
case vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST: return rr::PRIMITIVETYPE_TRIANGLES;
case vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN: return rr::PRIMITIVETYPE_TRIANGLE_FAN;
case vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP: return rr::PRIMITIVETYPE_TRIANGLE_STRIP;
case vk::VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY: return rr::PRIMITIVETYPE_LINES_ADJACENCY;
case vk::VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY: return rr::PRIMITIVETYPE_LINE_STRIP_ADJACENCY;
case vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY: return rr::PRIMITIVETYPE_TRIANGLES_ADJACENCY;
case vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY: return rr::PRIMITIVETYPE_TRIANGLE_STRIP_ADJACENCY;
default:
DE_ASSERT(false);
}
return rr::PRIMITIVETYPE_LAST;
}
template<typename T>
de::SharedPtr<Buffer> createAndUploadBuffer(const std::vector<T> data, const vk::DeviceInterface& vk, const Context& context)
{
const vk::VkDeviceSize dataSize = data.size() * sizeof(T);
de::SharedPtr<Buffer> vertexBuffer = Buffer::createAndAlloc(vk, context.getDevice(),
BufferCreateInfo(dataSize, vk::VK_BUFFER_USAGE_VERTEX_BUFFER_BIT),
context.getDefaultAllocator(),
vk::MemoryRequirement::HostVisible);
deUint8* ptr = reinterpret_cast<deUint8*>(vertexBuffer->getBoundMemory().getHostPtr());
deMemcpy(ptr, &data[0], static_cast<size_t>(dataSize));
vk::flushMappedMemoryRange(vk, context.getDevice(),
vertexBuffer->getBoundMemory().getMemory(),
vertexBuffer->getBoundMemory().getOffset(),
VK_WHOLE_SIZE);
return vertexBuffer;
}
class TestVertShader : public rr::VertexShader
{
public:
TestVertShader (int numInstances, int firstInstance)
: rr::VertexShader (3, 1)
, m_numInstances (numInstances)
, m_firstInstance (firstInstance)
{
m_inputs[0].type = rr::GENERICVECTYPE_FLOAT;
m_inputs[1].type = rr::GENERICVECTYPE_FLOAT;
m_inputs[2].type = rr::GENERICVECTYPE_FLOAT;
m_outputs[0].type = rr::GENERICVECTYPE_FLOAT;
}
void shadeVertices (const rr::VertexAttrib* inputs,
rr::VertexPacket* const* packets,
const int numPackets) const
{
for (int packetNdx = 0; packetNdx < numPackets; ++packetNdx)
{
const int instanceNdx = packets[packetNdx]->instanceNdx + m_firstInstance;
const tcu::Vec4 position = rr::readVertexAttribFloat(inputs[0], instanceNdx, packets[packetNdx]->vertexNdx);
const tcu::Vec4 color = rr::readVertexAttribFloat(inputs[1], instanceNdx, packets[packetNdx]->vertexNdx);
const tcu::Vec4 color2 = rr::readVertexAttribFloat(inputs[2], instanceNdx, packets[packetNdx]->vertexNdx);
packets[packetNdx]->position = position + tcu::Vec4((float)(packets[packetNdx]->instanceNdx * 2.0 / m_numInstances), 0.0, 0.0, 0.0);
packets[packetNdx]->outputs[0] = color + tcu::Vec4((float)instanceNdx / (float)m_numInstances, 0.0, 0.0, 1.0) + color2;
}
}
private:
const int m_numInstances;
const int m_firstInstance;
};
class TestFragShader : public rr::FragmentShader
{
public:
TestFragShader (void)
: rr::FragmentShader(1, 1)
{
m_inputs[0].type = rr::GENERICVECTYPE_FLOAT;
m_outputs[0].type = rr::GENERICVECTYPE_FLOAT;
}
void shadeFragments (rr::FragmentPacket* packets,
const int numPackets,
const rr::FragmentShadingContext& context) const
{
for (int packetNdx = 0; packetNdx < numPackets; ++packetNdx)
{
rr::FragmentPacket& packet = packets[packetNdx];
for (int fragNdx = 0; fragNdx < rr::NUM_FRAGMENTS_PER_PACKET; ++fragNdx)
{
const tcu::Vec4 color = rr::readVarying<float>(packet, context, 0, fragNdx);
rr::writeFragmentOutput(context, packetNdx, fragNdx, 0, color);
}
}
}
};
class InstancedDrawInstance : public TestInstance
{
public:
InstancedDrawInstance (Context& context, TestParams params);
virtual tcu::TestStatus iterate (void);
private:
void prepareVertexData (int instanceCount, int firstInstance);
const TestParams m_params;
const vk::DeviceInterface& m_vk;
vk::VkFormat m_colorAttachmentFormat;
vk::Move<vk::VkPipeline> m_pipeline;
vk::Move<vk::VkPipelineLayout> m_pipelineLayout;
de::SharedPtr<Image> m_colorTargetImage;
vk::Move<vk::VkImageView> m_colorTargetView;
PipelineCreateInfo::VertexInputState m_vertexInputState;
vk::Move<vk::VkCommandPool> m_cmdPool;
vk::Move<vk::VkCommandBuffer> m_cmdBuffer;
vk::Move<vk::VkFramebuffer> m_framebuffer;
vk::Move<vk::VkRenderPass> m_renderPass;
// Vertex data
std::vector<VertexPositionAndColor> m_data;
std::vector<deUint32> m_indexes;
std::vector<tcu::Vec4> m_instancedColor;
};
class InstancedDrawCase : public TestCase
{
public:
InstancedDrawCase (tcu::TestContext& testCtx,
const std::string& name,
const std::string& desc,
TestParams params)
: TestCase (testCtx, name, desc)
, m_params (params)
{
m_vertexShader = "#version 430\n"
"layout(location = 0) in vec4 in_position;\n"
"layout(location = 1) in vec4 in_color;\n"
"layout(location = 2) in vec4 in_color_2;\n"
"layout(push_constant) uniform TestParams {\n"
" float firstInstance;\n"
" float instanceCount;\n"
"} params;\n"
"layout(location = 0) out vec4 out_color;\n"
"out gl_PerVertex {\n"
" vec4 gl_Position;\n"
" float gl_PointSize;\n"
"};\n"
"void main() {\n"
" gl_PointSize = 1.0;\n"
" gl_Position = in_position + vec4(float(gl_InstanceIndex - params.firstInstance) * 2.0 / params.instanceCount, 0.0, 0.0, 0.0);\n"
" out_color = in_color + vec4(float(gl_InstanceIndex) / params.instanceCount, 0.0, 0.0, 1.0) + in_color_2;\n"
"}\n";
m_fragmentShader = "#version 430\n"
"layout(location = 0) in vec4 in_color;\n"
"layout(location = 0) out vec4 out_color;\n"
"void main()\n"
"{\n"
" out_color = in_color;\n"
"}\n";
}
TestInstance* createInstance (Context& context) const
{
return new InstancedDrawInstance(context, m_params);
}
virtual void initPrograms (vk::SourceCollections& programCollection) const
{
programCollection.glslSources.add("InstancedDrawVert") << glu::VertexSource(m_vertexShader);
programCollection.glslSources.add("InstancedDrawFrag") << glu::FragmentSource(m_fragmentShader);
}
private:
const TestParams m_params;
std::string m_vertexShader;
std::string m_fragmentShader;
};
InstancedDrawInstance::InstancedDrawInstance(Context &context, TestParams params)
: TestInstance (context)
, m_params (params)
, m_vk (context.getDeviceInterface())
, m_colorAttachmentFormat (vk::VK_FORMAT_R8G8B8A8_UNORM)
{
const vk::VkDevice device = m_context.getDevice();
const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex();
const vk::VkPushConstantRange pushConstantRange = {
vk::VK_SHADER_STAGE_VERTEX_BIT, // VkShaderStageFlags stageFlags;
0u, // uint32_t offset;
(deUint32)sizeof(float) * 2, // uint32_t size;
};
const PipelineLayoutCreateInfo pipelineLayoutCreateInfo(0, DE_NULL, 1, &pushConstantRange);
m_pipelineLayout = vk::createPipelineLayout(m_vk, device, &pipelineLayoutCreateInfo);
const vk::VkExtent3D targetImageExtent = { WIDTH, HEIGHT, 1 };
const ImageCreateInfo targetImageCreateInfo(vk::VK_IMAGE_TYPE_2D, m_colorAttachmentFormat, targetImageExtent, 1, 1, vk::VK_SAMPLE_COUNT_1_BIT,
vk::VK_IMAGE_TILING_OPTIMAL, vk::VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | vk::VK_IMAGE_USAGE_TRANSFER_SRC_BIT | vk::VK_IMAGE_USAGE_TRANSFER_DST_BIT);
m_colorTargetImage = Image::createAndAlloc(m_vk, device, targetImageCreateInfo, m_context.getDefaultAllocator());
const ImageViewCreateInfo colorTargetViewInfo(m_colorTargetImage->object(), vk::VK_IMAGE_VIEW_TYPE_2D, m_colorAttachmentFormat);
m_colorTargetView = vk::createImageView(m_vk, device, &colorTargetViewInfo);
RenderPassCreateInfo renderPassCreateInfo;
renderPassCreateInfo.addAttachment(AttachmentDescription(m_colorAttachmentFormat,
vk::VK_SAMPLE_COUNT_1_BIT,
vk::VK_ATTACHMENT_LOAD_OP_LOAD,
vk::VK_ATTACHMENT_STORE_OP_STORE,
vk::VK_ATTACHMENT_LOAD_OP_DONT_CARE,
vk::VK_ATTACHMENT_STORE_OP_STORE,
vk::VK_IMAGE_LAYOUT_GENERAL,
vk::VK_IMAGE_LAYOUT_GENERAL));
const vk::VkAttachmentReference colorAttachmentReference =
{
0,
vk::VK_IMAGE_LAYOUT_GENERAL
};
renderPassCreateInfo.addSubpass(SubpassDescription(vk::VK_PIPELINE_BIND_POINT_GRAPHICS,
0,
0,
DE_NULL,
1,
&colorAttachmentReference,
DE_NULL,
AttachmentReference(),
0,
DE_NULL));
m_renderPass = vk::createRenderPass(m_vk, device, &renderPassCreateInfo);
std::vector<vk::VkImageView> colorAttachments(1);
colorAttachments[0] = *m_colorTargetView;
const FramebufferCreateInfo framebufferCreateInfo(*m_renderPass, colorAttachments, WIDTH, HEIGHT, 1);
m_framebuffer = vk::createFramebuffer(m_vk, device, &framebufferCreateInfo);
const vk::VkVertexInputBindingDescription vertexInputBindingDescription[2] =
{
{
0u,
(deUint32)sizeof(VertexPositionAndColor),
vk::VK_VERTEX_INPUT_RATE_VERTEX,
},
{
1u,
(deUint32)sizeof(tcu::Vec4),
vk::VK_VERTEX_INPUT_RATE_INSTANCE,
},
};
const vk::VkVertexInputAttributeDescription vertexInputAttributeDescriptions[] =
{
{
0u,
0u,
vk::VK_FORMAT_R32G32B32A32_SFLOAT,
0u
},
{
1u,
0u,
vk::VK_FORMAT_R32G32B32A32_SFLOAT,
(deUint32)sizeof(tcu::Vec4),
},
{
2u,
1u,
vk::VK_FORMAT_R32G32B32A32_SFLOAT,
0,
}
};
m_vertexInputState = PipelineCreateInfo::VertexInputState(2,
vertexInputBindingDescription,
DE_LENGTH_OF_ARRAY(vertexInputAttributeDescriptions),
vertexInputAttributeDescriptions);
const CmdPoolCreateInfo cmdPoolCreateInfo(queueFamilyIndex);
m_cmdPool = vk::createCommandPool(m_vk, device, &cmdPoolCreateInfo);
const vk::VkCommandBufferAllocateInfo cmdBufferAllocateInfo =
{
vk::VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
*m_cmdPool, // VkCommandPool commandPool;
vk::VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level;
1u, // deUint32 bufferCount;
};
m_cmdBuffer = vk::allocateCommandBuffer(m_vk, device, &cmdBufferAllocateInfo);
const vk::Unique<vk::VkShaderModule> vs(createShaderModule(m_vk, device, m_context.getBinaryCollection().get("InstancedDrawVert"), 0));
const vk::Unique<vk::VkShaderModule> fs(createShaderModule(m_vk, device, m_context.getBinaryCollection().get("InstancedDrawFrag"), 0));
const PipelineCreateInfo::ColorBlendState::Attachment vkCbAttachmentState;
vk::VkViewport viewport;
viewport.x = 0;
viewport.y = 0;
viewport.width = static_cast<float>(WIDTH);
viewport.height = static_cast<float>(HEIGHT);
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
vk::VkRect2D scissor;
scissor.offset.x = 0;
scissor.offset.y = 0;
scissor.extent.width = WIDTH;
scissor.extent.height = HEIGHT;
PipelineCreateInfo pipelineCreateInfo(*m_pipelineLayout, *m_renderPass, 0, 0);
pipelineCreateInfo.addShader(PipelineCreateInfo::PipelineShaderStage(*vs, "main", vk::VK_SHADER_STAGE_VERTEX_BIT));
pipelineCreateInfo.addShader(PipelineCreateInfo::PipelineShaderStage(*fs, "main", vk::VK_SHADER_STAGE_FRAGMENT_BIT));
pipelineCreateInfo.addState(PipelineCreateInfo::VertexInputState(m_vertexInputState));
pipelineCreateInfo.addState(PipelineCreateInfo::InputAssemblerState(m_params.topology));
pipelineCreateInfo.addState(PipelineCreateInfo::ColorBlendState(1, &vkCbAttachmentState));
pipelineCreateInfo.addState(PipelineCreateInfo::ViewportState(1, std::vector<vk::VkViewport>(1, viewport), std::vector<vk::VkRect2D>(1, scissor)));
pipelineCreateInfo.addState(PipelineCreateInfo::DepthStencilState());
pipelineCreateInfo.addState(PipelineCreateInfo::RasterizerState());
pipelineCreateInfo.addState(PipelineCreateInfo::MultiSampleState());
m_pipeline = vk::createGraphicsPipeline(m_vk, device, DE_NULL, &pipelineCreateInfo);
}
tcu::TestStatus InstancedDrawInstance::iterate()
{
const vk::VkQueue queue = m_context.getUniversalQueue();
static const deUint32 instanceCounts[] = { 1, 2, 4, 20 };
static const deUint32 firstInstanceIndices[] = { 0, 1, 3, 4, 20 };
qpTestResult res = QP_TEST_RESULT_PASS;
const vk::VkClearColorValue clearColor = { { 0.0f, 0.0f, 0.0f, 1.0f } };
const CmdBufferBeginInfo beginInfo;
for (int instanceCountNdx = 0; instanceCountNdx < DE_LENGTH_OF_ARRAY(instanceCounts); instanceCountNdx++)
{
const deUint32 instanceCount = instanceCounts[instanceCountNdx];
for (int firstInstanceIndexNdx = 0; firstInstanceIndexNdx < DE_LENGTH_OF_ARRAY(firstInstanceIndices); firstInstanceIndexNdx++)
{
const deUint32 firstInstance = firstInstanceIndices[firstInstanceIndexNdx];
prepareVertexData(instanceCount, firstInstance);
const de::SharedPtr<Buffer> vertexBuffer = createAndUploadBuffer(m_data, m_vk, m_context);
const de::SharedPtr<Buffer> instancedVertexBuffer = createAndUploadBuffer(m_instancedColor, m_vk, m_context);
de::SharedPtr<Buffer> indexBuffer;
de::SharedPtr<Buffer> indirectBuffer;
m_vk.beginCommandBuffer(*m_cmdBuffer, &beginInfo);
initialTransitionColor2DImage(m_vk, *m_cmdBuffer, m_colorTargetImage->object(), vk::VK_IMAGE_LAYOUT_GENERAL);
const ImageSubresourceRange subresourceRange(vk::VK_IMAGE_ASPECT_COLOR_BIT);
m_vk.cmdClearColorImage(*m_cmdBuffer, m_colorTargetImage->object(),
vk::VK_IMAGE_LAYOUT_GENERAL, &clearColor, 1, &subresourceRange);
const vk::VkMemoryBarrier memBarrier =
{
vk::VK_STRUCTURE_TYPE_MEMORY_BARRIER,
DE_NULL,
vk::VK_ACCESS_TRANSFER_WRITE_BIT,
vk::VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | vk::VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT
};
m_vk.cmdPipelineBarrier(*m_cmdBuffer, vk::VK_PIPELINE_STAGE_TRANSFER_BIT,
vk::VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
0, 1, &memBarrier, 0, DE_NULL, 0, DE_NULL);
const vk::VkRect2D renderArea = { { 0, 0 }, { WIDTH, HEIGHT } };
const RenderPassBeginInfo renderPassBegin(*m_renderPass, *m_framebuffer, renderArea);
m_vk.cmdBeginRenderPass(*m_cmdBuffer, &renderPassBegin, vk::VK_SUBPASS_CONTENTS_INLINE);
if (m_params.function == TestParams::FUNCTION_DRAW_INDEXED || m_params.function == TestParams::FUNCTION_DRAW_INDEXED_INDIRECT)
{
indexBuffer = createAndUploadBuffer(m_indexes, m_vk, m_context);
m_vk.cmdBindIndexBuffer(*m_cmdBuffer, indexBuffer->object(), 0, vk::VK_INDEX_TYPE_UINT32);
}
const vk::VkBuffer vertexBuffers[] =
{
vertexBuffer->object(),
instancedVertexBuffer->object(),
};
const vk::VkDeviceSize vertexBufferOffsets[] =
{
0, // vertexBufferOffset
0, // instancedVertexBufferOffset
};
m_vk.cmdBindVertexBuffers(*m_cmdBuffer, 0, DE_LENGTH_OF_ARRAY(vertexBuffers), vertexBuffers, vertexBufferOffsets);
const float pushConstants[] = { (float)firstInstance, (float)instanceCount };
m_vk.cmdPushConstants(*m_cmdBuffer, *m_pipelineLayout, vk::VK_SHADER_STAGE_VERTEX_BIT, 0u, (deUint32)sizeof(pushConstants), pushConstants);
m_vk.cmdBindPipeline(*m_cmdBuffer, vk::VK_PIPELINE_BIND_POINT_GRAPHICS, *m_pipeline);
switch (m_params.function)
{
case TestParams::FUNCTION_DRAW:
m_vk.cmdDraw(*m_cmdBuffer, (deUint32)m_data.size(), instanceCount, 0u, firstInstance);
break;
case TestParams::FUNCTION_DRAW_INDEXED:
m_vk.cmdDrawIndexed(*m_cmdBuffer, (deUint32)m_indexes.size(), instanceCount, 0u, 0u, firstInstance);
break;
case TestParams::FUNCTION_DRAW_INDIRECT:
{
vk::VkDrawIndirectCommand drawCommand =
{
(deUint32)m_data.size(), // uint32_t vertexCount;
instanceCount, // uint32_t instanceCount;
0u, // uint32_t firstVertex;
firstInstance, // uint32_t firstInstance;
};
std::vector<vk::VkDrawIndirectCommand> drawCommands;
drawCommands.push_back(drawCommand);
indirectBuffer = createAndUploadBuffer(drawCommands, m_vk, m_context);
m_vk.cmdDrawIndirect(*m_cmdBuffer, indirectBuffer->object(), 0, 1u, 0u);
break;
}
case TestParams::FUNCTION_DRAW_INDEXED_INDIRECT:
{
vk::VkDrawIndexedIndirectCommand drawCommand =
{
(deUint32)m_indexes.size(), // uint32_t indexCount;
instanceCount, // uint32_t instanceCount;
0u, // uint32_t firstIndex;
0, // int32_t vertexOffset;
firstInstance, // uint32_t firstInstance;
};
std::vector<vk::VkDrawIndexedIndirectCommand> drawCommands;
drawCommands.push_back(drawCommand);
indirectBuffer = createAndUploadBuffer(drawCommands, m_vk, m_context);
m_vk.cmdDrawIndexedIndirect(*m_cmdBuffer, indirectBuffer->object(), 0, 1u, 0u);
break;
}
default:
DE_ASSERT(false);
}
m_vk.cmdEndRenderPass(*m_cmdBuffer);
m_vk.endCommandBuffer(*m_cmdBuffer);
vk::VkSubmitInfo submitInfo =
{
vk::VK_STRUCTURE_TYPE_SUBMIT_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0, // deUint32 waitSemaphoreCount;
DE_NULL, // const VkSemaphore* pWaitSemaphores;
(const vk::VkPipelineStageFlags*)DE_NULL, // const VkPipelineStageFlags* pWaitDstStageMask;
1, // deUint32 commandBufferCount;
&m_cmdBuffer.get(), // const VkCommandBuffer* pCommandBuffers;
0, // deUint32 signalSemaphoreCount;
DE_NULL // const VkSemaphore* pSignalSemaphores;
};
VK_CHECK(m_vk.queueSubmit(queue, 1, &submitInfo, DE_NULL));
VK_CHECK(m_vk.queueWaitIdle(queue));
// Reference rendering
std::vector<tcu::Vec4> vetrices;
std::vector<tcu::Vec4> colors;
for (std::vector<VertexPositionAndColor>::const_iterator it = m_data.begin(); it != m_data.end(); ++it)
{
vetrices.push_back(it->position);
colors.push_back(it->color);
}
tcu::TextureLevel refImage (vk::mapVkFormat(m_colorAttachmentFormat), (int)(0.5 + WIDTH), (int)(0.5 + HEIGHT));
tcu::clear(refImage.getAccess(), tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
const TestVertShader vertShader(instanceCount, firstInstance);
const TestFragShader fragShader;
const rr::Program program (&vertShader, &fragShader);
const rr::MultisamplePixelBufferAccess colorBuffer = rr::MultisamplePixelBufferAccess::fromSinglesampleAccess(refImage.getAccess());
const rr::RenderTarget renderTarget (colorBuffer);
const rr::RenderState renderState ((rr::ViewportState(colorBuffer)));
const rr::Renderer renderer;
const rr::VertexAttrib vertexAttribs[] =
{
rr::VertexAttrib(rr::VERTEXATTRIBTYPE_FLOAT, 4, sizeof(tcu::Vec4), 0, &vetrices[0]),
rr::VertexAttrib(rr::VERTEXATTRIBTYPE_FLOAT, 4, sizeof(tcu::Vec4), 0, &colors[0]),
rr::VertexAttrib(rr::VERTEXATTRIBTYPE_FLOAT, 4, sizeof(tcu::Vec4), 1, &m_instancedColor[0])
};
if (m_params.function == TestParams::FUNCTION_DRAW || m_params.function == TestParams::FUNCTION_DRAW_INDIRECT)
{
const rr::PrimitiveList primitives = rr::PrimitiveList(mapVkPrimitiveTopology(m_params.topology), (int)vetrices.size(), 0);
const rr::DrawCommand command(renderState, renderTarget, program, DE_LENGTH_OF_ARRAY(vertexAttribs), &vertexAttribs[0],
primitives);
renderer.drawInstanced(command, instanceCount);
}
else
{
const rr::DrawIndices indicies(m_indexes.data());
const rr::PrimitiveList primitives = rr::PrimitiveList(mapVkPrimitiveTopology(m_params.topology), (int)m_indexes.size(), indicies);
const rr::DrawCommand command(renderState, renderTarget, program, DE_LENGTH_OF_ARRAY(vertexAttribs), &vertexAttribs[0],
primitives);
renderer.drawInstanced(command, instanceCount);
}
const vk::VkOffset3D zeroOffset = { 0, 0, 0 };
const tcu::ConstPixelBufferAccess renderedFrame = m_colorTargetImage->readSurface(queue, m_context.getDefaultAllocator(),
vk::VK_IMAGE_LAYOUT_GENERAL, zeroOffset, WIDTH, HEIGHT, vk::VK_IMAGE_ASPECT_COLOR_BIT);
tcu::TestLog &log = m_context.getTestContext().getLog();
std::ostringstream resultDesc;
resultDesc << "Image comparison result. Instance count: " << instanceCount << " first instance index: " << firstInstance;
if (m_params.topology == vk::VK_PRIMITIVE_TOPOLOGY_POINT_LIST)
{
const bool ok = tcu::intThresholdPositionDeviationCompare(
log, "Result", resultDesc.str().c_str(), refImage.getAccess(), renderedFrame,
tcu::UVec4(4u), // color threshold
tcu::IVec3(1, 1, 0), // position deviation tolerance
true, // don't check the pixels at the boundary
tcu::COMPARE_LOG_RESULT);
if (!ok)
res = QP_TEST_RESULT_FAIL;
}
else
{
if (!tcu::fuzzyCompare(log, "Result", resultDesc.str().c_str(), refImage.getAccess(), renderedFrame, 0.05f, tcu::COMPARE_LOG_RESULT))
res = QP_TEST_RESULT_FAIL;
}
}
}
return tcu::TestStatus(res, qpGetTestResultName(res));
}
void InstancedDrawInstance::prepareVertexData(int instanceCount, int firstInstance)
{
m_data.clear();
m_indexes.clear();
m_instancedColor.clear();
if (m_params.function == TestParams::FUNCTION_DRAW || m_params.function == TestParams::FUNCTION_DRAW_INDIRECT)
{
for (int y = 0; y < QUAD_GRID_SIZE; y++)
{
for (int x = 0; x < QUAD_GRID_SIZE; x++)
{
const float fx0 = -1.0f + (float)(x+0) / (float)QUAD_GRID_SIZE * 2.0f / (float)instanceCount;
const float fx1 = -1.0f + (float)(x+1) / (float)QUAD_GRID_SIZE * 2.0f / (float)instanceCount;
const float fy0 = -1.0f + (float)(y+0) / (float)QUAD_GRID_SIZE * 2.0f;
const float fy1 = -1.0f + (float)(y+1) / (float)QUAD_GRID_SIZE * 2.0f;
// Vertices of a quad's lower-left triangle: (fx0, fy0), (fx1, fy0) and (fx0, fy1)
m_data.push_back(VertexPositionAndColor(tcu::Vec4(fx0, fy0, 1.0f, 1.0f), tcu::RGBA::blue().toVec()));
m_data.push_back(VertexPositionAndColor(tcu::Vec4(fx1, fy0, 1.0f, 1.0f), tcu::RGBA::blue().toVec()));
m_data.push_back(VertexPositionAndColor(tcu::Vec4(fx0, fy1, 1.0f, 1.0f), tcu::RGBA::green().toVec()));
// Vertices of a quad's upper-right triangle: (fx1, fy1), (fx0, fy1) and (fx1, fy0)
m_data.push_back(VertexPositionAndColor(tcu::Vec4(fx1, fy1, 1.0f, 1.0f), tcu::RGBA::green().toVec()));
m_data.push_back(VertexPositionAndColor(tcu::Vec4(fx0, fy1, 1.0f, 1.0f), tcu::RGBA::green().toVec()));
m_data.push_back(VertexPositionAndColor(tcu::Vec4(fx1, fy0, 1.0f, 1.0f), tcu::RGBA::blue().toVec()));
}
}
}
else
{
for (int y = 0; y < QUAD_GRID_SIZE + 1; y++)
{
for (int x = 0; x < QUAD_GRID_SIZE + 1; x++)
{
const float fx = -1.0f + (float)x / (float)QUAD_GRID_SIZE * 2.0f / (float)instanceCount;
const float fy = -1.0f + (float)y / (float)QUAD_GRID_SIZE * 2.0f;
m_data.push_back(VertexPositionAndColor(tcu::Vec4(fx, fy, 1.0f, 1.0f),
(y % 2 ? tcu::RGBA::blue().toVec() : tcu::RGBA::green().toVec())));
}
}
for (int y = 0; y < QUAD_GRID_SIZE; y++)
{
for (int x = 0; x < QUAD_GRID_SIZE; x++)
{
const int ndx00 = y*(QUAD_GRID_SIZE + 1) + x;
const int ndx10 = y*(QUAD_GRID_SIZE + 1) + x + 1;
const int ndx01 = (y + 1)*(QUAD_GRID_SIZE + 1) + x;
const int ndx11 = (y + 1)*(QUAD_GRID_SIZE + 1) + x + 1;
// Lower-left triangle of a quad.
m_indexes.push_back((deUint16)ndx00);
m_indexes.push_back((deUint16)ndx10);
m_indexes.push_back((deUint16)ndx01);
// Upper-right triangle of a quad.
m_indexes.push_back((deUint16)ndx11);
m_indexes.push_back((deUint16)ndx01);
m_indexes.push_back((deUint16)ndx10);
}
}
}
for (int i = 0; i < instanceCount + firstInstance; i++)
{
m_instancedColor.push_back(tcu::Vec4(0.0, (float)(1.0 - i * 1.0 / (instanceCount + firstInstance)) / 2, 0.0, 1.0));
}
}
} // anonymus
InstancedTests::InstancedTests(tcu::TestContext& testCtx)
: TestCaseGroup (testCtx, "instanced", "Instanced drawing tests")
{
static const vk::VkPrimitiveTopology topologies[] =
{
vk::VK_PRIMITIVE_TOPOLOGY_POINT_LIST,
vk::VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
vk::VK_PRIMITIVE_TOPOLOGY_LINE_STRIP,
vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN,
};
static const TestParams::DrawFunction functions[] =
{
TestParams::FUNCTION_DRAW,
TestParams::FUNCTION_DRAW_INDEXED,
TestParams::FUNCTION_DRAW_INDIRECT,
TestParams::FUNCTION_DRAW_INDEXED_INDIRECT,
};
for (int topologyNdx = 0; topologyNdx < DE_LENGTH_OF_ARRAY(topologies); topologyNdx++)
{
for (int functionNdx = 0; functionNdx < DE_LENGTH_OF_ARRAY(functions); functionNdx++)
{
TestParams param;
param.function = functions[functionNdx];
param.topology = topologies[topologyNdx];
std::string testName = de::toString(param);
addChild(new InstancedDrawCase(m_testCtx, de::toLower(testName), "Instanced drawing test", param));
}
}
}
InstancedTests::~InstancedTests() {}
} // DrawTests
} // vkt
Check 'drawIndirectFirstInstance' feature to run indirect draw tests
Component: Vulkan
VK-GL-CTS issue: 413
Change-Id: I13a86721ec76ac50af55e0730fd50e3d7ce159d8
/*------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2016 The Khronos Group Inc.
* Copyright (c) 2016 Samsung Electronics 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.
*
*//*!
* \file
* \brief Instanced Draw Tests
*//*--------------------------------------------------------------------*/
#include "vktDrawInstancedTests.hpp"
#include "deSharedPtr.hpp"
#include "rrRenderer.hpp"
#include "tcuImageCompare.hpp"
#include "tcuRGBA.hpp"
#include "tcuTextureUtil.hpp"
#include "vkImageUtil.hpp"
#include "vkPrograms.hpp"
#include "vktDrawBufferObjectUtil.hpp"
#include "vktDrawCreateInfoUtil.hpp"
#include "vktDrawImageObjectUtil.hpp"
#include "vktDrawTestCaseUtil.hpp"
namespace vkt
{
namespace Draw
{
namespace
{
static const int QUAD_GRID_SIZE = 8;
static const int WIDTH = 128;
static const int HEIGHT = 128;
struct TestParams
{
enum DrawFunction
{
FUNCTION_DRAW = 0,
FUNCTION_DRAW_INDEXED,
FUNCTION_DRAW_INDIRECT,
FUNCTION_DRAW_INDEXED_INDIRECT,
FUNTION_LAST
};
DrawFunction function;
vk::VkPrimitiveTopology topology;
};
struct VertexPositionAndColor
{
VertexPositionAndColor (tcu::Vec4 position_, tcu::Vec4 color_)
: position (position_)
, color (color_)
{
}
tcu::Vec4 position;
tcu::Vec4 color;
};
std::ostream & operator<<(std::ostream & str, TestParams const & v)
{
std::ostringstream string;
switch (v.function)
{
case TestParams::FUNCTION_DRAW:
string << "draw";
break;
case TestParams::FUNCTION_DRAW_INDEXED:
string << "draw_indexed";
break;
case TestParams::FUNCTION_DRAW_INDIRECT:
string << "draw_indirect";
break;
case TestParams::FUNCTION_DRAW_INDEXED_INDIRECT:
string << "draw_indexed_indirect";
break;
default:
DE_ASSERT(false);
}
string << "_" << de::toString(v.topology);
return str << string.str();
}
rr::PrimitiveType mapVkPrimitiveTopology (vk::VkPrimitiveTopology primitiveTopology)
{
switch (primitiveTopology)
{
case vk::VK_PRIMITIVE_TOPOLOGY_POINT_LIST: return rr::PRIMITIVETYPE_POINTS;
case vk::VK_PRIMITIVE_TOPOLOGY_LINE_LIST: return rr::PRIMITIVETYPE_LINES;
case vk::VK_PRIMITIVE_TOPOLOGY_LINE_STRIP: return rr::PRIMITIVETYPE_LINE_STRIP;
case vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST: return rr::PRIMITIVETYPE_TRIANGLES;
case vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN: return rr::PRIMITIVETYPE_TRIANGLE_FAN;
case vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP: return rr::PRIMITIVETYPE_TRIANGLE_STRIP;
case vk::VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY: return rr::PRIMITIVETYPE_LINES_ADJACENCY;
case vk::VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY: return rr::PRIMITIVETYPE_LINE_STRIP_ADJACENCY;
case vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY: return rr::PRIMITIVETYPE_TRIANGLES_ADJACENCY;
case vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY: return rr::PRIMITIVETYPE_TRIANGLE_STRIP_ADJACENCY;
default:
DE_ASSERT(false);
}
return rr::PRIMITIVETYPE_LAST;
}
template<typename T>
de::SharedPtr<Buffer> createAndUploadBuffer(const std::vector<T> data, const vk::DeviceInterface& vk, const Context& context)
{
const vk::VkDeviceSize dataSize = data.size() * sizeof(T);
de::SharedPtr<Buffer> vertexBuffer = Buffer::createAndAlloc(vk, context.getDevice(),
BufferCreateInfo(dataSize, vk::VK_BUFFER_USAGE_VERTEX_BUFFER_BIT),
context.getDefaultAllocator(),
vk::MemoryRequirement::HostVisible);
deUint8* ptr = reinterpret_cast<deUint8*>(vertexBuffer->getBoundMemory().getHostPtr());
deMemcpy(ptr, &data[0], static_cast<size_t>(dataSize));
vk::flushMappedMemoryRange(vk, context.getDevice(),
vertexBuffer->getBoundMemory().getMemory(),
vertexBuffer->getBoundMemory().getOffset(),
VK_WHOLE_SIZE);
return vertexBuffer;
}
class TestVertShader : public rr::VertexShader
{
public:
TestVertShader (int numInstances, int firstInstance)
: rr::VertexShader (3, 1)
, m_numInstances (numInstances)
, m_firstInstance (firstInstance)
{
m_inputs[0].type = rr::GENERICVECTYPE_FLOAT;
m_inputs[1].type = rr::GENERICVECTYPE_FLOAT;
m_inputs[2].type = rr::GENERICVECTYPE_FLOAT;
m_outputs[0].type = rr::GENERICVECTYPE_FLOAT;
}
void shadeVertices (const rr::VertexAttrib* inputs,
rr::VertexPacket* const* packets,
const int numPackets) const
{
for (int packetNdx = 0; packetNdx < numPackets; ++packetNdx)
{
const int instanceNdx = packets[packetNdx]->instanceNdx + m_firstInstance;
const tcu::Vec4 position = rr::readVertexAttribFloat(inputs[0], instanceNdx, packets[packetNdx]->vertexNdx);
const tcu::Vec4 color = rr::readVertexAttribFloat(inputs[1], instanceNdx, packets[packetNdx]->vertexNdx);
const tcu::Vec4 color2 = rr::readVertexAttribFloat(inputs[2], instanceNdx, packets[packetNdx]->vertexNdx);
packets[packetNdx]->position = position + tcu::Vec4((float)(packets[packetNdx]->instanceNdx * 2.0 / m_numInstances), 0.0, 0.0, 0.0);
packets[packetNdx]->outputs[0] = color + tcu::Vec4((float)instanceNdx / (float)m_numInstances, 0.0, 0.0, 1.0) + color2;
}
}
private:
const int m_numInstances;
const int m_firstInstance;
};
class TestFragShader : public rr::FragmentShader
{
public:
TestFragShader (void)
: rr::FragmentShader(1, 1)
{
m_inputs[0].type = rr::GENERICVECTYPE_FLOAT;
m_outputs[0].type = rr::GENERICVECTYPE_FLOAT;
}
void shadeFragments (rr::FragmentPacket* packets,
const int numPackets,
const rr::FragmentShadingContext& context) const
{
for (int packetNdx = 0; packetNdx < numPackets; ++packetNdx)
{
rr::FragmentPacket& packet = packets[packetNdx];
for (int fragNdx = 0; fragNdx < rr::NUM_FRAGMENTS_PER_PACKET; ++fragNdx)
{
const tcu::Vec4 color = rr::readVarying<float>(packet, context, 0, fragNdx);
rr::writeFragmentOutput(context, packetNdx, fragNdx, 0, color);
}
}
}
};
class InstancedDrawInstance : public TestInstance
{
public:
InstancedDrawInstance (Context& context, TestParams params);
virtual tcu::TestStatus iterate (void);
private:
void prepareVertexData (int instanceCount, int firstInstance);
const TestParams m_params;
const vk::DeviceInterface& m_vk;
vk::VkFormat m_colorAttachmentFormat;
vk::Move<vk::VkPipeline> m_pipeline;
vk::Move<vk::VkPipelineLayout> m_pipelineLayout;
de::SharedPtr<Image> m_colorTargetImage;
vk::Move<vk::VkImageView> m_colorTargetView;
PipelineCreateInfo::VertexInputState m_vertexInputState;
vk::Move<vk::VkCommandPool> m_cmdPool;
vk::Move<vk::VkCommandBuffer> m_cmdBuffer;
vk::Move<vk::VkFramebuffer> m_framebuffer;
vk::Move<vk::VkRenderPass> m_renderPass;
// Vertex data
std::vector<VertexPositionAndColor> m_data;
std::vector<deUint32> m_indexes;
std::vector<tcu::Vec4> m_instancedColor;
};
class InstancedDrawCase : public TestCase
{
public:
InstancedDrawCase (tcu::TestContext& testCtx,
const std::string& name,
const std::string& desc,
TestParams params)
: TestCase (testCtx, name, desc)
, m_params (params)
{
m_vertexShader = "#version 430\n"
"layout(location = 0) in vec4 in_position;\n"
"layout(location = 1) in vec4 in_color;\n"
"layout(location = 2) in vec4 in_color_2;\n"
"layout(push_constant) uniform TestParams {\n"
" float firstInstance;\n"
" float instanceCount;\n"
"} params;\n"
"layout(location = 0) out vec4 out_color;\n"
"out gl_PerVertex {\n"
" vec4 gl_Position;\n"
" float gl_PointSize;\n"
"};\n"
"void main() {\n"
" gl_PointSize = 1.0;\n"
" gl_Position = in_position + vec4(float(gl_InstanceIndex - params.firstInstance) * 2.0 / params.instanceCount, 0.0, 0.0, 0.0);\n"
" out_color = in_color + vec4(float(gl_InstanceIndex) / params.instanceCount, 0.0, 0.0, 1.0) + in_color_2;\n"
"}\n";
m_fragmentShader = "#version 430\n"
"layout(location = 0) in vec4 in_color;\n"
"layout(location = 0) out vec4 out_color;\n"
"void main()\n"
"{\n"
" out_color = in_color;\n"
"}\n";
}
TestInstance* createInstance (Context& context) const
{
return new InstancedDrawInstance(context, m_params);
}
virtual void initPrograms (vk::SourceCollections& programCollection) const
{
programCollection.glslSources.add("InstancedDrawVert") << glu::VertexSource(m_vertexShader);
programCollection.glslSources.add("InstancedDrawFrag") << glu::FragmentSource(m_fragmentShader);
}
private:
const TestParams m_params;
std::string m_vertexShader;
std::string m_fragmentShader;
};
InstancedDrawInstance::InstancedDrawInstance(Context &context, TestParams params)
: TestInstance (context)
, m_params (params)
, m_vk (context.getDeviceInterface())
, m_colorAttachmentFormat (vk::VK_FORMAT_R8G8B8A8_UNORM)
{
const vk::VkDevice device = m_context.getDevice();
const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex();
const vk::VkPushConstantRange pushConstantRange = {
vk::VK_SHADER_STAGE_VERTEX_BIT, // VkShaderStageFlags stageFlags;
0u, // uint32_t offset;
(deUint32)sizeof(float) * 2, // uint32_t size;
};
const PipelineLayoutCreateInfo pipelineLayoutCreateInfo(0, DE_NULL, 1, &pushConstantRange);
m_pipelineLayout = vk::createPipelineLayout(m_vk, device, &pipelineLayoutCreateInfo);
const vk::VkExtent3D targetImageExtent = { WIDTH, HEIGHT, 1 };
const ImageCreateInfo targetImageCreateInfo(vk::VK_IMAGE_TYPE_2D, m_colorAttachmentFormat, targetImageExtent, 1, 1, vk::VK_SAMPLE_COUNT_1_BIT,
vk::VK_IMAGE_TILING_OPTIMAL, vk::VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | vk::VK_IMAGE_USAGE_TRANSFER_SRC_BIT | vk::VK_IMAGE_USAGE_TRANSFER_DST_BIT);
m_colorTargetImage = Image::createAndAlloc(m_vk, device, targetImageCreateInfo, m_context.getDefaultAllocator());
const ImageViewCreateInfo colorTargetViewInfo(m_colorTargetImage->object(), vk::VK_IMAGE_VIEW_TYPE_2D, m_colorAttachmentFormat);
m_colorTargetView = vk::createImageView(m_vk, device, &colorTargetViewInfo);
RenderPassCreateInfo renderPassCreateInfo;
renderPassCreateInfo.addAttachment(AttachmentDescription(m_colorAttachmentFormat,
vk::VK_SAMPLE_COUNT_1_BIT,
vk::VK_ATTACHMENT_LOAD_OP_LOAD,
vk::VK_ATTACHMENT_STORE_OP_STORE,
vk::VK_ATTACHMENT_LOAD_OP_DONT_CARE,
vk::VK_ATTACHMENT_STORE_OP_STORE,
vk::VK_IMAGE_LAYOUT_GENERAL,
vk::VK_IMAGE_LAYOUT_GENERAL));
const vk::VkAttachmentReference colorAttachmentReference =
{
0,
vk::VK_IMAGE_LAYOUT_GENERAL
};
renderPassCreateInfo.addSubpass(SubpassDescription(vk::VK_PIPELINE_BIND_POINT_GRAPHICS,
0,
0,
DE_NULL,
1,
&colorAttachmentReference,
DE_NULL,
AttachmentReference(),
0,
DE_NULL));
m_renderPass = vk::createRenderPass(m_vk, device, &renderPassCreateInfo);
std::vector<vk::VkImageView> colorAttachments(1);
colorAttachments[0] = *m_colorTargetView;
const FramebufferCreateInfo framebufferCreateInfo(*m_renderPass, colorAttachments, WIDTH, HEIGHT, 1);
m_framebuffer = vk::createFramebuffer(m_vk, device, &framebufferCreateInfo);
const vk::VkVertexInputBindingDescription vertexInputBindingDescription[2] =
{
{
0u,
(deUint32)sizeof(VertexPositionAndColor),
vk::VK_VERTEX_INPUT_RATE_VERTEX,
},
{
1u,
(deUint32)sizeof(tcu::Vec4),
vk::VK_VERTEX_INPUT_RATE_INSTANCE,
},
};
const vk::VkVertexInputAttributeDescription vertexInputAttributeDescriptions[] =
{
{
0u,
0u,
vk::VK_FORMAT_R32G32B32A32_SFLOAT,
0u
},
{
1u,
0u,
vk::VK_FORMAT_R32G32B32A32_SFLOAT,
(deUint32)sizeof(tcu::Vec4),
},
{
2u,
1u,
vk::VK_FORMAT_R32G32B32A32_SFLOAT,
0,
}
};
m_vertexInputState = PipelineCreateInfo::VertexInputState(2,
vertexInputBindingDescription,
DE_LENGTH_OF_ARRAY(vertexInputAttributeDescriptions),
vertexInputAttributeDescriptions);
const CmdPoolCreateInfo cmdPoolCreateInfo(queueFamilyIndex);
m_cmdPool = vk::createCommandPool(m_vk, device, &cmdPoolCreateInfo);
const vk::VkCommandBufferAllocateInfo cmdBufferAllocateInfo =
{
vk::VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
*m_cmdPool, // VkCommandPool commandPool;
vk::VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level;
1u, // deUint32 bufferCount;
};
m_cmdBuffer = vk::allocateCommandBuffer(m_vk, device, &cmdBufferAllocateInfo);
const vk::Unique<vk::VkShaderModule> vs(createShaderModule(m_vk, device, m_context.getBinaryCollection().get("InstancedDrawVert"), 0));
const vk::Unique<vk::VkShaderModule> fs(createShaderModule(m_vk, device, m_context.getBinaryCollection().get("InstancedDrawFrag"), 0));
const PipelineCreateInfo::ColorBlendState::Attachment vkCbAttachmentState;
vk::VkViewport viewport;
viewport.x = 0;
viewport.y = 0;
viewport.width = static_cast<float>(WIDTH);
viewport.height = static_cast<float>(HEIGHT);
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
vk::VkRect2D scissor;
scissor.offset.x = 0;
scissor.offset.y = 0;
scissor.extent.width = WIDTH;
scissor.extent.height = HEIGHT;
PipelineCreateInfo pipelineCreateInfo(*m_pipelineLayout, *m_renderPass, 0, 0);
pipelineCreateInfo.addShader(PipelineCreateInfo::PipelineShaderStage(*vs, "main", vk::VK_SHADER_STAGE_VERTEX_BIT));
pipelineCreateInfo.addShader(PipelineCreateInfo::PipelineShaderStage(*fs, "main", vk::VK_SHADER_STAGE_FRAGMENT_BIT));
pipelineCreateInfo.addState(PipelineCreateInfo::VertexInputState(m_vertexInputState));
pipelineCreateInfo.addState(PipelineCreateInfo::InputAssemblerState(m_params.topology));
pipelineCreateInfo.addState(PipelineCreateInfo::ColorBlendState(1, &vkCbAttachmentState));
pipelineCreateInfo.addState(PipelineCreateInfo::ViewportState(1, std::vector<vk::VkViewport>(1, viewport), std::vector<vk::VkRect2D>(1, scissor)));
pipelineCreateInfo.addState(PipelineCreateInfo::DepthStencilState());
pipelineCreateInfo.addState(PipelineCreateInfo::RasterizerState());
pipelineCreateInfo.addState(PipelineCreateInfo::MultiSampleState());
m_pipeline = vk::createGraphicsPipeline(m_vk, device, DE_NULL, &pipelineCreateInfo);
}
tcu::TestStatus InstancedDrawInstance::iterate()
{
const vk::VkQueue queue = m_context.getUniversalQueue();
static const deUint32 instanceCounts[] = { 1, 2, 4, 20 };
static const deUint32 firstInstanceIndices[] = { 0, 1, 3, 4, 20 };
qpTestResult res = QP_TEST_RESULT_PASS;
const vk::VkClearColorValue clearColor = { { 0.0f, 0.0f, 0.0f, 1.0f } };
const CmdBufferBeginInfo beginInfo;
int firstInstanceIndicesCount = 1;
// Require 'drawIndirectFirstInstance' feature to run non-zero firstInstance indirect draw tests.
if (m_context.getDeviceFeatures().drawIndirectFirstInstance)
firstInstanceIndicesCount = DE_LENGTH_OF_ARRAY(firstInstanceIndices);
for (int instanceCountNdx = 0; instanceCountNdx < DE_LENGTH_OF_ARRAY(instanceCounts); instanceCountNdx++)
{
const deUint32 instanceCount = instanceCounts[instanceCountNdx];
for (int firstInstanceIndexNdx = 0; firstInstanceIndexNdx < firstInstanceIndicesCount; firstInstanceIndexNdx++)
{
const deUint32 firstInstance = firstInstanceIndices[firstInstanceIndexNdx];
prepareVertexData(instanceCount, firstInstance);
const de::SharedPtr<Buffer> vertexBuffer = createAndUploadBuffer(m_data, m_vk, m_context);
const de::SharedPtr<Buffer> instancedVertexBuffer = createAndUploadBuffer(m_instancedColor, m_vk, m_context);
de::SharedPtr<Buffer> indexBuffer;
de::SharedPtr<Buffer> indirectBuffer;
m_vk.beginCommandBuffer(*m_cmdBuffer, &beginInfo);
initialTransitionColor2DImage(m_vk, *m_cmdBuffer, m_colorTargetImage->object(), vk::VK_IMAGE_LAYOUT_GENERAL);
const ImageSubresourceRange subresourceRange(vk::VK_IMAGE_ASPECT_COLOR_BIT);
m_vk.cmdClearColorImage(*m_cmdBuffer, m_colorTargetImage->object(),
vk::VK_IMAGE_LAYOUT_GENERAL, &clearColor, 1, &subresourceRange);
const vk::VkMemoryBarrier memBarrier =
{
vk::VK_STRUCTURE_TYPE_MEMORY_BARRIER,
DE_NULL,
vk::VK_ACCESS_TRANSFER_WRITE_BIT,
vk::VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | vk::VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT
};
m_vk.cmdPipelineBarrier(*m_cmdBuffer, vk::VK_PIPELINE_STAGE_TRANSFER_BIT,
vk::VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
0, 1, &memBarrier, 0, DE_NULL, 0, DE_NULL);
const vk::VkRect2D renderArea = { { 0, 0 }, { WIDTH, HEIGHT } };
const RenderPassBeginInfo renderPassBegin(*m_renderPass, *m_framebuffer, renderArea);
m_vk.cmdBeginRenderPass(*m_cmdBuffer, &renderPassBegin, vk::VK_SUBPASS_CONTENTS_INLINE);
if (m_params.function == TestParams::FUNCTION_DRAW_INDEXED || m_params.function == TestParams::FUNCTION_DRAW_INDEXED_INDIRECT)
{
indexBuffer = createAndUploadBuffer(m_indexes, m_vk, m_context);
m_vk.cmdBindIndexBuffer(*m_cmdBuffer, indexBuffer->object(), 0, vk::VK_INDEX_TYPE_UINT32);
}
const vk::VkBuffer vertexBuffers[] =
{
vertexBuffer->object(),
instancedVertexBuffer->object(),
};
const vk::VkDeviceSize vertexBufferOffsets[] =
{
0, // vertexBufferOffset
0, // instancedVertexBufferOffset
};
m_vk.cmdBindVertexBuffers(*m_cmdBuffer, 0, DE_LENGTH_OF_ARRAY(vertexBuffers), vertexBuffers, vertexBufferOffsets);
const float pushConstants[] = { (float)firstInstance, (float)instanceCount };
m_vk.cmdPushConstants(*m_cmdBuffer, *m_pipelineLayout, vk::VK_SHADER_STAGE_VERTEX_BIT, 0u, (deUint32)sizeof(pushConstants), pushConstants);
m_vk.cmdBindPipeline(*m_cmdBuffer, vk::VK_PIPELINE_BIND_POINT_GRAPHICS, *m_pipeline);
switch (m_params.function)
{
case TestParams::FUNCTION_DRAW:
m_vk.cmdDraw(*m_cmdBuffer, (deUint32)m_data.size(), instanceCount, 0u, firstInstance);
break;
case TestParams::FUNCTION_DRAW_INDEXED:
m_vk.cmdDrawIndexed(*m_cmdBuffer, (deUint32)m_indexes.size(), instanceCount, 0u, 0u, firstInstance);
break;
case TestParams::FUNCTION_DRAW_INDIRECT:
{
vk::VkDrawIndirectCommand drawCommand =
{
(deUint32)m_data.size(), // uint32_t vertexCount;
instanceCount, // uint32_t instanceCount;
0u, // uint32_t firstVertex;
firstInstance, // uint32_t firstInstance;
};
std::vector<vk::VkDrawIndirectCommand> drawCommands;
drawCommands.push_back(drawCommand);
indirectBuffer = createAndUploadBuffer(drawCommands, m_vk, m_context);
m_vk.cmdDrawIndirect(*m_cmdBuffer, indirectBuffer->object(), 0, 1u, 0u);
break;
}
case TestParams::FUNCTION_DRAW_INDEXED_INDIRECT:
{
vk::VkDrawIndexedIndirectCommand drawCommand =
{
(deUint32)m_indexes.size(), // uint32_t indexCount;
instanceCount, // uint32_t instanceCount;
0u, // uint32_t firstIndex;
0, // int32_t vertexOffset;
firstInstance, // uint32_t firstInstance;
};
std::vector<vk::VkDrawIndexedIndirectCommand> drawCommands;
drawCommands.push_back(drawCommand);
indirectBuffer = createAndUploadBuffer(drawCommands, m_vk, m_context);
m_vk.cmdDrawIndexedIndirect(*m_cmdBuffer, indirectBuffer->object(), 0, 1u, 0u);
break;
}
default:
DE_ASSERT(false);
}
m_vk.cmdEndRenderPass(*m_cmdBuffer);
m_vk.endCommandBuffer(*m_cmdBuffer);
vk::VkSubmitInfo submitInfo =
{
vk::VK_STRUCTURE_TYPE_SUBMIT_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0, // deUint32 waitSemaphoreCount;
DE_NULL, // const VkSemaphore* pWaitSemaphores;
(const vk::VkPipelineStageFlags*)DE_NULL, // const VkPipelineStageFlags* pWaitDstStageMask;
1, // deUint32 commandBufferCount;
&m_cmdBuffer.get(), // const VkCommandBuffer* pCommandBuffers;
0, // deUint32 signalSemaphoreCount;
DE_NULL // const VkSemaphore* pSignalSemaphores;
};
VK_CHECK(m_vk.queueSubmit(queue, 1, &submitInfo, DE_NULL));
VK_CHECK(m_vk.queueWaitIdle(queue));
// Reference rendering
std::vector<tcu::Vec4> vetrices;
std::vector<tcu::Vec4> colors;
for (std::vector<VertexPositionAndColor>::const_iterator it = m_data.begin(); it != m_data.end(); ++it)
{
vetrices.push_back(it->position);
colors.push_back(it->color);
}
tcu::TextureLevel refImage (vk::mapVkFormat(m_colorAttachmentFormat), (int)(0.5 + WIDTH), (int)(0.5 + HEIGHT));
tcu::clear(refImage.getAccess(), tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
const TestVertShader vertShader(instanceCount, firstInstance);
const TestFragShader fragShader;
const rr::Program program (&vertShader, &fragShader);
const rr::MultisamplePixelBufferAccess colorBuffer = rr::MultisamplePixelBufferAccess::fromSinglesampleAccess(refImage.getAccess());
const rr::RenderTarget renderTarget (colorBuffer);
const rr::RenderState renderState ((rr::ViewportState(colorBuffer)));
const rr::Renderer renderer;
const rr::VertexAttrib vertexAttribs[] =
{
rr::VertexAttrib(rr::VERTEXATTRIBTYPE_FLOAT, 4, sizeof(tcu::Vec4), 0, &vetrices[0]),
rr::VertexAttrib(rr::VERTEXATTRIBTYPE_FLOAT, 4, sizeof(tcu::Vec4), 0, &colors[0]),
rr::VertexAttrib(rr::VERTEXATTRIBTYPE_FLOAT, 4, sizeof(tcu::Vec4), 1, &m_instancedColor[0])
};
if (m_params.function == TestParams::FUNCTION_DRAW || m_params.function == TestParams::FUNCTION_DRAW_INDIRECT)
{
const rr::PrimitiveList primitives = rr::PrimitiveList(mapVkPrimitiveTopology(m_params.topology), (int)vetrices.size(), 0);
const rr::DrawCommand command(renderState, renderTarget, program, DE_LENGTH_OF_ARRAY(vertexAttribs), &vertexAttribs[0],
primitives);
renderer.drawInstanced(command, instanceCount);
}
else
{
const rr::DrawIndices indicies(m_indexes.data());
const rr::PrimitiveList primitives = rr::PrimitiveList(mapVkPrimitiveTopology(m_params.topology), (int)m_indexes.size(), indicies);
const rr::DrawCommand command(renderState, renderTarget, program, DE_LENGTH_OF_ARRAY(vertexAttribs), &vertexAttribs[0],
primitives);
renderer.drawInstanced(command, instanceCount);
}
const vk::VkOffset3D zeroOffset = { 0, 0, 0 };
const tcu::ConstPixelBufferAccess renderedFrame = m_colorTargetImage->readSurface(queue, m_context.getDefaultAllocator(),
vk::VK_IMAGE_LAYOUT_GENERAL, zeroOffset, WIDTH, HEIGHT, vk::VK_IMAGE_ASPECT_COLOR_BIT);
tcu::TestLog &log = m_context.getTestContext().getLog();
std::ostringstream resultDesc;
resultDesc << "Image comparison result. Instance count: " << instanceCount << " first instance index: " << firstInstance;
if (m_params.topology == vk::VK_PRIMITIVE_TOPOLOGY_POINT_LIST)
{
const bool ok = tcu::intThresholdPositionDeviationCompare(
log, "Result", resultDesc.str().c_str(), refImage.getAccess(), renderedFrame,
tcu::UVec4(4u), // color threshold
tcu::IVec3(1, 1, 0), // position deviation tolerance
true, // don't check the pixels at the boundary
tcu::COMPARE_LOG_RESULT);
if (!ok)
res = QP_TEST_RESULT_FAIL;
}
else
{
if (!tcu::fuzzyCompare(log, "Result", resultDesc.str().c_str(), refImage.getAccess(), renderedFrame, 0.05f, tcu::COMPARE_LOG_RESULT))
res = QP_TEST_RESULT_FAIL;
}
}
}
return tcu::TestStatus(res, qpGetTestResultName(res));
}
void InstancedDrawInstance::prepareVertexData(int instanceCount, int firstInstance)
{
m_data.clear();
m_indexes.clear();
m_instancedColor.clear();
if (m_params.function == TestParams::FUNCTION_DRAW || m_params.function == TestParams::FUNCTION_DRAW_INDIRECT)
{
for (int y = 0; y < QUAD_GRID_SIZE; y++)
{
for (int x = 0; x < QUAD_GRID_SIZE; x++)
{
const float fx0 = -1.0f + (float)(x+0) / (float)QUAD_GRID_SIZE * 2.0f / (float)instanceCount;
const float fx1 = -1.0f + (float)(x+1) / (float)QUAD_GRID_SIZE * 2.0f / (float)instanceCount;
const float fy0 = -1.0f + (float)(y+0) / (float)QUAD_GRID_SIZE * 2.0f;
const float fy1 = -1.0f + (float)(y+1) / (float)QUAD_GRID_SIZE * 2.0f;
// Vertices of a quad's lower-left triangle: (fx0, fy0), (fx1, fy0) and (fx0, fy1)
m_data.push_back(VertexPositionAndColor(tcu::Vec4(fx0, fy0, 1.0f, 1.0f), tcu::RGBA::blue().toVec()));
m_data.push_back(VertexPositionAndColor(tcu::Vec4(fx1, fy0, 1.0f, 1.0f), tcu::RGBA::blue().toVec()));
m_data.push_back(VertexPositionAndColor(tcu::Vec4(fx0, fy1, 1.0f, 1.0f), tcu::RGBA::green().toVec()));
// Vertices of a quad's upper-right triangle: (fx1, fy1), (fx0, fy1) and (fx1, fy0)
m_data.push_back(VertexPositionAndColor(tcu::Vec4(fx1, fy1, 1.0f, 1.0f), tcu::RGBA::green().toVec()));
m_data.push_back(VertexPositionAndColor(tcu::Vec4(fx0, fy1, 1.0f, 1.0f), tcu::RGBA::green().toVec()));
m_data.push_back(VertexPositionAndColor(tcu::Vec4(fx1, fy0, 1.0f, 1.0f), tcu::RGBA::blue().toVec()));
}
}
}
else
{
for (int y = 0; y < QUAD_GRID_SIZE + 1; y++)
{
for (int x = 0; x < QUAD_GRID_SIZE + 1; x++)
{
const float fx = -1.0f + (float)x / (float)QUAD_GRID_SIZE * 2.0f / (float)instanceCount;
const float fy = -1.0f + (float)y / (float)QUAD_GRID_SIZE * 2.0f;
m_data.push_back(VertexPositionAndColor(tcu::Vec4(fx, fy, 1.0f, 1.0f),
(y % 2 ? tcu::RGBA::blue().toVec() : tcu::RGBA::green().toVec())));
}
}
for (int y = 0; y < QUAD_GRID_SIZE; y++)
{
for (int x = 0; x < QUAD_GRID_SIZE; x++)
{
const int ndx00 = y*(QUAD_GRID_SIZE + 1) + x;
const int ndx10 = y*(QUAD_GRID_SIZE + 1) + x + 1;
const int ndx01 = (y + 1)*(QUAD_GRID_SIZE + 1) + x;
const int ndx11 = (y + 1)*(QUAD_GRID_SIZE + 1) + x + 1;
// Lower-left triangle of a quad.
m_indexes.push_back((deUint16)ndx00);
m_indexes.push_back((deUint16)ndx10);
m_indexes.push_back((deUint16)ndx01);
// Upper-right triangle of a quad.
m_indexes.push_back((deUint16)ndx11);
m_indexes.push_back((deUint16)ndx01);
m_indexes.push_back((deUint16)ndx10);
}
}
}
for (int i = 0; i < instanceCount + firstInstance; i++)
{
m_instancedColor.push_back(tcu::Vec4(0.0, (float)(1.0 - i * 1.0 / (instanceCount + firstInstance)) / 2, 0.0, 1.0));
}
}
} // anonymus
InstancedTests::InstancedTests(tcu::TestContext& testCtx)
: TestCaseGroup (testCtx, "instanced", "Instanced drawing tests")
{
static const vk::VkPrimitiveTopology topologies[] =
{
vk::VK_PRIMITIVE_TOPOLOGY_POINT_LIST,
vk::VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
vk::VK_PRIMITIVE_TOPOLOGY_LINE_STRIP,
vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN,
};
static const TestParams::DrawFunction functions[] =
{
TestParams::FUNCTION_DRAW,
TestParams::FUNCTION_DRAW_INDEXED,
TestParams::FUNCTION_DRAW_INDIRECT,
TestParams::FUNCTION_DRAW_INDEXED_INDIRECT,
};
for (int topologyNdx = 0; topologyNdx < DE_LENGTH_OF_ARRAY(topologies); topologyNdx++)
{
for (int functionNdx = 0; functionNdx < DE_LENGTH_OF_ARRAY(functions); functionNdx++)
{
TestParams param;
param.function = functions[functionNdx];
param.topology = topologies[topologyNdx];
std::string testName = de::toString(param);
addChild(new InstancedDrawCase(m_testCtx, de::toLower(testName), "Instanced drawing test", param));
}
}
}
InstancedTests::~InstancedTests() {}
} // DrawTests
} // vkt
|
#include "selfdrive/common/params.h"
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif // _GNU_SOURCE
#include <dirent.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <unordered_map>
#include "selfdrive/common/swaglog.h"
#include "selfdrive/common/util.h"
#include "selfdrive/hardware/hw.h"
namespace {
volatile sig_atomic_t params_do_exit = 0;
void params_sig_handler(int signal) {
params_do_exit = 1;
}
int fsync_dir(const char* path) {
int fd = HANDLE_EINTR(open(path, O_RDONLY, 0755));
if (fd < 0) {
return -1;
}
int result = fsync(fd);
int result_close = close(fd);
if (result_close < 0) {
result = result_close;
}
return result;
}
int mkdir_p(std::string path) {
char * _path = (char *)path.c_str();
for (char *p = _path + 1; *p; p++) {
if (*p == '/') {
*p = '\0'; // Temporarily truncate
if (mkdir(_path, 0775) != 0) {
if (errno != EEXIST) return -1;
}
*p = '/';
}
}
if (mkdir(_path, 0775) != 0) {
if (errno != EEXIST) return -1;
}
return 0;
}
bool create_params_path(const std::string ¶m_path, const std::string &key_path) {
// Make sure params path exists
if (!util::file_exists(param_path) && mkdir_p(param_path) != 0) {
return false;
}
// See if the symlink exists, otherwise create it
if (!util::file_exists(key_path)) {
// 1) Create temp folder
// 2) Set permissions
// 3) Symlink it to temp link
// 4) Move symlink to <params>/d
std::string tmp_path = param_path + "/.tmp_XXXXXX";
// this should be OK since mkdtemp just replaces characters in place
char *tmp_dir = mkdtemp((char *)tmp_path.c_str());
if (tmp_dir == NULL) {
return false;
}
std::string link_path = std::string(tmp_dir) + ".link";
if (symlink(tmp_dir, link_path.c_str()) != 0) {
return false;
}
// don't return false if it has been created by other
if (rename(link_path.c_str(), key_path.c_str()) != 0 && errno != EEXIST) {
return false;
}
}
return true;
}
void ensure_params_path(const std::string ¶ms_path) {
if (!create_params_path(params_path, params_path + "/d")) {
throw std::runtime_error(util::string_format("Failed to ensure params path, errno=%d", errno));
}
}
class FileLock {
public:
FileLock(const std::string& file_name, int op) : fn_(file_name), op_(op) {}
void lock() {
fd_ = HANDLE_EINTR(open(fn_.c_str(), O_CREAT, 0775));
if (fd_ < 0) {
LOGE("Failed to open lock file %s, errno=%d", fn_.c_str(), errno);
return;
}
if (HANDLE_EINTR(flock(fd_, op_)) < 0) {
LOGE("Failed to lock file %s, errno=%d", fn_.c_str(), errno);
}
}
void unlock() { close(fd_); }
private:
int fd_ = -1, op_;
std::string fn_;
};
std::unordered_map<std::string, uint32_t> keys = {
{"AccessToken", CLEAR_ON_MANAGER_START | DONT_LOG},
{"ApiCache_DriveStats", PERSISTENT},
{"ApiCache_Device", PERSISTENT},
{"ApiCache_Owner", PERSISTENT},
{"ApiCache_NavDestinations", PERSISTENT},
{"AthenadPid", PERSISTENT},
{"CalibrationParams", PERSISTENT},
{"CarBatteryCapacity", PERSISTENT},
{"CarParams", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT | CLEAR_ON_IGNITION_ON},
{"CarParamsCache", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
{"CarVin", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT | CLEAR_ON_IGNITION_ON},
{"CommunityFeaturesToggle", PERSISTENT},
{"ControlsReady", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT | CLEAR_ON_IGNITION_ON},
{"CurrentRoute", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON},
{"DisableRadar", PERSISTENT}, // WARNING: THIS DISABLES AEB
{"EndToEndToggle", PERSISTENT},
{"CompletedTrainingVersion", PERSISTENT},
{"DisablePowerDown", PERSISTENT},
{"DisableUpdates", PERSISTENT},
{"EnableWideCamera", CLEAR_ON_MANAGER_START},
{"DoUninstall", CLEAR_ON_MANAGER_START},
{"DongleId", PERSISTENT},
{"GitDiff", PERSISTENT},
{"GitBranch", PERSISTENT},
{"GitCommit", PERSISTENT},
{"GitRemote", PERSISTENT},
{"GithubSshKeys", PERSISTENT},
{"GithubUsername", PERSISTENT},
{"HardwareSerial", PERSISTENT},
{"HasAcceptedTerms", PERSISTENT},
{"IsDriverViewEnabled", CLEAR_ON_MANAGER_START},
{"IMEI", PERSISTENT},
{"IsLdwEnabled", PERSISTENT},
{"IsMetric", PERSISTENT},
{"IsOffroad", CLEAR_ON_MANAGER_START},
{"IsOnroad", PERSISTENT},
{"IsRHD", PERSISTENT},
{"IsTakingSnapshot", CLEAR_ON_MANAGER_START},
{"IsUpdateAvailable", CLEAR_ON_MANAGER_START},
{"UploadRaw", PERSISTENT},
{"LastAthenaPingTime", CLEAR_ON_MANAGER_START},
{"LastGPSPosition", PERSISTENT},
{"LastUpdateException", PERSISTENT},
{"LastUpdateTime", PERSISTENT},
{"LiveParameters", PERSISTENT},
{"MapboxToken", PERSISTENT | DONT_LOG},
{"NavDestination", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
{"NavSettingTime24h", PERSISTENT},
{"OpenpilotEnabledToggle", PERSISTENT},
{"PandaFirmware", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
{"PandaFirmwareHex", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
{"PandaDongleId", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
{"PandaHeartbeatLost", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
{"Passive", PERSISTENT},
{"PrimeRedirected", PERSISTENT},
{"RecordFront", PERSISTENT},
{"RecordFrontLock", PERSISTENT}, // for the internal fleet
{"ReleaseNotes", PERSISTENT},
{"ShouldDoUpdate", CLEAR_ON_MANAGER_START},
{"SubscriberInfo", PERSISTENT},
{"SshEnabled", PERSISTENT},
{"TermsVersion", PERSISTENT},
{"Timezone", PERSISTENT},
{"TrainingVersion", PERSISTENT},
{"UpdateAvailable", CLEAR_ON_MANAGER_START},
{"UpdateFailedCount", CLEAR_ON_MANAGER_START},
{"Version", PERSISTENT},
{"VisionRadarToggle", PERSISTENT},
{"Offroad_ChargeDisabled", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
{"Offroad_ConnectivityNeeded", CLEAR_ON_MANAGER_START},
{"Offroad_ConnectivityNeededPrompt", CLEAR_ON_MANAGER_START},
{"Offroad_TemperatureTooHigh", CLEAR_ON_MANAGER_START},
{"Offroad_PandaFirmwareMismatch", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
{"Offroad_InvalidTime", CLEAR_ON_MANAGER_START},
{"Offroad_IsTakingSnapshot", CLEAR_ON_MANAGER_START},
{"Offroad_NeosUpdate", CLEAR_ON_MANAGER_START},
{"Offroad_UpdateFailed", CLEAR_ON_MANAGER_START},
{"Offroad_HardwareUnsupported", CLEAR_ON_MANAGER_START},
{"Offroad_UnofficialHardware", CLEAR_ON_MANAGER_START},
{"Offroad_NvmeMissing", CLEAR_ON_MANAGER_START},
{"ForcePowerDown", CLEAR_ON_MANAGER_START},
{"JoystickDebugMode", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
};
} // namespace
Params::Params() : params_path(Path::params()) {
static std::once_flag once_flag;
std::call_once(once_flag, ensure_params_path, params_path);
}
Params::Params(const std::string &path) : params_path(path) {
ensure_params_path(params_path);
}
bool Params::checkKey(const std::string &key) {
return keys.find(key) != keys.end();
}
ParamKeyType Params::getKeyType(const std::string &key) {
return static_cast<ParamKeyType>(keys[key]);
}
int Params::put(const char* key, const char* value, size_t value_size) {
// Information about safely and atomically writing a file: https://lwn.net/Articles/457667/
// 1) Create temp file
// 2) Write data to temp file
// 3) fsync() the temp file
// 4) rename the temp file to the real name
// 5) fsync() the containing directory
std::string tmp_path = params_path + "/.tmp_value_XXXXXX";
int tmp_fd = mkstemp((char*)tmp_path.c_str());
if (tmp_fd < 0) return -1;
int result = -1;
do {
// Write value to temp.
ssize_t bytes_written = HANDLE_EINTR(write(tmp_fd, value, value_size));
if (bytes_written < 0 || (size_t)bytes_written != value_size) {
result = -20;
break;
}
// fsync to force persist the changes.
if ((result = fsync(tmp_fd)) < 0) break;
FileLock file_lock(params_path + "/.lock", LOCK_EX);
std::lock_guard<FileLock> lk(file_lock);
// Move temp into place.
std::string path = params_path + "/d/" + std::string(key);
if ((result = rename(tmp_path.c_str(), path.c_str())) < 0) break;
// fsync parent directory
path = params_path + "/d";
result = fsync_dir(path.c_str());
} while (false);
close(tmp_fd);
remove(tmp_path.c_str());
return result;
}
int Params::remove(const char *key) {
FileLock file_lock(params_path + "/.lock", LOCK_EX);
std::lock_guard<FileLock> lk(file_lock);
// Delete value.
std::string path = params_path + "/d/" + key;
int result = ::remove(path.c_str());
if (result != 0) {
result = ERR_NO_VALUE;
return result;
}
// fsync parent directory
path = params_path + "/d";
return fsync_dir(path.c_str());
}
std::string Params::get(const char *key, bool block) {
std::string path = params_path + "/d/" + key;
if (!block) {
return util::read_file(path);
} else {
// blocking read until successful
params_do_exit = 0;
void (*prev_handler_sigint)(int) = std::signal(SIGINT, params_sig_handler);
void (*prev_handler_sigterm)(int) = std::signal(SIGTERM, params_sig_handler);
std::string value;
while (!params_do_exit) {
if (value = util::read_file(path); !value.empty()) {
break;
}
util::sleep_for(100); // 0.1 s
}
std::signal(SIGINT, prev_handler_sigint);
std::signal(SIGTERM, prev_handler_sigterm);
return value;
}
}
std::map<std::string, std::string> Params::readAll() {
FileLock file_lock(params_path + "/.lock", LOCK_SH);
std::lock_guard<FileLock> lk(file_lock);
std::string key_path = params_path + "/d";
return util::read_files_in_dir(key_path);
}
void Params::clearAll(ParamKeyType key_type) {
for (auto &[key, type] : keys) {
if (type & key_type) {
remove(key);
}
}
}
Params::put: fixed the wrong call to Params::remove instead of global ::remove (#21974)
* fix bug
* use unlink
#include "selfdrive/common/params.h"
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif // _GNU_SOURCE
#include <dirent.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <unordered_map>
#include "selfdrive/common/swaglog.h"
#include "selfdrive/common/util.h"
#include "selfdrive/hardware/hw.h"
namespace {
volatile sig_atomic_t params_do_exit = 0;
void params_sig_handler(int signal) {
params_do_exit = 1;
}
int fsync_dir(const char* path) {
int fd = HANDLE_EINTR(open(path, O_RDONLY, 0755));
if (fd < 0) {
return -1;
}
int result = fsync(fd);
int result_close = close(fd);
if (result_close < 0) {
result = result_close;
}
return result;
}
int mkdir_p(std::string path) {
char * _path = (char *)path.c_str();
for (char *p = _path + 1; *p; p++) {
if (*p == '/') {
*p = '\0'; // Temporarily truncate
if (mkdir(_path, 0775) != 0) {
if (errno != EEXIST) return -1;
}
*p = '/';
}
}
if (mkdir(_path, 0775) != 0) {
if (errno != EEXIST) return -1;
}
return 0;
}
bool create_params_path(const std::string ¶m_path, const std::string &key_path) {
// Make sure params path exists
if (!util::file_exists(param_path) && mkdir_p(param_path) != 0) {
return false;
}
// See if the symlink exists, otherwise create it
if (!util::file_exists(key_path)) {
// 1) Create temp folder
// 2) Set permissions
// 3) Symlink it to temp link
// 4) Move symlink to <params>/d
std::string tmp_path = param_path + "/.tmp_XXXXXX";
// this should be OK since mkdtemp just replaces characters in place
char *tmp_dir = mkdtemp((char *)tmp_path.c_str());
if (tmp_dir == NULL) {
return false;
}
std::string link_path = std::string(tmp_dir) + ".link";
if (symlink(tmp_dir, link_path.c_str()) != 0) {
return false;
}
// don't return false if it has been created by other
if (rename(link_path.c_str(), key_path.c_str()) != 0 && errno != EEXIST) {
return false;
}
}
return true;
}
void ensure_params_path(const std::string ¶ms_path) {
if (!create_params_path(params_path, params_path + "/d")) {
throw std::runtime_error(util::string_format("Failed to ensure params path, errno=%d", errno));
}
}
class FileLock {
public:
FileLock(const std::string& file_name, int op) : fn_(file_name), op_(op) {}
void lock() {
fd_ = HANDLE_EINTR(open(fn_.c_str(), O_CREAT, 0775));
if (fd_ < 0) {
LOGE("Failed to open lock file %s, errno=%d", fn_.c_str(), errno);
return;
}
if (HANDLE_EINTR(flock(fd_, op_)) < 0) {
LOGE("Failed to lock file %s, errno=%d", fn_.c_str(), errno);
}
}
void unlock() { close(fd_); }
private:
int fd_ = -1, op_;
std::string fn_;
};
std::unordered_map<std::string, uint32_t> keys = {
{"AccessToken", CLEAR_ON_MANAGER_START | DONT_LOG},
{"ApiCache_DriveStats", PERSISTENT},
{"ApiCache_Device", PERSISTENT},
{"ApiCache_Owner", PERSISTENT},
{"ApiCache_NavDestinations", PERSISTENT},
{"AthenadPid", PERSISTENT},
{"CalibrationParams", PERSISTENT},
{"CarBatteryCapacity", PERSISTENT},
{"CarParams", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT | CLEAR_ON_IGNITION_ON},
{"CarParamsCache", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
{"CarVin", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT | CLEAR_ON_IGNITION_ON},
{"CommunityFeaturesToggle", PERSISTENT},
{"ControlsReady", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT | CLEAR_ON_IGNITION_ON},
{"CurrentRoute", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON},
{"DisableRadar", PERSISTENT}, // WARNING: THIS DISABLES AEB
{"EndToEndToggle", PERSISTENT},
{"CompletedTrainingVersion", PERSISTENT},
{"DisablePowerDown", PERSISTENT},
{"DisableUpdates", PERSISTENT},
{"EnableWideCamera", CLEAR_ON_MANAGER_START},
{"DoUninstall", CLEAR_ON_MANAGER_START},
{"DongleId", PERSISTENT},
{"GitDiff", PERSISTENT},
{"GitBranch", PERSISTENT},
{"GitCommit", PERSISTENT},
{"GitRemote", PERSISTENT},
{"GithubSshKeys", PERSISTENT},
{"GithubUsername", PERSISTENT},
{"HardwareSerial", PERSISTENT},
{"HasAcceptedTerms", PERSISTENT},
{"IsDriverViewEnabled", CLEAR_ON_MANAGER_START},
{"IMEI", PERSISTENT},
{"IsLdwEnabled", PERSISTENT},
{"IsMetric", PERSISTENT},
{"IsOffroad", CLEAR_ON_MANAGER_START},
{"IsOnroad", PERSISTENT},
{"IsRHD", PERSISTENT},
{"IsTakingSnapshot", CLEAR_ON_MANAGER_START},
{"IsUpdateAvailable", CLEAR_ON_MANAGER_START},
{"UploadRaw", PERSISTENT},
{"LastAthenaPingTime", CLEAR_ON_MANAGER_START},
{"LastGPSPosition", PERSISTENT},
{"LastUpdateException", PERSISTENT},
{"LastUpdateTime", PERSISTENT},
{"LiveParameters", PERSISTENT},
{"MapboxToken", PERSISTENT | DONT_LOG},
{"NavDestination", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
{"NavSettingTime24h", PERSISTENT},
{"OpenpilotEnabledToggle", PERSISTENT},
{"PandaFirmware", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
{"PandaFirmwareHex", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
{"PandaDongleId", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
{"PandaHeartbeatLost", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
{"Passive", PERSISTENT},
{"PrimeRedirected", PERSISTENT},
{"RecordFront", PERSISTENT},
{"RecordFrontLock", PERSISTENT}, // for the internal fleet
{"ReleaseNotes", PERSISTENT},
{"ShouldDoUpdate", CLEAR_ON_MANAGER_START},
{"SubscriberInfo", PERSISTENT},
{"SshEnabled", PERSISTENT},
{"TermsVersion", PERSISTENT},
{"Timezone", PERSISTENT},
{"TrainingVersion", PERSISTENT},
{"UpdateAvailable", CLEAR_ON_MANAGER_START},
{"UpdateFailedCount", CLEAR_ON_MANAGER_START},
{"Version", PERSISTENT},
{"VisionRadarToggle", PERSISTENT},
{"Offroad_ChargeDisabled", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
{"Offroad_ConnectivityNeeded", CLEAR_ON_MANAGER_START},
{"Offroad_ConnectivityNeededPrompt", CLEAR_ON_MANAGER_START},
{"Offroad_TemperatureTooHigh", CLEAR_ON_MANAGER_START},
{"Offroad_PandaFirmwareMismatch", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
{"Offroad_InvalidTime", CLEAR_ON_MANAGER_START},
{"Offroad_IsTakingSnapshot", CLEAR_ON_MANAGER_START},
{"Offroad_NeosUpdate", CLEAR_ON_MANAGER_START},
{"Offroad_UpdateFailed", CLEAR_ON_MANAGER_START},
{"Offroad_HardwareUnsupported", CLEAR_ON_MANAGER_START},
{"Offroad_UnofficialHardware", CLEAR_ON_MANAGER_START},
{"Offroad_NvmeMissing", CLEAR_ON_MANAGER_START},
{"ForcePowerDown", CLEAR_ON_MANAGER_START},
{"JoystickDebugMode", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
};
} // namespace
Params::Params() : params_path(Path::params()) {
static std::once_flag once_flag;
std::call_once(once_flag, ensure_params_path, params_path);
}
Params::Params(const std::string &path) : params_path(path) {
ensure_params_path(params_path);
}
bool Params::checkKey(const std::string &key) {
return keys.find(key) != keys.end();
}
ParamKeyType Params::getKeyType(const std::string &key) {
return static_cast<ParamKeyType>(keys[key]);
}
int Params::put(const char* key, const char* value, size_t value_size) {
// Information about safely and atomically writing a file: https://lwn.net/Articles/457667/
// 1) Create temp file
// 2) Write data to temp file
// 3) fsync() the temp file
// 4) rename the temp file to the real name
// 5) fsync() the containing directory
std::string tmp_path = params_path + "/.tmp_value_XXXXXX";
int tmp_fd = mkstemp((char*)tmp_path.c_str());
if (tmp_fd < 0) return -1;
int result = -1;
do {
// Write value to temp.
ssize_t bytes_written = HANDLE_EINTR(write(tmp_fd, value, value_size));
if (bytes_written < 0 || (size_t)bytes_written != value_size) {
result = -20;
break;
}
// fsync to force persist the changes.
if ((result = fsync(tmp_fd)) < 0) break;
FileLock file_lock(params_path + "/.lock", LOCK_EX);
std::lock_guard<FileLock> lk(file_lock);
// Move temp into place.
std::string path = params_path + "/d/" + std::string(key);
if ((result = rename(tmp_path.c_str(), path.c_str())) < 0) break;
// fsync parent directory
path = params_path + "/d";
result = fsync_dir(path.c_str());
} while (false);
close(tmp_fd);
::unlink(tmp_path.c_str());
return result;
}
int Params::remove(const char *key) {
FileLock file_lock(params_path + "/.lock", LOCK_EX);
std::lock_guard<FileLock> lk(file_lock);
// Delete value.
std::string path = params_path + "/d/" + key;
int result = ::remove(path.c_str());
if (result != 0) {
result = ERR_NO_VALUE;
return result;
}
// fsync parent directory
path = params_path + "/d";
return fsync_dir(path.c_str());
}
std::string Params::get(const char *key, bool block) {
std::string path = params_path + "/d/" + key;
if (!block) {
return util::read_file(path);
} else {
// blocking read until successful
params_do_exit = 0;
void (*prev_handler_sigint)(int) = std::signal(SIGINT, params_sig_handler);
void (*prev_handler_sigterm)(int) = std::signal(SIGTERM, params_sig_handler);
std::string value;
while (!params_do_exit) {
if (value = util::read_file(path); !value.empty()) {
break;
}
util::sleep_for(100); // 0.1 s
}
std::signal(SIGINT, prev_handler_sigint);
std::signal(SIGTERM, prev_handler_sigterm);
return value;
}
}
std::map<std::string, std::string> Params::readAll() {
FileLock file_lock(params_path + "/.lock", LOCK_SH);
std::lock_guard<FileLock> lk(file_lock);
std::string key_path = params_path + "/d";
return util::read_files_in_dir(key_path);
}
void Params::clearAll(ParamKeyType key_type) {
for (auto &[key, type] : keys) {
if (type & key_type) {
remove(key);
}
}
}
|
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <cstdlib>
#include <errno.h>
#include <sys/wait.h>
#include <string.h>
#include <vector>
#include <string>
#include <sys/types.h>
#include <pwd.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
using namespace std;
vector<int> conn_order;
int words = 0;
static int *flag;
/*
* POSTCONDITION: Prints the username and hostname, if possible.
*/
void userInfo() {
char machine[100];
cout << endl;
struct passwd *password = getpwuid(getuid());
if (password == NULL) {
perror("getpwuid");
}
int hostname = gethostname(machine, 64);
if (hostname == -1) {
perror("gethostname");
}
if (password != NULL && hostname != -1) {
string username = password->pw_name;
cout << username << "@" << machine << " ";
}
cout << "$ ";
}
/*
* POSTCONDITION: Prints the username and hostname, if possible.
* OUTPUT: a string of chars with all commands.
*/
char *getCommands() {
string commandLine;
getline(cin, commandLine);
if (commandLine == "exit") exit(0);
char *commands = new char [commandLine.size() + 1];
strcpy(commands, commandLine.c_str());
return commands;
}
/*
* INPUT: char *cmd - holds a command.
* OUTPUT: True if it's a comment, or false if it's not.
*/
bool isComment(char *cmd) {
if (cmd[0] == '#') return true;
return false;
}
/*
* INPUT: char *cmd - holds a command.
* OUTPUT: The size of the command.
*/
size_t cmdSize(char *cmd) {
return strlen(cmd);
}
/*
* POSTCONDITION: Remove the comments from the command line.
*/
void tok_comment(char *cmd) {
cmd = strtok(cmd, "#");
}
/*
* INPUT: char *cmd - holds a command without comments already
* POSTCONDITION: Loops inside of the command line, char by char and
* pushes back some labels into a vector, whose value depends
* on the connector found.
*/
void read_order(char *cmd) {
for (int i = 0; cmd[i] != '\0'; ++i) {
if (cmd[i] == ';') {
conn_order.push_back(1);
}
else if (cmd[i] == '&' && cmd[i + 1] == '&') {
conn_order.push_back(2);
++i;
}
else if (cmd[i] == '|' && cmd[i + 1] == '|') {
conn_order.push_back(3);
++i;
}
}
}
/*
* INPUT:
* char **cmdlist - array of strings which will carry each individual command with its respective arguments;
* char *cmd - holds a command line that can have many other commands chained together using the "&& || ;" operators
* OUTPUT: The number of "argument-lines".
* POSTCONDITION: Everytime that the connectos "&& || ;" be found
* cmdline[x] will have that command and the number of commands will be increased by 1.
*/
int tok_conn(char **cmdlist, char *cmd) {
int argc = 0;
cmdlist[argc] = strtok(cmd, ";&|");
while(cmdlist[argc] != NULL) {
++argc;
cmdlist[argc] = strtok(NULL, ";&|");
}
return argc;
}
/*
* INPUT: char *cmd - holds a command.
* OUTPUT: True if it's exit, or false if it's not.
*/
bool isExit(char *c) {
if (!strcmp(c, "exit")) {
//cout << "BYE!" << endl;
return true;
}
return false;
}
/*
* INPUT: **cmdlist - holds the lines with commands whose connectors were tokenized.
* int size - value is the number of arguments calculated to exist between all connectors.
* POSTCONDITION: Loops inside the function tokenizing an entire argument line's
* white space and organizes those tokens to be executed with 'execvp()'
*/
void tok_space (char **cmdlist, int size) {
int curr = 0;
unsigned index = 0;
char **temp = new char *[size + 1];
while (curr != size) {
int argc = 0;
temp[argc] = strtok(cmdlist[curr], " ");
while (temp[argc] != NULL) {
if (isExit(temp[argc])) {
exit(0);
}
++argc;
temp[argc] = strtok(NULL, " ");
}
argc = 0;
int pid = fork();
if (pid == -1) {
perror("fork");
}
else if (pid == 0) {
int ret = execvp(temp[argc], temp);
if (ret == -1) {
perror("execvp");
}
exit(1);
}
else {
int ret;
waitpid(pid, &ret, 0);
if (conn_order.size() > 0 && index < conn_order.size()) {
if (ret != 0) {
if (conn_order.at(index) == 2) {
return;
}
++index;
}
else {
if (conn_order.at(index) == 3) {
return;
}
++index;
}
}
++curr;
}
}
}
char *addSpaces(char *cmd) {
string line = string(cmd);
for (unsigned int l = 0; l < line.length(); l++) {
if (line[l]== '<' && line[l + 1] != '<') {
line.insert(l + 1, " ");
line.insert(l, " ");
l++;
}
if (line[l]== '>' && line[l + 1]!= '>') {
line.insert(l + 1, " ");
if (!isdigit(line[l-1])) {
line.insert(l, " ");
l++;
}
}
if (line[l]== '>' && line[l + 1] == '>') {
line.insert(l + 2, " ");
l = l + 2;
}
if (line[l]== '<' && line[l + 1] == '<' && line[l + 2] == '<') {
line.insert(l + 3, " ");
line.insert(l, " ");
l = l + 3;
}
if (line[l]== '|' && line[l + 1] != '|') {
line.insert(l + 1, " ");
line.insert(l, " ");
l++;
}
}
char *spaceCmd = new char[line.length() + 1];
strcpy(spaceCmd,line.c_str());
return spaceCmd;
}
void execute (char *cmd) {
read_order(cmd);
char **cmdlist = new char *[cmdSize(cmd) + 1];
int list_size = tok_conn(cmdlist, cmd);
tok_space(cmdlist, list_size);
}
//function recieves commands and arguments before '>' and file to be output
void out_redirect(char *cpystr[], char *file_out, bool symbol, int fd_number) {
for (int i =0; i<3; i++) {
}
int fdo;
//open file descriptor as the argument after '>'
if (symbol) {
fdo = open(file_out, O_RDWR|O_CREAT|O_APPEND, 0666);
if (fdo == -1) {
perror("open");
exit(1);
}
}
else{
fdo = open(file_out, O_RDWR|O_CREAT, 0666);
if (fdo == -1) {
perror("open");
exit(1);
}
}
if (fd_number!=0) {
if (dup2(fdo,fd_number) == -1) {
perror("dup");
exit(1);
}
}
if (execvp(cpystr[0], cpystr) == -1)
perror("execvp");
}
//function recieves commands before '<' and file to be input
void in_redirect(char * cpystr[], char * file_in) {
int fdi;
fdi = open(file_in, O_RDONLY);
if (fdi == -1) {
perror("open");
exit(1);
}
if (dup2(fdi,0) == -1) {
perror("dup");
exit(1);
}
if (execvp(cpystr[0], cpystr) == -1)
perror("execvp 'in' failed");
}
void in_redirect2(char * cpystr[], int pos, char * str[], int size) {
if (memcmp(str[pos+1], "\"", 1) == 0) {
int fd[3];
if (pipe(fd)==-1) {
perror("pipe");
exit(1);
}
unsigned long len = strlen(str[size-1]) -1;
//removing quote marks
memmove(&str[pos+1][0], &str[pos+1][0 + 1], strlen(str[pos+1]));
memmove(&str[size-1][len], &str[size-1][len+1], strlen(str[size-1]) - len);
//add all the string after '<<<'
for (int i=pos+1; i<size; i++) {
if (-1 == write(fd[1],str[i],strlen(str[i]))) {
perror("write");
}
if (-1 == write(fd[1]," ",1)) {
perror("write");
}
}
if (-1 == write(fd[1],"\n",1)) {
perror("write");
}
if (dup2(fd[0],0) == -1) {
perror("dup");
exit(1);
}
if (close(fd[1]) == -1) {
perror("close");
}
if (execvp(cpystr[0], cpystr) == -1)
perror("execvp 'in' failed");
}
else if (size == 3) cout << str[pos+1] << endl;
else cout << "ERROR: no such file or directory" << endl;
}
//working
int checkpipe(char *str[], int size) {
for (int i = 0; i < size; i++) {
if (memcmp(str[i], "|\0", 2) == 0) {
//cout << str[i] << " Pipe found in: " << i << endl;
return i;
}
}
return -1;
}
int checkless(char *str[], int size) {
for (int i=0; i<size; i++) {
if (memcmp(str[i], "<\0", 2) == 0) {
return i;
}
}
return -1;
}
void redirect(char * str[], int size) {
int i, j;
char * cpystr[512];
for (i = 0;i < size; i++) {
if (*flag != 14)
*flag = 0;
int aux = 0;
for (j = i; j < size; j++) {
if (memcmp(str[j], "<\0", 2) == 0) {
*flag = 6;
//cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], ">\0", 2) == 0) {
*flag = 7;
//cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], ">>\0", 3) == 0) {
*flag = 8;
//cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], "|\0", 2) == 0) {
*flag = 9;
//cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], "<<<\0", 4) == 0) {
*flag = 10;
//cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], "2>\0", 3) == 0) {
*flag = 11;
cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], "2>>\0", 4) == 0) {
*flag = 12;
cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], "1>\0", 3) == 0) {
*flag = 7;
//cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], "1>>\0", 4) == 0) {
*flag = 8;
//cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], "0>", 2) == 0) {
*flag = 13;
//cout << "Flag :" << *flag << endl;
i = j;
break;
}
cpystr[aux] = str[j];
aux++;
i = j;
}
cpystr[aux] = (char*)'\0';
aux++;
int pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
}
else if (pid == 0) {
if (*flag == 6)in_redirect(cpystr, str[j+1]);
else if (*flag == 7)out_redirect(cpystr, str[j+1], false, 1);
else if (*flag == 8)out_redirect(cpystr, str[j+1], true, 1);
else if (*flag == 14) {
if (execvp(cpystr[0], cpystr) == -1) {
perror("execvp");
}
}
else if (*flag == 10) in_redirect2(cpystr, i, str, size);
else if (*flag == 11) out_redirect(cpystr, str[j+1],false, 2);
else if (*flag == 12) out_redirect(cpystr, str[j+1],true, 2);
else if (*flag == 13) out_redirect(cpystr, str[j+1],true, 0);
exit(1);
}
else if (pid > 0) {
int status;
wait(&status);
if (-1 == status) {
perror("wait");
}
}
// clear cpystr in order to execute + commands
memset(&cpystr[0], 0, sizeof(cpystr));
}
}
void piping(int index, int size, char *str[]) {
char *cpystr[256];
char *restof_str[256];
int end = 0;
int restof_size = 0;
//add whatever is before | to string
for (int i = 0; i < index; i++) {
cpystr[i] = str[i];
end = i;
}
cpystr[end+1] = (char *)'\0';
//add what ever is after the first | to string
for (int i = index+1; i < size; i++) {
restof_str[restof_size] = str[i];
restof_size++;
}
restof_str[restof_size+1] = (char*)'\0';
int fd[2];
if (pipe(fd)==-1) {
perror ("pipe");
exit(1);
}
int pid = fork();
if (pid == -1) {
perror("fork");
}
else if (pid == 0) {
// child doesn't read
if (close(fd[0]) == -1) {
perror("close");
}
// redirect stdout
if (dup2(fd[1],1) == -1) {
perror("dup");
}
int check = checkless(cpystr, end);
if (check == -1) {
if (-1 == execvp(cpystr[0], cpystr)) {
perror("execvp");
}
}
else {
//if line has pipes but start with redirection <
redirect(cpystr, end);
}
exit(1);
}
else {
int c_in = dup(0);
if (c_in == -1) {
perror("Dup failed.");
}
// parent doesn't write
if (close(fd[1]) == -1) {
perror("Close failed.");
}
// redirect stdin
if (dup2(fd[0],0) == -1) {
perror("Dup failed.");
}
if (wait(0) == -1) {
perror("Wait failed");
}
//look for + pipe
int chain = checkpipe(restof_str, restof_size);
if (chain != -1) {
//execute next pipe command
piping(chain, restof_size, restof_str);
}
else {
//if no more pipes
*flag = 14;
redirect(restof_str, restof_size);
}
if (dup2(c_in,0) == -1) {
perror("Dup failed.");
}
cout << flush;
cin.clear();
}
}
//works
int checkProcedure(char *str[], int size) {
for (int i = 0; i < size; i++) {
if (memcmp(str[i], "|\0", 2) == 0) {
//cout << "Procedure to | " << endl;
return 1;
}
if (memcmp(str[i], "<", 1) == 0) {
//cout << "Procedure to < " << endl;
return 1;
}
if (memcmp(str[i], ">", 1) == 0) {
//cout << "Procedure to > " << endl;
return 1;
}
if (memcmp(str[i], "2>", 2) == 0) {
//cout << "Procedure to 2> " << endl;
return 1;
}
if (memcmp(str[i], "1>", 2) == 0) {
//cout << "Procedure to 1> " << endl;
return 1;
}
if (memcmp(str[i], "0>", 2) == 0) {
//cout << "Procedure to 0> " << endl;
return 1;
}
}
return 0;
}
int main()
{
while(1) {
userInfo();
char *cmd = getCommands();
if (!isComment(cmd)) {
tok_comment(cmd);
if (memcmp(cmd, "exit", 4) == 0) exit(0);
//cout << cmd << " Cmd" << endl;
char *cmdSpaced = addSpaces(cmd); //copy with spaces when occur appearence of | or < >
//cout << cmdSpaced << " CmdSpaced" << endl;
int index = 0;
char *str[512];
char *pch = strtok(cmdSpaced, " ");
while (pch != NULL) {
str[index] = pch;
cout << str[index] << " index: " << index << endl;
pch = strtok(NULL, " ");
index++;
}
str[index] = NULL;
//create a shared memory to be accessed from child and process
//flag = (int*)mmap(NULL, sizeof *flag, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); in mac is MAP_ANON
flag = (int*)mmap(NULL, sizeof *flag, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
int pos = checkpipe(str, index);
if (pos != -1) {
//cout << "POS == -1" << endl;
piping(pos, index, str);
}
else if (checkProcedure(str, index)){
//cout << "CHECKPROCEDURE" << endl;
redirect(str, index);
}
else {
execute(cmd);
//cout << " CMD NORMAL" << endl;
}
}
conn_order.clear();
}
return 0;
}
Update hw0.cpp
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <cstdlib>
#include <errno.h>
#include <sys/wait.h>
#include <string.h>
#include <vector>
#include <string>
#include <sys/types.h>
#include <pwd.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
using namespace std;
#ifndef MAP_ANONYMOUS
#define MAP_ANONYMOUS MAP_ANON //in mac is MAP_ANON
#endif
vector<int> conn_order;
int words = 0;
static int *flag;
/*
* POSTCONDITION: Prints the username and hostname, if possible.
*/
void userInfo() {
char machine[100];
cout << endl;
struct passwd *password = getpwuid(getuid());
if (password == NULL) {
perror("getpwuid");
}
int hostname = gethostname(machine, 64);
if (hostname == -1) {
perror("gethostname");
}
if (password != NULL && hostname != -1) {
string username = password->pw_name;
cout << username << "@" << machine << " ";
}
cout << "$ ";
}
/*
* POSTCONDITION: Prints the username and hostname, if possible.
* OUTPUT: a string of chars with all commands.
*/
char *getCommands() {
string commandLine;
getline(cin, commandLine);
if (commandLine == "exit") exit(0);
char *commands = new char [commandLine.size() + 1];
strcpy(commands, commandLine.c_str());
return commands;
}
/*
* INPUT: char *cmd - holds a command.
* OUTPUT: True if it's a comment, or false if it's not.
*/
bool isComment(char *cmd) {
if (cmd[0] == '#') return true;
return false;
}
/*
* INPUT: char *cmd - holds a command.
* OUTPUT: The size of the command.
*/
size_t cmdSize(char *cmd) {
return strlen(cmd);
}
/*
* POSTCONDITION: Remove the comments from the command line.
*/
void tok_comment(char *cmd) {
cmd = strtok(cmd, "#");
}
/*
* INPUT: char *cmd - holds a command without comments already
* POSTCONDITION: Loops inside of the command line, char by char and
* pushes back some labels into a vector, whose value depends
* on the connector found.
*/
void read_order(char *cmd) {
for (int i = 0; cmd[i] != '\0'; ++i) {
if (cmd[i] == ';') {
conn_order.push_back(1);
}
else if (cmd[i] == '&' && cmd[i + 1] == '&') {
conn_order.push_back(2);
++i;
}
else if (cmd[i] == '|' && cmd[i + 1] == '|') {
conn_order.push_back(3);
++i;
}
}
}
/*
* INPUT:
* char **cmdlist - array of strings which will carry each individual command with its respective arguments;
* char *cmd - holds a command line that can have many other commands chained together using the "&& || ;" operators
* OUTPUT: The number of "argument-lines".
* POSTCONDITION: Everytime that the connectos "&& || ;" be found
* cmdline[x] will have that command and the number of commands will be increased by 1.
*/
int tok_conn(char **cmdlist, char *cmd) {
int argc = 0;
cmdlist[argc] = strtok(cmd, ";&|");
while(cmdlist[argc] != NULL) {
++argc;
cmdlist[argc] = strtok(NULL, ";&|");
}
return argc;
}
/*
* INPUT: char *cmd - holds a command.
* OUTPUT: True if it's exit, or false if it's not.
*/
bool isExit(char *c) {
if (!strcmp(c, "exit")) {
//cout << "BYE!" << endl;
return true;
}
return false;
}
/*
* INPUT: **cmdlist - holds the lines with commands whose connectors were tokenized.
* int size - value is the number of arguments calculated to exist between all connectors.
* POSTCONDITION: Loops inside the function tokenizing an entire argument line's
* white space and organizes those tokens to be executed with 'execvp()'
*/
void tok_space (char **cmdlist, int size) {
int curr = 0;
unsigned index = 0;
char **temp = new char *[size + 1];
while (curr != size) {
int argc = 0;
temp[argc] = strtok(cmdlist[curr], " ");
while (temp[argc] != NULL) {
if (isExit(temp[argc])) {
exit(0);
}
++argc;
temp[argc] = strtok(NULL, " ");
}
argc = 0;
int pid = fork();
if (pid == -1) {
perror("fork");
}
else if (pid == 0) {
int ret = execvp(temp[argc], temp);
if (ret == -1) {
perror("execvp");
}
exit(1);
}
else {
int ret;
waitpid(pid, &ret, 0);
if (conn_order.size() > 0 && index < conn_order.size()) {
if (ret != 0) {
if (conn_order.at(index) == 2) {
return;
}
++index;
}
else {
if (conn_order.at(index) == 3) {
return;
}
++index;
}
}
++curr;
}
}
}
char *addSpaces(char *cmd) {
string line = string(cmd);
for (unsigned int l = 0; l < line.length(); l++) {
if (line[l]== '<' && line[l + 1] != '<') {
line.insert(l + 1, " ");
line.insert(l, " ");
l++;
}
if (line[l]== '>' && line[l + 1]!= '>') {
line.insert(l + 1, " ");
if (!isdigit(line[l-1])) {
line.insert(l, " ");
l++;
}
}
if (line[l]== '>' && line[l + 1] == '>') {
line.insert(l + 2, " ");
l = l + 2;
}
if (line[l]== '<' && line[l + 1] == '<' && line[l + 2] == '<') {
line.insert(l + 3, " ");
line.insert(l, " ");
l = l + 3;
}
if (line[l]== '|' && line[l + 1] != '|') {
line.insert(l + 1, " ");
line.insert(l, " ");
l++;
}
}
char *spaceCmd = new char[line.length() + 1];
strcpy(spaceCmd,line.c_str());
return spaceCmd;
}
void execute (char *cmd) {
read_order(cmd);
char **cmdlist = new char *[cmdSize(cmd) + 1];
int list_size = tok_conn(cmdlist, cmd);
tok_space(cmdlist, list_size);
}
//function recieves commands and arguments before '>' and file to be output
void out_redirect(char *cpystr[], char *file_out, bool symbol, int fd_number) {
for (int i =0; i<3; i++) {
}
int fdo;
//open file descriptor as the argument after '>'
if (symbol) {
fdo = open(file_out, O_RDWR|O_CREAT|O_APPEND, 0666);
if (fdo == -1) {
perror("open");
exit(1);
}
}
else{
fdo = open(file_out, O_RDWR|O_CREAT, 0666);
if (fdo == -1) {
perror("open");
exit(1);
}
}
if (fd_number!=0) {
if (dup2(fdo,fd_number) == -1) {
perror("dup");
exit(1);
}
}
if (execvp(cpystr[0], cpystr) == -1)
perror("execvp");
}
//function recieves commands before '<' and file to be input
void in_redirect(char * cpystr[], char * file_in) {
int fdi;
fdi = open(file_in, O_RDONLY);
if (fdi == -1) {
perror("open");
exit(1);
}
if (dup2(fdi,0) == -1) {
perror("dup");
exit(1);
}
if (execvp(cpystr[0], cpystr) == -1)
perror("execvp 'in' failed");
}
void in_redirect2(char * cpystr[], int pos, char * str[], int size) {
if (memcmp(str[pos+1], "\"", 1) == 0) {
int fd[3];
if (pipe(fd)==-1) {
perror("pipe");
exit(1);
}
unsigned long len = strlen(str[size-1]) -1;
//removing quote marks
memmove(&str[pos+1][0], &str[pos+1][0 + 1], strlen(str[pos+1]));
memmove(&str[size-1][len], &str[size-1][len+1], strlen(str[size-1]) - len);
//add all the string after '<<<'
for (int i=pos+1; i<size; i++) {
if (-1 == write(fd[1],str[i],strlen(str[i]))) {
perror("write");
}
if (-1 == write(fd[1]," ",1)) {
perror("write");
}
}
if (-1 == write(fd[1],"\n",1)) {
perror("write");
}
if (dup2(fd[0],0) == -1) {
perror("dup");
exit(1);
}
if (close(fd[1]) == -1) {
perror("close");
}
if (execvp(cpystr[0], cpystr) == -1)
perror("execvp 'in' failed");
}
else if (size == 3) cout << str[pos+1] << endl;
else cout << "ERROR: no such file or directory" << endl;
}
//working
int checkpipe(char *str[], int size) {
for (int i = 0; i < size; i++) {
if (memcmp(str[i], "|\0", 2) == 0) {
//cout << str[i] << " Pipe found in: " << i << endl;
return i;
}
}
return -1;
}
int checkless(char *str[], int size) {
for (int i=0; i<size; i++) {
if (memcmp(str[i], "<\0", 2) == 0) {
return i;
}
}
return -1;
}
void redirect(char * str[], int size) {
int i, j;
char * cpystr[512];
for (i = 0;i < size; i++) {
if (*flag != 14)
*flag = 0;
int aux = 0;
for (j = i; j < size; j++) {
if (memcmp(str[j], "<\0", 2) == 0) {
*flag = 6;
//cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], ">\0", 2) == 0) {
*flag = 7;
//cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], ">>\0", 3) == 0) {
*flag = 8;
//cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], "|\0", 2) == 0) {
*flag = 9;
//cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], "<<<\0", 4) == 0) {
*flag = 10;
//cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], "2>\0", 3) == 0) {
*flag = 11;
cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], "2>>\0", 4) == 0) {
*flag = 12;
cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], "1>\0", 3) == 0) {
*flag = 7;
//cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], "1>>\0", 4) == 0) {
*flag = 8;
//cout << "Flag :" << *flag << endl;
i = j;
break;
}
if (memcmp(str[j], "0>", 2) == 0) {
*flag = 13;
//cout << "Flag :" << *flag << endl;
i = j;
break;
}
cpystr[aux] = str[j];
aux++;
i = j;
}
cpystr[aux] = (char*)'\0';
aux++;
int pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
}
else if (pid == 0) {
if (*flag == 6)in_redirect(cpystr, str[j+1]);
else if (*flag == 7)out_redirect(cpystr, str[j+1], false, 1);
else if (*flag == 8)out_redirect(cpystr, str[j+1], true, 1);
else if (*flag == 14) {
if (execvp(cpystr[0], cpystr) == -1) {
perror("execvp");
}
}
else if (*flag == 10) in_redirect2(cpystr, i, str, size);
else if (*flag == 11) out_redirect(cpystr, str[j+1],false, 2);
else if (*flag == 12) out_redirect(cpystr, str[j+1],true, 2);
else if (*flag == 13) out_redirect(cpystr, str[j+1],true, 0);
exit(1);
}
else if (pid > 0) {
int status;
wait(&status);
if (-1 == status) {
perror("wait");
}
}
// clear cpystr in order to execute + commands
memset(&cpystr[0], 0, sizeof(cpystr));
}
}
void piping(int index, int size, char *str[]) {
char *cpystr[256];
char *restof_str[256];
int end = 0;
int restof_size = 0;
//add whatever is before | to string
for (int i = 0; i < index; i++) {
cpystr[i] = str[i];
end = i;
}
cpystr[end+1] = (char *)'\0';
//add what ever is after the first | to string
for (int i = index+1; i < size; i++) {
restof_str[restof_size] = str[i];
restof_size++;
}
restof_str[restof_size+1] = (char*)'\0';
int fd[2];
if (pipe(fd)==-1) {
perror ("pipe");
exit(1);
}
int pid = fork();
if (pid == -1) {
perror("fork");
}
else if (pid == 0) {
// child doesn't read
if (close(fd[0]) == -1) {
perror("close");
}
// redirect stdout
if (dup2(fd[1],1) == -1) {
perror("dup");
}
int check = checkless(cpystr, end);
if (check == -1) {
if (-1 == execvp(cpystr[0], cpystr)) {
perror("execvp");
}
}
else {
//if line has pipes but start with redirection <
redirect(cpystr, end);
}
exit(1);
}
else {
int c_in = dup(0);
if (c_in == -1) {
perror("Dup failed.");
}
// parent doesn't write
if (close(fd[1]) == -1) {
perror("Close failed.");
}
// redirect stdin
if (dup2(fd[0],0) == -1) {
perror("Dup failed.");
}
if (wait(0) == -1) {
perror("Wait failed");
}
//look for + pipe
int chain = checkpipe(restof_str, restof_size);
if (chain != -1) {
//execute next pipe command
piping(chain, restof_size, restof_str);
}
else {
//if no more pipes
*flag = 14;
redirect(restof_str, restof_size);
}
if (dup2(c_in,0) == -1) {
perror("Dup failed.");
}
cout << flush;
cin.clear();
}
}
//works
int checkProcedure(char *str[], int size) {
for (int i = 0; i < size; i++) {
if (memcmp(str[i], "|\0", 2) == 0) {
//cout << "Procedure to | " << endl;
return 1;
}
if (memcmp(str[i], "<", 1) == 0) {
//cout << "Procedure to < " << endl;
return 1;
}
if (memcmp(str[i], ">", 1) == 0) {
//cout << "Procedure to > " << endl;
return 1;
}
if (memcmp(str[i], "2>", 2) == 0) {
//cout << "Procedure to 2> " << endl;
return 1;
}
if (memcmp(str[i], "1>", 2) == 0) {
//cout << "Procedure to 1> " << endl;
return 1;
}
if (memcmp(str[i], "0>", 2) == 0) {
//cout << "Procedure to 0> " << endl;
return 1;
}
}
return 0;
}
int main()
{
while(1) {
userInfo();
char *cmd = getCommands();
if (!isComment(cmd)) {
tok_comment(cmd);
if (memcmp(cmd, "exit", 4) == 0) exit(0);
//cout << cmd << " Cmd" << endl;
char *cmdSpaced = addSpaces(cmd); //copy with spaces when occur appearence of | or < >
//cout << cmdSpaced << " CmdSpaced" << endl;
int index = 0;
char *str[512];
char *pch = strtok(cmdSpaced, " ");
while (pch != NULL) {
str[index] = pch;
cout << str[index] << " index: " << index << endl;
pch = strtok(NULL, " ");
index++;
}
str[index] = NULL;
//create a shared memory to be accessed from child and process
flag = (int*)mmap(NULL, sizeof *flag, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
int pos = checkpipe(str, index);
if (pos != -1) {
//cout << "POS == -1" << endl;
piping(pos, index, str);
}
else if (checkProcedure(str, index)){
//cout << "CHECKPROCEDURE" << endl;
redirect(str, index);
}
else {
execute(cmd);
//cout << " CMD NORMAL" << endl;
}
}
conn_order.clear();
}
return 0;
}
|
#include <vector>
#include "AliHLTTRDTracker.h"
#include "AliGeomManager.h"
#include "AliTRDgeometry.h"
#include "TDatabasePDG.h"
#include "TTreeStream.h"
#include "TGeoMatrix.h"
ClassImp(AliHLTTRDTracker)
AliHLTTRDTracker::AliHLTTRDTracker() :
fTracks(0x0),
fNTracks(0),
fNEvents(0),
fTracklets(0x0),
fNtrackletsMax(1000),
fNTracklets(0),
fSpacePoints(0x0),
fTRDgeometry(0x0),
fEnableDebugOutput(false),
fStreamer(0x0)
{
for (int iDet=0; iDet<540; ++iDet) {
fTrackletIndexArray[iDet][0] = -1;
fTrackletIndexArray[iDet][1] = 0;
}
//Default constructor
}
AliHLTTRDTracker::AliHLTTRDTracker(const AliHLTTRDTracker &tracker) :
fTracks(0x0),
fNTracks(0),
fNEvents(0),
fTracklets(0x0),
fNtrackletsMax(1000),
fNTracklets(0),
fSpacePoints(0x0),
fTRDgeometry(0x0),
fEnableDebugOutput(false),
fStreamer(0x0)
{
//Copy constructor
//Dummy!
for (int iDet=0; iDet<540; ++iDet) {
fTrackletIndexArray[iDet][0] = tracker.fTrackletIndexArray[iDet][0];
fTrackletIndexArray[iDet][1] = tracker.fTrackletIndexArray[iDet][1];
}
}
AliHLTTRDTracker & AliHLTTRDTracker::operator=(const AliHLTTRDTracker &tracker){
//Assignment operator
this->~AliHLTTRDTracker();
new(this) AliHLTTRDTracker(tracker);
return *this;
}
AliHLTTRDTracker::~AliHLTTRDTracker()
{
//Destructor
delete[] fTracklets;
delete[] fTracks;
delete[] fSpacePoints;
delete fTRDgeometry;
if (fEnableDebugOutput) {
delete fStreamer;
}
}
void AliHLTTRDTracker::Init()
{
fTracklets = new AliHLTTRDTrackletWord[fNtrackletsMax];
fSpacePoints = new AliHLTTRDSpacePointInternal[fNtrackletsMax];
fTRDgeometry = new AliTRDgeometry();
if (!fTRDgeometry) {
Error("Init", "TRD geometry could not be loaded\n");
}
if (fEnableDebugOutput) {
fStreamer = new TTreeSRedirector("debug.root", "recreate");
}
}
void AliHLTTRDTracker::Reset()
{
fNTracklets = 0;
for (int i=0; i<fNtrackletsMax; ++i) {
fTracklets[i] = 0x0;
fSpacePoints[i].fX[0] = 0.;
fSpacePoints[i].fX[1] = 0.;
fSpacePoints[i].fX[2] = 0.;
fSpacePoints[i].fId = 0;
fSpacePoints[i].fVolumeId = 0;
}
for (int iDet=0; iDet<540; ++iDet) {
fTrackletIndexArray[iDet][0] = -1;
fTrackletIndexArray[iDet][1] = 0;
}
}
void AliHLTTRDTracker::StartLoadTracklets(const int nTrklts)
{
if (nTrklts > fNtrackletsMax) {
delete[] fTracklets;
delete[] fSpacePoints;
fNtrackletsMax += nTrklts - fNtrackletsMax;
fTracklets = new AliHLTTRDTrackletWord[fNtrackletsMax];
fSpacePoints = new AliHLTTRDSpacePointInternal[fNtrackletsMax];
}
}
void AliHLTTRDTracker::LoadTracklet(const AliHLTTRDTrackletWord &tracklet)
{
if (fNTracklets >= fNtrackletsMax ) {
Error("LoadTracklet", "running out of memory for tracklets, skipping tracklet(s). This should actually never happen.\n");
return;
}
fTracklets[fNTracklets++] = tracklet;
fTrackletIndexArray[tracklet.GetDetector()][1]++;
}
void AliHLTTRDTracker::DoTracking( AliExternalTrackParam *tracksTPC, int *tracksTPCLab, int nTPCTracks )
{
//--------------------------------------------------------------------
// This functions reconstructs TRD tracks
// using TPC tracks as seeds
//--------------------------------------------------------------------
fNEvents++;
// sort tracklets and fill index array
std::sort(fTracklets, fTracklets + fNTracklets);
int trkltCounter = 0;
for (int iDet=0; iDet<540; ++iDet) {
if (fTrackletIndexArray[iDet][1] != 0) {
fTrackletIndexArray[iDet][0] = trkltCounter;
trkltCounter += fTrackletIndexArray[iDet][1];
}
}
// test the correctness of the tracklet index array
// this can be deleted later...
if (!IsTrackletSortingOk()) {
Error("DoTracking", "bug in tracklet index array\n");
}
CalculateSpacePoints();
delete[] fTracks;
fNTracks = 0;
fTracks = new AliHLTTRDTrack[nTPCTracks];
double piMass = TDatabasePDG::Instance()->GetParticle(211)->Mass(); // pion mass as best guess for all particles
for (int i=0; i<nTPCTracks; ++i) {
AliHLTTRDTrack tMI(tracksTPC[i]);
AliHLTTRDTrack *t = &tMI;
t->SetTPCtrackId(i);
t->SetLabel(0); // use for monte carlo tracks later TODO: set correct label
t->SetMass(piMass);
int result = FollowProlongation(t, piMass);
t->SetNtracklets(result);
fTracks[fNTracks++] = *t;
double pT = t->Pt();
double alpha = t->GetAlpha();
if (fEnableDebugOutput) {
(*fStreamer) << "tracksFinal" <<
"ev=" << fNEvents <<
"iTrk=" << i <<
"pT=" << pT <<
"alpha=" << alpha <<
"nTrackletsAttached=" << result <<
"track.=" << t <<
"\n";
}
}
if (fEnableDebugOutput) {
(*fStreamer) << "statistics" <<
"nEvents=" << fNEvents <<
"nTrackletsTotal=" << fNTracklets <<
"nTPCtracksTotal=" << nTPCTracks <<
"\n";
}
}
bool AliHLTTRDTracker::IsTrackletSortingOk()
{
int nTrklts = 0;
for (int iDet=0; iDet<540; iDet++) {
for (int iTrklt=0; iTrklt<fTrackletIndexArray[iDet][1]; iTrklt++) {
++nTrklts;
int detTracklet = fTracklets[fTrackletIndexArray[iDet][0]+iTrklt].GetDetector();
if (iDet != detTracklet) {
return false;
}
}
}
if (nTrklts != fNTracklets) {
return false;
}
return true;
}
void AliHLTTRDTracker::CalculateSpacePoints()
{
//--------------------------------------------------------------------
// This functions calculates the TRD space points
// in sector tracking coordinates for all tracklets
//--------------------------------------------------------------------
for (int iDet=0; iDet<540; ++iDet) {
int layer = fTRDgeometry->GetLayer(iDet);
int stack = fTRDgeometry->GetStack(iDet);
int nTracklets = fTrackletIndexArray[iDet][1];
if (nTracklets == 0) {
continue;
}
TGeoHMatrix *matrix = fTRDgeometry->GetClusterMatrix(iDet);
if (!matrix){
Error("CalculateSpacePoints", "invalid TRD cluster matrix, skipping detector %i\n", iDet);
continue;
}
AliTRDpadPlane *padPlane = fTRDgeometry->GetPadPlane(layer, stack);
for (int iTrklt=0; iTrklt<nTracklets; ++iTrklt) {
int trkltIdx = fTrackletIndexArray[iDet][0] + iTrklt;
double xTrklt[3] = { 0. };
xTrklt[0] = AliTRDgeometry::AnodePos();
xTrklt[1] = fTracklets[trkltIdx].GetY();
if (stack == 2) {
xTrklt[2] = padPlane->GetRowPos(fTracklets[trkltIdx].GetZbin()) - (padPlane->GetRowSize(fTracklets[trkltIdx].GetZbin()))/2. - padPlane->GetRowPos(6);
}
else {
xTrklt[2] = padPlane->GetRowPos(fTracklets[trkltIdx].GetZbin()) - (padPlane->GetRowSize(fTracklets[trkltIdx].GetZbin()))/2. - padPlane->GetRowPos(8);
}
matrix->LocalToMaster(xTrklt, fSpacePoints[trkltIdx].fX);
fSpacePoints[trkltIdx].fId = fTracklets[trkltIdx].GetId();
AliGeomManager::ELayerID iLayer = AliGeomManager::ELayerID(AliGeomManager::kTRD1+fTRDgeometry->GetLayer(iDet));
int modId = fTRDgeometry->GetSector(iDet) * AliTRDgeometry::kNstack + fTRDgeometry->GetStack(iDet);
unsigned short volId = AliGeomManager::LayerToVolUID(iLayer, modId);
fSpacePoints[trkltIdx].fVolumeId = volId;
}
}
}
int AliHLTTRDTracker::FollowProlongation(AliHLTTRDTrack *t, double mass)
{
//--------------------------------------------------------------------
// This function propagates found tracks with pT > 1.0 GeV
// through the TRD and picks up the closest tracklet in each
// layer on the way.
// returns variable result = number of assigned tracklets
//--------------------------------------------------------------------
int result = 0;
int iTrack = t->GetTPCtrackId(); // for debugging individual tracks
// introduce momentum cut on tracks
// particles with pT < 0.9 GeV highly unlikely to have matching online TRD tracklets
if (t->Pt() < 1.0) {
return result;
}
// define some constants
const int nSector = fTRDgeometry->Nsector();
const int nStack = fTRDgeometry->Nstack();
const int nLayer = fTRDgeometry->Nlayer();
AliTRDpadPlane *pad = 0x0;
// the vector det holds the numbers of the detectors which are searched for tracklets
std::vector<int> det;
std::vector<int>::iterator iDet;
for (int iLayer=0; iLayer<nLayer; ++iLayer) {
det.clear();
// where the trackl initially ends up
int initialStack = -1;
int initialSector = -1;
int detector = -1;
pad = fTRDgeometry->GetPadPlane(iLayer, 0);
const float zMaxTRD = pad->GetRowPos(0);
const float yMax = pad->GetColPos(143) + pad->GetColSize(143);
const float xLayer = fTRDgeometry->GetTime0(iLayer);
if (!PropagateTrackToBxByBz(t, xLayer, mass, 5.0 /*max step*/, kFALSE /*rotateTo*/, 0.8 /*maxSnp*/) || (abs(t->GetZ()) >= (zMaxTRD + 10.)) ) {
return result;
}
// rotate track in new sector in case of sector crossing
if (!AdjustSector(t)) {
return result;
}
// debug purposes only -> store track information
double sigmaY = TMath::Sqrt(t->GetSigmaY2());
double sigmaZ = TMath::Sqrt(t->GetSigmaZ2());
AliExternalTrackParam param(*t);
if (fEnableDebugOutput) {
(*fStreamer) << "trackInfoLayerwise" <<
"iEv=" << fNEvents <<
"iTrk=" << iTrack <<
"layer=" << iLayer <<
"sigmaY=" << sigmaY <<
"sigmaZ=" << sigmaZ <<
"nUpdates=" << result <<
"track.=" << ¶m <<
"\n";
}
// determine initial chamber where the track ends up
// add more chambers of the same sector if track is close to edge of the chamber
detector = GetDetectorNumber(t->GetZ(), t->GetAlpha(), iLayer);
if (detector != -1) {
det.push_back(detector);
initialStack = fTRDgeometry->GetStack(detector);
initialSector = fTRDgeometry->GetSector(detector);
AliTRDpadPlane *padTmp = fTRDgeometry->GetPadPlane(iLayer, initialStack);
int lastPadRow = -1;
float zCenter = 0.;
if (initialStack == 2) {
lastPadRow = 11;
zCenter = padTmp->GetRowPos(6);
}
else {
lastPadRow = 15;
zCenter = padTmp->GetRowPos(8);
}
if ( t->GetZ() > (padTmp->GetRowPos(0) - 10.) || t->GetZ() < (padTmp->GetRowPos(lastPadRow) + 10) ) {
if ( !(initialStack == 0 && t->GetZ() > 0) && !(initialStack == nStack-1 && t->GetZ() < 0) ) {
// track not close to outer end of TRD -> add neighbouring stack
if (t->GetZ() > zCenter) {
det.push_back(fTRDgeometry->GetDetector(iLayer, initialStack-1, initialSector));
}
else {
det.push_back(fTRDgeometry->GetDetector(iLayer, initialStack+1, initialSector));
}
}
}
}
else {
if (TMath::Abs(t->GetZ()) > zMaxTRD) {
t->GetZ() > 0 ? // shift track in z so it is in the TRD acceptance
detector = GetDetectorNumber(t->GetZ()-10., t->GetAlpha(), iLayer) :
detector = GetDetectorNumber(t->GetZ()+10., t->GetAlpha(), iLayer);
if (detector != -1) {
det.push_back(detector);
initialStack = fTRDgeometry->GetStack(detector);
initialSector = fTRDgeometry->GetSector(detector);
}
else {
Error("FollowProlongation", "outer detector cannot be found although track %i was shifted in z", iTrack);
return result;
}
}
else {
// track in between two stacks, add both surrounding chambers
detector = GetDetectorNumber(t->GetZ()+4.0, t->GetAlpha(), iLayer);
if (detector != -1) {
det.push_back(detector);
initialStack = fTRDgeometry->GetStack(detector);
initialSector = fTRDgeometry->GetSector(detector);
}
else {
Error("FollowProlongation", "detector cannot be found although track %i was shifted in positive z", iTrack);
return result;
}
detector = GetDetectorNumber(t->GetZ()-4.0, t->GetAlpha(), iLayer);
if (detector != -1) {
det.push_back(detector);
}
else {
Error("FollowProlongation", "detector cannot be found although track %i was shifted in negative z", iTrack);
return result;
}
}
}
// add chamber(s) from neighbouring sector in case the track is close to the boundary
if ( TMath::Abs(t->GetY()) > (yMax - 10.) ) {
const int nStacksToSearch = det.size();
for (int idx = 0; idx < nStacksToSearch; ++idx) {
int currStack = fTRDgeometry->GetStack(det.at(idx));
if (t->GetY() > 0) {
int newSector = initialSector + 1;
if (newSector == nSector) {
newSector = 0;
}
det.push_back(fTRDgeometry->GetDetector(iLayer, currStack, newSector));
}
else {
int newSector = initialSector - 1;
if (newSector == -1) {
newSector = nSector - 1;
}
det.push_back(fTRDgeometry->GetDetector(iLayer, currStack, newSector));
}
}
}
if (fEnableDebugOutput) {
int nDetToSearch = det.size();
(*fStreamer) << "chambersToSearch" <<
"nChambers=" << nDetToSearch <<
"layer=" << iLayer <<
"iEv=" << fNEvents <<
"\n";
}
// define search window for tracklets
double deltaY = 7. * TMath::Sqrt(t->GetSigmaY2() + TMath::Power(0.03, 2)) + 2; // add constant to the road for better efficiency
double deltaZ = 7. * TMath::Sqrt(t->GetSigmaZ2() + TMath::Power(9./TMath::Sqrt(12), 2));
if (fEnableDebugOutput) {
(*fStreamer) << "searchWindow" <<
"layer=" << iLayer <<
"dY=" << deltaY <<
"dZ=" << deltaZ <<
"\n";
}
// look for tracklets in chamber(s)
double bestGuessChi2 = 100.; // TODO define meaningful chi2 cut
int bestGuessIdx = -1;
int bestGuessDet = -1;
double p[2] = { 0. };
double cov[3] = { 0. };
bool wasTrackRotated = false;
for (iDet = det.begin(); iDet != det.end(); ++iDet) {
int detToSearch = *iDet;
int stackToSearch = detToSearch / nLayer; // global stack number
int sectorToSearch = fTRDgeometry->GetSector(detToSearch);
if (sectorToSearch != initialSector && !wasTrackRotated) {
float alphaToSearch = 2.0 * TMath::Pi() / (float) nSector * ((float) sectorToSearch + 0.5);
t->Rotate(alphaToSearch);
wasTrackRotated = true; // tracks need to be rotated max once per layer
}
for (int iTrklt=0; iTrklt<fTrackletIndexArray[detToSearch][1]; ++iTrklt) {
int trkltIdx = fTrackletIndexArray[detToSearch][0] + iTrklt;
if ((fSpacePoints[trkltIdx].fX[1] < t->GetY() + deltaY) && (fSpacePoints[trkltIdx].fX[1] > t->GetY() - deltaY) &&
(fSpacePoints[trkltIdx].fX[2] < t->GetZ() + deltaZ) && (fSpacePoints[trkltIdx].fX[2] > t->GetZ() - deltaZ))
{
//tracklet is in windwow: get predicted chi2 for update and store tracklet index if best guess
p[0] = fSpacePoints[trkltIdx].fX[1];
p[1] = fSpacePoints[trkltIdx].fX[2];
if (TMath::Abs(p[0]) > 1000) {
Error("FollowProlongation", "impossible y-value of tracklet: y=%.12f\n", p[0]);
return result;
}
cov[0] = TMath::Power(0.03, 2);
cov[1] = 0;
cov[2] = TMath::Power(9./TMath::Sqrt(12), 2);
double chi2 = t->GetPredictedChi2(p, cov);
if (chi2 < bestGuessChi2) {
bestGuessChi2 = chi2;
bestGuessIdx = trkltIdx;
bestGuessDet = detToSearch;
}
float dY = t->GetY() - fSpacePoints[trkltIdx].fX[1];
float dZ = t->GetZ() - fSpacePoints[trkltIdx].fX[2];
if (fEnableDebugOutput) {
(*fStreamer) << "residuals" <<
"iEv=" << fNEvents <<
"iTrk=" << iTrack <<
"layer=" << iLayer <<
"iTrklt=" << iTrklt <<
"stack=" << stackToSearch <<
"det=" << detToSearch <<
"dY=" << dY <<
"dZ=" << dZ <<
"\n";
}
if (TMath::Abs(dZ) > 160) {
Error("FollowProlongation", "impossible dZ-value of tracklet: track z = %f, tracklet z = %f, detToSearch = %i\n", t->GetZ(), fSpacePoints[trkltIdx].fX[2], detToSearch);
}
}
}
}
if (bestGuessIdx != -1 ) {
// best matching tracklet found
p[0] = fSpacePoints[bestGuessIdx].fX[1];
p[1] = fSpacePoints[bestGuessIdx].fX[2];
cov[0] = TMath::Power(0.03, 2);
cov[1] = 0;
cov[2] = TMath::Power(9./TMath::Sqrt(12), 2);
t->Update(p, cov);
++result;
}
}
// after propagation, propagate track back to inner radius of TPC
float xInnerParam = 83.65;
if (!PropagateTrackToBxByBz(t, xInnerParam, mass, 5.0 /*max step*/, kFALSE /*rotateTo*/, 0.8 /*maxSnp*/)) {
Warning("FollowProlongation", "Back propagation for track %i failed", iTrack);
return result;
}
// rotate track back in old sector in case of sector crossing
AdjustSector(t);
return result;
}
// helper function for event display -> later not needed anymore
void AliHLTTRDTracker::Rotate(const double alpha, const double * const loc, double *glb)
{
glb[0] = loc[0] * TMath::Cos(alpha) - loc[1] * TMath::Sin(alpha);
glb[1] = loc[0] * TMath::Sin(alpha) + loc[1] * TMath::Cos(alpha);
glb[2] = loc[2];
}
int AliHLTTRDTracker::GetDetectorNumber(const double zPos, double alpha, int layer)
{
int stack = fTRDgeometry->GetStack(zPos, layer);
if (stack < 0) {
Info("GetDetectorNumber", "Stack determination failed for layer %i, z=%f", layer, zPos);
return -1;
}
double alphaTmp = (alpha > 0) ? alpha : alpha + 2. * TMath::Pi();
int sector = 18. * alphaTmp / (2. * TMath::Pi());
return fTRDgeometry->GetDetector(layer, stack, sector);
}
bool AliHLTTRDTracker::AdjustSector(AliHLTTRDTrack *t)
{
// rotate track in new sector if necessary
double alpha = fTRDgeometry->GetAlpha();
double y = t->GetY();
double yMax = t->GetX() * TMath::Tan(0.5 * alpha);
double alphaCurr = t->GetAlpha();
if (TMath::Abs(y) > 2. * yMax) {
Info("AdjustSector", "Track %i with pT = %f crossing two sector boundaries at x = %f\n", t->GetTPCtrackId(), t->Pt(), t->GetX());
return false;
}
if (y > yMax) {
if (!t->Rotate(alphaCurr+alpha)) {
return false;
}
}
else if (y < -yMax) {
if (!t->Rotate(alphaCurr-alpha)) {
return false;
}
}
return true;
}
More verbose debug output for HLT TRD tracker
#include <vector>
#include "AliHLTTRDTracker.h"
#include "AliGeomManager.h"
#include "AliTRDgeometry.h"
#include "TDatabasePDG.h"
#include "TTreeStream.h"
#include "TGeoMatrix.h"
ClassImp(AliHLTTRDTracker)
AliHLTTRDTracker::AliHLTTRDTracker() :
fTracks(0x0),
fNTracks(0),
fNEvents(0),
fTracklets(0x0),
fNtrackletsMax(1000),
fNTracklets(0),
fSpacePoints(0x0),
fTRDgeometry(0x0),
fEnableDebugOutput(false),
fStreamer(0x0)
{
for (int iDet=0; iDet<540; ++iDet) {
fTrackletIndexArray[iDet][0] = -1;
fTrackletIndexArray[iDet][1] = 0;
}
//Default constructor
}
AliHLTTRDTracker::AliHLTTRDTracker(const AliHLTTRDTracker &tracker) :
fTracks(0x0),
fNTracks(0),
fNEvents(0),
fTracklets(0x0),
fNtrackletsMax(1000),
fNTracklets(0),
fSpacePoints(0x0),
fTRDgeometry(0x0),
fEnableDebugOutput(false),
fStreamer(0x0)
{
//Copy constructor
//Dummy!
for (int iDet=0; iDet<540; ++iDet) {
fTrackletIndexArray[iDet][0] = tracker.fTrackletIndexArray[iDet][0];
fTrackletIndexArray[iDet][1] = tracker.fTrackletIndexArray[iDet][1];
}
}
AliHLTTRDTracker & AliHLTTRDTracker::operator=(const AliHLTTRDTracker &tracker){
//Assignment operator
this->~AliHLTTRDTracker();
new(this) AliHLTTRDTracker(tracker);
return *this;
}
AliHLTTRDTracker::~AliHLTTRDTracker()
{
//Destructor
delete[] fTracklets;
delete[] fTracks;
delete[] fSpacePoints;
delete fTRDgeometry;
if (fEnableDebugOutput) {
delete fStreamer;
}
}
void AliHLTTRDTracker::Init()
{
fTracklets = new AliHLTTRDTrackletWord[fNtrackletsMax];
fSpacePoints = new AliHLTTRDSpacePointInternal[fNtrackletsMax];
fTRDgeometry = new AliTRDgeometry();
if (!fTRDgeometry) {
Error("Init", "TRD geometry could not be loaded\n");
}
if (fEnableDebugOutput) {
fStreamer = new TTreeSRedirector("debug.root", "recreate");
}
}
void AliHLTTRDTracker::Reset()
{
fNTracklets = 0;
for (int i=0; i<fNtrackletsMax; ++i) {
fTracklets[i] = 0x0;
fSpacePoints[i].fX[0] = 0.;
fSpacePoints[i].fX[1] = 0.;
fSpacePoints[i].fX[2] = 0.;
fSpacePoints[i].fId = 0;
fSpacePoints[i].fVolumeId = 0;
}
for (int iDet=0; iDet<540; ++iDet) {
fTrackletIndexArray[iDet][0] = -1;
fTrackletIndexArray[iDet][1] = 0;
}
}
void AliHLTTRDTracker::StartLoadTracklets(const int nTrklts)
{
if (nTrklts > fNtrackletsMax) {
delete[] fTracklets;
delete[] fSpacePoints;
fNtrackletsMax += nTrklts - fNtrackletsMax;
fTracklets = new AliHLTTRDTrackletWord[fNtrackletsMax];
fSpacePoints = new AliHLTTRDSpacePointInternal[fNtrackletsMax];
}
}
void AliHLTTRDTracker::LoadTracklet(const AliHLTTRDTrackletWord &tracklet)
{
if (fNTracklets >= fNtrackletsMax ) {
Error("LoadTracklet", "running out of memory for tracklets, skipping tracklet(s). This should actually never happen.\n");
return;
}
fTracklets[fNTracklets++] = tracklet;
fTrackletIndexArray[tracklet.GetDetector()][1]++;
}
void AliHLTTRDTracker::DoTracking( AliExternalTrackParam *tracksTPC, int *tracksTPCLab, int nTPCTracks )
{
//--------------------------------------------------------------------
// This functions reconstructs TRD tracks
// using TPC tracks as seeds
//--------------------------------------------------------------------
fNEvents++;
// sort tracklets and fill index array
std::sort(fTracklets, fTracklets + fNTracklets);
int trkltCounter = 0;
for (int iDet=0; iDet<540; ++iDet) {
if (fTrackletIndexArray[iDet][1] != 0) {
fTrackletIndexArray[iDet][0] = trkltCounter;
trkltCounter += fTrackletIndexArray[iDet][1];
}
}
// test the correctness of the tracklet index array
// this can be deleted later...
if (!IsTrackletSortingOk()) {
Error("DoTracking", "bug in tracklet index array\n");
}
CalculateSpacePoints();
delete[] fTracks;
fNTracks = 0;
fTracks = new AliHLTTRDTrack[nTPCTracks];
double piMass = TDatabasePDG::Instance()->GetParticle(211)->Mass(); // pion mass as best guess for all particles
for (int i=0; i<nTPCTracks; ++i) {
AliHLTTRDTrack tMI(tracksTPC[i]);
AliHLTTRDTrack *t = &tMI;
t->SetTPCtrackId(i);
t->SetLabel(0); // use for monte carlo tracks later TODO: set correct label
t->SetMass(piMass);
int result = FollowProlongation(t, piMass);
t->SetNtracklets(result);
fTracks[fNTracks++] = *t;
double pT = t->Pt();
double alpha = t->GetAlpha();
if (fEnableDebugOutput) {
(*fStreamer) << "tracksFinal" <<
"ev=" << fNEvents <<
"iTrk=" << i <<
"pT=" << pT <<
"alpha=" << alpha <<
"nTrackletsAttached=" << result <<
"track.=" << t <<
"\n";
}
}
if (fEnableDebugOutput) {
(*fStreamer) << "statistics" <<
"nEvents=" << fNEvents <<
"nTrackletsTotal=" << fNTracklets <<
"nTPCtracksTotal=" << nTPCTracks <<
"\n";
}
}
bool AliHLTTRDTracker::IsTrackletSortingOk()
{
int nTrklts = 0;
for (int iDet=0; iDet<540; iDet++) {
for (int iTrklt=0; iTrklt<fTrackletIndexArray[iDet][1]; iTrklt++) {
++nTrklts;
int detTracklet = fTracklets[fTrackletIndexArray[iDet][0]+iTrklt].GetDetector();
if (iDet != detTracklet) {
return false;
}
}
}
if (nTrklts != fNTracklets) {
return false;
}
return true;
}
void AliHLTTRDTracker::CalculateSpacePoints()
{
//--------------------------------------------------------------------
// This functions calculates the TRD space points
// in sector tracking coordinates for all tracklets
//--------------------------------------------------------------------
for (int iDet=0; iDet<540; ++iDet) {
int layer = fTRDgeometry->GetLayer(iDet);
int stack = fTRDgeometry->GetStack(iDet);
int nTracklets = fTrackletIndexArray[iDet][1];
if (nTracklets == 0) {
continue;
}
TGeoHMatrix *matrix = fTRDgeometry->GetClusterMatrix(iDet);
if (!matrix){
Error("CalculateSpacePoints", "invalid TRD cluster matrix, skipping detector %i\n", iDet);
continue;
}
AliTRDpadPlane *padPlane = fTRDgeometry->GetPadPlane(layer, stack);
for (int iTrklt=0; iTrklt<nTracklets; ++iTrklt) {
int trkltIdx = fTrackletIndexArray[iDet][0] + iTrklt;
double xTrklt[3] = { 0. };
xTrklt[0] = AliTRDgeometry::AnodePos();
xTrklt[1] = fTracklets[trkltIdx].GetY();
if (stack == 2) {
xTrklt[2] = padPlane->GetRowPos(fTracklets[trkltIdx].GetZbin()) - (padPlane->GetRowSize(fTracklets[trkltIdx].GetZbin()))/2. - padPlane->GetRowPos(6);
}
else {
xTrklt[2] = padPlane->GetRowPos(fTracklets[trkltIdx].GetZbin()) - (padPlane->GetRowSize(fTracklets[trkltIdx].GetZbin()))/2. - padPlane->GetRowPos(8);
}
matrix->LocalToMaster(xTrklt, fSpacePoints[trkltIdx].fX);
fSpacePoints[trkltIdx].fId = fTracklets[trkltIdx].GetId();
AliGeomManager::ELayerID iLayer = AliGeomManager::ELayerID(AliGeomManager::kTRD1+fTRDgeometry->GetLayer(iDet));
int modId = fTRDgeometry->GetSector(iDet) * AliTRDgeometry::kNstack + fTRDgeometry->GetStack(iDet);
unsigned short volId = AliGeomManager::LayerToVolUID(iLayer, modId);
fSpacePoints[trkltIdx].fVolumeId = volId;
}
}
}
int AliHLTTRDTracker::FollowProlongation(AliHLTTRDTrack *t, double mass)
{
//--------------------------------------------------------------------
// This function propagates found tracks with pT > 1.0 GeV
// through the TRD and picks up the closest tracklet in each
// layer on the way.
// returns variable result = number of assigned tracklets
//--------------------------------------------------------------------
int result = 0;
int iTrack = t->GetTPCtrackId(); // for debugging individual tracks
// introduce momentum cut on tracks
// particles with pT < 0.9 GeV highly unlikely to have matching online TRD tracklets
if (t->Pt() < 1.0) {
return result;
}
// define some constants
const int nSector = fTRDgeometry->Nsector();
const int nStack = fTRDgeometry->Nstack();
const int nLayer = fTRDgeometry->Nlayer();
AliTRDpadPlane *pad = 0x0;
// the vector det holds the numbers of the detectors which are searched for tracklets
std::vector<int> det;
std::vector<int>::iterator iDet;
for (int iLayer=0; iLayer<nLayer; ++iLayer) {
det.clear();
// where the trackl initially ends up
int initialStack = -1;
int initialSector = -1;
int detector = -1;
pad = fTRDgeometry->GetPadPlane(iLayer, 0);
const float zMaxTRD = pad->GetRowPos(0);
const float yMax = pad->GetColPos(143) + pad->GetColSize(143);
const float xLayer = fTRDgeometry->GetTime0(iLayer);
if (!PropagateTrackToBxByBz(t, xLayer, mass, 5.0 /*max step*/, kFALSE /*rotateTo*/, 0.8 /*maxSnp*/) || (abs(t->GetZ()) >= (zMaxTRD + 10.)) ) {
return result;
}
// rotate track in new sector in case of sector crossing
if (!AdjustSector(t)) {
return result;
}
// debug purposes only -> store track information
double sigmaY = TMath::Sqrt(t->GetSigmaY2());
double sigmaZ = TMath::Sqrt(t->GetSigmaZ2());
AliExternalTrackParam param(*t);
if (fEnableDebugOutput) {
(*fStreamer) << "trackInfoLayerwise" <<
"iEv=" << fNEvents <<
"iTrk=" << iTrack <<
"layer=" << iLayer <<
"sigmaY=" << sigmaY <<
"sigmaZ=" << sigmaZ <<
"nUpdates=" << result <<
"track.=" << ¶m <<
"\n";
}
// determine initial chamber where the track ends up
// add more chambers of the same sector if track is close to edge of the chamber
detector = GetDetectorNumber(t->GetZ(), t->GetAlpha(), iLayer);
if (detector != -1) {
det.push_back(detector);
initialStack = fTRDgeometry->GetStack(detector);
initialSector = fTRDgeometry->GetSector(detector);
AliTRDpadPlane *padTmp = fTRDgeometry->GetPadPlane(iLayer, initialStack);
int lastPadRow = -1;
float zCenter = 0.;
if (initialStack == 2) {
lastPadRow = 11;
zCenter = padTmp->GetRowPos(6);
}
else {
lastPadRow = 15;
zCenter = padTmp->GetRowPos(8);
}
if ( t->GetZ() > (padTmp->GetRowPos(0) - 10.) || t->GetZ() < (padTmp->GetRowPos(lastPadRow) + 10) ) {
if ( !(initialStack == 0 && t->GetZ() > 0) && !(initialStack == nStack-1 && t->GetZ() < 0) ) {
// track not close to outer end of TRD -> add neighbouring stack
if (t->GetZ() > zCenter) {
det.push_back(fTRDgeometry->GetDetector(iLayer, initialStack-1, initialSector));
}
else {
det.push_back(fTRDgeometry->GetDetector(iLayer, initialStack+1, initialSector));
}
}
}
}
else {
if (TMath::Abs(t->GetZ()) > zMaxTRD) {
t->GetZ() > 0 ? // shift track in z so it is in the TRD acceptance
detector = GetDetectorNumber(t->GetZ()-10., t->GetAlpha(), iLayer) :
detector = GetDetectorNumber(t->GetZ()+10., t->GetAlpha(), iLayer);
if (detector != -1) {
det.push_back(detector);
initialStack = fTRDgeometry->GetStack(detector);
initialSector = fTRDgeometry->GetSector(detector);
}
else {
Error("FollowProlongation", "outer detector cannot be found although track %i was shifted in z", iTrack);
return result;
}
}
else {
// track in between two stacks, add both surrounding chambers
detector = GetDetectorNumber(t->GetZ()+4.0, t->GetAlpha(), iLayer);
if (detector != -1) {
det.push_back(detector);
initialStack = fTRDgeometry->GetStack(detector);
initialSector = fTRDgeometry->GetSector(detector);
}
else {
Error("FollowProlongation", "detector cannot be found although track %i was shifted in positive z", iTrack);
return result;
}
detector = GetDetectorNumber(t->GetZ()-4.0, t->GetAlpha(), iLayer);
if (detector != -1) {
det.push_back(detector);
}
else {
Error("FollowProlongation", "detector cannot be found although track %i was shifted in negative z", iTrack);
return result;
}
}
}
// add chamber(s) from neighbouring sector in case the track is close to the boundary
if ( TMath::Abs(t->GetY()) > (yMax - 10.) ) {
const int nStacksToSearch = det.size();
for (int idx = 0; idx < nStacksToSearch; ++idx) {
int currStack = fTRDgeometry->GetStack(det.at(idx));
if (t->GetY() > 0) {
int newSector = initialSector + 1;
if (newSector == nSector) {
newSector = 0;
}
det.push_back(fTRDgeometry->GetDetector(iLayer, currStack, newSector));
}
else {
int newSector = initialSector - 1;
if (newSector == -1) {
newSector = nSector - 1;
}
det.push_back(fTRDgeometry->GetDetector(iLayer, currStack, newSector));
}
}
}
if (fEnableDebugOutput) {
int nDetToSearch = det.size();
(*fStreamer) << "chambersToSearch" <<
"nChambers=" << nDetToSearch <<
"layer=" << iLayer <<
"iEv=" << fNEvents <<
"\n";
}
// define search window for tracklets
double deltaY = 7. * TMath::Sqrt(t->GetSigmaY2() + TMath::Power(0.03, 2)) + 2; // add constant to the road for better efficiency
double deltaZ = 7. * TMath::Sqrt(t->GetSigmaZ2() + TMath::Power(9./TMath::Sqrt(12), 2));
if (fEnableDebugOutput) {
(*fStreamer) << "searchWindow" <<
"layer=" << iLayer <<
"dY=" << deltaY <<
"dZ=" << deltaZ <<
"\n";
}
// look for tracklets in chamber(s)
double bestGuessChi2 = 100.; // TODO define meaningful chi2 cut
int bestGuessIdx = -1;
int bestGuessDet = -1;
double p[2] = { 0. };
double cov[3] = { 0. };
bool wasTrackRotated = false;
for (iDet = det.begin(); iDet != det.end(); ++iDet) {
int detToSearch = *iDet;
int stackToSearch = detToSearch / nLayer; // global stack number
int sectorToSearch = fTRDgeometry->GetSector(detToSearch);
if (sectorToSearch != initialSector && !wasTrackRotated) {
float alphaToSearch = 2.0 * TMath::Pi() / (float) nSector * ((float) sectorToSearch + 0.5);
t->Rotate(alphaToSearch);
wasTrackRotated = true; // tracks need to be rotated max once per layer
}
for (int iTrklt=0; iTrklt<fTrackletIndexArray[detToSearch][1]; ++iTrklt) {
int trkltIdx = fTrackletIndexArray[detToSearch][0] + iTrklt;
if ((fSpacePoints[trkltIdx].fX[1] < t->GetY() + deltaY) && (fSpacePoints[trkltIdx].fX[1] > t->GetY() - deltaY) &&
(fSpacePoints[trkltIdx].fX[2] < t->GetZ() + deltaZ) && (fSpacePoints[trkltIdx].fX[2] > t->GetZ() - deltaZ))
{
//tracklet is in windwow: get predicted chi2 for update and store tracklet index if best guess
p[0] = fSpacePoints[trkltIdx].fX[1];
p[1] = fSpacePoints[trkltIdx].fX[2];
if (TMath::Abs(p[0]) > 1000) {
Error("FollowProlongation", "impossible y-value of tracklet: y=%.12f\n", p[0]);
return result;
}
cov[0] = TMath::Power(0.03, 2);
cov[1] = 0;
cov[2] = TMath::Power(9./TMath::Sqrt(12), 2);
double chi2 = t->GetPredictedChi2(p, cov);
if (chi2 < bestGuessChi2) {
bestGuessChi2 = chi2;
bestGuessIdx = trkltIdx;
bestGuessDet = detToSearch;
}
float dY = t->GetY() - fSpacePoints[trkltIdx].fX[1];
float dZ = t->GetZ() - fSpacePoints[trkltIdx].fX[2];
if (fEnableDebugOutput) {
(*fStreamer) << "residuals" <<
"iEv=" << fNEvents <<
"iTrk=" << iTrack <<
"layer=" << iLayer <<
"iTrklt=" << iTrklt <<
"stack=" << stackToSearch <<
"det=" << detToSearch <<
"dY=" << dY <<
"dZ=" << dZ <<
"\n";
}
if (TMath::Abs(dZ) > 160) {
Error("FollowProlongation", "impossible dZ-value of tracklet: track z = %f, tracklet z = %f, detToSearch = %i\n", t->GetZ(), fSpacePoints[trkltIdx].fX[2], detToSearch);
}
}
}
}
if (bestGuessIdx != -1 ) {
// best matching tracklet found
p[0] = fSpacePoints[bestGuessIdx].fX[1];
p[1] = fSpacePoints[bestGuessIdx].fX[2];
cov[0] = TMath::Power(0.03, 2);
cov[1] = 0;
cov[2] = TMath::Power(9./TMath::Sqrt(12), 2);
t->Update(p, cov);
++result;
}
}
// after propagation, propagate track back to inner radius of TPC
float xInnerParam = 83.65;
if (!PropagateTrackToBxByBz(t, xInnerParam, mass, 5.0 /*max step*/, kFALSE /*rotateTo*/, 0.8 /*maxSnp*/)) {
Warning("FollowProlongation", "Back propagation for track %i failed", iTrack);
return result;
}
// rotate track back in old sector in case of sector crossing
AdjustSector(t);
return result;
}
// helper function for event display -> later not needed anymore
void AliHLTTRDTracker::Rotate(const double alpha, const double * const loc, double *glb)
{
glb[0] = loc[0] * TMath::Cos(alpha) - loc[1] * TMath::Sin(alpha);
glb[1] = loc[0] * TMath::Sin(alpha) + loc[1] * TMath::Cos(alpha);
glb[2] = loc[2];
}
int AliHLTTRDTracker::GetDetectorNumber(const double zPos, double alpha, int layer)
{
int stack = fTRDgeometry->GetStack(zPos, layer);
if (stack < 0) {
Info("GetDetectorNumber", "Stack determination failed for layer %i, alpha=%f, z=%f", layer, alpha, zPos);
return -1;
}
double alphaTmp = (alpha > 0) ? alpha : alpha + 2. * TMath::Pi();
int sector = 18. * alphaTmp / (2. * TMath::Pi());
return fTRDgeometry->GetDetector(layer, stack, sector);
}
bool AliHLTTRDTracker::AdjustSector(AliHLTTRDTrack *t)
{
// rotate track in new sector if necessary
double alpha = fTRDgeometry->GetAlpha();
double y = t->GetY();
double yMax = t->GetX() * TMath::Tan(0.5 * alpha);
double alphaCurr = t->GetAlpha();
if (TMath::Abs(y) > 2. * yMax) {
Info("AdjustSector", "Track %i with pT = %f crossing two sector boundaries at x = %f\n", t->GetTPCtrackId(), t->Pt(), t->GetX());
return false;
}
if (y > yMax) {
if (!t->Rotate(alphaCurr+alpha)) {
return false;
}
}
else if (y < -yMax) {
if (!t->Rotate(alphaCurr-alpha)) {
return false;
}
}
return true;
}
|
// **************************************************************************
// This file is property of and copyright by the ALICE HLT Project *
// ALICE Experiment at CERN, All rights reserved. *
// *
// Primary Authors: David Rohr <drohr@kip.uni-heidelberg.de> *
// for The ALICE HLT Project. *
// *
// Permission to use, copy, modify and distribute this software and its *
// documentation strictly for non-commercial purposes is hereby granted *
// without fee, provided that the above copyright notice appears in all *
// copies and that both the copyright notice and this permission notice *
// appear in the supporting documentation. The authors make no claims *
// about the suitability of this software for any purpose. It is *
// provided "as is" without express or implied warranty. *
// *
//***************************************************************************
#include "AliHLTCreateGRP.h"
#include <dic.hxx>
#include <stdio.h>
#include <ctime>
#include <iostream>
#include <memory>
#include <TString.h>
#include <TObjArray.h>
#include <TObjString.h>
#include <AliGRPObject.h>
#include <AliCDBManager.h>
#include <AliCDBStorage.h>
#include <AliCDBEntry.h>
#include <AliDCSSensor.h>
#include <AliMagF.h>
#include <AliDAQ.h>
using namespace std;
ClassImp(AliHLTCreateGRP)
/** Static string to define a local storage for the OCDB contact. */
static const TString kLOCAL_STORAGE_DEFINE = "local://";
/** Static define of T-HCDB */
static const char* THCDB_BASE_FOLDER = getenv("ALIHLT_T_HCDBDIR");
int AliHLTCreateGRP::CreateGRP(Int_t runNumber, TString detectorList, TString beamType, TString runType, UInt_t startShift, UInt_t endShift, Int_t defaults)
{
int l3Polarity;
float l3Current;
int dipolePolarity;
float dipoleCurrent;
float surfaceAtmosPressure;
float cavernAtmosPressure;
float cavernAtmosPressure2;
float beamEnergy;
if (defaults)
{
printf("WARNING: Defaults mode enabled, creating GRP with some default values for tests!\n");
dipoleCurrent = 5.999e+03; //Valid settings for running
l3Current = 3.000e+04;
dipolePolarity = 0;
l3Polarity = 0;
surfaceAtmosPressure = 971.127;
cavernAtmosPressure = 974.75;
cavernAtmosPressure2 = 975.55;
beamEnergy = 14000 / 0.12;
}
else
{
//Dim does not give a real error, but we have to define some values for the case of error, so let's take something unprobable. THIS SHOULD BE IMPROVED!!!
DimCurrentInfo solenoidPolarityDim("DCS_GRP_L3MAGNET_POLARITY", -12345678);
DimCurrentInfo solenoidCurrentDim("DCS_GRP_L3MAGNET_CURRENT", -123456.f);
DimCurrentInfo dipolePolarityDim("DCS_GRP_DIPOLE_POLARITY", -12345678);
DimCurrentInfo dipoleCurrentDim("DCS_GRP_DIPOLE_CURRENT", -123456.f);
DimCurrentInfo pressureSurfaceDim("DCS_GRP_PRESSURE_SURFACE", -123456.f);
DimCurrentInfo pressureCavernDim("DCS_GRP_PRESSURE_CAVERN", -123456.f);
DimCurrentInfo pressureCavernDim2("DCS_GRP_PRESSURE_CAVERN2", -123456.f);
//These 2 are not used yet, but it might make sense to use them perhaps?
//DimCurrentInfo LHCBeamType1Dim("DCS_GRP_LHC_BEAM_TYPE_1", -1);
//DimCurrentInfo LHCBeamType2Dim("DCS_GRP_LHC_BEAM_TYPE_2", -1);
//LHC Energy has not been used before, but it was seto to constant ((cmsEnergy = 14000) / 0.12), I think it is better to use dim value
DimCurrentInfo LHCBeamEnergyDim("DCS_GRP_LHC_BEAM_ENERGY", -123456.f);
l3Polarity = solenoidPolarityDim.getInt();
l3Current = solenoidCurrentDim.getFloat();
dipolePolarity = dipolePolarityDim.getInt();
dipoleCurrent = dipoleCurrentDim.getFloat();
surfaceAtmosPressure = pressureSurfaceDim.getFloat();
cavernAtmosPressure = pressureCavernDim.getFloat();
cavernAtmosPressure2 = pressureCavernDim2.getFloat();
beamEnergy = LHCBeamEnergyDim.getFloat();
}
if (l3Polarity == -12345678) {printf("Error obtaining L3 Polarity from DIM\n"); return(1);}
if (l3Current == -123456.f) {printf("Error obtaining L3 Current from DIM\n"); return(1);}
if (dipolePolarity == -12345678) {printf("Error obtaining Dipole Polarity from DIM\n"); return(1);}
if (dipoleCurrent == -123456.f) {printf("Error obtaining Dipole Current from DIM\n"); return(1);}
if (surfaceAtmosPressure == -123456.f) {printf("Error obtaining Surface Pressure from DIM\n"); return(1);}
if (cavernAtmosPressure == -123456.f) {printf("Error obtaining Cavern Pressure from DIM\n"); return(1);}
if (cavernAtmosPressure2 == -123456.f) {printf("Error obtaining Cavern Pressure 2 from DIM\n"); return(1);}
if (beamEnergy == -123456.f) {printf("Error obtaining Beam Energy from DIM\n"); return(1);}
AliMagF* field = AliMagF::CreateFieldMap(l3Current, dipoleCurrent, 0, kFALSE, beamEnergy, beamType, "$(ALICE_ROOT)/data/maps/mfchebKGI_sym.root", true);
if (field == NULL) return(4);
cout << "Values from DIM: L3 Polarity " << l3Polarity << ", L3 Current " << l3Current << ", Dipole Polarity " << dipolePolarity <<
", Dipole Current " << dipoleCurrent << ", Surface Pressure " << surfaceAtmosPressure << ", Cavern Pressure " << cavernAtmosPressure << " / " << cavernAtmosPressure2 <<
", Beam Energy " << beamEnergy << endl;
if (THCDB_BASE_FOLDER == NULL)
{
cout << "ALIHLT_T_HCDBDIR env variable must be set!" << endl;
return 5;
}
TString THCDBPath = kLOCAL_STORAGE_DEFINE + THCDB_BASE_FOLDER;
AliGRPObject grpObject;
// set GRP values to object
int curtime = time(NULL);
grpObject.SetTimeStart(curtime); // ?? not the time issued by ECS
grpObject.SetTimeEnd(curtime + 24 * 3600);
grpObject.SetBeamType(beamType);
grpObject.SetRunType(runType);
grpObject.SetLHCPeriod(getenv("LHC_PERIOD")); // ? This variable is wrong that way!
TObjArray* setOfDetectors = detectorList.Tokenize(",");
Char_t numOfDetectors = setOfDetectors->GetEntries();
grpObject.SetNumberOfDetectors(numOfDetectors);
UInt_t detectMask = createDetectorMask(setOfDetectors);
grpObject.SetDetectorMask(detectMask);
grpObject.SetBeamEnergy(beamEnergy);
grpObject.SetL3Current(l3Current, (AliGRPObject::Stats) 0);
grpObject.SetDipoleCurrent(dipoleCurrent, (AliGRPObject::Stats) 0);
grpObject.SetL3Polarity(l3Polarity);
grpObject.SetDipolePolarity(dipolePolarity);
grpObject.SetPolarityConventionLHC(); // LHC convention +/+ current -> -/- field main components
grpObject.SetCavernAtmosPressure(CreateSensor("CavernAtmosPressure", cavernAtmosPressure, startShift, endShift));
//This sensor is not yet present in DIM
grpObject.SetCavernAtmosPressure2(CreateSensor("CavernAtmosPressure2", cavernAtmosPressure2, startShift, endShift));
grpObject.SetSurfaceAtmosPressure(CreateSensor("SurfaceAtmosPressure", surfaceAtmosPressure, startShift, endShift));
cout << " ### GRP entry prepared with: " << endl;
cout << " start time: " << grpObject.GetTimeStart() << " (Sensor shiftTime " << startShift << " - " << endShift << ")" << endl;
cout << " beam type: " << grpObject.GetBeamType().Data() << ", run type: " << grpObject.GetRunType().Data() << endl;
cout << " LHC period: " << grpObject.GetLHCPeriod() << endl;
cout << " num of detectors: " << (Int_t) (grpObject.GetNumberOfDetectors()) << ", detector mask: " << grpObject.GetDetectorMask() << endl;
printf(" Detector mask hex: %x\n", grpObject.GetDetectorMask());
// Prepare storage of entry
// init connection to HCDB
AliCDBManager *man = AliCDBManager::Instance();
if (man)
{
cout << " --- Got a CDB Manager reference. " << endl;
}
else
{
cout << " *** ERROR cannot obtain a CDB Manager reference." << endl;
cout << " *** Exiting now " << endl << endl;
return 2;
}
AliCDBStorage *thcdb_storage = man->GetStorage(THCDBPath.Data());
if (thcdb_storage)
{
cout << " --- Contacted HCDB storage: " << THCDBPath.Data() << endl;
}
else
{
cout << " *** ERROR contacting HCDB storage:" << THCDBPath.Data() << endl;
cout << " *** Exiting now " << endl << endl;
return 3;
}
const char* aliroot_version = getenv("ALIROOT_VERSION");
if (aliroot_version == NULL) aliroot_version = "unknownAliRoot";
AliCDBMetaData meta("HLT", 0, aliroot_version, "GRP entry created online for HLT");
AliCDBPath path("GRP", "GRP", "Data");
int runmin, runmax;
if (defaults == 2)
{
runmin = 0;
runmax = 999999999;
printf("Creating Default Object\n");
}
else
{
runmin = runmax = runNumber;
}
AliCDBEntry THCDBEntry(&grpObject, path, runmin, runmax, &meta);
if (thcdb_storage->Put(&THCDBEntry))
{
cout << " +++ Successfully stored GRP entry." << endl;
}
else
{
cout << " *** ERROR storing GRP entry to HCDB." << endl << endl;
return 6;
}
return(0);
}
//COPIED FROM setGrpVal.C
/**
* Map detector list to detector mask
*
* @param listOfDetectors array containing the participating detectors
*
* @returns the detector mask encoded in an UInt_t
*/
UInt_t AliHLTCreateGRP::createDetectorMask(TObjArray* listOfDetectors)
{
UInt_t mask = 0x00000000;
for (Int_t i = 0; i < listOfDetectors->GetEntries(); i++) {
TObjString* detectorName = (TObjString*) listOfDetectors->At(i);
TString name(detectorName->String());
if (name.CompareTo("SPD") == 0) { // detector name
mask |= AliDAQ::kSPD;
} else if (name.CompareTo("SDD") == 0) {
mask |= AliDAQ::kSDD;
} else if (name.CompareTo("SSD") == 0) {
mask |= AliDAQ::kSSD;
} else if (name.CompareTo("TPC") == 0) {
mask |= AliDAQ::kTPC;
} else if (name.CompareTo("TRD") == 0) {
mask |= AliDAQ::kTRD;
} else if (name.CompareTo("TOF") == 0) {
mask |= AliDAQ::kTOF;
} else if (name.CompareTo("HMPID") == 0) {
mask |= AliDAQ::kHMPID;
} else if (name.CompareTo("PHOS") == 0) {
mask |= AliDAQ::kPHOS;
} else if (name.CompareTo("CPV") == 0) {
mask |= AliDAQ::kCPV;
} else if (name.CompareTo("PMD") == 0) {
mask |= AliDAQ::kPMD;
} else if (name.CompareTo("MUON_TRK") == 0) {
mask |= AliDAQ::kMUONTRK;
} else if (name.CompareTo("MUON_TRG") == 0) {
mask |= AliDAQ::kMUONTRG;
} else if (name.CompareTo("FMD") == 0) {
mask |= AliDAQ::kFMD;
} else if (name.CompareTo("T0") == 0) {
mask |= AliDAQ::kT0;
} else if (name.CompareTo("V0") == 0) {
mask |= AliDAQ::kVZERO;
} else if (name.CompareTo("ZDC") == 0) {
mask |= AliDAQ::kZDC;
} else if (name.CompareTo("ACORDE") == 0) {
mask |= AliDAQ::kACORDE;
} else if (name.CompareTo("TRG") == 0) {
mask |= AliDAQ::kTRG;
} else if (name.CompareTo("EMCAL") == 0) {
mask |= AliDAQ::kEMCAL;
} else if (name.CompareTo("DAQ_TEST") == 0) {
mask |= AliDAQ::kDAQTEST;
} else if (name.CompareTo("SHUTTLE") == 0) {
mask |= 0x20000000;
} else if (name.CompareTo("AD") == 0) {
mask |= AliDAQ::kAD;
} else if (name.CompareTo("MFT") == 0) {
mask |= AliDAQ::kMFT;
} else if (name.CompareTo("FIT") == 0) {
mask |= AliDAQ::kFIT;
} else if (name.CompareTo("HLT") == 0) {
mask |= AliDAQ::kHLT;
} else {
// Unknown detector names
cout << " *** Detector list contains unknown detector name, skipping ..." << endl;
}
}
//Always enable HLT and CTP flags
mask |= AliDAQ::kHLT;
mask |= AliDAQ::kTRG;
return mask;
}
//COPIED FROM AliHLTPredictionProcessorInterface.h
template <typename T> AliDCSSensor* AliHLTCreateGRP::CreateSensor(const char* id, T value, UInt_t starttime, UInt_t endtime)
{
// create an AliDCSSensor object with specified id and a linear graph
// There is no extrapolation in the online reconstruction, only the last value
// counts
if (!id) return NULL;
std::auto_ptr<AliDCSSensor> pSensor(new AliDCSSensor);
if (!pSensor.get())
{
//HLTFatal("memory allocation failed");
return NULL;
}
// AliDCSSensor allows two types of value representation: a spline fit and
// a graph. The online system uses a linear graph with const values between
// start and end time
// Note: AliDCSSensor::GetValue returns -99 if the requested time is before
// the start time and the last value if the time is after end time
// The measurements are stored in fractions of hours (see definition in
// class AliDCSSensor
const int points=2;
const Double_t kSecInHour = 3600.; // seconds in one hour
T x[points];
T y[points];
x[0]=0;
x[1]=(endtime-starttime)/kSecInHour;
y[0]=value;
y[1]=value;
std::auto_ptr<TGraph> pGraph(new TGraph(2,x,y));
if (!pGraph.get())
{
//HLTFatal("can not create graph for id %s", id);
return NULL;
}
AliSplineFit *fit = new AliSplineFit();
if (!fit) return NULL;
fit->SetMinPoints(10);
fit->InitKnots(pGraph.get(),10, 10, 0.0);
fit->SplineFit(2);
pSensor->SetStringID(id);
pSensor->SetStartTime(starttime);
pSensor->SetEndTime(endtime);
//note: AliDCSSensor has no correct cleanup in the destructor
// so the fit object is lost if the sensor is deleted
pSensor->SetFit(fit);
return pSensor.release();
}
Beam Energy is provided as integer not float
// **************************************************************************
// This file is property of and copyright by the ALICE HLT Project *
// ALICE Experiment at CERN, All rights reserved. *
// *
// Primary Authors: David Rohr <drohr@kip.uni-heidelberg.de> *
// for The ALICE HLT Project. *
// *
// Permission to use, copy, modify and distribute this software and its *
// documentation strictly for non-commercial purposes is hereby granted *
// without fee, provided that the above copyright notice appears in all *
// copies and that both the copyright notice and this permission notice *
// appear in the supporting documentation. The authors make no claims *
// about the suitability of this software for any purpose. It is *
// provided "as is" without express or implied warranty. *
// *
//***************************************************************************
#include "AliHLTCreateGRP.h"
#include <dic.hxx>
#include <stdio.h>
#include <ctime>
#include <iostream>
#include <memory>
#include <TString.h>
#include <TObjArray.h>
#include <TObjString.h>
#include <AliGRPObject.h>
#include <AliCDBManager.h>
#include <AliCDBStorage.h>
#include <AliCDBEntry.h>
#include <AliDCSSensor.h>
#include <AliMagF.h>
#include <AliDAQ.h>
using namespace std;
ClassImp(AliHLTCreateGRP)
/** Static string to define a local storage for the OCDB contact. */
static const TString kLOCAL_STORAGE_DEFINE = "local://";
/** Static define of T-HCDB */
static const char* THCDB_BASE_FOLDER = getenv("ALIHLT_T_HCDBDIR");
int AliHLTCreateGRP::CreateGRP(Int_t runNumber, TString detectorList, TString beamType, TString runType, UInt_t startShift, UInt_t endShift, Int_t defaults)
{
int l3Polarity;
float l3Current;
int dipolePolarity;
float dipoleCurrent;
float surfaceAtmosPressure;
float cavernAtmosPressure;
float cavernAtmosPressure2;
int beamEnergy;
if (defaults)
{
printf("WARNING: Defaults mode enabled, creating GRP with some default values for tests!\n");
dipoleCurrent = 5.999e+03; //Valid settings for running
l3Current = 3.000e+04;
dipolePolarity = 0;
l3Polarity = 0;
surfaceAtmosPressure = 971.127;
cavernAtmosPressure = 974.75;
cavernAtmosPressure2 = 975.55;
beamEnergy = 6501;
}
else
{
//Dim does not give a real error, but we have to define some values for the case of error, so let's take something unprobable. THIS SHOULD BE IMPROVED!!!
DimCurrentInfo solenoidPolarityDim("DCS_GRP_L3MAGNET_POLARITY", -12345678);
DimCurrentInfo solenoidCurrentDim("DCS_GRP_L3MAGNET_CURRENT", -123456.f);
DimCurrentInfo dipolePolarityDim("DCS_GRP_DIPOLE_POLARITY", -12345678);
DimCurrentInfo dipoleCurrentDim("DCS_GRP_DIPOLE_CURRENT", -123456.f);
DimCurrentInfo pressureSurfaceDim("DCS_GRP_PRESSURE_SURFACE", -123456.f);
DimCurrentInfo pressureCavernDim("DCS_GRP_PRESSURE_CAVERN", -123456.f);
DimCurrentInfo pressureCavernDim2("DCS_GRP_PRESSURE_CAVERN2", -123456.f);
//These 2 are not used yet, but it might make sense to use them perhaps?
//DimCurrentInfo LHCBeamType1Dim("DCS_GRP_LHC_BEAM_TYPE_1", -1);
//DimCurrentInfo LHCBeamType2Dim("DCS_GRP_LHC_BEAM_TYPE_2", -1);
//LHC Energy has not been used before, but it was seto to constant ((cmsEnergy = 14000) / 0.12), I think it is better to use dim value
DimCurrentInfo LHCBeamEnergyDim("DCS_GRP_LHC_BEAM_ENERGY", -12345678);
l3Polarity = solenoidPolarityDim.getInt();
l3Current = solenoidCurrentDim.getFloat();
dipolePolarity = dipolePolarityDim.getInt();
dipoleCurrent = dipoleCurrentDim.getFloat();
surfaceAtmosPressure = pressureSurfaceDim.getFloat();
cavernAtmosPressure = pressureCavernDim.getFloat();
cavernAtmosPressure2 = pressureCavernDim2.getFloat();
beamEnergy = LHCBeamEnergyDim.getInt();
}
if (l3Polarity == -12345678) {printf("Error obtaining L3 Polarity from DIM\n"); return(1);}
if (l3Current == -123456.f) {printf("Error obtaining L3 Current from DIM\n"); return(1);}
if (dipolePolarity == -12345678) {printf("Error obtaining Dipole Polarity from DIM\n"); return(1);}
if (dipoleCurrent == -123456.f) {printf("Error obtaining Dipole Current from DIM\n"); return(1);}
if (surfaceAtmosPressure == -123456.f) {printf("Error obtaining Surface Pressure from DIM\n"); return(1);}
if (cavernAtmosPressure == -123456.f) {printf("Error obtaining Cavern Pressure from DIM\n"); return(1);}
if (cavernAtmosPressure2 == -123456.f) {printf("Error obtaining Cavern Pressure 2 from DIM\n"); return(1);}
if (beamEnergy == -123456.f) {printf("Error obtaining Beam Energy from DIM\n"); return(1);}
AliMagF* field = AliMagF::CreateFieldMap(l3Current, dipoleCurrent, 0, kFALSE, beamEnergy, beamType, "$(ALICE_ROOT)/data/maps/mfchebKGI_sym.root", true);
if (field == NULL) return(4);
cout << "Values from DIM: L3 Polarity " << l3Polarity << ", L3 Current " << l3Current << ", Dipole Polarity " << dipolePolarity <<
", Dipole Current " << dipoleCurrent << ", Surface Pressure " << surfaceAtmosPressure << ", Cavern Pressure " << cavernAtmosPressure << " / " << cavernAtmosPressure2 <<
", Beam Energy " << beamEnergy << endl;
if (THCDB_BASE_FOLDER == NULL)
{
cout << "ALIHLT_T_HCDBDIR env variable must be set!" << endl;
return 5;
}
TString THCDBPath = kLOCAL_STORAGE_DEFINE + THCDB_BASE_FOLDER;
AliGRPObject grpObject;
// set GRP values to object
int curtime = time(NULL);
grpObject.SetTimeStart(curtime); // ?? not the time issued by ECS
grpObject.SetTimeEnd(curtime + 24 * 3600);
grpObject.SetBeamType(beamType);
grpObject.SetRunType(runType);
grpObject.SetLHCPeriod(getenv("LHC_PERIOD")); // ? This variable is wrong that way!
TObjArray* setOfDetectors = detectorList.Tokenize(",");
Char_t numOfDetectors = setOfDetectors->GetEntries();
grpObject.SetNumberOfDetectors(numOfDetectors);
UInt_t detectMask = createDetectorMask(setOfDetectors);
grpObject.SetDetectorMask(detectMask);
grpObject.SetBeamEnergy(beamEnergy);
grpObject.SetL3Current(l3Current, (AliGRPObject::Stats) 0);
grpObject.SetDipoleCurrent(dipoleCurrent, (AliGRPObject::Stats) 0);
grpObject.SetL3Polarity(l3Polarity);
grpObject.SetDipolePolarity(dipolePolarity);
grpObject.SetPolarityConventionLHC(); // LHC convention +/+ current -> -/- field main components
grpObject.SetCavernAtmosPressure(CreateSensor("CavernAtmosPressure", cavernAtmosPressure, startShift, endShift));
//This sensor is not yet present in DIM
grpObject.SetCavernAtmosPressure2(CreateSensor("CavernAtmosPressure2", cavernAtmosPressure2, startShift, endShift));
grpObject.SetSurfaceAtmosPressure(CreateSensor("SurfaceAtmosPressure", surfaceAtmosPressure, startShift, endShift));
cout << " ### GRP entry prepared with: " << endl;
cout << " start time: " << grpObject.GetTimeStart() << " (Sensor shiftTime " << startShift << " - " << endShift << ")" << endl;
cout << " beam type: " << grpObject.GetBeamType().Data() << ", run type: " << grpObject.GetRunType().Data() << endl;
cout << " LHC period: " << grpObject.GetLHCPeriod() << endl;
cout << " num of detectors: " << (Int_t) (grpObject.GetNumberOfDetectors()) << ", detector mask: " << grpObject.GetDetectorMask() << endl;
printf(" Detector mask hex: %x\n", grpObject.GetDetectorMask());
// Prepare storage of entry
// init connection to HCDB
AliCDBManager *man = AliCDBManager::Instance();
if (man)
{
cout << " --- Got a CDB Manager reference. " << endl;
}
else
{
cout << " *** ERROR cannot obtain a CDB Manager reference." << endl;
cout << " *** Exiting now " << endl << endl;
return 2;
}
AliCDBStorage *thcdb_storage = man->GetStorage(THCDBPath.Data());
if (thcdb_storage)
{
cout << " --- Contacted HCDB storage: " << THCDBPath.Data() << endl;
}
else
{
cout << " *** ERROR contacting HCDB storage:" << THCDBPath.Data() << endl;
cout << " *** Exiting now " << endl << endl;
return 3;
}
const char* aliroot_version = getenv("ALIROOT_VERSION");
if (aliroot_version == NULL) aliroot_version = "unknownAliRoot";
AliCDBMetaData meta("HLT", 0, aliroot_version, "GRP entry created online for HLT");
AliCDBPath path("GRP", "GRP", "Data");
int runmin, runmax;
if (defaults == 2)
{
runmin = 0;
runmax = 999999999;
printf("Creating Default Object\n");
}
else
{
runmin = runmax = runNumber;
}
AliCDBEntry THCDBEntry(&grpObject, path, runmin, runmax, &meta);
if (thcdb_storage->Put(&THCDBEntry))
{
cout << " +++ Successfully stored GRP entry." << endl;
}
else
{
cout << " *** ERROR storing GRP entry to HCDB." << endl << endl;
return 6;
}
return(0);
}
//COPIED FROM setGrpVal.C
/**
* Map detector list to detector mask
*
* @param listOfDetectors array containing the participating detectors
*
* @returns the detector mask encoded in an UInt_t
*/
UInt_t AliHLTCreateGRP::createDetectorMask(TObjArray* listOfDetectors)
{
UInt_t mask = 0x00000000;
for (Int_t i = 0; i < listOfDetectors->GetEntries(); i++) {
TObjString* detectorName = (TObjString*) listOfDetectors->At(i);
TString name(detectorName->String());
if (name.CompareTo("SPD") == 0) { // detector name
mask |= AliDAQ::kSPD;
} else if (name.CompareTo("SDD") == 0) {
mask |= AliDAQ::kSDD;
} else if (name.CompareTo("SSD") == 0) {
mask |= AliDAQ::kSSD;
} else if (name.CompareTo("TPC") == 0) {
mask |= AliDAQ::kTPC;
} else if (name.CompareTo("TRD") == 0) {
mask |= AliDAQ::kTRD;
} else if (name.CompareTo("TOF") == 0) {
mask |= AliDAQ::kTOF;
} else if (name.CompareTo("HMPID") == 0) {
mask |= AliDAQ::kHMPID;
} else if (name.CompareTo("PHOS") == 0) {
mask |= AliDAQ::kPHOS;
} else if (name.CompareTo("CPV") == 0) {
mask |= AliDAQ::kCPV;
} else if (name.CompareTo("PMD") == 0) {
mask |= AliDAQ::kPMD;
} else if (name.CompareTo("MUON_TRK") == 0) {
mask |= AliDAQ::kMUONTRK;
} else if (name.CompareTo("MUON_TRG") == 0) {
mask |= AliDAQ::kMUONTRG;
} else if (name.CompareTo("FMD") == 0) {
mask |= AliDAQ::kFMD;
} else if (name.CompareTo("T0") == 0) {
mask |= AliDAQ::kT0;
} else if (name.CompareTo("V0") == 0) {
mask |= AliDAQ::kVZERO;
} else if (name.CompareTo("ZDC") == 0) {
mask |= AliDAQ::kZDC;
} else if (name.CompareTo("ACORDE") == 0) {
mask |= AliDAQ::kACORDE;
} else if (name.CompareTo("TRG") == 0) {
mask |= AliDAQ::kTRG;
} else if (name.CompareTo("EMCAL") == 0) {
mask |= AliDAQ::kEMCAL;
} else if (name.CompareTo("DAQ_TEST") == 0) {
mask |= AliDAQ::kDAQTEST;
} else if (name.CompareTo("SHUTTLE") == 0) {
mask |= 0x20000000;
} else if (name.CompareTo("AD") == 0) {
mask |= AliDAQ::kAD;
} else if (name.CompareTo("MFT") == 0) {
mask |= AliDAQ::kMFT;
} else if (name.CompareTo("FIT") == 0) {
mask |= AliDAQ::kFIT;
} else if (name.CompareTo("HLT") == 0) {
mask |= AliDAQ::kHLT;
} else {
// Unknown detector names
cout << " *** Detector list contains unknown detector name, skipping ..." << endl;
}
}
//Always enable HLT and CTP flags
mask |= AliDAQ::kHLT;
mask |= AliDAQ::kTRG;
return mask;
}
//COPIED FROM AliHLTPredictionProcessorInterface.h
template <typename T> AliDCSSensor* AliHLTCreateGRP::CreateSensor(const char* id, T value, UInt_t starttime, UInt_t endtime)
{
// create an AliDCSSensor object with specified id and a linear graph
// There is no extrapolation in the online reconstruction, only the last value
// counts
if (!id) return NULL;
std::auto_ptr<AliDCSSensor> pSensor(new AliDCSSensor);
if (!pSensor.get())
{
//HLTFatal("memory allocation failed");
return NULL;
}
// AliDCSSensor allows two types of value representation: a spline fit and
// a graph. The online system uses a linear graph with const values between
// start and end time
// Note: AliDCSSensor::GetValue returns -99 if the requested time is before
// the start time and the last value if the time is after end time
// The measurements are stored in fractions of hours (see definition in
// class AliDCSSensor
const int points=2;
const Double_t kSecInHour = 3600.; // seconds in one hour
T x[points];
T y[points];
x[0]=0;
x[1]=(endtime-starttime)/kSecInHour;
y[0]=value;
y[1]=value;
std::auto_ptr<TGraph> pGraph(new TGraph(2,x,y));
if (!pGraph.get())
{
//HLTFatal("can not create graph for id %s", id);
return NULL;
}
AliSplineFit *fit = new AliSplineFit();
if (!fit) return NULL;
fit->SetMinPoints(10);
fit->InitKnots(pGraph.get(),10, 10, 0.0);
fit->SplineFit(2);
pSensor->SetStringID(id);
pSensor->SetStartTime(starttime);
pSensor->SetEndTime(endtime);
//note: AliDCSSensor has no correct cleanup in the destructor
// so the fit object is lost if the sensor is deleted
pSensor->SetFit(fit);
return pSensor.release();
}
|
AliAnalysisTask *AddTaskPIDResponse(Bool_t isMC=kFALSE, Bool_t autoMCesd=kTRUE)
{
// Macro to connect a centrality selection task to an existing analysis manager.
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskPIDResponse", "No analysis manager to connect to.");
return 0x0;
}
AliVEventHandler *inputHandler=mgr->GetInputEventHandler();
//case of multi input event handler (needed for mixing)
if (inputHandler->IsA() == AliMultiInputEventHandler::Class()) {
printf("========================================================================================\n");
printf("PIDResponse: AliMultiInputEventHandler detected, initialising AliPIDResponseInputHandler\n");
printf("========================================================================================\n");
AliMultiInputEventHandler *multiInputHandler=(AliMultiInputEventHandler*)inputHandler;
AliPIDResponseInputHandler *pidResponseIH = new AliPIDResponseInputHandler();
multiInputHandler->AddInputEventHandler(pidResponseIH);
if (autoMCesd &&
multiInputHandler->GetFirstInputEventHandler()->IsA()==AliESDInputHandler::Class() &&
multiInputHandler->GetFirstMCEventHandler()
) isMC=kTRUE;
pidResponseIH->SetIsMC(isMC);
return 0x0;
}
// standard with task
printf("========================================================================================\n");
printf("PIDResponse: Initialising AliAnalysisTaskPIDResponse\n");
printf("========================================================================================\n");
if ( autoMCesd && (inputHandler->IsA() == AliESDInputHandler::Class()) ) {
isMC=mgr->GetMCtruthEventHandler()!=0x0;
}
AliAnalysisTaskPIDResponse *pidTask = new AliAnalysisTaskPIDResponse("PIDResponseTask");
// pidTask->SelectCollisionCandidates(AliVEvent::kMB);
pidTask->SetIsMC(isMC);
mgr->AddTask(pidTask);
// AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("PIDResponseQA",
// TList::Class(), AliAnalysisManager::kOutputContainer,
// "PIDResponseQA.root");
mgr->ConnectInput(pidTask, 0, mgr->GetCommonInputContainer());
// mgr->ConnectOutput(pidTask,1,coutput1);
return pidTask;
}
o add option for tune on data
AliAnalysisTask *AddTaskPIDResponse(Bool_t isMC=kFALSE, Bool_t autoMCesd=kTRUE,Bool_t tuneOnData=kFALSE,Int_t recoPass=2)
{
// Macro to connect a centrality selection task to an existing analysis manager.
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskPIDResponse", "No analysis manager to connect to.");
return 0x0;
}
AliVEventHandler *inputHandler=mgr->GetInputEventHandler();
//case of multi input event handler (needed for mixing)
if (inputHandler->IsA() == AliMultiInputEventHandler::Class()) {
printf("========================================================================================\n");
printf("PIDResponse: AliMultiInputEventHandler detected, initialising AliPIDResponseInputHandler\n");
printf("========================================================================================\n");
AliMultiInputEventHandler *multiInputHandler=(AliMultiInputEventHandler*)inputHandler;
AliPIDResponseInputHandler *pidResponseIH = new AliPIDResponseInputHandler();
multiInputHandler->AddInputEventHandler(pidResponseIH);
if (autoMCesd &&
multiInputHandler->GetFirstInputEventHandler()->IsA()==AliESDInputHandler::Class() &&
multiInputHandler->GetFirstMCEventHandler()
) isMC=kTRUE;
pidResponseIH->SetIsMC(isMC);
return 0x0;
}
// standard with task
printf("========================================================================================\n");
printf("PIDResponse: Initialising AliAnalysisTaskPIDResponse\n");
printf("========================================================================================\n");
if ( autoMCesd && (inputHandler->IsA() == AliESDInputHandler::Class()) ) {
isMC=mgr->GetMCtruthEventHandler()!=0x0;
}
AliAnalysisTaskPIDResponse *pidTask = new AliAnalysisTaskPIDResponse("PIDResponseTask");
// pidTask->SelectCollisionCandidates(AliVEvent::kMB);
pidTask->SetIsMC(isMC);
if(isMC&&tuneOnData) pidTask->SetTuneOnData(kTRUE,recoPass);
mgr->AddTask(pidTask);
// AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("PIDResponseQA",
// TList::Class(), AliAnalysisManager::kOutputContainer,
// "PIDResponseQA.root");
mgr->ConnectInput(pidTask, 0, mgr->GetCommonInputContainer());
// mgr->ConnectOutput(pidTask,1,coutput1);
return pidTask;
}
|
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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.
*/
#include <Interface/Modules/Fields/ReportFieldGeometryMeasuresDialog.h>
#include <Modules/Legacy/Fields/ReportFieldGeometryMeasures.h>
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms::Fields;
ReportFieldGeometryMeasuresDialog::ReportFieldGeometryMeasuresDialog(const std::string& name, ModuleStateHandle state,
QWidget* parent /* = 0 */)
: ModuleDialogGeneric(state, parent)
{
setupUi(this);
setWindowTitle(QString::fromStdString(name));
fixSize();
//addCheckBoxManager(truncateDistanceCheckBox_, Parameters::Truncate);
//addCheckBoxManager(truncateDistanceCheckBox_, Parameters::Truncate);
//addCheckBoxManager(truncateDistanceCheckBox_, Parameters::Truncate);
//addCheckBoxManager(truncateDistanceCheckBox_, Parameters::Truncate);
//addCheckBoxManager(truncateDistanceCheckBox_, Parameters::Truncate);
//addCheckBoxManager(truncateDistanceCheckBox_, Parameters::Truncate);
//addComboBoxManager(dataTypeComboBox_, Parameters::OutputFieldDatatype);
}
UI hookup
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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.
*/
#include <Interface/Modules/Fields/ReportFieldGeometryMeasuresDialog.h>
#include <Modules/Legacy/Fields/ReportFieldGeometryMeasures.h>
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms::Fields;
ReportFieldGeometryMeasuresDialog::ReportFieldGeometryMeasuresDialog(const std::string& name, ModuleStateHandle state,
QWidget* parent /* = 0 */)
: ModuleDialogGeneric(state, parent)
{
setupUi(this);
setWindowTitle(QString::fromStdString(name));
fixSize();
addCheckBoxManager(xPositionCheckBox_, Parameters::XPositionFlag);
addCheckBoxManager(yPositionCheckBox_, Parameters::YPositionFlag);
addCheckBoxManager(zPositionCheckBox_, Parameters::ZPositionFlag);
addCheckBoxManager(indexCheckBox_, Parameters::IndexFlag);
addCheckBoxManager(sizeCheckBox_, Parameters::SizeFlag);
addCheckBoxManager(normalsCheckBox_, Parameters::NormalsFlag);
addComboBoxManager(simplexComboBox_, Parameters::MeasureLocation);
}
|
/**
* @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* 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.
*
* @file JPetTaskExecutor.cpp
*/
#include "JPetTaskExecutor.h"
#include <cassert>
#include "../JPetTaskInterface/JPetTaskInterface.h"
#include "../JPetScopeLoader/JPetScopeLoader.h"
#include "../JPetTaskLoader/JPetTaskLoader.h"
#include "../JPetParamGetterAscii/JPetParamGetterAscii.h"
#include "../JPetParamGetterAscii/JPetParamSaverAscii.h"
#include "../JPetLoggerInclude.h"
JPetTaskExecutor::JPetTaskExecutor(TaskGeneratorChain* taskGeneratorChain, int processedFileId, JPetOptions opt) :
fProcessedFile(processedFileId),
ftaskGeneratorChain(taskGeneratorChain),
fOptions(opt)
{
if (fOptions.isLocalDB()) {
fParamManager = new JPetParamManager(new JPetParamGetterAscii(fOptions.getLocalDB()));
} else {
fParamManager = new JPetParamManager();
}
if (taskGeneratorChain) {
for (auto taskGenerator : *ftaskGeneratorChain) {
auto task = taskGenerator();
task->setParamManager(fParamManager); // maybe that should not be here
fTasks.push_back(task);
}
} else {
ERROR("taskGeneratorChain is null while constructing JPetTaskExecutor");
}
}
bool JPetTaskExecutor::process()
{
if (!processFromCmdLineArgs(fProcessedFile)) {
ERROR("Error in processFromCmdLineArgs");
return false;
}
for (auto currentTask = fTasks.begin(); currentTask != fTasks.end(); currentTask++) {
JPetOptions::Options currOpts = fOptions.getOptions();
if (currentTask != fTasks.begin()) {
/// Ignore the event range options for all but the first task.
currOpts = JPetOptions::resetEventRange(currOpts);
/// For all but the first task,
/// the input path must be changed if
/// the output path argument -o was given, because the input
/// data for them will lay in the location defined by -o.
auto outPath = currOpts.at("outputPath");
if (!outPath.empty()) {
currOpts.at("inputFile") = outPath + JPetCommonTools::extractPathFromFile(currOpts.at("inputFile")) + JPetCommonTools::extractFileNameFromFullPath(currOpts.at("inputFile"));
}
}
INFO(Form("Starting task: %s", dynamic_cast<JPetTaskLoader*>(*currentTask)->getSubTask()->GetName()));
(*currentTask)->init(currOpts);
(*currentTask)->exec();
(*currentTask)->terminate();
INFO(Form("Finished task: %s", dynamic_cast<JPetTaskLoader*>(*currentTask)->getSubTask()->GetName()));
}
return true;
}
void* JPetTaskExecutor::processProxy(void* runner)
{
assert(runner);
static_cast<JPetTaskExecutor*>(runner)->process();
return 0;
}
TThread* JPetTaskExecutor::run()
{
TThread* thread = new TThread(to_string(fProcessedFile).c_str(), processProxy, (void*)this);
assert(thread);
thread->Run();
return thread;
}
bool JPetTaskExecutor::processFromCmdLineArgs(int)
{
auto runNum = fOptions.getRunNumber();
if (runNum >= 0) {
try {
fParamManager->fillParameterBank(runNum);
} catch (...) {
ERROR("Param bank was not generated correctly.\n The run number used:" + JPetCommonTools::intToString(runNum));
return false;
}
if (fOptions.isLocalDBCreate()) {
JPetParamSaverAscii saver;
saver.saveParamBank(fParamManager->getParamBank(), runNum, fOptions.getLocalDBCreate());
}
}
auto inputFileType = fOptions.getInputFileType();
auto inputFile = fOptions.getInputFile();
if (inputFileType == JPetOptions::kScope) {
if (!createScopeTaskAndAddToTaskList()) {
ERROR("Scope task not added correctly!!!");
return false;
}
} else if (inputFileType == JPetOptions::kHld) {
long long nevents = fOptions.getTotalEvents();
unpackFile(inputFile, nevents);
}
//Assumption that only HLD files can be zipped!!!!!! - Sz.N.
else if( inputFileType == JPetOptions::kZip){
INFO( std::string("Unzipping file before unpacking") );
if( !JPetCommonTools::unzipFile(inputFile) )
ERROR( std::string("Problem with unpacking file: ") + inputFile );
long long nevents = fOptions.getTotalEvents();
INFO( std::string("Unpacking") );
unpackFile( JPetCommonTools::stripFileNameSuffix( std::string(inputFile) ).c_str(), nevents);
}
if(fOptions.getInputFileType() == JPetOptions::kUndefinedFileType)
ERROR( Form("Unknown file type provided for file: %s", fOptions.getInputFile()) );
return true;
}
bool JPetTaskExecutor::createScopeTaskAndAddToTaskList()
{
JPetScopeLoader* module = new JPetScopeLoader(new JPetScopeTask("JPetScopeReader", "Process Oscilloscope ASCII data into JPetRecoSignal structures."));
assert(module);
module->setParamManager(fParamManager);
auto scopeFile = fOptions.getScopeConfigFile();
if (!fParamManager->getParametersFromScopeConfig(scopeFile)) {
ERROR("Unable to generate Param Bank from Scope Config");
return false;
}
fTasks.push_front(module);
return true;
}
void JPetTaskExecutor::unpackFile(const char* filename, const long long nevents)
{
if (nevents > 0) {
fUnpacker.setParams( filename, nevents);
WARNING(std::string("Even though the range of events was set, only the first ") + JPetCommonTools::intToString(nevents) + std::string(" will be unpacked by the unpacker. \n The unpacker always starts from the beginning of the file."));
} else {
fUnpacker.setParams( filename );
}
fUnpacker.exec();
}
JPetTaskExecutor::~JPetTaskExecutor()
{
for (auto & task : fTasks) {
if (task) {
delete task;
task = 0;
}
}
}
Fix std namespace after Unpacker headers' cleanup
/**
* @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* 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.
*
* @file JPetTaskExecutor.cpp
*/
#include "JPetTaskExecutor.h"
#include <cassert>
#include "../JPetTaskInterface/JPetTaskInterface.h"
#include "../JPetScopeLoader/JPetScopeLoader.h"
#include "../JPetTaskLoader/JPetTaskLoader.h"
#include "../JPetParamGetterAscii/JPetParamGetterAscii.h"
#include "../JPetParamGetterAscii/JPetParamSaverAscii.h"
#include "../JPetLoggerInclude.h"
JPetTaskExecutor::JPetTaskExecutor(TaskGeneratorChain* taskGeneratorChain, int processedFileId, JPetOptions opt) :
fProcessedFile(processedFileId),
ftaskGeneratorChain(taskGeneratorChain),
fOptions(opt)
{
if (fOptions.isLocalDB()) {
fParamManager = new JPetParamManager(new JPetParamGetterAscii(fOptions.getLocalDB()));
} else {
fParamManager = new JPetParamManager();
}
if (taskGeneratorChain) {
for (auto taskGenerator : *ftaskGeneratorChain) {
auto task = taskGenerator();
task->setParamManager(fParamManager); // maybe that should not be here
fTasks.push_back(task);
}
} else {
ERROR("taskGeneratorChain is null while constructing JPetTaskExecutor");
}
}
bool JPetTaskExecutor::process()
{
if (!processFromCmdLineArgs(fProcessedFile)) {
ERROR("Error in processFromCmdLineArgs");
return false;
}
for (auto currentTask = fTasks.begin(); currentTask != fTasks.end(); currentTask++) {
JPetOptions::Options currOpts = fOptions.getOptions();
if (currentTask != fTasks.begin()) {
/// Ignore the event range options for all but the first task.
currOpts = JPetOptions::resetEventRange(currOpts);
/// For all but the first task,
/// the input path must be changed if
/// the output path argument -o was given, because the input
/// data for them will lay in the location defined by -o.
auto outPath = currOpts.at("outputPath");
if (!outPath.empty()) {
currOpts.at("inputFile") = outPath + JPetCommonTools::extractPathFromFile(currOpts.at("inputFile")) + JPetCommonTools::extractFileNameFromFullPath(currOpts.at("inputFile"));
}
}
INFO(Form("Starting task: %s", dynamic_cast<JPetTaskLoader*>(*currentTask)->getSubTask()->GetName()));
(*currentTask)->init(currOpts);
(*currentTask)->exec();
(*currentTask)->terminate();
INFO(Form("Finished task: %s", dynamic_cast<JPetTaskLoader*>(*currentTask)->getSubTask()->GetName()));
}
return true;
}
void* JPetTaskExecutor::processProxy(void* runner)
{
assert(runner);
static_cast<JPetTaskExecutor*>(runner)->process();
return 0;
}
TThread* JPetTaskExecutor::run()
{
TThread* thread = new TThread(std::to_string(fProcessedFile).c_str(), processProxy, (void*)this);
assert(thread);
thread->Run();
return thread;
}
bool JPetTaskExecutor::processFromCmdLineArgs(int)
{
auto runNum = fOptions.getRunNumber();
if (runNum >= 0) {
try {
fParamManager->fillParameterBank(runNum);
} catch (...) {
ERROR("Param bank was not generated correctly.\n The run number used:" + JPetCommonTools::intToString(runNum));
return false;
}
if (fOptions.isLocalDBCreate()) {
JPetParamSaverAscii saver;
saver.saveParamBank(fParamManager->getParamBank(), runNum, fOptions.getLocalDBCreate());
}
}
auto inputFileType = fOptions.getInputFileType();
auto inputFile = fOptions.getInputFile();
if (inputFileType == JPetOptions::kScope) {
if (!createScopeTaskAndAddToTaskList()) {
ERROR("Scope task not added correctly!!!");
return false;
}
} else if (inputFileType == JPetOptions::kHld) {
long long nevents = fOptions.getTotalEvents();
unpackFile(inputFile, nevents);
}
//Assumption that only HLD files can be zipped!!!!!! - Sz.N.
else if( inputFileType == JPetOptions::kZip){
INFO( std::string("Unzipping file before unpacking") );
if( !JPetCommonTools::unzipFile(inputFile) )
ERROR( std::string("Problem with unpacking file: ") + inputFile );
long long nevents = fOptions.getTotalEvents();
INFO( std::string("Unpacking") );
unpackFile( JPetCommonTools::stripFileNameSuffix( std::string(inputFile) ).c_str(), nevents);
}
if(fOptions.getInputFileType() == JPetOptions::kUndefinedFileType)
ERROR( Form("Unknown file type provided for file: %s", fOptions.getInputFile()) );
return true;
}
bool JPetTaskExecutor::createScopeTaskAndAddToTaskList()
{
JPetScopeLoader* module = new JPetScopeLoader(new JPetScopeTask("JPetScopeReader", "Process Oscilloscope ASCII data into JPetRecoSignal structures."));
assert(module);
module->setParamManager(fParamManager);
auto scopeFile = fOptions.getScopeConfigFile();
if (!fParamManager->getParametersFromScopeConfig(scopeFile)) {
ERROR("Unable to generate Param Bank from Scope Config");
return false;
}
fTasks.push_front(module);
return true;
}
void JPetTaskExecutor::unpackFile(const char* filename, const long long nevents)
{
if (nevents > 0) {
fUnpacker.setParams( filename, nevents);
WARNING(std::string("Even though the range of events was set, only the first ") + JPetCommonTools::intToString(nevents) + std::string(" will be unpacked by the unpacker. \n The unpacker always starts from the beginning of the file."));
} else {
fUnpacker.setParams( filename );
}
fUnpacker.exec();
}
JPetTaskExecutor::~JPetTaskExecutor()
{
for (auto & task : fTasks) {
if (task) {
delete task;
task = 0;
}
}
}
|
// ConditioningFacility.cpp
// Implements the ConditioningFacility class
#include <iostream>
#include <fstream>
#include "ConditioningFacility.h"
#include "CycException.h"
#include "Env.h"
#include "InputXML.h"
#include "Logger.h"
#include "Material.h"
#include "GenericResource.h"
#include "MarketModel.h"
#include "Timer.h"
using namespace std;
/**
ConditioningFacility matches waste streams with
waste form loading densities and waste form
material definitions.
It attaches these properties to the material objects
as Material Properties.
TICK
On the tick, the ConditioningFacility makes requests for each
of the waste commodities (streams) that its table addresses
It also makes offers of any conditioned waste it contains
TOCK
On the tock, the ConditioningFacility first prepares
transactions by preparing and sending material from its stocks
all material in its stocks up to its monthly processing
capacity.
RECEIVE MATERIAL
Puts the material received in the stocks
SEND MATERIAL
Sends material from inventory to fulfill transactions
*/
/* --------------------
* all MODEL classes have these members
* --------------------
*/
// Database table for conditioned materials
table_ptr ConditioningFacility::cond_fac_table = new Table("ConditionedResources");
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ConditioningFacility::ConditioningFacility() {
// Initialize allowed formats map
allowed_formats_.insert(make_pair("sql", &ConditioningFacility::loadSQLFile));
allowed_formats_.insert(make_pair("xml", &ConditioningFacility::loadXMLFile));
allowed_formats_.insert(make_pair("csv", &ConditioningFacility::loadCSVFile));
stocks_ = deque<pair<string, mat_rsrc_ptr> >();
inventory_ = deque<pair<string, mat_rsrc_ptr> >();
file_is_open_ = false;
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ConditioningFacility::~ConditioningFacility() {};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::init(xmlNodePtr cur)
{
FacilityModel::init(cur);
/// move XML pointer to current model
cur = XMLinput->get_xpath_element(cur,"model/ConditioningFacility");
capacity_ = strtod(XMLinput->get_xpath_content(cur, "capacity"), NULL);
remaining_capacity_= capacity_;
/// initialize any ConditioningFacility-specific datamembers here
string datafile = XMLinput->get_xpath_content(cur, "datafile");
string fileformat = XMLinput->get_xpath_content(cur, "fileformat");
// all facilities require commodities - possibly many
string in_commod, out_commod;
int commod_id;
xmlNodeSetPtr nodes = XMLinput->get_xpath_elements(cur, "commodset");
// for each commod pair
for (int i = 0; i < nodes->nodeNr; i++){
xmlNodePtr pair_node = nodes->nodeTab[i];
// get name and id
in_commod = XMLinput->get_xpath_content(pair_node,"incommodity");
out_commod = XMLinput->get_xpath_content(pair_node,"outcommodity");
commod_id = strtol(XMLinput->get_xpath_content(pair_node,"id"), NULL, 10);
commod_map_.insert(make_pair( in_commod, make_pair(commod_id, out_commod)) );
};
loadTable(datafile, fileformat);
// we haven't conditioned anything yet
current_cond_rsrc_id_ = -1;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::copy(ConditioningFacility* src)
{
FacilityModel::copy(src);
allowed_formats_ = src->allowed_formats_;
capacity_ = src->capacity_;
remaining_capacity_ = capacity_;
file_is_open_ = src->file_is_open_;
commod_map_ = src->commod_map_;
stream_vec_ = src->stream_vec_;
loading_densities_ = src->loading_densities_;
current_cond_rsrc_id_ = -1;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::copyFreshModel(Model* src)
{
copy(dynamic_cast<ConditioningFacility*>(src));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::print()
{
FacilityModel::print();
string incommods, outcommods;
map<string, pair<int, string> >::const_iterator it;
for(it = commod_map_.begin(); it != commod_map_.end(); it++){
incommods += (*it).first;
incommods += ", ";
outcommods += (*it).second.second;
outcommods += ", ";
}
LOG(LEV_DEBUG2, "CondFac") << " conditions {"
<< incommods
<<"} into forms { "
<< outcommods
<< " }.";
};
/* ------------------- */
/* --------------------
* all COMMUNICATOR classes have these members
* --------------------
*/
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::receiveMessage(msg_ptr msg) {
LOG(LEV_DEBUG2, "CondFac") << "Warning, the ConditioningFacility ignores messages.";
};
/* ------------------- */
/* --------------------
* all FACILITYMODEL classes have these members
* --------------------
*/
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
vector<rsrc_ptr> ConditioningFacility::removeResource(msg_ptr order) {
vector<rsrc_ptr> toRet = vector<rsrc_ptr>() ;
Transaction trans = order->trans();
double order_amount = trans.resource->quantity()*trans.minfrac;
if (remaining_capacity_ >= order_amount){
toRet = processOrder(order);
} else {
string msg;
msg += "The ConditioningFacility has run out of processing capacity. ";
msg += "The order requested by ";
msg += order->requester()->name();
msg += " will not be sent.";
LOG(LEV_DEBUG2, "CondFac") << msg;
gen_rsrc_ptr empty = gen_rsrc_ptr(new GenericResource("kg","kg",0));
toRet.push_back(empty);
}
return toRet;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
vector<rsrc_ptr> ConditioningFacility::processOrder(msg_ptr order) {
// Send material from inventory to fulfill transactions
Transaction trans = order->trans();
double newAmt = 0;
// pull materials off of the inventory stack until you get the transaction amount
// start with an empty manifest
vector<rsrc_ptr> toSend;
while(trans.resource->quantity() > newAmt && !inventory_.empty() ) {
mat_rsrc_ptr m = inventory_.front().second;
// start with an empty material
mat_rsrc_ptr newMat = mat_rsrc_ptr(new Material());
// if the inventory obj isn't larger than the remaining need, send it as is.
if(m->quantity() <= (trans.resource->quantity() - newAmt)) {
newAmt += m->quantity();
newMat->absorb(m);
inventory_.pop_front();
remaining_capacity_ = remaining_capacity_ - newAmt;
} else {
// if the inventory obj is larger than the remaining need, split it.
mat_rsrc_ptr toAbsorb = m->extract(trans.resource->quantity() - newAmt);
newMat->absorb(toAbsorb);
newAmt += toAbsorb->quantity();
remaining_capacity_ = remaining_capacity_ - newAmt;
}
toSend.push_back(newMat);
LOG(LEV_DEBUG2, "CondFac") <<"ConditioningFacility "<< ID()
<<" is sending a mat with mass: "<< newMat->quantity();
}
return toSend;
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::addResource(msg_ptr msg, vector<rsrc_ptr> manifest) {
// Put the material received in the stocks
// grab each material object off of the manifest
// and move it into the stocks.
for (vector<rsrc_ptr>::iterator thisMat=manifest.begin();
thisMat != manifest.end();
thisMat++) {
LOG(LEV_DEBUG2, "CondFac") <<"ConditiondingFacility " << ID() << " is receiving material with mass "
<< (*thisMat)->quantity();
mat_rsrc_ptr mat = boost::dynamic_pointer_cast<Material>(*thisMat);
stocks_.push_front(make_pair(msg->trans().commod, mat));
}
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::handleTick(int time){
// TICK
// On the tick, the ConditioningFacility makes requests for each
// of the waste commodities (streams) that its table addresses
// It also makes offers of any conditioned waste it contains
remaining_capacity_ = capacity_;
makeRequests();
makeOffers();
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::handleTock(int time){
// TOCK
// On the tock, the ConditioningFacility first prepares
// all material in its stocks up to its monthly processing
// capacity.
conditionMaterials();
printStatus(time);
};
/* --------------------
* this FACILITYMODEL class has these members
* --------------------
*/
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::loadTable(string datafile, string fileformat){
// check that the format is supported
// if not, throw an exception
bool table_okay = verifyTable(datafile, fileformat);
// it will be a matrix
// rows/records = waste stream commodities
// columns/fields = waste forms
// data = loading, grams per m^3
// fill the data table
map<string, void(ConditioningFacility::*)(string)>::iterator format_found;
format_found = allowed_formats_.find(fileformat);
(this->*format_found->second)(datafile);
// match it with commodities
// verify number of commodities matches number of streams
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool ConditioningFacility::verifyTable(string datafile, string fileformat){
// start by assuming the table is bad
bool okay = false;
// if the fileformat is supported
map<string, void(ConditioningFacility::*)(string)>::iterator found = allowed_formats_.find(fileformat);
if (found != allowed_formats_.end()){
okay = true;
} else {
string err = "The file format, ";
err += fileformat;
err += ", is not supported by the Conditioning Facility.\n";
throw CycException(err);
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::loadXMLFile(string datafile){
// get dimensions
// // how many rows
// // how many columns
// create array
throw CycException("XML-based ConditioningFacility input is not yet supported.");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::loadSQLFile(string datafile){
// get dimensions
// // how many rows
// // how many columns
// create array
throw CycException("SQL-based ConditioningFacility input is not yet supported.");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::loadCSVFile(string datafile){
string file_path = Env::getCyclusPath() + "/" + datafile;
// create an ifstream for the file
ifstream file(file_path.c_str());
// and data structures to read the data into
string buffer;
stream_t stream;
if (file.is_open()){
while(file.good()){
// set the buffer string equal to everything up to the next comma
getline(file, buffer, ',');
// copy the data to the typed member of the stream struct
stream.streamID = strtol(buffer.c_str() , NULL, 10);
LOG(LEV_DEBUG2, "CondFac") << "streamID = " << stream.streamID ;;
getline(file, buffer, ',');
stream.formID = strtol(buffer.c_str() , NULL, 10);
LOG(LEV_DEBUG2, "CondFac") << "formID = " << stream.formID ;;
getline(file, buffer, ',');
stream.density = strtod(buffer.c_str() , NULL);
LOG(LEV_DEBUG2, "CondFac") << "density = " << stream.density ;;
getline(file, buffer, ',');
stream.wfvol = strtod(buffer.c_str() , NULL);
LOG(LEV_DEBUG2, "CondFac") << "wfvol = " << stream.wfvol ;;
getline(file, buffer, '\n');
stream.wfmass = strtod(buffer.c_str() , NULL);
LOG(LEV_DEBUG2, "CondFac") << "wfmass = " << stream.wfmass ;;
// put the full struct into the vector of structs
stream_vec_.push_back(stream);
}
file.close();
}
else {
string err = "CSV file, ";
err += file_path;
err += ", not found.";
throw CycException(err);
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::makeRequests(){
// The ConditioningFacility should make requests of all of the things it's
// capable of conditioning for each stream in the matrix
// calculate your capacity to condition
// MAKE A REQUEST
if(this->checkStocks() <= remaining_capacity_){
// It chooses the next in/out commodity pair in the preference lineup
map<string, pair<int, string> >::const_iterator it;
for(it = commod_map_.begin(); it != commod_map_.end(); it++){
string in_commod = (*it).first;
int in_id = (*it).second.first;
double requestAmt;
double minAmt = 0;
// The ConditioningFacility should ask for whatever it can process .
double sto = this->checkStocks();
// subtract sto from remaining_capacity_ to get total empty space.
double space = remaining_capacity_ - sto;
// this will be a request for free stuff
double commod_price = 0;
MarketModel* market = MarketModel::marketForCommod(in_commod);
Communicator* recipient = dynamic_cast<Communicator*>(market);
// if empty space is less than monthly acceptance capacity
requestAmt = space;
// request a generic resource
gen_rsrc_ptr request_res = gen_rsrc_ptr(new GenericResource(in_commod, "kg", requestAmt));
// build the transaction and message
Transaction trans;
trans.commod = in_commod;
trans.minfrac = minAmt/requestAmt;
trans.is_offer = false;
trans.price = commod_price;
trans.resource = request_res;
sendMessage(recipient, trans);
LOG(LEV_DEBUG2, "CondFac") << " The ConditioningFacility has requested "
<< requestAmt
<< " kg of "
<< in_commod
<< ".";
}
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::makeOffers(){
// Offer anything that has been conditioned or can be conditioned this month.
// this will be an offer of free stuff
double commod_price = 0;
// there are potentially many types of material in the inventory stack
double inv = this->checkInventory();
// send an offer for each material on the stack
string outcommod, offers;
Communicator* recipient;
double offer_amt;
for (deque< pair<string, mat_rsrc_ptr > >::iterator iter = inventory_.begin();
iter != inventory_.end();
iter++){
// get out commod
outcommod = iter->first;
MarketModel* market = MarketModel::marketForCommod(outcommod);
// decide what market to offer to
recipient = dynamic_cast<Communicator*>(market);
// get amt
offer_amt = iter->second->quantity();
// make a material to offer
mat_rsrc_ptr offer_mat = iter->second;
offer_mat->setQuantity(offer_amt);
// build the transaction and message
Transaction trans;
trans.commod = outcommod;
trans.minfrac = 1;
trans.is_offer = true;
trans.price = commod_price;
trans.resource = offer_mat;
sendMessage(recipient, trans);
offers += offer_mat->quantity();
offers += " kg ";
offers += outcommod;
if(inventory_.end()!=iter){
offers += " , ";
}
}
LOG(LEV_DEBUG2, "CondFac") << " The ConditioningFacility has offered "
<< offers
<< ".";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::sendMessage(Communicator* recipient, Transaction trans){
msg_ptr msg(new Message(this, recipient, trans));
msg->setNextDest(facInst());
msg->sendOn();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double ConditioningFacility::checkInventory(){
double total = 0;
// Iterate through the inventory and sum the amount of whatever
// material unit is in each object.
for (deque< pair<string, mat_rsrc_ptr> >::iterator iter = inventory_.begin();
iter != inventory_.end();
iter ++){
total += iter->second->quantity();
}
return total;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double ConditioningFacility::checkStocks(){
double total = 0;
// Iterate through the stocks and sum the amount of whatever
// material unit is in each object.
if(!stocks_.empty()){
for (deque< pair<string, mat_rsrc_ptr> >::iterator iter = stocks_.begin();
iter != stocks_.end();
iter ++){
total += iter->second->quantity();
};
};
return total;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::conditionMaterials(){
LOG(LEV_INFO3, "CondFac ") << facName() << " is conditioning {";
// Partition the in-stream according to loading density
// for each stream object in stocks
map<string, mat_rsrc_ptr> remainders;
while( !stocks_.empty() && remaining_capacity_ > 0){
// move stocks to currMat
string currCommod = stocks_.front().first;
mat_rsrc_ptr currMat = stocks_.front().second;
if(remainders.find(currCommod)!=remainders.end()){
(remainders[currCommod])->absorb(condition(currCommod, currMat));
} else {
remainders.insert(make_pair(currCommod, condition(currCommod, currMat)));
}
stocks_.pop_front();
}
map<string, mat_rsrc_ptr>::const_iterator rem;
for(rem=remainders.begin(); rem!=remainders.end(); rem++){
stocks_.push_back(*rem);
}
LOG(LEV_INFO3, "CondFac ") << "}";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mat_rsrc_ptr ConditioningFacility::condition(string commod, mat_rsrc_ptr mat){
stream_t stream = getStream(commod);
double mass_to_condition = stream.wfmass;
double mass_remaining = mat->quantity();
string out_commod;
while( mass_remaining > mass_to_condition && remaining_capacity_ > mass_to_condition) {
out_commod = commod_map_.find(commod)->second.second;
inventory_.push_back(make_pair(out_commod, mat->extract(mass_to_condition)));
remaining_capacity_ = remaining_capacity_ - mass_to_condition;
mass_remaining = mat->quantity();
// log the fact that we just conditioned stuff
LOG(LEV_INFO3, "CondFac ") << " " << commod << " has been conditioned into " <<
out_commod << " with mass : " << mass_to_condition;
current_cond_rsrc_id_ = TI->time();
addToTable();
}
return mat;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ConditioningFacility::stream_t ConditioningFacility::getStream(string commod){
int stream_id =(commod_map_.find(commod))->second.first;
vector<stream_t>::const_iterator it = stream_vec_.begin();
bool found = false;
stream_t toRet;
while(!found){
if((*it).streamID == stream_id){
toRet = (*it);
found = true;
} else if (it == stream_vec_.end() ) {
string msg;
msg += "The stream for id ";
msg += stream_id;
msg += " was not found in the ConditioningFacility stream map.";
throw CycException(msg);
} else {
it++;
}
}
return toRet;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::printStatus(int time){
// For now, lets just print out what we have at each timestep.
LOG(LEV_DEBUG2, "CondFac") << "ConditioningFacility " << this->ID()
<< " is holding " << this->checkInventory()
<< " units of material in inventory, and "
<< this->checkStocks()
<< " in stocks at the close of month "
<< time
<< ".";
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::define_table() {
// declare the table columns
column cond_fac_id("ID","INTEGER");
column time("Time","INTEGER");
column conditioned_rsrc_id("ConditionedRsrcID","INTEGER");
// declare the table's primary key
primary_key pk;
pk.push_back("ID"), pk.push_back("ConditionedRsrcID");
cond_fac_table->setPrimaryKey(pk);
// add columns to the table
cond_fac_table->addColumn(cond_fac_id);
cond_fac_table->addColumn(time);
cond_fac_table->addColumn(conditioned_rsrc_id);
// we've now defined the table
cond_fac_table->tableDefined();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::addToTable(){
// if we haven't logged some conditioned material yet, define the table
if ( !cond_fac_table->defined() ) {
ConditioningFacility::define_table();
}
// make a row
// declare data
data an_id( this->ID() ), a_time( TI->time() ),
a_rsrc_id( this->current_cond_rsrc_id_ );
// declare entries
entry id("ID",an_id), time("Time",a_time), rid("ConditionedRsrcID",a_rsrc_id);
// declare row
row aRow;
aRow.push_back(id), aRow.push_back(time), aRow.push_back(rid);
// add the row
cond_fac_table->addRow(aRow);
}
/* --------------------
* all MODEL classes have these members
* --------------------
*/
extern "C" Model* constructConditioningFacility() {
return new ConditioningFacility();
}
/* ------------------- */
minor simplifications to table making function.
// ConditioningFacility.cpp
// Implements the ConditioningFacility class
#include <iostream>
#include <fstream>
#include "ConditioningFacility.h"
#include "CycException.h"
#include "Env.h"
#include "InputXML.h"
#include "Logger.h"
#include "Material.h"
#include "GenericResource.h"
#include "MarketModel.h"
#include "Timer.h"
using namespace std;
/**
ConditioningFacility matches waste streams with
waste form loading densities and waste form
material definitions.
It attaches these properties to the material objects
as Material Properties.
TICK
On the tick, the ConditioningFacility makes requests for each
of the waste commodities (streams) that its table addresses
It also makes offers of any conditioned waste it contains
TOCK
On the tock, the ConditioningFacility first prepares
transactions by preparing and sending material from its stocks
all material in its stocks up to its monthly processing
capacity.
RECEIVE MATERIAL
Puts the material received in the stocks
SEND MATERIAL
Sends material from inventory to fulfill transactions
*/
/* --------------------
* all MODEL classes have these members
* --------------------
*/
// Database table for conditioned materials
table_ptr ConditioningFacility::cond_fac_table = new Table("ConditionedResources");
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ConditioningFacility::ConditioningFacility() {
// Initialize allowed formats map
allowed_formats_.insert(make_pair("sql", &ConditioningFacility::loadSQLFile));
allowed_formats_.insert(make_pair("xml", &ConditioningFacility::loadXMLFile));
allowed_formats_.insert(make_pair("csv", &ConditioningFacility::loadCSVFile));
stocks_ = deque<pair<string, mat_rsrc_ptr> >();
inventory_ = deque<pair<string, mat_rsrc_ptr> >();
file_is_open_ = false;
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ConditioningFacility::~ConditioningFacility() {};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::init(xmlNodePtr cur)
{
FacilityModel::init(cur);
/// move XML pointer to current model
cur = XMLinput->get_xpath_element(cur,"model/ConditioningFacility");
capacity_ = strtod(XMLinput->get_xpath_content(cur, "capacity"), NULL);
remaining_capacity_= capacity_;
/// initialize any ConditioningFacility-specific datamembers here
string datafile = XMLinput->get_xpath_content(cur, "datafile");
string fileformat = XMLinput->get_xpath_content(cur, "fileformat");
// all facilities require commodities - possibly many
string in_commod, out_commod;
int commod_id;
xmlNodeSetPtr nodes = XMLinput->get_xpath_elements(cur, "commodset");
// for each commod pair
for (int i = 0; i < nodes->nodeNr; i++){
xmlNodePtr pair_node = nodes->nodeTab[i];
// get name and id
in_commod = XMLinput->get_xpath_content(pair_node,"incommodity");
out_commod = XMLinput->get_xpath_content(pair_node,"outcommodity");
commod_id = strtol(XMLinput->get_xpath_content(pair_node,"id"), NULL, 10);
commod_map_.insert(make_pair( in_commod, make_pair(commod_id, out_commod)) );
};
loadTable(datafile, fileformat);
// we haven't conditioned anything yet
current_cond_rsrc_id_ = -1;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::copy(ConditioningFacility* src)
{
FacilityModel::copy(src);
allowed_formats_ = src->allowed_formats_;
capacity_ = src->capacity_;
remaining_capacity_ = capacity_;
file_is_open_ = src->file_is_open_;
commod_map_ = src->commod_map_;
stream_vec_ = src->stream_vec_;
loading_densities_ = src->loading_densities_;
current_cond_rsrc_id_ = -1;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::copyFreshModel(Model* src)
{
copy(dynamic_cast<ConditioningFacility*>(src));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::print()
{
FacilityModel::print();
string incommods, outcommods;
map<string, pair<int, string> >::const_iterator it;
for(it = commod_map_.begin(); it != commod_map_.end(); it++){
incommods += (*it).first;
incommods += ", ";
outcommods += (*it).second.second;
outcommods += ", ";
}
LOG(LEV_DEBUG2, "CondFac") << " conditions {"
<< incommods
<<"} into forms { "
<< outcommods
<< " }.";
};
/* ------------------- */
/* --------------------
* all COMMUNICATOR classes have these members
* --------------------
*/
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::receiveMessage(msg_ptr msg) {
LOG(LEV_DEBUG2, "CondFac") << "Warning, the ConditioningFacility ignores messages.";
};
/* ------------------- */
/* --------------------
* all FACILITYMODEL classes have these members
* --------------------
*/
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
vector<rsrc_ptr> ConditioningFacility::removeResource(msg_ptr order) {
vector<rsrc_ptr> toRet = vector<rsrc_ptr>() ;
Transaction trans = order->trans();
double order_amount = trans.resource->quantity()*trans.minfrac;
if (remaining_capacity_ >= order_amount){
toRet = processOrder(order);
} else {
string msg;
msg += "The ConditioningFacility has run out of processing capacity. ";
msg += "The order requested by ";
msg += order->requester()->name();
msg += " will not be sent.";
LOG(LEV_DEBUG2, "CondFac") << msg;
gen_rsrc_ptr empty = gen_rsrc_ptr(new GenericResource("kg","kg",0));
toRet.push_back(empty);
}
return toRet;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
vector<rsrc_ptr> ConditioningFacility::processOrder(msg_ptr order) {
// Send material from inventory to fulfill transactions
Transaction trans = order->trans();
double newAmt = 0;
// pull materials off of the inventory stack until you get the transaction amount
// start with an empty manifest
vector<rsrc_ptr> toSend;
while(trans.resource->quantity() > newAmt && !inventory_.empty() ) {
mat_rsrc_ptr m = inventory_.front().second;
// start with an empty material
mat_rsrc_ptr newMat = mat_rsrc_ptr(new Material());
// if the inventory obj isn't larger than the remaining need, send it as is.
if(m->quantity() <= (trans.resource->quantity() - newAmt)) {
newAmt += m->quantity();
newMat->absorb(m);
inventory_.pop_front();
remaining_capacity_ = remaining_capacity_ - newAmt;
} else {
// if the inventory obj is larger than the remaining need, split it.
mat_rsrc_ptr toAbsorb = m->extract(trans.resource->quantity() - newAmt);
newMat->absorb(toAbsorb);
newAmt += toAbsorb->quantity();
remaining_capacity_ = remaining_capacity_ - newAmt;
}
toSend.push_back(newMat);
LOG(LEV_DEBUG2, "CondFac") <<"ConditioningFacility "<< ID()
<<" is sending a mat with mass: "<< newMat->quantity();
}
return toSend;
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::addResource(msg_ptr msg, vector<rsrc_ptr> manifest) {
// Put the material received in the stocks
// grab each material object off of the manifest
// and move it into the stocks.
for (vector<rsrc_ptr>::iterator thisMat=manifest.begin();
thisMat != manifest.end();
thisMat++) {
LOG(LEV_DEBUG2, "CondFac") <<"ConditiondingFacility " << ID() << " is receiving material with mass "
<< (*thisMat)->quantity();
mat_rsrc_ptr mat = boost::dynamic_pointer_cast<Material>(*thisMat);
stocks_.push_front(make_pair(msg->trans().commod, mat));
}
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::handleTick(int time){
// TICK
// On the tick, the ConditioningFacility makes requests for each
// of the waste commodities (streams) that its table addresses
// It also makes offers of any conditioned waste it contains
remaining_capacity_ = capacity_;
makeRequests();
makeOffers();
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::handleTock(int time){
// TOCK
// On the tock, the ConditioningFacility first prepares
// all material in its stocks up to its monthly processing
// capacity.
conditionMaterials();
printStatus(time);
};
/* --------------------
* this FACILITYMODEL class has these members
* --------------------
*/
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::loadTable(string datafile, string fileformat){
// check that the format is supported
// if not, throw an exception
bool table_okay = verifyTable(datafile, fileformat);
// it will be a matrix
// rows/records = waste stream commodities
// columns/fields = waste forms
// data = loading, grams per m^3
// fill the data table
map<string, void(ConditioningFacility::*)(string)>::iterator format_found;
format_found = allowed_formats_.find(fileformat);
(this->*format_found->second)(datafile);
// match it with commodities
// verify number of commodities matches number of streams
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool ConditioningFacility::verifyTable(string datafile, string fileformat){
// start by assuming the table is bad
bool okay = false;
// if the fileformat is supported
map<string, void(ConditioningFacility::*)(string)>::iterator found = allowed_formats_.find(fileformat);
if (found != allowed_formats_.end()){
okay = true;
} else {
string err = "The file format, ";
err += fileformat;
err += ", is not supported by the Conditioning Facility.\n";
throw CycException(err);
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::loadXMLFile(string datafile){
// get dimensions
// // how many rows
// // how many columns
// create array
throw CycException("XML-based ConditioningFacility input is not yet supported.");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::loadSQLFile(string datafile){
// get dimensions
// // how many rows
// // how many columns
// create array
throw CycException("SQL-based ConditioningFacility input is not yet supported.");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::loadCSVFile(string datafile){
string file_path = Env::getCyclusPath() + "/" + datafile;
// create an ifstream for the file
ifstream file(file_path.c_str());
// and data structures to read the data into
string buffer;
stream_t stream;
if (file.is_open()){
while(file.good()){
// set the buffer string equal to everything up to the next comma
getline(file, buffer, ',');
// copy the data to the typed member of the stream struct
stream.streamID = strtol(buffer.c_str() , NULL, 10);
LOG(LEV_DEBUG2, "CondFac") << "streamID = " << stream.streamID ;;
getline(file, buffer, ',');
stream.formID = strtol(buffer.c_str() , NULL, 10);
LOG(LEV_DEBUG2, "CondFac") << "formID = " << stream.formID ;;
getline(file, buffer, ',');
stream.density = strtod(buffer.c_str() , NULL);
LOG(LEV_DEBUG2, "CondFac") << "density = " << stream.density ;;
getline(file, buffer, ',');
stream.wfvol = strtod(buffer.c_str() , NULL);
LOG(LEV_DEBUG2, "CondFac") << "wfvol = " << stream.wfvol ;;
getline(file, buffer, '\n');
stream.wfmass = strtod(buffer.c_str() , NULL);
LOG(LEV_DEBUG2, "CondFac") << "wfmass = " << stream.wfmass ;;
// put the full struct into the vector of structs
stream_vec_.push_back(stream);
}
file.close();
}
else {
string err = "CSV file, ";
err += file_path;
err += ", not found.";
throw CycException(err);
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::makeRequests(){
// The ConditioningFacility should make requests of all of the things it's
// capable of conditioning for each stream in the matrix
// calculate your capacity to condition
// MAKE A REQUEST
if(this->checkStocks() <= remaining_capacity_){
// It chooses the next in/out commodity pair in the preference lineup
map<string, pair<int, string> >::const_iterator it;
for(it = commod_map_.begin(); it != commod_map_.end(); it++){
string in_commod = (*it).first;
int in_id = (*it).second.first;
double requestAmt;
double minAmt = 0;
// The ConditioningFacility should ask for whatever it can process .
double sto = this->checkStocks();
// subtract sto from remaining_capacity_ to get total empty space.
double space = remaining_capacity_ - sto;
// this will be a request for free stuff
double commod_price = 0;
MarketModel* market = MarketModel::marketForCommod(in_commod);
Communicator* recipient = dynamic_cast<Communicator*>(market);
// if empty space is less than monthly acceptance capacity
requestAmt = space;
// request a generic resource
gen_rsrc_ptr request_res = gen_rsrc_ptr(new GenericResource(in_commod, "kg", requestAmt));
// build the transaction and message
Transaction trans;
trans.commod = in_commod;
trans.minfrac = minAmt/requestAmt;
trans.is_offer = false;
trans.price = commod_price;
trans.resource = request_res;
sendMessage(recipient, trans);
LOG(LEV_DEBUG2, "CondFac") << " The ConditioningFacility has requested "
<< requestAmt
<< " kg of "
<< in_commod
<< ".";
}
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::makeOffers(){
// Offer anything that has been conditioned or can be conditioned this month.
// this will be an offer of free stuff
double commod_price = 0;
// there are potentially many types of material in the inventory stack
double inv = this->checkInventory();
// send an offer for each material on the stack
string outcommod, offers;
Communicator* recipient;
double offer_amt;
for (deque< pair<string, mat_rsrc_ptr > >::iterator iter = inventory_.begin();
iter != inventory_.end();
iter++){
// get out commod
outcommod = iter->first;
MarketModel* market = MarketModel::marketForCommod(outcommod);
// decide what market to offer to
recipient = dynamic_cast<Communicator*>(market);
// get amt
offer_amt = iter->second->quantity();
// make a material to offer
mat_rsrc_ptr offer_mat = iter->second;
offer_mat->setQuantity(offer_amt);
// build the transaction and message
Transaction trans;
trans.commod = outcommod;
trans.minfrac = 1;
trans.is_offer = true;
trans.price = commod_price;
trans.resource = offer_mat;
sendMessage(recipient, trans);
offers += offer_mat->quantity();
offers += " kg ";
offers += outcommod;
if(inventory_.end()!=iter){
offers += " , ";
}
}
LOG(LEV_DEBUG2, "CondFac") << " The ConditioningFacility has offered "
<< offers
<< ".";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::sendMessage(Communicator* recipient, Transaction trans){
msg_ptr msg(new Message(this, recipient, trans));
msg->setNextDest(facInst());
msg->sendOn();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double ConditioningFacility::checkInventory(){
double total = 0;
// Iterate through the inventory and sum the amount of whatever
// material unit is in each object.
for (deque< pair<string, mat_rsrc_ptr> >::iterator iter = inventory_.begin();
iter != inventory_.end();
iter ++){
total += iter->second->quantity();
}
return total;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double ConditioningFacility::checkStocks(){
double total = 0;
// Iterate through the stocks and sum the amount of whatever
// material unit is in each object.
if(!stocks_.empty()){
for (deque< pair<string, mat_rsrc_ptr> >::iterator iter = stocks_.begin();
iter != stocks_.end();
iter ++){
total += iter->second->quantity();
};
};
return total;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::conditionMaterials(){
LOG(LEV_INFO3, "CondFac ") << facName() << " is conditioning {";
// Partition the in-stream according to loading density
// for each stream object in stocks
map<string, mat_rsrc_ptr> remainders;
while( !stocks_.empty() && remaining_capacity_ > 0){
// move stocks to currMat
string currCommod = stocks_.front().first;
mat_rsrc_ptr currMat = stocks_.front().second;
if(remainders.find(currCommod)!=remainders.end()){
(remainders[currCommod])->absorb(condition(currCommod, currMat));
} else {
remainders.insert(make_pair(currCommod, condition(currCommod, currMat)));
}
stocks_.pop_front();
}
map<string, mat_rsrc_ptr>::const_iterator rem;
for(rem=remainders.begin(); rem!=remainders.end(); rem++){
stocks_.push_back(*rem);
}
LOG(LEV_INFO3, "CondFac ") << "}";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mat_rsrc_ptr ConditioningFacility::condition(string commod, mat_rsrc_ptr mat){
stream_t stream = getStream(commod);
double mass_to_condition = stream.wfmass;
double mass_remaining = mat->quantity();
string out_commod;
while( mass_remaining > mass_to_condition && remaining_capacity_ > mass_to_condition) {
out_commod = commod_map_.find(commod)->second.second;
inventory_.push_back(make_pair(out_commod, mat->extract(mass_to_condition)));
remaining_capacity_ = remaining_capacity_ - mass_to_condition;
mass_remaining = mat->quantity();
// log the fact that we just conditioned stuff
LOG(LEV_INFO3, "CondFac ") << " " << commod << " has been conditioned into " <<
out_commod << " with mass : " << mass_to_condition;
current_cond_rsrc_id_ = TI->time();
addToTable();
}
return mat;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ConditioningFacility::stream_t ConditioningFacility::getStream(string commod){
int stream_id =(commod_map_.find(commod))->second.first;
vector<stream_t>::const_iterator it = stream_vec_.begin();
bool found = false;
stream_t toRet;
while(!found){
if((*it).streamID == stream_id){
toRet = (*it);
found = true;
} else if (it == stream_vec_.end() ) {
string msg;
msg += "The stream for id ";
msg += stream_id;
msg += " was not found in the ConditioningFacility stream map.";
throw CycException(msg);
} else {
it++;
}
}
return toRet;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::printStatus(int time){
// For now, lets just print out what we have at each timestep.
LOG(LEV_DEBUG2, "CondFac") << "ConditioningFacility " << this->ID()
<< " is holding " << this->checkInventory()
<< " units of material in inventory, and "
<< this->checkStocks()
<< " in stocks at the close of month "
<< time
<< ".";
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::define_table() {
// declare the table columns
vector<column> col_vec;
col_vec.push_back(make_pair("ID","INTEGER"));
col_vec.push_back(make_pair("Time","INTEGER"));
col_vec.push_back(make_pair("ConditionedRsrcID","INTEGER"));
// declare the table's primary key
primary_key pk;
pk.push_back("ID"), pk.push_back("ConditionedRsrcID");
cond_fac_table->setPrimaryKey(pk);
// add columns to the table
vector<column>::iterator it;
for(it=col_vec.begin(); it!=col_vec.end();it++){
cond_fac_table->addColumn((*it));
}
// we've now defined the table
cond_fac_table->tableDefined();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ConditioningFacility::addToTable(){
// if we haven't logged some conditioned material yet, define the table
if ( !cond_fac_table->defined() ) {
ConditioningFacility::define_table();
}
// make a row
// declare data
data an_id( this->ID() ), a_time( TI->time() ),
a_rsrc_id( this->current_cond_rsrc_id_ );
// declare entries
entry id("ID",an_id), time("Time",a_time), rid("ConditionedRsrcID",a_rsrc_id);
// declare row
row aRow;
aRow.push_back(id), aRow.push_back(time), aRow.push_back(rid);
// add the row
cond_fac_table->addRow(aRow);
}
/* --------------------
* all MODEL classes have these members
* --------------------
*/
extern "C" Model* constructConditioningFacility() {
return new ConditioningFacility();
}
/* ------------------- */
|
/**
* @file
* @author Jason Lingle
* @date 2012.03.15
* @brief Implementation of NetworkGame classes.
*/
#include <map>
#include <set>
#include <string>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <iterator>
#include <sstream>
#include <cassert>
#include <asio.hpp>
#include "network_game.hxx"
#include "network_geraet.hxx"
#include "tuner.hxx"
#include "connection_listener.hxx"
#include "seq_text_geraet.hxx"
#include "text_message_geraet.hxx"
#include "async_ack_geraet.hxx"
#include "io.hxx"
#include "globalid.hxx"
#include "game_advertiser.hxx"
#include "game_discoverer.hxx"
using namespace std;
namespace network_game {
/* Simple ConnectionListener to forward connection attempts to NetworkGame.
*/
class NGConnectionListener: public ConnectionListener {
NetworkGame*const game;
public:
NGConnectionListener(NetworkGame* game_)
: ConnectionListener(game_->assembly.getTuner()),
game(game_)
{ }
virtual bool acceptConnection(const Antenna::endpoint& source,
Antenna* antenna, Tuner* tuner,
string& errmsg, string& errl10n)
noth {
return game->acceptConnection(source, errmsg, errl10n);
}
};
/* Handles encoding and decoding of sequential text messages, including
* message types and fragmentation, and provides a symbolic interface to
* the messaging system.
*/
class NGSeqTextGeraet: public SeqTextInputGeraet, public SeqTextOutputGeraet {
//Accumulation of input extensions
string extension;
//Allow finding the output side associated with each NetworkConnection
typedef map<NetworkConnection*,NGSeqTextGeraet*> geraete_t;
static geraete_t geraete;
NetworkGame*const game;
public:
static const NetworkConnection::geraet_num num;
NGSeqTextGeraet(NetworkGame* game_, NetworkConnection* cxn)
: SeqTextInputGeraet(cxn->aag, InputNetworkGeraet::DSEternal),
SeqTextOutputGeraet(cxn->aag, OutputNetworkGeraet::DSBidir),
game(game_)
{
geraete[cxn] = this;
}
virtual ~NGSeqTextGeraet() {
geraete.erase(cxn);
}
virtual void receiveText(string txt) noth {
if (txt.empty()) {
#ifdef DEBUG
cerr << "Warning: Ignoring empty sequential text message" << endl;
#endif
return;
}
const char* body = txt.c_str()+1;
//Don't let the remote system fill up memory with extensions
if (extension.size() < 65536)
extension += body;
else {
#ifdef DEBUG
cerr << "Warning: STG ext dropped due to extension size"<< endl;
#endif
}
switch (txt[0]) {
case 'x':
return; //Nothing further to do, and don't clear extension
case 'o':
if (game->iface)
game->iface->receiveOverseer(game->peers[cxn], extension.c_str());
break;
case 'u':
if (game->iface)
game->iface->receiveUnicast(game->peers[cxn], extension.c_str());
break;
case 'b':
if (game->iface)
game->iface->receiveBroadcast(game->peers[cxn], extension.c_str());
break;
case 's':
if (game->iface && game->overseer == game->peers[cxn])
game->iface->alterDats(extension.c_str());
break;
case 'p':
if (game->iface)
game->iface->alterDatp(game->peers[cxn], extension.c_str());
break;
case 'M':
if (game->iface && game->overseer == game->peers[cxn])
game->iface->setGameMode(extension.c_str());
break;
case 'V':
//TODO
break;
case 'R':
game->peerIsOverseerReady(game->peers[cxn]);
break;
default:
#ifdef DEBUG
cerr << "Warning: Ignoring unknown STG message: " << txt[0] << endl;
#endif
break;
}
//Clear accumulated text
extension.clear();
}
void sendOverseer(const std::string& str) throw() {
send(str, 'o');
}
void sendUnicast(const std::string& str) throw() {
send(str, 'u');
}
void sendBroadcast(const std::string& str) throw() {
send(str, 'b');
}
void sendDats(const std::string& str) throw() {
send(str, 's');
}
void sendDatp(const std::string& str) throw() {
send(str, 'p');
}
void sendMode(const std::string& str) throw() {
send(str, 'M');
}
void sendVote(const std::string& str) throw() {
send(str, 'V');
}
void sendReady() throw() {
SeqTextOutputGeraet::send(string("R"));
}
private:
void send(const std::string& str, char type) throw() {
static const unsigned segsz = 250;
for (unsigned i=0; i<str.size(); i += segsz) {
//Only the last (where i+segsz >= str.size()) gets the actual type;
//other fragments have type x for extension.
string msg(1, i+segsz < str.size()? 'x' : type);
msg += str.substr(i, segsz);
SeqTextOutputGeraet::send(msg);
}
}
static InputNetworkGeraet* create(NetworkConnection* cxn) {
geraete_t::iterator it = geraete.find(cxn);
if (it == geraete.end()) return NULL;
InputNetworkGeraet* ong = it->second;
geraete.erase(it);
return ong;
}
};
NGSeqTextGeraet::geraete_t NGSeqTextGeraet::geraete;
const NetworkConnection::geraet_num NGSeqTextGeraet::num =
NetworkConnection::registerGeraetCreator(&create, 2);
/* Handles both sides of the PeerConnectivityGeraet (see documentation in
* newnetworking.txt).
*
* Since this has a strong dependency on NetworkGame, it is not placed in
* a separate header/implementation file pair.
*/
class PeerConnectivityGeraet: public AAGReceiver, public ReliableSender {
//Map NetworkConnection*s to unopened input sides.
typedef map<NetworkConnection*,PeerConnectivityGeraet*> geraete_t;
static geraete_t geraete;
NetworkGame*const game;
//Sizes of GlobalID data for IPv4 and IPv6, respectively
static const unsigned ipv4size = 2*(4+2);
static const unsigned ipv6size = 2*(8*2+2);
public:
static const unsigned positiveDec = 0,
negativeDec = 1,
specificQuery = 2,
generalQuery = 3;
static const NetworkConnection::geraet_num num;
PeerConnectivityGeraet(NetworkConnection* cxn, NetworkGame* game_)
: AAGReceiver(cxn->aag, InputNetworkGeraet::DSEternal),
ReliableSender(cxn->aag, OutputNetworkGeraet::DSBidir),
game(game_)
{
geraete[cxn] = this;
}
virtual ~PeerConnectivityGeraet() {
geraete.erase(cxn);
}
void sendPacket(unsigned type, const GlobalID& gid) throw() {
byte pack[NetworkConnection::headerSize + 1 + ipv6size];
byte* dst = pack+NetworkConnection::headerSize;
*dst++ = type;
unsigned gidlen = writeGid(dst, gid);
send(pack, NetworkConnection::headerSize + 1 + gidlen);
}
void sendGeneralQuery() throw() {
byte pack[NetworkConnection::headerSize + 1];
pack[NetworkConnection::headerSize] = generalQuery;
send(pack, sizeof(pack));
}
protected:
virtual void receiveAccepted(NetworkConnection::seq_t seq, const byte* data,
unsigned len)
throw() {
if (!len) {
#ifdef DEBUG
cerr << "Warning: Dropping empty packet to Peer Connectivity Geraet."
<< endl;
#endif
return;
}
GlobalID gid;
unsigned type = data[0];
++data, --len;
switch (type) {
case positiveDec:
case negativeDec:
if (len == ipv4size)
readGid(gid, data, true);
else if (len == ipv6size)
readGid(gid, data, false);
else {
#ifdef DEBUG
cerr << "Warning: Dropping packet with bad length to Peer"
<< "Connectivity Geraet" << endl;
#endif
return;
}
game->receivePCGDeclaration(game->peers[cxn], gid,
type == positiveDec);
break;
case specificQuery:
if (len == ipv4size)
readGid(gid, data, true);
else if (len == ipv6size)
readGid(gid, data, false);
else {
#ifdef DEBUG
cerr << "Warning: Dropping packet with bad length to Peer"
<< "Connectivity Geraet" << endl;
#endif
return;
}
game->receivePCGQuery(game->peers[cxn], gid);
break;
case generalQuery:
game->receivePCGGeneralQuery(game->peers[cxn]);
break;
default:
#ifdef DEBUG
cerr << "Warning: Dropping packet of unknown type "
<< type << " to Peer Connectivity Geraet" << endl;
#endif
return;
}
}
private:
static InputNetworkGeraet* create(NetworkConnection* cxn) {
geraete_t::iterator it = geraete.find(cxn);
if (it == geraete.end()) return NULL;
InputNetworkGeraet* ing = it->second;
geraete.erase(it);
return ing;
}
unsigned writeGid(byte* dst, const GlobalID& gid) const throw() {
if (gid.ipv == GlobalID::IPv4) {
memcpy(dst, gid.ia4, 4);
dst += 4;
io::write(dst, gid.iport);
memcpy(dst, gid.la4, 4);
dst += 4;
io::write(dst, gid.lport);
return ipv4size;
} else {
for (unsigned i=0; i<8; ++i)
io::write(dst, gid.ia6[i]);
io::write(dst, gid.iport);
for (unsigned i=0; i<8; ++i)
io::write(dst, gid.la6[i]);
io::write(dst, gid.lport);
return ipv6size;
}
}
void readGid(GlobalID& gid, const byte* src, bool ipv4) const throw() {
if (ipv4) {
memcpy(gid.ia4, src, 4);
src += 4;
io::read(src, gid.iport);
memcpy(gid.la4, src, 4);
src += 4;
io::read(src, gid.lport);
gid.ipv = GlobalID::IPv4;
} else {
for (unsigned i=0; i<8; ++i)
io::read(src, gid.ia6[i]);
io::read(src, gid.iport);
for (unsigned i=0; i<8; ++i)
io::read(src, gid.la6[i]);
io::read(src, gid.lport);
gid.ipv = GlobalID::IPv6;
}
}
};
PeerConnectivityGeraet::geraete_t PeerConnectivityGeraet::geraete;
const NetworkConnection::geraet_num PeerConnectivityGeraet::num =
NetworkConnection::registerGeraetCreator(&create, 5);
}
NetworkGame::NetworkGame(GameField* field)
: overseer(NULL), assembly(field, &antenna),
iface(NULL), advertiser(NULL), discoverer(NULL),
timeSinceSpuriousPCGQuery(0)
{
localPeer.overseerReady=false;
localPeer.connectionAttempts=0;
localPeer.cxn = NULL;
}
NetworkGame::~NetworkGame() {
if (advertiser)
delete advertiser;
if (discoverer)
delete discoverer;
if (listener)
delete listener;
}
void NetworkGame::setNetIface(NetIface* ifc) throw() {
iface = ifc;
}
void NetworkGame::setAdvertising(const char* gameMode) throw() {
if (advertiser)
advertiser->setGameMode(gameMode);
else
advertiser = new GameAdvertiser(assembly.getTuner(),
localPeer.gid.ipv == GlobalID::IPv6,
overseer? overseer->nid : localPeer.nid,
peers.size()+1, //+1 for self
false, //TODO
gameMode);
}
void NetworkGame::stopAdvertising() throw() {
if (advertiser) {
delete advertiser;
advertiser = NULL;
}
}
void NetworkGame::startDiscoveryScan() throw() {
if (!discoverer)
discoverer = new GameDiscoverer(assembly.getTuner());
discoverer->start();
}
float NetworkGame::discoveryScanProgress() const throw() {
if (discoverer)
return discoverer->progress();
else
return 0;
}
bool NetworkGame::discoveryScanDone() const throw() {
return discoverer && 1.0f == discoverer->progress();
}
string NetworkGame::getDiscoveryResults() throw() {
ostringstream oss;
if (!discoverer) return oss.str();
const vector<GameDiscoverer::Result>& results = discoverer->getResults();
for (unsigned i=0; i<results.size(); ++i) {
char gameMode[5], buffer[256];
string ipa(results[i].peer.address().to_string());
//Get NTBS from game mode
strncpy(gameMode, results[i].gameMode, sizeof(gameMode));
//TODO: localise game mode (doing so will also sanitise it of characters
//such as \} that would otherwise break the list)
#ifndef WIN32
#warning Game mode not localised in NetworkGame::getDiscoveryResults()
#endif
sprintf(buffer, "{%4s %02d %c %s} ",
gameMode, results[i].peerCount,
results[i].passwordProtected? '*' : ' ',
ipa.c_str());
oss << buffer;
}
return oss.str();
}
void NetworkGame::connectToNothing(bool v6, bool lanMode) throw() {
initialiseListener(v6);
this->lanMode = lanMode;
//Since we need no data from anyone, we are immediately overseer-ready
localPeer.overseerReady = true;
}
void NetworkGame::connectToLan(const char* ipaddress, unsigned port) throw() {
lanMode = true;
asio::ip::address address;
//It would be nice if Asio's documentation on from_string actually specified
//what would happen when the address is invalid (I found this out by trial
//and error...)
try {
address = asio::ip::address::from_string(ipaddress);
} catch (asio::system_error err) {
//Invalid address
lastDisconnectReason = err.what();
if (iface)
iface->connectionLost(lastDisconnectReason.c_str());
return;
}
initialiseListener(address.is_v6());
createPeer(asio::ip::udp::endpoint(address, port));
}
bool NetworkGame::acceptConnection(const Antenna::endpoint& source,
string& errmsg, string& errl10n)
throw() {
/* If there already exists a NetworkConnection to this endpoint, return true
* but do nothing else (this could happen if we opened a NetworkConnection
* before updating the NetworkAssembly).
*
* Otherwise, count the number of connections from the given IP address. If
* it is already 4 or greater, deny the connection.
*
* Also deny the connection if the remote host is using a different IP
* version than we are expecting.
*/
unsigned addressCount = 0;
if (source.address().is_v6() != (localPeer.gid.ipv == GlobalID::IPv6)) {
errmsg = "Wrong IP version";
errl10n = "wrong_ip_version";
return false;
}
for (unsigned i=0; i < assembly.numConnections(); ++i) {
const NetworkConnection* cxn = assembly.getConnection(i);
if (cxn->endpoint == source) {
//Already have this connection
return true;
}
if (cxn->endpoint.address() == source.address())
++addressCount;
}
if (addressCount >= 4)
return false;
//All checks passed
NetworkConnection* cxn = new NetworkConnection(&assembly, source, true);
assembly.addConnection(cxn);
createPeer(cxn);
return true;
}
void NetworkGame::peerIsOverseerReady(Peer* peer) throw() {
peer->overseerReady = true;
refreshOverseer();
}
void NetworkGame::receivePCGDeclaration(Peer* peer, const GlobalID& gid,
bool positive)
throw() {
Peer* referred = getPeerByGid(gid);
if (positive) {
if (referred)
peer->connectionsFrom.insert(referred);
else if (overseer == peer)
//Newly discovered peer
peer->connectionsFrom.insert(createPeer(gid));
} else {
if (referred) {
//If this is comming from the overseer, take it as an instruction to
//disconnect. Otherwise, just record the lost connection.
if (overseer == peer)
closePeer(referred, 15000); //15-second "ban" to prevent reconnect attempts
peer->connectionsFrom.erase(referred);
delete referred;
}
//Else, we know nothing of this peer, so just ignore.
}
}
void NetworkGame::receivePCGQuery(Peer* peer, const GlobalID& gid)
throw() {
bool positive = (bool)getPeerByGid(gid);
//Broadcast answer to all peers
unsigned type = positive?
/* G++ for some reason wants to externalise these when used here.
* But we can't make them proper constants (eg, with effectively extern
* linkage) because we need them to be usable in constexprs.
* So we're just substituting the values in by hand for now...
network_game::PeerConnectivityGeraet::positiveDec :
network_game::PeerConnectivityGeraet::negativeDec;
*/ 0:1;
for (pcgs_t::const_iterator it = pcgs.begin(); it != pcgs.end(); ++it)
it->second->sendPacket(type, gid);
}
void NetworkGame::receivePCGGeneralQuery(Peer* peer) throw() {
//Send responses to sender
network_game::PeerConnectivityGeraet* pcg = pcgs[peer->cxn];
for (peers_t::const_iterator it = peers.begin(); it != peers.end(); ++it)
pcg->sendPacket(network_game::PeerConnectivityGeraet::positiveDec,
it->second->gid);
}
void NetworkGame::initialiseListener(bool ipv6) throw() {
localPeer.gid = *(ipv6? antenna.getGlobalID6() : antenna.getGlobalID4());
listener = new network_game::NGConnectionListener(this);
}
void NetworkGame::endpointToLanGid(GlobalID& gid,
const asio::ip::udp::endpoint& endpoint)
throw() {
const asio::ip::address& address = endpoint.address();
if (address.is_v4()) {
gid.ipv = GlobalID::IPv4;
const asio::ip::address_v4 addr(address.to_v4());
memcpy(gid.la4, &addr.to_bytes()[0], 4);
} else {
gid.ipv = GlobalID::IPv6;
const asio::ip::address_v6 addr(address.to_v6());
const asio::ip::address_v6::bytes_type data(addr.to_bytes());
for (unsigned i=0; i<8; ++i)
gid.la6[i] = data[i*2] | (data[i*2+1] << 8);
}
gid.lport = endpoint.port();
}
Peer* NetworkGame::createPeer(const asio::ip::udp::endpoint& endpoint) throw() {
//This should only be called in lanMode.
assert(lanMode);
//Convert to a GlobalID and connect to that.
GlobalID gid;
endpointToLanGid(gid, endpoint);
return createPeer(gid);
}
Peer* NetworkGame::createPeer(const GlobalID& gid) throw() {
Peer* peer = new Peer;
peer->gid = gid;
peer->overseerReady = false;
peer->connectionAttempts = 0;
peer->cxn = NULL;
connectToPeer(peer);
}
Peer* NetworkGame::createPeer(NetworkConnection* cxn) throw() {
Peer* peer = new Peer;
//TODO: For now, just infer the gid from the IP address.
#ifndef WIN32
#warning NetworkGame::createPeer(NetworkConnection*) does not honour provided GID
#endif
endpointToLanGid(peer->gid, cxn->endpoint);
//TODO: Numeric ID
#ifndef WIN32
#warning NetworkGame::createPeer(NetworkConnection*) does not set NID
#endif
peer->overseerReady = false;
peer->connectionAttempts = 0;
peer->cxn = cxn;
peers[cxn] = peer;
}
void NetworkGame::connectToPeer(Peer* peer) throw() {
//TODO
}
void NetworkGame::closePeer(Peer* peer, unsigned banLength) throw() {
//TODO
}
void NetworkGame::refreshOverseer() throw() {
//TODO
}
Peer* NetworkGame::getPeerByGid(const GlobalID& gid) throw() {
//TODO
}
void NetworkGame::update(unsigned et) throw() {
//TODO
}
Implement NetworkGame::closeConnection().
/**
* @file
* @author Jason Lingle
* @date 2012.03.15
* @brief Implementation of NetworkGame classes.
*/
#include <map>
#include <set>
#include <string>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <iterator>
#include <sstream>
#include <cassert>
#include <asio.hpp>
#include "network_game.hxx"
#include "network_geraet.hxx"
#include "tuner.hxx"
#include "connection_listener.hxx"
#include "seq_text_geraet.hxx"
#include "text_message_geraet.hxx"
#include "async_ack_geraet.hxx"
#include "io.hxx"
#include "globalid.hxx"
#include "game_advertiser.hxx"
#include "game_discoverer.hxx"
#include "synchronous_control_geraet.hxx"
using namespace std;
namespace network_game {
/* Simple ConnectionListener to forward connection attempts to NetworkGame.
*/
class NGConnectionListener: public ConnectionListener {
NetworkGame*const game;
public:
NGConnectionListener(NetworkGame* game_)
: ConnectionListener(game_->assembly.getTuner()),
game(game_)
{ }
virtual bool acceptConnection(const Antenna::endpoint& source,
Antenna* antenna, Tuner* tuner,
string& errmsg, string& errl10n)
noth {
return game->acceptConnection(source, errmsg, errl10n);
}
};
/* Handles encoding and decoding of sequential text messages, including
* message types and fragmentation, and provides a symbolic interface to
* the messaging system.
*/
class NGSeqTextGeraet: public SeqTextInputGeraet, public SeqTextOutputGeraet {
//Accumulation of input extensions
string extension;
//Allow finding the output side associated with each NetworkConnection
typedef map<NetworkConnection*,NGSeqTextGeraet*> geraete_t;
static geraete_t geraete;
NetworkGame*const game;
public:
static const NetworkConnection::geraet_num num;
NGSeqTextGeraet(NetworkGame* game_, NetworkConnection* cxn)
: SeqTextInputGeraet(cxn->aag, InputNetworkGeraet::DSEternal),
SeqTextOutputGeraet(cxn->aag, OutputNetworkGeraet::DSBidir),
game(game_)
{
geraete[cxn] = this;
}
virtual ~NGSeqTextGeraet() {
geraete.erase(cxn);
}
virtual void receiveText(string txt) noth {
if (txt.empty()) {
#ifdef DEBUG
cerr << "Warning: Ignoring empty sequential text message" << endl;
#endif
return;
}
const char* body = txt.c_str()+1;
//Don't let the remote system fill up memory with extensions
if (extension.size() < 65536)
extension += body;
else {
#ifdef DEBUG
cerr << "Warning: STG ext dropped due to extension size"<< endl;
#endif
}
switch (txt[0]) {
case 'x':
return; //Nothing further to do, and don't clear extension
case 'o':
if (game->iface)
game->iface->receiveOverseer(game->peers[cxn], extension.c_str());
break;
case 'u':
if (game->iface)
game->iface->receiveUnicast(game->peers[cxn], extension.c_str());
break;
case 'b':
if (game->iface)
game->iface->receiveBroadcast(game->peers[cxn], extension.c_str());
break;
case 's':
if (game->iface && game->overseer == game->peers[cxn])
game->iface->alterDats(extension.c_str());
break;
case 'p':
if (game->iface)
game->iface->alterDatp(game->peers[cxn], extension.c_str());
break;
case 'M':
if (game->iface && game->overseer == game->peers[cxn])
game->iface->setGameMode(extension.c_str());
break;
case 'V':
//TODO
break;
case 'R':
game->peerIsOverseerReady(game->peers[cxn]);
break;
default:
#ifdef DEBUG
cerr << "Warning: Ignoring unknown STG message: " << txt[0] << endl;
#endif
break;
}
//Clear accumulated text
extension.clear();
}
void sendOverseer(const std::string& str) throw() {
send(str, 'o');
}
void sendUnicast(const std::string& str) throw() {
send(str, 'u');
}
void sendBroadcast(const std::string& str) throw() {
send(str, 'b');
}
void sendDats(const std::string& str) throw() {
send(str, 's');
}
void sendDatp(const std::string& str) throw() {
send(str, 'p');
}
void sendMode(const std::string& str) throw() {
send(str, 'M');
}
void sendVote(const std::string& str) throw() {
send(str, 'V');
}
void sendReady() throw() {
SeqTextOutputGeraet::send(string("R"));
}
private:
void send(const std::string& str, char type) throw() {
static const unsigned segsz = 250;
for (unsigned i=0; i<str.size(); i += segsz) {
//Only the last (where i+segsz >= str.size()) gets the actual type;
//other fragments have type x for extension.
string msg(1, i+segsz < str.size()? 'x' : type);
msg += str.substr(i, segsz);
SeqTextOutputGeraet::send(msg);
}
}
static InputNetworkGeraet* create(NetworkConnection* cxn) {
geraete_t::iterator it = geraete.find(cxn);
if (it == geraete.end()) return NULL;
InputNetworkGeraet* ong = it->second;
geraete.erase(it);
return ong;
}
};
NGSeqTextGeraet::geraete_t NGSeqTextGeraet::geraete;
const NetworkConnection::geraet_num NGSeqTextGeraet::num =
NetworkConnection::registerGeraetCreator(&create, 2);
/* Handles both sides of the PeerConnectivityGeraet (see documentation in
* newnetworking.txt).
*
* Since this has a strong dependency on NetworkGame, it is not placed in
* a separate header/implementation file pair.
*/
class PeerConnectivityGeraet: public AAGReceiver, public ReliableSender {
//Map NetworkConnection*s to unopened input sides.
typedef map<NetworkConnection*,PeerConnectivityGeraet*> geraete_t;
static geraete_t geraete;
NetworkGame*const game;
//Sizes of GlobalID data for IPv4 and IPv6, respectively
static const unsigned ipv4size = 2*(4+2);
static const unsigned ipv6size = 2*(8*2+2);
public:
static const unsigned positiveDec = 0,
negativeDec = 1,
specificQuery = 2,
generalQuery = 3;
static const NetworkConnection::geraet_num num;
PeerConnectivityGeraet(NetworkConnection* cxn, NetworkGame* game_)
: AAGReceiver(cxn->aag, InputNetworkGeraet::DSEternal),
ReliableSender(cxn->aag, OutputNetworkGeraet::DSBidir),
game(game_)
{
geraete[cxn] = this;
}
virtual ~PeerConnectivityGeraet() {
geraete.erase(cxn);
}
void sendPacket(unsigned type, const GlobalID& gid) throw() {
byte pack[NetworkConnection::headerSize + 1 + ipv6size];
byte* dst = pack+NetworkConnection::headerSize;
*dst++ = type;
unsigned gidlen = writeGid(dst, gid);
send(pack, NetworkConnection::headerSize + 1 + gidlen);
}
void sendGeneralQuery() throw() {
byte pack[NetworkConnection::headerSize + 1];
pack[NetworkConnection::headerSize] = generalQuery;
send(pack, sizeof(pack));
}
protected:
virtual void receiveAccepted(NetworkConnection::seq_t seq, const byte* data,
unsigned len)
throw() {
if (!len) {
#ifdef DEBUG
cerr << "Warning: Dropping empty packet to Peer Connectivity Geraet."
<< endl;
#endif
return;
}
GlobalID gid;
unsigned type = data[0];
++data, --len;
switch (type) {
case positiveDec:
case negativeDec:
if (len == ipv4size)
readGid(gid, data, true);
else if (len == ipv6size)
readGid(gid, data, false);
else {
#ifdef DEBUG
cerr << "Warning: Dropping packet with bad length to Peer"
<< "Connectivity Geraet" << endl;
#endif
return;
}
game->receivePCGDeclaration(game->peers[cxn], gid,
type == positiveDec);
break;
case specificQuery:
if (len == ipv4size)
readGid(gid, data, true);
else if (len == ipv6size)
readGid(gid, data, false);
else {
#ifdef DEBUG
cerr << "Warning: Dropping packet with bad length to Peer"
<< "Connectivity Geraet" << endl;
#endif
return;
}
game->receivePCGQuery(game->peers[cxn], gid);
break;
case generalQuery:
game->receivePCGGeneralQuery(game->peers[cxn]);
break;
default:
#ifdef DEBUG
cerr << "Warning: Dropping packet of unknown type "
<< type << " to Peer Connectivity Geraet" << endl;
#endif
return;
}
}
private:
static InputNetworkGeraet* create(NetworkConnection* cxn) {
geraete_t::iterator it = geraete.find(cxn);
if (it == geraete.end()) return NULL;
InputNetworkGeraet* ing = it->second;
geraete.erase(it);
return ing;
}
unsigned writeGid(byte* dst, const GlobalID& gid) const throw() {
if (gid.ipv == GlobalID::IPv4) {
memcpy(dst, gid.ia4, 4);
dst += 4;
io::write(dst, gid.iport);
memcpy(dst, gid.la4, 4);
dst += 4;
io::write(dst, gid.lport);
return ipv4size;
} else {
for (unsigned i=0; i<8; ++i)
io::write(dst, gid.ia6[i]);
io::write(dst, gid.iport);
for (unsigned i=0; i<8; ++i)
io::write(dst, gid.la6[i]);
io::write(dst, gid.lport);
return ipv6size;
}
}
void readGid(GlobalID& gid, const byte* src, bool ipv4) const throw() {
if (ipv4) {
memcpy(gid.ia4, src, 4);
src += 4;
io::read(src, gid.iport);
memcpy(gid.la4, src, 4);
src += 4;
io::read(src, gid.lport);
gid.ipv = GlobalID::IPv4;
} else {
for (unsigned i=0; i<8; ++i)
io::read(src, gid.ia6[i]);
io::read(src, gid.iport);
for (unsigned i=0; i<8; ++i)
io::read(src, gid.la6[i]);
io::read(src, gid.lport);
gid.ipv = GlobalID::IPv6;
}
}
};
PeerConnectivityGeraet::geraete_t PeerConnectivityGeraet::geraete;
const NetworkConnection::geraet_num PeerConnectivityGeraet::num =
NetworkConnection::registerGeraetCreator(&create, 5);
}
NetworkGame::NetworkGame(GameField* field)
: overseer(NULL), assembly(field, &antenna),
iface(NULL), advertiser(NULL), discoverer(NULL),
timeSinceSpuriousPCGQuery(0)
{
localPeer.overseerReady=false;
localPeer.connectionAttempts=0;
localPeer.cxn = NULL;
}
NetworkGame::~NetworkGame() {
if (advertiser)
delete advertiser;
if (discoverer)
delete discoverer;
if (listener)
delete listener;
}
void NetworkGame::setNetIface(NetIface* ifc) throw() {
iface = ifc;
}
void NetworkGame::setAdvertising(const char* gameMode) throw() {
if (advertiser)
advertiser->setGameMode(gameMode);
else
advertiser = new GameAdvertiser(assembly.getTuner(),
localPeer.gid.ipv == GlobalID::IPv6,
overseer? overseer->nid : localPeer.nid,
peers.size()+1, //+1 for self
false, //TODO
gameMode);
}
void NetworkGame::stopAdvertising() throw() {
if (advertiser) {
delete advertiser;
advertiser = NULL;
}
}
void NetworkGame::startDiscoveryScan() throw() {
if (!discoverer)
discoverer = new GameDiscoverer(assembly.getTuner());
discoverer->start();
}
float NetworkGame::discoveryScanProgress() const throw() {
if (discoverer)
return discoverer->progress();
else
return 0;
}
bool NetworkGame::discoveryScanDone() const throw() {
return discoverer && 1.0f == discoverer->progress();
}
string NetworkGame::getDiscoveryResults() throw() {
ostringstream oss;
if (!discoverer) return oss.str();
const vector<GameDiscoverer::Result>& results = discoverer->getResults();
for (unsigned i=0; i<results.size(); ++i) {
char gameMode[5], buffer[256];
string ipa(results[i].peer.address().to_string());
//Get NTBS from game mode
strncpy(gameMode, results[i].gameMode, sizeof(gameMode));
//TODO: localise game mode (doing so will also sanitise it of characters
//such as \} that would otherwise break the list)
#ifndef WIN32
#warning Game mode not localised in NetworkGame::getDiscoveryResults()
#endif
sprintf(buffer, "{%4s %02d %c %s} ",
gameMode, results[i].peerCount,
results[i].passwordProtected? '*' : ' ',
ipa.c_str());
oss << buffer;
}
return oss.str();
}
void NetworkGame::connectToNothing(bool v6, bool lanMode) throw() {
initialiseListener(v6);
this->lanMode = lanMode;
//Since we need no data from anyone, we are immediately overseer-ready
localPeer.overseerReady = true;
}
void NetworkGame::connectToLan(const char* ipaddress, unsigned port) throw() {
lanMode = true;
asio::ip::address address;
//It would be nice if Asio's documentation on from_string actually specified
//what would happen when the address is invalid (I found this out by trial
//and error...)
try {
address = asio::ip::address::from_string(ipaddress);
} catch (asio::system_error err) {
//Invalid address
lastDisconnectReason = err.what();
if (iface)
iface->connectionLost(lastDisconnectReason.c_str());
return;
}
initialiseListener(address.is_v6());
createPeer(asio::ip::udp::endpoint(address, port));
}
bool NetworkGame::acceptConnection(const Antenna::endpoint& source,
string& errmsg, string& errl10n)
throw() {
/* If there already exists a NetworkConnection to this endpoint, return true
* but do nothing else (this could happen if we opened a NetworkConnection
* before updating the NetworkAssembly).
*
* Otherwise, count the number of connections from the given IP address. If
* it is already 4 or greater, deny the connection.
*
* Also deny the connection if the remote host is using a different IP
* version than we are expecting.
*/
unsigned addressCount = 0;
if (source.address().is_v6() != (localPeer.gid.ipv == GlobalID::IPv6)) {
errmsg = "Wrong IP version";
errl10n = "wrong_ip_version";
return false;
}
for (unsigned i=0; i < assembly.numConnections(); ++i) {
const NetworkConnection* cxn = assembly.getConnection(i);
if (cxn->endpoint == source) {
//Already have this connection
return true;
}
if (cxn->endpoint.address() == source.address())
++addressCount;
}
if (addressCount >= 4)
return false;
//All checks passed
NetworkConnection* cxn = new NetworkConnection(&assembly, source, true);
assembly.addConnection(cxn);
createPeer(cxn);
return true;
}
void NetworkGame::peerIsOverseerReady(Peer* peer) throw() {
peer->overseerReady = true;
refreshOverseer();
}
void NetworkGame::receivePCGDeclaration(Peer* peer, const GlobalID& gid,
bool positive)
throw() {
Peer* referred = getPeerByGid(gid);
if (positive) {
if (referred)
peer->connectionsFrom.insert(referred);
else if (overseer == peer)
//Newly discovered peer
peer->connectionsFrom.insert(createPeer(gid));
} else {
if (referred) {
//If this is comming from the overseer, take it as an instruction to
//disconnect. Otherwise, just record the lost connection.
if (overseer == peer)
closePeer(referred, 15000); //15-second "ban" to prevent reconnect attempts
peer->connectionsFrom.erase(referred);
delete referred;
}
//Else, we know nothing of this peer, so just ignore.
}
}
void NetworkGame::receivePCGQuery(Peer* peer, const GlobalID& gid)
throw() {
bool positive = (bool)getPeerByGid(gid);
//Broadcast answer to all peers
unsigned type = positive?
/* G++ for some reason wants to externalise these when used here.
* But we can't make them proper constants (eg, with effectively extern
* linkage) because we need them to be usable in constexprs.
* So we're just substituting the values in by hand for now...
network_game::PeerConnectivityGeraet::positiveDec :
network_game::PeerConnectivityGeraet::negativeDec;
*/ 0:1;
for (pcgs_t::const_iterator it = pcgs.begin(); it != pcgs.end(); ++it)
it->second->sendPacket(type, gid);
}
void NetworkGame::receivePCGGeneralQuery(Peer* peer) throw() {
//Send responses to sender
network_game::PeerConnectivityGeraet* pcg = pcgs[peer->cxn];
for (peers_t::const_iterator it = peers.begin(); it != peers.end(); ++it)
pcg->sendPacket(network_game::PeerConnectivityGeraet::positiveDec,
it->second->gid);
}
void NetworkGame::initialiseListener(bool ipv6) throw() {
localPeer.gid = *(ipv6? antenna.getGlobalID6() : antenna.getGlobalID4());
listener = new network_game::NGConnectionListener(this);
}
void NetworkGame::endpointToLanGid(GlobalID& gid,
const asio::ip::udp::endpoint& endpoint)
throw() {
const asio::ip::address& address = endpoint.address();
if (address.is_v4()) {
gid.ipv = GlobalID::IPv4;
const asio::ip::address_v4 addr(address.to_v4());
memcpy(gid.la4, &addr.to_bytes()[0], 4);
} else {
gid.ipv = GlobalID::IPv6;
const asio::ip::address_v6 addr(address.to_v6());
const asio::ip::address_v6::bytes_type data(addr.to_bytes());
for (unsigned i=0; i<8; ++i)
gid.la6[i] = data[i*2] | (data[i*2+1] << 8);
}
gid.lport = endpoint.port();
}
Peer* NetworkGame::createPeer(const asio::ip::udp::endpoint& endpoint) throw() {
//This should only be called in lanMode.
assert(lanMode);
//Convert to a GlobalID and connect to that.
GlobalID gid;
endpointToLanGid(gid, endpoint);
return createPeer(gid);
}
Peer* NetworkGame::createPeer(const GlobalID& gid) throw() {
Peer* peer = new Peer;
peer->gid = gid;
peer->overseerReady = false;
peer->connectionAttempts = 0;
peer->cxn = NULL;
connectToPeer(peer);
}
Peer* NetworkGame::createPeer(NetworkConnection* cxn) throw() {
Peer* peer = new Peer;
//TODO: For now, just infer the gid from the IP address.
#ifndef WIN32
#warning NetworkGame::createPeer(NetworkConnection*) does not honour provided GID
#endif
endpointToLanGid(peer->gid, cxn->endpoint);
//TODO: Numeric ID
#ifndef WIN32
#warning NetworkGame::createPeer(NetworkConnection*) does not set NID
#endif
peer->overseerReady = false;
peer->connectionAttempts = 0;
peer->cxn = cxn;
peers[cxn] = peer;
}
void NetworkGame::connectToPeer(Peer* peer) throw() {
//TODO
}
void NetworkGame::closePeer(Peer* peer, unsigned banLength) throw() {
peer->cxn->scg->closeConnection();
peers.erase(peer->cxn);
//Remove references and send notifications
for (peers_t::const_iterator it = peers.begin(); it != peers.end(); ++it) {
Peer* p = it->second;
p->connectionsFrom.erase(peer);
pcgs[p->cxn]->sendPacket(network_game::PeerConnectivityGeraet::negativeDec,
peer->gid);
}
//TODO: handle banning
}
void NetworkGame::refreshOverseer() throw() {
//TODO
}
Peer* NetworkGame::getPeerByGid(const GlobalID& gid) throw() {
//TODO
}
void NetworkGame::update(unsigned et) throw() {
//TODO
}
|
/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 the <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h"
#include "CppUTest/MemoryLeakAllocator.h"
#include "CppUTest/PlatformSpecificFunctions.h"
static char* checkedMalloc(size_t size)
{
char* mem = (char*) PlatformSpecificMalloc(size);
if (mem == 0)FAIL("malloc returned nul pointer");
return mem;
}
MemoryLeakAllocator* MemoryLeakAllocator::currentNewAllocator = 0;
MemoryLeakAllocator* MemoryLeakAllocator::currentNewArrayAllocator = 0;
MemoryLeakAllocator* MemoryLeakAllocator::currentMallocAllocator = 0;
int MemoryLeakAllocator::isOfEqualType(MemoryLeakAllocator* allocator)
{
return PlatformSpecificStrCmp(this->name(), allocator->name()) == 0;
}
void MemoryLeakAllocator::setCurrentNewAllocator(MemoryLeakAllocator* allocator)
{
currentNewAllocator = allocator;
}
MemoryLeakAllocator* MemoryLeakAllocator::getCurrentNewAllocator()
{
if (currentNewAllocator == 0)
setCurrentNewAllocatorToDefault();
return currentNewAllocator;
}
void MemoryLeakAllocator::setCurrentNewAllocatorToDefault()
{
currentNewAllocator = StandardNewAllocator::defaultAllocator();
}
void MemoryLeakAllocator::setCurrentNewArrayAllocator(MemoryLeakAllocator* allocator)
{
currentNewArrayAllocator = allocator;
}
MemoryLeakAllocator* MemoryLeakAllocator::getCurrentNewArrayAllocator()
{
if (currentNewArrayAllocator == 0)
setCurrentNewArrayAllocatorToDefault();
return currentNewArrayAllocator;
}
void MemoryLeakAllocator::setCurrentNewArrayAllocatorToDefault()
{
currentNewArrayAllocator = StandardNewArrayAllocator::defaultAllocator();
}
void MemoryLeakAllocator::setCurrentMallocAllocator(MemoryLeakAllocator* allocator)
{
currentMallocAllocator = allocator;
}
MemoryLeakAllocator* MemoryLeakAllocator::getCurrentMallocAllocator()
{
if (currentMallocAllocator == 0)
setCurrentMallocAllocatorToDefault();
return currentMallocAllocator;
}
void MemoryLeakAllocator::setCurrentMallocAllocatorToDefault()
{
currentMallocAllocator = StandardMallocAllocator::defaultAllocator();
}
char* StandardMallocAllocator::alloc_memory(size_t size)
{
return checkedMalloc(size);
}
void StandardMallocAllocator::free_memory(char* memory)
{
PlatformSpecificFree(memory);
}
const char* StandardMallocAllocator::name()
{
return "Standard Malloc Allocator";
}
const char* StandardMallocAllocator::alloc_name()
{
return "malloc";
}
const char* StandardMallocAllocator::free_name()
{
return "free";
}
MemoryLeakAllocator* StandardMallocAllocator::defaultAllocator()
{
static StandardMallocAllocator allocator;
return &allocator;
}
char* StandardNewAllocator::alloc_memory(size_t size)
{
return checkedMalloc(size);
}
void StandardNewAllocator::free_memory(char* memory)
{
PlatformSpecificFree(memory);
}
const char* StandardNewAllocator::name()
{
return "Standard New Allocator";
}
const char* StandardNewAllocator::alloc_name()
{
return "new";
}
const char* StandardNewAllocator::free_name()
{
return "delete";
}
MemoryLeakAllocator* StandardNewAllocator::defaultAllocator()
{
static StandardNewAllocator allocator;
return &allocator;
}
char* StandardNewArrayAllocator::alloc_memory(size_t size)
{
return checkedMalloc(size);
}
void StandardNewArrayAllocator::free_memory(char* memory)
{
PlatformSpecificFree(memory);
}
const char* StandardNewArrayAllocator::name()
{
return "Standard New [] Allocator";
}
const char* StandardNewArrayAllocator::alloc_name()
{
return "new []";
}
const char* StandardNewArrayAllocator::free_name()
{
return "delete []";
}
MemoryLeakAllocator* StandardNewArrayAllocator::defaultAllocator()
{
static StandardNewArrayAllocator allocator;
return &allocator;
}
char* NullUnknownAllocator::alloc_memory(size_t size)
{
return 0;
}
void NullUnknownAllocator::free_memory(char* memory)
{
}
const char* NullUnknownAllocator::name()
{
return "Null Allocator";
}
const char* NullUnknownAllocator::alloc_name()
{
return "unknown";
}
const char* NullUnknownAllocator::free_name()
{
return "unknown";
}
MemoryLeakAllocator* NullUnknownAllocator::defaultAllocator()
{
static NullUnknownAllocator allocator;
return &allocator;
}
Removed a warning
/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 the <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h"
#include "CppUTest/MemoryLeakAllocator.h"
#include "CppUTest/PlatformSpecificFunctions.h"
static char* checkedMalloc(size_t size)
{
char* mem = (char*) PlatformSpecificMalloc(size);
if (mem == 0)FAIL("malloc returned nul pointer");
return mem;
}
MemoryLeakAllocator* MemoryLeakAllocator::currentNewAllocator = 0;
MemoryLeakAllocator* MemoryLeakAllocator::currentNewArrayAllocator = 0;
MemoryLeakAllocator* MemoryLeakAllocator::currentMallocAllocator = 0;
int MemoryLeakAllocator::isOfEqualType(MemoryLeakAllocator* allocator)
{
return PlatformSpecificStrCmp(this->name(), allocator->name()) == 0;
}
void MemoryLeakAllocator::setCurrentNewAllocator(MemoryLeakAllocator* allocator)
{
currentNewAllocator = allocator;
}
MemoryLeakAllocator* MemoryLeakAllocator::getCurrentNewAllocator()
{
if (currentNewAllocator == 0)
setCurrentNewAllocatorToDefault();
return currentNewAllocator;
}
void MemoryLeakAllocator::setCurrentNewAllocatorToDefault()
{
currentNewAllocator = StandardNewAllocator::defaultAllocator();
}
void MemoryLeakAllocator::setCurrentNewArrayAllocator(MemoryLeakAllocator* allocator)
{
currentNewArrayAllocator = allocator;
}
MemoryLeakAllocator* MemoryLeakAllocator::getCurrentNewArrayAllocator()
{
if (currentNewArrayAllocator == 0)
setCurrentNewArrayAllocatorToDefault();
return currentNewArrayAllocator;
}
void MemoryLeakAllocator::setCurrentNewArrayAllocatorToDefault()
{
currentNewArrayAllocator = StandardNewArrayAllocator::defaultAllocator();
}
void MemoryLeakAllocator::setCurrentMallocAllocator(MemoryLeakAllocator* allocator)
{
currentMallocAllocator = allocator;
}
MemoryLeakAllocator* MemoryLeakAllocator::getCurrentMallocAllocator()
{
if (currentMallocAllocator == 0)
setCurrentMallocAllocatorToDefault();
return currentMallocAllocator;
}
void MemoryLeakAllocator::setCurrentMallocAllocatorToDefault()
{
currentMallocAllocator = StandardMallocAllocator::defaultAllocator();
}
char* StandardMallocAllocator::alloc_memory(size_t size)
{
return checkedMalloc(size);
}
void StandardMallocAllocator::free_memory(char* memory)
{
PlatformSpecificFree(memory);
}
const char* StandardMallocAllocator::name()
{
return "Standard Malloc Allocator";
}
const char* StandardMallocAllocator::alloc_name()
{
return "malloc";
}
const char* StandardMallocAllocator::free_name()
{
return "free";
}
MemoryLeakAllocator* StandardMallocAllocator::defaultAllocator()
{
static StandardMallocAllocator allocator;
return &allocator;
}
char* StandardNewAllocator::alloc_memory(size_t size)
{
return checkedMalloc(size);
}
void StandardNewAllocator::free_memory(char* memory)
{
PlatformSpecificFree(memory);
}
const char* StandardNewAllocator::name()
{
return "Standard New Allocator";
}
const char* StandardNewAllocator::alloc_name()
{
return "new";
}
const char* StandardNewAllocator::free_name()
{
return "delete";
}
MemoryLeakAllocator* StandardNewAllocator::defaultAllocator()
{
static StandardNewAllocator allocator;
return &allocator;
}
char* StandardNewArrayAllocator::alloc_memory(size_t size)
{
return checkedMalloc(size);
}
void StandardNewArrayAllocator::free_memory(char* memory)
{
PlatformSpecificFree(memory);
}
const char* StandardNewArrayAllocator::name()
{
return "Standard New [] Allocator";
}
const char* StandardNewArrayAllocator::alloc_name()
{
return "new []";
}
const char* StandardNewArrayAllocator::free_name()
{
return "delete []";
}
MemoryLeakAllocator* StandardNewArrayAllocator::defaultAllocator()
{
static StandardNewArrayAllocator allocator;
return &allocator;
}
char* NullUnknownAllocator::alloc_memory(size_t /*size*/)
{
return 0;
}
void NullUnknownAllocator::free_memory(char* /*memory*/)
{
}
const char* NullUnknownAllocator::name()
{
return "Null Allocator";
}
const char* NullUnknownAllocator::alloc_name()
{
return "unknown";
}
const char* NullUnknownAllocator::free_name()
{
return "unknown";
}
MemoryLeakAllocator* NullUnknownAllocator::defaultAllocator()
{
static NullUnknownAllocator allocator;
return &allocator;
}
|
/* 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/. */
#include <cassert>
#include <cstring>
#include <map>
#include <utility>
#include <linux/if_packet.h>
#include <glog/logging.h>
#include <netlink/route/link.h>
#include <netlink/route/mdb.h>
#include <netlink/route/link/vlan.h>
#include <netlink/route/link/vxlan.h>
#include <netlink/route/neighbour.h>
#include <rofl/common/openflow/cofport.h>
#include "cnetlink.h"
#include "netlink-utils.h"
#include "nl_bridge.h"
#include "nl_output.h"
#include "nl_vxlan.h"
#include "sai.h"
#include "tap_manager.h"
namespace basebox {
nl_bridge::nl_bridge(switch_interface *sw, std::shared_ptr<tap_manager> tap_man,
cnetlink *nl, std::shared_ptr<nl_vxlan> vxlan)
: bridge(nullptr), sw(sw), tap_man(std::move(tap_man)), nl(nl),
vxlan(std::move(vxlan)),
l2_cache(nl_cache_alloc(nl_cache_ops_lookup("route/neigh")),
nl_cache_free) {
memset(&empty_br_vlan, 0, sizeof(rtnl_link_bridge_vlan));
memset(&vxlan_dom_bitmap, 0, sizeof(vxlan_dom_bitmap));
}
nl_bridge::~nl_bridge() { rtnl_link_put(bridge); }
static rofl::caddress_in4 libnl_in4addr_2_rofl(struct nl_addr *addr, int *rv) {
struct sockaddr_in sin;
socklen_t salen = sizeof(sin);
assert(rv);
*rv = nl_addr_fill_sockaddr(addr, (struct sockaddr *)&sin, &salen);
return rofl::caddress_in4(&sin, salen);
}
void nl_bridge::set_bridge_interface(rtnl_link *bridge) {
assert(bridge);
assert(std::string("bridge").compare(rtnl_link_get_type(bridge)) == 0);
this->bridge = bridge;
nl_object_get(OBJ_CAST(bridge));
if (!get_vlan_filtering())
LOG(FATAL) << __FUNCTION__
<< " unsupported: bridge configured with vlan_filtering 0";
}
bool nl_bridge::is_bridge_interface(rtnl_link *link) {
assert(link);
if (rtnl_link_get_ifindex(link) != rtnl_link_get_ifindex(bridge))
return false;
// TODO compare more?
return true;
}
// Read sysfs to obtain the value for the VLAN protocol on the switch.
// Only two values are suported: 0x8100 and 0x88a8
uint32_t nl_bridge::get_vlan_proto() {
std::string portname(rtnl_link_get_name(bridge));
return nl->load_from_file(
"/sys/class/net/" + portname + "/bridge/vlan_protocol", 16);
}
// Read sysfs to obtain the value for the VLAN filtering value on the switch.
// baseboxd currently only supports VLAN-aware bridges, set with the
// vlan_filtering flag to 1.
uint32_t nl_bridge::get_vlan_filtering() {
std::string portname(rtnl_link_get_name(bridge));
return nl->load_from_file("/sys/class/net/" + portname +
"/bridge/vlan_filtering");
}
static bool br_vlan_equal(const rtnl_link_bridge_vlan *lhs,
const rtnl_link_bridge_vlan *rhs) {
assert(lhs);
assert(rhs);
return (memcmp(lhs, rhs, sizeof(struct rtnl_link_bridge_vlan)) == 0);
}
static bool is_vid_set(unsigned vid, uint32_t *addr) {
if (vid >= RTNL_LINK_BRIDGE_VLAN_BITMAP_MAX) {
LOG(FATAL) << __FUNCTION__ << ": vid " << vid << " out of range";
return false;
}
return !!(addr[vid / 32] & (((uint32_t)1) << (vid % 32)));
}
static void set_vid(unsigned vid, uint32_t *addr) {
if (vid < RTNL_LINK_BRIDGE_VLAN_BITMAP_MAX)
addr[vid / 32] |= (((uint32_t)1) << (vid % 32));
}
static void unset_vid(unsigned vid, uint32_t *addr) {
if (vid < RTNL_LINK_BRIDGE_VLAN_BITMAP_MAX)
addr[vid / 32] &= ~(((uint32_t)1) << (vid % 32));
}
static int find_next_bit(int i, uint32_t x) {
int j;
if (i >= 32)
return -1;
/* find first bit */
if (i < 0)
return __builtin_ffs(x);
/* mask off prior finds to get next */
j = __builtin_ffs(x >> i);
return j ? j + i : 0;
}
void nl_bridge::add_interface(rtnl_link *link) {
assert(rtnl_link_get_family(link) == AF_BRIDGE);
if (bridge == nullptr) {
LOG(ERROR) << __FUNCTION__ << ": cannot be done without bridge";
return;
}
if (rtnl_link_get_ifindex(bridge) != rtnl_link_get_master(link)) {
LOG(INFO) << __FUNCTION__ << ": link " << rtnl_link_get_name(link)
<< " is no slave of " << rtnl_link_get_name(bridge);
return;
}
update_vlans(nullptr, link);
if (get_vlan_proto() == ETH_P_8021AD)
sw->set_egress_tpid(nl->get_port_id(link));
}
void nl_bridge::update_interface(rtnl_link *old_link, rtnl_link *new_link) {
assert(rtnl_link_get_family(old_link) == AF_BRIDGE);
assert(rtnl_link_get_family(new_link) == AF_BRIDGE);
// sanity checks
if (bridge == nullptr) {
LOG(ERROR) << __FUNCTION__ << ": cannot be done without bridge";
return;
}
if (rtnl_link_get_ifindex(bridge) != rtnl_link_get_master(new_link)) {
LOG(INFO) << __FUNCTION__ << ": link " << rtnl_link_get_name(new_link)
<< " is no slave of " << rtnl_link_get_name(bridge);
return;
}
update_vlans(old_link, new_link);
}
void nl_bridge::delete_interface(rtnl_link *link) {
assert(rtnl_link_get_family(link) == AF_BRIDGE);
// sanity checks
if (bridge == nullptr) {
LOG(ERROR) << __FUNCTION__ << ": cannot be done without bridge";
return;
}
if (rtnl_link_get_ifindex(bridge) != rtnl_link_get_master(link)) {
LOG(INFO) << __FUNCTION__ << ": link " << rtnl_link_get_name(link)
<< " is no slave of " << rtnl_link_get_name(bridge);
return;
}
update_vlans(link, nullptr);
if (get_vlan_proto() == ETH_P_8021AD)
sw->delete_egress_tpid(nl->get_port_id(link));
}
void nl_bridge::update_vlans(rtnl_link *old_link, rtnl_link *new_link) {
assert(sw);
assert(bridge); // already checked
rtnl_link_bridge_vlan *old_br_vlan, *new_br_vlan;
rtnl_link *_link;
if (old_link == nullptr) {
// link added
old_br_vlan = &empty_br_vlan;
new_br_vlan = rtnl_link_bridge_get_port_vlan(new_link);
_link = nl->get_link(rtnl_link_get_ifindex(new_link), AF_UNSPEC);
} else if (new_link == nullptr) {
// link deleted
old_br_vlan = rtnl_link_bridge_get_port_vlan(old_link);
new_br_vlan = &empty_br_vlan;
_link = nl->get_link(rtnl_link_get_ifindex(old_link), AF_UNSPEC);
} else {
// link updated
old_br_vlan = rtnl_link_bridge_get_port_vlan(old_link);
new_br_vlan = rtnl_link_bridge_get_port_vlan(new_link);
_link = nl->get_link(rtnl_link_get_ifindex(new_link), AF_UNSPEC);
}
if (old_br_vlan == nullptr) {
old_br_vlan = &empty_br_vlan;
}
if (new_br_vlan == nullptr) {
new_br_vlan = &empty_br_vlan;
}
if (_link == nullptr) {
// XXX FIXME in case a vxlan has been deleted the vxlan_domain and
// vxlan_dom_bitmap need an update, maybe this can be handled already from
// the link_deleted of the vxlan itself?
LOG(WARNING) << __FUNCTION__
<< ": could not get parent link of bridge interface. This "
"case needs further checks if everything got already "
"deleted.";
return;
}
// check for vid changes
if (br_vlan_equal(old_br_vlan, new_br_vlan)) {
VLOG(2) << __FUNCTION__ << ": vlans did not change";
return;
}
link_type lt = get_link_type(_link);
uint32_t pport_no = 0;
uint32_t tunnel_id = -1;
std::deque<rtnl_link *> bridge_ports;
if (lt == LT_VXLAN) {
assert(nl);
nl->get_bridge_ports(rtnl_link_get_master(_link), &bridge_ports);
if (vxlan->get_tunnel_id(_link, nullptr, &tunnel_id) != 0) {
LOG(ERROR) << __FUNCTION__ << ": failed to get vni of link "
<< OBJ_CAST(_link);
}
} else {
pport_no = nl->get_port_id(_link);
if (pport_no == 0) {
LOG(ERROR) << __FUNCTION__
<< ": invalid pport_no=0 of link: " << OBJ_CAST(_link);
return;
}
}
for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) {
int base_bit;
uint32_t a = old_br_vlan->vlan_bitmap[k];
uint32_t b = new_br_vlan->vlan_bitmap[k];
uint32_t vlan_diff = a ^ b;
#if 0 // untagged change not yet implemented
uint32_t c = old_br_vlan->untagged_bitmap[k];
uint32_t d = new_br_vlan->untagged_bitmap[k];
uint32_t untagged_diff = c ^ d;
#endif // 0
base_bit = k * 32;
int i = -1;
int done = 0;
while (!done) {
int j = find_next_bit(i, vlan_diff);
if (j > 0) {
// vlan added or removed
int vid = j - 1 + base_bit;
bool egress_untagged = false;
// check if egress is untagged
if (new_br_vlan->untagged_bitmap[k] & 1 << (j - 1)) {
egress_untagged = true;
#if 0 // untagged change not yet implemented
// clear untagged_diff bit
untagged_diff &= ~((uint32_t)1 << (j - 1));
#endif // 0
}
if (new_br_vlan->vlan_bitmap[k] & 1 << (j - 1)) {
// vlan added
if (lt == LT_VXLAN) {
// update vxlan domain
if (!is_vid_set(vid, vxlan_dom_bitmap)) {
VLOG(1) << __FUNCTION__ << ": new vxlan domain vid=" << vid
<< ", tunnel_id=" << tunnel_id;
vxlan_domain.emplace(vid, tunnel_id);
set_vid(vid, vxlan_dom_bitmap);
} else {
// XXX TODO check the map
}
// update all bridge ports to be access ports
update_access_ports(_link, new_link ? new_link : old_link, vid,
tunnel_id, bridge_ports, true);
} else {
assert(pport_no);
if (is_vid_set(vid, vxlan_dom_bitmap)) {
// configure as access port
std::string port_name = std::string(rtnl_link_get_name(_link));
auto vxd_it = vxlan_domain.find(vid);
if (vxd_it != vxlan_domain.end()) {
vxlan->create_access_port((new_link) ? new_link : old_link,
vxd_it->second, port_name, pport_no,
vid, egress_untagged, nullptr);
} else {
LOG(FATAL) << __FUNCTION__
<< ": should not happen, something is broken";
}
} else {
// normal vlan port
VLOG(3) << __FUNCTION__ << ": add vid=" << vid
<< " on pport_no=" << pport_no
<< " link: " << OBJ_CAST(_link);
sw->egress_bridge_port_vlan_add(pport_no, vid, egress_untagged);
sw->ingress_port_vlan_add(pport_no, vid,
new_br_vlan->pvid == vid);
}
}
} else {
// vlan removed
if (lt == LT_VXLAN) {
unset_vid(vid, vxlan_dom_bitmap);
vxlan_domain.erase(vid);
// update all bridge ports to be normal bridge ports
update_access_ports(_link, new_link ? new_link : old_link, vid,
tunnel_id, bridge_ports, false);
} else {
VLOG(3) << __FUNCTION__ << ": remove vid=" << vid
<< " on pport_no=" << pport_no
<< " link: " << OBJ_CAST(_link);
sw->ingress_port_vlan_remove(pport_no, vid,
old_br_vlan->pvid == vid);
// delete all FM pointing to this group first
sw->l2_addr_remove_all_in_vlan(pport_no, vid);
std::unique_ptr<rtnl_neigh, decltype(&rtnl_neigh_put)> filter(
rtnl_neigh_alloc(), rtnl_neigh_put);
rtnl_neigh_set_ifindex(filter.get(), rtnl_link_get_ifindex(bridge));
rtnl_neigh_set_master(filter.get(), rtnl_link_get_master(bridge));
rtnl_neigh_set_family(filter.get(), AF_BRIDGE);
rtnl_neigh_set_vlan(filter.get(), vid);
rtnl_neigh_set_flags(filter.get(), NTF_MASTER | NTF_EXT_LEARNED);
rtnl_neigh_set_state(filter.get(), NUD_REACHABLE);
nl_cache_foreach_filter(l2_cache.get(), OBJ_CAST(filter.get()),
[](struct nl_object *o, void *arg) {
VLOG(3) << "l2_cache remove object " << o;
nl_cache_remove(o);
},
nullptr);
sw->egress_bridge_port_vlan_remove(pport_no, vid);
}
}
i = j;
} else {
done = 1;
}
}
#if 0 // not yet implemented the update
done = 0;
i = -1;
while (!done) {
// vlan is existing, but swapping egress tagged/untagged
int j = find_next_bit(i, untagged_diff);
if (j > 0) {
// egress untagged changed
int vid = j - 1 + base_bit;
bool egress_untagged = false;
// check if egress is untagged
if (new_br_vlan->untagged_bitmap[k] & 1 << (j-1)) {
egress_untagged = true;
}
// XXX implement update
fm_driver.update_port_vid_egress(devname, vid, egress_untagged);
i = j;
} else {
done = 1;
}
}
#endif
}
}
std::deque<rtnl_neigh *> nl_bridge::get_fdb_entries_of_port(rtnl_link *br_port,
uint16_t vid,
nl_addr *lladdr) {
std::unique_ptr<rtnl_neigh, decltype(&rtnl_neigh_put)> filter(
rtnl_neigh_alloc(), rtnl_neigh_put);
rtnl_neigh_set_ifindex(filter.get(), rtnl_link_get_ifindex(br_port));
rtnl_neigh_set_master(filter.get(), rtnl_link_get_ifindex(bridge));
rtnl_neigh_set_family(filter.get(), AF_BRIDGE);
if (vid)
rtnl_neigh_set_vlan(filter.get(), vid);
if (lladdr)
rtnl_neigh_set_lladdr(filter.get(), lladdr);
VLOG(3) << __FUNCTION__ << ": searching for " << OBJ_CAST(filter.get());
std::deque<rtnl_neigh *> neighs;
nl_cache_foreach_filter(nl->get_cache(cnetlink::NL_NEIGH_CACHE),
OBJ_CAST(filter.get()),
[](struct nl_object *o, void *arg) {
auto *neighs = (std::deque<rtnl_neigh *> *)arg;
neighs->push_back(NEIGH_CAST(o));
VLOG(3) << "needs to be updated " << o;
},
&neighs);
return neighs;
}
int nl_bridge::update_access_ports(rtnl_link *vxlan_link, rtnl_link *br_link,
const uint32_t tunnel_id, bool add) {
if (vxlan_link == nullptr) {
LOG(ERROR) << __FUNCTION__ << ": vxlan_link cannot be nullptr";
return -EINVAL;
}
if (br_link == nullptr) {
LOG(ERROR) << __FUNCTION__ << ": br_link cannot be nullptr";
return -EINVAL;
}
// XXX get pvid from br_link
auto br_port_vlans = rtnl_link_bridge_get_port_vlan(br_link);
auto vid = br_port_vlans->pvid;
auto vxlan_domain_it = vxlan_domain.find(vid);
if (vxlan_domain_it != vxlan_domain.end()) {
if (vxlan_domain_it->second != tunnel_id) {
LOG(ERROR) << __FUNCTION__ << ": different tunnel_id ("
<< vxlan_domain_it->second
<< ") in vxlan_domain expected id=" << tunnel_id;
}
VLOG(2) << __FUNCTION__
<< ": access ports already configured for vid=" << vid
<< " and tunnel_id=" << tunnel_id;
// already vxlan domain
return 0;
}
// XXX get all bridge_ports
std::deque<rtnl_link *> bridge_ports;
nl->get_bridge_ports(rtnl_link_get_master(br_link), &bridge_ports);
update_access_ports(vxlan_link, br_link, vid, tunnel_id, bridge_ports, add);
// update vxlan_domain
vxlan_domain.emplace(vid, tunnel_id);
return 0;
}
void nl_bridge::update_access_ports(rtnl_link *vxlan_link, rtnl_link *br_link,
const uint16_t vid,
const uint32_t tunnel_id,
const std::deque<rtnl_link *> &bridge_ports,
bool add) {
// XXX pvid is currently not taken into account
for (auto _br_port : bridge_ports) {
auto br_port_vlans = rtnl_link_bridge_get_port_vlan(_br_port);
if (rtnl_link_get_ifindex(vxlan_link) == rtnl_link_get_ifindex(_br_port))
continue;
if (br_port_vlans == nullptr)
continue;
if (!is_vid_set(vid, br_port_vlans->vlan_bitmap))
continue;
bool untagged = is_vid_set(vid, br_port_vlans->untagged_bitmap);
int ifindex = rtnl_link_get_ifindex(_br_port);
uint32_t pport_no = nl->get_port_id(ifindex);
if (pport_no == 0) {
LOG(WARNING) << __FUNCTION__ << ": ignoring unknown port "
<< OBJ_CAST(_br_port);
continue;
}
rtnl_link *link = nl->get_link(rtnl_link_get_ifindex(_br_port), AF_UNSPEC);
VLOG(2) << __FUNCTION__ << ": vid=" << vid << ", untagged=" << untagged
<< ", tunnel_id=" << tunnel_id << ", add=" << add
<< ", ifindex=" << ifindex << ", pport_no=" << pport_no
<< ", port: " << OBJ_CAST(_br_port);
if (add) {
std::string port_name = std::string(rtnl_link_get_name(_br_port));
// this is no longer a normal bridge interface thus we delete all the
// bridging entries
sw->l2_addr_remove_all_in_vlan(pport_no, vid);
vxlan->create_access_port(_br_port, tunnel_id, port_name, pport_no, vid,
untagged, nullptr);
auto neighs = get_fdb_entries_of_port(_br_port, vid);
for (auto n : neighs) {
// ignore ll addr of bridge on slave
if (nl_addr_cmp(rtnl_link_get_addr(bridge), rtnl_neigh_get_lladdr(n)) ==
0) {
continue;
}
VLOG(3) << ": needs to be updated " << OBJ_CAST(n);
vxlan->add_l2_neigh(n, link, br_link);
}
} else {
// delete access port and all bridging entries
vxlan->delete_access_port(_br_port, pport_no, vid, true);
sw->egress_bridge_port_vlan_add(pport_no, vid, untagged);
sw->ingress_port_vlan_add(pport_no, vid, br_port_vlans->pvid == vid);
auto neighs = get_fdb_entries_of_port(_br_port, vid);
for (auto n : neighs) {
// ignore ll addr of bridge on slave
if (nl_addr_cmp(rtnl_link_get_addr(bridge), rtnl_neigh_get_lladdr(n)) ==
0) {
continue;
}
VLOG(3) << ": needs to be updated " << OBJ_CAST(n);
add_neigh_to_fdb(n);
}
}
}
}
void nl_bridge::add_neigh_to_fdb(rtnl_neigh *neigh) {
assert(sw);
assert(neigh);
uint32_t port = nl->get_port_id(rtnl_neigh_get_ifindex(neigh));
if (port == 0) {
VLOG(1) << __FUNCTION__ << ": unknown port for neigh " << OBJ_CAST(neigh);
return;
}
nl_addr *mac = rtnl_neigh_get_lladdr(neigh);
int vlan = rtnl_neigh_get_vlan(neigh);
bool permanent = true;
// for sure this is master (sw bridged)
if (rtnl_neigh_get_master(neigh) &&
!(rtnl_neigh_get_flags(neigh) & NTF_MASTER)) {
rtnl_neigh_set_flags(neigh, NTF_MASTER);
}
// check if entry already exists in cache
if (is_mac_in_l2_cache(neigh)) {
permanent = false;
}
rofl::caddress_ll _mac((uint8_t *)nl_addr_get_binary_addr(mac),
nl_addr_get_len(mac));
LOG(INFO) << __FUNCTION__ << ": add mac=" << _mac << " to bridge "
<< rtnl_link_get_name(bridge) << " on port=" << port
<< " vlan=" << (unsigned)vlan << ", permanent=" << permanent;
LOG(INFO) << __FUNCTION__ << ": object: " << OBJ_CAST(neigh);
sw->l2_addr_add(port, vlan, _mac, true, permanent);
}
void nl_bridge::remove_neigh_from_fdb(rtnl_neigh *neigh) {
assert(sw);
nl_addr *addr = rtnl_neigh_get_lladdr(neigh);
if (nl_addr_cmp(rtnl_link_get_addr(bridge), addr) == 0) {
// ignore ll addr of bridge on slave
return;
}
// lookup l2_cache as well
std::unique_ptr<rtnl_neigh, decltype(&rtnl_neigh_put)> n_lookup(
NEIGH_CAST(nl_cache_search(l2_cache.get(), OBJ_CAST(neigh))),
rtnl_neigh_put);
if (n_lookup) {
nl_cache_remove(OBJ_CAST(n_lookup.get()));
}
const uint32_t port = nl->get_port_id(rtnl_neigh_get_ifindex(neigh));
rofl::caddress_ll mac((uint8_t *)nl_addr_get_binary_addr(addr),
nl_addr_get_len(addr));
sw->l2_addr_remove(port, rtnl_neigh_get_vlan(neigh), mac);
}
bool nl_bridge::is_mac_in_l2_cache(rtnl_neigh *n) {
assert(n);
std::unique_ptr<rtnl_neigh, decltype(&rtnl_neigh_put)> n_lookup(
NEIGH_CAST(nl_cache_search(l2_cache.get(), OBJ_CAST(n))), rtnl_neigh_put);
if (n_lookup) {
VLOG(2) << __FUNCTION__ << ": found existing l2_cache entry "
<< OBJ_CAST(n_lookup.get());
return true;
}
return false;
}
int nl_bridge::learn_source_mac(rtnl_link *br_link, packet *p) {
// we still assume vlan filtering bridge
assert(rtnl_link_get_family(br_link) == AF_BRIDGE);
VLOG(2) << __FUNCTION__ << ": pkt " << p << " on link " << OBJ_CAST(br_link);
rtnl_link_bridge_vlan *br_vlan = rtnl_link_bridge_get_port_vlan(br_link);
if (br_vlan == nullptr) {
LOG(ERROR) << __FUNCTION__
<< ": only the vlan filtering bridge is supported";
return -EINVAL;
}
// parse ether frame and check for vid
auto *hdr = reinterpret_cast<basebox::vlan_hdr *>(p->data);
uint16_t vid = 0;
// XXX TODO maybe move this to the utils to have a std lib for parsing the
// ether frame
switch (ntohs(hdr->eth.h_proto)) {
case ETH_P_8021Q:
case ETH_P_8021AD:
// vid
vid = ntohs(hdr->vlan) & 0xfff;
break;
default:
// no vid, set vid to pvid
vid = br_vlan->pvid;
LOG(WARNING) << __FUNCTION__ << ": assuming untagged for ethertype "
<< std::showbase << std::hex << ntohs(hdr->eth.h_proto);
break;
}
// verify that the vid is in use here
if (!is_vid_set(vid, br_vlan->vlan_bitmap)) {
LOG(WARNING) << __FUNCTION__ << ": got packet on unconfigured port";
return -ENOTSUP;
}
// set nl neighbour to NL
std::unique_ptr<nl_addr, decltype(&nl_addr_put)> h_src(
nl_addr_build(AF_LLC, hdr->eth.h_source, sizeof(hdr->eth.h_source)),
nl_addr_put);
if (!h_src) {
LOG(ERROR) << __FUNCTION__ << ": failed to allocate src mac";
return -ENOMEM;
}
std::unique_ptr<rtnl_neigh, decltype(&rtnl_neigh_put)> n(rtnl_neigh_alloc(),
rtnl_neigh_put);
rtnl_neigh_set_ifindex(n.get(), rtnl_link_get_ifindex(br_link));
rtnl_neigh_set_master(n.get(), rtnl_link_get_master(br_link));
rtnl_neigh_set_family(n.get(), AF_BRIDGE);
rtnl_neigh_set_vlan(n.get(), vid);
rtnl_neigh_set_lladdr(n.get(), h_src.get());
rtnl_neigh_set_flags(n.get(), NTF_MASTER | NTF_EXT_LEARNED);
rtnl_neigh_set_state(n.get(), NUD_REACHABLE);
// check if entry already exists in cache
if (is_mac_in_l2_cache(n.get())) {
return 0;
}
nl_msg *msg = nullptr;
rtnl_neigh_build_add_request(n.get(),
NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL, &msg);
assert(msg);
// send the message and create new fdb entry
if (nl->send_nl_msg(msg) < 0) {
LOG(ERROR) << __FUNCTION__ << ": failed to send netlink message";
return -EINVAL;
}
// cache the entry
if (nl_cache_add(l2_cache.get(), OBJ_CAST(n.get())) < 0) {
LOG(ERROR) << __FUNCTION__ << ": failed to add entry to l2_cache "
<< OBJ_CAST(n.get());
return -EINVAL;
}
VLOG(2) << __FUNCTION__ << ": learned new source mac " << OBJ_CAST(n.get());
return 0;
}
int nl_bridge::fdb_timeout(rtnl_link *br_link, uint16_t vid,
const rofl::caddress_ll &mac) {
int rv = 0;
std::unique_ptr<rtnl_neigh, decltype(&rtnl_neigh_put)> n(rtnl_neigh_alloc(),
rtnl_neigh_put);
std::unique_ptr<nl_addr, decltype(&nl_addr_put)> h_src(
nl_addr_build(AF_LLC, mac.somem(), mac.memlen()), nl_addr_put);
rtnl_neigh_set_ifindex(n.get(), rtnl_link_get_ifindex(br_link));
rtnl_neigh_set_master(n.get(), rtnl_link_get_master(br_link));
rtnl_neigh_set_family(n.get(), AF_BRIDGE);
rtnl_neigh_set_vlan(n.get(), vid);
rtnl_neigh_set_lladdr(n.get(), h_src.get());
rtnl_neigh_set_flags(n.get(), NTF_MASTER | NTF_EXT_LEARNED);
rtnl_neigh_set_state(n.get(), NUD_REACHABLE);
// find entry in local l2_cache
std::unique_ptr<rtnl_neigh, decltype(&rtnl_neigh_put)> n_lookup(
NEIGH_CAST(nl_cache_search(l2_cache.get(), OBJ_CAST(n.get()))),
rtnl_neigh_put);
if (n_lookup) {
// * remove l2 entry from kernel
nl_msg *msg = nullptr;
rtnl_neigh_build_delete_request(n.get(), NLM_F_REQUEST, &msg);
assert(msg);
// send the message and create new fdb entry
if (nl->send_nl_msg(msg) < 0) {
LOG(ERROR) << __FUNCTION__ << ": failed to send netlink message";
return -EINVAL;
}
// XXX TODO maybe delete after NL event and not yet here
nl_cache_remove(OBJ_CAST(n_lookup.get()));
}
return rv;
}
bool nl_bridge::is_port_flooding(rtnl_link *br_link) const {
assert(br_link);
assert(rtnl_link_is_bridge(br_link));
int flags = rtnl_link_bridge_get_flags(br_link);
return !!(flags & RTNL_BRIDGE_UNICAST_FLOOD);
}
void nl_bridge::clear_tpid_entries() {
std::deque<rtnl_link *> bridge_ports;
nl->get_bridge_ports(rtnl_link_get_ifindex(bridge), &bridge_ports);
for (auto iface : bridge_ports)
sw->delete_egress_tpid(nl->get_port_id(iface));
}
int nl_bridge::mdb_entry_add(rtnl_mdb *mdb_entry) {
int rv = 0;
std::deque<struct rtnl_mdb_entry *> mdb;
uint32_t bridge = rtnl_mdb_get_ifindex(mdb_entry);
if (!is_bridge_interface(nl->get_link_by_ifindex(bridge).get())) {
LOG(ERROR) << ": bridge not set correctly";
return -EINVAL;
}
// parse MDB object to get all nested information
rtnl_mdb_foreach_entry(
mdb_entry,
[](struct rtnl_mdb_entry *it, void *arg) {
auto m_database =
static_cast<std::deque<struct rtnl_mdb_entry *> *>(arg);
m_database->push_back(it);
},
&mdb);
for (auto i : mdb) {
uint32_t port_ifindex = rtnl_mdb_entry_get_ifindex(i);
uint32_t port_id = nl->get_port_id(port_ifindex);
uint16_t vid = rtnl_mdb_entry_get_vid(i);
if (port_ifindex == get_ifindex()) {
return rv;
}
auto addr = rtnl_mdb_entry_get_addr(i);
if (rtnl_mdb_entry_get_proto(i) == ETH_P_IP) {
rofl::caddress_in4 ipv4_dst = libnl_in4addr_2_rofl(addr, &rv);
if (rv < 0) {
LOG(ERROR) << __FUNCTION__ << ": could not parse addr " << addr;
return rv;
}
unsigned char buf[ETH_ALEN];
multicast_ipv4_to_ll(ipv4_dst.get_addr_hbo(), buf);
rofl::caddress_ll mc_ll = rofl::caddress_ll(buf, ETH_ALEN);
rv = sw->l2_multicast_group_add(port_id, vid, mc_ll);
if (rv < 0) {
LOG(ERROR) << __FUNCTION__
<< ": failed to add Layer 2 Multicast Group Entry";
return rv;
}
rv = sw->l2_multicast_addr_add(port_id, vid, mc_ll);
if (rv < 0) {
LOG(ERROR) << __FUNCTION__ << ": failed to add bridging MC entry";
return rv;
}
} else if (rtnl_mdb_entry_get_proto(i) == ETH_P_IPV6) {
struct in6_addr *v6_addr =
(struct in6_addr *)nl_addr_get_binary_addr(addr);
unsigned char buf[ETH_ALEN];
multicast_ipv6_to_ll(v6_addr, buf);
rofl::caddress_ll mc_ll = rofl::caddress_ll(buf, ETH_ALEN);
rv = sw->l2_multicast_group_add(port_id, vid, mc_ll);
if (rv < 0) {
LOG(ERROR) << __FUNCTION__
<< ": failed to add Layer 2 Multicast Group Entry";
return rv;
}
rv = sw->l2_multicast_addr_add(port_id, vid, mc_ll);
if (rv < 0) {
LOG(ERROR) << __FUNCTION__ << ": failed to add bridging MC entry";
return rv;
}
}
VLOG(2) << __FUNCTION__ << ": mdb entry added, port" << port_id
<< " grp= " << addr;
}
return rv;
}
int nl_bridge::mdb_entry_remove(rtnl_mdb *mdb_entry) {
int rv = 0;
uint32_t bridge = rtnl_mdb_get_ifindex(mdb_entry);
if (!is_bridge_interface(nl->get_link_by_ifindex(bridge).get())) {
LOG(ERROR) << ": bridge not set correctly";
return -EINVAL;
}
std::deque<struct rtnl_mdb_entry *> mdb;
// parse MDB object to get all nested information
rtnl_mdb_foreach_entry(
mdb_entry,
[](struct rtnl_mdb_entry *it, void *arg) {
auto m_database =
static_cast<std::deque<struct rtnl_mdb_entry *> *>(arg);
m_database->push_back(it);
},
&mdb);
for (auto i : mdb) {
uint32_t port_ifindex = rtnl_mdb_entry_get_ifindex(i);
uint32_t port_id = nl->get_port_id(port_ifindex);
uint16_t vid = rtnl_mdb_entry_get_vid(i);
auto addr = rtnl_mdb_entry_get_addr(i);
if (rtnl_mdb_entry_get_proto(i) == ETH_P_IP) {
rofl::caddress_in4 ipv4_dst = libnl_in4addr_2_rofl(addr, &rv);
if (rv < 0) {
LOG(ERROR) << __FUNCTION__ << ": could not parse addr " << addr;
return rv;
}
unsigned char buf[ETH_ALEN];
multicast_ipv4_to_ll(ipv4_dst.get_addr_hbo(), buf);
rofl::caddress_ll mc_ll = rofl::caddress_ll(buf, ETH_ALEN);
rv = sw->l2_multicast_group_remove(port_id, vid, mc_ll);
// nothing left to do, there are still entries in the mc group
if (rv == -ENOTEMPTY) {
return 0;
} else if (rv < 0) {
LOG(ERROR) << __FUNCTION__
<< ": failed to remove Layer 2 Multicast Group Entry";
return rv;
}
rv = sw->l2_multicast_addr_remove(port_id, vid, mc_ll);
if (rv < 0) {
LOG(ERROR) << __FUNCTION__ << ": failed to add bridging MC entry";
return rv;
}
} else if (rtnl_mdb_entry_get_proto(i) == ETH_P_IPV6) {
struct in6_addr *v6_addr =
(struct in6_addr *)nl_addr_get_binary_addr(addr);
unsigned char buf[ETH_ALEN];
multicast_ipv6_to_ll(v6_addr, buf);
rofl::caddress_ll mc_ll = rofl::caddress_ll(buf, ETH_ALEN);
rv = sw->l2_multicast_group_remove(port_id, vid, mc_ll);
// nothing left to do, there are still entries in the mc group
if (rv == -ENOTEMPTY) {
return 0;
} else if (rv < 0) {
LOG(ERROR) << __FUNCTION__
<< ": failed to remove Layer 2 Multicast Group Entry";
return rv;
}
rv = sw->l2_multicast_addr_remove(port_id, vid, mc_ll);
if (rv < 0) {
LOG(ERROR) << __FUNCTION__ << ": failed to add bridging MC entry";
return rv;
}
}
VLOG(2) << __FUNCTION__ << ": mdb entry removed, port" << port_id
<< " grp= " << addr;
}
return rv;
}
} /* namespace basebox */
nl_bridge: do not install link local multicast entries
Signed-off-by: Rubens Figueiredo <22177f75c46bd149db738f8a1dfeab4c8cbd2d82@bisdn.de>
/* 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/. */
#include <cassert>
#include <cstring>
#include <map>
#include <utility>
#include <linux/if_packet.h>
#include <glog/logging.h>
#include <netlink/route/link.h>
#include <netlink/route/mdb.h>
#include <netlink/route/link/vlan.h>
#include <netlink/route/link/vxlan.h>
#include <netlink/route/neighbour.h>
#include <rofl/common/openflow/cofport.h>
#include "cnetlink.h"
#include "netlink-utils.h"
#include "nl_bridge.h"
#include "nl_output.h"
#include "nl_vxlan.h"
#include "sai.h"
#include "tap_manager.h"
namespace basebox {
nl_bridge::nl_bridge(switch_interface *sw, std::shared_ptr<tap_manager> tap_man,
cnetlink *nl, std::shared_ptr<nl_vxlan> vxlan)
: bridge(nullptr), sw(sw), tap_man(std::move(tap_man)), nl(nl),
vxlan(std::move(vxlan)),
l2_cache(nl_cache_alloc(nl_cache_ops_lookup("route/neigh")),
nl_cache_free) {
memset(&empty_br_vlan, 0, sizeof(rtnl_link_bridge_vlan));
memset(&vxlan_dom_bitmap, 0, sizeof(vxlan_dom_bitmap));
}
nl_bridge::~nl_bridge() { rtnl_link_put(bridge); }
static rofl::caddress_in4 libnl_in4addr_2_rofl(struct nl_addr *addr, int *rv) {
struct sockaddr_in sin;
socklen_t salen = sizeof(sin);
assert(rv);
*rv = nl_addr_fill_sockaddr(addr, (struct sockaddr *)&sin, &salen);
return rofl::caddress_in4(&sin, salen);
}
void nl_bridge::set_bridge_interface(rtnl_link *bridge) {
assert(bridge);
assert(std::string("bridge").compare(rtnl_link_get_type(bridge)) == 0);
this->bridge = bridge;
nl_object_get(OBJ_CAST(bridge));
if (!get_vlan_filtering())
LOG(FATAL) << __FUNCTION__
<< " unsupported: bridge configured with vlan_filtering 0";
}
bool nl_bridge::is_bridge_interface(rtnl_link *link) {
assert(link);
if (rtnl_link_get_ifindex(link) != rtnl_link_get_ifindex(bridge))
return false;
// TODO compare more?
return true;
}
// Read sysfs to obtain the value for the VLAN protocol on the switch.
// Only two values are suported: 0x8100 and 0x88a8
uint32_t nl_bridge::get_vlan_proto() {
std::string portname(rtnl_link_get_name(bridge));
return nl->load_from_file(
"/sys/class/net/" + portname + "/bridge/vlan_protocol", 16);
}
// Read sysfs to obtain the value for the VLAN filtering value on the switch.
// baseboxd currently only supports VLAN-aware bridges, set with the
// vlan_filtering flag to 1.
uint32_t nl_bridge::get_vlan_filtering() {
std::string portname(rtnl_link_get_name(bridge));
return nl->load_from_file("/sys/class/net/" + portname +
"/bridge/vlan_filtering");
}
static bool br_vlan_equal(const rtnl_link_bridge_vlan *lhs,
const rtnl_link_bridge_vlan *rhs) {
assert(lhs);
assert(rhs);
return (memcmp(lhs, rhs, sizeof(struct rtnl_link_bridge_vlan)) == 0);
}
static bool is_vid_set(unsigned vid, uint32_t *addr) {
if (vid >= RTNL_LINK_BRIDGE_VLAN_BITMAP_MAX) {
LOG(FATAL) << __FUNCTION__ << ": vid " << vid << " out of range";
return false;
}
return !!(addr[vid / 32] & (((uint32_t)1) << (vid % 32)));
}
static void set_vid(unsigned vid, uint32_t *addr) {
if (vid < RTNL_LINK_BRIDGE_VLAN_BITMAP_MAX)
addr[vid / 32] |= (((uint32_t)1) << (vid % 32));
}
static void unset_vid(unsigned vid, uint32_t *addr) {
if (vid < RTNL_LINK_BRIDGE_VLAN_BITMAP_MAX)
addr[vid / 32] &= ~(((uint32_t)1) << (vid % 32));
}
static int find_next_bit(int i, uint32_t x) {
int j;
if (i >= 32)
return -1;
/* find first bit */
if (i < 0)
return __builtin_ffs(x);
/* mask off prior finds to get next */
j = __builtin_ffs(x >> i);
return j ? j + i : 0;
}
void nl_bridge::add_interface(rtnl_link *link) {
assert(rtnl_link_get_family(link) == AF_BRIDGE);
if (bridge == nullptr) {
LOG(ERROR) << __FUNCTION__ << ": cannot be done without bridge";
return;
}
if (rtnl_link_get_ifindex(bridge) != rtnl_link_get_master(link)) {
LOG(INFO) << __FUNCTION__ << ": link " << rtnl_link_get_name(link)
<< " is no slave of " << rtnl_link_get_name(bridge);
return;
}
update_vlans(nullptr, link);
if (get_vlan_proto() == ETH_P_8021AD)
sw->set_egress_tpid(nl->get_port_id(link));
}
void nl_bridge::update_interface(rtnl_link *old_link, rtnl_link *new_link) {
assert(rtnl_link_get_family(old_link) == AF_BRIDGE);
assert(rtnl_link_get_family(new_link) == AF_BRIDGE);
// sanity checks
if (bridge == nullptr) {
LOG(ERROR) << __FUNCTION__ << ": cannot be done without bridge";
return;
}
if (rtnl_link_get_ifindex(bridge) != rtnl_link_get_master(new_link)) {
LOG(INFO) << __FUNCTION__ << ": link " << rtnl_link_get_name(new_link)
<< " is no slave of " << rtnl_link_get_name(bridge);
return;
}
update_vlans(old_link, new_link);
}
void nl_bridge::delete_interface(rtnl_link *link) {
assert(rtnl_link_get_family(link) == AF_BRIDGE);
// sanity checks
if (bridge == nullptr) {
LOG(ERROR) << __FUNCTION__ << ": cannot be done without bridge";
return;
}
if (rtnl_link_get_ifindex(bridge) != rtnl_link_get_master(link)) {
LOG(INFO) << __FUNCTION__ << ": link " << rtnl_link_get_name(link)
<< " is no slave of " << rtnl_link_get_name(bridge);
return;
}
update_vlans(link, nullptr);
if (get_vlan_proto() == ETH_P_8021AD)
sw->delete_egress_tpid(nl->get_port_id(link));
}
void nl_bridge::update_vlans(rtnl_link *old_link, rtnl_link *new_link) {
assert(sw);
assert(bridge); // already checked
rtnl_link_bridge_vlan *old_br_vlan, *new_br_vlan;
rtnl_link *_link;
if (old_link == nullptr) {
// link added
old_br_vlan = &empty_br_vlan;
new_br_vlan = rtnl_link_bridge_get_port_vlan(new_link);
_link = nl->get_link(rtnl_link_get_ifindex(new_link), AF_UNSPEC);
} else if (new_link == nullptr) {
// link deleted
old_br_vlan = rtnl_link_bridge_get_port_vlan(old_link);
new_br_vlan = &empty_br_vlan;
_link = nl->get_link(rtnl_link_get_ifindex(old_link), AF_UNSPEC);
} else {
// link updated
old_br_vlan = rtnl_link_bridge_get_port_vlan(old_link);
new_br_vlan = rtnl_link_bridge_get_port_vlan(new_link);
_link = nl->get_link(rtnl_link_get_ifindex(new_link), AF_UNSPEC);
}
if (old_br_vlan == nullptr) {
old_br_vlan = &empty_br_vlan;
}
if (new_br_vlan == nullptr) {
new_br_vlan = &empty_br_vlan;
}
if (_link == nullptr) {
// XXX FIXME in case a vxlan has been deleted the vxlan_domain and
// vxlan_dom_bitmap need an update, maybe this can be handled already from
// the link_deleted of the vxlan itself?
LOG(WARNING) << __FUNCTION__
<< ": could not get parent link of bridge interface. This "
"case needs further checks if everything got already "
"deleted.";
return;
}
// check for vid changes
if (br_vlan_equal(old_br_vlan, new_br_vlan)) {
VLOG(2) << __FUNCTION__ << ": vlans did not change";
return;
}
link_type lt = get_link_type(_link);
uint32_t pport_no = 0;
uint32_t tunnel_id = -1;
std::deque<rtnl_link *> bridge_ports;
if (lt == LT_VXLAN) {
assert(nl);
nl->get_bridge_ports(rtnl_link_get_master(_link), &bridge_ports);
if (vxlan->get_tunnel_id(_link, nullptr, &tunnel_id) != 0) {
LOG(ERROR) << __FUNCTION__ << ": failed to get vni of link "
<< OBJ_CAST(_link);
}
} else {
pport_no = nl->get_port_id(_link);
if (pport_no == 0) {
LOG(ERROR) << __FUNCTION__
<< ": invalid pport_no=0 of link: " << OBJ_CAST(_link);
return;
}
}
for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) {
int base_bit;
uint32_t a = old_br_vlan->vlan_bitmap[k];
uint32_t b = new_br_vlan->vlan_bitmap[k];
uint32_t vlan_diff = a ^ b;
#if 0 // untagged change not yet implemented
uint32_t c = old_br_vlan->untagged_bitmap[k];
uint32_t d = new_br_vlan->untagged_bitmap[k];
uint32_t untagged_diff = c ^ d;
#endif // 0
base_bit = k * 32;
int i = -1;
int done = 0;
while (!done) {
int j = find_next_bit(i, vlan_diff);
if (j > 0) {
// vlan added or removed
int vid = j - 1 + base_bit;
bool egress_untagged = false;
// check if egress is untagged
if (new_br_vlan->untagged_bitmap[k] & 1 << (j - 1)) {
egress_untagged = true;
#if 0 // untagged change not yet implemented
// clear untagged_diff bit
untagged_diff &= ~((uint32_t)1 << (j - 1));
#endif // 0
}
if (new_br_vlan->vlan_bitmap[k] & 1 << (j - 1)) {
// vlan added
if (lt == LT_VXLAN) {
// update vxlan domain
if (!is_vid_set(vid, vxlan_dom_bitmap)) {
VLOG(1) << __FUNCTION__ << ": new vxlan domain vid=" << vid
<< ", tunnel_id=" << tunnel_id;
vxlan_domain.emplace(vid, tunnel_id);
set_vid(vid, vxlan_dom_bitmap);
} else {
// XXX TODO check the map
}
// update all bridge ports to be access ports
update_access_ports(_link, new_link ? new_link : old_link, vid,
tunnel_id, bridge_ports, true);
} else {
assert(pport_no);
if (is_vid_set(vid, vxlan_dom_bitmap)) {
// configure as access port
std::string port_name = std::string(rtnl_link_get_name(_link));
auto vxd_it = vxlan_domain.find(vid);
if (vxd_it != vxlan_domain.end()) {
vxlan->create_access_port((new_link) ? new_link : old_link,
vxd_it->second, port_name, pport_no,
vid, egress_untagged, nullptr);
} else {
LOG(FATAL) << __FUNCTION__
<< ": should not happen, something is broken";
}
} else {
// normal vlan port
VLOG(3) << __FUNCTION__ << ": add vid=" << vid
<< " on pport_no=" << pport_no
<< " link: " << OBJ_CAST(_link);
sw->egress_bridge_port_vlan_add(pport_no, vid, egress_untagged);
sw->ingress_port_vlan_add(pport_no, vid,
new_br_vlan->pvid == vid);
}
}
} else {
// vlan removed
if (lt == LT_VXLAN) {
unset_vid(vid, vxlan_dom_bitmap);
vxlan_domain.erase(vid);
// update all bridge ports to be normal bridge ports
update_access_ports(_link, new_link ? new_link : old_link, vid,
tunnel_id, bridge_ports, false);
} else {
VLOG(3) << __FUNCTION__ << ": remove vid=" << vid
<< " on pport_no=" << pport_no
<< " link: " << OBJ_CAST(_link);
sw->ingress_port_vlan_remove(pport_no, vid,
old_br_vlan->pvid == vid);
// delete all FM pointing to this group first
sw->l2_addr_remove_all_in_vlan(pport_no, vid);
std::unique_ptr<rtnl_neigh, decltype(&rtnl_neigh_put)> filter(
rtnl_neigh_alloc(), rtnl_neigh_put);
rtnl_neigh_set_ifindex(filter.get(), rtnl_link_get_ifindex(bridge));
rtnl_neigh_set_master(filter.get(), rtnl_link_get_master(bridge));
rtnl_neigh_set_family(filter.get(), AF_BRIDGE);
rtnl_neigh_set_vlan(filter.get(), vid);
rtnl_neigh_set_flags(filter.get(), NTF_MASTER | NTF_EXT_LEARNED);
rtnl_neigh_set_state(filter.get(), NUD_REACHABLE);
nl_cache_foreach_filter(l2_cache.get(), OBJ_CAST(filter.get()),
[](struct nl_object *o, void *arg) {
VLOG(3) << "l2_cache remove object " << o;
nl_cache_remove(o);
},
nullptr);
sw->egress_bridge_port_vlan_remove(pport_no, vid);
}
}
i = j;
} else {
done = 1;
}
}
#if 0 // not yet implemented the update
done = 0;
i = -1;
while (!done) {
// vlan is existing, but swapping egress tagged/untagged
int j = find_next_bit(i, untagged_diff);
if (j > 0) {
// egress untagged changed
int vid = j - 1 + base_bit;
bool egress_untagged = false;
// check if egress is untagged
if (new_br_vlan->untagged_bitmap[k] & 1 << (j-1)) {
egress_untagged = true;
}
// XXX implement update
fm_driver.update_port_vid_egress(devname, vid, egress_untagged);
i = j;
} else {
done = 1;
}
}
#endif
}
}
std::deque<rtnl_neigh *> nl_bridge::get_fdb_entries_of_port(rtnl_link *br_port,
uint16_t vid,
nl_addr *lladdr) {
std::unique_ptr<rtnl_neigh, decltype(&rtnl_neigh_put)> filter(
rtnl_neigh_alloc(), rtnl_neigh_put);
rtnl_neigh_set_ifindex(filter.get(), rtnl_link_get_ifindex(br_port));
rtnl_neigh_set_master(filter.get(), rtnl_link_get_ifindex(bridge));
rtnl_neigh_set_family(filter.get(), AF_BRIDGE);
if (vid)
rtnl_neigh_set_vlan(filter.get(), vid);
if (lladdr)
rtnl_neigh_set_lladdr(filter.get(), lladdr);
VLOG(3) << __FUNCTION__ << ": searching for " << OBJ_CAST(filter.get());
std::deque<rtnl_neigh *> neighs;
nl_cache_foreach_filter(nl->get_cache(cnetlink::NL_NEIGH_CACHE),
OBJ_CAST(filter.get()),
[](struct nl_object *o, void *arg) {
auto *neighs = (std::deque<rtnl_neigh *> *)arg;
neighs->push_back(NEIGH_CAST(o));
VLOG(3) << "needs to be updated " << o;
},
&neighs);
return neighs;
}
int nl_bridge::update_access_ports(rtnl_link *vxlan_link, rtnl_link *br_link,
const uint32_t tunnel_id, bool add) {
if (vxlan_link == nullptr) {
LOG(ERROR) << __FUNCTION__ << ": vxlan_link cannot be nullptr";
return -EINVAL;
}
if (br_link == nullptr) {
LOG(ERROR) << __FUNCTION__ << ": br_link cannot be nullptr";
return -EINVAL;
}
// XXX get pvid from br_link
auto br_port_vlans = rtnl_link_bridge_get_port_vlan(br_link);
auto vid = br_port_vlans->pvid;
auto vxlan_domain_it = vxlan_domain.find(vid);
if (vxlan_domain_it != vxlan_domain.end()) {
if (vxlan_domain_it->second != tunnel_id) {
LOG(ERROR) << __FUNCTION__ << ": different tunnel_id ("
<< vxlan_domain_it->second
<< ") in vxlan_domain expected id=" << tunnel_id;
}
VLOG(2) << __FUNCTION__
<< ": access ports already configured for vid=" << vid
<< " and tunnel_id=" << tunnel_id;
// already vxlan domain
return 0;
}
// XXX get all bridge_ports
std::deque<rtnl_link *> bridge_ports;
nl->get_bridge_ports(rtnl_link_get_master(br_link), &bridge_ports);
update_access_ports(vxlan_link, br_link, vid, tunnel_id, bridge_ports, add);
// update vxlan_domain
vxlan_domain.emplace(vid, tunnel_id);
return 0;
}
void nl_bridge::update_access_ports(rtnl_link *vxlan_link, rtnl_link *br_link,
const uint16_t vid,
const uint32_t tunnel_id,
const std::deque<rtnl_link *> &bridge_ports,
bool add) {
// XXX pvid is currently not taken into account
for (auto _br_port : bridge_ports) {
auto br_port_vlans = rtnl_link_bridge_get_port_vlan(_br_port);
if (rtnl_link_get_ifindex(vxlan_link) == rtnl_link_get_ifindex(_br_port))
continue;
if (br_port_vlans == nullptr)
continue;
if (!is_vid_set(vid, br_port_vlans->vlan_bitmap))
continue;
bool untagged = is_vid_set(vid, br_port_vlans->untagged_bitmap);
int ifindex = rtnl_link_get_ifindex(_br_port);
uint32_t pport_no = nl->get_port_id(ifindex);
if (pport_no == 0) {
LOG(WARNING) << __FUNCTION__ << ": ignoring unknown port "
<< OBJ_CAST(_br_port);
continue;
}
rtnl_link *link = nl->get_link(rtnl_link_get_ifindex(_br_port), AF_UNSPEC);
VLOG(2) << __FUNCTION__ << ": vid=" << vid << ", untagged=" << untagged
<< ", tunnel_id=" << tunnel_id << ", add=" << add
<< ", ifindex=" << ifindex << ", pport_no=" << pport_no
<< ", port: " << OBJ_CAST(_br_port);
if (add) {
std::string port_name = std::string(rtnl_link_get_name(_br_port));
// this is no longer a normal bridge interface thus we delete all the
// bridging entries
sw->l2_addr_remove_all_in_vlan(pport_no, vid);
vxlan->create_access_port(_br_port, tunnel_id, port_name, pport_no, vid,
untagged, nullptr);
auto neighs = get_fdb_entries_of_port(_br_port, vid);
for (auto n : neighs) {
// ignore ll addr of bridge on slave
if (nl_addr_cmp(rtnl_link_get_addr(bridge), rtnl_neigh_get_lladdr(n)) ==
0) {
continue;
}
VLOG(3) << ": needs to be updated " << OBJ_CAST(n);
vxlan->add_l2_neigh(n, link, br_link);
}
} else {
// delete access port and all bridging entries
vxlan->delete_access_port(_br_port, pport_no, vid, true);
sw->egress_bridge_port_vlan_add(pport_no, vid, untagged);
sw->ingress_port_vlan_add(pport_no, vid, br_port_vlans->pvid == vid);
auto neighs = get_fdb_entries_of_port(_br_port, vid);
for (auto n : neighs) {
// ignore ll addr of bridge on slave
if (nl_addr_cmp(rtnl_link_get_addr(bridge), rtnl_neigh_get_lladdr(n)) ==
0) {
continue;
}
VLOG(3) << ": needs to be updated " << OBJ_CAST(n);
add_neigh_to_fdb(n);
}
}
}
}
void nl_bridge::add_neigh_to_fdb(rtnl_neigh *neigh) {
assert(sw);
assert(neigh);
uint32_t port = nl->get_port_id(rtnl_neigh_get_ifindex(neigh));
if (port == 0) {
VLOG(1) << __FUNCTION__ << ": unknown port for neigh " << OBJ_CAST(neigh);
return;
}
nl_addr *mac = rtnl_neigh_get_lladdr(neigh);
int vlan = rtnl_neigh_get_vlan(neigh);
bool permanent = true;
// for sure this is master (sw bridged)
if (rtnl_neigh_get_master(neigh) &&
!(rtnl_neigh_get_flags(neigh) & NTF_MASTER)) {
rtnl_neigh_set_flags(neigh, NTF_MASTER);
}
// check if entry already exists in cache
if (is_mac_in_l2_cache(neigh)) {
permanent = false;
}
rofl::caddress_ll _mac((uint8_t *)nl_addr_get_binary_addr(mac),
nl_addr_get_len(mac));
LOG(INFO) << __FUNCTION__ << ": add mac=" << _mac << " to bridge "
<< rtnl_link_get_name(bridge) << " on port=" << port
<< " vlan=" << (unsigned)vlan << ", permanent=" << permanent;
LOG(INFO) << __FUNCTION__ << ": object: " << OBJ_CAST(neigh);
sw->l2_addr_add(port, vlan, _mac, true, permanent);
}
void nl_bridge::remove_neigh_from_fdb(rtnl_neigh *neigh) {
assert(sw);
nl_addr *addr = rtnl_neigh_get_lladdr(neigh);
if (nl_addr_cmp(rtnl_link_get_addr(bridge), addr) == 0) {
// ignore ll addr of bridge on slave
return;
}
// lookup l2_cache as well
std::unique_ptr<rtnl_neigh, decltype(&rtnl_neigh_put)> n_lookup(
NEIGH_CAST(nl_cache_search(l2_cache.get(), OBJ_CAST(neigh))),
rtnl_neigh_put);
if (n_lookup) {
nl_cache_remove(OBJ_CAST(n_lookup.get()));
}
const uint32_t port = nl->get_port_id(rtnl_neigh_get_ifindex(neigh));
rofl::caddress_ll mac((uint8_t *)nl_addr_get_binary_addr(addr),
nl_addr_get_len(addr));
sw->l2_addr_remove(port, rtnl_neigh_get_vlan(neigh), mac);
}
bool nl_bridge::is_mac_in_l2_cache(rtnl_neigh *n) {
assert(n);
std::unique_ptr<rtnl_neigh, decltype(&rtnl_neigh_put)> n_lookup(
NEIGH_CAST(nl_cache_search(l2_cache.get(), OBJ_CAST(n))), rtnl_neigh_put);
if (n_lookup) {
VLOG(2) << __FUNCTION__ << ": found existing l2_cache entry "
<< OBJ_CAST(n_lookup.get());
return true;
}
return false;
}
int nl_bridge::learn_source_mac(rtnl_link *br_link, packet *p) {
// we still assume vlan filtering bridge
assert(rtnl_link_get_family(br_link) == AF_BRIDGE);
VLOG(2) << __FUNCTION__ << ": pkt " << p << " on link " << OBJ_CAST(br_link);
rtnl_link_bridge_vlan *br_vlan = rtnl_link_bridge_get_port_vlan(br_link);
if (br_vlan == nullptr) {
LOG(ERROR) << __FUNCTION__
<< ": only the vlan filtering bridge is supported";
return -EINVAL;
}
// parse ether frame and check for vid
auto *hdr = reinterpret_cast<basebox::vlan_hdr *>(p->data);
uint16_t vid = 0;
// XXX TODO maybe move this to the utils to have a std lib for parsing the
// ether frame
switch (ntohs(hdr->eth.h_proto)) {
case ETH_P_8021Q:
case ETH_P_8021AD:
// vid
vid = ntohs(hdr->vlan) & 0xfff;
break;
default:
// no vid, set vid to pvid
vid = br_vlan->pvid;
LOG(WARNING) << __FUNCTION__ << ": assuming untagged for ethertype "
<< std::showbase << std::hex << ntohs(hdr->eth.h_proto);
break;
}
// verify that the vid is in use here
if (!is_vid_set(vid, br_vlan->vlan_bitmap)) {
LOG(WARNING) << __FUNCTION__ << ": got packet on unconfigured port";
return -ENOTSUP;
}
// set nl neighbour to NL
std::unique_ptr<nl_addr, decltype(&nl_addr_put)> h_src(
nl_addr_build(AF_LLC, hdr->eth.h_source, sizeof(hdr->eth.h_source)),
nl_addr_put);
if (!h_src) {
LOG(ERROR) << __FUNCTION__ << ": failed to allocate src mac";
return -ENOMEM;
}
std::unique_ptr<rtnl_neigh, decltype(&rtnl_neigh_put)> n(rtnl_neigh_alloc(),
rtnl_neigh_put);
rtnl_neigh_set_ifindex(n.get(), rtnl_link_get_ifindex(br_link));
rtnl_neigh_set_master(n.get(), rtnl_link_get_master(br_link));
rtnl_neigh_set_family(n.get(), AF_BRIDGE);
rtnl_neigh_set_vlan(n.get(), vid);
rtnl_neigh_set_lladdr(n.get(), h_src.get());
rtnl_neigh_set_flags(n.get(), NTF_MASTER | NTF_EXT_LEARNED);
rtnl_neigh_set_state(n.get(), NUD_REACHABLE);
// check if entry already exists in cache
if (is_mac_in_l2_cache(n.get())) {
return 0;
}
nl_msg *msg = nullptr;
rtnl_neigh_build_add_request(n.get(),
NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL, &msg);
assert(msg);
// send the message and create new fdb entry
if (nl->send_nl_msg(msg) < 0) {
LOG(ERROR) << __FUNCTION__ << ": failed to send netlink message";
return -EINVAL;
}
// cache the entry
if (nl_cache_add(l2_cache.get(), OBJ_CAST(n.get())) < 0) {
LOG(ERROR) << __FUNCTION__ << ": failed to add entry to l2_cache "
<< OBJ_CAST(n.get());
return -EINVAL;
}
VLOG(2) << __FUNCTION__ << ": learned new source mac " << OBJ_CAST(n.get());
return 0;
}
int nl_bridge::fdb_timeout(rtnl_link *br_link, uint16_t vid,
const rofl::caddress_ll &mac) {
int rv = 0;
std::unique_ptr<rtnl_neigh, decltype(&rtnl_neigh_put)> n(rtnl_neigh_alloc(),
rtnl_neigh_put);
std::unique_ptr<nl_addr, decltype(&nl_addr_put)> h_src(
nl_addr_build(AF_LLC, mac.somem(), mac.memlen()), nl_addr_put);
rtnl_neigh_set_ifindex(n.get(), rtnl_link_get_ifindex(br_link));
rtnl_neigh_set_master(n.get(), rtnl_link_get_master(br_link));
rtnl_neigh_set_family(n.get(), AF_BRIDGE);
rtnl_neigh_set_vlan(n.get(), vid);
rtnl_neigh_set_lladdr(n.get(), h_src.get());
rtnl_neigh_set_flags(n.get(), NTF_MASTER | NTF_EXT_LEARNED);
rtnl_neigh_set_state(n.get(), NUD_REACHABLE);
// find entry in local l2_cache
std::unique_ptr<rtnl_neigh, decltype(&rtnl_neigh_put)> n_lookup(
NEIGH_CAST(nl_cache_search(l2_cache.get(), OBJ_CAST(n.get()))),
rtnl_neigh_put);
if (n_lookup) {
// * remove l2 entry from kernel
nl_msg *msg = nullptr;
rtnl_neigh_build_delete_request(n.get(), NLM_F_REQUEST, &msg);
assert(msg);
// send the message and create new fdb entry
if (nl->send_nl_msg(msg) < 0) {
LOG(ERROR) << __FUNCTION__ << ": failed to send netlink message";
return -EINVAL;
}
// XXX TODO maybe delete after NL event and not yet here
nl_cache_remove(OBJ_CAST(n_lookup.get()));
}
return rv;
}
bool nl_bridge::is_port_flooding(rtnl_link *br_link) const {
assert(br_link);
assert(rtnl_link_is_bridge(br_link));
int flags = rtnl_link_bridge_get_flags(br_link);
return !!(flags & RTNL_BRIDGE_UNICAST_FLOOD);
}
void nl_bridge::clear_tpid_entries() {
std::deque<rtnl_link *> bridge_ports;
nl->get_bridge_ports(rtnl_link_get_ifindex(bridge), &bridge_ports);
for (auto iface : bridge_ports)
sw->delete_egress_tpid(nl->get_port_id(iface));
}
int nl_bridge::mdb_entry_add(rtnl_mdb *mdb_entry) {
int rv = 0;
std::deque<struct rtnl_mdb_entry *> mdb;
uint32_t bridge = rtnl_mdb_get_ifindex(mdb_entry);
if (!is_bridge_interface(nl->get_link_by_ifindex(bridge).get())) {
LOG(ERROR) << ": bridge not set correctly";
return -EINVAL;
}
// parse MDB object to get all nested information
rtnl_mdb_foreach_entry(
mdb_entry,
[](struct rtnl_mdb_entry *it, void *arg) {
auto m_database =
static_cast<std::deque<struct rtnl_mdb_entry *> *>(arg);
m_database->push_back(it);
},
&mdb);
for (auto i : mdb) {
uint32_t port_ifindex = rtnl_mdb_entry_get_ifindex(i);
uint32_t port_id = nl->get_port_id(port_ifindex);
uint16_t vid = rtnl_mdb_entry_get_vid(i);
if (port_ifindex == get_ifindex()) {
return rv;
}
auto addr = rtnl_mdb_entry_get_addr(i);
if (rtnl_mdb_entry_get_proto(i) == ETH_P_IP) {
rofl::caddress_in4 ipv4_dst = libnl_in4addr_2_rofl(addr, &rv);
if (rv < 0) {
LOG(ERROR) << __FUNCTION__ << ": could not parse addr " << addr;
return rv;
}
unsigned char buf[ETH_ALEN];
multicast_ipv4_to_ll(ipv4_dst.get_addr_hbo(), buf);
rofl::caddress_ll mc_ll = rofl::caddress_ll(buf, ETH_ALEN);
rv = sw->l2_multicast_group_add(port_id, vid, mc_ll);
if (rv < 0) {
LOG(ERROR) << __FUNCTION__
<< ": failed to add Layer 2 Multicast Group Entry";
return rv;
}
rv = sw->l2_multicast_addr_add(port_id, vid, mc_ll);
if (rv < 0) {
LOG(ERROR) << __FUNCTION__ << ": failed to add bridging MC entry";
return rv;
}
} else if (rtnl_mdb_entry_get_proto(i) == ETH_P_IPV6) {
// Is address Linklocal Multicast
auto p = nl_addr_alloc(16);
nl_addr_parse("ff02::/10", AF_INET6, &p);
std::unique_ptr<nl_addr, decltype(&nl_addr_put)> tm_addr(p, nl_addr_put);
if (!nl_addr_cmp_prefix(addr, tm_addr.get()))
return 0;
struct in6_addr *v6_addr =
(struct in6_addr *)nl_addr_get_binary_addr(addr);
unsigned char buf[ETH_ALEN];
multicast_ipv6_to_ll(v6_addr, buf);
rofl::caddress_ll mc_ll = rofl::caddress_ll(buf, ETH_ALEN);
rv = sw->l2_multicast_group_add(port_id, vid, mc_ll);
if (rv < 0) {
LOG(ERROR) << __FUNCTION__
<< ": failed to add Layer 2 Multicast Group Entry";
return rv;
}
rv = sw->l2_multicast_addr_add(port_id, vid, mc_ll);
if (rv < 0) {
LOG(ERROR) << __FUNCTION__ << ": failed to add bridging MC entry";
return rv;
}
}
VLOG(2) << __FUNCTION__ << ": mdb entry added, port" << port_id
<< " grp= " << addr;
}
return rv;
}
int nl_bridge::mdb_entry_remove(rtnl_mdb *mdb_entry) {
int rv = 0;
uint32_t bridge = rtnl_mdb_get_ifindex(mdb_entry);
if (!is_bridge_interface(nl->get_link_by_ifindex(bridge).get())) {
LOG(ERROR) << ": bridge not set correctly";
return -EINVAL;
}
std::deque<struct rtnl_mdb_entry *> mdb;
// parse MDB object to get all nested information
rtnl_mdb_foreach_entry(
mdb_entry,
[](struct rtnl_mdb_entry *it, void *arg) {
auto m_database =
static_cast<std::deque<struct rtnl_mdb_entry *> *>(arg);
m_database->push_back(it);
},
&mdb);
for (auto i : mdb) {
uint32_t port_ifindex = rtnl_mdb_entry_get_ifindex(i);
uint32_t port_id = nl->get_port_id(port_ifindex);
uint16_t vid = rtnl_mdb_entry_get_vid(i);
auto addr = rtnl_mdb_entry_get_addr(i);
if (rtnl_mdb_entry_get_proto(i) == ETH_P_IP) {
rofl::caddress_in4 ipv4_dst = libnl_in4addr_2_rofl(addr, &rv);
if (rv < 0) {
LOG(ERROR) << __FUNCTION__ << ": could not parse addr " << addr;
return rv;
}
unsigned char buf[ETH_ALEN];
multicast_ipv4_to_ll(ipv4_dst.get_addr_hbo(), buf);
rofl::caddress_ll mc_ll = rofl::caddress_ll(buf, ETH_ALEN);
rv = sw->l2_multicast_group_remove(port_id, vid, mc_ll);
// nothing left to do, there are still entries in the mc group
if (rv == -ENOTEMPTY) {
return 0;
} else if (rv < 0) {
LOG(ERROR) << __FUNCTION__
<< ": failed to remove Layer 2 Multicast Group Entry";
return rv;
}
rv = sw->l2_multicast_addr_remove(port_id, vid, mc_ll);
if (rv < 0) {
LOG(ERROR) << __FUNCTION__ << ": failed to add bridging MC entry";
return rv;
}
} else if (rtnl_mdb_entry_get_proto(i) == ETH_P_IPV6) {
struct in6_addr *v6_addr =
(struct in6_addr *)nl_addr_get_binary_addr(addr);
unsigned char buf[ETH_ALEN];
multicast_ipv6_to_ll(v6_addr, buf);
rofl::caddress_ll mc_ll = rofl::caddress_ll(buf, ETH_ALEN);
rv = sw->l2_multicast_group_remove(port_id, vid, mc_ll);
// nothing left to do, there are still entries in the mc group
if (rv == -ENOTEMPTY) {
return 0;
} else if (rv < 0) {
LOG(ERROR) << __FUNCTION__
<< ": failed to remove Layer 2 Multicast Group Entry";
return rv;
}
rv = sw->l2_multicast_addr_remove(port_id, vid, mc_ll);
if (rv < 0) {
LOG(ERROR) << __FUNCTION__ << ": failed to add bridging MC entry";
return rv;
}
}
VLOG(2) << __FUNCTION__ << ": mdb entry removed, port" << port_id
<< " grp= " << addr;
}
return rv;
}
} /* namespace basebox */
|
/*
* Copyright (C) 2014 Andrew Duggan
* Copyright (C) 2014 Synaptics Inc
*
* 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 <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <linux/types.h>
#include <linux/input.h>
#include <linux/hidraw.h>
#include <signal.h>
#include <stdlib.h>
#include "hiddevice.h"
#define RMI_WRITE_REPORT_ID 0x9 // Output Report
#define RMI_READ_ADDR_REPORT_ID 0xa // Output Report
#define RMI_READ_DATA_REPORT_ID 0xb // Input Report
#define RMI_ATTN_REPORT_ID 0xc // Input Report
#define RMI_SET_RMI_MODE_REPORT_ID 0xf // Feature Report
enum rmi_hid_mode_type {
HID_RMI4_MODE_MOUSE = 0,
HID_RMI4_MODE_ATTN_REPORTS = 1,
HID_RMI4_MODE_NO_PACKED_ATTN_REPORTS = 2,
};
enum hid_report_type {
HID_REPORT_TYPE_UNKNOWN = 0x0,
HID_REPORT_TYPE_INPUT = 0x81,
HID_REPORT_TYPE_OUTPUT = 0x91,
HID_REPORT_TYPE_FEATURE = 0xb1,
};
#define HID_RMI4_REPORT_ID 0
#define HID_RMI4_READ_INPUT_COUNT 1
#define HID_RMI4_READ_INPUT_DATA 2
#define HID_RMI4_READ_OUTPUT_ADDR 2
#define HID_RMI4_READ_OUTPUT_COUNT 4
#define HID_RMI4_WRITE_OUTPUT_COUNT 1
#define HID_RMI4_WRITE_OUTPUT_ADDR 2
#define HID_RMI4_WRITE_OUTPUT_DATA 4
#define HID_RMI4_FEATURE_MODE 1
#define HID_RMI4_ATTN_INTERUPT_SOURCES 1
#define HID_RMI4_ATTN_DATA 2
int HIDDevice::Open(const char * filename)
{
int rc;
int desc_size;
if (!filename)
return -EINVAL;
m_fd = open(filename, O_RDWR);
if (m_fd < 0)
return -1;
memset(&m_rptDesc, 0, sizeof(m_rptDesc));
memset(&m_info, 0, sizeof(m_info));
rc = ioctl(m_fd, HIDIOCGRDESCSIZE, &desc_size);
if (rc < 0)
return rc;
m_rptDesc.size = desc_size;
rc = ioctl(m_fd, HIDIOCGRDESC, &m_rptDesc);
if (rc < 0)
return rc;
rc = ioctl(m_fd, HIDIOCGRAWINFO, &m_info);
if (rc < 0)
return rc;
ParseReportSizes();
m_inputReport = new unsigned char[m_inputReportSize]();
if (!m_inputReport)
return -ENOMEM;
m_outputReport = new unsigned char[m_outputReportSize]();
if (!m_outputReport)
return -ENOMEM;
m_readData = new unsigned char[m_inputReportSize]();
if (!m_readData)
return -ENOMEM;
m_attnReportQueue = new unsigned char[m_inputReportSize * HID_REPORT_QUEUE_MAX_SIZE]();
if (!m_attnReportQueue)
return -ENOMEM;
m_deviceOpen = true;
rc = SetMode(HID_RMI4_MODE_ATTN_REPORTS);
if (rc)
return -1;
return 0;
}
void HIDDevice::ParseReportSizes()
{
bool isVendorSpecific = false;
bool isReport = false;
int totalReportSize = 0;
int reportSize = 0;
int reportCount = 0;
enum hid_report_type hidReportType = HID_REPORT_TYPE_UNKNOWN;
for (unsigned int i = 0; i < m_rptDesc.size; ++i) {
if (isVendorSpecific) {
if (m_rptDesc.value[i] == 0x85 || m_rptDesc.value[i] == 0xc0) {
if (isReport) {
// finish up data on the previous report
totalReportSize = (reportSize * reportCount) >> 3;
switch (hidReportType) {
case HID_REPORT_TYPE_INPUT:
m_inputReportSize = totalReportSize + 1;
break;
case HID_REPORT_TYPE_OUTPUT:
m_outputReportSize = totalReportSize + 1;
break;
case HID_REPORT_TYPE_FEATURE:
m_featureReportSize = totalReportSize + 1;
break;
case HID_REPORT_TYPE_UNKNOWN:
default:
break;
}
}
// reset values for the new report
totalReportSize = 0;
reportSize = 0;
reportCount = 0;
hidReportType = HID_REPORT_TYPE_UNKNOWN;
if (m_rptDesc.value[i] == 0x85)
isReport = true;
else
isReport = false;
if (m_rptDesc.value[i] == 0xc0)
isVendorSpecific = false;
}
if (isReport) {
if (m_rptDesc.value[i] == 0x75) {
reportSize = m_rptDesc.value[++i];
continue;
}
if (m_rptDesc.value[i] == 0x95) {
reportCount = m_rptDesc.value[++i];
continue;
}
if (m_rptDesc.value[i] == HID_REPORT_TYPE_INPUT)
hidReportType = HID_REPORT_TYPE_INPUT;
if (m_rptDesc.value[i] == HID_REPORT_TYPE_OUTPUT)
hidReportType = HID_REPORT_TYPE_OUTPUT;
if (m_rptDesc.value[i] == HID_REPORT_TYPE_FEATURE) {
hidReportType = HID_REPORT_TYPE_FEATURE;
}
}
}
if (m_rptDesc.value[i] == 0x06 && m_rptDesc.value[i + 1] == 0x00
&& m_rptDesc.value[i + 2] == 0xFF) {
isVendorSpecific = true;
i += 2;
}
}
}
int HIDDevice::Read(unsigned short addr, unsigned char *buf, unsigned short len)
{
size_t count;
size_t bytesReadPerRequest;
size_t bytesInDataReport;
size_t totalBytesRead;
size_t bytesPerRequest;
size_t bytesWritten;
size_t bytesToRequest;
int rc;
if (!m_deviceOpen)
return -1;
if (m_bytesPerReadRequest)
bytesPerRequest = m_bytesPerReadRequest;
else
bytesPerRequest = len;
for (totalBytesRead = 0; totalBytesRead < len; totalBytesRead += bytesReadPerRequest) {
count = 0;
if ((len - totalBytesRead) < bytesPerRequest)
bytesToRequest = len % bytesPerRequest;
else
bytesToRequest = bytesPerRequest;
m_outputReport[HID_RMI4_REPORT_ID] = RMI_READ_ADDR_REPORT_ID;
m_outputReport[1] = 0; /* old 1 byte read count */
m_outputReport[HID_RMI4_READ_OUTPUT_ADDR] = addr & 0xFF;
m_outputReport[HID_RMI4_READ_OUTPUT_ADDR + 1] = (addr >> 8) & 0xFF;
m_outputReport[HID_RMI4_READ_OUTPUT_COUNT] = bytesToRequest & 0xFF;
m_outputReport[HID_RMI4_READ_OUTPUT_COUNT + 1] = (bytesToRequest >> 8) & 0xFF;
m_dataBytesRead = 0;
for (bytesWritten = 0; bytesWritten < m_outputReportSize; bytesWritten += count) {
m_bCancel = false;
count = write(m_fd, m_outputReport + bytesWritten,
m_outputReportSize - bytesWritten);
if (count < 0) {
if (errno == EINTR && m_deviceOpen && !m_bCancel)
continue;
else
return count;
}
break;
}
bytesReadPerRequest = 0;
while (bytesReadPerRequest < bytesToRequest) {
rc = GetReport(RMI_READ_DATA_REPORT_ID);
if (rc > 0) {
bytesInDataReport = m_readData[HID_RMI4_READ_INPUT_COUNT];
memcpy(buf + bytesReadPerRequest, &m_readData[HID_RMI4_READ_INPUT_DATA],
bytesInDataReport);
bytesReadPerRequest += bytesInDataReport;
m_dataBytesRead = 0;
}
}
addr += bytesPerRequest;
}
return totalBytesRead;
}
int HIDDevice::Write(unsigned short addr, const unsigned char *buf, unsigned short len)
{
size_t count;
if (!m_deviceOpen)
return -1;
m_outputReport[HID_RMI4_REPORT_ID] = RMI_WRITE_REPORT_ID;
m_outputReport[HID_RMI4_WRITE_OUTPUT_COUNT] = len;
m_outputReport[HID_RMI4_WRITE_OUTPUT_ADDR] = addr & 0xFF;
m_outputReport[HID_RMI4_WRITE_OUTPUT_ADDR + 1] = (addr >> 8) & 0xFF;
memcpy(&m_outputReport[HID_RMI4_WRITE_OUTPUT_DATA], buf, len);
for (;;) {
m_bCancel = false;
count = write(m_fd, m_outputReport, m_outputReportSize);
if (count < 0) {
if (errno == EINTR && m_deviceOpen && !m_bCancel)
continue;
else
return count;
}
return count;
}
}
int HIDDevice::SetMode(int mode)
{
int rc;
char buf[2];
if (!m_deviceOpen)
return -1;
buf[0] = 0xF;
buf[1] = mode;
rc = ioctl(m_fd, HIDIOCSFEATURE(2), buf);
if (rc < 0) {
perror("HIDIOCSFEATURE");
return rc;
}
return 0;
}
void HIDDevice::Close()
{
if (!m_deviceOpen)
return;
SetMode(HID_RMI4_MODE_MOUSE);
m_deviceOpen = false;
close(m_fd);
m_fd = -1;
delete[] m_inputReport;
m_inputReport = NULL;
delete[] m_outputReport;
m_outputReport = NULL;
delete[] m_readData;
m_readData = NULL;
delete[] m_attnReportQueue;
m_attnReportQueue = NULL;
}
int HIDDevice::WaitForAttention(struct timeval * timeout, int *sources)
{
return GetAttentionReport(timeout, sources, NULL, NULL);
}
int HIDDevice::GetAttentionReport(struct timeval * timeout, int *sources, unsigned char *buf, unsigned int *len)
{
int rc;
int interrupt_sources;
const unsigned char * queue_report;
int bytes = m_inputReportSize;
if (len && m_inputReportSize < *len) {
bytes = *len;
*len = m_inputReportSize;
}
rc = GetReport(RMI_ATTN_REPORT_ID, timeout);
if (rc > 0) {
queue_report = m_attnReportQueue
+ m_inputReportSize * m_tailIdx;
interrupt_sources = queue_report[HID_RMI4_ATTN_INTERUPT_SOURCES];
if (buf)
memcpy(buf, queue_report, bytes);
m_tailIdx = (m_tailIdx + 1) & (HID_REPORT_QUEUE_MAX_SIZE - 1);
--m_attnQueueCount;
if (sources)
*sources = interrupt_sources;
return rc;
}
return rc;
}
int HIDDevice::GetReport(int reportid, struct timeval * timeout)
{
size_t count = 0;
unsigned char *queue_report;
fd_set fds;
int rc;
int report_count = 0;
if (!m_deviceOpen)
return -1;
for (;;) {
FD_ZERO(&fds);
FD_SET(m_fd, &fds);
rc = select(m_fd + 1, &fds, NULL, NULL, timeout);
if (rc == 0) {
return -ETIMEDOUT;
} else if (rc < 0) {
if (errno == EINTR && m_deviceOpen && !m_bCancel)
continue;
else
return rc;
} else if (rc > 0 && FD_ISSET(m_fd, &fds)) {
size_t offset = 0;
for (;;) {
m_bCancel = false;
count = read(m_fd, m_inputReport + offset, m_inputReportSize - offset);
if (count < 0) {
if (errno == EINTR && m_deviceOpen && !m_bCancel)
continue;
else
return count;
}
offset += count;
if (offset == m_inputReportSize)
break;
}
}
if (m_inputReport[HID_RMI4_REPORT_ID] == RMI_ATTN_REPORT_ID) {
queue_report = m_attnReportQueue
+ m_inputReportSize * m_headIdx;
memcpy(queue_report, m_inputReport, count);
m_headIdx = (m_headIdx + 1) & (HID_REPORT_QUEUE_MAX_SIZE - 1);
++m_attnQueueCount;
} else if (m_inputReport[HID_RMI4_REPORT_ID] == RMI_READ_DATA_REPORT_ID) {
memcpy(m_readData, m_inputReport, count);
m_dataBytesRead = count;
}
++report_count;
if (m_inputReport[HID_RMI4_REPORT_ID] == reportid)
break;
}
return report_count;
}
void HIDDevice::PrintReport(const unsigned char *report)
{
int i;
int len = 0;
const unsigned char * data;
int addr = 0;
switch (report[HID_RMI4_REPORT_ID]) {
case RMI_WRITE_REPORT_ID:
len = report[HID_RMI4_WRITE_OUTPUT_COUNT];
data = &report[HID_RMI4_WRITE_OUTPUT_DATA];
addr = (report[HID_RMI4_WRITE_OUTPUT_ADDR] & 0xFF)
| ((report[HID_RMI4_WRITE_OUTPUT_ADDR + 1] & 0xFF) << 8);
fprintf(stdout, "Write Report:\n");
fprintf(stdout, "Address = 0x%02X\n", addr);
fprintf(stdout, "Length = 0x%02X\n", len);
break;
case RMI_READ_ADDR_REPORT_ID:
addr = (report[HID_RMI4_READ_OUTPUT_ADDR] & 0xFF)
| ((report[HID_RMI4_READ_OUTPUT_ADDR + 1] & 0xFF) << 8);
len = (report[HID_RMI4_READ_OUTPUT_COUNT] & 0xFF)
| ((report[HID_RMI4_READ_OUTPUT_COUNT + 1] & 0xFF) << 8);
fprintf(stdout, "Read Request (Output Report):\n");
fprintf(stdout, "Address = 0x%02X\n", addr);
fprintf(stdout, "Length = 0x%02X\n", len);
return;
break;
case RMI_READ_DATA_REPORT_ID:
len = report[HID_RMI4_READ_INPUT_COUNT];
data = &report[HID_RMI4_READ_INPUT_DATA];
fprintf(stdout, "Read Data Report:\n");
fprintf(stdout, "Length = 0x%02X\n", len);
break;
case RMI_ATTN_REPORT_ID:
fprintf(stdout, "Attention Report:\n");
len = 28;
data = &report[HID_RMI4_ATTN_DATA];
fprintf(stdout, "Interrupt Sources: 0x%02X\n",
report[HID_RMI4_ATTN_INTERUPT_SOURCES]);
break;
default:
fprintf(stderr, "Unknown Report: ID 0x%02x\n", report[HID_RMI4_REPORT_ID]);
return;
}
fprintf(stdout, "Data:\n");
for (i = 0; i < len; ++i) {
fprintf(stdout, "0x%02X ", data[i]);
if (i % 8 == 7) {
fprintf(stdout, "\n");
}
}
fprintf(stdout, "\n\n");
}
Used signed variables to store the result from read/write.
/*
* Copyright (C) 2014 Andrew Duggan
* Copyright (C) 2014 Synaptics Inc
*
* 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 <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <linux/types.h>
#include <linux/input.h>
#include <linux/hidraw.h>
#include <signal.h>
#include <stdlib.h>
#include "hiddevice.h"
#define RMI_WRITE_REPORT_ID 0x9 // Output Report
#define RMI_READ_ADDR_REPORT_ID 0xa // Output Report
#define RMI_READ_DATA_REPORT_ID 0xb // Input Report
#define RMI_ATTN_REPORT_ID 0xc // Input Report
#define RMI_SET_RMI_MODE_REPORT_ID 0xf // Feature Report
enum rmi_hid_mode_type {
HID_RMI4_MODE_MOUSE = 0,
HID_RMI4_MODE_ATTN_REPORTS = 1,
HID_RMI4_MODE_NO_PACKED_ATTN_REPORTS = 2,
};
enum hid_report_type {
HID_REPORT_TYPE_UNKNOWN = 0x0,
HID_REPORT_TYPE_INPUT = 0x81,
HID_REPORT_TYPE_OUTPUT = 0x91,
HID_REPORT_TYPE_FEATURE = 0xb1,
};
#define HID_RMI4_REPORT_ID 0
#define HID_RMI4_READ_INPUT_COUNT 1
#define HID_RMI4_READ_INPUT_DATA 2
#define HID_RMI4_READ_OUTPUT_ADDR 2
#define HID_RMI4_READ_OUTPUT_COUNT 4
#define HID_RMI4_WRITE_OUTPUT_COUNT 1
#define HID_RMI4_WRITE_OUTPUT_ADDR 2
#define HID_RMI4_WRITE_OUTPUT_DATA 4
#define HID_RMI4_FEATURE_MODE 1
#define HID_RMI4_ATTN_INTERUPT_SOURCES 1
#define HID_RMI4_ATTN_DATA 2
int HIDDevice::Open(const char * filename)
{
int rc;
int desc_size;
if (!filename)
return -EINVAL;
m_fd = open(filename, O_RDWR);
if (m_fd < 0)
return -1;
memset(&m_rptDesc, 0, sizeof(m_rptDesc));
memset(&m_info, 0, sizeof(m_info));
rc = ioctl(m_fd, HIDIOCGRDESCSIZE, &desc_size);
if (rc < 0)
return rc;
m_rptDesc.size = desc_size;
rc = ioctl(m_fd, HIDIOCGRDESC, &m_rptDesc);
if (rc < 0)
return rc;
rc = ioctl(m_fd, HIDIOCGRAWINFO, &m_info);
if (rc < 0)
return rc;
ParseReportSizes();
m_inputReport = new unsigned char[m_inputReportSize]();
if (!m_inputReport)
return -ENOMEM;
m_outputReport = new unsigned char[m_outputReportSize]();
if (!m_outputReport)
return -ENOMEM;
m_readData = new unsigned char[m_inputReportSize]();
if (!m_readData)
return -ENOMEM;
m_attnReportQueue = new unsigned char[m_inputReportSize * HID_REPORT_QUEUE_MAX_SIZE]();
if (!m_attnReportQueue)
return -ENOMEM;
m_deviceOpen = true;
rc = SetMode(HID_RMI4_MODE_ATTN_REPORTS);
if (rc)
return -1;
return 0;
}
void HIDDevice::ParseReportSizes()
{
bool isVendorSpecific = false;
bool isReport = false;
int totalReportSize = 0;
int reportSize = 0;
int reportCount = 0;
enum hid_report_type hidReportType = HID_REPORT_TYPE_UNKNOWN;
for (unsigned int i = 0; i < m_rptDesc.size; ++i) {
if (isVendorSpecific) {
if (m_rptDesc.value[i] == 0x85 || m_rptDesc.value[i] == 0xc0) {
if (isReport) {
// finish up data on the previous report
totalReportSize = (reportSize * reportCount) >> 3;
switch (hidReportType) {
case HID_REPORT_TYPE_INPUT:
m_inputReportSize = totalReportSize + 1;
break;
case HID_REPORT_TYPE_OUTPUT:
m_outputReportSize = totalReportSize + 1;
break;
case HID_REPORT_TYPE_FEATURE:
m_featureReportSize = totalReportSize + 1;
break;
case HID_REPORT_TYPE_UNKNOWN:
default:
break;
}
}
// reset values for the new report
totalReportSize = 0;
reportSize = 0;
reportCount = 0;
hidReportType = HID_REPORT_TYPE_UNKNOWN;
if (m_rptDesc.value[i] == 0x85)
isReport = true;
else
isReport = false;
if (m_rptDesc.value[i] == 0xc0)
isVendorSpecific = false;
}
if (isReport) {
if (m_rptDesc.value[i] == 0x75) {
reportSize = m_rptDesc.value[++i];
continue;
}
if (m_rptDesc.value[i] == 0x95) {
reportCount = m_rptDesc.value[++i];
continue;
}
if (m_rptDesc.value[i] == HID_REPORT_TYPE_INPUT)
hidReportType = HID_REPORT_TYPE_INPUT;
if (m_rptDesc.value[i] == HID_REPORT_TYPE_OUTPUT)
hidReportType = HID_REPORT_TYPE_OUTPUT;
if (m_rptDesc.value[i] == HID_REPORT_TYPE_FEATURE) {
hidReportType = HID_REPORT_TYPE_FEATURE;
}
}
}
if (m_rptDesc.value[i] == 0x06 && m_rptDesc.value[i + 1] == 0x00
&& m_rptDesc.value[i + 2] == 0xFF) {
isVendorSpecific = true;
i += 2;
}
}
}
int HIDDevice::Read(unsigned short addr, unsigned char *buf, unsigned short len)
{
ssize_t count;
size_t bytesReadPerRequest;
size_t bytesInDataReport;
size_t totalBytesRead;
size_t bytesPerRequest;
size_t bytesWritten;
size_t bytesToRequest;
int rc;
if (!m_deviceOpen)
return -1;
if (m_bytesPerReadRequest)
bytesPerRequest = m_bytesPerReadRequest;
else
bytesPerRequest = len;
for (totalBytesRead = 0; totalBytesRead < len; totalBytesRead += bytesReadPerRequest) {
count = 0;
if ((len - totalBytesRead) < bytesPerRequest)
bytesToRequest = len % bytesPerRequest;
else
bytesToRequest = bytesPerRequest;
m_outputReport[HID_RMI4_REPORT_ID] = RMI_READ_ADDR_REPORT_ID;
m_outputReport[1] = 0; /* old 1 byte read count */
m_outputReport[HID_RMI4_READ_OUTPUT_ADDR] = addr & 0xFF;
m_outputReport[HID_RMI4_READ_OUTPUT_ADDR + 1] = (addr >> 8) & 0xFF;
m_outputReport[HID_RMI4_READ_OUTPUT_COUNT] = bytesToRequest & 0xFF;
m_outputReport[HID_RMI4_READ_OUTPUT_COUNT + 1] = (bytesToRequest >> 8) & 0xFF;
m_dataBytesRead = 0;
for (bytesWritten = 0; bytesWritten < m_outputReportSize; bytesWritten += count) {
m_bCancel = false;
count = write(m_fd, m_outputReport + bytesWritten,
m_outputReportSize - bytesWritten);
if (count < 0) {
if (errno == EINTR && m_deviceOpen && !m_bCancel)
continue;
else
return count;
}
break;
}
bytesReadPerRequest = 0;
while (bytesReadPerRequest < bytesToRequest) {
rc = GetReport(RMI_READ_DATA_REPORT_ID);
if (rc > 0) {
bytesInDataReport = m_readData[HID_RMI4_READ_INPUT_COUNT];
memcpy(buf + bytesReadPerRequest, &m_readData[HID_RMI4_READ_INPUT_DATA],
bytesInDataReport);
bytesReadPerRequest += bytesInDataReport;
m_dataBytesRead = 0;
}
}
addr += bytesPerRequest;
}
return totalBytesRead;
}
int HIDDevice::Write(unsigned short addr, const unsigned char *buf, unsigned short len)
{
ssize_t count;
if (!m_deviceOpen)
return -1;
m_outputReport[HID_RMI4_REPORT_ID] = RMI_WRITE_REPORT_ID;
m_outputReport[HID_RMI4_WRITE_OUTPUT_COUNT] = len;
m_outputReport[HID_RMI4_WRITE_OUTPUT_ADDR] = addr & 0xFF;
m_outputReport[HID_RMI4_WRITE_OUTPUT_ADDR + 1] = (addr >> 8) & 0xFF;
memcpy(&m_outputReport[HID_RMI4_WRITE_OUTPUT_DATA], buf, len);
for (;;) {
m_bCancel = false;
count = write(m_fd, m_outputReport, m_outputReportSize);
if (count < 0) {
if (errno == EINTR && m_deviceOpen && !m_bCancel)
continue;
else
return count;
}
return count;
}
}
int HIDDevice::SetMode(int mode)
{
int rc;
char buf[2];
if (!m_deviceOpen)
return -1;
buf[0] = 0xF;
buf[1] = mode;
rc = ioctl(m_fd, HIDIOCSFEATURE(2), buf);
if (rc < 0) {
perror("HIDIOCSFEATURE");
return rc;
}
return 0;
}
void HIDDevice::Close()
{
if (!m_deviceOpen)
return;
SetMode(HID_RMI4_MODE_MOUSE);
m_deviceOpen = false;
close(m_fd);
m_fd = -1;
delete[] m_inputReport;
m_inputReport = NULL;
delete[] m_outputReport;
m_outputReport = NULL;
delete[] m_readData;
m_readData = NULL;
delete[] m_attnReportQueue;
m_attnReportQueue = NULL;
}
int HIDDevice::WaitForAttention(struct timeval * timeout, int *sources)
{
return GetAttentionReport(timeout, sources, NULL, NULL);
}
int HIDDevice::GetAttentionReport(struct timeval * timeout, int *sources, unsigned char *buf, unsigned int *len)
{
int rc;
int interrupt_sources;
const unsigned char * queue_report;
int bytes = m_inputReportSize;
if (len && m_inputReportSize < *len) {
bytes = *len;
*len = m_inputReportSize;
}
rc = GetReport(RMI_ATTN_REPORT_ID, timeout);
if (rc > 0) {
queue_report = m_attnReportQueue
+ m_inputReportSize * m_tailIdx;
interrupt_sources = queue_report[HID_RMI4_ATTN_INTERUPT_SOURCES];
if (buf)
memcpy(buf, queue_report, bytes);
m_tailIdx = (m_tailIdx + 1) & (HID_REPORT_QUEUE_MAX_SIZE - 1);
--m_attnQueueCount;
if (sources)
*sources = interrupt_sources;
return rc;
}
return rc;
}
int HIDDevice::GetReport(int reportid, struct timeval * timeout)
{
ssize_t count = 0;
unsigned char *queue_report;
fd_set fds;
int rc;
int report_count = 0;
if (!m_deviceOpen)
return -1;
for (;;) {
FD_ZERO(&fds);
FD_SET(m_fd, &fds);
rc = select(m_fd + 1, &fds, NULL, NULL, timeout);
if (rc == 0) {
return -ETIMEDOUT;
} else if (rc < 0) {
if (errno == EINTR && m_deviceOpen && !m_bCancel)
continue;
else
return rc;
} else if (rc > 0 && FD_ISSET(m_fd, &fds)) {
size_t offset = 0;
for (;;) {
m_bCancel = false;
count = read(m_fd, m_inputReport + offset, m_inputReportSize - offset);
if (count < 0) {
if (errno == EINTR && m_deviceOpen && !m_bCancel)
continue;
else
return count;
}
offset += count;
if (offset == m_inputReportSize)
break;
}
}
if (m_inputReport[HID_RMI4_REPORT_ID] == RMI_ATTN_REPORT_ID) {
queue_report = m_attnReportQueue
+ m_inputReportSize * m_headIdx;
memcpy(queue_report, m_inputReport, count);
m_headIdx = (m_headIdx + 1) & (HID_REPORT_QUEUE_MAX_SIZE - 1);
++m_attnQueueCount;
} else if (m_inputReport[HID_RMI4_REPORT_ID] == RMI_READ_DATA_REPORT_ID) {
memcpy(m_readData, m_inputReport, count);
m_dataBytesRead = count;
}
++report_count;
if (m_inputReport[HID_RMI4_REPORT_ID] == reportid)
break;
}
return report_count;
}
void HIDDevice::PrintReport(const unsigned char *report)
{
int i;
int len = 0;
const unsigned char * data;
int addr = 0;
switch (report[HID_RMI4_REPORT_ID]) {
case RMI_WRITE_REPORT_ID:
len = report[HID_RMI4_WRITE_OUTPUT_COUNT];
data = &report[HID_RMI4_WRITE_OUTPUT_DATA];
addr = (report[HID_RMI4_WRITE_OUTPUT_ADDR] & 0xFF)
| ((report[HID_RMI4_WRITE_OUTPUT_ADDR + 1] & 0xFF) << 8);
fprintf(stdout, "Write Report:\n");
fprintf(stdout, "Address = 0x%02X\n", addr);
fprintf(stdout, "Length = 0x%02X\n", len);
break;
case RMI_READ_ADDR_REPORT_ID:
addr = (report[HID_RMI4_READ_OUTPUT_ADDR] & 0xFF)
| ((report[HID_RMI4_READ_OUTPUT_ADDR + 1] & 0xFF) << 8);
len = (report[HID_RMI4_READ_OUTPUT_COUNT] & 0xFF)
| ((report[HID_RMI4_READ_OUTPUT_COUNT + 1] & 0xFF) << 8);
fprintf(stdout, "Read Request (Output Report):\n");
fprintf(stdout, "Address = 0x%02X\n", addr);
fprintf(stdout, "Length = 0x%02X\n", len);
return;
break;
case RMI_READ_DATA_REPORT_ID:
len = report[HID_RMI4_READ_INPUT_COUNT];
data = &report[HID_RMI4_READ_INPUT_DATA];
fprintf(stdout, "Read Data Report:\n");
fprintf(stdout, "Length = 0x%02X\n", len);
break;
case RMI_ATTN_REPORT_ID:
fprintf(stdout, "Attention Report:\n");
len = 28;
data = &report[HID_RMI4_ATTN_DATA];
fprintf(stdout, "Interrupt Sources: 0x%02X\n",
report[HID_RMI4_ATTN_INTERUPT_SOURCES]);
break;
default:
fprintf(stderr, "Unknown Report: ID 0x%02x\n", report[HID_RMI4_REPORT_ID]);
return;
}
fprintf(stdout, "Data:\n");
for (i = 0; i < len; ++i) {
fprintf(stdout, "0x%02X ", data[i]);
if (i % 8 == 7) {
fprintf(stdout, "\n");
}
}
fprintf(stdout, "\n\n");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.