commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
9ac68abd5c0c523bf2489840fb7d31729d40b508
|
src/modules/mc_pos_control/PositionControl/ControlMathTest.cpp
|
src/modules/mc_pos_control/PositionControl/ControlMathTest.cpp
|
/****************************************************************************
*
* Copyright (C) 2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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 <gtest/gtest.h>
#include <ControlMath.hpp>
#include <px4_platform_common/defines.h>
using namespace matrix;
using namespace ControlMath;
TEST(ControlMathTest, ThrottleAttitudeMapping)
{
/* expected: zero roll, zero pitch, zero yaw, full thr mag
* reason: thrust pointing full upward */
Vector3f thr{0.0f, 0.0f, -1.0f};
float yaw = 0.0f;
vehicle_attitude_setpoint_s att{};
thrustToAttitude(thr, yaw, att);
EXPECT_EQ(att.roll_body, 0);
EXPECT_EQ(att.pitch_body, 0);
EXPECT_EQ(att.yaw_body, 0);
EXPECT_EQ(att.thrust_body[2], -1.f);
/* expected: same as before but with 90 yaw
* reason: only yaw changed */
yaw = M_PI_2_F;
thrustToAttitude(thr, yaw, att);
EXPECT_EQ(att.roll_body, 0);
EXPECT_EQ(att.pitch_body, 0);
EXPECT_EQ(att.yaw_body, M_PI_2_F);
EXPECT_EQ(att.thrust_body[2], -1.f);
/* expected: same as before but roll 180
* reason: thrust points straight down and order Euler
* order is: 1. roll, 2. pitch, 3. yaw */
thr = Vector3f(0.0f, 0.0f, 1.0f);
thrustToAttitude(thr, yaw, att);
EXPECT_NEAR(att.roll_body, -M_PI_F, 1e-4);
EXPECT_EQ(att.pitch_body, 0);
EXPECT_EQ(att.yaw_body, M_PI_2_F);
EXPECT_EQ(att.thrust_body[2], -1.f);
}
TEST(ControlMathTest, ConstrainXYPriorities)
{
const float max = 5.0f;
// v0 already at max
Vector2f v0(max, 0);
Vector2f v1(v0(1), -v0(0));
Vector2f v_r = constrainXY(v0, v1, max);
EXPECT_EQ(v_r(0), max);
EXPECT_EQ(v_r(1), 0);
// norm of v1 exceeds max but v0 is zero
v0.zero();
v_r = constrainXY(v0, v1, max);
EXPECT_EQ(v_r(1), -max);
EXPECT_EQ(v_r(0), 0);
v0 = Vector2f(0.5f, 0.5f);
v1 = Vector2f(0.5f, -0.5f);
v_r = constrainXY(v0, v1, max);
const float diff = Vector2f(v_r - (v0 + v1)).length();
EXPECT_EQ(diff, 0);
// v0 and v1 exceed max and are perpendicular
v0 = Vector2f(4.0f, 0.0f);
v1 = Vector2f(0.0f, -4.0f);
v_r = constrainXY(v0, v1, max);
EXPECT_EQ(v_r(0), v0(0));
EXPECT_GT(v_r(0), 0);
const float remaining = sqrtf(max * max - (v0(0) * v0(0)));
EXPECT_EQ(v_r(1), -remaining);
}
TEST(ControlMathTest, CrossSphereLine)
{
/* Testing 9 positions (+) around waypoints (o):
*
* Far + + +
*
* Near + + +
* On trajectory --+----o---------+---------o----+--
* prev curr
*
* Expected targets (1, 2, 3):
* Far + + +
*
*
* On trajectory -------1---------2---------3-------
*
*
* Near + + +
* On trajectory -------o---1---------2-----3-------
*
*
* On trajectory --+----o----1----+--------2/3---+-- */
const Vector3f prev = Vector3f(0.0f, 0.0f, 0.0f);
const Vector3f curr = Vector3f(0.0f, 0.0f, 2.0f);
Vector3f res;
bool retval = false;
// on line, near, before previous waypoint
retval = cross_sphere_line(Vector3f(0.0f, 0.0f, -0.5f), 1.0f, prev, curr, res);
EXPECT_TRUE(retval);
EXPECT_EQ(res, Vector3f(0.f, 0.f, 0.5f));
// on line, near, before target waypoint
retval = cross_sphere_line(Vector3f(0.0f, 0.0f, 1.0f), 1.0f, prev, curr, res);
EXPECT_TRUE(retval);
EXPECT_EQ(res, Vector3f(0.f, 0.f, 2.f));
// on line, near, after target waypoint
retval = cross_sphere_line(Vector3f(0.0f, 0.0f, 2.5f), 1.0f, prev, curr, res);
EXPECT_TRUE(retval);
EXPECT_EQ(res, Vector3f(0.f, 0.f, 2.f));
// near, before previous waypoint
retval = cross_sphere_line(Vector3f(0.0f, 0.5f, -0.5f), 1.0f, prev, curr, res);
EXPECT_TRUE(retval);
EXPECT_EQ(res, Vector3f(0.f, 0.f, 0.366025388f));
// near, before target waypoint
retval = cross_sphere_line(Vector3f(0.0f, 0.5f, 1.0f), 1.0f, prev, curr, res);
EXPECT_TRUE(retval);
EXPECT_EQ(res, Vector3f(0.f, 0.f, 1.866025448f));
// near, after target waypoint
retval = ControlMath::cross_sphere_line(matrix::Vector3f(0.0f, 0.5f, 2.5f), 1.0f, prev, curr, res);
EXPECT_TRUE(retval);
EXPECT_EQ(res, Vector3f(0.f, 0.f, 2.f));
// far, before previous waypoint
retval = ControlMath::cross_sphere_line(matrix::Vector3f(0.0f, 2.0f, -0.5f), 1.0f, prev, curr, res);
EXPECT_FALSE(retval);
EXPECT_EQ(res, Vector3f());
// far, before target waypoint
retval = ControlMath::cross_sphere_line(matrix::Vector3f(0.0f, 2.0f, 1.0f), 1.0f, prev, curr, res);
EXPECT_FALSE(retval);
EXPECT_EQ(res, Vector3f(0.f, 0.f, 1.f));
// far, after target waypoint
retval = ControlMath::cross_sphere_line(matrix::Vector3f(0.0f, 2.0f, 2.5f), 1.0f, prev, curr, res);
EXPECT_FALSE(retval);
EXPECT_EQ(res, Vector3f(0.f, 0.f, 2.f));
}
|
/****************************************************************************
*
* Copyright (C) 2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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 <gtest/gtest.h>
#include <ControlMath.hpp>
#include <px4_platform_common/defines.h>
using namespace matrix;
using namespace ControlMath;
TEST(ControlMathTest, ThrottleAttitudeMapping)
{
/* expected: zero roll, zero pitch, zero yaw, full thr mag
* reason: thrust pointing full upward */
Vector3f thr{0.0f, 0.0f, -1.0f};
float yaw = 0.0f;
vehicle_attitude_setpoint_s att{};
thrustToAttitude(thr, yaw, att);
EXPECT_FLOAT_EQ(att.roll_body, 0.0f);
EXPECT_FLOAT_EQ(att.pitch_body, 0.0f);
EXPECT_FLOAT_EQ(att.yaw_body, 0.0f);
EXPECT_FLOAT_EQ(att.thrust_body[2], -1.f);
/* expected: same as before but with 90 yaw
* reason: only yaw changed */
yaw = M_PI_2_F;
thrustToAttitude(thr, yaw, att);
EXPECT_FLOAT_EQ(att.roll_body, 0.0f);
EXPECT_FLOAT_EQ(att.pitch_body, 0.0f);
EXPECT_FLOAT_EQ(att.yaw_body, M_PI_2_F);
EXPECT_FLOAT_EQ(att.thrust_body[2], -1.f);
/* expected: same as before but roll 180
* reason: thrust points straight down and order Euler
* order is: 1. roll, 2. pitch, 3. yaw */
thr = Vector3f(0.0f, 0.0f, 1.0f);
thrustToAttitude(thr, yaw, att);
EXPECT_FLOAT_EQ(att.roll_body, -M_PI_F);
EXPECT_FLOAT_EQ(att.pitch_body, 0.0f);
EXPECT_FLOAT_EQ(att.yaw_body, M_PI_2_F);
EXPECT_FLOAT_EQ(att.thrust_body[2], -1.f);
}
TEST(ControlMathTest, ConstrainXYPriorities)
{
const float max = 5.0f;
// v0 already at max
Vector2f v0(max, 0);
Vector2f v1(v0(1), -v0(0));
Vector2f v_r = constrainXY(v0, v1, max);
EXPECT_FLOAT_EQ(v_r(0), max);
EXPECT_FLOAT_EQ(v_r(1), 0);
// norm of v1 exceeds max but v0 is zero
v0.zero();
v_r = constrainXY(v0, v1, max);
EXPECT_FLOAT_EQ(v_r(1), -max);
EXPECT_FLOAT_EQ(v_r(0), 0.0f);
v0 = Vector2f(0.5f, 0.5f);
v1 = Vector2f(0.5f, -0.5f);
v_r = constrainXY(v0, v1, max);
const float diff = Vector2f(v_r - (v0 + v1)).length();
EXPECT_FLOAT_EQ(diff, 0.0f);
// v0 and v1 exceed max and are perpendicular
v0 = Vector2f(4.0f, 0.0f);
v1 = Vector2f(0.0f, -4.0f);
v_r = constrainXY(v0, v1, max);
EXPECT_FLOAT_EQ(v_r(0), v0(0));
EXPECT_GT(v_r(0), 0);
const float remaining = sqrtf(max * max - (v0(0) * v0(0)));
EXPECT_FLOAT_EQ(v_r(1), -remaining);
}
TEST(ControlMathTest, CrossSphereLine)
{
/* Testing 9 positions (+) around waypoints (o):
*
* Far + + +
*
* Near + + +
* On trajectory --+----o---------+---------o----+--
* prev curr
*
* Expected targets (1, 2, 3):
* Far + + +
*
*
* On trajectory -------1---------2---------3-------
*
*
* Near + + +
* On trajectory -------o---1---------2-----3-------
*
*
* On trajectory --+----o----1----+--------2/3---+-- */
const Vector3f prev = Vector3f(0.0f, 0.0f, 0.0f);
const Vector3f curr = Vector3f(0.0f, 0.0f, 2.0f);
Vector3f res;
bool retval = false;
// on line, near, before previous waypoint
retval = cross_sphere_line(Vector3f(0.0f, 0.0f, -0.5f), 1.0f, prev, curr, res);
EXPECT_TRUE(retval);
EXPECT_TRUE(matrix::isEqual(res, Vector3f(0.f, 0.f, 0.5f)));
// on line, near, before target waypoint
retval = cross_sphere_line(Vector3f(0.0f, 0.0f, 1.0f), 1.0f, prev, curr, res);
EXPECT_TRUE(retval);
EXPECT_TRUE(matrix::isEqual(res, Vector3f(0.f, 0.f, 2.f)));
// on line, near, after target waypoint
retval = cross_sphere_line(Vector3f(0.0f, 0.0f, 2.5f), 1.0f, prev, curr, res);
EXPECT_TRUE(retval);
EXPECT_TRUE(matrix::isEqual(res, Vector3f(0.f, 0.f, 2.f)));
// near, before previous waypoint
retval = cross_sphere_line(Vector3f(0.0f, 0.5f, -0.5f), 1.0f, prev, curr, res);
EXPECT_TRUE(retval);
EXPECT_TRUE(matrix::isEqual(res, Vector3f(0.f, 0.f, 0.366025388f)));
// near, before target waypoint
retval = cross_sphere_line(Vector3f(0.0f, 0.5f, 1.0f), 1.0f, prev, curr, res);
EXPECT_TRUE(retval);
EXPECT_TRUE(matrix::isEqual(res, Vector3f(0.f, 0.f, 1.866025448f)));
// near, after target waypoint
retval = ControlMath::cross_sphere_line(matrix::Vector3f(0.0f, 0.5f, 2.5f), 1.0f, prev, curr, res);
EXPECT_TRUE(retval);
EXPECT_TRUE(matrix::isEqual(res, Vector3f(0.f, 0.f, 2.f)));
// far, before previous waypoint
retval = ControlMath::cross_sphere_line(matrix::Vector3f(0.0f, 2.0f, -0.5f), 1.0f, prev, curr, res);
EXPECT_FALSE(retval);
EXPECT_TRUE(matrix::isEqual(res, Vector3f()));
// far, before target waypoint
retval = ControlMath::cross_sphere_line(matrix::Vector3f(0.0f, 2.0f, 1.0f), 1.0f, prev, curr, res);
EXPECT_FALSE(retval);
EXPECT_TRUE(matrix::isEqual(res, Vector3f(0.f, 0.f, 1.f)));
// far, after target waypoint
retval = ControlMath::cross_sphere_line(matrix::Vector3f(0.0f, 2.0f, 2.5f), 1.0f, prev, curr, res);
EXPECT_FALSE(retval);
EXPECT_TRUE(matrix::isEqual(res, Vector3f(0.f, 0.f, 2.f)));
}
|
Fix float accuracy in ControlMathTest The test was testing the result of 3D float vector operations with binary equality of the floating point numbers, which is not a valid assumption to make for floating point math. This change switches to proper comparisons with float accuracy and compares vectors using the norm of their difference.
|
Fix float accuracy in ControlMathTest
The test was testing the result of 3D float vector operations with binary equality of the floating point numbers, which is not a valid assumption to make for floating point math. This change switches to proper comparisons with float accuracy and compares vectors using the norm of their difference.
|
C++
|
bsd-3-clause
|
krbeverx/Firmware,krbeverx/Firmware,acfloria/Firmware,acfloria/Firmware,PX4/Firmware,PX4/Firmware,krbeverx/Firmware,PX4/Firmware,krbeverx/Firmware,acfloria/Firmware,acfloria/Firmware,PX4/Firmware,PX4/Firmware,PX4/Firmware,PX4/Firmware,krbeverx/Firmware,krbeverx/Firmware,acfloria/Firmware,acfloria/Firmware,acfloria/Firmware,krbeverx/Firmware
|
1dece75d382ca8db267d68194ab9afaef032f17b
|
Modules/Segmentation/Rendering/mitkContourModelGLMapper2D.cpp
|
Modules/Segmentation/Rendering/mitkContourModelGLMapper2D.cpp
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkContourModelGLMapper2D.h"
#include "mitkBaseRenderer.h"
#include "mitkPlaneGeometry.h"
#include "mitkColorProperty.h"
#include "mitkProperties.h"
#include "mitkContourModel.h"
#include <vtkLinearTransform.h>
#include "mitkGL.h"
mitk::ContourModelGLMapper2D::ContourModelGLMapper2D()
{
}
mitk::ContourModelGLMapper2D::~ContourModelGLMapper2D()
{
}
void mitk::ContourModelGLMapper2D::Paint(mitk::BaseRenderer * renderer)
{
if(IsVisible(renderer)==false) return;
//// @FIXME: Logic for update
bool updateNeccesary=true;
mitk::ContourModel::Pointer input = const_cast<mitk::ContourModel*>(this->GetInput());
int timestep = renderer->GetTimeStep();
if(input->GetNumberOfVertices(timestep) < 1)
updateNeccesary = false;
if (updateNeccesary)
{
// ok, das ist aus GenerateData kopiert
mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry();
assert(displayGeometry.IsNotNull());
//apply color and opacity read from the PropertyList
ApplyProperties(renderer);
mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty*>(GetDataNode()->GetProperty("color", renderer));
if(colorprop)
{
//set the color of the contour
double red = colorprop->GetColor().GetRed();
double green = colorprop->GetColor().GetGreen();
double blue = colorprop->GetColor().GetBlue();
glColor4f(red,green,blue,0.5);
}
mitk::ColorProperty::Pointer selectedcolor = dynamic_cast<mitk::ColorProperty*>(GetDataNode()->GetProperty("selectedcolor", renderer));
if(!selectedcolor)
{
selectedcolor = mitk::ColorProperty::New(0.5,0.5,0.1);
}
vtkLinearTransform* transform = GetDataNode()->GetVtkTransform();
// ContourModel::OutputType point;
mitk::Point3D point;
mitk::Point3D p, projected_p;
float vtkp[3];
float lineWidth = 3.0;
if (dynamic_cast<mitk::FloatProperty *>(this->GetDataNode()->GetProperty("width")) != NULL)
lineWidth = dynamic_cast<mitk::FloatProperty*>(this->GetDataNode()->GetProperty("width"))->GetValue();
glLineWidth(lineWidth);
bool drawit=false;
mitk::ContourModel::VertexIterator pointsIt = input->IteratorBegin(timestep);
Point2D pt2d; // projected_p in display coordinates
Point2D lastPt2d;
while ( pointsIt != input->IteratorEnd(timestep) )
{
lastPt2d = pt2d;
point = (*pointsIt)->Coordinates;
itk2vtk(point, vtkp);
transform->TransformPoint(vtkp, vtkp);
vtk2itk(vtkp,p);
displayGeometry->Project(p, projected_p);
displayGeometry->Map(projected_p, pt2d);
displayGeometry->WorldToDisplay(pt2d, pt2d);
Vector3D diff=p-projected_p;
ScalarType scalardiff = diff.GetSquaredNorm();
//draw lines
bool projectmode=false;
GetDataNode()->GetVisibility(projectmode, renderer, "project");
if(projectmode)
drawit=true;
else
{
if(diff.GetSquaredNorm()<0.5)
drawit=true;
}
if(drawit)
{
//lastPt2d is not valid in first step
if( !(pointsIt == input->IteratorBegin(timestep)) )
{
glBegin (GL_LINES);
glVertex2f(pt2d[0], pt2d[1]);
glVertex2f(lastPt2d[0], lastPt2d[1]);
glEnd();
}
//draw active points
if ((*pointsIt)->IsActive)
{
float pointsize = 4;
Point2D tmp;
Vector2D horz,vert;
horz[0]=pointsize-scalardiff*2; horz[1]=0;
vert[0]=0; vert[1]=pointsize-scalardiff*2;
horz[0]=pointsize;
vert[1]=pointsize;
glColor3f(selectedcolor->GetColor().GetRed(), selectedcolor->GetColor().GetBlue(), selectedcolor->GetColor().GetGreen());
glLineWidth(1);
//a diamond around the point with the selected color
glBegin (GL_LINE_LOOP);
tmp=pt2d-horz; glVertex2fv(&tmp[0]);
tmp=pt2d+vert; glVertex2fv(&tmp[0]);
tmp=pt2d+horz; glVertex2fv(&tmp[0]);
tmp=pt2d-vert; glVertex2fv(&tmp[0]);
glEnd ();
glLineWidth(1);
//the actual point in the specified color to see the usual color of the point
glColor3f(colorprop->GetColor().GetRed(),colorprop->GetColor().GetGreen(),colorprop->GetColor().GetBlue());
glPointSize(1);
glBegin (GL_POINTS);
tmp=pt2d; glVertex2fv(&tmp[0]);
glEnd ();
}
}
pointsIt++;
}//end while iterate over controlpoints
//close contour if necessary
if(input->IsClosed(timestep) && drawit)
{
lastPt2d = pt2d;
point = input->GetVertexAt(0,timestep)->Coordinates;
itk2vtk(point, vtkp);
transform->TransformPoint(vtkp, vtkp);
vtk2itk(vtkp,p);
displayGeometry->Project(p, projected_p);
displayGeometry->Map(projected_p, pt2d);
displayGeometry->WorldToDisplay(pt2d, pt2d);
glBegin (GL_LINES);
glVertex2f(lastPt2d[0], lastPt2d[1]);
glVertex2f( pt2d[0], pt2d[1] );
glEnd();
}
}
}
const mitk::ContourModel* mitk::ContourModelGLMapper2D::GetInput(void)
{
return static_cast<const mitk::ContourModel * > ( GetData() );
}
void mitk::ContourModelGLMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{
node->AddProperty( "color", ColorProperty::New(0.9, 1.0, 0.1), renderer, overwrite );
node->AddProperty( "selectedcolor", ColorProperty::New(0.5, 0.5, 0.1), renderer, overwrite );
node->AddProperty( "width", mitk::FloatProperty::New( 1.0 ), renderer, overwrite );
node->AddProperty( "use cutting plane", mitk::BoolProperty::New( true ), renderer, overwrite );
node->AddProperty( "subdivision curve", mitk::BoolProperty::New( false ), renderer, overwrite );
Superclass::SetDefaultProperties(node, renderer, overwrite);
}
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkContourModelGLMapper2D.h"
#include "mitkBaseRenderer.h"
#include "mitkPlaneGeometry.h"
#include "mitkColorProperty.h"
#include "mitkProperties.h"
#include "mitkContourModel.h"
#include <vtkLinearTransform.h>
#include "mitkGL.h"
mitk::ContourModelGLMapper2D::ContourModelGLMapper2D()
{
}
mitk::ContourModelGLMapper2D::~ContourModelGLMapper2D()
{
}
void mitk::ContourModelGLMapper2D::Paint(mitk::BaseRenderer * renderer)
{
if(IsVisible(renderer)==false) return;
bool updateNeccesary=true;
int timestep = renderer->GetTimeStep();
mitk::ContourModel::Pointer input = const_cast<mitk::ContourModel*>(this->GetInput());
input->UpdateOutputInformation();
if( input->GetMTime() < this->m_LastUpdateTime )
updateNeccesary = false;
if(input->GetNumberOfVertices(timestep) < 1)
updateNeccesary = false;
if (updateNeccesary)
{
// ok, das ist aus GenerateData kopiert
mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry();
assert(displayGeometry.IsNotNull());
//apply color and opacity read from the PropertyList
ApplyProperties(renderer);
mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty*>(GetDataNode()->GetProperty("color", renderer));
if(colorprop)
{
//set the color of the contour
double red = colorprop->GetColor().GetRed();
double green = colorprop->GetColor().GetGreen();
double blue = colorprop->GetColor().GetBlue();
glColor4f(red,green,blue,0.5);
}
mitk::ColorProperty::Pointer selectedcolor = dynamic_cast<mitk::ColorProperty*>(GetDataNode()->GetProperty("selectedcolor", renderer));
if(!selectedcolor)
{
selectedcolor = mitk::ColorProperty::New(0.5,0.5,0.1);
}
vtkLinearTransform* transform = GetDataNode()->GetVtkTransform();
// ContourModel::OutputType point;
mitk::Point3D point;
mitk::Point3D p, projected_p;
float vtkp[3];
float lineWidth = 3.0;
if (dynamic_cast<mitk::FloatProperty *>(this->GetDataNode()->GetProperty("width")) != NULL)
lineWidth = dynamic_cast<mitk::FloatProperty*>(this->GetDataNode()->GetProperty("width"))->GetValue();
glLineWidth(lineWidth);
bool drawit=false;
mitk::ContourModel::VertexIterator pointsIt = input->IteratorBegin(timestep);
Point2D pt2d; // projected_p in display coordinates
Point2D lastPt2d;
while ( pointsIt != input->IteratorEnd(timestep) )
{
lastPt2d = pt2d;
point = (*pointsIt)->Coordinates;
itk2vtk(point, vtkp);
transform->TransformPoint(vtkp, vtkp);
vtk2itk(vtkp,p);
displayGeometry->Project(p, projected_p);
displayGeometry->Map(projected_p, pt2d);
displayGeometry->WorldToDisplay(pt2d, pt2d);
Vector3D diff=p-projected_p;
ScalarType scalardiff = diff.GetSquaredNorm();
//draw lines
bool projectmode=false;
GetDataNode()->GetVisibility(projectmode, renderer, "project");
if(projectmode)
drawit=true;
else
{
if(diff.GetSquaredNorm()<0.5)
drawit=true;
}
if(drawit)
{
//lastPt2d is not valid in first step
if( !(pointsIt == input->IteratorBegin(timestep)) )
{
glBegin (GL_LINES);
glVertex2f(pt2d[0], pt2d[1]);
glVertex2f(lastPt2d[0], lastPt2d[1]);
glEnd();
}
//draw active points
if ((*pointsIt)->IsActive)
{
float pointsize = 4;
Point2D tmp;
Vector2D horz,vert;
horz[0]=pointsize-scalardiff*2; horz[1]=0;
vert[0]=0; vert[1]=pointsize-scalardiff*2;
horz[0]=pointsize;
vert[1]=pointsize;
glColor3f(selectedcolor->GetColor().GetRed(), selectedcolor->GetColor().GetBlue(), selectedcolor->GetColor().GetGreen());
glLineWidth(1);
//a diamond around the point with the selected color
glBegin (GL_LINE_LOOP);
tmp=pt2d-horz; glVertex2fv(&tmp[0]);
tmp=pt2d+vert; glVertex2fv(&tmp[0]);
tmp=pt2d+horz; glVertex2fv(&tmp[0]);
tmp=pt2d-vert; glVertex2fv(&tmp[0]);
glEnd ();
glLineWidth(1);
//the actual point in the specified color to see the usual color of the point
glColor3f(colorprop->GetColor().GetRed(),colorprop->GetColor().GetGreen(),colorprop->GetColor().GetBlue());
glPointSize(1);
glBegin (GL_POINTS);
tmp=pt2d; glVertex2fv(&tmp[0]);
glEnd ();
}
}
pointsIt++;
}//end while iterate over controlpoints
//close contour if necessary
if(input->IsClosed(timestep) && drawit)
{
lastPt2d = pt2d;
point = input->GetVertexAt(0,timestep)->Coordinates;
itk2vtk(point, vtkp);
transform->TransformPoint(vtkp, vtkp);
vtk2itk(vtkp,p);
displayGeometry->Project(p, projected_p);
displayGeometry->Map(projected_p, pt2d);
displayGeometry->WorldToDisplay(pt2d, pt2d);
glBegin (GL_LINES);
glVertex2f(lastPt2d[0], lastPt2d[1]);
glVertex2f( pt2d[0], pt2d[1] );
glEnd();
}
}
}
const mitk::ContourModel* mitk::ContourModelGLMapper2D::GetInput(void)
{
return static_cast<const mitk::ContourModel * > ( GetData() );
}
void mitk::ContourModelGLMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{
node->AddProperty( "color", ColorProperty::New(0.9, 1.0, 0.1), renderer, overwrite );
node->AddProperty( "selectedcolor", ColorProperty::New(0.5, 0.5, 0.1), renderer, overwrite );
node->AddProperty( "width", mitk::FloatProperty::New( 1.0 ), renderer, overwrite );
node->AddProperty( "use cutting plane", mitk::BoolProperty::New( true ), renderer, overwrite );
node->AddProperty( "subdivision curve", mitk::BoolProperty::New( false ), renderer, overwrite );
Superclass::SetDefaultProperties(node, renderer, overwrite);
}
|
check for update
|
check for update
|
C++
|
bsd-3-clause
|
iwegner/MITK,danielknorr/MITK,lsanzdiaz/MITK-BiiG,fmilano/mitk,fmilano/mitk,danielknorr/MITK,lsanzdiaz/MITK-BiiG,fmilano/mitk,fmilano/mitk,iwegner/MITK,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,fmilano/mitk,RabadanLab/MITKats,MITK/MITK,rfloca/MITK,NifTK/MITK,rfloca/MITK,fmilano/mitk,danielknorr/MITK,MITK/MITK,MITK/MITK,RabadanLab/MITKats,NifTK/MITK,MITK/MITK,RabadanLab/MITKats,danielknorr/MITK,nocnokneo/MITK,iwegner/MITK,danielknorr/MITK,rfloca/MITK,RabadanLab/MITKats,fmilano/mitk,iwegner/MITK,danielknorr/MITK,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,rfloca/MITK,rfloca/MITK,nocnokneo/MITK,RabadanLab/MITKats,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,NifTK/MITK,NifTK/MITK,nocnokneo/MITK,iwegner/MITK,MITK/MITK,NifTK/MITK,NifTK/MITK,rfloca/MITK,MITK/MITK,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,danielknorr/MITK,iwegner/MITK,nocnokneo/MITK,rfloca/MITK
|
ef442ceec96e2b4ed69315ce6fb531f23273e808
|
src/cpp/session/include/session/SessionScopes.hpp
|
src/cpp/session/include/session/SessionScopes.hpp
|
/*
* SessionScopes.hpp
*
* Copyright (C) 2009-2015 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
// Everything is defined inine here so we can share code between
// rsession and rworkspace without linking
#ifndef SESSION_SCOPES_HPP
#define SESSION_SCOPES_HPP
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/range/adaptor/map.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/StringUtils.hpp>
#include <core/system/System.hpp>
#include <core/json/Json.hpp>
#include <core/json/JsonRpc.hpp>
#ifndef _WIN32
#include <core/system/FileMode.hpp>
#include <sys/stat.h>
#endif
#include <core/r_util/RSessionContext.hpp>
#include <session/projects/ProjectsSettings.hpp>
#include <session/projects/SessionProjectSharing.hpp>
namespace rstudio {
namespace session {
namespace {
inline core::FilePath projectIdsFilePath(const core::FilePath& userScratchPath)
{
core::FilePath filePath = userScratchPath.childPath(
kProjectsSettings "/project-id-mappings");
core::Error error = filePath.parent().ensureDirectory();
if (error)
LOG_ERROR(error);
return filePath;
}
inline std::map<std::string,std::string> projectIdsMap(
const core::FilePath& projectIdsPath)
{
std::map<std::string,std::string> idMap;
if (projectIdsPath.exists())
{
core::Error error = core::readStringMapFromFile(projectIdsPath, &idMap);
if (error)
LOG_ERROR(error);
}
// somewhere in our system we've had .Rproj files get injected into
// the project ids map -- we need to fix this up here
size_t previousMapSize = idMap.size();
for (std::map<std::string,std::string>::iterator
it = idMap.begin(); it != idMap.end();)
{
if (boost::algorithm::iends_with(it->second, ".Rproj"))
idMap.erase(it++);
else
++it;
}
// persist if we made any changes
if (idMap.size() != previousMapSize)
{
core::Error error = core::writeStringMapToFile(projectIdsPath, idMap);
if (error)
LOG_ERROR(error);
}
return idMap;
}
inline core::Error projectPathFromEntry(const core::FilePath& projectEntry,
std::string* pPath)
{
// get the path from shared storage
std::string entryContents;
core::Error error = core::readStringFromFile(projectEntry,
&entryContents);
if (error)
return error;
// read the contents
core::json::Value projectEntryVal;
if (!core::json::parse(entryContents, &projectEntryVal))
{
error = core::Error(core::json::errc::ParseError,
ERROR_LOCATION);
error.addProperty("path", projectEntry.absolutePath());
return error;
}
// extract the path
std::string projectPath;
if (projectEntryVal.type() == core::json::ObjectType)
{
core::json::Object obj = projectEntryVal.get_obj();
core::json::Object::iterator it = obj.find(kProjectEntryDir);
if (it != obj.end() && it->second.type() == core::json::StringType)
{
projectPath = it->second.get_str();
}
}
// ensure we got a path from the shared project data
if (projectPath.empty())
{
error = core::systemError(boost::system::errc::invalid_argument,
"No project directory found in " kProjectEntryDir,
ERROR_LOCATION);
error.addProperty("path", projectEntry.absolutePath());
return error;
}
*pPath = projectPath;
return core::Success();
}
inline std::string toFilePath(const core::r_util::ProjectId& projectId,
const core::FilePath& userScratchPath,
const core::FilePath& sharedStoragePath)
{
// try the map first; it contains both our own projects and shared projects
// that we've opened
core::FilePath projectIdsPath = projectIdsFilePath(userScratchPath);
std::map<std::string,std::string> idMap = projectIdsMap(projectIdsPath);
std::map<std::string,std::string>::iterator it;
// see if the project came from another user
bool fromOtherUser = !projectId.userId().empty() &&
projectId.userId() != core::r_util::obfuscatedUserId(::geteuid());
// if it did, use the fully qualified name; otherwise, use just the project
// ID (our own projects are stored unqualified in the map)
if (fromOtherUser)
it = idMap.find(projectId.asString());
else
it = idMap.find(projectId.id());
if (it != idMap.end())
{
// we found it!
return it->second;
}
else if (fromOtherUser)
{
// this project does not belong to us; see if it has an entry in shared
// storage
core::FilePath projectEntryPath =
sharedStoragePath.complete(kProjectSharedDir)
.complete(projectId.asString() + kProjectEntryExt);
if (projectEntryPath.exists())
{
// extract the path from the entry
std::string projectPath;
core::Error error = projectPathFromEntry(projectEntryPath,
&projectPath);
if (error)
{
LOG_ERROR(error);
return "";
}
// save the path to our own mapping so we can reverse lookup later
core::FilePath projectIdsPath = projectIdsFilePath(userScratchPath);
std::map<std::string,std::string> idMap = projectIdsMap(projectIdsPath);
idMap[projectId.asString()] = projectPath;
error = core::writeStringMapToFile(projectIdsPath, idMap);
if (error)
LOG_ERROR(error);
// return the path
return projectPath;
}
}
return "";
}
#ifndef _WIN32
inline std::string sharedProjectId(const core::FilePath& sharedStoragePath,
const std::string& projectDir)
{
// enumerate the project entries in shared storage (this should succeed)
std::vector<core::FilePath> projectEntries;
core::Error error = sharedStoragePath.complete(kProjectSharedDir)
.children(&projectEntries);
if (error)
{
LOG_ERROR(error);
return "";
}
BOOST_FOREACH(const core::FilePath& projectEntry, projectEntries)
{
// skip files that don't look like project entries
if (projectEntry.extensionLowerCase() != kProjectEntryExt)
continue;
std::string projectPath;
error = projectPathFromEntry(projectEntry, &projectPath);
if (error)
{
// this is very much expected (we aren't going to be able to examine
// the contents of most project entries)
continue;
}
else if (projectDir == projectPath)
{
return projectEntry.stem();
}
}
return "";
}
#endif
inline core::r_util::ProjectId toProjectId(const std::string& projectDir,
const core::FilePath& userScratchPath,
const core::FilePath& sharedStoragePath)
{
// warn if this is a project file
if (boost::algorithm::iends_with(projectDir, ".Rproj"))
LOG_WARNING_MESSAGE("Project file path not directory: " + projectDir);
// get the id map
core::FilePath projectIdsPath = projectIdsFilePath(userScratchPath);
std::map<std::string,std::string> idMap = projectIdsMap(projectIdsPath);
std::string id;
// look for this value
std::map<std::string,std::string>::iterator it;
for (it = idMap.begin(); it != idMap.end(); it++)
{
if (it->second == projectDir)
{
id = it->first;
// if this ID includes both project and user information, we can
// return it immediately
if (id.length() == kUserIdLen + kProjectIdLen)
return core::r_util::ProjectId(id);
break;
}
}
// if this project belongs to someone else, try to look up its shared
// project ID (we currently have to do this even if we found the ID in the
// map; see note below)
#ifndef _WIN32
struct stat st;
if (::stat(projectDir.c_str(), &st) == 0 &&
st.st_uid != ::geteuid())
{
// if we already found an ID but it doesn't contain any user information
// (just a raw project ID), we need to do some fixup
if (id.length() == kProjectIdLen)
{
// TODO: The following code is temporary. There was a period of time
// during which it was possible to get your own project ID for a
// project that did not belong to you.
//
// This is no longer possible, but mismatched project IDs cause
// features such as distributed events to fail, and the project IDs
// are cached in the mapping file, so until all the per-user IDs are
// flushed and replaced with shared IDs, we need to leave this in; it
// causes us to erase the per-user ID so it's replaced with a shared
// ID.
idMap.erase(it);
it = idMap.end();
}
id = sharedProjectId(sharedStoragePath, projectDir);
}
#endif
// if we found a cached ID, return it now
if (it != idMap.end() && !id.empty())
{
return core::r_util::ProjectId(id);
}
// if we didn't find it, and we don't already have an ID, then we need to
// generate a new one (loop until we find one that isn't already in the map)
while (id.empty())
{
std::string candidateId = core::r_util::generateScopeId();
if (idMap.find(candidateId) == idMap.end())
id = candidateId;
}
// add it to the map then save the map
idMap[id] = projectDir;
core::Error error = core::writeStringMapToFile(projectIdsPath, idMap);
if (error)
LOG_ERROR(error);
// ensure the file has restrictive permissions
#ifndef _WIN32
error = core::system::changeFileMode(projectIdsPath,
core::system::UserReadWriteMode);
if (error)
LOG_ERROR(error);
#endif
// return the id
return core::r_util::ProjectId(id);
}
} // anonymous namespace
inline core::r_util::ProjectIdToFilePath projectIdToFilePath(
const core::FilePath& userScratchPath,
const core::FilePath& sharedProjectPath)
{
return boost::bind(toFilePath, _1, userScratchPath, sharedProjectPath);
}
inline core::r_util::FilePathToProjectId filePathToProjectId(
const core::FilePath& userScratchPath,
const core::FilePath& sharedStoragePath)
{
return boost::bind(toProjectId, _1, userScratchPath, sharedStoragePath);
}
inline core::r_util::ProjectId projectToProjectId(
const core::FilePath& userScratchPath,
const core::FilePath& sharedStoragePath,
const std::string& project)
{
if (project == kProjectNone)
return core::r_util::ProjectId(kProjectNoneId);
else
return session::filePathToProjectId(userScratchPath, sharedStoragePath)
(project);
}
inline std::string projectIdToProject(
const core::FilePath& userScratchPath,
const core::FilePath& sharedStoragePath,
const core::r_util::ProjectId& projectId)
{
if (projectId.id() == kProjectNone)
return kProjectNone;
else
return session::projectIdToFilePath(userScratchPath, sharedStoragePath)
(projectId);
}
} // namespace session
} // namespace rstudio
#endif /* SESSION_SCOPES_HPP */
|
/*
* SessionScopes.hpp
*
* Copyright (C) 2009-2015 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
// Everything is defined inine here so we can share code between
// rsession and rworkspace without linking
#ifndef SESSION_SCOPES_HPP
#define SESSION_SCOPES_HPP
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/range/adaptor/map.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/StringUtils.hpp>
#include <core/system/System.hpp>
#include <core/json/Json.hpp>
#include <core/json/JsonRpc.hpp>
#ifndef _WIN32
#include <core/system/FileMode.hpp>
#include <sys/stat.h>
#endif
#include <core/r_util/RSessionContext.hpp>
#include <session/projects/ProjectsSettings.hpp>
#include <session/projects/SessionProjectSharing.hpp>
namespace rstudio {
namespace session {
namespace {
inline core::FilePath projectIdsFilePath(const core::FilePath& userScratchPath)
{
core::FilePath filePath = userScratchPath.childPath(
kProjectsSettings "/project-id-mappings");
core::Error error = filePath.parent().ensureDirectory();
if (error)
LOG_ERROR(error);
return filePath;
}
inline std::map<std::string,std::string> projectIdsMap(
const core::FilePath& projectIdsPath)
{
std::map<std::string,std::string> idMap;
if (projectIdsPath.exists())
{
core::Error error = core::readStringMapFromFile(projectIdsPath, &idMap);
if (error)
LOG_ERROR(error);
}
// somewhere in our system we've had .Rproj files get injected into
// the project ids map -- we need to fix this up here
size_t previousMapSize = idMap.size();
for (std::map<std::string,std::string>::iterator
it = idMap.begin(); it != idMap.end();)
{
if (boost::algorithm::iends_with(it->second, ".Rproj"))
idMap.erase(it++);
else
++it;
}
// persist if we made any changes
if (idMap.size() != previousMapSize)
{
core::Error error = core::writeStringMapToFile(projectIdsPath, idMap);
if (error)
LOG_ERROR(error);
}
return idMap;
}
inline core::Error projectPathFromEntry(const core::FilePath& projectEntry,
std::string* pPath)
{
// get the path from shared storage
std::string entryContents;
core::Error error = core::readStringFromFile(projectEntry,
&entryContents);
if (error)
return error;
// read the contents
core::json::Value projectEntryVal;
if (!core::json::parse(entryContents, &projectEntryVal))
{
error = core::Error(core::json::errc::ParseError,
ERROR_LOCATION);
error.addProperty("path", projectEntry.absolutePath());
return error;
}
// extract the path
std::string projectPath;
if (projectEntryVal.type() == core::json::ObjectType)
{
core::json::Object obj = projectEntryVal.get_obj();
core::json::Object::iterator it = obj.find(kProjectEntryDir);
if (it != obj.end() && it->second.type() == core::json::StringType)
{
projectPath = it->second.get_str();
}
}
// ensure we got a path from the shared project data
if (projectPath.empty())
{
error = core::systemError(boost::system::errc::invalid_argument,
"No project directory found in " kProjectEntryDir,
ERROR_LOCATION);
error.addProperty("path", projectEntry.absolutePath());
return error;
}
*pPath = projectPath;
return core::Success();
}
inline std::string toFilePath(const core::r_util::ProjectId& projectId,
const core::FilePath& userScratchPath,
const core::FilePath& sharedStoragePath)
{
// try the map first; it contains both our own projects and shared projects
// that we've opened
core::FilePath projectIdsPath = projectIdsFilePath(userScratchPath);
std::map<std::string,std::string> idMap = projectIdsMap(projectIdsPath);
std::map<std::string,std::string>::iterator it;
// see if the project came from another user
bool fromOtherUser = !projectId.userId().empty() &&
projectId.userId() != core::r_util::obfuscatedUserId(::geteuid());
// if it did, use the fully qualified name; otherwise, use just the project
// ID (our own projects are stored unqualified in the map)
if (fromOtherUser)
it = idMap.find(projectId.asString());
else
it = idMap.find(projectId.id());
if (it != idMap.end())
{
// we found it!
return it->second;
}
else if (fromOtherUser)
{
// this project does not belong to us; see if it has an entry in shared
// storage
core::FilePath projectEntryPath =
sharedStoragePath.complete(kProjectSharedDir)
.complete(projectId.asString() + kProjectEntryExt);
if (projectEntryPath.exists())
{
// extract the path from the entry
std::string projectPath;
core::Error error = projectPathFromEntry(projectEntryPath,
&projectPath);
if (error)
{
LOG_ERROR(error);
return "";
}
// save the path to our own mapping so we can reverse lookup later
core::FilePath projectIdsPath = projectIdsFilePath(userScratchPath);
std::map<std::string,std::string> idMap = projectIdsMap(projectIdsPath);
idMap[projectId.asString()] = projectPath;
error = core::writeStringMapToFile(projectIdsPath, idMap);
if (error)
LOG_ERROR(error);
// return the path
return projectPath;
}
}
return "";
}
#ifndef _WIN32
inline std::string sharedProjectId(const core::FilePath& sharedStoragePath,
const std::string& projectDir)
{
// enumerate the project entries in shared storage (this should succeed)
std::vector<core::FilePath> projectEntries;
core::Error error = sharedStoragePath.complete(kProjectSharedDir)
.children(&projectEntries);
if (error)
{
LOG_ERROR(error);
return "";
}
BOOST_FOREACH(const core::FilePath& projectEntry, projectEntries)
{
// skip files that don't look like project entries
if (projectEntry.extensionLowerCase() != kProjectEntryExt)
continue;
std::string projectPath;
error = projectPathFromEntry(projectEntry, &projectPath);
if (error)
{
// this is very much expected (we aren't going to be able to examine
// the contents of most project entries)
continue;
}
else if (projectDir == projectPath)
{
return projectEntry.stem();
}
}
return "";
}
#endif
inline core::r_util::ProjectId toProjectId(const std::string& projectDir,
const core::FilePath& userScratchPath,
const core::FilePath& sharedStoragePath)
{
// warn if this is a project file
if (boost::algorithm::iends_with(projectDir, ".Rproj"))
LOG_WARNING_MESSAGE("Project file path not directory: " + projectDir);
// get the id map
core::FilePath projectIdsPath = projectIdsFilePath(userScratchPath);
std::map<std::string,std::string> idMap = projectIdsMap(projectIdsPath);
std::string id;
// look for this value
std::map<std::string,std::string>::iterator it;
for (it = idMap.begin(); it != idMap.end(); it++)
{
if (it->second == projectDir)
{
id = it->first;
// if this ID includes both project and user information, we can
// return it immediately
if (id.length() == kUserIdLen + kProjectIdLen)
return core::r_util::ProjectId(id);
break;
}
}
#ifndef _WIN32
// if we don't have a user ID as part of the project ID, there may be
// more work to do
if (id.length() == kProjectIdLen)
{
// if this project belongs to someone else, try to look up its shared
// project ID
struct stat st;
if (::stat(projectDir.c_str(), &st) == 0 &&
st.st_uid != ::geteuid())
{
// fix it up to a shared project ID if we have one. this could happen
// if e.g. a project is opened as an unshared project and later opened
// as a shared one.
std::string sharedId = sharedProjectId(sharedStoragePath, projectDir);
if (!sharedId.empty())
{
idMap.erase(it);
it = idMap.end();
id = sharedId;
}
}
}
#endif
// if we found a cached ID, return it now
if (it != idMap.end() && !id.empty())
{
return core::r_util::ProjectId(id);
}
// if we didn't find it, and we don't already have an ID, then we need to
// generate a new one (loop until we find one that isn't already in the map)
while (id.empty())
{
std::string candidateId = core::r_util::generateScopeId();
if (idMap.find(candidateId) == idMap.end())
id = candidateId;
}
// add it to the map then save the map
idMap[id] = projectDir;
core::Error error = core::writeStringMapToFile(projectIdsPath, idMap);
if (error)
LOG_ERROR(error);
// ensure the file has restrictive permissions
#ifndef _WIN32
error = core::system::changeFileMode(projectIdsPath,
core::system::UserReadWriteMode);
if (error)
LOG_ERROR(error);
#endif
// return the id
return core::r_util::ProjectId(id);
}
} // anonymous namespace
inline core::r_util::ProjectIdToFilePath projectIdToFilePath(
const core::FilePath& userScratchPath,
const core::FilePath& sharedProjectPath)
{
return boost::bind(toFilePath, _1, userScratchPath, sharedProjectPath);
}
inline core::r_util::FilePathToProjectId filePathToProjectId(
const core::FilePath& userScratchPath,
const core::FilePath& sharedStoragePath)
{
return boost::bind(toProjectId, _1, userScratchPath, sharedStoragePath);
}
inline core::r_util::ProjectId projectToProjectId(
const core::FilePath& userScratchPath,
const core::FilePath& sharedStoragePath,
const std::string& project)
{
if (project == kProjectNone)
return core::r_util::ProjectId(kProjectNoneId);
else
return session::filePathToProjectId(userScratchPath, sharedStoragePath)
(project);
}
inline std::string projectIdToProject(
const core::FilePath& userScratchPath,
const core::FilePath& sharedStoragePath,
const core::r_util::ProjectId& projectId)
{
if (projectId.id() == kProjectNone)
return kProjectNone;
else
return session::projectIdToFilePath(userScratchPath, sharedStoragePath)
(projectId);
}
} // namespace session
} // namespace rstudio
#endif /* SESSION_SCOPES_HPP */
|
fix 'project not found' issue with other users' unshared projects
|
fix 'project not found' issue with other users' unshared projects
|
C++
|
agpl-3.0
|
jar1karp/rstudio,JanMarvin/rstudio,jrnold/rstudio,jrnold/rstudio,jar1karp/rstudio,jar1karp/rstudio,JanMarvin/rstudio,jar1karp/rstudio,jar1karp/rstudio,JanMarvin/rstudio,jrnold/rstudio,JanMarvin/rstudio,jar1karp/rstudio,jar1karp/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,jrnold/rstudio,jrnold/rstudio,jrnold/rstudio,jrnold/rstudio,jrnold/rstudio,jar1karp/rstudio,JanMarvin/rstudio,jar1karp/rstudio,jrnold/rstudio,JanMarvin/rstudio,JanMarvin/rstudio
|
a7249bfe5d2348e5c273905e0030fb6c3fd3ee94
|
Dev/Cpp/Viewer/Graphics/Platform/DX11/efk.PostEffectsDX11.cpp
|
Dev/Cpp/Viewer/Graphics/Platform/DX11/efk.PostEffectsDX11.cpp
|
#if _WIN32
#define NOMINMAX
#endif
#include <algorithm>
#include "efk.PostEffectsDX11.h"
namespace efk
{
namespace PostFX_Basic_VS
{
static
#include "Shader/efk.GraphicsDX11.PostFX_Basic_VS.h"
}
namespace PostFX_Copy_PS
{
static
#include "Shader/efk.GraphicsDX11.PostFX_Copy_PS.h"
}
namespace PostFX_Extract_PS
{
static
#include "Shader/efk.GraphicsDX11.PostFX_Extract_PS.h"
}
namespace PostFX_Downsample_PS
{
static
#include "Shader/efk.GraphicsDX11.PostFX_Downsample_PS.h"
}
namespace PostFX_Blend_PS
{
static
#include "Shader/efk.GraphicsDX11.PostFX_Blend_PS.h"
}
namespace PostFX_BlurH_PS
{
static
#include "Shader/efk.GraphicsDX11.PostFX_BlurH_PS.h"
}
namespace PostFX_BlurV_PS
{
static
#include "Shader/efk.GraphicsDX11.PostFX_BlurV_PS.h"
}
namespace PostFX_Tonemap_PS
{
static
#include "Shader/efk.GraphicsDX11.PostFX_Tonemap_PS.h"
}
// Position(2) UV(2)
static const D3D11_INPUT_ELEMENT_DESC PostFx_ShaderDecl[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
BlitterDX11::BlitterDX11(Graphics* graphics)
: graphics(graphics)
{
using namespace Effekseer;
using namespace EffekseerRendererDX11;
auto renderer = (RendererImplemented*)graphics->GetRenderer();
// Generate vertex data
vertexBuffer.reset(VertexBuffer::Create(renderer,
sizeof(Vertex) * 4, true));
vertexBuffer->Lock(); {
Vertex* verteces = (Vertex*)vertexBuffer->GetBufferDirect(sizeof(Vertex) * 4);
verteces[0] = Vertex{-1.0f, 1.0f, 0.0f, 0.0f};
verteces[1] = Vertex{-1.0f, -1.0f, 0.0f, 1.0f};
verteces[2] = Vertex{ 1.0f, 1.0f, 1.0f, 0.0f};
verteces[3] = Vertex{ 1.0f, -1.0f, 1.0f, 1.0f};
}
vertexBuffer->Unlock();
// Generate Sampler State
{
const D3D11_SAMPLER_DESC SamlerDesc = {
D3D11_FILTER_MIN_MAG_MIP_LINEAR,
D3D11_TEXTURE_ADDRESS_CLAMP,
D3D11_TEXTURE_ADDRESS_CLAMP,
D3D11_TEXTURE_ADDRESS_CLAMP,
0.0f,
0,
D3D11_COMPARISON_ALWAYS,
{ 0.0f, 0.0f, 0.0f, 0.0f },
0.0f,
D3D11_FLOAT32_MAX, };
renderer->GetDevice()->CreateSamplerState( &SamlerDesc, &sampler );
}
}
BlitterDX11::~BlitterDX11()
{
ES_SAFE_RELEASE( sampler );
}
void BlitterDX11::Blit(EffekseerRendererDX11::Shader* shader,
int32_t numTextures, ID3D11ShaderResourceView* const* textures,
const void* constantData, size_t constantDataSize, RenderTexture* dest,
Effekseer::AlphaBlendType blendType)
{
using namespace Effekseer;
using namespace EffekseerRendererDX11;
auto renderer = (RendererImplemented*)graphics->GetRenderer();
auto& state = renderer->GetRenderState()->Push();
state.AlphaBlend = blendType;
state.DepthWrite = false;
state.DepthTest = false;
state.CullingType = CullingType::Double;
state.TextureFilterTypes[0] = TextureFilterType::Linear;
state.TextureWrapTypes[0] = TextureWrapType::Clamp;
renderer->GetRenderState()->Update(false);
renderer->SetRenderMode(RenderMode::Normal);
renderer->SetVertexBuffer(vertexBuffer.get(), sizeof(Vertex));
renderer->GetContext()->IASetIndexBuffer(nullptr, DXGI_FORMAT_R16_UINT, 0);
renderer->GetContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
renderer->GetContext()->PSSetSamplers(0, 1, &sampler);
renderer->BeginShader(shader);
renderer->GetContext()->IASetInputLayout(shader->GetLayoutInterface());
if (constantData)
{
memcpy(shader->GetPixelConstantBuffer(), constantData, constantDataSize);
shader->SetConstantBuffer();
}
graphics->SetRenderTarget(dest, nullptr);
renderer->GetContext()->PSSetShaderResources(0, numTextures, textures);
renderer->GetContext()->Draw(4, 0);
renderer->EndShader(shader);
// Reset texture/sampler state
{
ID3D11ShaderResourceView* srv[4] = {};
renderer->GetContext()->PSSetShaderResources(0, 4, srv);
ID3D11SamplerState* samplers[1] = {};
renderer->GetContext()->PSSetSamplers(0, 1, samplers);
}
renderer->GetRenderState()->Update(true);
renderer->GetRenderState()->Pop();
}
BloomEffectDX11::BloomEffectDX11(Graphics* graphics)
: BloomEffect(graphics), blitter(graphics)
{
using namespace Effekseer;
using namespace EffekseerRendererDX11;
auto renderer = (RendererImplemented*)graphics->GetRenderer();
// Extract shader
shaderExtract.reset(Shader::Create(renderer,
PostFX_Basic_VS::g_VS, sizeof(PostFX_Basic_VS::g_VS),
PostFX_Extract_PS::g_PS, sizeof(PostFX_Extract_PS::g_PS),
"Bloom extract", PostFx_ShaderDecl, 2));
shaderExtract->SetPixelConstantBufferSize(sizeof(float) * 8);
shaderExtract->SetPixelRegisterCount(2);
// Downsample shader
shaderDownsample.reset(Shader::Create(renderer,
PostFX_Basic_VS::g_VS, sizeof(PostFX_Basic_VS::g_VS),
PostFX_Downsample_PS::g_PS, sizeof(PostFX_Downsample_PS::g_PS),
"Bloom downsample", PostFx_ShaderDecl, 2));
// Blend shader
shaderBlend.reset(Shader::Create(renderer,
PostFX_Basic_VS::g_VS, sizeof(PostFX_Basic_VS::g_VS),
PostFX_Blend_PS::g_PS, sizeof(PostFX_Blend_PS::g_PS),
"Bloom blend", PostFx_ShaderDecl, 2));
// Blur(horizontal) shader
shaderBlurH.reset(Shader::Create(renderer,
PostFX_Basic_VS::g_VS, sizeof(PostFX_Basic_VS::g_VS),
PostFX_BlurH_PS::g_PS, sizeof(PostFX_BlurH_PS::g_PS),
"Bloom blurH", PostFx_ShaderDecl, 2));
// Blur(vertical) shader
shaderBlurV.reset(Shader::Create(renderer,
PostFX_Basic_VS::g_VS, sizeof(PostFX_Basic_VS::g_VS),
PostFX_BlurV_PS::g_PS, sizeof(PostFX_BlurV_PS::g_PS),
"Bloom blurV", PostFx_ShaderDecl, 2));
}
BloomEffectDX11::~BloomEffectDX11()
{
}
void BloomEffectDX11::Render(RenderTexture* src, RenderTexture* dest)
{
if( !enabled )
{
return;
}
using namespace Effekseer;
using namespace EffekseerRendererDX11;
auto renderer = (RendererImplemented*)graphics->GetRenderer();
if (renderTextureWidth != src->GetWidth() ||
renderTextureHeight != src->GetHeight())
{
SetupBuffers(src->GetWidth(), src->GetHeight());
}
// Extract pass
{
const float knee = threshold * softKnee;
const float constantData[8] = {
threshold,
threshold - knee,
knee * 2.0f,
0.25f / (knee + 0.00001f),
intensity,
};
ID3D11ShaderResourceView* textures[1] = {
(ID3D11ShaderResourceView*)src->GetViewID()};
blitter.Blit(shaderExtract.get(), 1, textures, constantData, sizeof(constantData), extractBuffer.get());
}
// Shrink pass
for (int i = 0; i < BlurIterations; i++)
{
ID3D11ShaderResourceView* textures[1];
textures[0] = (i == 0) ?
(ID3D11ShaderResourceView*)extractBuffer->GetViewID() :
(ID3D11ShaderResourceView*)lowresBuffers[0][i - 1]->GetViewID();
blitter.Blit(shaderDownsample.get(), 1, textures, nullptr, 0, lowresBuffers[0][i].get());
}
// Horizontal gaussian blur pass
for (int i = 0; i < BlurIterations; i++)
{
ID3D11ShaderResourceView* textures[1] = {
(ID3D11ShaderResourceView*)lowresBuffers[0][i]->GetViewID()};
blitter.Blit(shaderBlurH.get(), 1, textures, nullptr, 0, lowresBuffers[1][i].get());
}
// Vertical gaussian blur pass
for (int i = 0; i < BlurIterations; i++)
{
ID3D11ShaderResourceView* textures[1] = {
(ID3D11ShaderResourceView*)lowresBuffers[1][i]->GetViewID()};
blitter.Blit(shaderBlurV.get(), 1, textures, nullptr, 0, lowresBuffers[0][i].get());
}
// Blending pass
{
ID3D11ShaderResourceView* textures[4] = {
(ID3D11ShaderResourceView*)lowresBuffers[0][0]->GetViewID(),
(ID3D11ShaderResourceView*)lowresBuffers[0][1]->GetViewID(),
(ID3D11ShaderResourceView*)lowresBuffers[0][2]->GetViewID(),
(ID3D11ShaderResourceView*)lowresBuffers[0][3]->GetViewID()};
blitter.Blit(shaderBlend.get(), 4, textures, nullptr, 0, dest, AlphaBlendType::Add);
}
}
void BloomEffectDX11::OnLostDevice()
{
ReleaseBuffers();
}
void BloomEffectDX11::OnResetDevice()
{
}
void BloomEffectDX11::SetupBuffers(int32_t width, int32_t height)
{
ReleaseBuffers();
renderTextureWidth = width;
renderTextureHeight = height;
// Create high brightness extraction buffer
{
int32_t bufferWidth = width;
int32_t bufferHeight = height;
extractBuffer.reset(RenderTexture::Create(graphics));
extractBuffer->Initialize(bufferWidth, bufferHeight, TextureFormat::RGBA16F);
}
// Create low-resolution buffers
for (int i = 0; i < BlurBuffers; i++) {
int32_t bufferWidth = width;
int32_t bufferHeight = height;
for (int j = 0; j < BlurIterations; j++) {
bufferWidth = std::max(1, (bufferWidth + 1) / 2);
bufferHeight = std::max(1, (bufferHeight + 1) / 2);
lowresBuffers[i][j].reset(RenderTexture::Create(graphics));
lowresBuffers[i][j]->Initialize(bufferWidth, bufferHeight, TextureFormat::RGBA16F);
}
}
}
void BloomEffectDX11::ReleaseBuffers()
{
renderTextureWidth = 0;
renderTextureHeight = 0;
extractBuffer.reset();
for (int i = 0; i < BlurBuffers; i++) {
for (int j = 0; j < BlurIterations; j++) {
lowresBuffers[i][j].reset();
}
}
}
TonemapEffectDX11::TonemapEffectDX11(Graphics* graphics)
: TonemapEffect(graphics), blitter(graphics)
{
using namespace Effekseer;
using namespace EffekseerRendererDX11;
auto renderer = (RendererImplemented*)graphics->GetRenderer();
// Copy shader
shaderCopy.reset(Shader::Create(renderer,
PostFX_Basic_VS::g_VS, sizeof(PostFX_Basic_VS::g_VS),
PostFX_Copy_PS::g_PS, sizeof(PostFX_Copy_PS::g_PS),
"Tonemap Copy", PostFx_ShaderDecl, 2));
// Reinhard shader
shaderReinhard.reset(Shader::Create(renderer,
PostFX_Basic_VS::g_VS, sizeof(PostFX_Basic_VS::g_VS),
PostFX_Tonemap_PS::g_PS, sizeof(PostFX_Tonemap_PS::g_PS),
"Tonemap Reinhard", PostFx_ShaderDecl, 2));
shaderReinhard->SetPixelConstantBufferSize(sizeof(float) * 4);
shaderReinhard->SetPixelRegisterCount(1);
}
TonemapEffectDX11::~TonemapEffectDX11()
{
}
void TonemapEffectDX11::Render(RenderTexture* src, RenderTexture* dest)
{
using namespace Effekseer;
using namespace EffekseerRendererDX11;
auto renderer = (RendererImplemented*)graphics->GetRenderer();
// Tonemap pass
ID3D11ShaderResourceView* textures[1] = {
(ID3D11ShaderResourceView*)src->GetViewID()};
if (algorithm == Algorithm::Off) {
blitter.Blit(shaderCopy.get(), 1, textures, nullptr, 0, dest);
} else if (algorithm == Algorithm::Reinhard) {
const float constantData[4] = {exposure, 16.0f * 16.0f};
blitter.Blit(shaderReinhard.get(), 1, textures, constantData, sizeof(constantData), dest);
}
}
}
|
#if _WIN32
#define NOMINMAX
#endif
#include <algorithm>
#include "efk.PostEffectsDX11.h"
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/spdlog.h>
namespace efk
{
namespace PostFX_Basic_VS
{
static
#include "Shader/efk.GraphicsDX11.PostFX_Basic_VS.h"
}
namespace PostFX_Copy_PS
{
static
#include "Shader/efk.GraphicsDX11.PostFX_Copy_PS.h"
}
namespace PostFX_Extract_PS
{
static
#include "Shader/efk.GraphicsDX11.PostFX_Extract_PS.h"
}
namespace PostFX_Downsample_PS
{
static
#include "Shader/efk.GraphicsDX11.PostFX_Downsample_PS.h"
}
namespace PostFX_Blend_PS
{
static
#include "Shader/efk.GraphicsDX11.PostFX_Blend_PS.h"
}
namespace PostFX_BlurH_PS
{
static
#include "Shader/efk.GraphicsDX11.PostFX_BlurH_PS.h"
}
namespace PostFX_BlurV_PS
{
static
#include "Shader/efk.GraphicsDX11.PostFX_BlurV_PS.h"
}
namespace PostFX_Tonemap_PS
{
static
#include "Shader/efk.GraphicsDX11.PostFX_Tonemap_PS.h"
}
// Position(2) UV(2)
static const D3D11_INPUT_ELEMENT_DESC PostFx_ShaderDecl[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
BlitterDX11::BlitterDX11(Graphics* graphics)
: graphics(graphics)
{
using namespace Effekseer;
using namespace EffekseerRendererDX11;
auto renderer = (RendererImplemented*)graphics->GetRenderer();
// Generate vertex data
vertexBuffer.reset(VertexBuffer::Create(renderer,
sizeof(Vertex) * 4, true));
vertexBuffer->Lock(); {
Vertex* verteces = (Vertex*)vertexBuffer->GetBufferDirect(sizeof(Vertex) * 4);
verteces[0] = Vertex{-1.0f, 1.0f, 0.0f, 0.0f};
verteces[1] = Vertex{-1.0f, -1.0f, 0.0f, 1.0f};
verteces[2] = Vertex{ 1.0f, 1.0f, 1.0f, 0.0f};
verteces[3] = Vertex{ 1.0f, -1.0f, 1.0f, 1.0f};
}
vertexBuffer->Unlock();
// Generate Sampler State
{
const D3D11_SAMPLER_DESC SamlerDesc = {
D3D11_FILTER_MIN_MAG_MIP_LINEAR,
D3D11_TEXTURE_ADDRESS_CLAMP,
D3D11_TEXTURE_ADDRESS_CLAMP,
D3D11_TEXTURE_ADDRESS_CLAMP,
0.0f,
0,
D3D11_COMPARISON_ALWAYS,
{ 0.0f, 0.0f, 0.0f, 0.0f },
0.0f,
D3D11_FLOAT32_MAX, };
renderer->GetDevice()->CreateSamplerState( &SamlerDesc, &sampler );
}
}
BlitterDX11::~BlitterDX11()
{
ES_SAFE_RELEASE( sampler );
}
void BlitterDX11::Blit(EffekseerRendererDX11::Shader* shader,
int32_t numTextures, ID3D11ShaderResourceView* const* textures,
const void* constantData, size_t constantDataSize, RenderTexture* dest,
Effekseer::AlphaBlendType blendType)
{
using namespace Effekseer;
using namespace EffekseerRendererDX11;
auto renderer = (RendererImplemented*)graphics->GetRenderer();
auto& state = renderer->GetRenderState()->Push();
state.AlphaBlend = blendType;
state.DepthWrite = false;
state.DepthTest = false;
state.CullingType = CullingType::Double;
state.TextureFilterTypes[0] = TextureFilterType::Linear;
state.TextureWrapTypes[0] = TextureWrapType::Clamp;
renderer->GetRenderState()->Update(false);
renderer->SetRenderMode(RenderMode::Normal);
renderer->SetVertexBuffer(vertexBuffer.get(), sizeof(Vertex));
renderer->GetContext()->IASetIndexBuffer(nullptr, DXGI_FORMAT_R16_UINT, 0);
renderer->GetContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
renderer->GetContext()->PSSetSamplers(0, 1, &sampler);
renderer->BeginShader(shader);
renderer->GetContext()->IASetInputLayout(shader->GetLayoutInterface());
if (constantData)
{
memcpy(shader->GetPixelConstantBuffer(), constantData, constantDataSize);
shader->SetConstantBuffer();
}
graphics->SetRenderTarget(dest, nullptr);
renderer->GetContext()->PSSetShaderResources(0, numTextures, textures);
renderer->GetContext()->Draw(4, 0);
renderer->EndShader(shader);
// Reset texture/sampler state
{
ID3D11ShaderResourceView* srv[4] = {};
renderer->GetContext()->PSSetShaderResources(0, 4, srv);
ID3D11SamplerState* samplers[1] = {};
renderer->GetContext()->PSSetSamplers(0, 1, samplers);
}
renderer->GetRenderState()->Update(true);
renderer->GetRenderState()->Pop();
}
BloomEffectDX11::BloomEffectDX11(Graphics* graphics)
: BloomEffect(graphics), blitter(graphics)
{
using namespace Effekseer;
using namespace EffekseerRendererDX11;
auto renderer = (RendererImplemented*)graphics->GetRenderer();
// Extract shader
shaderExtract.reset(Shader::Create(renderer,
PostFX_Basic_VS::g_VS, sizeof(PostFX_Basic_VS::g_VS),
PostFX_Extract_PS::g_PS, sizeof(PostFX_Extract_PS::g_PS),
"Bloom extract", PostFx_ShaderDecl, 2));
if (shaderExtract != nullptr)
{
shaderExtract->SetPixelConstantBufferSize(sizeof(float) * 8);
shaderExtract->SetPixelRegisterCount(2);
}
else
{
spdlog::trace("FAIL Create shaderExtract");
}
// Downsample shader
shaderDownsample.reset(Shader::Create(renderer,
PostFX_Basic_VS::g_VS, sizeof(PostFX_Basic_VS::g_VS),
PostFX_Downsample_PS::g_PS, sizeof(PostFX_Downsample_PS::g_PS),
"Bloom downsample", PostFx_ShaderDecl, 2));
// Blend shader
shaderBlend.reset(Shader::Create(renderer,
PostFX_Basic_VS::g_VS, sizeof(PostFX_Basic_VS::g_VS),
PostFX_Blend_PS::g_PS, sizeof(PostFX_Blend_PS::g_PS),
"Bloom blend", PostFx_ShaderDecl, 2));
// Blur(horizontal) shader
shaderBlurH.reset(Shader::Create(renderer,
PostFX_Basic_VS::g_VS, sizeof(PostFX_Basic_VS::g_VS),
PostFX_BlurH_PS::g_PS, sizeof(PostFX_BlurH_PS::g_PS),
"Bloom blurH", PostFx_ShaderDecl, 2));
// Blur(vertical) shader
shaderBlurV.reset(Shader::Create(renderer,
PostFX_Basic_VS::g_VS, sizeof(PostFX_Basic_VS::g_VS),
PostFX_BlurV_PS::g_PS, sizeof(PostFX_BlurV_PS::g_PS),
"Bloom blurV", PostFx_ShaderDecl, 2));
}
BloomEffectDX11::~BloomEffectDX11()
{
}
void BloomEffectDX11::Render(RenderTexture* src, RenderTexture* dest)
{
if( !enabled )
{
return;
}
using namespace Effekseer;
using namespace EffekseerRendererDX11;
auto renderer = (RendererImplemented*)graphics->GetRenderer();
if (renderTextureWidth != src->GetWidth() ||
renderTextureHeight != src->GetHeight())
{
SetupBuffers(src->GetWidth(), src->GetHeight());
}
// Extract pass
{
const float knee = threshold * softKnee;
const float constantData[8] = {
threshold,
threshold - knee,
knee * 2.0f,
0.25f / (knee + 0.00001f),
intensity,
};
ID3D11ShaderResourceView* textures[1] = {
(ID3D11ShaderResourceView*)src->GetViewID()};
blitter.Blit(shaderExtract.get(), 1, textures, constantData, sizeof(constantData), extractBuffer.get());
}
// Shrink pass
for (int i = 0; i < BlurIterations; i++)
{
ID3D11ShaderResourceView* textures[1];
textures[0] = (i == 0) ?
(ID3D11ShaderResourceView*)extractBuffer->GetViewID() :
(ID3D11ShaderResourceView*)lowresBuffers[0][i - 1]->GetViewID();
blitter.Blit(shaderDownsample.get(), 1, textures, nullptr, 0, lowresBuffers[0][i].get());
}
// Horizontal gaussian blur pass
for (int i = 0; i < BlurIterations; i++)
{
ID3D11ShaderResourceView* textures[1] = {
(ID3D11ShaderResourceView*)lowresBuffers[0][i]->GetViewID()};
blitter.Blit(shaderBlurH.get(), 1, textures, nullptr, 0, lowresBuffers[1][i].get());
}
// Vertical gaussian blur pass
for (int i = 0; i < BlurIterations; i++)
{
ID3D11ShaderResourceView* textures[1] = {
(ID3D11ShaderResourceView*)lowresBuffers[1][i]->GetViewID()};
blitter.Blit(shaderBlurV.get(), 1, textures, nullptr, 0, lowresBuffers[0][i].get());
}
// Blending pass
{
ID3D11ShaderResourceView* textures[4] = {
(ID3D11ShaderResourceView*)lowresBuffers[0][0]->GetViewID(),
(ID3D11ShaderResourceView*)lowresBuffers[0][1]->GetViewID(),
(ID3D11ShaderResourceView*)lowresBuffers[0][2]->GetViewID(),
(ID3D11ShaderResourceView*)lowresBuffers[0][3]->GetViewID()};
blitter.Blit(shaderBlend.get(), 4, textures, nullptr, 0, dest, AlphaBlendType::Add);
}
}
void BloomEffectDX11::OnLostDevice()
{
ReleaseBuffers();
}
void BloomEffectDX11::OnResetDevice()
{
}
void BloomEffectDX11::SetupBuffers(int32_t width, int32_t height)
{
ReleaseBuffers();
renderTextureWidth = width;
renderTextureHeight = height;
// Create high brightness extraction buffer
{
int32_t bufferWidth = width;
int32_t bufferHeight = height;
extractBuffer.reset(RenderTexture::Create(graphics));
if (extractBuffer != nullptr)
{
extractBuffer->Initialize(bufferWidth, bufferHeight, TextureFormat::RGBA16F);
}
else
{
spdlog::trace("FAIL Create extractBuffer");
}
}
// Create low-resolution buffers
for (int i = 0; i < BlurBuffers; i++) {
int32_t bufferWidth = width;
int32_t bufferHeight = height;
for (int j = 0; j < BlurIterations; j++) {
bufferWidth = std::max(1, (bufferWidth + 1) / 2);
bufferHeight = std::max(1, (bufferHeight + 1) / 2);
lowresBuffers[i][j].reset(RenderTexture::Create(graphics));
if (lowresBuffers[i][j] != nullptr)
{
lowresBuffers[i][j]->Initialize(bufferWidth, bufferHeight, TextureFormat::RGBA16F);
}
else
{
spdlog::trace("FAIL Create lowresBuffers[i][j]");
}
}
}
}
void BloomEffectDX11::ReleaseBuffers()
{
renderTextureWidth = 0;
renderTextureHeight = 0;
extractBuffer.reset();
for (int i = 0; i < BlurBuffers; i++) {
for (int j = 0; j < BlurIterations; j++) {
lowresBuffers[i][j].reset();
}
}
}
TonemapEffectDX11::TonemapEffectDX11(Graphics* graphics)
: TonemapEffect(graphics), blitter(graphics)
{
using namespace Effekseer;
using namespace EffekseerRendererDX11;
auto renderer = (RendererImplemented*)graphics->GetRenderer();
// Copy shader
shaderCopy.reset(Shader::Create(renderer,
PostFX_Basic_VS::g_VS, sizeof(PostFX_Basic_VS::g_VS),
PostFX_Copy_PS::g_PS, sizeof(PostFX_Copy_PS::g_PS),
"Tonemap Copy", PostFx_ShaderDecl, 2));
// Reinhard shader
shaderReinhard.reset(Shader::Create(renderer,
PostFX_Basic_VS::g_VS, sizeof(PostFX_Basic_VS::g_VS),
PostFX_Tonemap_PS::g_PS, sizeof(PostFX_Tonemap_PS::g_PS),
"Tonemap Reinhard", PostFx_ShaderDecl, 2));
if (shaderReinhard != nullptr)
{
shaderReinhard->SetPixelConstantBufferSize(sizeof(float) * 4);
shaderReinhard->SetPixelRegisterCount(1);
}
else
{
spdlog::trace("FAIL Create shaderReinhard");
}
}
TonemapEffectDX11::~TonemapEffectDX11()
{
}
void TonemapEffectDX11::Render(RenderTexture* src, RenderTexture* dest)
{
using namespace Effekseer;
using namespace EffekseerRendererDX11;
auto renderer = (RendererImplemented*)graphics->GetRenderer();
// Tonemap pass
ID3D11ShaderResourceView* textures[1] = {
(ID3D11ShaderResourceView*)src->GetViewID()};
if (algorithm == Algorithm::Off) {
blitter.Blit(shaderCopy.get(), 1, textures, nullptr, 0, dest);
} else if (algorithm == Algorithm::Reinhard) {
const float constantData[4] = {exposure, 16.0f * 16.0f};
blitter.Blit(shaderReinhard.get(), 1, textures, constantData, sizeof(constantData), dest);
}
}
}
|
Add logger
|
Add logger
|
C++
|
mit
|
effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer
|
62cf07dc2904d80587934e2176719880f24325e1
|
Modules/ContourModel/Testing/mitkContourModelTest.cpp
|
Modules/ContourModel/Testing/mitkContourModelTest.cpp
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkTestingMacros.h>
#include <mitkContourModel.h>
//Add a vertex to the contour and see if size changed
static void TestAddVertex()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
MITK_TEST_CONDITION(contour->GetNumberOfVertices() > 0, "Add a Vertex, size increased");
}
//Select a vertex by index. successful if the selected vertex member of the contour is no longer set to null
static void TestSelectVertexAtIndex()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
contour->SelectVertexAt(0);
MITK_TEST_CONDITION(contour->GetSelectedVertex() != NULL, "Vertex was selected at index");
}
//Select a vertex by worldposition. successful if the selected vertex member of the contour is no longer set to null
static void TestSelectVertexAtWorldposition()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
//same point is used here so the epsilon can be chosen very small
contour->SelectVertexAt(p, 0.01);
MITK_TEST_CONDITION(contour->GetSelectedVertex() != NULL, "Vertex was selected at position");
}
//Move a vertex by a translation vector
static void TestMoveSelectedVertex()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
//Same point is used here so the epsilon can be chosen very small
contour->SelectVertexAt(p, 0.01);
mitk::Vector3D v;
v[0] = 1;
v[1] = 3;
v[2] = -1;
contour->ShiftSelectedVertex(v);
const mitk::ContourModel::VertexType* vertex = contour->GetSelectedVertex();
bool correctlyMoved = false;
correctlyMoved = (vertex->Coordinates)[0] == (v[0]) &&
(vertex->Coordinates)[1] == (v[1]) &&
(vertex->Coordinates)[2] == (v[2]);
MITK_TEST_CONDITION(correctlyMoved, "Vertex has been moved");
}
//Test to move the whole contour
static void TestMoveContour()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
mitk::Point3D p2;
p2[0] = p2[1] = p2[2] = 0;
contour->AddVertex(p2);
mitk::Vector3D v;
v[0] = 1;
v[1] = 3;
v[2] = -1;
contour->ShiftContour(v);
mitk::ContourModel::VertexIterator it = contour->IteratorBegin();
mitk::ContourModel::VertexIterator end = contour->IteratorEnd();
bool correctlyMoved = false;
while(it != end)
{
correctlyMoved &= (*it)->Coordinates[0] == (v[0]) &&
(*it)->Coordinates[1] == (v[1]) &&
(*it)->Coordinates[2] == (v[2]);
}
MITK_TEST_CONDITION(correctlyMoved, "Contour has been moved");
}
//Remove a vertex by index
static void TestRemoveVertexAtIndex()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
contour->RemoveVertexAt(0);
MITK_TEST_CONDITION(contour->GetNumberOfVertices() == 0, "removed vertex");
}
//Remove a vertex by position
static void TestRemoveVertexAtWorldPosition()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
contour->RemoveVertexAt(p, 0.01);
MITK_TEST_CONDITION(contour->GetNumberOfVertices() == 0, "removed vertex");
}
//Check closeable contour
static void TestIsclosed()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
mitk::Point3D p2;
p2[0] = p2[1] = p2[2] = 1;
contour->AddVertex(p2);
contour->Close();
MITK_TEST_CONDITION(contour->IsClosed(), "closed contour");
//no vertices should be added to a closed contour
int oldNumberOfVertices = contour->GetNumberOfVertices();
mitk::Point3D p3;
p3[0] = p3[1] = p3[2] = 4;
contour->AddVertex(p3);
int newNumberOfVertices = contour->GetNumberOfVertices();
MITK_TEST_CONDITION(oldNumberOfVertices != newNumberOfVertices, "vertices added to closed contour");
}
//Test concatenating two contours
static void TestConcatenate()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
mitk::Point3D p2;
p2[0] = p2[1] = p2[2] = 1;
contour->AddVertex(p2);
mitk::ContourModel::Pointer contour2 = mitk::ContourModel::New();
mitk::Point3D p3;
p3[0] = -2;
p3[1] = 10;
p3[2] = 0;
contour2->AddVertex(p3);
mitk::Point3D p4;
p4[0] = -3;
p4[1] = 6;
p4[2] = -5;
contour2->AddVertex(p4);
contour->Concatenate(contour2);
MITK_TEST_CONDITION(contour->GetNumberOfVertices() == 4, "two contours were concatenated");
}
//Try to select a vertex at position (within a epsilon of course) where no vertex is.
//So the selected verted member should be null.
static void TestSelectVertexAtWrongPosition()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
MITK_TEST_CONDITION_REQUIRED(contour->GetSelectedVertex() == NULL, "selected vertex is NULL");
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
mitk::Point3D p2;
p2[0] = p2[1] = p2[2] = 2;
contour->SelectVertexAt(p2, 0.1);
MITK_TEST_CONDITION(contour->GetSelectedVertex() == NULL, "Vertex was not selected");
}
static void TestInsertVertex()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
mitk::Point3D p2;
p2[0] = p2[1] = p2[2] = 1;
contour->AddVertex(p2);
mitk::Point3D pointToInsert;
pointToInsert[0] = pointToInsert[1] = pointToInsert[2] = 10;
contour->InsertVertexAtIndex(pointToInsert, 1);
MITK_TEST_CONDITION(contour->GetNumberOfVertices() == 3, "test insert vertex");
MITK_TEST_CONDITION(contour->GetVertexAt(1)->Coordinates == pointToInsert, "compare inserted vertex");
}
//try to access an invalid timestep
static void TestInvalidTimeStep()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
mitk::Point3D p2;
p2[0] = p2[1] = p2[2] = 1;
contour->AddVertex(p2);
int invalidTimeStep = 42;
MITK_TEST_CONDITION_REQUIRED(contour->IsEmptyTimeStep(invalidTimeStep), "invalid timestep required");
MITK_TEST_FOR_EXCEPTION(std::exception, contour->IteratorBegin(-1));
contour->Close(invalidTimeStep);
MITK_TEST_CONDITION(contour->IsClosed() == false, "test close for timestep 0");
MITK_TEST_CONDITION(contour->IsClosed(invalidTimeStep) == false, "test close at invalid timestep");
contour->SetClosed(true, invalidTimeStep);
MITK_TEST_CONDITION(contour->GetNumberOfVertices(invalidTimeStep) == -1, "test number of vertices at invalid timestep");
contour->AddVertex(p2, invalidTimeStep);
MITK_TEST_CONDITION(contour->GetNumberOfVertices(invalidTimeStep) == -1, "test add vertex at invalid timestep");
contour->InsertVertexAtIndex(p2, 0, false, invalidTimeStep);
MITK_TEST_CONDITION(contour->GetNumberOfVertices(invalidTimeStep) == -1, "test insert vertex at invalid timestep");
MITK_TEST_CONDITION(contour->SelectVertexAt(0, invalidTimeStep) == NULL, "test select vertex at invalid timestep");
MITK_TEST_CONDITION(contour->RemoveVertexAt(0, invalidTimeStep) == false, "test remove vertex at invalid timestep");
}
static void TestEmptyContour()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
MITK_TEST_CONDITION(contour->IteratorBegin() == contour->IteratorEnd(), "test iterator of emtpy contour");
MITK_TEST_CONDITION(contour->GetNumberOfVertices() == 0, "test numberof vertices of empty contour");
}
static void TestSetVertices()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
mitk::Point3D newCoordinates;
newCoordinates[0] = newCoordinates[1] = newCoordinates[2] = 1;
contour->SetVertexAt(0, newCoordinates );
MITK_TEST_EQUAL(contour->GetVertexAt(0)->Coordinates, newCoordinates, "set coordinates" );
mitk::ContourModel::Pointer contour2 = mitk::ContourModel::New();
mitk::Point3D p3;
p3[0] = -2;
p3[1] = 10;
p3[2] = 0;
contour2->AddVertex(p3);
mitk::Point3D p4;
p4[0] = -3;
p4[1] = 6;
p4[2] = -5;
contour2->AddVertex(p4);
contour->AddVertex(p);
contour->SetVertexAt(0, contour2->GetVertexAt(1));
MITK_TEST_EQUAL(contour->GetVertexAt(1)->Coordinates, contour2->GetVertexAt(1)->Coordinates, "Use setter and getter combination");
MITK_TEST_CONDITION(contour->GetIndex(contour2->GetVertexAt(1)) == 0, "Index is correct");
}
static void TestContourModelAPI()
{
mitk::ContourModel::Pointer contour1 = mitk::ContourModel::New();
mitk::Point3D p1;
p1[0] = -2;
p1[1] = 10;
p1[2] = 0;
contour1->AddVertex(p1);
//adding vertices should always copy the content and not store pointers or references.
MITK_TEST_CONDITION( &p1 != &(contour1->GetVertexAt(0)->Coordinates), "copied point" );
mitk::Point3D p2;
p2[0] = -3;
p2[1] = 6;
p2[2] = -5;
contour1->AddVertex(p2);
//test use of setter and getter with const and non-const pointers
const mitk::ContourModel::VertexType* vertex = contour1->GetVertexAt(1);
MITK_TEST_CONDITION(contour1->GetIndex(vertex) == 1, "Get index");
mitk::ContourModel::VertexType* nonConstVertex = const_cast<mitk::ContourModel::VertexType*>(vertex);
MITK_TEST_CONDITION(contour1->GetIndex(nonConstVertex) == 1, "Get index non-const");
mitk::ContourModel::Pointer contour2 = mitk::ContourModel::New();
mitk::Point3D p3;
p3[0] = p3[1] = p3[2] = 3;
contour2->AddVertex(p3);
contour1->AddVertex(contour2->GetVertexAt(0));
}
int mitkContourModelTest(int itkNotUsed(argc), char** itkNotUsed(argv))
{
MITK_TEST_BEGIN("mitkContourModelTest")
TestAddVertex();
TestSelectVertexAtIndex();
TestSelectVertexAtWorldposition();
TestMoveSelectedVertex();
TestRemoveVertexAtIndex();
TestRemoveVertexAtWorldPosition();
TestIsclosed();
TestConcatenate();
TestInvalidTimeStep();
TestInsertVertex();
TestEmptyContour();
TestSetVertices();
TestSelectVertexAtWrongPosition();
TestContourModelAPI();
MITK_TEST_END()
}
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkTestingMacros.h>
#include <mitkContourModel.h>
//Add a vertex to the contour and see if size changed
static void TestAddVertex()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
MITK_TEST_CONDITION(contour->GetNumberOfVertices() > 0, "Add a Vertex, size increased");
}
//Select a vertex by index. successful if the selected vertex member of the contour is no longer set to null
static void TestSelectVertexAtIndex()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
contour->SelectVertexAt(0);
MITK_TEST_CONDITION(contour->GetSelectedVertex() != NULL, "Vertex was selected at index");
}
//Select a vertex by worldposition. successful if the selected vertex member of the contour is no longer set to null
static void TestSelectVertexAtWorldposition()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
//same point is used here so the epsilon can be chosen very small
contour->SelectVertexAt(p, 0.01);
MITK_TEST_CONDITION(contour->GetSelectedVertex() != NULL, "Vertex was selected at position");
}
//Move a vertex by a translation vector
static void TestMoveSelectedVertex()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
//Same point is used here so the epsilon can be chosen very small
contour->SelectVertexAt(p, 0.01);
mitk::Vector3D v;
v[0] = 1;
v[1] = 3;
v[2] = -1;
contour->ShiftSelectedVertex(v);
const mitk::ContourModel::VertexType* vertex = contour->GetSelectedVertex();
bool correctlyMoved = false;
correctlyMoved = (vertex->Coordinates)[0] == (v[0]) &&
(vertex->Coordinates)[1] == (v[1]) &&
(vertex->Coordinates)[2] == (v[2]);
MITK_TEST_CONDITION(correctlyMoved, "Vertex has been moved");
}
//Test to move the whole contour
static void TestMoveContour()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
mitk::Point3D p2;
p2[0] = p2[1] = p2[2] = 0;
contour->AddVertex(p2);
mitk::Vector3D v;
v[0] = 1;
v[1] = 3;
v[2] = -1;
contour->ShiftContour(v);
mitk::ContourModel::VertexIterator it = contour->IteratorBegin();
mitk::ContourModel::VertexIterator end = contour->IteratorEnd();
bool correctlyMoved = false;
while(it != end)
{
correctlyMoved &= (*it)->Coordinates[0] == (v[0]) &&
(*it)->Coordinates[1] == (v[1]) &&
(*it)->Coordinates[2] == (v[2]);
}
MITK_TEST_CONDITION(correctlyMoved, "Contour has been moved");
}
//Remove a vertex by index
static void TestRemoveVertexAtIndex()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
contour->RemoveVertexAt(0);
MITK_TEST_CONDITION(contour->GetNumberOfVertices() == 0, "removed vertex");
}
//Remove a vertex by position
static void TestRemoveVertexAtWorldPosition()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
contour->RemoveVertexAt(p, 0.01);
MITK_TEST_CONDITION(contour->GetNumberOfVertices() == 0, "removed vertex");
}
//Check closeable contour
static void TestIsclosed()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
mitk::Point3D p2;
p2[0] = p2[1] = p2[2] = 1;
contour->AddVertex(p2);
contour->Close();
MITK_TEST_CONDITION(contour->IsClosed(), "closed contour");
//no vertices should be added to a closed contour
int oldNumberOfVertices = contour->GetNumberOfVertices();
mitk::Point3D p3;
p3[0] = p3[1] = p3[2] = 4;
contour->AddVertex(p3);
int newNumberOfVertices = contour->GetNumberOfVertices();
MITK_TEST_CONDITION(oldNumberOfVertices != newNumberOfVertices, "vertices added to closed contour");
}
//Test concatenating two contours
static void TestConcatenate()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
mitk::Point3D p2;
p2[0] = p2[1] = p2[2] = 1;
contour->AddVertex(p2);
mitk::ContourModel::Pointer contour2 = mitk::ContourModel::New();
mitk::Point3D p3;
p3[0] = -2;
p3[1] = 10;
p3[2] = 0;
contour2->AddVertex(p3);
mitk::Point3D p4;
p4[0] = -3;
p4[1] = 6;
p4[2] = -5;
contour2->AddVertex(p4);
contour->Concatenate(contour2);
MITK_TEST_CONDITION(contour->GetNumberOfVertices() == 4, "two contours were concatenated");
}
//Try to select a vertex at position (within a epsilon of course) where no vertex is.
//So the selected verted member should be null.
static void TestSelectVertexAtWrongPosition()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
MITK_TEST_CONDITION_REQUIRED(contour->GetSelectedVertex() == NULL, "selected vertex is NULL");
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
mitk::Point3D p2;
p2[0] = p2[1] = p2[2] = 2;
contour->SelectVertexAt(p2, 0.1);
MITK_TEST_CONDITION(contour->GetSelectedVertex() == NULL, "Vertex was not selected");
}
static void TestInsertVertex()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
mitk::Point3D p2;
p2[0] = p2[1] = p2[2] = 1;
contour->AddVertex(p2);
mitk::Point3D pointToInsert;
pointToInsert[0] = pointToInsert[1] = pointToInsert[2] = 10;
contour->InsertVertexAtIndex(pointToInsert, 1);
MITK_TEST_CONDITION(contour->GetNumberOfVertices() == 3, "test insert vertex");
MITK_TEST_CONDITION(contour->GetVertexAt(1)->Coordinates == pointToInsert, "compare inserted vertex");
}
//try to access an invalid timestep
static void TestInvalidTimeStep()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
mitk::Point3D p2;
p2[0] = p2[1] = p2[2] = 1;
contour->AddVertex(p2);
int invalidTimeStep = 42;
MITK_TEST_CONDITION_REQUIRED(contour->IsEmptyTimeStep(invalidTimeStep), "invalid timestep required");
MITK_TEST_FOR_EXCEPTION(std::exception, contour->IteratorBegin(-1));
contour->Close(invalidTimeStep);
MITK_TEST_CONDITION(contour->IsClosed() == false, "test close for timestep 0");
MITK_TEST_CONDITION(contour->IsClosed(invalidTimeStep) == false, "test close at invalid timestep");
contour->SetClosed(true, invalidTimeStep);
MITK_TEST_CONDITION(contour->GetNumberOfVertices(invalidTimeStep) == -1, "test number of vertices at invalid timestep");
contour->AddVertex(p2, invalidTimeStep);
MITK_TEST_CONDITION(contour->GetNumberOfVertices(invalidTimeStep) == -1, "test add vertex at invalid timestep");
contour->InsertVertexAtIndex(p2, 0, false, invalidTimeStep);
MITK_TEST_CONDITION(contour->GetNumberOfVertices(invalidTimeStep) == -1, "test insert vertex at invalid timestep");
MITK_TEST_CONDITION(contour->SelectVertexAt(0, invalidTimeStep) == NULL, "test select vertex at invalid timestep");
MITK_TEST_CONDITION(contour->RemoveVertexAt(0, invalidTimeStep) == false, "test remove vertex at invalid timestep");
}
static void TestEmptyContour()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
MITK_TEST_CONDITION(contour->IteratorBegin() == contour->IteratorEnd(), "test iterator of emtpy contour");
MITK_TEST_CONDITION(contour->GetNumberOfVertices() == 0, "test numberof vertices of empty contour");
}
static void TestSetVertices()
{
mitk::ContourModel::Pointer contour = mitk::ContourModel::New();
mitk::Point3D p;
p[0] = p[1] = p[2] = 0;
contour->AddVertex(p);
mitk::Point3D newCoordinates;
newCoordinates[0] = newCoordinates[1] = newCoordinates[2] = 1;
contour->SetVertexAt(0, newCoordinates );
MITK_TEST_EQUAL(contour->GetVertexAt(0)->Coordinates, newCoordinates, "set coordinates" );
mitk::ContourModel::Pointer contour2 = mitk::ContourModel::New();
mitk::Point3D p3;
p3[0] = -2;
p3[1] = 10;
p3[2] = 0;
contour2->AddVertex(p3);
mitk::Point3D p4;
p4[0] = -3;
p4[1] = 6;
p4[2] = -5;
contour2->AddVertex(p4);
contour->AddVertex(p);
contour->SetVertexAt(0, contour2->GetVertexAt(1));
MITK_TEST_EQUAL(contour->GetVertexAt(1)->Coordinates, contour2->GetVertexAt(1)->Coordinates, "Use setter and getter combination");
MITK_TEST_CONDITION(contour->GetIndex(contour2->GetVertexAt(1)) == 0, "Index is correct");
}
static void TestContourModelAPI()
{
mitk::ContourModel::Pointer contour1 = mitk::ContourModel::New();
mitk::Point3D p1;
p1[0] = -2;
p1[1] = 10;
p1[2] = 0;
contour1->AddVertex(p1);
//adding vertices should always copy the content and not store pointers or references.
MITK_TEST_CONDITION( &p1 != &(contour1->GetVertexAt(0)->Coordinates), "copied point" );
mitk::Point3D p2;
p2[0] = -3;
p2[1] = 6;
p2[2] = -5;
contour1->AddVertex(p2);
//test use of setter and getter with const and non-const pointers
const mitk::ContourModel::VertexType* vertex = contour1->GetVertexAt(1);
MITK_TEST_CONDITION(contour1->GetIndex(vertex) == 1, "Get index");
mitk::ContourModel::VertexType* nonConstVertex = const_cast<mitk::ContourModel::VertexType*>(vertex);
MITK_TEST_CONDITION(contour1->GetIndex(nonConstVertex) == 1, "Get index non-const");
mitk::ContourModel::Pointer contour2 = mitk::ContourModel::New();
mitk::Point3D p3;
p3[0] = p3[1] = p3[2] = 3;
contour2->AddVertex(p3);
contour1->AddVertex(contour2->GetVertexAt(0));
}
int mitkContourModelTest(int argc, char* argv[])
{
MITK_TEST_BEGIN("mitkContourModelTest")
TestAddVertex();
TestSelectVertexAtIndex();
TestSelectVertexAtWorldposition();
TestMoveSelectedVertex();
TestRemoveVertexAtIndex();
TestRemoveVertexAtWorldPosition();
TestIsclosed();
TestConcatenate();
TestInvalidTimeStep();
TestInsertVertex();
TestEmptyContour();
TestSetVertices();
TestSelectVertexAtWrongPosition();
TestContourModelAPI();
MITK_TEST_END()
}
|
fix unresolved test function.
|
COMP: fix unresolved test function.
|
C++
|
bsd-3-clause
|
iwegner/MITK,NifTK/MITK,MITK/MITK,danielknorr/MITK,fmilano/mitk,danielknorr/MITK,iwegner/MITK,danielknorr/MITK,RabadanLab/MITKats,NifTK/MITK,NifTK/MITK,iwegner/MITK,MITK/MITK,fmilano/mitk,lsanzdiaz/MITK-BiiG,iwegner/MITK,lsanzdiaz/MITK-BiiG,rfloca/MITK,fmilano/mitk,MITK/MITK,rfloca/MITK,lsanzdiaz/MITK-BiiG,MITK/MITK,iwegner/MITK,rfloca/MITK,danielknorr/MITK,RabadanLab/MITKats,rfloca/MITK,fmilano/mitk,NifTK/MITK,lsanzdiaz/MITK-BiiG,MITK/MITK,rfloca/MITK,lsanzdiaz/MITK-BiiG,fmilano/mitk,RabadanLab/MITKats,NifTK/MITK,NifTK/MITK,danielknorr/MITK,danielknorr/MITK,rfloca/MITK,RabadanLab/MITKats,fmilano/mitk,rfloca/MITK,lsanzdiaz/MITK-BiiG,RabadanLab/MITKats,MITK/MITK,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,RabadanLab/MITKats,danielknorr/MITK,iwegner/MITK,fmilano/mitk
|
594401ea5766f50d8bb9d3e5a2acf3df271a3ece
|
chrome/browser/chromeos/settings/session_manager_operation.cc
|
chrome/browser/chromeos/settings/session_manager_operation.cc
|
// Copyright (c) 2012 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 "chrome/browser/chromeos/settings/session_manager_operation.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/files/file_path.h"
#include "base/message_loop/message_loop.h"
#include "base/stl_util.h"
#include "base/task_runner_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/time/time.h"
#include "chrome/browser/chromeos/settings/owner_key_util.h"
#include "chrome/browser/policy/cloud/cloud_policy_constants.h"
#include "chrome/browser/policy/proto/chromeos/chrome_device_policy.pb.h"
#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h"
#include "content/public/browser/browser_thread.h"
#include "crypto/rsa_private_key.h"
#include "crypto/signature_creator.h"
namespace em = enterprise_management;
namespace chromeos {
SessionManagerOperation::SessionManagerOperation(const Callback& callback)
: session_manager_client_(NULL),
weak_factory_(this),
callback_(callback),
force_key_load_(false),
is_loading_(false) {}
SessionManagerOperation::~SessionManagerOperation() {}
void SessionManagerOperation::Start(
SessionManagerClient* session_manager_client,
scoped_refptr<OwnerKeyUtil> owner_key_util,
scoped_refptr<OwnerKey> owner_key) {
session_manager_client_ = session_manager_client;
owner_key_util_ = owner_key_util;
owner_key_ = owner_key;
Run();
}
void SessionManagerOperation::RestartLoad(bool key_changed) {
if (key_changed)
owner_key_ = NULL;
if (!is_loading_)
return;
// Abort previous load operations.
weak_factory_.InvalidateWeakPtrs();
StartLoading();
}
void SessionManagerOperation::StartLoading() {
is_loading_ = true;
EnsureOwnerKey(base::Bind(&SessionManagerOperation::RetrieveDeviceSettings,
weak_factory_.GetWeakPtr()));
}
void SessionManagerOperation::ReportResult(
DeviceSettingsService::Status status) {
callback_.Run(this, status);
}
void SessionManagerOperation::EnsureOwnerKey(const base::Closure& callback) {
if (force_key_load_ || !owner_key_.get() || !owner_key_->public_key()) {
base::PostTaskAndReplyWithResult(
content::BrowserThread::GetBlockingPool(),
FROM_HERE,
base::Bind(&SessionManagerOperation::LoadOwnerKey,
owner_key_util_, owner_key_),
base::Bind(&SessionManagerOperation::StoreOwnerKey,
weak_factory_.GetWeakPtr(), callback));
} else {
callback.Run();
}
}
// static
scoped_refptr<OwnerKey> SessionManagerOperation::LoadOwnerKey(
scoped_refptr<OwnerKeyUtil> util,
scoped_refptr<OwnerKey> current_key) {
scoped_ptr<std::vector<uint8> > public_key;
scoped_ptr<crypto::RSAPrivateKey> private_key;
// Keep any already-existing keys.
if (current_key.get()) {
if (current_key->public_key())
public_key.reset(new std::vector<uint8>(*current_key->public_key()));
if (current_key->private_key())
private_key.reset(current_key->private_key()->Copy());
}
if (!public_key.get() && util->IsPublicKeyPresent()) {
public_key.reset(new std::vector<uint8>());
if (!util->ImportPublicKey(public_key.get()))
LOG(ERROR) << "Failed to load public owner key.";
}
if (public_key.get() && !private_key.get()) {
private_key.reset(util->FindPrivateKey(*public_key));
if (!private_key.get())
VLOG(1) << "Failed to load private owner key.";
}
return new OwnerKey(public_key.Pass(), private_key.Pass());
}
void SessionManagerOperation::StoreOwnerKey(const base::Closure& callback,
scoped_refptr<OwnerKey> new_key) {
force_key_load_ = false;
owner_key_ = new_key;
if (!owner_key_.get() || !owner_key_->public_key()) {
ReportResult(DeviceSettingsService::STORE_KEY_UNAVAILABLE);
return;
}
callback.Run();
}
void SessionManagerOperation::RetrieveDeviceSettings() {
session_manager_client()->RetrieveDevicePolicy(
base::Bind(&SessionManagerOperation::ValidateDeviceSettings,
weak_factory_.GetWeakPtr()));
}
void SessionManagerOperation::ValidateDeviceSettings(
const std::string& policy_blob) {
scoped_ptr<em::PolicyFetchResponse> policy(new em::PolicyFetchResponse());
if (policy_blob.empty()) {
ReportResult(DeviceSettingsService::STORE_NO_POLICY);
return;
}
if (!policy->ParseFromString(policy_blob) ||
!policy->IsInitialized()) {
ReportResult(DeviceSettingsService::STORE_INVALID_POLICY);
return;
}
base::SequencedWorkerPool* pool =
content::BrowserThread::GetBlockingPool();
scoped_refptr<base::SequencedTaskRunner> background_task_runner =
pool->GetSequencedTaskRunnerWithShutdownBehavior(
pool->GetSequenceToken(),
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
policy::DeviceCloudPolicyValidator* validator =
policy::DeviceCloudPolicyValidator::Create(policy.Pass(),
background_task_runner);
// Policy auto-generated by session manager doesn't include a timestamp, so we
// need to allow missing timestamps.
const bool require_timestamp =
policy_data_.get() && policy_data_->has_request_token();
validator->ValidateAgainstCurrentPolicy(
policy_data_.get(),
require_timestamp ?
policy::CloudPolicyValidatorBase::TIMESTAMP_REQUIRED :
policy::CloudPolicyValidatorBase::TIMESTAMP_NOT_REQUIRED,
policy::CloudPolicyValidatorBase::DM_TOKEN_NOT_REQUIRED);
validator->ValidatePolicyType(policy::dm_protocol::kChromeDevicePolicyType);
validator->ValidatePayload();
validator->ValidateSignature(*owner_key_->public_key(), false);
validator->StartValidation(
base::Bind(&SessionManagerOperation::ReportValidatorStatus,
weak_factory_.GetWeakPtr()));
}
void SessionManagerOperation::ReportValidatorStatus(
policy::DeviceCloudPolicyValidator* validator) {
DeviceSettingsService::Status status =
DeviceSettingsService::STORE_VALIDATION_ERROR;
if (validator->success()) {
status = DeviceSettingsService::STORE_SUCCESS;
policy_data_ = validator->policy_data().Pass();
device_settings_ = validator->payload().Pass();
} else {
LOG(ERROR) << "Policy validation failed: " << validator->status();
// Those are mostly caused by RTC loss and are recoverable.
if (validator->status() ==
policy::DeviceCloudPolicyValidator::VALIDATION_BAD_TIMESTAMP) {
status = DeviceSettingsService::STORE_TEMP_VALIDATION_ERROR;
}
}
ReportResult(status);
}
LoadSettingsOperation::LoadSettingsOperation(const Callback& callback)
: SessionManagerOperation(callback) {}
LoadSettingsOperation::~LoadSettingsOperation() {}
void LoadSettingsOperation::Run() {
StartLoading();
}
StoreSettingsOperation::StoreSettingsOperation(
const Callback& callback,
scoped_ptr<em::PolicyFetchResponse> policy)
: SessionManagerOperation(callback),
policy_(policy.Pass()),
weak_factory_(this) {}
StoreSettingsOperation::~StoreSettingsOperation() {}
void StoreSettingsOperation::Run() {
session_manager_client()->StoreDevicePolicy(
policy_->SerializeAsString(),
base::Bind(&StoreSettingsOperation::HandleStoreResult,
weak_factory_.GetWeakPtr()));
}
void StoreSettingsOperation::HandleStoreResult(bool success) {
if (!success)
ReportResult(DeviceSettingsService::STORE_OPERATION_FAILED);
else
StartLoading();
}
SignAndStoreSettingsOperation::SignAndStoreSettingsOperation(
const Callback& callback,
scoped_ptr<em::ChromeDeviceSettingsProto> new_settings,
const std::string& username)
: SessionManagerOperation(callback),
new_settings_(new_settings.Pass()),
username_(username),
weak_factory_(this) {
DCHECK(new_settings_.get());
}
SignAndStoreSettingsOperation::~SignAndStoreSettingsOperation() {}
void SignAndStoreSettingsOperation::Run() {
EnsureOwnerKey(base::Bind(&SignAndStoreSettingsOperation::StartSigning,
weak_factory_.GetWeakPtr()));
}
void SignAndStoreSettingsOperation::StartSigning() {
if (!owner_key().get() || !owner_key()->private_key() || username_.empty()) {
ReportResult(DeviceSettingsService::STORE_KEY_UNAVAILABLE);
return;
}
base::PostTaskAndReplyWithResult(
content::BrowserThread::GetBlockingPool(),
FROM_HERE,
base::Bind(&SignAndStoreSettingsOperation::AssembleAndSignPolicy,
base::Passed(&new_settings_), username_, owner_key()),
base::Bind(&SignAndStoreSettingsOperation::StoreDeviceSettingsBlob,
weak_factory_.GetWeakPtr()));
}
// static
std::string SignAndStoreSettingsOperation::AssembleAndSignPolicy(
scoped_ptr<em::ChromeDeviceSettingsProto> device_settings,
const std::string& username,
scoped_refptr<OwnerKey> owner_key) {
// Assemble the policy.
em::PolicyFetchResponse policy_response;
em::PolicyData policy;
policy.set_policy_type(policy::dm_protocol::kChromeDevicePolicyType);
policy.set_timestamp((base::Time::NowFromSystemTime() -
base::Time::UnixEpoch()).InMilliseconds());
policy.set_username(username);
if (!device_settings->SerializeToString(policy.mutable_policy_value()) ||
!policy.SerializeToString(policy_response.mutable_policy_data())) {
LOG(ERROR) << "Failed to encode policy payload.";
return std::string();
}
// Generate the signature.
scoped_ptr<crypto::SignatureCreator> signature_creator(
crypto::SignatureCreator::Create(owner_key->private_key()));
signature_creator->Update(
reinterpret_cast<const uint8*>(policy_response.policy_data().c_str()),
policy_response.policy_data().size());
std::vector<uint8> signature_bytes;
std::string policy_blob;
if (!signature_creator->Final(&signature_bytes)) {
LOG(ERROR) << "Failed to create policy signature.";
return std::string();
}
policy_response.mutable_policy_data_signature()->assign(
reinterpret_cast<const char*>(vector_as_array(&signature_bytes)),
signature_bytes.size());
return policy_response.SerializeAsString();
}
void SignAndStoreSettingsOperation::StoreDeviceSettingsBlob(
std::string device_settings_blob) {
if (device_settings_blob.empty()) {
ReportResult(DeviceSettingsService::STORE_POLICY_ERROR);
return;
}
session_manager_client()->StoreDevicePolicy(
device_settings_blob,
base::Bind(&SignAndStoreSettingsOperation::HandleStoreResult,
weak_factory_.GetWeakPtr()));
}
void SignAndStoreSettingsOperation::HandleStoreResult(bool success) {
if (!success)
ReportResult(DeviceSettingsService::STORE_OPERATION_FAILED);
else
StartLoading();
}
} // namespace chromeos
|
// Copyright (c) 2012 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 "chrome/browser/chromeos/settings/session_manager_operation.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/files/file_path.h"
#include "base/message_loop/message_loop.h"
#include "base/stl_util.h"
#include "base/task_runner_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/time/time.h"
#include "chrome/browser/chromeos/settings/owner_key_util.h"
#include "chrome/browser/policy/cloud/cloud_policy_constants.h"
#include "chrome/browser/policy/proto/chromeos/chrome_device_policy.pb.h"
#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h"
#include "content/public/browser/browser_thread.h"
#include "crypto/rsa_private_key.h"
#include "crypto/signature_creator.h"
namespace em = enterprise_management;
namespace chromeos {
SessionManagerOperation::SessionManagerOperation(const Callback& callback)
: session_manager_client_(NULL),
weak_factory_(this),
callback_(callback),
force_key_load_(false),
is_loading_(false) {}
SessionManagerOperation::~SessionManagerOperation() {}
void SessionManagerOperation::Start(
SessionManagerClient* session_manager_client,
scoped_refptr<OwnerKeyUtil> owner_key_util,
scoped_refptr<OwnerKey> owner_key) {
session_manager_client_ = session_manager_client;
owner_key_util_ = owner_key_util;
owner_key_ = owner_key;
Run();
}
void SessionManagerOperation::RestartLoad(bool key_changed) {
if (key_changed)
owner_key_ = NULL;
if (!is_loading_)
return;
// Abort previous load operations.
weak_factory_.InvalidateWeakPtrs();
// Mark as not loading to start loading again.
is_loading_ = false;
StartLoading();
}
void SessionManagerOperation::StartLoading() {
if (is_loading_)
return;
is_loading_ = true;
EnsureOwnerKey(base::Bind(&SessionManagerOperation::RetrieveDeviceSettings,
weak_factory_.GetWeakPtr()));
}
void SessionManagerOperation::ReportResult(
DeviceSettingsService::Status status) {
callback_.Run(this, status);
}
void SessionManagerOperation::EnsureOwnerKey(const base::Closure& callback) {
if (force_key_load_ || !owner_key_.get() || !owner_key_->public_key()) {
scoped_refptr<base::TaskRunner> task_runner =
content::BrowserThread::GetBlockingPool()->
GetTaskRunnerWithShutdownBehavior(
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
base::PostTaskAndReplyWithResult(
task_runner.get(),
FROM_HERE,
base::Bind(&SessionManagerOperation::LoadOwnerKey,
owner_key_util_, owner_key_),
base::Bind(&SessionManagerOperation::StoreOwnerKey,
weak_factory_.GetWeakPtr(), callback));
} else {
callback.Run();
}
}
// static
scoped_refptr<OwnerKey> SessionManagerOperation::LoadOwnerKey(
scoped_refptr<OwnerKeyUtil> util,
scoped_refptr<OwnerKey> current_key) {
scoped_ptr<std::vector<uint8> > public_key;
scoped_ptr<crypto::RSAPrivateKey> private_key;
// Keep any already-existing keys.
if (current_key.get()) {
if (current_key->public_key())
public_key.reset(new std::vector<uint8>(*current_key->public_key()));
if (current_key->private_key())
private_key.reset(current_key->private_key()->Copy());
}
if (!public_key.get() && util->IsPublicKeyPresent()) {
public_key.reset(new std::vector<uint8>());
if (!util->ImportPublicKey(public_key.get()))
LOG(ERROR) << "Failed to load public owner key.";
}
if (public_key.get() && !private_key.get()) {
private_key.reset(util->FindPrivateKey(*public_key));
if (!private_key.get())
VLOG(1) << "Failed to load private owner key.";
}
return new OwnerKey(public_key.Pass(), private_key.Pass());
}
void SessionManagerOperation::StoreOwnerKey(const base::Closure& callback,
scoped_refptr<OwnerKey> new_key) {
force_key_load_ = false;
owner_key_ = new_key;
if (!owner_key_.get() || !owner_key_->public_key()) {
ReportResult(DeviceSettingsService::STORE_KEY_UNAVAILABLE);
return;
}
callback.Run();
}
void SessionManagerOperation::RetrieveDeviceSettings() {
session_manager_client()->RetrieveDevicePolicy(
base::Bind(&SessionManagerOperation::ValidateDeviceSettings,
weak_factory_.GetWeakPtr()));
}
void SessionManagerOperation::ValidateDeviceSettings(
const std::string& policy_blob) {
scoped_ptr<em::PolicyFetchResponse> policy(new em::PolicyFetchResponse());
if (policy_blob.empty()) {
ReportResult(DeviceSettingsService::STORE_NO_POLICY);
return;
}
if (!policy->ParseFromString(policy_blob) ||
!policy->IsInitialized()) {
ReportResult(DeviceSettingsService::STORE_INVALID_POLICY);
return;
}
base::SequencedWorkerPool* pool =
content::BrowserThread::GetBlockingPool();
scoped_refptr<base::SequencedTaskRunner> background_task_runner =
pool->GetSequencedTaskRunnerWithShutdownBehavior(
pool->GetSequenceToken(),
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
policy::DeviceCloudPolicyValidator* validator =
policy::DeviceCloudPolicyValidator::Create(policy.Pass(),
background_task_runner);
// Policy auto-generated by session manager doesn't include a timestamp, so we
// need to allow missing timestamps.
const bool require_timestamp =
policy_data_.get() && policy_data_->has_request_token();
validator->ValidateAgainstCurrentPolicy(
policy_data_.get(),
require_timestamp ?
policy::CloudPolicyValidatorBase::TIMESTAMP_REQUIRED :
policy::CloudPolicyValidatorBase::TIMESTAMP_NOT_REQUIRED,
policy::CloudPolicyValidatorBase::DM_TOKEN_NOT_REQUIRED);
validator->ValidatePolicyType(policy::dm_protocol::kChromeDevicePolicyType);
validator->ValidatePayload();
validator->ValidateSignature(*owner_key_->public_key(), false);
validator->StartValidation(
base::Bind(&SessionManagerOperation::ReportValidatorStatus,
weak_factory_.GetWeakPtr()));
}
void SessionManagerOperation::ReportValidatorStatus(
policy::DeviceCloudPolicyValidator* validator) {
DeviceSettingsService::Status status =
DeviceSettingsService::STORE_VALIDATION_ERROR;
if (validator->success()) {
status = DeviceSettingsService::STORE_SUCCESS;
policy_data_ = validator->policy_data().Pass();
device_settings_ = validator->payload().Pass();
} else {
LOG(ERROR) << "Policy validation failed: " << validator->status();
// Those are mostly caused by RTC loss and are recoverable.
if (validator->status() ==
policy::DeviceCloudPolicyValidator::VALIDATION_BAD_TIMESTAMP) {
status = DeviceSettingsService::STORE_TEMP_VALIDATION_ERROR;
}
}
ReportResult(status);
}
LoadSettingsOperation::LoadSettingsOperation(const Callback& callback)
: SessionManagerOperation(callback) {}
LoadSettingsOperation::~LoadSettingsOperation() {}
void LoadSettingsOperation::Run() {
StartLoading();
}
StoreSettingsOperation::StoreSettingsOperation(
const Callback& callback,
scoped_ptr<em::PolicyFetchResponse> policy)
: SessionManagerOperation(callback),
policy_(policy.Pass()),
weak_factory_(this) {}
StoreSettingsOperation::~StoreSettingsOperation() {}
void StoreSettingsOperation::Run() {
session_manager_client()->StoreDevicePolicy(
policy_->SerializeAsString(),
base::Bind(&StoreSettingsOperation::HandleStoreResult,
weak_factory_.GetWeakPtr()));
}
void StoreSettingsOperation::HandleStoreResult(bool success) {
if (!success)
ReportResult(DeviceSettingsService::STORE_OPERATION_FAILED);
else
StartLoading();
}
SignAndStoreSettingsOperation::SignAndStoreSettingsOperation(
const Callback& callback,
scoped_ptr<em::ChromeDeviceSettingsProto> new_settings,
const std::string& username)
: SessionManagerOperation(callback),
new_settings_(new_settings.Pass()),
username_(username),
weak_factory_(this) {
DCHECK(new_settings_.get());
}
SignAndStoreSettingsOperation::~SignAndStoreSettingsOperation() {}
void SignAndStoreSettingsOperation::Run() {
EnsureOwnerKey(base::Bind(&SignAndStoreSettingsOperation::StartSigning,
weak_factory_.GetWeakPtr()));
}
void SignAndStoreSettingsOperation::StartSigning() {
if (!owner_key().get() || !owner_key()->private_key() || username_.empty()) {
ReportResult(DeviceSettingsService::STORE_KEY_UNAVAILABLE);
return;
}
base::PostTaskAndReplyWithResult(
content::BrowserThread::GetBlockingPool(),
FROM_HERE,
base::Bind(&SignAndStoreSettingsOperation::AssembleAndSignPolicy,
base::Passed(&new_settings_), username_, owner_key()),
base::Bind(&SignAndStoreSettingsOperation::StoreDeviceSettingsBlob,
weak_factory_.GetWeakPtr()));
}
// static
std::string SignAndStoreSettingsOperation::AssembleAndSignPolicy(
scoped_ptr<em::ChromeDeviceSettingsProto> device_settings,
const std::string& username,
scoped_refptr<OwnerKey> owner_key) {
// Assemble the policy.
em::PolicyFetchResponse policy_response;
em::PolicyData policy;
policy.set_policy_type(policy::dm_protocol::kChromeDevicePolicyType);
policy.set_timestamp((base::Time::NowFromSystemTime() -
base::Time::UnixEpoch()).InMilliseconds());
policy.set_username(username);
if (!device_settings->SerializeToString(policy.mutable_policy_value()) ||
!policy.SerializeToString(policy_response.mutable_policy_data())) {
LOG(ERROR) << "Failed to encode policy payload.";
return std::string();
}
// Generate the signature.
scoped_ptr<crypto::SignatureCreator> signature_creator(
crypto::SignatureCreator::Create(owner_key->private_key()));
signature_creator->Update(
reinterpret_cast<const uint8*>(policy_response.policy_data().c_str()),
policy_response.policy_data().size());
std::vector<uint8> signature_bytes;
std::string policy_blob;
if (!signature_creator->Final(&signature_bytes)) {
LOG(ERROR) << "Failed to create policy signature.";
return std::string();
}
policy_response.mutable_policy_data_signature()->assign(
reinterpret_cast<const char*>(vector_as_array(&signature_bytes)),
signature_bytes.size());
return policy_response.SerializeAsString();
}
void SignAndStoreSettingsOperation::StoreDeviceSettingsBlob(
std::string device_settings_blob) {
if (device_settings_blob.empty()) {
ReportResult(DeviceSettingsService::STORE_POLICY_ERROR);
return;
}
session_manager_client()->StoreDevicePolicy(
device_settings_blob,
base::Bind(&SignAndStoreSettingsOperation::HandleStoreResult,
weak_factory_.GetWeakPtr()));
}
void SignAndStoreSettingsOperation::HandleStoreResult(bool success) {
if (!success)
ReportResult(DeviceSettingsService::STORE_OPERATION_FAILED);
else
StartLoading();
}
} // namespace chromeos
|
Use SKIP_ON_SHUTDOWN behavior for the task to load OwnerKey
|
Use SKIP_ON_SHUTDOWN behavior for the task to load OwnerKey
Try to load only once.
BUG=308636
Review URL: https://codereview.chromium.org/49983002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@231655 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
hgl888/chromium-crosswalk,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,dednal/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,jaruba/chromium.src,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,patrickm/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,M4sse/chromium.src,Just-D/chromium-1,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,M4sse/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,patrickm/chromium.src,ltilve/chromium,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,ltilve/chromium,Fireblend/chromium-crosswalk,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,dednal/chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,littlstar/chromium.src,M4sse/chromium.src,patrickm/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,markYoungH/chromium.src,Just-D/chromium-1,ChromiumWebApps/chromium,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,M4sse/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,jaruba/chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,ltilve/chromium,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,patrickm/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,dednal/chromium.src,patrickm/chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,ChromiumWebApps/chromium,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,anirudhSK/chromium,Chilledheart/chromium,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,littlstar/chromium.src,dednal/chromium.src,M4sse/chromium.src,patrickm/chromium.src,chuan9/chromium-crosswalk,littlstar/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,ltilve/chromium,ltilve/chromium,axinging/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,M4sse/chromium.src,ltilve/chromium,anirudhSK/chromium,Jonekee/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,ChromiumWebApps/chromium,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,Just-D/chromium-1,jaruba/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,chuan9/chromium-crosswalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,Chilledheart/chromium,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,dednal/chromium.src,Chilledheart/chromium,jaruba/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,dednal/chromium.src,dushu1203/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk,dushu1203/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,ltilve/chromium,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,ltilve/chromium,dednal/chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,Just-D/chromium-1,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,jaruba/chromium.src
|
55c6e8d4ea29e26c58ee8cba7a48abb423ff108a
|
Library/Sources/Stroika/Foundation/Memory/MemoryAllocator.inl
|
Library/Sources/Stroika/Foundation/Memory/MemoryAllocator.inl
|
/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#ifndef _Stroika_Foundation_Memory_MemoryAllocator_inl_
#define _Stroika_Foundation_Memory_MemoryAllocator_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika {
namespace Foundation {
namespace Memory {
// class Memory::AbstractGeneralPurposeAllocator
inline AbstractGeneralPurposeAllocator::~AbstractGeneralPurposeAllocator ()
{
}
// class Memory::STLAllocator<T,BASE_ALLOCATOR>
template <typename T, typename BASE_ALLOCATOR>
inline typename STLAllocator<T,BASE_ALLOCATOR>::pointer STLAllocator<T,BASE_ALLOCATOR>::address (typename STLAllocator<T,BASE_ALLOCATOR>::reference _Val) const
{
return (&_Val);
}
template <typename T, typename BASE_ALLOCATOR>
inline typename STLAllocator<T,BASE_ALLOCATOR>::const_pointer STLAllocator<T,BASE_ALLOCATOR>::address (typename STLAllocator<T,BASE_ALLOCATOR>::const_reference _Val) const
{
return (&_Val);
}
template <typename T, typename BASE_ALLOCATOR>
inline STLAllocator<T,BASE_ALLOCATOR>::STLAllocator ()
: fBaseAllocator ()
{
}
template <typename T, typename BASE_ALLOCATOR>
inline STLAllocator<T,BASE_ALLOCATOR>::STLAllocator (const STLAllocator<T,BASE_ALLOCATOR>& from)
: fBaseAllocator (from.fBaseAllocator)
{
}
template <typename T, typename BASE_ALLOCATOR>
template <typename OTHER>
inline STLAllocator<T,BASE_ALLOCATOR>::STLAllocator(const STLAllocator<OTHER, BASE_ALLOCATOR>& from)
: fBaseAllocator (from.fBaseAllocator)
{
}
template <typename T, typename BASE_ALLOCATOR>
template <typename OTHER>
inline STLAllocator<T,BASE_ALLOCATOR>& STLAllocator<T,BASE_ALLOCATOR>::operator= (const STLAllocator<OTHER,BASE_ALLOCATOR>& rhs)
{
fBaseAllocator = rhs.from.fBaseAllocator;
return (*this);
}
template <typename T, typename BASE_ALLOCATOR>
inline typename STLAllocator<T,BASE_ALLOCATOR>::pointer STLAllocator<T,BASE_ALLOCATOR>::allocate (size_type nElements)
{
// allocate storage for _Count elements of type T
return ((T*)fBaseAllocator.Allocate (nElements * sizeof (T)));
}
template <typename T, typename BASE_ALLOCATOR>
inline typename STLAllocator<T,BASE_ALLOCATOR>::pointer STLAllocator<T,BASE_ALLOCATOR>::allocate (size_type nElements, const void*)
{
return (allocate (n));
}
template <typename T, typename BASE_ALLOCATOR>
inline void STLAllocator<T,BASE_ALLOCATOR>::deallocate (pointer ptr, size_type)
{
if (ptr != NULL) {
fBaseAllocator.Deallocate (ptr);
}
}
template <typename T, typename BASE_ALLOCATOR>
inline void STLAllocator<T,BASE_ALLOCATOR>::construct (pointer ptr, const T& v)
{
new (ptr) T (v);
}
template <typename T, typename BASE_ALLOCATOR>
inline void STLAllocator<T,BASE_ALLOCATOR>::destroy (pointer p)
{
p->~T ();
}
template <typename T, typename BASE_ALLOCATOR>
inline size_t STLAllocator<T,BASE_ALLOCATOR>::max_size () const throw ()
{
return numeric_limits<size_type>::max () / sizeof (T);
}
template <typename T, typename BASE_ALLOCATOR>
inline bool STLAllocator<T,BASE_ALLOCATOR>::operator== (const STLAllocator<T,BASE_ALLOCATOR>& rhs) const
{
return true;
}
template <typename T, typename BASE_ALLOCATOR>
inline bool STLAllocator<T,BASE_ALLOCATOR>::operator!= (const STLAllocator<T,BASE_ALLOCATOR>& rhs) const
{
return !operator== (rhs);
}
}
}
}
#endif /*_Stroika_Foundation_Memory_MemoryAllocator_inl_*/
|
/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#ifndef _Stroika_Foundation_Memory_MemoryAllocator_inl_
#define _Stroika_Foundation_Memory_MemoryAllocator_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika {
namespace Foundation {
namespace Memory {
// class Memory::AbstractGeneralPurposeAllocator
inline AbstractGeneralPurposeAllocator::~AbstractGeneralPurposeAllocator ()
{
}
// class Memory::STLAllocator<T,BASE_ALLOCATOR>
template <typename T, typename BASE_ALLOCATOR>
inline typename STLAllocator<T,BASE_ALLOCATOR>::pointer STLAllocator<T,BASE_ALLOCATOR>::address (typename STLAllocator<T,BASE_ALLOCATOR>::reference _Val) const
{
return (&_Val);
}
template <typename T, typename BASE_ALLOCATOR>
inline typename STLAllocator<T,BASE_ALLOCATOR>::const_pointer STLAllocator<T,BASE_ALLOCATOR>::address (typename STLAllocator<T,BASE_ALLOCATOR>::const_reference _Val) const
{
return (&_Val);
}
template <typename T, typename BASE_ALLOCATOR>
inline STLAllocator<T,BASE_ALLOCATOR>::STLAllocator ()
: fBaseAllocator ()
{
}
template <typename T, typename BASE_ALLOCATOR>
inline STLAllocator<T,BASE_ALLOCATOR>::STLAllocator (const STLAllocator<T,BASE_ALLOCATOR>& from)
: fBaseAllocator (from.fBaseAllocator)
{
}
template <typename T, typename BASE_ALLOCATOR>
template <typename OTHER>
inline STLAllocator<T,BASE_ALLOCATOR>::STLAllocator(const STLAllocator<OTHER, BASE_ALLOCATOR>& from)
: fBaseAllocator (from.fBaseAllocator)
{
}
template <typename T, typename BASE_ALLOCATOR>
template <typename OTHER>
inline STLAllocator<T,BASE_ALLOCATOR>& STLAllocator<T,BASE_ALLOCATOR>::operator= (const STLAllocator<OTHER,BASE_ALLOCATOR>& rhs)
{
fBaseAllocator = rhs.from.fBaseAllocator;
return (*this);
}
template <typename T, typename BASE_ALLOCATOR>
inline typename STLAllocator<T,BASE_ALLOCATOR>::pointer STLAllocator<T,BASE_ALLOCATOR>::allocate (size_type nElements)
{
// allocate storage for _Count elements of type T
return ((T*)fBaseAllocator.Allocate (nElements * sizeof (T)));
}
template <typename T, typename BASE_ALLOCATOR>
inline typename STLAllocator<T,BASE_ALLOCATOR>::pointer STLAllocator<T,BASE_ALLOCATOR>::allocate (size_type nElements, const void*)
{
return (allocate (nElements));
}
template <typename T, typename BASE_ALLOCATOR>
inline void STLAllocator<T,BASE_ALLOCATOR>::deallocate (pointer ptr, size_type)
{
if (ptr != NULL) {
fBaseAllocator.Deallocate (ptr);
}
}
template <typename T, typename BASE_ALLOCATOR>
inline void STLAllocator<T,BASE_ALLOCATOR>::construct (pointer ptr, const T& v)
{
new (ptr) T (v);
}
template <typename T, typename BASE_ALLOCATOR>
inline void STLAllocator<T,BASE_ALLOCATOR>::destroy (pointer p)
{
p->~T ();
}
template <typename T, typename BASE_ALLOCATOR>
inline size_t STLAllocator<T,BASE_ALLOCATOR>::max_size () const throw ()
{
return numeric_limits<size_type>::max () / sizeof (T);
}
template <typename T, typename BASE_ALLOCATOR>
inline bool STLAllocator<T,BASE_ALLOCATOR>::operator== (const STLAllocator<T,BASE_ALLOCATOR>& rhs) const
{
return true;
}
template <typename T, typename BASE_ALLOCATOR>
inline bool STLAllocator<T,BASE_ALLOCATOR>::operator!= (const STLAllocator<T,BASE_ALLOCATOR>& rhs) const
{
return !operator== (rhs);
}
}
}
}
#endif /*_Stroika_Foundation_Memory_MemoryAllocator_inl_*/
|
fix small error in MemoryAllocator.inl
|
fix small error in MemoryAllocator.inl
|
C++
|
mit
|
SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika
|
4c49fedaf15bca9f8cb82d92a8dc934e7d1a3309
|
util/thread_local.cc
|
util/thread_local.cc
|
// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "util/thread_local.h"
#include "util/mutexlock.h"
#include "port/likely.h"
#include <stdlib.h>
namespace rocksdb {
port::Mutex ThreadLocalPtr::StaticMeta::mutex_;
#if !defined(OS_MACOSX)
__thread ThreadLocalPtr::ThreadData* ThreadLocalPtr::StaticMeta::tls_ = nullptr;
#endif
ThreadLocalPtr::StaticMeta* ThreadLocalPtr::Instance() {
static ThreadLocalPtr::StaticMeta inst;
return &inst;
}
void ThreadLocalPtr::StaticMeta::OnThreadExit(void* ptr) {
auto* tls = static_cast<ThreadData*>(ptr);
assert(tls != nullptr);
auto* inst = Instance();
pthread_setspecific(inst->pthread_key_, nullptr);
MutexLock l(&mutex_);
inst->RemoveThreadData(tls);
// Unref stored pointers of current thread from all instances
uint32_t id = 0;
for (auto& e : tls->entries) {
void* raw = e.ptr.load(std::memory_order_relaxed);
if (raw != nullptr) {
auto unref = inst->GetHandler(id);
if (unref != nullptr) {
unref(raw);
}
}
++id;
}
// Delete thread local structure no matter if it is Mac platform
delete tls;
}
ThreadLocalPtr::StaticMeta::StaticMeta() : next_instance_id_(0) {
if (pthread_key_create(&pthread_key_, &OnThreadExit) != 0) {
abort();
}
head_.next = &head_;
head_.prev = &head_;
}
void ThreadLocalPtr::StaticMeta::AddThreadData(ThreadLocalPtr::ThreadData* d) {
mutex_.AssertHeld();
d->next = &head_;
d->prev = head_.prev;
head_.prev->next = d;
head_.prev = d;
}
void ThreadLocalPtr::StaticMeta::RemoveThreadData(
ThreadLocalPtr::ThreadData* d) {
mutex_.AssertHeld();
d->next->prev = d->prev;
d->prev->next = d->next;
d->next = d->prev = d;
}
ThreadLocalPtr::ThreadData* ThreadLocalPtr::StaticMeta::GetThreadLocal() {
#if defined(OS_MACOSX)
// Make this local variable name look like a member variable so that we
// can share all the code below
ThreadData* tls_ =
static_cast<ThreadData*>(pthread_getspecific(Instance()->pthread_key_));
#endif
if (UNLIKELY(tls_ == nullptr)) {
auto* inst = Instance();
tls_ = new ThreadData();
{
// Register it in the global chain, needs to be done before thread exit
// handler registration
MutexLock l(&mutex_);
inst->AddThreadData(tls_);
}
// Even it is not OS_MACOSX, need to register value for pthread_key_ so that
// its exit handler will be triggered.
if (pthread_setspecific(inst->pthread_key_, tls_) != 0) {
{
MutexLock l(&mutex_);
inst->RemoveThreadData(tls_);
}
delete tls_;
abort();
}
}
return tls_;
}
void* ThreadLocalPtr::StaticMeta::Get(uint32_t id) const {
auto* tls = GetThreadLocal();
if (UNLIKELY(id >= tls->entries.size())) {
return nullptr;
}
return tls->entries[id].ptr.load(std::memory_order_relaxed);
}
void ThreadLocalPtr::StaticMeta::Reset(uint32_t id, void* ptr) {
auto* tls = GetThreadLocal();
if (UNLIKELY(id >= tls->entries.size())) {
// Need mutex to protect entries access within ReclaimId
MutexLock l(&mutex_);
tls->entries.resize(id + 1);
}
tls->entries[id].ptr.store(ptr, std::memory_order_relaxed);
}
void* ThreadLocalPtr::StaticMeta::Swap(uint32_t id, void* ptr) {
auto* tls = GetThreadLocal();
if (UNLIKELY(id >= tls->entries.size())) {
// Need mutex to protect entries access within ReclaimId
MutexLock l(&mutex_);
tls->entries.resize(id + 1);
}
return tls->entries[id].ptr.exchange(ptr, std::memory_order_relaxed);
}
bool ThreadLocalPtr::StaticMeta::CompareAndSwap(uint32_t id, void* ptr,
void*& expected) {
auto* tls = GetThreadLocal();
if (UNLIKELY(id >= tls->entries.size())) {
// Need mutex to protect entries access within ReclaimId
MutexLock l(&mutex_);
tls->entries.resize(id + 1);
}
return tls->entries[id].ptr.compare_exchange_strong(expected, ptr,
std::memory_order_relaxed, std::memory_order_relaxed);
}
void ThreadLocalPtr::StaticMeta::Scrape(uint32_t id, autovector<void*>* ptrs,
void* const replacement) {
MutexLock l(&mutex_);
for (ThreadData* t = head_.next; t != &head_; t = t->next) {
if (id < t->entries.size()) {
void* ptr =
t->entries[id].ptr.exchange(replacement, std::memory_order_relaxed);
if (ptr != nullptr) {
ptrs->push_back(ptr);
}
}
}
}
void ThreadLocalPtr::StaticMeta::SetHandler(uint32_t id, UnrefHandler handler) {
MutexLock l(&mutex_);
handler_map_[id] = handler;
}
UnrefHandler ThreadLocalPtr::StaticMeta::GetHandler(uint32_t id) {
mutex_.AssertHeld();
auto iter = handler_map_.find(id);
if (iter == handler_map_.end()) {
return nullptr;
}
return iter->second;
}
uint32_t ThreadLocalPtr::StaticMeta::GetId() {
MutexLock l(&mutex_);
if (free_instance_ids_.empty()) {
return next_instance_id_++;
}
uint32_t id = free_instance_ids_.back();
free_instance_ids_.pop_back();
return id;
}
uint32_t ThreadLocalPtr::StaticMeta::PeekId() const {
MutexLock l(&mutex_);
if (!free_instance_ids_.empty()) {
return free_instance_ids_.back();
}
return next_instance_id_;
}
void ThreadLocalPtr::StaticMeta::ReclaimId(uint32_t id) {
// This id is not used, go through all thread local data and release
// corresponding value
MutexLock l(&mutex_);
auto unref = GetHandler(id);
for (ThreadData* t = head_.next; t != &head_; t = t->next) {
if (id < t->entries.size()) {
void* ptr =
t->entries[id].ptr.exchange(nullptr, std::memory_order_relaxed);
if (ptr != nullptr && unref != nullptr) {
unref(ptr);
}
}
}
handler_map_[id] = nullptr;
free_instance_ids_.push_back(id);
}
ThreadLocalPtr::ThreadLocalPtr(UnrefHandler handler)
: id_(Instance()->GetId()) {
if (handler != nullptr) {
Instance()->SetHandler(id_, handler);
}
}
ThreadLocalPtr::~ThreadLocalPtr() {
Instance()->ReclaimId(id_);
}
void* ThreadLocalPtr::Get() const {
return Instance()->Get(id_);
}
void ThreadLocalPtr::Reset(void* ptr) {
Instance()->Reset(id_, ptr);
}
void* ThreadLocalPtr::Swap(void* ptr) {
return Instance()->Swap(id_, ptr);
}
bool ThreadLocalPtr::CompareAndSwap(void* ptr, void*& expected) {
return Instance()->CompareAndSwap(id_, ptr, expected);
}
void ThreadLocalPtr::Scrape(autovector<void*>* ptrs, void* const replacement) {
Instance()->Scrape(id_, ptrs, replacement);
}
} // namespace rocksdb
|
// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "util/thread_local.h"
#include "util/mutexlock.h"
#include "port/likely.h"
#include <stdlib.h>
namespace rocksdb {
port::Mutex ThreadLocalPtr::StaticMeta::mutex_;
#if !defined(OS_MACOSX)
__thread ThreadLocalPtr::ThreadData* ThreadLocalPtr::StaticMeta::tls_ = nullptr;
#endif
ThreadLocalPtr::StaticMeta* ThreadLocalPtr::Instance() {
static ThreadLocalPtr::StaticMeta inst;
return &inst;
}
void ThreadLocalPtr::StaticMeta::OnThreadExit(void* ptr) {
auto* tls = static_cast<ThreadData*>(ptr);
assert(tls != nullptr);
auto* inst = Instance();
pthread_setspecific(inst->pthread_key_, nullptr);
MutexLock l(&mutex_);
inst->RemoveThreadData(tls);
// Unref stored pointers of current thread from all instances
uint32_t id = 0;
for (auto& e : tls->entries) {
void* raw = e.ptr.load();
if (raw != nullptr) {
auto unref = inst->GetHandler(id);
if (unref != nullptr) {
unref(raw);
}
}
++id;
}
// Delete thread local structure no matter if it is Mac platform
delete tls;
}
ThreadLocalPtr::StaticMeta::StaticMeta() : next_instance_id_(0) {
if (pthread_key_create(&pthread_key_, &OnThreadExit) != 0) {
abort();
}
head_.next = &head_;
head_.prev = &head_;
}
void ThreadLocalPtr::StaticMeta::AddThreadData(ThreadLocalPtr::ThreadData* d) {
mutex_.AssertHeld();
d->next = &head_;
d->prev = head_.prev;
head_.prev->next = d;
head_.prev = d;
}
void ThreadLocalPtr::StaticMeta::RemoveThreadData(
ThreadLocalPtr::ThreadData* d) {
mutex_.AssertHeld();
d->next->prev = d->prev;
d->prev->next = d->next;
d->next = d->prev = d;
}
ThreadLocalPtr::ThreadData* ThreadLocalPtr::StaticMeta::GetThreadLocal() {
#if defined(OS_MACOSX)
// Make this local variable name look like a member variable so that we
// can share all the code below
ThreadData* tls_ =
static_cast<ThreadData*>(pthread_getspecific(Instance()->pthread_key_));
#endif
if (UNLIKELY(tls_ == nullptr)) {
auto* inst = Instance();
tls_ = new ThreadData();
{
// Register it in the global chain, needs to be done before thread exit
// handler registration
MutexLock l(&mutex_);
inst->AddThreadData(tls_);
}
// Even it is not OS_MACOSX, need to register value for pthread_key_ so that
// its exit handler will be triggered.
if (pthread_setspecific(inst->pthread_key_, tls_) != 0) {
{
MutexLock l(&mutex_);
inst->RemoveThreadData(tls_);
}
delete tls_;
abort();
}
}
return tls_;
}
void* ThreadLocalPtr::StaticMeta::Get(uint32_t id) const {
auto* tls = GetThreadLocal();
if (UNLIKELY(id >= tls->entries.size())) {
return nullptr;
}
return tls->entries[id].ptr.load(std::memory_order_acquire);
}
void ThreadLocalPtr::StaticMeta::Reset(uint32_t id, void* ptr) {
auto* tls = GetThreadLocal();
if (UNLIKELY(id >= tls->entries.size())) {
// Need mutex to protect entries access within ReclaimId
MutexLock l(&mutex_);
tls->entries.resize(id + 1);
}
tls->entries[id].ptr.store(ptr, std::memory_order_release);
}
void* ThreadLocalPtr::StaticMeta::Swap(uint32_t id, void* ptr) {
auto* tls = GetThreadLocal();
if (UNLIKELY(id >= tls->entries.size())) {
// Need mutex to protect entries access within ReclaimId
MutexLock l(&mutex_);
tls->entries.resize(id + 1);
}
return tls->entries[id].ptr.exchange(ptr, std::memory_order_acquire);
}
bool ThreadLocalPtr::StaticMeta::CompareAndSwap(uint32_t id, void* ptr,
void*& expected) {
auto* tls = GetThreadLocal();
if (UNLIKELY(id >= tls->entries.size())) {
// Need mutex to protect entries access within ReclaimId
MutexLock l(&mutex_);
tls->entries.resize(id + 1);
}
return tls->entries[id].ptr.compare_exchange_strong(
expected, ptr, std::memory_order_release, std::memory_order_relaxed);
}
void ThreadLocalPtr::StaticMeta::Scrape(uint32_t id, autovector<void*>* ptrs,
void* const replacement) {
MutexLock l(&mutex_);
for (ThreadData* t = head_.next; t != &head_; t = t->next) {
if (id < t->entries.size()) {
void* ptr =
t->entries[id].ptr.exchange(replacement, std::memory_order_acquire);
if (ptr != nullptr) {
ptrs->push_back(ptr);
}
}
}
}
void ThreadLocalPtr::StaticMeta::SetHandler(uint32_t id, UnrefHandler handler) {
MutexLock l(&mutex_);
handler_map_[id] = handler;
}
UnrefHandler ThreadLocalPtr::StaticMeta::GetHandler(uint32_t id) {
mutex_.AssertHeld();
auto iter = handler_map_.find(id);
if (iter == handler_map_.end()) {
return nullptr;
}
return iter->second;
}
uint32_t ThreadLocalPtr::StaticMeta::GetId() {
MutexLock l(&mutex_);
if (free_instance_ids_.empty()) {
return next_instance_id_++;
}
uint32_t id = free_instance_ids_.back();
free_instance_ids_.pop_back();
return id;
}
uint32_t ThreadLocalPtr::StaticMeta::PeekId() const {
MutexLock l(&mutex_);
if (!free_instance_ids_.empty()) {
return free_instance_ids_.back();
}
return next_instance_id_;
}
void ThreadLocalPtr::StaticMeta::ReclaimId(uint32_t id) {
// This id is not used, go through all thread local data and release
// corresponding value
MutexLock l(&mutex_);
auto unref = GetHandler(id);
for (ThreadData* t = head_.next; t != &head_; t = t->next) {
if (id < t->entries.size()) {
void* ptr = t->entries[id].ptr.exchange(nullptr);
if (ptr != nullptr && unref != nullptr) {
unref(ptr);
}
}
}
handler_map_[id] = nullptr;
free_instance_ids_.push_back(id);
}
ThreadLocalPtr::ThreadLocalPtr(UnrefHandler handler)
: id_(Instance()->GetId()) {
if (handler != nullptr) {
Instance()->SetHandler(id_, handler);
}
}
ThreadLocalPtr::~ThreadLocalPtr() {
Instance()->ReclaimId(id_);
}
void* ThreadLocalPtr::Get() const {
return Instance()->Get(id_);
}
void ThreadLocalPtr::Reset(void* ptr) {
Instance()->Reset(id_, ptr);
}
void* ThreadLocalPtr::Swap(void* ptr) {
return Instance()->Swap(id_, ptr);
}
bool ThreadLocalPtr::CompareAndSwap(void* ptr, void*& expected) {
return Instance()->CompareAndSwap(id_, ptr, expected);
}
void ThreadLocalPtr::Scrape(autovector<void*>* ptrs, void* const replacement) {
Instance()->Scrape(id_, ptrs, replacement);
}
} // namespace rocksdb
|
Use ustricter consistency in thread local operations
|
Use ustricter consistency in thread local operations
Summary:
ThreadSanitizer complains data race of super version and version's destructor with Get(). This patch will fix those warning.
The warning is likely from ColumnFamilyData::ReturnThreadLocalSuperVersion(). With relaxed consistency of CAS, reading the data of the super version can technically happen after swapping it in, enabling the background thread to clean it up.
Test Plan: make all check
Reviewers: rven, igor, yhchiang
Reviewed By: yhchiang
Subscribers: leveldb, dhruba
Differential Revision: https://reviews.facebook.net/D32265
|
C++
|
bsd-3-clause
|
facebook/rocksdb,biddyweb/rocksdb,hobinyoon/rocksdb,ryneli/rocksdb,luckywhu/rocksdb,vmx/rocksdb,facebook/rocksdb,alihalabyah/rocksdb,jalexanderqed/rocksdb,temicai/rocksdb,Applied-Duality/rocksdb,vashstorm/rocksdb,virtdb/rocksdb,wskplho/rocksdb,siddhartharay007/rocksdb,wenduo/rocksdb,Vaisman/rocksdb,SunguckLee/RocksDB,flabby/rocksdb,wat-ze-hex/rocksdb,wat-ze-hex/rocksdb,anagav/rocksdb,wlqGit/rocksdb,luckywhu/rocksdb,siddhartharay007/rocksdb,wat-ze-hex/rocksdb,sorphi/rocksdb,jalexanderqed/rocksdb,ryneli/rocksdb,Applied-Duality/rocksdb,norton/rocksdb,biddyweb/rocksdb,amyvmiwei/rocksdb,zhangpng/rocksdb,JoeWoo/rocksdb,norton/rocksdb,fengshao0907/rocksdb,kaschaeffer/rocksdb,lgscofield/rocksdb,alihalabyah/rocksdb,dkorolev/rocksdb,JohnPJenkins/rocksdb,rDSN-Projects/rocksdb.replicated,dkorolev/rocksdb,Applied-Duality/rocksdb,sorphi/rocksdb,norton/rocksdb,lgscofield/rocksdb,Andymic/rocksdb,geraldoandradee/rocksdb,dkorolev/rocksdb,OverlordQ/rocksdb,amyvmiwei/rocksdb,JoeWoo/rocksdb,facebook/rocksdb,bbiao/rocksdb,Applied-Duality/rocksdb,RyanTech/rocksdb,wenduo/rocksdb,skunkwerks/rocksdb,alihalabyah/rocksdb,IMCG/RcoksDB,hobinyoon/rocksdb,ryneli/rocksdb,JackLian/rocksdb,Andymic/rocksdb,zhangpng/rocksdb,biddyweb/rocksdb,kaschaeffer/rocksdb,wlqGit/rocksdb,rDSN-Projects/rocksdb.replicated,NickCis/rocksdb,alihalabyah/rocksdb,norton/rocksdb,wat-ze-hex/rocksdb,sorphi/rocksdb,luckywhu/rocksdb,tsheasha/rocksdb,Andymic/rocksdb,ylong/rocksdb,mbarbon/rocksdb,virtdb/rocksdb,anagav/rocksdb,wskplho/rocksdb,Andymic/rocksdb,makelivedotnet/rocksdb,anagav/rocksdb,anagav/rocksdb,skunkwerks/rocksdb,hobinyoon/rocksdb,caijieming-baidu/rocksdb,lgscofield/rocksdb,IMCG/RcoksDB,ylong/rocksdb,JackLian/rocksdb,wlqGit/rocksdb,temicai/rocksdb,zhangpng/rocksdb,sorphi/rocksdb,jalexanderqed/rocksdb,tsheasha/rocksdb,NickCis/rocksdb,NickCis/rocksdb,JoeWoo/rocksdb,zhangpng/rocksdb,RyanTech/rocksdb,kaschaeffer/rocksdb,norton/rocksdb,hobinyoon/rocksdb,alihalabyah/rocksdb,vashstorm/rocksdb,wskplho/rocksdb,wskplho/rocksdb,lgscofield/rocksdb,virtdb/rocksdb,amyvmiwei/rocksdb,kaschaeffer/rocksdb,zhangpng/rocksdb,rDSN-Projects/rocksdb.replicated,kaschaeffer/rocksdb,OverlordQ/rocksdb,tizzybec/rocksdb,tizzybec/rocksdb,geraldoandradee/rocksdb,vashstorm/rocksdb,tsheasha/rocksdb,JoeWoo/rocksdb,siddhartharay007/rocksdb,NickCis/rocksdb,temicai/rocksdb,geraldoandradee/rocksdb,RyanTech/rocksdb,bbiao/rocksdb,fengshao0907/rocksdb,geraldoandradee/rocksdb,kaschaeffer/rocksdb,bbiao/rocksdb,amyvmiwei/rocksdb,fengshao0907/rocksdb,lgscofield/rocksdb,makelivedotnet/rocksdb,wenduo/rocksdb,Applied-Duality/rocksdb,ylong/rocksdb,JackLian/rocksdb,skunkwerks/rocksdb,wenduo/rocksdb,jalexanderqed/rocksdb,norton/rocksdb,facebook/rocksdb,ryneli/rocksdb,amyvmiwei/rocksdb,RyanTech/rocksdb,JoeWoo/rocksdb,zhangpng/rocksdb,ryneli/rocksdb,siddhartharay007/rocksdb,JohnPJenkins/rocksdb,virtdb/rocksdb,jalexanderqed/rocksdb,caijieming-baidu/rocksdb,anagav/rocksdb,IMCG/RcoksDB,facebook/rocksdb,SunguckLee/RocksDB,NickCis/rocksdb,fengshao0907/rocksdb,JohnPJenkins/rocksdb,vashstorm/rocksdb,JoeWoo/rocksdb,Vaisman/rocksdb,hobinyoon/rocksdb,wenduo/rocksdb,makelivedotnet/rocksdb,virtdb/rocksdb,dkorolev/rocksdb,anagav/rocksdb,amyvmiwei/rocksdb,vashstorm/rocksdb,wlqGit/rocksdb,Andymic/rocksdb,SunguckLee/RocksDB,amyvmiwei/rocksdb,NickCis/rocksdb,Vaisman/rocksdb,Vaisman/rocksdb,wlqGit/rocksdb,sorphi/rocksdb,anagav/rocksdb,makelivedotnet/rocksdb,wlqGit/rocksdb,virtdb/rocksdb,hobinyoon/rocksdb,tsheasha/rocksdb,luckywhu/rocksdb,tizzybec/rocksdb,flabby/rocksdb,tizzybec/rocksdb,tsheasha/rocksdb,OverlordQ/rocksdb,bbiao/rocksdb,luckywhu/rocksdb,ylong/rocksdb,Andymic/rocksdb,fengshao0907/rocksdb,mbarbon/rocksdb,Vaisman/rocksdb,temicai/rocksdb,tizzybec/rocksdb,makelivedotnet/rocksdb,dkorolev/rocksdb,hobinyoon/rocksdb,rDSN-Projects/rocksdb.replicated,OverlordQ/rocksdb,JohnPJenkins/rocksdb,wskplho/rocksdb,jalexanderqed/rocksdb,facebook/rocksdb,JoeWoo/rocksdb,bbiao/rocksdb,OverlordQ/rocksdb,temicai/rocksdb,ryneli/rocksdb,geraldoandradee/rocksdb,mbarbon/rocksdb,wat-ze-hex/rocksdb,zhangpng/rocksdb,hobinyoon/rocksdb,IMCG/RcoksDB,bbiao/rocksdb,skunkwerks/rocksdb,skunkwerks/rocksdb,temicai/rocksdb,JackLian/rocksdb,SunguckLee/RocksDB,tsheasha/rocksdb,kaschaeffer/rocksdb,biddyweb/rocksdb,bbiao/rocksdb,flabby/rocksdb,siddhartharay007/rocksdb,flabby/rocksdb,luckywhu/rocksdb,wenduo/rocksdb,vmx/rocksdb,rDSN-Projects/rocksdb.replicated,caijieming-baidu/rocksdb,bbiao/rocksdb,temicai/rocksdb,SunguckLee/RocksDB,vmx/rocksdb,Applied-Duality/rocksdb,vmx/rocksdb,siddhartharay007/rocksdb,IMCG/RcoksDB,fengshao0907/rocksdb,JackLian/rocksdb,sorphi/rocksdb,flabby/rocksdb,JohnPJenkins/rocksdb,tsheasha/rocksdb,mbarbon/rocksdb,vmx/rocksdb,SunguckLee/RocksDB,wskplho/rocksdb,luckywhu/rocksdb,lgscofield/rocksdb,Vaisman/rocksdb,caijieming-baidu/rocksdb,tsheasha/rocksdb,dkorolev/rocksdb,virtdb/rocksdb,JackLian/rocksdb,vmx/rocksdb,IMCG/RcoksDB,SunguckLee/RocksDB,wenduo/rocksdb,vmx/rocksdb,geraldoandradee/rocksdb,IMCG/RcoksDB,facebook/rocksdb,OverlordQ/rocksdb,ryneli/rocksdb,caijieming-baidu/rocksdb,JackLian/rocksdb,vashstorm/rocksdb,makelivedotnet/rocksdb,sorphi/rocksdb,flabby/rocksdb,biddyweb/rocksdb,vmx/rocksdb,norton/rocksdb,wskplho/rocksdb,facebook/rocksdb,biddyweb/rocksdb,Vaisman/rocksdb,Andymic/rocksdb,dkorolev/rocksdb,ylong/rocksdb,mbarbon/rocksdb,wat-ze-hex/rocksdb,JohnPJenkins/rocksdb,RyanTech/rocksdb,RyanTech/rocksdb,fengshao0907/rocksdb,alihalabyah/rocksdb,jalexanderqed/rocksdb,flabby/rocksdb,skunkwerks/rocksdb,ylong/rocksdb,wat-ze-hex/rocksdb,alihalabyah/rocksdb,NickCis/rocksdb,Andymic/rocksdb,rDSN-Projects/rocksdb.replicated,vashstorm/rocksdb,tizzybec/rocksdb,wlqGit/rocksdb,RyanTech/rocksdb,mbarbon/rocksdb,SunguckLee/RocksDB,mbarbon/rocksdb,rDSN-Projects/rocksdb.replicated,caijieming-baidu/rocksdb,makelivedotnet/rocksdb,wat-ze-hex/rocksdb,norton/rocksdb,OverlordQ/rocksdb,caijieming-baidu/rocksdb,ylong/rocksdb,tizzybec/rocksdb,lgscofield/rocksdb,siddhartharay007/rocksdb,biddyweb/rocksdb,skunkwerks/rocksdb,Applied-Duality/rocksdb,wenduo/rocksdb,geraldoandradee/rocksdb,JohnPJenkins/rocksdb
|
8e8fcada6fe7e10b661e27d886079467da04afef
|
sxc-register/src/Registerer.cxx
|
sxc-register/src/Registerer.cxx
|
// LICENSE/*{{{*/
/*
sxc-tools
Copyright (C) 2008 Dennis Felsing, Andreas Waidler
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*}}}*/
// INCLUDE/*{{{*/
#include <gloox/client.h>
#include <gloox/connectionlistener.h>
#include <gloox/registration.h>
#include <libsxc/generateString.hxx>
#include <iostream>
#include <string>
#include <cstdio> // stdin
#include <stdexcept> // std::runtime_error
#include <termios.h> // struct termios
#include <stdio.h> // fileno()
#include <string.h> // strerror()
#include <errno.h> // errno
#include <Registerer.hxx>
#ifdef HAVE_CONFIG_H
# include <config.hxx>
#endif
#include <libsxc/Debug/Logger.hxx>
/*}}}*/
Registerer::Registerer(gloox::JID jid, int port, bool pwOnce)/*{{{*/
: _pwOnce(pwOnce),
_isTerm(true),
_jid(jid),
_client(jid.server())
{
_client.disableRoster();
_client.registerConnectionListener(this);
_client.setPort(port);
_registration = new gloox::Registration(&_client);
_registration->registerRegistrationHandler(this);
}/*}}}*/
Registerer::~Registerer()/*{{{*/
{
_client.disconnect();
delete _registration;
}/*}}}*/
void Registerer::run()/*{{{*/
{
_client.connect(); // Blocking connection.
}/*}}}*/
const std::string Registerer::enterPassword(bool retype)/*{{{*/
{
struct termios savedTermState;
std::string password;
try {
// Save a copy of the console state.
if (tcgetattr(fileno(stdin), &savedTermState)) // Cin must track stdin.
throw std::runtime_error(std::string("Get: ") + strerror(errno));
// Suppress echo so password is not logged.
struct termios newTermState = savedTermState;
newTermState.c_lflag &= ~ECHO;
if (tcsetattr(fileno(stdin), TCSAFLUSH, &newTermState))
throw std::runtime_error(std::string("Set: ") + strerror(errno));
// Verify that echo suppression is supported.
if (newTermState.c_lflag & ECHO)
throw std::runtime_error("Verify: unable to suppress echo");
} catch (...) {
LOG("Securing the terminal failed, assuming no terminal.");
_pwOnce = true; // Don't ask to retype.
_isTerm = false;
getline(std::cin, password);
return password;
}
// Prompt the user for a password.
std::cerr << (retype ? "Retype Password: " : "Password: ") << std::flush;
getline(std::cin, password);
// Restore the terminal state.
tcsetattr(fileno(stdin), TCSANOW, &savedTermState);
std::cerr << std::endl;
return password;
}/*}}}*/
void Registerer::handleRegistrationFields(/*{{{*/
const gloox::JID &from,
int fields,
std::string instructions)
{
gloox::RegistrationFields values;
if (fields & gloox::Registration::FieldUsername)
values.username = _jid.username();
if (fields & gloox::Registration::FieldPassword) {
while (true) {
values.password = enterPassword();
if (values.password == "") {
std::cerr << "Empty password not allowed." << std::endl;
if (!_isTerm)
throw "NoTerminal"; //Exception::NoTerminal();
} else if (_pwOnce || enterPassword(true) == values.password) {
break;
} else {
std::cerr << "Mismatch, try again." << std::endl;
}
}
}
_registration->createAccount(fields, values);
}/*}}}*/
void Registerer::handleRegistrationResult(/*{{{*/
const gloox::JID &from,
gloox::RegistrationResult result)
{
std::string text;
switch (result) {
case gloox::RegistrationSuccess:
text = "Succeeded.";
break;
case gloox::RegistrationNotAcceptable:
text = "Not all necassary information provided.";
break;
case gloox::RegistrationConflict:
text = "Username already exists.";
break;
case gloox::RegistrationNotAuthorized:
text = "Not authorized.";
break;
case gloox::RegistrationBadRequest:
text = "Bad request.";
break;
case gloox::RegistrationForbidden:
text = "Forbidden.";
break;
case gloox::RegistrationUnexpectedRequest:
text = "Unexpected request.";
break;
default:
text = "Unknown error.";
break;
}
std::cerr << "Registration: " << text << std::endl;
_client.disconnect();
exit(result); // Exit the program.
}/*}}}*/
void Registerer::onConnect()/*{{{*/
{
// Request the registration fields the server requires.
_registration->fetchRegistrationFields();
}/*}}}*/
void Registerer::onDisconnect(gloox::ConnectionError e)/*{{{*/
{
std::string text = libsxc::genConnErrorString(
e,
_client.streamError(),
_client.streamErrorText(),
_client.authError());
if (!text.empty())
std::cerr << "Disconnected: " << text << std::cerr;
}/*}}}*/
bool Registerer::onTLSConnect(const gloox::CertInfo& info)/*{{{*/
{
return true;
}/*}}}*/
void Registerer::handleAlreadyRegistered(const gloox::JID &from)/*{{{*/
{
}/*}}}*/
void Registerer::handleDataForm(/*{{{*/
const gloox::JID &from,
const gloox::DataForm &form)
{
}/*}}}*/
void Registerer::handleOOB(/*{{{*/
const gloox::JID &from,
const gloox::OOB &oob)
{
}/*}}}*/
// Use no tabs at all; two spaces indentation; max. eighty chars per line.
// vim: et ts=2 sw=2 sts=2 tw=80 fdm=marker
|
// LICENSE/*{{{*/
/*
sxc-tools
Copyright (C) 2008 Dennis Felsing, Andreas Waidler
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*}}}*/
// INCLUDE/*{{{*/
#include <gloox/client.h>
#include <gloox/connectionlistener.h>
#include <gloox/registration.h>
#include <libsxc/generateString.hxx>
#include <iostream>
#include <string>
#include <cstdio> // stdin
#include <stdexcept> // std::runtime_error
#include <termios.h> // struct termios
#include <stdio.h> // fileno()
#include <string.h> // strerror()
#include <errno.h> // errno
#include <unistd.h>
#include <Registerer.hxx>
#ifdef HAVE_CONFIG_H
# include <config.hxx>
#endif
#include <libsxc/Debug/Logger.hxx>
/*}}}*/
Registerer::Registerer(gloox::JID jid, int port, bool pwOnce)/*{{{*/
: _pwOnce(pwOnce),
_isTerm(true),
_jid(jid),
_client(jid.server())
{
_client.disableRoster();
_client.registerConnectionListener(this);
_client.setPort(port);
_registration = new gloox::Registration(&_client);
_registration->registerRegistrationHandler(this);
}/*}}}*/
Registerer::~Registerer()/*{{{*/
{
_client.disconnect();
delete _registration;
}/*}}}*/
void Registerer::run()/*{{{*/
{
_client.connect(); // Blocking connection.
}/*}}}*/
const std::string Registerer::enterPassword(bool retype)/*{{{*/
{
struct termios savedTermState;
std::string password;
try {
// Save a copy of the console state.
if (tcgetattr(fileno(stdin), &savedTermState)) // Cin must track stdin.
throw std::runtime_error(std::string("Get: ") + strerror(errno));
// Suppress echo so password is not logged.
struct termios newTermState = savedTermState;
newTermState.c_lflag &= ~ECHO;
if (tcsetattr(fileno(stdin), TCSAFLUSH, &newTermState))
throw std::runtime_error(std::string("Set: ") + strerror(errno));
// Verify that echo suppression is supported.
if (newTermState.c_lflag & ECHO)
throw std::runtime_error("Verify: unable to suppress echo");
} catch (...) {
LOG("Securing the terminal failed, assuming no terminal.");
_pwOnce = true; // Don't ask to retype.
_isTerm = false;
getline(std::cin, password);
return password;
}
// Prompt the user for a password.
std::cerr << (retype ? "Retype Password: " : "Password: ") << std::flush;
getline(std::cin, password);
// Restore the terminal state.
tcsetattr(fileno(stdin), TCSANOW, &savedTermState);
std::cerr << std::endl;
return password;
}/*}}}*/
void Registerer::handleRegistrationFields(/*{{{*/
const gloox::JID &from,
int fields,
std::string instructions)
{
gloox::RegistrationFields values;
if (fields & gloox::Registration::FieldUsername)
values.username = _jid.username();
if (fields & gloox::Registration::FieldPassword) {
while (true) {
values.password = enterPassword();
if (values.password == "") {
std::cerr << "Empty password not allowed." << std::endl;
if (!_isTerm)
throw "NoTerminal"; //Exception::NoTerminal();
} else if (_pwOnce || enterPassword(true) == values.password) {
break;
} else {
std::cerr << "Mismatch, try again." << std::endl;
}
}
}
_registration->createAccount(fields, values);
}/*}}}*/
void Registerer::handleRegistrationResult(/*{{{*/
const gloox::JID &from,
gloox::RegistrationResult result)
{
std::string text;
switch (result) {
case gloox::RegistrationSuccess:
text = "Succeeded.";
break;
case gloox::RegistrationNotAcceptable:
text = "Not all necassary information provided.";
break;
case gloox::RegistrationConflict:
text = "Username already exists.";
break;
case gloox::RegistrationNotAuthorized:
text = "Not authorized.";
break;
case gloox::RegistrationBadRequest:
text = "Bad request.";
break;
case gloox::RegistrationForbidden:
text = "Forbidden.";
break;
case gloox::RegistrationUnexpectedRequest:
text = "Unexpected request.";
break;
default:
text = "Unknown error.";
break;
}
std::cerr << "Registration: " << text << std::endl;
_client.disconnect();
exit(result); // Exit the program.
}/*}}}*/
void Registerer::onConnect()/*{{{*/
{
// Request the registration fields the server requires.
_registration->fetchRegistrationFields();
}/*}}}*/
void Registerer::onDisconnect(gloox::ConnectionError e)/*{{{*/
{
std::string text = libsxc::genConnErrorString(
e,
_client.streamError(),
_client.streamErrorText(),
_client.authError());
if (!text.empty())
std::cerr << "Disconnected: " << text << std::cerr;
}/*}}}*/
bool Registerer::onTLSConnect(const gloox::CertInfo& info)/*{{{*/
{
return true;
}/*}}}*/
void Registerer::handleAlreadyRegistered(const gloox::JID &from)/*{{{*/
{
}/*}}}*/
void Registerer::handleDataForm(/*{{{*/
const gloox::JID &from,
const gloox::DataForm &form)
{
}/*}}}*/
void Registerer::handleOOB(/*{{{*/
const gloox::JID &from,
const gloox::OOB &oob)
{
}/*}}}*/
// Use no tabs at all; two spaces indentation; max. eighty chars per line.
// vim: et ts=2 sw=2 sts=2 tw=80 fdm=marker
|
Include neccessary system headers
|
Fix: Include neccessary system headers
|
C++
|
isc
|
def-/sxc-tools
|
1576a5ccb8a08518231ef634ab72a573f4fdeb46
|
taichi/backends/struct_llvm.cpp
|
taichi/backends/struct_llvm.cpp
|
// Codegen for the hierarchical data structure (LLVM)
#include "struct_llvm.h"
#include "../ir.h"
#include "../program.h"
#include "../unified_allocator.h"
#include "struct.h"
#include "llvm/IR/Verifier.h"
#include <llvm/IR/IRBuilder.h>
extern "C" void *taichi_allocate_aligned(std::size_t size, int alignment);
TLANG_NAMESPACE_BEGIN
void assert_failed_host(const char *msg) {
TC_ERROR("Assertion failure: {}", msg);
}
StructCompilerLLVM::StructCompilerLLVM(Arch arch)
: StructCompiler(),
ModuleBuilder(
get_current_program().get_llvm_context(arch)->get_init_module()),
arch(arch) {
creator = [] {
TC_WARN("Data structure creation not implemented");
return nullptr;
};
tlctx = get_current_program().get_llvm_context(arch);
llvm_ctx = tlctx->ctx.get();
}
void StructCompilerLLVM::generate_types(SNode &snode) {
auto type = snode.type;
llvm::Type *llvm_type = nullptr;
auto ctx = llvm_ctx;
// create children type that supports forking...
std::vector<llvm::Type *> ch_types;
for (int i = 0; i < snode.ch.size(); i++) {
auto ch = snode_attr[snode.ch[i]].llvm_type;
ch_types.push_back(ch);
}
auto ch_type =
llvm::StructType::create(*ctx, ch_types, snode.node_type_name + "_ch");
ch_type->setName(snode.node_type_name + "_ch");
snode_attr[snode].llvm_element_type = ch_type;
llvm::Type *body_type = nullptr, *aux_type = nullptr;
if (type == SNodeType::dense) {
TC_ASSERT(snode._morton == false);
body_type = llvm::ArrayType::get(ch_type, snode.max_num_elements());
if (snode._bitmasked) {
aux_type = llvm::ArrayType::get(Type::getInt32Ty(*llvm_ctx),
(snode.max_num_elements() + 31) / 32);
}
} else if (type == SNodeType::root) {
body_type = ch_type;
} else if (type == SNodeType::place) {
if (snode.dt == DataType::f32) {
body_type = llvm::Type::getFloatTy(*ctx);
} else if (snode.dt == DataType::i32) {
body_type = llvm::Type::getInt32Ty(*ctx);
} else {
body_type = llvm::Type::getDoubleTy(*ctx);
}
} else if (type == SNodeType::pointer) {
// mutex
aux_type = llvm::PointerType::getInt64Ty(*ctx);
body_type = llvm::PointerType::getInt8PtrTy(*ctx);
} else if (type == SNodeType::dynamic) {
// mutex and n (number of elements)
aux_type =
llvm::StructType::get(*ctx, {llvm::PointerType::getInt32Ty(*ctx),
llvm::PointerType::getInt32Ty(*ctx)});
body_type = llvm::PointerType::getInt8PtrTy(*ctx);
} else {
TC_P(snode.type_name());
TC_NOT_IMPLEMENTED;
}
if (aux_type != nullptr) {
llvm_type = llvm::StructType::create(*ctx, {aux_type, body_type}, "");
snode.has_aux_structure = true;
} else {
llvm_type = body_type;
snode.has_aux_structure = false;
}
TC_ASSERT(llvm_type != nullptr);
snode_attr[snode].llvm_type = llvm_type;
snode_attr[snode].llvm_aux_type = aux_type;
snode_attr[snode].llvm_body_type = body_type;
}
void StructCompilerLLVM::generate_refine_coordinates(SNode *snode) {
auto coord_type = get_runtime_type("PhysicalCoordinates");
auto coord_type_ptr = llvm::PointerType::get(coord_type, 0);
auto ft = llvm::FunctionType::get(
llvm::Type::getVoidTy(*llvm_ctx),
{coord_type_ptr, coord_type_ptr, llvm::Type::getInt32Ty(*llvm_ctx)},
false);
auto func = Function::Create(ft, Function::ExternalLinkage,
snode->refine_coordinates_func_name(), *module);
auto bb = BasicBlock::Create(*llvm_ctx, "entry", func);
llvm::IRBuilder<> builder(bb, bb->begin());
std::vector<Value *> args;
for (auto &arg : func->args()) {
args.push_back(&arg);
}
auto inp_coords = args[0];
auto outp_coords = args[1];
auto l = args[2];
for (int i = 0; i < max_num_indices; i++) {
auto addition = tlctx->get_constant(0);
if (snode->extractors[i].num_bits) {
auto mask = ((1 << snode->extractors[i].num_bits) - 1);
addition = builder.CreateAnd(
builder.CreateAShr(l, snode->extractors[i].acc_offset), mask);
addition = builder.CreateShl(
addition, tlctx->get_constant(snode->extractors[i].start));
}
auto in = call(&builder, "PhysicalCoordinates_get_val", inp_coords,
tlctx->get_constant(i));
auto added = builder.CreateOr(in, addition);
call(&builder, "PhysicalCoordinates_set_val", outp_coords,
tlctx->get_constant(i), added);
}
builder.CreateRetVoid();
}
void StructCompilerLLVM::generate_leaf_accessors(SNode &snode) {
auto type = snode.type;
stack.push_back(&snode);
bool is_leaf = type == SNodeType::place;
if (!is_leaf) {
generate_refine_coordinates(&snode);
}
if (snode.parent != nullptr) {
// create the get ch function
auto parent = snode.parent;
auto inp_type =
llvm::PointerType::get(snode_attr[parent].llvm_element_type, 0);
// auto ret_type = llvm::PointerType::get(snode.llvm_type, 0);
auto ft =
llvm::FunctionType::get(llvm::Type::getInt8PtrTy(*llvm_ctx),
{llvm::Type::getInt8PtrTy(*llvm_ctx)}, false);
auto func = Function::Create(ft, Function::ExternalLinkage,
snode.get_ch_from_parent_func_name(), *module);
auto bb = BasicBlock::Create(*llvm_ctx, "entry", func);
llvm::IRBuilder<> builder(bb, bb->begin());
std::vector<Value *> args;
for (auto &arg : func->args()) {
args.push_back(&arg);
}
llvm::Value *ret;
ret = builder.CreateGEP(
builder.CreateBitCast(args[0], inp_type),
{tlctx->get_constant(0), tlctx->get_constant(parent->child_id(&snode))},
"getch");
builder.CreateRet(
builder.CreateBitCast(ret, llvm::Type::getInt8PtrTy(*llvm_ctx)));
}
// SNode::place & indirect
// emit end2end accessors for leaf (place) nodes, using chain accessors
constexpr int mode_weak_access = 0;
constexpr int mode_strong_access = 1;
constexpr int mode_activate = 2;
constexpr int mode_query = 3;
std::vector<std::string> verbs(4);
verbs[mode_weak_access] = "weak_access";
verbs[mode_strong_access] = "access";
verbs[mode_activate] = "activate";
verbs[mode_query] = "query";
for (auto ch : snode.ch) {
generate_leaf_accessors(*ch);
}
stack.pop_back();
}
void StructCompilerLLVM::load_accessors(SNode &snode) {
}
void StructCompilerLLVM::run(SNode &root, bool host) {
// bottom to top
collect_snodes(root);
if (host)
infer_snode_properties(root);
auto snodes_rev = snodes;
std::reverse(snodes_rev.begin(), snodes_rev.end());
for (auto &n : snodes_rev)
generate_types(*n);
// TODO: general allocators
root_type = root.node_type_name;
generate_leaf_accessors(root);
if (get_current_program().config.print_struct_llvm_ir) {
TC_INFO("Struct Module IR");
module->print(errs(), nullptr);
}
TC_ASSERT((int)snodes.size() <= max_num_snodes);
auto root_size =
tlctx->jit->getDataLayout().getTypeAllocSize(snode_attr[root].llvm_type);
module->setDataLayout(tlctx->jit->getDataLayout());
tlctx->set_struct_module(module);
if (arch == Arch::x86_64) // Do not compile the GPU struct module alone since
// it's useless unless used with kernels
tlctx->jit->addModule(std::move(module));
if (host) {
for (auto n : snodes) {
load_accessors(*n);
}
auto initialize_data_structure = tlctx->lookup_function<
std::function<void *(void *, int, std::size_t, int, void *, bool)>>(
"Runtime_initialize");
auto get_allocator =
tlctx->lookup_function<std::function<void *(void *, int)>>(
"Runtime_get_node_allocators");
auto set_assert_failed =
tlctx->lookup_function<std::function<void(void *, void *)>>(
"Runtime_set_assert_failed");
auto allocate_ambient =
tlctx->lookup_function<std::function<void(void *, int)>>(
"Runtime_allocate_ambient");
auto initialize_allocator = tlctx->lookup_function<
std::function<void *(void *, void *, std::size_t)>>(
"NodeAllocator_initialize");
auto runtime_initialize_thread_pool =
tlctx->lookup_function<std::function<void(void *, void *, void *)>>(
"Runtime_initialize_thread_pool");
auto snodes = this->snodes;
auto tlctx = this->tlctx;
auto root_id = root.id;
creator = [=]() {
TC_INFO("Allocating data structure of size {}", root_size);
auto root_ptr = initialize_data_structure(
&get_current_program().llvm_runtime, (int)snodes.size(), root_size,
root_id, (void *)&::taichi_allocate_aligned,
get_current_program().config.verbose);
for (int i = 0; i < (int)snodes.size(); i++) {
if (snodes[i]->type == SNodeType::pointer ||
snodes[i]->type == SNodeType::dynamic) {
std::size_t chunk_size;
if (snodes[i]->type == SNodeType::pointer)
chunk_size =
tlctx->get_type_size(snode_attr[snodes[i]].llvm_element_type);
else {
// dynamic. Allocators are for the chunks
chunk_size =
sizeof(void *) +
tlctx->get_type_size(snode_attr[snodes[i]].llvm_element_type) *
snodes[i]->chunk_size;
}
TC_INFO("Initializing allocator for snode {} (chunk size {})",
snodes[i]->id, chunk_size);
auto rt = get_current_program().llvm_runtime;
auto allocator = get_allocator(rt, i);
initialize_allocator(rt, allocator, chunk_size);
TC_INFO("Allocating ambient element for snode {} (chunk size {})",
snodes[i]->id, chunk_size);
allocate_ambient(rt, i);
}
}
runtime_initialize_thread_pool(get_current_program().llvm_runtime,
&get_current_program().thread_pool,
(void *)ThreadPool::static_run);
set_assert_failed(get_current_program().llvm_runtime,
(void *)assert_failed_host);
return (void *)root_ptr;
};
}
tlctx->snode_attr = snode_attr;
}
std::unique_ptr<StructCompiler> StructCompiler::make(bool use_llvm, Arch arch) {
if (use_llvm) {
return std::make_unique<StructCompilerLLVM>(arch);
} else {
return std::make_unique<StructCompiler>();
}
}
bool SNode::need_activation() const {
return type == SNodeType::pointer || type == SNodeType::hash ||
(type == SNodeType::dense && _bitmasked) ||
(get_current_program().config.use_llvm && type == SNodeType::dynamic);
}
TLANG_NAMESPACE_END
|
// Codegen for the hierarchical data structure (LLVM)
#include "struct_llvm.h"
#include "../ir.h"
#include "../program.h"
#include "../unified_allocator.h"
#include "struct.h"
#include "llvm/IR/Verifier.h"
#include <llvm/IR/IRBuilder.h>
extern "C" void *taichi_allocate_aligned(std::size_t size, int alignment);
TLANG_NAMESPACE_BEGIN
void assert_failed_host(const char *msg) {
TC_ERROR("Assertion failure: {}", msg);
}
StructCompilerLLVM::StructCompilerLLVM(Arch arch)
: StructCompiler(),
ModuleBuilder(
get_current_program().get_llvm_context(arch)->get_init_module()),
arch(arch) {
creator = [] {
TC_WARN("Data structure creation not implemented");
return nullptr;
};
tlctx = get_current_program().get_llvm_context(arch);
llvm_ctx = tlctx->ctx.get();
}
void StructCompilerLLVM::generate_types(SNode &snode) {
auto type = snode.type;
llvm::Type *llvm_type = nullptr;
auto ctx = llvm_ctx;
// create children type that supports forking...
std::vector<llvm::Type *> ch_types;
for (int i = 0; i < snode.ch.size(); i++) {
auto ch = snode_attr[snode.ch[i]].llvm_type;
ch_types.push_back(ch);
}
auto ch_type =
llvm::StructType::create(*ctx, ch_types, snode.node_type_name + "_ch");
ch_type->setName(snode.node_type_name + "_ch");
snode_attr[snode].llvm_element_type = ch_type;
llvm::Type *body_type = nullptr, *aux_type = nullptr;
if (type == SNodeType::dense) {
TC_ASSERT(snode._morton == false);
body_type = llvm::ArrayType::get(ch_type, snode.max_num_elements());
if (snode._bitmasked) {
aux_type = llvm::ArrayType::get(Type::getInt32Ty(*llvm_ctx),
(snode.max_num_elements() + 31) / 32);
}
} else if (type == SNodeType::root) {
body_type = ch_type;
} else if (type == SNodeType::place) {
if (snode.dt == DataType::f32) {
body_type = llvm::Type::getFloatTy(*ctx);
} else if (snode.dt == DataType::i32) {
body_type = llvm::Type::getInt32Ty(*ctx);
} else {
body_type = llvm::Type::getDoubleTy(*ctx);
}
} else if (type == SNodeType::pointer) {
// mutex
aux_type = llvm::PointerType::getInt64Ty(*ctx);
body_type = llvm::PointerType::getInt8PtrTy(*ctx);
} else if (type == SNodeType::dynamic) {
// mutex and n (number of elements)
aux_type =
llvm::StructType::get(*ctx, {llvm::PointerType::getInt32Ty(*ctx),
llvm::PointerType::getInt32Ty(*ctx)});
body_type = llvm::PointerType::getInt8PtrTy(*ctx);
} else {
TC_P(snode.type_name());
TC_NOT_IMPLEMENTED;
}
if (aux_type != nullptr) {
llvm_type = llvm::StructType::create(*ctx, {aux_type, body_type}, "");
snode.has_aux_structure = true;
} else {
llvm_type = body_type;
snode.has_aux_structure = false;
}
TC_ASSERT(llvm_type != nullptr);
snode_attr[snode].llvm_type = llvm_type;
snode_attr[snode].llvm_aux_type = aux_type;
snode_attr[snode].llvm_body_type = body_type;
}
void StructCompilerLLVM::generate_refine_coordinates(SNode *snode) {
auto coord_type = get_runtime_type("PhysicalCoordinates");
auto coord_type_ptr = llvm::PointerType::get(coord_type, 0);
auto ft = llvm::FunctionType::get(
llvm::Type::getVoidTy(*llvm_ctx),
{coord_type_ptr, coord_type_ptr, llvm::Type::getInt32Ty(*llvm_ctx)},
false);
auto func = Function::Create(ft, Function::ExternalLinkage,
snode->refine_coordinates_func_name(), *module);
auto bb = BasicBlock::Create(*llvm_ctx, "entry", func);
llvm::IRBuilder<> builder(bb, bb->begin());
std::vector<Value *> args;
for (auto &arg : func->args()) {
args.push_back(&arg);
}
auto inp_coords = args[0];
auto outp_coords = args[1];
auto l = args[2];
for (int i = 0; i < max_num_indices; i++) {
auto addition = tlctx->get_constant(0);
if (snode->extractors[i].num_bits) {
auto mask = ((1 << snode->extractors[i].num_bits) - 1);
addition = builder.CreateAnd(
builder.CreateAShr(l, snode->extractors[i].acc_offset), mask);
addition = builder.CreateShl(
addition, tlctx->get_constant(snode->extractors[i].start));
}
auto in = call(&builder, "PhysicalCoordinates_get_val", inp_coords,
tlctx->get_constant(i));
auto added = builder.CreateOr(in, addition);
call(&builder, "PhysicalCoordinates_set_val", outp_coords,
tlctx->get_constant(i), added);
}
builder.CreateRetVoid();
}
void StructCompilerLLVM::generate_leaf_accessors(SNode &snode) {
auto type = snode.type;
stack.push_back(&snode);
bool is_leaf = type == SNodeType::place;
if (!is_leaf) {
generate_refine_coordinates(&snode);
}
if (snode.parent != nullptr) {
// create the get ch function
auto parent = snode.parent;
auto inp_type =
llvm::PointerType::get(snode_attr[parent].llvm_element_type, 0);
// auto ret_type = llvm::PointerType::get(snode.llvm_type, 0);
auto ft =
llvm::FunctionType::get(llvm::Type::getInt8PtrTy(*llvm_ctx),
{llvm::Type::getInt8PtrTy(*llvm_ctx)}, false);
auto func = Function::Create(ft, Function::ExternalLinkage,
snode.get_ch_from_parent_func_name(), *module);
auto bb = BasicBlock::Create(*llvm_ctx, "entry", func);
llvm::IRBuilder<> builder(bb, bb->begin());
std::vector<Value *> args;
for (auto &arg : func->args()) {
args.push_back(&arg);
}
llvm::Value *ret;
ret = builder.CreateGEP(
builder.CreateBitCast(args[0], inp_type),
{tlctx->get_constant(0), tlctx->get_constant(parent->child_id(&snode))},
"getch");
builder.CreateRet(
builder.CreateBitCast(ret, llvm::Type::getInt8PtrTy(*llvm_ctx)));
}
// SNode::place & indirect
// emit end2end accessors for leaf (place) nodes, using chain accessors
constexpr int mode_weak_access = 0;
constexpr int mode_strong_access = 1;
constexpr int mode_activate = 2;
constexpr int mode_query = 3;
std::vector<std::string> verbs(4);
verbs[mode_weak_access] = "weak_access";
verbs[mode_strong_access] = "access";
verbs[mode_activate] = "activate";
verbs[mode_query] = "query";
for (auto ch : snode.ch) {
generate_leaf_accessors(*ch);
}
stack.pop_back();
}
void StructCompilerLLVM::load_accessors(SNode &snode) {
}
void StructCompilerLLVM::run(SNode &root, bool host) {
// bottom to top
collect_snodes(root);
if (host)
infer_snode_properties(root);
auto snodes_rev = snodes;
std::reverse(snodes_rev.begin(), snodes_rev.end());
for (auto &n : snodes_rev)
generate_types(*n);
// TODO: general allocators
root_type = root.node_type_name;
generate_leaf_accessors(root);
if (get_current_program().config.print_struct_llvm_ir) {
TC_INFO("Struct Module IR");
module->print(errs(), nullptr);
}
TC_ASSERT((int)snodes.size() <= max_num_snodes);
auto root_size =
tlctx->jit->getDataLayout().getTypeAllocSize(snode_attr[root].llvm_type);
module->setDataLayout(tlctx->jit->getDataLayout());
tlctx->set_struct_module(module);
if (arch == Arch::x86_64) // Do not compile the GPU struct module alone since
// it's useless unless used with kernels
tlctx->jit->addModule(std::move(module));
if (host) {
for (auto n : snodes) {
load_accessors(*n);
}
auto initialize_data_structure = tlctx->lookup_function<
std::function<void *(void *, int, std::size_t, int, void *, bool)>>(
"Runtime_initialize");
auto get_allocator =
tlctx->lookup_function<std::function<void *(void *, int)>>(
"Runtime_get_node_allocators");
auto set_assert_failed =
tlctx->lookup_function<std::function<void(void *, void *)>>(
"Runtime_set_assert_failed");
auto allocate_ambient =
tlctx->lookup_function<std::function<void(void *, int)>>(
"Runtime_allocate_ambient");
auto initialize_allocator = tlctx->lookup_function<
std::function<void *(void *, void *, std::size_t)>>(
"NodeAllocator_initialize");
auto runtime_initialize_thread_pool =
tlctx->lookup_function<std::function<void(void *, void *, void *)>>(
"Runtime_initialize_thread_pool");
auto snodes = this->snodes;
auto tlctx = this->tlctx;
auto root_id = root.id;
creator = [=]() {
TC_INFO("Allocating data structure of size {} B", root_size);
auto root_ptr = initialize_data_structure(
&get_current_program().llvm_runtime, (int)snodes.size(), root_size,
root_id, (void *)&::taichi_allocate_aligned,
get_current_program().config.verbose);
for (int i = 0; i < (int)snodes.size(); i++) {
if (snodes[i]->type == SNodeType::pointer ||
snodes[i]->type == SNodeType::dynamic) {
std::size_t chunk_size;
if (snodes[i]->type == SNodeType::pointer)
chunk_size =
tlctx->get_type_size(snode_attr[snodes[i]].llvm_element_type);
else {
// dynamic. Allocators are for the chunks
chunk_size =
sizeof(void *) +
tlctx->get_type_size(snode_attr[snodes[i]].llvm_element_type) *
snodes[i]->chunk_size;
}
TC_INFO("Initializing allocator for snode {} (chunk size {})",
snodes[i]->id, chunk_size);
auto rt = get_current_program().llvm_runtime;
auto allocator = get_allocator(rt, i);
initialize_allocator(rt, allocator, chunk_size);
TC_INFO("Allocating ambient element for snode {} (chunk size {})",
snodes[i]->id, chunk_size);
allocate_ambient(rt, i);
}
}
runtime_initialize_thread_pool(get_current_program().llvm_runtime,
&get_current_program().thread_pool,
(void *)ThreadPool::static_run);
set_assert_failed(get_current_program().llvm_runtime,
(void *)assert_failed_host);
return (void *)root_ptr;
};
}
tlctx->snode_attr = snode_attr;
}
std::unique_ptr<StructCompiler> StructCompiler::make(bool use_llvm, Arch arch) {
if (use_llvm) {
return std::make_unique<StructCompilerLLVM>(arch);
} else {
return std::make_unique<StructCompiler>();
}
}
bool SNode::need_activation() const {
return type == SNodeType::pointer || type == SNodeType::hash ||
(type == SNodeType::dense && _bitmasked) ||
(get_current_program().config.use_llvm && type == SNodeType::dynamic);
}
TLANG_NAMESPACE_END
|
improve logging msg
|
improve logging msg
|
C++
|
apache-2.0
|
yuanming-hu/taichi,yuanming-hu/taichi,yuanming-hu/taichi,yuanming-hu/taichi
|
c4cb318a0ea0a0033d706bac975b2dac3b66ebf8
|
Tests/UnitTests/Tasks/BasicTasks/InitAttackCountTaskTests.cpp
|
Tests/UnitTests/Tasks/BasicTasks/InitAttackCountTaskTests.cpp
|
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include "gtest/gtest.h"
#include <Utils/TestUtils.h>
#include <hspp/Tasks/BasicTasks/InitAttackCountTask.h>
using namespace Hearthstonepp;
TEST(InitAttackCountTask, GetTaskID)
{
BasicTasks::InitAttackCountTask init;
EXPECT_EQ(init.GetTaskID(), +TaskID::INIT_ATTACK_COUNT);
}
TEST(InitAttackCountTask, Run)
{
BasicTasks::InitAttackCountTask init;
TestUtils::PlayerGenerator gen(CardClass::DRUID, CardClass::ROGUE);
gen.player1.id = 100;
MetaData result = init.Run(gen.player1, gen.player2);
EXPECT_EQ(result, MetaData::INIT_ATTACK_COUNT_SUCCESS);
TaskMeta meta;
result = init.Run(gen.player1, gen.player2, meta);
EXPECT_EQ(result, MetaData::INIT_ATTACK_COUNT_SUCCESS);
EXPECT_EQ(meta.id, +TaskID::INIT_ATTACK_COUNT);
EXPECT_EQ(meta.status, MetaData::INIT_ATTACK_COUNT_SUCCESS);
EXPECT_EQ(meta.userID, gen.player1.id);
}
TEST(InitAttackCountTask, RunFrozen)
{
BasicTasks::InitAttackCountTask init;
TestUtils::PlayerGenerator gen(CardClass::DRUID, CardClass::ROGUE);
Card card1;
Card card2;
Card card3;
Minion* minion1 = new Minion(card1);
Minion* minion2 = new Minion(card2);
Minion* minion3 = new Minion(card3);
minion2->gameTags[GameTag::FROZEN] = 1;
minion3->gameTags[GameTag::FROZEN] = 2;
gen.player1.field.emplace_back(minion1);
gen.player1.field.emplace_back(minion2);
gen.player1.field.emplace_back(minion3);
MetaData result = init.Run(gen.player1, gen.player2);
EXPECT_EQ(result, MetaData::INIT_ATTACK_COUNT_SUCCESS);
EXPECT_EQ(minion1->attackableCount, static_cast<size_t>(1));
EXPECT_EQ(minion2->gameTags[GameTag::FROZEN], static_cast<int>(0));
EXPECT_EQ(minion2->attackableCount, static_cast<size_t>(1));
EXPECT_EQ(minion3->gameTags[GameTag::FROZEN], static_cast<int>(1));
EXPECT_EQ(minion3->attackableCount, static_cast<size_t>(0));
}
TEST(InitAttackCountTask, RunWindFury)
{
BasicTasks::InitAttackCountTask init;
TestUtils::PlayerGenerator gen(CardClass::DRUID, CardClass::ROGUE);
Card card1;
Card card2;
Minion* minion1 = new Minion(card1);
Minion* minion2 = new Minion(card2);
minion2->gameTags[GameTag::WINDFURY] = 1;
gen.player1.field.emplace_back(minion1);
gen.player1.field.emplace_back(minion2);
MetaData result = init.Run(gen.player1, gen.player2);
EXPECT_EQ(result, MetaData::INIT_ATTACK_COUNT_SUCCESS);
EXPECT_EQ(minion1->attackableCount, static_cast<size_t>(1));
EXPECT_EQ(minion2->attackableCount, static_cast<size_t>(2));
}
|
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include "gtest/gtest.h"
#include <Utils/TestUtils.h>
#include <hspp/Tasks/BasicTasks/InitAttackCountTask.h>
using namespace Hearthstonepp;
TEST(InitAttackCountTask, GetTaskID)
{
BasicTasks::InitAttackCountTask init;
EXPECT_EQ(init.GetTaskID(), +TaskID::INIT_ATTACK_COUNT);
}
TEST(InitAttackCountTask, Run)
{
BasicTasks::InitAttackCountTask init;
TestUtils::PlayerGenerator gen(CardClass::DRUID, CardClass::ROGUE);
gen.player1.id = 100;
MetaData result = init.Run(gen.player1, gen.player2);
EXPECT_EQ(result, MetaData::INIT_ATTACK_COUNT_SUCCESS);
TaskMeta meta;
result = init.Run(gen.player1, gen.player2, meta);
EXPECT_EQ(result, MetaData::INIT_ATTACK_COUNT_SUCCESS);
EXPECT_EQ(meta.id, +TaskID::INIT_ATTACK_COUNT);
EXPECT_EQ(meta.status, MetaData::INIT_ATTACK_COUNT_SUCCESS);
EXPECT_EQ(meta.userID, gen.player1.id);
}
TEST(InitAttackCountTask, RunFrozen)
{
BasicTasks::InitAttackCountTask init;
TestUtils::PlayerGenerator gen(CardClass::DRUID, CardClass::ROGUE);
Card card;
Minion* minion1 = new Minion(card);
Minion* minion2 = new Minion(card);
Minion* minion3 = new Minion(card);
Minion* minion4 = new Minion(card);
Minion* minion5 = new Minion(card);
Minion* minion6 = new Minion(card);
// Case 1
minion6->gameTags[GameTag::FROZEN] = 1;
minion6->remainTurnToThaw = 2;
// Case 2-1
minion2->gameTags[GameTag::FROZEN] = 1;
minion2->attackableCount = 1;
minion2->remainTurnToThaw = 1;
// Case 2-2
minion3->gameTags[GameTag::FROZEN] = 1;
minion3->attackableCount = 0;
minion3->remainTurnToThaw = 3;
minion4->gameTags[GameTag::FROZEN] = 1;
minion4->gameTags[GameTag::WINDFURY] = 1;
minion4->attackableCount = 1;
minion4->remainTurnToThaw = 3;
gen.player1.field.emplace_back(minion1);
gen.player1.field.emplace_back(minion2);
gen.player1.field.emplace_back(minion3);
gen.player1.field.emplace_back(minion4);
gen.player2.field.emplace_back(minion5);
gen.player2.field.emplace_back(minion6);
MetaData result = init.Run(gen.player2, gen.player1);
EXPECT_EQ(result, MetaData::INIT_ATTACK_COUNT_SUCCESS);
EXPECT_EQ(minion1->gameTags[GameTag::FROZEN], static_cast<int>(0));
EXPECT_EQ(minion1->attackableCount, static_cast<size_t>(0));
EXPECT_EQ(minion2->gameTags[GameTag::FROZEN], static_cast<int>(0));
EXPECT_EQ(minion2->attackableCount, static_cast<size_t>(0));
EXPECT_EQ(minion3->gameTags[GameTag::FROZEN], static_cast<int>(1));
EXPECT_EQ(minion3->attackableCount, static_cast<size_t>(0));
EXPECT_EQ(minion4->gameTags[GameTag::FROZEN], static_cast<int>(1));
EXPECT_EQ(minion4->attackableCount, static_cast<size_t>(0));
EXPECT_EQ(minion5->gameTags[GameTag::FROZEN], static_cast<int>(0));
EXPECT_EQ(minion5->attackableCount, static_cast<size_t>(1));
EXPECT_EQ(minion6->gameTags[GameTag::FROZEN], static_cast<int>(1));
EXPECT_EQ(minion6->attackableCount, static_cast<size_t>(0));
result = init.Run(gen.player1, gen.player2);
EXPECT_EQ(result, MetaData::INIT_ATTACK_COUNT_SUCCESS);
EXPECT_EQ(minion1->gameTags[GameTag::FROZEN], static_cast<int>(0));
EXPECT_EQ(minion1->attackableCount, static_cast<size_t>(1));
EXPECT_EQ(minion2->gameTags[GameTag::FROZEN], static_cast<int>(0));
EXPECT_EQ(minion2->attackableCount, static_cast<size_t>(1));
EXPECT_EQ(minion3->gameTags[GameTag::FROZEN], static_cast<int>(1));
EXPECT_EQ(minion3->attackableCount, static_cast<size_t>(0));
EXPECT_EQ(minion4->gameTags[GameTag::FROZEN], static_cast<int>(1));
EXPECT_EQ(minion4->attackableCount, static_cast<size_t>(0));
EXPECT_EQ(minion5->gameTags[GameTag::FROZEN], static_cast<int>(0));
EXPECT_EQ(minion5->attackableCount, static_cast<size_t>(0));
EXPECT_EQ(minion6->gameTags[GameTag::FROZEN], static_cast<int>(0));
EXPECT_EQ(minion6->attackableCount, static_cast<size_t>(0));
result = init.Run(gen.player2, gen.player1);
EXPECT_EQ(result, MetaData::INIT_ATTACK_COUNT_SUCCESS);
EXPECT_EQ(minion1->gameTags[GameTag::FROZEN], static_cast<int>(0));
EXPECT_EQ(minion1->attackableCount, static_cast<size_t>(0));
EXPECT_EQ(minion2->gameTags[GameTag::FROZEN], static_cast<int>(0));
EXPECT_EQ(minion2->attackableCount, static_cast<size_t>(0));
EXPECT_EQ(minion3->gameTags[GameTag::FROZEN], static_cast<int>(0));
EXPECT_EQ(minion3->attackableCount, static_cast<size_t>(0));
EXPECT_EQ(minion4->gameTags[GameTag::FROZEN], static_cast<int>(0));
EXPECT_EQ(minion4->attackableCount, static_cast<size_t>(0));
EXPECT_EQ(minion5->gameTags[GameTag::FROZEN], static_cast<int>(0));
EXPECT_EQ(minion5->attackableCount, static_cast<size_t>(1));
EXPECT_EQ(minion6->gameTags[GameTag::FROZEN], static_cast<int>(0));
EXPECT_EQ(minion6->attackableCount, static_cast<size_t>(1));
}
TEST(InitAttackCountTask, RunWindFury)
{
BasicTasks::InitAttackCountTask init;
TestUtils::PlayerGenerator gen(CardClass::DRUID, CardClass::ROGUE);
Card card1;
Card card2;
Minion* minion1 = new Minion(card1);
Minion* minion2 = new Minion(card2);
minion2->gameTags[GameTag::WINDFURY] = 1;
gen.player1.field.emplace_back(minion1);
gen.player1.field.emplace_back(minion2);
MetaData result = init.Run(gen.player1, gen.player2);
EXPECT_EQ(result, MetaData::INIT_ATTACK_COUNT_SUCCESS);
EXPECT_EQ(minion1->attackableCount, static_cast<size_t>(1));
EXPECT_EQ(minion2->attackableCount, static_cast<size_t>(2));
}
|
Add unit test for changed FreezeTask
|
feat(change-freeze): Add unit test for changed FreezeTask
- Case 1
- Case 2-1
- Case 2-2
|
C++
|
mit
|
Hearthstonepp/Hearthstonepp,Hearthstonepp/Hearthstonepp
|
f11c9a419b99563b462356add5446d9fc2dbe2eb
|
techlibs/xilinx/synth_xilinx.cc
|
techlibs/xilinx/synth_xilinx.cc
|
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
#define XC7_WIRE_DELAY "300" // Number with which ABC will map a 6-input gate
// to one LUT6 (instead of a LUT5 + LUT2)
struct SynthXilinxPass : public ScriptPass
{
SynthXilinxPass() : ScriptPass("synth_xilinx", "synthesis for Xilinx FPGAs") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" synth_xilinx [options]\n");
log("\n");
log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n");
log("partly selected designs. At the moment this command creates netlists that are\n");
log("compatible with 7-Series Xilinx devices.\n");
log("\n");
log(" -top <module>\n");
log(" use the specified module as top module\n");
log("\n");
log(" -arch {xcup|xcu|xc7|xc6s}\n");
log(" run synthesis for the specified Xilinx architecture\n");
log(" default: xc7\n");
log("\n");
log(" -edif <file>\n");
log(" write the design to the specified edif file. writing of an output file\n");
log(" is omitted if this parameter is not specified.\n");
log("\n");
log(" -blif <file>\n");
log(" write the design to the specified BLIF file. writing of an output file\n");
log(" is omitted if this parameter is not specified.\n");
log("\n");
log(" -vpr\n");
log(" generate an output netlist (and BLIF file) suitable for VPR\n");
log(" (this feature is experimental and incomplete)\n");
log("\n");
log(" -nocarry\n");
log(" disable inference of carry chains\n");
log("\n");
log(" -nobram\n");
log(" disable inference of block rams\n");
log("\n");
log(" -nodram\n");
log(" disable inference of distributed rams\n");
log("\n");
log(" -nosrl\n");
log(" disable inference of shift registers\n");
log("\n");
log(" -run <from_label>:<to_label>\n");
log(" only run the commands between the labels (see below). an empty\n");
log(" from label is synonymous to 'begin', and empty to label is\n");
log(" synonymous to the end of the command list.\n");
log("\n");
log(" -flatten\n");
log(" flatten design before synthesis\n");
log("\n");
log(" -retime\n");
log(" run 'abc' with -dff option\n");
log("\n");
log(" -abc9\n");
log(" use new ABC9 flow (EXPERIMENTAL)\n");
log("\n");
log("\n");
log("The following commands are executed by this synthesis command:\n");
help_script();
log("\n");
}
std::string top_opt, edif_file, blif_file, abc, arch;
bool flatten, retime, vpr, nocarry, nobram, nodram, nosrl;
void clear_flags() YS_OVERRIDE
{
top_opt = "-auto-top";
edif_file.clear();
blif_file.clear();
abc = "abc";
flatten = false;
retime = false;
vpr = false;
nocarry = false;
nobram = false;
nodram = false;
nosrl = false;
arch = "xc7";
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
std::string run_from, run_to;
clear_flags();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-top" && argidx+1 < args.size()) {
top_opt = "-top " + args[++argidx];
continue;
}
if (args[argidx] == "-arch" && argidx+1 < args.size()) {
arch = args[++argidx];
continue;
}
if (args[argidx] == "-edif" && argidx+1 < args.size()) {
edif_file = args[++argidx];
continue;
}
if (args[argidx] == "-blif" && argidx+1 < args.size()) {
blif_file = args[++argidx];
continue;
}
if (args[argidx] == "-run" && argidx+1 < args.size()) {
size_t pos = args[argidx+1].find(':');
if (pos == std::string::npos)
break;
run_from = args[++argidx].substr(0, pos);
run_to = args[argidx].substr(pos+1);
continue;
}
if (args[argidx] == "-flatten") {
flatten = true;
continue;
}
if (args[argidx] == "-retime") {
retime = true;
continue;
}
if (args[argidx] == "-vpr") {
vpr = true;
continue;
}
if (args[argidx] == "-nocarry") {
nocarry = true;
continue;
}
if (args[argidx] == "-nobram") {
nobram = true;
continue;
}
if (args[argidx] == "-nodram") {
nodram = true;
continue;
}
if (args[argidx] == "-nosrl") {
nosrl = true;
continue;
}
if (args[argidx] == "-abc9") {
abc = "abc9";
continue;
}
break;
}
extra_args(args, argidx, design);
if (arch != "xcup" && arch != "xcu" && arch != "xc7" && arch != "xc6s")
log_cmd_error("Invalid Xilinx -arch setting: %s\n", arch.c_str());
if (!design->full_selection())
log_cmd_error("This command only operates on fully selected designs!\n");
log_header(design, "Executing SYNTH_XILINX pass.\n");
log_push();
run_script(design, run_from, run_to);
log_pop();
}
void script() YS_OVERRIDE
{
if (check_label("begin")) {
if (vpr)
run("read_verilog -lib -D _ABC -D_EXPLICIT_CARRY +/xilinx/cells_sim.v");
else
run("read_verilog -lib -D _ABC +/xilinx/cells_sim.v");
run("read_verilog -lib +/xilinx/cells_xtra.v");
if (!nobram || help_mode)
run("read_verilog -lib +/xilinx/brams_bb.v", "(skip if '-nobram')");
run(stringf("hierarchy -check %s", top_opt.c_str()));
}
if (check_label("flatten", "(with '-flatten' only)")) {
if (flatten || help_mode) {
run("proc");
run("flatten");
}
}
if (check_label("coarse")) {
run("synth -run coarse");
// shregmap -tech xilinx can cope with $shiftx and $mux
// cells for identifying variable-length shift registers,
// so attempt to convert $pmux-es to the former
if (!nosrl || help_mode)
run("pmux2shiftx", "(skip if '-nosrl')");
// Run a number of peephole optimisations, including one
// that optimises $mul cells driving $shiftx's B input
// and that aids wide mux analysis
run("peepopt");
}
if (check_label("bram", "(skip if '-nobram')")) {
if (!nobram || help_mode) {
run("memory_bram -rules +/xilinx/brams.txt");
run("techmap -map +/xilinx/brams_map.v");
}
}
if (check_label("dram", "(skip if '-nodram')")) {
if (!nodram || help_mode) {
run("memory_bram -rules +/xilinx/drams.txt");
run("techmap -map +/xilinx/drams_map.v");
}
}
if (check_label("fine")) {
run("opt -fast -full");
run("memory_map");
run("dffsr2dff");
run("dff2dffe");
run("opt -full");
if (!nosrl || help_mode) {
// shregmap operates on bit-level flops, not word-level,
// so break those down here
run("simplemap t:$dff t:$dffe", "(skip if '-nosrl')");
// shregmap with '-tech xilinx' infers variable length shift regs
run("shregmap -tech xilinx -minlen 3", "(skip if '-nosrl')");
}
std::string techmap_files = " -map +/techmap.v";
if (help_mode)
techmap_files += " [-map +/xilinx/arith_map.v]";
else if (!nocarry) {
techmap_files += " -map +/xilinx/arith_map.v";
if (vpr)
techmap_files += " -D _EXPLICIT_CARRY";
else if (abc == "abc9")
techmap_files += " -D _CLB_CARRY";
}
run("techmap " + techmap_files);
run("opt -fast");
}
if (check_label("map_cells")) {
run("techmap -map +/techmap.v -map +/xilinx/cells_map.v");
run("clean");
}
if (check_label("map_luts")) {
if (abc == "abc9")
run(abc + " -lut +/xilinx/abc_xc7.lut -box +/xilinx/abc_xc7.box -W " + XC7_WIRE_DELAY + string(retime ? " -dff" : ""));
else if (help_mode)
run(abc + " -luts 2:2,3,6:5,10,20 [-dff]");
else
run(abc + " -luts 2:2,3,6:5,10,20" + string(retime ? " -dff" : ""));
run("clean");
// This shregmap call infers fixed length shift registers after abc
// has performed any necessary retiming
if (!nosrl || help_mode)
run("shregmap -minlen 3 -init -params -enpol any_or_none", "(skip if '-nosrl')");
run("techmap -map +/xilinx/lut_map.v -map +/xilinx/ff_map.v -map +/xilinx/cells_map.v");
run("dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT "
"-ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT");
run("clean");
}
if (check_label("check")) {
run("hierarchy -check");
run("stat -tech xilinx");
run("check -noinit");
}
if (check_label("edif")) {
if (!edif_file.empty() || help_mode)
run(stringf("write_edif -pvector bra %s", edif_file.c_str()));
}
if (check_label("blif")) {
if (!blif_file.empty() || help_mode)
run(stringf("write_blif %s", edif_file.c_str()));
}
}
} SynthXilinxPass;
PRIVATE_NAMESPACE_END
|
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
#define XC7_WIRE_DELAY "300" // Number with which ABC will map a 6-input gate
// to one LUT6 (instead of a LUT5 + LUT2)
struct SynthXilinxPass : public ScriptPass
{
SynthXilinxPass() : ScriptPass("synth_xilinx", "synthesis for Xilinx FPGAs") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" synth_xilinx [options]\n");
log("\n");
log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n");
log("partly selected designs. At the moment this command creates netlists that are\n");
log("compatible with 7-Series Xilinx devices.\n");
log("\n");
log(" -top <module>\n");
log(" use the specified module as top module\n");
log("\n");
log(" -arch {xcup|xcu|xc7|xc6s}\n");
log(" run synthesis for the specified Xilinx architecture\n");
log(" default: xc7\n");
log("\n");
log(" -edif <file>\n");
log(" write the design to the specified edif file. writing of an output file\n");
log(" is omitted if this parameter is not specified.\n");
log("\n");
log(" -blif <file>\n");
log(" write the design to the specified BLIF file. writing of an output file\n");
log(" is omitted if this parameter is not specified.\n");
log("\n");
log(" -vpr\n");
log(" generate an output netlist (and BLIF file) suitable for VPR\n");
log(" (this feature is experimental and incomplete)\n");
log("\n");
log(" -nocarry\n");
log(" disable inference of carry chains\n");
log("\n");
log(" -nobram\n");
log(" disable inference of block rams\n");
log("\n");
log(" -nodram\n");
log(" disable inference of distributed rams\n");
log("\n");
log(" -nosrl\n");
log(" disable inference of shift registers\n");
log("\n");
log(" -run <from_label>:<to_label>\n");
log(" only run the commands between the labels (see below). an empty\n");
log(" from label is synonymous to 'begin', and empty to label is\n");
log(" synonymous to the end of the command list.\n");
log("\n");
log(" -flatten\n");
log(" flatten design before synthesis\n");
log("\n");
log(" -retime\n");
log(" run 'abc' with -dff option\n");
log("\n");
log(" -abc9\n");
log(" use new ABC9 flow (EXPERIMENTAL)\n");
log("\n");
log("\n");
log("The following commands are executed by this synthesis command:\n");
help_script();
log("\n");
}
std::string top_opt, edif_file, blif_file, abc, arch;
bool flatten, retime, vpr, nocarry, nobram, nodram, nosrl;
void clear_flags() YS_OVERRIDE
{
top_opt = "-auto-top";
edif_file.clear();
blif_file.clear();
abc = "abc";
flatten = false;
retime = false;
vpr = false;
nocarry = false;
nobram = false;
nodram = false;
nosrl = false;
arch = "xc7";
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
std::string run_from, run_to;
clear_flags();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-top" && argidx+1 < args.size()) {
top_opt = "-top " + args[++argidx];
continue;
}
if (args[argidx] == "-arch" && argidx+1 < args.size()) {
arch = args[++argidx];
continue;
}
if (args[argidx] == "-edif" && argidx+1 < args.size()) {
edif_file = args[++argidx];
continue;
}
if (args[argidx] == "-blif" && argidx+1 < args.size()) {
blif_file = args[++argidx];
continue;
}
if (args[argidx] == "-run" && argidx+1 < args.size()) {
size_t pos = args[argidx+1].find(':');
if (pos == std::string::npos)
break;
run_from = args[++argidx].substr(0, pos);
run_to = args[argidx].substr(pos+1);
continue;
}
if (args[argidx] == "-flatten") {
flatten = true;
continue;
}
if (args[argidx] == "-retime") {
retime = true;
continue;
}
if (args[argidx] == "-vpr") {
vpr = true;
continue;
}
if (args[argidx] == "-nocarry") {
nocarry = true;
continue;
}
if (args[argidx] == "-nobram") {
nobram = true;
continue;
}
if (args[argidx] == "-nodram") {
nodram = true;
continue;
}
if (args[argidx] == "-nosrl") {
nosrl = true;
continue;
}
if (args[argidx] == "-abc9") {
abc = "abc9";
continue;
}
break;
}
extra_args(args, argidx, design);
if (arch != "xcup" && arch != "xcu" && arch != "xc7" && arch != "xc6s")
log_cmd_error("Invalid Xilinx -arch setting: %s\n", arch.c_str());
if (!design->full_selection())
log_cmd_error("This command only operates on fully selected designs!\n");
log_header(design, "Executing SYNTH_XILINX pass.\n");
log_push();
run_script(design, run_from, run_to);
log_pop();
}
void script() YS_OVERRIDE
{
if (check_label("begin")) {
if (vpr)
run("read_verilog -lib -D _ABC -D_EXPLICIT_CARRY +/xilinx/cells_sim.v");
else
run("read_verilog -lib -D _ABC +/xilinx/cells_sim.v");
run("read_verilog -lib +/xilinx/cells_xtra.v");
if (!nobram || help_mode)
run("read_verilog -lib +/xilinx/brams_bb.v", "(skip if '-nobram')");
run(stringf("hierarchy -check %s", top_opt.c_str()));
}
if (check_label("flatten", "(with '-flatten' only)")) {
if (flatten || help_mode) {
run("proc");
run("flatten");
}
}
if (check_label("coarse")) {
run("synth -run coarse");
// shregmap -tech xilinx can cope with $shiftx and $mux
// cells for identifying variable-length shift registers,
// so attempt to convert $pmux-es to the former
if (!nosrl || help_mode)
run("pmux2shiftx", "(skip if '-nosrl')");
// Run a number of peephole optimisations, including one
// that optimises $mul cells driving $shiftx's B input
// and that aids wide mux analysis
run("peepopt");
}
if (check_label("bram", "(skip if '-nobram')")) {
if (!nobram || help_mode) {
run("memory_bram -rules +/xilinx/brams.txt");
run("techmap -map +/xilinx/brams_map.v");
}
}
if (check_label("dram", "(skip if '-nodram')")) {
if (!nodram || help_mode) {
run("memory_bram -rules +/xilinx/drams.txt");
run("techmap -map +/xilinx/drams_map.v");
}
}
if (check_label("fine")) {
run("opt -fast -full");
run("memory_map");
run("dffsr2dff");
run("dff2dffe");
run("opt -full");
if (!nosrl || help_mode) {
// shregmap operates on bit-level flops, not word-level,
// so break those down here
run("simplemap t:$dff t:$dffe", "(skip if '-nosrl')");
// shregmap with '-tech xilinx' infers variable length shift regs
run("shregmap -tech xilinx -minlen 3", "(skip if '-nosrl')");
}
std::string techmap_files = " -map +/techmap.v";
if (help_mode)
techmap_files += " [-map +/xilinx/arith_map.v]";
else if (!nocarry) {
techmap_files += " -map +/xilinx/arith_map.v";
if (vpr)
techmap_files += " -D _EXPLICIT_CARRY";
else if (abc == "abc9")
techmap_files += " -D _CLB_CARRY";
}
run("techmap " + techmap_files);
run("opt -fast");
}
if (check_label("map_cells")) {
run("techmap -map +/techmap.v -map +/xilinx/cells_map.v");
run("clean");
}
if (check_label("map_luts")) {
run("opt_expr -mux_undef");
if (abc == "abc9")
run(abc + " -lut +/xilinx/abc_xc7.lut -box +/xilinx/abc_xc7.box -W " + XC7_WIRE_DELAY + string(retime ? " -dff" : ""));
else if (help_mode)
run(abc + " -luts 2:2,3,6:5,10,20 [-dff]");
else
run(abc + " -luts 2:2,3,6:5,10,20" + string(retime ? " -dff" : ""));
run("clean");
// This shregmap call infers fixed length shift registers after abc
// has performed any necessary retiming
if (!nosrl || help_mode)
run("shregmap -minlen 3 -init -params -enpol any_or_none", "(skip if '-nosrl')");
run("techmap -map +/xilinx/lut_map.v -map +/xilinx/ff_map.v -map +/xilinx/cells_map.v");
run("dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT "
"-ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT");
run("clean");
}
if (check_label("check")) {
run("hierarchy -check");
run("stat -tech xilinx");
run("check -noinit");
}
if (check_label("edif")) {
if (!edif_file.empty() || help_mode)
run(stringf("write_edif -pvector bra %s", edif_file.c_str()));
}
if (check_label("blif")) {
if (!blif_file.empty() || help_mode)
run(stringf("write_blif %s", edif_file.c_str()));
}
}
} SynthXilinxPass;
PRIVATE_NAMESPACE_END
|
Call opt_expr -mux_undef to get rid of 1'bx in muxes prior to abc
|
Call opt_expr -mux_undef to get rid of 1'bx in muxes prior to abc
|
C++
|
isc
|
cliffordwolf/yosys,antmicro/yosys,SymbiFlow/yosys,YosysHQ/yosys,YosysHQ/yosys,YosysHQ/yosys,antmicro/yosys,YosysHQ/yosys,cliffordwolf/yosys,cliffordwolf/yosys,cliffordwolf/yosys,cliffordwolf/yosys,antmicro/yosys,antmicro/yosys,SymbiFlow/yosys,YosysHQ/yosys,antmicro/yosys,antmicro/yosys,SymbiFlow/yosys,SymbiFlow/yosys,YosysHQ/yosys,cliffordwolf/yosys,antmicro/yosys,cliffordwolf/yosys,SymbiFlow/yosys,SymbiFlow/yosys,SymbiFlow/yosys,YosysHQ/yosys,cliffordwolf/yosys,cliffordwolf/yosys,YosysHQ/yosys,SymbiFlow/yosys,antmicro/yosys
|
f4e3c558f3c57a372515b708c5f8f4a0b2d342df
|
main.cc
|
main.cc
|
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <cstdlib>
#include <cstdio>
#include <ctime>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
namespace pt = boost::property_tree;
#define VERSION 0.2
#define DEFAULT_CARD_LEN 16
// we need some generic string to lower functions for later
void cstrtolower(char *cstring)
{
for (int i=0; i<strlen(cstring); i++)
{
cstring[i] = tolower(cstring[i]);
}
}
void cstrtolower(string *cstring)
{
for (int i=0; i<cstring->size(); i++)
{
(*cstring)[i] = tolower((*cstring)[i]);
}
}
// also convert to digit
int to_digit(char c)
{
return c - '0';
}
// we also need a class to hold our app args
class arguments
{
public:
bool random;
bool verify;
bool version;
bool walk;
arguments();
void set(string);
};
arguments::arguments()
{
random = true;
verify = false;
walk = false;
version = false;
}
void arguments::set(string key)
{
random = false;
verify = false;
walk = false;
if (key == "version")
{
version = true;
}
if (key == "random")
{
random = true;
}
else if (key == "verify")
{
verify = true;
}
else if (key == "walk")
{
walk = true;
}
return;
}
// ...and a class to hold IIN data for later
class iin
{
public:
long prefix;
long length;
iin(long, long);
};
iin::iin(long p, long l)
{
prefix = p;
length = l;
}
vector<iin> prefixes;
// calculate and return our check digit using luhn algo
int get_check_digit(string number)
{
int sum = 0;
for (int i = number.size()-1; i >= 0; i-=2)
{
// double the reverse odds and calculate the sum of their digits
int x = to_digit(number[i]) * 2;
while (x > 9)
{
x -= 9;
}
// add this to the total sum
sum += x;
// reverse evens are simply added to the total sum
if (i-1 >=0)
{
sum += to_digit(number[i-1]);
}
}
return ((sum / 10 + 1) * 10 - sum) % 10;
}
// generate a random PAN for a given prefix
void rand_pan(int prefix, int length)
{
string pan;
pan = to_string(prefix);
while (pan.size() < length-1)
{
pan.append(to_string(rand() % 10));
}
cout << pan << get_check_digit(pan) << endl;
}
// generate all valid PANs for a given prefix
void walk_pan(int prefix, int length)
{
string pan;
int bucket(0);
int prefix_size = to_string(prefix).size();
int bucket_size = to_string(bucket).size();
int counter = 1;
while(bucket_size <= length - prefix_size - 1)
{
pan = to_string(prefix);
if (length - prefix_size - bucket_size - 1)
{
pan.append(length - prefix_size - bucket_size - 1, '0');
}
pan.append(to_string(bucket));
cout << pan << get_check_digit(pan) << endl;
bucket++;
bucket_size = to_string(bucket).size();
}
}
// verify if a given PAN passes the Luhn algorithm
bool verify_pan(string pan)
{
try
{
// make sure our input is a number
stol(pan);
// convert our check digit to an int
int check_digit = to_digit(pan[pan.size()-1]);
// validate check digit
if (get_check_digit(pan.substr(0, pan.size()-1)) == check_digit)
{
return true;
}
}
catch (invalid_argument& e)
{
}
catch (out_of_range& e)
{
cerr << "Error! Invalid input." << endl;
}
return false;
}
int main(int argc, char** argv)
{
arguments args;
string iin_filename = "iin.txt";
string opt;
vector<string> countries;
vector<string> issuers;
vector<string> vendors;
int force_len = 0;
// parse options
for ( int i=1; i<argc; i++ )
{
if (argv[i][0] != '-')
{
break;
}
opt = argv[i];
if (opt == "-h" || opt == "--help")
{
cout << "usage: " << argv[0] << " [options]" << endl;
cout << " -c, --country Specify a comma-separated list of 2-letter country codes to add IINs to the pool based on geographic location." << endl;
cout << " -d, --debug Enable debug output" << endl;
cout << " -h, --help Displays this help notice" << endl;
cout << " -i, --iin Specify a list of IINs to use in the IIN pool. You can add an optional PAN length (colon-separated) for each IIN" << endl;
cout << " -I, --issuers Specify a comma-separated list of issuers to use in the IIN pool" << endl;
cout << " -l, --length Force the length of the PANs being generated" << endl;
cout << " -r, --random Generate random PAN candidates for each IIN" << endl;
cout << " --verify Checks input on stdin and outputs only the valid PANs" << endl;
cout << " -v, --version Displays version info" << endl;
cout << " -V, --vendors Specify a comma-separated list of vendors to use in the IIN pool" << endl;
cout << " -w, --walk Generate all PAN candidates for each IIN" << endl;
cout << endl;
cout << "issuers:" << endl;
cout << " Card issuers can be referenced by the issuer's name. Additionally, you can use shortnames with select issuers. Please reference the iin.txt file to view all entries. e.g." << endl;
cout << " amex" << endl;
cout << " dinersclub" << endl;
cout << " jcb" << endl;
cout << " mastercard" << endl;
cout << " visa" << endl;
return 1;
}
else if (opt == "-c" || opt == "--country")
{
// split the argument into tokens
cstrtolower(argv[++i]);
boost::split(countries, argv[i], boost::is_any_of(","));
}
else if (opt == "-i" || opt == "--iin")
{
// split the argument into tokens
vector<string> iin_list;
boost::split(iin_list, argv[++i], boost::is_any_of(","));
// now tokenize each entry into IIN and length
for (int ii=0; ii < iin_list.size(); ii++)
{
vector<string> iin_meta;
boost::split(iin_meta, iin_list[ii], boost::is_any_of(":"));
// default length if none specified
if (iin_meta.size() == 1)
{
iin_meta.push_back(std::to_string(DEFAULT_CARD_LEN));
}
// push IINs to pool
prefixes.push_back(iin(stol(iin_meta[0]), stol(iin_meta[1])));
}
}
else if (opt == "-I" || opt == "--issuers")
{
// split the argument into tokens
cstrtolower(argv[++i]);
boost::split(issuers, argv[i], boost::is_any_of(","));
// expand issuer short names
for (int i=0; i< issuers.size(); i++)
{
string issuer = issuers[i];
cstrtolower(&issuer);
if (issuer == "amex")
{
issuers[i] = "american express";
}
else if (issuer == "diners")
{
issuers[i] = "diners club";
}
}
}
else if (opt == "-l" || opt == "--length")
{
force_len = std::stoi(argv[++i]);
}
else if (opt == "-V" || opt == "--vendors")
{
// split the argument into tokens
cstrtolower(argv[++i]);
boost::split(vendors, argv[i], boost::is_any_of(","));
}
else if (opt == "--verify")
{
args.set("verify");
}
else if (opt == "-v" || opt == "--version")
{
args.set("version");
}
else if (opt == "-w" || opt == "--walk")
{
args.set("walk");
}
}
if (args.version)
{
cout << "ccsiege v" << VERSION << endl;
cout << "written by unix-ninja" << endl;
cout << "(please use this software responsibly)" << endl;
return 1;
}
if (args.verify)
{
string line_input;
while (cin >> line_input)
{
if (verify_pan(line_input))
{
cout << line_input << endl;
}
}
return 0;
}
// seed PRNG for generating PANs (does not need to be crypto safe)
srand(time(NULL));
if (!prefixes.size() || vendors.size() || issuers.size())
{
// verify iin file
FILE *fp = fopen(iin_filename.c_str(),"r");
if(!fp)
{
cerr << "Error! Unable to open IIN prefix file (" << iin_filename << ")." << endl;
return 2;
}
fclose(fp);
// seed the prefix pool
pt::ptree json;
try
{
pt::read_json(iin_filename, json);
}
catch (pt::json_parser::json_parser_error e)
{
}
if (json.empty())
{
cerr << "Error! Unable to parse IIN prefix file (" << iin_filename << ")." << endl;
return 2;
}
// push prefixes to pool
for (pt::ptree::iterator it = json.begin(); it != json.end(); it++)
{
bool add_iin = true;
// filter by vendor
if (vendors.size())
{
string current_vendor = it->second.get<string>("vendor", "");
cstrtolower(¤t_vendor);
if (find(vendors.begin(), vendors.end(), current_vendor) == vendors.end())
{
add_iin = false;
}
}
// filter by issuer
if (issuers.size())
{
string current_issuer = it->second.get<string>("issuer", "");
cstrtolower(¤t_issuer);
if (find(issuers.begin(), issuers.end(), current_issuer) == issuers.end())
{
add_iin = false;
}
}
// filter by country
if (countries.size())
{
string current_country = it->second.get<string>("country", "");
cstrtolower(¤t_country);
if (find(countries.begin(), countries.end(), current_country) == countries.end())
{
add_iin = false;
}
}
if (add_iin)
{
prefixes.push_back(iin(it->second.get<int>("iin"),
(force_len ? force_len : it->second.get<int>("length", DEFAULT_CARD_LEN))));
}
}
}
// loop through PAN generation
for (int i=0; i< prefixes.size(); i++)
{
if (args.random)
{
rand_pan(prefixes[i].prefix, prefixes[i].length);
}
if (args.walk)
{
walk_pan(prefixes[i].prefix, prefixes[i].length);
}
}
return 0;
}
|
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <cstdlib>
#include <cstdio>
#include <ctime>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
namespace pt = boost::property_tree;
#define VERSION 0.2
#define DEFAULT_CARD_LEN 16
std::string app_filename;
// we need some generic string to lower functions for later
void cstrtolower(char *cstring)
{
for (int i=0; i<strlen(cstring); i++)
{
cstring[i] = tolower(cstring[i]);
}
}
void cstrtolower(string *cstring)
{
for (int i=0; i<cstring->size(); i++)
{
(*cstring)[i] = tolower((*cstring)[i]);
}
}
// also convert to digit
int to_digit(char c)
{
return c - '0';
}
// we also need a class to hold our app args
class arguments
{
public:
bool random;
bool verify;
bool version;
bool walk;
arguments();
void set(string);
};
arguments::arguments()
{
random = true;
verify = false;
walk = false;
version = false;
}
void arguments::set(string key)
{
random = false;
verify = false;
walk = false;
if (key == "version")
{
version = true;
}
if (key == "random")
{
random = true;
}
else if (key == "verify")
{
verify = true;
}
else if (key == "walk")
{
walk = true;
}
return;
}
// ...and a class to hold IIN data for later
class iin
{
public:
long prefix;
long length;
iin(long, long);
};
iin::iin(long p, long l)
{
prefix = p;
length = l;
}
vector<iin> prefixes;
// calculate and return our check digit using luhn algo
int get_check_digit(string number)
{
int sum = 0;
for (int i = number.size()-1; i >= 0; i-=2)
{
// double the reverse odds and calculate the sum of their digits
int x = to_digit(number[i]) * 2;
while (x > 9)
{
x -= 9;
}
// add this to the total sum
sum += x;
// reverse evens are simply added to the total sum
if (i-1 >=0)
{
sum += to_digit(number[i-1]);
}
}
return ((sum / 10 + 1) * 10 - sum) % 10;
}
// generate a random PAN for a given prefix
void rand_pan(int prefix, int length)
{
string pan;
pan = to_string(prefix);
while (pan.size() < length-1)
{
pan.append(to_string(rand() % 10));
}
cout << pan << get_check_digit(pan) << endl;
}
// generate all valid PANs for a given prefix
void walk_pan(int prefix, int length)
{
string pan;
int bucket(0);
int prefix_size = to_string(prefix).size();
int bucket_size = to_string(bucket).size();
int counter = 1;
while(bucket_size <= length - prefix_size - 1)
{
pan = to_string(prefix);
if (length - prefix_size - bucket_size - 1)
{
pan.append(length - prefix_size - bucket_size - 1, '0');
}
pan.append(to_string(bucket));
cout << pan << get_check_digit(pan) << endl;
bucket++;
bucket_size = to_string(bucket).size();
}
}
// verify if a given PAN passes the Luhn algorithm
bool verify_pan(string pan)
{
try
{
// make sure our input is a number
stol(pan);
// convert our check digit to an int
int check_digit = to_digit(pan[pan.size()-1]);
// validate check digit
if (get_check_digit(pan.substr(0, pan.size()-1)) == check_digit)
{
return true;
}
}
catch (invalid_argument& e)
{
}
catch (out_of_range& e)
{
cerr << "Error! Invalid input." << endl;
}
return false;
}
int usage()
{
cout << "usage: " << app_filename << " [options]" << endl;
cout << " -c, --country Specify a comma-separated list of 2-letter country codes to add IINs to the pool based on geographic location." << endl;
cout << " -d, --debug Enable debug output" << endl;
cout << " -h, --help Displays this help notice" << endl;
cout << " -i, --iin Specify a list of IINs to use in the IIN pool. You can add an optional PAN length (colon-separated) for each IIN" << endl;
cout << " -I, --issuers Specify a comma-separated list of issuers to use in the IIN pool" << endl;
cout << " -l, --length Force the length of the PANs being generated" << endl;
cout << " -r, --random Generate random PAN candidates for each IIN" << endl;
cout << " --verify Checks input on stdin and outputs only the valid PANs" << endl;
cout << " -v, --version Displays version info" << endl;
cout << " -V, --vendors Specify a comma-separated list of vendors to use in the IIN pool" << endl;
cout << " -w, --walk Generate all PAN candidates for each IIN" << endl;
cout << endl;
cout << "issuers:" << endl;
cout << " Card issuers can be referenced by the issuer's name. Additionally, you can use shortnames with select issuers. Please reference the iin.txt file to view all entries. e.g." << endl;
cout << " amex" << endl;
cout << " dinersclub" << endl;
cout << " jcb" << endl;
cout << " mastercard" << endl;
cout << " visa" << endl;
return 1;
}
int main(int argc, char** argv)
{
arguments args;
string iin_filename = "iin.txt";
string opt;
vector<string> countries;
vector<string> issuers;
vector<string> vendors;
int force_len = 0;
app_filename = argv[0];
// parse options
for ( int i=1; i<argc; i++ )
{
if (argv[i][0] != '-')
{
break;
}
opt = argv[i];
if (opt == "-h" || opt == "--help")
{
return usage();
}
else if (opt == "-c" || opt == "--country")
{
// split the argument into tokens
cstrtolower(argv[++i]);
boost::split(countries, argv[i], boost::is_any_of(","));
}
else if (opt == "-i" || opt == "--iin")
{
// make sure we have an argument to assign
if (i == argc-1) return usage();
// split the argument into tokens
vector<string> iin_list;
boost::split(iin_list, argv[++i], boost::is_any_of(","));
// now tokenize each entry into IIN and length
for (int ii=0; ii < iin_list.size(); ii++)
{
vector<string> iin_meta;
boost::split(iin_meta, iin_list[ii], boost::is_any_of(":"));
// default length if none specified
if (iin_meta.size() == 1)
{
iin_meta.push_back(std::to_string(DEFAULT_CARD_LEN));
}
// push IINs to pool
prefixes.push_back(iin(stol(iin_meta[0]), stol(iin_meta[1])));
}
}
else if (opt == "-I" || opt == "--issuers")
{
// make sure we have an argument to assign
if (i == argc-1) return usage();
// split the argument into tokens
cstrtolower(argv[++i]);
boost::split(issuers, argv[i], boost::is_any_of(","));
// expand issuer short names
for (int i=0; i< issuers.size(); i++)
{
string issuer = issuers[i];
cstrtolower(&issuer);
if (issuer == "amex")
{
issuers[i] = "american express";
}
else if (issuer == "diners")
{
issuers[i] = "diners club";
}
}
}
else if (opt == "-l" || opt == "--length")
{
// make sure we have an argument to assign
if (i == argc-1) return usage();
force_len = std::stoi(argv[++i]);
}
else if (opt == "-V" || opt == "--vendors")
{
// make sure we have an argument to assign
if (i == argc-1) return usage();
// split the argument into tokens
cstrtolower(argv[++i]);
boost::split(vendors, argv[i], boost::is_any_of(","));
}
else if (opt == "--verify")
{
args.set("verify");
}
else if (opt == "-v" || opt == "--version")
{
args.set("version");
}
else if (opt == "-w" || opt == "--walk")
{
args.set("walk");
}
}
if (args.version)
{
cout << "ccsiege v" << VERSION << endl;
cout << "written by unix-ninja" << endl;
cout << "(please use this software responsibly)" << endl;
return 1;
}
if (args.verify)
{
string line_input;
while (cin >> line_input)
{
if (verify_pan(line_input))
{
cout << line_input << endl;
}
}
return 0;
}
// seed PRNG for generating PANs (does not need to be crypto safe)
srand(time(NULL));
if (!prefixes.size() || vendors.size() || issuers.size())
{
// verify iin file
FILE *fp = fopen(iin_filename.c_str(),"r");
if(!fp)
{
cerr << "Error! Unable to open IIN prefix file (" << iin_filename << ")." << endl;
return 2;
}
fclose(fp);
// seed the prefix pool
pt::ptree json;
try
{
pt::read_json(iin_filename, json);
}
catch (pt::json_parser::json_parser_error e)
{
}
if (json.empty())
{
cerr << "Error! Unable to parse IIN prefix file (" << iin_filename << ")." << endl;
return 2;
}
// push prefixes to pool
for (pt::ptree::iterator it = json.begin(); it != json.end(); it++)
{
bool add_iin = true;
// filter by vendor
if (vendors.size())
{
string current_vendor = it->second.get<string>("vendor", "");
cstrtolower(¤t_vendor);
if (find(vendors.begin(), vendors.end(), current_vendor) == vendors.end())
{
add_iin = false;
}
}
// filter by issuer
if (issuers.size())
{
string current_issuer = it->second.get<string>("issuer", "");
cstrtolower(¤t_issuer);
if (find(issuers.begin(), issuers.end(), current_issuer) == issuers.end())
{
add_iin = false;
}
}
// filter by country
if (countries.size())
{
string current_country = it->second.get<string>("country", "");
cstrtolower(¤t_country);
if (find(countries.begin(), countries.end(), current_country) == countries.end())
{
add_iin = false;
}
}
if (add_iin)
{
prefixes.push_back(iin(it->second.get<int>("iin"),
(force_len ? force_len : it->second.get<int>("length", DEFAULT_CARD_LEN))));
}
}
}
// loop through PAN generation
for (int i=0; i< prefixes.size(); i++)
{
if (args.random)
{
rand_pan(prefixes[i].prefix, prefixes[i].length);
}
if (args.walk)
{
walk_pan(prefixes[i].prefix, prefixes[i].length);
}
}
return 0;
}
|
Validate arugments for flags
|
Validate arugments for flags
|
C++
|
bsd-2-clause
|
unix-ninja/ccsiege
|
49f340fd1690ef6c83910bb2a07bb71aa41b2af0
|
test/core/promise/sleep_test.cc
|
test/core/promise/sleep_test.cc
|
// Copyright 2022 gRPC authors.
//
// 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 "src/core/lib/promise/sleep.h"
#include <algorithm>
#include <cstddef>
#include <memory>
#include <utility>
#include <vector>
#include "absl/synchronization/notification.h"
#include "gtest/gtest.h"
#include <grpc/grpc.h>
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/promise/exec_ctx_wakeup_scheduler.h"
#include "src/core/lib/promise/race.h"
#include "test/core/promise/test_wakeup_schedulers.h"
namespace grpc_core {
namespace {
TEST(Sleep, Zzzz) {
ExecCtx exec_ctx;
absl::Notification done;
Timestamp done_time = ExecCtx::Get()->Now() + Duration::Seconds(1);
// Sleep for one second then set done to true.
auto activity = MakeActivity(Sleep(done_time), InlineWakeupScheduler(),
[&done](absl::Status r) {
EXPECT_EQ(r, absl::OkStatus());
done.Notify();
});
done.WaitForNotification();
exec_ctx.InvalidateNow();
EXPECT_GE(ExecCtx::Get()->Now(), done_time);
}
TEST(Sleep, AlreadyDone) {
ExecCtx exec_ctx;
absl::Notification done;
Timestamp done_time = ExecCtx::Get()->Now() - Duration::Seconds(1);
// Sleep for no time at all then set done to true.
auto activity = MakeActivity(Sleep(done_time), InlineWakeupScheduler(),
[&done](absl::Status r) {
EXPECT_EQ(r, absl::OkStatus());
done.Notify();
});
done.WaitForNotification();
}
TEST(Sleep, Cancel) {
ExecCtx exec_ctx;
absl::Notification done;
Timestamp done_time = ExecCtx::Get()->Now() + Duration::Seconds(1);
// Sleep for one second but race it to complete immediately
auto activity = MakeActivity(
Race(Sleep(done_time), [] { return absl::CancelledError(); }),
InlineWakeupScheduler(), [&done](absl::Status r) {
EXPECT_EQ(r, absl::CancelledError());
done.Notify();
});
done.WaitForNotification();
exec_ctx.InvalidateNow();
EXPECT_LT(ExecCtx::Get()->Now(), done_time);
}
TEST(Sleep, MoveSemantics) {
// ASAN should help determine if there are any memory leaks here
ExecCtx exec_ctx;
absl::Notification done;
Timestamp done_time = ExecCtx::Get()->Now() + Duration::Milliseconds(111);
Sleep donor(done_time);
Sleep sleeper = std::move(donor);
auto activity = MakeActivity(std::move(sleeper), InlineWakeupScheduler(),
[&done](absl::Status r) {
EXPECT_EQ(r, absl::OkStatus());
done.Notify();
});
done.WaitForNotification();
exec_ctx.InvalidateNow();
EXPECT_GE(ExecCtx::Get()->Now(), done_time);
}
TEST(Sleep, StressTest) {
// Kick off a bunch sleeps for one second.
static const int kNumActivities = 100000;
ExecCtx exec_ctx;
std::vector<std::shared_ptr<absl::Notification>> notifications;
std::vector<ActivityPtr> activities;
gpr_log(GPR_INFO, "Starting %d sleeps for 1sec", kNumActivities);
for (int i = 0; i < kNumActivities; i++) {
auto notification = std::make_shared<absl::Notification>();
auto activity = MakeActivity(
Sleep(exec_ctx.Now() + Duration::Seconds(1)), ExecCtxWakeupScheduler(),
[notification](absl::Status r) { notification->Notify(); });
notifications.push_back(std::move(notification));
activities.push_back(std::move(activity));
}
gpr_log(GPR_INFO,
"Waiting for the first %d sleeps, whilst cancelling the other half",
kNumActivities / 2);
for (size_t i = 0; i < kNumActivities / 2; i++) {
notifications[i]->WaitForNotification();
activities[i].reset();
activities[i + kNumActivities / 2].reset();
exec_ctx.Flush();
}
}
} // namespace
} // namespace grpc_core
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
grpc_init();
int r = RUN_ALL_TESTS();
grpc_shutdown();
return r;
}
|
// Copyright 2022 gRPC authors.
//
// 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 "src/core/lib/promise/sleep.h"
#include <algorithm>
#include <cstddef>
#include <memory>
#include <utility>
#include <vector>
#include "absl/synchronization/notification.h"
#include "gtest/gtest.h"
#include <grpc/grpc.h>
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/promise/exec_ctx_wakeup_scheduler.h"
#include "src/core/lib/promise/race.h"
#include "test/core/promise/test_wakeup_schedulers.h"
namespace grpc_core {
namespace {
TEST(Sleep, Zzzz) {
ExecCtx exec_ctx;
absl::Notification done;
Timestamp done_time = ExecCtx::Get()->Now() + Duration::Seconds(1);
// Sleep for one second then set done to true.
auto activity = MakeActivity(Sleep(done_time), InlineWakeupScheduler(),
[&done](absl::Status r) {
EXPECT_EQ(r, absl::OkStatus());
done.Notify();
});
done.WaitForNotification();
exec_ctx.InvalidateNow();
EXPECT_GE(ExecCtx::Get()->Now(), done_time);
}
TEST(Sleep, AlreadyDone) {
ExecCtx exec_ctx;
absl::Notification done;
Timestamp done_time = ExecCtx::Get()->Now() - Duration::Seconds(1);
// Sleep for no time at all then set done to true.
auto activity = MakeActivity(Sleep(done_time), InlineWakeupScheduler(),
[&done](absl::Status r) {
EXPECT_EQ(r, absl::OkStatus());
done.Notify();
});
done.WaitForNotification();
}
TEST(Sleep, Cancel) {
ExecCtx exec_ctx;
absl::Notification done;
Timestamp done_time = ExecCtx::Get()->Now() + Duration::Seconds(1);
// Sleep for one second but race it to complete immediately
auto activity = MakeActivity(
Race(Sleep(done_time), [] { return absl::CancelledError(); }),
InlineWakeupScheduler(), [&done](absl::Status r) {
EXPECT_EQ(r, absl::CancelledError());
done.Notify();
});
done.WaitForNotification();
exec_ctx.InvalidateNow();
EXPECT_LT(ExecCtx::Get()->Now(), done_time);
}
TEST(Sleep, MoveSemantics) {
// ASAN should help determine if there are any memory leaks here
ExecCtx exec_ctx;
absl::Notification done;
Timestamp done_time = ExecCtx::Get()->Now() + Duration::Milliseconds(111);
Sleep donor(done_time);
Sleep sleeper = std::move(donor);
auto activity = MakeActivity(std::move(sleeper), InlineWakeupScheduler(),
[&done](absl::Status r) {
EXPECT_EQ(r, absl::OkStatus());
done.Notify();
});
done.WaitForNotification();
exec_ctx.InvalidateNow();
EXPECT_GE(ExecCtx::Get()->Now(), done_time);
}
TEST(Sleep, StressTest) {
// Kick off a bunch sleeps for one second.
static const int kNumActivities = 100000;
ExecCtx exec_ctx;
std::vector<std::shared_ptr<absl::Notification>> notifications;
std::vector<ActivityPtr> activities;
gpr_log(GPR_INFO, "Starting %d sleeps for 1sec", kNumActivities);
for (int i = 0; i < kNumActivities; i++) {
auto notification = std::make_shared<absl::Notification>();
auto activity = MakeActivity(
Sleep(exec_ctx.Now() + Duration::Seconds(1)), ExecCtxWakeupScheduler(),
[notification](absl::Status /*r*/) { notification->Notify(); });
notifications.push_back(std::move(notification));
activities.push_back(std::move(activity));
}
gpr_log(GPR_INFO,
"Waiting for the first %d sleeps, whilst cancelling the other half",
kNumActivities / 2);
for (size_t i = 0; i < kNumActivities / 2; i++) {
notifications[i]->WaitForNotification();
activities[i].reset();
activities[i + kNumActivities / 2].reset();
exec_ctx.Flush();
}
}
} // namespace
} // namespace grpc_core
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
grpc_init();
int r = RUN_ALL_TESTS();
grpc_shutdown();
return r;
}
|
Fix unused parameter error (#30482)
|
Fix unused parameter error (#30482)
|
C++
|
apache-2.0
|
jtattermusch/grpc,stanley-cheung/grpc,ctiller/grpc,ctiller/grpc,ctiller/grpc,grpc/grpc,stanley-cheung/grpc,stanley-cheung/grpc,stanley-cheung/grpc,ctiller/grpc,stanley-cheung/grpc,stanley-cheung/grpc,stanley-cheung/grpc,ejona86/grpc,stanley-cheung/grpc,jtattermusch/grpc,ctiller/grpc,ctiller/grpc,ctiller/grpc,jtattermusch/grpc,grpc/grpc,grpc/grpc,grpc/grpc,grpc/grpc,stanley-cheung/grpc,grpc/grpc,ctiller/grpc,jtattermusch/grpc,grpc/grpc,ejona86/grpc,ctiller/grpc,grpc/grpc,grpc/grpc,ctiller/grpc,ejona86/grpc,jtattermusch/grpc,ejona86/grpc,ejona86/grpc,ejona86/grpc,ejona86/grpc,jtattermusch/grpc,jtattermusch/grpc,jtattermusch/grpc,ejona86/grpc,grpc/grpc,ctiller/grpc,stanley-cheung/grpc,ejona86/grpc,stanley-cheung/grpc,ejona86/grpc,ejona86/grpc,grpc/grpc,jtattermusch/grpc,ctiller/grpc,jtattermusch/grpc,stanley-cheung/grpc,grpc/grpc,jtattermusch/grpc,ejona86/grpc,jtattermusch/grpc
|
171af2b154232760d901bcb827472a70f2826342
|
chrome/browser/notifications/notification_audio_controller_unittest.cc
|
chrome/browser/notifications/notification_audio_controller_unittest.cc
|
// Copyright 2013 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 "chrome/browser/notifications/notification_audio_controller.h"
#include "base/bind.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/run_loop.h"
#include "chrome/test/base/testing_profile.h"
#include "media/audio/audio_manager.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// Sample audio data
const char kTestAudioData[] = "RIFF\x26\x00\x00\x00WAVEfmt \x10\x00\x00\x00"
"\x01\x00\x02\x00\x80\xbb\x00\x00\x00\x77\x01\x00\x02\x00\x10\x00"
"data\x04\x00\x00\x00\x01\x00\x01\x00";
const char kInvalidAudioData[] = "invalid audio data";
const char kDummyNotificationId[] = "dummy_id";
const char kDummyNotificationId2[] = "dummy_id2";
void CopyResultAndQuit(
base::RunLoop* run_loop, size_t *result_ptr, size_t result) {
*result_ptr = result;
run_loop->Quit();
}
} // namespace
class NotificationAudioControllerTest : public testing::Test {
public:
NotificationAudioControllerTest() {
audio_manager_.reset(media::AudioManager::Create());
notification_audio_controller_ = new NotificationAudioController();
notification_audio_controller_->UseFakeAudioOutputForTest();
}
virtual ~NotificationAudioControllerTest() {
notification_audio_controller_->RequestShutdown();
audio_manager_.reset();
}
protected:
NotificationAudioController* notification_audio_controller() {
return notification_audio_controller_;
}
Profile* profile() { return &profile_; }
size_t GetHandlersSize() {
base::RunLoop run_loop;
size_t result = 0;
notification_audio_controller_->GetAudioHandlersSizeForTest(
base::Bind(&CopyResultAndQuit, &run_loop, &result));
run_loop.Run();
return result;
}
private:
base::MessageLoopForUI message_loop_;
TestingProfile profile_;
NotificationAudioController* notification_audio_controller_;
scoped_ptr<media::AudioManager> audio_manager_;
DISALLOW_COPY_AND_ASSIGN(NotificationAudioControllerTest);
};
TEST_F(NotificationAudioControllerTest, PlaySound) {
notification_audio_controller()->RequestPlayNotificationSound(
kDummyNotificationId,
profile(),
base::StringPiece(kTestAudioData, arraysize(kTestAudioData)));
// Still playing the sound, not empty yet.
EXPECT_EQ(1u, GetHandlersSize());
}
TEST_F(NotificationAudioControllerTest, PlayInvalidSound) {
notification_audio_controller()->RequestPlayNotificationSound(
kDummyNotificationId,
profile(),
base::StringPiece(kInvalidAudioData, arraysize(kInvalidAudioData)));
EXPECT_EQ(0u, GetHandlersSize());
}
TEST_F(NotificationAudioControllerTest, PlayTwoSounds) {
notification_audio_controller()->RequestPlayNotificationSound(
kDummyNotificationId,
profile(),
base::StringPiece(kTestAudioData, arraysize(kTestAudioData)));
notification_audio_controller()->RequestPlayNotificationSound(
kDummyNotificationId2,
profile(),
base::StringPiece(kTestAudioData, arraysize(kTestAudioData)));
EXPECT_EQ(2u, GetHandlersSize());
}
TEST_F(NotificationAudioControllerTest, PlaySoundTwice) {
notification_audio_controller()->RequestPlayNotificationSound(
kDummyNotificationId,
profile(),
base::StringPiece(kTestAudioData, arraysize(kTestAudioData)));
notification_audio_controller()->RequestPlayNotificationSound(
kDummyNotificationId,
profile(),
base::StringPiece(kTestAudioData, arraysize(kTestAudioData)));
EXPECT_EQ(1u, GetHandlersSize());
}
TEST_F(NotificationAudioControllerTest, MultiProfiles) {
TestingProfile profile2;
notification_audio_controller()->RequestPlayNotificationSound(
kDummyNotificationId,
profile(),
base::StringPiece(kTestAudioData, arraysize(kTestAudioData)));
notification_audio_controller()->RequestPlayNotificationSound(
kDummyNotificationId,
&profile2,
base::StringPiece(kTestAudioData, arraysize(kTestAudioData)));
EXPECT_EQ(2u, GetHandlersSize());
}
|
// Copyright 2013 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 "chrome/browser/notifications/notification_audio_controller.h"
#include "base/bind.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/run_loop.h"
#include "chrome/test/base/testing_profile.h"
#include "media/audio/audio_manager.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// Sample audio data
const char kTestAudioData[] = "RIFF\x26\x00\x00\x00WAVEfmt \x10\x00\x00\x00"
"\x01\x00\x02\x00\x80\xbb\x00\x00\x00\x77\x01\x00\x02\x00\x10\x00"
"data\x04\x00\x00\x00\x01\x00\x01\x00";
const char kInvalidAudioData[] = "invalid audio data";
const char kDummyNotificationId[] = "dummy_id";
const char kDummyNotificationId2[] = "dummy_id2";
void CopyResultAndQuit(
base::RunLoop* run_loop, size_t *result_ptr, size_t result) {
*result_ptr = result;
run_loop->Quit();
}
} // namespace
class NotificationAudioControllerTest : public testing::Test {
public:
NotificationAudioControllerTest() {
audio_manager_.reset(media::AudioManager::Create());
notification_audio_controller_ = new NotificationAudioController();
notification_audio_controller_->UseFakeAudioOutputForTest();
}
virtual ~NotificationAudioControllerTest() {
notification_audio_controller_->RequestShutdown();
audio_manager_.reset();
}
protected:
NotificationAudioController* notification_audio_controller() {
return notification_audio_controller_;
}
Profile* profile() { return &profile_; }
size_t GetHandlersSize() {
base::RunLoop run_loop;
size_t result = 0;
notification_audio_controller_->GetAudioHandlersSizeForTest(
base::Bind(&CopyResultAndQuit, &run_loop, &result));
run_loop.Run();
return result;
}
private:
base::MessageLoopForUI message_loop_;
TestingProfile profile_;
NotificationAudioController* notification_audio_controller_;
scoped_ptr<media::AudioManager> audio_manager_;
DISALLOW_COPY_AND_ASSIGN(NotificationAudioControllerTest);
};
TEST_F(NotificationAudioControllerTest, PlaySound) {
notification_audio_controller()->RequestPlayNotificationSound(
kDummyNotificationId,
profile(),
base::StringPiece(kTestAudioData, arraysize(kTestAudioData)));
// Still playing the sound, not empty yet.
EXPECT_EQ(1u, GetHandlersSize());
}
// TODO(mukai): http://crbug.com/246061
#if !defined(OS_WIN) && !defined(ARCH_CPU_X86_64)
TEST_F(NotificationAudioControllerTest, PlayInvalidSound) {
notification_audio_controller()->RequestPlayNotificationSound(
kDummyNotificationId,
profile(),
base::StringPiece(kInvalidAudioData, arraysize(kInvalidAudioData)));
EXPECT_EQ(0u, GetHandlersSize());
}
#endif
TEST_F(NotificationAudioControllerTest, PlayTwoSounds) {
notification_audio_controller()->RequestPlayNotificationSound(
kDummyNotificationId,
profile(),
base::StringPiece(kTestAudioData, arraysize(kTestAudioData)));
notification_audio_controller()->RequestPlayNotificationSound(
kDummyNotificationId2,
profile(),
base::StringPiece(kTestAudioData, arraysize(kTestAudioData)));
EXPECT_EQ(2u, GetHandlersSize());
}
TEST_F(NotificationAudioControllerTest, PlaySoundTwice) {
notification_audio_controller()->RequestPlayNotificationSound(
kDummyNotificationId,
profile(),
base::StringPiece(kTestAudioData, arraysize(kTestAudioData)));
notification_audio_controller()->RequestPlayNotificationSound(
kDummyNotificationId,
profile(),
base::StringPiece(kTestAudioData, arraysize(kTestAudioData)));
EXPECT_EQ(1u, GetHandlersSize());
}
TEST_F(NotificationAudioControllerTest, MultiProfiles) {
TestingProfile profile2;
notification_audio_controller()->RequestPlayNotificationSound(
kDummyNotificationId,
profile(),
base::StringPiece(kTestAudioData, arraysize(kTestAudioData)));
notification_audio_controller()->RequestPlayNotificationSound(
kDummyNotificationId,
&profile2,
base::StringPiece(kTestAudioData, arraysize(kTestAudioData)));
EXPECT_EQ(2u, GetHandlersSize());
}
|
Disable NotificationAudioControllerTest.PlayInvalidSound on Win64 build
|
Disable NotificationAudioControllerTest.PlayInvalidSound on Win64 build
[email protected]
[email protected]
Review URL: https://codereview.chromium.org/16310003
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@203655 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,ltilve/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,anirudhSK/chromium,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,M4sse/chromium.src,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,patrickm/chromium.src,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,markYoungH/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,anirudhSK/chromium,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,littlstar/chromium.src,ltilve/chromium,Jonekee/chromium.src,M4sse/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,Chilledheart/chromium,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,dednal/chromium.src,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,Chilledheart/chromium,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,anirudhSK/chromium,dushu1203/chromium.src,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,markYoungH/chromium.src,hujiajie/pa-chromium,dushu1203/chromium.src,axinging/chromium-crosswalk,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,ltilve/chromium,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,jaruba/chromium.src,littlstar/chromium.src,Just-D/chromium-1,Just-D/chromium-1,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,dushu1203/chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,ondra-novak/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,dushu1203/chromium.src,dednal/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,anirudhSK/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,patrickm/chromium.src,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,ltilve/chromium,mogoweb/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,patrickm/chromium.src,anirudhSK/chromium,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,littlstar/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,dednal/chromium.src,Chilledheart/chromium,mogoweb/chromium-crosswalk,M4sse/chromium.src,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,Just-D/chromium-1,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,Jonekee/chromium.src,Chilledheart/chromium,littlstar/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,Just-D/chromium-1,axinging/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,Jonekee/chromium.src,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,Chilledheart/chromium,jaruba/chromium.src,mogoweb/chromium-crosswalk,ltilve/chromium,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,dushu1203/chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,dednal/chromium.src,ltilve/chromium,littlstar/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,M4sse/chromium.src,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,dushu1203/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,dushu1203/chromium.src,fujunwei/chromium-crosswalk,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk
|
050c957a495efc03f6a08efd4d019eee2e834cb4
|
chrome/browser/safe_browsing/client_side_detection_service_unittest.cc
|
chrome/browser/safe_browsing/client_side_detection_service_unittest.cc
|
// 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 <map>
#include <string>
#include "base/callback.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/file_util_proxy.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/platform_file.h"
#include "base/scoped_ptr.h"
#include "base/scoped_temp_dir.h"
#include "base/task.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/safe_browsing/client_side_detection_service.h"
#include "chrome/browser/safe_browsing/csd.pb.h"
#include "chrome/common/net/test_url_fetcher_factory.h"
#include "chrome/common/net/url_fetcher.h"
#include "googleurl/src/gurl.h"
#include "net/url_request/url_request_status.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace safe_browsing {
class ClientSideDetectionServiceTest : public testing::Test {
protected:
virtual void SetUp() {
file_thread_.reset(new BrowserThread(BrowserThread::FILE));
file_thread_->Start();
factory_.reset(new FakeURLFetcherFactory());
URLFetcher::set_factory(factory_.get());
browser_thread_.reset(new BrowserThread(BrowserThread::UI, &msg_loop_));
}
virtual void TearDown() {
csd_service_.reset();
msg_loop_.RunAllPending();
URLFetcher::set_factory(NULL);
file_thread_.reset();
browser_thread_.reset();
}
base::PlatformFile GetModelFile() {
model_file_ = base::kInvalidPlatformFileValue;
csd_service_->GetModelFile(NewCallback(
this, &ClientSideDetectionServiceTest::GetModelFileDone));
// This method will block this thread until GetModelFileDone is called.
msg_loop_.Run();
return model_file_;
}
std::string ReadModelFile(base::PlatformFile model_file) {
char buf[1024];
int n = base::ReadPlatformFile(model_file, 0, buf, 1024);
EXPECT_LE(0, n);
return (n < 0) ? "" : std::string(buf, n);
}
bool SendClientReportPhishingRequest(const GURL& phishing_url,
double score,
SkBitmap thumbnail) {
csd_service_->SendClientReportPhishingRequest(
phishing_url,
score,
thumbnail,
NewCallback(this, &ClientSideDetectionServiceTest::SendRequestDone));
phishing_url_ = phishing_url;
msg_loop_.Run(); // Waits until callback is called.
return is_phishing_;
}
void SetModelFetchResponse(std::string response_data, bool success) {
factory_->SetFakeResponse(ClientSideDetectionService::kClientModelUrl,
response_data, success);
}
void SetClientReportPhishingResponse(std::string response_data,
bool success) {
factory_->SetFakeResponse(
ClientSideDetectionService::kClientReportPhishingUrl,
response_data, success);
}
protected:
scoped_ptr<ClientSideDetectionService> csd_service_;
scoped_ptr<FakeURLFetcherFactory> factory_;
private:
void GetModelFileDone(base::PlatformFile model_file) {
model_file_ = model_file;
msg_loop_.Quit();
}
void SendRequestDone(GURL phishing_url, bool is_phishing) {
ASSERT_EQ(phishing_url, phishing_url_);
is_phishing_ = is_phishing;
msg_loop_.Quit();
}
MessageLoop msg_loop_;
scoped_ptr<BrowserThread> browser_thread_;
base::PlatformFile model_file_;
scoped_ptr<BrowserThread> file_thread_;
GURL phishing_url_;
bool is_phishing_;
};
TEST_F(ClientSideDetectionServiceTest, TestFetchingModel) {
ScopedTempDir tmp_dir;
ASSERT_TRUE(tmp_dir.CreateUniqueTempDir());
FilePath model_path = tmp_dir.path().AppendASCII("model");
// The first time we create the csd service the model file does not exist so
// we expect there to be a fetch.
SetModelFetchResponse("BOGUS MODEL", true);
csd_service_.reset(ClientSideDetectionService::Create(model_path, NULL));
base::PlatformFile model_file = GetModelFile();
EXPECT_NE(model_file, base::kInvalidPlatformFileValue);
EXPECT_EQ(ReadModelFile(model_file), "BOGUS MODEL");
// If you call GetModelFile() multiple times you always get the same platform
// file back. We don't re-open the file.
EXPECT_EQ(GetModelFile(), model_file);
// The second time the model already exists on disk. In this case there
// should not be any fetch. To ensure that we clear the factory.
factory_->ClearFakeReponses();
csd_service_.reset(ClientSideDetectionService::Create(model_path, NULL));
model_file = GetModelFile();
EXPECT_NE(model_file, base::kInvalidPlatformFileValue);
EXPECT_EQ(ReadModelFile(model_file), "BOGUS MODEL");
// If the model does not exist and the fetch fails we should get an error.
model_path = tmp_dir.path().AppendASCII("another_model");
SetModelFetchResponse("", false /* success */);
csd_service_.reset(ClientSideDetectionService::Create(model_path, NULL));
EXPECT_EQ(GetModelFile(), base::kInvalidPlatformFileValue);
}
TEST_F(ClientSideDetectionServiceTest, SendClientReportPhishingRequest) {
SetModelFetchResponse("bogus model", true /* success */);
ScopedTempDir tmp_dir;
ASSERT_TRUE(tmp_dir.CreateUniqueTempDir());
csd_service_.reset(ClientSideDetectionService::Create(
tmp_dir.path().AppendASCII("model"), NULL));
// Invalid thumbnail.
SkBitmap thumbnail;
GURL url("http://a.com/");
double score = 0.4; // Some random client score.
EXPECT_FALSE(SendClientReportPhishingRequest(url, score, thumbnail));
// Valid thumbnail but the server returns an error.
thumbnail.setConfig(SkBitmap::kARGB_8888_Config, 100, 100);
ASSERT_TRUE(thumbnail.allocPixels());
thumbnail.eraseRGB(255, 0, 0);
SetClientReportPhishingResponse("", false /* fail */);
EXPECT_FALSE(SendClientReportPhishingRequest(url, score, thumbnail));
// Invalid response body from the server.
SetClientReportPhishingResponse("invalid proto response", true /* success */);
EXPECT_FALSE(SendClientReportPhishingRequest(url, score, thumbnail));
// Normal behavior.
ClientPhishingResponse response;
response.set_phishy(true);
SetClientReportPhishingResponse(response.SerializeAsString(),
true /* success */);
EXPECT_TRUE(SendClientReportPhishingRequest(url, score, thumbnail));
response.set_phishy(false);
SetClientReportPhishingResponse(response.SerializeAsString(),
true /* success */);
EXPECT_FALSE(SendClientReportPhishingRequest(url, score, thumbnail));
}
} // namespace safe_browsing
|
// 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 <map>
#include <string>
#include "base/callback.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/file_util_proxy.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/platform_file.h"
#include "base/scoped_ptr.h"
#include "base/scoped_temp_dir.h"
#include "base/task.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/safe_browsing/client_side_detection_service.h"
#include "chrome/browser/safe_browsing/csd.pb.h"
#include "chrome/common/net/test_url_fetcher_factory.h"
#include "chrome/common/net/url_fetcher.h"
#include "googleurl/src/gurl.h"
#include "net/url_request/url_request_status.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace safe_browsing {
class ClientSideDetectionServiceTest : public testing::Test {
protected:
virtual void SetUp() {
file_thread_.reset(new BrowserThread(BrowserThread::FILE));
file_thread_->Start();
factory_.reset(new FakeURLFetcherFactory());
URLFetcher::set_factory(factory_.get());
browser_thread_.reset(new BrowserThread(BrowserThread::UI, &msg_loop_));
}
virtual void TearDown() {
csd_service_.reset();
msg_loop_.RunAllPending();
URLFetcher::set_factory(NULL);
file_thread_.reset();
browser_thread_.reset();
}
base::PlatformFile GetModelFile() {
model_file_ = base::kInvalidPlatformFileValue;
csd_service_->GetModelFile(NewCallback(
this, &ClientSideDetectionServiceTest::GetModelFileDone));
// This method will block this thread until GetModelFileDone is called.
msg_loop_.Run();
return model_file_;
}
std::string ReadModelFile(base::PlatformFile model_file) {
char buf[1024];
int n = base::ReadPlatformFile(model_file, 0, buf, 1024);
EXPECT_LE(0, n);
return (n < 0) ? "" : std::string(buf, n);
}
bool SendClientReportPhishingRequest(const GURL& phishing_url,
double score,
SkBitmap thumbnail) {
csd_service_->SendClientReportPhishingRequest(
phishing_url,
score,
thumbnail,
NewCallback(this, &ClientSideDetectionServiceTest::SendRequestDone));
phishing_url_ = phishing_url;
msg_loop_.Run(); // Waits until callback is called.
return is_phishing_;
}
void SetModelFetchResponse(std::string response_data, bool success) {
factory_->SetFakeResponse(ClientSideDetectionService::kClientModelUrl,
response_data, success);
}
void SetClientReportPhishingResponse(std::string response_data,
bool success) {
factory_->SetFakeResponse(
ClientSideDetectionService::kClientReportPhishingUrl,
response_data, success);
}
protected:
scoped_ptr<ClientSideDetectionService> csd_service_;
scoped_ptr<FakeURLFetcherFactory> factory_;
private:
void GetModelFileDone(base::PlatformFile model_file) {
model_file_ = model_file;
msg_loop_.Quit();
}
void SendRequestDone(GURL phishing_url, bool is_phishing) {
ASSERT_EQ(phishing_url, phishing_url_);
is_phishing_ = is_phishing;
msg_loop_.Quit();
}
MessageLoop msg_loop_;
scoped_ptr<BrowserThread> browser_thread_;
base::PlatformFile model_file_;
scoped_ptr<BrowserThread> file_thread_;
GURL phishing_url_;
bool is_phishing_;
};
TEST_F(ClientSideDetectionServiceTest, TestFetchingModel) {
ScopedTempDir tmp_dir;
ASSERT_TRUE(tmp_dir.CreateUniqueTempDir());
FilePath model_path = tmp_dir.path().AppendASCII("model");
// The first time we create the csd service the model file does not exist so
// we expect there to be a fetch.
SetModelFetchResponse("BOGUS MODEL", true);
csd_service_.reset(ClientSideDetectionService::Create(model_path, NULL));
base::PlatformFile model_file = GetModelFile();
EXPECT_NE(model_file, base::kInvalidPlatformFileValue);
EXPECT_EQ(ReadModelFile(model_file), "BOGUS MODEL");
// If you call GetModelFile() multiple times you always get the same platform
// file back. We don't re-open the file.
EXPECT_EQ(GetModelFile(), model_file);
// The second time the model already exists on disk. In this case there
// should not be any fetch. To ensure that we clear the factory.
factory_->ClearFakeReponses();
csd_service_.reset(ClientSideDetectionService::Create(model_path, NULL));
model_file = GetModelFile();
EXPECT_NE(model_file, base::kInvalidPlatformFileValue);
EXPECT_EQ(ReadModelFile(model_file), "BOGUS MODEL");
// If the model does not exist and the fetch fails we should get an error.
model_path = tmp_dir.path().AppendASCII("another_model");
SetModelFetchResponse("", false /* success */);
csd_service_.reset(ClientSideDetectionService::Create(model_path, NULL));
EXPECT_EQ(GetModelFile(), base::kInvalidPlatformFileValue);
}
#if defined(OS_MACOSX)
// Sometimes crashes on Mac 10.5 bot: http://crbug.com/63358
#define MAYBE_SendClientReportPhishingRequest \
DISABLED_SendClientReportPhishingRequest
#else
#define MAYBE_SendClientReportPhishingRequest SendClientReportPhishingRequest
#endif
TEST_F(ClientSideDetectionServiceTest, MAYBE_SendClientReportPhishingRequest) {
SetModelFetchResponse("bogus model", true /* success */);
ScopedTempDir tmp_dir;
ASSERT_TRUE(tmp_dir.CreateUniqueTempDir());
csd_service_.reset(ClientSideDetectionService::Create(
tmp_dir.path().AppendASCII("model"), NULL));
// Invalid thumbnail.
SkBitmap thumbnail;
GURL url("http://a.com/");
double score = 0.4; // Some random client score.
EXPECT_FALSE(SendClientReportPhishingRequest(url, score, thumbnail));
// Valid thumbnail but the server returns an error.
thumbnail.setConfig(SkBitmap::kARGB_8888_Config, 100, 100);
ASSERT_TRUE(thumbnail.allocPixels());
thumbnail.eraseRGB(255, 0, 0);
SetClientReportPhishingResponse("", false /* fail */);
EXPECT_FALSE(SendClientReportPhishingRequest(url, score, thumbnail));
// Invalid response body from the server.
SetClientReportPhishingResponse("invalid proto response", true /* success */);
EXPECT_FALSE(SendClientReportPhishingRequest(url, score, thumbnail));
// Normal behavior.
ClientPhishingResponse response;
response.set_phishy(true);
SetClientReportPhishingResponse(response.SerializeAsString(),
true /* success */);
EXPECT_TRUE(SendClientReportPhishingRequest(url, score, thumbnail));
response.set_phishy(false);
SetClientReportPhishingResponse(response.SerializeAsString(),
true /* success */);
EXPECT_FALSE(SendClientReportPhishingRequest(url, score, thumbnail));
}
} // namespace safe_browsing
|
Disable ClientSideDetectionServiceTest.SendClientReportPhishingRequest on Mac
|
Disable ClientSideDetectionServiceTest.SendClientReportPhishingRequest on Mac
Sometimes crashes on the Mac 10.5 tests bot.
BUG=63358
TEST=greener tree
Review URL: http://codereview.chromium.org/5072002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@66316 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
markYoungH/chromium.src,hujiajie/pa-chromium,Jonekee/chromium.src,littlstar/chromium.src,zcbenz/cefode-chromium,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,robclark/chromium,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,hujiajie/pa-chromium,patrickm/chromium.src,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,axinging/chromium-crosswalk,anirudhSK/chromium,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,Jonekee/chromium.src,keishi/chromium,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,axinging/chromium-crosswalk,Jonekee/chromium.src,ondra-novak/chromium.src,dednal/chromium.src,ondra-novak/chromium.src,jaruba/chromium.src,M4sse/chromium.src,keishi/chromium,ChromiumWebApps/chromium,zcbenz/cefode-chromium,robclark/chromium,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,rogerwang/chromium,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,jaruba/chromium.src,ltilve/chromium,ondra-novak/chromium.src,littlstar/chromium.src,hujiajie/pa-chromium,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,nacl-webkit/chrome_deps,M4sse/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,ondra-novak/chromium.src,robclark/chromium,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,dushu1203/chromium.src,patrickm/chromium.src,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,Chilledheart/chromium,anirudhSK/chromium,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,ChromiumWebApps/chromium,keishi/chromium,hujiajie/pa-chromium,axinging/chromium-crosswalk,M4sse/chromium.src,patrickm/chromium.src,littlstar/chromium.src,nacl-webkit/chrome_deps,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,M4sse/chromium.src,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,rogerwang/chromium,krieger-od/nwjs_chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,littlstar/chromium.src,keishi/chromium,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,littlstar/chromium.src,littlstar/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,M4sse/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,robclark/chromium,keishi/chromium,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,anirudhSK/chromium,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,dednal/chromium.src,timopulkkinen/BubbleFish,robclark/chromium,M4sse/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,mogoweb/chromium-crosswalk,markYoungH/chromium.src,jaruba/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,dushu1203/chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,ltilve/chromium,hgl888/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,rogerwang/chromium,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,jaruba/chromium.src,Just-D/chromium-1,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,Jonekee/chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,anirudhSK/chromium,keishi/chromium,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,rogerwang/chromium,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,anirudhSK/chromium,dushu1203/chromium.src,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,keishi/chromium,chuan9/chromium-crosswalk,robclark/chromium,rogerwang/chromium,M4sse/chromium.src,markYoungH/chromium.src,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,keishi/chromium,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,anirudhSK/chromium,nacl-webkit/chrome_deps,rogerwang/chromium,Pluto-tv/chromium-crosswalk,rogerwang/chromium,Pluto-tv/chromium-crosswalk,ltilve/chromium,anirudhSK/chromium,Chilledheart/chromium,jaruba/chromium.src,dednal/chromium.src,ltilve/chromium,markYoungH/chromium.src,chuan9/chromium-crosswalk,ltilve/chromium,anirudhSK/chromium,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,ondra-novak/chromium.src,patrickm/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,dushu1203/chromium.src,hujiajie/pa-chromium,chuan9/chromium-crosswalk,Just-D/chromium-1,robclark/chromium,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,robclark/chromium,rogerwang/chromium,mogoweb/chromium-crosswalk,keishi/chromium,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,Fireblend/chromium-crosswalk,patrickm/chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,patrickm/chromium.src,jaruba/chromium.src,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,keishi/chromium,Chilledheart/chromium,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,zcbenz/cefode-chromium,dednal/chromium.src,mogoweb/chromium-crosswalk,anirudhSK/chromium,Just-D/chromium-1,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,ltilve/chromium,hgl888/chromium-crosswalk,jaruba/chromium.src,dushu1203/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,Jonekee/chromium.src,timopulkkinen/BubbleFish,rogerwang/chromium,chuan9/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,keishi/chromium,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,dednal/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,ChromiumWebApps/chromium
|
5803f2d3c9662a4d4367686f1ba2d8f0a37c113f
|
test/gtest/uct/test_uct_perf.cc
|
test/gtest/uct/test_uct_perf.cc
|
/**
* Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED.
*
* Copyright (C) UT-Battelle, LLC. 2015. ALL RIGHTS RESERVED.
* See file LICENSE for terms.
*/
#include "uct_test.h"
#include <gtest/common/test_perf.h>
extern "C" {
#include <ucs/arch/cpu.h>
}
#define MB pow(1024.0, -2)
class test_uct_perf : public uct_test, public test_perf {
protected:
static test_spec tests[];
};
test_perf::test_spec test_uct_perf::tests[] =
{
{ "am latency", "usec",
UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_PINGPONG,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, latency.total_average), 1e6, 0.01, 2.5},
{ "am rate", "Mpps",
UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 2000000l,
ucs_offsetof(ucx_perf_result_t, msgrate.total_average), 1e-6, 0.8, 80.0 },
{ "am rate64", "Mpps",
UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 64 }, 1, 2000000l,
ucs_offsetof(ucx_perf_result_t, msgrate.total_average), 1e-6, 0.8, 80.0 },
{ "am bcopy bw", "MB/sec",
UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_BCOPY, 0, 1, { 1000 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, bandwidth.total_average), MB, 620.0, 15000.0 },
{ "am zcopy bw", "MB/sec",
UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_ZCOPY, 0, 1, { 1000 }, 32, 100000l,
ucs_offsetof(ucx_perf_result_t, bandwidth.total_average), MB, 600.0, 15000.0 },
{ "put latency", "usec",
UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_PINGPONG,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, latency.total_average), 1e6, 0.01, 1.5 },
{ "put rate", "Mpps",
UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 2000000l,
ucs_offsetof(ucx_perf_result_t, msgrate.total_average), 1e-6, 0.8, 80.0 },
{ "put bcopy bw", "MB/sec",
UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_BCOPY, 0, 1, { 2048 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, bandwidth.total_average), MB, 620.0, 50000.0 },
{ "put zcopy bw", "MB/sec",
UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_ZCOPY, 0, 1, { 2048 }, 32, 100000l,
ucs_offsetof(ucx_perf_result_t, bandwidth.total_average), MB, 620.0, 50000.0 },
{ "get latency", "usec",
UCX_PERF_API_UCT, UCX_PERF_CMD_GET, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_ZCOPY, 0, 1, { 8 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, latency.total_average), 1e6, 0.01, 3.5 },
{ "atomic add latency", "usec",
UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_PINGPONG,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, latency.total_average), 1e6, 0.01, 3.5 },
{ "atomic add rate", "Mpps",
UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 2000000l,
ucs_offsetof(ucx_perf_result_t, msgrate.total_average), 1e-6, 0.5, 50.0 },
{ "atomic fadd latency", "usec",
UCX_PERF_API_UCT, UCX_PERF_CMD_FADD, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, latency.total_average), 1e6, 0.01, 3.5 },
{ "atomic cswap latency", "usec",
UCX_PERF_API_UCT, UCX_PERF_CMD_CSWAP, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, latency.total_average), 1e6, 0.01, 3.5 },
{ "atomic swap latency", "usec",
UCX_PERF_API_UCT, UCX_PERF_CMD_SWAP, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, latency.total_average), 1e6, 0.01, 3.5 },
{ "am iov bw", "MB/sec",
UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_ZCOPY, 8192, 3, { 256, 256, 512 }, 32, 100000l,
ucs_offsetof(ucx_perf_result_t, bandwidth.total_average), MB, 600.0, 15000.0 },
{ NULL }
};
UCS_TEST_P(test_uct_perf, envelope) {
bool check_perf;
if (GetParam()->tl_name == "cm" || GetParam()->tl_name == "ugni_udt") {
/* TODO calibrate expected performance and iterations based on transport */
UCS_TEST_SKIP;
}
/* For SandyBridge CPUs, don't check performance of far-socket devices */
std::vector<int> cpus = get_affinity();
check_perf = true;
if (ucs_arch_get_cpu_model() == UCS_CPU_MODEL_INTEL_SANDYBRIDGE) {
for (std::vector<int>::iterator iter = cpus.begin(); iter != cpus.end(); ++iter) {
if (!CPU_ISSET(*iter, &GetParam()->local_cpus)) {
UCS_TEST_MESSAGE << "Not enforcing performance on SandyBridge far socket";
check_perf = false;
break;
}
}
}
/* Run all tests */
for (test_spec *test = tests; test->title != NULL; ++test) {
run_test(*test, 0, check_perf, GetParam()->tl_name, GetParam()->dev_name);
}
}
UCT_INSTANTIATE_NO_SELF_TEST_CASE(test_uct_perf);
|
/**
* Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED.
*
* Copyright (C) UT-Battelle, LLC. 2015. ALL RIGHTS RESERVED.
* See file LICENSE for terms.
*/
#include "uct_test.h"
#include <gtest/common/test_perf.h>
extern "C" {
#include <ucs/arch/cpu.h>
}
#define MB pow(1024.0, -2)
#define UCT_PERF_TEST_MULTIPLIER 2
class test_uct_perf : public uct_test, public test_perf {
protected:
static test_spec tests[];
};
test_perf::test_spec test_uct_perf::tests[] =
{
{ "am latency", "usec",
UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_PINGPONG,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, latency.total_average), 1e6, 0.01, 2.5},
{ "am rate", "Mpps",
UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 2000000l,
ucs_offsetof(ucx_perf_result_t, msgrate.total_average), 1e-6, 0.8, 80.0 },
{ "am rate64", "Mpps",
UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 64 }, 1, 2000000l,
ucs_offsetof(ucx_perf_result_t, msgrate.total_average), 1e-6, 0.8, 80.0 },
{ "am bcopy bw", "MB/sec",
UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_BCOPY, 0, 1, { 1000 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, bandwidth.total_average), MB, 620.0, 15000.0 },
{ "am zcopy bw", "MB/sec",
UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_ZCOPY, 0, 1, { 1000 }, 32, 100000l,
ucs_offsetof(ucx_perf_result_t, bandwidth.total_average), MB, 600.0, 15000.0 },
{ "put latency", "usec",
UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_PINGPONG,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, latency.total_average), 1e6, 0.01, 1.5 },
{ "put rate", "Mpps",
UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 2000000l,
ucs_offsetof(ucx_perf_result_t, msgrate.total_average), 1e-6, 0.8, 80.0 },
{ "put bcopy bw", "MB/sec",
UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_BCOPY, 0, 1, { 2048 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, bandwidth.total_average), MB, 620.0, 50000.0 },
{ "put zcopy bw", "MB/sec",
UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_ZCOPY, 0, 1, { 2048 }, 32, 100000l,
ucs_offsetof(ucx_perf_result_t, bandwidth.total_average), MB, 620.0, 50000.0 },
{ "get latency", "usec",
UCX_PERF_API_UCT, UCX_PERF_CMD_GET, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_ZCOPY, 0, 1, { 8 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, latency.total_average), 1e6, 0.01, 3.5 },
{ "atomic add latency", "usec",
UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_PINGPONG,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, latency.total_average), 1e6, 0.01, 3.5 },
{ "atomic add rate", "Mpps",
UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 2000000l,
ucs_offsetof(ucx_perf_result_t, msgrate.total_average), 1e-6, 0.5, 50.0 },
{ "atomic fadd latency", "usec",
UCX_PERF_API_UCT, UCX_PERF_CMD_FADD, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, latency.total_average), 1e6, 0.01, 3.5 },
{ "atomic cswap latency", "usec",
UCX_PERF_API_UCT, UCX_PERF_CMD_CSWAP, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, latency.total_average), 1e6, 0.01, 3.5 },
{ "atomic swap latency", "usec",
UCX_PERF_API_UCT, UCX_PERF_CMD_SWAP, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_SHORT, 0, 1, { 8 }, 1, 100000l,
ucs_offsetof(ucx_perf_result_t, latency.total_average), 1e6, 0.01, 3.5 },
{ "am iov bw", "MB/sec",
UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI,
UCT_PERF_DATA_LAYOUT_ZCOPY, 8192, 3, { 256, 256, 512 }, 32, 100000l,
ucs_offsetof(ucx_perf_result_t, bandwidth.total_average), MB, 600.0, 15000.0 },
{ NULL }
};
UCS_TEST_P(test_uct_perf, envelope) {
bool check_perf;
if (GetParam()->tl_name == "cm" || GetParam()->tl_name == "ugni_udt") {
/* TODO calibrate expected performance and iterations based on transport */
UCS_TEST_SKIP;
}
/* For SandyBridge CPUs, don't check performance of far-socket devices */
std::vector<int> cpus = get_affinity();
check_perf = true;
if (ucs_arch_get_cpu_model() == UCS_CPU_MODEL_INTEL_SANDYBRIDGE) {
for (std::vector<int>::iterator iter = cpus.begin(); iter != cpus.end(); ++iter) {
if (!CPU_ISSET(*iter, &GetParam()->local_cpus)) {
UCS_TEST_MESSAGE << "Not enforcing performance on SandyBridge far socket";
check_perf = false;
break;
}
}
}
/* Run all tests */
for (test_spec *test = tests; test->title != NULL; ++test) {
test->max *= UCT_PERF_TEST_MULTIPLIER;
test->min /= UCT_PERF_TEST_MULTIPLIER;
run_test(*test, 0, check_perf, GetParam()->tl_name, GetParam()->dev_name);
}
}
UCT_INSTANTIATE_NO_SELF_TEST_CASE(test_uct_perf);
|
increase max values in perf test
|
UCT/GTEST: increase max values in perf test
|
C++
|
bsd-3-clause
|
shssf/ucx,sergsagal1/ucx_rocm,shssf/ucx,sergsagal1/ucx_rocm,sergsagal1/ucx_rocm,shssf/ucx
|
4e4e184e5a91289dfb5da4647e87541c43333aad
|
test/mocks/stream_info/mocks.cc
|
test/mocks/stream_info/mocks.cc
|
#include "test/mocks/stream_info/mocks.h"
#include "source/common/network/address_impl.h"
#include "test/mocks/ssl/mocks.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::_;
using testing::Const;
using testing::Invoke;
using testing::Return;
using testing::ReturnPointee;
using testing::ReturnRef;
namespace Envoy {
namespace StreamInfo {
MockUpstreamInfo::MockUpstreamInfo()
: upstream_local_address_(new Network::Address::Ipv4Instance("127.1.2.3", 58443)),
upstream_remote_address_(new Network::Address::Ipv4Instance("10.0.0.1", 443)),
upstream_host_(new testing::NiceMock<Upstream::MockHostDescription>()) {
ON_CALL(*this, dumpState(_, _)).WillByDefault(Invoke([](std::ostream& os, int indent_level) {
os << "MockUpstreamInfo test dumpState with indent: " << indent_level << std::endl;
}));
ON_CALL(*this, setUpstreamConnectionId(_)).WillByDefault(Invoke([this](uint64_t id) {
upstream_connection_id_ = id;
}));
ON_CALL(*this, upstreamConnectionId()).WillByDefault(ReturnPointee(&upstream_connection_id_));
ON_CALL(*this, setUpstreamInterfaceName(_))
.WillByDefault(
Invoke([this](absl::string_view interface_name) { interface_name_ = interface_name; }));
ON_CALL(*this, upstreamInterfaceName()).WillByDefault(ReturnPointee(&interface_name_));
ON_CALL(*this, setUpstreamSslConnection(_))
.WillByDefault(Invoke([this](const Ssl::ConnectionInfoConstSharedPtr& ssl_connection_info) {
ssl_connection_info_ = ssl_connection_info;
}));
ON_CALL(*this, upstreamSslConnection()).WillByDefault(ReturnPointee(&ssl_connection_info_));
ON_CALL(*this, upstreamTiming()).WillByDefault(ReturnRef(upstream_timing_));
ON_CALL(Const(*this), upstreamTiming()).WillByDefault(ReturnRef(upstream_timing_));
ON_CALL(*this, setUpstreamLocalAddress(_))
.WillByDefault(
Invoke([this](const Network::Address::InstanceConstSharedPtr& upstream_local_address) {
upstream_local_address_ = upstream_local_address;
}));
ON_CALL(*this, upstreamLocalAddress()).WillByDefault(ReturnRef(upstream_local_address_));
ON_CALL(*this, setUpstreamTransportFailureReason(_))
.WillByDefault(Invoke([this](absl::string_view failure_reason) {
failure_reason_ = std::string(failure_reason);
}));
ON_CALL(*this, upstreamTransportFailureReason()).WillByDefault(ReturnRef(failure_reason_));
ON_CALL(*this, setUpstreamHost(_))
.WillByDefault(Invoke([this](Upstream::HostDescriptionConstSharedPtr upstream_host) {
upstream_host_ = upstream_host;
}));
ON_CALL(*this, upstreamHost()).WillByDefault(ReturnPointee(&upstream_host_));
ON_CALL(*this, setUpstreamFilterState(_))
.WillByDefault(Invoke(
[this](const FilterStateSharedPtr& filter_state) { filter_state_ = filter_state; }));
ON_CALL(*this, upstreamFilterState()).WillByDefault(ReturnRef(filter_state_));
ON_CALL(*this, setUpstreamNumStreams(_)).WillByDefault(Invoke([this](uint64_t num_streams) {
num_streams_ = num_streams;
}));
ON_CALL(*this, upstreamNumStreams()).WillByDefault(ReturnPointee(&num_streams_));
ON_CALL(*this, setUpstreamProtocol(_)).WillByDefault(Invoke([this](Http::Protocol protocol) {
upstream_protocol_ = protocol;
}));
ON_CALL(*this, upstreamProtocol()).WillByDefault(ReturnPointee(&upstream_protocol_));
ON_CALL(*this, upstreamRemoteAddress()).WillByDefault(ReturnRef(upstream_remote_address_));
}
MockUpstreamInfo::~MockUpstreamInfo() = default;
MockStreamInfo::MockStreamInfo()
: start_time_(ts_.systemTime()),
// upstream
upstream_info_(std::make_shared<testing::NiceMock<MockUpstreamInfo>>()),
filter_state_(std::make_shared<FilterStateImpl>(FilterState::LifeSpan::FilterChain)),
downstream_connection_info_provider_(std::make_shared<Network::ConnectionInfoSetterImpl>(
std::make_shared<Network::Address::Ipv4Instance>("127.0.0.2"),
std::make_shared<Network::Address::Ipv4Instance>("127.0.0.1"))) {
// downstream:direct_remote
auto downstream_direct_remote_address = Network::Address::InstanceConstSharedPtr{
new Network::Address::Ipv4Instance("127.0.0.3", 63443)};
downstream_connection_info_provider_->setDirectRemoteAddressForTest(
downstream_direct_remote_address);
ON_CALL(*this, setResponseFlag(_)).WillByDefault(Invoke([this](ResponseFlag response_flag) {
response_flags_ |= response_flag;
}));
ON_CALL(*this, setResponseCode(_)).WillByDefault(Invoke([this](uint32_t code) {
response_code_ = code;
}));
ON_CALL(*this, setResponseCodeDetails(_)).WillByDefault(Invoke([this](absl::string_view details) {
response_code_details_ = std::string(details);
}));
ON_CALL(*this, setConnectionTerminationDetails(_))
.WillByDefault(Invoke([this](absl::string_view details) {
connection_termination_details_ = std::string(details);
}));
ON_CALL(*this, startTime()).WillByDefault(ReturnPointee(&start_time_));
ON_CALL(*this, startTimeMonotonic()).WillByDefault(ReturnPointee(&start_time_monotonic_));
ON_CALL(*this, requestComplete()).WillByDefault(ReturnPointee(&end_time_));
ON_CALL(*this, onRequestComplete()).WillByDefault(Invoke([this]() {
end_time_ = absl::make_optional<std::chrono::nanoseconds>(
std::chrono::duration_cast<std::chrono::nanoseconds>(ts_.systemTime() - start_time_)
.count());
}));
ON_CALL(*this, downstreamTiming()).WillByDefault(Invoke([this]() -> DownstreamTiming& {
return downstream_timing_;
}));
ON_CALL(Const(*this), downstreamTiming())
.WillByDefault(
Invoke([this]() -> OptRef<const DownstreamTiming> { return downstream_timing_; }));
ON_CALL(*this, upstreamInfo()).WillByDefault(Invoke([this]() { return upstream_info_; }));
ON_CALL(testing::Const(*this), upstreamInfo())
.WillByDefault(Invoke([this]() -> OptRef<const UpstreamInfo> {
if (!upstream_info_) {
return {};
}
return *upstream_info_;
}));
ON_CALL(*this, downstreamAddressProvider())
.WillByDefault(ReturnPointee(downstream_connection_info_provider_));
ON_CALL(*this, protocol()).WillByDefault(ReturnPointee(&protocol_));
ON_CALL(*this, responseCode()).WillByDefault(ReturnPointee(&response_code_));
ON_CALL(*this, responseCodeDetails()).WillByDefault(ReturnPointee(&response_code_details_));
ON_CALL(*this, connectionTerminationDetails())
.WillByDefault(ReturnPointee(&connection_termination_details_));
ON_CALL(*this, addBytesReceived(_)).WillByDefault(Invoke([this](uint64_t bytes_received) {
bytes_received_ += bytes_received;
}));
ON_CALL(*this, bytesReceived()).WillByDefault(ReturnPointee(&bytes_received_));
ON_CALL(*this, addBytesSent(_)).WillByDefault(Invoke([this](uint64_t bytes_sent) {
bytes_sent_ += bytes_sent;
}));
ON_CALL(*this, bytesSent()).WillByDefault(ReturnPointee(&bytes_sent_));
ON_CALL(*this, hasResponseFlag(_)).WillByDefault(Invoke([this](ResponseFlag flag) {
return response_flags_ & flag;
}));
ON_CALL(*this, intersectResponseFlags(_)).WillByDefault(Invoke([this](uint64_t response_flags) {
return (response_flags_ & response_flags) != 0;
}));
ON_CALL(*this, hasAnyResponseFlag()).WillByDefault(Invoke([this]() {
return response_flags_ != 0;
}));
ON_CALL(*this, responseFlags()).WillByDefault(Return(response_flags_));
ON_CALL(*this, dynamicMetadata()).WillByDefault(ReturnRef(metadata_));
ON_CALL(Const(*this), dynamicMetadata()).WillByDefault(ReturnRef(metadata_));
ON_CALL(*this, filterState()).WillByDefault(ReturnRef(filter_state_));
ON_CALL(Const(*this), filterState()).WillByDefault(Invoke([this]() -> const FilterState& {
return *filter_state_;
}));
ON_CALL(*this, setRouteName(_)).WillByDefault(Invoke([this](const absl::string_view route_name) {
route_name_ = std::string(route_name);
}));
ON_CALL(*this, setVirtualClusterName(_))
.WillByDefault(Invoke([this](const absl::optional<std::string>& virtual_cluster_name) {
virtual_cluster_name_ = virtual_cluster_name;
}));
ON_CALL(*this, getRouteName()).WillByDefault(ReturnRef(route_name_));
ON_CALL(*this, setUpstreamInfo(_))
.WillByDefault(Invoke([this](std::shared_ptr<UpstreamInfo> info) { upstream_info_ = info; }));
ON_CALL(*this, virtualClusterName()).WillByDefault(ReturnRef(virtual_cluster_name_));
ON_CALL(*this, setFilterChainName(_))
.WillByDefault(Invoke([this](const absl::string_view filter_chain_name) {
filter_chain_name_ = std::string(filter_chain_name);
}));
ON_CALL(*this, filterChainName()).WillByDefault(ReturnRef(filter_chain_name_));
ON_CALL(*this, setAttemptCount(_)).WillByDefault(Invoke([this](uint32_t attempt_count) {
attempt_count_ = attempt_count;
}));
ON_CALL(*this, attemptCount()).WillByDefault(Invoke([this]() { return attempt_count_; }));
ON_CALL(*this, getUpstreamBytesMeter()).WillByDefault(ReturnPointee(&upstream_bytes_meter_));
ON_CALL(*this, getDownstreamBytesMeter()).WillByDefault(ReturnPointee(&downstream_bytes_meter_));
ON_CALL(*this, setUpstreamBytesMeter(_))
.WillByDefault(Invoke([this](const BytesMeterSharedPtr& upstream_bytes_meter) {
upstream_bytes_meter_ = upstream_bytes_meter;
}));
ON_CALL(*this, setDownstreamBytesMeter(_))
.WillByDefault(Invoke([this](const BytesMeterSharedPtr& downstream_bytes_meter) {
downstream_bytes_meter_ = downstream_bytes_meter;
}));
}
MockStreamInfo::~MockStreamInfo() = default;
} // namespace StreamInfo
} // namespace Envoy
|
#include "test/mocks/stream_info/mocks.h"
#include "source/common/network/address_impl.h"
#include "test/mocks/ssl/mocks.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::_;
using testing::Const;
using testing::Invoke;
using testing::Return;
using testing::ReturnPointee;
using testing::ReturnRef;
namespace Envoy {
namespace StreamInfo {
MockUpstreamInfo::MockUpstreamInfo()
: upstream_local_address_(new Network::Address::Ipv4Instance("127.1.2.3", 58443)),
upstream_remote_address_(new Network::Address::Ipv4Instance("10.0.0.1", 443)),
upstream_host_(new testing::NiceMock<Upstream::MockHostDescription>()) {
ON_CALL(*this, dumpState(_, _)).WillByDefault(Invoke([](std::ostream& os, int indent_level) {
os << "MockUpstreamInfo test dumpState with indent: " << indent_level << std::endl;
}));
ON_CALL(*this, setUpstreamConnectionId(_)).WillByDefault(Invoke([this](uint64_t id) {
upstream_connection_id_ = id;
}));
ON_CALL(*this, upstreamConnectionId()).WillByDefault(ReturnPointee(&upstream_connection_id_));
ON_CALL(*this, setUpstreamInterfaceName(_))
.WillByDefault(
Invoke([this](absl::string_view interface_name) { interface_name_ = interface_name; }));
ON_CALL(*this, upstreamInterfaceName()).WillByDefault(ReturnPointee(&interface_name_));
ON_CALL(*this, setUpstreamSslConnection(_))
.WillByDefault(Invoke([this](const Ssl::ConnectionInfoConstSharedPtr& ssl_connection_info) {
ssl_connection_info_ = ssl_connection_info;
}));
ON_CALL(*this, upstreamSslConnection()).WillByDefault(ReturnPointee(&ssl_connection_info_));
ON_CALL(*this, upstreamTiming()).WillByDefault(ReturnRef(upstream_timing_));
ON_CALL(Const(*this), upstreamTiming()).WillByDefault(ReturnRef(upstream_timing_));
ON_CALL(*this, setUpstreamLocalAddress(_))
.WillByDefault(
Invoke([this](const Network::Address::InstanceConstSharedPtr& upstream_local_address) {
upstream_local_address_ = upstream_local_address;
}));
ON_CALL(*this, upstreamLocalAddress()).WillByDefault(ReturnRef(upstream_local_address_));
ON_CALL(*this, setUpstreamTransportFailureReason(_))
.WillByDefault(Invoke([this](absl::string_view failure_reason) {
failure_reason_ = std::string(failure_reason);
}));
ON_CALL(*this, upstreamTransportFailureReason()).WillByDefault(ReturnRef(failure_reason_));
ON_CALL(*this, setUpstreamHost(_))
.WillByDefault(Invoke([this](Upstream::HostDescriptionConstSharedPtr upstream_host) {
upstream_host_ = upstream_host;
}));
ON_CALL(*this, upstreamHost()).WillByDefault(ReturnPointee(&upstream_host_));
ON_CALL(*this, setUpstreamFilterState(_))
.WillByDefault(Invoke(
[this](const FilterStateSharedPtr& filter_state) { filter_state_ = filter_state; }));
ON_CALL(*this, upstreamFilterState()).WillByDefault(ReturnRef(filter_state_));
ON_CALL(*this, setUpstreamNumStreams(_)).WillByDefault(Invoke([this](uint64_t num_streams) {
num_streams_ = num_streams;
}));
ON_CALL(*this, upstreamNumStreams()).WillByDefault(ReturnPointee(&num_streams_));
ON_CALL(*this, setUpstreamProtocol(_)).WillByDefault(Invoke([this](Http::Protocol protocol) {
upstream_protocol_ = protocol;
}));
ON_CALL(*this, upstreamProtocol()).WillByDefault(ReturnPointee(&upstream_protocol_));
ON_CALL(*this, upstreamRemoteAddress()).WillByDefault(ReturnRef(upstream_remote_address_));
}
MockUpstreamInfo::~MockUpstreamInfo() = default;
MockStreamInfo::MockStreamInfo()
: start_time_(ts_.systemTime()),
// upstream
upstream_info_(std::make_shared<testing::NiceMock<MockUpstreamInfo>>()),
filter_state_(std::make_shared<FilterStateImpl>(FilterState::LifeSpan::FilterChain)),
downstream_connection_info_provider_(std::make_shared<Network::ConnectionInfoSetterImpl>(
std::make_shared<Network::Address::Ipv4Instance>("127.0.0.2"),
std::make_shared<Network::Address::Ipv4Instance>("127.0.0.1"))) {
// downstream:direct_remote
auto downstream_direct_remote_address = Network::Address::InstanceConstSharedPtr{
new Network::Address::Ipv4Instance("127.0.0.3", 63443)};
downstream_connection_info_provider_->setDirectRemoteAddressForTest(
downstream_direct_remote_address);
ON_CALL(*this, setResponseFlag(_)).WillByDefault(Invoke([this](ResponseFlag response_flag) {
response_flags_ |= response_flag;
}));
ON_CALL(*this, setResponseCode(_)).WillByDefault(Invoke([this](uint32_t code) {
response_code_ = code;
}));
ON_CALL(*this, setResponseCodeDetails(_)).WillByDefault(Invoke([this](absl::string_view details) {
response_code_details_ = std::string(details);
}));
ON_CALL(*this, setConnectionTerminationDetails(_))
.WillByDefault(Invoke([this](absl::string_view details) {
connection_termination_details_ = std::string(details);
}));
ON_CALL(*this, startTime()).WillByDefault(ReturnPointee(&start_time_));
ON_CALL(*this, startTimeMonotonic()).WillByDefault(ReturnPointee(&start_time_monotonic_));
ON_CALL(*this, requestComplete()).WillByDefault(ReturnPointee(&end_time_));
ON_CALL(*this, onRequestComplete()).WillByDefault(Invoke([this]() {
end_time_ = absl::make_optional<std::chrono::nanoseconds>(
std::chrono::duration_cast<std::chrono::nanoseconds>(ts_.systemTime() - start_time_)
.count());
}));
ON_CALL(*this, downstreamTiming()).WillByDefault(Invoke([this]() -> DownstreamTiming& {
return downstream_timing_;
}));
ON_CALL(Const(*this), downstreamTiming())
.WillByDefault(
Invoke([this]() -> OptRef<const DownstreamTiming> { return downstream_timing_; }));
ON_CALL(*this, upstreamInfo()).WillByDefault(Invoke([this]() { return upstream_info_; }));
ON_CALL(testing::Const(*this), upstreamInfo())
.WillByDefault(Invoke([this]() -> OptRef<const UpstreamInfo> {
if (!upstream_info_) {
return {};
}
return *upstream_info_;
}));
ON_CALL(*this, downstreamAddressProvider())
.WillByDefault(ReturnPointee(downstream_connection_info_provider_));
ON_CALL(*this, protocol()).WillByDefault(ReturnPointee(&protocol_));
ON_CALL(*this, responseCode()).WillByDefault(ReturnPointee(&response_code_));
ON_CALL(*this, responseCodeDetails()).WillByDefault(ReturnPointee(&response_code_details_));
ON_CALL(*this, connectionTerminationDetails())
.WillByDefault(ReturnPointee(&connection_termination_details_));
ON_CALL(*this, addBytesReceived(_)).WillByDefault(Invoke([this](uint64_t bytes_received) {
bytes_received_ += bytes_received;
}));
ON_CALL(*this, bytesReceived()).WillByDefault(ReturnPointee(&bytes_received_));
ON_CALL(*this, addBytesSent(_)).WillByDefault(Invoke([this](uint64_t bytes_sent) {
bytes_sent_ += bytes_sent;
}));
ON_CALL(*this, bytesSent()).WillByDefault(ReturnPointee(&bytes_sent_));
ON_CALL(*this, hasResponseFlag(_)).WillByDefault(Invoke([this](ResponseFlag flag) {
return response_flags_ & flag;
}));
ON_CALL(*this, intersectResponseFlags(_)).WillByDefault(Invoke([this](uint64_t response_flags) {
return (response_flags_ & response_flags) != 0;
}));
ON_CALL(*this, hasAnyResponseFlag()).WillByDefault(Invoke([this]() {
return response_flags_ != 0;
}));
ON_CALL(*this, responseFlags()).WillByDefault(Invoke([this]() -> uint64_t {
return response_flags_;
}));
ON_CALL(*this, dynamicMetadata()).WillByDefault(ReturnRef(metadata_));
ON_CALL(Const(*this), dynamicMetadata()).WillByDefault(ReturnRef(metadata_));
ON_CALL(*this, filterState()).WillByDefault(ReturnRef(filter_state_));
ON_CALL(Const(*this), filterState()).WillByDefault(Invoke([this]() -> const FilterState& {
return *filter_state_;
}));
ON_CALL(*this, setRouteName(_)).WillByDefault(Invoke([this](const absl::string_view route_name) {
route_name_ = std::string(route_name);
}));
ON_CALL(*this, setVirtualClusterName(_))
.WillByDefault(Invoke([this](const absl::optional<std::string>& virtual_cluster_name) {
virtual_cluster_name_ = virtual_cluster_name;
}));
ON_CALL(*this, getRouteName()).WillByDefault(ReturnRef(route_name_));
ON_CALL(*this, setUpstreamInfo(_))
.WillByDefault(Invoke([this](std::shared_ptr<UpstreamInfo> info) { upstream_info_ = info; }));
ON_CALL(*this, virtualClusterName()).WillByDefault(ReturnRef(virtual_cluster_name_));
ON_CALL(*this, setFilterChainName(_))
.WillByDefault(Invoke([this](const absl::string_view filter_chain_name) {
filter_chain_name_ = std::string(filter_chain_name);
}));
ON_CALL(*this, filterChainName()).WillByDefault(ReturnRef(filter_chain_name_));
ON_CALL(*this, setAttemptCount(_)).WillByDefault(Invoke([this](uint32_t attempt_count) {
attempt_count_ = attempt_count;
}));
ON_CALL(*this, attemptCount()).WillByDefault(Invoke([this]() { return attempt_count_; }));
ON_CALL(*this, getUpstreamBytesMeter()).WillByDefault(ReturnPointee(&upstream_bytes_meter_));
ON_CALL(*this, getDownstreamBytesMeter()).WillByDefault(ReturnPointee(&downstream_bytes_meter_));
ON_CALL(*this, setUpstreamBytesMeter(_))
.WillByDefault(Invoke([this](const BytesMeterSharedPtr& upstream_bytes_meter) {
upstream_bytes_meter_ = upstream_bytes_meter;
}));
ON_CALL(*this, setDownstreamBytesMeter(_))
.WillByDefault(Invoke([this](const BytesMeterSharedPtr& downstream_bytes_meter) {
downstream_bytes_meter_ = downstream_bytes_meter;
}));
}
MockStreamInfo::~MockStreamInfo() = default;
} // namespace StreamInfo
} // namespace Envoy
|
Fix bug in stream_info mock (#23870)
|
Fix bug in stream_info mock (#23870)
Fix bug in stream_info mock
Return(value) in gmock copies value at setup time. Any updates to value during use of mock will not be reflected.
This caused responseFlags to always return the default value of 0 instead of any updates done by setResponseFlag
Signed-off-by: silverstar195 <[email protected]>
|
C++
|
apache-2.0
|
envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy
|
e054a8126b5643e4e51df8e52a3bfa40590414f5
|
test/ErrorRecovery/NestedTags.C
|
test/ErrorRecovery/NestedTags.C
|
// RUN: cat %s | %cling -Xclang -verify 2>&1 | FileCheck %s
// Tests the removal of nested decls
.storeState "testNestedDecls1"
struct Outer { struct Inner { enum E{i = 1}; }; };error_here; // expected-error {{use of undeclared identifier 'error_here'}}
.compareState "testNestedDecls1"
.rawInput
namespace Outer { struct Inner { enum E{i = 2}; }; };
.rawInput
Outer::Inner::i
// CHECK: (Outer::Inner::E::i) : (int) 2
enum A{a};
.storeState "testNestedDecls2"
enum A{a}; // expected-error {{redefinition of 'A'}} expected-note {{previous definition is here}}
.compareState "testNestedDecls2"
// CHECK-NOT: Differences
a // CHECK: (enum A) (A::a) : (int) 0
.q
|
// RUN: cat %s | %cling -Xclang -verify 2>&1 | FileCheck %s
// Tests the removal of nested decls
.storeState "testNestedDecls1"
struct Outer { struct Inner { enum E{i = 1}; }; };error_here; // expected-error {{use of undeclared identifier 'error_here'}}
.compareState "testNestedDecls1"
// CHECK-NOT: Differences
.rawInput 1
.storeState "parentLookupTables"
enum AnEnum {
aa = 3,
bb = 4,
}; error_here; // expected-error {{C++ requires a type specifier for all declarations}}
.compareState "parentLookupTables"
.rawInput 0
// CHECK-NOT: Differences
.rawInput
namespace Outer { struct Inner { enum E{i = 2}; }; };
.rawInput
enum A{a};
.storeState "testNestedDecls2"
enum A{a}; // expected-error {{redefinition of 'A'}} expected-note {{previous definition is here}}
.compareState "testNestedDecls2"
// CHECK-NOT: Differences
Outer::Inner::i
// CHECK: (Outer::Inner::E::i) : (int) 2
a // CHECK: (enum A) (A::a) : (int) 0
.q
|
Test enum constant cleanup.
|
Test enum constant cleanup.
|
C++
|
lgpl-2.1
|
root-mirror/cling,root-mirror/cling,perovic/cling,marsupial/cling,karies/cling,marsupial/cling,karies/cling,root-mirror/cling,marsupial/cling,marsupial/cling,karies/cling,root-mirror/cling,root-mirror/cling,marsupial/cling,karies/cling,perovic/cling,marsupial/cling,root-mirror/cling,perovic/cling,karies/cling,perovic/cling,karies/cling,perovic/cling
|
0564e164800e64cb5584a942bc3907f80975ba63
|
Source/core/rendering/compositing/CompositingReasonFinder.cpp
|
Source/core/rendering/compositing/CompositingReasonFinder.cpp
|
// Copyright 2014 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 "config.h"
#include "core/rendering/compositing/CompositingReasonFinder.h"
#include "core/CSSPropertyNames.h"
#include "core/dom/Document.h"
#include "core/frame/FrameView.h"
#include "core/frame/Settings.h"
#include "core/page/Page.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/compositing/RenderLayerCompositor.h"
namespace WebCore {
CompositingReasonFinder::CompositingReasonFinder(RenderView& renderView)
: m_renderView(renderView)
, m_compositingTriggers(static_cast<CompositingTriggerFlags>(AllCompositingTriggers))
{
updateTriggers();
}
void CompositingReasonFinder::updateTriggers()
{
m_compositingTriggers = 0;
Settings& settings = m_renderView.document().page()->settings();
if (settings.acceleratedCompositingForVideoEnabled())
m_compositingTriggers |= VideoTrigger;
if (settings.acceleratedCompositingForCanvasEnabled())
m_compositingTriggers |= CanvasTrigger;
if (settings.compositedScrollingForFramesEnabled())
m_compositingTriggers |= ScrollableInnerFrameTrigger;
if (settings.acceleratedCompositingForFiltersEnabled())
m_compositingTriggers |= FilterTrigger;
// We map both these settings to universal overlow scrolling.
// FIXME: Replace these settings with a generic compositing setting for HighDPI.
if (settings.acceleratedCompositingForOverflowScrollEnabled() || settings.compositorDrivenAcceleratedScrollingEnabled())
m_compositingTriggers |= OverflowScrollTrigger;
if (settings.acceleratedCompositingForFixedPositionEnabled())
m_compositingTriggers |= ViewportConstrainedPositionedTrigger;
}
bool CompositingReasonFinder::hasOverflowScrollTrigger() const
{
return m_compositingTriggers & OverflowScrollTrigger;
}
bool CompositingReasonFinder::isMainFrame() const
{
// FIXME: LocalFrame::isMainFrame() is probably better.
return !m_renderView.document().ownerElement();
}
CompositingReasons CompositingReasonFinder::directReasons(const RenderLayer* layer) const
{
ASSERT(potentialCompositingReasonsFromStyle(layer->renderer()) == layer->potentialCompositingReasonsFromStyle());
CompositingReasons styleDeterminedDirectCompositingReasons = layer->potentialCompositingReasonsFromStyle() & CompositingReasonComboAllDirectStyleDeterminedReasons;
return styleDeterminedDirectCompositingReasons | nonStyleDeterminedDirectReasons(layer);
}
// This information doesn't appear to be incorporated into CompositingReasons.
bool CompositingReasonFinder::requiresCompositingForScrollableFrame() const
{
// Need this done first to determine overflow.
ASSERT(!m_renderView.needsLayout());
if (isMainFrame())
return false;
if (!(m_compositingTriggers & ScrollableInnerFrameTrigger))
return false;
return m_renderView.frameView()->isScrollable();
}
CompositingReasons CompositingReasonFinder::potentialCompositingReasonsFromStyle(RenderObject* renderer) const
{
CompositingReasons reasons = CompositingReasonNone;
RenderStyle* style = renderer->style();
if (requiresCompositingForTransform(renderer))
reasons |= CompositingReason3DTransform;
if (requiresCompositingForFilters(renderer))
reasons |= CompositingReasonFilters;
if (style->backfaceVisibility() == BackfaceVisibilityHidden)
reasons |= CompositingReasonBackfaceVisibilityHidden;
if (requiresCompositingForAnimation(style))
reasons |= CompositingReasonActiveAnimation;
if (style->hasWillChangeCompositingHint() && !style->subtreeWillChangeContents())
reasons |= CompositingReasonWillChangeCompositingHint;
if (style->hasInlineTransform())
reasons |= CompositingReasonInlineTransform;
if (style->transformStyle3D() == TransformStyle3DPreserve3D)
reasons |= CompositingReasonPreserve3DWith3DDescendants;
if (style->hasPerspective())
reasons |= CompositingReasonPerspectiveWith3DDescendants;
// If the implementation of createsGroup changes, we need to be aware of that in this part of code.
ASSERT((renderer->isTransparent() || renderer->hasMask() || renderer->hasFilter() || renderer->hasBlendMode()) == renderer->createsGroup());
if (style->hasMask())
reasons |= CompositingReasonMaskWithCompositedDescendants;
if (style->hasFilter())
reasons |= CompositingReasonFilterWithCompositedDescendants;
// See RenderLayer::updateTransform for an explanation of why we check both.
if (renderer->hasTransform() && style->hasTransform())
reasons |= CompositingReasonTransformWithCompositedDescendants;
if (renderer->isTransparent())
reasons |= CompositingReasonOpacityWithCompositedDescendants;
if (renderer->hasBlendMode())
reasons |= CompositingReasonBlendingWithCompositedDescendants;
if (renderer->hasReflection())
reasons |= CompositingReasonReflectionWithCompositedDescendants;
ASSERT(!(reasons & ~CompositingReasonComboAllStyleDeterminedReasons));
return reasons;
}
bool CompositingReasonFinder::requiresCompositingForTransform(RenderObject* renderer) const
{
// Note that we ask the renderer if it has a transform, because the style may have transforms,
// but the renderer may be an inline that doesn't suppport them.
return renderer->hasTransform() && renderer->style()->transform().has3DOperation();
}
bool CompositingReasonFinder::requiresCompositingForFilters(RenderObject* renderer) const
{
if (!(m_compositingTriggers & FilterTrigger))
return false;
return renderer->hasFilter();
}
CompositingReasons CompositingReasonFinder::nonStyleDeterminedDirectReasons(const RenderLayer* layer) const
{
CompositingReasons directReasons = CompositingReasonNone;
RenderObject* renderer = layer->renderer();
if (hasOverflowScrollTrigger()) {
// IsUnclippedDescendant is only actually stale during the chicken/egg code path.
// FIXME: Use compositingInputs().isUnclippedDescendant to ASSERT that
// this value isn't stale.
if (layer->compositingInputs().isUnclippedDescendant)
directReasons |= CompositingReasonOutOfFlowClipping;
if (layer->scrollParent())
directReasons |= CompositingReasonOverflowScrollingParent;
if (layer->needsCompositedScrolling())
directReasons |= CompositingReasonOverflowScrollingTouch;
}
if (requiresCompositingForPositionFixed(renderer, layer, 0))
directReasons |= CompositingReasonPositionFixed;
directReasons |= renderer->additionalCompositingReasons(m_compositingTriggers);
ASSERT(!(directReasons & CompositingReasonComboAllStyleDeterminedReasons));
return directReasons;
}
bool CompositingReasonFinder::requiresCompositingForAnimation(RenderStyle* style) const
{
if (style->subtreeWillChangeContents())
return style->isRunningAnimationOnCompositor();
return style->shouldCompositeForCurrentAnimations();
}
bool CompositingReasonFinder::requiresCompositingForPositionFixed(RenderObject* renderer, const RenderLayer* layer, RenderLayer::ViewportConstrainedNotCompositedReason* viewportConstrainedNotCompositedReason) const
{
if (!(m_compositingTriggers & ViewportConstrainedPositionedTrigger))
return false;
if (renderer->style()->position() != FixedPosition)
return false;
RenderObject* container = renderer->container();
// If the renderer is not hooked up yet then we have to wait until it is.
if (!container) {
ASSERT(m_renderView.document().lifecycle().state() < DocumentLifecycle::InCompositingUpdate);
// FIXME: Remove this and ASSERT(container) once we get rid of the incremental
// allocateOrClearCompositedLayerMapping compositing update. This happens when
// adding the renderer to the tree because we setStyle before addChild in
// createRendererForElementIfNeeded.
return false;
}
// Don't promote fixed position elements that are descendants of a non-view container, e.g. transformed elements.
// They will stay fixed wrt the container rather than the enclosing frame.
if (container != &m_renderView) {
if (viewportConstrainedNotCompositedReason)
*viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForNonViewContainer;
return false;
}
// If the fixed-position element does not have any scrollable ancestor between it and
// its container, then we do not need to spend compositor resources for it. Start by
// assuming we can opt-out (i.e. no scrollable ancestor), and refine the answer below.
bool hasScrollableAncestor = false;
// The FrameView has the scrollbars associated with the top level viewport, so we have to
// check the FrameView in addition to the hierarchy of ancestors.
FrameView* frameView = m_renderView.frameView();
if (frameView && frameView->isScrollable())
hasScrollableAncestor = true;
RenderLayer* ancestor = layer->parent();
while (ancestor && !hasScrollableAncestor) {
if (ancestor->scrollsOverflow())
hasScrollableAncestor = true;
if (ancestor->renderer() == &m_renderView)
break;
ancestor = ancestor->parent();
}
if (!hasScrollableAncestor) {
if (viewportConstrainedNotCompositedReason)
*viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForUnscrollableAncestors;
return false;
}
// Subsequent tests depend on layout. If we can't tell now, just keep things the way they are until layout is done.
// FIXME: Get rid of this codepath once we get rid of the incremental compositing update in RenderLayer::styleChanged.
if (m_renderView.document().lifecycle().state() < DocumentLifecycle::LayoutClean)
return layer->hasCompositedLayerMapping();
bool paintsContent = layer->isVisuallyNonEmpty() || layer->hasVisibleDescendant();
if (!paintsContent) {
if (viewportConstrainedNotCompositedReason)
*viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForNoVisibleContent;
return false;
}
// Fixed position elements that are invisible in the current view don't get their own layer.
if (FrameView* frameView = m_renderView.frameView()) {
ASSERT(m_renderView.document().lifecycle().state() == DocumentLifecycle::InCompositingUpdate);
LayoutRect viewBounds = frameView->viewportConstrainedVisibleContentRect();
LayoutRect layerBounds = layer->boundingBoxForCompositing(layer->compositor()->rootRenderLayer(), RenderLayer::ApplyBoundsChickenEggHacks);
if (!viewBounds.intersects(enclosingIntRect(layerBounds))) {
if (viewportConstrainedNotCompositedReason)
*viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForBoundsOutOfView;
return false;
}
}
return true;
}
}
|
// Copyright 2014 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 "config.h"
#include "core/rendering/compositing/CompositingReasonFinder.h"
#include "core/CSSPropertyNames.h"
#include "core/dom/Document.h"
#include "core/frame/FrameView.h"
#include "core/frame/Settings.h"
#include "core/page/Page.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/compositing/RenderLayerCompositor.h"
namespace WebCore {
CompositingReasonFinder::CompositingReasonFinder(RenderView& renderView)
: m_renderView(renderView)
, m_compositingTriggers(static_cast<CompositingTriggerFlags>(AllCompositingTriggers))
{
updateTriggers();
}
void CompositingReasonFinder::updateTriggers()
{
m_compositingTriggers = 0;
Settings& settings = m_renderView.document().page()->settings();
if (settings.acceleratedCompositingForVideoEnabled())
m_compositingTriggers |= VideoTrigger;
if (settings.acceleratedCompositingForCanvasEnabled())
m_compositingTriggers |= CanvasTrigger;
if (settings.compositedScrollingForFramesEnabled())
m_compositingTriggers |= ScrollableInnerFrameTrigger;
if (settings.acceleratedCompositingForFiltersEnabled())
m_compositingTriggers |= FilterTrigger;
// We map both these settings to universal overlow scrolling.
// FIXME: Replace these settings with a generic compositing setting for HighDPI.
if (settings.acceleratedCompositingForOverflowScrollEnabled() || settings.compositorDrivenAcceleratedScrollingEnabled())
m_compositingTriggers |= OverflowScrollTrigger;
if (settings.acceleratedCompositingForFixedPositionEnabled())
m_compositingTriggers |= ViewportConstrainedPositionedTrigger;
}
bool CompositingReasonFinder::hasOverflowScrollTrigger() const
{
return m_compositingTriggers & OverflowScrollTrigger;
}
bool CompositingReasonFinder::isMainFrame() const
{
// FIXME: LocalFrame::isMainFrame() is probably better.
return !m_renderView.document().ownerElement();
}
CompositingReasons CompositingReasonFinder::directReasons(const RenderLayer* layer) const
{
ASSERT(potentialCompositingReasonsFromStyle(layer->renderer()) == layer->potentialCompositingReasonsFromStyle());
CompositingReasons styleDeterminedDirectCompositingReasons = layer->potentialCompositingReasonsFromStyle() & CompositingReasonComboAllDirectStyleDeterminedReasons;
return styleDeterminedDirectCompositingReasons | nonStyleDeterminedDirectReasons(layer);
}
// This information doesn't appear to be incorporated into CompositingReasons.
bool CompositingReasonFinder::requiresCompositingForScrollableFrame() const
{
// Need this done first to determine overflow.
ASSERT(!m_renderView.needsLayout());
if (isMainFrame())
return false;
if (!(m_compositingTriggers & ScrollableInnerFrameTrigger))
return false;
return m_renderView.frameView()->isScrollable();
}
CompositingReasons CompositingReasonFinder::potentialCompositingReasonsFromStyle(RenderObject* renderer) const
{
CompositingReasons reasons = CompositingReasonNone;
RenderStyle* style = renderer->style();
if (requiresCompositingForTransform(renderer))
reasons |= CompositingReason3DTransform;
if (requiresCompositingForFilters(renderer))
reasons |= CompositingReasonFilters;
if (style->backfaceVisibility() == BackfaceVisibilityHidden)
reasons |= CompositingReasonBackfaceVisibilityHidden;
if (requiresCompositingForAnimation(style))
reasons |= CompositingReasonActiveAnimation;
if (style->hasWillChangeCompositingHint() && !style->subtreeWillChangeContents())
reasons |= CompositingReasonWillChangeCompositingHint;
if (style->hasInlineTransform())
reasons |= CompositingReasonInlineTransform;
if (style->transformStyle3D() == TransformStyle3DPreserve3D)
reasons |= CompositingReasonPreserve3DWith3DDescendants;
if (style->hasPerspective())
reasons |= CompositingReasonPerspectiveWith3DDescendants;
// If the implementation of createsGroup changes, we need to be aware of that in this part of code.
ASSERT((renderer->isTransparent() || renderer->hasMask() || renderer->hasFilter() || renderer->hasBlendMode()) == renderer->createsGroup());
if (style->hasMask())
reasons |= CompositingReasonMaskWithCompositedDescendants;
if (style->hasFilter())
reasons |= CompositingReasonFilterWithCompositedDescendants;
// See RenderLayer::updateTransform for an explanation of why we check both.
if (renderer->hasTransform() && style->hasTransform())
reasons |= CompositingReasonTransformWithCompositedDescendants;
if (renderer->isTransparent())
reasons |= CompositingReasonOpacityWithCompositedDescendants;
if (renderer->hasBlendMode())
reasons |= CompositingReasonBlendingWithCompositedDescendants;
if (renderer->hasReflection())
reasons |= CompositingReasonReflectionWithCompositedDescendants;
ASSERT(!(reasons & ~CompositingReasonComboAllStyleDeterminedReasons));
return reasons;
}
bool CompositingReasonFinder::requiresCompositingForTransform(RenderObject* renderer) const
{
// Note that we ask the renderer if it has a transform, because the style may have transforms,
// but the renderer may be an inline that doesn't suppport them.
return renderer->hasTransform() && renderer->style()->transform().has3DOperation();
}
bool CompositingReasonFinder::requiresCompositingForFilters(RenderObject* renderer) const
{
if (!(m_compositingTriggers & FilterTrigger))
return false;
return renderer->hasFilter();
}
CompositingReasons CompositingReasonFinder::nonStyleDeterminedDirectReasons(const RenderLayer* layer) const
{
CompositingReasons directReasons = CompositingReasonNone;
RenderObject* renderer = layer->renderer();
if (hasOverflowScrollTrigger()) {
if (layer->compositingInputs().isUnclippedDescendant)
directReasons |= CompositingReasonOutOfFlowClipping;
if (layer->scrollParent())
directReasons |= CompositingReasonOverflowScrollingParent;
if (layer->needsCompositedScrolling())
directReasons |= CompositingReasonOverflowScrollingTouch;
}
if (requiresCompositingForPositionFixed(renderer, layer, 0))
directReasons |= CompositingReasonPositionFixed;
directReasons |= renderer->additionalCompositingReasons(m_compositingTriggers);
ASSERT(!(directReasons & CompositingReasonComboAllStyleDeterminedReasons));
return directReasons;
}
bool CompositingReasonFinder::requiresCompositingForAnimation(RenderStyle* style) const
{
if (style->subtreeWillChangeContents())
return style->isRunningAnimationOnCompositor();
return style->shouldCompositeForCurrentAnimations();
}
bool CompositingReasonFinder::requiresCompositingForPositionFixed(RenderObject* renderer, const RenderLayer* layer, RenderLayer::ViewportConstrainedNotCompositedReason* viewportConstrainedNotCompositedReason) const
{
if (!(m_compositingTriggers & ViewportConstrainedPositionedTrigger))
return false;
if (renderer->style()->position() != FixedPosition)
return false;
RenderObject* container = renderer->container();
// If the renderer is not hooked up yet then we have to wait until it is.
if (!container) {
ASSERT(m_renderView.document().lifecycle().state() < DocumentLifecycle::InCompositingUpdate);
// FIXME: Remove this and ASSERT(container) once we get rid of the incremental
// allocateOrClearCompositedLayerMapping compositing update. This happens when
// adding the renderer to the tree because we setStyle before addChild in
// createRendererForElementIfNeeded.
return false;
}
// Don't promote fixed position elements that are descendants of a non-view container, e.g. transformed elements.
// They will stay fixed wrt the container rather than the enclosing frame.
if (container != &m_renderView) {
if (viewportConstrainedNotCompositedReason)
*viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForNonViewContainer;
return false;
}
// If the fixed-position element does not have any scrollable ancestor between it and
// its container, then we do not need to spend compositor resources for it. Start by
// assuming we can opt-out (i.e. no scrollable ancestor), and refine the answer below.
bool hasScrollableAncestor = false;
// The FrameView has the scrollbars associated with the top level viewport, so we have to
// check the FrameView in addition to the hierarchy of ancestors.
FrameView* frameView = m_renderView.frameView();
if (frameView && frameView->isScrollable())
hasScrollableAncestor = true;
RenderLayer* ancestor = layer->parent();
while (ancestor && !hasScrollableAncestor) {
if (ancestor->scrollsOverflow())
hasScrollableAncestor = true;
if (ancestor->renderer() == &m_renderView)
break;
ancestor = ancestor->parent();
}
if (!hasScrollableAncestor) {
if (viewportConstrainedNotCompositedReason)
*viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForUnscrollableAncestors;
return false;
}
// Subsequent tests depend on layout. If we can't tell now, just keep things the way they are until layout is done.
// FIXME: Get rid of this codepath once we get rid of the incremental compositing update in RenderLayer::styleChanged.
if (m_renderView.document().lifecycle().state() < DocumentLifecycle::LayoutClean)
return layer->hasCompositedLayerMapping();
bool paintsContent = layer->isVisuallyNonEmpty() || layer->hasVisibleDescendant();
if (!paintsContent) {
if (viewportConstrainedNotCompositedReason)
*viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForNoVisibleContent;
return false;
}
// Fixed position elements that are invisible in the current view don't get their own layer.
if (FrameView* frameView = m_renderView.frameView()) {
ASSERT(m_renderView.document().lifecycle().state() == DocumentLifecycle::InCompositingUpdate);
LayoutRect viewBounds = frameView->viewportConstrainedVisibleContentRect();
LayoutRect layerBounds = layer->boundingBoxForCompositing(layer->compositor()->rootRenderLayer(), RenderLayer::ApplyBoundsChickenEggHacks);
if (!viewBounds.intersects(enclosingIntRect(layerBounds))) {
if (viewportConstrainedNotCompositedReason)
*viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForBoundsOutOfView;
return false;
}
}
return true;
}
}
|
Remove outdated comment
|
Remove outdated comment
[email protected]
Review URL: https://codereview.chromium.org/372043002
git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@177615 bbb929c8-8fbe-4397-9dbb-9b2b20218538
|
C++
|
bsd-3-clause
|
primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs
|
03ffd834825fdfe39283ec62d8c8b691a96c4ffa
|
kernel/src/tree/node_events.cpp
|
kernel/src/tree/node_events.cpp
|
/// @file
/// @author uentity
/// @date 30.03.2020
/// @brief BS tree node events handling
/// @copyright
/// 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 https://mozilla.org/MPL/2.0/
#include "node_actor.h"
#include "ev_listener_actor.h"
#include "../serialize/tree_impl.h"
#include <bs/kernel/radio.h>
#include <bs/log.h>
#include <bs/serialize/cafbind.h>
#include <bs/serialize/tree.h>
NAMESPACE_BEGIN(blue_sky::tree)
auto node::subscribe(event_handler f, Event listen_to) const -> std::uint64_t {
using namespace kernel::radio;
using namespace allow_enumops;
using baby_t = ev_listener_actor<node>;
static const auto handler_impl = [](
baby_t* self, auto& weak_root, const caf::actor& subn_actor, Event ev, prop::propdict params
) {
if(auto r = weak_root.lock()) {
// reconstruct subnode via node impl
auto subnode = node::nil();
if(subn_actor) {
actorf<sp_nimpl>(subn_actor, kernel::radio::timeout(), a_impl())
.map([&](const sp_nimpl& subn_impl) { subnode = subn_impl->super_engine(); });
}
// invoke callback
self->f(std::move(r), std::move(subnode), ev, std::move(params));
}
else // if root source is dead, quit
self->quit();
};
auto make_ev_character = [weak_root = weak_ptr(*this), listen_to](baby_t* self) {
auto res = caf::message_handler{};
if(enumval(listen_to & Event::LinkRenamed)) {
const auto renamed_impl = [=](
const caf::actor& subn_actor, auto& lid, auto& new_name, auto& old_name
) {
bsout() << "*-* node: fired LinkRenamed event" << bs_end;
handler_impl(self, weak_root, subn_actor, Event::LinkRenamed, {
{"link_id", lid},
{"new_name", std::move(new_name)},
{"prev_name", std::move(old_name)}
});
};
// this node leaf was renamed
res = res.or_else(
[=] (
a_ack, const lid_type& lid, a_lnk_rename, std::string new_name, std::string old_name
) {
renamed_impl({}, lid, new_name, old_name);
}
);
// deeper subtree leaf was renamed
res = res.or_else(
[=] (
a_ack, const caf::actor& src, const lid_type& lid,
a_lnk_rename, std::string new_name, std::string old_name
) {
renamed_impl(src, lid, new_name, old_name);
}
);
bsout() << "*-* node: subscribed to LinkRenamed event" << bs_end;
}
if(enumval(listen_to & Event::LinkStatusChanged)) {
const auto status_impl = [=](
const caf::actor& subn_actor, auto& lid, auto req, auto new_s, auto prev_s
) {
bsout() << "*-* node: fired LinkStatusChanged event" << bs_end;
handler_impl(self, weak_root, subn_actor, Event::LinkStatusChanged, {
{"link_id", lid},
{"request", prop::integer(req)},
{"new_status", prop::integer(new_s)},
{"prev_status", prop::integer(prev_s)}
});
};
// this node leaf status changed
res = res.or_else(
[=](
a_ack, const lid_type& lid,
a_lnk_status, Req req, ReqStatus new_s, ReqStatus prev_s
) {
status_impl({}, lid, req, new_s, prev_s);
}
);
// deeper subtree leaf status changed
res = res.or_else(
[=](
a_ack, const caf::actor& src, const lid_type& lid,
a_lnk_status, Req req, ReqStatus new_s, ReqStatus prev_s
) {
status_impl(src, lid, req, new_s, prev_s);
}
);
bsout() << "*-* node: subscribed to LinkStatusChanged event" << bs_end;
}
if(enumval(listen_to & Event::DataModified)) {
const auto datamod_impl = [=](
const caf::actor& subn_actor, auto& lid, tr_result::box&& tres_box
) {
bsout() << "*-* node: fired DataModified event" << bs_end;
auto params = prop::propdict{{ "link_id", lid }};
if(auto tres = tr_result{std::move(tres_box)})
params = extract_info(std::move(tres));
else
params["error"] = to_string(extract_err(std::move(tres)));
handler_impl(self, weak_root, subn_actor, Event::DataModified, std::move(params));
};
// this node leaf data changed
res = res.or_else(
[=](a_ack, const lid_type& lid, a_data, tr_result::box trbox) {
datamod_impl({}, lid, std::move(trbox));
}
);
// deeper subtree leaf status changed
res = res.or_else(
[=](a_ack, const caf::actor& src, const lid_type& lid, a_data, tr_result::box trbox) {
datamod_impl(src, lid, std::move(trbox));
}
);
bsout() << "*-* node: subscribed to DataModified event" << bs_end;
}
if(enumval(listen_to & Event::LinkInserted)) {
res = res.or_else(
// insert
[=](
a_ack, const caf::actor& src, a_node_insert,
const lid_type& lid, std::size_t pos
) {
bsout() << "*-* node: fired LinkInserted event" << bs_end;
handler_impl(self, weak_root, src, Event::LinkInserted, {
{"link_id", lid},
{"pos", (prop::integer)pos}
});
},
// move
[=](
a_ack, const caf::actor& src, a_node_insert,
const lid_type& lid, std::size_t to_idx, std::size_t from_idx
) {
bsout() << "*-* node: fired LinkInserted event (move)" << bs_end;
handler_impl(self, weak_root, src, Event::LinkInserted, {
{"link_id", lid},
{"to_idx", (prop::integer)to_idx},
{"from_idx", (prop::integer)from_idx}
});
}
);
bsout() << "*-* node: subscribed to LinkInserted event" << bs_end;
}
if(enumval(listen_to & Event::LinkErased)) {
res = res.or_else(
[=](
a_ack, const caf::actor& src, a_node_erase, lids_v lids
) {
bsout() << "*-* node: fired LinkErased event" << bs_end;
handler_impl(self, weak_root, src, Event::LinkErased, {
{"lids", std::move(lids)}
});
}
);
bsout() << "*-* node: subscribed to LinkErased event" << bs_end;
}
return res;
};
// make shiny new subscriber actor and place into parent's room
auto baby = system().spawn_in_group<baby_t>(
pimpl()->home, pimpl()->home, std::move(f), std::move(make_ev_character)
);
// and return ID
return baby.id();
}
auto node::unsubscribe(std::uint64_t event_cb_id) -> void {
kernel::radio::bye_actor(event_cb_id);
}
NAMESPACE_END(blue_sky::tree)
|
/// @file
/// @author uentity
/// @date 30.03.2020
/// @brief BS tree node events handling
/// @copyright
/// 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 https://mozilla.org/MPL/2.0/
#include "node_actor.h"
#include "ev_listener_actor.h"
#include "../serialize/tree_impl.h"
#include <bs/kernel/radio.h>
#include <bs/log.h>
#include <bs/serialize/cafbind.h>
#include <bs/serialize/tree.h>
NAMESPACE_BEGIN(blue_sky::tree)
auto node::subscribe(event_handler f, Event listen_to) const -> std::uint64_t {
using namespace kernel::radio;
using namespace allow_enumops;
using baby_t = ev_listener_actor<node>;
static const auto handler_impl = [](
baby_t* self, auto& weak_root, const caf::actor& subn_actor, Event ev, prop::propdict params
) {
if(auto r = weak_root.lock()) {
// reconstruct subnode via node impl
auto subnode = node::nil();
if(subn_actor) {
actorf<sp_nimpl>(subn_actor, kernel::radio::timeout(), a_impl())
.map([&](const sp_nimpl& subn_impl) { subnode = subn_impl->super_engine(); });
}
// invoke callback
self->f(std::move(r), std::move(subnode), ev, std::move(params));
}
else // if root source is dead, quit
self->quit();
};
auto make_ev_character = [weak_root = weak_ptr(*this), listen_to](baby_t* self) {
auto res = caf::message_handler{};
if(enumval(listen_to & Event::LinkRenamed)) {
const auto renamed_impl = [=](
const caf::actor& subn_actor, auto& lid, auto& new_name, auto& old_name
) {
bsout() << "*-* node: fired LinkRenamed event" << bs_end;
handler_impl(self, weak_root, subn_actor, Event::LinkRenamed, {
{"link_id", lid},
{"new_name", std::move(new_name)},
{"prev_name", std::move(old_name)}
});
};
// this node leaf was renamed
res = res.or_else(
[=] (
a_ack, const lid_type& lid, a_lnk_rename, std::string new_name, std::string old_name
) {
renamed_impl({}, lid, new_name, old_name);
}
);
// deeper subtree leaf was renamed
res = res.or_else(
[=] (
a_ack, const caf::actor& src, const lid_type& lid,
a_lnk_rename, std::string new_name, std::string old_name
) {
renamed_impl(src, lid, new_name, old_name);
}
);
bsout() << "*-* node: subscribed to LinkRenamed event" << bs_end;
}
if(enumval(listen_to & Event::LinkStatusChanged)) {
const auto status_impl = [=](
const caf::actor& subn_actor, auto& lid, auto req, auto new_s, auto prev_s
) {
bsout() << "*-* node: fired LinkStatusChanged event" << bs_end;
handler_impl(self, weak_root, subn_actor, Event::LinkStatusChanged, {
{"link_id", lid},
{"request", prop::integer(req)},
{"new_status", prop::integer(new_s)},
{"prev_status", prop::integer(prev_s)}
});
};
// this node leaf status changed
res = res.or_else(
[=](
a_ack, const lid_type& lid,
a_lnk_status, Req req, ReqStatus new_s, ReqStatus prev_s
) {
status_impl({}, lid, req, new_s, prev_s);
}
);
// deeper subtree leaf status changed
res = res.or_else(
[=](
a_ack, const caf::actor& src, const lid_type& lid,
a_lnk_status, Req req, ReqStatus new_s, ReqStatus prev_s
) {
status_impl(src, lid, req, new_s, prev_s);
}
);
bsout() << "*-* node: subscribed to LinkStatusChanged event" << bs_end;
}
if(enumval(listen_to & Event::DataModified)) {
const auto datamod_impl = [=](
const caf::actor& subn_actor, auto& lid, tr_result::box&& tres_box
) {
bsout() << "*-* node: fired DataModified event" << bs_end;
auto params = prop::propdict{{ "link_id", lid }};
if(auto tres = tr_result{std::move(tres_box)})
params.merge_props(extract_info(std::move(tres)));
else
params["error"] = to_string(extract_err(std::move(tres)));
handler_impl(self, weak_root, subn_actor, Event::DataModified, std::move(params));
};
// this node leaf data changed
res = res.or_else(
[=](a_ack, const lid_type& lid, a_data, tr_result::box trbox) {
datamod_impl({}, lid, std::move(trbox));
}
);
// deeper subtree leaf status changed
res = res.or_else(
[=](a_ack, const caf::actor& src, const lid_type& lid, a_data, tr_result::box trbox) {
datamod_impl(src, lid, std::move(trbox));
}
);
bsout() << "*-* node: subscribed to DataModified event" << bs_end;
}
if(enumval(listen_to & Event::LinkInserted)) {
res = res.or_else(
// insert
[=](
a_ack, const caf::actor& src, a_node_insert,
const lid_type& lid, std::size_t pos
) {
bsout() << "*-* node: fired LinkInserted event" << bs_end;
handler_impl(self, weak_root, src, Event::LinkInserted, {
{"link_id", lid},
{"pos", (prop::integer)pos}
});
},
// move
[=](
a_ack, const caf::actor& src, a_node_insert,
const lid_type& lid, std::size_t to_idx, std::size_t from_idx
) {
bsout() << "*-* node: fired LinkInserted event (move)" << bs_end;
handler_impl(self, weak_root, src, Event::LinkInserted, {
{"link_id", lid},
{"to_idx", (prop::integer)to_idx},
{"from_idx", (prop::integer)from_idx}
});
}
);
bsout() << "*-* node: subscribed to LinkInserted event" << bs_end;
}
if(enumval(listen_to & Event::LinkErased)) {
res = res.or_else(
[=](
a_ack, const caf::actor& src, a_node_erase, lids_v lids
) {
bsout() << "*-* node: fired LinkErased event" << bs_end;
handler_impl(self, weak_root, src, Event::LinkErased, {
{"lids", std::move(lids)}
});
}
);
bsout() << "*-* node: subscribed to LinkErased event" << bs_end;
}
return res;
};
// make shiny new subscriber actor and place into parent's room
auto baby = system().spawn_in_group<baby_t>(
pimpl()->home, pimpl()->home, std::move(f), std::move(make_ev_character)
);
// and return ID
return baby.id();
}
auto node::unsubscribe(std::uint64_t event_cb_id) -> void {
kernel::radio::bye_actor(event_cb_id);
}
NAMESPACE_END(blue_sky::tree)
|
fix link ID wasn't preserved in params for DataModified ev
|
node/events: fix link ID wasn't preserved in params for DataModified ev
|
C++
|
mpl-2.0
|
uentity/blue-sky-re,uentity/blue-sky-re,uentity/blue-sky-re
|
356436c0ffbda464d0b2f6f33178de48d66091df
|
kfile-plugins/vcf/kfile_vcf.cpp
|
kfile-plugins/vcf/kfile_vcf.cpp
|
/* This file is part of the KDE project
* Copyright (C) 2002 Shane Wright <[email protected]>
*
* 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 version 2.
*
* 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
*/
#include <config.h>
#include "kfile_vcf.h"
#include <kprocess.h>
#include <klocale.h>
#include <kgenericfactory.h>
#include <kstringvalidator.h>
#include <kdebug.h>
#include <qdict.h>
#include <qvalidator.h>
#include <qcstring.h>
#include <qfile.h>
#include <qdatetime.h>
#if !defined(__osf__)
#include <inttypes.h>
#else
typedef unsigned short uint32_t;
#endif
typedef KGenericFactory<KVcfPlugin> VcfFactory;
K_EXPORT_COMPONENT_FACTORY(kfile_vcf, VcfFactory( "kfile_vcf" ))
KVcfPlugin::KVcfPlugin(QObject *parent, const char *name,
const QStringList &args)
: KFilePlugin(parent, name, args)
{
KFileMimeTypeInfo* info = addMimeTypeInfo( "text/x-vcard" );
KFileMimeTypeInfo::GroupInfo* group = 0L;
group = addGroupInfo(info, "Technical", i18n("Technical Details"));
KFileMimeTypeInfo::ItemInfo* item;
item = addItemInfo(group, "Name", i18n("Name"), QVariant::String);
item = addItemInfo(group, "Email", i18n("Email"), QVariant::String);
item = addItemInfo(group, "Telephone", i18n("Telephone"), QVariant::String);
}
bool KVcfPlugin::readInfo( KFileMetaInfo& info, uint /*what*/ )
{
QFile file(info.path());
if (!file.open(IO_ReadOnly))
{
kdDebug(7034) << "Couldn't open " << QFile::encodeName(info.path()) << endl;
return false;
}
char id_name[] = "FN:";
char id_email[] = "EMAIL;INTERNET:";
// we need a buffer for lines
char linebuf[1000];
// we need a buffer for other stuff
char buf_name[1000] = "";
char buf_email[1000] = "";
buf_name[999] = '\0';
buf_email[999] = '\0';
char * myptr;
bool done=false;
while (!done) {
// read a line
file.readLine(linebuf, 4096);
// have we got something useful?
if (memcmp(linebuf, id_name, 3) == 0) {
// we have a name
myptr = linebuf + 3;
strncpy(buf_name, myptr, 999);
} else if (memcmp(linebuf, id_email, 15) == 0) {
// we have a name
myptr = linebuf + 15;
strncpy(buf_email, myptr, 999);
}
// are we done yet?
if (
((strlen(buf_name) > 0) && (strlen(buf_email) > 0)) ||
(file.atEnd())
)
done = true;
};
KFileMetaInfoGroup group = appendGroup(info, "Technical");
if (strlen(buf_name) > 0)
appendItem(group, "Name", buf_name);
if (strlen(buf_email) > 0)
appendItem(group, "Email", buf_email);
return true;
}
#include "kfile_vcf.moc"
|
/* This file is part of the KDE project
* Copyright (C) 2002 Shane Wright <[email protected]>
*
* 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 version 2.
*
* 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
*/
#include <config.h>
#include "kfile_vcf.h"
#include <kprocess.h>
#include <klocale.h>
#include <kgenericfactory.h>
#include <kstringvalidator.h>
#include <kdebug.h>
#include <qdict.h>
#include <qvalidator.h>
#include <qcstring.h>
#include <qfile.h>
#include <qdatetime.h>
#if !defined(__osf__)
#include <inttypes.h>
#else
typedef unsigned short uint32_t;
#endif
typedef KGenericFactory<KVcfPlugin> VcfFactory;
K_EXPORT_COMPONENT_FACTORY(kfile_vcf, VcfFactory( "kfile_vcf" ))
KVcfPlugin::KVcfPlugin(QObject *parent, const char *name,
const QStringList &args)
: KFilePlugin(parent, name, args)
{
KFileMimeTypeInfo* info = addMimeTypeInfo( "text/x-vcard" );
KFileMimeTypeInfo::GroupInfo* group = 0L;
group = addGroupInfo(info, "Technical", i18n("Technical Details"));
KFileMimeTypeInfo::ItemInfo* item;
item = addItemInfo(group, "Name", i18n("Name"), QVariant::String);
item = addItemInfo(group, "Email", i18n("Email"), QVariant::String);
item = addItemInfo(group, "Telephone", i18n("Telephone"), QVariant::String);
}
bool KVcfPlugin::readInfo( KFileMetaInfo& info, uint /*what*/ )
{
QFile file(info.path());
if (!file.open(IO_ReadOnly))
{
kdDebug(7034) << "Couldn't open " << QFile::encodeName(info.path()) << endl;
return false;
}
char id_name[] = "FN:";
char id_email[] = "EMAIL;INTERNET:";
// we need a buffer for lines
char linebuf[1000];
// we need a buffer for other stuff
char buf_name[1000] = "";
char buf_email[1000] = "";
buf_name[999] = '\0';
buf_email[999] = '\0';
char * myptr;
bool done=false;
while (!done) {
// read a line
file.readLine(linebuf, sizeof(linebuf));
// have we got something useful?
if (memcmp(linebuf, id_name, 3) == 0) {
// we have a name
myptr = linebuf + 3;
strncpy(buf_name, myptr, sizeof( buf_name ));
} else if (memcmp(linebuf, id_email, 15) == 0) {
// we have a name
myptr = linebuf + 15;
strncpy(buf_email, myptr, sizeof( buf_email ));
}
// are we done yet?
if (
((strlen(buf_name) > 0) && (strlen(buf_email) > 0)) ||
(file.atEnd())
)
done = true;
};
KFileMetaInfoGroup group = appendGroup(info, "Technical");
if (strlen(buf_name) > 0)
appendItem(group, "Name", buf_name);
if (strlen(buf_email) > 0)
appendItem(group, "Email", buf_email);
return true;
}
#include "kfile_vcf.moc"
|
fix buffer overflow
|
fix buffer overflow
svn path=/trunk/kdepim/; revision=273189
|
C++
|
lgpl-2.1
|
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
|
c57354418b70b4708cfaecbf97edad16f8da66b8
|
src/gpu/ops/GrAALinearizingConvexPathRenderer.cpp
|
src/gpu/ops/GrAALinearizingConvexPathRenderer.cpp
|
/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrAALinearizingConvexPathRenderer.h"
#include "GrAAConvexTessellator.h"
#include "GrContext.h"
#include "GrDefaultGeoProcFactory.h"
#include "GrDrawOpTest.h"
#include "GrGeometryProcessor.h"
#include "GrOpFlushState.h"
#include "GrPathUtils.h"
#include "GrProcessor.h"
#include "GrStyle.h"
#include "SkGeometry.h"
#include "SkPathPriv.h"
#include "SkString.h"
#include "SkTraceEvent.h"
#include "glsl/GrGLSLGeometryProcessor.h"
#include "ops/GrMeshDrawOp.h"
#include "ops/GrSimpleMeshDrawOpHelper.h"
static const int DEFAULT_BUFFER_SIZE = 100;
// The thicker the stroke, the harder it is to produce high-quality results using tessellation. For
// the time being, we simply drop back to software rendering above this stroke width.
static const SkScalar kMaxStrokeWidth = 20.0;
GrAALinearizingConvexPathRenderer::GrAALinearizingConvexPathRenderer() {
}
///////////////////////////////////////////////////////////////////////////////
GrPathRenderer::CanDrawPath
GrAALinearizingConvexPathRenderer::onCanDrawPath(const CanDrawPathArgs& args) const {
if (GrAAType::kCoverage != args.fAAType) {
return CanDrawPath::kNo;
}
if (!args.fShape->knownToBeConvex()) {
return CanDrawPath::kNo;
}
if (args.fShape->style().pathEffect()) {
return CanDrawPath::kNo;
}
if (args.fShape->inverseFilled()) {
return CanDrawPath::kNo;
}
if (args.fShape->bounds().width() <= 0 && args.fShape->bounds().height() <= 0) {
// Stroked zero length lines should draw, but this PR doesn't handle that case
return CanDrawPath::kNo;
}
const SkStrokeRec& stroke = args.fShape->style().strokeRec();
if (stroke.getStyle() == SkStrokeRec::kStroke_Style ||
stroke.getStyle() == SkStrokeRec::kStrokeAndFill_Style) {
if (!args.fViewMatrix->isSimilarity()) {
return CanDrawPath::kNo;
}
SkScalar strokeWidth = args.fViewMatrix->getMaxScale() * stroke.getWidth();
if (strokeWidth < 1.0f && stroke.getStyle() == SkStrokeRec::kStroke_Style) {
return CanDrawPath::kNo;
}
if (strokeWidth > kMaxStrokeWidth ||
!args.fShape->knownToBeClosed() ||
stroke.getJoin() == SkPaint::Join::kRound_Join) {
return CanDrawPath::kNo;
}
return CanDrawPath::kYes;
}
if (stroke.getStyle() != SkStrokeRec::kFill_Style) {
return CanDrawPath::kNo;
}
return CanDrawPath::kYes;
}
// extract the result vertices and indices from the GrAAConvexTessellator
static void extract_verts(const GrAAConvexTessellator& tess,
void* vertices,
size_t vertexStride,
GrColor color,
uint16_t firstIndex,
uint16_t* idxs,
bool tweakAlphaForCoverage) {
intptr_t verts = reinterpret_cast<intptr_t>(vertices);
for (int i = 0; i < tess.numPts(); ++i) {
*((SkPoint*)((intptr_t)verts + i * vertexStride)) = tess.point(i);
}
// Make 'verts' point to the colors
verts += sizeof(SkPoint);
for (int i = 0; i < tess.numPts(); ++i) {
if (tweakAlphaForCoverage) {
SkASSERT(SkScalarRoundToInt(255.0f * tess.coverage(i)) <= 255);
unsigned scale = SkScalarRoundToInt(255.0f * tess.coverage(i));
GrColor scaledColor = (0xff == scale) ? color : SkAlphaMulQ(color, scale);
*reinterpret_cast<GrColor*>(verts + i * vertexStride) = scaledColor;
} else {
*reinterpret_cast<GrColor*>(verts + i * vertexStride) = color;
*reinterpret_cast<float*>(verts + i * vertexStride + sizeof(GrColor)) =
tess.coverage(i);
}
}
for (int i = 0; i < tess.numIndices(); ++i) {
idxs[i] = tess.index(i) + firstIndex;
}
}
static sk_sp<GrGeometryProcessor> create_lines_only_gp(bool tweakAlphaForCoverage,
const SkMatrix& viewMatrix,
bool usesLocalCoords) {
using namespace GrDefaultGeoProcFactory;
Coverage::Type coverageType;
if (tweakAlphaForCoverage) {
coverageType = Coverage::kSolid_Type;
} else {
coverageType = Coverage::kAttribute_Type;
}
LocalCoords::Type localCoordsType =
usesLocalCoords ? LocalCoords::kUsePosition_Type : LocalCoords::kUnused_Type;
return MakeForDeviceSpace(Color::kPremulGrColorAttribute_Type, coverageType, localCoordsType,
viewMatrix);
}
namespace {
class AAFlatteningConvexPathOp final : public GrMeshDrawOp {
private:
using Helper = GrSimpleMeshDrawOpHelperWithStencil;
public:
DEFINE_OP_CLASS_ID
static std::unique_ptr<GrDrawOp> Make(GrPaint&& paint,
const SkMatrix& viewMatrix,
const SkPath& path,
SkScalar strokeWidth,
SkStrokeRec::Style style,
SkPaint::Join join,
SkScalar miterLimit,
const GrUserStencilSettings* stencilSettings) {
return Helper::FactoryHelper<AAFlatteningConvexPathOp>(std::move(paint), viewMatrix, path,
strokeWidth, style, join, miterLimit,
stencilSettings);
}
AAFlatteningConvexPathOp(const Helper::MakeArgs& helperArgs,
GrColor color,
const SkMatrix& viewMatrix,
const SkPath& path,
SkScalar strokeWidth,
SkStrokeRec::Style style,
SkPaint::Join join,
SkScalar miterLimit,
const GrUserStencilSettings* stencilSettings)
: INHERITED(ClassID()), fHelper(helperArgs, GrAAType::kCoverage, stencilSettings) {
fPaths.emplace_back(
PathData{color, viewMatrix, path, strokeWidth, style, join, miterLimit});
// compute bounds
SkRect bounds = path.getBounds();
SkScalar w = strokeWidth;
if (w > 0) {
w /= 2;
// If the half stroke width is < 1 then we effectively fallback to bevel joins.
if (SkPaint::kMiter_Join == join && w > 1.f) {
w *= miterLimit;
}
bounds.outset(w, w);
}
this->setTransformedBounds(bounds, viewMatrix, HasAABloat::kYes, IsZeroArea::kNo);
}
const char* name() const override { return "AAFlatteningConvexPathOp"; }
void visitProxies(const VisitProxyFunc& func) const override {
fHelper.visitProxies(func);
}
SkString dumpInfo() const override {
SkString string;
for (const auto& path : fPaths) {
string.appendf(
"Color: 0x%08x, StrokeWidth: %.2f, Style: %d, Join: %d, "
"MiterLimit: %.2f\n",
path.fColor, path.fStrokeWidth, path.fStyle, path.fJoin, path.fMiterLimit);
}
string += fHelper.dumpInfo();
string += INHERITED::dumpInfo();
return string;
}
FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
RequiresDstTexture finalize(const GrCaps& caps, const GrAppliedClip* clip,
GrPixelConfigIsClamped dstIsClamped) override {
return fHelper.xpRequiresDstTexture(caps, clip, dstIsClamped,
GrProcessorAnalysisCoverage::kSingleChannel,
&fPaths.back().fColor);
}
private:
void draw(GrMeshDrawOp::Target* target, const GrGeometryProcessor* gp,
const GrPipeline* pipeline, int vertexCount, size_t vertexStride, void* vertices,
int indexCount, uint16_t* indices) const {
if (vertexCount == 0 || indexCount == 0) {
return;
}
const GrBuffer* vertexBuffer;
GrMesh mesh(GrPrimitiveType::kTriangles);
int firstVertex;
void* verts = target->makeVertexSpace(vertexStride, vertexCount, &vertexBuffer,
&firstVertex);
if (!verts) {
SkDebugf("Could not allocate vertices\n");
return;
}
memcpy(verts, vertices, vertexCount * vertexStride);
const GrBuffer* indexBuffer;
int firstIndex;
uint16_t* idxs = target->makeIndexSpace(indexCount, &indexBuffer, &firstIndex);
if (!idxs) {
SkDebugf("Could not allocate indices\n");
return;
}
memcpy(idxs, indices, indexCount * sizeof(uint16_t));
mesh.setIndexed(indexBuffer, indexCount, firstIndex, 0, vertexCount - 1);
mesh.setVertexData(vertexBuffer, firstVertex);
target->draw(gp, pipeline, mesh);
}
void onPrepareDraws(Target* target) override {
const GrPipeline* pipeline = fHelper.makePipeline(target);
// Setup GrGeometryProcessor
sk_sp<GrGeometryProcessor> gp(create_lines_only_gp(fHelper.compatibleWithAlphaAsCoverage(),
this->viewMatrix(),
fHelper.usesLocalCoords()));
if (!gp) {
SkDebugf("Couldn't create a GrGeometryProcessor\n");
return;
}
size_t vertexStride = gp->getVertexStride();
SkASSERT(fHelper.compatibleWithAlphaAsCoverage()
? vertexStride == sizeof(GrDefaultGeoProcFactory::PositionColorAttr)
: vertexStride ==
sizeof(GrDefaultGeoProcFactory::PositionColorCoverageAttr));
int instanceCount = fPaths.count();
int vertexCount = 0;
int indexCount = 0;
int maxVertices = DEFAULT_BUFFER_SIZE;
int maxIndices = DEFAULT_BUFFER_SIZE;
uint8_t* vertices = (uint8_t*) sk_malloc_throw(maxVertices * vertexStride);
uint16_t* indices = (uint16_t*) sk_malloc_throw(maxIndices * sizeof(uint16_t));
for (int i = 0; i < instanceCount; i++) {
const PathData& args = fPaths[i];
GrAAConvexTessellator tess(args.fStyle, args.fStrokeWidth,
args.fJoin, args.fMiterLimit);
if (!tess.tessellate(args.fViewMatrix, args.fPath)) {
continue;
}
int currentIndices = tess.numIndices();
if (indexCount + currentIndices > UINT16_MAX) {
// if we added the current instance, we would overflow the indices we can store in a
// uint16_t. Draw what we've got so far and reset.
this->draw(target, gp.get(), pipeline, vertexCount, vertexStride, vertices,
indexCount, indices);
vertexCount = 0;
indexCount = 0;
}
int currentVertices = tess.numPts();
if (vertexCount + currentVertices > maxVertices) {
maxVertices = SkTMax(vertexCount + currentVertices, maxVertices * 2);
vertices = (uint8_t*) sk_realloc_throw(vertices, maxVertices * vertexStride);
}
if (indexCount + currentIndices > maxIndices) {
maxIndices = SkTMax(indexCount + currentIndices, maxIndices * 2);
indices = (uint16_t*) sk_realloc_throw(indices, maxIndices * sizeof(uint16_t));
}
extract_verts(tess, vertices + vertexStride * vertexCount, vertexStride, args.fColor,
vertexCount, indices + indexCount,
fHelper.compatibleWithAlphaAsCoverage());
vertexCount += currentVertices;
indexCount += currentIndices;
}
this->draw(target, gp.get(), pipeline, vertexCount, vertexStride, vertices, indexCount,
indices);
sk_free(vertices);
sk_free(indices);
}
bool onCombineIfPossible(GrOp* t, const GrCaps& caps) override {
AAFlatteningConvexPathOp* that = t->cast<AAFlatteningConvexPathOp>();
if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
return false;
}
fPaths.push_back_n(that->fPaths.count(), that->fPaths.begin());
this->joinBounds(*that);
return true;
}
const SkMatrix& viewMatrix() const { return fPaths[0].fViewMatrix; }
struct PathData {
GrColor fColor;
SkMatrix fViewMatrix;
SkPath fPath;
SkScalar fStrokeWidth;
SkStrokeRec::Style fStyle;
SkPaint::Join fJoin;
SkScalar fMiterLimit;
};
SkSTArray<1, PathData, true> fPaths;
Helper fHelper;
typedef GrMeshDrawOp INHERITED;
};
} // anonymous namespace
bool GrAALinearizingConvexPathRenderer::onDrawPath(const DrawPathArgs& args) {
GR_AUDIT_TRAIL_AUTO_FRAME(args.fRenderTargetContext->auditTrail(),
"GrAALinearizingConvexPathRenderer::onDrawPath");
SkASSERT(GrFSAAType::kUnifiedMSAA != args.fRenderTargetContext->fsaaType());
SkASSERT(!args.fShape->isEmpty());
SkASSERT(!args.fShape->style().pathEffect());
SkPath path;
args.fShape->asPath(&path);
bool fill = args.fShape->style().isSimpleFill();
const SkStrokeRec& stroke = args.fShape->style().strokeRec();
SkScalar strokeWidth = fill ? -1.0f : stroke.getWidth();
SkPaint::Join join = fill ? SkPaint::Join::kMiter_Join : stroke.getJoin();
SkScalar miterLimit = stroke.getMiter();
std::unique_ptr<GrDrawOp> op = AAFlatteningConvexPathOp::Make(
std::move(args.fPaint), *args.fViewMatrix, path, strokeWidth, stroke.getStyle(), join,
miterLimit, args.fUserStencilSettings);
args.fRenderTargetContext->addDrawOp(*args.fClip, std::move(op));
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#if GR_TEST_UTILS
GR_DRAW_OP_TEST_DEFINE(AAFlatteningConvexPathOp) {
SkMatrix viewMatrix = GrTest::TestMatrixPreservesRightAngles(random);
SkPath path = GrTest::TestPathConvex(random);
SkStrokeRec::Style styles[3] = { SkStrokeRec::kFill_Style,
SkStrokeRec::kStroke_Style,
SkStrokeRec::kStrokeAndFill_Style };
SkStrokeRec::Style style = styles[random->nextU() % 3];
SkScalar strokeWidth = -1.f;
SkPaint::Join join = SkPaint::kMiter_Join;
SkScalar miterLimit = 0.5f;
if (SkStrokeRec::kFill_Style != style) {
strokeWidth = random->nextRangeF(1.0f, 10.0f);
if (random->nextBool()) {
join = SkPaint::kMiter_Join;
} else {
join = SkPaint::kBevel_Join;
}
miterLimit = random->nextRangeF(0.5f, 2.0f);
}
const GrUserStencilSettings* stencilSettings = GrGetRandomStencil(random, context);
return AAFlatteningConvexPathOp::Make(std::move(paint), viewMatrix, path, strokeWidth, style,
join, miterLimit, stencilSettings);
}
#endif
|
/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrAALinearizingConvexPathRenderer.h"
#include "GrAAConvexTessellator.h"
#include "GrContext.h"
#include "GrDefaultGeoProcFactory.h"
#include "GrDrawOpTest.h"
#include "GrGeometryProcessor.h"
#include "GrOpFlushState.h"
#include "GrPathUtils.h"
#include "GrProcessor.h"
#include "GrStyle.h"
#include "SkGeometry.h"
#include "SkPathPriv.h"
#include "SkString.h"
#include "SkTraceEvent.h"
#include "glsl/GrGLSLGeometryProcessor.h"
#include "ops/GrMeshDrawOp.h"
#include "ops/GrSimpleMeshDrawOpHelper.h"
static const int DEFAULT_BUFFER_SIZE = 100;
// The thicker the stroke, the harder it is to produce high-quality results using tessellation. For
// the time being, we simply drop back to software rendering above this stroke width.
static const SkScalar kMaxStrokeWidth = 20.0;
GrAALinearizingConvexPathRenderer::GrAALinearizingConvexPathRenderer() {
}
///////////////////////////////////////////////////////////////////////////////
GrPathRenderer::CanDrawPath
GrAALinearizingConvexPathRenderer::onCanDrawPath(const CanDrawPathArgs& args) const {
if (GrAAType::kCoverage != args.fAAType) {
return CanDrawPath::kNo;
}
if (!args.fShape->knownToBeConvex()) {
return CanDrawPath::kNo;
}
if (args.fShape->style().pathEffect()) {
return CanDrawPath::kNo;
}
if (args.fShape->inverseFilled()) {
return CanDrawPath::kNo;
}
if (args.fShape->bounds().width() <= 0 && args.fShape->bounds().height() <= 0) {
// Stroked zero length lines should draw, but this PR doesn't handle that case
return CanDrawPath::kNo;
}
const SkStrokeRec& stroke = args.fShape->style().strokeRec();
if (stroke.getStyle() == SkStrokeRec::kStroke_Style ||
stroke.getStyle() == SkStrokeRec::kStrokeAndFill_Style) {
if (!args.fViewMatrix->isSimilarity()) {
return CanDrawPath::kNo;
}
SkScalar strokeWidth = args.fViewMatrix->getMaxScale() * stroke.getWidth();
if (strokeWidth < 1.0f && stroke.getStyle() == SkStrokeRec::kStroke_Style) {
return CanDrawPath::kNo;
}
if (strokeWidth > kMaxStrokeWidth ||
!args.fShape->knownToBeClosed() ||
stroke.getJoin() == SkPaint::Join::kRound_Join) {
return CanDrawPath::kNo;
}
return CanDrawPath::kYes;
}
if (stroke.getStyle() != SkStrokeRec::kFill_Style) {
return CanDrawPath::kNo;
}
return CanDrawPath::kYes;
}
// extract the result vertices and indices from the GrAAConvexTessellator
static void extract_verts(const GrAAConvexTessellator& tess,
void* vertices,
size_t vertexStride,
GrColor color,
uint16_t firstIndex,
uint16_t* idxs,
bool tweakAlphaForCoverage) {
intptr_t verts = reinterpret_cast<intptr_t>(vertices);
for (int i = 0; i < tess.numPts(); ++i) {
*((SkPoint*)((intptr_t)verts + i * vertexStride)) = tess.point(i);
}
// Make 'verts' point to the colors
verts += sizeof(SkPoint);
for (int i = 0; i < tess.numPts(); ++i) {
if (tweakAlphaForCoverage) {
SkASSERT(SkScalarRoundToInt(255.0f * tess.coverage(i)) <= 255);
unsigned scale = SkScalarRoundToInt(255.0f * tess.coverage(i));
GrColor scaledColor = (0xff == scale) ? color : SkAlphaMulQ(color, scale);
*reinterpret_cast<GrColor*>(verts + i * vertexStride) = scaledColor;
} else {
*reinterpret_cast<GrColor*>(verts + i * vertexStride) = color;
*reinterpret_cast<float*>(verts + i * vertexStride + sizeof(GrColor)) =
tess.coverage(i);
}
}
for (int i = 0; i < tess.numIndices(); ++i) {
idxs[i] = tess.index(i) + firstIndex;
}
}
static sk_sp<GrGeometryProcessor> create_lines_only_gp(bool tweakAlphaForCoverage,
const SkMatrix& viewMatrix,
bool usesLocalCoords) {
using namespace GrDefaultGeoProcFactory;
Coverage::Type coverageType;
if (tweakAlphaForCoverage) {
coverageType = Coverage::kSolid_Type;
} else {
coverageType = Coverage::kAttribute_Type;
}
LocalCoords::Type localCoordsType =
usesLocalCoords ? LocalCoords::kUsePosition_Type : LocalCoords::kUnused_Type;
return MakeForDeviceSpace(Color::kPremulGrColorAttribute_Type, coverageType, localCoordsType,
viewMatrix);
}
namespace {
class AAFlatteningConvexPathOp final : public GrMeshDrawOp {
private:
using Helper = GrSimpleMeshDrawOpHelperWithStencil;
public:
DEFINE_OP_CLASS_ID
static std::unique_ptr<GrDrawOp> Make(GrPaint&& paint,
const SkMatrix& viewMatrix,
const SkPath& path,
SkScalar strokeWidth,
SkStrokeRec::Style style,
SkPaint::Join join,
SkScalar miterLimit,
const GrUserStencilSettings* stencilSettings) {
return Helper::FactoryHelper<AAFlatteningConvexPathOp>(std::move(paint), viewMatrix, path,
strokeWidth, style, join, miterLimit,
stencilSettings);
}
AAFlatteningConvexPathOp(const Helper::MakeArgs& helperArgs,
GrColor color,
const SkMatrix& viewMatrix,
const SkPath& path,
SkScalar strokeWidth,
SkStrokeRec::Style style,
SkPaint::Join join,
SkScalar miterLimit,
const GrUserStencilSettings* stencilSettings)
: INHERITED(ClassID()), fHelper(helperArgs, GrAAType::kCoverage, stencilSettings) {
fPaths.emplace_back(
PathData{color, viewMatrix, path, strokeWidth, style, join, miterLimit});
// compute bounds
SkRect bounds = path.getBounds();
SkScalar w = strokeWidth;
if (w > 0) {
w /= 2;
// If the half stroke width is < 1 then we effectively fallback to bevel joins.
if (SkPaint::kMiter_Join == join && w > 1.f) {
w *= miterLimit;
}
bounds.outset(w, w);
}
this->setTransformedBounds(bounds, viewMatrix, HasAABloat::kYes, IsZeroArea::kNo);
}
const char* name() const override { return "AAFlatteningConvexPathOp"; }
void visitProxies(const VisitProxyFunc& func) const override {
fHelper.visitProxies(func);
}
SkString dumpInfo() const override {
SkString string;
for (const auto& path : fPaths) {
string.appendf(
"Color: 0x%08x, StrokeWidth: %.2f, Style: %d, Join: %d, "
"MiterLimit: %.2f\n",
path.fColor, path.fStrokeWidth, path.fStyle, path.fJoin, path.fMiterLimit);
}
string += fHelper.dumpInfo();
string += INHERITED::dumpInfo();
return string;
}
FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
RequiresDstTexture finalize(const GrCaps& caps, const GrAppliedClip* clip,
GrPixelConfigIsClamped dstIsClamped) override {
return fHelper.xpRequiresDstTexture(caps, clip, dstIsClamped,
GrProcessorAnalysisCoverage::kSingleChannel,
&fPaths.back().fColor);
}
private:
void draw(GrMeshDrawOp::Target* target, const GrGeometryProcessor* gp,
const GrPipeline* pipeline, int vertexCount, size_t vertexStride, void* vertices,
int indexCount, uint16_t* indices) const {
if (vertexCount == 0 || indexCount == 0) {
return;
}
const GrBuffer* vertexBuffer;
GrMesh mesh(GrPrimitiveType::kTriangles);
int firstVertex;
void* verts = target->makeVertexSpace(vertexStride, vertexCount, &vertexBuffer,
&firstVertex);
if (!verts) {
SkDebugf("Could not allocate vertices\n");
return;
}
memcpy(verts, vertices, vertexCount * vertexStride);
const GrBuffer* indexBuffer;
int firstIndex;
uint16_t* idxs = target->makeIndexSpace(indexCount, &indexBuffer, &firstIndex);
if (!idxs) {
SkDebugf("Could not allocate indices\n");
return;
}
memcpy(idxs, indices, indexCount * sizeof(uint16_t));
mesh.setIndexed(indexBuffer, indexCount, firstIndex, 0, vertexCount - 1);
mesh.setVertexData(vertexBuffer, firstVertex);
target->draw(gp, pipeline, mesh);
}
void onPrepareDraws(Target* target) override {
const GrPipeline* pipeline = fHelper.makePipeline(target);
// Setup GrGeometryProcessor
sk_sp<GrGeometryProcessor> gp(create_lines_only_gp(fHelper.compatibleWithAlphaAsCoverage(),
this->viewMatrix(),
fHelper.usesLocalCoords()));
if (!gp) {
SkDebugf("Couldn't create a GrGeometryProcessor\n");
return;
}
size_t vertexStride = gp->getVertexStride();
SkASSERT(fHelper.compatibleWithAlphaAsCoverage()
? vertexStride == sizeof(GrDefaultGeoProcFactory::PositionColorAttr)
: vertexStride ==
sizeof(GrDefaultGeoProcFactory::PositionColorCoverageAttr));
int instanceCount = fPaths.count();
int vertexCount = 0;
int indexCount = 0;
int maxVertices = DEFAULT_BUFFER_SIZE;
int maxIndices = DEFAULT_BUFFER_SIZE;
uint8_t* vertices = (uint8_t*) sk_malloc_throw(maxVertices * vertexStride);
uint16_t* indices = (uint16_t*) sk_malloc_throw(maxIndices * sizeof(uint16_t));
for (int i = 0; i < instanceCount; i++) {
const PathData& args = fPaths[i];
GrAAConvexTessellator tess(args.fStyle, args.fStrokeWidth,
args.fJoin, args.fMiterLimit);
if (!tess.tessellate(args.fViewMatrix, args.fPath)) {
continue;
}
int currentIndices = tess.numIndices();
if (indexCount + currentIndices > static_cast<int>(UINT16_MAX)) {
// if we added the current instance, we would overflow the indices we can store in a
// uint16_t. Draw what we've got so far and reset.
this->draw(target, gp.get(), pipeline, vertexCount, vertexStride, vertices,
indexCount, indices);
vertexCount = 0;
indexCount = 0;
}
int currentVertices = tess.numPts();
if (vertexCount + currentVertices > maxVertices) {
maxVertices = SkTMax(vertexCount + currentVertices, maxVertices * 2);
vertices = (uint8_t*) sk_realloc_throw(vertices, maxVertices * vertexStride);
}
if (indexCount + currentIndices > maxIndices) {
maxIndices = SkTMax(indexCount + currentIndices, maxIndices * 2);
indices = (uint16_t*) sk_realloc_throw(indices, maxIndices * sizeof(uint16_t));
}
extract_verts(tess, vertices + vertexStride * vertexCount, vertexStride, args.fColor,
vertexCount, indices + indexCount,
fHelper.compatibleWithAlphaAsCoverage());
vertexCount += currentVertices;
indexCount += currentIndices;
}
this->draw(target, gp.get(), pipeline, vertexCount, vertexStride, vertices, indexCount,
indices);
sk_free(vertices);
sk_free(indices);
}
bool onCombineIfPossible(GrOp* t, const GrCaps& caps) override {
AAFlatteningConvexPathOp* that = t->cast<AAFlatteningConvexPathOp>();
if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
return false;
}
fPaths.push_back_n(that->fPaths.count(), that->fPaths.begin());
this->joinBounds(*that);
return true;
}
const SkMatrix& viewMatrix() const { return fPaths[0].fViewMatrix; }
struct PathData {
GrColor fColor;
SkMatrix fViewMatrix;
SkPath fPath;
SkScalar fStrokeWidth;
SkStrokeRec::Style fStyle;
SkPaint::Join fJoin;
SkScalar fMiterLimit;
};
SkSTArray<1, PathData, true> fPaths;
Helper fHelper;
typedef GrMeshDrawOp INHERITED;
};
} // anonymous namespace
bool GrAALinearizingConvexPathRenderer::onDrawPath(const DrawPathArgs& args) {
GR_AUDIT_TRAIL_AUTO_FRAME(args.fRenderTargetContext->auditTrail(),
"GrAALinearizingConvexPathRenderer::onDrawPath");
SkASSERT(GrFSAAType::kUnifiedMSAA != args.fRenderTargetContext->fsaaType());
SkASSERT(!args.fShape->isEmpty());
SkASSERT(!args.fShape->style().pathEffect());
SkPath path;
args.fShape->asPath(&path);
bool fill = args.fShape->style().isSimpleFill();
const SkStrokeRec& stroke = args.fShape->style().strokeRec();
SkScalar strokeWidth = fill ? -1.0f : stroke.getWidth();
SkPaint::Join join = fill ? SkPaint::Join::kMiter_Join : stroke.getJoin();
SkScalar miterLimit = stroke.getMiter();
std::unique_ptr<GrDrawOp> op = AAFlatteningConvexPathOp::Make(
std::move(args.fPaint), *args.fViewMatrix, path, strokeWidth, stroke.getStyle(), join,
miterLimit, args.fUserStencilSettings);
args.fRenderTargetContext->addDrawOp(*args.fClip, std::move(op));
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#if GR_TEST_UTILS
GR_DRAW_OP_TEST_DEFINE(AAFlatteningConvexPathOp) {
SkMatrix viewMatrix = GrTest::TestMatrixPreservesRightAngles(random);
SkPath path = GrTest::TestPathConvex(random);
SkStrokeRec::Style styles[3] = { SkStrokeRec::kFill_Style,
SkStrokeRec::kStroke_Style,
SkStrokeRec::kStrokeAndFill_Style };
SkStrokeRec::Style style = styles[random->nextU() % 3];
SkScalar strokeWidth = -1.f;
SkPaint::Join join = SkPaint::kMiter_Join;
SkScalar miterLimit = 0.5f;
if (SkStrokeRec::kFill_Style != style) {
strokeWidth = random->nextRangeF(1.0f, 10.0f);
if (random->nextBool()) {
join = SkPaint::kMiter_Join;
} else {
join = SkPaint::kBevel_Join;
}
miterLimit = random->nextRangeF(0.5f, 2.0f);
}
const GrUserStencilSettings* stencilSettings = GrGetRandomStencil(random, context);
return AAFlatteningConvexPathOp::Make(std::move(paint), viewMatrix, path, strokeWidth, style,
join, miterLimit, stencilSettings);
}
#endif
|
Fix skia compilation error
|
Fix skia compilation error
UINT16_MAX is unsigned int. cast it to int before using it with other
int variables
Change-Id: I77d88a8d3011424a05ab54201c815ce38f9854ca
Reviewed-on: https://skia-review.googlesource.com/125805
Reviewed-by: Brian Osman <[email protected]>
Commit-Queue: Brian Osman <[email protected]>
|
C++
|
bsd-3-clause
|
Hikari-no-Tenshi/android_external_skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,HalCanary/skia-hc,rubenvb/skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,HalCanary/skia-hc,rubenvb/skia,google/skia,HalCanary/skia-hc,rubenvb/skia,google/skia,google/skia,HalCanary/skia-hc,rubenvb/skia,aosp-mirror/platform_external_skia,rubenvb/skia,rubenvb/skia,rubenvb/skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,google/skia,HalCanary/skia-hc,rubenvb/skia,google/skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,rubenvb/skia,google/skia,google/skia,Hikari-no-Tenshi/android_external_skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,Hikari-no-Tenshi/android_external_skia
|
006bd93c29fc1f4b92d87f771569c99c7412a50e
|
smbase/hashtbl.cc
|
smbase/hashtbl.cc
|
// hashtbl.cc see license.txt for copyright and terms of use
// code for hashtbl.h
#include "hashtbl.h" // this module
#include "xassert.h" // xassert
#include <string.h> // memset
unsigned HashTable::hashFunction(void const *key) const
{
return coreHashFn(key) % (unsigned)tableSize;
}
HashTable::HashTable(GetKeyFn gk, HashFn hf, EqualKeyFn ek, int initSize)
: getKey(gk),
coreHashFn(hf),
equalKeys(ek),
enableShrink(false)
{
makeTable(initSize);
}
HashTable::~HashTable()
{
delete[] hashTable;
}
void HashTable::makeTable(int size)
{
hashTable = new void*[size];
tableSize = size;
memset(hashTable, 0, sizeof(void*) * tableSize);
numEntries = 0;
}
int HashTable::getEntry(void const *key) const
{
int index = hashFunction(key);
int originalIndex = index;
for(;;) {
if (hashTable[index] == NULL) {
// unmapped
return index;
}
if (equalKeys(key, getKey(hashTable[index]))) {
// mapped here
return index;
}
// this entry is mapped, but not with this key, i.e.
// we have a collision -- so just go to the next entry,
// wrapping as necessary
index = nextIndex(index);
// detect infinite looping
xassert(index != originalIndex);
}
}
void *HashTable::get(void const *key) const
{
return hashTable[getEntry(key)];
}
void HashTable::resizeTable(int newSize)
{
// save old stuff
void **oldTable = hashTable;
int oldSize = tableSize;
int oldEntries = numEntries;
// make the new table
makeTable(newSize);
// move entries to the new table
for (int i=0; i<oldSize; i++) {
if (oldTable[i] != NULL) {
add(getKey(oldTable[i]), oldTable[i]);
oldEntries--;
}
}
xassert(oldEntries == 0);
// deallocate the old table
delete[] oldTable;
}
void HashTable::add(void const *key, void *value)
{
if (numEntries+1 > tableSize*2/3) {
// we're over the usage threshold; increase table size
resizeTable(tableSize * 2 + 1);
}
int index = getEntry(key);
xassert(hashTable[index] == NULL); // must not be a mapping yet
hashTable[index] = value;
numEntries++;
}
void *HashTable::remove(void const *key)
{
if (enableShrink &&
numEntries-1 < tableSize/5 &&
tableSize > defaultSize) {
// we're below threshold; reduce table size
resizeTable(tableSize / 2);
}
int index = getEntry(key);
xassert(hashTable[index] != NULL); // must be a mapping to remove
// remove this entry
void *retval = hashTable[index];
hashTable[index] = NULL;
numEntries--;
// now, if we ever inserted something and it collided with this one,
// leaving things like this would prevent us from finding that other
// mapping because the search stops as soon as a NULL entry is
// discovered; so we must examine all entries that could have
// collided, and re-insert them
int originalIndex = index;
for(;;) {
index = nextIndex(index);
xassert(index != originalIndex); // prevent infinite loops
if (hashTable[index] == NULL) {
// we've reached the end of the list of possible colliders
break;
}
// remove this one
void *data = hashTable[index];
hashTable[index] = NULL;
numEntries--;
// add it back
add(getKey(data), data);
}
return retval;
}
void HashTable::empty(int initSize)
{
delete[] hashTable;
makeTable(initSize);
}
void HashTable::selfCheck() const
{
int ct=0;
for (int i=0; i<tableSize; i++) {
if (hashTable[i] != NULL) {
checkEntry(i);
ct++;
}
}
xassert(ct == numEntries);
}
void HashTable::checkEntry(int entry) const
{
int index = getEntry(getKey(hashTable[entry]));
int originalIndex = index;
for(;;) {
if (index == entry) {
// the entry lives where it will be found, so that's good
return;
}
if (hashTable[index] == NULL) {
// the search for this entry would stop before finding it,
// so that's bad!
xfailure("checkEntry: entry in wrong slot");
}
// collision; keep looking
index = nextIndex(index);
xassert(index != originalIndex);
}
}
// ------------------ HashTableIter --------------------
HashTableIter::HashTableIter(HashTable &t)
: table(t)
{
index = 0;
moveToSth();
}
void HashTableIter::adv()
{
xassert(!isDone());
// move off the current item
index++;
// keep moving until we find something
moveToSth();
}
void HashTableIter::moveToSth()
{
while (index < table.tableSize &&
table.hashTable[index] == NULL) {
index++;
}
if (index == table.tableSize) {
index = -1; // mark as done
}
}
void *HashTableIter::data() const
{
xassert(!isDone());
return table.hashTable[index];
}
STATICDEF void const *HashTable::identityKeyFn(void *data)
{
return data;
}
unsigned lcprngTwoSteps(unsigned v)
{
// this is the core of the LC PRNG in one of the many libcs
// running around the net
v = (v * 1103515245) + 12345;
// do it again for good measure
v = (v * 1103515245) + 12345;
return v;
}
STATICDEF unsigned HashTable::lcprngHashFn(void const *key)
{
return lcprngTwoSteps((unsigned)pointerToInteger(key));
}
STATICDEF bool HashTable::
pointerEqualKeyFn(void const *key1, void const *key2)
{
return key1 == key2;
}
|
// hashtbl.cc see license.txt for copyright and terms of use
// code for hashtbl.h
#include "hashtbl.h" // this module
#include "xassert.h" // xassert
#include <string.h> // memset
unsigned HashTable::hashFunction(void const *key) const
{
return coreHashFn(key) % (unsigned)tableSize;
}
HashTable::HashTable(GetKeyFn gk, HashFn hf, EqualKeyFn ek, int initSize)
: getKey(gk),
coreHashFn(hf),
equalKeys(ek),
enableShrink(true)
{
makeTable(initSize);
}
HashTable::~HashTable()
{
delete[] hashTable;
}
void HashTable::makeTable(int size)
{
hashTable = new void*[size];
tableSize = size;
memset(hashTable, 0, sizeof(void*) * tableSize);
numEntries = 0;
}
int HashTable::getEntry(void const *key) const
{
int index = hashFunction(key);
int originalIndex = index;
for(;;) {
if (hashTable[index] == NULL) {
// unmapped
return index;
}
if (equalKeys(key, getKey(hashTable[index]))) {
// mapped here
return index;
}
// this entry is mapped, but not with this key, i.e.
// we have a collision -- so just go to the next entry,
// wrapping as necessary
index = nextIndex(index);
// detect infinite looping
xassert(index != originalIndex);
}
}
void *HashTable::get(void const *key) const
{
return hashTable[getEntry(key)];
}
void HashTable::resizeTable(int newSize)
{
// save old stuff
void **oldTable = hashTable;
int oldSize = tableSize;
int oldEntries = numEntries;
// make the new table
makeTable(newSize);
// move entries to the new table
for (int i=0; i<oldSize; i++) {
if (oldTable[i] != NULL) {
add(getKey(oldTable[i]), oldTable[i]);
oldEntries--;
}
}
xassert(oldEntries == 0);
// deallocate the old table
delete[] oldTable;
}
void HashTable::add(void const *key, void *value)
{
if (numEntries+1 > tableSize*2/3) {
// we're over the usage threshold; increase table size
resizeTable(tableSize * 2 + 1);
}
int index = getEntry(key);
xassert(hashTable[index] == NULL); // must not be a mapping yet
hashTable[index] = value;
numEntries++;
}
void *HashTable::remove(void const *key)
{
if (enableShrink &&
numEntries-1 < tableSize/5 &&
tableSize > defaultSize) {
// we're below threshold; reduce table size
resizeTable(tableSize / 2);
}
int index = getEntry(key);
xassert(hashTable[index] != NULL); // must be a mapping to remove
// remove this entry
void *retval = hashTable[index];
hashTable[index] = NULL;
numEntries--;
// now, if we ever inserted something and it collided with this one,
// leaving things like this would prevent us from finding that other
// mapping because the search stops as soon as a NULL entry is
// discovered; so we must examine all entries that could have
// collided, and re-insert them
int originalIndex = index;
for(;;) {
index = nextIndex(index);
xassert(index != originalIndex); // prevent infinite loops
if (hashTable[index] == NULL) {
// we've reached the end of the list of possible colliders
break;
}
// remove this one
void *data = hashTable[index];
hashTable[index] = NULL;
numEntries--;
// add it back
add(getKey(data), data);
}
return retval;
}
void HashTable::empty(int initSize)
{
delete[] hashTable;
makeTable(initSize);
}
void HashTable::selfCheck() const
{
int ct=0;
for (int i=0; i<tableSize; i++) {
if (hashTable[i] != NULL) {
checkEntry(i);
ct++;
}
}
xassert(ct == numEntries);
}
void HashTable::checkEntry(int entry) const
{
int index = getEntry(getKey(hashTable[entry]));
int originalIndex = index;
for(;;) {
if (index == entry) {
// the entry lives where it will be found, so that's good
return;
}
if (hashTable[index] == NULL) {
// the search for this entry would stop before finding it,
// so that's bad!
xfailure("checkEntry: entry in wrong slot");
}
// collision; keep looking
index = nextIndex(index);
xassert(index != originalIndex);
}
}
// ------------------ HashTableIter --------------------
HashTableIter::HashTableIter(HashTable &t)
: table(t)
{
index = 0;
moveToSth();
}
void HashTableIter::adv()
{
xassert(!isDone());
// move off the current item
index++;
// keep moving until we find something
moveToSth();
}
void HashTableIter::moveToSth()
{
while (index < table.tableSize &&
table.hashTable[index] == NULL) {
index++;
}
if (index == table.tableSize) {
index = -1; // mark as done
}
}
void *HashTableIter::data() const
{
xassert(!isDone());
return table.hashTable[index];
}
STATICDEF void const *HashTable::identityKeyFn(void *data)
{
return data;
}
unsigned lcprngTwoSteps(unsigned v)
{
// this is the core of the LC PRNG in one of the many libcs
// running around the net
v = (v * 1103515245) + 12345;
// do it again for good measure
v = (v * 1103515245) + 12345;
return v;
}
STATICDEF unsigned HashTable::lcprngHashFn(void const *key)
{
return lcprngTwoSteps((unsigned)pointerToInteger(key));
}
STATICDEF bool HashTable::
pointerEqualKeyFn(void const *key1, void const *key2)
{
return key1 == key2;
}
|
Change default enableShrink to true, as documented.
|
Change default enableShrink to true, as documented.
|
C++
|
bsd-3-clause
|
angavrilov/olmar,angavrilov/olmar,angavrilov/olmar,angavrilov/olmar
|
46ec4ff093f176d51af7dbb0723a2ae5ef28a6ba
|
vm/os-windows-nt.cpp
|
vm/os-windows-nt.cpp
|
#include "master.hpp"
namespace factor
{
THREADHANDLE start_thread(void *(*start_routine)(void *), void *args)
{
return (void *)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)start_routine, args, 0, 0);
}
DWORD dwTlsIndex;
void init_platform_globals()
{
if ((dwTlsIndex = TlsAlloc()) == TLS_OUT_OF_INDEXES)
fatal_error("TlsAlloc failed - out of indexes",0);
}
void register_vm_with_thread(factor_vm *vm)
{
if (! TlsSetValue(dwTlsIndex, vm))
fatal_error("TlsSetValue failed",0);
}
factor_vm *current_vm()
{
factor_vm *vm = (factor_vm *)TlsGetValue(dwTlsIndex);
assert(vm != NULL);
return vm;
}
u64 system_micros()
{
FILETIME t;
GetSystemTimeAsFileTime(&t);
return (((u64)t.dwLowDateTime | (u64)t.dwHighDateTime<<32)
- EPOCH_OFFSET) / 10;
}
u64 nano_count()
{
LARGE_INTEGER count;
LARGE_INTEGER frequency;
static u32 hi = 0;
static u32 lo = 0;
BOOL ret;
ret = QueryPerformanceCounter(&count);
if(ret == 0)
fatal_error("QueryPerformanceCounter", 0);
ret = QueryPerformanceFrequency(&frequency);
if(ret == 0)
fatal_error("QueryPerformanceFrequency", 0);
#ifdef FACTOR_64
hi = count.HighPart;
#else
/* On VirtualBox, QueryPerformanceCounter does not increment
the high part every time the low part overflows. Workaround. */
if(lo > count.LowPart)
hi++;
#endif
lo = count.LowPart;
return (u64)((((u64)hi << 32) | (u64)lo)*(1000000000.0/frequency.QuadPart));
}
void sleep_nanos(u64 nsec)
{
Sleep((DWORD)(nsec/1000000));
}
LONG factor_vm::exception_handler(PEXCEPTION_POINTERS pe)
{
PEXCEPTION_RECORD e = (PEXCEPTION_RECORD)pe->ExceptionRecord;
CONTEXT *c = (CONTEXT*)pe->ContextRecord;
c->ESP = (cell)fix_callstack_top((stack_frame *)c->ESP);
if(in_code_heap_p(c->EIP))
signal_callstack_top = (stack_frame *)c->ESP;
else
signal_callstack_top = NULL;
switch (e->ExceptionCode)
{
case EXCEPTION_ACCESS_VIOLATION:
signal_fault_addr = e->ExceptionInformation[1];
c->EIP = (cell)factor::memory_signal_handler_impl;
break;
case STATUS_FLOAT_DENORMAL_OPERAND:
case STATUS_FLOAT_DIVIDE_BY_ZERO:
case STATUS_FLOAT_INEXACT_RESULT:
case STATUS_FLOAT_INVALID_OPERATION:
case STATUS_FLOAT_OVERFLOW:
case STATUS_FLOAT_STACK_CHECK:
case STATUS_FLOAT_UNDERFLOW:
case STATUS_FLOAT_MULTIPLE_FAULTS:
case STATUS_FLOAT_MULTIPLE_TRAPS:
#ifdef FACTOR_64
signal_fpu_status = fpu_status(MXCSR(c));
#else
signal_fpu_status = fpu_status(X87SW(c) | MXCSR(c));
X87SW(c) = 0;
#endif
MXCSR(c) &= 0xffffffc0;
c->EIP = (cell)factor::fp_signal_handler_impl;
break;
case 0x40010006:
/* If the Widcomm bluetooth stack is installed, the BTTray.exe
process injects code into running programs. For some reason this
results in random SEH exceptions with this (undocumented)
exception code being raised. The workaround seems to be ignoring
this altogether, since that is what happens if SEH is not
enabled. Don't really have any idea what this exception means. */
break;
default:
signal_number = e->ExceptionCode;
c->EIP = (cell)factor::misc_signal_handler_impl;
break;
}
return EXCEPTION_CONTINUE_EXECUTION;
}
FACTOR_STDCALL(LONG) exception_handler(PEXCEPTION_POINTERS pe)
{
return current_vm()->exception_handler(pe);
}
void factor_vm::c_to_factor_toplevel(cell quot)
{
if(!AddVectoredExceptionHandler(0, (PVECTORED_EXCEPTION_HANDLER)factor::exception_handler))
fatal_error("AddVectoredExceptionHandler failed", 0);
c_to_factor(quot);
RemoveVectoredExceptionHandler((void *)factor::exception_handler);
}
void factor_vm::open_console()
{
}
}
|
#include "master.hpp"
namespace factor
{
THREADHANDLE start_thread(void *(*start_routine)(void *), void *args)
{
return (void *)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)start_routine, args, 0, 0);
}
DWORD dwTlsIndex;
void init_platform_globals()
{
if ((dwTlsIndex = TlsAlloc()) == TLS_OUT_OF_INDEXES)
fatal_error("TlsAlloc failed - out of indexes",0);
}
void register_vm_with_thread(factor_vm *vm)
{
if (! TlsSetValue(dwTlsIndex, vm))
fatal_error("TlsSetValue failed",0);
}
factor_vm *current_vm()
{
factor_vm *vm = (factor_vm *)TlsGetValue(dwTlsIndex);
assert(vm != NULL);
return vm;
}
u64 system_micros()
{
FILETIME t;
GetSystemTimeAsFileTime(&t);
return (((u64)t.dwLowDateTime | (u64)t.dwHighDateTime<<32)
- EPOCH_OFFSET) / 10;
}
u64 nano_count()
{
LARGE_INTEGER count;
LARGE_INTEGER frequency;
static u32 hi = 0;
static u32 lo = 0;
BOOL ret;
ret = QueryPerformanceCounter(&count);
if(ret == 0)
fatal_error("QueryPerformanceCounter", 0);
ret = QueryPerformanceFrequency(&frequency);
if(ret == 0)
fatal_error("QueryPerformanceFrequency", 0);
#ifdef FACTOR_64
hi = count.HighPart;
#else
/* On VirtualBox, QueryPerformanceCounter does not increment
the high part every time the low part overflows. Workaround. */
if(lo > count.LowPart)
hi++;
#endif
lo = count.LowPart;
return (u64)((((u64)hi << 32) | (u64)lo)*(1000000000.0/frequency.QuadPart));
}
void sleep_nanos(u64 nsec)
{
Sleep((DWORD)(nsec/1000000));
}
LONG factor_vm::exception_handler(PEXCEPTION_POINTERS pe)
{
PEXCEPTION_RECORD e = (PEXCEPTION_RECORD)pe->ExceptionRecord;
CONTEXT *c = (CONTEXT*)pe->ContextRecord;
c->ESP = (cell)fix_callstack_top((stack_frame *)c->ESP);
signal_callstack_top = (stack_frame *)c->ESP;
switch (e->ExceptionCode)
{
case EXCEPTION_ACCESS_VIOLATION:
signal_fault_addr = e->ExceptionInformation[1];
c->EIP = (cell)factor::memory_signal_handler_impl;
break;
case STATUS_FLOAT_DENORMAL_OPERAND:
case STATUS_FLOAT_DIVIDE_BY_ZERO:
case STATUS_FLOAT_INEXACT_RESULT:
case STATUS_FLOAT_INVALID_OPERATION:
case STATUS_FLOAT_OVERFLOW:
case STATUS_FLOAT_STACK_CHECK:
case STATUS_FLOAT_UNDERFLOW:
case STATUS_FLOAT_MULTIPLE_FAULTS:
case STATUS_FLOAT_MULTIPLE_TRAPS:
#ifdef FACTOR_64
signal_fpu_status = fpu_status(MXCSR(c));
#else
signal_fpu_status = fpu_status(X87SW(c) | MXCSR(c));
X87SW(c) = 0;
#endif
MXCSR(c) &= 0xffffffc0;
c->EIP = (cell)factor::fp_signal_handler_impl;
break;
case 0x40010006:
/* If the Widcomm bluetooth stack is installed, the BTTray.exe
process injects code into running programs. For some reason this
results in random SEH exceptions with this (undocumented)
exception code being raised. The workaround seems to be ignoring
this altogether, since that is what happens if SEH is not
enabled. Don't really have any idea what this exception means. */
break;
default:
signal_number = e->ExceptionCode;
c->EIP = (cell)factor::misc_signal_handler_impl;
break;
}
return EXCEPTION_CONTINUE_EXECUTION;
}
FACTOR_STDCALL(LONG) exception_handler(PEXCEPTION_POINTERS pe)
{
return current_vm()->exception_handler(pe);
}
void factor_vm::c_to_factor_toplevel(cell quot)
{
if(!AddVectoredExceptionHandler(0, (PVECTORED_EXCEPTION_HANDLER)factor::exception_handler))
fatal_error("AddVectoredExceptionHandler failed", 0);
c_to_factor(quot);
RemoveVectoredExceptionHandler((void *)factor::exception_handler);
}
void factor_vm::open_console()
{
}
}
|
fix SEH on Windows
|
vm: fix SEH on Windows
|
C++
|
bsd-2-clause
|
factor/factor,dch/factor,bpollack/factor,tgunr/factor,sarvex/factor-lang,mrjbq7/factor,nicolas-p/factor,slavapestov/factor,factor/factor,tgunr/factor,tgunr/factor,mrjbq7/factor,mrjbq7/factor,tgunr/factor,factor/factor,nicolas-p/factor,dch/factor,bjourne/factor,slavapestov/factor,sarvex/factor-lang,mrjbq7/factor,nicolas-p/factor,AlexIljin/factor,nicolas-p/factor,bjourne/factor,bpollack/factor,slavapestov/factor,bjourne/factor,bjourne/factor,mrjbq7/factor,nicolas-p/factor,mrjbq7/factor,factor/factor,tgunr/factor,AlexIljin/factor,tgunr/factor,AlexIljin/factor,dch/factor,dch/factor,slavapestov/factor,bjourne/factor,slavapestov/factor,sarvex/factor-lang,nicolas-p/factor,bjourne/factor,bjourne/factor,dch/factor,sarvex/factor-lang,bpollack/factor,bpollack/factor,AlexIljin/factor,nicolas-p/factor,sarvex/factor-lang,AlexIljin/factor,sarvex/factor-lang,dch/factor,AlexIljin/factor,bpollack/factor,slavapestov/factor,slavapestov/factor,sarvex/factor-lang,AlexIljin/factor,factor/factor,factor/factor,bpollack/factor,bpollack/factor
|
e42d98e7c6979246561b025e9237b24ad24f81b6
|
software/main.cpp
|
software/main.cpp
|
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include "xil_cache.h"
#include "SparseMatrix.h"
#include "SoftwareSpMV.h"
#include "malloc_aligned.h"
using namespace std;
unsigned int matrixMetaBase = 0x08000100;
unsigned int accBase = 0x40000000;
unsigned int resBase = 0x43c00000;
// use compile-time defines to decide which type of HW SpMV to use
#if defined(HWSPMV_BUFFERALL)
#include "HardwareSpMV.h"
#define HWSPMV HardwareSPMV
#elif defined(HWSPMV_BUFFERNONE)
#include "HardwareSpMVBufferNone.h"
#define HWSPMV HardwareSpMVBufferNone
#endif
int main(int argc, char *argv[]) {
Xil_DCacheDisable();
cout << "SpMVAccel-BufferAll" << endl;
cout << "=====================================" << endl;
SparseMatrix * A = SparseMatrix::fromMemory(matrixMetaBase);
A->printSummary();
SpMVData *x = (SpMVData *) malloc_aligned(64, sizeof(SpMVData)*A->getCols());
SpMVData *y = (SpMVData *) malloc_aligned(64, sizeof(SpMVData)*A->getRows());
for(SpMVIndex i = 0; i < A->getCols(); i++) { x[i] = (SpMVData) 1; }
for(SpMVIndex i = 0; i < A->getRows(); i++) { y[i] = (SpMVData) 0; }
SpMV * spmv = new HWSPMV(accBase, resBase, A, x, y);
SoftwareSpMV check(A);
spmv->exec();
check.exec();
SpMVData * goldenY = check.getY();
int res = memcmp(goldenY, y, sizeof(SpMVData)*A->getRows());
cout << "Memcmp result = " << res << endl;
cout << "Exiting..." << endl;
return 0;
}
|
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include "xil_cache.h"
#include "SparseMatrix.h"
#include "SoftwareSpMV.h"
#include "malloc_aligned.h"
using namespace std;
unsigned int matrixMetaBase = 0x08000100;
unsigned int accBase = 0x40000000;
unsigned int resBase = 0x43c00000;
// use compile-time defines to decide which type of HW SpMV to use
#if defined(HWSPMV_BUFFERALL)
#include "HardwareSpMV.h"
#define HWSPMV HardwareSPMV
static const char * hwSpMVIDString = "BufferAll";
#elif defined(HWSPMV_BUFFERNONE)
#include "HardwareSpMVBufferNone.h"
#define HWSPMV HardwareSpMVBufferNone
static const char * hwSpMVIDString = "BufferNone";
#endif
int main(int argc, char *argv[]) {
Xil_DCacheDisable();
cout << "SpMVAccel-" << hwSpMVIDString << endl;
cout << "=====================================" << endl;
SparseMatrix * A = SparseMatrix::fromMemory(matrixMetaBase);
A->printSummary();
SpMVData *x = (SpMVData *) malloc_aligned(64, sizeof(SpMVData)*A->getCols());
SpMVData *y = (SpMVData *) malloc_aligned(64, sizeof(SpMVData)*A->getRows());
for(SpMVIndex i = 0; i < A->getCols(); i++) { x[i] = (SpMVData) 1; }
for(SpMVIndex i = 0; i < A->getRows(); i++) { y[i] = (SpMVData) 0; }
SpMV * spmv = new HWSPMV(accBase, resBase, A, x, y);
SoftwareSpMV check(A);
spmv->exec();
check.exec();
SpMVData * goldenY = check.getY();
int res = memcmp(goldenY, y, sizeof(SpMVData)*A->getRows());
cout << "Memcmp result = " << res << endl;
cout << "Exiting..." << endl;
return 0;
}
|
add HW SpMV type identifier string
|
add HW SpMV type identifier string
|
C++
|
bsd-3-clause
|
maltanar/spmv-vector-cache,maltanar/spmv-vector-cache,maltanar/spmv-vector-cache,maltanar/spmv-vector-cache
|
13593fff1614e4f925a5d1e8a07c5f1673a2d6be
|
include/depthai-shared/properties/FeatureTrackerProperties.hpp
|
include/depthai-shared/properties/FeatureTrackerProperties.hpp
|
#pragma once
#include <depthai-shared/common/optional.hpp>
#include <depthai-shared/datatype/RawFeatureTrackerConfig.hpp>
#include <nlohmann/json.hpp>
#include <vector>
namespace dai {
/**
* Specify properties for FeatureTracker
*/
struct FeatureTrackerProperties {
RawFeatureTrackerConfig initialConfig;
/// Whether to wait for config at 'inputConfig' IO
bool inputConfigSync = false;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(FeatureTrackerProperties, initialConfig, inputConfigSync);
} // namespace dai
|
#pragma once
#include <depthai-shared/common/optional.hpp>
#include <depthai-shared/datatype/RawFeatureTrackerConfig.hpp>
#include <nlohmann/json.hpp>
#include <vector>
namespace dai {
/**
* Specify properties for FeatureTracker
*/
struct FeatureTrackerProperties {
/// Initial feature tracker config
RawFeatureTrackerConfig initialConfig;
/// Whether to wait for config at 'inputConfig' IO
bool inputConfigSync = false;
/**
* Number of shaves reserved for feature tracking.
* Optical flow can use 1 or 2 shaves, while for corner detection only 1 is enough.
* Maximum 2, minimum 1.
*/
std::int32_t numShaves = 1;
/**
* Number of memory slices reserved for feature tracking.
* Optical flow can use 1 or 2 memory slices, while for corner detection only 1 is enough.
* Maximum number of features depends on the number of allocated memory slices.
* Maximum 2, minimum 1.
*/
std::int32_t numMemorySlices = 1;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(FeatureTrackerProperties, initialConfig, inputConfigSync, numShaves, numMemorySlices);
} // namespace dai
|
Add configurable shave/cmx slices
|
Add configurable shave/cmx slices
|
C++
|
mit
|
luxonis/depthai-shared
|
55fea4785843f945e523bc6cb142042d398515d4
|
source/Camera.cpp
|
source/Camera.cpp
|
#include <cassert>
#include "Camera.h"
Camera::Camera(
const QVector3D & eye
, const QVector3D & center
, const QVector3D & up)
: m_dirty(false)
, m_eye(eye)
, m_center(center)
, m_up(up)
, m_fovy(40.f)
, m_aspect(1.f)
, m_zNear(0.1f)
, m_zFar(1024.f)
{
}
Camera::~Camera()
{
}
void Camera::invalidateMatrices()
{
m_view.invalidate();
m_viewInverted.invalidate();
m_projection.invalidate();
m_projectionInverted.invalidate();
m_viewProjection.invalidate();
m_viewProjectionInverted.invalidate();
}
void Camera::dirty(bool update)
{
m_dirty = true;
if (update)
this->update();
}
const QVector3D & Camera::eye() const
{
return m_eye;
}
void Camera::setEye(const QVector3D & eye)
{
if (eye == m_eye)
return;
m_eye = eye;
dirty();
}
const QVector3D & Camera::center() const
{
return m_center;
}
void Camera::setCenter(const QVector3D & center)
{
if (center == m_center)
return;
m_center = center;
dirty();
}
const QVector3D & Camera::up() const
{
return m_up;
}
void Camera::setUp(const QVector3D & up)
{
if (up == m_up)
return;
m_up = up;
dirty();
}
const float Camera::zNear() const
{
return m_zNear;
}
void Camera::setZNear(const float zNear)
{
if (zNear == m_zNear)
return;
m_zNear = zNear;
assert(m_zNear > 0.0);
dirty();
}
const float Camera::zFar() const
{
return m_zFar;
}
void Camera::setZFar(const float zFar)
{
if (zFar == m_zFar)
return;
m_zFar = zFar;
assert(m_zFar > m_zNear);
dirty();
}
const float Camera::fovy() const
{
return m_fovy;
}
void Camera::setFovy(const float fovy)
{
if (fovy == m_fovy)
return;
m_fovy = fovy;
assert(m_fovy > 0.0);
dirty();
}
const QSize & Camera::viewport() const
{
return m_viewport;
}
void Camera::setViewport(const QSize & viewport)
{
if (viewport == m_viewport)
return;
m_aspect = viewport.width() / qMax<float>(static_cast<float>(viewport.height()), 1.f);
m_viewport = viewport;
dirty();
}
void Camera::update()
{
if (!m_dirty)
return;
invalidateMatrices();
m_dirty = false;
emit(changed());
}
const QMatrix4x4 & Camera::view()
{
if (m_dirty)
update();
if (!m_view.isValid())
{
m_view.value().setToIdentity();
m_view.value().lookAt(m_eye, m_center, m_up);
m_view.validate();
}
return m_view.value();
}
const QMatrix4x4 & Camera::projection()
{
if (m_dirty)
update();
if (!m_projection.isValid())
{
m_projection.value().setToIdentity();
m_projection.value().perspective(m_fovy, m_aspect, m_zNear, m_zFar);
m_projection.validate();
}
return m_projection.value();
}
const QMatrix4x4 & Camera::viewProjection()
{
if (m_dirty)
update();
if (!m_viewProjection.isValid())
m_viewProjection.setValue(projection() * view());
return m_viewProjection.value();
}
const QMatrix4x4 & Camera::viewInverted()
{
if (m_dirty)
update();
if (!m_viewInverted.isValid())
m_viewInverted.setValue(QMatrix4x4(view().inverted()));
return m_viewInverted.value();
}
const QMatrix4x4 & Camera::projectionInverted()
{
if (m_dirty)
update();
if (!m_projectionInverted.isValid())
m_projectionInverted.setValue(QMatrix4x4(projection().inverted()));
return m_projectionInverted.value();
}
const QMatrix4x4 & Camera::viewProjectionInverted()
{
if (m_dirty)
update();
if (!m_viewProjectionInverted.isValid())
m_viewProjectionInverted.setValue(QMatrix4x4(viewProjection().inverted()));
return m_viewProjectionInverted.value();
}
|
#include <cassert>
#include "Camera.h"
Camera::Camera(
const QVector3D & eye
, const QVector3D & center
, const QVector3D & up)
: m_dirty(false)
, m_eye(eye)
, m_center(center)
, m_up(up)
, m_fovy(40.f)
, m_aspect(1.f)
, m_zNear(0.1f)
, m_zFar(64.0f)
{
}
Camera::~Camera()
{
}
void Camera::invalidateMatrices()
{
m_view.invalidate();
m_viewInverted.invalidate();
m_projection.invalidate();
m_projectionInverted.invalidate();
m_viewProjection.invalidate();
m_viewProjectionInverted.invalidate();
}
void Camera::dirty(bool update)
{
m_dirty = true;
if (update)
this->update();
}
const QVector3D & Camera::eye() const
{
return m_eye;
}
void Camera::setEye(const QVector3D & eye)
{
if (eye == m_eye)
return;
m_eye = eye;
dirty();
}
const QVector3D & Camera::center() const
{
return m_center;
}
void Camera::setCenter(const QVector3D & center)
{
if (center == m_center)
return;
m_center = center;
dirty();
}
const QVector3D & Camera::up() const
{
return m_up;
}
void Camera::setUp(const QVector3D & up)
{
if (up == m_up)
return;
m_up = up;
dirty();
}
const float Camera::zNear() const
{
return m_zNear;
}
void Camera::setZNear(const float zNear)
{
if (zNear == m_zNear)
return;
m_zNear = zNear;
assert(m_zNear > 0.0);
dirty();
}
const float Camera::zFar() const
{
return m_zFar;
}
void Camera::setZFar(const float zFar)
{
if (zFar == m_zFar)
return;
m_zFar = zFar;
assert(m_zFar > m_zNear);
dirty();
}
const float Camera::fovy() const
{
return m_fovy;
}
void Camera::setFovy(const float fovy)
{
if (fovy == m_fovy)
return;
m_fovy = fovy;
assert(m_fovy > 0.0);
dirty();
}
const QSize & Camera::viewport() const
{
return m_viewport;
}
void Camera::setViewport(const QSize & viewport)
{
if (viewport == m_viewport)
return;
m_aspect = viewport.width() / qMax<float>(static_cast<float>(viewport.height()), 1.f);
m_viewport = viewport;
dirty();
}
void Camera::update()
{
if (!m_dirty)
return;
invalidateMatrices();
m_dirty = false;
emit(changed());
}
const QMatrix4x4 & Camera::view()
{
if (m_dirty)
update();
if (!m_view.isValid())
{
m_view.value().setToIdentity();
m_view.value().lookAt(m_eye, m_center, m_up);
m_view.validate();
}
return m_view.value();
}
const QMatrix4x4 & Camera::projection()
{
if (m_dirty)
update();
if (!m_projection.isValid())
{
m_projection.value().setToIdentity();
m_projection.value().perspective(m_fovy, m_aspect, m_zNear, m_zFar);
m_projection.validate();
}
return m_projection.value();
}
const QMatrix4x4 & Camera::viewProjection()
{
if (m_dirty)
update();
if (!m_viewProjection.isValid())
m_viewProjection.setValue(projection() * view());
return m_viewProjection.value();
}
const QMatrix4x4 & Camera::viewInverted()
{
if (m_dirty)
update();
if (!m_viewInverted.isValid())
m_viewInverted.setValue(QMatrix4x4(view().inverted()));
return m_viewInverted.value();
}
const QMatrix4x4 & Camera::projectionInverted()
{
if (m_dirty)
update();
if (!m_projectionInverted.isValid())
m_projectionInverted.setValue(QMatrix4x4(projection().inverted()));
return m_projectionInverted.value();
}
const QMatrix4x4 & Camera::viewProjectionInverted()
{
if (m_dirty)
update();
if (!m_viewProjectionInverted.isValid())
m_viewProjectionInverted.setValue(QMatrix4x4(viewProjection().inverted()));
return m_viewProjectionInverted.value();
}
|
adjust default far plane
|
adjust default far plane
|
C++
|
mit
|
lanice/cg2sandbox,stephde/CG2Uebung,stiXits/demo_ter,hpicgs/cg2sandbox,stiXits/demo_ray,stephde/CG2Uebung,stiXits/demo_ray,stiXits/demo_lod,stiXits/demo_lod,stiXits/demo_ray,stiXits/demo_ter,stiXits/demo_ter,stiXits/demo_lod,stephde/CG2Uebung,lanice/cg2sandbox,hpicgs/cg2sandbox,lanice/cg2sandbox
|
b5f17b7db737adfcdbe93a7f9615e88bf384e992
|
Engine/Src/Ancona/Framework/EntityFramework/SystemManager.cpp
|
Engine/Src/Ancona/Framework/EntityFramework/SystemManager.cpp
|
#include <map>
#include <unordered_map>
#include <Ancona/Framework/EntityFramework/AbstractSystem.hpp>
#include <Ancona/Framework/EntityFramework/SystemManager.hpp>
#include <Ancona/Framework/Serializing/Serializing.hpp>
#include <Ancona/Util/Algorithm.hpp>
using namespace ild;
SystemManager::SystemManager()
{
_maxEntityId = 0;
}
void SystemManager::Update(float delta, UpdateStepEnum updateStep)
{
FetchWaitingDependencies();
for(auto & system : _systems[updateStep])
{
system->Update(delta);
system->DeleteQueuedComponents();
}
DeleteQueuedEntities();
}
void SystemManager::DeleteEntity(Entity entity)
{
Assert(_components.find(entity) != _components.end(),
"Cannot delete an entity that is not managed by the system manager");
for(AbstractSystem * system : _components.at(entity))
{
system->EntityIsDeleted(entity);
}
auto reverseIter = _entitiesReverse.find(entity);
if(reverseIter != _entitiesReverse.end())
{
_entities.erase(reverseIter->second);
_entitiesReverse.erase(reverseIter);
}
_components.erase(entity);
}
void SystemManager::QueueDeleteEntity(Entity entity)
{
_deleteQueue.push_back(entity);
}
Entity SystemManager::CreateEntity()
{
Assert(_maxEntityId != ~0u, "Entity key has overflown");
Entity entity = _maxEntityId++;
//Create a structure for the entity
_components[entity];
return entity;
}
Entity SystemManager::CreateEntity(const std::string & key)
{
Assert(_entities.find(key) == _entities.end(), "Cannot use the same key for two entities.");
Entity entity = CreateEntity();
_entities[key] = entity;
_entitiesReverse[entity] = key;
return entity;
}
Entity SystemManager::GetEntity(const std::string & key)
{
auto entityIter = _entities.find(key);
if(entityIter == _entities.end())
{
return nullentity;
}
return entityIter->second;
}
bool SystemManager::ContainsName(std::string & systemName)
{
return alg::any_of(_keyedSystems,
[=](std::pair<std::string, AbstractSystem *> & nameSystemPair)
{
return nameSystemPair.first == systemName;
});
}
void SystemManager::RegisterSystem(
std::string systemName,
AbstractSystem * system,
UpdateStepEnum updateStep)
{
auto & systems = _systems[updateStep];
Assert(!alg::count_if(systems,[system](std::unique_ptr<AbstractSystem> & ptr)
{
return ptr.get() == system;
}
), "A System Manager cannot contain the same system twice");
systems.emplace_back(system);
if(systemName != "")
{
Assert(!ContainsName(systemName), "System name must be unique.");
_keyedSystems.emplace_back(systemName, system);
}
}
void SystemManager::RegisterComponent(Entity entity, AbstractSystem * owningSystem)
{
Assert(_components.find(entity) != _components.end(),
"Cannot add a component to an entity that does not exist");
_components[entity].insert(owningSystem);
_needDependencyFetch.emplace_back(entity, owningSystem);
}
void SystemManager::UnregisterComponent(Entity entity, AbstractSystem * owningSystem)
{
Assert(_components.find(entity) != _components.end(),
"Can not remove a component from an entity that does not exist");
Assert(_components[entity].find(owningSystem) != _components[entity].end(),
"Can not remove a component that does not exist");
_components[entity].erase(owningSystem);
}
void SystemManager::AddEntitySaveableSystemPair(std::string entity, std::string system)
{
Assert(_entities.count(entity), "Cannot add entity-system saveable pair: Entity " + entity + " does not exist.");
Assert(alg::count_if(_keyedSystems, [system](std::pair<std::string, AbstractSystem *> sysNamePair)
{
return sysNamePair.first == system;
}
), "Cannot add entity-system saveable pair: System " + system + " does not exist or is not keyed.");
if(alg::count(_entitySaveableSystems[system], entity))
{
_entitySaveableSystems[system].push_back(entity);
}
}
void SystemManager::DeleteQueuedEntities()
{
for(Entity & entity : _deleteQueue)
{
DeleteEntity(entity);
}
_deleteQueue.clear();
}
void SystemManager::FetchWaitingDependencies()
{
for(auto & entitySystemPair : _needDependencyFetch)
{
entitySystemPair.second->FetchComponentDependencies(entitySystemPair.first);
}
_needDependencyFetch.clear();
}
void SystemManager::Serialize(Archive & arc)
{
arc(_entitySaveableSystems, "entity-system-saveables");
}
|
#include <map>
#include <unordered_map>
#include <Ancona/Framework/EntityFramework/AbstractSystem.hpp>
#include <Ancona/Framework/EntityFramework/SystemManager.hpp>
#include <Ancona/Framework/Serializing/Serializing.hpp>
#include <Ancona/Util/Algorithm.hpp>
using namespace ild;
SystemManager::SystemManager()
{
_maxEntityId = 0;
}
void SystemManager::Update(float delta, UpdateStepEnum updateStep)
{
FetchWaitingDependencies();
for(auto & system : _systems[updateStep])
{
system->Update(delta);
system->DeleteQueuedComponents();
}
DeleteQueuedEntities();
}
void SystemManager::DeleteEntity(Entity entity)
{
Assert(_components.find(entity) != _components.end(),
"Cannot delete an entity that is not managed by the system manager");
for(AbstractSystem * system : _components.at(entity))
{
system->EntityIsDeleted(entity);
}
auto reverseIter = _entitiesReverse.find(entity);
if(reverseIter != _entitiesReverse.end())
{
_entities.erase(reverseIter->second);
_entitiesReverse.erase(reverseIter);
}
_components.erase(entity);
}
void SystemManager::QueueDeleteEntity(Entity entity)
{
_deleteQueue.push_back(entity);
}
Entity SystemManager::CreateEntity()
{
Assert(_maxEntityId != ~0u, "Entity key has overflown");
Entity entity = _maxEntityId++;
//Create a structure for the entity
_components[entity];
return entity;
}
Entity SystemManager::CreateEntity(const std::string & key)
{
Assert(_entities.find(key) == _entities.end(), "Cannot use the same key for two entities.");
Entity entity = CreateEntity();
_entities[key] = entity;
_entitiesReverse[entity] = key;
return entity;
}
Entity SystemManager::GetEntity(const std::string & key)
{
auto entityIter = _entities.find(key);
if(entityIter == _entities.end())
{
return nullentity;
}
return entityIter->second;
}
bool SystemManager::ContainsName(std::string & systemName)
{
return alg::any_of(_keyedSystems,
[=](std::pair<std::string, AbstractSystem *> & nameSystemPair)
{
return nameSystemPair.first == systemName;
});
}
void SystemManager::RegisterSystem(
std::string systemName,
AbstractSystem * system,
UpdateStepEnum updateStep)
{
auto & systems = _systems[updateStep];
Assert(!alg::count_if(systems,[system](std::unique_ptr<AbstractSystem> & ptr)
{
return ptr.get() == system;
}
), "A System Manager cannot contain the same system twice");
systems.emplace_back(system);
if(systemName != "")
{
Assert(!ContainsName(systemName), "System name must be unique.");
_keyedSystems.emplace_back(systemName, system);
}
}
void SystemManager::RegisterComponent(Entity entity, AbstractSystem * owningSystem)
{
Assert(_components.find(entity) != _components.end(),
"Cannot add a component to an entity that does not exist");
_components[entity].insert(owningSystem);
_needDependencyFetch.emplace_back(entity, owningSystem);
}
void SystemManager::UnregisterComponent(Entity entity, AbstractSystem * owningSystem)
{
Assert(_components.find(entity) != _components.end(),
"Can not remove a component from an entity that does not exist");
Assert(_components[entity].find(owningSystem) != _components[entity].end(),
"Can not remove a component that does not exist");
_components[entity].erase(owningSystem);
}
void SystemManager::AddEntitySaveableSystemPair(std::string entity, std::string system)
{
Assert(_entities.count(entity), "Cannot add entity-system saveable pair: Entity " + entity + " does not exist.");
Assert(alg::count_if(_keyedSystems, [system](std::pair<std::string, AbstractSystem *> sysNamePair)
{
return sysNamePair.first == system;
}
), "Cannot add entity-system saveable pair: System " + system + " does not exist or is not keyed.");
if(!alg::count(_entitySaveableSystems[system], entity))
{
_entitySaveableSystems[system].push_back(entity);
}
}
void SystemManager::DeleteQueuedEntities()
{
for(Entity & entity : _deleteQueue)
{
DeleteEntity(entity);
}
_deleteQueue.clear();
}
void SystemManager::FetchWaitingDependencies()
{
for(auto & entitySystemPair : _needDependencyFetch)
{
entitySystemPair.second->FetchComponentDependencies(entitySystemPair.first);
}
_needDependencyFetch.clear();
}
void SystemManager::Serialize(Archive & arc)
{
arc(_entitySaveableSystems, "entity-system-saveables");
}
|
add reverse condition when adding entity-system saveables to the SystemManager
|
add reverse condition when adding entity-system saveables to the SystemManager
|
C++
|
mit
|
tlein/Ancona,tlein/Ancona,tlein/Ancona,tlein/Ancona
|
963bd55db99821ba89e13ebb0b0f3407de6bef2d
|
test/ofp/byteorder_unittest.cpp
|
test/ofp/byteorder_unittest.cpp
|
// Copyright (c) 2015-2017 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#include "ofp/byteorder.h"
#include "ofp/unittest.h"
using namespace ofp;
TEST(byteorder, IsHostBigEndian) {
const char *be = "\1\2\3\4";
const char *le = "\4\3\2\1";
UInt32 n = 0x01020304;
if (detail::IsHostBigEndian) {
EXPECT_FALSE(detail::IsHostLittleEndian);
EXPECT_EQ(0, std::memcmp(be, &n, 4));
EXPECT_NE(0, std::memcmp(le, &n, 4));
} else {
EXPECT_TRUE(detail::IsHostLittleEndian);
EXPECT_EQ(0, std::memcmp(le, &n, 4));
EXPECT_NE(0, std::memcmp(be, &n, 4));
}
}
TEST(byteorder, SwapTwoBytes) {
EXPECT_EQ(0x0201, detail::SwapTwoBytes(0x0102));
EXPECT_EQ(0xf2f4, detail::SwapTwoBytes(0xf4f2));
}
TEST(byteorder, SwapFourBytes) {
EXPECT_EQ(0x04030201, detail::SwapFourBytes(0x01020304));
EXPECT_EQ(0xf2f4f8fa, detail::SwapFourBytes(0xfaf8f4f2));
}
TEST(byteorder, SwapEightBytes) {
EXPECT_EQ(0x0807060504030201, detail::SwapEightBytes(0x0102030405060708));
EXPECT_EQ(0xf2f4f8fafcfef0f4, detail::SwapEightBytes(0xf4f0fefcfaf8f4f2));
}
TEST(byteorder, Big8) {
Big8 a{2};
EXPECT_EQ(0, std::memcmp(&a, "\2", 1));
EXPECT_EQ(2, a);
a = 5;
EXPECT_EQ(0, std::memcmp(&a, "\5", 1));
EXPECT_EQ(5, a);
}
TEST(byteorder, Big16) {
Big16 a{0x0201U};
EXPECT_EQ(0, std::memcmp(&a, "\2\1", 2));
EXPECT_EQ(0x0201U, a);
a = 0x0102U;
EXPECT_EQ(0, std::memcmp(&a, "\1\2", 2));
EXPECT_EQ(0x0102U, a);
}
TEST(byteorder, Big32) {
Big32 a{0x04050607};
EXPECT_EQ(0, std::memcmp(&a, "\4\5\6\7", 4));
EXPECT_EQ(0x04050607, a);
a = 0x01020304UL;
EXPECT_EQ(0, std::memcmp(&a, "\1\2\3\4", 4));
EXPECT_EQ(0x01020304UL, a);
}
TEST(byteorder, Big64) {
Big64 a{0x0807060504030201ULL};
EXPECT_EQ(0, std::memcmp(&a, "\10\7\6\5\4\3\2\1", 8));
EXPECT_EQ(0x0807060504030201ULL, a);
a = 0x0102030405060708ULL;
EXPECT_EQ(0, std::memcmp(&a, "\1\2\3\4\5\6\7\10", 8));
EXPECT_EQ(0x0102030405060708ULL, a);
}
TEST(byteorder, BigEnum8) {
// Test enum class of type UInt8.
enum class Foo8 : UInt8 { a, b, c };
Big<Foo8> x;
static_assert(sizeof(x) == sizeof(UInt8), "Unexpected enum size.");
x = Foo8::a;
EXPECT_EQ(Foo8::a, x);
EXPECT_EQ(0, std::memcmp(&x, "\0", 1));
x = Foo8::b;
EXPECT_EQ(Foo8::b, x);
EXPECT_EQ(0, std::memcmp(&x, "\1", 1));
x = Foo8::c;
EXPECT_EQ(Foo8::c, x);
EXPECT_EQ(0, std::memcmp(&x, "\2", 1));
}
TEST(byteorder, BigEnum16) {
// Test enum class of type UInt16.
enum class Foo16 : UInt16 { a, b, c };
Big<Foo16> x;
static_assert(sizeof(x) == sizeof(UInt16), "Unexpected enum size.");
x = Foo16::a;
EXPECT_EQ(Foo16::a, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\0", 2));
x = Foo16::b;
EXPECT_EQ(Foo16::b, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\1", 2));
x = Foo16::c;
EXPECT_EQ(Foo16::c, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\2", 2));
}
TEST(byteorder, BigEnum32) {
// Test enum class of type UInt32.
enum class Foo32 : UInt32 { a, b, c };
Big<Foo32> x;
static_assert(sizeof(x) == sizeof(UInt32), "Unexpected enum size.");
x = Foo32::a;
EXPECT_EQ(Foo32::a, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\0\0\0", 4));
x = Foo32::b;
EXPECT_EQ(Foo32::b, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\0\0\1", 4));
x = Foo32::c;
EXPECT_EQ(Foo32::c, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\0\0\2", 4));
}
TEST(byteorder, BigEnum) {
// Plain unadorned enum.
enum Foo : int { a, b, c };
Big<Foo> x;
static_assert(sizeof(x) == sizeof(int), "Unexpected enum size.");
static_assert(sizeof(int) == 4, "Unexpected int size.");
x = a;
EXPECT_EQ(a, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\0\0\0", sizeof(int)));
x = b;
EXPECT_EQ(b, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\0\0\1", sizeof(int)));
x = c;
EXPECT_EQ(c, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\0\0\2", sizeof(int)));
}
// Make sure we can use BigEndianFromNative in a constexpr.
constexpr UInt32 ConvertToBigEndian(UInt32 value) {
return BigEndianFromNative(value);
}
TEST(byteorder, BigEndianFromNative) {
UInt32 val = ConvertToBigEndian(0x01020304U);
EXPECT_EQ(0, std::memcmp(&val, "\1\2\3\4", 4));
}
TEST(byteorder, BigEndianToNative) {
auto a = BigEndianFromNative(0x80000000UL);
auto b = BigEndianToNative(a);
EXPECT_EQ(0x80000000UL, b);
}
TEST(byteorder, equals) {
Big16 a{3};
Big16 b{3};
EXPECT_TRUE(a == b);
}
TEST(byteorder, operator_not) {
Big16 a{0x1122};
Big16 b{0};
EXPECT_FALSE(!a);
EXPECT_TRUE(!b);
}
TEST(byteorder, Big24) {
Big24 a{0x04050607};
EXPECT_EQ(0, std::memcmp(&a, "\5\6\7", 3));
EXPECT_EQ(0x050607, a);
a = 0x01020304UL;
EXPECT_EQ(0, std::memcmp(&a, "\2\3\4", 3));
EXPECT_EQ(0x020304UL, a);
Big24 b;
EXPECT_EQ(0, std::memcmp(&b, "\0\0\0", 3));
EXPECT_EQ(0, b);
}
TEST(byteorder, fromBytes) {
Big32 val32 = 0x11111111;
Big64 val64 = 0x1111111122222222;
auto a = Big32::fromBytes(BytePtr(&val32), 0);
EXPECT_EQ(0, a);
auto b = Big32::fromBytes(BytePtr(&val32), 4);
EXPECT_EQ(0x11111111, b);
auto c = Big32::fromBytes(BytePtr(&val64), 8);
EXPECT_EQ(0x22222222, c);
}
TEST(byteorder, Big16_unaligned) {
Big32 x = 0x01020304;
const UInt8 *p = BytePtr(&x);
EXPECT_EQ(0x0203, Big16_unaligned(p + 1));
}
TEST(byteorder, Big32_unaligned) {
Big64 x = 0x0102030405060708;
const UInt8 *p = BytePtr(&x);
EXPECT_EQ(0x02030405, Big32_unaligned(p + 1));
}
|
// Copyright (c) 2015-2017 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#include "ofp/byteorder.h"
#include "ofp/unittest.h"
using namespace ofp;
TEST(byteorder, IsHostBigEndian) {
const char *be = "\1\2\3\4";
const char *le = "\4\3\2\1";
UInt32 n = 0x01020304;
if (detail::IsHostBigEndian) {
EXPECT_FALSE(detail::IsHostLittleEndian);
EXPECT_EQ(0, std::memcmp(be, &n, 4));
EXPECT_NE(0, std::memcmp(le, &n, 4));
} else {
EXPECT_TRUE(detail::IsHostLittleEndian);
EXPECT_EQ(0, std::memcmp(le, &n, 4));
EXPECT_NE(0, std::memcmp(be, &n, 4));
}
}
TEST(byteorder, SwapTwoBytes) {
EXPECT_EQ(0x0201, detail::SwapTwoBytes(0x0102));
EXPECT_EQ(0xf2f4, detail::SwapTwoBytes(0xf4f2));
}
TEST(byteorder, SwapFourBytes) {
EXPECT_EQ(0x04030201, detail::SwapFourBytes(0x01020304));
EXPECT_EQ(0xf2f4f8fa, detail::SwapFourBytes(0xfaf8f4f2));
}
TEST(byteorder, SwapEightBytes) {
EXPECT_EQ(0x0807060504030201, detail::SwapEightBytes(0x0102030405060708));
EXPECT_EQ(0xf2f4f8fafcfef0f4, detail::SwapEightBytes(0xf4f0fefcfaf8f4f2));
}
TEST(byteorder, Big8) {
Big8 a{2};
EXPECT_EQ(0, std::memcmp(&a, "\2", 1));
EXPECT_EQ(2, a);
a = 5;
EXPECT_EQ(0, std::memcmp(&a, "\5", 1));
EXPECT_EQ(5, a);
}
TEST(byteorder, Big16) {
Big16 a{0x0201U};
EXPECT_EQ(0, std::memcmp(&a, "\2\1", 2));
EXPECT_EQ(0x0201U, a);
a = 0x0102U;
EXPECT_EQ(0, std::memcmp(&a, "\1\2", 2));
EXPECT_EQ(0x0102U, a);
}
TEST(byteorder, Big32) {
Big32 a{0x04050607};
EXPECT_EQ(0, std::memcmp(&a, "\4\5\6\7", 4));
EXPECT_EQ(0x04050607, a);
a = 0x01020304UL;
EXPECT_EQ(0, std::memcmp(&a, "\1\2\3\4", 4));
EXPECT_EQ(0x01020304UL, a);
}
TEST(byteorder, Big64) {
Big64 a{0x0807060504030201ULL};
EXPECT_EQ(0, std::memcmp(&a, "\10\7\6\5\4\3\2\1", 8));
EXPECT_EQ(0x0807060504030201ULL, a);
a = 0x0102030405060708ULL;
EXPECT_EQ(0, std::memcmp(&a, "\1\2\3\4\5\6\7\10", 8));
EXPECT_EQ(0x0102030405060708ULL, a);
}
TEST(byteorder, BigEnum8) {
// Test enum class of type UInt8.
enum class Foo8 : UInt8 { a, b, c };
Big<Foo8> x;
static_assert(sizeof(x) == sizeof(UInt8), "Unexpected enum size.");
x = Foo8::a;
EXPECT_EQ(Foo8::a, x);
EXPECT_EQ(0, std::memcmp(&x, "\0", 1));
x = Foo8::b;
EXPECT_EQ(Foo8::b, x);
EXPECT_EQ(0, std::memcmp(&x, "\1", 1));
x = Foo8::c;
EXPECT_EQ(Foo8::c, x);
EXPECT_EQ(0, std::memcmp(&x, "\2", 1));
}
TEST(byteorder, BigEnum16) {
// Test enum class of type UInt16.
enum class Foo16 : UInt16 { a, b, c };
Big<Foo16> x;
static_assert(sizeof(x) == sizeof(UInt16), "Unexpected enum size.");
x = Foo16::a;
EXPECT_EQ(Foo16::a, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\0", 2));
x = Foo16::b;
EXPECT_EQ(Foo16::b, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\1", 2));
x = Foo16::c;
EXPECT_EQ(Foo16::c, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\2", 2));
}
TEST(byteorder, BigEnum32) {
// Test enum class of type UInt32.
enum class Foo32 : UInt32 { a, b, c };
Big<Foo32> x;
static_assert(sizeof(x) == sizeof(UInt32), "Unexpected enum size.");
x = Foo32::a;
EXPECT_EQ(Foo32::a, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\0\0\0", 4));
x = Foo32::b;
EXPECT_EQ(Foo32::b, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\0\0\1", 4));
x = Foo32::c;
EXPECT_EQ(Foo32::c, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\0\0\2", 4));
}
TEST(byteorder, BigEnum) {
// Plain unadorned enum.
enum Foo : int { a, b, c };
Big<Foo> x;
static_assert(sizeof(x) == sizeof(int), "Unexpected enum size.");
static_assert(sizeof(int) == 4, "Unexpected int size.");
x = a;
EXPECT_EQ(a, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\0\0\0", sizeof(int)));
x = b;
EXPECT_EQ(b, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\0\0\1", sizeof(int)));
x = c;
EXPECT_EQ(c, x);
EXPECT_EQ(0, std::memcmp(&x, "\0\0\0\2", sizeof(int)));
}
// Make sure we can use BigEndianFromNative in a constexpr.
constexpr UInt32 ConvertToBigEndian(UInt32 value) {
return BigEndianFromNative(value);
}
TEST(byteorder, BigEndianFromNative) {
UInt32 val = ConvertToBigEndian(0x01020304U);
EXPECT_EQ(0, std::memcmp(&val, "\1\2\3\4", 4));
}
TEST(byteorder, BigEndianToNative) {
auto a = BigEndianFromNative(0x80000000UL);
auto b = BigEndianToNative(a);
EXPECT_EQ(0x80000000UL, b);
}
TEST(byteorder, equals) {
Big16 a{3};
Big16 b{3};
EXPECT_TRUE(a == b);
}
TEST(byteorder, operator_not) {
Big16 a{0x1122};
Big16 b{0};
EXPECT_FALSE(!a);
EXPECT_TRUE(!b);
}
TEST(byteorder, Big24) {
Big24 a{0x04050607};
EXPECT_EQ(0, std::memcmp(&a, "\5\6\7", 3));
EXPECT_EQ(0x050607, a);
a = 0x01020304UL;
EXPECT_EQ(0, std::memcmp(&a, "\2\3\4", 3));
EXPECT_EQ(0x020304UL, a);
Big24 b;
EXPECT_EQ(0, std::memcmp(&b, "\0\0\0", 3));
EXPECT_EQ(0, b);
}
TEST(byteorder, fromBytes) {
Big32 val32 = 0x11111111;
Big64 val64 = 0x1111111122222222;
auto a = Big32::fromBytes(BytePtr(&val32), 0);
EXPECT_EQ(0, a);
auto b = Big32::fromBytes(BytePtr(&val32), 4);
EXPECT_EQ(0x11111111, b);
auto c = Big32::fromBytes(BytePtr(&val64), 8);
EXPECT_EQ(0x22222222, c);
}
TEST(byteorder, Big16_unaligned) {
Big32 x = 0x01020304;
const UInt8 *p = BytePtr(&x);
EXPECT_EQ(0x0203, Big16_unaligned(p + 1));
}
TEST(byteorder, Big32_unaligned) {
Big64 x = 0x0102030405060708;
const UInt8 *p = BytePtr(&x);
EXPECT_EQ(0x02030405, Big32_unaligned(p + 1));
}
// Test NativeTypeOf construct.
static_assert(std::is_same<NativeTypeOf<Big64>::type, UInt64>::value, "Unexpected type");
static_assert(std::is_same<NativeTypeOf<Big32>::type, UInt32>::value, "Unexpected type");
static_assert(std::is_same<NativeTypeOf<Big16>::type, UInt16>::value, "Unexpected type");
static_assert(std::is_same<NativeTypeOf<Big8>::type, UInt8>::value, "Unexpected type");
static_assert(std::is_same<NativeTypeOf<Big24>::type, UInt32>::value, "Unexpected type");
static_assert(std::is_same<NativeTypeOf<UInt32>::type, UInt32>::value, "Unexpected type");
struct Foo {};
static_assert(std::is_same<NativeTypeOf<Foo>::type, Foo>::value, "Unexpected type");
struct Bar {
using NativeType = Foo;
};
static_assert(std::is_same<NativeTypeOf<Bar>::type, Foo>::value, "Unexpected type");
|
Add static_asserts to test NativeTypeOf trait check.
|
Add static_asserts to test NativeTypeOf trait check.
|
C++
|
mit
|
byllyfish/oftr,byllyfish/libofp,byllyfish/oftr,byllyfish/oftr,byllyfish/oftr,byllyfish/libofp,byllyfish/oftr,byllyfish/libofp
|
8823a987f7dd18cc67d167bcd49d17e202029d9b
|
arsel.cpp
|
arsel.cpp
|
// 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 "burg.hpp"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <vector>
template <class Real, class In>
std::size_t process(In& in,
Real& mean,
std::size_t &order,
std::vector<Real>& params,
std::vector<Real>& sigma2e,
std::vector<Real>& gain,
std::vector<Real>& autocor,
bool subtract_mean)
{
// Use burg_method to estimate a hierarchy of AR models from input data
params .reserve(order*(order + 1)/2);
sigma2e.reserve(order + 1);
gain .reserve(order + 1);
autocor.reserve(order + 1);
const std::size_t N = burg_method(std::istream_iterator<Real>(in),
std::istream_iterator<Real>(),
mean,
order,
std::back_inserter(params),
std::back_inserter(sigma2e),
std::back_inserter(gain),
std::back_inserter(autocor),
subtract_mean,
/* output hierarchy? */ true);
// Find the best model according to CIC accounting for subtract_mean.
typename std::vector<Real>::difference_type best;
if (subtract_mean) {
best = evaluate_models<CIC<Burg<mean_subtracted> > >(
N, 0u, sigma2e.begin(), sigma2e.end());
} else {
best = evaluate_models<CIC<Burg<mean_retained> > >(
N, 0u, sigma2e.begin(), sigma2e.end());
}
// Trim away everything but the best model (where ranges might overlap)
// AR(0) is trivial and AR(1) starts at params.begin(), hence off by one.
std::copy_backward(params.begin() + ((best-1)*best)/2,
params.begin() + ((best-1)*best)/2 + best,
params.begin() + best);
params.resize(best);
sigma2e[0] = sigma2e[best]; sigma2e.resize(1);
gain [0] = gain [best]; gain .resize(1);
autocor.resize(best + 1);
return N;
}
// Test burg_method against synthetic data
int main(int argc, char *argv[])
{
using namespace std;
// Process a possible --subtract-mean flag, shifting arguments if needed
bool subtract_mean = false;
if (argc > 1 && 0 == strcmp("--subtract-mean", argv[1])) {
subtract_mean = true;
argv[1] = argv[0];
++argv;
--argc;
}
double mean;
size_t order = 512;
vector<double> params, sigma2e, gain, autocor;
size_t N = process(cin, mean, order, params,
sigma2e, gain, autocor, subtract_mean);
cout.precision(std::numeric_limits<double>::digits10 + 2);
cout << showpos
<< "# N " << N
<< "\n# AR(p) " << params.size()
<< "\n# Mean " << mean
<< "\n# \\sigma^2_\\epsilon " << sigma2e[0]
<< "\n# Gain " << gain[0]
<< "\n# \\sigma^2_x " << gain[0]*sigma2e[0]
<< '\n';
copy(params.begin(), params.end(), ostream_iterator<double>(cout,"\n"));
cout.flush();
return 0;
}
|
// 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 "burg.hpp"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <vector>
// Estimate the best AR(p) model given data on standard input
int main(int argc, char *argv[])
{
using namespace std;
// Process a possible --subtract-mean flag, shifting arguments if needed
bool subtract_mean = false;
if (argc > 1 && 0 == strcmp("--subtract-mean", argv[1])) {
subtract_mean = true;
argv[1] = argv[0];
++argv;
--argc;
}
// Use burg_method to estimate a hierarchy of AR models from input data
double mean;
size_t order = 512;
vector<double> params, sigma2e, gain, autocor;
params .reserve(order*(order + 1)/2);
sigma2e.reserve(order + 1);
gain .reserve(order + 1);
autocor.reserve(order + 1);
const std::size_t N = burg_method(std::istream_iterator<double>(cin),
std::istream_iterator<double>(),
mean,
order,
std::back_inserter(params),
std::back_inserter(sigma2e),
std::back_inserter(gain),
std::back_inserter(autocor),
subtract_mean,
/* output hierarchy? */ true);
// Keep only best model according to CIC accounting for subtract_mean.
if (subtract_mean) {
best_model<CIC<Burg<mean_subtracted> > >(
N, params, sigma2e, gain, autocor);
} else {
best_model<CIC<Burg<mean_retained> > >(
N, params, sigma2e, gain, autocor);
}
// Output some details about the best model
cout.precision(std::numeric_limits<double>::digits10 + 2);
cout << showpos
<< "# N " << N
<< "\n# AR(p) " << params.size()
<< "\n# Mean " << mean
<< "\n# \\sigma^2_\\epsilon " << sigma2e[0]
<< "\n# Gain " << gain[0]
<< "\n# \\sigma^2_x " << gain[0]*sigma2e[0]
<< '\n';
copy(params.begin(), params.end(), ostream_iterator<double>(cout,"\n"));
cout.flush();
return 0;
}
|
use the new best_model method to simplify code
|
use the new best_model method to simplify code
|
C++
|
mpl-2.0
|
RhysU/ar,RhysU/ar
|
b9a9c638b98ab814e4535b09b62186599bb0934d
|
src/net/instaweb/system/system_rewrite_options.cc
|
src/net/instaweb/system/system_rewrite_options.cc
|
// Copyright 2013 Google 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.
//
// Author: [email protected] (Joshua Marantz)
#include "net/instaweb/system/public/system_rewrite_options.h"
#include "base/logging.h"
#include "net/instaweb/util/public/basictypes.h"
#include "net/instaweb/util/public/timer.h"
namespace net_instaweb {
class ThreadSystem;
namespace {
const int64 kDefaultCacheFlushIntervalSec = 5;
} // namespace
RewriteOptions::Properties* SystemRewriteOptions::system_properties_ = NULL;
void SystemRewriteOptions::Initialize() {
if (Properties::Initialize(&system_properties_)) {
RewriteOptions::Initialize();
AddProperties();
}
}
void SystemRewriteOptions::Terminate() {
if (Properties::Terminate(&system_properties_)) {
RewriteOptions::Terminate();
}
}
SystemRewriteOptions::SystemRewriteOptions(ThreadSystem* thread_system)
: RewriteOptions(thread_system) {
DCHECK(system_properties_ != NULL)
<< "Call SystemRewriteOptions::Initialize() before construction";
InitializeOptions(system_properties_);
}
SystemRewriteOptions::SystemRewriteOptions(const StringPiece& description,
ThreadSystem* thread_system)
: RewriteOptions(thread_system),
description_(description.data(), description.size()) {
DCHECK(system_properties_ != NULL)
<< "Call SystemRewriteOptions::Initialize() before construction";
InitializeOptions(system_properties_);
}
SystemRewriteOptions::~SystemRewriteOptions() {
}
void SystemRewriteOptions::AddProperties() {
AddSystemProperty("", &SystemRewriteOptions::fetcher_proxy_, "afp",
RewriteOptions::kFetcherProxy,
"Set the fetch proxy");
AddSystemProperty("", &SystemRewriteOptions::file_cache_path_, "afcp",
RewriteOptions::kFileCachePath,
"Set the path for file cache");
AddSystemProperty("", &SystemRewriteOptions::log_dir_, "ald",
RewriteOptions::kLogDir,
"Directory to store logs in.");
AddSystemProperty("", &SystemRewriteOptions::memcached_servers_, "ams",
RewriteOptions::kMemcachedServers,
"Comma-separated list of servers e.g. "
"host1:port1,host2:port2");
AddSystemProperty(1, &SystemRewriteOptions::memcached_threads_, "amt",
RewriteOptions::kMemcachedThreads,
"Number of background threads to use to run "
"memcached fetches");
AddSystemProperty(0, &SystemRewriteOptions::memcached_timeout_us_, "amo",
RewriteOptions::kMemcachedTimeoutUs,
"Maximum time in microseconds to allow for memcached "
"transactions");
AddSystemProperty(true, &SystemRewriteOptions::statistics_enabled_, "ase",
RewriteOptions::kStatisticsEnabled,
"Whether to collect cross-process statistics.");
AddSystemProperty("/pagespeed_statistics",
&SystemRewriteOptions::statistics_handler_path_, "ashp",
RewriteOptions::kStatisticsHandlerPath,
"Absolute path URL to statistics handler.");
AddSystemProperty("", &SystemRewriteOptions::statistics_logging_charts_css_,
"aslcc", RewriteOptions::kStatisticsLoggingChartsCSS,
"Where to find an offline copy of the Google Charts Tools "
"API CSS.");
AddSystemProperty("", &SystemRewriteOptions::statistics_logging_charts_js_,
"aslcj", RewriteOptions::kStatisticsLoggingChartsJS,
"Where to find an offline copy of the Google Charts Tools "
"API JS.");
AddSystemProperty(false, &SystemRewriteOptions::statistics_logging_enabled_,
"asle", RewriteOptions::kStatisticsLoggingEnabled,
"Whether to log statistics if they're being collected.");
AddSystemProperty(1 * Timer::kMinuteMs,
&SystemRewriteOptions::statistics_logging_interval_ms_,
"asli", RewriteOptions::kStatisticsLoggingIntervalMs,
"How often to log statistics, in milliseconds.");
AddSystemProperty(100 * 1024 /* 100 Megabytes */,
&SystemRewriteOptions::statistics_logging_max_file_size_kb_,
"aslfs", RewriteOptions::kStatisticsLoggingMaxFileSizeKb,
"Max size for statistics logging file.");
AddSystemProperty(true, &SystemRewriteOptions::use_shared_mem_locking_,
"ausml", RewriteOptions::kUseSharedMemLocking,
"Use shared memory for internal named lock service");
AddSystemProperty(Timer::kHourMs,
&SystemRewriteOptions::file_cache_clean_interval_ms_,
"afcci", RewriteOptions::kFileCacheCleanIntervalMs,
"Set the interval (in ms) for cleaning the file cache");
AddSystemProperty(100 * 1024 /* 100 megabytes */,
&SystemRewriteOptions::file_cache_clean_size_kb_,
"afc", RewriteOptions::kFileCacheCleanSizeKb,
"Set the target size (in kilobytes) for file cache");
// Default to no inode limit so that existing installations are not affected.
// pagespeed.conf.template contains suggested limit for new installations.
// TODO(morlovich): Inject this as an argument, since we want a different
// default for ngx_pagespeed?
AddSystemProperty(0, &SystemRewriteOptions::file_cache_clean_inode_limit_,
"afcl", RewriteOptions::kFileCacheCleanInodeLimit,
"Set the target number of inodes for the file cache; 0 "
"means no limit");
AddSystemProperty(0, &SystemRewriteOptions::lru_cache_byte_limit_, "alcb",
RewriteOptions::kLruCacheByteLimit,
"Set the maximum byte size entry to store in the "
"per-process in-memory LRU cache");
AddSystemProperty(0, &SystemRewriteOptions::lru_cache_kb_per_process_, "alcp",
RewriteOptions::kLruCacheKbPerProcess,
"Set the total size, in KB, of the per-process in-memory "
"LRU cache");
AddSystemProperty("", &SystemRewriteOptions::cache_flush_filename_, "acff",
RewriteOptions::kCacheFlushFilename,
"Name of file to check for timestamp updates used to flush "
"cache. This file will be relative to the "
"ModPagespeedFileCachePath if it does not begin with a "
"slash.");
AddSystemProperty(kDefaultCacheFlushIntervalSec,
&SystemRewriteOptions::cache_flush_poll_interval_sec_,
"acfpi", RewriteOptions::kCacheFlushPollIntervalSec,
"Number of seconds to wait between polling for cache-flush "
"requests");
AddSystemProperty(false,
&SystemRewriteOptions::compress_metadata_cache_,
"cc", RewriteOptions::kCompressMetadataCache,
"Whether to compress cache entries before writing them to "
"memory or disk.");
AddSystemProperty("", &SystemRewriteOptions::ssl_cert_directory_, "assld",
RewriteOptions::kSslCertDirectory,
"Directory to find SSL certificates.");
AddSystemProperty("", &SystemRewriteOptions::ssl_cert_file_, "asslf",
RewriteOptions::kSslCertFile,
"File with SSL certificates.");
AddSystemProperty("", &SystemRewriteOptions::slurp_directory_, "asd",
RewriteOptions::kSlurpDirectory,
"Directory from which to read slurped resources");
AddSystemProperty(false, &SystemRewriteOptions::test_proxy_, "atp",
RewriteOptions::kTestProxy,
"Direct non-PageSpeed URLs to a fetcher, acting as a "
"simple proxy. Meant for test use only");
AddSystemProperty("", &SystemRewriteOptions::test_proxy_slurp_, "atps",
RewriteOptions::kTestProxySlurp,
"If set, the fetcher used by the TestProxy mode will be a "
"readonly slurp fetcher from the given directory");
AddSystemProperty(false, &SystemRewriteOptions::slurp_read_only_, "asro",
RewriteOptions::kSlurpReadOnly,
"Only read from the slurped directory, fail to fetch "
"URLs not already in the slurped directory");
AddSystemProperty(false,
&SystemRewriteOptions::rate_limit_background_fetches_,
"rlbf",
RewriteOptions::kRateLimitBackgroundFetches,
"Rate-limit the number of background HTTP fetches done at "
"once");
AddSystemProperty(0, &SystemRewriteOptions::slurp_flush_limit_, "asfl",
RewriteOptions::kSlurpFlushLimit,
"Set the maximum byte size for the slurped content to hold "
"before a flush");
AddSystemProperty(false, &SystemRewriteOptions::disable_loopback_routing_,
"adlr",
"DangerPermitFetchFromUnknownHosts",
kProcessScopeStrict,
"Disable security checks that prohibit fetching from "
"hostnames mod_pagespeed does not know about");
AddSystemProperty(false, &SystemRewriteOptions::fetch_with_gzip_,
"afg", "FetchWithGzip", kProcessScope,
"Request http content from origin servers using gzip");
AddSystemProperty(1024 * 1024 * 10, /* 10 Megabytes */
&SystemRewriteOptions::ipro_max_response_bytes_,
"imrb", "IproMaxResponseBytes", kProcessScope,
"Limit allowed size of IPRO responses. "
"Set to 0 for unlimited.");
AddSystemProperty(10,
&SystemRewriteOptions::ipro_max_concurrent_recordings_,
"imcr", "IproMaxConcurrentRecordings", kProcessScope,
"Limit allowed number of IPRO recordings");
MergeSubclassProperties(system_properties_);
// We allow a special instantiation of the options with a null thread system
// because we are only updating the static properties on process startup; we
// won't have a thread-system yet or multiple threads.
//
// Leave slurp_read_only out of the signature as (a) we don't actually change
// this spontaneously, and (b) it's useful to keep the metadata cache between
// slurping read-only and slurp read/write.
SystemRewriteOptions config("dummy_options", NULL);
config.slurp_read_only_.DoNotUseForSignatureComputation();
}
SystemRewriteOptions* SystemRewriteOptions::Clone() const {
SystemRewriteOptions* options = NewOptions();
options->Merge(*this);
return options;
}
SystemRewriteOptions* SystemRewriteOptions::NewOptions() const {
return new SystemRewriteOptions("new_options", thread_system());
}
const SystemRewriteOptions* SystemRewriteOptions::DynamicCast(
const RewriteOptions* instance) {
const SystemRewriteOptions* config =
dynamic_cast<const SystemRewriteOptions*>(instance);
DCHECK(config != NULL);
return config;
}
SystemRewriteOptions* SystemRewriteOptions::DynamicCast(
RewriteOptions* instance) {
SystemRewriteOptions* config = dynamic_cast<SystemRewriteOptions*>(instance);
DCHECK(config != NULL);
return config;
}
} // namespace net_instaweb
|
// Copyright 2013 Google 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.
//
// Author: [email protected] (Joshua Marantz)
#include "net/instaweb/system/public/system_rewrite_options.h"
#include "base/logging.h"
#include "net/instaweb/util/public/basictypes.h"
#include "net/instaweb/util/public/timer.h"
namespace net_instaweb {
class ThreadSystem;
namespace {
const int64 kDefaultCacheFlushIntervalSec = 5;
} // namespace
RewriteOptions::Properties* SystemRewriteOptions::system_properties_ = NULL;
void SystemRewriteOptions::Initialize() {
if (Properties::Initialize(&system_properties_)) {
RewriteOptions::Initialize();
AddProperties();
}
}
void SystemRewriteOptions::Terminate() {
if (Properties::Terminate(&system_properties_)) {
RewriteOptions::Terminate();
}
}
SystemRewriteOptions::SystemRewriteOptions(ThreadSystem* thread_system)
: RewriteOptions(thread_system) {
DCHECK(system_properties_ != NULL)
<< "Call SystemRewriteOptions::Initialize() before construction";
InitializeOptions(system_properties_);
}
SystemRewriteOptions::SystemRewriteOptions(const StringPiece& description,
ThreadSystem* thread_system)
: RewriteOptions(thread_system),
description_(description.data(), description.size()) {
DCHECK(system_properties_ != NULL)
<< "Call SystemRewriteOptions::Initialize() before construction";
InitializeOptions(system_properties_);
}
SystemRewriteOptions::~SystemRewriteOptions() {
}
void SystemRewriteOptions::AddProperties() {
AddSystemProperty("", &SystemRewriteOptions::fetcher_proxy_, "afp",
RewriteOptions::kFetcherProxy,
"Set the fetch proxy");
AddSystemProperty("", &SystemRewriteOptions::file_cache_path_, "afcp",
RewriteOptions::kFileCachePath,
"Set the path for file cache");
AddSystemProperty("", &SystemRewriteOptions::log_dir_, "ald",
RewriteOptions::kLogDir,
"Directory to store logs in.");
AddSystemProperty("", &SystemRewriteOptions::memcached_servers_, "ams",
RewriteOptions::kMemcachedServers,
"Comma-separated list of servers e.g. "
"host1:port1,host2:port2");
AddSystemProperty(1, &SystemRewriteOptions::memcached_threads_, "amt",
RewriteOptions::kMemcachedThreads,
"Number of background threads to use to run "
"memcached fetches");
AddSystemProperty(0, &SystemRewriteOptions::memcached_timeout_us_, "amo",
RewriteOptions::kMemcachedTimeoutUs,
"Maximum time in microseconds to allow for memcached "
"transactions");
AddSystemProperty(true, &SystemRewriteOptions::statistics_enabled_, "ase",
RewriteOptions::kStatisticsEnabled,
"Whether to collect cross-process statistics.");
AddSystemProperty("/pagespeed_statistics",
&SystemRewriteOptions::statistics_handler_path_, "ashp",
RewriteOptions::kStatisticsHandlerPath,
"Absolute path URL to statistics handler.");
AddSystemProperty("", &SystemRewriteOptions::statistics_logging_charts_css_,
"aslcc", RewriteOptions::kStatisticsLoggingChartsCSS,
"Where to find an offline copy of the Google Charts Tools "
"API CSS.");
AddSystemProperty("", &SystemRewriteOptions::statistics_logging_charts_js_,
"aslcj", RewriteOptions::kStatisticsLoggingChartsJS,
"Where to find an offline copy of the Google Charts Tools "
"API JS.");
AddSystemProperty(false, &SystemRewriteOptions::statistics_logging_enabled_,
"asle", RewriteOptions::kStatisticsLoggingEnabled,
"Whether to log statistics if they're being collected.");
AddSystemProperty(10 * Timer::kMinuteMs,
&SystemRewriteOptions::statistics_logging_interval_ms_,
"asli", RewriteOptions::kStatisticsLoggingIntervalMs,
"How often to log statistics, in milliseconds.");
// 2 Weeks of data w/ 10 minute intervals.
// Takes about 0.1s to parse 1MB file for modpagespeed.com/pagespeed_console
// TODO(sligocki): Increase once we have a better method for reading
// historical data.
AddSystemProperty(1 * 1024 /* 1 Megabytes */,
&SystemRewriteOptions::statistics_logging_max_file_size_kb_,
"aslfs", RewriteOptions::kStatisticsLoggingMaxFileSizeKb,
"Max size for statistics logging file.");
AddSystemProperty(true, &SystemRewriteOptions::use_shared_mem_locking_,
"ausml", RewriteOptions::kUseSharedMemLocking,
"Use shared memory for internal named lock service");
AddSystemProperty(Timer::kHourMs,
&SystemRewriteOptions::file_cache_clean_interval_ms_,
"afcci", RewriteOptions::kFileCacheCleanIntervalMs,
"Set the interval (in ms) for cleaning the file cache");
AddSystemProperty(100 * 1024 /* 100 megabytes */,
&SystemRewriteOptions::file_cache_clean_size_kb_,
"afc", RewriteOptions::kFileCacheCleanSizeKb,
"Set the target size (in kilobytes) for file cache");
// Default to no inode limit so that existing installations are not affected.
// pagespeed.conf.template contains suggested limit for new installations.
// TODO(morlovich): Inject this as an argument, since we want a different
// default for ngx_pagespeed?
AddSystemProperty(0, &SystemRewriteOptions::file_cache_clean_inode_limit_,
"afcl", RewriteOptions::kFileCacheCleanInodeLimit,
"Set the target number of inodes for the file cache; 0 "
"means no limit");
AddSystemProperty(0, &SystemRewriteOptions::lru_cache_byte_limit_, "alcb",
RewriteOptions::kLruCacheByteLimit,
"Set the maximum byte size entry to store in the "
"per-process in-memory LRU cache");
AddSystemProperty(0, &SystemRewriteOptions::lru_cache_kb_per_process_, "alcp",
RewriteOptions::kLruCacheKbPerProcess,
"Set the total size, in KB, of the per-process in-memory "
"LRU cache");
AddSystemProperty("", &SystemRewriteOptions::cache_flush_filename_, "acff",
RewriteOptions::kCacheFlushFilename,
"Name of file to check for timestamp updates used to flush "
"cache. This file will be relative to the "
"ModPagespeedFileCachePath if it does not begin with a "
"slash.");
AddSystemProperty(kDefaultCacheFlushIntervalSec,
&SystemRewriteOptions::cache_flush_poll_interval_sec_,
"acfpi", RewriteOptions::kCacheFlushPollIntervalSec,
"Number of seconds to wait between polling for cache-flush "
"requests");
AddSystemProperty(false,
&SystemRewriteOptions::compress_metadata_cache_,
"cc", RewriteOptions::kCompressMetadataCache,
"Whether to compress cache entries before writing them to "
"memory or disk.");
AddSystemProperty("", &SystemRewriteOptions::ssl_cert_directory_, "assld",
RewriteOptions::kSslCertDirectory,
"Directory to find SSL certificates.");
AddSystemProperty("", &SystemRewriteOptions::ssl_cert_file_, "asslf",
RewriteOptions::kSslCertFile,
"File with SSL certificates.");
AddSystemProperty("", &SystemRewriteOptions::slurp_directory_, "asd",
RewriteOptions::kSlurpDirectory,
"Directory from which to read slurped resources");
AddSystemProperty(false, &SystemRewriteOptions::test_proxy_, "atp",
RewriteOptions::kTestProxy,
"Direct non-PageSpeed URLs to a fetcher, acting as a "
"simple proxy. Meant for test use only");
AddSystemProperty("", &SystemRewriteOptions::test_proxy_slurp_, "atps",
RewriteOptions::kTestProxySlurp,
"If set, the fetcher used by the TestProxy mode will be a "
"readonly slurp fetcher from the given directory");
AddSystemProperty(false, &SystemRewriteOptions::slurp_read_only_, "asro",
RewriteOptions::kSlurpReadOnly,
"Only read from the slurped directory, fail to fetch "
"URLs not already in the slurped directory");
AddSystemProperty(false,
&SystemRewriteOptions::rate_limit_background_fetches_,
"rlbf",
RewriteOptions::kRateLimitBackgroundFetches,
"Rate-limit the number of background HTTP fetches done at "
"once");
AddSystemProperty(0, &SystemRewriteOptions::slurp_flush_limit_, "asfl",
RewriteOptions::kSlurpFlushLimit,
"Set the maximum byte size for the slurped content to hold "
"before a flush");
AddSystemProperty(false, &SystemRewriteOptions::disable_loopback_routing_,
"adlr",
"DangerPermitFetchFromUnknownHosts",
kProcessScopeStrict,
"Disable security checks that prohibit fetching from "
"hostnames mod_pagespeed does not know about");
AddSystemProperty(false, &SystemRewriteOptions::fetch_with_gzip_,
"afg", "FetchWithGzip", kProcessScope,
"Request http content from origin servers using gzip");
AddSystemProperty(1024 * 1024 * 10, /* 10 Megabytes */
&SystemRewriteOptions::ipro_max_response_bytes_,
"imrb", "IproMaxResponseBytes", kProcessScope,
"Limit allowed size of IPRO responses. "
"Set to 0 for unlimited.");
AddSystemProperty(10,
&SystemRewriteOptions::ipro_max_concurrent_recordings_,
"imcr", "IproMaxConcurrentRecordings", kProcessScope,
"Limit allowed number of IPRO recordings");
MergeSubclassProperties(system_properties_);
// We allow a special instantiation of the options with a null thread system
// because we are only updating the static properties on process startup; we
// won't have a thread-system yet or multiple threads.
//
// Leave slurp_read_only out of the signature as (a) we don't actually change
// this spontaneously, and (b) it's useful to keep the metadata cache between
// slurping read-only and slurp read/write.
SystemRewriteOptions config("dummy_options", NULL);
config.slurp_read_only_.DoNotUseForSignatureComputation();
}
SystemRewriteOptions* SystemRewriteOptions::Clone() const {
SystemRewriteOptions* options = NewOptions();
options->Merge(*this);
return options;
}
SystemRewriteOptions* SystemRewriteOptions::NewOptions() const {
return new SystemRewriteOptions("new_options", thread_system());
}
const SystemRewriteOptions* SystemRewriteOptions::DynamicCast(
const RewriteOptions* instance) {
const SystemRewriteOptions* config =
dynamic_cast<const SystemRewriteOptions*>(instance);
DCHECK(config != NULL);
return config;
}
SystemRewriteOptions* SystemRewriteOptions::DynamicCast(
RewriteOptions* instance) {
SystemRewriteOptions* config = dynamic_cast<SystemRewriteOptions*>(instance);
DCHECK(config != NULL);
return config;
}
} // namespace net_instaweb
|
Update StatisticsLogging defaults so that we only log once every 10 minutes and only store 1 MB of log data. This is still about 2 weeks of back-data, but takes only about 0.1s to parse the 1 MB file, whereas 100MB took about 10s, blocking /pagespeed_console render.
|
Update StatisticsLogging defaults so that we only log once every 10 minutes and only store 1 MB of log data. This is still about 2 weeks of back-data, but takes only about 0.1s to parse the 1 MB file, whereas 100MB took about 10s, blocking /pagespeed_console render.
We should really fix this to be more efficient in parsing in some way, but for now this should help people with default settings (especially those with cheap shared hosting).
|
C++
|
apache-2.0
|
patricmutwiri/mod_pagespeed,hashashin/src,pagespeed/mod_pagespeed,ajayanandgit/mod_pagespeed,ajayanandgit/mod_pagespeed,webscale-networks/mod_pagespeed,VersoBit/mod_pagespeed,VersoBit/mod_pagespeed,patricmutwiri/mod_pagespeed,patricmutwiri/mod_pagespeed,patricmutwiri/mod_pagespeed,webhost/mod_pagespeed,webscale-networks/mod_pagespeed,webhost/mod_pagespeed,webscale-networks/mod_pagespeed,pagespeed/mod_pagespeed,VersoBit/mod_pagespeed,VersoBit/mod_pagespeed,wanrui/mod_pagespeed,hashashin/src,ajayanandgit/mod_pagespeed,patricmutwiri/mod_pagespeed,hashashin/src,webscale-networks/mod_pagespeed,hashashin/src,jalonsoa/mod_pagespeed,webhost/mod_pagespeed,pagespeed/mod_pagespeed,patricmutwiri/mod_pagespeed,jalonsoa/mod_pagespeed,wanrui/mod_pagespeed,ajayanandgit/mod_pagespeed,jalonsoa/mod_pagespeed,webhost/mod_pagespeed,VersoBit/mod_pagespeed,hashashin/src,webhost/mod_pagespeed,patricmutwiri/mod_pagespeed,wanrui/mod_pagespeed,jalonsoa/mod_pagespeed,hashashin/src,wanrui/mod_pagespeed,webhost/mod_pagespeed,wanrui/mod_pagespeed,jalonsoa/mod_pagespeed,pagespeed/mod_pagespeed,wanrui/mod_pagespeed,wanrui/mod_pagespeed,webhost/mod_pagespeed,webscale-networks/mod_pagespeed,pagespeed/mod_pagespeed,webscale-networks/mod_pagespeed,VersoBit/mod_pagespeed,jalonsoa/mod_pagespeed,webhost/mod_pagespeed,wanrui/mod_pagespeed,pagespeed/mod_pagespeed,VersoBit/mod_pagespeed,jalonsoa/mod_pagespeed,hashashin/src,webscale-networks/mod_pagespeed,hashashin/src,pagespeed/mod_pagespeed,jalonsoa/mod_pagespeed,ajayanandgit/mod_pagespeed,patricmutwiri/mod_pagespeed,ajayanandgit/mod_pagespeed,ajayanandgit/mod_pagespeed,webscale-networks/mod_pagespeed,ajayanandgit/mod_pagespeed
|
dea467bdbd8a2b40f472e4a606b001db79d1b651
|
src/platforms/posix/px4_layer/px4_posix_tasks.cpp
|
src/platforms/posix/px4_layer/px4_posix_tasks.cpp
|
/****************************************************************************
*
* Copyright (C) 2015 Mark Charlebois. All rights reserved.
* Author: @author Mark Charlebois <charlebm#gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file px4_posix_tasks.c
* Implementation of existing task API for Linux
*/
#include <px4_log.h>
#include <px4_defines.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <stdbool.h>
#include <signal.h>
#include <fcntl.h>
#include <sched.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <limits.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string>
#include <px4_tasks.h>
#include <px4_posix.h>
#include <systemlib/err.h>
#define MAX_CMD_LEN 100
#define PX4_MAX_TASKS 50
#define SHELL_TASK_ID (PX4_MAX_TASKS+1)
pthread_t _shell_task_id = 0;
pthread_mutex_t task_mutex = PTHREAD_MUTEX_INITIALIZER;
struct task_entry {
pthread_t pid;
std::string name;
bool isused;
task_entry() : isused(false) {}
};
static task_entry taskmap[PX4_MAX_TASKS] = {};
typedef struct {
px4_main_t entry;
char name[16]; //pthread_setname_np is restricted to 16 chars
int argc;
char *argv[];
// strings are allocated after the struct data
} pthdata_t;
static void *entry_adapter(void *ptr)
{
pthdata_t *data = (pthdata_t *) ptr;
int rv;
// set the threads name
#ifdef __PX4_DARWIN
rv = pthread_setname_np(data->name);
#else
rv = pthread_setname_np(pthread_self(), data->name);
#endif
if (rv) {
PX4_ERR("px4_task_spawn_cmd: failed to set name of thread %d %d\n", rv, errno);
}
data->entry(data->argc, data->argv);
free(ptr);
PX4_DEBUG("Before px4_task_exit");
px4_task_exit(0);
PX4_DEBUG("After px4_task_exit");
return nullptr;
}
void
px4_systemreset(bool to_bootloader)
{
PX4_WARN("Called px4_system_reset");
exit(0);
}
px4_task_t px4_task_spawn_cmd(const char *name, int scheduler, int priority, int stack_size, px4_main_t entry,
char *const argv[])
{
int rv;
int argc = 0;
int i;
unsigned int len = 0;
unsigned long offset;
unsigned long structsize;
char *p = (char *)argv;
pthread_attr_t attr;
struct sched_param param = {};
// Calculate argc
while (p != (char *)nullptr) {
p = argv[argc];
if (p == (char *)nullptr) {
break;
}
++argc;
len += strlen(p) + 1;
}
structsize = sizeof(pthdata_t) + (argc + 1) * sizeof(char *);
// not safe to pass stack data to the thread creation
pthdata_t *taskdata = (pthdata_t *)malloc(structsize + len);
memset(taskdata, 0, structsize + len);
offset = ((unsigned long)taskdata) + structsize;
strncpy(taskdata->name, name, 16);
taskdata->name[15] = 0;
taskdata->entry = entry;
taskdata->argc = argc;
for (i = 0; i < argc; i++) {
PX4_DEBUG("arg %d %s\n", i, argv[i]);
taskdata->argv[i] = (char *)offset;
strcpy((char *)offset, argv[i]);
offset += strlen(argv[i]) + 1;
}
// Must add NULL at end of argv
taskdata->argv[argc] = (char *)nullptr;
PX4_DEBUG("starting task %s", name);
rv = pthread_attr_init(&attr);
if (rv != 0) {
PX4_ERR("px4_task_spawn_cmd: failed to init thread attrs");
free(taskdata);
return (rv < 0) ? rv : -rv;
}
#ifndef __PX4_DARWIN
if (stack_size < PTHREAD_STACK_MIN) {
stack_size = PTHREAD_STACK_MIN;
}
rv = pthread_attr_setstacksize(&attr, PX4_STACK_ADJUSTED(stack_size));
if (rv != 0) {
PX4_ERR("pthread_attr_setstacksize to %d returned error (%d)", stack_size, rv);
pthread_attr_destroy(&attr);
free(taskdata);
return (rv < 0) ? rv : -rv;
}
#endif
rv = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
if (rv != 0) {
PX4_ERR("px4_task_spawn_cmd: failed to set inherit sched");
pthread_attr_destroy(&attr);
free(taskdata);
return (rv < 0) ? rv : -rv;
}
rv = pthread_attr_setschedpolicy(&attr, scheduler);
if (rv != 0) {
PX4_ERR("px4_task_spawn_cmd: failed to set sched policy");
pthread_attr_destroy(&attr);
free(taskdata);
return (rv < 0) ? rv : -rv;
}
param.sched_priority = priority;
rv = pthread_attr_setschedparam(&attr, ¶m);
if (rv != 0) {
PX4_ERR("px4_task_spawn_cmd: failed to set sched param");
pthread_attr_destroy(&attr);
free(taskdata);
return (rv < 0) ? rv : -rv;
}
pthread_mutex_lock(&task_mutex);
int taskid = 0;
for (i = 0; i < PX4_MAX_TASKS; ++i) {
if (taskmap[i].isused == false) {
taskmap[i].name = name;
taskmap[i].isused = true;
taskid = i;
break;
}
}
if (i >= PX4_MAX_TASKS) {
pthread_attr_destroy(&attr);
pthread_mutex_unlock(&task_mutex);
free(taskdata);
return -ENOSPC;
}
rv = pthread_create(&taskmap[taskid].pid, &attr, &entry_adapter, (void *) taskdata);
if (rv != 0) {
if (rv == EPERM) {
//printf("WARNING: NOT RUNING AS ROOT, UNABLE TO RUN REALTIME THREADS\n");
rv = pthread_create(&taskmap[taskid].pid, nullptr, &entry_adapter, (void *) taskdata);
if (rv != 0) {
PX4_ERR("px4_task_spawn_cmd: failed to create thread %d %d\n", rv, errno);
taskmap[taskid].isused = false;
pthread_attr_destroy(&attr);
pthread_mutex_unlock(&task_mutex);
free(taskdata);
return (rv < 0) ? rv : -rv;
}
} else {
pthread_attr_destroy(&attr);
pthread_mutex_unlock(&task_mutex);
free(taskdata);
return (rv < 0) ? rv : -rv;
}
}
pthread_attr_destroy(&attr);
pthread_mutex_unlock(&task_mutex);
return i;
}
int px4_task_delete(px4_task_t id)
{
int rv = 0;
pthread_t pid;
PX4_DEBUG("Called px4_task_delete");
if (id < PX4_MAX_TASKS && taskmap[id].isused) {
pid = taskmap[id].pid;
} else {
return -EINVAL;
}
pthread_mutex_lock(&task_mutex);
// If current thread then exit, otherwise cancel
if (pthread_self() == pid) {
pthread_join(pid, nullptr);
taskmap[id].isused = false;
pthread_mutex_unlock(&task_mutex);
pthread_exit(nullptr);
} else {
rv = pthread_cancel(pid);
}
taskmap[id].isused = false;
pthread_mutex_unlock(&task_mutex);
return rv;
}
void px4_task_exit(int ret)
{
int i;
pthread_t pid = pthread_self();
// Get pthread ID from the opaque ID
for (i = 0; i < PX4_MAX_TASKS; ++i) {
if (taskmap[i].pid == pid) {
pthread_mutex_lock(&task_mutex);
taskmap[i].isused = false;
break;
}
}
if (i >= PX4_MAX_TASKS) {
PX4_ERR("px4_task_exit: self task not found!");
} else {
PX4_DEBUG("px4_task_exit: %s", taskmap[i].name.c_str());
}
pthread_mutex_unlock(&task_mutex);
pthread_exit((void *)(unsigned long)ret);
}
int px4_task_kill(px4_task_t id, int sig)
{
int rv = 0;
pthread_t pid;
PX4_DEBUG("Called px4_task_kill %d", sig);
if (id < PX4_MAX_TASKS && taskmap[id].isused && taskmap[id].pid != 0) {
pthread_mutex_lock(&task_mutex);
pid = taskmap[id].pid;
pthread_mutex_unlock(&task_mutex);
} else {
return -EINVAL;
}
// If current thread then exit, otherwise cancel
rv = pthread_kill(pid, sig);
return rv;
}
void px4_show_tasks()
{
int idx;
int count = 0;
PX4_INFO("Active Tasks:");
for (idx = 0; idx < PX4_MAX_TASKS; idx++) {
if (taskmap[idx].isused) {
PX4_INFO(" %-10s %lu", taskmap[idx].name.c_str(), (unsigned long)taskmap[idx].pid);
count++;
}
}
if (count == 0) {
PX4_INFO(" No running tasks");
}
}
bool px4_task_is_running(const char *taskname)
{
int idx;
for (idx = 0; idx < PX4_MAX_TASKS; idx++) {
if (taskmap[idx].isused && (strcmp(taskmap[idx].name.c_str(), taskname) == 0)) {
return true;
}
}
return false;
}
px4_task_t px4_getpid()
{
pthread_t pid = pthread_self();
px4_task_t ret = -1;
pthread_mutex_lock(&task_mutex);
for (int i = 0; i < PX4_MAX_TASKS; i++) {
if (taskmap[i].isused && taskmap[i].pid == pid) {
ret = i;
}
}
pthread_mutex_unlock(&task_mutex);
return ret;
}
const char *px4_get_taskname()
{
pthread_t pid = pthread_self();
const char *prog_name = "UnknownApp";
pthread_mutex_lock(&task_mutex);
for (int i = 0; i < PX4_MAX_TASKS; i++) {
if (taskmap[i].isused && taskmap[i].pid == pid) {
prog_name = taskmap[i].name.c_str();
}
}
pthread_mutex_unlock(&task_mutex);
return prog_name;
}
int px4_prctl(int option, const char *arg2, px4_task_t pid)
{
int rv;
switch (option) {
case PR_SET_NAME:
// set the threads name
#ifdef __PX4_DARWIN
rv = pthread_setname_np(arg2);
#else
rv = pthread_setname_np(pthread_self(), arg2);
#endif
break;
default:
rv = -1;
PX4_WARN("FAILED SETTING TASK NAME");
break;
}
return rv;
}
|
/****************************************************************************
*
* Copyright (C) 2015 Mark Charlebois. All rights reserved.
* Author: @author Mark Charlebois <charlebm#gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file px4_posix_tasks.c
* Implementation of existing task API for Linux
*/
#include <px4_log.h>
#include <px4_defines.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <stdbool.h>
#include <signal.h>
#include <fcntl.h>
#include <sched.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <limits.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string>
#include <px4_tasks.h>
#include <px4_posix.h>
#include <systemlib/err.h>
#define MAX_CMD_LEN 100
#define PX4_MAX_TASKS 100
#define SHELL_TASK_ID (PX4_MAX_TASKS+1)
pthread_t _shell_task_id = 0;
pthread_mutex_t task_mutex = PTHREAD_MUTEX_INITIALIZER;
struct task_entry {
pthread_t pid;
std::string name;
bool isused;
task_entry() : isused(false) {}
};
static task_entry taskmap[PX4_MAX_TASKS] = {};
typedef struct {
px4_main_t entry;
char name[16]; //pthread_setname_np is restricted to 16 chars
int argc;
char *argv[];
// strings are allocated after the struct data
} pthdata_t;
static void *entry_adapter(void *ptr)
{
pthdata_t *data = (pthdata_t *) ptr;
int rv;
// set the threads name
#ifdef __PX4_DARWIN
rv = pthread_setname_np(data->name);
#else
rv = pthread_setname_np(pthread_self(), data->name);
#endif
if (rv) {
PX4_ERR("px4_task_spawn_cmd: failed to set name of thread %d %d\n", rv, errno);
}
data->entry(data->argc, data->argv);
free(ptr);
PX4_DEBUG("Before px4_task_exit");
px4_task_exit(0);
PX4_DEBUG("After px4_task_exit");
return nullptr;
}
void
px4_systemreset(bool to_bootloader)
{
PX4_WARN("Called px4_system_reset");
exit(0);
}
px4_task_t px4_task_spawn_cmd(const char *name, int scheduler, int priority, int stack_size, px4_main_t entry,
char *const argv[])
{
int rv;
int argc = 0;
int i;
unsigned int len = 0;
unsigned long offset;
unsigned long structsize;
char *p = (char *)argv;
pthread_attr_t attr;
struct sched_param param = {};
// Calculate argc
while (p != (char *)nullptr) {
p = argv[argc];
if (p == (char *)nullptr) {
break;
}
++argc;
len += strlen(p) + 1;
}
structsize = sizeof(pthdata_t) + (argc + 1) * sizeof(char *);
// not safe to pass stack data to the thread creation
pthdata_t *taskdata = (pthdata_t *)malloc(structsize + len);
memset(taskdata, 0, structsize + len);
offset = ((unsigned long)taskdata) + structsize;
strncpy(taskdata->name, name, 16);
taskdata->name[15] = 0;
taskdata->entry = entry;
taskdata->argc = argc;
for (i = 0; i < argc; i++) {
PX4_DEBUG("arg %d %s\n", i, argv[i]);
taskdata->argv[i] = (char *)offset;
strcpy((char *)offset, argv[i]);
offset += strlen(argv[i]) + 1;
}
// Must add NULL at end of argv
taskdata->argv[argc] = (char *)nullptr;
PX4_DEBUG("starting task %s", name);
rv = pthread_attr_init(&attr);
if (rv != 0) {
PX4_ERR("px4_task_spawn_cmd: failed to init thread attrs");
free(taskdata);
return (rv < 0) ? rv : -rv;
}
#ifndef __PX4_DARWIN
if (stack_size < PTHREAD_STACK_MIN) {
stack_size = PTHREAD_STACK_MIN;
}
rv = pthread_attr_setstacksize(&attr, PX4_STACK_ADJUSTED(stack_size));
if (rv != 0) {
PX4_ERR("pthread_attr_setstacksize to %d returned error (%d)", stack_size, rv);
pthread_attr_destroy(&attr);
free(taskdata);
return (rv < 0) ? rv : -rv;
}
#endif
rv = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
if (rv != 0) {
PX4_ERR("px4_task_spawn_cmd: failed to set inherit sched");
pthread_attr_destroy(&attr);
free(taskdata);
return (rv < 0) ? rv : -rv;
}
rv = pthread_attr_setschedpolicy(&attr, scheduler);
if (rv != 0) {
PX4_ERR("px4_task_spawn_cmd: failed to set sched policy");
pthread_attr_destroy(&attr);
free(taskdata);
return (rv < 0) ? rv : -rv;
}
param.sched_priority = priority;
rv = pthread_attr_setschedparam(&attr, ¶m);
if (rv != 0) {
PX4_ERR("px4_task_spawn_cmd: failed to set sched param");
pthread_attr_destroy(&attr);
free(taskdata);
return (rv < 0) ? rv : -rv;
}
pthread_mutex_lock(&task_mutex);
int taskid = 0;
for (i = 0; i < PX4_MAX_TASKS; ++i) {
if (taskmap[i].isused == false) {
taskmap[i].name = name;
taskmap[i].isused = true;
taskid = i;
break;
}
}
if (i >= PX4_MAX_TASKS) {
pthread_attr_destroy(&attr);
pthread_mutex_unlock(&task_mutex);
free(taskdata);
return -ENOSPC;
}
rv = pthread_create(&taskmap[taskid].pid, &attr, &entry_adapter, (void *) taskdata);
if (rv != 0) {
if (rv == EPERM) {
//printf("WARNING: NOT RUNING AS ROOT, UNABLE TO RUN REALTIME THREADS\n");
rv = pthread_create(&taskmap[taskid].pid, nullptr, &entry_adapter, (void *) taskdata);
if (rv != 0) {
PX4_ERR("px4_task_spawn_cmd: failed to create thread %d %d\n", rv, errno);
taskmap[taskid].isused = false;
pthread_attr_destroy(&attr);
pthread_mutex_unlock(&task_mutex);
free(taskdata);
return (rv < 0) ? rv : -rv;
}
} else {
pthread_attr_destroy(&attr);
pthread_mutex_unlock(&task_mutex);
free(taskdata);
return (rv < 0) ? rv : -rv;
}
}
pthread_attr_destroy(&attr);
pthread_mutex_unlock(&task_mutex);
return i;
}
int px4_task_delete(px4_task_t id)
{
int rv = 0;
pthread_t pid;
PX4_DEBUG("Called px4_task_delete");
if (id < PX4_MAX_TASKS && taskmap[id].isused) {
pid = taskmap[id].pid;
} else {
return -EINVAL;
}
pthread_mutex_lock(&task_mutex);
// If current thread then exit, otherwise cancel
if (pthread_self() == pid) {
pthread_join(pid, nullptr);
taskmap[id].isused = false;
pthread_mutex_unlock(&task_mutex);
pthread_exit(nullptr);
} else {
rv = pthread_cancel(pid);
}
taskmap[id].isused = false;
pthread_mutex_unlock(&task_mutex);
return rv;
}
void px4_task_exit(int ret)
{
int i;
pthread_t pid = pthread_self();
// Get pthread ID from the opaque ID
for (i = 0; i < PX4_MAX_TASKS; ++i) {
if (taskmap[i].pid == pid) {
pthread_mutex_lock(&task_mutex);
taskmap[i].isused = false;
break;
}
}
if (i >= PX4_MAX_TASKS) {
PX4_ERR("px4_task_exit: self task not found!");
} else {
PX4_DEBUG("px4_task_exit: %s", taskmap[i].name.c_str());
}
pthread_mutex_unlock(&task_mutex);
pthread_exit((void *)(unsigned long)ret);
}
int px4_task_kill(px4_task_t id, int sig)
{
int rv = 0;
pthread_t pid;
PX4_DEBUG("Called px4_task_kill %d", sig);
if (id < PX4_MAX_TASKS && taskmap[id].isused && taskmap[id].pid != 0) {
pthread_mutex_lock(&task_mutex);
pid = taskmap[id].pid;
pthread_mutex_unlock(&task_mutex);
} else {
return -EINVAL;
}
// If current thread then exit, otherwise cancel
rv = pthread_kill(pid, sig);
return rv;
}
void px4_show_tasks()
{
int idx;
int count = 0;
PX4_INFO("Active Tasks:");
for (idx = 0; idx < PX4_MAX_TASKS; idx++) {
if (taskmap[idx].isused) {
PX4_INFO(" %-10s %lu", taskmap[idx].name.c_str(), (unsigned long)taskmap[idx].pid);
count++;
}
}
if (count == 0) {
PX4_INFO(" No running tasks");
}
}
bool px4_task_is_running(const char *taskname)
{
int idx;
for (idx = 0; idx < PX4_MAX_TASKS; idx++) {
if (taskmap[idx].isused && (strcmp(taskmap[idx].name.c_str(), taskname) == 0)) {
return true;
}
}
return false;
}
px4_task_t px4_getpid()
{
pthread_t pid = pthread_self();
px4_task_t ret = -1;
pthread_mutex_lock(&task_mutex);
for (int i = 0; i < PX4_MAX_TASKS; i++) {
if (taskmap[i].isused && taskmap[i].pid == pid) {
ret = i;
}
}
pthread_mutex_unlock(&task_mutex);
return ret;
}
const char *px4_get_taskname()
{
pthread_t pid = pthread_self();
const char *prog_name = "UnknownApp";
pthread_mutex_lock(&task_mutex);
for (int i = 0; i < PX4_MAX_TASKS; i++) {
if (taskmap[i].isused && taskmap[i].pid == pid) {
prog_name = taskmap[i].name.c_str();
}
}
pthread_mutex_unlock(&task_mutex);
return prog_name;
}
int px4_prctl(int option, const char *arg2, px4_task_t pid)
{
int rv;
switch (option) {
case PR_SET_NAME:
// set the threads name
#ifdef __PX4_DARWIN
rv = pthread_setname_np(arg2);
#else
rv = pthread_setname_np(pthread_self(), arg2);
#endif
break;
default:
rv = -1;
PX4_WARN("FAILED SETTING TASK NAME");
break;
}
return rv;
}
|
Make sure we do not run out of PX4 file descriptors
|
POSIX: Make sure we do not run out of PX4 file descriptors
|
C++
|
bsd-3-clause
|
acfloria/Firmware,mcgill-robotics/Firmware,krbeverx/Firmware,Aerotenna/Firmware,krbeverx/Firmware,krbeverx/Firmware,mje-nz/PX4-Firmware,Aerotenna/Firmware,PX4/Firmware,acfloria/Firmware,mcgill-robotics/Firmware,Aerotenna/Firmware,mcgill-robotics/Firmware,jlecoeur/Firmware,Aerotenna/Firmware,PX4/Firmware,PX4/Firmware,dagar/Firmware,jlecoeur/Firmware,dagar/Firmware,krbeverx/Firmware,krbeverx/Firmware,mcgill-robotics/Firmware,jlecoeur/Firmware,Aerotenna/Firmware,mcgill-robotics/Firmware,dagar/Firmware,mje-nz/PX4-Firmware,mje-nz/PX4-Firmware,dagar/Firmware,dagar/Firmware,Aerotenna/Firmware,krbeverx/Firmware,acfloria/Firmware,acfloria/Firmware,mje-nz/PX4-Firmware,mcgill-robotics/Firmware,dagar/Firmware,PX4/Firmware,Aerotenna/Firmware,mje-nz/PX4-Firmware,PX4/Firmware,acfloria/Firmware,PX4/Firmware,acfloria/Firmware,krbeverx/Firmware,jlecoeur/Firmware,jlecoeur/Firmware,mje-nz/PX4-Firmware,dagar/Firmware,PX4/Firmware,jlecoeur/Firmware,jlecoeur/Firmware,acfloria/Firmware,mcgill-robotics/Firmware,jlecoeur/Firmware,mje-nz/PX4-Firmware
|
637f0155ac3effeceda3ed49e8a1e41700bcaf63
|
stan/math/prim/mat/prob/ordered_logistic_lpmf.hpp
|
stan/math/prim/mat/prob/ordered_logistic_lpmf.hpp
|
#ifndef STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_LPMF_HPP
#define STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_LPMF_HPP
#include <stan/math/prim/mat/fun/value_of.hpp>
#include <stan/math/prim/mat/fun/size.hpp>
#include <stan/math/prim/mat/meta/vector_seq_view.hpp>
#include <stan/math/prim/mat/err/check_ordered.hpp>
#include <stan/math/prim/scal/fun/inv_logit.hpp>
#include <stan/math/prim/scal/fun/log1p_exp.hpp>
#include <stan/math/prim/scal/fun/log_inv_logit_diff.hpp>
#include <stan/math/prim/scal/err/check_bounded.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/scal/err/check_greater.hpp>
#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>
#include <stan/math/prim/scal/meta/include_summand.hpp>
#include <stan/math/prim/scal/meta/return_type.hpp>
#include <stan/math/prim/scal/meta/partials_return_type.hpp>
#include <stan/math/prim/scal/meta/operands_and_partials.hpp>
#include <stan/math/prim/scal/meta/is_constant_struct.hpp>
#include <stan/math/prim/scal/meta/scalar_seq_view.hpp>
#include <vector>
namespace stan {
namespace math {
template <typename T>
struct ordLog_helper {
/**
* Returns the (natural) log probability of the specified integer
* outcome given the continuous location and specified cutpoints
* in an ordered logistic model.
*
* Error-checking handled by main distribution functions, with this
* function only called once inputs have been validated.
*
* @tparam T Type of location & cutpoint variables.
* @param y Outcome.
* @param K Number of categories.
* @param lambda Location.
* @param c Positive increasing vector of cutpoints.
* @return Log probability of outcome given location and
* cutpoints.
*/
T logp(const int& y, const int& K, const T& lambda,
const Eigen::Matrix<T, Eigen::Dynamic, 1>& c) {
if (y == 1)
return -log1p_exp(lambda - c[0]);
else if (y == K)
return -log1p_exp(c[K - 2] - lambda);
else
return log_inv_logit_diff(lambda - c[y - 2], lambda - c[y - 1]);
}
/**
* Returns a vector with the gradients of the the continuous location
* and ordered cutpoints in an ordered logistic model. The first element
* of the vector contains the gradient for the location variable (lambda),
* followed by the gradients for the ordered cutpoints (c).
*
* Error-checking handled by main distribution functions, with this
* function only called once inputs have been validated.
*
* @tparam T Type of location & cutpoint variables.
* @param y Outcome.
* @param K Number of categories.
* @param lambda Location.
* @param c Positive increasing vector of cutpoints.
* @return Vector of gradients.
*/
Eigen::Matrix<T, Eigen::Dynamic, 1> deriv(
const int& y, const int& K, const T& lambda,
const Eigen::Matrix<T, Eigen::Dynamic, 1>& c) {
using std::exp;
Eigen::Matrix<T, Eigen::Dynamic, 1> d(
Eigen::Matrix<T, Eigen::Dynamic, 1>::Zero(K));
if (y == 1) {
d[0] -= inv_logit(lambda - c[0]);
d[1] -= d[0];
return d;
} else if (y == K) {
d[0] += inv_logit(c[K - 2] - lambda);
d[K - 1] -= d[0];
return d;
} else {
d[y - 1]
+= inv(1 - exp(c[y - 1] - c[y - 2])) - inv_logit(c[y - 2] - lambda);
d[y] += inv(1 - exp(c[y - 2] - c[y - 1])) - inv_logit(c[y - 1] - lambda);
d[0] -= d[y] + d[y - 1];
return d;
}
}
};
/**
* Returns the (natural) log probability of the specified array
* of integers given the vector of continuous locations and
* specified cutpoints in an ordered logistic model.
*
* <p>Typically the continous location
* will be the dot product of a vector of regression coefficients
* and a vector of predictors for the outcome.
*
* @tparam propto True if calculating up to a proportion.
* @tparam T_loc Location type.
* @tparam T_cut Cut-point type.
* @param y Array of integers
* @param lambda Vector of continuous location variables.
* @param c Positive increasing vector of cutpoints.
* @return Log probability of outcome given location and
* cutpoints.
* @throw std::domain_error If the outcome is not between 1 and
* the number of cutpoints plus 2; if the cutpoint vector is
* empty; if the cutpoint vector contains a non-positive,
* non-finite value; or if the cutpoint vector is not sorted in
* ascending order.
* @throw std::invalid_argument If y and lambda are different
* lengths.
*/
template <bool propto, typename T_y, typename T_loc, typename T_cut>
typename return_type<T_loc, T_cut>::type ordered_logistic_lpmf(
const T_y& y, const T_loc& lambda, const T_cut& c) {
static const char* function = "ordered_logistic";
typedef
typename stan::partials_return_type<T_loc, T_cut>::type T_partials_return;
typedef typename Eigen::Matrix<T_partials_return, -1, 1> T_partials_vec;
scalar_seq_view<T_loc> lam_vec(lambda);
scalar_seq_view<T_y> y_vec(y);
vector_seq_view<T_cut> c_vec(c);
int K = c_vec[0].size() + 1;
int N = length(lambda);
check_consistent_sizes(function, "Integers", y, "Locations", lambda);
for (int n = 0; n < N; n++) {
check_bounded(function, "Random variable", y_vec[n], 1, K);
check_finite(function, "Location parameter", lam_vec[n]);
}
for (size_t i = 0, size_ = length(c_vec); i < size_; i++) {
check_ordered(function, "Cut-points", c_vec[i]);
check_greater(function, "Size of cut points parameter", c_vec[i].size(), 0);
check_finite(function, "Final cut-point", c_vec[i](c_vec[i].size() - 1));
check_finite(function, "First cut-point", c_vec[i](0));
}
ordLog_helper<T_partials_return> ordhelp;
operands_and_partials<T_loc, T_cut> ops_partials(lambda, c);
T_partials_return logp(0.0);
for (int n = 0; n < N; ++n) {
for (size_t i = 0, size_ = length(c_vec); i < size_; i++) {
T_partials_return lam_dbl = value_of(lam_vec[n]);
T_partials_vec c_dbl
= value_of(c_vec[i]).template cast<T_partials_return>();
T_partials_vec d = ordhelp.deriv(y_vec[n], K, lam_dbl, c_dbl);
logp += ordhelp.logp(y_vec[n], K, lam_dbl, c_dbl);
if (!is_constant_struct<T_loc>::value)
ops_partials.edge1_.partials_[n] = d[0];
if (!is_constant_struct<T_cut>::value)
ops_partials.edge2_.partials_vec_[n] += d.tail(K - 1);
}
}
return ops_partials.build(logp);
}
template <typename T_y, typename T_loc, typename T_cut>
typename return_type<T_loc, T_cut>::type ordered_logistic_lpmf(
const T_y& y, const T_loc& lambda, const T_cut& c) {
return ordered_logistic_lpmf<false>(y, lambda, c);
}
} // namespace math
} // namespace stan
#endif
|
#ifndef STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_LPMF_HPP
#define STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_LPMF_HPP
#include <stan/math/prim/mat/fun/value_of.hpp>
#include <stan/math/prim/mat/fun/size.hpp>
#include <stan/math/prim/mat/meta/vector_seq_view.hpp>
#include <stan/math/prim/mat/meta/length_mvt.hpp>
#include <stan/math/prim/mat/err/check_ordered.hpp>
#include <stan/math/prim/scal/fun/inv_logit.hpp>
#include <stan/math/prim/scal/fun/log1p_exp.hpp>
#include <stan/math/prim/scal/fun/log_inv_logit_diff.hpp>
#include <stan/math/prim/scal/err/check_bounded.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/scal/err/check_greater.hpp>
#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>
#include <stan/math/prim/scal/meta/include_summand.hpp>
#include <stan/math/prim/scal/meta/return_type.hpp>
#include <stan/math/prim/scal/meta/partials_return_type.hpp>
#include <stan/math/prim/scal/meta/operands_and_partials.hpp>
#include <stan/math/prim/scal/meta/is_constant_struct.hpp>
#include <stan/math/prim/scal/meta/scalar_seq_view.hpp>
#include <vector>
namespace stan {
namespace math {
/**
* Returns the (natural) log probability of the specified array
* of integers given the vector of continuous locations and
* specified cutpoints in an ordered logistic model.
*
* <p>Typically the continous location
* will be the dot product of a vector of regression coefficients
* and a vector of predictors for the outcome.
*
* @tparam propto True if calculating up to a proportion.
* @tparam T_loc Location type.
* @tparam T_cut Cut-point type.
* @param y Array of integers
* @param lambda Vector of continuous location variables.
* @param c Positive increasing vector of cutpoints.
* @return Log probability of outcome given location and
* cutpoints.
* @throw std::domain_error If the outcome is not between 1 and
* the number of cutpoints plus 2; if the cutpoint vector is
* empty; if the cutpoint vector contains a non-positive,
* non-finite value; or if the cutpoint vector is not sorted in
* ascending order.
* @throw std::invalid_argument If y and lambda are different
* lengths.
*/
template <bool propto, typename T_y, typename T_loc, typename T_cut>
typename return_type<T_loc, T_cut>::type ordered_logistic_lpmf(
const T_y& y, const T_loc& lambda, const T_cut& c) {
static const char* function = "ordered_logistic";
typedef
typename stan::partials_return_type<T_loc, T_cut>::type T_partials_return;
typedef typename Eigen::Matrix<T_partials_return, -1, 1> T_partials_vec;
scalar_seq_view<T_loc> lam_vec(lambda);
scalar_seq_view<T_y> y_vec(y);
vector_seq_view<T_cut> c_vec(c);
int K = c_vec[0].size() + 1;
int N = length(lambda);
check_consistent_sizes(function, "Integers", y, "Locations", lambda);
for (int n = 0; n < N; n++) {
check_bounded(function, "Random variable", y_vec[n], 1, K);
check_finite(function, "Location parameter", lam_vec[n]);
}
for (size_t i = 0, size_ = length_mvt(c); i < size_; i++) {
check_ordered(function, "Cut-points", c_vec[i]);
check_greater(function, "Size of cut points parameter", c_vec[i].size(), 0);
check_finite(function, "Final cut-point", c_vec[i](c_vec[i].size() - 1));
check_finite(function, "First cut-point", c_vec[i](0));
}
operands_and_partials<T_loc, T_cut> ops_partials(lambda, c);
T_partials_return logp(0.0);
for (int n = 0; n < N; ++n) {
int i = length_mvt(c) == 1 ? 0 : n;
T_partials_vec c_dbl
= value_of(c_vec[i]).template cast<T_partials_return>();
T_partials_return lam_dbl = value_of(lam_vec[n]);
T_partials_vec d(T_partials_vec::Zero(K-1));
if (y_vec[n] == 1) {
d[0] = inv_logit(lam_dbl - c_dbl[0]);
logp -= log1p_exp(lam_dbl - c_dbl[0]);
} else if (y_vec[n] == K) {
d[K - 2] -= inv_logit(c_dbl[K - 2] - lam_dbl);
logp -= log1p_exp(c_dbl[K - 2] - lam_dbl);
} else {
d[y_vec[n] - 2]
+= inv(1 - exp(c_dbl[y_vec[n] - 1] - c_dbl[y_vec[n] - 2]))
- inv_logit(c_dbl[y_vec[n] - 2] - lam_dbl);
d[y_vec[n] - 1]
+= inv(1 - exp(c_dbl[y_vec[n] - 2] - c_dbl[y_vec[n] - 1]))
- inv_logit(c_dbl[y_vec[n] - 1] - lam_dbl);
logp += log_inv_logit_diff(lam_dbl - c_dbl[y_vec[n] - 2],
lam_dbl - c_dbl[y_vec[n] - 1]);
}
if (!is_constant_struct<T_loc>::value)
ops_partials.edge1_.partials_[n] -= d.sum();
if (!is_constant_struct<T_cut>::value)
ops_partials.edge2_.partials_vec_[n] += d;
}
return ops_partials.build(logp);
}
template <typename T_y, typename T_loc, typename T_cut>
typename return_type<T_loc, T_cut>::type ordered_logistic_lpmf(
const T_y& y, const T_loc& lambda, const T_cut& c) {
return ordered_logistic_lpmf<false>(y, lambda, c);
}
} // namespace math
} // namespace stan
#endif
|
Move log-prob and gradient calc back into main function
|
Move log-prob and gradient calc back into main function
|
C++
|
bsd-3-clause
|
stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math
|
064a89b5c215afa779548ecb09706a022f83f7df
|
Core/Code/Testing/mitkLogTest.cpp
|
Core/Code/Testing/mitkLogTest.cpp
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkCommon.h"
#include "mitkTestingMacros.h"
#include <mitkLog.h>
#include <mitkVector.h>
#include <itkMultiThreader.h>
#include <itksys/SystemTools.hxx>
#include <mitkStandardFileLocations.h>
/** Documentation
*
* @brief Objects of this class can start an internal thread by calling the Start() method.
* The thread is then logging messages until the method Stop() is called. The class
* can be used to test if logging is thread-save by using multiple objects and let
* them log simuntanously.
*/
class mitkTestLoggingThread
{
protected:
bool LoggingRunning;
int ThreadID;
itk::MultiThreader::Pointer m_MultiThreader;
void LogMessages()
{
while(LoggingRunning)
{
MITK_INFO << "Test info stream in thread " << ThreadID;
MITK_WARN << "Test warning stream in thread " << ThreadID;
MITK_DEBUG << "Test debugging stream in thread " << ThreadID;
MITK_ERROR << "Test error stream in thread " << ThreadID;
MITK_FATAL << "Test fatal stream in thread " << ThreadID;
}
}
static ITK_THREAD_RETURN_TYPE ThreadStartTracking(void* pInfoStruct)
{
/* extract this pointer from Thread Info structure */
struct itk::MultiThreader::ThreadInfoStruct * pInfo = (struct itk::MultiThreader::ThreadInfoStruct*)pInfoStruct;
if (pInfo == NULL)
{
return ITK_THREAD_RETURN_VALUE;
}
if (pInfo->UserData == NULL)
{
return ITK_THREAD_RETURN_VALUE;
}
mitkTestLoggingThread *thisthread = (mitkTestLoggingThread*)pInfo->UserData;
if (thisthread != NULL)
thisthread->LogMessages();
return ITK_THREAD_RETURN_VALUE;
}
public:
mitkTestLoggingThread(int number, itk::MultiThreader::Pointer MultiThreader)
{
ThreadID = number;
m_MultiThreader = MultiThreader;
}
void Start()
{
LoggingRunning = true;
m_MultiThreader->SpawnThread(this->ThreadStartTracking, this);
}
void Stop()
{
LoggingRunning = false;
}
};
/** Documentation
*
* @brief This class holds static test methods to sturcture the test of the mitk logging mechanism.
*/
class mitkLogTestClass
{
public:
static void TestSimpleLog()
{
bool testSucceded = true;
try
{
MITK_INFO << "Test info stream.";
MITK_WARN << "Test warning stream.";
MITK_DEBUG << "Test debugging stream."; //only activated if cmake variable is on!
//so no worries if you see no output for this line
MITK_ERROR << "Test error stream.";
MITK_FATAL << "Test fatal stream.";
}
catch(mitk::Exception e)
{
testSucceded = false;
}
MITK_TEST_CONDITION_REQUIRED(testSucceded,"Test logging streams.");
}
static void TestObjectInfoLogging()
{
bool testSucceded = true;
try
{
int i = 123;
float f = .32234;
double d = 123123;
std::string testString = "testString";
std::stringstream testStringStream;
testStringStream << "test" << "String" << "Stream";
mitk::Point3D testMitkPoint;
testMitkPoint.Fill(2);
MITK_INFO << i;
MITK_INFO << f;
MITK_INFO << d;
MITK_INFO << testString;
MITK_INFO << testStringStream;
MITK_INFO << testMitkPoint;
}
catch(mitk::Exception e)
{
testSucceded = false;
}
MITK_TEST_CONDITION_REQUIRED(testSucceded,"Test logging of object information.");
}
static void TestThreadSaveLog()
{
bool testSucceded = true;
try
{
//initialize two threads...
itk::MultiThreader::Pointer myThreader = itk::MultiThreader::New();
mitkTestLoggingThread myThreadClass1 = mitkTestLoggingThread(1,myThreader);
mitkTestLoggingThread myThreadClass2 = mitkTestLoggingThread(2,myThreader);
//start them
myThreadClass1.Start();
myThreadClass2.Start();
//wait for 500 ms
itksys::SystemTools::Delay(500);
//stop them
myThreadClass1.Stop();
myThreadClass2.Stop();
//sleep again to let all threads end
itksys::SystemTools::Delay(500);
}
catch(...)
{
testSucceded = false;
}
//if no error occured until now, everything is ok
MITK_TEST_CONDITION_REQUIRED(testSucceded,"Test logging in different threads.");
}
static void TestLoggingToFile()
{
std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory() + "/testlog.log";
mitk::LoggingBackend::SetLogFile(filename.c_str());
MITK_INFO << "Test logging to default filename: " << mitk::LoggingBackend::GetLogFile();
MITK_TEST_CONDITION_REQUIRED(itksys::SystemTools::FileExists(filename.c_str()),"Testing if log file exists.");
//TODO delete log file?
}
static void TestAddAndRemoveBackends()
{
mbilog::BackendCout myBackend = mbilog::BackendCout();
mbilog::RegisterBackend(&myBackend);
MITK_INFO << "Test logging";
mbilog::UnregisterBackend(&myBackend);
//if no error occured until now, everything is ok
MITK_TEST_CONDITION_REQUIRED(true,"Test add/remove logging backend.");
}
static void TestDefaultBackend()
{
//not possible now, because we cannot unregister the mitk logging backend in the moment. If such a method is added to mbilog utility one may add this test.
}
};
int mitkLogTest(int /* argc */, char* /*argv*/[])
{
// always start with this!
MITK_TEST_BEGIN("Log")
MITK_TEST_OUTPUT(<<"TESTING ALL LOGGING OUTPUTS, ERROR MESSAGES ARE ALSO TESTED AND NOT MEANING AN ERROR OCCURED!")
mitkLogTestClass::TestSimpleLog();
mitkLogTestClass::TestObjectInfoLogging();
mitkLogTestClass::TestThreadSaveLog();
mitkLogTestClass::TestLoggingToFile();
mitkLogTestClass::TestAddAndRemoveBackends();
// always end with this!
MITK_TEST_END()
}
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkCommon.h"
#include "mitkTestingMacros.h"
#include <mitkLog.h>
#include <mitkVector.h>
#include <itkMultiThreader.h>
#include <itksys/SystemTools.hxx>
#include <mitkStandardFileLocations.h>
/** Documentation
*
* @brief Objects of this class can start an internal thread by calling the Start() method.
* The thread is then logging messages until the method Stop() is called. The class
* can be used to test if logging is thread-save by using multiple objects and let
* them log simuntanously.
*/
class mitkTestLoggingThread
{
protected:
bool LoggingRunning;
int ThreadID;
itk::MultiThreader::Pointer m_MultiThreader;
void LogMessages()
{
while(LoggingRunning)
{
MITK_INFO << "Test info stream in thread " << ThreadID;
MITK_WARN << "Test warning stream in thread " << ThreadID;
MITK_DEBUG << "Test debugging stream in thread " << ThreadID;
MITK_ERROR << "Test error stream in thread " << ThreadID;
MITK_FATAL << "Test fatal stream in thread " << ThreadID;
}
}
static ITK_THREAD_RETURN_TYPE ThreadStartTracking(void* pInfoStruct)
{
/* extract this pointer from Thread Info structure */
struct itk::MultiThreader::ThreadInfoStruct * pInfo = (struct itk::MultiThreader::ThreadInfoStruct*)pInfoStruct;
if (pInfo == NULL)
{
return ITK_THREAD_RETURN_VALUE;
}
if (pInfo->UserData == NULL)
{
return ITK_THREAD_RETURN_VALUE;
}
mitkTestLoggingThread *thisthread = (mitkTestLoggingThread*)pInfo->UserData;
if (thisthread != NULL)
thisthread->LogMessages();
return ITK_THREAD_RETURN_VALUE;
}
public:
mitkTestLoggingThread(int number, itk::MultiThreader::Pointer MultiThreader)
{
ThreadID = number;
m_MultiThreader = MultiThreader;
}
void Start()
{
LoggingRunning = true;
m_MultiThreader->SpawnThread(this->ThreadStartTracking, this);
}
void Stop()
{
LoggingRunning = false;
}
};
/** Documentation
*
* @brief This class holds static test methods to sturcture the test of the mitk logging mechanism.
*/
class mitkLogTestClass
{
public:
static void TestSimpleLog()
{
bool testSucceded = true;
try
{
MITK_INFO << "Test info stream.";
MITK_WARN << "Test warning stream.";
MITK_DEBUG << "Test debugging stream."; //only activated if cmake variable is on!
//so no worries if you see no output for this line
MITK_ERROR << "Test error stream.";
MITK_FATAL << "Test fatal stream.";
}
catch(mitk::Exception e)
{
testSucceded = false;
}
MITK_TEST_CONDITION_REQUIRED(testSucceded,"Test logging streams.");
}
static void TestObjectInfoLogging()
{
bool testSucceded = true;
try
{
int i = 123;
float f = .32234;
double d = 123123;
std::string testString = "testString";
std::stringstream testStringStream;
testStringStream << "test" << "String" << "Stream";
mitk::Point3D testMitkPoint;
testMitkPoint.Fill(2);
MITK_INFO << i;
MITK_INFO << f;
MITK_INFO << d;
MITK_INFO << testString;
MITK_INFO << testStringStream;
MITK_INFO << testMitkPoint;
}
catch(mitk::Exception e)
{
testSucceded = false;
}
MITK_TEST_CONDITION_REQUIRED(testSucceded,"Test logging of object information.");
}
static void TestThreadSaveLog()
{
bool testSucceded = true;
try
{
//initialize two threads...
itk::MultiThreader::Pointer myThreader = itk::MultiThreader::New();
mitkTestLoggingThread myThreadClass1 = mitkTestLoggingThread(1,myThreader);
mitkTestLoggingThread myThreadClass2 = mitkTestLoggingThread(2,myThreader);
//start them
myThreadClass1.Start();
myThreadClass2.Start();
//wait for 500 ms
itksys::SystemTools::Delay(500);
//stop them
myThreadClass1.Stop();
myThreadClass2.Stop();
//Wait for all threads to end
myThreader->TerminateThread(1);
myThreader->TerminateThread(2);
}
catch(...)
{
testSucceded = false;
}
//if no error occured until now, everything is ok
MITK_TEST_CONDITION_REQUIRED(testSucceded,"Test logging in different threads.");
}
static void TestLoggingToFile()
{
std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory() + "/testlog.log";
mitk::LoggingBackend::SetLogFile(filename.c_str());
MITK_INFO << "Test logging to default filename: " << mitk::LoggingBackend::GetLogFile();
MITK_TEST_CONDITION_REQUIRED(itksys::SystemTools::FileExists(filename.c_str()),"Testing if log file exists.");
//TODO delete log file?
}
static void TestAddAndRemoveBackends()
{
mbilog::BackendCout myBackend = mbilog::BackendCout();
mbilog::RegisterBackend(&myBackend);
MITK_INFO << "Test logging";
mbilog::UnregisterBackend(&myBackend);
//if no error occured until now, everything is ok
MITK_TEST_CONDITION_REQUIRED(true,"Test add/remove logging backend.");
}
static void TestDefaultBackend()
{
//not possible now, because we cannot unregister the mitk logging backend in the moment. If such a method is added to mbilog utility one may add this test.
}
};
int mitkLogTest(int /* argc */, char* /*argv*/[])
{
// always start with this!
MITK_TEST_BEGIN("Log")
MITK_TEST_OUTPUT(<<"TESTING ALL LOGGING OUTPUTS, ERROR MESSAGES ARE ALSO TESTED AND NOT MEANING AN ERROR OCCURED!")
mitkLogTestClass::TestSimpleLog();
mitkLogTestClass::TestObjectInfoLogging();
mitkLogTestClass::TestThreadSaveLog();
mitkLogTestClass::TestLoggingToFile();
mitkLogTestClass::TestAddAndRemoveBackends();
// always end with this!
MITK_TEST_END()
}
|
Call of method to wait for threads to end added
|
Call of method to wait for threads to end added
|
C++
|
bsd-3-clause
|
danielknorr/MITK,lsanzdiaz/MITK-BiiG,iwegner/MITK,rfloca/MITK,rfloca/MITK,NifTK/MITK,iwegner/MITK,NifTK/MITK,nocnokneo/MITK,MITK/MITK,NifTK/MITK,RabadanLab/MITKats,MITK/MITK,nocnokneo/MITK,fmilano/mitk,MITK/MITK,MITK/MITK,danielknorr/MITK,nocnokneo/MITK,RabadanLab/MITKats,rfloca/MITK,nocnokneo/MITK,MITK/MITK,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,NifTK/MITK,nocnokneo/MITK,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,NifTK/MITK,rfloca/MITK,rfloca/MITK,lsanzdiaz/MITK-BiiG,danielknorr/MITK,RabadanLab/MITKats,fmilano/mitk,nocnokneo/MITK,NifTK/MITK,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,danielknorr/MITK,danielknorr/MITK,rfloca/MITK,rfloca/MITK,fmilano/mitk,fmilano/mitk,lsanzdiaz/MITK-BiiG,iwegner/MITK,fmilano/mitk,iwegner/MITK,fmilano/mitk,iwegner/MITK,MITK/MITK,iwegner/MITK,danielknorr/MITK,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,danielknorr/MITK,RabadanLab/MITKats,fmilano/mitk
|
9296c56739a9afec793463441e85f5267d2859a5
|
src/contextify.cc
|
src/contextify.cc
|
#include "node.h"
#include "node_version.h"
#include "nan.h"
#include <string>
using namespace v8;
using namespace node;
class ContextWrap;
class ContextifyContext : public Nan::ObjectWrap {
public:
Nan::Persistent<Context> context;
Nan::Persistent<Object> sandbox;
Nan::Persistent<Object> proxyGlobal;
static Nan::Persistent<FunctionTemplate> jsTmpl;
ContextifyContext(Local<Object> sbox) {
Nan::HandleScope scope;
sandbox.Reset(sbox);
}
~ContextifyContext() {
context.Reset();
proxyGlobal.Reset();
sandbox.Reset();
// Provide a GC hint that the context has gone away. Without this call it
// does not seem that the collector will touch the context until under extreme
// stress.
Nan::ContextDisposedNotification();
}
// We override ObjectWrap::Wrap so that we can create our context after
// we have a reference to our "host" JavaScript object. If we try to use
// handle_ in the ContextifyContext constructor, it will be empty since it's
// set in ObjectWrap::Wrap.
void Wrap(Local<Object> handle);
static void Init(Local<Object> target) {
Nan::HandleScope scope;
Local<String> className = Nan::New("ContextifyContext").ToLocalChecked();
Local<FunctionTemplate> ljsTmpl = Nan::New<FunctionTemplate>(New);
ljsTmpl->InstanceTemplate()->SetInternalFieldCount(1);
ljsTmpl->SetClassName(className);
Nan::SetPrototypeMethod(ljsTmpl, "run", ContextifyContext::Run);
Nan::SetPrototypeMethod(ljsTmpl, "getGlobal", ContextifyContext::GetGlobal);
jsTmpl.Reset(ljsTmpl);
target->Set(className, ljsTmpl->GetFunction());
}
static NAN_METHOD(New) {
if (info.Length() < 1)
return Nan::ThrowError("Wrong number of arguments passed to ContextifyContext constructor");
if (!info[0]->IsObject())
return Nan::ThrowTypeError("Argument to ContextifyContext constructor must be an object.");
ContextifyContext* ctx = new ContextifyContext(info[0]->ToObject());
ctx->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
static NAN_METHOD(Run) {
if (info.Length() == 0)
return Nan::ThrowError("Must supply at least 1 argument to run");
if (!info[0]->IsString())
return Nan::ThrowTypeError("First argument to run must be a String.");
ContextifyContext* ctx = Nan::ObjectWrap::Unwrap<ContextifyContext>(info.This());
Local<Context> lcontext = Nan::New(ctx->context);
Context::Scope ctxScope(lcontext);
Local<String> code = info[0]->ToString();
Nan::TryCatch trycatch;
Nan::MaybeLocal<Nan::BoundScript> script;
if (info.Length() > 1 && info[1]->IsString()) {
ScriptOrigin origin(info[1]->ToString());
script = Nan::CompileScript(code, origin);
} else {
script = Nan::CompileScript(code);
}
if (script.IsEmpty()) {
trycatch.ReThrow();
return;
}
Nan::MaybeLocal<Value> result = Nan::RunScript(script.ToLocalChecked());
if (result.IsEmpty()) {
trycatch.ReThrow();
} else {
info.GetReturnValue().Set(result.ToLocalChecked());
}
}
static bool InstanceOf(Local<Value> value) {
return Nan::New(jsTmpl)->HasInstance(value);
}
static NAN_METHOD(GetGlobal) {
ContextifyContext* ctx = Nan::ObjectWrap::Unwrap<ContextifyContext>(info.This());
info.GetReturnValue().Set(Nan::New(ctx->proxyGlobal));
}
};
// This is an object that just keeps an internal pointer to this
// ContextifyContext. It's passed to the NamedPropertyHandler. If we
// pass the main JavaScript context object we're embedded in, then the
// NamedPropertyHandler will store a reference to it forever and keep it
// from getting gc'd.
class ContextWrap : public Nan::ObjectWrap {
public:
static void Init(void) {
Nan::HandleScope scope;
Local<FunctionTemplate> tmpl = Nan::New<FunctionTemplate>();
tmpl->InstanceTemplate()->SetInternalFieldCount(1);
functionTemplate.Reset(tmpl);
constructor.Reset(tmpl->GetFunction());
}
static Local<Context> createV8Context(Local<Object> jsContextify) {
Nan::EscapableHandleScope scope;
Local<Object> wrapper = Nan::New(constructor)->NewInstance();
ContextWrap *contextWrapper = new ContextWrap();
contextWrapper->Wrap(wrapper);
Nan::Persistent<Object>(jsContextify).SetWeak(contextWrapper, &ContextWrap::weakCallback, Nan::WeakCallbackType::kParameter);
contextWrapper->ctx = Nan::ObjectWrap::Unwrap<ContextifyContext>(jsContextify);
Local<FunctionTemplate> ftmpl = Nan::New<FunctionTemplate>();
ftmpl->SetHiddenPrototype(true);
ftmpl->SetClassName(Nan::New(contextWrapper->ctx->sandbox)->GetConstructorName());
Local<ObjectTemplate> otmpl = ftmpl->InstanceTemplate();
Nan::SetNamedPropertyHandler(otmpl,
GlobalPropertyGetter,
GlobalPropertySetter,
GlobalPropertyQuery,
GlobalPropertyDeleter,
GlobalPropertyEnumerator,
wrapper);
#if NODE_MODULE_VERSION <= NODE_6_0_MODULE_VERSION
otmpl->SetAccessCheckCallbacks(GlobalPropertyNamedAccessCheck,
GlobalPropertyIndexedAccessCheck);
#else
NamedPropertyHandlerConfiguration namedPropertyHandlerConfiguration;
IndexedPropertyHandlerConfiguration indexedPropertyHandlerConfiguration;
otmpl->SetAccessCheckCallbackAndHandler(AccessCheckCallback,
namedPropertyHandlerConfiguration,
indexedPropertyHandlerConfiguration);
#endif
return scope.Escape(Nan::New<Context>(static_cast<ExtensionConfiguration*>(NULL), otmpl));
}
private:
ContextWrap() :ctx(NULL) {}
~ContextWrap() {
}
#if NODE_MODULE_VERSION <= NODE_6_0_MODULE_VERSION
static bool GlobalPropertyNamedAccessCheck(Local<Object> host,
Local<Value> key,
AccessType type,
Local<Value> data) {
return true;
}
static bool GlobalPropertyIndexedAccessCheck(Local<Object> host,
uint32_t key,
AccessType type,
Local<Value> data) {
return true;
}
#else
static bool AccessCheckCallback(Local<Context> accessing_context,
Local<Object> accessed_object,
Local<Value> data) {
return true;
}
#endif
static void GlobalPropertyGetter(Local<String> property, const Nan::PropertyCallbackInfo<Value>& info) {
Local<Object> data = info.Data()->ToObject();
ContextifyContext* ctx = Nan::ObjectWrap::Unwrap<ContextWrap>(data)->ctx;
if (!ctx)
return;
Local<Value> rv = Nan::New(ctx->sandbox)->GetRealNamedProperty(property);
// if (rv.IsEmpty()) {
// rv = Nan::New(ctx->proxyGlobal)->GetRealNamedProperty(property);
// }
info.GetReturnValue().Set(rv);
}
static void GlobalPropertySetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<Value>& info) {
Local<Object> data = info.Data()->ToObject();
ContextifyContext* ctx = Nan::ObjectWrap::Unwrap<ContextWrap>(data)->ctx;
if (!ctx)
return;
Nan::New(ctx->sandbox)->Set(property, value);
info.GetReturnValue().Set(value);
}
static void GlobalPropertyQuery(Local<String> property, const Nan::PropertyCallbackInfo<Integer>& info) {
Local<Object> data = info.Data()->ToObject();
ContextifyContext* ctx = Nan::ObjectWrap::Unwrap<ContextWrap>(data)->ctx;
if (!ctx)
return info.GetReturnValue().Set(Nan::New<Integer>(None));
if (!Nan::New(ctx->sandbox)->GetRealNamedProperty(property).IsEmpty() ||
!Nan::New(ctx->proxyGlobal)->GetRealNamedProperty(property).IsEmpty()) {
info.GetReturnValue().Set(Nan::New<Integer>(None));
} else {
info.GetReturnValue().Set(Local<Integer>());
}
}
static void GlobalPropertyDeleter(Local<String> property, const Nan::PropertyCallbackInfo<Boolean>& info) {
Local<Object> data = info.Data()->ToObject();
ContextifyContext* ctx = Nan::ObjectWrap::Unwrap<ContextWrap>(data)->ctx;
if (!ctx)
return info.GetReturnValue().Set(Nan::New(false));
bool success = Nan::New(ctx->sandbox)->Delete(property);
info.GetReturnValue().Set(Nan::New(success));
}
static void GlobalPropertyEnumerator(const Nan::PropertyCallbackInfo<Array>& info) {
Local<Object> data = info.Data()->ToObject();
ContextifyContext* ctx = Nan::ObjectWrap::Unwrap<ContextWrap>(data)->ctx;
if (!ctx) {
Local<Array> blank = Array::New(0);
return info.GetReturnValue().Set(blank);
}
info.GetReturnValue().Set(Nan::New(ctx->sandbox)->GetPropertyNames());
}
static void weakCallback(const Nan::WeakCallbackInfo<ContextWrap>& data) {
ContextWrap *self = data.GetParameter();
self->ctx = NULL;
}
static Nan::Persistent<FunctionTemplate> functionTemplate;
static Nan::Persistent<Function> constructor;
ContextifyContext *ctx;
};
Nan::Persistent<FunctionTemplate> ContextWrap::functionTemplate;
Nan::Persistent<Function> ContextWrap::constructor;
void ContextifyContext::Wrap(Local<Object> handle) {
Nan::ObjectWrap::Wrap(handle);
Local<Context> lcontext = ContextWrap::createV8Context(handle);
context.Reset(lcontext);
proxyGlobal.Reset(lcontext->Global());
}
class ContextifyScript : public Nan::ObjectWrap {
public:
static Nan::Persistent<FunctionTemplate> scriptTmpl;
Nan::Persistent<Nan::UnboundScript> script;
static void Init(Local<Object> target) {
Nan::HandleScope scope;
Local<String> className = Nan::New("ContextifyScript").ToLocalChecked();
Local<FunctionTemplate> lscriptTmpl = Nan::New<FunctionTemplate>(New);
lscriptTmpl->InstanceTemplate()->SetInternalFieldCount(1);
lscriptTmpl->SetClassName(className);
Nan::SetPrototypeMethod(lscriptTmpl, "runInContext", RunInContext);
scriptTmpl.Reset(lscriptTmpl);
target->Set(className, lscriptTmpl->GetFunction());
}
static NAN_METHOD(New) {
ContextifyScript *contextify_script = new ContextifyScript();
contextify_script->Wrap(info.Holder());
if (info.Length() < 1)
return Nan::ThrowTypeError("needs at least 'code' argument.");
Local<String> code = info[0]->ToString();
Nan::TryCatch trycatch;
Nan::MaybeLocal<String> filename = info.Length() > 1
? info[1]->ToString()
: Nan::New("ContextifyScript.<anonymous>");
if (filename.IsEmpty()) {
trycatch.ReThrow();
return;
}
Local<Context> context = Nan::GetCurrentContext();
Context::Scope context_scope(context);
ScriptOrigin origin(filename.ToLocalChecked());
Nan::MaybeLocal<Nan::UnboundScript> v8_script = Nan::New<Nan::UnboundScript>(code, origin);
if (v8_script.IsEmpty()) {
trycatch.ReThrow();
return;
}
contextify_script->script.Reset(v8_script.ToLocalChecked());
info.GetReturnValue().Set(info.This());
}
static NAN_METHOD(RunInContext) {
if (info.Length() == 0)
return Nan::ThrowError("Must supply at least 1 argument to runInContext");
if (!ContextifyContext::InstanceOf(info[0]->ToObject()))
return Nan::ThrowTypeError("First argument must be a ContextifyContext.");
ContextifyContext* ctx = Nan::ObjectWrap::Unwrap<ContextifyContext>(info[0]->ToObject());
Local<Context> lcontext = Nan::New(ctx->context);
Context::Scope scope(lcontext);
ContextifyScript* wrapped_script = Nan::ObjectWrap::Unwrap<ContextifyScript>(info.This());
Nan::MaybeLocal<Nan::UnboundScript> script = Nan::New(wrapped_script->script);
Nan::TryCatch trycatch;
if (script.IsEmpty()) {
trycatch.ReThrow();
return;
}
Nan::MaybeLocal<Value> result = Nan::RunScript(script.ToLocalChecked());
if (result.IsEmpty()) {
trycatch.ReThrow();
} else {
info.GetReturnValue().Set(result.ToLocalChecked());
}
}
~ContextifyScript() {
script.Reset();
}
};
Nan::Persistent<FunctionTemplate> ContextifyContext::jsTmpl;
Nan::Persistent<FunctionTemplate> ContextifyScript::scriptTmpl;
extern "C" {
static void init(Local<Object> target) {
ContextifyContext::Init(target);
ContextifyScript::Init(target);
ContextWrap::Init();
}
NODE_MODULE(contextify, init)
};
|
#include "node.h"
#include "node_version.h"
#include "nan.h"
#include <string>
using namespace v8;
using namespace node;
class ContextWrap;
class ContextifyContext : public Nan::ObjectWrap {
public:
Nan::Persistent<Context> context;
Nan::Persistent<Object> sandbox;
Nan::Persistent<Object> proxyGlobal;
static Nan::Persistent<FunctionTemplate> jsTmpl;
ContextifyContext(Local<Object> sbox) {
Nan::HandleScope scope;
sandbox.Reset(sbox);
}
~ContextifyContext() {
context.Reset();
proxyGlobal.Reset();
sandbox.Reset();
// Provide a GC hint that the context has gone away. Without this call it
// does not seem that the collector will touch the context until under extreme
// stress.
Nan::ContextDisposedNotification();
}
// We override ObjectWrap::Wrap so that we can create our context after
// we have a reference to our "host" JavaScript object. If we try to use
// handle_ in the ContextifyContext constructor, it will be empty since it's
// set in ObjectWrap::Wrap.
void Wrap(Local<Object> handle);
static void Init(Local<Object> target) {
Nan::HandleScope scope;
Local<String> className = Nan::New("ContextifyContext").ToLocalChecked();
Local<FunctionTemplate> ljsTmpl = Nan::New<FunctionTemplate>(New);
ljsTmpl->InstanceTemplate()->SetInternalFieldCount(1);
ljsTmpl->SetClassName(className);
Nan::SetPrototypeMethod(ljsTmpl, "run", ContextifyContext::Run);
Nan::SetPrototypeMethod(ljsTmpl, "getGlobal", ContextifyContext::GetGlobal);
jsTmpl.Reset(ljsTmpl);
target->Set(className, ljsTmpl->GetFunction());
}
static NAN_METHOD(New) {
if (info.Length() < 1)
return Nan::ThrowError("Wrong number of arguments passed to ContextifyContext constructor");
if (!info[0]->IsObject())
return Nan::ThrowTypeError("Argument to ContextifyContext constructor must be an object.");
ContextifyContext* ctx = new ContextifyContext(info[0]->ToObject());
ctx->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
static NAN_METHOD(Run) {
if (info.Length() == 0)
return Nan::ThrowError("Must supply at least 1 argument to run");
if (!info[0]->IsString())
return Nan::ThrowTypeError("First argument to run must be a String.");
ContextifyContext* ctx = Nan::ObjectWrap::Unwrap<ContextifyContext>(info.This());
Local<Context> lcontext = Nan::New(ctx->context);
Context::Scope ctxScope(lcontext);
Local<String> code = info[0]->ToString();
Nan::TryCatch trycatch;
Nan::MaybeLocal<Nan::BoundScript> script;
if (info.Length() > 1 && info[1]->IsString()) {
ScriptOrigin origin(info[1]->ToString());
script = Nan::CompileScript(code, origin);
} else {
script = Nan::CompileScript(code);
}
if (script.IsEmpty()) {
trycatch.ReThrow();
return;
}
Nan::MaybeLocal<Value> result = Nan::RunScript(script.ToLocalChecked());
if (result.IsEmpty()) {
trycatch.ReThrow();
} else {
info.GetReturnValue().Set(result.ToLocalChecked());
}
}
static bool InstanceOf(Local<Value> value) {
return Nan::New(jsTmpl)->HasInstance(value);
}
static NAN_METHOD(GetGlobal) {
ContextifyContext* ctx = Nan::ObjectWrap::Unwrap<ContextifyContext>(info.This());
info.GetReturnValue().Set(Nan::New(ctx->proxyGlobal));
}
};
// This is an object that just keeps an internal pointer to this
// ContextifyContext. It's passed to the NamedPropertyHandler. If we
// pass the main JavaScript context object we're embedded in, then the
// NamedPropertyHandler will store a reference to it forever and keep it
// from getting gc'd.
class ContextWrap : public Nan::ObjectWrap {
public:
static void Init(void) {
Nan::HandleScope scope;
Local<FunctionTemplate> tmpl = Nan::New<FunctionTemplate>();
tmpl->InstanceTemplate()->SetInternalFieldCount(1);
functionTemplate.Reset(tmpl);
constructor.Reset(tmpl->GetFunction());
}
static Local<Context> createV8Context(Local<Object> jsContextify) {
Nan::EscapableHandleScope scope;
Local<Object> wrapper = Nan::NewInstance(Nan::New(constructor)).ToLocalChecked();
ContextWrap *contextWrapper = new ContextWrap();
contextWrapper->Wrap(wrapper);
Nan::Persistent<Object>(jsContextify).SetWeak(contextWrapper, &ContextWrap::weakCallback, Nan::WeakCallbackType::kParameter);
contextWrapper->ctx = Nan::ObjectWrap::Unwrap<ContextifyContext>(jsContextify);
Local<FunctionTemplate> ftmpl = Nan::New<FunctionTemplate>();
ftmpl->SetHiddenPrototype(true);
ftmpl->SetClassName(Nan::New(contextWrapper->ctx->sandbox)->GetConstructorName());
Local<ObjectTemplate> otmpl = ftmpl->InstanceTemplate();
Nan::SetNamedPropertyHandler(otmpl,
GlobalPropertyGetter,
GlobalPropertySetter,
GlobalPropertyQuery,
GlobalPropertyDeleter,
GlobalPropertyEnumerator,
wrapper);
#if NODE_MODULE_VERSION <= NODE_6_0_MODULE_VERSION
otmpl->SetAccessCheckCallbacks(GlobalPropertyNamedAccessCheck,
GlobalPropertyIndexedAccessCheck);
#else
NamedPropertyHandlerConfiguration namedPropertyHandlerConfiguration;
IndexedPropertyHandlerConfiguration indexedPropertyHandlerConfiguration;
otmpl->SetAccessCheckCallbackAndHandler(AccessCheckCallback,
namedPropertyHandlerConfiguration,
indexedPropertyHandlerConfiguration);
#endif
return scope.Escape(Nan::New<Context>(static_cast<ExtensionConfiguration*>(NULL), otmpl));
}
private:
ContextWrap() :ctx(NULL) {}
~ContextWrap() {
}
#if NODE_MODULE_VERSION <= NODE_6_0_MODULE_VERSION
static bool GlobalPropertyNamedAccessCheck(Local<Object> host,
Local<Value> key,
AccessType type,
Local<Value> data) {
return true;
}
static bool GlobalPropertyIndexedAccessCheck(Local<Object> host,
uint32_t key,
AccessType type,
Local<Value> data) {
return true;
}
#else
static bool AccessCheckCallback(Local<Context> accessing_context,
Local<Object> accessed_object,
Local<Value> data) {
return true;
}
#endif
static void GlobalPropertyGetter(Local<String> property, const Nan::PropertyCallbackInfo<Value>& info) {
Local<Object> data = info.Data()->ToObject();
ContextifyContext* ctx = Nan::ObjectWrap::Unwrap<ContextWrap>(data)->ctx;
if (!ctx)
return;
Nan::MaybeLocal<Value> rv = Nan::GetRealNamedProperty(Nan::New(ctx->sandbox),
property);
if (rv.IsEmpty())
return;
info.GetReturnValue().Set(rv.ToLocalChecked());
}
static void GlobalPropertySetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<Value>& info) {
Local<Object> data = info.Data()->ToObject();
ContextifyContext* ctx = Nan::ObjectWrap::Unwrap<ContextWrap>(data)->ctx;
if (!ctx)
return;
Nan::New(ctx->sandbox)->Set(property, value);
info.GetReturnValue().Set(value);
}
static void GlobalPropertyQuery(Local<String> property, const Nan::PropertyCallbackInfo<Integer>& info) {
Local<Object> data = info.Data()->ToObject();
ContextifyContext* ctx = Nan::ObjectWrap::Unwrap<ContextWrap>(data)->ctx;
if (!ctx)
return info.GetReturnValue().Set(Nan::New<Integer>(None));
if (!Nan::GetRealNamedProperty(Nan::New(ctx->sandbox), property).IsEmpty() ||
!Nan::GetRealNamedProperty(Nan::New(ctx->proxyGlobal), property).IsEmpty()) {
info.GetReturnValue().Set(Nan::New<Integer>(None));
} else {
info.GetReturnValue().Set(Local<Integer>());
}
}
static void GlobalPropertyDeleter(Local<String> property, const Nan::PropertyCallbackInfo<Boolean>& info) {
Local<Object> data = info.Data()->ToObject();
ContextifyContext* ctx = Nan::ObjectWrap::Unwrap<ContextWrap>(data)->ctx;
if (!ctx)
return info.GetReturnValue().Set(Nan::New(false));
bool success = Nan::New(ctx->sandbox)->Delete(property);
info.GetReturnValue().Set(Nan::New(success));
}
static void GlobalPropertyEnumerator(const Nan::PropertyCallbackInfo<Array>& info) {
Local<Object> data = info.Data()->ToObject();
ContextifyContext* ctx = Nan::ObjectWrap::Unwrap<ContextWrap>(data)->ctx;
if (!ctx) {
Local<Array> blank = Array::New(0);
return info.GetReturnValue().Set(blank);
}
info.GetReturnValue().Set(Nan::New(ctx->sandbox)->GetPropertyNames());
}
static void weakCallback(const Nan::WeakCallbackInfo<ContextWrap>& data) {
ContextWrap *self = data.GetParameter();
self->ctx = NULL;
}
static Nan::Persistent<FunctionTemplate> functionTemplate;
static Nan::Persistent<Function> constructor;
ContextifyContext *ctx;
};
Nan::Persistent<FunctionTemplate> ContextWrap::functionTemplate;
Nan::Persistent<Function> ContextWrap::constructor;
void ContextifyContext::Wrap(Local<Object> handle) {
Nan::ObjectWrap::Wrap(handle);
Local<Context> lcontext = ContextWrap::createV8Context(handle);
context.Reset(lcontext);
proxyGlobal.Reset(lcontext->Global());
}
class ContextifyScript : public Nan::ObjectWrap {
public:
static Nan::Persistent<FunctionTemplate> scriptTmpl;
Nan::Persistent<Nan::UnboundScript> script;
static void Init(Local<Object> target) {
Nan::HandleScope scope;
Local<String> className = Nan::New("ContextifyScript").ToLocalChecked();
Local<FunctionTemplate> lscriptTmpl = Nan::New<FunctionTemplate>(New);
lscriptTmpl->InstanceTemplate()->SetInternalFieldCount(1);
lscriptTmpl->SetClassName(className);
Nan::SetPrototypeMethod(lscriptTmpl, "runInContext", RunInContext);
scriptTmpl.Reset(lscriptTmpl);
target->Set(className, lscriptTmpl->GetFunction());
}
static NAN_METHOD(New) {
ContextifyScript *contextify_script = new ContextifyScript();
contextify_script->Wrap(info.Holder());
if (info.Length() < 1)
return Nan::ThrowTypeError("needs at least 'code' argument.");
Local<String> code = info[0]->ToString();
Nan::TryCatch trycatch;
Nan::MaybeLocal<String> filename = info.Length() > 1
? info[1]->ToString()
: Nan::New("ContextifyScript.<anonymous>");
if (filename.IsEmpty()) {
trycatch.ReThrow();
return;
}
Local<Context> context = Nan::GetCurrentContext();
Context::Scope context_scope(context);
ScriptOrigin origin(filename.ToLocalChecked());
Nan::MaybeLocal<Nan::UnboundScript> v8_script = Nan::New<Nan::UnboundScript>(code, origin);
if (v8_script.IsEmpty()) {
trycatch.ReThrow();
return;
}
contextify_script->script.Reset(v8_script.ToLocalChecked());
info.GetReturnValue().Set(info.This());
}
static NAN_METHOD(RunInContext) {
if (info.Length() == 0)
return Nan::ThrowError("Must supply at least 1 argument to runInContext");
if (!ContextifyContext::InstanceOf(info[0]->ToObject()))
return Nan::ThrowTypeError("First argument must be a ContextifyContext.");
ContextifyContext* ctx = Nan::ObjectWrap::Unwrap<ContextifyContext>(info[0]->ToObject());
Local<Context> lcontext = Nan::New(ctx->context);
Context::Scope scope(lcontext);
ContextifyScript* wrapped_script = Nan::ObjectWrap::Unwrap<ContextifyScript>(info.This());
Nan::MaybeLocal<Nan::UnboundScript> script = Nan::New(wrapped_script->script);
Nan::TryCatch trycatch;
if (script.IsEmpty()) {
trycatch.ReThrow();
return;
}
Nan::MaybeLocal<Value> result = Nan::RunScript(script.ToLocalChecked());
if (result.IsEmpty()) {
trycatch.ReThrow();
} else {
info.GetReturnValue().Set(result.ToLocalChecked());
}
}
~ContextifyScript() {
script.Reset();
}
};
Nan::Persistent<FunctionTemplate> ContextifyContext::jsTmpl;
Nan::Persistent<FunctionTemplate> ContextifyScript::scriptTmpl;
extern "C" {
static void init(Local<Object> target) {
ContextifyContext::Init(target);
ContextifyScript::Init(target);
ContextWrap::Init();
}
NODE_MODULE(contextify, init)
};
|
Replace deprecated methods with Nan (#221)
|
Replace deprecated methods with Nan (#221)
* Modify using `Nan::NewInstance`
For recent Node.js, a deprecated warning is issued.
* Modify using `Nan::GetRealNamedProperty`
For recent Node.js, a deprecated warning is issued.
* Use notEqual
Because the expected value is not an object.
|
C++
|
mit
|
brianmcd/contextify,brianmcd/contextify,brianmcd/contextify
|
a4f8e383fda8d0f75bc1b358e3c06f94dcc06381
|
src/core_read.cpp
|
src/core_read.cpp
|
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <psbt.h>
#include <script/script.h>
#include <script/sign.h>
#include <serialize.h>
#include <streams.h>
#include <util/strencodings.h>
#include <version.h>
#include <univalue.h>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <algorithm>
CScript ParseScript(const std::string &s) {
CScript result;
static std::map<std::string, opcodetype> mapOpNames;
if (mapOpNames.empty()) {
for (int op = 0; op < FIRST_UNDEFINED_OP_VALUE; op++) {
if (op < OP_PUSHDATA1) {
continue;
}
const char *name = GetOpName(static_cast<opcodetype>(op));
if (strcmp(name, "OP_UNKNOWN") == 0) {
continue;
}
std::string strName(name);
mapOpNames[strName] = static_cast<opcodetype>(op);
// Convenience: OP_ADD and just ADD are both recognized:
boost::algorithm::replace_first(strName, "OP_", "");
mapOpNames[strName] = static_cast<opcodetype>(op);
}
}
std::vector<std::string> words;
boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"),
boost::algorithm::token_compress_on);
size_t push_size = 0, next_push_size = 0;
size_t script_size = 0;
// Deal with PUSHDATA1 operation with some more hacks.
size_t push_data_size = 0;
for (const auto &w : words) {
if (w.empty()) {
// Empty string, ignore. (boost::split given '' will return one
// word)
continue;
}
// Update script size.
script_size = result.size();
// Make sure we keep track of the size of push operations.
push_size = next_push_size;
next_push_size = 0;
// Decimal numbers
if (std::all_of(w.begin(), w.end(), ::IsDigit) ||
(w.front() == '-' && w.size() > 1 &&
std::all_of(w.begin() + 1, w.end(), ::IsDigit))) {
// Number
int64_t n = atoi64(w);
result << n;
goto next;
}
// Hex Data
if (w.substr(0, 2) == "0x" && w.size() > 2) {
if (!IsHex(std::string(w.begin() + 2, w.end()))) {
// Should only arrive here for improperly formatted hex values
throw std::runtime_error("Hex numbers expected to be formatted "
"in full-byte chunks (ex: 0x00 "
"instead of 0x0)");
}
// Raw hex data, inserted NOT pushed onto stack:
std::vector<uint8_t> raw =
ParseHex(std::string(w.begin() + 2, w.end()));
result.insert(result.end(), raw.begin(), raw.end());
goto next;
}
if (w.size() >= 2 && w.front() == '\'' && w.back() == '\'') {
// Single-quoted string, pushed as data. NOTE: this is poor-man's
// parsing, spaces/tabs/newlines in single-quoted strings won't
// work.
std::vector<uint8_t> value(w.begin() + 1, w.end() - 1);
result << value;
goto next;
}
if (mapOpNames.count(w)) {
// opcode, e.g. OP_ADD or ADD:
opcodetype op = mapOpNames[w];
result << op;
goto next;
}
throw std::runtime_error("Error parsing script: " + s);
next:
size_t size_change = result.size() - script_size;
// If push_size is set, ensure have added the right amount of stuff.
if (push_size != 0 && size_change != push_size) {
throw std::runtime_error(
"Wrong number of bytes being pushed. Expected:" +
std::to_string(push_size) +
" Pushed:" + std::to_string(size_change));
}
// If push_size is set, and we have push_data_size set, then we have a
// PUSHDATAX opcode. We need to read it's push size as a LE value for
// the next iteration of this loop.
if (push_size != 0 && push_data_size != 0) {
auto offset = &result[script_size];
// Push data size is not a CScriptNum (Because it is
// 2's-complement instead of 1's complement). We need to use
// ReadLE(N) instead of converting to a CScriptNum.
if (push_data_size == 1) {
next_push_size = *offset;
} else if (push_data_size == 2) {
next_push_size = ReadLE16(offset);
} else if (push_data_size == 4) {
next_push_size = ReadLE32(offset);
}
push_data_size = 0;
}
// If push_size is unset, but size_change is 1, that means we have an
// opcode in the form of `0x00` or <opcodename>. We will check to see
// if it is a push operation and set state accordingly
if (push_size == 0 && size_change == 1) {
opcodetype op = opcodetype(*result.rbegin());
// If we have what looks like an immediate push, figure out its
// size.
if (op < OP_PUSHDATA1) {
next_push_size = op;
continue;
}
switch (op) {
case OP_PUSHDATA1:
push_data_size = next_push_size = 1;
break;
case OP_PUSHDATA2:
push_data_size = next_push_size = 2;
break;
case OP_PUSHDATA4:
push_data_size = next_push_size = 4;
break;
default:
break;
}
}
}
return result;
}
bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx) {
if (!IsHex(strHexTx)) {
return false;
}
std::vector<uint8_t> txData(ParseHex(strHexTx));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssData >> tx;
if (ssData.eof()) {
return true;
}
} catch (const std::exception &e) {
// Fall through.
}
return false;
}
bool DecodeHexBlockHeader(CBlockHeader &header, const std::string &hex_header) {
if (!IsHex(hex_header)) {
return false;
}
const std::vector<uint8_t> header_data{ParseHex(hex_header)};
CDataStream ser_header(header_data, SER_NETWORK, PROTOCOL_VERSION);
try {
ser_header >> header;
} catch (const std::exception &) {
return false;
}
return true;
}
bool DecodeHexBlk(CBlock &block, const std::string &strHexBlk) {
if (!IsHex(strHexBlk)) {
return false;
}
std::vector<uint8_t> blockData(ParseHex(strHexBlk));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssBlock >> block;
} catch (const std::exception &) {
return false;
}
return true;
}
bool ParseHashStr(const std::string &strHex, uint256 &result) {
if ((strHex.size() != 64) || !IsHex(strHex)) {
return false;
}
result.SetHex(strHex);
return true;
}
std::vector<uint8_t> ParseHexUV(const UniValue &v, const std::string &strName) {
std::string strHex;
if (v.isStr()) {
strHex = v.getValStr();
}
if (!IsHex(strHex)) {
throw std::runtime_error(
strName + " must be hexadecimal string (not '" + strHex + "')");
}
return ParseHex(strHex);
}
SigHashType ParseSighashString(const UniValue &sighash) {
SigHashType sigHashType = SigHashType().withForkId();
if (!sighash.isNull()) {
static std::map<std::string, int> map_sighash_values = {
{"ALL", SIGHASH_ALL},
{"ALL|ANYONECANPAY", SIGHASH_ALL | SIGHASH_ANYONECANPAY},
{"ALL|FORKID", SIGHASH_ALL | SIGHASH_FORKID},
{"ALL|FORKID|ANYONECANPAY",
SIGHASH_ALL | SIGHASH_FORKID | SIGHASH_ANYONECANPAY},
{"NONE", SIGHASH_NONE},
{"NONE|ANYONECANPAY", SIGHASH_NONE | SIGHASH_ANYONECANPAY},
{"NONE|FORKID", SIGHASH_NONE | SIGHASH_FORKID},
{"NONE|FORKID|ANYONECANPAY",
SIGHASH_NONE | SIGHASH_FORKID | SIGHASH_ANYONECANPAY},
{"SINGLE", SIGHASH_SINGLE},
{"SINGLE|ANYONECANPAY", SIGHASH_SINGLE | SIGHASH_ANYONECANPAY},
{"SINGLE|FORKID", SIGHASH_SINGLE | SIGHASH_FORKID},
{"SINGLE|FORKID|ANYONECANPAY",
SIGHASH_SINGLE | SIGHASH_FORKID | SIGHASH_ANYONECANPAY},
};
std::string strHashType = sighash.get_str();
const auto &it = map_sighash_values.find(strHashType);
if (it != map_sighash_values.end()) {
sigHashType = SigHashType(it->second);
} else {
throw std::runtime_error(strHashType +
" is not a valid sighash parameter.");
}
}
return sigHashType;
}
|
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <core_io.h>
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <psbt.h>
#include <script/script.h>
#include <script/sign.h>
#include <serialize.h>
#include <streams.h>
#include <util/strencodings.h>
#include <version.h>
#include <univalue.h>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <algorithm>
CScript ParseScript(const std::string &s) {
CScript result;
static std::map<std::string, opcodetype> mapOpNames;
if (mapOpNames.empty()) {
for (int op = 0; op < FIRST_UNDEFINED_OP_VALUE; op++) {
if (op < OP_PUSHDATA1) {
continue;
}
const char *name = GetOpName(static_cast<opcodetype>(op));
if (strcmp(name, "OP_UNKNOWN") == 0) {
continue;
}
std::string strName(name);
mapOpNames[strName] = static_cast<opcodetype>(op);
// Convenience: OP_ADD and just ADD are both recognized:
boost::algorithm::replace_first(strName, "OP_", "");
mapOpNames[strName] = static_cast<opcodetype>(op);
}
}
std::vector<std::string> words;
boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"),
boost::algorithm::token_compress_on);
size_t push_size = 0, next_push_size = 0;
size_t script_size = 0;
// Deal with PUSHDATA1 operation with some more hacks.
size_t push_data_size = 0;
for (const auto &w : words) {
if (w.empty()) {
// Empty string, ignore. (boost::split given '' will return one
// word)
continue;
}
// Update script size.
script_size = result.size();
// Make sure we keep track of the size of push operations.
push_size = next_push_size;
next_push_size = 0;
// Decimal numbers
if (std::all_of(w.begin(), w.end(), ::IsDigit) ||
(w.front() == '-' && w.size() > 1 &&
std::all_of(w.begin() + 1, w.end(), ::IsDigit))) {
// Number
int64_t n = atoi64(w);
result << n;
goto next;
}
// Hex Data
if (w.substr(0, 2) == "0x" && w.size() > 2) {
if (!IsHex(std::string(w.begin() + 2, w.end()))) {
// Should only arrive here for improperly formatted hex values
throw std::runtime_error("Hex numbers expected to be formatted "
"in full-byte chunks (ex: 0x00 "
"instead of 0x0)");
}
// Raw hex data, inserted NOT pushed onto stack:
std::vector<uint8_t> raw =
ParseHex(std::string(w.begin() + 2, w.end()));
result.insert(result.end(), raw.begin(), raw.end());
goto next;
}
if (w.size() >= 2 && w.front() == '\'' && w.back() == '\'') {
// Single-quoted string, pushed as data. NOTE: this is poor-man's
// parsing, spaces/tabs/newlines in single-quoted strings won't
// work.
std::vector<uint8_t> value(w.begin() + 1, w.end() - 1);
result << value;
goto next;
}
if (mapOpNames.count(w)) {
// opcode, e.g. OP_ADD or ADD:
opcodetype op = mapOpNames[w];
result << op;
goto next;
}
throw std::runtime_error("Error parsing script: " + s);
next:
size_t size_change = result.size() - script_size;
// If push_size is set, ensure have added the right amount of stuff.
if (push_size != 0 && size_change != push_size) {
throw std::runtime_error(
"Wrong number of bytes being pushed. Expected:" +
std::to_string(push_size) +
" Pushed:" + std::to_string(size_change));
}
// If push_size is set, and we have push_data_size set, then we have a
// PUSHDATAX opcode. We need to read it's push size as a LE value for
// the next iteration of this loop.
if (push_size != 0 && push_data_size != 0) {
auto offset = &result[script_size];
// Push data size is not a CScriptNum (Because it is
// 2's-complement instead of 1's complement). We need to use
// ReadLE(N) instead of converting to a CScriptNum.
if (push_data_size == 1) {
next_push_size = *offset;
} else if (push_data_size == 2) {
next_push_size = ReadLE16(offset);
} else if (push_data_size == 4) {
next_push_size = ReadLE32(offset);
}
push_data_size = 0;
}
// If push_size is unset, but size_change is 1, that means we have an
// opcode in the form of `0x00` or <opcodename>. We will check to see
// if it is a push operation and set state accordingly
if (push_size == 0 && size_change == 1) {
opcodetype op = opcodetype(*result.rbegin());
// If we have what looks like an immediate push, figure out its
// size.
if (op < OP_PUSHDATA1) {
next_push_size = op;
continue;
}
switch (op) {
case OP_PUSHDATA1:
push_data_size = next_push_size = 1;
break;
case OP_PUSHDATA2:
push_data_size = next_push_size = 2;
break;
case OP_PUSHDATA4:
push_data_size = next_push_size = 4;
break;
default:
break;
}
}
}
return result;
}
bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx) {
if (!IsHex(strHexTx)) {
return false;
}
std::vector<uint8_t> txData(ParseHex(strHexTx));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssData >> tx;
if (ssData.eof()) {
return true;
}
} catch (const std::exception &e) {
// Fall through.
}
return false;
}
bool DecodeHexBlockHeader(CBlockHeader &header, const std::string &hex_header) {
if (!IsHex(hex_header)) {
return false;
}
const std::vector<uint8_t> header_data{ParseHex(hex_header)};
CDataStream ser_header(header_data, SER_NETWORK, PROTOCOL_VERSION);
try {
ser_header >> header;
} catch (const std::exception &) {
return false;
}
return true;
}
bool DecodeHexBlk(CBlock &block, const std::string &strHexBlk) {
if (!IsHex(strHexBlk)) {
return false;
}
std::vector<uint8_t> blockData(ParseHex(strHexBlk));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssBlock >> block;
} catch (const std::exception &) {
return false;
}
return true;
}
bool ParseHashStr(const std::string &strHex, uint256 &result) {
if ((strHex.size() != 64) || !IsHex(strHex)) {
return false;
}
result.SetHex(strHex);
return true;
}
std::vector<uint8_t> ParseHexUV(const UniValue &v, const std::string &strName) {
std::string strHex;
if (v.isStr()) {
strHex = v.getValStr();
}
if (!IsHex(strHex)) {
throw std::runtime_error(
strName + " must be hexadecimal string (not '" + strHex + "')");
}
return ParseHex(strHex);
}
SigHashType ParseSighashString(const UniValue &sighash) {
SigHashType sigHashType = SigHashType().withForkId();
if (!sighash.isNull()) {
static std::map<std::string, int> map_sighash_values = {
{"ALL", SIGHASH_ALL},
{"ALL|ANYONECANPAY", SIGHASH_ALL | SIGHASH_ANYONECANPAY},
{"ALL|FORKID", SIGHASH_ALL | SIGHASH_FORKID},
{"ALL|FORKID|ANYONECANPAY",
SIGHASH_ALL | SIGHASH_FORKID | SIGHASH_ANYONECANPAY},
{"NONE", SIGHASH_NONE},
{"NONE|ANYONECANPAY", SIGHASH_NONE | SIGHASH_ANYONECANPAY},
{"NONE|FORKID", SIGHASH_NONE | SIGHASH_FORKID},
{"NONE|FORKID|ANYONECANPAY",
SIGHASH_NONE | SIGHASH_FORKID | SIGHASH_ANYONECANPAY},
{"SINGLE", SIGHASH_SINGLE},
{"SINGLE|ANYONECANPAY", SIGHASH_SINGLE | SIGHASH_ANYONECANPAY},
{"SINGLE|FORKID", SIGHASH_SINGLE | SIGHASH_FORKID},
{"SINGLE|FORKID|ANYONECANPAY",
SIGHASH_SINGLE | SIGHASH_FORKID | SIGHASH_ANYONECANPAY},
};
std::string strHashType = sighash.get_str();
const auto &it = map_sighash_values.find(strHashType);
if (it != map_sighash_values.end()) {
sigHashType = SigHashType(it->second);
} else {
throw std::runtime_error(strHashType +
" is not a valid sighash parameter.");
}
}
return sigHashType;
}
|
Include core_io.h from core_read.cpp
|
[backport#16129] Include core_io.h from core_read.cpp
Summary:
https://github.com/bitcoin/bitcoin/pull/16129/commits/67f4e9c52270f9ddf8f7e83f0906af5e6743b33a
---
Concludes backport of Core [[https://github.com/bitcoin/bitcoin/pull/16129 | PR16129]]
Test Plan:
ninja check
Reviewers: #bitcoin_abc, deadalnix
Reviewed By: #bitcoin_abc, deadalnix
Differential Revision: https://reviews.bitcoinabc.org/D6331
|
C++
|
mit
|
cculianu/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,cculianu/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,cculianu/bitcoin-abc,cculianu/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,cculianu/bitcoin-abc,cculianu/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,cculianu/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,cculianu/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc
|
e85bb2c4c33a63f51fd5cfb539a17db79ebac88b
|
src/data/JSON.cpp
|
src/data/JSON.cpp
|
#include "JSON.h"
#include <string>
namespace ouroboros
{
JSON::JSON()
:mpArr(nullptr)
{}
JSON::JSON(const std::string& aJSON)
:mpArr(parse_json2(aJSON.c_str(), aJSON.length()))
{}
JSON::~JSON()
{
free(mpArr);
}
bool JSON::exists(const std::string& aPath) const
{
if (mpArr)
{
const json_token * ptr = find_json_token(mpArr, aPath.c_str());
if (ptr)
{
return true;
}
}
return false;
}
std::string JSON::get(const std::string& aPath) const
{
if (mpArr)
{
const json_token * ptr = find_json_token(mpArr, aPath.c_str());
if (ptr)
{
return std::string(ptr->ptr, ptr->len);
}
}
return std::string();
}
bool JSON::empty() const
{
return (!mpArr);
}
}
|
#include "JSON.h"
#include <string>
#include <cstdlib>
namespace ouroboros
{
JSON::JSON()
:mpArr(nullptr)
{}
JSON::JSON(const std::string& aJSON)
:mpArr(parse_json2(aJSON.c_str(), aJSON.length()))
{}
JSON::~JSON()
{
free(mpArr);
}
bool JSON::exists(const std::string& aPath) const
{
if (mpArr)
{
const json_token * ptr = find_json_token(mpArr, aPath.c_str());
if (ptr)
{
return true;
}
}
return false;
}
std::string JSON::get(const std::string& aPath) const
{
if (mpArr)
{
const json_token * ptr = find_json_token(mpArr, aPath.c_str());
if (ptr)
{
return std::string(ptr->ptr, ptr->len);
}
}
return std::string();
}
bool JSON::empty() const
{
return (!mpArr);
}
}
|
Add cstdlib so that the code compiles on OSX
|
Add cstdlib so that the code compiles on OSX
|
C++
|
mit
|
TeamCobra/ouroboros,TeamCobra/ouroboros,TeamCobra/ouroboros,TeamCobra/ouroboros,TeamCobra/ouroboros,TeamCobra/ouroboros
|
c46268889dbc57ddd0d72e1333ec15e618311299
|
ksp_physics/ksp_physics_lib.cpp
|
ksp_physics/ksp_physics_lib.cpp
|
#include "ksp_physics/ksp_physics_lib.hpp"
#if !OS_WIN
#error The isolated KSP physics library is currently only supported on windows.
#endif
#define NOGDI
#include <windows.h>
#include <psapi.h>
#include "base/version.hpp"
#include "glog/logging.h"
namespace principia {
namespace physics {
void LogPhysicsDLLBaseAddress() {
LOG(INFO) << "Principia KSP physics DLL version " << principia::base::Version
<< " built on " << principia::base::BuildDate
<< " by " << principia::base::CompilerName
<< " version " << principia::base::CompilerVersion
<< " for " << principia::base::OperatingSystem
<< " " << principia::base::Architecture;
MODULEINFO module_info;
memset(&module_info, 0, sizeof(module_info));
CHECK(GetModuleInformation(GetCurrentProcess(),
GetModuleHandle(TEXT("principia_physics")),
&module_info,
sizeof(module_info)));
LOG(INFO) << "Base address is " << module_info.lpBaseOfDll;
}
} // namespace physics
} // namespace principia
|
#include "ksp_physics/ksp_physics_lib.hpp"
#if !OS_WIN
#error The isolated KSP physics library is currently only supported on windows.
#endif
#define NOGDI
#include <windows.h>
#include <psapi.h>
#include "base/version.hpp"
#include "glog/logging.h"
namespace principia {
namespace physics {
void LogPhysicsDLLBaseAddress() {
LOG(INFO) << "Principia KSP physics DLL version " << principia::base::Version
<< " built on " << principia::base::BuildDate
<< " by " << principia::base::CompilerName
<< " version " << principia::base::CompilerVersion
<< " for " << principia::base::OperatingSystem
<< " " << principia::base::Architecture;
MODULEINFO module_info;
memset(&module_info, 0, sizeof(module_info));
CHECK(GetModuleInformation(GetCurrentProcess(),
GetModuleHandle(TEXT("principia_physics")),
&module_info,
sizeof(module_info)));
LOG(INFO) << "Base address is " << module_info.lpBaseOfDll;
google::protobuf::SetLogHandler([](google::protobuf::LogLevel const level,
char const* const filename,
int const line,
std::string const& message) {
LOG_AT_LEVEL(level) << "[" << filename << ":" << line << "] " << message;
});
}
} // namespace physics
} // namespace principia
|
set proto logging on both sides
|
set proto logging on both sides
|
C++
|
mit
|
eggrobin/Principia,pleroy/Principia,eggrobin/Principia,pleroy/Principia,pleroy/Principia,mockingbirdnest/Principia,eggrobin/Principia,mockingbirdnest/Principia,pleroy/Principia,mockingbirdnest/Principia,mockingbirdnest/Principia
|
48b7b1010bc7408527efdca947e259bd7d8039a6
|
tests/base/state_operations.cpp
|
tests/base/state_operations.cpp
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Rice University
* 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 Rice University 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.
*********************************************************************/
/* Author: Ioan Sucan */
#include <gtest/gtest.h>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
#include <libgen.h>
#include <iostream>
#include "ompl/base/ScopedState.h"
#include "ompl/base/manifolds/SE3StateManifold.h"
#include "ompl/base/SpaceInformation.h"
#include "ompl/util/Time.h"
using namespace ompl;
TEST(State, Scoped)
{
base::SE3StateManifold *mSE3 = new base::SE3StateManifold();
base::StateManifoldPtr pSE3(mSE3);
base::RealVectorBounds b(3);
b.setLow(0);
b.setHigh(1);
mSE3->setBounds(b);
base::CompoundStateManifold *mC0 = new base::CompoundStateManifold();
base::StateManifoldPtr pC0(mC0);
mC0->addSubManifold(pSE3, 1.0);
base::CompoundStateManifold *mC1 = new base::CompoundStateManifold();
base::StateManifoldPtr pC1(mC1);
mC1->addSubManifold(pC0, 1.0);
base::CompoundStateManifold *mC2 = new base::CompoundStateManifold();
base::StateManifoldPtr pC2(mC2);
mC2->addSubManifold(mSE3->getSubManifold(1), 1.0);
mC2->addSubManifold(mSE3->getSubManifold(0), 1.0);
base::ScopedState<base::SE3StateManifold> sSE3(pSE3);
base::ScopedState<base::RealVectorStateManifold> sSE3_R(mSE3->getSubManifold(0));
base::ScopedState<base::SO3StateManifold> sSE3_SO2(mSE3->getSubManifold(1));
base::ScopedState<base::CompoundStateManifold> sC0(pC0);
base::ScopedState<> sC1(pC1);
base::ScopedState<> sC2(pC2);
sSE3.random();
sSE3 >> sSE3_SO2;
EXPECT_EQ(sSE3->rotation().x, sSE3_SO2->x);
EXPECT_EQ(sSE3->rotation().y, sSE3_SO2->y);
EXPECT_EQ(sSE3->rotation().z, sSE3_SO2->z);
EXPECT_EQ(sSE3->rotation().w, sSE3_SO2->w);
base::ScopedState<> sSE3_copy(pSE3);
sSE3_copy << sSE3;
EXPECT_EQ(sSE3_copy, sSE3);
sSE3 >> sSE3_copy;
EXPECT_EQ(sSE3_copy, sSE3);
sSE3_R << sSE3_copy;
EXPECT_EQ(sSE3->getX(), sSE3_R->values[0]);
EXPECT_EQ(sSE3->getY(), sSE3_R->values[1]);
EXPECT_EQ(sSE3->getZ(), sSE3_R->values[2]);
sSE3_SO2 >> sC1;
sC1 << sSE3_R;
sC1 >> sC0;
sSE3_copy = sC0->components[0];
EXPECT_EQ(sSE3_copy, sSE3);
sSE3.random();
sSE3 >> sC2;
sSE3_copy << sC2;
EXPECT_EQ(sSE3_copy, sSE3);
sSE3.random();
sSE3 >> sSE3_SO2;
sSE3 >> sSE3_R;
(sSE3_R ^ sSE3_SO2) >> sSE3_copy;
EXPECT_EQ(sSE3_copy, sSE3);
EXPECT_EQ(sSE3_copy[pSE3 * sSE3_R.getManifold()], sSE3_R);
EXPECT_EQ(sSE3_copy[sSE3_SO2.getManifold()], sSE3_SO2);
sSE3->setY(1.0);
EXPECT_NEAR(sSE3.reals()[1], 1.0, 1e-12);
sSE3.random();
std::vector<double> r = sSE3.reals();
EXPECT_EQ(r.size(), 7);
sSE3_copy = r;
EXPECT_EQ(sSE3_copy, sSE3);
}
TEST(State, Allocation)
{
base::StateManifoldPtr m(new base::SE3StateManifold());
base::RealVectorBounds b(3);
b.setLow(0);
b.setHigh(1);
m->as<base::SE3StateManifold>()->setBounds(b);
base::SpaceInformation si(m);
si.setup();
const unsigned int N = 50000;
const unsigned int M = 20;
std::vector<base::State*> states(N, NULL);
ompl::time::point start = ompl::time::now();
for (unsigned int j = 0 ; j < M ; ++j)
{
for (unsigned int i = 0 ; i < N ; ++i)
states[i] = si.allocState();
for (unsigned int i = 0 ; i < N ; ++i)
si.freeState(states[i]);
}
double d = ompl::time::seconds(ompl::time::now() - start);
std::cout << (double)N * (double)M / d << " state allocations then frees per second" << std::endl;
start = ompl::time::now();
for (unsigned int j = 0 ; j < M ; ++j)
{
for (unsigned int i = 0 ; i < N ; ++i)
{
base::State *s = si.allocState();
si.freeState(s);
}
}
d = ompl::time::seconds(ompl::time::now() - start);
std::cout << (double)N * (double)M / d << " mixed state allocations & frees per second" << std::endl;
start = ompl::time::now();
for (unsigned int j = 0 ; j < M ; ++j)
{
for (unsigned int i = 0 ; i < N ; ++i)
{
base::State *s = si.allocState();
si.freeState(s);
states[i] = si.allocState();
}
for (unsigned int i = 0 ; i < N ; ++i)
si.freeState(states[i]);
}
d = ompl::time::seconds(ompl::time::now() - start);
std::cout << (double)N * (double)M / d << " allocations per second" << std::endl;
}
void randomizedAllocator(const base::SpaceInformation *si)
{
RNG r;
const unsigned int n = 5000;
std::vector<base::State*> states(n + 1, NULL);
for (unsigned int i = 0 ; i < n * 1000 ; ++i)
{
int j = r.uniformInt(0, n);
if (states[j] == NULL)
states[j] = si->allocState();
else
{
si->freeState(states[j]);
states[j] = NULL;
}
}
for (unsigned int i = 0 ; i < states.size() ; ++i)
if (states[i])
si->freeState(states[i]);
}
TEST(State, AllocationWithThreads)
{
base::StateManifoldPtr m(new base::SE3StateManifold());
base::RealVectorBounds b(3);
b.setLow(0);
b.setHigh(1);
m->as<base::SE3StateManifold>()->setBounds(b);
base::SpaceInformation si(m);
si.setup();
const int NT = 10;
ompl::time::point start = ompl::time::now();
std::vector<boost::thread*> threads;
for (int i = 0 ; i < NT ; ++i)
threads.push_back(new boost::thread(boost::bind(&randomizedAllocator, &si)));
for (int i = 0 ; i < NT ; ++i)
{
threads[i]->join();
delete threads[i];
}
std::cout << "Time spent randomly allocating & freeing states: "
<< ompl::time::seconds(ompl::time::now() - start) << std::endl;
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Rice University
* 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 Rice University 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.
*********************************************************************/
/* Author: Ioan Sucan */
#include <gtest/gtest.h>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
#include <libgen.h>
#include <iostream>
#include "ompl/base/ScopedState.h"
#include "ompl/base/manifolds/SE3StateManifold.h"
#include "ompl/base/SpaceInformation.h"
#include "ompl/util/Time.h"
using namespace ompl;
TEST(State, Scoped)
{
base::SE3StateManifold *mSE3 = new base::SE3StateManifold();
base::StateManifoldPtr pSE3(mSE3);
base::RealVectorBounds b(3);
b.setLow(0);
b.setHigh(1);
mSE3->setBounds(b);
base::CompoundStateManifold *mC0 = new base::CompoundStateManifold();
base::StateManifoldPtr pC0(mC0);
mC0->addSubManifold(pSE3, 1.0);
base::CompoundStateManifold *mC1 = new base::CompoundStateManifold();
base::StateManifoldPtr pC1(mC1);
mC1->addSubManifold(pC0, 1.0);
base::CompoundStateManifold *mC2 = new base::CompoundStateManifold();
base::StateManifoldPtr pC2(mC2);
mC2->addSubManifold(mSE3->getSubManifold(1), 1.0);
mC2->addSubManifold(mSE3->getSubManifold(0), 1.0);
base::ScopedState<base::SE3StateManifold> sSE3(pSE3);
base::ScopedState<base::RealVectorStateManifold> sSE3_R(mSE3->getSubManifold(0));
base::ScopedState<base::SO3StateManifold> sSE3_SO2(mSE3->getSubManifold(1));
base::ScopedState<base::CompoundStateManifold> sC0(pC0);
base::ScopedState<> sC1(pC1);
base::ScopedState<> sC2(pC2);
sSE3.random();
sSE3 >> sSE3_SO2;
EXPECT_EQ(sSE3->rotation().x, sSE3_SO2->x);
EXPECT_EQ(sSE3->rotation().y, sSE3_SO2->y);
EXPECT_EQ(sSE3->rotation().z, sSE3_SO2->z);
EXPECT_EQ(sSE3->rotation().w, sSE3_SO2->w);
base::ScopedState<> sSE3_copy(pSE3);
sSE3_copy << sSE3;
EXPECT_EQ(sSE3_copy, sSE3);
sSE3 >> sSE3_copy;
EXPECT_EQ(sSE3_copy, sSE3);
sSE3_R << sSE3_copy;
EXPECT_EQ(sSE3->getX(), sSE3_R->values[0]);
EXPECT_EQ(sSE3->getY(), sSE3_R->values[1]);
EXPECT_EQ(sSE3->getZ(), sSE3_R->values[2]);
sSE3_SO2 >> sC1;
sC1 << sSE3_R;
sC1 >> sC0;
sSE3_copy = sC0->components[0];
EXPECT_EQ(sSE3_copy, sSE3);
sSE3.random();
sSE3 >> sC2;
sSE3_copy << sC2;
EXPECT_EQ(sSE3_copy, sSE3);
sSE3.random();
sSE3 >> sSE3_SO2;
sSE3 >> sSE3_R;
(sSE3_R ^ sSE3_SO2) >> sSE3_copy;
EXPECT_EQ(sSE3_copy, sSE3);
EXPECT_EQ(sSE3_copy[pSE3 * sSE3_R.getManifold()], sSE3_R);
EXPECT_EQ(sSE3_copy[sSE3_SO2.getManifold()], sSE3_SO2);
sSE3->setY(1.0);
EXPECT_NEAR(sSE3.reals()[1], 1.0, 1e-12);
sSE3.random();
std::vector<double> r = sSE3.reals();
EXPECT_EQ(r.size(), 7u);
sSE3_copy = r;
EXPECT_EQ(sSE3_copy, sSE3);
}
TEST(State, Allocation)
{
base::StateManifoldPtr m(new base::SE3StateManifold());
base::RealVectorBounds b(3);
b.setLow(0);
b.setHigh(1);
m->as<base::SE3StateManifold>()->setBounds(b);
base::SpaceInformation si(m);
si.setup();
const unsigned int N = 50000;
const unsigned int M = 20;
std::vector<base::State*> states(N, NULL);
ompl::time::point start = ompl::time::now();
for (unsigned int j = 0 ; j < M ; ++j)
{
for (unsigned int i = 0 ; i < N ; ++i)
states[i] = si.allocState();
for (unsigned int i = 0 ; i < N ; ++i)
si.freeState(states[i]);
}
double d = ompl::time::seconds(ompl::time::now() - start);
std::cout << (double)N * (double)M / d << " state allocations then frees per second" << std::endl;
start = ompl::time::now();
for (unsigned int j = 0 ; j < M ; ++j)
{
for (unsigned int i = 0 ; i < N ; ++i)
{
base::State *s = si.allocState();
si.freeState(s);
}
}
d = ompl::time::seconds(ompl::time::now() - start);
std::cout << (double)N * (double)M / d << " mixed state allocations & frees per second" << std::endl;
start = ompl::time::now();
for (unsigned int j = 0 ; j < M ; ++j)
{
for (unsigned int i = 0 ; i < N ; ++i)
{
base::State *s = si.allocState();
si.freeState(s);
states[i] = si.allocState();
}
for (unsigned int i = 0 ; i < N ; ++i)
si.freeState(states[i]);
}
d = ompl::time::seconds(ompl::time::now() - start);
std::cout << (double)N * (double)M / d << " allocations per second" << std::endl;
}
void randomizedAllocator(const base::SpaceInformation *si)
{
RNG r;
const unsigned int n = 5000;
std::vector<base::State*> states(n + 1, NULL);
for (unsigned int i = 0 ; i < n * 1000 ; ++i)
{
int j = r.uniformInt(0, n);
if (states[j] == NULL)
states[j] = si->allocState();
else
{
si->freeState(states[j]);
states[j] = NULL;
}
}
for (unsigned int i = 0 ; i < states.size() ; ++i)
if (states[i])
si->freeState(states[i]);
}
TEST(State, AllocationWithThreads)
{
base::StateManifoldPtr m(new base::SE3StateManifold());
base::RealVectorBounds b(3);
b.setLow(0);
b.setHigh(1);
m->as<base::SE3StateManifold>()->setBounds(b);
base::SpaceInformation si(m);
si.setup();
const int NT = 10;
ompl::time::point start = ompl::time::now();
std::vector<boost::thread*> threads;
for (int i = 0 ; i < NT ; ++i)
threads.push_back(new boost::thread(boost::bind(&randomizedAllocator, &si)));
for (int i = 0 ; i < NT ; ++i)
{
threads[i]->join();
delete threads[i];
}
std::cout << "Time spent randomly allocating & freeing states: "
<< ompl::time::seconds(ompl::time::now() - start) << std::endl;
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
fix compilation warning
|
fix compilation warning
--HG--
extra : transplant_source : %00x%5B%F5f%BDR%AFGL%2Ag7%A4gx%A22%C1%09
|
C++
|
bsd-3-clause
|
sonny-tarbouriech/ompl,jvgomez/ompl,florianhauer/ompl,jvgomez/ompl,utiasASRL/batch-informed-trees,utiasASRL/batch-informed-trees,davetcoleman/ompl,jvgomez/ompl,utiasASRL/batch-informed-trees,sonny-tarbouriech/ompl,davetcoleman/ompl,florianhauer/ompl,davetcoleman/ompl,sonny-tarbouriech/ompl,utiasASRL/batch-informed-trees,florianhauer/ompl,sonny-tarbouriech/ompl,jvgomez/ompl,davetcoleman/ompl,utiasASRL/batch-informed-trees,sonny-tarbouriech/ompl,florianhauer/ompl,jvgomez/ompl,davetcoleman/ompl,davetcoleman/ompl,utiasASRL/batch-informed-trees,florianhauer/ompl,florianhauer/ompl,sonny-tarbouriech/ompl,jvgomez/ompl
|
bed1851d14975831137ba5a75f363b89cc81c5d0
|
core/source/api/zinc/status.hpp
|
core/source/api/zinc/status.hpp
|
/**
* FILE : status.hpp
*
* C++ function status/error codes.
*
*/
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is OpenCMISS-Zinc Library.
*
* The Initial Developer of the Original Code is
* Auckland Uniservices Ltd, Auckland, New Zealand.
* Portions created by the Initial Developer are Copyright (C) 2013
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef CMZN_STATUS_HPP
#define CMZN_STATUS_HPP
namespace zinc
{
enum Status
{
ERROR_MEMORY = CMISS_ERROR_MEMORY,
/*!< failed to allocate memory. */
ERROR_ARGUMENT = CMISS_ERROR_ARGUMENT,
/*!< invalid argument(s) passed to API function. Only reported for new APIs. */
ERROR_GENERAL = CMISS_ERROR_GENERAL,
/*!< unspecified error occurred. Can include invalid argument(s) for old APIs. */
OK = CMISS_OK
/*!< value to be returned on success */
};
} // namespace zinc
#endif // CMZN_STATUS_HPP
|
/**
* FILE : status.hpp
*
* C++ function status/error codes.
*
*/
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is OpenCMISS-Zinc Library.
*
* The Initial Developer of the Original Code is
* Auckland Uniservices Ltd, Auckland, New Zealand.
* Portions created by the Initial Developer are Copyright (C) 2013
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef CMZN_STATUS_HPP
#define CMZN_STATUS_HPP
#include "zinc/status.h"
namespace zinc
{
enum Status
{
ERROR_MEMORY = CMISS_ERROR_MEMORY,
/*!< failed to allocate memory. */
ERROR_ARGUMENT = CMISS_ERROR_ARGUMENT,
/*!< invalid argument(s) passed to API function. Only reported for new APIs. */
ERROR_GENERAL = CMISS_ERROR_GENERAL,
/*!< unspecified error occurred. Can include invalid argument(s) for old APIs. */
OK = CMISS_OK
/*!< value to be returned on success */
};
} // namespace zinc
#endif // CMZN_STATUS_HPP
|
Fix include on C++ status header. Issue 3649.
|
Fix include on C++ status header. Issue 3649.
|
C++
|
mpl-2.0
|
hsorby/zinc,hsorby/zinc,OpenCMISS/zinc,hsorby/zinc,hsorby/zinc,OpenCMISS/zinc,OpenCMISS/zinc,OpenCMISS/zinc
|
73e09d25d02a8685a0fc026d0eff69b9e0325350
|
views/examples/widget_example.cc
|
views/examples/widget_example.cc
|
// Copyright (c) 2011 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 "views/examples/widget_example.h"
#include "views/controls/button/native_button.h"
#include "views/layout/box_layout.h"
#include "views/layout/layout_manager.h"
#include "views/view.h"
#if defined(OS_LINUX)
#include "views/widget/widget_gtk.h"
#endif
namespace {
// A layout manager that layouts a single child at
// the center of the host view.
class CenterLayout : public views::LayoutManager {
public:
CenterLayout() {}
virtual ~CenterLayout() {}
// Overridden from LayoutManager:
virtual void Layout(views::View* host) {
views::View* child = host->GetChildViewAt(0);
gfx::Size size = child->GetPreferredSize();
child->SetBounds((host->width() - size.width()) / 2,
(host->height() - size.height()) / 2,
size.width(), size.height());
}
virtual gfx::Size GetPreferredSize(views::View* host) {
return host->GetPreferredSize();
}
private:
DISALLOW_COPY_AND_ASSIGN(CenterLayout);
};
} // namespace
namespace examples {
WidgetExample::WidgetExample(ExamplesMain* main)
: ExampleBase(main) {
}
WidgetExample::~WidgetExample() {
}
std::wstring WidgetExample::GetExampleTitle() {
return L"Widget";
}
void WidgetExample::CreateExampleView(views::View* container) {
container->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0, 2));
BuildButton(container, L"Create a popup widget", POPUP);
BuildButton(container, L"Create a transparent popup widget",
TRANSPARENT_POPUP);
#if defined(OS_LINUX)
views::View* vert_container = new views::View();
container->AddChildView(vert_container);
vert_container->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 20));
BuildButton(vert_container, L"Create a child widget", CHILD);
BuildButton(vert_container, L"Create a transparent child widget",
TRANSPARENT_CHILD);
#endif
}
void WidgetExample::BuildButton(views::View* container,
const std::wstring& label,
int tag) {
views::TextButton* button = new views::TextButton(this, label);
button->set_tag(tag);
container->AddChildView(button);
}
void WidgetExample::InitWidget(
views::Widget* widget,
const views::Widget::TransparencyParam transparency) {
// Add view/native buttons to close the popup widget.
views::TextButton* close_button = new views::TextButton(this, L"Close");
close_button->set_tag(CLOSE_WIDGET);
// TODO(oshima): support transparent native view.
views::NativeButton* native_button =
new views::NativeButton(this, L"Native Close");
native_button->set_tag(CLOSE_WIDGET);
views::View* button_container = new views::View();
button_container->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0, 1));
button_container->AddChildView(close_button);
button_container->AddChildView(native_button);
views::View* widget_container = new views::View();
widget_container->SetLayoutManager(new CenterLayout);
widget_container->AddChildView(button_container);
widget->SetContentsView(widget_container);
if (transparency != views::Widget::Transparent) {
widget_container->set_background(
views::Background::CreateStandardPanelBackground());
}
// Show the widget.
widget->Show();
}
#if defined(OS_LINUX)
void WidgetExample::CreateChild(
views::View* parent,
const views::Widget::TransparencyParam transparency) {
views::WidgetGtk* widget =
new views::WidgetGtk(views::WidgetGtk::TYPE_CHILD);
if (transparency == views::Widget::Transparent)
widget->MakeTransparent();
// Compute where to place the child widget.
// We'll place it at the center of the root widget.
views::Widget* parent_widget = parent->GetWidget();
gfx::Rect bounds;
parent_widget->GetBounds(&bounds, false);
// Child widget is 200x200 square.
bounds.SetRect((bounds.width() - 200) / 2, (bounds.height() - 200) / 2,
200, 200);
// Initialize the child widget with the computed bounds.
widget->InitWithWidget(parent_widget, bounds);
InitWidget(widget, transparency);
}
#endif
void WidgetExample::CreatePopup(
views::View* parent,
const views::Widget::TransparencyParam transparency) {
views::Widget* widget = views::Widget::CreatePopupWidget(
transparency,
views::Widget::AcceptEvents,
views::Widget::DeleteOnDestroy,
views::Widget::MirrorOriginInRTL);
// Compute where to place the popup widget.
// We'll place it right below the create button.
gfx::Point point = parent->GetMirroredPosition();
// The position in point is relative to the parent. Make it absolute.
views::View::ConvertPointToScreen(parent, &point);
// Add the height of create_button_.
point.Offset(0, parent->size().height());
gfx::Rect bounds(point.x(), point.y(), 200, 300);
// Initialize the popup widget with the computed bounds.
widget->InitWithWidget(parent->GetWidget(), bounds);
InitWidget(widget, transparency);
}
void WidgetExample::ButtonPressed(views::Button* sender,
const views::Event& event) {
switch (sender->tag()) {
case POPUP:
CreatePopup(sender, views::Widget::NotTransparent);
break;
case TRANSPARENT_POPUP:
CreatePopup(sender, views::Widget::Transparent);
break;
#if defined(OS_LINUX)
case CHILD:
CreateChild(sender, views::Widget::NotTransparent);
break;
case TRANSPARENT_CHILD:
CreateChild(sender, views::Widget::Transparent);
break;
#endif
case CLOSE_WIDGET:
sender->GetWidget()->Close();
break;
}
}
} // namespace examples
|
// Copyright (c) 2011 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 "views/examples/widget_example.h"
#include "views/controls/button/native_button.h"
#include "views/layout/box_layout.h"
#include "views/layout/layout_manager.h"
#include "views/view.h"
#if defined(OS_LINUX)
#include "views/widget/widget_gtk.h"
#endif
namespace {
// A layout manager that layouts a single child at
// the center of the host view.
class CenterLayout : public views::LayoutManager {
public:
CenterLayout() {}
virtual ~CenterLayout() {}
// Overridden from LayoutManager:
virtual void Layout(views::View* host) {
views::View* child = host->GetChildViewAt(0);
gfx::Size size = child->GetPreferredSize();
child->SetBounds((host->width() - size.width()) / 2,
(host->height() - size.height()) / 2,
size.width(), size.height());
}
virtual gfx::Size GetPreferredSize(views::View* host) {
return host->GetPreferredSize();
}
private:
DISALLOW_COPY_AND_ASSIGN(CenterLayout);
};
} // namespace
namespace examples {
WidgetExample::WidgetExample(ExamplesMain* main)
: ExampleBase(main) {
}
WidgetExample::~WidgetExample() {
}
std::wstring WidgetExample::GetExampleTitle() {
return L"Widget";
}
void WidgetExample::CreateExampleView(views::View* container) {
container->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0, 2));
BuildButton(container, L"Create a popup widget", POPUP);
BuildButton(container, L"Create a transparent popup widget",
TRANSPARENT_POPUP);
#if defined(OS_LINUX)
views::View* vert_container = new views::View();
container->AddChildView(vert_container);
vert_container->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 20));
BuildButton(vert_container, L"Create a child widget", CHILD);
BuildButton(vert_container, L"Create a transparent child widget",
TRANSPARENT_CHILD);
#endif
}
void WidgetExample::BuildButton(views::View* container,
const std::wstring& label,
int tag) {
views::TextButton* button = new views::TextButton(this, label);
button->set_tag(tag);
container->AddChildView(button);
}
void WidgetExample::InitWidget(
views::Widget* widget,
const views::Widget::TransparencyParam transparency) {
// Add view/native buttons to close the popup widget.
views::TextButton* close_button = new views::TextButton(this, L"Close");
close_button->set_tag(CLOSE_WIDGET);
// TODO(oshima): support transparent native view.
views::NativeButton* native_button =
new views::NativeButton(this, L"Native Close");
native_button->set_tag(CLOSE_WIDGET);
views::View* button_container = new views::View();
button_container->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0, 1));
button_container->AddChildView(close_button);
button_container->AddChildView(native_button);
views::View* widget_container = new views::View();
widget_container->SetLayoutManager(new CenterLayout);
widget_container->AddChildView(button_container);
widget->SetContentsView(widget_container);
if (transparency != views::Widget::Transparent) {
widget_container->set_background(
views::Background::CreateStandardPanelBackground());
}
// Show the widget.
widget->Show();
}
#if defined(OS_LINUX)
void WidgetExample::CreateChild(
views::View* parent,
const views::Widget::TransparencyParam transparency) {
views::WidgetGtk* widget =
new views::WidgetGtk(views::WidgetGtk::TYPE_CHILD);
if (transparency == views::Widget::Transparent)
widget->MakeTransparent();
// Compute where to place the child widget.
// We'll place it at the center of the root widget.
views::Widget* parent_widget = parent->GetWidget();
gfx::Rect bounds = parent_widget->GetClientAreaScreenBounds();
// Child widget is 200x200 square.
bounds.SetRect((bounds.width() - 200) / 2, (bounds.height() - 200) / 2,
200, 200);
// Initialize the child widget with the computed bounds.
widget->InitWithWidget(parent_widget, bounds);
InitWidget(widget, transparency);
}
#endif
void WidgetExample::CreatePopup(
views::View* parent,
const views::Widget::TransparencyParam transparency) {
views::Widget* widget = views::Widget::CreatePopupWidget(
transparency,
views::Widget::AcceptEvents,
views::Widget::DeleteOnDestroy,
views::Widget::MirrorOriginInRTL);
// Compute where to place the popup widget.
// We'll place it right below the create button.
gfx::Point point = parent->GetMirroredPosition();
// The position in point is relative to the parent. Make it absolute.
views::View::ConvertPointToScreen(parent, &point);
// Add the height of create_button_.
point.Offset(0, parent->size().height());
gfx::Rect bounds(point.x(), point.y(), 200, 300);
// Initialize the popup widget with the computed bounds.
widget->InitWithWidget(parent->GetWidget(), bounds);
InitWidget(widget, transparency);
}
void WidgetExample::ButtonPressed(views::Button* sender,
const views::Event& event) {
switch (sender->tag()) {
case POPUP:
CreatePopup(sender, views::Widget::NotTransparent);
break;
case TRANSPARENT_POPUP:
CreatePopup(sender, views::Widget::Transparent);
break;
#if defined(OS_LINUX)
case CHILD:
CreateChild(sender, views::Widget::NotTransparent);
break;
case TRANSPARENT_CHILD:
CreateChild(sender, views::Widget::Transparent);
break;
#endif
case CLOSE_WIDGET:
sender->GetWidget()->Close();
break;
}
}
} // namespace examples
|
Fix compile for views_examples after GetBounds removal.
|
Fix compile for views_examples after GetBounds removal.
BUG=none
TEST=views_examples compiles
[email protected]
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@76776 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
chuan9/chromium-crosswalk,rogerwang/chromium,dednal/chromium.src,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,rogerwang/chromium,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,markYoungH/chromium.src,dushu1203/chromium.src,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,nacl-webkit/chrome_deps,jaruba/chromium.src,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,mogoweb/chromium-crosswalk,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,M4sse/chromium.src,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,dushu1203/chromium.src,Just-D/chromium-1,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,zcbenz/cefode-chromium,dushu1203/chromium.src,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,M4sse/chromium.src,markYoungH/chromium.src,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,markYoungH/chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,chuan9/chromium-crosswalk,patrickm/chromium.src,Jonekee/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,keishi/chromium,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,timopulkkinen/BubbleFish,keishi/chromium,littlstar/chromium.src,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,M4sse/chromium.src,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,rogerwang/chromium,anirudhSK/chromium,rogerwang/chromium,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,patrickm/chromium.src,timopulkkinen/BubbleFish,Jonekee/chromium.src,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,hujiajie/pa-chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,Just-D/chromium-1,keishi/chromium,rogerwang/chromium,hujiajie/pa-chromium,rogerwang/chromium,dushu1203/chromium.src,Chilledheart/chromium,bright-sparks/chromium-spacewalk,robclark/chromium,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,dednal/chromium.src,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,zcbenz/cefode-chromium,ltilve/chromium,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,dushu1203/chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,dushu1203/chromium.src,littlstar/chromium.src,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,nacl-webkit/chrome_deps,Jonekee/chromium.src,keishi/chromium,ltilve/chromium,rogerwang/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,ltilve/chromium,pozdnyakov/chromium-crosswalk,keishi/chromium,ondra-novak/chromium.src,zcbenz/cefode-chromium,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,littlstar/chromium.src,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,robclark/chromium,littlstar/chromium.src,mogoweb/chromium-crosswalk,rogerwang/chromium,Chilledheart/chromium,jaruba/chromium.src,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,Just-D/chromium-1,Just-D/chromium-1,robclark/chromium,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,rogerwang/chromium,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,robclark/chromium,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,keishi/chromium,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,keishi/chromium,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,jaruba/chromium.src,hujiajie/pa-chromium,patrickm/chromium.src,hgl888/chromium-crosswalk,patrickm/chromium.src,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,M4sse/chromium.src,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,ltilve/chromium,ondra-novak/chromium.src,jaruba/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,keishi/chromium,zcbenz/cefode-chromium,anirudhSK/chromium,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,dednal/chromium.src,Just-D/chromium-1,hujiajie/pa-chromium,robclark/chromium,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,keishi/chromium,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,keishi/chromium,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,M4sse/chromium.src,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,dednal/chromium.src,anirudhSK/chromium,Chilledheart/chromium,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,dednal/chromium.src,ondra-novak/chromium.src,markYoungH/chromium.src,rogerwang/chromium,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,ltilve/chromium,robclark/chromium,markYoungH/chromium.src,littlstar/chromium.src,ondra-novak/chromium.src,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,patrickm/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,Chilledheart/chromium,krieger-od/nwjs_chromium.src,anirudhSK/chromium,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,robclark/chromium,bright-sparks/chromium-spacewalk,dednal/chromium.src,jaruba/chromium.src,ondra-novak/chromium.src,anirudhSK/chromium,keishi/chromium,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,robclark/chromium,dednal/chromium.src,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,anirudhSK/chromium,dushu1203/chromium.src,Just-D/chromium-1,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk
|
02a6a607092c7301d6ecdb44cff12a8b447a6e3b
|
wilt-narray/narraydatablock.hpp
|
wilt-narray/narraydatablock.hpp
|
////////////////////////////////////////////////////////////////////////////////
// FILE: narraydatablock.hpp
// DATE: 2018-11-12
// AUTH: Trevor Wilson <[email protected]>
// DESC: Defines a shared-resource class for holding N-dimensional data
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2019 Trevor Wilson
//
// 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.
#ifndef WILT_NARRAYDATABLOCK_HPP
#define WILT_NARRAYDATABLOCK_HPP
#include <memory>
#include <cstddef>
#include <type_traits>
namespace wilt
{
enum NArrayDataAcquireType
{
ASSUME,
COPY,
REFERENCE
};
namespace detail
{
template <class T, class A = std::allocator<T>>
class NArrayDataBlock : public std::enable_shared_from_this<NArrayDataBlock<T, A>>
{
private:
////////////////////////////////////////////////////////////////////////////
// PRIVATE MEMBERS
////////////////////////////////////////////////////////////////////////////
T* data_;
std::size_t size_;
A alloc_;
bool owned_;
public:
////////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS
////////////////////////////////////////////////////////////////////////////
NArrayDataBlock()
: data_(nullptr),
size_(0),
alloc_(),
owned_(true)
{
}
NArrayDataBlock(std::size_t size)
: data_(nullptr),
size_(size),
alloc_(),
owned_(true)
{
data_ = alloc_.allocate(size);
if (!std::is_trivially_default_constructible<T>::value)
for (std::size_t i = 0; i < size; ++i)
alloc_.construct(data_ + i);
}
NArrayDataBlock(std::size_t size, const T& val)
: data_(nullptr),
size_(size),
alloc_(),
owned_(true)
{
data_ = alloc_.allocate(size);
for (std::size_t i = 0; i < size; ++i)
alloc_.construct(data_ + i, val);
}
NArrayDataBlock(std::size_t size, T* data, NArrayDataAcquireType atype)
: data_(nullptr),
size_(size),
alloc_(),
owned_(true)
{
switch (atype)
{
case wilt::ASSUME:
data_ = data;
break;
case wilt::COPY:
data_ = alloc_.allocate(size);
for (size_t i = 0; i < size; ++i)
alloc_.construct(data_ + i, data[i]);
break;
case wilt::REFERENCE:
data_ = data;
owned_ = false;
break;
}
}
template <class Generator>
NArrayDataBlock(std::size_t size, Generator gen)
: data_(nullptr),
size_(size),
alloc_(),
owned_(true)
{
data_ = alloc_.allocate(size);
for (std::size_t i = 0; i < size; ++i)
alloc_.construct(data_ + i, gen());
}
template <class Iterator>
NArrayDataBlock(std::size_t size, Iterator first, Iterator last)
: data_(nullptr),
size_(size),
alloc_(),
owned_(true)
{
data_ = alloc_.allocate(size);
std::size_t i = 0;
for (; i < size && first != last; ++i, ++first)
alloc_.construct(data_ + i, *first);
if (i != size)
for (; i < size; ++i)
alloc_.construct(data_ + i);
}
~NArrayDataBlock()
{
if (data_ && owned_)
{
if (!std::is_trivially_destructible<T>::value)
for (std::size_t i = 0; i < size_; ++i)
alloc_.destroy(data_ + i);
alloc_.deallocate(data_, size_);
}
}
public:
////////////////////////////////////////////////////////////////////////////
// ACCESS FUNCTIONS
////////////////////////////////////////////////////////////////////////////
std::shared_ptr<T> data() const
{
return std::shared_ptr<T>(shared_from_this(), data_);
}
}; // class NArrayDataBlock
} // namespace detail
} // namespace wilt
#endif // !WILT_NARRAYDATABLOCK_HPP
|
////////////////////////////////////////////////////////////////////////////////
// FILE: narraydatablock.hpp
// DATE: 2018-11-12
// AUTH: Trevor Wilson <[email protected]>
// DESC: Defines a shared-resource class for holding N-dimensional data
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2019 Trevor Wilson
//
// 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.
#ifndef WILT_NARRAYDATABLOCK_HPP
#define WILT_NARRAYDATABLOCK_HPP
#include <memory>
#include <cstddef>
#include <type_traits>
namespace wilt
{
enum NArrayDataAcquireType
{
ASSUME,
COPY,
REFERENCE
};
namespace detail
{
template <class T, class A = std::allocator<T>>
class NArrayDataBlock : public std::enable_shared_from_this<NArrayDataBlock<T, A>>
{
private:
////////////////////////////////////////////////////////////////////////////
// PRIVATE MEMBERS
////////////////////////////////////////////////////////////////////////////
T* data_;
std::size_t size_;
A alloc_;
bool owned_;
public:
////////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS
////////////////////////////////////////////////////////////////////////////
NArrayDataBlock()
: data_(nullptr),
size_(0),
alloc_(),
owned_(true)
{
}
NArrayDataBlock(std::size_t size)
: data_(nullptr),
size_(size),
alloc_(),
owned_(true)
{
data_ = std::allocator_traits<A>::allocate(alloc_, size);
if (!std::is_trivially_default_constructible<T>::value)
for (std::size_t i = 0; i < size; ++i)
std::allocator_traits<A>::construct(alloc_, data_ + i);
}
NArrayDataBlock(std::size_t size, const T& val)
: data_(nullptr),
size_(size),
alloc_(),
owned_(true)
{
data_ = std::allocator_traits<A>::allocate(alloc_, size);
for (std::size_t i = 0; i < size; ++i)
std::allocator_traits<A>::construct(alloc_, data_ + i, val);
}
NArrayDataBlock(std::size_t size, T* data, NArrayDataAcquireType atype)
: data_(nullptr),
size_(size),
alloc_(),
owned_(true)
{
switch (atype)
{
case wilt::ASSUME:
data_ = data;
break;
case wilt::COPY:
data_ = std::allocator_traits<A>::allocate(alloc_, size);
for (size_t i = 0; i < size; ++i)
std::allocator_traits<A>::construct(alloc_, data_ + i, data[i]);
break;
case wilt::REFERENCE:
data_ = data;
owned_ = false;
break;
}
}
template <class Generator>
NArrayDataBlock(std::size_t size, Generator gen)
: data_(nullptr),
size_(size),
alloc_(),
owned_(true)
{
data_ = std::allocator_traits<A>::allocate(alloc_, size);
for (std::size_t i = 0; i < size; ++i)
std::allocator_traits<A>::construct(alloc_, data_ + i, gen());
}
template <class Iterator>
NArrayDataBlock(std::size_t size, Iterator first, Iterator last)
: data_(nullptr),
size_(size),
alloc_(),
owned_(true)
{
data_ = std::allocator_traits<A>::allocate(alloc_, size);
std::size_t i = 0;
for (; i < size && first != last; ++i, ++first)
std::allocator_traits<A>::construct(alloc_, data_ + i, *first);
if (i != size)
for (; i < size; ++i)
std::allocator_traits<A>::construct(alloc_, data_ + i);
}
~NArrayDataBlock()
{
if (data_ && owned_)
{
if (!std::is_trivially_destructible<T>::value)
for (std::size_t i = 0; i < size_; ++i)
std::allocator_traits<A>::destroy(alloc_, data_ + i);
std::allocator_traits<A>::deallocate(alloc_, data_, size_);
}
}
public:
////////////////////////////////////////////////////////////////////////////
// ACCESS FUNCTIONS
////////////////////////////////////////////////////////////////////////////
std::shared_ptr<T> data() const
{
return std::shared_ptr<T>(shared_from_this(), data_);
}
}; // class NArrayDataBlock
} // namespace detail
} // namespace wilt
#endif // !WILT_NARRAYDATABLOCK_HPP
|
convert allocator calls to use allocator_traits
|
convert allocator calls to use allocator_traits
some allocator calls are deprecated in C++17 in lieu of static calls through `allocator_traits` due to changes and improvements in allocator behavior
|
C++
|
mit
|
kmdreko/wilt,kmdreko/wilt
|
df967b6a20060415a5aa6a062fd5dfd4cd17c783
|
Modules/Applications/AppDomainTransform/app/otbDomainTransform.cxx
|
Modules/Applications/AppDomainTransform/app/otbDomainTransform.cxx
|
/*=========================================================================
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.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbWaveletImageFilter.h"
#include "otbWaveletInverseImageFilter.h"
#include "otbWaveletGenerator.h"
#include <itkConfigure.h>
#include <itkForwardFFTImageFilter.h>
#include <itkInverseFFTImageFilter.h>
#include <itkUnaryFunctorImageFilter.h>
#include <itkFFTShiftImageFilter.h>
namespace otb
{
namespace Wrapper
{
template< class TInput, class TOutput>
class FromComplexPixel
{
public:
FromComplexPixel ( ) { };
~FromComplexPixel( ) { };
bool operator!=( const FromComplexPixel & ) const
{
return false;
}
bool operator==( const FromComplexPixel & other ) const
{
return !(*this != other);
}
inline TOutput operator( )( const TInput & A ) const
{
TOutput out;
out.SetSize(2);
out[0] = A.real();
out[1] = A.imag();
return out;
}
};
template< class TInput, class TOutput>
class ToComplexPixel
{
public:
ToComplexPixel ( ) { };
~ToComplexPixel( ) { };
bool operator!=( const ToComplexPixel & ) const
{
return false;
}
bool operator==( const ToComplexPixel & other ) const
{
return !(*this != other);
}
inline TOutput operator( )( const TInput & A ) const
{
TOutput out(A[0], A[1]);
return out;
}
};
class DomainTransform : public Application
{
public:
/** Standard class typedefs. */
typedef DomainTransform Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef float TInputPixel;
typedef float TOutputPixel;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(Self, otb::Application);
private:
void DoInit() ITK_OVERRIDE
{
SetName("DomainTransform");
const char * app_descr = "Domain Transform application for wavelet and fourier";
SetDescription(app_descr);
// Documentation
SetDocName(app_descr);
SetDocLongDescription("TODO");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("otbWaveletImageFilter, otbWaveletInverseImageFilter, otbWaveletTransform");
AddDocTag(Tags::Filter);
AddParameter(ParameterType_InputImage, "in", "Input Image");
SetParameterDescription("in", "This will take an input image to be transformed image. For FFT inverse transform, it expects a complex image as two-band image in which first band represent real part and second band represent imaginary part.");
AddRAMParameter();
AddParameter(ParameterType_Choice, "mode", "mode");
SetParameterDescription("mode", "This parameter allows one to select between fft(fourier) and wavelet");
AddChoice("mode.fft", "FFT transform");
SetParameterDescription("mode.fft", "FFT transform");
AddParameter(ParameterType_Empty, "mode.fft.shift", "false");
SetParameterDescription("mode.fft.shift",
"shift transform of fft filter");
AddChoice("mode.wavelet", "wavelet");
SetParameterDescription("mode.wavelet", "Wavelet transform");
AddParameter(ParameterType_Choice,
"mode.wavelet.form",
"Select wavelet form. default is HAAR");
AddChoice("mode.wavelet.form.haar", "HAAR");
AddChoice("mode.wavelet.form.db4", "DAUBECHIES4");
AddChoice("mode.wavelet.form.db6", "DAUBECHIES6");
AddChoice("mode.wavelet.form.db8", "DAUBECHIES8");
AddChoice("mode.wavelet.form.db12", "DAUBECHIES12");
AddChoice("mode.wavelet.form.db20", "DAUBECHIES20");
AddChoice("mode.wavelet.form.sb24", "SPLINE_BIORTHOGONAL_2_4");
AddChoice("mode.wavelet.form.sb44", "SPLINE_BIORTHOGONAL_4_4");
AddChoice("mode.wavelet.form.sym8", "SYMLET8");
//Default value
SetParameterString("mode", "wavelet");
SetParameterString("mode.wavelet.form", "haar");
AddParameter(ParameterType_Int,"mode.wavelet.nlevels","Number of decomposition levels");
SetParameterDescription("mode.wavelet.nlevels","Number of decomposition levels");
SetDefaultParameterInt("mode.wavelet.nlevels",2);
SetMinimumParameterIntValue("mode.wavelet.nlevels",2);
AddParameter(ParameterType_Choice,
"dir",
"dir: forward/inverse");
AddChoice("dir.fwd", "fwd");
AddChoice("dir.inv", "inv");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "This parameter holds the output file name to which transformed image will be written. This has a slightly different behaviour depending on transform type. \n For Wavelet, output is a single band image for both forward and inverse transform. \n For FFT forward transform, output is two band image where first band represents real part and second band represents imaginary part of a complex image.");
SetDocExampleParameterValue("in", "input.tif");
SetDocExampleParameterValue("mode.wavelet.form", "haar");
SetDocExampleParameterValue("out", "output_wavelet_haar.tif");
}
void DoUpdateParameters() ITK_OVERRIDE
{
// wavelet and fourier are mutually exclusive parameters.
// check it here
#if 0
if ( HasUserValue("mode.wavelet.form") &&
GetParameterString("mode") == "fft"
)
{
std::stringstream oss;
oss << std::endl
<< this->GetNameOfClass() << "::DoUpdateParameters() "
<< "Cannot use 'mode.wavelet.form' and '-mode fft' at same time"
<< std::endl;
throw std::runtime_error( oss.str() );
}
#endif
}
void DoExecute() ITK_OVERRIDE
{
int dir = GetParameterInt("dir");
int mode = GetParameterInt("mode");
if( dir != 0 && dir != 1)
{
itkExceptionMacro( << "-dir is '"
<< dir << "'."
<< "It must be either 'fwd' or 'inv'");
}
if( mode != 0 && mode != 1)
{
itkExceptionMacro( << "mode is '"
<< mode << "'."
<< "It must must be either 'fft' or 'wavelet'");
}
if ( mode == 1)
{
int wavelet_type = GetParameterInt("mode.wavelet.form");
unsigned int nlevels = GetParameterInt("mode.wavelet.nlevels");
switch (wavelet_type)
{
case 0:
DoWaveletTransform<otb::Wavelet::HAAR> ( dir, nlevels );
break;
case 1:
DoWaveletTransform< otb::Wavelet::DB4 > ( dir, nlevels );
break;
case 2:
DoWaveletTransform<otb::Wavelet::DB4> ( dir, nlevels );
break;
case 3:
DoWaveletTransform<otb::Wavelet::DB6> ( dir, nlevels );
break;
case 4:
DoWaveletTransform<otb::Wavelet::DB8> ( dir, nlevels );
break;
case 5:
DoWaveletTransform<otb::Wavelet::DB12> ( dir, nlevels );
break;
case 6:
DoWaveletTransform<otb::Wavelet::DB20> ( dir, nlevels );
break;
case 7:
DoWaveletTransform<otb::Wavelet::SPLINE_BIORTHOGONAL_2_4 > ( dir, nlevels );
break;
case 8:
DoWaveletTransform<otb::Wavelet::SPLINE_BIORTHOGONAL_4_4> ( dir, nlevels );
break;
case 9:
DoWaveletTransform<otb::Wavelet::SYMLET8> ( dir, nlevels );
break;
default:
itkExceptionMacro( << "Invalid wavelet type: '" << wavelet_type << "'");
break;
}
}
// fft ttransform
else
{
bool shift = IsParameterEnabled( "mode.fft.shift");
//forward fft
if (dir == 0 )
{
typedef otb::Image<TInputPixel> TInputImage;
typedef TInputImage::Pointer TInputImagePointer;
//get input paramter as otb::Image<TInputPixel>
TInputImagePointer inImage = GetParameterImage<TInputImage>("in");
inImage->UpdateOutputInformation();
//typedef itk::::ForwardFFTImageFilter over otbImage< TInputPixel >
typedef itk::ForwardFFTImageFilter < TInputImage> FFTFilter;
FFTFilter::Pointer fwdFilter = FFTFilter::New();
fwdFilter->SetInput( inImage );
//typedef VectorImage for output of UnaryFunctorImageFilter
typedef otb::VectorImage<TOutputPixel> TOutputImage;
//UnaryFunctorImageFilter for Complex to VectorImage
typedef itk::UnaryFunctorImageFilter<
typename FFTFilter::OutputImageType,
TOutputImage,
FromComplexPixel<
typename FFTFilter::OutputImageType::PixelType,
TOutputImage::PixelType> > UnaryFunctorImageFilter;
//convert complex pixel to variable length vector
//with unaryfunctor image filter
UnaryFunctorImageFilter::Pointer unaryFunctorImageFilter
= UnaryFunctorImageFilter::New();
if( shift)
{
otbAppLogINFO( << "Applying Shift image filter" );
typedef itk::FFTShiftImageFilter<
typename FFTFilter::OutputImageType,
typename FFTFilter::OutputImageType > FFTShiftFilterType;
FFTShiftFilterType::Pointer
fftShiftFilter = FFTShiftFilterType::New();
fftShiftFilter->SetInput( fwdFilter->GetOutput() );
fftShiftFilter->Update();
unaryFunctorImageFilter->SetInput(fftShiftFilter->GetOutput() );
}
else
{
unaryFunctorImageFilter->SetInput(fwdFilter->GetOutput());
}
unaryFunctorImageFilter->Update();
//set output image
SetParameterOutputImage<TOutputImage>
( "out", unaryFunctorImageFilter->GetOutput() );
}
//inverse fft
else
{
typedef otb::VectorImage<TInputPixel> TInputImage;
typedef TInputImage::Pointer TInputImagePointer;
TInputImagePointer inImage = GetParameterImage("in");
inImage->UpdateOutputInformation();
// typedef TComplexImage for InverseFFTImageFilter input
// This a image type of std::complex<TInputPixel>
typedef otb::Image<
std::complex<TInputPixel>, 2 > TComplexImage;
//typedef TOutputImage for InverseFFTImageFilter output
typedef otb::Image< TOutputPixel > TOutputImage;
// a unary functor to convert vectorimage to complex image
typedef itk::UnaryFunctorImageFilter
<TInputImage,
TComplexImage,
ToComplexPixel
<TInputImage::PixelType,
TComplexImage::PixelType> > UnaryFunctorImageFilter;
UnaryFunctorImageFilter::Pointer
unaryFunctorImageFilter = UnaryFunctorImageFilter::New();
if( shift)
{
typedef itk::FFTShiftImageFilter<
TInputImage,
TInputImage > FFTShiftFilterType;
FFTShiftFilterType::Pointer
fftShiftFilter = FFTShiftFilterType::New();
fftShiftFilter->SetInput( inImage );
fftShiftFilter->Update();
unaryFunctorImageFilter->SetInput(fftShiftFilter->GetOutput() );
}
else
{
unaryFunctorImageFilter->SetInput(inImage);
}
unaryFunctorImageFilter->Update();
//typedef itk::::InverseFFTImageFilter over TComplexImage
typedef itk::InverseFFTImageFilter
< TComplexImage,
TOutputImage > FFTFilter;
FFTFilter::Pointer invFilter = FFTFilter::New();
invFilter->SetInput( unaryFunctorImageFilter->GetOutput() );
invFilter->Update();
//set output image
SetParameterOutputImage<
TOutputImage >
( "out", invFilter->GetOutput() );
}
}
}
template<otb::Wavelet::Wavelet TWaveletOperator>
void DoWaveletTransform(const int dir,
const unsigned int nlevels,
const std::string inkey = "in",
const std::string outkey = "out")
{
typedef otb::Image< TInputPixel > TInputImage;
typedef otb::Image< TOutputPixel > TOutputImage;
typedef typename TInputImage::Pointer TInputImagePointer;
TInputImagePointer inImage = GetParameterImage<TInputImage>(inkey);
inImage->UpdateOutputInformation();
if( dir == 0)
{
typedef otb::WaveletImageFilter<
TInputImage,
TOutputImage,
TWaveletOperator> TWaveletImageFilter;
typedef typename
TWaveletImageFilter::Pointer
TWaveletImageFilterPointer;
TWaveletImageFilterPointer waveletImageFilter =
TWaveletImageFilter::New();
waveletImageFilter->SetInput(inImage);
waveletImageFilter->SetNumberOfDecompositions(nlevels);
waveletImageFilter->Update();
SetParameterOutputImage<TOutputImage>(outkey, waveletImageFilter->GetOutput() );
}
else
{
typedef otb::WaveletInverseImageFilter<
TInputImage,
TOutputImage,
TWaveletOperator > TWaveletImageFilter;
typedef typename
TWaveletImageFilter::Pointer
TWaveletImageFilterPointer;
TWaveletImageFilterPointer waveletImageFilter =
TWaveletImageFilter::New();
waveletImageFilter->SetInput(inImage);
waveletImageFilter->SetNumberOfDecompositions(nlevels);
waveletImageFilter->Update();
SetParameterOutputImage<TOutputImage>( outkey, waveletImageFilter->GetOutput() );
}
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::DomainTransform)
|
/*=========================================================================
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.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbWaveletImageFilter.h"
#include "otbWaveletInverseImageFilter.h"
#include "otbWaveletGenerator.h"
#include <itkConfigure.h>
#include <itkForwardFFTImageFilter.h>
#include <itkInverseFFTImageFilter.h>
#include <itkUnaryFunctorImageFilter.h>
#include <itkFFTShiftImageFilter.h>
namespace otb
{
namespace Wrapper
{
template< class TInput, class TOutput>
class FromComplexPixel
{
public:
FromComplexPixel ( ) { };
~FromComplexPixel( ) { };
bool operator!=( const FromComplexPixel & ) const
{
return false;
}
bool operator==( const FromComplexPixel & other ) const
{
return !(*this != other);
}
inline TOutput operator( )( const TInput & A ) const
{
TOutput out;
out.SetSize(2);
out[0] = A.real();
out[1] = A.imag();
return out;
}
};
template< class TInput, class TOutput>
class ToComplexPixel
{
public:
ToComplexPixel ( ) { };
~ToComplexPixel( ) { };
bool operator!=( const ToComplexPixel & ) const
{
return false;
}
bool operator==( const ToComplexPixel & other ) const
{
return !(*this != other);
}
inline TOutput operator( )( const TInput & A ) const
{
TOutput out(A[0], A[1]);
return out;
}
};
class DomainTransform : public Application
{
public:
/** Standard class typedefs. */
typedef DomainTransform Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef float TInputPixel;
typedef float TOutputPixel;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(Self, otb::Application);
private:
void DoInit() ITK_OVERRIDE
{
SetName("DomainTransform");
SetDescription("Domain Transform application for wavelet and fourier");
// Documentation
SetDocName("DomainTransform");
SetDocLongDescription("Domain Transform application for wavelet and fourier");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("otbWaveletImageFilter, otbWaveletInverseImageFilter, otbWaveletTransform");
AddDocTag(Tags::Filter);
AddParameter(ParameterType_InputImage, "in", "Input Image");
SetParameterDescription("in", "This will take an input image to be transformed image. For FFT inverse transform, it expects a complex image as two-band image in which first band represent real part and second band represent imaginary part.");
AddRAMParameter();
AddParameter(ParameterType_Choice, "mode", "mode");
SetParameterDescription("mode", "This parameter allows one to select between fft(fourier) and wavelet");
AddChoice("mode.fft", "FFT transform");
SetParameterDescription("mode.fft", "FFT transform");
AddParameter(ParameterType_Empty, "mode.fft.shift", "false");
SetParameterDescription("mode.fft.shift",
"shift transform of fft filter");
AddChoice("mode.wavelet", "wavelet");
SetParameterDescription("mode.wavelet", "Wavelet transform");
AddParameter(ParameterType_Choice,
"mode.wavelet.form",
"Select wavelet form. default is HAAR");
AddChoice("mode.wavelet.form.haar", "HAAR");
AddChoice("mode.wavelet.form.db4", "DAUBECHIES4");
AddChoice("mode.wavelet.form.db6", "DAUBECHIES6");
AddChoice("mode.wavelet.form.db8", "DAUBECHIES8");
AddChoice("mode.wavelet.form.db12", "DAUBECHIES12");
AddChoice("mode.wavelet.form.db20", "DAUBECHIES20");
AddChoice("mode.wavelet.form.sb24", "SPLINE_BIORTHOGONAL_2_4");
AddChoice("mode.wavelet.form.sb44", "SPLINE_BIORTHOGONAL_4_4");
AddChoice("mode.wavelet.form.sym8", "SYMLET8");
//Default value
SetParameterString("mode", "wavelet");
SetParameterString("mode.wavelet.form", "haar");
AddParameter(ParameterType_Int,"mode.wavelet.nlevels","Number of decomposition levels");
SetParameterDescription("mode.wavelet.nlevels","Number of decomposition levels");
SetDefaultParameterInt("mode.wavelet.nlevels",2);
SetMinimumParameterIntValue("mode.wavelet.nlevels",2);
AddParameter(ParameterType_Choice,
"dir",
"dir: forward/inverse");
AddChoice("dir.fwd", "fwd");
AddChoice("dir.inv", "inv");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "This parameter holds the output file name to which transformed image will be written. This has a slightly different behaviour depending on transform type. \n For Wavelet, output is a single band image for both forward and inverse transform. \n For FFT forward transform, output is two band image where first band represents real part and second band represents imaginary part of a complex image.");
SetDocExampleParameterValue("in", "input.tif");
SetDocExampleParameterValue("mode.wavelet.form", "haar");
SetDocExampleParameterValue("out", "output_wavelet_haar.tif");
}
void DoUpdateParameters() ITK_OVERRIDE
{
// wavelet and fourier are mutually exclusive parameters.
// check it here
#if 0
if ( HasUserValue("mode.wavelet.form") &&
GetParameterString("mode") == "fft"
)
{
std::stringstream oss;
oss << std::endl
<< this->GetNameOfClass() << "::DoUpdateParameters() "
<< "Cannot use 'mode.wavelet.form' and '-mode fft' at same time"
<< std::endl;
throw std::runtime_error( oss.str() );
}
#endif
}
void DoExecute() ITK_OVERRIDE
{
int dir = GetParameterInt("dir");
int mode = GetParameterInt("mode");
if( dir != 0 && dir != 1)
{
itkExceptionMacro( << "-dir is '"
<< dir << "'."
<< "It must be either 'fwd' or 'inv'");
}
if( mode != 0 && mode != 1)
{
itkExceptionMacro( << "mode is '"
<< mode << "'."
<< "It must must be either 'fft' or 'wavelet'");
}
if ( mode == 1)
{
int wavelet_type = GetParameterInt("mode.wavelet.form");
unsigned int nlevels = GetParameterInt("mode.wavelet.nlevels");
switch (wavelet_type)
{
case 0:
DoWaveletTransform<otb::Wavelet::HAAR> ( dir, nlevels );
break;
case 1:
DoWaveletTransform< otb::Wavelet::DB4 > ( dir, nlevels );
break;
case 2:
DoWaveletTransform<otb::Wavelet::DB4> ( dir, nlevels );
break;
case 3:
DoWaveletTransform<otb::Wavelet::DB6> ( dir, nlevels );
break;
case 4:
DoWaveletTransform<otb::Wavelet::DB8> ( dir, nlevels );
break;
case 5:
DoWaveletTransform<otb::Wavelet::DB12> ( dir, nlevels );
break;
case 6:
DoWaveletTransform<otb::Wavelet::DB20> ( dir, nlevels );
break;
case 7:
DoWaveletTransform<otb::Wavelet::SPLINE_BIORTHOGONAL_2_4 > ( dir, nlevels );
break;
case 8:
DoWaveletTransform<otb::Wavelet::SPLINE_BIORTHOGONAL_4_4> ( dir, nlevels );
break;
case 9:
DoWaveletTransform<otb::Wavelet::SYMLET8> ( dir, nlevels );
break;
default:
itkExceptionMacro( << "Invalid wavelet type: '" << wavelet_type << "'");
break;
}
}
// fft ttransform
else
{
bool shift = IsParameterEnabled( "mode.fft.shift");
//forward fft
if (dir == 0 )
{
typedef otb::Image<TInputPixel> TInputImage;
typedef TInputImage::Pointer TInputImagePointer;
//get input paramter as otb::Image<TInputPixel>
TInputImagePointer inImage = GetParameterImage<TInputImage>("in");
inImage->UpdateOutputInformation();
//typedef itk::::ForwardFFTImageFilter over otbImage< TInputPixel >
typedef itk::ForwardFFTImageFilter < TInputImage> FFTFilter;
FFTFilter::Pointer fwdFilter = FFTFilter::New();
fwdFilter->SetInput( inImage );
//typedef VectorImage for output of UnaryFunctorImageFilter
typedef otb::VectorImage<TOutputPixel> TOutputImage;
//UnaryFunctorImageFilter for Complex to VectorImage
typedef itk::UnaryFunctorImageFilter<
typename FFTFilter::OutputImageType,
TOutputImage,
FromComplexPixel<
typename FFTFilter::OutputImageType::PixelType,
TOutputImage::PixelType> > UnaryFunctorImageFilter;
//convert complex pixel to variable length vector
//with unaryfunctor image filter
UnaryFunctorImageFilter::Pointer unaryFunctorImageFilter
= UnaryFunctorImageFilter::New();
if( shift)
{
otbAppLogINFO( << "Applying Shift image filter" );
typedef itk::FFTShiftImageFilter<
typename FFTFilter::OutputImageType,
typename FFTFilter::OutputImageType > FFTShiftFilterType;
FFTShiftFilterType::Pointer
fftShiftFilter = FFTShiftFilterType::New();
fftShiftFilter->SetInput( fwdFilter->GetOutput() );
fftShiftFilter->Update();
unaryFunctorImageFilter->SetInput(fftShiftFilter->GetOutput() );
}
else
{
unaryFunctorImageFilter->SetInput(fwdFilter->GetOutput());
}
unaryFunctorImageFilter->Update();
//set output image
SetParameterOutputImage<TOutputImage>
( "out", unaryFunctorImageFilter->GetOutput() );
}
//inverse fft
else
{
typedef otb::VectorImage<TInputPixel> TInputImage;
typedef TInputImage::Pointer TInputImagePointer;
TInputImagePointer inImage = GetParameterImage("in");
inImage->UpdateOutputInformation();
// typedef TComplexImage for InverseFFTImageFilter input
// This a image type of std::complex<TInputPixel>
typedef otb::Image<
std::complex<TInputPixel>, 2 > TComplexImage;
//typedef TOutputImage for InverseFFTImageFilter output
typedef otb::Image< TOutputPixel > TOutputImage;
// a unary functor to convert vectorimage to complex image
typedef itk::UnaryFunctorImageFilter
<TInputImage,
TComplexImage,
ToComplexPixel
<TInputImage::PixelType,
TComplexImage::PixelType> > UnaryFunctorImageFilter;
UnaryFunctorImageFilter::Pointer
unaryFunctorImageFilter = UnaryFunctorImageFilter::New();
if( shift)
{
typedef itk::FFTShiftImageFilter<
TInputImage,
TInputImage > FFTShiftFilterType;
FFTShiftFilterType::Pointer
fftShiftFilter = FFTShiftFilterType::New();
fftShiftFilter->SetInput( inImage );
fftShiftFilter->Update();
unaryFunctorImageFilter->SetInput(fftShiftFilter->GetOutput() );
}
else
{
unaryFunctorImageFilter->SetInput(inImage);
}
unaryFunctorImageFilter->Update();
//typedef itk::::InverseFFTImageFilter over TComplexImage
typedef itk::InverseFFTImageFilter
< TComplexImage,
TOutputImage > FFTFilter;
FFTFilter::Pointer invFilter = FFTFilter::New();
invFilter->SetInput( unaryFunctorImageFilter->GetOutput() );
invFilter->Update();
//set output image
SetParameterOutputImage<
TOutputImage >
( "out", invFilter->GetOutput() );
}
}
}
template<otb::Wavelet::Wavelet TWaveletOperator>
void DoWaveletTransform(const int dir,
const unsigned int nlevels,
const std::string inkey = "in",
const std::string outkey = "out")
{
typedef otb::Image< TInputPixel > TInputImage;
typedef otb::Image< TOutputPixel > TOutputImage;
typedef typename TInputImage::Pointer TInputImagePointer;
TInputImagePointer inImage = GetParameterImage<TInputImage>(inkey);
inImage->UpdateOutputInformation();
if( dir == 0)
{
typedef otb::WaveletImageFilter<
TInputImage,
TOutputImage,
TWaveletOperator> TWaveletImageFilter;
typedef typename
TWaveletImageFilter::Pointer
TWaveletImageFilterPointer;
TWaveletImageFilterPointer waveletImageFilter =
TWaveletImageFilter::New();
waveletImageFilter->SetInput(inImage);
waveletImageFilter->SetNumberOfDecompositions(nlevels);
waveletImageFilter->Update();
SetParameterOutputImage<TOutputImage>(outkey, waveletImageFilter->GetOutput() );
}
else
{
typedef otb::WaveletInverseImageFilter<
TInputImage,
TOutputImage,
TWaveletOperator > TWaveletImageFilter;
typedef typename
TWaveletImageFilter::Pointer
TWaveletImageFilterPointer;
TWaveletImageFilterPointer waveletImageFilter =
TWaveletImageFilter::New();
waveletImageFilter->SetInput(inImage);
waveletImageFilter->SetNumberOfDecompositions(nlevels);
waveletImageFilter->Update();
SetParameterOutputImage<TOutputImage>( outkey, waveletImageFilter->GetOutput() );
}
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::DomainTransform)
|
fix DocLongDescription too small
|
TEST: fix DocLongDescription too small
|
C++
|
apache-2.0
|
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
|
a6af9e78873cac68ea5b53e84936f289526e882f
|
include/util/datastream/topk/cms/TopKItemEstimation.hpp
|
include/util/datastream/topk/cms/TopKItemEstimation.hpp
|
/*
* @file TopKItemEstimation.hpp
* @author Kuilong Liu
* @date 2013.04.24
* @ TopKItem by count min sketch
*/
#ifndef IZENELIB_UTIL_TOPKITEM_ESTIMATION_H_
#define IZENELIB_UTIL_TOPKITEM_ESTIMATION_H_
#include <list>
#include <iterator>
#include <iostream>
#include <boost/unordered_map.hpp>
#include <boost/shared_ptr.hpp>
namespace izenelib { namespace util {
template<typename ElemType, typename CountType>
class Bucket;
template<typename ElemType, typename CountType>
class Item
{
public:
typedef Bucket<ElemType, CountType> BucketT;
typedef Item<ElemType, CountType> ItemT;
Item(ElemType e, BucketT* b, ItemT* p, ItemT* n)
:elem_(e), b_(b), prev_(p), next_(n)
{
}
~Item()
{
b_ = NULL;
if(next_)delete next_;
}
ElemType elem_;
BucketT* b_;
ItemT* prev_;
ItemT* next_;
};
template<typename ElemType, typename CountType>
class Bucket
{
public:
typedef Item<ElemType, CountType> ItemT;
typedef Bucket<ElemType, CountType> BucketT;
Bucket(CountType c, BucketT* p, BucketT* n)
:size_(0), c_(c), head_(NULL), end_(NULL), prev_(p), next_(n)
{
}
~Bucket()
{
if(head_)delete head_;
if(next_)delete next_;
}
bool insert(ItemT* i)
{
if(size_==0)
{
head_=end_=i;
i->prev_=NULL;
}
else
{
end_->next_=i;
i->prev_=end_;
end_=i;
}
i->b_=this;
i->next_=NULL;
size_++;
return true;
}
bool erase(ItemT* i)
{
if(size_==1)
{
head_=end_=NULL;
}
else if(i->next_==NULL)
{
end_=end_->prev_;
end_->next_=NULL;
}
else if(i->prev_==NULL)
{
head_=i->next_;
head_->prev_=NULL;
}
else
{
i->prev_->next_=i->next_;
i->next_->prev_=i->prev_;
}
size_--;
i->prev_=i->next_=NULL;
i->b_=NULL;
return true;
}
CountType size_;
CountType c_;
ItemT* head_;
ItemT* end_;
BucketT* prev_;
BucketT* next_;
};
template<typename ElemType, typename CountType>
class TopKEstimation
{
public:
typedef Bucket<ElemType, CountType> BucketT;
typedef Item<ElemType, CountType> ItemT;
TopKEstimation(CountType m)
:MAXSIZE_(m),
size_(0),
th_(0)
{
bs_ = new BucketT(0, NULL, NULL);
end_=bs_;
}
~TopKEstimation()
{
if(bs_)delete bs_;
gps_.clear();
}
bool reset()
{
if(bs_) delete bs_;
bs_=new BucketT(0, NULL, NULL);
gps_.clear();
size_=th_=0;
return true;
}
bool insert(ElemType elem, CountType count)
{
if(gps_.find(elem) != gps_.end())
{
return update(elem, count);
}
else if(size_ >= MAXSIZE_ && count <= th_)
return true;
else if(size_ >= MAXSIZE_)
{
return replace(elem, count);
}
else
{
return additem(elem, count);
}
}
bool get(std::list<ElemType>& elem, std::list<CountType>& count)
{
BucketT* bp = bs_->next_;
while(bp)
{
ItemT* i=bp->head_;
while(i)
{
elem.push_front(i->elem_);
count.push_front(i->b_->c_);
i=i->next_;
}
bp=bp->next_;
}
return true;
}
bool get(std::list<std::pair<ElemType, CountType> >& topk)
{
BucketT* bp = bs_->next_;
while(bp)
{
ItemT* i=bp->head_;
while(i)
{
topk.push_front(make_pair(i->elem_, i->b_->c_));
i=i->next_;
}
bp=bp->next_;
}
return true;
}
bool get(CountType k, std::list<std::pair<ElemType, CountType> >& topk)
{
BucketT* bp = end_;
CountType tempk=0;
while(bp!=bs_)
{
ItemT* i=bp->head_;
while(i)
{
topk.push_back(make_pair(i->elem_, i->b_->c_));
tempk++;
if(tempk >= k || tempk >= size_)break;
i=i->next_;
}
if(tempk >= k || tempk >= size_)break;
bp=bp->prev_;
}
return true;
}
private:
bool update(ElemType elem, CountType count)
{
ItemT* i = gps_[elem];
BucketT* bp = i->b_;
count = bp->c_+1;
if(bp->size_==1 && (!(bp->next_) || bp->next_->c_ > count))
{
bp->c_++;
th_ = bs_->next_->c_;
return true;
}
bp->erase(i);
if(!(bp->next_))
{
bp->next_=new BucketT(count, bp, NULL);
end_=bp->next_;
}
else if(bp->next_->c_ > count)
{
BucketT* tp=new BucketT(count, bp, bp->next_);
bp->next_=tp;
tp->next_->prev_=tp;
}
bp->next_->insert(i);
if(bp->size_==0)
{
bp->prev_->next_=bp->next_;
bp->next_->prev_=bp->prev_;
bp->next_=bp->prev_=NULL;
delete bp;
}
return true;
}
bool replace(ElemType elem, CountType count)
{
count = bs_->next_->c_+1;
ItemT* i = bs_->next_->end_;
gps_.erase(gps_.find(i->elem_));
gps_[elem] = i;
i->elem_=elem;
return update(elem,count);
}
bool additem(ElemType elem, CountType count)
{
count=1;
if(bs_->next_==NULL)
{
bs_->next_=new BucketT(count, bs_, NULL);
end_=bs_->next_;
}
BucketT* bp=bs_->next_;
ItemT* i=new ItemT(elem, bp, NULL, NULL);
if(bp->c_ == count)
{
bp->insert(i);
}
else
{
BucketT* nbp = new BucketT(count, bs_, bs_->next_);
bs_->next_ = nbp;
nbp->next_->prev_=nbp;
nbp->insert(i);
}
size_++;
gps_[elem]=i;
th_=bs_->next_->c_;
return true;
}
CountType MAXSIZE_;
//current size
CountType size_;
//threshold
CountType th_;
BucketT* bs_;
BucketT* end_;
boost::unordered_map<ElemType, ItemT* > gps_;
};
} //end of namespace util
} //end of namespace izenelib
#endif
|
/*
* @file TopKItemEstimation.hpp
* @author Kuilong Liu
* @date 2013.04.24
* @ TopKItem by count min sketch
*/
#ifndef IZENELIB_UTIL_TOPKITEM_ESTIMATION_H_
#define IZENELIB_UTIL_TOPKITEM_ESTIMATION_H_
#include <list>
#include <iterator>
#include <iostream>
#include <boost/unordered_map.hpp>
#include <boost/shared_ptr.hpp>
namespace izenelib { namespace util {
template<typename ElemType, typename CountType>
class Bucket;
template<typename ElemType, typename CountType>
class Item
{
public:
typedef Bucket<ElemType, CountType> BucketT;
typedef Item<ElemType, CountType> ItemT;
Item(ElemType e, BucketT* b, ItemT* p, ItemT* n)
:elem_(e), b_(b), prev_(p), next_(n)
{
}
~Item()
{
b_ = NULL;
if(next_)delete next_;
}
ElemType elem_;
BucketT* b_;
ItemT* prev_;
ItemT* next_;
};
template<typename ElemType, typename CountType>
class Bucket
{
public:
typedef Item<ElemType, CountType> ItemT;
typedef Bucket<ElemType, CountType> BucketT;
Bucket(CountType c, BucketT* p, BucketT* n)
:size_(0), c_(c), head_(NULL), end_(NULL), prev_(p), next_(n)
{
}
~Bucket()
{
if(head_)delete head_;
if(next_)delete next_;
}
bool insert(ItemT* i)
{
if(size_==0)
{
head_=end_=i;
i->prev_=NULL;
}
else
{
end_->next_=i;
i->prev_=end_;
end_=i;
}
i->b_=this;
i->next_=NULL;
size_++;
return true;
}
bool erase(ItemT* i)
{
if(size_==1)
{
head_=end_=NULL;
}
else if(i->next_==NULL)
{
end_=end_->prev_;
end_->next_=NULL;
}
else if(i->prev_==NULL)
{
head_=i->next_;
head_->prev_=NULL;
}
else
{
i->prev_->next_=i->next_;
i->next_->prev_=i->prev_;
}
size_--;
i->prev_=i->next_=NULL;
i->b_=NULL;
return true;
}
CountType size_;
CountType c_;
ItemT* head_;
ItemT* end_;
BucketT* prev_;
BucketT* next_;
};
template<typename ElemType, typename CountType>
class TopKEstimation
{
public:
typedef Bucket<ElemType, CountType> BucketT;
typedef Item<ElemType, CountType> ItemT;
TopKEstimation(CountType m)
:MAXSIZE_(m),
size_(0),
th_(0)
{
bs_ = new BucketT(0, NULL, NULL);
end_=bs_;
}
~TopKEstimation()
{
if(bs_)delete bs_;
gps_.clear();
}
bool reset()
{
if(bs_) delete bs_;
bs_=new BucketT(0, NULL, NULL);
end_=bs_;
gps_.clear();
size_=th_=0;
return true;
}
bool insert(ElemType elem, CountType count)
{
if(gps_.find(elem) != gps_.end())
{
return update(elem, count);
}
else if(size_ >= MAXSIZE_ && count <= th_)
return true;
else if(size_ >= MAXSIZE_)
{
return replace(elem, count);
}
else
{
return additem(elem, count);
}
}
bool get(std::list<ElemType>& elem, std::list<CountType>& count)
{
BucketT* bp = bs_->next_;
while(bp)
{
ItemT* i=bp->head_;
while(i)
{
elem.push_front(i->elem_);
count.push_front(i->b_->c_);
i=i->next_;
}
bp=bp->next_;
}
return true;
}
bool get(std::list<std::pair<ElemType, CountType> >& topk)
{
BucketT* bp = bs_->next_;
while(bp)
{
ItemT* i=bp->head_;
while(i)
{
topk.push_front(make_pair(i->elem_, i->b_->c_));
i=i->next_;
}
bp=bp->next_;
}
return true;
}
bool get(CountType k, std::list<std::pair<ElemType, CountType> >& topk)
{
BucketT* bp = end_;
CountType tempk=0;
while(bp!=bs_)
{
ItemT* i=bp->head_;
while(i)
{
topk.push_back(make_pair(i->elem_, i->b_->c_));
tempk++;
if(tempk >= k || tempk >= size_)break;
i=i->next_;
}
if(tempk >= k || tempk >= size_)break;
bp=bp->prev_;
}
return true;
}
private:
bool update(ElemType elem, CountType count)
{
ItemT* i = gps_[elem];
BucketT* bp = i->b_;
count = bp->c_+1;
if(bp->size_==1 && (!(bp->next_) || bp->next_->c_ > count))
{
bp->c_++;
th_ = bs_->next_->c_;
return true;
}
bp->erase(i);
if(!(bp->next_))
{
bp->next_=new BucketT(count, bp, NULL);
end_=bp->next_;
}
else if(bp->next_->c_ > count)
{
BucketT* tp=new BucketT(count, bp, bp->next_);
bp->next_=tp;
tp->next_->prev_=tp;
}
bp->next_->insert(i);
if(bp->size_==0)
{
bp->prev_->next_=bp->next_;
bp->next_->prev_=bp->prev_;
bp->next_=bp->prev_=NULL;
delete bp;
}
return true;
}
bool replace(ElemType elem, CountType count)
{
count = bs_->next_->c_+1;
ItemT* i = bs_->next_->end_;
gps_.erase(gps_.find(i->elem_));
gps_[elem] = i;
i->elem_=elem;
return update(elem,count);
}
bool additem(ElemType elem, CountType count)
{
count=1;
if(bs_->next_==NULL)
{
bs_->next_=new BucketT(count, bs_, NULL);
end_=bs_->next_;
}
BucketT* bp=bs_->next_;
ItemT* i=new ItemT(elem, bp, NULL, NULL);
if(bp->c_ == count)
{
bp->insert(i);
}
else
{
BucketT* nbp = new BucketT(count, bs_, bs_->next_);
bs_->next_ = nbp;
nbp->next_->prev_=nbp;
nbp->insert(i);
}
size_++;
gps_[elem]=i;
th_=bs_->next_->c_;
return true;
}
CountType MAXSIZE_;
//current size
CountType size_;
//threshold
CountType th_;
BucketT* bs_;
BucketT* end_;
boost::unordered_map<ElemType, ItemT* > gps_;
};
} //end of namespace util
} //end of namespace izenelib
#endif
|
fix a small bug when reset
|
fix a small bug when reset
|
C++
|
apache-2.0
|
pombredanne/izenelib,izenecloud/izenelib,izenecloud/izenelib,pombredanne/izenelib,pombredanne/izenelib,pombredanne/izenelib,izenecloud/izenelib,izenecloud/izenelib
|
9a22a4270ef9969f5845ef9c35a34359d9ae2920
|
Game/Source/Game/src/UI_Event.cpp
|
Game/Source/Game/src/UI_Event.cpp
|
#pragma once
#include <UI_Event.h>
#include <MY_ResourceManager.h>
#include <scenario/Dialogue.h>
UI_Event::UI_Event(BulletWorld * _world, Shader * _textShader) :
VerticalLinearLayout(_world),
image(new NodeUI(_world)),
text(new TextArea(_world, MY_ResourceManager::scenario->getFont("HURLY-BURLY")->font, _textShader, 1.f)),
nextButton(new MY_Button(_world, MY_ResourceManager::scenario->getFont("HURLY-BURLY")->font, _textShader, 282, 45)),
optionOne(new MY_Button(_world, MY_ResourceManager::scenario->getFont("HURLY-BURLY")->font, _textShader, 282, 45)),
optionTwo(new MY_Button(_world, MY_ResourceManager::scenario->getFont("HURLY-BURLY")->font, _textShader, 282, 45)),
done(false),
optionsLayout(new HorizontalLinearLayout(_world)),
currentEvent(nullptr)
{
setRenderMode(kTEXTURE);
//optionOne->renderMode = kTEXTURE;
verticalAlignment = kTOP;
horizontalAlignment = kCENTER;
setBackgroundColour(1.f, 1.f, 1.f, 1.f);
background->mesh->pushTexture2D(MY_ResourceManager::scenario->getTexture("SCROLL_EVENT")->texture);
setMargin(0.05f);
setPadding(0.125f, 0.125f);
setRationalWidth(1.f);
setRationalHeight(1.f);
addChild(image);
addChild(text);
addChild(optionsLayout);
optionsLayout->addChild(optionOne);
optionsLayout->addChild(optionTwo);
optionsLayout->setVisible(false);
addChild(nextButton);
image->setRationalWidth(1.0f);
image->setRationalHeight(0.8f);
image->background->mesh->scaleModeMag = image->background->mesh->scaleModeMin = GL_NEAREST;
text->setWidth(1.f);
//text->setHeight(0.4f);
text->setText(L"Bacon ipsum dolor amet anim occaecat pork loin.");
text->verticalAlignment = kTOP;
text->setWrapMode(kWORD);
nextButton->label->setText("NEXT");
nextButton->eventManager.addEventListener("click", [this](sweet::Event * _event){
done = !this->sayNext();
});
optionOne->eventManager.addEventListener("click", [this](sweet::Event * _event){
select(0);
});
optionTwo->eventManager.addEventListener("click", [this](sweet::Event * _event){
select(1);
});
setVisible(false);
}
UI_Event::~UI_Event(){}
void UI_Event::startEvent(Event * _event){
currentEvent = _event;
done = false;
setVisible(true);
currentConversation = _event->scenario->conversations["intro"];
currentConversation->reset();
sayNext();
}
bool UI_Event::sayNext(){
invalidateLayout();
if(ConversationIterator::sayNext()){
// remove existing images
while(image->background->mesh->textures.size() > 0){
delete image->background->mesh->textures.back();
image->background->mesh->textures.pop_back();
}
// make the image "textures/event/SCENARIO_CONVERSATION.png"
std::stringstream imgSrc;
imgSrc << currentEvent->scenario->id << "_" << currentConversation->id << ".png";
Texture * tex = new Texture(imgSrc.str(), false, false, false);
tex->load();
image->background->mesh->pushTexture2D(tex);
text->setText(currentConversation->getCurrentDialogue()->getCurrentText());
if(waitingForInput){
nextButton->setVisible(false);
optionsLayout->setVisible(true);
nextButton->setMouseEnabled(false);
optionOne->setMouseEnabled(true);
optionTwo->setMouseEnabled(true);
optionOne->label->setText(currentConversation->options.at(0)->text);
optionTwo->label->setText(currentConversation->options.at(1)->text);
}else{
nextButton->setVisible(true);
optionsLayout->setVisible(false);
nextButton->setMouseEnabled(true);
optionOne->setMouseEnabled(false);
optionTwo->setMouseEnabled(false);
}
return true;
}else{
return false;
}
}
|
#pragma once
#include <UI_Event.h>
#include <MY_ResourceManager.h>
#include <scenario/Dialogue.h>
UI_Event::UI_Event(BulletWorld * _world, Shader * _textShader) :
VerticalLinearLayout(_world),
image(new NodeUI(_world)),
text(new TextArea(_world, MY_ResourceManager::scenario->getFont("HURLY-BURLY")->font, _textShader, 1.f)),
nextButton(new MY_Button(_world, MY_ResourceManager::scenario->getFont("HURLY-BURLY")->font, _textShader, 282, 45)),
optionOne(new MY_Button(_world, MY_ResourceManager::scenario->getFont("HURLY-BURLY")->font, _textShader, 282, 45)),
optionTwo(new MY_Button(_world, MY_ResourceManager::scenario->getFont("HURLY-BURLY")->font, _textShader, 282, 45)),
done(false),
optionsLayout(new HorizontalLinearLayout(_world)),
currentEvent(nullptr)
{
setRenderMode(kTEXTURE);
//optionOne->renderMode = kTEXTURE;
verticalAlignment = kTOP;
horizontalAlignment = kCENTER;
setBackgroundColour(1.f, 1.f, 1.f, 1.f);
background->mesh->pushTexture2D(MY_ResourceManager::scenario->getTexture("SCROLL_EVENT")->texture);
setMargin(0.05f);
setPadding(0.125f, 0.125f);
setRationalWidth(1.f);
setRationalHeight(1.f);
addChild(image);
addChild(text);
addChild(optionsLayout);
optionsLayout->addChild(optionOne);
optionsLayout->addChild(optionTwo);
optionsLayout->setVisible(false);
addChild(nextButton);
image->setRationalWidth(1.0f);
image->setRationalHeight(0.8f);
image->background->mesh->scaleModeMag = image->background->mesh->scaleModeMin = GL_NEAREST;
text->setWidth(1.f);
//text->setHeight(0.4f);
text->setText(L"Bacon ipsum dolor amet anim occaecat pork loin.");
text->verticalAlignment = kTOP;
text->setWrapMode(kWORD);
nextButton->label->setText("NEXT");
nextButton->eventManager.addEventListener("click", [this](sweet::Event * _event){
done = !this->sayNext();
if(done){
nextButton->setMouseEnabled(false);
optionOne->setMouseEnabled(false);
optionTwo->setMouseEnabled(false);
}
});
optionOne->eventManager.addEventListener("click", [this](sweet::Event * _event){
select(0);
});
optionTwo->eventManager.addEventListener("click", [this](sweet::Event * _event){
select(1);
});
nextButton->setMouseEnabled(false);
optionOne->setMouseEnabled(false);
optionTwo->setMouseEnabled(false);
setVisible(false);
}
UI_Event::~UI_Event(){}
void UI_Event::startEvent(Event * _event){
currentEvent = _event;
done = false;
setVisible(true);
currentConversation = _event->scenario->conversations["intro"];
currentConversation->reset();
sayNext();
}
bool UI_Event::sayNext(){
invalidateLayout();
if(ConversationIterator::sayNext()){
// remove existing images
while(image->background->mesh->textures.size() > 0){
delete image->background->mesh->textures.back();
image->background->mesh->textures.pop_back();
}
// make the image "textures/event/SCENARIO_CONVERSATION.png"
std::stringstream imgSrc;
imgSrc << currentEvent->scenario->id << "_" << currentConversation->id << ".png";
Texture * tex = new Texture(imgSrc.str(), false, false, false);
tex->load();
image->background->mesh->pushTexture2D(tex);
text->setText(currentConversation->getCurrentDialogue()->getCurrentText());
if(waitingForInput){
nextButton->setVisible(false);
optionsLayout->setVisible(true);
nextButton->setMouseEnabled(false);
optionOne->setMouseEnabled(true);
optionTwo->setMouseEnabled(true);
optionOne->label->setText(currentConversation->options.at(0)->text);
optionTwo->label->setText(currentConversation->options.at(1)->text);
}else{
nextButton->setVisible(true);
optionsLayout->setVisible(false);
nextButton->setMouseEnabled(true);
optionOne->setMouseEnabled(false);
optionTwo->setMouseEnabled(false);
}
return true;
}else{
return false;
}
}
|
disable event popup buttons when not in use
|
disable event popup buttons when not in use
|
C++
|
mit
|
PureBread/Game,PureBread/Game
|
1ca20dd4d2a16cbc095fc5185fe2489648e83fd1
|
benchmarks/linear_algebra/blas/level2/syr2/wrapper_syr2_2.cpp
|
benchmarks/linear_algebra/blas/level2/syr2/wrapper_syr2_2.cpp
|
#include "Halide.h"
#include "wrapper_syr2.h"
#include <tiramisu/utils.h>
#include <cstdlib>
#include <iostream>
#include <chrono>
#define NN 100
#define alpha 3
using namespace std;
using namespace std::chrono;
int main(int, char **)
{
Halide::Buffer<uint8_t> A_buf(NN, NN);
Halide::Buffer<uint8_t> x_buf(NN);
Halide::Buffer<uint8_t> y_buf(NN);
//output syr2
Halide::Buffer<uint8_t> output1_buf(NN, NN);
// Initialize matrix A with pseudorandom values:
for (int i = 0; i < NN; i++) {
for (int j = 0; j < NN; j++) {
A_buf(j, i) = (i + 3) * (j + 1);
}
}
// Initialize Vector X with pseudorandom values:
for (int i = 0; i < NN; i++) {
x_buf(i) = 2;
}
// Initialize Vector Y with pseudorandom values:
for (int j = 0; j < NN; j++) {
y_buf(j) = j;
}
// TRAMISU CODE EXECUTION STARTS:
auto start1 = std::chrono::high_resolution_clock::now();
syr2(A_buf.raw_buffer(), x_buf.raw_buffer(), y_buf.raw_buffer(), output1_buf.raw_buffer() );
auto end1 = std::chrono::high_resolution_clock::now();
auto duration1 =duration_cast<microseconds>(end1 - start1);
// TRAMISU CODE EXECUTION ENDS.
// REFERENCE Output buffer
Halide::Buffer<uint8_t> output2_buf(NN, NN);
init_buffer(output2_buf, (uint8_t)0);
// REFERENCE C++ CODE EXECUTION STARTS
auto start2 = std::chrono::high_resolution_clock::now();
for (int i = 0; i < NN; i++) {
for (int j = 0; j < NN; j++) {
output2_buf(j, i) = alpha * x_buf(i) * y_buf(j) + alpha * x_buf(j) * y_buf(i) + A_buf(j, i) ;
}
}
// REFERENCE C++ CODE EXECUTION ENDS.
auto end2 = std::chrono::high_resolution_clock::now();
auto duration2 =duration_cast<microseconds>(end2 - start2);
//===== printing REFERECE EXEC TIME: =====
std::cout << "\n REF RESOLUTION TIME : " << duration2.count() << "microseconds";
//===== printing TIRAMISU EXEC TIME: =====
std::cout << "\n TIRAMISU RESOLUTION TIME : " << duration1.count() << "microseconds";
printf("\n");
//===== Verify if TIRAMISU output is correct: =====
compare_buffers("syr2", output1_buf, output2_buf);
return 0;
}
|
#include "Halide.h"
#include "wrapper_syr2_2.h"
#include <tiramisu/utils.h>
#include <cstdlib>
#include <iostream>
#include <chrono>
#define NN 100
#define alpha 3
using namespace std;
using namespace std::chrono;
int main(int, char **)
{
Halide::Buffer<uint8_t> A_buf(NN, NN);
Halide::Buffer<uint8_t> x_buf(NN);
Halide::Buffer<uint8_t> y_buf(NN);
//output syr2
Halide::Buffer<uint8_t> output1_buf(NN, NN);
// Initialize matrix A with pseudorandom values:
for (int i = 0; i < NN; i++) {
for (int j = 0; j < NN; j++) {
A_buf(j, i) = (i + 3) * (j + 1);
}
}
// Initialize Vector X with pseudorandom values:
for (int i = 0; i < NN; i++) {
x_buf(i) = 2;
}
// Initialize Vector Y with pseudorandom values:
for (int j = 0; j < NN; j++) {
y_buf(j) = j;
}
// TRAMISU CODE EXECUTION STARTS:
auto start1 = std::chrono::high_resolution_clock::now();
syr2(A_buf.raw_buffer(), x_buf.raw_buffer(), y_buf.raw_buffer(), output1_buf.raw_buffer() );
auto end1 = std::chrono::high_resolution_clock::now();
auto duration1 =duration_cast<microseconds>(end1 - start1);
// TRAMISU CODE EXECUTION ENDS.
// REFERENCE Output buffer
Halide::Buffer<uint8_t> output2_buf(NN, NN);
init_buffer(output2_buf, (uint8_t)0);
// REFERENCE C++ CODE EXECUTION STARTS
auto start2 = std::chrono::high_resolution_clock::now();
for (int i = 0; i < NN; i++) {
for (int j = 0; j < NN; j++) {
output2_buf(j, i) = alpha * x_buf(i) * y_buf(j) + alpha * x_buf(j) * y_buf(i) + A_buf(j, i) ;
}
}
// REFERENCE C++ CODE EXECUTION ENDS.
auto end2 = std::chrono::high_resolution_clock::now();
auto duration2 =duration_cast<microseconds>(end2 - start2);
//===== printing REFERECE EXEC TIME: =====
std::cout << "\n REF RESOLUTION TIME : " << duration2.count() << "microseconds";
//===== printing TIRAMISU EXEC TIME: =====
std::cout << "\n TIRAMISU RESOLUTION TIME : " << duration1.count() << "microseconds";
printf("\n");
//===== Verify if TIRAMISU output is correct: =====
compare_buffers("syr2", output1_buf, output2_buf);
return 0;
}
|
Update wrapper_syr2_2.cpp
|
Update wrapper_syr2_2.cpp
|
C++
|
mit
|
rbaghdadi/ISIR,rbaghdadi/COLi,rbaghdadi/COLi,rbaghdadi/ISIR
|
1c23b424193dc40fcacd1bad72b1ca17d7918686
|
src/ecwrapper.cpp
|
src/ecwrapper.cpp
|
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "ecwrapper.h"
#include "serialize.h"
#include "uint256.h"
#include <openssl/bn.h>
#include <openssl/ecdsa.h>
#include <openssl/obj_mac.h>
namespace {
/**
* Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
* recid selects which key is recovered
* if check is non-zero, additional checks are performed
*/
int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
{
if (!eckey) return 0;
int ret = 0;
BN_CTX *ctx = NULL;
BIGNUM *x = NULL;
BIGNUM *e = NULL;
BIGNUM *order = NULL;
BIGNUM *sor = NULL;
BIGNUM *eor = NULL;
BIGNUM *field = NULL;
EC_POINT *R = NULL;
EC_POINT *O = NULL;
EC_POINT *Q = NULL;
BIGNUM *rr = NULL;
BIGNUM *zero = NULL;
int n = 0;
int i = recid / 2;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
BN_CTX_start(ctx);
order = BN_CTX_get(ctx);
if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
x = BN_CTX_get(ctx);
if (!BN_copy(x, order)) { ret=-1; goto err; }
if (!BN_mul_word(x, i)) { ret=-1; goto err; }
if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
field = BN_CTX_get(ctx);
if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
if (check)
{
if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
}
if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
n = EC_GROUP_get_degree(group);
e = BN_CTX_get(ctx);
if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
zero = BN_CTX_get(ctx);
if (!BN_zero(zero)) { ret=-1; goto err; }
if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
rr = BN_CTX_get(ctx);
if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
sor = BN_CTX_get(ctx);
if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
eor = BN_CTX_get(ctx);
if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
ret = 1;
err:
if (ctx) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
if (R != NULL) EC_POINT_free(R);
if (O != NULL) EC_POINT_free(O);
if (Q != NULL) EC_POINT_free(Q);
return ret;
}
} // anon namespace
CECKey::CECKey() {
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
assert(pkey != NULL);
}
CECKey::~CECKey() {
EC_KEY_free(pkey);
}
void CECKey::GetPubKey(std::vector<unsigned char> &pubkey, bool fCompressed) {
EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
int nSize = i2o_ECPublicKey(pkey, NULL);
assert(nSize);
assert(nSize <= 65);
pubkey.clear();
pubkey.resize(nSize);
unsigned char *pbegin(begin_ptr(pubkey));
int nSize2 = i2o_ECPublicKey(pkey, &pbegin);
assert(nSize == nSize2);
}
bool CECKey::SetPubKey(const unsigned char* pubkey, size_t size) {
return o2i_ECPublicKey(&pkey, &pubkey, size) != NULL;
}
bool CECKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
if (vchSig.empty())
return false;
// New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first.
unsigned char *norm_der = NULL;
ECDSA_SIG *norm_sig = ECDSA_SIG_new();
const unsigned char* sigptr = &vchSig[0];
d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size());
int derlen = i2d_ECDSA_SIG(norm_sig, &norm_der);
ECDSA_SIG_free(norm_sig);
if (derlen <= 0)
return false;
// -1 = error, 0 = bad sig, 1 = good
bool ret = ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
OPENSSL_free(norm_der);
return ret;
}
bool CECKey::Recover(const uint256 &hash, const unsigned char *p64, int rec)
{
if (rec<0 || rec>=3)
return false;
ECDSA_SIG *sig = ECDSA_SIG_new();
BN_bin2bn(&p64[0], 32, sig->r);
BN_bin2bn(&p64[32], 32, sig->s);
bool ret = ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), rec, 0) == 1;
ECDSA_SIG_free(sig);
return ret;
}
bool CECKey::TweakPublic(const unsigned char vchTweak[32]) {
bool ret = true;
BN_CTX *ctx = BN_CTX_new();
BN_CTX_start(ctx);
BIGNUM *bnTweak = BN_CTX_get(ctx);
BIGNUM *bnOrder = BN_CTX_get(ctx);
BIGNUM *bnOne = BN_CTX_get(ctx);
const EC_GROUP *group = EC_KEY_get0_group(pkey);
EC_GROUP_get_order(group, bnOrder, ctx); // what a grossly inefficient way to get the (constant) group order...
BN_bin2bn(vchTweak, 32, bnTweak);
if (BN_cmp(bnTweak, bnOrder) >= 0)
ret = false; // extremely unlikely
EC_POINT *point = EC_POINT_dup(EC_KEY_get0_public_key(pkey), group);
BN_one(bnOne);
EC_POINT_mul(group, point, bnTweak, point, bnOne, ctx);
if (EC_POINT_is_at_infinity(group, point))
ret = false; // ridiculously unlikely
EC_KEY_set_public_key(pkey, point);
EC_POINT_free(point);
BN_CTX_end(ctx);
BN_CTX_free(ctx);
return ret;
}
bool CECKey::SanityCheck()
{
EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if(pkey == NULL)
return false;
EC_KEY_free(pkey);
// TODO Is there more EC functionality that could be missing?
return true;
}
|
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "ecwrapper.h"
#include "serialize.h"
#include "uint256.h"
#include <openssl/bn.h>
#include <openssl/ecdsa.h>
#include <openssl/obj_mac.h>
namespace {
/**
* Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
* recid selects which key is recovered
* if check is non-zero, additional checks are performed
*/
int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
{
if (!eckey) return 0;
int ret = 0;
BN_CTX *ctx = NULL;
BIGNUM *x = NULL;
BIGNUM *e = NULL;
BIGNUM *order = NULL;
BIGNUM *sor = NULL;
BIGNUM *eor = NULL;
BIGNUM *field = NULL;
EC_POINT *R = NULL;
EC_POINT *O = NULL;
EC_POINT *Q = NULL;
BIGNUM *rr = NULL;
BIGNUM *zero = NULL;
int n = 0;
int i = recid / 2;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
BN_CTX_start(ctx);
order = BN_CTX_get(ctx);
if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
x = BN_CTX_get(ctx);
if (!BN_copy(x, order)) { ret=-1; goto err; }
if (!BN_mul_word(x, i)) { ret=-1; goto err; }
if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
field = BN_CTX_get(ctx);
if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
if (check)
{
if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
}
if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
n = EC_GROUP_get_degree(group);
e = BN_CTX_get(ctx);
if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
zero = BN_CTX_get(ctx);
if (!BN_zero(zero)) { ret=-1; goto err; }
if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
rr = BN_CTX_get(ctx);
if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
sor = BN_CTX_get(ctx);
if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
eor = BN_CTX_get(ctx);
if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
ret = 1;
err:
if (ctx) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
if (R != NULL) EC_POINT_free(R);
if (O != NULL) EC_POINT_free(O);
if (Q != NULL) EC_POINT_free(Q);
return ret;
}
} // anon namespace
CECKey::CECKey() {
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
assert(pkey != NULL);
}
CECKey::~CECKey() {
EC_KEY_free(pkey);
}
void CECKey::GetPubKey(std::vector<unsigned char> &pubkey, bool fCompressed) {
EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
int nSize = i2o_ECPublicKey(pkey, NULL);
assert(nSize);
assert(nSize <= 65);
pubkey.clear();
pubkey.resize(nSize);
unsigned char *pbegin(begin_ptr(pubkey));
int nSize2 = i2o_ECPublicKey(pkey, &pbegin);
assert(nSize == nSize2);
}
bool CECKey::SetPubKey(const unsigned char* pubkey, size_t size) {
return o2i_ECPublicKey(&pkey, &pubkey, size) != NULL;
}
bool CECKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
if (vchSig.empty())
return false;
// New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first.
unsigned char *norm_der = NULL;
ECDSA_SIG *norm_sig = ECDSA_SIG_new();
const unsigned char* sigptr = &vchSig[0];
assert(norm_sig);
if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
{
/* As of OpenSSL 1.0.0p d2i_ECDSA_SIG frees and nulls the pointer on
* error. But OpenSSL's own use of this function redundantly frees the
* result. As ECDSA_SIG_free(NULL) is a no-op, and in the absence of a
* clear contract for the function behaving the same way is more
* conservative.
*/
ECDSA_SIG_free(norm_sig);
return false;
}
int derlen = i2d_ECDSA_SIG(norm_sig, &norm_der);
ECDSA_SIG_free(norm_sig);
if (derlen <= 0)
return false;
// -1 = error, 0 = bad sig, 1 = good
bool ret = ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
OPENSSL_free(norm_der);
return ret;
}
bool CECKey::Recover(const uint256 &hash, const unsigned char *p64, int rec)
{
if (rec<0 || rec>=3)
return false;
ECDSA_SIG *sig = ECDSA_SIG_new();
BN_bin2bn(&p64[0], 32, sig->r);
BN_bin2bn(&p64[32], 32, sig->s);
bool ret = ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), rec, 0) == 1;
ECDSA_SIG_free(sig);
return ret;
}
bool CECKey::TweakPublic(const unsigned char vchTweak[32]) {
bool ret = true;
BN_CTX *ctx = BN_CTX_new();
BN_CTX_start(ctx);
BIGNUM *bnTweak = BN_CTX_get(ctx);
BIGNUM *bnOrder = BN_CTX_get(ctx);
BIGNUM *bnOne = BN_CTX_get(ctx);
const EC_GROUP *group = EC_KEY_get0_group(pkey);
EC_GROUP_get_order(group, bnOrder, ctx); // what a grossly inefficient way to get the (constant) group order...
BN_bin2bn(vchTweak, 32, bnTweak);
if (BN_cmp(bnTweak, bnOrder) >= 0)
ret = false; // extremely unlikely
EC_POINT *point = EC_POINT_dup(EC_KEY_get0_public_key(pkey), group);
BN_one(bnOne);
EC_POINT_mul(group, point, bnTweak, point, bnOne, ctx);
if (EC_POINT_is_at_infinity(group, point))
ret = false; // ridiculously unlikely
EC_KEY_set_public_key(pkey, point);
EC_POINT_free(point);
BN_CTX_end(ctx);
BN_CTX_free(ctx);
return ret;
}
bool CECKey::SanityCheck()
{
EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if(pkey == NULL)
return false;
EC_KEY_free(pkey);
// TODO Is there more EC functionality that could be missing?
return true;
}
|
Improve robustness of DER recoding code
|
Improve robustness of DER recoding code
Add some defensive programming on top of #5634.
This copies the respective OpenSSL code in ECDSA_verify in
OpenSSL pre-1.0.1k (e.g. https://github.com/openssl/openssl/blob/OpenSSL_1_0_1j/crypto/ecdsa/ecs_vrf.c#L89)
more closely.
As reported by @sergiodemianlerner.
Github-Pull: #5640
Rebased-From: c6b7b29f232c651f898eeffb93f36c8f537c56d2
|
C++
|
mit
|
Crowndev/crowncoin,Infernoman/crowncoin,domob1812/crowncoin,Crowndev/crowncoin,Infernoman/crowncoin,Infernoman/crowncoin,Crowndev/crowncoin,domob1812/crowncoin,Infernoman/crowncoin,domob1812/crowncoin,Infernoman/crowncoin,domob1812/crowncoin,domob1812/crowncoin,Crowndev/crowncoin,Crowndev/crowncoin,Crowndev/crowncoin,domob1812/crowncoin,Infernoman/crowncoin
|
e92e980fde9127c46274c86fe5f1f666733a9002
|
deps/ox/src/ox/std/error.hpp
|
deps/ox/src/ox/std/error.hpp
|
/*
* Copyright 2015 - 2018 [email protected]
*
* 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/.
*/
#pragma once
#include "defines.hpp"
#include "strongint.hpp"
#include "typetraits.hpp"
#include "utility.hpp"
#define OxError(...) ox::_error(__FILE__, __LINE__, __VA_ARGS__)
namespace ox {
struct BaseError {
const char *msg = nullptr;
const char *file = "";
uint16_t line = 0;
BaseError() = default;
constexpr BaseError(const BaseError &o) noexcept {
msg = o.msg;
file = o.file;
line = o.line;
}
constexpr BaseError operator=(const BaseError &o) noexcept {
msg = o.msg;
file = o.file;
line = o.line;
return *this;
}
};
using Error = Integer<uint64_t, BaseError>;
static constexpr Error _error(const char *file, uint32_t line, uint64_t errCode, const char *msg = nullptr) {
Error err = static_cast<ox::Error>(errCode);
err.file = file;
err.line = line;
err.msg = msg;
return err;
}
template<typename T>
struct ValErr {
T value;
Error error;
constexpr ValErr() noexcept: error(0) {
}
constexpr ValErr(Error error) noexcept: value(ox::move(value)), error(error) {
this->error = error;
}
constexpr ValErr(T value, Error error = OxError(0)) noexcept: value(ox::move(value)), error(error) {
}
explicit constexpr operator const T&() const noexcept {
return value;
}
explicit constexpr operator T&() noexcept {
return value;
}
[[nodiscard]] constexpr bool ok() const noexcept {
return error == 0;
}
[[nodiscard]] constexpr ox::Error get(T *val) noexcept {
*val = value;
return error;
}
};
namespace error {
[[nodiscard]] constexpr ox::Error toError(ox::Error e) noexcept {
return e;
}
template<typename T>
[[nodiscard]] constexpr ox::Error toError(ox::ValErr<T> ve) noexcept {
return ve.error;
}
}
}
inline void oxIgnoreError(ox::Error) {}
#define oxReturnError(x) if (const auto _ox_error = ox::error::toError(x)) return _ox_error
#define oxThrowError(x) if (const auto _ox_error = ox::error::toError(x)) throw _ox_error
|
/*
* Copyright 2015 - 2018 [email protected]
*
* 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/.
*/
#pragma once
#include "defines.hpp"
#include "strongint.hpp"
#include "typetraits.hpp"
#include "utility.hpp"
#define OxError(...) ox::_error(__FILE__, __LINE__, __VA_ARGS__)
namespace ox {
struct BaseError {
const char *msg = nullptr;
const char *file = "";
uint16_t line = 0;
BaseError() = default;
constexpr BaseError(const BaseError &o) noexcept {
msg = o.msg;
file = o.file;
line = o.line;
}
constexpr BaseError operator=(const BaseError &o) noexcept {
msg = o.msg;
file = o.file;
line = o.line;
return *this;
}
};
using Error = Integer<uint64_t, BaseError>;
static constexpr Error _error(const char *file, uint32_t line, uint64_t errCode, const char *msg = nullptr) {
Error err = static_cast<ox::Error>(errCode);
err.file = file;
err.line = line;
err.msg = msg;
return err;
}
template<typename T>
struct ValErr {
T value;
Error error;
constexpr ValErr() noexcept: error(0) {
}
constexpr ValErr(Error error) noexcept: value(ox::move(value)), error(error) {
this->error = error;
}
constexpr ValErr(T value, Error error = OxError(0)) noexcept: value(ox::move(value)), error(error) {
}
explicit constexpr operator const T&() const noexcept {
return value;
}
explicit constexpr operator T&() noexcept {
return value;
}
[[nodiscard]] constexpr bool ok() const noexcept {
return error == 0;
}
[[nodiscard]] constexpr ox::Error get(T *val) noexcept {
*val = value;
return error;
}
};
namespace error {
[[nodiscard]] constexpr ox::Error toError(ox::Error e) noexcept {
return e;
}
template<typename T>
[[nodiscard]] constexpr ox::Error toError(const ox::ValErr<T> &ve) noexcept {
return ve.error;
}
}
}
inline void oxIgnoreError(ox::Error) {}
#define oxReturnError(x) if (const auto _ox_error = ox::error::toError(x)) return _ox_error
#define oxThrowError(x) if (const auto _ox_error = ox::error::toError(x)) throw _ox_error
|
Change toError(ox::ValErr<T>) to toError(const ox::ValErr<T>&)
|
[ox/std] Change toError(ox::ValErr<T>) to toError(const ox::ValErr<T>&)
|
C++
|
mpl-2.0
|
wombatant/nostalgia,wombatant/nostalgia,wombatant/nostalgia
|
823bc67ed14e5c9e6473e4c554a926ea1329673e
|
warpcoil/cpp/client_pipeline.hpp
|
warpcoil/cpp/client_pipeline.hpp
|
#pragma once
#include <warpcoil/protocol.hpp>
#include <warpcoil/cpp/buffered_writer.hpp>
#include <warpcoil/cpp/integer_parser.hpp>
#include <warpcoil/cpp/tuple_parser.hpp>
#include <map>
namespace warpcoil
{
namespace cpp
{
enum class client_pipeline_request_status
{
ok,
failure
};
template <class AsyncWriteStream, class AsyncReadStream>
struct client_pipeline
{
explicit client_pipeline(AsyncWriteStream &requests, AsyncReadStream &responses)
: writer(requests)
, responses(responses)
, response_buffer_used(0)
, state(response_state::not_expecting_response)
{
}
std::size_t pending_requests() const
{
return expected_responses.size();
}
template <class ResultParser, class RequestBuilder, class ResultHandler>
void request(RequestBuilder build_request, ResultHandler &handler)
{
if (!writer.is_running())
{
writer.async_run([this](boost::system::error_code ec)
{
on_error(ec);
});
}
auto sink = Si::Sink<std::uint8_t>::erase(writer.buffer_sink());
write_integer(sink, static_cast<message_type_int>(message_type::request));
request_id const current_id = next_request_id;
++next_request_id;
write_integer(sink, current_id);
switch (build_request(sink))
{
case client_pipeline_request_status::ok:
break;
case client_pipeline_request_status::failure:
return;
}
writer.send_buffer();
expected_responses.insert(std::make_pair(
current_id,
expected_response{[handler](boost::system::error_code const error) mutable
{
handler(error, typename ResultParser::result_type{});
},
[this, handler]() mutable
{
assert(state == response_state::parsing_result);
begin_parse_value(
responses, boost::asio::buffer(response_buffer), response_buffer_used,
ResultParser(),
parse_result_operation<ResultHandler, typename ResultParser::result_type>(
*this, std::move(handler)));
}}));
switch (state)
{
case response_state::not_expecting_response:
parse_header(handler);
break;
case response_state::parsing_header:
case response_state::parsing_result:
break;
}
}
private:
enum response_state
{
not_expecting_response,
parsing_header,
parsing_result
};
struct expected_response
{
std::function<void(boost::system::error_code)> on_error;
std::function<void()> parse_result;
};
typedef std::tuple<message_type_int, request_id> response_header;
buffered_writer<AsyncWriteStream> writer;
std::array<std::uint8_t, 512> response_buffer;
AsyncReadStream &responses;
std::size_t response_buffer_used;
request_id next_request_id = 0;
response_state state;
std::map<request_id, expected_response> expected_responses;
template <class DummyHandler>
void parse_header(DummyHandler &handler)
{
state = response_state::parsing_header;
begin_parse_value(responses, boost::asio::buffer(response_buffer), response_buffer_used,
tuple_parser<integer_parser<message_type_int>, integer_parser<request_id>>(),
parse_header_operation<DummyHandler>(*this, handler));
}
void on_error(boost::system::error_code ec)
{
std::map<request_id, expected_response> local_expected_responses = std::move(expected_responses);
assert(expected_responses.empty());
state = response_state::not_expecting_response;
for (auto const &entry : local_expected_responses)
{
entry.second.on_error(ec);
}
}
template <class DummyHandler>
struct parse_header_operation
{
client_pipeline &pipeline;
DummyHandler handler;
explicit parse_header_operation(client_pipeline &pipeline, DummyHandler handler)
: pipeline(pipeline)
, handler(std::move(handler))
{
}
void operator()(boost::system::error_code ec, response_header const header) const
{
assert(pipeline.state == response_state::parsing_header);
if (!!ec)
{
pipeline.on_error(ec);
return;
}
if (std::get<0>(header) != static_cast<message_type_int>(message_type::response))
{
pipeline.on_error(make_invalid_input_error());
return;
}
auto const entry_found = pipeline.expected_responses.find(std::get<1>(header));
if (entry_found == pipeline.expected_responses.end())
{
pipeline.state = response_state::not_expecting_response;
throw std::logic_error("TODO handle protocol violation");
}
std::function<void()> parse_result = std::move(entry_found->second.parse_result);
pipeline.expected_responses.erase(entry_found);
pipeline.state = response_state::parsing_result;
parse_result();
}
template <class Function>
friend void asio_handler_invoke(Function &&f, parse_header_operation *operation)
{
using boost::asio::asio_handler_invoke;
asio_handler_invoke(f, &operation->handler);
}
};
template <class ResultHandler, class Result>
struct parse_result_operation
{
client_pipeline &pipeline;
ResultHandler handler;
explicit parse_result_operation(client_pipeline &pipeline, ResultHandler handler)
: pipeline(pipeline)
, handler(std::move(handler))
{
}
void operator()(boost::system::error_code ec, Result result)
{
assert(pipeline.state == response_state::parsing_result);
if (!!ec)
{
pipeline.on_error(ec);
return;
}
if (pipeline.expected_responses.empty())
{
pipeline.state = response_state::not_expecting_response;
}
else
{
pipeline.parse_header(handler);
}
handler(ec, std::move(result));
}
template <class Function>
friend void asio_handler_invoke(Function &&f, parse_result_operation *operation)
{
using boost::asio::asio_handler_invoke;
asio_handler_invoke(f, &operation->handler);
}
};
};
}
}
|
#pragma once
#include <warpcoil/protocol.hpp>
#include <warpcoil/cpp/buffered_writer.hpp>
#include <warpcoil/cpp/integer_parser.hpp>
#include <warpcoil/cpp/tuple_parser.hpp>
#include <map>
namespace warpcoil
{
namespace cpp
{
enum class client_pipeline_request_status
{
ok,
failure
};
template <class AsyncReadStream>
struct expected_response_registry
{
explicit expected_response_registry(AsyncReadStream &input)
: m_input(input)
, state(response_state::not_expecting_response)
, response_buffer_used(0)
{
}
template <class ResultParser, class ResultHandler>
void expect_response(request_id const request, ResultHandler handler)
{
expected_responses.insert(std::make_pair(
request,
expected_response{[handler](boost::system::error_code const error) mutable
{
handler(error, typename ResultParser::result_type{});
},
[this, handler]() mutable
{
assert(state == response_state::parsing_result);
begin_parse_value(
m_input, boost::asio::buffer(response_buffer), response_buffer_used,
ResultParser(),
parse_result_operation<ResultHandler, typename ResultParser::result_type>(
*this, std::move(handler)));
}}));
switch (state)
{
case response_state::not_expecting_response:
parse_header(handler);
break;
case response_state::parsing_header:
case response_state::parsing_result:
break;
}
}
std::size_t pending_requests() const
{
return expected_responses.size();
}
void on_error(boost::system::error_code ec)
{
std::map<request_id, expected_response> local_expected_responses = std::move(expected_responses);
assert(expected_responses.empty());
state = response_state::not_expecting_response;
for (auto const &entry : local_expected_responses)
{
entry.second.on_error(ec);
}
}
private:
enum response_state
{
not_expecting_response,
parsing_header,
parsing_result
};
struct expected_response
{
std::function<void(boost::system::error_code)> on_error;
std::function<void()> parse_result;
};
typedef std::tuple<message_type_int, request_id> response_header;
AsyncReadStream &m_input;
response_state state;
std::map<request_id, expected_response> expected_responses;
std::array<std::uint8_t, 512> response_buffer;
std::size_t response_buffer_used;
template <class DummyHandler>
void parse_header(DummyHandler &handler)
{
state = response_state::parsing_header;
begin_parse_value(m_input, boost::asio::buffer(response_buffer), response_buffer_used,
tuple_parser<integer_parser<message_type_int>, integer_parser<request_id>>(),
parse_header_operation<DummyHandler>(*this, handler));
}
template <class DummyHandler>
struct parse_header_operation
{
expected_response_registry &pipeline;
DummyHandler handler;
explicit parse_header_operation(expected_response_registry &pipeline, DummyHandler handler)
: pipeline(pipeline)
, handler(std::move(handler))
{
}
void operator()(boost::system::error_code ec, response_header const header) const
{
assert(pipeline.state == response_state::parsing_header);
if (!!ec)
{
pipeline.on_error(ec);
return;
}
if (std::get<0>(header) != static_cast<message_type_int>(message_type::response))
{
pipeline.on_error(make_invalid_input_error());
return;
}
auto const entry_found = pipeline.expected_responses.find(std::get<1>(header));
if (entry_found == pipeline.expected_responses.end())
{
pipeline.state = response_state::not_expecting_response;
throw std::logic_error("TODO handle protocol violation");
}
std::function<void()> parse_result = std::move(entry_found->second.parse_result);
pipeline.expected_responses.erase(entry_found);
pipeline.state = response_state::parsing_result;
parse_result();
}
template <class Function>
friend void asio_handler_invoke(Function &&f, parse_header_operation *operation)
{
using boost::asio::asio_handler_invoke;
asio_handler_invoke(f, &operation->handler);
}
};
template <class ResultHandler, class Result>
struct parse_result_operation
{
expected_response_registry &pipeline;
ResultHandler handler;
explicit parse_result_operation(expected_response_registry &pipeline, ResultHandler handler)
: pipeline(pipeline)
, handler(std::move(handler))
{
}
void operator()(boost::system::error_code ec, Result result)
{
assert(pipeline.state == response_state::parsing_result);
if (!!ec)
{
pipeline.on_error(ec);
return;
}
if (pipeline.expected_responses.empty())
{
pipeline.state = response_state::not_expecting_response;
}
else
{
pipeline.parse_header(handler);
}
handler(ec, std::move(result));
}
template <class Function>
friend void asio_handler_invoke(Function &&f, parse_result_operation *operation)
{
using boost::asio::asio_handler_invoke;
asio_handler_invoke(f, &operation->handler);
}
};
};
template <class AsyncWriteStream, class AsyncReadStream>
struct client_pipeline
{
explicit client_pipeline(AsyncWriteStream &requests, AsyncReadStream &responses)
: writer(requests)
, responses(responses)
{
}
std::size_t pending_requests() const
{
return responses.pending_requests();
}
template <class ResultParser, class RequestBuilder, class ResultHandler>
void request(RequestBuilder build_request, ResultHandler &handler)
{
if (!writer.is_running())
{
writer.async_run([this](boost::system::error_code ec)
{
responses.on_error(ec);
});
}
auto sink = Si::Sink<std::uint8_t>::erase(writer.buffer_sink());
write_integer(sink, static_cast<message_type_int>(message_type::request));
request_id const current_id = next_request_id;
++next_request_id;
write_integer(sink, current_id);
switch (build_request(sink))
{
case client_pipeline_request_status::ok:
break;
case client_pipeline_request_status::failure:
return;
}
writer.send_buffer();
responses.template expect_response<ResultParser>(current_id, handler);
}
private:
buffered_writer<AsyncWriteStream> writer;
expected_response_registry<AsyncReadStream> responses;
request_id next_request_id = 0;
};
}
}
|
split client_pipeline into two classes
|
split client_pipeline into two classes
|
C++
|
mit
|
TyRoXx/warpcoil,TyRoXx/warpcoil,TyRoXx/warpcoil,TyRoXx/warpcoil,TyRoXx/warpcoil
|
21412c2cdf3300496fa4a285445db64ddc845603
|
tensorflow/compiler/xla/service/hlo_live_range.cc
|
tensorflow/compiler/xla/service/hlo_live_range.cc
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/hlo_live_range.h"
#include "absl/strings/str_format.h"
#include "tensorflow/compiler/xla/service/dfs_hlo_visitor.h"
#include "tensorflow/compiler/xla/service/hlo_value.h"
namespace xla {
/*static*/
StatusOr<std::unique_ptr<HloLiveRange>> HloLiveRange::Run(
const HloSchedule& schedule, const HloAliasAnalysis& alias_analysis,
const HloComputation* computation, bool module_scoped_analysis) {
std::unique_ptr<HloLiveRange> hlo_live_range(
new HloLiveRange(schedule, alias_analysis, module_scoped_analysis));
hlo_live_range->schedule_end_time_ =
hlo_live_range->FlattenSchedule(*computation, 0);
hlo_live_range->CalculateBufferStartEndMap();
hlo_live_range->NormalizeAliasedBuffers();
return std::move(hlo_live_range);
}
void HloLiveRange::NormalizeAliasedBuffers() {
for (const HloBuffer& hlo_buffer : alias_analysis_.buffers()) {
std::vector<const HloValue*> aliased_buffers;
for (const HloValue* hlo_value : hlo_buffer.values()) {
if (buffer_live_ranges_.contains(hlo_value)) {
aliased_buffers.push_back(hlo_value);
}
}
absl::c_sort(
aliased_buffers, [&](const HloValue* value1, const HloValue* value2) {
const TimeBound& live_range1 = buffer_live_ranges_.at(value1);
const TimeBound& live_range2 = buffer_live_ranges_.at(value2);
return std::forward_as_tuple(live_range1.start, live_range1.end) <
std::forward_as_tuple(live_range2.start, live_range2.end);
});
for (int64_t i = 0; i + 1 < aliased_buffers.size(); ++i) {
const HloValue* value1 = aliased_buffers[i];
const HloValue* value2 = aliased_buffers[i + 1];
TimeBound& live_range1 = buffer_live_ranges_[value1];
TimeBound& live_range2 = buffer_live_ranges_[value2];
if (live_range1.start == live_range2.start) {
// If value1 has the same start time as value2, make value1 disappear
// by setting the end time same as start time:
//
// Before:
// +----+ value1
// +----------+ value2
//
// After:
// + value1
// +----------+ value2
//
// Note that only when heap simulator runs before copy insertion can
// this happen where one instruction defines multiple aliased buffers
// -- This is illegle to execute and can be fixed by copy insertion
// later.
live_range1.end = live_range2.end;
continue;
}
if (live_range1.end < live_range2.start) {
continue;
}
if (live_range1.end > live_range2.end) {
live_range2.end = live_range1.end;
}
live_range1.end = live_range2.start - 1;
}
}
}
// FlattenSchedule walks through the computation and tracks down the ordinal
// number of each instruction in the schedule.
int64_t HloLiveRange::FlattenSchedule(const HloComputation& computation,
int64_t start_time) {
if (!schedule_.is_computation_scheduled(&computation)) {
total_order_scheduled_ = false;
return start_time;
}
const HloInstructionSequence& instruction_sequence =
schedule_.sequence(&computation);
int64_t time = start_time;
for (HloInstruction* instruction : instruction_sequence.instructions()) {
if (module_scoped_analysis_) {
// Recurse into sub computations if running with module scoped analysis
// mode.
if (instruction->opcode() == HloOpcode::kCall ||
instruction->opcode() == HloOpcode::kConditional) {
for (const HloComputation* called_computation :
instruction->called_computations()) {
time = FlattenSchedule(*called_computation, time);
}
}
if (instruction->opcode() == HloOpcode::kWhile) {
time = FlattenSchedule(*instruction->while_condition(), time);
time = FlattenSchedule(*instruction->while_body(), time);
}
}
if (instruction_schedule_.count(instruction) != 0) {
continue;
}
instruction_schedule_.insert({instruction, time++});
flattened_instruction_sequence_.push_back(instruction);
}
computation_span_times_.try_emplace(&computation,
TimeBound{start_time, time});
DCHECK_EQ(instruction_schedule_.size(),
flattened_instruction_sequence_.size());
DCHECK_LE(instruction_schedule_.size(), time);
return time;
}
void HloLiveRange::CalculateBufferStartEndMap() {
for (const HloValue* value : alias_analysis_.dataflow_analysis().values()) {
// Ignore buffers that are not defined.
if (instruction_schedule_.count(value->defining_instruction()) == 0) {
continue;
}
int64_t buffer_start_time = instruction_schedule_[value->instruction()];
int64_t buffer_end_time = -1;
for (const HloUse& use : value->uses()) {
const HloInstruction* used = use.instruction;
// As an optimization, we deem a while's init value's live range ends as
// soon as the loop body starts. This optimization is only applicable in
// module scoped mode.
if (module_scoped_analysis_ && used->opcode() == HloOpcode::kWhile) {
// The current live range is at the end of the while, move it to the
// beginning of the body.
used = used->while_body()->parameter_instruction(0);
VLOG(1) << "Moved value " << value->ToShortString()
<< " to while param: " << used->ToString();
}
if (instruction_schedule_.count(used) == 0) {
// We didn't track the instruction `used`. This happens when we do
// computation scope (versus module scope) heap simulation and when
// the used instruction is outside of the computation being simulated.
continue;
}
buffer_end_time = std::max(buffer_end_time, instruction_schedule_[used]);
}
// Parameters are defined at the beginning of the computation. This prevents
// any instruction that's scheduled before the parameter clobbers the
// parameter's buffer.
if (value->instruction()->opcode() == HloOpcode::kParameter) {
const HloComputation* computation = value->instruction()->parent();
auto it = computation_span_times_.find(computation);
if (it != computation_span_times_.end()) {
buffer_start_time = std::min(buffer_start_time, it->second.start);
}
}
if (buffer_end_time == -1) {
buffer_end_time = buffer_start_time;
}
HloPosition end_position;
int64_t max_end_time = 0;
for (const HloPosition& position : value->positions()) {
if (instruction_schedule_[position.instruction] >= max_end_time) {
max_end_time = instruction_schedule_[value->instruction()];
end_position = position;
}
const HloComputation* position_comp = position.instruction->parent();
// If this instruction lives out, the live range of the instruction
// should be extended to the end of the computation.
if (position.instruction == position_comp->root_instruction()) {
auto it = computation_span_times_.find(position_comp);
if (it == computation_span_times_.end()) {
continue;
}
if (buffer_end_time < it->second.end) {
buffer_end_time = it->second.end;
end_position = position;
}
}
}
const HloModule* module = value->instruction()->parent()->parent();
// Readonly entry parameters (parameters that don't alias) live across whole
// computation.
if (value->instruction()->opcode() == HloOpcode::kParameter &&
value->instruction()->parent() == module->entry_computation() &&
!module->input_output_alias_config().ParameterHasAlias(
value->instruction()->parameter_number(), value->index())) {
buffer_end_time = schedule_end_time_;
}
CHECK(buffer_start_time <= buffer_end_time)
<< buffer_start_time << ", " << buffer_end_time
<< value->instruction()->ToString();
auto& live_range = buffer_live_ranges_[value];
live_range.start = buffer_start_time;
live_range.end = buffer_end_time;
live_range.end_position = end_position;
}
}
int64_t HloLiveRange::ComputePeakMemoryMoment() const {
std::vector<std::tuple<int64_t /*time*/, bool /*is_end*/, const HloValue*>>
events;
for (const HloValue* value : alias_analysis_.dataflow_analysis().values()) {
auto it = buffer_live_ranges_.find(value);
if (it != buffer_live_ranges_.end()) {
events.emplace_back(it->second.start, false, value);
events.emplace_back(it->second.end + 1, true, value);
}
}
std::sort(events.begin(), events.end());
int64_t memory_usage = 0;
int64_t peak_usage = 0;
absl::optional<int64_t> peak_time;
for (const auto& event : events) {
int64_t time;
bool is_end;
const HloValue* value;
std::tie(time, is_end, value) = event;
auto buffer_size = ShapeUtil::ByteSizeOf(value->instruction()->shape(), 8);
if (is_end) {
memory_usage -= buffer_size;
} else {
memory_usage += buffer_size;
}
if (peak_usage < memory_usage) {
peak_usage = memory_usage;
peak_time = time;
}
}
return peak_time.value_or(0);
}
std::string HloLiveRange::ToString() const {
std::string output;
absl::StrAppendFormat(&output, "HloLiveRange (max %d):\n",
schedule_end_time_);
absl::StrAppendFormat(&output, " InstructionSequence:\n");
auto& instructions = flattened_instruction_sequence().instructions();
for (int64_t i = 0; i < instructions.size(); ++i) {
absl::StrAppendFormat(&output, " %d:%s\n", i, instructions[i]->name());
}
absl::StrAppendFormat(&output, " BufferLiveRange:\n");
for (const HloValue* value : alias_analysis_.dataflow_analysis().values()) {
auto it = buffer_live_ranges_.find(value);
if (it != buffer_live_ranges_.end()) {
absl::StrAppendFormat(
&output, " %s%s:%d-%d\n", value->instruction()->name(),
value->index().ToString(), it->second.start, it->second.end);
}
}
int64_t peak_moment = ComputePeakMemoryMoment();
absl::StrAppendFormat(&output, " Live ranges at %lld (peak):\n",
peak_moment);
for (const HloValue* value : alias_analysis_.dataflow_analysis().values()) {
auto it = buffer_live_ranges_.find(value);
if (it != buffer_live_ranges_.end()) {
if (it->second.start <= peak_moment && peak_moment <= it->second.end) {
int64_t bytes = ShapeUtil::ByteSizeOf(value->instruction()->shape(), 8);
absl::StrAppendFormat(&output, " %s: %lld bytes\n",
value->instruction()->name(), bytes);
}
}
}
return output;
}
} // namespace xla
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/hlo_live_range.h"
#include <algorithm>
#include <tuple>
#include <vector>
#include "absl/strings/str_format.h"
#include "tensorflow/compiler/xla/service/dfs_hlo_visitor.h"
#include "tensorflow/compiler/xla/service/hlo_value.h"
namespace xla {
/*static*/
StatusOr<std::unique_ptr<HloLiveRange>> HloLiveRange::Run(
const HloSchedule& schedule, const HloAliasAnalysis& alias_analysis,
const HloComputation* computation, bool module_scoped_analysis) {
std::unique_ptr<HloLiveRange> hlo_live_range(
new HloLiveRange(schedule, alias_analysis, module_scoped_analysis));
hlo_live_range->schedule_end_time_ =
hlo_live_range->FlattenSchedule(*computation, 0);
hlo_live_range->CalculateBufferStartEndMap();
hlo_live_range->NormalizeAliasedBuffers();
return std::move(hlo_live_range);
}
void HloLiveRange::NormalizeAliasedBuffers() {
for (const HloBuffer& hlo_buffer : alias_analysis_.buffers()) {
std::vector<TimeBound*> aliased_live_ranges;
aliased_live_ranges.reserve(hlo_buffer.values().size());
for (const HloValue* hlo_value : hlo_buffer.values()) {
auto it = buffer_live_ranges_.find(hlo_value);
if (it != buffer_live_ranges_.end()) {
aliased_live_ranges.push_back(&it->second);
}
}
absl::c_sort(aliased_live_ranges,
[](const TimeBound* a, const TimeBound* b) {
return std::forward_as_tuple(a->start, a->end) <
std::forward_as_tuple(b->start, b->end);
});
for (int64_t i = 0; i + 1 < aliased_live_ranges.size(); ++i) {
TimeBound& live_range1 = *aliased_live_ranges[i];
TimeBound& live_range2 = *aliased_live_ranges[i + 1];
if (live_range1.start == live_range2.start) {
// If value1 has the same start time as value2, make value1 disappear
// by setting the end time same as start time:
//
// Before:
// +----+ value1
// +----------+ value2
//
// After:
// + value1
// +----------+ value2
//
// Note that only when heap simulator runs before copy insertion can
// this happen where one instruction defines multiple aliased buffers
// -- This is illegal to execute and can be fixed by copy insertion
// later.
// FIXME(cjfj): This code doesn't match the behaviour described above.
live_range1.end = live_range2.end;
continue;
}
if (live_range1.end < live_range2.start) {
continue;
}
live_range2.end = std::max(live_range1.end, live_range2.end);
live_range1.end = live_range2.start - 1;
}
}
}
// FlattenSchedule walks through the computation and tracks down the ordinal
// number of each instruction in the schedule.
int64_t HloLiveRange::FlattenSchedule(const HloComputation& computation,
int64_t start_time) {
if (!schedule_.is_computation_scheduled(&computation)) {
total_order_scheduled_ = false;
return start_time;
}
const HloInstructionSequence& instruction_sequence =
schedule_.sequence(&computation);
int64_t time = start_time;
for (HloInstruction* instruction : instruction_sequence.instructions()) {
if (module_scoped_analysis_) {
// Recurse into sub computations if running with module scoped analysis
// mode.
if (instruction->opcode() == HloOpcode::kCall ||
instruction->opcode() == HloOpcode::kConditional) {
for (const HloComputation* called_computation :
instruction->called_computations()) {
time = FlattenSchedule(*called_computation, time);
}
}
if (instruction->opcode() == HloOpcode::kWhile) {
time = FlattenSchedule(*instruction->while_condition(), time);
time = FlattenSchedule(*instruction->while_body(), time);
}
}
if (instruction_schedule_.count(instruction) != 0) {
continue;
}
instruction_schedule_.insert({instruction, time++});
flattened_instruction_sequence_.push_back(instruction);
}
computation_span_times_.try_emplace(&computation,
TimeBound{start_time, time});
DCHECK_EQ(instruction_schedule_.size(),
flattened_instruction_sequence_.size());
DCHECK_LE(instruction_schedule_.size(), time);
return time;
}
void HloLiveRange::CalculateBufferStartEndMap() {
for (const HloValue* value : alias_analysis_.dataflow_analysis().values()) {
// Ignore buffers that are not defined.
if (instruction_schedule_.count(value->defining_instruction()) == 0) {
continue;
}
int64_t buffer_start_time = instruction_schedule_[value->instruction()];
int64_t buffer_end_time = -1;
for (const HloUse& use : value->uses()) {
const HloInstruction* used = use.instruction;
// As an optimization, we deem a while's init value's live range ends as
// soon as the loop body starts. This optimization is only applicable in
// module scoped mode.
if (module_scoped_analysis_ && used->opcode() == HloOpcode::kWhile) {
// The current live range is at the end of the while, move it to the
// beginning of the body.
used = used->while_body()->parameter_instruction(0);
VLOG(1) << "Moved value " << value->ToShortString()
<< " to while param: " << used->ToString();
}
if (instruction_schedule_.count(used) == 0) {
// We didn't track the instruction `used`. This happens when we do
// computation scope (versus module scope) heap simulation and when
// the used instruction is outside of the computation being simulated.
continue;
}
buffer_end_time = std::max(buffer_end_time, instruction_schedule_[used]);
}
// Parameters are defined at the beginning of the computation. This prevents
// any instruction that's scheduled before the parameter clobbers the
// parameter's buffer.
if (value->instruction()->opcode() == HloOpcode::kParameter) {
const HloComputation* computation = value->instruction()->parent();
auto it = computation_span_times_.find(computation);
if (it != computation_span_times_.end()) {
buffer_start_time = std::min(buffer_start_time, it->second.start);
}
}
if (buffer_end_time == -1) {
buffer_end_time = buffer_start_time;
}
HloPosition end_position;
int64_t max_end_time = 0;
for (const HloPosition& position : value->positions()) {
if (instruction_schedule_[position.instruction] >= max_end_time) {
max_end_time = instruction_schedule_[value->instruction()];
end_position = position;
}
const HloComputation* position_comp = position.instruction->parent();
// If this instruction lives out, the live range of the instruction
// should be extended to the end of the computation.
if (position.instruction == position_comp->root_instruction()) {
auto it = computation_span_times_.find(position_comp);
if (it == computation_span_times_.end()) {
continue;
}
if (buffer_end_time < it->second.end) {
buffer_end_time = it->second.end;
end_position = position;
}
}
}
const HloModule* module = value->instruction()->parent()->parent();
// Readonly entry parameters (parameters that don't alias) live across whole
// computation.
if (value->instruction()->opcode() == HloOpcode::kParameter &&
value->instruction()->parent() == module->entry_computation() &&
!module->input_output_alias_config().ParameterHasAlias(
value->instruction()->parameter_number(), value->index())) {
buffer_end_time = schedule_end_time_;
}
CHECK(buffer_start_time <= buffer_end_time)
<< buffer_start_time << ", " << buffer_end_time
<< value->instruction()->ToString();
auto& live_range = buffer_live_ranges_[value];
live_range.start = buffer_start_time;
live_range.end = buffer_end_time;
live_range.end_position = end_position;
}
}
int64_t HloLiveRange::ComputePeakMemoryMoment() const {
std::vector<std::tuple<int64_t /*time*/, bool /*is_end*/, const HloValue*>>
events;
for (const HloValue* value : alias_analysis_.dataflow_analysis().values()) {
auto it = buffer_live_ranges_.find(value);
if (it != buffer_live_ranges_.end()) {
events.emplace_back(it->second.start, false, value);
events.emplace_back(it->second.end + 1, true, value);
}
}
std::sort(events.begin(), events.end());
int64_t memory_usage = 0;
int64_t peak_usage = 0;
absl::optional<int64_t> peak_time;
for (const auto& event : events) {
int64_t time;
bool is_end;
const HloValue* value;
std::tie(time, is_end, value) = event;
auto buffer_size = ShapeUtil::ByteSizeOf(value->instruction()->shape(), 8);
if (is_end) {
memory_usage -= buffer_size;
} else {
memory_usage += buffer_size;
}
if (peak_usage < memory_usage) {
peak_usage = memory_usage;
peak_time = time;
}
}
return peak_time.value_or(0);
}
std::string HloLiveRange::ToString() const {
std::string output;
absl::StrAppendFormat(&output, "HloLiveRange (max %d):\n",
schedule_end_time_);
absl::StrAppendFormat(&output, " InstructionSequence:\n");
auto& instructions = flattened_instruction_sequence().instructions();
for (int64_t i = 0; i < instructions.size(); ++i) {
absl::StrAppendFormat(&output, " %d:%s\n", i, instructions[i]->name());
}
absl::StrAppendFormat(&output, " BufferLiveRange:\n");
for (const HloValue* value : alias_analysis_.dataflow_analysis().values()) {
auto it = buffer_live_ranges_.find(value);
if (it != buffer_live_ranges_.end()) {
absl::StrAppendFormat(
&output, " %s%s:%d-%d\n", value->instruction()->name(),
value->index().ToString(), it->second.start, it->second.end);
}
}
int64_t peak_moment = ComputePeakMemoryMoment();
absl::StrAppendFormat(&output, " Live ranges at %lld (peak):\n",
peak_moment);
for (const HloValue* value : alias_analysis_.dataflow_analysis().values()) {
auto it = buffer_live_ranges_.find(value);
if (it != buffer_live_ranges_.end()) {
if (it->second.start <= peak_moment && peak_moment <= it->second.end) {
int64_t bytes = ShapeUtil::ByteSizeOf(value->instruction()->shape(), 8);
absl::StrAppendFormat(&output, " %s: %lld bytes\n",
value->instruction()->name(), bytes);
}
}
}
return output;
}
} // namespace xla
|
Remove duplicate live range look-ups in `NormalizeAliasedBuffers`.
|
Remove duplicate live range look-ups in `NormalizeAliasedBuffers`.
PiperOrigin-RevId: 430201867
Change-Id: I891a9260e612aa296cc4953ed00437d04c21ee64
|
C++
|
apache-2.0
|
tensorflow/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,karllessard/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,yongtang/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once
|
f991a2deb5ad79ff72652d2f0bf92276b4e4fc19
|
tests/row_cache_alloc_stress.cc
|
tests/row_cache_alloc_stress.cc
|
/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <core/distributed.hh>
#include <core/app-template.hh>
#include <core/sstring.hh>
#include <core/thread.hh>
#include "utils/managed_bytes.hh"
#include "utils/logalloc.hh"
#include "row_cache.hh"
#include "log.hh"
#include "schema_builder.hh"
#include "memtable.hh"
#include "disk-error-handler.hh"
thread_local disk_error_signal_type commit_error;
thread_local disk_error_signal_type general_disk_error;
static
partition_key new_key(schema_ptr s) {
static thread_local int next = 0;
return partition_key::from_single_value(*s, to_bytes(sprint("key%d", next++)));
}
static
clustering_key new_ckey(schema_ptr s) {
static thread_local int next = 0;
return clustering_key::from_single_value(*s, to_bytes(sprint("ckey%d", next++)));
}
int main(int argc, char** argv) {
namespace bpo = boost::program_options;
app_template app;
app.add_options()
("debug", "enable debug logging");
return app.run(argc, argv, [&app] {
if (app.configuration().count("debug")) {
logging::logger_registry().set_all_loggers_level(logging::log_level::debug);
}
// This test is supposed to verify that when we're low on memory but
// we still have plenty of evictable memory in cache, we should be
// able to populate cache with large mutations This test works only
// with seastar's allocator.
return seastar::async([] {
auto s = schema_builder("ks", "cf")
.with_column("pk", bytes_type, column_kind::partition_key)
.with_column("ck", bytes_type, column_kind::clustering_key)
.with_column("v", bytes_type, column_kind::regular_column)
.build();
auto mt = make_lw_shared<memtable>(s);
cache_tracker tracker;
row_cache cache(s, mt->as_data_source(), mt->as_key_source(), tracker);
std::vector<dht::decorated_key> keys;
size_t cell_size = 1024;
size_t row_count = 40 * 1024; // 40M mutations
size_t large_cell_size = cell_size * row_count;
auto make_small_mutation = [&] {
mutation m(new_key(s), s);
m.set_clustered_cell(new_ckey(s), "v", data_value(bytes(bytes::initialized_later(), cell_size)), 1);
return m;
};
auto make_large_mutation = [&] {
mutation m(new_key(s), s);
m.set_clustered_cell(new_ckey(s), "v", data_value(bytes(bytes::initialized_later(), large_cell_size)), 2);
return m;
};
for (int i = 0; i < 10; i++) {
auto key = dht::global_partitioner().decorate_key(*s, new_key(s));
mutation m1(key, s);
m1.set_clustered_cell(new_ckey(s), "v", data_value(bytes(bytes::initialized_later(), cell_size)), 1);
cache.populate(m1);
// Putting large mutations into the memtable. Should take about row_count*cell_size each.
mutation m2(key, s);
for (size_t j = 0; j < row_count; j++) {
m2.set_clustered_cell(new_ckey(s), "v", data_value(bytes(bytes::initialized_later(), cell_size)), 2);
}
mt->apply(m2);
keys.push_back(key);
}
auto reclaimable_memory = [] {
return memory::stats().free_memory() + logalloc::shard_tracker().occupancy().free_space();
};
std::cout << "memtable occupancy: " << mt->occupancy() << "\n";
std::cout << "Cache occupancy: " << tracker.region().occupancy() << "\n";
std::cout << "Reclaimable memory: " << reclaimable_memory() << "\n";
// We need to have enough Free memory to copy memtable into cache
// When this assertion fails, increase amount of memory
assert(mt->occupancy().used_space() < reclaimable_memory());
auto checker = [](const partition_key& key) {
return partition_presence_checker_result::maybe_exists;
};
std::deque<dht::decorated_key> cache_stuffing;
auto fill_cache_to_the_top = [&] {
std::cout << "Filling up memory with evictable data\n";
while (true) {
// Ensure that entries matching memtable partitions are evicted
// last, we want to hit the merge path in row_cache::update()
for (auto&& key : keys) {
cache.touch(key);
}
auto occupancy_before = tracker.region().occupancy().used_space();
auto m = make_small_mutation();
cache_stuffing.push_back(m.decorated_key());
cache.populate(m);
if (tracker.region().occupancy().used_space() <= occupancy_before) {
break;
}
}
std::cout << "Shuffling..\n";
// Evict in random order to create fragmentation.
std::random_shuffle(cache_stuffing.begin(), cache_stuffing.end());
for (auto&& key : cache_stuffing) {
cache.touch(key);
}
// Ensure that entries matching memtable partitions are evicted
// last, we want to hit the merge path in row_cache::update()
for (auto&& key : keys) {
cache.touch(key);
}
std::cout << "Reclaimable memory: " << reclaimable_memory() << "\n";
std::cout << "Cache occupancy: " << tracker.region().occupancy() << "\n";
};
std::deque<std::unique_ptr<char[]>> stuffing;
auto fragment_free_space = [&] {
stuffing.clear();
std::cout << "Reclaimable memory: " << reclaimable_memory() << "\n";
std::cout << "Free memory: " << memory::stats().free_memory() << "\n";
std::cout << "Cache occupancy: " << tracker.region().occupancy() << "\n";
// Induce memory fragmentation by taking down cache segments,
// which should be evicted in random order, and inducing high
// waste level in them. Should leave around up to 100M free,
// but no LSA segment should fit.
for (unsigned i = 0; i < 100 * 1024 * 1024 / (logalloc::segment_size / 2); ++i) {
stuffing.emplace_back(std::make_unique<char[]>(logalloc::segment_size / 2 + 1));
}
std::cout << "After fragmenting:\n";
std::cout << "Reclaimable memory: " << reclaimable_memory() << "\n";
std::cout << "Free memory: " << memory::stats().free_memory() << "\n";
std::cout << "Cache occupancy: " << tracker.region().occupancy() << "\n";
};
fill_cache_to_the_top();
fragment_free_space();
cache.update(*mt, checker).get();
stuffing.clear();
cache_stuffing.clear();
// Verify that all mutations from memtable went through
for (auto&& key : keys) {
auto range = query::partition_range::make_singular(key);
auto reader = cache.make_reader(s, range);
auto mo = mutation_from_streamed_mutation(reader().get0()).get0();
assert(mo);
assert(mo->partition().live_row_count(*s) ==
row_count + 1 /* one row was already in cache before update()*/);
}
std::cout << "Testing reading from cache.\n";
fill_cache_to_the_top();
for (auto&& key : keys) {
cache.touch(key);
}
for (auto&& key : keys) {
auto range = query::partition_range::make_singular(key);
auto reader = cache.make_reader(s, range);
auto mo = reader().get0();
assert(mo);
}
std::cout << "Testing reading when memory can't be reclaimed.\n";
// We want to check that when we really can't reserve memory, allocating_section
// throws rather than enter infinite loop.
{
stuffing.clear();
cache_stuffing.clear();
tracker.clear();
// eviction victims
for (unsigned i = 0; i < logalloc::segment_size / cell_size; ++i) {
cache.populate(make_small_mutation());
}
const mutation& m = make_large_mutation();
auto range = query::partition_range::make_singular(m.decorated_key());
cache.populate(m);
logalloc::shard_tracker().reclaim_all_free_segments();
{
logalloc::reclaim_lock _(tracker.region());
try {
while (true) {
stuffing.emplace_back(std::make_unique<char[]>(logalloc::segment_size));
}
} catch (const std::bad_alloc&) {
//expected
}
}
try {
auto reader = cache.make_reader(s, range);
assert(!reader().get0());
auto evicted_from_cache = logalloc::segment_size + large_cell_size;
new char[evicted_from_cache + logalloc::segment_size];
assert(false); // The test is not invoking the case which it's supposed to test
} catch (const std::bad_alloc&) {
// expected
}
}
});
});
}
|
/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <core/distributed.hh>
#include <core/app-template.hh>
#include <core/sstring.hh>
#include <core/thread.hh>
#include "utils/managed_bytes.hh"
#include "utils/logalloc.hh"
#include "row_cache.hh"
#include "log.hh"
#include "schema_builder.hh"
#include "memtable.hh"
#include "disk-error-handler.hh"
thread_local disk_error_signal_type commit_error;
thread_local disk_error_signal_type general_disk_error;
static
partition_key new_key(schema_ptr s) {
static thread_local int next = 0;
return partition_key::from_single_value(*s, to_bytes(sprint("key%d", next++)));
}
static
clustering_key new_ckey(schema_ptr s) {
static thread_local int next = 0;
return clustering_key::from_single_value(*s, to_bytes(sprint("ckey%d", next++)));
}
int main(int argc, char** argv) {
namespace bpo = boost::program_options;
app_template app;
app.add_options()
("debug", "enable debug logging");
return app.run(argc, argv, [&app] {
if (app.configuration().count("debug")) {
logging::logger_registry().set_all_loggers_level(logging::log_level::debug);
}
// This test is supposed to verify that when we're low on memory but
// we still have plenty of evictable memory in cache, we should be
// able to populate cache with large mutations This test works only
// with seastar's allocator.
return seastar::async([] {
auto s = schema_builder("ks", "cf")
.with_column("pk", bytes_type, column_kind::partition_key)
.with_column("ck", bytes_type, column_kind::clustering_key)
.with_column("v", bytes_type, column_kind::regular_column)
.build();
auto mt0 = make_lw_shared<memtable>(s);
cache_tracker tracker;
row_cache cache(s, mt0->as_data_source(), mt0->as_key_source(), tracker);
auto mt = make_lw_shared<memtable>(s);
std::vector<dht::decorated_key> keys;
size_t cell_size = 1024;
size_t row_count = 40 * 1024; // 40M mutations
size_t large_cell_size = cell_size * row_count;
auto make_small_mutation = [&] {
mutation m(new_key(s), s);
m.set_clustered_cell(new_ckey(s), "v", data_value(bytes(bytes::initialized_later(), cell_size)), 1);
return m;
};
auto make_large_mutation = [&] {
mutation m(new_key(s), s);
m.set_clustered_cell(new_ckey(s), "v", data_value(bytes(bytes::initialized_later(), large_cell_size)), 2);
return m;
};
for (int i = 0; i < 10; i++) {
auto key = dht::global_partitioner().decorate_key(*s, new_key(s));
mutation m1(key, s);
m1.set_clustered_cell(new_ckey(s), "v", data_value(bytes(bytes::initialized_later(), cell_size)), 1);
cache.populate(m1);
// Putting large mutations into the memtable. Should take about row_count*cell_size each.
mutation m2(key, s);
for (size_t j = 0; j < row_count; j++) {
m2.set_clustered_cell(new_ckey(s), "v", data_value(bytes(bytes::initialized_later(), cell_size)), 2);
}
mt->apply(m2);
keys.push_back(key);
}
auto reclaimable_memory = [] {
return memory::stats().free_memory() + logalloc::shard_tracker().occupancy().free_space();
};
std::cout << "memtable occupancy: " << mt->occupancy() << "\n";
std::cout << "Cache occupancy: " << tracker.region().occupancy() << "\n";
std::cout << "Reclaimable memory: " << reclaimable_memory() << "\n";
// We need to have enough Free memory to copy memtable into cache
// When this assertion fails, increase amount of memory
assert(mt->occupancy().used_space() < reclaimable_memory());
auto checker = [](const partition_key& key) {
return partition_presence_checker_result::maybe_exists;
};
std::deque<dht::decorated_key> cache_stuffing;
auto fill_cache_to_the_top = [&] {
std::cout << "Filling up memory with evictable data\n";
while (true) {
// Ensure that entries matching memtable partitions are evicted
// last, we want to hit the merge path in row_cache::update()
for (auto&& key : keys) {
cache.touch(key);
}
auto occupancy_before = tracker.region().occupancy().used_space();
auto m = make_small_mutation();
cache_stuffing.push_back(m.decorated_key());
cache.populate(m);
if (tracker.region().occupancy().used_space() <= occupancy_before) {
break;
}
}
std::cout << "Shuffling..\n";
// Evict in random order to create fragmentation.
std::random_shuffle(cache_stuffing.begin(), cache_stuffing.end());
for (auto&& key : cache_stuffing) {
cache.touch(key);
}
// Ensure that entries matching memtable partitions are evicted
// last, we want to hit the merge path in row_cache::update()
for (auto&& key : keys) {
cache.touch(key);
}
std::cout << "Reclaimable memory: " << reclaimable_memory() << "\n";
std::cout << "Cache occupancy: " << tracker.region().occupancy() << "\n";
};
std::deque<std::unique_ptr<char[]>> stuffing;
auto fragment_free_space = [&] {
stuffing.clear();
std::cout << "Reclaimable memory: " << reclaimable_memory() << "\n";
std::cout << "Free memory: " << memory::stats().free_memory() << "\n";
std::cout << "Cache occupancy: " << tracker.region().occupancy() << "\n";
// Induce memory fragmentation by taking down cache segments,
// which should be evicted in random order, and inducing high
// waste level in them. Should leave around up to 100M free,
// but no LSA segment should fit.
for (unsigned i = 0; i < 100 * 1024 * 1024 / (logalloc::segment_size / 2); ++i) {
stuffing.emplace_back(std::make_unique<char[]>(logalloc::segment_size / 2 + 1));
}
std::cout << "After fragmenting:\n";
std::cout << "Reclaimable memory: " << reclaimable_memory() << "\n";
std::cout << "Free memory: " << memory::stats().free_memory() << "\n";
std::cout << "Cache occupancy: " << tracker.region().occupancy() << "\n";
};
fill_cache_to_the_top();
fragment_free_space();
cache.update(*mt, checker).get();
stuffing.clear();
cache_stuffing.clear();
// Verify that all mutations from memtable went through
for (auto&& key : keys) {
auto range = query::partition_range::make_singular(key);
auto reader = cache.make_reader(s, range);
auto mo = mutation_from_streamed_mutation(reader().get0()).get0();
assert(mo);
assert(mo->partition().live_row_count(*s) ==
row_count + 1 /* one row was already in cache before update()*/);
}
std::cout << "Testing reading from cache.\n";
fill_cache_to_the_top();
for (auto&& key : keys) {
cache.touch(key);
}
for (auto&& key : keys) {
auto range = query::partition_range::make_singular(key);
auto reader = cache.make_reader(s, range);
auto mo = reader().get0();
assert(mo);
}
std::cout << "Testing reading when memory can't be reclaimed.\n";
// We want to check that when we really can't reserve memory, allocating_section
// throws rather than enter infinite loop.
{
stuffing.clear();
cache_stuffing.clear();
tracker.clear();
// eviction victims
for (unsigned i = 0; i < logalloc::segment_size / cell_size; ++i) {
cache.populate(make_small_mutation());
}
const mutation& m = make_large_mutation();
auto range = query::partition_range::make_singular(m.decorated_key());
cache.populate(m);
logalloc::shard_tracker().reclaim_all_free_segments();
{
logalloc::reclaim_lock _(tracker.region());
try {
while (true) {
stuffing.emplace_back(std::make_unique<char[]>(logalloc::segment_size));
}
} catch (const std::bad_alloc&) {
//expected
}
}
try {
auto reader = cache.make_reader(s, range);
assert(!reader().get0());
auto evicted_from_cache = logalloc::segment_size + large_cell_size;
new char[evicted_from_cache + logalloc::segment_size];
assert(false); // The test is not invoking the case which it's supposed to test
} catch (const std::bad_alloc&) {
// expected
}
}
});
});
}
|
use another memtable for underlying storage
|
tests/row_cache_alloc_stress: use another memtable for underlying storage
It is incorrect to update row_cache with a memtable that is also its
underlying storage. The reason for that is that after memtable is merged
into row_cache they share lsa region. Then when there is a cache miss
it asks underlying storage for data. This will result with memtable
reader running under row_cache allocation section. Since memtable reader
also uses allocation section the result is an assertion fault since
allocation sections from the same lsa region cannot be nested.
Signed-off-by: Paweł Dziepak <[email protected]>
|
C++
|
agpl-3.0
|
raphaelsc/scylla,scylladb/scylla,kjniemi/scylla,duarten/scylla,avikivity/scylla,duarten/scylla,scylladb/scylla,kjniemi/scylla,scylladb/scylla,raphaelsc/scylla,avikivity/scylla,avikivity/scylla,duarten/scylla,kjniemi/scylla,scylladb/scylla,raphaelsc/scylla
|
1c597f09b1caad3e490e2146068d933b3906fce0
|
src/eventloop.cpp
|
src/eventloop.cpp
|
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <boost/thread.hpp>
#include <boost/program_options.hpp>
#include <qi/preproc.hpp>
#include <qi/log.hpp>
#include <qi/application.hpp>
#include <qi/threadpool.hpp>
#include <qi/eventloop.hpp>
#include "eventloop_p.hpp"
namespace qi {
EventLoopAsio::EventLoopAsio()
: _destroyMe(false)
, _running(false)
, _threaded(false)
{
}
void EventLoopAsio::start()
{
if (_running || _threaded)
return;
_threaded = true;
_thd = boost::thread(&EventLoopPrivate::run, this);
while (!_running)
qi::os::msleep(0);
}
EventLoopAsio::~EventLoopAsio()
{
if (_running && boost::this_thread::get_id() != _id)
qiLogError("Destroying EventLoopPrivate from itself while running");
stop();
join();
}
void EventLoopAsio::destroy()
{
if (isInEventLoopThread())
boost::thread(&EventLoopAsio::destroy, this);
else
{
stop();
join();
delete this;
}
}
void EventLoopAsio::run()
{
qiLogDebug("qi.EventLoop") << this << "run starting";
_running = true;
_id = boost::this_thread::get_id();
_work = new boost::asio::io_service::work(_io);
_io.run();
bool destroyMe;
{
boost::recursive_mutex::scoped_lock sl(_mutex);
_running = false;
destroyMe = _destroyMe;
}
if (destroyMe)
delete this;
}
bool EventLoopAsio::isInEventLoopThread()
{
return boost::this_thread::get_id() == _id;
}
void EventLoopAsio::stop()
{
qiLogDebug("qi.EventLoop") << this << "stopping";
boost::recursive_mutex::scoped_lock sl(_mutex);
if (_work)
{
delete _work;
_work = 0;
}
}
void EventLoopAsio::join()
{
if (boost::this_thread::get_id() == _id)
{
qiLogError("qi.EventLoop") << "Cannot join from within event loop thread";
return;
}
if (_threaded)
try {
_thd.join();
}
catch(const boost::thread_resource_error& e)
{
qiLogWarning("qi.EventLoop") << "Join an already joined thread: " << e.what();
}
else
while (_running)
qi::os::msleep(0);
}
void EventLoopAsio::post(uint64_t usDelay, const boost::function<void ()>& cb)
{
if (!usDelay)
_io.post(cb);
else
asyncCall(usDelay, cb);
}
static void invoke_maybe(boost::function<void()> f, qi::Promise<void> p, const boost::system::error_code& erc)
{
if (!erc)
{
f();
p.setValue(0);
}
else
p.setError("Operation cancelled");
}
qi::Future<void> EventLoopAsio::asyncCall(uint64_t usDelay, boost::function<void ()> cb)
{
boost::shared_ptr<boost::asio::deadline_timer> timer(new boost::asio::deadline_timer(_io));
timer->expires_from_now(boost::posix_time::microseconds(usDelay));
qi::Promise<void> prom(boost::bind(&boost::asio::deadline_timer::cancel, timer));
timer->async_wait(boost::bind(&invoke_maybe, cb, prom, _1));
return prom.future();
}
void* EventLoopAsio::nativeHandle()
{
return static_cast<void*>(&_io);
}
EventLoopThreadPool::EventLoopThreadPool(int minWorkers, int maxWorkers, int minIdleWorkers, int maxIdleWorkers)
{
_stopping = false;
_pool = new ThreadPool(minWorkers, maxWorkers, minIdleWorkers, maxIdleWorkers);
}
bool EventLoopThreadPool::isInEventLoopThread()
{
// The point is to know if a call will be synchronous. It never is
// with thread pool
return false;
}
void EventLoopThreadPool::start()
{
}
void EventLoopThreadPool::run()
{
}
void EventLoopThreadPool::join()
{
_pool->waitForAll();
}
void EventLoopThreadPool::stop()
{
_stopping = true;
}
void* EventLoopThreadPool::nativeHandle()
{
return 0;
}
void EventLoopThreadPool::destroy()
{
_stopping = true;
// Ensure delete is not called from one of the threads of the event loop
boost::thread(&EventLoopThreadPool::destroy, this);
}
EventLoopThreadPool::~EventLoopThreadPool()
{
delete _pool;
}
static void delay_call(uint64_t usDelay, boost::function<void()> callback)
{
if (usDelay)
qi::os::msleep(static_cast<unsigned int>(usDelay/1000));
try
{
callback();
}
catch(const std::exception& e)
{
qiLogError("qi.EventLoop") << "Exception caught in async call: " << e.what();
}
catch(...)
{
qiLogError("qi.EventLoop") << "Unknown exception caught in async call";
}
}
static void delay_call_notify(uint64_t usDelay, boost::function<void()> callback,
qi::Promise<void> promise)
{
if (usDelay)
qi::os::msleep(static_cast<unsigned int>(usDelay/1000));
try
{
callback();
promise.setValue(0);
}
catch(const std::exception& e)
{
promise.setError(std::string("Exception caught in async call: ") + e.what());
}
catch(...)
{
promise.setError("Unknown exception caught in async call");
}
}
void EventLoopThreadPool::post(uint64_t usDelay,
const boost::function<void ()>& callback)
{
_pool->schedule(boost::bind(&delay_call, usDelay, callback));
}
qi::Future<void> EventLoopThreadPool::asyncCall(uint64_t usDelay,
boost::function<void ()> callback)
{
if (_stopping)
return qi::makeFutureError<void>("Schedule attempt on destroyed thread pool");
qi::Promise<void> promise;
_pool->schedule(boost::bind(&delay_call_notify, usDelay, callback, promise));
return promise.future();
}
// Basic pimpl bouncers.
EventLoop::AsyncCallHandle::AsyncCallHandle()
{
_p = boost::shared_ptr<AsyncCallHandlePrivate>(new AsyncCallHandlePrivate());
}
EventLoop::AsyncCallHandle::~AsyncCallHandle()
{
}
void EventLoop::AsyncCallHandle::cancel()
{
_p->cancel();
}
EventLoop::EventLoop()
: _p(0)
{
}
EventLoop::~EventLoop()
{
if (_p)
_p->destroy();
_p = 0;
}
#define CHECK_STARTED \
do { \
if (!_p) \
throw std::runtime_error("EventLoop " __HERE " : EventLoop not started"); \
} while(0)
bool EventLoop::isInEventLoopThread()
{
CHECK_STARTED;
return _p->isInEventLoopThread();
}
void EventLoop::join()
{
CHECK_STARTED;
_p->join();
}
void EventLoop::start()
{
if (_p)
return;
_p = new EventLoopAsio();
_p->start();
}
void EventLoop::startThreadPool(int minWorkers, int maxWorkers, int minIdleWorkers, int maxIdleWorkers)
{
#define OR(name, val) (name==-1?val:name)
if (_p)
return;
_p = new EventLoopThreadPool(OR(minWorkers, 2), OR(maxWorkers, 8), OR(minIdleWorkers,1), OR(maxIdleWorkers, 4));
#undef OR
}
void EventLoop::stop()
{
CHECK_STARTED;
_p->stop();
}
void EventLoop::run()
{
if (_p)
return;
_p = new EventLoopAsio();
_p->run();
}
void *EventLoop::nativeHandle() {
CHECK_STARTED;
return _p->nativeHandle();
}
void EventLoop::post(const boost::function<void ()>& callback,uint64_t usDelay)
{
CHECK_STARTED;
_p->post(usDelay, callback);
}
qi::Future<void>
EventLoop::async(
boost::function<void ()> callback,
uint64_t usDelay)
{
CHECK_STARTED;
return _p->asyncCall(usDelay, callback);
}
struct MonitorContext
{
EventLoop* target;
EventLoop* helper;
Future<void> mon;
bool isFired; // true: pinging, false: waiting for next ping.
bool ending;
uint64_t maxDelay;
Promise<void> promise;
int64_t startTime;
};
static void monitor_pingtimeout(boost::shared_ptr<MonitorContext> ctx)
{
//qiLogDebug("qi.EventLoop") << os::ustime() << " MON timeout " << ctx->isFired
// << ' ' << (os::ustime() - ctx->startTime);
if (!ctx->isFired)
return; // Got the pong in the meantime, abort
ctx->promise.setError("Event loop monitor timeout");
/* Ping system is still on, but promise is set.
* So future invocations of cancel() will be ignored, which makes the
* monitoring unstopable.
* So reset the value.
*/
ctx->promise.reset();
}
static void monitor_cancel(boost::shared_ptr<MonitorContext> ctx)
{
//qiLogDebug("qi.EventLoop") << os::ustime() << " MON cancel " << ctx->isFired;
ctx->ending = true;
try {
ctx->mon.cancel();
}
catch (...)
{}
}
static void monitor_ping(boost::shared_ptr<MonitorContext> ctx)
{
if (ctx->ending)
return;
//qiLogDebug("qi.EventLoop") << os::ustime() << " MON ping " << ctx->isFired;
if (ctx->isFired)
{ // This is a pong
ctx->isFired = false;
// Cancel monitoring async call
try {
ctx->mon.cancel();
}
catch (const std::exception& /*e*/) {
//qiLogDebug("qi.EventLoop") << "MON " << e.what();
}
int64_t pingDelay = os::ustime() - ctx->startTime;
if (pingDelay > ctx->maxDelay / 2)
qiLogDebug("qi.EventLoop") << "Long ping " << pingDelay;
// Wait a bit before pinging againg
//qiLogDebug("qi.EventLoop") << os::ustime() << " MON delay " << ctx->maxDelay;
ctx->helper->async(boost::bind(&monitor_ping, ctx), ctx->maxDelay*5);
}
else
{ // Delay between pings reached, ping again
ctx->startTime = os::ustime();
ctx->isFired = true;
// Start monitor async first, or the ping async can trigger before the
// monitor async is setup
ctx->mon = ctx->helper->async(boost::bind(&monitor_pingtimeout, ctx), ctx->maxDelay);
ctx->target->post(boost::bind(&monitor_ping, ctx));
assert(ctx->mon.isCanceleable());
}
}
qi::Future<void> EventLoop::monitorEventLoop(EventLoop* helper, uint64_t maxDelay)
{
// Context data is a Future*[2]
boost::shared_ptr<MonitorContext> ctx(new MonitorContext);
ctx->target = this;
ctx->helper = helper;
ctx->maxDelay = maxDelay;
ctx->promise = Promise<void>(boost::bind(&monitor_cancel, ctx));
ctx->isFired = false;
ctx->ending = false;
monitor_ping(ctx);
return ctx->promise.future();
}
static void eventloop_stop(EventLoop* ctx)
{
ctx->stop();
ctx->join();
delete ctx;
}
static EventLoop* _netEventLoop = 0;
static EventLoop* _objEventLoop = 0;
static EventLoop* _poolEventLoop = 0;
static double _monitorInterval = 0;
static void monitor_notify(const char* which)
{
qiLogError("qi.EventLoop") << which << " event loop stuck?";
}
static EventLoop* _get(EventLoop* &ctx, bool isPool)
{
if (!ctx)
{
if (! qi::Application::initialized())
{
qiLogInfo("EventLoop") << "Creating event loop while no qi::Application() is running";
}
ctx = new EventLoop();
if (isPool)
ctx->startThreadPool();
else
ctx->start();
Application::atExit(boost::bind(&eventloop_stop, ctx));
if (!isPool && _netEventLoop && _objEventLoop && _monitorInterval)
{
int64_t d = static_cast<qi::int64_t>(_monitorInterval * 1e6);
_netEventLoop->monitorEventLoop(_objEventLoop, d)
.connect(boost::bind(&monitor_notify, "network"));
_objEventLoop->monitorEventLoop(_netEventLoop, d)
.connect(boost::bind(&monitor_notify, "object"));
}
}
return ctx;
}
EventLoop* getDefaultNetworkEventLoop()
{
return _get(_netEventLoop, false);
}
EventLoop* getDefaultObjectEventLoop()
{
return _get(_objEventLoop, false);
}
EventLoop* getDefaultThreadPoolEventLoop()
{
return _get(_poolEventLoop, true);
}
static void setMonitorInterval(double v)
{
_monitorInterval = v;
}
namespace {
_QI_COMMAND_LINE_OPTIONS(
"EventLoop monitoring",
("loop-monitor-latency", value<double>()->notifier(&setMonitorInterval), "Warn if event loop is stuck more than given duration in seconds")
)
}
}
|
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <boost/thread.hpp>
#include <boost/program_options.hpp>
#include <qi/preproc.hpp>
#include <qi/log.hpp>
#include <qi/application.hpp>
#include <qi/threadpool.hpp>
#include <qi/eventloop.hpp>
#include "eventloop_p.hpp"
namespace qi {
EventLoopAsio::EventLoopAsio()
: _destroyMe(false)
, _running(false)
, _threaded(false)
{
}
void EventLoopAsio::start()
{
if (_running || _threaded)
return;
_threaded = true;
_thd = boost::thread(&EventLoopPrivate::run, this);
while (!_running)
qi::os::msleep(0);
}
EventLoopAsio::~EventLoopAsio()
{
if (_running && boost::this_thread::get_id() != _id)
qiLogError("Destroying EventLoopPrivate from itself while running");
stop();
join();
}
void EventLoopAsio::destroy()
{
if (isInEventLoopThread())
boost::thread(&EventLoopAsio::destroy, this);
else
{
stop();
join();
delete this;
}
}
void EventLoopAsio::run()
{
qiLogDebug("qi.EventLoop") << this << "run starting";
_running = true;
_id = boost::this_thread::get_id();
_work = new boost::asio::io_service::work(_io);
_io.run();
bool destroyMe;
{
boost::recursive_mutex::scoped_lock sl(_mutex);
_running = false;
destroyMe = _destroyMe;
}
if (destroyMe)
delete this;
}
bool EventLoopAsio::isInEventLoopThread()
{
return boost::this_thread::get_id() == _id;
}
void EventLoopAsio::stop()
{
qiLogDebug("qi.EventLoop") << this << "stopping";
boost::recursive_mutex::scoped_lock sl(_mutex);
if (_work)
{
delete _work;
_work = 0;
}
}
void EventLoopAsio::join()
{
if (boost::this_thread::get_id() == _id)
{
qiLogError("qi.EventLoop") << "Cannot join from within event loop thread";
return;
}
if (_threaded)
try {
_thd.join();
}
catch(const boost::thread_resource_error& e)
{
qiLogWarning("qi.EventLoop") << "Join an already joined thread: " << e.what();
}
else
while (_running)
qi::os::msleep(0);
}
void EventLoopAsio::post(uint64_t usDelay, const boost::function<void ()>& cb)
{
if (!usDelay)
_io.post(cb);
else
asyncCall(usDelay, cb);
}
static void invoke_maybe(boost::function<void()> f, qi::Promise<void> p, const boost::system::error_code& erc)
{
if (!erc)
{
f();
p.setValue(0);
}
else
p.setError("Operation cancelled");
}
qi::Future<void> EventLoopAsio::asyncCall(uint64_t usDelay, boost::function<void ()> cb)
{
boost::shared_ptr<boost::asio::deadline_timer> timer(new boost::asio::deadline_timer(_io));
timer->expires_from_now(boost::posix_time::microseconds(usDelay));
qi::Promise<void> prom(boost::bind(&boost::asio::deadline_timer::cancel, timer));
timer->async_wait(boost::bind(&invoke_maybe, cb, prom, _1));
return prom.future();
}
void* EventLoopAsio::nativeHandle()
{
return static_cast<void*>(&_io);
}
EventLoopThreadPool::EventLoopThreadPool(int minWorkers, int maxWorkers, int minIdleWorkers, int maxIdleWorkers)
{
_stopping = false;
_pool = new ThreadPool(minWorkers, maxWorkers, minIdleWorkers, maxIdleWorkers);
}
bool EventLoopThreadPool::isInEventLoopThread()
{
// The point is to know if a call will be synchronous. It never is
// with thread pool
return false;
}
void EventLoopThreadPool::start()
{
}
void EventLoopThreadPool::run()
{
}
void EventLoopThreadPool::join()
{
_pool->waitForAll();
}
void EventLoopThreadPool::stop()
{
_stopping = true;
}
void* EventLoopThreadPool::nativeHandle()
{
return 0;
}
void EventLoopThreadPool::destroy()
{
_stopping = true;
// Ensure delete is not called from one of the threads of the event loop
boost::thread(&EventLoopThreadPool::destroy, this);
}
EventLoopThreadPool::~EventLoopThreadPool()
{
delete _pool;
}
static void delay_call(uint64_t usDelay, boost::function<void()> callback)
{
if (usDelay)
qi::os::msleep(static_cast<unsigned int>(usDelay/1000));
try
{
callback();
}
catch(const std::exception& e)
{
qiLogError("qi.EventLoop") << "Exception caught in async call: " << e.what();
}
catch(...)
{
qiLogError("qi.EventLoop") << "Unknown exception caught in async call";
}
}
static void delay_call_notify(uint64_t usDelay, boost::function<void()> callback,
qi::Promise<void> promise)
{
if (usDelay)
qi::os::msleep(static_cast<unsigned int>(usDelay/1000));
try
{
callback();
promise.setValue(0);
}
catch(const std::exception& e)
{
promise.setError(std::string("Exception caught in async call: ") + e.what());
}
catch(...)
{
promise.setError("Unknown exception caught in async call");
}
}
void EventLoopThreadPool::post(uint64_t usDelay,
const boost::function<void ()>& callback)
{
_pool->schedule(boost::bind(&delay_call, usDelay, callback));
}
qi::Future<void> EventLoopThreadPool::asyncCall(uint64_t usDelay,
boost::function<void ()> callback)
{
if (_stopping)
return qi::makeFutureError<void>("Schedule attempt on destroyed thread pool");
qi::Promise<void> promise;
_pool->schedule(boost::bind(&delay_call_notify, usDelay, callback, promise));
return promise.future();
}
// Basic pimpl bouncers.
EventLoop::AsyncCallHandle::AsyncCallHandle()
{
_p = boost::shared_ptr<AsyncCallHandlePrivate>(new AsyncCallHandlePrivate());
}
EventLoop::AsyncCallHandle::~AsyncCallHandle()
{
}
void EventLoop::AsyncCallHandle::cancel()
{
_p->cancel();
}
EventLoop::EventLoop()
: _p(0)
{
}
EventLoop::~EventLoop()
{
if (_p)
_p->destroy();
_p = 0;
}
#define CHECK_STARTED \
do { \
if (!_p) \
throw std::runtime_error("EventLoop " __HERE " : EventLoop not started"); \
} while(0)
bool EventLoop::isInEventLoopThread()
{
CHECK_STARTED;
return _p->isInEventLoopThread();
}
void EventLoop::join()
{
CHECK_STARTED;
_p->join();
}
void EventLoop::start()
{
if (_p)
return;
_p = new EventLoopAsio();
_p->start();
}
void EventLoop::startThreadPool(int minWorkers, int maxWorkers, int minIdleWorkers, int maxIdleWorkers)
{
#define OR(name, val) (name==-1?val:name)
if (_p)
return;
_p = new EventLoopThreadPool(OR(minWorkers, 2), OR(maxWorkers, 8), OR(minIdleWorkers,1), OR(maxIdleWorkers, 4));
#undef OR
}
void EventLoop::stop()
{
CHECK_STARTED;
_p->stop();
}
void EventLoop::run()
{
if (_p)
return;
_p = new EventLoopAsio();
_p->run();
}
void *EventLoop::nativeHandle() {
CHECK_STARTED;
return _p->nativeHandle();
}
void EventLoop::post(const boost::function<void ()>& callback,uint64_t usDelay)
{
CHECK_STARTED;
_p->post(usDelay, callback);
}
qi::Future<void>
EventLoop::async(
boost::function<void ()> callback,
uint64_t usDelay)
{
CHECK_STARTED;
return _p->asyncCall(usDelay, callback);
}
struct MonitorContext
{
EventLoop* target;
EventLoop* helper;
Future<void> mon;
bool isFired; // true: pinging, false: waiting for next ping.
bool ending;
uint64_t maxDelay;
Promise<void> promise;
int64_t startTime;
};
static void monitor_pingtimeout(boost::shared_ptr<MonitorContext> ctx)
{
//qiLogDebug("qi.EventLoop") << os::ustime() << " MON timeout " << ctx->isFired
// << ' ' << (os::ustime() - ctx->startTime);
if (!ctx->isFired)
return; // Got the pong in the meantime, abort
ctx->promise.setError("Event loop monitor timeout");
/* Ping system is still on, but promise is set.
* So future invocations of cancel() will be ignored, which makes the
* monitoring unstopable.
* So reset the value.
*/
ctx->promise.reset();
}
static void monitor_cancel(boost::shared_ptr<MonitorContext> ctx)
{
//qiLogDebug("qi.EventLoop") << os::ustime() << " MON cancel " << ctx->isFired;
ctx->ending = true;
try {
ctx->mon.cancel();
}
catch (...)
{}
}
static void monitor_ping(boost::shared_ptr<MonitorContext> ctx)
{
if (ctx->ending)
return;
//qiLogDebug("qi.EventLoop") << os::ustime() << " MON ping " << ctx->isFired;
if (ctx->isFired)
{ // This is a pong
ctx->isFired = false;
// Cancel monitoring async call
try {
ctx->mon.cancel();
}
catch (const std::exception& /*e*/) {
//qiLogDebug("qi.EventLoop") << "MON " << e.what();
}
uint64_t pingDelay = os::ustime() - ctx->startTime;
if (pingDelay > ctx->maxDelay / 2)
qiLogDebug("qi.EventLoop") << "Long ping " << pingDelay;
// Wait a bit before pinging againg
//qiLogDebug("qi.EventLoop") << os::ustime() << " MON delay " << ctx->maxDelay;
ctx->helper->async(boost::bind(&monitor_ping, ctx), ctx->maxDelay*5);
}
else
{ // Delay between pings reached, ping again
ctx->startTime = os::ustime();
ctx->isFired = true;
// Start monitor async first, or the ping async can trigger before the
// monitor async is setup
ctx->mon = ctx->helper->async(boost::bind(&monitor_pingtimeout, ctx), ctx->maxDelay);
ctx->target->post(boost::bind(&monitor_ping, ctx));
assert(ctx->mon.isCanceleable());
}
}
qi::Future<void> EventLoop::monitorEventLoop(EventLoop* helper, uint64_t maxDelay)
{
// Context data is a Future*[2]
boost::shared_ptr<MonitorContext> ctx(new MonitorContext);
ctx->target = this;
ctx->helper = helper;
ctx->maxDelay = maxDelay;
ctx->promise = Promise<void>(boost::bind(&monitor_cancel, ctx));
ctx->isFired = false;
ctx->ending = false;
monitor_ping(ctx);
return ctx->promise.future();
}
static void eventloop_stop(EventLoop* ctx)
{
ctx->stop();
ctx->join();
delete ctx;
}
static EventLoop* _netEventLoop = 0;
static EventLoop* _objEventLoop = 0;
static EventLoop* _poolEventLoop = 0;
static double _monitorInterval = 0;
static void monitor_notify(const char* which)
{
qiLogError("qi.EventLoop") << which << " event loop stuck?";
}
static EventLoop* _get(EventLoop* &ctx, bool isPool)
{
if (!ctx)
{
if (! qi::Application::initialized())
{
qiLogInfo("EventLoop") << "Creating event loop while no qi::Application() is running";
}
ctx = new EventLoop();
if (isPool)
ctx->startThreadPool();
else
ctx->start();
Application::atExit(boost::bind(&eventloop_stop, ctx));
if (!isPool && _netEventLoop && _objEventLoop && _monitorInterval)
{
int64_t d = static_cast<qi::int64_t>(_monitorInterval * 1e6);
_netEventLoop->monitorEventLoop(_objEventLoop, d)
.connect(boost::bind(&monitor_notify, "network"));
_objEventLoop->monitorEventLoop(_netEventLoop, d)
.connect(boost::bind(&monitor_notify, "object"));
}
}
return ctx;
}
EventLoop* getDefaultNetworkEventLoop()
{
return _get(_netEventLoop, false);
}
EventLoop* getDefaultObjectEventLoop()
{
return _get(_objEventLoop, false);
}
EventLoop* getDefaultThreadPoolEventLoop()
{
return _get(_poolEventLoop, true);
}
static void setMonitorInterval(double v)
{
_monitorInterval = v;
}
namespace {
_QI_COMMAND_LINE_OPTIONS(
"EventLoop monitoring",
("loop-monitor-latency", value<double>()->notifier(&setMonitorInterval), "Warn if event loop is stuck more than given duration in seconds")
)
}
}
|
Fix comparison between signed and unsigned
|
Fix comparison between signed and unsigned
Change-Id: Ib1f0952e0acc254cc639284dcdd8758a53db18c3
Reviewed-on: http://gerrit.aldebaran.lan:8080/12732
Reviewed-by: llec <[email protected]>
Tested-by: llec <[email protected]>
|
C++
|
bsd-3-clause
|
bsautron/libqi,aldebaran/libqi,aldebaran/libqi,vbarbaresi/libqi,aldebaran/libqi
|
279ccf18f42137bac6fb86fc490e91a0270a3aa6
|
test/CodeGenCXX/implicit-allocation-functions.cpp
|
test/CodeGenCXX/implicit-allocation-functions.cpp
|
// RUN: %clang_cc1 -emit-llvm -triple %itanium_abi_triple -o - -std=c++11 %s 2>&1 | FileCheck %s -check-prefix=CHECKDEF -check-prefix=CHECK11
// RUN: %clang_cc1 -emit-llvm -triple %itanium_abi_triple -o - -std=c++11 -fvisibility hidden %s 2>&1 | FileCheck %s -check-prefix=CHECKHID -check-prefix=CHECK11
// RUN: %clang_cc1 -emit-llvm -triple %itanium_abi_triple -o - -std=c++14 %s 2>&1 | FileCheck %s -check-prefix=CHECKDEF -check-prefix=CHECK14
// RUN: %clang_cc1 -emit-llvm -triple %itanium_abi_triple -o - -std=c++14 -fvisibility hidden %s 2>&1 | FileCheck %s -check-prefix=CHECKHID -check-prefix=CHECK14
// PR22419: Implicit sized deallocation functions always have default visibility.
// Generalized to all implicit allocation functions.
// CHECK14-DAG: %struct.A = type { i8 }
struct A { };
// CHECKDEF-DAG: define void @_Z3fooP1A(%struct.A* %is)
// CHECKHID-DAG: define hidden void @_Z3fooP1A(%struct.A* %is)
void foo(A* is) {
// CHECK11-DAG: call noalias i8* @_Znwm(i64 1)
// CHECK14-DAG: call noalias i8* @_Znwm(i64 1)
is = new A();
// CHECK11-DAG: call void @_ZdlPv(i8* %{{.+}})
// CHECK14-DAG: call void @_ZdlPvm(i8* %{{.+}}, i64 1)
delete is;
}
// CHECK11-DAG: declare noalias i8* @_Znwm(i64)
// CHECK11-DAG: declare void @_ZdlPv(i8*)
// CHECK14-DAG: declare noalias i8* @_Znwm(i64)
// CHECK14-DAG: define linkonce void @_ZdlPvm(i8*, i64)
// CHECK14-DAG: declare void @_ZdlPv(i8*)
// CHECK14-DAG: %struct.B = type { i8 }
struct B { ~B() { }};
// CHECKDEF-DAG: define void @_Z1fP1B(%struct.B* %p)
// CHECKHID-DAG: define hidden void @_Z1fP1B(%struct.B* %p)
void f(B *p) {
// CHECK11-DAG: call noalias i8* @_Znam(i64 13)
// CHECK14-DAG: call noalias i8* @_Znam(i64 13)
p = new B[5];
// CHECK11-DAG: call void @_ZdaPv(i8* %{{.+}})
// CHECK14-DAG: call void @_ZdaPvm(i8* %{{.+}}, i64 %{{.+}})
delete[] p;
}
// CHECK11-DAG: declare noalias i8* @_Znam(i64)
// CHECK11-DAG: declare void @_ZdaPv(i8*)
// CHECK14-DAG: declare noalias i8* @_Znam(i64)
// CHECK14-DAG: define linkonce void @_ZdaPvm(i8*, i64)
// CHECK14-DAG: declare void @_ZdaPv(i8*)
|
// RUN: %clang_cc1 -emit-llvm -triple x86_64-unknown-unknown -o - -std=c++11 %s 2>&1 | FileCheck %s -check-prefix=CHECKDEF -check-prefix=CHECK11
// RUN: %clang_cc1 -emit-llvm -triple x86_64-unknown-unknown-o - -std=c++11 -fvisibility hidden %s 2>&1 | FileCheck %s -check-prefix=CHECKHID -check-prefix=CHECK11
// RUN: %clang_cc1 -emit-llvm -triple x86_64-unknown-unknown -o - -std=c++14 %s 2>&1 | FileCheck %s -check-prefix=CHECKDEF -check-prefix=CHECK14
// RUN: %clang_cc1 -emit-llvm -triple x86_64-unknown-unknown -o - -std=c++14 -fvisibility hidden %s 2>&1 | FileCheck %s -check-prefix=CHECKHID -check-prefix=CHECK14
// PR22419: Implicit sized deallocation functions always have default visibility.
// Generalized to all implicit allocation functions.
// CHECK14-DAG: %struct.A = type { i8 }
struct A { };
// CHECKDEF-DAG: define void @_Z3fooP1A(%struct.A* %is)
// CHECKHID-DAG: define hidden void @_Z3fooP1A(%struct.A* %is)
void foo(A* is) {
// CHECK11-DAG: call noalias i8* @_Znwm(i64 1)
// CHECK14-DAG: call noalias i8* @_Znwm(i64 1)
is = new A();
// CHECK11-DAG: call void @_ZdlPv(i8* %{{.+}})
// CHECK14-DAG: call void @_ZdlPvm(i8* %{{.+}}, i64 1)
delete is;
}
// CHECK11-DAG: declare noalias i8* @_Znwm(i64)
// CHECK11-DAG: declare void @_ZdlPv(i8*)
// CHECK14-DAG: declare noalias i8* @_Znwm(i64)
// CHECK14-DAG: define linkonce void @_ZdlPvm(i8*, i64)
// CHECK14-DAG: declare void @_ZdlPv(i8*)
// CHECK14-DAG: %struct.B = type { i8 }
struct B { ~B() { }};
// CHECKDEF-DAG: define void @_Z1fP1B(%struct.B* %p)
// CHECKHID-DAG: define hidden void @_Z1fP1B(%struct.B* %p)
void f(B *p) {
// CHECK11-DAG: call noalias i8* @_Znam(i64 13)
// CHECK14-DAG: call noalias i8* @_Znam(i64 13)
p = new B[5];
// CHECK11-DAG: call void @_ZdaPv(i8* %{{.+}})
// CHECK14-DAG: call void @_ZdaPvm(i8* %{{.+}}, i64 %{{.+}})
delete[] p;
}
// CHECK11-DAG: declare noalias i8* @_Znam(i64)
// CHECK11-DAG: declare void @_ZdaPv(i8*)
// CHECK14-DAG: declare noalias i8* @_Znam(i64)
// CHECK14-DAG: define linkonce void @_ZdaPvm(i8*, i64)
// CHECK14-DAG: declare void @_ZdaPv(i8*)
|
Fix typo in test case.
|
Fix typo in test case.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@228108 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang
|
ec8430270a9f1adbf9b790319a1d4781658359fd
|
lib/ExecutionEngine/JIT/JIT.cpp
|
lib/ExecutionEngine/JIT/JIT.cpp
|
//===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tool implements a just-in-time compiler for LLVM, allowing direct
// execution of LLVM bytecode in an efficient manner.
//
//===----------------------------------------------------------------------===//
#include "JIT.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/GlobalVariable.h"
#include "llvm/Instructions.h"
#include "llvm/ModuleProvider.h"
#include "llvm/CodeGen/MachineCodeEmitter.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetJITInfo.h"
#include "llvm/Support/DynamicLinker.h"
#include <iostream>
using namespace llvm;
JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
: ExecutionEngine(MP), TM(tm), TJI(tji), PM(MP) {
setTargetData(TM.getTargetData());
// Initialize MCE
MCE = createEmitter(*this);
// Add target data
PM.add(new TargetData(TM.getTargetData()));
// Compile LLVM Code down to machine code in the intermediate representation
TJI.addPassesToJITCompile(PM);
// Turn the machine code intermediate representation into bytes in memory that
// may be executed.
if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
std::cerr << "Target '" << TM.getName()
<< "' doesn't support machine code emission!\n";
abort();
}
}
JIT::~JIT() {
delete MCE;
delete &TM;
}
/// run - Start execution with the specified function and arguments.
///
GenericValue JIT::runFunction(Function *F,
const std::vector<GenericValue> &ArgValues) {
assert(F && "Function *F was null at entry to run()");
void *FPtr = getPointerToFunction(F);
assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
const FunctionType *FTy = F->getFunctionType();
const Type *RetTy = FTy->getReturnType();
assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
"Too many arguments passed into function!");
assert(FTy->getNumParams() == ArgValues.size() &&
"This doesn't support passing arguments through varargs (yet)!");
// Handle some common cases first. These cases correspond to common 'main'
// prototypes.
if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
switch (ArgValues.size()) {
case 3:
if ((FTy->getParamType(0) == Type::IntTy ||
FTy->getParamType(0) == Type::UIntTy) &&
isa<PointerType>(FTy->getParamType(1)) &&
isa<PointerType>(FTy->getParamType(2))) {
int (*PF)(int, char **, const char **) =
(int(*)(int, char **, const char **))FPtr;
// Call the function.
GenericValue rv;
rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
(const char **)GVTOP(ArgValues[2]));
return rv;
}
break;
case 2:
if ((FTy->getParamType(0) == Type::IntTy ||
FTy->getParamType(0) == Type::UIntTy) &&
isa<PointerType>(FTy->getParamType(1))) {
int (*PF)(int, char **) = (int(*)(int, char **))FPtr;
// Call the function.
GenericValue rv;
rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]));
return rv;
}
break;
case 1:
if (FTy->getNumParams() == 1 &&
(FTy->getParamType(0) == Type::IntTy ||
FTy->getParamType(0) == Type::UIntTy)) {
GenericValue rv;
int (*PF)(int) = (int(*)(int))FPtr;
rv.IntVal = PF(ArgValues[0].IntVal);
return rv;
}
break;
}
}
// Handle cases where no arguments are passed first.
if (ArgValues.empty()) {
GenericValue rv;
switch (RetTy->getTypeID()) {
default: assert(0 && "Unknown return type for function call!");
case Type::BoolTyID:
rv.BoolVal = ((bool(*)())FPtr)();
return rv;
case Type::SByteTyID:
case Type::UByteTyID:
rv.SByteVal = ((char(*)())FPtr)();
return rv;
case Type::ShortTyID:
case Type::UShortTyID:
rv.ShortVal = ((short(*)())FPtr)();
return rv;
case Type::VoidTyID:
case Type::IntTyID:
case Type::UIntTyID:
rv.IntVal = ((int(*)())FPtr)();
return rv;
case Type::LongTyID:
case Type::ULongTyID:
rv.LongVal = ((int64_t(*)())FPtr)();
return rv;
case Type::FloatTyID:
rv.FloatVal = ((float(*)())FPtr)();
return rv;
case Type::DoubleTyID:
rv.DoubleVal = ((double(*)())FPtr)();
return rv;
case Type::PointerTyID:
return PTOGV(((void*(*)())FPtr)());
}
}
// Okay, this is not one of our quick and easy cases. Because we don't have a
// full FFI, we have to codegen a nullary stub function that just calls the
// function we are interested in, passing in constants for all of the
// arguments. Make this function and return.
// First, create the function.
FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
Function *Stub = new Function(STy, Function::InternalLinkage, "",
F->getParent());
// Insert a basic block.
BasicBlock *StubBB = new BasicBlock("", Stub);
// Convert all of the GenericValue arguments over to constants. Note that we
// currently don't support varargs.
std::vector<Value*> Args;
for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
Constant *C = 0;
const Type *ArgTy = FTy->getParamType(i);
const GenericValue &AV = ArgValues[i];
switch (ArgTy->getTypeID()) {
default: assert(0 && "Unknown argument type for function call!");
case Type::BoolTyID: C = ConstantBool::get(AV.BoolVal); break;
case Type::SByteTyID: C = ConstantSInt::get(ArgTy, AV.SByteVal); break;
case Type::UByteTyID: C = ConstantUInt::get(ArgTy, AV.UByteVal); break;
case Type::ShortTyID: C = ConstantSInt::get(ArgTy, AV.ShortVal); break;
case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break;
case Type::IntTyID: C = ConstantSInt::get(ArgTy, AV.IntVal); break;
case Type::UIntTyID: C = ConstantUInt::get(ArgTy, AV.UIntVal); break;
case Type::LongTyID: C = ConstantSInt::get(ArgTy, AV.LongVal); break;
case Type::ULongTyID: C = ConstantUInt::get(ArgTy, AV.ULongVal); break;
case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
case Type::PointerTyID:
void *ArgPtr = GVTOP(AV);
if (sizeof(void*) == 4) {
C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr);
} else {
C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr);
}
C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer
break;
}
Args.push_back(C);
}
Value *TheCall = new CallInst(F, Args, "", StubBB);
if (TheCall->getType() != Type::VoidTy)
new ReturnInst(TheCall, StubBB); // Return result of the call.
else
new ReturnInst(StubBB); // Just return void.
// Finally, return the value returned by our nullary stub function.
return runFunction(Stub, std::vector<GenericValue>());
}
/// runJITOnFunction - Run the FunctionPassManager full of
/// just-in-time compilation passes on F, hopefully filling in
/// GlobalAddress[F] with the address of F's machine code.
///
void JIT::runJITOnFunction(Function *F) {
static bool isAlreadyCodeGenerating = false;
assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
// JIT the function
isAlreadyCodeGenerating = true;
PM.run(*F);
isAlreadyCodeGenerating = false;
// If the function referred to a global variable that had not yet been
// emitted, it allocates memory for the global, but doesn't emit it yet. Emit
// all of these globals now.
while (!PendingGlobals.empty()) {
const GlobalVariable *GV = PendingGlobals.back();
PendingGlobals.pop_back();
EmitGlobalVariable(GV);
}
}
/// getPointerToFunction - This method is used to get the address of the
/// specified function, compiling it if neccesary.
///
void *JIT::getPointerToFunction(Function *F) {
if (void *Addr = getPointerToGlobalIfAvailable(F))
return Addr; // Check if function already code gen'd
// Make sure we read in the function if it exists in this Module
try {
MP->materializeFunction(F);
} catch ( std::string& errmsg ) {
std::cerr << "Error reading bytecode file: " << errmsg << "\n";
abort();
} catch (...) {
std::cerr << "Error reading bytecode file!\n";
abort();
}
if (F->isExternal()) {
void *Addr = getPointerToNamedFunction(F->getName());
addGlobalMapping(F, Addr);
return Addr;
}
runJITOnFunction(F);
void *Addr = getPointerToGlobalIfAvailable(F);
assert(Addr && "Code generation didn't add function to GlobalAddress table!");
return Addr;
}
// getPointerToFunctionOrStub - If the specified function has been
// code-gen'd, return a pointer to the function. If not, compile it, or use
// a stub to implement lazy compilation if available.
//
void *JIT::getPointerToFunctionOrStub(Function *F) {
// If we have already code generated the function, just return the address.
if (void *Addr = getPointerToGlobalIfAvailable(F))
return Addr;
// If the target supports "stubs" for functions, get a stub now.
if (void *Ptr = TJI.getJITStubForFunction(F, *MCE))
return Ptr;
// Otherwise, if the target doesn't support it, just codegen the function.
return getPointerToFunction(F);
}
/// getOrEmitGlobalVariable - Return the address of the specified global
/// variable, possibly emitting it to memory if needed. This is used by the
/// Emitter.
void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
void *Ptr = getPointerToGlobalIfAvailable(GV);
if (Ptr) return Ptr;
// If the global is external, just remember the address.
if (GV->isExternal()) {
Ptr = GetAddressOfSymbol(GV->getName().c_str());
if (Ptr == 0) {
std::cerr << "Could not resolve external global address: "
<< GV->getName() << "\n";
abort();
}
} else {
// If the global hasn't been emitted to memory yet, allocate space. We will
// actually initialize the global after current function has finished
// compilation.
Ptr =new char[getTargetData().getTypeSize(GV->getType()->getElementType())];
PendingGlobals.push_back(GV);
}
addGlobalMapping(GV, Ptr);
return Ptr;
}
/// recompileAndRelinkFunction - This method is used to force a function
/// which has already been compiled, to be compiled again, possibly
/// after it has been modified. Then the entry to the old copy is overwritten
/// with a branch to the new copy. If there was no old copy, this acts
/// just like JIT::getPointerToFunction().
///
void *JIT::recompileAndRelinkFunction(Function *F) {
void *OldAddr = getPointerToGlobalIfAvailable(F);
// If it's not already compiled there is no reason to patch it up.
if (OldAddr == 0) { return getPointerToFunction(F); }
// Delete the old function mapping.
addGlobalMapping(F, 0);
// Recodegen the function
runJITOnFunction(F);
// Update state, forward the old function to the new function.
void *Addr = getPointerToGlobalIfAvailable(F);
assert(Addr && "Code generation didn't add function to GlobalAddress table!");
TJI.replaceMachineCodeForFunction(OldAddr, Addr);
return Addr;
}
|
//===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tool implements a just-in-time compiler for LLVM, allowing direct
// execution of LLVM bytecode in an efficient manner.
//
//===----------------------------------------------------------------------===//
#include "JIT.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/GlobalVariable.h"
#include "llvm/Instructions.h"
#include "llvm/ModuleProvider.h"
#include "llvm/CodeGen/MachineCodeEmitter.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetJITInfo.h"
#include "llvm/Support/DynamicLinker.h"
#include <iostream>
using namespace llvm;
JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
: ExecutionEngine(MP), TM(tm), TJI(tji), PM(MP) {
setTargetData(TM.getTargetData());
// Initialize MCE
MCE = createEmitter(*this);
// Add target data
PM.add(new TargetData(TM.getTargetData()));
// Compile LLVM Code down to machine code in the intermediate representation
TJI.addPassesToJITCompile(PM);
// Turn the machine code intermediate representation into bytes in memory that
// may be executed.
if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
std::cerr << "Target '" << TM.getName()
<< "' doesn't support machine code emission!\n";
abort();
}
}
JIT::~JIT() {
delete MCE;
delete &TM;
}
/// run - Start execution with the specified function and arguments.
///
GenericValue JIT::runFunction(Function *F,
const std::vector<GenericValue> &ArgValues) {
assert(F && "Function *F was null at entry to run()");
void *FPtr = getPointerToFunction(F);
assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
const FunctionType *FTy = F->getFunctionType();
const Type *RetTy = FTy->getReturnType();
assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
"Too many arguments passed into function!");
assert(FTy->getNumParams() == ArgValues.size() &&
"This doesn't support passing arguments through varargs (yet)!");
// Handle some common cases first. These cases correspond to common `main'
// prototypes.
if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
switch (ArgValues.size()) {
case 3:
if ((FTy->getParamType(0) == Type::IntTy ||
FTy->getParamType(0) == Type::UIntTy) &&
isa<PointerType>(FTy->getParamType(1)) &&
isa<PointerType>(FTy->getParamType(2))) {
int (*PF)(int, char **, const char **) =
(int(*)(int, char **, const char **))FPtr;
// Call the function.
GenericValue rv;
rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
(const char **)GVTOP(ArgValues[2]));
return rv;
}
break;
case 2:
if ((FTy->getParamType(0) == Type::IntTy ||
FTy->getParamType(0) == Type::UIntTy) &&
isa<PointerType>(FTy->getParamType(1))) {
int (*PF)(int, char **) = (int(*)(int, char **))FPtr;
// Call the function.
GenericValue rv;
rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]));
return rv;
}
break;
case 1:
if (FTy->getNumParams() == 1 &&
(FTy->getParamType(0) == Type::IntTy ||
FTy->getParamType(0) == Type::UIntTy)) {
GenericValue rv;
int (*PF)(int) = (int(*)(int))FPtr;
rv.IntVal = PF(ArgValues[0].IntVal);
return rv;
}
break;
}
}
// Handle cases where no arguments are passed first.
if (ArgValues.empty()) {
GenericValue rv;
switch (RetTy->getTypeID()) {
default: assert(0 && "Unknown return type for function call!");
case Type::BoolTyID:
rv.BoolVal = ((bool(*)())FPtr)();
return rv;
case Type::SByteTyID:
case Type::UByteTyID:
rv.SByteVal = ((char(*)())FPtr)();
return rv;
case Type::ShortTyID:
case Type::UShortTyID:
rv.ShortVal = ((short(*)())FPtr)();
return rv;
case Type::VoidTyID:
case Type::IntTyID:
case Type::UIntTyID:
rv.IntVal = ((int(*)())FPtr)();
return rv;
case Type::LongTyID:
case Type::ULongTyID:
rv.LongVal = ((int64_t(*)())FPtr)();
return rv;
case Type::FloatTyID:
rv.FloatVal = ((float(*)())FPtr)();
return rv;
case Type::DoubleTyID:
rv.DoubleVal = ((double(*)())FPtr)();
return rv;
case Type::PointerTyID:
return PTOGV(((void*(*)())FPtr)());
}
}
// Okay, this is not one of our quick and easy cases. Because we don't have a
// full FFI, we have to codegen a nullary stub function that just calls the
// function we are interested in, passing in constants for all of the
// arguments. Make this function and return.
// First, create the function.
FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
Function *Stub = new Function(STy, Function::InternalLinkage, "",
F->getParent());
// Insert a basic block.
BasicBlock *StubBB = new BasicBlock("", Stub);
// Convert all of the GenericValue arguments over to constants. Note that we
// currently don't support varargs.
std::vector<Value*> Args;
for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
Constant *C = 0;
const Type *ArgTy = FTy->getParamType(i);
const GenericValue &AV = ArgValues[i];
switch (ArgTy->getTypeID()) {
default: assert(0 && "Unknown argument type for function call!");
case Type::BoolTyID: C = ConstantBool::get(AV.BoolVal); break;
case Type::SByteTyID: C = ConstantSInt::get(ArgTy, AV.SByteVal); break;
case Type::UByteTyID: C = ConstantUInt::get(ArgTy, AV.UByteVal); break;
case Type::ShortTyID: C = ConstantSInt::get(ArgTy, AV.ShortVal); break;
case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break;
case Type::IntTyID: C = ConstantSInt::get(ArgTy, AV.IntVal); break;
case Type::UIntTyID: C = ConstantUInt::get(ArgTy, AV.UIntVal); break;
case Type::LongTyID: C = ConstantSInt::get(ArgTy, AV.LongVal); break;
case Type::ULongTyID: C = ConstantUInt::get(ArgTy, AV.ULongVal); break;
case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
case Type::PointerTyID:
void *ArgPtr = GVTOP(AV);
if (sizeof(void*) == 4) {
C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr);
} else {
C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr);
}
C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer
break;
}
Args.push_back(C);
}
Value *TheCall = new CallInst(F, Args, "", StubBB);
if (TheCall->getType() != Type::VoidTy)
new ReturnInst(TheCall, StubBB); // Return result of the call.
else
new ReturnInst(StubBB); // Just return void.
// Finally, return the value returned by our nullary stub function.
return runFunction(Stub, std::vector<GenericValue>());
}
/// runJITOnFunction - Run the FunctionPassManager full of
/// just-in-time compilation passes on F, hopefully filling in
/// GlobalAddress[F] with the address of F's machine code.
///
void JIT::runJITOnFunction(Function *F) {
static bool isAlreadyCodeGenerating = false;
assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
// JIT the function
isAlreadyCodeGenerating = true;
PM.run(*F);
isAlreadyCodeGenerating = false;
// If the function referred to a global variable that had not yet been
// emitted, it allocates memory for the global, but doesn't emit it yet. Emit
// all of these globals now.
while (!PendingGlobals.empty()) {
const GlobalVariable *GV = PendingGlobals.back();
PendingGlobals.pop_back();
EmitGlobalVariable(GV);
}
}
/// getPointerToFunction - This method is used to get the address of the
/// specified function, compiling it if neccesary.
///
void *JIT::getPointerToFunction(Function *F) {
if (void *Addr = getPointerToGlobalIfAvailable(F))
return Addr; // Check if function already code gen'd
// Make sure we read in the function if it exists in this Module
try {
MP->materializeFunction(F);
} catch ( std::string& errmsg ) {
std::cerr << "Error reading bytecode file: " << errmsg << "\n";
abort();
} catch (...) {
std::cerr << "Error reading bytecode file!\n";
abort();
}
if (F->isExternal()) {
void *Addr = getPointerToNamedFunction(F->getName());
addGlobalMapping(F, Addr);
return Addr;
}
runJITOnFunction(F);
void *Addr = getPointerToGlobalIfAvailable(F);
assert(Addr && "Code generation didn't add function to GlobalAddress table!");
return Addr;
}
// getPointerToFunctionOrStub - If the specified function has been
// code-gen'd, return a pointer to the function. If not, compile it, or use
// a stub to implement lazy compilation if available.
//
void *JIT::getPointerToFunctionOrStub(Function *F) {
// If we have already code generated the function, just return the address.
if (void *Addr = getPointerToGlobalIfAvailable(F))
return Addr;
// If the target supports "stubs" for functions, get a stub now.
if (void *Ptr = TJI.getJITStubForFunction(F, *MCE))
return Ptr;
// Otherwise, if the target doesn't support it, just codegen the function.
return getPointerToFunction(F);
}
/// getOrEmitGlobalVariable - Return the address of the specified global
/// variable, possibly emitting it to memory if needed. This is used by the
/// Emitter.
void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
void *Ptr = getPointerToGlobalIfAvailable(GV);
if (Ptr) return Ptr;
// If the global is external, just remember the address.
if (GV->isExternal()) {
Ptr = GetAddressOfSymbol(GV->getName().c_str());
if (Ptr == 0) {
std::cerr << "Could not resolve external global address: "
<< GV->getName() << "\n";
abort();
}
} else {
// If the global hasn't been emitted to memory yet, allocate space. We will
// actually initialize the global after current function has finished
// compilation.
Ptr =new char[getTargetData().getTypeSize(GV->getType()->getElementType())];
PendingGlobals.push_back(GV);
}
addGlobalMapping(GV, Ptr);
return Ptr;
}
/// recompileAndRelinkFunction - This method is used to force a function
/// which has already been compiled, to be compiled again, possibly
/// after it has been modified. Then the entry to the old copy is overwritten
/// with a branch to the new copy. If there was no old copy, this acts
/// just like JIT::getPointerToFunction().
///
void *JIT::recompileAndRelinkFunction(Function *F) {
void *OldAddr = getPointerToGlobalIfAvailable(F);
// If it's not already compiled there is no reason to patch it up.
if (OldAddr == 0) { return getPointerToFunction(F); }
// Delete the old function mapping.
addGlobalMapping(F, 0);
// Recodegen the function
runJITOnFunction(F);
// Update state, forward the old function to the new function.
void *Addr = getPointerToGlobalIfAvailable(F);
assert(Addr && "Code generation didn't add function to GlobalAddress table!");
TJI.replaceMachineCodeForFunction(OldAddr, Addr);
return Addr;
}
|
Use cleaner quoting and eliminate blank space
|
Use cleaner quoting and eliminate blank space
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@17174 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap
|
05b7eaffdd7440ad61e30b75790094791776c5f8
|
lib/Support/LockFileManager.cpp
|
lib/Support/LockFileManager.cpp
|
//===--- LockFileManager.cpp - File-level Locking Utility------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/LockFileManager.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <sys/stat.h>
#include <sys/types.h>
#if LLVM_ON_WIN32
#include <windows.h>
#endif
#if LLVM_ON_UNIX
#include <unistd.h>
#endif
using namespace llvm;
/// \brief Attempt to read the lock file with the given name, if it exists.
///
/// \param LockFileName The name of the lock file to read.
///
/// \returns The process ID of the process that owns this lock file
Optional<std::pair<std::string, int> >
LockFileManager::readLockFile(StringRef LockFileName) {
// Read the owning host and PID out of the lock file. If it appears that the
// owning process is dead, the lock file is invalid.
ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
MemoryBuffer::getFile(LockFileName);
if (!MBOrErr) {
sys::fs::remove(LockFileName);
return None;
}
MemoryBuffer &MB = *MBOrErr.get();
StringRef Hostname;
StringRef PIDStr;
std::tie(Hostname, PIDStr) = getToken(MB.getBuffer(), " ");
PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
int PID;
if (!PIDStr.getAsInteger(10, PID)) {
auto Owner = std::make_pair(std::string(Hostname), PID);
if (processStillExecuting(Owner.first, Owner.second))
return Owner;
}
// Delete the lock file. It's invalid anyway.
sys::fs::remove(LockFileName);
return None;
}
bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
#if LLVM_ON_UNIX && !defined(__ANDROID__)
char MyHostname[256];
MyHostname[255] = 0;
MyHostname[0] = 0;
gethostname(MyHostname, 255);
// Check whether the process is dead. If so, we're done.
if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
return false;
#endif
return true;
}
LockFileManager::LockFileManager(StringRef FileName)
{
this->FileName = FileName;
if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
Error = EC;
return;
}
LockFileName = this->FileName;
LockFileName += ".lock";
// If the lock file already exists, don't bother to try to create our own
// lock file; it won't work anyway. Just figure out who owns this lock file.
if ((Owner = readLockFile(LockFileName)))
return;
// Create a lock file that is unique to this instance.
UniqueLockFileName = LockFileName;
UniqueLockFileName += "-%%%%%%%%";
int UniqueLockFileID;
if (std::error_code EC = sys::fs::createUniqueFile(
UniqueLockFileName.str(), UniqueLockFileID, UniqueLockFileName)) {
Error = EC;
return;
}
// Write our process ID to our unique lock file.
{
raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
#if LLVM_ON_UNIX
// FIXME: move getpid() call into LLVM
char hostname[256];
hostname[255] = 0;
hostname[0] = 0;
gethostname(hostname, 255);
Out << hostname << ' ' << getpid();
#else
Out << "localhost 1";
#endif
Out.close();
if (Out.has_error()) {
// We failed to write out PID, so make up an excuse, remove the
// unique lock file, and fail.
Error = make_error_code(errc::no_space_on_device);
sys::fs::remove(UniqueLockFileName.c_str());
return;
}
}
while (1) {
// Create a link from the lock file name. If this succeeds, we're done.
std::error_code EC =
sys::fs::create_link(UniqueLockFileName.str(), LockFileName.str());
if (!EC)
return;
if (EC != errc::file_exists) {
Error = EC;
return;
}
// Someone else managed to create the lock file first. Read the process ID
// from the lock file.
if ((Owner = readLockFile(LockFileName))) {
// Wipe out our unique lock file (it's useless now)
sys::fs::remove(UniqueLockFileName.str());
return;
}
if (!sys::fs::exists(LockFileName.str())) {
// The previous owner released the lock file before we could read it.
// Try to get ownership again.
continue;
}
// There is a lock file that nobody owns; try to clean it up and get
// ownership.
if ((EC = sys::fs::remove(LockFileName.str()))) {
Error = EC;
return;
}
}
}
LockFileManager::LockFileState LockFileManager::getState() const {
if (Owner)
return LFS_Shared;
if (Error)
return LFS_Error;
return LFS_Owned;
}
LockFileManager::~LockFileManager() {
if (getState() != LFS_Owned)
return;
// Since we own the lock, remove the lock file and our own unique lock file.
sys::fs::remove(LockFileName.str());
sys::fs::remove(UniqueLockFileName.str());
}
LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
if (getState() != LFS_Shared)
return Res_Success;
#if LLVM_ON_WIN32
unsigned long Interval = 1;
#else
struct timespec Interval;
Interval.tv_sec = 0;
Interval.tv_nsec = 1000000;
#endif
// Don't wait more than one minute for the file to appear.
const unsigned MaxSeconds = 60;
do {
// Sleep for the designated interval, to allow the owning process time to
// finish up and remove the lock file.
// FIXME: Should we hook in to system APIs to get a notification when the
// lock file is deleted?
#if LLVM_ON_WIN32
Sleep(Interval);
#else
nanosleep(&Interval, nullptr);
#endif
if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) ==
errc::no_such_file_or_directory) {
// If the original file wasn't created, somone thought the lock was dead.
if (!sys::fs::exists(FileName.str()))
return Res_OwnerDied;
return Res_Success;
}
// If the process owning the lock died without cleaning up, just bail out.
if (!processStillExecuting((*Owner).first, (*Owner).second))
return Res_OwnerDied;
// Exponentially increase the time we wait for the lock to be removed.
#if LLVM_ON_WIN32
Interval *= 2;
#else
Interval.tv_sec *= 2;
Interval.tv_nsec *= 2;
if (Interval.tv_nsec >= 1000000000) {
++Interval.tv_sec;
Interval.tv_nsec -= 1000000000;
}
#endif
} while (
#if LLVM_ON_WIN32
Interval < MaxSeconds * 1000
#else
Interval.tv_sec < (time_t)MaxSeconds
#endif
);
// Give up.
return Res_Timeout;
}
std::error_code LockFileManager::unsafeRemoveLockFile() {
return sys::fs::remove(LockFileName.str());
}
|
//===--- LockFileManager.cpp - File-level Locking Utility------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/LockFileManager.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <sys/stat.h>
#include <sys/types.h>
#if LLVM_ON_WIN32
#include <windows.h>
#endif
#if LLVM_ON_UNIX
#include <unistd.h>
#endif
using namespace llvm;
/// \brief Attempt to read the lock file with the given name, if it exists.
///
/// \param LockFileName The name of the lock file to read.
///
/// \returns The process ID of the process that owns this lock file
Optional<std::pair<std::string, int> >
LockFileManager::readLockFile(StringRef LockFileName) {
// Read the owning host and PID out of the lock file. If it appears that the
// owning process is dead, the lock file is invalid.
ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
MemoryBuffer::getFile(LockFileName);
if (!MBOrErr) {
sys::fs::remove(LockFileName);
return None;
}
MemoryBuffer &MB = *MBOrErr.get();
StringRef Hostname;
StringRef PIDStr;
std::tie(Hostname, PIDStr) = getToken(MB.getBuffer(), " ");
PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
int PID;
if (!PIDStr.getAsInteger(10, PID)) {
auto Owner = std::make_pair(std::string(Hostname), PID);
if (processStillExecuting(Owner.first, Owner.second))
return Owner;
}
// Delete the lock file. It's invalid anyway.
sys::fs::remove(LockFileName);
return None;
}
bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
#if LLVM_ON_UNIX && !defined(__ANDROID__)
char MyHostname[256];
MyHostname[255] = 0;
MyHostname[0] = 0;
gethostname(MyHostname, 255);
// Check whether the process is dead. If so, we're done.
if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
return false;
#endif
return true;
}
LockFileManager::LockFileManager(StringRef FileName)
{
this->FileName = FileName;
if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
Error = EC;
return;
}
LockFileName = this->FileName;
LockFileName += ".lock";
// If the lock file already exists, don't bother to try to create our own
// lock file; it won't work anyway. Just figure out who owns this lock file.
if ((Owner = readLockFile(LockFileName)))
return;
// Create a lock file that is unique to this instance.
UniqueLockFileName = LockFileName;
UniqueLockFileName += "-%%%%%%%%";
int UniqueLockFileID;
if (std::error_code EC = sys::fs::createUniqueFile(
UniqueLockFileName.str(), UniqueLockFileID, UniqueLockFileName)) {
Error = EC;
return;
}
// Write our process ID to our unique lock file.
{
raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
#if LLVM_ON_UNIX
// FIXME: move getpid() call into LLVM
char hostname[256];
hostname[255] = 0;
hostname[0] = 0;
gethostname(hostname, 255);
Out << hostname << ' ' << getpid();
#else
Out << "localhost 1";
#endif
Out.close();
if (Out.has_error()) {
// We failed to write out PID, so make up an excuse, remove the
// unique lock file, and fail.
Error = make_error_code(errc::no_space_on_device);
sys::fs::remove(UniqueLockFileName.c_str());
return;
}
}
while (1) {
// Create a link from the lock file name. If this succeeds, we're done.
std::error_code EC =
sys::fs::create_link(UniqueLockFileName.str(), LockFileName.str());
if (!EC)
return;
if (EC != errc::file_exists) {
Error = EC;
return;
}
// Someone else managed to create the lock file first. Read the process ID
// from the lock file.
if ((Owner = readLockFile(LockFileName))) {
// Wipe out our unique lock file (it's useless now)
sys::fs::remove(UniqueLockFileName.str());
return;
}
if (!sys::fs::exists(LockFileName.str())) {
// The previous owner released the lock file before we could read it.
// Try to get ownership again.
continue;
}
// There is a lock file that nobody owns; try to clean it up and get
// ownership.
if ((EC = sys::fs::remove(LockFileName.str()))) {
Error = EC;
return;
}
}
}
LockFileManager::LockFileState LockFileManager::getState() const {
if (Owner)
return LFS_Shared;
if (Error)
return LFS_Error;
return LFS_Owned;
}
LockFileManager::~LockFileManager() {
if (getState() != LFS_Owned)
return;
// Since we own the lock, remove the lock file and our own unique lock file.
sys::fs::remove(LockFileName.str());
sys::fs::remove(UniqueLockFileName.str());
}
LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
if (getState() != LFS_Shared)
return Res_Success;
#if LLVM_ON_WIN32
unsigned long Interval = 1;
#else
struct timespec Interval;
Interval.tv_sec = 0;
Interval.tv_nsec = 1000000;
#endif
// Don't wait more than five minutes per iteration. Total timeout for the file
// to appear is ~8.5 mins.
const unsigned MaxSeconds = 5*60;
do {
// Sleep for the designated interval, to allow the owning process time to
// finish up and remove the lock file.
// FIXME: Should we hook in to system APIs to get a notification when the
// lock file is deleted?
#if LLVM_ON_WIN32
Sleep(Interval);
#else
nanosleep(&Interval, nullptr);
#endif
if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) ==
errc::no_such_file_or_directory) {
// If the original file wasn't created, somone thought the lock was dead.
if (!sys::fs::exists(FileName.str()))
return Res_OwnerDied;
return Res_Success;
}
// If the process owning the lock died without cleaning up, just bail out.
if (!processStillExecuting((*Owner).first, (*Owner).second))
return Res_OwnerDied;
// Exponentially increase the time we wait for the lock to be removed.
#if LLVM_ON_WIN32
Interval *= 2;
#else
Interval.tv_sec *= 2;
Interval.tv_nsec *= 2;
if (Interval.tv_nsec >= 1000000000) {
++Interval.tv_sec;
Interval.tv_nsec -= 1000000000;
}
#endif
} while (
#if LLVM_ON_WIN32
Interval < MaxSeconds * 1000
#else
Interval.tv_sec < (time_t)MaxSeconds
#endif
);
// Give up.
return Res_Timeout;
}
std::error_code LockFileManager::unsafeRemoveLockFile() {
return sys::fs::remove(LockFileName.str());
}
|
Increase timeout for the LockFileManager back to 5 mins.
|
[Support] Increase timeout for the LockFileManager back to 5 mins.
Waiting for just 1 min may not be enough for some contexts.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@231309 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm
|
b6ebc1a67bdbe8244ed334fec8cd7edc71e41a10
|
cc/simple_example.cc
|
cc/simple_example.cc
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 <iostream>
#include "cc/dual_net/factory.h"
#include "cc/game.h"
#include "cc/init.h"
#include "cc/logging.h"
#include "cc/mcts_player.h"
#include "cc/platform/utils.h"
#include "cc/random.h"
#include "cc/zobrist.h"
#include "gflags/gflags.h"
// Inference flags.
DEFINE_string(model, "",
"Path to a minigo model. The format of the model depends on the "
"inference engine. For engine=tf, the model should be a GraphDef "
"proto. For engine=lite, the model should be .tflite "
"flatbuffer.");
DEFINE_int32(num_readouts, 100,
"Number of readouts to make during tree search for each move.");
namespace minigo {
namespace {
void SimpleExample() {
// Determine whether ANSI color codes are supported (used when printing
// the board state after each move).
const bool use_ansi_colors = FdSupportsAnsiColors(fileno(stderr));
// Load the model specified by the command line arguments.
auto model_factory = NewDualNetFactory();
auto model = model_factory->NewDualNet(FLAGS_model);
// Create the player.
MctsPlayer::Options options;
options.inject_noise = false;
options.soft_pick = false;
options.num_readouts = FLAGS_num_readouts;
MctsPlayer player(std::move(model), options);
// Create a game object that tracks the move history & final score.
Game game(player.name(), player.name(), options.game_options);
// Tell the model factory we're starting a game.
// TODO(tommadams): Remove this once BatchingDualNetFactory is no longer a
// DualNetFactory.
model_factory->StartGame(player.network(), player.network());
// Play the game.
while (!player.root()->game_over() && !player.root()->at_move_limit()) {
auto move = player.SuggestMove();
const auto& position = player.root()->position;
MG_LOG(INFO) << player.root()->position.ToPrettyString(use_ansi_colors);
MG_LOG(INFO) << "Move: " << position.n()
<< " Captures X: " << position.num_captures()[0]
<< " O: " << position.num_captures()[1];
MG_LOG(INFO) << player.root()->Describe();
MG_CHECK(player.PlayMove(move, &game));
}
// Tell the model factory we're ending a game.
// TODO(tommadams): Remove this once BatchingDualNetFactory is no longer a
// DualNetFactory.
model_factory->EndGame(player.network(), player.network());
std::cout << game.result_string() << std::endl;
}
} // namespace
} // namespace minigo
int main(int argc, char* argv[]) {
minigo::Init(&argc, &argv);
minigo::zobrist::Init(0);
minigo::SimpleExample();
return 0;
}
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 <iostream>
#include "cc/dual_net/factory.h"
#include "cc/game.h"
#include "cc/init.h"
#include "cc/logging.h"
#include "cc/mcts_player.h"
#include "cc/platform/utils.h"
#include "cc/random.h"
#include "cc/zobrist.h"
#include "gflags/gflags.h"
// Inference flags.
DEFINE_string(model, "",
"Path to a minigo model. The format of the model depends on the "
"inference engine. For engine=tf, the model should be a GraphDef "
"proto. For engine=lite, the model should be .tflite "
"flatbuffer.");
DEFINE_int32(num_readouts, 100,
"Number of readouts to make during tree search for each move.");
namespace minigo {
namespace {
void SimpleExample() {
// Determine whether ANSI color codes are supported (used when printing
// the board state after each move).
const bool use_ansi_colors = FdSupportsAnsiColors(fileno(stderr));
// Load the model specified by the command line arguments.
auto model_factory = NewDualNetFactory();
auto model = model_factory->NewDualNet(FLAGS_model);
// Create the player.
MctsPlayer::Options options;
options.inject_noise = false;
options.soft_pick = false;
options.num_readouts = FLAGS_num_readouts;
MctsPlayer player(std::move(model), options);
// Create a game object that tracks the move history & final score.
Game game(player.name(), player.name(), options.game_options);
// Tell the model factory we're starting a game.
// TODO(tommadams): Remove this once BatchingDualNetFactory is no longer a
// DualNetFactory.
model_factory->StartGame(player.network(), player.network());
// Play the game.
while (!player.root()->game_over() && !player.root()->at_move_limit()) {
auto move = player.SuggestMove();
const auto& position = player.root()->position;
std::cout << player.root()->position.ToPrettyString(use_ansi_colors)
<< "\n";
std::cout << "Move: " << position.n()
<< " Captures X: " << position.num_captures()[0]
<< " O: " << position.num_captures()[1] << "\n";
std::cout << player.root()->Describe() << "\n";
MG_CHECK(player.PlayMove(move, &game));
}
// Tell the model factory we're ending a game.
// TODO(tommadams): Remove this once BatchingDualNetFactory is no longer a
// DualNetFactory.
model_factory->EndGame(player.network(), player.network());
std::cout << game.result_string() << std::endl;
}
} // namespace
} // namespace minigo
int main(int argc, char* argv[]) {
minigo::Init(&argc, &argv);
minigo::zobrist::Init(0);
minigo::SimpleExample();
return 0;
}
|
use std::cout instead of MG_LOG(INFO)
|
use std::cout instead of MG_LOG(INFO)
|
C++
|
apache-2.0
|
tensorflow/minigo,tensorflow/minigo,tensorflow/minigo,tensorflow/minigo,tensorflow/minigo,tensorflow/minigo
|
7a9493c51d09d87f22357297879c6c1ae9ee0067
|
modules/canbus/vehicle/gem/protocol/wheel_speed_rpt_7a_test.cc
|
modules/canbus/vehicle/gem/protocol/wheel_speed_rpt_7a_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo 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 "modules/canbus/vehicle/gem/protocol/wheel_speed_rpt_7a.h"
#include "gtest/gtest.h"
namespace apollo {
namespace canbus {
namespace gem {
class Wheelspeedrpt7aTest : public ::testing::Test {
public:
virtual void SetUp() {}
};
TEST_F(Wheelspeedrpt7aTest, reset) {
Wheelspeedrpt7a wheelspeed;
int32_t length = 8;
ChassisDetail chassis_detail;
uint8_t bytes[8] = {0x01, 0x02, 0x03, 0x04, 0x11, 0x12, 0x13, 0x14};
wheelspeed.Parse(bytes, length, &chassis_detail);
EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\
.wheel_spd_rear_right(), 4884);
EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\
.wheel_spd_rear_left(), 4370);
EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\
.wheel_spd_front_right(), 772);
EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\
.wheel_spd_front_left(), 258);
}
} // namespace gem
} // namespace canbus
} // namespace apollo
|
/******************************************************************************
* Copyright 2018 The Apollo 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 "modules/canbus/vehicle/gem/protocol/wheel_speed_rpt_7a.h"
#include "gtest/gtest.h"
namespace apollo {
namespace canbus {
namespace gem {
class Wheelspeedrpt7aTest : public ::testing::Test {
public:
virtual void SetUp() {}
};
TEST_F(Wheelspeedrpt7aTest, reset) {
Wheelspeedrpt7a wheelspeed;
int32_t length = 8;
ChassisDetail chassis_detail;
uint8_t bytes[8] = {0x01, 0x02, 0x03, 0x04, 0x11, 0x12, 0x13, 0x14};
wheelspeed.Parse(bytes, length, &chassis_detail);
EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\
.wheel_spd_rear_right(), 4884);
EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\
.wheel_spd_rear_left(), 4370);
EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\
.wheel_spd_front_right(), 772);
EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\
.wheel_spd_front_left(), 258);
}
} // namespace gem
} // namespace canbus
} // namespace apollo
|
Update wheel_speed_rpt_7a_test.cc
|
Update wheel_speed_rpt_7a_test.cc
|
C++
|
apache-2.0
|
startcode/apollo,startcode/apollo,startcode/apollo,startcode/apollo,startcode/apollo,startcode/apollo
|
3c2d09220d59cd711f5c042644adf1f50fd0c552
|
modules/tensor_mechanics/src/userobjects/CavityPressureUserObject.C
|
modules/tensor_mechanics/src/userobjects/CavityPressureUserObject.C
|
/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "CavityPressureUserObject.h"
template<>
InputParameters validParams<CavityPressureUserObject>()
{
InputParameters params = validParams<GeneralUserObject>();
params.addParam<Real>("initial_pressure", 0, "The initial pressure in the cavity. If not given, a zero initial pressure will be used.");
params.addParam<std::vector<PostprocessorName> >("material_input", "The name of the postprocessor(s) that holds the amount of material injected into the cavity.");
params.addRequiredParam<Real>("R", "The universal gas constant for the units used.");
params.addRequiredParam<PostprocessorName>("temperature", "The name of the average temperature postprocessor value.");
params.addParam<Real>("initial_temperature", "Initial temperature (optional)");
params.addRequiredParam<PostprocessorName>("volume", "The name of the internal volume postprocessor value.");
params.addParam<Real>("startup_time", 0, "The amount of time during which the pressure will ramp from zero to its true value.");
params.set<bool>("use_displaced_mesh") = true;
params.addPrivateParam<std::string>("built_by_action", "");// Hide from input file dump
return params;
}
CavityPressureUserObject::CavityPressureUserObject(const InputParameters & params) :
GeneralUserObject(params),
_cavity_pressure(declareRestartableData<Real>("cavity_pressure", 0)),
_n0(declareRestartableData<Real>("initial_moles", 0)),
_initial_pressure(getParam<Real>("initial_pressure")),
_material_input(),
_R(getParam<Real>("R")),
_temperature(getPostprocessorValue("temperature")),
_init_temp_given(isParamValid("initial_temperature")),
_init_temp(_init_temp_given ? getParam<Real>("initial_temperature") : 0),
_volume(getPostprocessorValue("volume")),
_start_time(0),
_startup_time(getParam<Real>("startup_time")),
_initialized(declareRestartableData<bool>("initialized", false))
{
if (isParamValid("material_input"))
{
std::vector<PostprocessorName> ppn = params.get<std::vector<PostprocessorName> >("material_input");
const unsigned int len = ppn.size();
for (unsigned int i = 0; i < len; ++i)
_material_input.push_back(&getPostprocessorValueByName(ppn[i]));
}
}
Real
CavityPressureUserObject::getValue(const std::string & quantity) const
{
Real value = 0;
if ("initial_moles" == quantity)
value = _n0;
else if ("cavity_pressure" == quantity)
value = _cavity_pressure;
else
mooseError("Unknown quantity in " + name());
return value;
}
void
CavityPressureUserObject::initialize()
{
if (!_initialized)
{
Real init_temp = _temperature;
if (_init_temp_given)
init_temp = _init_temp;
_n0 = _initial_pressure * _volume / (_R * init_temp);
_start_time = _t - _dt;
const Real factor = _t >= _start_time + _startup_time ? 1.0 : (_t - _start_time) / _startup_time;
_cavity_pressure = factor * _initial_pressure;
_initialized = true;
}
}
void
CavityPressureUserObject::execute()
{
Real mat = 0;
for (unsigned int i = 0; i < _material_input.size(); ++i)
mat += *_material_input[i];
const Real pressure = (_n0 + mat) * _R * _temperature / _volume;
const Real factor = _t >= _start_time + _startup_time ? 1.0 : (_t - _start_time) / _startup_time;
_cavity_pressure = factor * pressure;
}
|
/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "CavityPressureUserObject.h"
template<>
InputParameters validParams<CavityPressureUserObject>()
{
InputParameters params = validParams<GeneralUserObject>();
params.addParam<Real>("initial_pressure", 0, "The initial pressure in the cavity. If not given, a zero initial pressure will be used.");
params.addParam<std::vector<PostprocessorName> >("material_input", "The name of the postprocessor(s) that holds the amount of material injected into the cavity.");
params.addRequiredParam<Real>("R", "The universal gas constant for the units used.");
params.addRequiredParam<PostprocessorName>("temperature", "The name of the average temperature postprocessor value.");
params.addParam<Real>("initial_temperature", "Initial temperature (optional)");
params.addRequiredParam<PostprocessorName>("volume", "The name of the internal volume postprocessor value.");
params.addParam<Real>("startup_time", 0, "The amount of time during which the pressure will ramp from zero to its true value.");
params.set<bool>("use_displaced_mesh") = true;
params.addPrivateParam<std::string>("built_by_action", "");// Hide from input file dump
return params;
}
CavityPressureUserObject::CavityPressureUserObject(const InputParameters & params) :
GeneralUserObject(params),
_cavity_pressure(declareRestartableData<Real>("cavity_pressure", 0)),
_n0(declareRestartableData<Real>("initial_moles", 0)),
_initial_pressure(getParam<Real>("initial_pressure")),
_material_input(),
_R(getParam<Real>("R")),
_temperature(getPostprocessorValue("temperature")),
_init_temp_given(isParamValid("initial_temperature")),
_init_temp(_init_temp_given ? getParam<Real>("initial_temperature") : 0),
_volume(getPostprocessorValue("volume")),
_start_time(0),
_startup_time(getParam<Real>("startup_time")),
_initialized(declareRestartableData<bool>("initialized", false))
{
if (isParamValid("material_input"))
{
std::vector<PostprocessorName> ppn = params.get<std::vector<PostprocessorName> >("material_input");
const unsigned int len = ppn.size();
for (unsigned int i = 0; i < len; ++i)
_material_input.push_back(&getPostprocessorValueByName(ppn[i]));
}
}
Real
CavityPressureUserObject::getValue(const std::string & quantity) const
{
Real value = 0;
if ("initial_moles" == quantity)
value = _n0;
else if ("cavity_pressure" == quantity)
value = _cavity_pressure;
else
mooseError("Unknown quantity in " + name());
return value;
}
void
CavityPressureUserObject::initialize()
{
if (!_initialized)
{
Real init_temp = _temperature;
if (_init_temp_given)
init_temp = _init_temp;
if (MooseUtils::absoluteFuzzyLessEqual(init_temp, 0.0))
mooseError("Cannot have initial temperature of zero when initializing cavity pressure. "
"Does the supplied Postprocessor for temperature execute at initial?");
_n0 = _initial_pressure * _volume / (_R * init_temp);
_start_time = _t - _dt;
const Real factor = _t >= _start_time + _startup_time ? 1.0 : (_t - _start_time) / _startup_time;
_cavity_pressure = factor * _initial_pressure;
_initialized = true;
}
}
void
CavityPressureUserObject::execute()
{
Real mat = 0;
for (unsigned int i = 0; i < _material_input.size(); ++i)
mat += *_material_input[i];
const Real pressure = (_n0 + mat) * _R * _temperature / _volume;
const Real factor = _t >= _start_time + _startup_time ? 1.0 : (_t - _start_time) / _startup_time;
_cavity_pressure = factor * pressure;
}
|
Add error message and avoid a divide by zero. Closes #8490.
|
Add error message and avoid a divide by zero. Closes #8490.
|
C++
|
lgpl-2.1
|
lindsayad/moose,liuwenf/moose,YaqiWang/moose,milljm/moose,milljm/moose,sapitts/moose,permcody/moose,sapitts/moose,YaqiWang/moose,harterj/moose,bwspenc/moose,yipenggao/moose,liuwenf/moose,permcody/moose,friedmud/moose,jessecarterMOOSE/moose,andrsd/moose,Chuban/moose,dschwen/moose,friedmud/moose,harterj/moose,stimpsonsg/moose,backmari/moose,Chuban/moose,andrsd/moose,lindsayad/moose,stimpsonsg/moose,jessecarterMOOSE/moose,nuclear-wizard/moose,YaqiWang/moose,nuclear-wizard/moose,stimpsonsg/moose,andrsd/moose,backmari/moose,yipenggao/moose,sapitts/moose,SudiptaBiswas/moose,idaholab/moose,SudiptaBiswas/moose,harterj/moose,bwspenc/moose,bwspenc/moose,SudiptaBiswas/moose,YaqiWang/moose,SudiptaBiswas/moose,dschwen/moose,jessecarterMOOSE/moose,harterj/moose,liuwenf/moose,idaholab/moose,friedmud/moose,idaholab/moose,stimpsonsg/moose,lindsayad/moose,laagesen/moose,laagesen/moose,sapitts/moose,liuwenf/moose,Chuban/moose,idaholab/moose,lindsayad/moose,jessecarterMOOSE/moose,milljm/moose,dschwen/moose,permcody/moose,Chuban/moose,dschwen/moose,harterj/moose,bwspenc/moose,liuwenf/moose,yipenggao/moose,backmari/moose,backmari/moose,yipenggao/moose,lindsayad/moose,jessecarterMOOSE/moose,idaholab/moose,laagesen/moose,milljm/moose,nuclear-wizard/moose,nuclear-wizard/moose,milljm/moose,andrsd/moose,dschwen/moose,laagesen/moose,andrsd/moose,SudiptaBiswas/moose,liuwenf/moose,sapitts/moose,permcody/moose,laagesen/moose,bwspenc/moose,friedmud/moose
|
d2a94ff1458cccff1ebd7ccad0bd72dc50a84330
|
JPetTaskLoader/JPetTaskLoader.cpp
|
JPetTaskLoader/JPetTaskLoader.cpp
|
/**
* @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 JPetTaskLoader.cpp
* @brief Class loads user task and execute in a loop of events
*/
#include "JPetTaskLoader.h"
#include <iostream>
#include "../JPetTask/JPetTask.h"
//ClassImp(JPetTaskLoader);
#include <boost/filesystem.hpp>
JPetTaskLoader::JPetTaskLoader(const char* in_file_type,
const char* out_file_type,
JPetTask* taskToExecute):
JPetTaskIO(),
fInFileType(in_file_type),
fOutFileType(out_file_type)
{
addSubTask(taskToExecute);
}
void JPetTaskLoader::init(const JPetOptions::Options& opts)
{
auto newOpts(opts);
auto inFile = newOpts.at("inputFile");
auto outFile = inFile;
inFile = generateProperNameFile(inFile, fInFileType);
outFile = generateProperNameFile(outFile, fOutFileType);
newOpts.at("inputFile") = inFile;
newOpts.at("inputFileType") = fInFileType;
newOpts.at("outputFile") = outFile;
newOpts.at("outputFileType") = fOutFileType;
setOptions(JPetOptions(newOpts));
//here we should call some function to parse options
std::string inputFilename(fOptions.getInputFile());
std::string outputPath(fOptions.getOutputPath());
auto outputFilename = outputPath + std::string(fOptions.getOutputFile());
createInputObjects(inputFilename.c_str());
createOutputObjects(outputFilename.c_str());
}
std::string JPetTaskLoader::generateProperNameFile(const std::string& srcFilename, const std::string& fileType) const
{
auto baseFileName = getBaseFilePath(srcFilename);
return baseFileName + "." + fileType + ".root";
}
std::string JPetTaskLoader::getBaseFilePath(const std::string& srcName) const
{
boost::filesystem::path p(srcName);
// the file name and path are treated separately not to strip dots from the path
std::string name = p.filename().native();
boost::filesystem::path dir = p.parent_path().native();
//strip the "extension" starting from the first dot in the file name
auto pos = name.find(".");
if ( pos != std::string::npos ) {
name.erase( pos );
}
boost::filesystem::path bare_name(name);
return (dir / bare_name).native();
}
JPetTaskLoader::~JPetTaskLoader()
{
}
|
/**
* @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 JPetTaskLoader.cpp
* @brief Class loads user task and execute in a loop of events
*/
#include "JPetTaskLoader.h"
#include <iostream>
#include "../JPetTask/JPetTask.h"
//ClassImp(JPetTaskLoader);
#include <boost/filesystem.hpp>
JPetTaskLoader::JPetTaskLoader(const char* in_file_type,
const char* out_file_type,
JPetTask* taskToExecute):
JPetTaskIO(),
fInFileType(in_file_type),
fOutFileType(out_file_type)
{
addSubTask(taskToExecute);
}
void JPetTaskLoader::init(const JPetOptions::Options& opts)
{
auto newOpts(opts);
auto inFile = newOpts.at("inputFile");
auto outFile = inFile; /// @todo This line is potentially dangerous if the output directory is different than the input one.
inFile = generateProperNameFile(inFile, fInFileType);
outFile = generateProperNameFile(outFile, fOutFileType);
newOpts.at("inputFile") = inFile;
newOpts.at("inputFileType") = fInFileType;
newOpts.at("outputFile") = outFile;
newOpts.at("outputFileType") = fOutFileType;
setOptions(JPetOptions(newOpts));
//here we should call some function to parse options
std::string inputFilename(fOptions.getInputFile());
std::string outputPath(fOptions.getOutputPath());
auto outputFilename = outputPath + std::string(fOptions.getOutputFile());
createInputObjects(inputFilename.c_str());
createOutputObjects(outputFilename.c_str());
}
std::string JPetTaskLoader::generateProperNameFile(const std::string& srcFilename, const std::string& fileType) const
{
auto baseFileName = getBaseFilePath(srcFilename);
if (!fileType.empty()) {
baseFileName = baseFileName + "." + fileType;
}
return baseFileName + ".root";
}
std::string JPetTaskLoader::getBaseFilePath(const std::string& srcName) const
{
boost::filesystem::path p(srcName);
// the file name and path are treated separately not to strip dots from the path
std::string name = p.filename().native();
boost::filesystem::path dir = p.parent_path().native();
//strip the "extension" starting from the first dot in the file name
auto pos = name.find(".");
if ( pos != std::string::npos ) {
name.erase( pos );
}
boost::filesystem::path bare_name(name);
return (dir / bare_name).native();
}
JPetTaskLoader::~JPetTaskLoader()
{
}
|
Correct the method for proper file name generation to handle empty input path case
|
Correct the method for proper file name generation to handle empty input
path case
|
C++
|
apache-2.0
|
wkrzemien/j-pet-framework,wkrzemien/j-pet-framework,wkrzemien/j-pet-framework,wkrzemien/j-pet-framework,wkrzemien/j-pet-framework
|
31753b50f3927ab45f8442cbe687bab9cee6d3bc
|
src/glsl/main.cpp
|
src/glsl/main.cpp
|
/*
* Copyright © 2008, 2009 Intel Corporation
*
* 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 (including the next
* paragraph) 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 <getopt.h>
#include "ast.h"
#include "glsl_parser_extras.h"
#include "glsl_parser.h"
#include "ir_optimization.h"
#include "ir_print_visitor.h"
#include "program.h"
#include "loop_analysis.h"
#include "standalone_scaffolding.h"
static void
initialize_context(struct gl_context *ctx, gl_api api)
{
initialize_context_to_defaults(ctx, api);
/* GLSL 1.30 isn't fully supported, but we need to advertise 1.30 so that
* the built-in functions for 1.30 can be built.
*/
ctx->Const.GLSLVersion = 130;
ctx->Const.MaxClipPlanes = 8;
ctx->Const.MaxDrawBuffers = 2;
/* More than the 1.10 minimum to appease parser tests taken from
* apps that (hopefully) already checked the number of coords.
*/
ctx->Const.MaxTextureCoordUnits = 4;
ctx->Driver.NewShader = _mesa_new_shader;
}
/* Returned string will have 'ctx' as its ralloc owner. */
static char *
load_text_file(void *ctx, const char *file_name)
{
char *text = NULL;
size_t size;
size_t total_read = 0;
FILE *fp = fopen(file_name, "rb");
if (!fp) {
return NULL;
}
fseek(fp, 0L, SEEK_END);
size = ftell(fp);
fseek(fp, 0L, SEEK_SET);
text = (char *) ralloc_size(ctx, size + 1);
if (text != NULL) {
do {
size_t bytes = fread(text + total_read,
1, size - total_read, fp);
if (bytes < size - total_read) {
free(text);
text = NULL;
break;
}
if (bytes == 0) {
break;
}
total_read += bytes;
} while (total_read < size);
text[total_read] = '\0';
}
fclose(fp);
return text;
}
int glsl_es = 0;
int dump_ast = 0;
int dump_hir = 0;
int dump_lir = 0;
int do_link = 0;
const struct option compiler_opts[] = {
{ "glsl-es", 0, &glsl_es, 1 },
{ "dump-ast", 0, &dump_ast, 1 },
{ "dump-hir", 0, &dump_hir, 1 },
{ "dump-lir", 0, &dump_lir, 1 },
{ "link", 0, &do_link, 1 },
{ NULL, 0, NULL, 0 }
};
/**
* \brief Print proper usage and exit with failure.
*/
void
usage_fail(const char *name)
{
const char *header =
"usage: %s [options] <file.vert | file.geom | file.frag>\n"
"\n"
"Possible options are:\n";
printf(header, name, name);
for (const struct option *o = compiler_opts; o->name != 0; ++o) {
printf(" --%s\n", o->name);
}
exit(EXIT_FAILURE);
}
void
compile_shader(struct gl_context *ctx, struct gl_shader *shader)
{
struct _mesa_glsl_parse_state *state =
new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);
const char *source = shader->Source;
state->error = preprocess(state, &source, &state->info_log,
state->extensions, ctx->API) != 0;
if (!state->error) {
_mesa_glsl_lexer_ctor(state, source);
_mesa_glsl_parse(state);
_mesa_glsl_lexer_dtor(state);
}
if (dump_ast) {
foreach_list_const(n, &state->translation_unit) {
ast_node *ast = exec_node_data(ast_node, n, link);
ast->print();
}
printf("\n\n");
}
shader->ir = new(shader) exec_list;
if (!state->error && !state->translation_unit.is_empty())
_mesa_ast_to_hir(shader->ir, state);
/* Print out the unoptimized IR. */
if (!state->error && dump_hir) {
validate_ir_tree(shader->ir);
_mesa_print_ir(shader->ir, state);
}
/* Optimization passes */
if (!state->error && !shader->ir->is_empty()) {
bool progress;
do {
progress = do_common_optimization(shader->ir, false, 32);
} while (progress);
validate_ir_tree(shader->ir);
}
/* Print out the resulting IR */
if (!state->error && dump_lir) {
_mesa_print_ir(shader->ir, state);
}
shader->symbols = state->symbols;
shader->CompileStatus = !state->error;
shader->Version = state->language_version;
memcpy(shader->builtins_to_link, state->builtins_to_link,
sizeof(shader->builtins_to_link[0]) * state->num_builtins_to_link);
shader->num_builtins_to_link = state->num_builtins_to_link;
if (shader->InfoLog)
ralloc_free(shader->InfoLog);
shader->InfoLog = state->info_log;
/* Retain any live IR, but trash the rest. */
reparent_ir(shader->ir, shader);
ralloc_free(state);
return;
}
int
main(int argc, char **argv)
{
int status = EXIT_SUCCESS;
struct gl_context local_ctx;
struct gl_context *ctx = &local_ctx;
int c;
int idx = 0;
while ((c = getopt_long(argc, argv, "", compiler_opts, &idx)) != -1)
/* empty */ ;
if (argc <= optind)
usage_fail(argv[0]);
initialize_context(ctx, (glsl_es) ? API_OPENGLES2 : API_OPENGL);
struct gl_shader_program *whole_program;
whole_program = rzalloc (NULL, struct gl_shader_program);
assert(whole_program != NULL);
whole_program->InfoLog = ralloc_strdup(whole_program, "");
for (/* empty */; argc > optind; optind++) {
whole_program->Shaders =
reralloc(whole_program, whole_program->Shaders,
struct gl_shader *, whole_program->NumShaders + 1);
assert(whole_program->Shaders != NULL);
struct gl_shader *shader = rzalloc(whole_program, gl_shader);
whole_program->Shaders[whole_program->NumShaders] = shader;
whole_program->NumShaders++;
const unsigned len = strlen(argv[optind]);
if (len < 6)
usage_fail(argv[0]);
const char *const ext = & argv[optind][len - 5];
if (strncmp(".vert", ext, 5) == 0)
shader->Type = GL_VERTEX_SHADER;
else if (strncmp(".geom", ext, 5) == 0)
shader->Type = GL_GEOMETRY_SHADER;
else if (strncmp(".frag", ext, 5) == 0)
shader->Type = GL_FRAGMENT_SHADER;
else
usage_fail(argv[0]);
shader->Source = load_text_file(whole_program, argv[optind]);
if (shader->Source == NULL) {
printf("File \"%s\" does not exist.\n", argv[optind]);
exit(EXIT_FAILURE);
}
compile_shader(ctx, shader);
if (!shader->CompileStatus) {
printf("Info log for %s:\n%s\n", argv[optind], shader->InfoLog);
status = EXIT_FAILURE;
break;
}
}
if ((status == EXIT_SUCCESS) && do_link) {
link_shaders(ctx, whole_program);
status = (whole_program->LinkStatus) ? EXIT_SUCCESS : EXIT_FAILURE;
if (strlen(whole_program->InfoLog) > 0)
printf("Info log for linking:\n%s\n", whole_program->InfoLog);
}
for (unsigned i = 0; i < MESA_SHADER_TYPES; i++)
ralloc_free(whole_program->_LinkedShaders[i]);
ralloc_free(whole_program);
_mesa_glsl_release_types();
_mesa_glsl_release_functions();
return status;
}
|
/*
* Copyright © 2008, 2009 Intel Corporation
*
* 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 (including the next
* paragraph) 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 <getopt.h>
#include "ast.h"
#include "glsl_parser_extras.h"
#include "ir_optimization.h"
#include "ir_print_visitor.h"
#include "program.h"
#include "loop_analysis.h"
#include "standalone_scaffolding.h"
static void
initialize_context(struct gl_context *ctx, gl_api api)
{
initialize_context_to_defaults(ctx, api);
/* GLSL 1.30 isn't fully supported, but we need to advertise 1.30 so that
* the built-in functions for 1.30 can be built.
*/
ctx->Const.GLSLVersion = 130;
ctx->Const.MaxClipPlanes = 8;
ctx->Const.MaxDrawBuffers = 2;
/* More than the 1.10 minimum to appease parser tests taken from
* apps that (hopefully) already checked the number of coords.
*/
ctx->Const.MaxTextureCoordUnits = 4;
ctx->Driver.NewShader = _mesa_new_shader;
}
/* Returned string will have 'ctx' as its ralloc owner. */
static char *
load_text_file(void *ctx, const char *file_name)
{
char *text = NULL;
size_t size;
size_t total_read = 0;
FILE *fp = fopen(file_name, "rb");
if (!fp) {
return NULL;
}
fseek(fp, 0L, SEEK_END);
size = ftell(fp);
fseek(fp, 0L, SEEK_SET);
text = (char *) ralloc_size(ctx, size + 1);
if (text != NULL) {
do {
size_t bytes = fread(text + total_read,
1, size - total_read, fp);
if (bytes < size - total_read) {
free(text);
text = NULL;
break;
}
if (bytes == 0) {
break;
}
total_read += bytes;
} while (total_read < size);
text[total_read] = '\0';
}
fclose(fp);
return text;
}
int glsl_es = 0;
int dump_ast = 0;
int dump_hir = 0;
int dump_lir = 0;
int do_link = 0;
const struct option compiler_opts[] = {
{ "glsl-es", 0, &glsl_es, 1 },
{ "dump-ast", 0, &dump_ast, 1 },
{ "dump-hir", 0, &dump_hir, 1 },
{ "dump-lir", 0, &dump_lir, 1 },
{ "link", 0, &do_link, 1 },
{ NULL, 0, NULL, 0 }
};
/**
* \brief Print proper usage and exit with failure.
*/
void
usage_fail(const char *name)
{
const char *header =
"usage: %s [options] <file.vert | file.geom | file.frag>\n"
"\n"
"Possible options are:\n";
printf(header, name, name);
for (const struct option *o = compiler_opts; o->name != 0; ++o) {
printf(" --%s\n", o->name);
}
exit(EXIT_FAILURE);
}
void
compile_shader(struct gl_context *ctx, struct gl_shader *shader)
{
struct _mesa_glsl_parse_state *state =
new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);
const char *source = shader->Source;
state->error = preprocess(state, &source, &state->info_log,
state->extensions, ctx->API) != 0;
if (!state->error) {
_mesa_glsl_lexer_ctor(state, source);
_mesa_glsl_parse(state);
_mesa_glsl_lexer_dtor(state);
}
if (dump_ast) {
foreach_list_const(n, &state->translation_unit) {
ast_node *ast = exec_node_data(ast_node, n, link);
ast->print();
}
printf("\n\n");
}
shader->ir = new(shader) exec_list;
if (!state->error && !state->translation_unit.is_empty())
_mesa_ast_to_hir(shader->ir, state);
/* Print out the unoptimized IR. */
if (!state->error && dump_hir) {
validate_ir_tree(shader->ir);
_mesa_print_ir(shader->ir, state);
}
/* Optimization passes */
if (!state->error && !shader->ir->is_empty()) {
bool progress;
do {
progress = do_common_optimization(shader->ir, false, 32);
} while (progress);
validate_ir_tree(shader->ir);
}
/* Print out the resulting IR */
if (!state->error && dump_lir) {
_mesa_print_ir(shader->ir, state);
}
shader->symbols = state->symbols;
shader->CompileStatus = !state->error;
shader->Version = state->language_version;
memcpy(shader->builtins_to_link, state->builtins_to_link,
sizeof(shader->builtins_to_link[0]) * state->num_builtins_to_link);
shader->num_builtins_to_link = state->num_builtins_to_link;
if (shader->InfoLog)
ralloc_free(shader->InfoLog);
shader->InfoLog = state->info_log;
/* Retain any live IR, but trash the rest. */
reparent_ir(shader->ir, shader);
ralloc_free(state);
return;
}
int
main(int argc, char **argv)
{
int status = EXIT_SUCCESS;
struct gl_context local_ctx;
struct gl_context *ctx = &local_ctx;
int c;
int idx = 0;
while ((c = getopt_long(argc, argv, "", compiler_opts, &idx)) != -1)
/* empty */ ;
if (argc <= optind)
usage_fail(argv[0]);
initialize_context(ctx, (glsl_es) ? API_OPENGLES2 : API_OPENGL);
struct gl_shader_program *whole_program;
whole_program = rzalloc (NULL, struct gl_shader_program);
assert(whole_program != NULL);
whole_program->InfoLog = ralloc_strdup(whole_program, "");
for (/* empty */; argc > optind; optind++) {
whole_program->Shaders =
reralloc(whole_program, whole_program->Shaders,
struct gl_shader *, whole_program->NumShaders + 1);
assert(whole_program->Shaders != NULL);
struct gl_shader *shader = rzalloc(whole_program, gl_shader);
whole_program->Shaders[whole_program->NumShaders] = shader;
whole_program->NumShaders++;
const unsigned len = strlen(argv[optind]);
if (len < 6)
usage_fail(argv[0]);
const char *const ext = & argv[optind][len - 5];
if (strncmp(".vert", ext, 5) == 0)
shader->Type = GL_VERTEX_SHADER;
else if (strncmp(".geom", ext, 5) == 0)
shader->Type = GL_GEOMETRY_SHADER;
else if (strncmp(".frag", ext, 5) == 0)
shader->Type = GL_FRAGMENT_SHADER;
else
usage_fail(argv[0]);
shader->Source = load_text_file(whole_program, argv[optind]);
if (shader->Source == NULL) {
printf("File \"%s\" does not exist.\n", argv[optind]);
exit(EXIT_FAILURE);
}
compile_shader(ctx, shader);
if (!shader->CompileStatus) {
printf("Info log for %s:\n%s\n", argv[optind], shader->InfoLog);
status = EXIT_FAILURE;
break;
}
}
if ((status == EXIT_SUCCESS) && do_link) {
link_shaders(ctx, whole_program);
status = (whole_program->LinkStatus) ? EXIT_SUCCESS : EXIT_FAILURE;
if (strlen(whole_program->InfoLog) > 0)
printf("Info log for linking:\n%s\n", whole_program->InfoLog);
}
for (unsigned i = 0; i < MESA_SHADER_TYPES; i++)
ralloc_free(whole_program->_LinkedShaders[i]);
ralloc_free(whole_program);
_mesa_glsl_release_types();
_mesa_glsl_release_functions();
return status;
}
|
remove an unnecessary header include
|
glsl: remove an unnecessary header include
Reviewed-by: Brian Paul <[email protected]>
Reviewed-by: Ian Romanick <[email protected]>
Reviewed-by: Chad Versace <[email protected]>
|
C++
|
mit
|
djreep81/glsl-optimizer,tokyovigilante/glsl-optimizer,zeux/glsl-optimizer,dellis1972/glsl-optimizer,djreep81/glsl-optimizer,zeux/glsl-optimizer,bkaradzic/glsl-optimizer,mapbox/glsl-optimizer,wolf96/glsl-optimizer,jbarczak/glsl-optimizer,tokyovigilante/glsl-optimizer,tokyovigilante/glsl-optimizer,metora/MesaGLSLCompiler,djreep81/glsl-optimizer,mapbox/glsl-optimizer,jbarczak/glsl-optimizer,mapbox/glsl-optimizer,dellis1972/glsl-optimizer,zeux/glsl-optimizer,zeux/glsl-optimizer,benaadams/glsl-optimizer,mcanthony/glsl-optimizer,mcanthony/glsl-optimizer,jbarczak/glsl-optimizer,djreep81/glsl-optimizer,benaadams/glsl-optimizer,dellis1972/glsl-optimizer,bkaradzic/glsl-optimizer,tokyovigilante/glsl-optimizer,wolf96/glsl-optimizer,benaadams/glsl-optimizer,mcanthony/glsl-optimizer,jbarczak/glsl-optimizer,wolf96/glsl-optimizer,zz85/glsl-optimizer,zz85/glsl-optimizer,zz85/glsl-optimizer,wolf96/glsl-optimizer,bkaradzic/glsl-optimizer,mapbox/glsl-optimizer,metora/MesaGLSLCompiler,zeux/glsl-optimizer,benaadams/glsl-optimizer,bkaradzic/glsl-optimizer,jbarczak/glsl-optimizer,zz85/glsl-optimizer,dellis1972/glsl-optimizer,benaadams/glsl-optimizer,wolf96/glsl-optimizer,mapbox/glsl-optimizer,benaadams/glsl-optimizer,zz85/glsl-optimizer,zz85/glsl-optimizer,bkaradzic/glsl-optimizer,dellis1972/glsl-optimizer,tokyovigilante/glsl-optimizer,mcanthony/glsl-optimizer,mcanthony/glsl-optimizer,djreep81/glsl-optimizer,metora/MesaGLSLCompiler
|
45f96a3a6a988712f74dabdc9333c391f8a9a937
|
src/lb/Config.hxx
|
src/lb/Config.hxx
|
/*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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
* FOUNDATION 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 "lb/ListenerConfig.hxx"
#include "lb/GotoConfig.hxx"
#include "lb/ClusterConfig.hxx"
#include "lb/MonitorConfig.hxx"
#include "access_log/Config.hxx"
#include "net/SocketConfig.hxx"
#include "certdb/Config.hxx"
#include <map>
#include <list>
#include <string>
#include <memory>
struct LbHttpCheckConfig;
struct LbControlConfig : SocketConfig {
LbControlConfig() noexcept {
pass_cred = true;
}
};
struct LbCertDatabaseConfig : CertDatabaseConfig {
std::string name;
/**
* List of PEM path names containing certificator authorities
* we're going to use to build the certificate chain.
*/
std::list<std::string> ca_certs;
explicit LbCertDatabaseConfig(const char *_name) noexcept
:name(_name) {}
};
struct LbConfig {
AccessLogConfig access_log;
std::list<LbControlConfig> controls;
std::map<std::string, LbCertDatabaseConfig> cert_dbs;
std::map<std::string, LbMonitorConfig> monitors;
std::map<std::string, LbNodeConfig> nodes;
std::map<std::string, LbClusterConfig> clusters;
std::map<std::string, LbBranchConfig> branches;
std::map<std::string, LbLuaHandlerConfig> lua_handlers;
std::map<std::string, LbTranslationHandlerConfig> translation_handlers;
std::list<LbListenerConfig> listeners;
std::unique_ptr<LbHttpCheckConfig> global_http_check;
LbConfig() noexcept;
~LbConfig() noexcept;
template<typename T>
[[gnu::pure]]
const LbMonitorConfig *FindMonitor(T &&t) const noexcept {
const auto i = monitors.find(std::forward<T>(t));
return i != monitors.end()
? &i->second
: nullptr;
}
template<typename T>
[[gnu::pure]]
const LbCertDatabaseConfig *FindCertDb(T &&t) const noexcept {
const auto i = cert_dbs.find(std::forward<T>(t));
return i != cert_dbs.end()
? &i->second
: nullptr;
}
template<typename T>
[[gnu::pure]]
const LbNodeConfig *FindNode(T &&t) const noexcept {
const auto i = nodes.find(std::forward<T>(t));
return i != nodes.end()
? &i->second
: nullptr;
}
template<typename T>
[[gnu::pure]]
const LbClusterConfig *FindCluster(T &&t) const noexcept {
const auto i = clusters.find(std::forward<T>(t));
return i != clusters.end()
? &i->second
: nullptr;
}
template<typename T>
[[gnu::pure]]
LbGotoConfig FindGoto(T &&t) const noexcept {
const auto *cluster = FindCluster(t);
if (cluster != nullptr)
return LbGotoConfig(*cluster);
const auto *branch = FindBranch(t);
if (branch != nullptr)
return LbGotoConfig(*branch);
const auto *lua = FindLuaHandler(t);
if (lua != nullptr)
return LbGotoConfig(*lua);
const auto *translation = FindTranslationHandler(t);
if (translation != nullptr)
return LbGotoConfig(*translation);
return {};
}
template<typename T>
[[gnu::pure]]
const LbBranchConfig *FindBranch(T &&t) const noexcept {
const auto i = branches.find(std::forward<T>(t));
return i != branches.end()
? &i->second
: nullptr;
}
template<typename T>
[[gnu::pure]]
const LbLuaHandlerConfig *FindLuaHandler(T &&t) const noexcept {
const auto i = lua_handlers.find(std::forward<T>(t));
return i != lua_handlers.end()
? &i->second
: nullptr;
}
template<typename T>
[[gnu::pure]]
const LbTranslationHandlerConfig *FindTranslationHandler(T &&t) const noexcept {
const auto i = translation_handlers.find(std::forward<T>(t));
return i != translation_handlers.end()
? &i->second
: nullptr;
}
template<typename T>
[[gnu::pure]]
const LbListenerConfig *FindListener(T &&t) const noexcept {
for (const auto &i : listeners)
if (i.name == t)
return &i;
return nullptr;
}
bool HasCertDatabase() const noexcept {
for (const auto &i : listeners)
if (i.cert_db != nullptr)
return true;
return false;
}
[[gnu::pure]]
bool HasZeroConf() const noexcept {
#ifdef HAVE_AVAHI
for (const auto &i : listeners)
if (i.HasZeroConf())
return true;
#endif
return false;
}
[[gnu::pure]]
bool HasTransparentSource() const noexcept {
for (const auto &i : clusters)
if (i.second.transparent_source)
return true;
return false;
}
};
/**
* Load and parse the specified configuration file. Throws an
* exception on error.
*/
void
LoadConfigFile(LbConfig &config, const char *path);
|
/*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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
* FOUNDATION 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 "ListenerConfig.hxx"
#include "GotoConfig.hxx"
#include "ClusterConfig.hxx"
#include "MonitorConfig.hxx"
#include "access_log/Config.hxx"
#include "net/SocketConfig.hxx"
#include "certdb/Config.hxx"
#include <map>
#include <list>
#include <string>
#include <memory>
struct LbHttpCheckConfig;
struct LbControlConfig : SocketConfig {
LbControlConfig() noexcept {
pass_cred = true;
}
};
struct LbCertDatabaseConfig : CertDatabaseConfig {
std::string name;
/**
* List of PEM path names containing certificator authorities
* we're going to use to build the certificate chain.
*/
std::list<std::string> ca_certs;
explicit LbCertDatabaseConfig(const char *_name) noexcept
:name(_name) {}
};
struct LbConfig {
AccessLogConfig access_log;
std::list<LbControlConfig> controls;
std::map<std::string, LbCertDatabaseConfig> cert_dbs;
std::map<std::string, LbMonitorConfig> monitors;
std::map<std::string, LbNodeConfig> nodes;
std::map<std::string, LbClusterConfig> clusters;
std::map<std::string, LbBranchConfig> branches;
std::map<std::string, LbLuaHandlerConfig> lua_handlers;
std::map<std::string, LbTranslationHandlerConfig> translation_handlers;
std::list<LbListenerConfig> listeners;
std::unique_ptr<LbHttpCheckConfig> global_http_check;
LbConfig() noexcept;
~LbConfig() noexcept;
template<typename T>
[[gnu::pure]]
const LbMonitorConfig *FindMonitor(T &&t) const noexcept {
const auto i = monitors.find(std::forward<T>(t));
return i != monitors.end()
? &i->second
: nullptr;
}
template<typename T>
[[gnu::pure]]
const LbCertDatabaseConfig *FindCertDb(T &&t) const noexcept {
const auto i = cert_dbs.find(std::forward<T>(t));
return i != cert_dbs.end()
? &i->second
: nullptr;
}
template<typename T>
[[gnu::pure]]
const LbNodeConfig *FindNode(T &&t) const noexcept {
const auto i = nodes.find(std::forward<T>(t));
return i != nodes.end()
? &i->second
: nullptr;
}
template<typename T>
[[gnu::pure]]
const LbClusterConfig *FindCluster(T &&t) const noexcept {
const auto i = clusters.find(std::forward<T>(t));
return i != clusters.end()
? &i->second
: nullptr;
}
template<typename T>
[[gnu::pure]]
LbGotoConfig FindGoto(T &&t) const noexcept {
const auto *cluster = FindCluster(t);
if (cluster != nullptr)
return LbGotoConfig(*cluster);
const auto *branch = FindBranch(t);
if (branch != nullptr)
return LbGotoConfig(*branch);
const auto *lua = FindLuaHandler(t);
if (lua != nullptr)
return LbGotoConfig(*lua);
const auto *translation = FindTranslationHandler(t);
if (translation != nullptr)
return LbGotoConfig(*translation);
return {};
}
template<typename T>
[[gnu::pure]]
const LbBranchConfig *FindBranch(T &&t) const noexcept {
const auto i = branches.find(std::forward<T>(t));
return i != branches.end()
? &i->second
: nullptr;
}
template<typename T>
[[gnu::pure]]
const LbLuaHandlerConfig *FindLuaHandler(T &&t) const noexcept {
const auto i = lua_handlers.find(std::forward<T>(t));
return i != lua_handlers.end()
? &i->second
: nullptr;
}
template<typename T>
[[gnu::pure]]
const LbTranslationHandlerConfig *FindTranslationHandler(T &&t) const noexcept {
const auto i = translation_handlers.find(std::forward<T>(t));
return i != translation_handlers.end()
? &i->second
: nullptr;
}
template<typename T>
[[gnu::pure]]
const LbListenerConfig *FindListener(T &&t) const noexcept {
for (const auto &i : listeners)
if (i.name == t)
return &i;
return nullptr;
}
bool HasCertDatabase() const noexcept {
for (const auto &i : listeners)
if (i.cert_db != nullptr)
return true;
return false;
}
[[gnu::pure]]
bool HasZeroConf() const noexcept {
#ifdef HAVE_AVAHI
for (const auto &i : listeners)
if (i.HasZeroConf())
return true;
#endif
return false;
}
[[gnu::pure]]
bool HasTransparentSource() const noexcept {
for (const auto &i : clusters)
if (i.second.transparent_source)
return true;
return false;
}
};
/**
* Load and parse the specified configuration file. Throws an
* exception on error.
*/
void
LoadConfigFile(LbConfig &config, const char *path);
|
include cleanup
|
lb/Config: include cleanup
|
C++
|
bsd-2-clause
|
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
|
1d0ccdfd7be184036bf4920b14d4341d269487d6
|
moveit_ros/warehouse/warehouse/src/import_from_text.cpp
|
moveit_ros/warehouse/warehouse/src/import_from_text.cpp
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* 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 Willow Garage 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.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/warehouse/planning_scene_storage.h>
#include <moveit/warehouse/constraints_storage.h>
#include <moveit/warehouse/state_storage.h>
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>
#include <moveit/kinematic_constraints/utils.h>
#include <moveit/robot_state/conversions.h>
#include <tf2_eigen/tf2_eigen.h>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <ros/ros.h>
static const std::string ROBOT_DESCRIPTION = "robot_description";
void parseStart(std::istream& in, planning_scene_monitor::PlanningSceneMonitor* psm,
moveit_warehouse::RobotStateStorage* rs)
{
int count;
in >> count;
if (in.good() && !in.eof())
{
for (int i = 0; i < count; ++i)
{
std::map<std::string, double> v;
std::string name;
in >> name;
if (in.good() && !in.eof())
{
std::string joint;
std::string marker;
double value;
in >> joint;
while (joint != "." && in.good() && !in.eof())
{
in >> marker;
if (marker != "=")
joint = ".";
else
in >> value;
v[joint] = value;
if (joint != ".")
in >> joint;
}
}
if (!v.empty())
{
robot_state::RobotState st = psm->getPlanningScene()->getCurrentState();
st.setVariablePositions(v);
moveit_msgs::RobotState msg;
robot_state::robotStateToRobotStateMsg(st, msg);
ROS_INFO("Parsed start state '%s'", name.c_str());
rs->addRobotState(msg, name);
}
}
}
}
void parseLinkConstraint(std::istream& in, planning_scene_monitor::PlanningSceneMonitor* psm,
moveit_warehouse::ConstraintsStorage* cs)
{
Eigen::Translation3d pos(Eigen::Vector3d::Zero());
Eigen::Quaterniond rot(Eigen::Quaterniond::Identity());
bool have_position = false;
bool have_orientation = false;
std::string name;
std::getline(in, name);
// The link name is optional, in which case there would be a blank line
std::string link_name;
std::getline(in, link_name);
std::string type;
in >> type;
while (type != "." && in.good() && !in.eof())
{
if (type == "xyz")
{
have_position = true;
double x, y, z;
in >> x >> y >> z;
pos = Eigen::Translation3d(x, y, z);
}
else if (type == "rpy")
{
have_orientation = true;
double r, p, y;
in >> r >> p >> y;
rot = Eigen::Quaterniond(Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX()) *
Eigen::AngleAxisd(p, Eigen::Vector3d::UnitY()) *
Eigen::AngleAxisd(y, Eigen::Vector3d::UnitZ()));
}
else
ROS_ERROR("Unknown link constraint element: '%s'", type.c_str());
in >> type;
}
// Convert to getLine method by eating line break
std::string end_link;
std::getline(in, end_link);
if (have_position && have_orientation)
{
geometry_msgs::PoseStamped pose;
pose.pose = tf2::toMsg(pos * rot);
pose.header.frame_id = psm->getRobotModel()->getModelFrame();
moveit_msgs::Constraints constr = kinematic_constraints::constructGoalConstraints(link_name, pose);
constr.name = name;
ROS_INFO("Parsed link constraint '%s'", name.c_str());
cs->addConstraints(constr);
}
}
void parseGoal(std::istream& in, planning_scene_monitor::PlanningSceneMonitor* psm,
moveit_warehouse::ConstraintsStorage* cs)
{
int count;
in >> count;
// Convert to getLine method from here-on, so eat the line break.
std::string end_link;
std::getline(in, end_link);
if (in.good() && !in.eof())
{
for (int i = 0; i < count; ++i)
{
std::string type;
std::getline(in, type);
if (in.good() && !in.eof())
{
if (type == "link_constraint")
parseLinkConstraint(in, psm, cs);
else
ROS_ERROR("Unknown goal type: '%s'", type.c_str());
}
}
}
}
void parseQueries(std::istream& in, planning_scene_monitor::PlanningSceneMonitor* psm,
moveit_warehouse::RobotStateStorage* rs, moveit_warehouse::ConstraintsStorage* cs)
{
std::string scene_name;
in >> scene_name;
while (in.good() && !in.eof())
{
std::string type;
in >> type;
if (in.good() && !in.eof())
{
if (type == "start")
parseStart(in, psm, rs);
else if (type == "goal")
parseGoal(in, psm, cs);
else
ROS_ERROR("Unknown query type: '%s'", type.c_str());
}
}
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "import_from_text_to_warehouse", ros::init_options::AnonymousName);
boost::program_options::options_description desc;
desc.add_options()("help", "Show help message")("queries", boost::program_options::value<std::string>(),
"Name of file containing motion planning queries.")(
"scene", boost::program_options::value<std::string>(), "Name of file containing motion planning scene.")(
"host", boost::program_options::value<std::string>(),
"Host for the DB.")("port", boost::program_options::value<std::size_t>(), "Port for the DB.");
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
boost::program_options::notify(vm);
if (vm.count("help") || argc == 1) // show help if no parameters passed
{
std::cout << desc << std::endl;
return 1;
}
// Set up db
warehouse_ros::DatabaseConnection::Ptr conn = moveit_warehouse::loadDatabase();
if (vm.count("host") && vm.count("port"))
conn->setParams(vm["host"].as<std::string>(), vm["port"].as<std::size_t>());
if (!conn->connect())
return 1;
ros::AsyncSpinner spinner(1);
spinner.start();
ros::NodeHandle nh;
planning_scene_monitor::PlanningSceneMonitor psm(ROBOT_DESCRIPTION);
if (!psm.getPlanningScene())
{
ROS_ERROR("Unable to initialize PlanningSceneMonitor");
return 1;
}
moveit_warehouse::PlanningSceneStorage pss(conn);
moveit_warehouse::ConstraintsStorage cs(conn);
moveit_warehouse::RobotStateStorage rs(conn);
if (vm.count("scene"))
{
std::ifstream fin(vm["scene"].as<std::string>().c_str());
psm.getPlanningScene()->loadGeometryFromStream(fin);
fin.close();
moveit_msgs::PlanningScene psmsg;
psm.getPlanningScene()->getPlanningSceneMsg(psmsg);
pss.addPlanningScene(psmsg);
}
if (vm.count("queries"))
{
std::ifstream fin(vm["queries"].as<std::string>().c_str());
if (fin.good() && !fin.eof())
parseQueries(fin, &psm, &rs, &cs);
fin.close();
}
return 0;
}
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* 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 Willow Garage 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.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/warehouse/planning_scene_storage.h>
#include <moveit/warehouse/constraints_storage.h>
#include <moveit/warehouse/state_storage.h>
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>
#include <moveit/kinematic_constraints/utils.h>
#include <moveit/robot_state/conversions.h>
#include <tf2_eigen/tf2_eigen.h>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <ros/ros.h>
static const std::string ROBOT_DESCRIPTION = "robot_description";
void parseStart(std::istream& in, planning_scene_monitor::PlanningSceneMonitor* psm,
moveit_warehouse::RobotStateStorage* rs)
{
int count;
in >> count;
if (in.good() && !in.eof())
{
for (int i = 0; i < count; ++i)
{
std::map<std::string, double> v;
std::string name;
in >> name;
if (in.good() && !in.eof())
{
std::string joint;
std::string marker;
double value;
in >> joint;
while (joint != "." && in.good() && !in.eof())
{
in >> marker;
if (marker != "=")
joint = ".";
else
{
in >> value;
v[joint] = value;
}
if (joint != ".")
in >> joint;
}
}
if (!v.empty())
{
robot_state::RobotState st = psm->getPlanningScene()->getCurrentState();
st.setVariablePositions(v);
moveit_msgs::RobotState msg;
robot_state::robotStateToRobotStateMsg(st, msg);
ROS_INFO("Parsed start state '%s'", name.c_str());
rs->addRobotState(msg, name);
}
}
}
}
void parseLinkConstraint(std::istream& in, planning_scene_monitor::PlanningSceneMonitor* psm,
moveit_warehouse::ConstraintsStorage* cs)
{
Eigen::Translation3d pos(Eigen::Vector3d::Zero());
Eigen::Quaterniond rot(Eigen::Quaterniond::Identity());
bool have_position = false;
bool have_orientation = false;
std::string name;
std::getline(in, name);
// The link name is optional, in which case there would be a blank line
std::string link_name;
std::getline(in, link_name);
std::string type;
in >> type;
while (type != "." && in.good() && !in.eof())
{
if (type == "xyz")
{
have_position = true;
double x, y, z;
in >> x >> y >> z;
pos = Eigen::Translation3d(x, y, z);
}
else if (type == "rpy")
{
have_orientation = true;
double r, p, y;
in >> r >> p >> y;
rot = Eigen::Quaterniond(Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX()) *
Eigen::AngleAxisd(p, Eigen::Vector3d::UnitY()) *
Eigen::AngleAxisd(y, Eigen::Vector3d::UnitZ()));
}
else
ROS_ERROR("Unknown link constraint element: '%s'", type.c_str());
in >> type;
}
// Convert to getLine method by eating line break
std::string end_link;
std::getline(in, end_link);
if (have_position && have_orientation)
{
geometry_msgs::PoseStamped pose;
pose.pose = tf2::toMsg(pos * rot);
pose.header.frame_id = psm->getRobotModel()->getModelFrame();
moveit_msgs::Constraints constr = kinematic_constraints::constructGoalConstraints(link_name, pose);
constr.name = name;
ROS_INFO("Parsed link constraint '%s'", name.c_str());
cs->addConstraints(constr);
}
}
void parseGoal(std::istream& in, planning_scene_monitor::PlanningSceneMonitor* psm,
moveit_warehouse::ConstraintsStorage* cs)
{
int count;
in >> count;
// Convert to getLine method from here-on, so eat the line break.
std::string end_link;
std::getline(in, end_link);
if (in.good() && !in.eof())
{
for (int i = 0; i < count; ++i)
{
std::string type;
std::getline(in, type);
if (in.good() && !in.eof())
{
if (type == "link_constraint")
parseLinkConstraint(in, psm, cs);
else
ROS_ERROR("Unknown goal type: '%s'", type.c_str());
}
}
}
}
void parseQueries(std::istream& in, planning_scene_monitor::PlanningSceneMonitor* psm,
moveit_warehouse::RobotStateStorage* rs, moveit_warehouse::ConstraintsStorage* cs)
{
std::string scene_name;
in >> scene_name;
while (in.good() && !in.eof())
{
std::string type;
in >> type;
if (in.good() && !in.eof())
{
if (type == "start")
parseStart(in, psm, rs);
else if (type == "goal")
parseGoal(in, psm, cs);
else
ROS_ERROR("Unknown query type: '%s'", type.c_str());
}
}
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "import_from_text_to_warehouse", ros::init_options::AnonymousName);
boost::program_options::options_description desc;
desc.add_options()("help", "Show help message")("queries", boost::program_options::value<std::string>(),
"Name of file containing motion planning queries.")(
"scene", boost::program_options::value<std::string>(), "Name of file containing motion planning scene.")(
"host", boost::program_options::value<std::string>(),
"Host for the DB.")("port", boost::program_options::value<std::size_t>(), "Port for the DB.");
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
boost::program_options::notify(vm);
if (vm.count("help") || argc == 1) // show help if no parameters passed
{
std::cout << desc << std::endl;
return 1;
}
// Set up db
warehouse_ros::DatabaseConnection::Ptr conn = moveit_warehouse::loadDatabase();
if (vm.count("host") && vm.count("port"))
conn->setParams(vm["host"].as<std::string>(), vm["port"].as<std::size_t>());
if (!conn->connect())
return 1;
ros::AsyncSpinner spinner(1);
spinner.start();
ros::NodeHandle nh;
planning_scene_monitor::PlanningSceneMonitor psm(ROBOT_DESCRIPTION);
if (!psm.getPlanningScene())
{
ROS_ERROR("Unable to initialize PlanningSceneMonitor");
return 1;
}
moveit_warehouse::PlanningSceneStorage pss(conn);
moveit_warehouse::ConstraintsStorage cs(conn);
moveit_warehouse::RobotStateStorage rs(conn);
if (vm.count("scene"))
{
std::ifstream fin(vm["scene"].as<std::string>().c_str());
psm.getPlanningScene()->loadGeometryFromStream(fin);
fin.close();
moveit_msgs::PlanningScene psmsg;
psm.getPlanningScene()->getPlanningSceneMsg(psmsg);
pss.addPlanningScene(psmsg);
}
if (vm.count("queries"))
{
std::ifstream fin(vm["queries"].as<std::string>().c_str());
if (fin.good() && !fin.eof())
parseQueries(fin, &psm, &rs, &cs);
fin.close();
}
return 0;
}
|
Add the conditional branch scope when the condition is false in inport_from_text.cpp. (#1818)
|
Add the conditional branch scope when the condition is false in inport_from_text.cpp. (#1818)
|
C++
|
bsd-3-clause
|
ros-planning/moveit,ros-planning/moveit,ros-planning/moveit,ros-planning/moveit,ros-planning/moveit
|
e716b602e8066ede297b5e0be4d23720c26cdcf9
|
lib/tsan/rtl/tsan_rtl_thread.cc
|
lib/tsan/rtl/tsan_rtl_thread.cc
|
//===-- tsan_rtl_thread.cc ------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer (TSan), a race detector.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_placement_new.h"
#include "tsan_rtl.h"
#include "tsan_mman.h"
#include "tsan_platform.h"
#include "tsan_report.h"
#include "tsan_sync.h"
namespace __tsan {
const int kThreadQuarantineSize = 16;
static void MaybeReportThreadLeak(ThreadContext *tctx) {
if (tctx->detached)
return;
if (tctx->status != ThreadStatusCreated
&& tctx->status != ThreadStatusRunning
&& tctx->status != ThreadStatusFinished)
return;
ScopedReport rep(ReportTypeThreadLeak);
rep.AddThread(tctx);
OutputReport(rep);
}
void ThreadFinalize(ThreadState *thr) {
CHECK_GT(thr->in_rtl, 0);
if (!flags()->report_thread_leaks)
return;
Context *ctx = CTX();
Lock l(&ctx->thread_mtx);
for (unsigned i = 0; i < kMaxTid; i++) {
ThreadContext *tctx = ctx->threads[i];
if (tctx == 0)
continue;
MaybeReportThreadLeak(tctx);
}
}
static void ThreadDead(ThreadState *thr, ThreadContext *tctx) {
Context *ctx = CTX();
CHECK_GT(thr->in_rtl, 0);
CHECK(tctx->status == ThreadStatusRunning
|| tctx->status == ThreadStatusFinished);
DPrintf("#%d: ThreadDead uid=%zu\n", thr->tid, tctx->user_id);
tctx->status = ThreadStatusDead;
tctx->user_id = 0;
tctx->sync.Reset();
// Put to dead list.
tctx->dead_next = 0;
if (ctx->dead_list_size == 0)
ctx->dead_list_head = tctx;
else
ctx->dead_list_tail->dead_next = tctx;
ctx->dead_list_tail = tctx;
ctx->dead_list_size++;
}
int ThreadCreate(ThreadState *thr, uptr pc, uptr uid, bool detached) {
CHECK_GT(thr->in_rtl, 0);
Context *ctx = CTX();
Lock l(&ctx->thread_mtx);
StatInc(thr, StatThreadCreate);
int tid = -1;
ThreadContext *tctx = 0;
if (ctx->dead_list_size > kThreadQuarantineSize
|| ctx->thread_seq >= kMaxTid) {
if (ctx->dead_list_size == 0) {
TsanPrintf("ThreadSanitizer: %d thread limit exceeded. Dying.\n",
kMaxTid);
Die();
}
StatInc(thr, StatThreadReuse);
tctx = ctx->dead_list_head;
ctx->dead_list_head = tctx->dead_next;
ctx->dead_list_size--;
if (ctx->dead_list_size == 0) {
CHECK_EQ(tctx->dead_next, 0);
ctx->dead_list_head = 0;
}
CHECK_EQ(tctx->status, ThreadStatusDead);
tctx->status = ThreadStatusInvalid;
tctx->reuse_count++;
tctx->sync.Reset();
tid = tctx->tid;
DestroyAndFree(tctx->dead_info);
} else {
StatInc(thr, StatThreadMaxTid);
tid = ctx->thread_seq++;
void *mem = internal_alloc(MBlockThreadContex, sizeof(ThreadContext));
tctx = new(mem) ThreadContext(tid);
ctx->threads[tid] = tctx;
}
CHECK_NE(tctx, 0);
CHECK_GE(tid, 0);
CHECK_LT(tid, kMaxTid);
DPrintf("#%d: ThreadCreate tid=%d uid=%zu\n", thr->tid, tid, uid);
CHECK_EQ(tctx->status, ThreadStatusInvalid);
ctx->alive_threads++;
if (ctx->max_alive_threads < ctx->alive_threads) {
ctx->max_alive_threads++;
CHECK_EQ(ctx->max_alive_threads, ctx->alive_threads);
StatInc(thr, StatThreadMaxAlive);
}
tctx->status = ThreadStatusCreated;
tctx->thr = 0;
tctx->user_id = uid;
tctx->unique_id = ctx->unique_thread_seq++;
tctx->detached = detached;
if (tid) {
thr->fast_state.IncrementEpoch();
// Can't increment epoch w/o writing to the trace as well.
TraceAddEvent(thr, thr->fast_state.epoch(), EventTypeMop, 0);
thr->clock.set(thr->tid, thr->fast_state.epoch());
thr->fast_synch_epoch = thr->fast_state.epoch();
thr->clock.release(&tctx->sync);
StatInc(thr, StatSyncRelease);
tctx->creation_stack.ObtainCurrent(thr, pc);
}
return tid;
}
void ThreadStart(ThreadState *thr, int tid) {
CHECK_GT(thr->in_rtl, 0);
uptr stk_addr = 0;
uptr stk_size = 0;
uptr tls_addr = 0;
uptr tls_size = 0;
GetThreadStackAndTls(tid == 0, &stk_addr, &stk_size, &tls_addr, &tls_size);
if (tid) {
if (stk_addr && stk_size) {
MemoryResetRange(thr, /*pc=*/ 1, stk_addr, stk_size);
}
if (tls_addr && tls_size) {
// Check that the thr object is in tls;
const uptr thr_beg = (uptr)thr;
const uptr thr_end = (uptr)thr + sizeof(*thr);
CHECK_GE(thr_beg, tls_addr);
CHECK_LE(thr_beg, tls_addr + tls_size);
CHECK_GE(thr_end, tls_addr);
CHECK_LE(thr_end, tls_addr + tls_size);
// Since the thr object is huge, skip it.
MemoryResetRange(thr, /*pc=*/ 2, tls_addr, thr_beg - tls_addr);
MemoryResetRange(thr, /*pc=*/ 2, thr_end, tls_addr + tls_size - thr_end);
}
}
Lock l(&CTX()->thread_mtx);
ThreadContext *tctx = CTX()->threads[tid];
CHECK_NE(tctx, 0);
CHECK_EQ(tctx->status, ThreadStatusCreated);
tctx->status = ThreadStatusRunning;
tctx->epoch0 = tctx->epoch1 + 1;
tctx->epoch1 = (u64)-1;
new(thr) ThreadState(CTX(), tid, tctx->epoch0, stk_addr, stk_size,
tls_addr, tls_size);
tctx->thr = thr;
thr->fast_synch_epoch = tctx->epoch0;
thr->clock.set(tid, tctx->epoch0);
thr->clock.acquire(&tctx->sync);
StatInc(thr, StatSyncAcquire);
DPrintf("#%d: ThreadStart epoch=%zu stk_addr=%zx stk_size=%zx "
"tls_addr=%zx tls_size=%zx\n",
tid, (uptr)tctx->epoch0, stk_addr, stk_size, tls_addr, tls_size);
thr->is_alive = true;
}
void ThreadFinish(ThreadState *thr) {
CHECK_GT(thr->in_rtl, 0);
StatInc(thr, StatThreadFinish);
// FIXME: Treat it as write.
if (thr->stk_addr && thr->stk_size)
MemoryResetRange(thr, /*pc=*/ 3, thr->stk_addr, thr->stk_size);
if (thr->tls_addr && thr->tls_size) {
const uptr thr_beg = (uptr)thr;
const uptr thr_end = (uptr)thr + sizeof(*thr);
// Since the thr object is huge, skip it.
MemoryResetRange(thr, /*pc=*/ 4, thr->tls_addr, thr_beg - thr->tls_addr);
MemoryResetRange(thr, /*pc=*/ 5,
thr_end, thr->tls_addr + thr->tls_size - thr_end);
}
thr->is_alive = false;
Context *ctx = CTX();
Lock l(&ctx->thread_mtx);
ThreadContext *tctx = ctx->threads[thr->tid];
CHECK_NE(tctx, 0);
CHECK_EQ(tctx->status, ThreadStatusRunning);
CHECK_GT(ctx->alive_threads, 0);
ctx->alive_threads--;
if (tctx->detached) {
ThreadDead(thr, tctx);
} else {
thr->fast_state.IncrementEpoch();
// Can't increment epoch w/o writing to the trace as well.
TraceAddEvent(thr, thr->fast_state.epoch(), EventTypeMop, 0);
thr->clock.set(thr->tid, thr->fast_state.epoch());
thr->fast_synch_epoch = thr->fast_state.epoch();
thr->clock.release(&tctx->sync);
StatInc(thr, StatSyncRelease);
tctx->status = ThreadStatusFinished;
}
// Save from info about the thread.
tctx->dead_info = new(internal_alloc(MBlockDeadInfo, sizeof(ThreadDeadInfo)))
ThreadDeadInfo();
internal_memcpy(&tctx->dead_info->trace.events[0],
&thr->trace.events[0], sizeof(thr->trace.events));
for (int i = 0; i < kTraceParts; i++) {
tctx->dead_info->trace.headers[i].stack0.CopyFrom(
thr->trace.headers[i].stack0);
}
tctx->epoch1 = thr->fast_state.epoch();
thr->~ThreadState();
StatAggregate(ctx->stat, thr->stat);
tctx->thr = 0;
}
int ThreadTid(ThreadState *thr, uptr pc, uptr uid) {
CHECK_GT(thr->in_rtl, 0);
Context *ctx = CTX();
Lock l(&ctx->thread_mtx);
int res = -1;
for (unsigned tid = 0; tid < kMaxTid; tid++) {
ThreadContext *tctx = ctx->threads[tid];
if (tctx != 0 && tctx->user_id == uid
&& tctx->status != ThreadStatusInvalid) {
tctx->user_id = 0;
res = tid;
break;
}
}
DPrintf("#%d: ThreadTid uid=%zu tid=%d\n", thr->tid, uid, res);
return res;
}
void ThreadJoin(ThreadState *thr, uptr pc, int tid) {
CHECK_GT(thr->in_rtl, 0);
CHECK_GT(tid, 0);
CHECK_LT(tid, kMaxTid);
DPrintf("#%d: ThreadJoin tid=%d\n", thr->tid, tid);
Context *ctx = CTX();
Lock l(&ctx->thread_mtx);
ThreadContext *tctx = ctx->threads[tid];
if (tctx->status == ThreadStatusInvalid) {
TsanPrintf("ThreadSanitizer: join of non-existent thread\n");
return;
}
CHECK_EQ(tctx->detached, false);
CHECK_EQ(tctx->status, ThreadStatusFinished);
thr->clock.acquire(&tctx->sync);
StatInc(thr, StatSyncAcquire);
ThreadDead(thr, tctx);
}
void ThreadDetach(ThreadState *thr, uptr pc, int tid) {
CHECK_GT(thr->in_rtl, 0);
CHECK_GT(tid, 0);
CHECK_LT(tid, kMaxTid);
Context *ctx = CTX();
Lock l(&ctx->thread_mtx);
ThreadContext *tctx = ctx->threads[tid];
if (tctx->status == ThreadStatusInvalid) {
TsanPrintf("ThreadSanitizer: detach of non-existent thread\n");
return;
}
if (tctx->status == ThreadStatusFinished) {
ThreadDead(thr, tctx);
} else {
tctx->detached = true;
}
}
void MemoryAccessRange(ThreadState *thr, uptr pc, uptr addr,
uptr size, bool is_write) {
if (size == 0)
return;
u64 *shadow_mem = (u64*)MemToShadow(addr);
DPrintf2("#%d: MemoryAccessRange: @%p %p size=%d is_write=%d\n",
thr->tid, (void*)pc, (void*)addr,
(int)size, is_write);
#if TSAN_DEBUG
if (!IsAppMem(addr)) {
TsanPrintf("Access to non app mem %zx\n", addr);
DCHECK(IsAppMem(addr));
}
if (!IsAppMem(addr + size - 1)) {
TsanPrintf("Access to non app mem %zx\n", addr + size - 1);
DCHECK(IsAppMem(addr + size - 1));
}
if (!IsShadowMem((uptr)shadow_mem)) {
TsanPrintf("Bad shadow addr %p (%zx)\n", shadow_mem, addr);
DCHECK(IsShadowMem((uptr)shadow_mem));
}
if (!IsShadowMem((uptr)(shadow_mem + size * kShadowCnt / 8 - 1))) {
TsanPrintf("Bad shadow addr %p (%zx)\n",
shadow_mem + size * kShadowCnt / 8 - 1, addr + size - 1);
DCHECK(IsShadowMem((uptr)(shadow_mem + size * kShadowCnt / 8 - 1)));
}
#endif
StatInc(thr, StatMopRange);
FastState fast_state = thr->fast_state;
if (fast_state.GetIgnoreBit())
return;
fast_state.IncrementEpoch();
thr->fast_state = fast_state;
TraceAddEvent(thr, fast_state.epoch(), EventTypeMop, pc);
bool unaligned = (addr % kShadowCell) != 0;
// Handle unaligned beginning, if any.
for (; addr % kShadowCell && size; addr++, size--) {
int const kAccessSizeLog = 0;
Shadow cur(fast_state);
cur.SetWrite(is_write);
cur.SetAddr0AndSizeLog(addr & (kShadowCell - 1), kAccessSizeLog);
MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, fast_state,
shadow_mem, cur);
}
if (unaligned)
shadow_mem += kShadowCnt;
// Handle middle part, if any.
for (; size >= kShadowCell; addr += kShadowCell, size -= kShadowCell) {
int const kAccessSizeLog = 3;
Shadow cur(fast_state);
cur.SetWrite(is_write);
cur.SetAddr0AndSizeLog(0, kAccessSizeLog);
MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, fast_state,
shadow_mem, cur);
shadow_mem += kShadowCnt;
}
// Handle ending, if any.
for (; size; addr++, size--) {
int const kAccessSizeLog = 0;
Shadow cur(fast_state);
cur.SetWrite(is_write);
cur.SetAddr0AndSizeLog(addr & (kShadowCell - 1), kAccessSizeLog);
MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, fast_state,
shadow_mem, cur);
}
}
void MemoryRead1Byte(ThreadState *thr, uptr pc, uptr addr) {
MemoryAccess(thr, pc, addr, 0, 0);
}
void MemoryWrite1Byte(ThreadState *thr, uptr pc, uptr addr) {
MemoryAccess(thr, pc, addr, 0, 1);
}
void MemoryRead8Byte(ThreadState *thr, uptr pc, uptr addr) {
MemoryAccess(thr, pc, addr, 3, 0);
}
void MemoryWrite8Byte(ThreadState *thr, uptr pc, uptr addr) {
MemoryAccess(thr, pc, addr, 3, 1);
}
} // namespace __tsan
|
//===-- tsan_rtl_thread.cc ------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer (TSan), a race detector.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_placement_new.h"
#include "tsan_rtl.h"
#include "tsan_mman.h"
#include "tsan_platform.h"
#include "tsan_report.h"
#include "tsan_sync.h"
namespace __tsan {
#ifndef TSAN_GO
const int kThreadQuarantineSize = 16;
#else
const int kThreadQuarantineSize = 64;
#endif
static void MaybeReportThreadLeak(ThreadContext *tctx) {
if (tctx->detached)
return;
if (tctx->status != ThreadStatusCreated
&& tctx->status != ThreadStatusRunning
&& tctx->status != ThreadStatusFinished)
return;
ScopedReport rep(ReportTypeThreadLeak);
rep.AddThread(tctx);
OutputReport(rep);
}
void ThreadFinalize(ThreadState *thr) {
CHECK_GT(thr->in_rtl, 0);
if (!flags()->report_thread_leaks)
return;
Context *ctx = CTX();
Lock l(&ctx->thread_mtx);
for (unsigned i = 0; i < kMaxTid; i++) {
ThreadContext *tctx = ctx->threads[i];
if (tctx == 0)
continue;
MaybeReportThreadLeak(tctx);
}
}
static void ThreadDead(ThreadState *thr, ThreadContext *tctx) {
Context *ctx = CTX();
CHECK_GT(thr->in_rtl, 0);
CHECK(tctx->status == ThreadStatusRunning
|| tctx->status == ThreadStatusFinished);
DPrintf("#%d: ThreadDead uid=%zu\n", thr->tid, tctx->user_id);
tctx->status = ThreadStatusDead;
tctx->user_id = 0;
tctx->sync.Reset();
// Put to dead list.
tctx->dead_next = 0;
if (ctx->dead_list_size == 0)
ctx->dead_list_head = tctx;
else
ctx->dead_list_tail->dead_next = tctx;
ctx->dead_list_tail = tctx;
ctx->dead_list_size++;
}
int ThreadCreate(ThreadState *thr, uptr pc, uptr uid, bool detached) {
CHECK_GT(thr->in_rtl, 0);
Context *ctx = CTX();
Lock l(&ctx->thread_mtx);
StatInc(thr, StatThreadCreate);
int tid = -1;
ThreadContext *tctx = 0;
if (ctx->dead_list_size > kThreadQuarantineSize
|| ctx->thread_seq >= kMaxTid) {
if (ctx->dead_list_size == 0) {
TsanPrintf("ThreadSanitizer: %d thread limit exceeded. Dying.\n",
kMaxTid);
Die();
}
StatInc(thr, StatThreadReuse);
tctx = ctx->dead_list_head;
ctx->dead_list_head = tctx->dead_next;
ctx->dead_list_size--;
if (ctx->dead_list_size == 0) {
CHECK_EQ(tctx->dead_next, 0);
ctx->dead_list_head = 0;
}
CHECK_EQ(tctx->status, ThreadStatusDead);
tctx->status = ThreadStatusInvalid;
tctx->reuse_count++;
tctx->sync.Reset();
tid = tctx->tid;
DestroyAndFree(tctx->dead_info);
} else {
StatInc(thr, StatThreadMaxTid);
tid = ctx->thread_seq++;
void *mem = internal_alloc(MBlockThreadContex, sizeof(ThreadContext));
tctx = new(mem) ThreadContext(tid);
ctx->threads[tid] = tctx;
}
CHECK_NE(tctx, 0);
CHECK_GE(tid, 0);
CHECK_LT(tid, kMaxTid);
DPrintf("#%d: ThreadCreate tid=%d uid=%zu\n", thr->tid, tid, uid);
CHECK_EQ(tctx->status, ThreadStatusInvalid);
ctx->alive_threads++;
if (ctx->max_alive_threads < ctx->alive_threads) {
ctx->max_alive_threads++;
CHECK_EQ(ctx->max_alive_threads, ctx->alive_threads);
StatInc(thr, StatThreadMaxAlive);
}
tctx->status = ThreadStatusCreated;
tctx->thr = 0;
tctx->user_id = uid;
tctx->unique_id = ctx->unique_thread_seq++;
tctx->detached = detached;
if (tid) {
thr->fast_state.IncrementEpoch();
// Can't increment epoch w/o writing to the trace as well.
TraceAddEvent(thr, thr->fast_state.epoch(), EventTypeMop, 0);
thr->clock.set(thr->tid, thr->fast_state.epoch());
thr->fast_synch_epoch = thr->fast_state.epoch();
thr->clock.release(&tctx->sync);
StatInc(thr, StatSyncRelease);
tctx->creation_stack.ObtainCurrent(thr, pc);
}
return tid;
}
void ThreadStart(ThreadState *thr, int tid) {
CHECK_GT(thr->in_rtl, 0);
uptr stk_addr = 0;
uptr stk_size = 0;
uptr tls_addr = 0;
uptr tls_size = 0;
GetThreadStackAndTls(tid == 0, &stk_addr, &stk_size, &tls_addr, &tls_size);
if (tid) {
if (stk_addr && stk_size) {
MemoryResetRange(thr, /*pc=*/ 1, stk_addr, stk_size);
}
if (tls_addr && tls_size) {
// Check that the thr object is in tls;
const uptr thr_beg = (uptr)thr;
const uptr thr_end = (uptr)thr + sizeof(*thr);
CHECK_GE(thr_beg, tls_addr);
CHECK_LE(thr_beg, tls_addr + tls_size);
CHECK_GE(thr_end, tls_addr);
CHECK_LE(thr_end, tls_addr + tls_size);
// Since the thr object is huge, skip it.
MemoryResetRange(thr, /*pc=*/ 2, tls_addr, thr_beg - tls_addr);
MemoryResetRange(thr, /*pc=*/ 2, thr_end, tls_addr + tls_size - thr_end);
}
}
Lock l(&CTX()->thread_mtx);
ThreadContext *tctx = CTX()->threads[tid];
CHECK_NE(tctx, 0);
CHECK_EQ(tctx->status, ThreadStatusCreated);
tctx->status = ThreadStatusRunning;
tctx->epoch0 = tctx->epoch1 + 1;
tctx->epoch1 = (u64)-1;
new(thr) ThreadState(CTX(), tid, tctx->epoch0, stk_addr, stk_size,
tls_addr, tls_size);
tctx->thr = thr;
thr->fast_synch_epoch = tctx->epoch0;
thr->clock.set(tid, tctx->epoch0);
thr->clock.acquire(&tctx->sync);
StatInc(thr, StatSyncAcquire);
DPrintf("#%d: ThreadStart epoch=%zu stk_addr=%zx stk_size=%zx "
"tls_addr=%zx tls_size=%zx\n",
tid, (uptr)tctx->epoch0, stk_addr, stk_size, tls_addr, tls_size);
thr->is_alive = true;
}
void ThreadFinish(ThreadState *thr) {
CHECK_GT(thr->in_rtl, 0);
StatInc(thr, StatThreadFinish);
// FIXME: Treat it as write.
if (thr->stk_addr && thr->stk_size)
MemoryResetRange(thr, /*pc=*/ 3, thr->stk_addr, thr->stk_size);
if (thr->tls_addr && thr->tls_size) {
const uptr thr_beg = (uptr)thr;
const uptr thr_end = (uptr)thr + sizeof(*thr);
// Since the thr object is huge, skip it.
MemoryResetRange(thr, /*pc=*/ 4, thr->tls_addr, thr_beg - thr->tls_addr);
MemoryResetRange(thr, /*pc=*/ 5,
thr_end, thr->tls_addr + thr->tls_size - thr_end);
}
thr->is_alive = false;
Context *ctx = CTX();
Lock l(&ctx->thread_mtx);
ThreadContext *tctx = ctx->threads[thr->tid];
CHECK_NE(tctx, 0);
CHECK_EQ(tctx->status, ThreadStatusRunning);
CHECK_GT(ctx->alive_threads, 0);
ctx->alive_threads--;
if (tctx->detached) {
ThreadDead(thr, tctx);
} else {
thr->fast_state.IncrementEpoch();
// Can't increment epoch w/o writing to the trace as well.
TraceAddEvent(thr, thr->fast_state.epoch(), EventTypeMop, 0);
thr->clock.set(thr->tid, thr->fast_state.epoch());
thr->fast_synch_epoch = thr->fast_state.epoch();
thr->clock.release(&tctx->sync);
StatInc(thr, StatSyncRelease);
tctx->status = ThreadStatusFinished;
}
// Save from info about the thread.
tctx->dead_info = new(internal_alloc(MBlockDeadInfo, sizeof(ThreadDeadInfo)))
ThreadDeadInfo();
internal_memcpy(&tctx->dead_info->trace.events[0],
&thr->trace.events[0], sizeof(thr->trace.events));
for (int i = 0; i < kTraceParts; i++) {
tctx->dead_info->trace.headers[i].stack0.CopyFrom(
thr->trace.headers[i].stack0);
}
tctx->epoch1 = thr->fast_state.epoch();
thr->~ThreadState();
StatAggregate(ctx->stat, thr->stat);
tctx->thr = 0;
}
int ThreadTid(ThreadState *thr, uptr pc, uptr uid) {
CHECK_GT(thr->in_rtl, 0);
Context *ctx = CTX();
Lock l(&ctx->thread_mtx);
int res = -1;
for (unsigned tid = 0; tid < kMaxTid; tid++) {
ThreadContext *tctx = ctx->threads[tid];
if (tctx != 0 && tctx->user_id == uid
&& tctx->status != ThreadStatusInvalid) {
tctx->user_id = 0;
res = tid;
break;
}
}
DPrintf("#%d: ThreadTid uid=%zu tid=%d\n", thr->tid, uid, res);
return res;
}
void ThreadJoin(ThreadState *thr, uptr pc, int tid) {
CHECK_GT(thr->in_rtl, 0);
CHECK_GT(tid, 0);
CHECK_LT(tid, kMaxTid);
DPrintf("#%d: ThreadJoin tid=%d\n", thr->tid, tid);
Context *ctx = CTX();
Lock l(&ctx->thread_mtx);
ThreadContext *tctx = ctx->threads[tid];
if (tctx->status == ThreadStatusInvalid) {
TsanPrintf("ThreadSanitizer: join of non-existent thread\n");
return;
}
CHECK_EQ(tctx->detached, false);
CHECK_EQ(tctx->status, ThreadStatusFinished);
thr->clock.acquire(&tctx->sync);
StatInc(thr, StatSyncAcquire);
ThreadDead(thr, tctx);
}
void ThreadDetach(ThreadState *thr, uptr pc, int tid) {
CHECK_GT(thr->in_rtl, 0);
CHECK_GT(tid, 0);
CHECK_LT(tid, kMaxTid);
Context *ctx = CTX();
Lock l(&ctx->thread_mtx);
ThreadContext *tctx = ctx->threads[tid];
if (tctx->status == ThreadStatusInvalid) {
TsanPrintf("ThreadSanitizer: detach of non-existent thread\n");
return;
}
if (tctx->status == ThreadStatusFinished) {
ThreadDead(thr, tctx);
} else {
tctx->detached = true;
}
}
void MemoryAccessRange(ThreadState *thr, uptr pc, uptr addr,
uptr size, bool is_write) {
if (size == 0)
return;
u64 *shadow_mem = (u64*)MemToShadow(addr);
DPrintf2("#%d: MemoryAccessRange: @%p %p size=%d is_write=%d\n",
thr->tid, (void*)pc, (void*)addr,
(int)size, is_write);
#if TSAN_DEBUG
if (!IsAppMem(addr)) {
TsanPrintf("Access to non app mem %zx\n", addr);
DCHECK(IsAppMem(addr));
}
if (!IsAppMem(addr + size - 1)) {
TsanPrintf("Access to non app mem %zx\n", addr + size - 1);
DCHECK(IsAppMem(addr + size - 1));
}
if (!IsShadowMem((uptr)shadow_mem)) {
TsanPrintf("Bad shadow addr %p (%zx)\n", shadow_mem, addr);
DCHECK(IsShadowMem((uptr)shadow_mem));
}
if (!IsShadowMem((uptr)(shadow_mem + size * kShadowCnt / 8 - 1))) {
TsanPrintf("Bad shadow addr %p (%zx)\n",
shadow_mem + size * kShadowCnt / 8 - 1, addr + size - 1);
DCHECK(IsShadowMem((uptr)(shadow_mem + size * kShadowCnt / 8 - 1)));
}
#endif
StatInc(thr, StatMopRange);
FastState fast_state = thr->fast_state;
if (fast_state.GetIgnoreBit())
return;
fast_state.IncrementEpoch();
thr->fast_state = fast_state;
TraceAddEvent(thr, fast_state.epoch(), EventTypeMop, pc);
bool unaligned = (addr % kShadowCell) != 0;
// Handle unaligned beginning, if any.
for (; addr % kShadowCell && size; addr++, size--) {
int const kAccessSizeLog = 0;
Shadow cur(fast_state);
cur.SetWrite(is_write);
cur.SetAddr0AndSizeLog(addr & (kShadowCell - 1), kAccessSizeLog);
MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, fast_state,
shadow_mem, cur);
}
if (unaligned)
shadow_mem += kShadowCnt;
// Handle middle part, if any.
for (; size >= kShadowCell; addr += kShadowCell, size -= kShadowCell) {
int const kAccessSizeLog = 3;
Shadow cur(fast_state);
cur.SetWrite(is_write);
cur.SetAddr0AndSizeLog(0, kAccessSizeLog);
MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, fast_state,
shadow_mem, cur);
shadow_mem += kShadowCnt;
}
// Handle ending, if any.
for (; size; addr++, size--) {
int const kAccessSizeLog = 0;
Shadow cur(fast_state);
cur.SetWrite(is_write);
cur.SetAddr0AndSizeLog(addr & (kShadowCell - 1), kAccessSizeLog);
MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, fast_state,
shadow_mem, cur);
}
}
void MemoryRead1Byte(ThreadState *thr, uptr pc, uptr addr) {
MemoryAccess(thr, pc, addr, 0, 0);
}
void MemoryWrite1Byte(ThreadState *thr, uptr pc, uptr addr) {
MemoryAccess(thr, pc, addr, 0, 1);
}
void MemoryRead8Byte(ThreadState *thr, uptr pc, uptr addr) {
MemoryAccess(thr, pc, addr, 3, 0);
}
void MemoryWrite8Byte(ThreadState *thr, uptr pc, uptr addr) {
MemoryAccess(thr, pc, addr, 3, 1);
}
} // namespace __tsan
|
increase number of dead threads for Go
|
tsan: increase number of dead threads for Go
git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@160283 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
|
1b3126ce16d8d0d09ce4f19980ae740011bf3970
|
src/main-menu.cpp
|
src/main-menu.cpp
|
#include <sstream>
#include "factory/collector.h"
#include "network/network.h"
#include "util/token_exception.h"
#include "music.h"
#include "menu/menu.h"
#include "menu/menu_global.h"
#include "input/input-manager.h"
#include "game/mod.h"
#include "shutdown_exception.h"
#include "util/timedifference.h"
#include "util/funcs.h"
#include "util/file-system.h"
#include "util/tokenreader.h"
#include "util/token.h"
#include "globals.h"
#include "configuration.h"
#include "init.h"
#include <vector>
using namespace std;
static int gfx = Global::WINDOWED;
#define NUM_ARGS(d) (sizeof(d)/sizeof(char*))
static const char * WINDOWED_ARG[] = {"-w", "fullscreen", "nowindowed", "no-windowed"};
static const char * DATAPATH_ARG[] = {"-d", "data", "datapath", "data-path", "path"};
static const char * DEBUG_ARG[] = {"-l", "debug"};
static const char * MUSIC_ARG[] = {"-m", "music", "nomusic", "no-music"};
static const char * closestMatch(const char * s1, vector<const char *> args){
const char * good = NULL;
int minimum = -1;
for (vector<const char *>::iterator it = args.begin(); it != args.end(); it++){
const char * compare = *it;
if (strlen(compare) > 2){
int distance = Util::levenshtein(s1, compare);
if (distance != -1 && (minimum == -1 || distance < minimum)){
minimum = distance;
good = compare;
}
}
}
return good;
}
static bool isArg( const char * s1, const char * s2[], int num){
for (int i = 0; i < num; i++){
if (strcasecmp(s1, s2[i]) == 0){
return true;
}
}
return false;
}
/* {"a", "b", "c"}, 3, ',' => "a, b, c"
*/
static const char * all(const char * args[], const int num, const char separate = ','){
static char buffer[1<<10];
strcpy(buffer, "");
for (int i = 0; i < num; i++){
char fuz[10];
sprintf(fuz, "%c ", separate);
strcat(buffer, args[i]);
if (i != num - 1){
strcat(buffer, fuz);
}
}
return buffer;
}
static void showOptions(){
Global::debug( 0 ) << "Paintown by Jon Rafkind" << endl;
Global::debug( 0 ) << all(WINDOWED_ARG, NUM_ARGS(WINDOWED_ARG), ',') << " : Fullscreen mode" << endl;
Global::debug( 0 ) << all(DATAPATH_ARG, NUM_ARGS(DATAPATH_ARG)) << " <path> : Use data path of <path>. Default is " << Util::getDataPath2() << endl;
Global::debug( 0 ) << all(DEBUG_ARG, NUM_ARGS(DEBUG_ARG)) << " # : Enable debug statements. Higher numbers gives more debugging. Default is 0. Example: -l 3" << endl;
Global::debug( 0 ) << all(MUSIC_ARG, NUM_ARGS(MUSIC_ARG)) << " : Turn off music" << endl;
Global::debug( 0 ) << endl;
}
static void addArgs(vector<const char *> & args, const char * strings[], int num){
for (int i = 0; i < num; i++){
args.push_back(strings[i]);
}
}
static string mainMenuPath() throw (TokenException, LoadException, Filesystem::NotFound){
string menu = Paintown::Mod::getCurrentMod()->getMenu();
return Filesystem::find(menu);
/*
string file = Filesystem::find(currentMod());
TokenReader tr(file);
Token * head = tr.readToken();
Token * menu = head->findToken("game/menu");
if (menu == NULL){
throw LoadException(file + " does not contain a game/menu token");
}
string path;
*menu >> path;
// string path = "/menu/main.txt"
return Filesystem::find(path);
*/
}
int paintown_main( int argc, char ** argv ){
bool music_on = true;
Collector janitor;
Global::setDebug( 0 );
vector<const char *> all_args;
#define ADD_ARGS(args) addArgs(all_args, args, NUM_ARGS(args))
ADD_ARGS(WINDOWED_ARG);
ADD_ARGS(DATAPATH_ARG);
ADD_ARGS(DEBUG_ARG);
ADD_ARGS(MUSIC_ARG);
#undef ADD_ARGS
for ( int q = 1; q < argc; q++ ){
if ( isArg( argv[ q ], WINDOWED_ARG, NUM_ARGS(WINDOWED_ARG) ) ){
gfx = Global::FULLSCREEN;
} else if ( isArg( argv[ q ], DATAPATH_ARG, NUM_ARGS(DATAPATH_ARG) ) ){
q += 1;
if ( q < argc ){
Util::setDataPath( argv[ q ] );
}
} else if ( isArg( argv[ q ], MUSIC_ARG, NUM_ARGS(MUSIC_ARG) ) ){
music_on = false;
} else if ( isArg( argv[ q ], DEBUG_ARG, NUM_ARGS(DEBUG_ARG) ) ){
q += 1;
if ( q < argc ){
istringstream i( argv[ q ] );
int f;
i >> f;
Global::setDebug( f );
}
} else {
const char * arg = argv[q];
const char * closest = closestMatch(arg, all_args);
if (closest == NULL){
Global::debug(0) << "I don't recognize option '" << arg << "'" << endl;
} else {
Global::debug(0) << "You gave option '" << arg << "'. Did you mean '" << closest << "'?" << endl;
}
}
}
#undef NUM_ARGS
showOptions();
Global::debug(0) << "Debug level: " << Global::getDebug() << endl;
/* time how long init takes */
TimeDifference diff;
diff.startTime();
/* init initializes practically everything including
* graphics
* sound
* input
* network
* configuration
* ...
*/
if (! Global::init(gfx)){
Global::debug( 0 ) << "Could not initialize system" << endl;
return -1;
} else {
MenuGlobals::setFullscreen((gfx == Global::FULLSCREEN ? true : false));
}
diff.endTime();
Global::debug(0) << diff.printTime("Init:") << endl;
Paintown::Mod::loadMod(Configuration::getCurrentGame());
InputManager input;
Music music(music_on);
try{
Menu game;
game.load(mainMenuPath());
game.run();
} catch (const Filesystem::NotFound & ex){
Global::debug(0) << "There was a problem loading the main menu. Error was:\n " << ex.getReason() << endl;
} catch (const TokenException & ex){
Global::debug(0) << "There was a problem with the token. Error was:\n " << ex.getReason() << endl;
return -1;
} catch (const LoadException & ex){
Global::debug(0) << "There was a problem loading the main menu. Error was:\n " << ex.getReason() << endl;
return -1;
} catch (const ReturnException & ex){
} catch (const ShutdownException & shutdown){
Global::debug(1) << "Forced a shutdown. Cya!" << endl;
}
Configuration::saveConfiguration();
return 0;
}
|
#include <sstream>
#include "factory/collector.h"
#include "network/network.h"
#include "util/token_exception.h"
#include "music.h"
#include "menu/menu.h"
#include "menu/menu_global.h"
#include "input/input-manager.h"
#include "game/mod.h"
#include "shutdown_exception.h"
#include "util/timedifference.h"
#include "util/funcs.h"
#include "util/file-system.h"
#include "util/tokenreader.h"
#include "util/token.h"
#include "globals.h"
#include "configuration.h"
#include "init.h"
#include <vector>
using namespace std;
static int gfx = Global::WINDOWED;
#define NUM_ARGS(d) (sizeof(d)/sizeof(char*))
static const char * WINDOWED_ARG[] = {"-w", "fullscreen", "nowindowed", "no-windowed"};
static const char * DATAPATH_ARG[] = {"-d", "data", "datapath", "data-path", "path"};
static const char * DEBUG_ARG[] = {"-l", "debug"};
static const char * MUSIC_ARG[] = {"-m", "music", "nomusic", "no-music"};
static const char * closestMatch(const char * s1, vector<const char *> args){
const char * good = NULL;
int minimum = -1;
for (vector<const char *>::iterator it = args.begin(); it != args.end(); it++){
const char * compare = *it;
if (strlen(compare) > 2){
int distance = Util::levenshtein(s1, compare);
if (distance != -1 && (minimum == -1 || distance < minimum)){
minimum = distance;
good = compare;
}
}
}
return good;
}
static bool isArg( const char * s1, const char * s2[], int num){
for (int i = 0; i < num; i++){
if (strcasecmp(s1, s2[i]) == 0){
return true;
}
}
return false;
}
/* {"a", "b", "c"}, 3, ',' => "a, b, c"
*/
static const char * all(const char * args[], const int num, const char separate = ','){
static char buffer[1<<10];
strcpy(buffer, "");
for (int i = 0; i < num; i++){
char fuz[10];
sprintf(fuz, "%c ", separate);
strcat(buffer, args[i]);
if (i != num - 1){
strcat(buffer, fuz);
}
}
return buffer;
}
static void showOptions(){
Global::debug(0) << "Paintown by Jon Rafkind" << endl;
Global::debug(0) << all(WINDOWED_ARG, NUM_ARGS(WINDOWED_ARG), ',') << " : Fullscreen mode" << endl;
Global::debug(0) << all(DATAPATH_ARG, NUM_ARGS(DATAPATH_ARG)) << " <path> : Use data path of <path>. Default is " << Util::getDataPath2() << endl;
Global::debug(0) << all(DEBUG_ARG, NUM_ARGS(DEBUG_ARG)) << " # : Enable debug statements. Higher numbers gives more debugging. Default is 0. Negative numbers are allowed. Example: -l 3" << endl;
Global::debug(0) << all(MUSIC_ARG, NUM_ARGS(MUSIC_ARG)) << " : Turn off music" << endl;
Global::debug(0) << endl;
}
static void addArgs(vector<const char *> & args, const char * strings[], int num){
for (int i = 0; i < num; i++){
args.push_back(strings[i]);
}
}
static string mainMenuPath() throw (TokenException, LoadException, Filesystem::NotFound){
string menu = Paintown::Mod::getCurrentMod()->getMenu();
return Filesystem::find(menu);
/*
string file = Filesystem::find(currentMod());
TokenReader tr(file);
Token * head = tr.readToken();
Token * menu = head->findToken("game/menu");
if (menu == NULL){
throw LoadException(file + " does not contain a game/menu token");
}
string path;
*menu >> path;
// string path = "/menu/main.txt"
return Filesystem::find(path);
*/
}
int paintown_main( int argc, char ** argv ){
bool music_on = true;
Collector janitor;
Global::setDebug( 0 );
vector<const char *> all_args;
#define ADD_ARGS(args) addArgs(all_args, args, NUM_ARGS(args))
ADD_ARGS(WINDOWED_ARG);
ADD_ARGS(DATAPATH_ARG);
ADD_ARGS(DEBUG_ARG);
ADD_ARGS(MUSIC_ARG);
#undef ADD_ARGS
for ( int q = 1; q < argc; q++ ){
if ( isArg( argv[ q ], WINDOWED_ARG, NUM_ARGS(WINDOWED_ARG) ) ){
gfx = Global::FULLSCREEN;
} else if ( isArg( argv[ q ], DATAPATH_ARG, NUM_ARGS(DATAPATH_ARG) ) ){
q += 1;
if ( q < argc ){
Util::setDataPath( argv[ q ] );
}
} else if ( isArg( argv[ q ], MUSIC_ARG, NUM_ARGS(MUSIC_ARG) ) ){
music_on = false;
} else if ( isArg( argv[ q ], DEBUG_ARG, NUM_ARGS(DEBUG_ARG) ) ){
q += 1;
if ( q < argc ){
istringstream i( argv[ q ] );
int f;
i >> f;
Global::setDebug( f );
}
} else {
const char * arg = argv[q];
const char * closest = closestMatch(arg, all_args);
if (closest == NULL){
Global::debug(0) << "I don't recognize option '" << arg << "'" << endl;
} else {
Global::debug(0) << "You gave option '" << arg << "'. Did you mean '" << closest << "'?" << endl;
}
}
}
#undef NUM_ARGS
showOptions();
Global::debug(0) << "Debug level: " << Global::getDebug() << endl;
/* time how long init takes */
TimeDifference diff;
diff.startTime();
/* init initializes practically everything including
* graphics
* sound
* input
* network
* configuration
* ...
*/
if (! Global::init(gfx)){
Global::debug( 0 ) << "Could not initialize system" << endl;
return -1;
} else {
MenuGlobals::setFullscreen((gfx == Global::FULLSCREEN ? true : false));
}
diff.endTime();
Global::debug(0) << diff.printTime("Init took") << endl;
Paintown::Mod::loadMod(Configuration::getCurrentGame());
InputManager input;
Music music(music_on);
try{
Menu game;
game.load(mainMenuPath());
game.run();
} catch (const Filesystem::NotFound & ex){
Global::debug(0) << "There was a problem loading the main menu. Error was:\n " << ex.getReason() << endl;
} catch (const TokenException & ex){
Global::debug(0) << "There was a problem with the token. Error was:\n " << ex.getReason() << endl;
return -1;
} catch (const LoadException & ex){
Global::debug(0) << "There was a problem loading the main menu. Error was:\n " << ex.getReason() << endl;
return -1;
} catch (const ReturnException & ex){
} catch (const ShutdownException & shutdown){
Global::debug(1) << "Forced a shutdown. Cya!" << endl;
}
Configuration::saveConfiguration();
return 0;
}
|
print out times better
|
print out times better
|
C++
|
bsd-3-clause
|
scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown
|
481a803f5793097b62f06207e5cab74988d5ceed
|
decoder/DecoderApi_unittest.cpp
|
decoder/DecoderApi_unittest.cpp
|
/*
* Copyright 2016 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
//
// The unittest header must be included before va_x11.h (which might be included
// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers
// define 'Bool' and 'None' preprocessor types. Gtest uses the same names
// to define some struct placeholders. Thus, this creates a compile conflict
// if X defines them before gtest. Hence, the include order requirement here
// is the only fix for this right now.
//
// See bug filed on gtest at https://github.com/google/googletest/issues/371
// for more details.
//
#include "common/factory_unittest.h"
#include "common/common_def.h"
#include "common/log.h"
#include "decoder/FrameData.h"
#include "vaapi/vaapidisplay.h"
#include "vaapi/vaapisurfaceallocator.h"
// primary header
#include "VideoDecoderHost.h"
// system headers
#include <algorithm>
#include <stdint.h>
namespace YamiMediaCodec {
static FrameData g_h264data[] = {
g_avc8x8I,
g_avc8x8P,
g_avc8x8B,
g_avc8x16,
g_avc16x16,
g_EOF,
};
class TestDecodeFrames {
public:
typedef SharedPtr<TestDecodeFrames> Shared;
static Shared create(
const FrameData* data,
const char* mime)
{
Shared frames(new TestDecodeFrames(data, mime));
return frames;
}
const char* getMime() const
{
return m_mime;
}
bool getFrame(VideoDecodeBuffer& buffer, FrameInfo& info)
{
const FrameData& d = m_data[m_idx];
if (d.m_data != NULL) {
buffer.data = (uint8_t*)d.m_data;
buffer.size = d.m_size;
info = d.m_info;
m_idx++;
return true;
}
return false;
}
friend std::ostream& operator<<(std::ostream& os, const TestDecodeFrames& t)
{
os << t.m_mime;
return os;
}
private:
TestDecodeFrames(
const FrameData* data,
const char* mime)
: m_data(data)
, m_mime(mime)
, m_idx(0)
{
}
const FrameData* m_data;
const char* m_mime;
int m_idx;
};
class DecodeSurfaceAllocator : public VaapiSurfaceAllocator {
public:
DecodeSurfaceAllocator(const DisplayPtr& display)
: VaapiSurfaceAllocator(display->getID())
, m_width(0)
, m_height(0)
{
}
void onFormatChange(const VideoFormatInfo* format)
{
m_width = format->surfaceWidth;
m_height = format->surfaceHeight;
}
protected:
YamiStatus doAlloc(SurfaceAllocParams* params)
{
EXPECT_EQ(m_width, params->width);
EXPECT_EQ(m_height, params->height);
return VaapiSurfaceAllocator::doAlloc(params);
}
void doUnref()
{
delete this;
}
private:
uint32_t m_width;
uint32_t m_height;
};
class DecodeApiTest
: public ::testing::Test,
public ::testing::WithParamInterface<TestDecodeFrames::Shared> {
};
bool checkOutput(SharedPtr<IVideoDecoder>& decoder, VideoFormatInfo& format)
{
SharedPtr<VideoFrame> output(decoder->getOutput());
bool gotOutput = bool(output);
if (gotOutput) {
EXPECT_EQ(format.width, output->crop.width);
EXPECT_EQ(format.height, output->crop.height);
}
return gotOutput;
}
TEST_P(DecodeApiTest, Format_Change)
{
NativeDisplay nativeDisplay;
memset(&nativeDisplay, 0, sizeof(nativeDisplay));
DisplayPtr display = VaapiDisplay::create(nativeDisplay);
DecodeSurfaceAllocator* allocator = new DecodeSurfaceAllocator(display);
SharedPtr<IVideoDecoder> decoder;
TestDecodeFrames frames = *GetParam();
decoder.reset(createVideoDecoder(frames.getMime()), releaseVideoDecoder);
ASSERT_TRUE(bool(decoder));
decoder->setAllocator(allocator);
VideoConfigBuffer config;
memset(&config, 0, sizeof(config));
ASSERT_EQ(YAMI_SUCCESS, decoder->start(&config));
VideoDecodeBuffer buffer;
FrameInfo info;
uint32_t inFrames = 0;
uint32_t outFrames = 0;
//keep previous resolution
VideoFormatInfo prevFormat;
memset(&prevFormat, 0, sizeof(prevFormat));
while (frames.getFrame(buffer, info)) {
YamiStatus status = decoder->decode(&buffer);
if (prevFormat.width != info.m_width
|| prevFormat.width != info.m_width) {
EXPECT_EQ(YAMI_DECODE_FORMAT_CHANGE, status);
}
while (checkOutput(decoder, prevFormat))
outFrames++;
if (status == YAMI_DECODE_FORMAT_CHANGE) {
//we need ouptut all previous frames
EXPECT_EQ(inFrames, outFrames);
//check format
const VideoFormatInfo* format = decoder->getFormatInfo();
ASSERT_TRUE(format);
EXPECT_EQ(info.m_width, format->width);
EXPECT_EQ(info.m_height, format->height);
allocator->onFormatChange(format);
prevFormat = *format;
//send buffer again
EXPECT_EQ(YAMI_SUCCESS, decoder->decode(&buffer));
}
else {
EXPECT_EQ(YAMI_SUCCESS, status);
}
inFrames++;
}
//drain the decoder
EXPECT_EQ(YAMI_SUCCESS, decoder->decode(NULL));
while (checkOutput(decoder, prevFormat))
outFrames++;
EXPECT_TRUE(inFrames > 0);
EXPECT_EQ(inFrames, outFrames);
}
/** Teach Google Test how to print a TestDecodeFrames::Shared object */
void PrintTo(const TestDecodeFrames::Shared& t, std::ostream* os)
{
*os << *t;
}
INSTANTIATE_TEST_CASE_P(
VaapiDecoder, DecodeApiTest,
::testing::Values(
TestDecodeFrames::create(g_h264data, YAMI_MIME_H264)));
}
|
/*
* Copyright 2016 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
//
// The unittest header must be included before va_x11.h (which might be included
// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers
// define 'Bool' and 'None' preprocessor types. Gtest uses the same names
// to define some struct placeholders. Thus, this creates a compile conflict
// if X defines them before gtest. Hence, the include order requirement here
// is the only fix for this right now.
//
// See bug filed on gtest at https://github.com/google/googletest/issues/371
// for more details.
//
#include "common/factory_unittest.h"
#include "common/common_def.h"
#include "common/log.h"
#include "decoder/FrameData.h"
#include "vaapi/vaapidisplay.h"
#include "vaapi/vaapisurfaceallocator.h"
// primary header
#include "VideoDecoderHost.h"
// system headers
#include <algorithm>
#include <stdint.h>
namespace YamiMediaCodec {
static FrameData g_h264data[] = {
g_avc8x8I,
g_avc8x8P,
g_avc8x8B,
g_avc8x16,
g_avc16x16,
g_avc8x8I,
g_avc8x8P,
g_avc8x8B,
g_avc8x8I,
g_avc8x8P,
g_avc8x8B,
g_EOF,
};
class TestDecodeFrames {
public:
typedef SharedPtr<TestDecodeFrames> Shared;
static Shared create(
const FrameData* data,
const char* mime)
{
Shared frames(new TestDecodeFrames(data, mime));
return frames;
}
const char* getMime() const
{
return m_mime;
}
const uint32_t getFrameCount() const
{
uint32_t i = 0;
FrameData d = m_data[i];
while (d.m_data != NULL) {
i++;
d = m_data[i];
}
return i;
}
bool getFrame(VideoDecodeBuffer& buffer, FrameInfo& info)
{
const FrameData& d = m_data[m_idx];
if (d.m_data != NULL) {
buffer.data = (uint8_t*)d.m_data;
buffer.size = d.m_size;
info = d.m_info;
m_idx++;
return true;
}
return false;
}
void seekToStart()
{
m_idx = 0;
}
friend std::ostream& operator<<(std::ostream& os, const TestDecodeFrames& t)
{
os << t.m_mime;
return os;
}
private:
TestDecodeFrames(
const FrameData* data,
const char* mime)
: m_data(data)
, m_mime(mime)
, m_idx(0)
{
}
const FrameData* m_data;
const char* m_mime;
int m_idx;
};
class DecodeSurfaceAllocator : public VaapiSurfaceAllocator {
public:
DecodeSurfaceAllocator(const DisplayPtr& display)
: VaapiSurfaceAllocator(display->getID())
, m_width(0)
, m_height(0)
{
}
void onFormatChange(const VideoFormatInfo* format)
{
m_width = format->surfaceWidth;
m_height = format->surfaceHeight;
}
protected:
YamiStatus doAlloc(SurfaceAllocParams* params)
{
EXPECT_EQ(m_width, params->width);
EXPECT_EQ(m_height, params->height);
return VaapiSurfaceAllocator::doAlloc(params);
}
void doUnref()
{
delete this;
}
private:
uint32_t m_width;
uint32_t m_height;
};
class DecodeApiTest
: public ::testing::Test,
public ::testing::WithParamInterface<TestDecodeFrames::Shared> {
};
bool checkOutput(SharedPtr<IVideoDecoder>& decoder, VideoFormatInfo& format)
{
SharedPtr<VideoFrame> output(decoder->getOutput());
bool gotOutput = bool(output);
if (gotOutput) {
EXPECT_EQ(format.width, output->crop.width);
EXPECT_EQ(format.height, output->crop.height);
}
return gotOutput;
}
TEST_P(DecodeApiTest, Format_Change)
{
NativeDisplay nativeDisplay;
memset(&nativeDisplay, 0, sizeof(nativeDisplay));
DisplayPtr display = VaapiDisplay::create(nativeDisplay);
DecodeSurfaceAllocator* allocator = new DecodeSurfaceAllocator(display);
SharedPtr<IVideoDecoder> decoder;
TestDecodeFrames frames = *GetParam();
decoder.reset(createVideoDecoder(frames.getMime()), releaseVideoDecoder);
ASSERT_TRUE(bool(decoder));
decoder->setAllocator(allocator);
VideoConfigBuffer config;
memset(&config, 0, sizeof(config));
ASSERT_EQ(YAMI_SUCCESS, decoder->start(&config));
VideoDecodeBuffer buffer;
FrameInfo info;
uint32_t inFrames = 0;
uint32_t outFrames = 0;
//keep previous resolution
VideoFormatInfo prevFormat;
memset(&prevFormat, 0, sizeof(prevFormat));
while (frames.getFrame(buffer, info)) {
YamiStatus status = decoder->decode(&buffer);
if (prevFormat.width != info.m_width
|| prevFormat.width != info.m_width) {
EXPECT_EQ(YAMI_DECODE_FORMAT_CHANGE, status);
}
while (checkOutput(decoder, prevFormat))
outFrames++;
if (status == YAMI_DECODE_FORMAT_CHANGE) {
//we need ouptut all previous frames
EXPECT_EQ(inFrames, outFrames);
//check format
const VideoFormatInfo* format = decoder->getFormatInfo();
ASSERT_TRUE(format);
EXPECT_EQ(info.m_width, format->width);
EXPECT_EQ(info.m_height, format->height);
allocator->onFormatChange(format);
prevFormat = *format;
//send buffer again
EXPECT_EQ(YAMI_SUCCESS, decoder->decode(&buffer));
}
else {
EXPECT_EQ(YAMI_SUCCESS, status);
}
inFrames++;
}
//drain the decoder
EXPECT_EQ(YAMI_SUCCESS, decoder->decode(NULL));
while (checkOutput(decoder, prevFormat))
outFrames++;
EXPECT_TRUE(inFrames > 0);
EXPECT_EQ(inFrames, outFrames);
}
TEST_P(DecodeApiTest, Flush)
{
NativeDisplay nativeDisplay;
memset(&nativeDisplay, 0, sizeof(nativeDisplay));
DisplayPtr display = VaapiDisplay::create(nativeDisplay);
DecodeSurfaceAllocator* allocator = new DecodeSurfaceAllocator(display);
SharedPtr<IVideoDecoder> decoder;
TestDecodeFrames frames = *GetParam();
decoder.reset(createVideoDecoder(frames.getMime()), releaseVideoDecoder);
ASSERT_TRUE(bool(decoder));
decoder->setAllocator(allocator);
VideoConfigBuffer config;
memset(&config, 0, sizeof(config));
ASSERT_EQ(YAMI_SUCCESS, decoder->start(&config));
VideoDecodeBuffer buffer;
FrameInfo info;
int64_t timeBeforeFlush = 0;
int64_t timeCurrent = 0;
SharedPtr<VideoFrame> output;
int32_t size = frames.getFrameCount();
int32_t outFrames = 0;
for (int i = 0; i < size; i++) {
outFrames = 0;
frames.seekToStart();
for (int j = 0; j <= i; j++) {
if (!frames.getFrame(buffer, info))
break;
buffer.timeStamp = timeCurrent;
timeCurrent++;
YamiStatus status = decoder->decode(&buffer);
while ((output = decoder->getOutput())) {
EXPECT_TRUE(output->timeStamp > timeBeforeFlush);
outFrames++;
}
if (status == YAMI_DECODE_FORMAT_CHANGE) {
//check format
const VideoFormatInfo* format = decoder->getFormatInfo();
allocator->onFormatChange(format);
//send buffer again
EXPECT_EQ(YAMI_SUCCESS, decoder->decode(&buffer));
}
else {
EXPECT_EQ(YAMI_SUCCESS, status);
}
}
timeBeforeFlush = buffer.timeStamp;
// No flush at last round, it has EOS at the end
if (i < (size - 1))
decoder->flush();
}
//drain the decoder
EXPECT_EQ(YAMI_SUCCESS, decoder->decode(NULL));
while (decoder->getOutput()) {
outFrames++;
}
EXPECT_EQ(outFrames, size);
}
/** Teach Google Test how to print a TestDecodeFrames::Shared object */
void PrintTo(const TestDecodeFrames::Shared& t, std::ostream* os)
{
*os << *t;
}
INSTANTIATE_TEST_CASE_P(
VaapiDecoder, DecodeApiTest,
::testing::Values(
TestDecodeFrames::create(g_h264data, YAMI_MIME_H264)));
}
|
add flush unittest
|
unittest: add flush unittest
Signed-off-by: Linda Yu <[email protected]>
|
C++
|
apache-2.0
|
lizhong1008/libyami,YuJiankang/libyami,stripes416/libyami,yizhouwei/libyami,01org/libyami,lizhong1008/libyami,yizhouwei/libyami,01org/libyami,stripes416/libyami,YuJiankang/libyami,YuJiankang/libyami,yizhouwei/libyami,stripes416/libyami,01org/libyami,lizhong1008/libyami
|
10877b1d43782f3dce8349626ad6ad1eca1ce034
|
pandatool/src/mayaprogs/mayaWrapper.cxx
|
pandatool/src/mayaprogs/mayaWrapper.cxx
|
///////////////////////////////////////////////////////////////////////
//
// When multiple versions of maya are installed, maya2egg can
// accidentally use the wrong version of the OpenMaya libraries.
// This small wrapper program alters your PATH, MAYA_LOCATION, etc
// environment variables in order to ensure that maya2egg finds the
// right ligraries.
//
// To use this wrapper, maya2egg must be renamed to maya2egg-wrapped.
// Then, this wrapper program must be installed as maya2egg.
//
///////////////////////////////////////////////////////////////////////
#ifndef MAYAVERSION
#error You must define the symbol MAYAVERSION when compiling mayawrapper.
#endif
#define QUOTESTR(x) #x
#define TOSTRING(x) QUOTESTR(x)
#define _CRT_SECURE_NO_DEPRECATE 1
#ifdef _WIN32
#include <windows.h>
#include <winuser.h>
#include <process.h>
#else
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define _putenv putenv
#endif
#ifdef __APPLE__
#include <sys/malloc.h>
#else
#include <malloc.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <limits.h>
#define PATH_MAX 1024
#ifdef __APPLE__
// This is for _NSGetExecutablePath().
#include <mach-o/dyld.h>
#endif
struct { char *ver, *key; } maya_versions[] = {
{ "MAYA6", "6.0" },
{ "MAYA65", "6.5" },
{ "MAYA7", "7.0" },
{ "MAYA8", "8.0" },
{ "MAYA85", "8.5" },
{ "MAYA2008", "2008" },
{ "MAYA2009", "2009" },
{ "MAYA2010", "2010" },
{ "MAYA2011", "2011"},
{ 0, 0 },
};
char *getVersionNumber(char *ver) {
for (int i=0; maya_versions[i].ver != 0; i++) {
if (strcmp(maya_versions[i].ver, ver)==0) {
return maya_versions[i].key;
}
}
return 0;
}
#if defined(_WIN32)
void getMayaLocation(char *ver, char *loc)
{
char fullkey[1024], *developer;
HKEY hkey; DWORD size, dtype; LONG res; int dev, hive;
for (dev=0; dev<3; dev++) {
switch (dev) {
case 0: developer="Alias|Wavefront"; break;
case 1: developer="Alias"; break;
case 2: developer="Autodesk"; break;
}
sprintf(fullkey, "SOFTWARE\\%s\\Maya\\%s\\Setup\\InstallPath", developer, ver);
for (hive=0; hive<2; hive++) {
loc[0] = 0;
res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, fullkey, 0, KEY_READ | (hive ? 256:0), &hkey);
if (res == ERROR_SUCCESS) {
size=1024;
res = RegQueryValueEx(hkey, "MAYA_INSTALL_LOCATION", NULL, &dtype, (LPBYTE)loc, &size);
if ((res == ERROR_SUCCESS)&&(dtype == REG_SZ)) {
loc[size] = 0;
return;
} else {
loc[0] = 0;
}
RegCloseKey(hkey);
}
}
}
}
void getWrapperName(char *prog)
{
DWORD res;
res = GetModuleFileName(NULL, prog, 1000);
if (res == 0) {
prog[0] = 0;
return;
}
int len = strlen(prog);
if (_stricmp(prog+len-4, ".exe")) {
prog[0] = 0;
return;
}
prog[len-4] = 0;
}
#elif defined(__APPLE__)
void getMayaLocation(char *ver, char *loc)
{
char mpath[64];
sprintf(mpath, "/Applications/Autodesk/maya%s/Maya.app/Contents", ver);
struct stat st;
if(stat(mpath, &st) == 0) {
strcpy(loc, mpath);
} else {
loc[0] = 0;
}
}
void getWrapperName(char *prog)
{
char *pathbuf = new char[PATH_MAX];
uint32_t bufsize = PATH_MAX;
if (_NSGetExecutablePath(pathbuf, &bufsize) == 0) {
strcpy(prog, pathbuf);
} else {
prog[0] = 0;
}
delete[] pathbuf;
}
#else
void getMayaLocation(char *ver, char *loc)
{
char mpath[64];
#if __WORDSIZE == 64
sprintf(mpath, "/usr/autodesk/maya%s-x64", ver);
#else
sprintf(mpath, "/usr/autodesk/maya%s", ver);
#endif
struct stat st;
if(stat(mpath, &st) == 0) {
strcpy(loc, mpath);
} else {
#if __WORDSIZE == 64
sprintf(mpath, "/usr/aw/maya%s-x64", ver);
#else
sprintf(mpath, "/usr/aw/maya%s", ver);
#endif
if(stat(mpath, &st) == 0) {
strcpy(loc, mpath);
} else {
loc[0] = 0;
}
}
}
void getWrapperName(char *prog)
{
char readlinkbuf[PATH_MAX];
int pathlen = readlink("/proc/self/exe", readlinkbuf, PATH_MAX-1);
if (pathlen > 0) {
readlinkbuf[pathlen] = 0;
strcpy(prog, readlinkbuf);
} else {
prog[0] = 0;
}
}
#endif
int main(int argc, char **argv)
{
char loc[PATH_MAX], prog[PATH_MAX];
char *key, *path, *env1, *env2, *env3, *env4;
int nLocLen;
key = getVersionNumber(TOSTRING(MAYAVERSION));
if (key == 0) {
printf("MayaWrapper: unknown maya version %s\n", TOSTRING(MAYAVERSION));
exit(1);
}
getMayaLocation(key, loc);
if (loc[0]==0) {
printf("Cannot locate %s - it does not appear to be installed\n", TOSTRING(MAYAVERSION));
exit(1);
}
getWrapperName(prog);
if (prog[0]==0) {
printf("mayaWrapper cannot determine its own filename (bug)\n");
exit(1);
}
#ifdef _WIN32
strcat(prog, "-wrapped.exe");
#else
strcat(prog, "-wrapped");
#endif
// "loc" == MAYA_LOCATION
// Now set PYTHONHOME & PYTHONPATH. Maya requires this to be
// set and pointing within MAYA_LOCATION, or it might get itself
// confused with another Python installation (e.g. Panda's).
// Finally, prepend PATH with MAYA_LOCATION\bin; as well.
// As of Sept. 2009, at least some WIN32 platforms had
// much difficulty with Maya 2009 egging, e.g., see forums:
// http://www.panda3d.org/phpbb2/viewtopic.php?p=42790
//
// Historically:
// http://www.panda3d.org/phpbb2/viewtopic.php?t=3842
// http://www.panda3d.org/phpbb2/viewtopic.php?t=6468
// http://www.panda3d.org/phpbb2/viewtopic.php?t=6533
// http://www.panda3d.org/phpbb2/viewtopic.php?t=5070
//
// Hoped solution: carry over code that was in mayapath.cxx
// and use that here to set 4 important environment variables:
// MAYA_LOCATION
// PYTHONPATH
// PYTHONHOME
// PATH (add Maya bin to start of this)
// BUT... mayapath.cxx makes use of FILENAME and other code
// from the rest of the Panda build, so for now, to keep this
// wrapper thinner, just correct/verify that the latter 3 environment
// variables are set properly (as they are in mayapath.cxx)
// for use with Maya under WIN32.
// FIRST TRY, keeping PYTHONPATH simple, as just loc\Python, failed.
// SECOND TRY, as coded formerly here (in mayaWrapper.cxx), also fails:
// PYTHONPATH=%s\\bin;%s\\Python;%s\\Python\\DLLs;%s\\Python\\lib;%s\\Python\\lib\\site-packages
// Eventually, solution was found that has AT MOST this (which does NOT match mayapath.cxx....):
// PYTHONPATH=%s\\bin\\python25.zip;%s\\Python\\DLLs;%s\\Python\\lib;%s\\Python\\lib\\plat-win;%s\\Python\\lib\\lib-tk;%s\\bin;%s\\Python;%s\\Python\\lib\\site-packages", loc, loc, loc, loc, loc, loc, loc, loc);
// One attempt to thin down to just the .zip file and the site-packages file works! This seems to be minimum needed
// as removing the .zip file mentioned first will then break again with the dreaded:
// "Invalid Python Environment: Python is unable to find Maya's Python modules"
// Again, this minimal necessary set (for Maya 2009 32-bit at least) does NOT match mayapath.cxx....):
// PYTHONPATH=%s\\bin\\python25.zip;%s\\Python\\lib\\site-packages", loc, loc);
//
#ifdef _WIN32
// Not sure of non-WIN32 environments, but for WIN32,
// verify that terminating directory/folder separator
// character \ is NOT found at end of "loc" string:
nLocLen = strlen(loc);
if (nLocLen > 0 && loc[nLocLen - 1] == '\\')
{
loc[nLocLen - 1] = '\0';
}
path = getenv("PATH");
if (path == 0) path = "";
env1 = (char*)malloc(100 + strlen(loc) + strlen(path));
sprintf(env1, "PATH=%s\\bin;%s", loc, path);
env2 = (char*)malloc(100 + strlen(loc));
sprintf(env2, "MAYA_LOCATION=%s", loc);
env3 = (char*)malloc(100 + strlen(loc));
sprintf(env3, "PYTHONHOME=%s\\Python", loc);
env4 = (char*)malloc(100 + 2*strlen(loc));
// FYI, background on what does Maya (e.g., Maya 2009) expect
// in PYTHONPATH by doing a check of sys.paths in Python
// as discussed in
// http://www.rtrowbridge.com/blog/2008/11/27/maya-python-import-scripts/
// gives this:
// C:\Program Files\Autodesk\Maya2009\bin\python25.zip
// C:\Program Files\Autodesk\Maya2009\Python\DLLs
// C:\Program Files\Autodesk\Maya2009\Python\lib
// C:\Program Files\Autodesk\Maya2009\Python\lib\plat-win
// C:\Program Files\Autodesk\Maya2009\Python\lib\lib-tk
// C:\Program Files\Autodesk\Maya2009\bin
// C:\Program Files\Autodesk\Maya2009\Python
// C:\Program Files\Autodesk\Maya2009\Python\lib\site-packages
// ...
// Experimenting and a check of
// http://www.panda3d.org/phpbb2/viewtopic.php?t=3842
// leads to these 2 items being necessary and hopefully sufficient:
// bin\python25.zip (within loc)
// Python\lib\site-packages (within loc)
// ...so set PYTHONPATH accordingly:
sprintf(env4, "PYTHONPATH=%s\\bin\\python25.zip;%s\\Python\\lib\\site-packages", loc, loc);
// Set environment variables MAYA_LOCATION, PYTHONHOME, PYTHONPATH, PATH
_putenv(env2);
_putenv(env3);
_putenv(env4);
_putenv(env1);
#else
#ifdef __APPLE__
path = getenv("DYLD_LIBRARY_PATH");
if (path == 0) path = "";
env1 = (char*)malloc(100 + strlen(loc) + strlen(path));
sprintf(env1, "DYLD_LIBRARY_PATH=%s/MacOS:%s", loc, path);
env3 = (char*)malloc(100 + strlen(loc));
sprintf(env3, "PYTHONHOME=%s/Frameworks/Python.framework/Versions/Current", loc);
_putenv(env3);
#else
path = getenv("LD_LIBRARY_PATH");
if (path == 0) path = "";
env1 = (char*)malloc(100 + strlen(loc) + strlen(path));
sprintf(env1, "LD_LIBRARY_PATH=%s/lib:%s", loc, path);
#endif // __APPLE__
env2 = (char*)malloc(100 + strlen(loc));
sprintf(env2, "MAYA_LOCATION=%s", loc);
_putenv(env1);
_putenv(env2);
#endif // _WIN32
#ifdef _WIN32
STARTUPINFO si; PROCESS_INFORMATION pi;
char *cmd;
cmd = GetCommandLine();
memset(&si, 0, sizeof(si));
si.cb = sizeof(STARTUPINFO);
if (CreateProcess(prog, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
WaitForSingleObject(pi.hProcess, INFINITE);
exit(0);
} else {
printf("Could not launch %s\n", prog);
exit(1);
}
#else
if (execvp(prog, argv) == 0) {
exit(0);
} else {
printf("Could not launch %s\n", prog);
exit(1);
}
#endif
}
|
///////////////////////////////////////////////////////////////////////
//
// When multiple versions of maya are installed, maya2egg can
// accidentally use the wrong version of the OpenMaya libraries.
// This small wrapper program alters your PATH, MAYA_LOCATION, etc
// environment variables in order to ensure that maya2egg finds the
// right ligraries.
//
// To use this wrapper, maya2egg must be renamed to maya2egg-wrapped.
// Then, this wrapper program must be installed as maya2egg.
//
///////////////////////////////////////////////////////////////////////
#ifndef MAYAVERSION
#error You must define the symbol MAYAVERSION when compiling mayawrapper.
#endif
#define QUOTESTR(x) #x
#define TOSTRING(x) QUOTESTR(x)
#define _CRT_SECURE_NO_DEPRECATE 1
#ifdef _WIN32
#include <windows.h>
#include <winuser.h>
#include <process.h>
#else
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define _putenv putenv
#endif
#ifdef __APPLE__
#include <sys/malloc.h>
#else
#include <malloc.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <limits.h>
#define PATH_MAX 1024
#ifdef __APPLE__
// This is for _NSGetExecutablePath().
#include <mach-o/dyld.h>
#endif
struct { char *ver, *key; } maya_versions[] = {
{ "MAYA6", "6.0" },
{ "MAYA65", "6.5" },
{ "MAYA7", "7.0" },
{ "MAYA8", "8.0" },
{ "MAYA85", "8.5" },
{ "MAYA2008", "2008" },
{ "MAYA2009", "2009" },
{ "MAYA2010", "2010" },
{ "MAYA2011", "2011"},
{ 0, 0 },
};
char *getVersionNumber(char *ver) {
for (int i=0; maya_versions[i].ver != 0; i++) {
if (strcmp(maya_versions[i].ver, ver)==0) {
return maya_versions[i].key;
}
}
return 0;
}
#if defined(_WIN32)
void getMayaLocation(char *ver, char *loc)
{
char fullkey[1024], *developer;
HKEY hkey; DWORD size, dtype; LONG res; int dev, hive;
for (dev=0; dev<3; dev++) {
switch (dev) {
case 0: developer="Alias|Wavefront"; break;
case 1: developer="Alias"; break;
case 2: developer="Autodesk"; break;
}
sprintf(fullkey, "SOFTWARE\\%s\\Maya\\%s\\Setup\\InstallPath", developer, ver);
for (hive=0; hive<2; hive++) {
loc[0] = 0;
res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, fullkey, 0, KEY_READ | (hive ? 256:0), &hkey);
if (res == ERROR_SUCCESS) {
size=1024;
res = RegQueryValueEx(hkey, "MAYA_INSTALL_LOCATION", NULL, &dtype, (LPBYTE)loc, &size);
if ((res == ERROR_SUCCESS)&&(dtype == REG_SZ)) {
loc[size] = 0;
return;
} else {
loc[0] = 0;
}
RegCloseKey(hkey);
}
}
}
}
void getWrapperName(char *prog)
{
DWORD res;
res = GetModuleFileName(NULL, prog, 1000);
if (res == 0) {
prog[0] = 0;
return;
}
int len = strlen(prog);
if (_stricmp(prog+len-4, ".exe")) {
prog[0] = 0;
return;
}
prog[len-4] = 0;
}
#elif defined(__APPLE__)
void getMayaLocation(char *ver, char *loc)
{
char mpath[64];
sprintf(mpath, "/Applications/Autodesk/maya%s/Maya.app/Contents", ver);
struct stat st;
if(stat(mpath, &st) == 0) {
strcpy(loc, mpath);
} else {
loc[0] = 0;
}
}
void getWrapperName(char *prog)
{
char *pathbuf = new char[PATH_MAX];
uint32_t bufsize = PATH_MAX;
if (_NSGetExecutablePath(pathbuf, &bufsize) == 0) {
strcpy(prog, pathbuf);
} else {
prog[0] = 0;
}
delete[] pathbuf;
}
#else
void getMayaLocation(char *ver, char *loc)
{
char mpath[64];
#if __WORDSIZE == 64
sprintf(mpath, "/usr/autodesk/maya%s-x64", ver);
#else
sprintf(mpath, "/usr/autodesk/maya%s", ver);
#endif
struct stat st;
if(stat(mpath, &st) == 0) {
strcpy(loc, mpath);
} else {
#if __WORDSIZE == 64
sprintf(mpath, "/usr/aw/maya%s-x64", ver);
#else
sprintf(mpath, "/usr/aw/maya%s", ver);
#endif
if(stat(mpath, &st) == 0) {
strcpy(loc, mpath);
} else {
loc[0] = 0;
}
}
}
void getWrapperName(char *prog)
{
char readlinkbuf[PATH_MAX];
int pathlen = readlink("/proc/self/exe", readlinkbuf, PATH_MAX-1);
if (pathlen > 0) {
readlinkbuf[pathlen] = 0;
strcpy(prog, readlinkbuf);
} else {
prog[0] = 0;
}
}
#endif
int main(int argc, char **argv)
{
char loc[PATH_MAX], prog[PATH_MAX];
char *key, *path, *env1, *env2, *env3, *env4;
int nLocLen;
key = getVersionNumber(TOSTRING(MAYAVERSION));
if (key == 0) {
printf("MayaWrapper: unknown maya version %s\n", TOSTRING(MAYAVERSION));
exit(1);
}
getMayaLocation(key, loc);
if (loc[0]==0) {
printf("Cannot locate %s - it does not appear to be installed\n", TOSTRING(MAYAVERSION));
exit(1);
}
getWrapperName(prog);
if (prog[0]==0) {
printf("mayaWrapper cannot determine its own filename (bug)\n");
exit(1);
}
#ifdef _WIN32
strcat(prog, "-wrapped.exe");
#else
strcat(prog, "-wrapped");
#endif
// "loc" == MAYA_LOCATION
// Now set PYTHONHOME & PYTHONPATH. Maya requires this to be
// set and pointing within MAYA_LOCATION, or it might get itself
// confused with another Python installation (e.g. Panda's).
// Finally, prepend PATH with MAYA_LOCATION\bin; as well.
// As of Sept. 2009, at least some WIN32 platforms had
// much difficulty with Maya 2009 egging, e.g., see forums:
// http://www.panda3d.org/phpbb2/viewtopic.php?p=42790
//
// Historically:
// http://www.panda3d.org/phpbb2/viewtopic.php?t=3842
// http://www.panda3d.org/phpbb2/viewtopic.php?t=6468
// http://www.panda3d.org/phpbb2/viewtopic.php?t=6533
// http://www.panda3d.org/phpbb2/viewtopic.php?t=5070
//
// Hoped solution: carry over code that was in mayapath.cxx
// and use that here to set 4 important environment variables:
// MAYA_LOCATION
// PYTHONPATH
// PYTHONHOME
// PATH (add Maya bin to start of this)
// BUT... mayapath.cxx makes use of FILENAME and other code
// from the rest of the Panda build, so for now, to keep this
// wrapper thinner, just correct/verify that the latter 3 environment
// variables are set properly (as they are in mayapath.cxx)
// for use with Maya under WIN32.
// FIRST TRY, keeping PYTHONPATH simple, as just loc\Python, failed.
// SECOND TRY, as coded formerly here (in mayaWrapper.cxx), also fails:
// PYTHONPATH=%s\\bin;%s\\Python;%s\\Python\\DLLs;%s\\Python\\lib;%s\\Python\\lib\\site-packages
// Eventually, solution was found that has AT MOST this (which does NOT match mayapath.cxx....):
// PYTHONPATH=%s\\bin\\python25.zip;%s\\Python\\DLLs;%s\\Python\\lib;%s\\Python\\lib\\plat-win;%s\\Python\\lib\\lib-tk;%s\\bin;%s\\Python;%s\\Python\\lib\\site-packages", loc, loc, loc, loc, loc, loc, loc, loc);
// One attempt to thin down to just the .zip file and the site-packages file works! This seems to be minimum needed
// as removing the .zip file mentioned first will then break again with the dreaded:
// "Invalid Python Environment: Python is unable to find Maya's Python modules"
// Again, this minimal necessary set (for Maya 2009 32-bit at least) does NOT match mayapath.cxx....):
// PYTHONPATH=%s\\bin\\python25.zip;%s\\Python\\lib\\site-packages", loc, loc);
//
#ifdef _WIN32
// Not sure of non-WIN32 environments, but for WIN32,
// verify that terminating directory/folder separator
// character \ is NOT found at end of "loc" string:
nLocLen = strlen(loc);
if (nLocLen > 0 && loc[nLocLen - 1] == '\\')
{
loc[nLocLen - 1] = '\0';
}
path = getenv("PATH");
if (path == 0) path = "";
env1 = (char*)malloc(100 + strlen(loc) + strlen(path));
sprintf(env1, "PATH=%s\\bin;%s", loc, path);
env2 = (char*)malloc(100 + strlen(loc));
sprintf(env2, "MAYA_LOCATION=%s", loc);
env3 = (char*)malloc(100 + strlen(loc));
sprintf(env3, "PYTHONHOME=%s\\Python", loc);
env4 = (char*)malloc(100 + 2*strlen(loc));
// FYI, background on what does Maya (e.g., Maya 2009) expect
// in PYTHONPATH by doing a check of sys.paths in Python
// as discussed in
// http://www.rtrowbridge.com/blog/2008/11/27/maya-python-import-scripts/
// gives this:
// C:\Program Files\Autodesk\Maya2009\bin\python25.zip
// C:\Program Files\Autodesk\Maya2009\Python\DLLs
// C:\Program Files\Autodesk\Maya2009\Python\lib
// C:\Program Files\Autodesk\Maya2009\Python\lib\plat-win
// C:\Program Files\Autodesk\Maya2009\Python\lib\lib-tk
// C:\Program Files\Autodesk\Maya2009\bin
// C:\Program Files\Autodesk\Maya2009\Python
// C:\Program Files\Autodesk\Maya2009\Python\lib\site-packages
// ...
// Experimenting and a check of
// http://www.panda3d.org/phpbb2/viewtopic.php?t=3842
// leads to these 2 items being necessary and hopefully sufficient:
// bin\python25.zip (within loc)
// Python\lib\site-packages (within loc)
// ...so set PYTHONPATH accordingly:
if (strcmp(key, "2011") == 0) {
//Maya 2011 is built against Python 2.6 so look for that one instead
sprintf(env4, "PYTHONPATH=%s\\bin\\python26.zip;%s\\Python\\lib\\site-packages", loc, loc);
} else {
sprintf(env4, "PYTHONPATH=%s\\bin\\python25.zip;%s\\Python\\lib\\site-packages", loc, loc);
}
// Set environment variables MAYA_LOCATION, PYTHONHOME, PYTHONPATH, PATH
_putenv(env2);
_putenv(env3);
_putenv(env4);
_putenv(env1);
#else
#ifdef __APPLE__
path = getenv("DYLD_LIBRARY_PATH");
if (path == 0) path = "";
env1 = (char*)malloc(100 + strlen(loc) + strlen(path));
sprintf(env1, "DYLD_LIBRARY_PATH=%s/MacOS:%s", loc, path);
env3 = (char*)malloc(100 + strlen(loc));
sprintf(env3, "PYTHONHOME=%s/Frameworks/Python.framework/Versions/Current", loc);
_putenv(env3);
#else
path = getenv("LD_LIBRARY_PATH");
if (path == 0) path = "";
env1 = (char*)malloc(100 + strlen(loc) + strlen(path));
sprintf(env1, "LD_LIBRARY_PATH=%s/lib:%s", loc, path);
#endif // __APPLE__
env2 = (char*)malloc(100 + strlen(loc));
sprintf(env2, "MAYA_LOCATION=%s", loc);
_putenv(env1);
_putenv(env2);
#endif // _WIN32
#ifdef _WIN32
STARTUPINFO si; PROCESS_INFORMATION pi;
char *cmd;
cmd = GetCommandLine();
memset(&si, 0, sizeof(si));
si.cb = sizeof(STARTUPINFO);
if (CreateProcess(prog, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
WaitForSingleObject(pi.hProcess, INFINITE);
exit(0);
} else {
printf("Could not launch %s\n", prog);
exit(1);
}
#else
if (execvp(prog, argv) == 0) {
exit(0);
} else {
printf("Could not launch %s\n", prog);
exit(1);
}
#endif
}
|
Update for Maya 2011, which uses python26.dll rather than python25.dll
|
Update for Maya 2011, which uses python26.dll rather than python25.dll
|
C++
|
bsd-3-clause
|
hj3938/panda3d,jjkoletar/panda3d,hj3938/panda3d,chandler14362/panda3d,cc272309126/panda3d,brakhane/panda3d,ee08b397/panda3d,cc272309126/panda3d,jjkoletar/panda3d,grimfang/panda3d,ee08b397/panda3d,chandler14362/panda3d,matthiascy/panda3d,mgracer48/panda3d,hj3938/panda3d,Wilee999/panda3d,tobspr/panda3d,ee08b397/panda3d,hj3938/panda3d,brakhane/panda3d,matthiascy/panda3d,chandler14362/panda3d,jjkoletar/panda3d,cc272309126/panda3d,cc272309126/panda3d,brakhane/panda3d,ee08b397/panda3d,grimfang/panda3d,grimfang/panda3d,jjkoletar/panda3d,chandler14362/panda3d,tobspr/panda3d,ee08b397/panda3d,matthiascy/panda3d,chandler14362/panda3d,tobspr/panda3d,mgracer48/panda3d,brakhane/panda3d,mgracer48/panda3d,mgracer48/panda3d,Wilee999/panda3d,matthiascy/panda3d,brakhane/panda3d,grimfang/panda3d,jjkoletar/panda3d,chandler14362/panda3d,mgracer48/panda3d,matthiascy/panda3d,tobspr/panda3d,grimfang/panda3d,matthiascy/panda3d,mgracer48/panda3d,jjkoletar/panda3d,tobspr/panda3d,tobspr/panda3d,grimfang/panda3d,brakhane/panda3d,tobspr/panda3d,brakhane/panda3d,hj3938/panda3d,ee08b397/panda3d,ee08b397/panda3d,matthiascy/panda3d,matthiascy/panda3d,brakhane/panda3d,chandler14362/panda3d,tobspr/panda3d,Wilee999/panda3d,grimfang/panda3d,mgracer48/panda3d,hj3938/panda3d,Wilee999/panda3d,jjkoletar/panda3d,hj3938/panda3d,cc272309126/panda3d,jjkoletar/panda3d,hj3938/panda3d,Wilee999/panda3d,mgracer48/panda3d,chandler14362/panda3d,cc272309126/panda3d,Wilee999/panda3d,tobspr/panda3d,ee08b397/panda3d,cc272309126/panda3d,Wilee999/panda3d,chandler14362/panda3d,hj3938/panda3d,matthiascy/panda3d,tobspr/panda3d,grimfang/panda3d,ee08b397/panda3d,grimfang/panda3d,Wilee999/panda3d,jjkoletar/panda3d,grimfang/panda3d,Wilee999/panda3d,cc272309126/panda3d,mgracer48/panda3d,cc272309126/panda3d,chandler14362/panda3d,brakhane/panda3d
|
02569adfd492d84e2e568f3512a67ab45b96fc34
|
webrtc/media/engine/simulcast.cc
|
webrtc/media/engine/simulcast.cc
|
/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include "webrtc/base/arraysize.h"
#include "webrtc/base/logging.h"
#include "webrtc/media/base/streamparams.h"
#include "webrtc/media/engine/constants.h"
#include "webrtc/media/engine/simulcast.h"
#include "webrtc/system_wrappers/include/field_trial.h"
namespace cricket {
struct SimulcastFormat {
int width;
int height;
// The maximum number of simulcast layers can be used for
// resolutions at |widthxheigh|.
size_t max_layers;
// The maximum bitrate for encoding stream at |widthxheight|, when we are
// not sending the next higher spatial stream.
int max_bitrate_kbps;
// The target bitrate for encoding stream at |widthxheight|, when this layer
// is not the highest layer (i.e., when we are sending another higher spatial
// stream).
int target_bitrate_kbps;
// The minimum bitrate needed for encoding stream at |widthxheight|.
int min_bitrate_kbps;
};
// These tables describe from which resolution we can use how many
// simulcast layers at what bitrates (maximum, target, and minimum).
// Important!! Keep this table from high resolution to low resolution.
const SimulcastFormat kSimulcastFormats[] = {
{1920, 1080, 3, 5000, 4000, 800},
{1280, 720, 3, 2500, 2500, 600},
{960, 540, 3, 900, 900, 450},
{640, 360, 2, 700, 500, 150},
{480, 270, 2, 450, 350, 150},
{320, 180, 1, 200, 150, 30},
{0, 0, 1, 200, 150, 30}
};
const int kDefaultScreenshareSimulcastStreams = 2;
// Multiway: Number of temporal layers for each simulcast stream, for maximum
// possible number of simulcast streams |kMaxSimulcastStreams|. The array
// goes from lowest resolution at position 0 to highest resolution.
// For example, first three elements correspond to say: QVGA, VGA, WHD.
static const int
kDefaultConferenceNumberOfTemporalLayers[webrtc::kMaxSimulcastStreams] =
{3, 3, 3, 3};
void GetSimulcastSsrcs(const StreamParams& sp, std::vector<uint32_t>* ssrcs) {
const SsrcGroup* sim_group = sp.get_ssrc_group(kSimSsrcGroupSemantics);
if (sim_group) {
ssrcs->insert(
ssrcs->end(), sim_group->ssrcs.begin(), sim_group->ssrcs.end());
}
}
void MaybeExchangeWidthHeight(int* width, int* height) {
// |kSimulcastFormats| assumes |width| >= |height|. If not, exchange them
// before comparing.
if (*width < *height) {
int temp = *width;
*width = *height;
*height = temp;
}
}
int FindSimulcastFormatIndex(int width, int height) {
MaybeExchangeWidthHeight(&width, &height);
for (uint32_t i = 0; i < arraysize(kSimulcastFormats); ++i) {
if (width * height >=
kSimulcastFormats[i].width * kSimulcastFormats[i].height) {
return i;
}
}
return -1;
}
int FindSimulcastFormatIndex(int width, int height, size_t max_layers) {
MaybeExchangeWidthHeight(&width, &height);
for (uint32_t i = 0; i < arraysize(kSimulcastFormats); ++i) {
if (width * height >=
kSimulcastFormats[i].width * kSimulcastFormats[i].height &&
max_layers == kSimulcastFormats[i].max_layers) {
return i;
}
}
return -1;
}
// Simulcast stream width and height must both be dividable by
// |2 ^ simulcast_layers - 1|.
int NormalizeSimulcastSize(int size, size_t simulcast_layers) {
const int base2_exponent = static_cast<int>(simulcast_layers) - 1;
return ((size >> base2_exponent) << base2_exponent);
}
size_t FindSimulcastMaxLayers(int width, int height) {
int index = FindSimulcastFormatIndex(width, height);
if (index == -1) {
return -1;
}
return kSimulcastFormats[index].max_layers;
}
// TODO(marpan): Investigate if we should return 0 instead of -1 in
// FindSimulcast[Max/Target/Min]Bitrate functions below, since the
// codec struct max/min/targeBitrates are unsigned.
int FindSimulcastMaxBitrateBps(int width, int height) {
const int format_index = FindSimulcastFormatIndex(width, height);
if (format_index == -1) {
return -1;
}
return kSimulcastFormats[format_index].max_bitrate_kbps * 1000;
}
int FindSimulcastTargetBitrateBps(int width, int height) {
const int format_index = FindSimulcastFormatIndex(width, height);
if (format_index == -1) {
return -1;
}
return kSimulcastFormats[format_index].target_bitrate_kbps * 1000;
}
int FindSimulcastMinBitrateBps(int width, int height) {
const int format_index = FindSimulcastFormatIndex(width, height);
if (format_index == -1) {
return -1;
}
return kSimulcastFormats[format_index].min_bitrate_kbps * 1000;
}
bool SlotSimulcastMaxResolution(size_t max_layers, int* width, int* height) {
int index = FindSimulcastFormatIndex(*width, *height, max_layers);
if (index == -1) {
LOG(LS_ERROR) << "SlotSimulcastMaxResolution";
return false;
}
*width = kSimulcastFormats[index].width;
*height = kSimulcastFormats[index].height;
LOG(LS_INFO) << "SlotSimulcastMaxResolution to width:" << *width
<< " height:" << *height;
return true;
}
int GetTotalMaxBitrateBps(const std::vector<webrtc::VideoStream>& streams) {
int total_max_bitrate_bps = 0;
for (size_t s = 0; s < streams.size() - 1; ++s) {
total_max_bitrate_bps += streams[s].target_bitrate_bps;
}
total_max_bitrate_bps += streams.back().max_bitrate_bps;
return total_max_bitrate_bps;
}
std::vector<webrtc::VideoStream> GetSimulcastConfig(size_t max_streams,
int width,
int height,
int max_bitrate_bps,
int max_qp,
int max_framerate,
bool is_screencast) {
size_t num_simulcast_layers;
if (is_screencast) {
num_simulcast_layers =
UseSimulcastScreenshare() ? kDefaultScreenshareSimulcastStreams : 1;
} else {
num_simulcast_layers = FindSimulcastMaxLayers(width, height);
}
if (num_simulcast_layers > max_streams) {
// If the number of SSRCs in the group differs from our target
// number of simulcast streams for current resolution, switch down
// to a resolution that matches our number of SSRCs.
if (!SlotSimulcastMaxResolution(max_streams, &width, &height)) {
return std::vector<webrtc::VideoStream>();
}
num_simulcast_layers = max_streams;
}
std::vector<webrtc::VideoStream> streams;
streams.resize(num_simulcast_layers);
if (!is_screencast) {
// Format width and height has to be divisible by |2 ^ number_streams - 1|.
width = NormalizeSimulcastSize(width, num_simulcast_layers);
height = NormalizeSimulcastSize(height, num_simulcast_layers);
}
// Add simulcast sub-streams from lower resolution to higher resolutions.
// Add simulcast streams, from highest resolution (|s| = number_streams -1)
// to lowest resolution at |s| = 0.
for (size_t s = num_simulcast_layers - 1;; --s) {
streams[s].width = width;
streams[s].height = height;
// TODO(pbos): Fill actual temporal-layer bitrate thresholds.
streams[s].max_qp = max_qp;
if (is_screencast && s == 0) {
ScreenshareLayerConfig config = ScreenshareLayerConfig::GetDefault();
// For legacy screenshare in conference mode, tl0 and tl1 bitrates are
// piggybacked on the VideoCodec struct as target and max bitrates,
// respectively. See eg. webrtc::VP8EncoderImpl::SetRates().
streams[s].min_bitrate_bps = kMinVideoBitrateKbps * 1000;
streams[s].target_bitrate_bps = config.tl0_bitrate_kbps * 1000;
streams[s].max_bitrate_bps = config.tl1_bitrate_kbps * 1000;
streams[s].temporal_layer_thresholds_bps.clear();
streams[s].temporal_layer_thresholds_bps.push_back(
config.tl0_bitrate_kbps * 1000);
streams[s].max_framerate = 5;
} else {
streams[s].temporal_layer_thresholds_bps.resize(
kDefaultConferenceNumberOfTemporalLayers[s] - 1);
streams[s].max_bitrate_bps = FindSimulcastMaxBitrateBps(width, height);
streams[s].target_bitrate_bps =
FindSimulcastTargetBitrateBps(width, height);
streams[s].min_bitrate_bps = FindSimulcastMinBitrateBps(width, height);
streams[s].max_framerate = max_framerate;
}
if (!is_screencast) {
width /= 2;
height /= 2;
}
if (s == 0)
break;
}
// Spend additional bits to boost the max stream.
int bitrate_left_bps = max_bitrate_bps - GetTotalMaxBitrateBps(streams);
if (bitrate_left_bps > 0) {
streams.back().max_bitrate_bps += bitrate_left_bps;
}
return streams;
}
static const int kScreenshareMinBitrateKbps = 50;
static const int kScreenshareMaxBitrateKbps = 6000;
static const int kScreenshareDefaultTl0BitrateKbps = 200;
static const int kScreenshareDefaultTl1BitrateKbps = 1000;
static const char* kScreencastLayerFieldTrialName =
"WebRTC-ScreenshareLayerRates";
static const char* kSimulcastScreenshareFieldTrialName =
"WebRTC-SimulcastScreenshare";
ScreenshareLayerConfig::ScreenshareLayerConfig(int tl0_bitrate, int tl1_bitrate)
: tl0_bitrate_kbps(tl0_bitrate), tl1_bitrate_kbps(tl1_bitrate) {
}
ScreenshareLayerConfig ScreenshareLayerConfig::GetDefault() {
std::string group =
webrtc::field_trial::FindFullName(kScreencastLayerFieldTrialName);
ScreenshareLayerConfig config(kScreenshareDefaultTl0BitrateKbps,
kScreenshareDefaultTl1BitrateKbps);
if (!group.empty() && !FromFieldTrialGroup(group, &config)) {
LOG(LS_WARNING) << "Unable to parse WebRTC-ScreenshareLayerRates"
" field trial group: '" << group << "'.";
}
return config;
}
bool ScreenshareLayerConfig::FromFieldTrialGroup(
const std::string& group,
ScreenshareLayerConfig* config) {
// Parse field trial group name, containing bitrates for tl0 and tl1.
int tl0_bitrate;
int tl1_bitrate;
if (sscanf(group.c_str(), "%d-%d", &tl0_bitrate, &tl1_bitrate) != 2) {
return false;
}
// Sanity check.
if (tl0_bitrate < kScreenshareMinBitrateKbps ||
tl0_bitrate > kScreenshareMaxBitrateKbps ||
tl1_bitrate < kScreenshareMinBitrateKbps ||
tl1_bitrate > kScreenshareMaxBitrateKbps || tl0_bitrate > tl1_bitrate) {
return false;
}
config->tl0_bitrate_kbps = tl0_bitrate;
config->tl1_bitrate_kbps = tl1_bitrate;
return true;
}
bool UseSimulcastScreenshare() {
return webrtc::field_trial::IsEnabled(kSimulcastScreenshareFieldTrialName);
}
} // namespace cricket
|
/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include "webrtc/base/arraysize.h"
#include "webrtc/base/logging.h"
#include "webrtc/media/base/streamparams.h"
#include "webrtc/media/engine/constants.h"
#include "webrtc/media/engine/simulcast.h"
#include "webrtc/system_wrappers/include/field_trial.h"
namespace cricket {
struct SimulcastFormat {
int width;
int height;
// The maximum number of simulcast layers can be used for
// resolutions at |widthxheigh|.
size_t max_layers;
// The maximum bitrate for encoding stream at |widthxheight|, when we are
// not sending the next higher spatial stream.
int max_bitrate_kbps;
// The target bitrate for encoding stream at |widthxheight|, when this layer
// is not the highest layer (i.e., when we are sending another higher spatial
// stream).
int target_bitrate_kbps;
// The minimum bitrate needed for encoding stream at |widthxheight|.
int min_bitrate_kbps;
};
// These tables describe from which resolution we can use how many
// simulcast layers at what bitrates (maximum, target, and minimum).
// Important!! Keep this table from high resolution to low resolution.
const SimulcastFormat kSimulcastFormats[] = {
{1920, 1080, 3, 5000, 4000, 800},
{1280, 720, 3, 2500, 2500, 600},
{960, 540, 3, 900, 900, 450},
{640, 360, 2, 700, 500, 150},
{480, 270, 2, 450, 350, 150},
{320, 180, 1, 200, 150, 30},
{0, 0, 1, 200, 150, 30}
};
const int kMaxScreenshareSimulcastStreams = 2;
// Multiway: Number of temporal layers for each simulcast stream, for maximum
// possible number of simulcast streams |kMaxSimulcastStreams|. The array
// goes from lowest resolution at position 0 to highest resolution.
// For example, first three elements correspond to say: QVGA, VGA, WHD.
static const int
kDefaultConferenceNumberOfTemporalLayers[webrtc::kMaxSimulcastStreams] =
{3, 3, 3, 3};
void GetSimulcastSsrcs(const StreamParams& sp, std::vector<uint32_t>* ssrcs) {
const SsrcGroup* sim_group = sp.get_ssrc_group(kSimSsrcGroupSemantics);
if (sim_group) {
ssrcs->insert(
ssrcs->end(), sim_group->ssrcs.begin(), sim_group->ssrcs.end());
}
}
void MaybeExchangeWidthHeight(int* width, int* height) {
// |kSimulcastFormats| assumes |width| >= |height|. If not, exchange them
// before comparing.
if (*width < *height) {
int temp = *width;
*width = *height;
*height = temp;
}
}
int FindSimulcastFormatIndex(int width, int height) {
MaybeExchangeWidthHeight(&width, &height);
for (uint32_t i = 0; i < arraysize(kSimulcastFormats); ++i) {
if (width * height >=
kSimulcastFormats[i].width * kSimulcastFormats[i].height) {
return i;
}
}
return -1;
}
int FindSimulcastFormatIndex(int width, int height, size_t max_layers) {
MaybeExchangeWidthHeight(&width, &height);
for (uint32_t i = 0; i < arraysize(kSimulcastFormats); ++i) {
if (width * height >=
kSimulcastFormats[i].width * kSimulcastFormats[i].height &&
max_layers == kSimulcastFormats[i].max_layers) {
return i;
}
}
return -1;
}
// Simulcast stream width and height must both be dividable by
// |2 ^ simulcast_layers - 1|.
int NormalizeSimulcastSize(int size, size_t simulcast_layers) {
const int base2_exponent = static_cast<int>(simulcast_layers) - 1;
return ((size >> base2_exponent) << base2_exponent);
}
size_t FindSimulcastMaxLayers(int width, int height) {
int index = FindSimulcastFormatIndex(width, height);
if (index == -1) {
return -1;
}
return kSimulcastFormats[index].max_layers;
}
// TODO(marpan): Investigate if we should return 0 instead of -1 in
// FindSimulcast[Max/Target/Min]Bitrate functions below, since the
// codec struct max/min/targeBitrates are unsigned.
int FindSimulcastMaxBitrateBps(int width, int height) {
const int format_index = FindSimulcastFormatIndex(width, height);
if (format_index == -1) {
return -1;
}
return kSimulcastFormats[format_index].max_bitrate_kbps * 1000;
}
int FindSimulcastTargetBitrateBps(int width, int height) {
const int format_index = FindSimulcastFormatIndex(width, height);
if (format_index == -1) {
return -1;
}
return kSimulcastFormats[format_index].target_bitrate_kbps * 1000;
}
int FindSimulcastMinBitrateBps(int width, int height) {
const int format_index = FindSimulcastFormatIndex(width, height);
if (format_index == -1) {
return -1;
}
return kSimulcastFormats[format_index].min_bitrate_kbps * 1000;
}
bool SlotSimulcastMaxResolution(size_t max_layers, int* width, int* height) {
int index = FindSimulcastFormatIndex(*width, *height, max_layers);
if (index == -1) {
LOG(LS_ERROR) << "SlotSimulcastMaxResolution";
return false;
}
*width = kSimulcastFormats[index].width;
*height = kSimulcastFormats[index].height;
LOG(LS_INFO) << "SlotSimulcastMaxResolution to width:" << *width
<< " height:" << *height;
return true;
}
int GetTotalMaxBitrateBps(const std::vector<webrtc::VideoStream>& streams) {
int total_max_bitrate_bps = 0;
for (size_t s = 0; s < streams.size() - 1; ++s) {
total_max_bitrate_bps += streams[s].target_bitrate_bps;
}
total_max_bitrate_bps += streams.back().max_bitrate_bps;
return total_max_bitrate_bps;
}
std::vector<webrtc::VideoStream> GetSimulcastConfig(size_t max_streams,
int width,
int height,
int max_bitrate_bps,
int max_qp,
int max_framerate,
bool is_screencast) {
size_t num_simulcast_layers;
if (is_screencast) {
if (UseSimulcastScreenshare()) {
num_simulcast_layers =
std::min<int>(max_streams, kMaxScreenshareSimulcastStreams);
} else {
num_simulcast_layers = 1;
}
} else {
num_simulcast_layers = FindSimulcastMaxLayers(width, height);
}
if (num_simulcast_layers > max_streams) {
// If the number of SSRCs in the group differs from our target
// number of simulcast streams for current resolution, switch down
// to a resolution that matches our number of SSRCs.
if (!SlotSimulcastMaxResolution(max_streams, &width, &height)) {
return std::vector<webrtc::VideoStream>();
}
num_simulcast_layers = max_streams;
}
std::vector<webrtc::VideoStream> streams;
streams.resize(num_simulcast_layers);
if (is_screencast) {
ScreenshareLayerConfig config = ScreenshareLayerConfig::GetDefault();
// For legacy screenshare in conference mode, tl0 and tl1 bitrates are
// piggybacked on the VideoCodec struct as target and max bitrates,
// respectively. See eg. webrtc::VP8EncoderImpl::SetRates().
streams[0].width = width;
streams[0].height = height;
streams[0].max_qp = max_qp;
streams[0].max_framerate = 5;
streams[0].min_bitrate_bps = kMinVideoBitrateKbps * 1000;
streams[0].target_bitrate_bps = config.tl0_bitrate_kbps * 1000;
streams[0].max_bitrate_bps = config.tl1_bitrate_kbps * 1000;
streams[0].temporal_layer_thresholds_bps.clear();
streams[0].temporal_layer_thresholds_bps.push_back(config.tl0_bitrate_kbps *
1000);
// With simulcast enabled, add another spatial layer. This one will have a
// more normal layout, with the regular 3 temporal layer pattern and no fps
// restrictions. The base simulcast stream will still use legacy setup.
if (num_simulcast_layers == kMaxScreenshareSimulcastStreams) {
// Add optional upper simulcast layer.
// Lowest temporal layers of a 3 layer setup will have 40% of the total
// bitrate allocation for that stream. Make sure the gap between the
// target of the lower stream and first temporal layer of the higher one
// is at most 2x the bitrate, so that upswitching is not hampered by
// stalled bitrate estimates.
int max_bitrate_bps = 2 * ((streams[0].target_bitrate_bps * 10) / 4);
// Cap max bitrate so it isn't overly high for the given resolution.
max_bitrate_bps = std::min<int>(
max_bitrate_bps, FindSimulcastMaxBitrateBps(width, height));
streams[1].width = width;
streams[1].height = height;
streams[1].max_qp = max_qp;
streams[1].max_framerate = max_framerate;
// Three temporal layers means two thresholds.
streams[1].temporal_layer_thresholds_bps.resize(2);
streams[1].min_bitrate_bps = streams[0].target_bitrate_bps * 2;
streams[1].target_bitrate_bps = max_bitrate_bps;
streams[1].max_bitrate_bps = max_bitrate_bps;
}
} else {
// Format width and height has to be divisible by |2 ^ number_streams - 1|.
width = NormalizeSimulcastSize(width, num_simulcast_layers);
height = NormalizeSimulcastSize(height, num_simulcast_layers);
// Add simulcast sub-streams from lower resolution to higher resolutions.
// Add simulcast streams, from highest resolution (|s| = number_streams -1)
// to lowest resolution at |s| = 0.
for (size_t s = num_simulcast_layers - 1;; --s) {
streams[s].width = width;
streams[s].height = height;
// TODO(pbos): Fill actual temporal-layer bitrate thresholds.
streams[s].max_qp = max_qp;
streams[s].temporal_layer_thresholds_bps.resize(
kDefaultConferenceNumberOfTemporalLayers[s] - 1);
streams[s].max_bitrate_bps = FindSimulcastMaxBitrateBps(width, height);
streams[s].target_bitrate_bps =
FindSimulcastTargetBitrateBps(width, height);
streams[s].min_bitrate_bps = FindSimulcastMinBitrateBps(width, height);
streams[s].max_framerate = max_framerate;
width /= 2;
height /= 2;
if (s == 0)
break;
}
// Spend additional bits to boost the max stream.
int bitrate_left_bps = max_bitrate_bps - GetTotalMaxBitrateBps(streams);
if (bitrate_left_bps > 0) {
streams.back().max_bitrate_bps += bitrate_left_bps;
}
}
return streams;
}
static const int kScreenshareMinBitrateKbps = 50;
static const int kScreenshareMaxBitrateKbps = 6000;
static const int kScreenshareDefaultTl0BitrateKbps = 200;
static const int kScreenshareDefaultTl1BitrateKbps = 1000;
static const char* kScreencastLayerFieldTrialName =
"WebRTC-ScreenshareLayerRates";
static const char* kSimulcastScreenshareFieldTrialName =
"WebRTC-SimulcastScreenshare";
ScreenshareLayerConfig::ScreenshareLayerConfig(int tl0_bitrate, int tl1_bitrate)
: tl0_bitrate_kbps(tl0_bitrate), tl1_bitrate_kbps(tl1_bitrate) {
}
ScreenshareLayerConfig ScreenshareLayerConfig::GetDefault() {
std::string group =
webrtc::field_trial::FindFullName(kScreencastLayerFieldTrialName);
ScreenshareLayerConfig config(kScreenshareDefaultTl0BitrateKbps,
kScreenshareDefaultTl1BitrateKbps);
if (!group.empty() && !FromFieldTrialGroup(group, &config)) {
LOG(LS_WARNING) << "Unable to parse WebRTC-ScreenshareLayerRates"
" field trial group: '" << group << "'.";
}
return config;
}
bool ScreenshareLayerConfig::FromFieldTrialGroup(
const std::string& group,
ScreenshareLayerConfig* config) {
// Parse field trial group name, containing bitrates for tl0 and tl1.
int tl0_bitrate;
int tl1_bitrate;
if (sscanf(group.c_str(), "%d-%d", &tl0_bitrate, &tl1_bitrate) != 2) {
return false;
}
// Sanity check.
if (tl0_bitrate < kScreenshareMinBitrateKbps ||
tl0_bitrate > kScreenshareMaxBitrateKbps ||
tl1_bitrate < kScreenshareMinBitrateKbps ||
tl1_bitrate > kScreenshareMaxBitrateKbps || tl0_bitrate > tl1_bitrate) {
return false;
}
config->tl0_bitrate_kbps = tl0_bitrate;
config->tl1_bitrate_kbps = tl1_bitrate;
return true;
}
bool UseSimulcastScreenshare() {
return webrtc::field_trial::IsEnabled(kSimulcastScreenshareFieldTrialName);
}
} // namespace cricket
|
Update screen simulcast config
|
Update screen simulcast config
Lower then bitrate so that the delta between the highest layer of the
lower stream and lowest layer of the higher stream is not too large.
BUG=webrtc:4172
This is a reland of the following CL:
Review-Url: https://codereview.webrtc.org/2791273002
Cr-Commit-Position: refs/heads/master@{#18232}
Committed: https://chromium.googlesource.com/external/webrtc/+/dceb42da3e7d24ffeee93e20c4ce1ce90953bf88
https: //codereview.webrtc.org/2883963002
Review-Url: https://codereview.webrtc.org/2966833002
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#18913}
|
C++
|
bsd-3-clause
|
TimothyGu/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc
|
4f97b60b349b973280a5faa235d84b8e88b9d078
|
test/extensions/common/wasm/test_data/test_cpp.cc
|
test/extensions/common/wasm/test_data/test_cpp.cc
|
// NOLINT(namespace-envoy)
#include <unistd.h>
#include <cerrno>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <limits>
#include <string>
#ifndef NULL_PLUGIN
#include "proxy_wasm_intrinsics.h"
#else
#include "include/proxy-wasm/null_plugin.h"
#endif
START_WASM_PLUGIN(CommonWasmTestCpp)
static int* badptr = nullptr;
static float gNan = std::nan("1");
static float gInfinity = INFINITY;
#ifndef CHECK_RESULT
#define CHECK_RESULT(_c) \
do { \
if ((_c) != WasmResult::Ok) { \
proxy_log(LogLevel::critical, #_c, sizeof(#_c) - 1); \
abort(); \
} \
} while (0)
#endif
#define FAIL_NOW(_msg) \
do { \
const std::string __message = _msg; \
proxy_log(LogLevel::critical, __message.c_str(), __message.size()); \
abort(); \
} while (0)
WASM_EXPORT(void, proxy_abi_version_0_2_1, (void)) {}
WASM_EXPORT(void, proxy_on_context_create, (uint32_t, uint32_t)) {}
WASM_EXPORT(uint32_t, proxy_on_vm_start, (uint32_t context_id, uint32_t configuration_size)) {
const char* configuration_ptr = nullptr;
size_t size;
proxy_get_buffer_bytes(WasmBufferType::VmConfiguration, 0, configuration_size, &configuration_ptr,
&size);
std::string configuration(configuration_ptr, size);
if (configuration == "logging") {
std::string trace_message = "test trace logging";
proxy_log(LogLevel::trace, trace_message.c_str(), trace_message.size());
std::string debug_message = "test debug logging";
proxy_log(LogLevel::debug, debug_message.c_str(), debug_message.size());
std::string warn_message = "test warn logging";
proxy_log(LogLevel::warn, warn_message.c_str(), warn_message.size());
std::string error_message = "test error logging";
proxy_log(LogLevel::error, error_message.c_str(), error_message.size());
LogLevel log_level;
CHECK_RESULT(proxy_get_log_level(&log_level));
std::string level_message = "log level is " + std::to_string(static_cast<uint32_t>(log_level));
proxy_log(LogLevel::info, level_message.c_str(), level_message.size());
} else if (configuration == "segv") {
std::string message = "before badptr";
proxy_log(LogLevel::error, message.c_str(), message.size());
::free(const_cast<void*>(reinterpret_cast<const void*>(configuration_ptr)));
*badptr = 1;
message = "after badptr";
proxy_log(LogLevel::error, message.c_str(), message.size());
} else if (configuration == "divbyzero") {
std::string message = "before div by zero";
proxy_log(LogLevel::error, message.c_str(), message.size());
::free(const_cast<void*>(reinterpret_cast<const void*>(configuration_ptr)));
#pragma clang optimize off
int zero = context_id / 1000;
message = "divide by zero: " + std::to_string(100 / zero);
#pragma clang optimize on
proxy_log(LogLevel::error, message.c_str(), message.size());
} else if (configuration == "globals") {
std::string message = "NaN " + std::to_string(gNan);
proxy_log(LogLevel::warn, message.c_str(), message.size());
message = "inf " + std::to_string(gInfinity);
proxy_log(LogLevel::warn, message.c_str(), message.size());
message = "inf " + std::to_string(1.0 / 0.0);
proxy_log(LogLevel::warn, message.c_str(), message.size());
message = std::string("inf ") + (std::isinf(gInfinity) ? "inf" : "nan");
proxy_log(LogLevel::warn, message.c_str(), message.size());
} else if (configuration == "stats") {
uint32_t c, g, h;
std::string name = "test_counter";
CHECK_RESULT(proxy_define_metric(MetricType::Counter, name.data(), name.size(), &c));
name = "test_gauge";
CHECK_RESULT(proxy_define_metric(MetricType::Gauge, name.data(), name.size(), &g));
name = "test_historam";
CHECK_RESULT(proxy_define_metric(MetricType::Histogram, name.data(), name.size(), &h));
CHECK_RESULT(proxy_increment_metric(c, 1));
CHECK_RESULT(proxy_record_metric(g, 2));
CHECK_RESULT(proxy_record_metric(h, 3));
uint64_t value;
std::string message;
CHECK_RESULT(proxy_get_metric(c, &value));
message = std::string("get counter = ") + std::to_string(value);
proxy_log(LogLevel::trace, message.c_str(), message.size());
CHECK_RESULT(proxy_increment_metric(c, 1));
CHECK_RESULT(proxy_get_metric(c, &value));
message = std::string("get counter = ") + std::to_string(value);
proxy_log(LogLevel::debug, message.c_str(), message.size());
CHECK_RESULT(proxy_record_metric(c, 3));
CHECK_RESULT(proxy_get_metric(c, &value));
message = std::string("get counter = ") + std::to_string(value);
proxy_log(LogLevel::info, message.c_str(), message.size());
CHECK_RESULT(proxy_get_metric(g, &value));
message = std::string("get gauge = ") + std::to_string(value);
proxy_log(LogLevel::warn, message.c_str(), message.size());
// Get on histograms is not supported.
if (proxy_get_metric(h, &value) != WasmResult::Ok) {
message = std::string("get histogram = Unsupported");
proxy_log(LogLevel::error, message.c_str(), message.size());
}
} else if (configuration == "foreign") {
std::string function = "compress";
std::string argument = "something to compress dup dup dup dup dup";
char* compressed = nullptr;
size_t compressed_size = 0;
CHECK_RESULT(proxy_call_foreign_function(function.data(), function.size(), argument.data(),
argument.size(), &compressed, &compressed_size));
auto message = std::string("compress ") + std::to_string(argument.size()) + " -> " +
std::to_string(compressed_size);
proxy_log(LogLevel::trace, message.c_str(), message.size());
function = "uncompress";
char* result = nullptr;
size_t result_size = 0;
CHECK_RESULT(proxy_call_foreign_function(function.data(), function.size(), compressed,
compressed_size, &result, &result_size));
message = std::string("uncompress ") + std::to_string(compressed_size) + " -> " +
std::to_string(result_size);
proxy_log(LogLevel::debug, message.c_str(), message.size());
if (argument != std::string(result, result_size)) {
message = "compress mismatch ";
proxy_log(LogLevel::error, message.c_str(), message.size());
}
::free(compressed);
::free(result);
} else if (configuration == "WASI") {
// These checks depend on Emscripten's support for `WASI` and will only
// work if invoked on a "real" Wasm VM.
int err = fprintf(stdout, "WASI write to stdout\n");
if (err < 0) {
FAIL_NOW("stdout write should succeed");
}
err = fprintf(stderr, "WASI write to stderr\n");
if (err < 0) {
FAIL_NOW("stderr write should succeed");
}
// We explicitly don't support reading from stdin
char tmp[16];
size_t rc = fread(static_cast<void*>(tmp), 1, 16, stdin);
if (rc != 0 || errno != ENOSYS) {
FAIL_NOW("stdin read should fail. errno = " + std::to_string(errno));
}
// No environment variables should be available
char* pathenv = getenv("PATH");
if (pathenv != nullptr) {
FAIL_NOW("PATH environment variable should not be available");
}
// Exercise the `WASI` `fd_fdstat_get` a little bit
int tty = isatty(1);
if (errno != ENOTTY || tty != 0) {
FAIL_NOW("stdout is not a tty");
}
tty = isatty(2);
if (errno != ENOTTY || tty != 0) {
FAIL_NOW("stderr is not a tty");
}
tty = isatty(99);
if (errno != EBADF || tty != 0) {
FAIL_NOW("isatty errors on bad fds. errno = " + std::to_string(errno));
}
} else if (configuration == "on_foreign") {
std::string message = "on_foreign start";
proxy_log(LogLevel::debug, message.c_str(), message.size());
} else {
std::string message = "on_vm_start " + configuration;
proxy_log(LogLevel::info, message.c_str(), message.size());
}
::free(const_cast<void*>(reinterpret_cast<const void*>(configuration_ptr)));
return 1;
}
WASM_EXPORT(uint32_t, proxy_on_configure, (uint32_t, uint32_t configuration_size)) {
const char* configuration_ptr = nullptr;
size_t size;
proxy_get_buffer_bytes(WasmBufferType::PluginConfiguration, 0, configuration_size,
&configuration_ptr, &size);
std::string configuration(configuration_ptr, size);
if (configuration == "done") {
proxy_done();
} else {
std::string message = "on_configuration " + configuration;
proxy_log(LogLevel::info, message.c_str(), message.size());
}
::free(const_cast<void*>(reinterpret_cast<const void*>(configuration_ptr)));
return 1;
}
WASM_EXPORT(void, proxy_on_foreign_function, (uint32_t, uint32_t token, uint32_t data_size)) {
std::string message =
"on_foreign_function " + std::to_string(token) + " " + std::to_string(data_size);
proxy_log(LogLevel::info, message.c_str(), message.size());
}
WASM_EXPORT(uint32_t, proxy_on_done, (uint32_t)) {
std::string message = "on_done logging";
proxy_log(LogLevel::info, message.c_str(), message.size());
return 0;
}
WASM_EXPORT(void, proxy_on_delete, (uint32_t)) {
std::string message = "on_delete logging";
proxy_log(LogLevel::info, message.c_str(), message.size());
}
END_WASM_PLUGIN
|
// NOLINT(namespace-envoy)
#include <unistd.h>
#include <cerrno>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <limits>
#include <string>
#ifndef NULL_PLUGIN
#include "proxy_wasm_intrinsics.h"
#else
#include "include/proxy-wasm/null_plugin.h"
#endif
START_WASM_PLUGIN(CommonWasmTestCpp)
static int* badptr = nullptr;
static float gNan = std::nan("1");
static float gInfinity = INFINITY;
#ifndef CHECK_RESULT
#define CHECK_RESULT(_c) \
do { \
if ((_c) != WasmResult::Ok) { \
proxy_log(LogLevel::critical, #_c, sizeof(#_c) - 1); \
abort(); \
} \
} while (0)
#endif
#define FAIL_NOW(_msg) \
do { \
const std::string __message = _msg; \
proxy_log(LogLevel::critical, __message.c_str(), __message.size()); \
abort(); \
} while (0)
WASM_EXPORT(void, proxy_abi_version_0_2_1, (void)) {}
WASM_EXPORT(void, proxy_on_context_create, (uint32_t, uint32_t)) {}
WASM_EXPORT(uint32_t, proxy_on_vm_start, (uint32_t context_id, uint32_t configuration_size)) {
const char* configuration_ptr = nullptr;
size_t size;
proxy_get_buffer_bytes(WasmBufferType::VmConfiguration, 0, configuration_size, &configuration_ptr,
&size);
std::string configuration(configuration_ptr, size);
if (configuration == "logging") {
std::string trace_message = "test trace logging";
proxy_log(LogLevel::trace, trace_message.c_str(), trace_message.size());
std::string debug_message = "test debug logging";
proxy_log(LogLevel::debug, debug_message.c_str(), debug_message.size());
std::string warn_message = "test warn logging";
proxy_log(LogLevel::warn, warn_message.c_str(), warn_message.size());
std::string error_message = "test error logging";
proxy_log(LogLevel::error, error_message.c_str(), error_message.size());
LogLevel log_level;
CHECK_RESULT(proxy_get_log_level(&log_level));
std::string level_message = "log level is " + std::to_string(static_cast<uint32_t>(log_level));
proxy_log(LogLevel::info, level_message.c_str(), level_message.size());
} else if (configuration == "segv") {
std::string message = "before badptr";
proxy_log(LogLevel::error, message.c_str(), message.size());
::free(const_cast<void*>(reinterpret_cast<const void*>(configuration_ptr)));
*badptr = 1;
message = "after badptr";
proxy_log(LogLevel::error, message.c_str(), message.size());
} else if (configuration == "divbyzero") {
std::string message = "before div by zero";
proxy_log(LogLevel::error, message.c_str(), message.size());
::free(const_cast<void*>(reinterpret_cast<const void*>(configuration_ptr)));
int zero = context_id & 0x100000;
message = "divide by zero: " + std::to_string(100 / zero);
proxy_log(LogLevel::error, message.c_str(), message.size());
} else if (configuration == "globals") {
std::string message = "NaN " + std::to_string(gNan);
proxy_log(LogLevel::warn, message.c_str(), message.size());
message = "inf " + std::to_string(gInfinity);
proxy_log(LogLevel::warn, message.c_str(), message.size());
message = "inf " + std::to_string(1.0 / 0.0);
proxy_log(LogLevel::warn, message.c_str(), message.size());
message = std::string("inf ") + (std::isinf(gInfinity) ? "inf" : "nan");
proxy_log(LogLevel::warn, message.c_str(), message.size());
} else if (configuration == "stats") {
uint32_t c, g, h;
std::string name = "test_counter";
CHECK_RESULT(proxy_define_metric(MetricType::Counter, name.data(), name.size(), &c));
name = "test_gauge";
CHECK_RESULT(proxy_define_metric(MetricType::Gauge, name.data(), name.size(), &g));
name = "test_historam";
CHECK_RESULT(proxy_define_metric(MetricType::Histogram, name.data(), name.size(), &h));
CHECK_RESULT(proxy_increment_metric(c, 1));
CHECK_RESULT(proxy_record_metric(g, 2));
CHECK_RESULT(proxy_record_metric(h, 3));
uint64_t value;
std::string message;
CHECK_RESULT(proxy_get_metric(c, &value));
message = std::string("get counter = ") + std::to_string(value);
proxy_log(LogLevel::trace, message.c_str(), message.size());
CHECK_RESULT(proxy_increment_metric(c, 1));
CHECK_RESULT(proxy_get_metric(c, &value));
message = std::string("get counter = ") + std::to_string(value);
proxy_log(LogLevel::debug, message.c_str(), message.size());
CHECK_RESULT(proxy_record_metric(c, 3));
CHECK_RESULT(proxy_get_metric(c, &value));
message = std::string("get counter = ") + std::to_string(value);
proxy_log(LogLevel::info, message.c_str(), message.size());
CHECK_RESULT(proxy_get_metric(g, &value));
message = std::string("get gauge = ") + std::to_string(value);
proxy_log(LogLevel::warn, message.c_str(), message.size());
// Get on histograms is not supported.
if (proxy_get_metric(h, &value) != WasmResult::Ok) {
message = std::string("get histogram = Unsupported");
proxy_log(LogLevel::error, message.c_str(), message.size());
}
} else if (configuration == "foreign") {
std::string function = "compress";
std::string argument = "something to compress dup dup dup dup dup";
char* compressed = nullptr;
size_t compressed_size = 0;
CHECK_RESULT(proxy_call_foreign_function(function.data(), function.size(), argument.data(),
argument.size(), &compressed, &compressed_size));
auto message = std::string("compress ") + std::to_string(argument.size()) + " -> " +
std::to_string(compressed_size);
proxy_log(LogLevel::trace, message.c_str(), message.size());
function = "uncompress";
char* result = nullptr;
size_t result_size = 0;
CHECK_RESULT(proxy_call_foreign_function(function.data(), function.size(), compressed,
compressed_size, &result, &result_size));
message = std::string("uncompress ") + std::to_string(compressed_size) + " -> " +
std::to_string(result_size);
proxy_log(LogLevel::debug, message.c_str(), message.size());
if (argument != std::string(result, result_size)) {
message = "compress mismatch ";
proxy_log(LogLevel::error, message.c_str(), message.size());
}
::free(compressed);
::free(result);
} else if (configuration == "WASI") {
// These checks depend on Emscripten's support for `WASI` and will only
// work if invoked on a "real" Wasm VM.
int err = fprintf(stdout, "WASI write to stdout\n");
if (err < 0) {
FAIL_NOW("stdout write should succeed");
}
err = fprintf(stderr, "WASI write to stderr\n");
if (err < 0) {
FAIL_NOW("stderr write should succeed");
}
// We explicitly don't support reading from stdin
char tmp[16];
size_t rc = fread(static_cast<void*>(tmp), 1, 16, stdin);
if (rc != 0 || errno != ENOSYS) {
FAIL_NOW("stdin read should fail. errno = " + std::to_string(errno));
}
// No environment variables should be available
char* pathenv = getenv("PATH");
if (pathenv != nullptr) {
FAIL_NOW("PATH environment variable should not be available");
}
// Exercise the `WASI` `fd_fdstat_get` a little bit
int tty = isatty(1);
if (errno != ENOTTY || tty != 0) {
FAIL_NOW("stdout is not a tty");
}
tty = isatty(2);
if (errno != ENOTTY || tty != 0) {
FAIL_NOW("stderr is not a tty");
}
tty = isatty(99);
if (errno != EBADF || tty != 0) {
FAIL_NOW("isatty errors on bad fds. errno = " + std::to_string(errno));
}
} else if (configuration == "on_foreign") {
std::string message = "on_foreign start";
proxy_log(LogLevel::debug, message.c_str(), message.size());
} else {
std::string message = "on_vm_start " + configuration;
proxy_log(LogLevel::info, message.c_str(), message.size());
}
::free(const_cast<void*>(reinterpret_cast<const void*>(configuration_ptr)));
return 1;
}
WASM_EXPORT(uint32_t, proxy_on_configure, (uint32_t, uint32_t configuration_size)) {
const char* configuration_ptr = nullptr;
size_t size;
proxy_get_buffer_bytes(WasmBufferType::PluginConfiguration, 0, configuration_size,
&configuration_ptr, &size);
std::string configuration(configuration_ptr, size);
if (configuration == "done") {
proxy_done();
} else {
std::string message = "on_configuration " + configuration;
proxy_log(LogLevel::info, message.c_str(), message.size());
}
::free(const_cast<void*>(reinterpret_cast<const void*>(configuration_ptr)));
return 1;
}
WASM_EXPORT(void, proxy_on_foreign_function, (uint32_t, uint32_t token, uint32_t data_size)) {
std::string message =
"on_foreign_function " + std::to_string(token) + " " + std::to_string(data_size);
proxy_log(LogLevel::info, message.c_str(), message.size());
}
WASM_EXPORT(uint32_t, proxy_on_done, (uint32_t)) {
std::string message = "on_done logging";
proxy_log(LogLevel::info, message.c_str(), message.size());
return 0;
}
WASM_EXPORT(void, proxy_on_delete, (uint32_t)) {
std::string message = "on_delete logging";
proxy_log(LogLevel::info, message.c_str(), message.size());
}
END_WASM_PLUGIN
|
Remove clang specific pragma which breaks gcc.
|
Remove clang specific pragma which breaks gcc.
Signed-off-by: John Plevyak <[email protected]>
|
C++
|
apache-2.0
|
envoyproxy/envoy-wasm,envoyproxy/envoy-wasm,envoyproxy/envoy-wasm,envoyproxy/envoy-wasm,envoyproxy/envoy-wasm,envoyproxy/envoy-wasm,envoyproxy/envoy-wasm
|
a9deb15cbfa256d6a81e4ff4836304c2b6b464ca
|
tools/BitFunnel/src/TheBard.cpp
|
tools/BitFunnel/src/TheBard.cpp
|
// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 <iostream>
#include <memory>
#include <sstream>
#include "BitFunnel/Configuration/Factories.h"
#include "BitFunnel/Configuration/IFileSystem.h"
#include "BitFunnel/Data/Sonnets.h"
#include "BitFunnel/Exceptions.h"
#include "BitFunnelTool.h"
#include "CmdLineParser/CmdLineParser.h"
#include "LoggerInterfaces/Check.h"
namespace BitFunnel
{
//*************************************************************************
//
// TheBard is a sample application that configures a BitFunnel index based
// on a small corpus of 154 Shakespeare sonnets. This standalone example
// performs an end-to-end configuration, including corpus statistics
// analysis and TermTable construction.
//
// The sonnets are incorporated into the codebase as cstrings, allowing the
// example to run without touching the filesystem.
//
//*************************************************************************
void Run(bool verbose)
{
//
// This example uses the RAM filesystem.
//
auto fileSystem = BitFunnel::Factories::CreateRAMFileSystem();
auto fileManager =
BitFunnel::Factories::CreateFileManager(
"config",
"statistics",
"index",
*fileSystem);
//
// Initialize RAM filesystem with input files.
//
{
std::cout << "Initializing RAM filesystem." << std::endl;
// Open the manifest file.
auto manifest = fileSystem->OpenForWrite("manifest.txt");
// Iterate over sequence of Shakespeare sonnet chunk data.
for (size_t i = 0; i < Sonnets::chunks.size(); ++i)
{
// Create chunk file name, and write chunk data.
std::stringstream name;
name << "sonnet" << i;
auto out = fileSystem->OpenForWrite(name.str().c_str());
// TODO: consider checking for cast overflow?
out->write(Sonnets::chunks[i].second,
static_cast<std::streamsize>(Sonnets::chunks[i].first));
// Add chunk file to manifest.
*manifest << name.str() << std::endl;
}
}
//
// Create the BitFunnelTool based on the RAM filesystem.
//
BitFunnel::BitFunnelTool tool(*fileSystem);
//
// Use the tool to run the statistics builder.
//
{
std::cout << "Gathering corpus statistics." << std::endl;
std::vector<char const *> argv = {
"BitFunnel",
"statistics",
"manifest.txt",
"config",
"-text"
};
std::stringstream ignore;
std::ostream& out = (verbose) ? std::cout : ignore;
tool.Main(std::cin,
out,
static_cast<int>(argv.size()),
argv.data());
}
//
// Use the tool to run the TermTable builder.
//
{
std::cout << "Building the TermTable." << std::endl;
std::vector<char const *> argv = {
"BitFunnel",
"termtable",
"config",
"0.1",
"PrivateSharedRank0ToN"
};
std::stringstream ignore;
std::ostream& out = (verbose) ? std::cout : ignore;
auto result = tool.Main(std::cin,
out,
static_cast<int>(argv.size()),
argv.data());
CHECK_EQ(result, 0) << "TermTableBuilder failed.";
std::cout
<< "Index is now configured."
<< std::endl
<< std::endl;
}
//
// Use the tool to run the REPL.
//
{
std::vector<char const *> argv = {
"BitFunnel",
"repl",
"config"
};
tool.Main(std::cin,
std::cout,
static_cast<int>(argv.size()),
argv.data());
}
}
}
int main(int argc, char** argv)
{
CmdLine::CmdLineParser parser(
"TheBard",
"A small end-to-end index configuration and ingestion example "
"based on 154 Shakespeare sonnets.");
CmdLine::OptionalParameterList verbose(
"verbose",
"Print information gathered during statistics and "
"termtable stages.");
// TODO: This parameter should be unsigned, but it doesn't seem to work
// with CmdLineParser.
CmdLine::OptionalParameter<int> gramSize(
"gramsize",
"Set the maximum ngram size for phrases.",
1u);
parser.AddParameter(verbose);
parser.AddParameter(gramSize);
int returnCode = 1;
if (parser.TryParse(std::cout, argc, argv))
{
try
{
BitFunnel::Run(verbose.IsActivated());
}
catch (BitFunnel::RecoverableError e)
{
std::cout << "Error: " << e.what() << std::endl;
}
catch (...)
{
// TODO: Do we really want to catch all exceptions here?
// Seems we want to at least print out the error message for BitFunnel exceptions.
std::cout << "Unexpected error." << std::endl;
}
}
return returnCode;
}
|
// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 <iostream>
#include <sstream>
#include "BitFunnel/Configuration/Factories.h"
#include "BitFunnel/Configuration/IFileSystem.h"
#include "BitFunnel/Data/Sonnets.h"
#include "BitFunnel/Exceptions.h"
#include "BitFunnelTool.h"
#include "CmdLineParser/CmdLineParser.h"
#include "LoggerInterfaces/Check.h"
namespace BitFunnel
{
//*************************************************************************
//
// TheBard is a sample application that configures a BitFunnel index based
// on a small corpus of 154 Shakespeare sonnets. This standalone example
// performs an end-to-end configuration, including corpus statistics
// analysis and TermTable construction.
//
// The sonnets are incorporated into the codebase as cstrings, allowing the
// example to run without touching the filesystem.
//
//*************************************************************************
void Run(bool verbose)
{
//
// This example uses the RAM filesystem.
//
auto fileSystem = BitFunnel::Factories::CreateRAMFileSystem();
auto fileManager =
BitFunnel::Factories::CreateFileManager(
"config",
"statistics",
"index",
*fileSystem);
//
// Initialize RAM filesystem with input files.
//
{
std::cout << "Initializing RAM filesystem." << std::endl;
// Open the manifest file.
auto manifest = fileSystem->OpenForWrite("manifest.txt");
// Iterate over sequence of Shakespeare sonnet chunk data.
for (size_t i = 0; i < Sonnets::chunks.size(); ++i)
{
// Create chunk file name, and write chunk data.
std::stringstream name;
name << "sonnet" << i;
auto out = fileSystem->OpenForWrite(name.str().c_str());
// TODO: consider checking for cast overflow?
out->write(Sonnets::chunks[i].second,
static_cast<std::streamsize>(Sonnets::chunks[i].first));
// Add chunk file to manifest.
*manifest << name.str() << std::endl;
}
}
//
// Create the BitFunnelTool based on the RAM filesystem.
//
BitFunnel::BitFunnelTool tool(*fileSystem);
//
// Use the tool to run the statistics builder.
//
{
std::cout << "Gathering corpus statistics." << std::endl;
std::vector<char const *> argv = {
"BitFunnel",
"statistics",
"manifest.txt",
"config",
"-text"
};
std::stringstream ignore;
std::ostream& out = (verbose) ? std::cout : ignore;
tool.Main(std::cin,
out,
static_cast<int>(argv.size()),
argv.data());
}
//
// Use the tool to run the TermTable builder.
//
{
std::cout << "Building the TermTable." << std::endl;
std::vector<char const *> argv = {
"BitFunnel",
"termtable",
"config",
"0.1",
"PrivateSharedRank0ToN"
};
std::stringstream ignore;
std::ostream& out = (verbose) ? std::cout : ignore;
auto result = tool.Main(std::cin,
out,
static_cast<int>(argv.size()),
argv.data());
CHECK_EQ(result, 0) << "TermTableBuilder failed.";
std::cout
<< "Index is now configured."
<< std::endl
<< std::endl;
}
//
// Use the tool to run the REPL.
//
{
std::vector<char const *> argv = {
"BitFunnel",
"repl",
"config"
};
tool.Main(std::cin,
std::cout,
static_cast<int>(argv.size()),
argv.data());
}
}
}
int main(int argc, const char *const *argv)
{
CmdLine::CmdLineParser parser(
"TheBard",
"A small end-to-end index configuration and ingestion example "
"based on 154 Shakespeare sonnets.");
CmdLine::OptionalParameterList verbose(
"verbose",
"Print information gathered during statistics and "
"termtable stages.");
// TODO: This parameter should be unsigned, but it doesn't seem to work
// with CmdLineParser.
CmdLine::OptionalParameter<int> gramSize(
"gramsize",
"Set the maximum n-gram size for phrases.",
1u);
parser.AddParameter(verbose);
parser.AddParameter(gramSize);
int returnCode = 1;
if (parser.TryParse(std::cout, argc, argv))
{
try
{
BitFunnel::Run(verbose.IsActivated());
}
catch (BitFunnel::RecoverableError e)
{
std::cout << "Error: " << e.what() << std::endl;
}
catch (...)
{
// TODO: Do we really want to catch all exceptions here?
// Seems we want to at least print out the error message for BitFunnel exceptions.
std::cout << "Unexpected error." << std::endl;
}
}
return returnCode;
}
|
Fix misc CLion inspection warnings.
|
Fix misc CLion inspection warnings.
|
C++
|
mit
|
BitFunnel/BitFunnel,danluu/BitFunnel,danluu/BitFunnel,danluu/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,danluu/BitFunnel,danluu/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,danluu/BitFunnel
|
f8fba3f14246143a19720121f7b0e466b926e2ba
|
dune/gdt/test/operators/base.hh
|
dune/gdt/test/operators/base.hh
|
// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2015 - 2017)
// Rene Milk (2016 - 2017)
// Tobias Leibner (2016)
#ifndef DUNE_GDT_TEST_OPERATORS_BASE_HH
#define DUNE_GDT_TEST_OPERATORS_BASE_HH
#include <dune/common/unused.hh>
#include <dune/xt/common/test/gtest/gtest.h>
#include <dune/xt/la/container.hh>
#include <dune/xt/grid/gridprovider/cube.hh>
#include <dune/xt/grid/walker.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/functions/expression.hh>
#include <dune/xt/functions/constant.hh>
#include <dune/gdt/operators/interfaces.hh>
#include <dune/gdt/spaces/interface.hh>
namespace Dune {
namespace GDT {
namespace Test {
namespace internal {
template <class SpaceType>
struct OperatorBaseTraits
{
static_assert(is_space<SpaceType>::value, "");
typedef typename SpaceType::GridLayerType GridLayerType;
using EntityType = XT::Grid::extract_entity_t<GridLayerType>;
typedef typename SpaceType::DomainFieldType DomainFieldType;
static const size_t dimDomain = SpaceType::dimDomain;
typedef typename SpaceType::RangeFieldType RangeFieldType;
static const size_t dimRange = SpaceType::dimRange;
static const unsigned int polOrder = SpaceType::polOrder;
typedef Dune::XT::Functions::ExpressionFunction<EntityType, DomainFieldType, dimDomain, RangeFieldType, 1>
ScalarFunctionType;
typedef Dune::XT::Functions::ExpressionFunction<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange>
FunctionType;
typedef Dune::XT::Functions::
ConstantFunction<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain, dimDomain>
TensorFunctionType;
typedef typename XT::LA::Container<RangeFieldType, XT::LA::default_backend>::MatrixType MatrixType;
typedef typename XT::LA::Container<RangeFieldType, XT::LA::default_backend>::VectorType VectorType;
typedef DiscreteFunction<SpaceType, VectorType> DiscreteFunctionType;
}; // class OperatorBaseTraits
} // namespace internal
template <class SpaceType>
struct OperatorBase : public ::testing::Test
{
typedef internal::OperatorBaseTraits<SpaceType> Traits;
typedef typename Traits::GridLayerType GridLayerType;
typedef typename GridLayerType::Grid GridType;
typedef Dune::XT::Grid::GridProvider<GridType> GridProviderType;
typedef typename Traits::RangeFieldType RangeFieldType;
typedef typename Traits::ScalarFunctionType ScalarFunctionType;
typedef typename Traits::FunctionType FunctionType;
typedef typename Traits::TensorFunctionType TensorFunctionType;
typedef typename Traits::DiscreteFunctionType DiscreteFunctionType;
typedef typename Traits::MatrixType MatrixType;
typedef typename Traits::VectorType VectorType;
static const size_t dimDomain = Traits::dimDomain;
OperatorBase()
: grid_provider_(XT::Grid::make_cube_grid<GridType>(0.0, 1.0, 6u))
, space_(grid_provider_.leaf<SpaceType::layer_backend>())
, scalar_function_("x", "x[0]", 1, "scalar function", {{"1.0", "0.0", "0.0"}})
, function_("x", {"x[0]", "0", "0"}, 1)
, tensor_function_(XT::Functions::internal::UnitMatrix<RangeFieldType, dimDomain>::value())
, discrete_function_(space_)
{
}
GridProviderType grid_provider_;
const SpaceType space_;
const ScalarFunctionType scalar_function_;
const FunctionType function_;
const TensorFunctionType tensor_function_;
DiscreteFunctionType discrete_function_;
}; // class OperatorBase
template <class SpaceType>
struct LocalizableProductBase : public OperatorBase<SpaceType>
{
typedef OperatorBase<SpaceType> BaseType;
using typename BaseType::GridLayerType;
template <class ProductImp>
void localizable_product_test(ProductImp& prod)
{
const auto& source DUNE_UNUSED = prod.source();
const auto& range DUNE_UNUSED = prod.range();
auto& non_const_range DUNE_UNUSED = prod.range();
XT::Grid::Walker<GridLayerType> walker(this->space_.grid_layer());
walker.append(prod);
walker.walk();
auto result DUNE_UNUSED = prod.apply2();
} // ... localizable_product_test(...)
}; // class LocalizableProductBase
template <class SpaceType>
struct MatrixOperatorBase : public OperatorBase<SpaceType>
{
typedef OperatorBase<SpaceType> BaseType;
using typename BaseType::GridLayerType;
using typename BaseType::MatrixType;
template <class OperatorImp>
void matrix_operator_test(OperatorImp& op)
{
const auto& matrix DUNE_UNUSED = op.matrix();
auto& non_const_matrix DUNE_UNUSED = op.matrix();
const auto& source_space DUNE_UNUSED = op.source_space();
const auto& range_space DUNE_UNUSED = op.range_space();
XT::Grid::Walker<GridLayerType> walker(this->space_.grid_layer());
walker.append(op);
walker.walk();
} // ... matrix_operator_test(...)
}; // class LocalizableProductBase
} // namespace Test
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_TEST_OPERATORS_BASE_HH
|
// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2015 - 2017)
// Rene Milk (2016 - 2017)
// Tobias Leibner (2016)
#ifndef DUNE_GDT_TEST_OPERATORS_BASE_HH
#define DUNE_GDT_TEST_OPERATORS_BASE_HH
#include <dune/common/unused.hh>
#include <dune/xt/common/test/gtest/gtest.h>
#include <dune/xt/la/container.hh>
#include <dune/xt/grid/gridprovider/cube.hh>
#include <dune/xt/grid/walker.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/functions/expression.hh>
#include <dune/xt/functions/constant.hh>
#include <dune/gdt/operators/interfaces.hh>
#include <dune/gdt/spaces/interface.hh>
namespace Dune {
namespace GDT {
namespace Test {
namespace internal {
template <class SpaceType>
struct OperatorBaseTraits
{
static_assert(is_space<SpaceType>::value, "");
typedef typename SpaceType::GridLayerType GridLayerType;
using EntityType = XT::Grid::extract_entity_t<GridLayerType>;
typedef typename SpaceType::DomainFieldType DomainFieldType;
static const size_t dimDomain = SpaceType::dimDomain;
typedef typename SpaceType::RangeFieldType RangeFieldType;
static const size_t dimRange = SpaceType::dimRange;
static const unsigned int polOrder = SpaceType::polOrder;
typedef Dune::XT::Functions::ExpressionFunction<EntityType, DomainFieldType, dimDomain, RangeFieldType, 1>
ScalarFunctionType;
typedef Dune::XT::Functions::ExpressionFunction<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange>
FunctionType;
typedef Dune::XT::Functions::
ConstantFunction<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain, dimDomain>
TensorFunctionType;
typedef typename XT::LA::Container<RangeFieldType, XT::LA::default_backend>::MatrixType MatrixType;
typedef typename XT::LA::Container<RangeFieldType, XT::LA::default_backend>::VectorType VectorType;
typedef DiscreteFunction<SpaceType, VectorType> DiscreteFunctionType;
}; // class OperatorBaseTraits
} // namespace internal
template <class SpaceType>
struct OperatorBase : public ::testing::Test
{
typedef internal::OperatorBaseTraits<SpaceType> Traits;
typedef typename Traits::GridLayerType GridLayerType;
typedef typename GridLayerType::Grid GridType;
typedef Dune::XT::Grid::GridProvider<GridType> GridProviderType;
typedef typename Traits::RangeFieldType RangeFieldType;
typedef typename Traits::ScalarFunctionType ScalarFunctionType;
typedef typename Traits::FunctionType FunctionType;
typedef typename Traits::TensorFunctionType TensorFunctionType;
typedef typename Traits::DiscreteFunctionType DiscreteFunctionType;
typedef typename Traits::MatrixType MatrixType;
typedef typename Traits::VectorType VectorType;
static const size_t dimDomain = Traits::dimDomain;
OperatorBase()
: grid_provider_(XT::Grid::make_cube_grid<GridType>(0.0, 1.0, 6u))
, space_(grid_provider_.template layer<XT::Grid::Layers::leaf, SpaceType::layer_backend>())
, scalar_function_("x", "x[0]", 1, "scalar function", {"1.0", "0.0", "0.0"})
, function_("x", {"x[0]", "0", "0"}, 1)
, tensor_function_(XT::Functions::internal::UnitMatrix<RangeFieldType, dimDomain>::value())
, discrete_function_(space_)
{
}
GridProviderType grid_provider_;
const SpaceType space_;
const ScalarFunctionType scalar_function_;
const FunctionType function_;
const TensorFunctionType tensor_function_;
DiscreteFunctionType discrete_function_;
}; // class OperatorBase
template <class SpaceType>
struct LocalizableProductBase : public OperatorBase<SpaceType>
{
typedef OperatorBase<SpaceType> BaseType;
using typename BaseType::GridLayerType;
template <class ProductImp>
void localizable_product_test(ProductImp& prod)
{
const auto& source DUNE_UNUSED = prod.source();
const auto& range DUNE_UNUSED = prod.range();
auto& non_const_range DUNE_UNUSED = prod.range();
XT::Grid::Walker<GridLayerType> walker(this->space_.grid_layer());
walker.append(prod);
walker.walk();
auto result DUNE_UNUSED = prod.apply2();
} // ... localizable_product_test(...)
}; // class LocalizableProductBase
template <class SpaceType>
struct MatrixOperatorBase : public OperatorBase<SpaceType>
{
typedef OperatorBase<SpaceType> BaseType;
using typename BaseType::GridLayerType;
using typename BaseType::MatrixType;
template <class OperatorImp>
void matrix_operator_test(OperatorImp& op)
{
const auto& matrix DUNE_UNUSED = op.matrix();
auto& non_const_matrix DUNE_UNUSED = op.matrix();
const auto& source_space DUNE_UNUSED = op.source_space();
const auto& range_space DUNE_UNUSED = op.range_space();
XT::Grid::Walker<GridLayerType> walker(this->space_.grid_layer());
walker.append(op);
walker.walk();
} // ... matrix_operator_test(...)
}; // class LocalizableProductBase
} // namespace Test
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_TEST_OPERATORS_BASE_HH
|
update grid and funcitons usage
|
[test.operators.base] update grid and funcitons usage
|
C++
|
bsd-2-clause
|
pymor/dune-gdt
|
6458e5c826667631db870c764af4520e4f5d0fd9
|
integrators/embedded_explicit_runge_kutta_nyström_integrator_test.cpp
|
integrators/embedded_explicit_runge_kutta_nyström_integrator_test.cpp
|
#include "integrators/embedded_explicit_runge_kutta_nyström_integrator.hpp"
#include <algorithm>
#include <vector>
#include "base/macros.hpp"
#include "glog/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "quantities/si.hpp"
#include "testing_utilities/integration.hpp"
#include "testing_utilities/numerics.hpp"
namespace principia {
using quantities::Abs;
using quantities::Length;
using si::Centi;
using si::Metre;
using si::Milli;
using si::Second;
using testing_utilities::AbsoluteError;
using ::std::placeholders::_1;
using ::std::placeholders::_2;
using ::std::placeholders::_3;
using ::testing::AllOf;
using ::testing::Ge;
using ::testing::Le;
namespace integrators {
using ODE = SpecialSecondOrderDifferentialEquation<Length>;
namespace {
// TODO(egg): use the one from testing_utilities/integration again when everyone
// uses |Instant|s.
void ComputeHarmonicOscillatorAcceleration(
Instant const& t,
std::vector<Length> const& q,
std::vector<Acceleration>* const result,
not_null<int*> evaluation_count) {
(*result)[0] = -q[0] * (SIUnit<Stiffness>() / SIUnit<Mass>());
++*evaluation_count;
}
double HarmonicOscillatorToleranceRatio(
Time const& h,
ODE::SystemStateError const& error,
Length const& q_tolerance,
Speed const& v_tolerance,
not_null<int*> rejection_count) {
double const r = std::min(q_tolerance / Abs(error.position_error[0]),
v_tolerance / Abs(error.velocity_error[0]));
if (r < 1.0) {
++*rejection_count;
}
return r;
}
} // namespace
class EmbeddedExplicitRungeKuttaNyströmIntegratorTest
: public ::testing::Test {};
TEST_F(EmbeddedExplicitRungeKuttaNyströmIntegratorTest,
HarmonicOscillatorBackAndForth) {
AdaptiveSizeIntegrator<ODE> const& integrator =
DormandElMikkawyPrince1986RKN434FM<Length>();
Length const x_initial = 1 * Metre;
Speed const v_initial = 0 * Metre / Second;
Time const period = 2 * π * Second;
Instant const t_initial;
Instant const t_final = t_initial + 10 * period;
Length const length_tolerance = 1 * Milli(Metre);
Speed const speed_tolerance = 1 * Milli(Metre) / Second;
int const steps_forward = 132;
// We integrate backward with double the tolerance.
int const steps_backward = 112;
int evaluation_count = 0;
int rejection_count = 0;
std::vector<ODE::SystemState> solution;
ODE harmonic_oscillator;
harmonic_oscillator.compute_acceleration =
std::bind(ComputeHarmonicOscillatorAcceleration,
_1, _2, _3, &evaluation_count);
IntegrationProblem<ODE> problem;
problem.equation = harmonic_oscillator;
ODE::SystemState const initial_state = {{x_initial}, {v_initial}, t_initial};
problem.initial_state = &initial_state;
problem.t_final = t_final;
problem.append_state = [&solution](ODE::SystemState const& state) {
solution.push_back(state);
};
AdaptiveStepSize<ODE> adaptive_step_size;
adaptive_step_size.first_time_step = t_final - t_initial;
adaptive_step_size.safety_factor = 0.9;
adaptive_step_size.tolerance_to_error_ratio =
std::bind(HarmonicOscillatorToleranceRatio,
_1, _2, length_tolerance, speed_tolerance, &rejection_count);
integrator.Solve(problem, adaptive_step_size);
EXPECT_THAT(AbsoluteError(x_initial, solution.back().positions[0].value),
AllOf(Ge(3E-4 * Metre), Le(4E-4 * Metre)));
EXPECT_THAT(AbsoluteError(v_initial, solution.back().velocities[0].value),
AllOf(Ge(2E-3 * Metre / Second), Le(3E-3 * Metre / Second)));
EXPECT_EQ(t_final, solution.back().time.value);
EXPECT_EQ(steps_forward, solution.size());
EXPECT_EQ((steps_forward + rejection_count) * 4, evaluation_count);
evaluation_count = 0;
rejection_count = 0;
problem.initial_state = &solution.back();
problem.t_final = t_initial;
adaptive_step_size.first_time_step = t_initial - t_final;
adaptive_step_size.tolerance_to_error_ratio =
std::bind(HarmonicOscillatorToleranceRatio,
_1, _2, 2 * length_tolerance, 2 * speed_tolerance,
&rejection_count);
integrator.Solve(problem, adaptive_step_size);
EXPECT_THAT(AbsoluteError(x_initial, solution.back().positions[0].value),
AllOf(Ge(1E-3 * Metre), Le(2E-3 * Metre)));
EXPECT_THAT(AbsoluteError(v_initial, solution.back().velocities[0].value),
AllOf(Ge(2E-3 * Metre / Second), Le(3E-3 * Metre / Second)));
EXPECT_EQ(t_initial, solution.back().time.value);
EXPECT_EQ(steps_backward, solution.size() - steps_forward);
EXPECT_EQ((steps_backward + rejection_count) * 4, evaluation_count);
}
} // namespace integrators
} // namespace principia
|
#include "integrators/embedded_explicit_runge_kutta_nyström_integrator.hpp"
#include <algorithm>
#include <vector>
#include "base/macros.hpp"
#include "glog/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "quantities/si.hpp"
#include "testing_utilities/integration.hpp"
#include "testing_utilities/numerics.hpp"
namespace principia {
using quantities::Abs;
using quantities::Length;
using si::Centi;
using si::Metre;
using si::Milli;
using si::Second;
using testing_utilities::AbsoluteError;
using ::std::placeholders::_1;
using ::std::placeholders::_2;
using ::std::placeholders::_3;
using ::testing::AllOf;
using ::testing::Ge;
using ::testing::Le;
namespace integrators {
using ODE = SpecialSecondOrderDifferentialEquation<Length>;
namespace {
// TODO(egg): use the one from testing_utilities/integration again when everyone
// uses |Instant|s.
void ComputeHarmonicOscillatorAcceleration(
Instant const& t,
std::vector<Length> const& q,
std::vector<Acceleration>* const result,
not_null<int*> evaluations) {
(*result)[0] = -q[0] * (SIUnit<Stiffness>() / SIUnit<Mass>());
++*evaluations;
}
double HarmonicOscillatorToleranceRatio(
Time const& h,
ODE::SystemStateError const& error,
Length const& q_tolerance,
Speed const& v_tolerance,
std::function<void(bool tolerable)> callback) {
double const r = std::min(q_tolerance / Abs(error.position_error[0]),
v_tolerance / Abs(error.velocity_error[0]));
callback(r > 1.0);
return r;
}
} // namespace
class EmbeddedExplicitRungeKuttaNyströmIntegratorTest
: public ::testing::Test {};
TEST_F(EmbeddedExplicitRungeKuttaNyströmIntegratorTest,
HarmonicOscillatorBackAndForth) {
AdaptiveSizeIntegrator<ODE> const& integrator =
DormandElMikkawyPrince1986RKN434FM<Length>();
Length const x_initial = 1 * Metre;
Speed const v_initial = 0 * Metre / Second;
Time const period = 2 * π * Second;
Instant const t_initial;
Instant const t_final = t_initial + 10 * period;
Length const length_tolerance = 1 * Milli(Metre);
Speed const speed_tolerance = 1 * Milli(Metre) / Second;
int const steps_forward = 132;
// We integrate backward with double the tolerance.
int const steps_backward = 112;
int evaluations = 0;
int initial_rejections = 0;
int subsequent_rejections = 0;
bool first_step = true;
auto const step_size_callback = [&initial_rejections, &subsequent_rejections,
&first_step](bool tolerable) {
if (!tolerable) {
if (first_step) {
++initial_rejections;
} else {
++subsequent_rejections;
}
} else if (first_step) {
first_step = false;
}
};
std::vector<ODE::SystemState> solution;
ODE harmonic_oscillator;
harmonic_oscillator.compute_acceleration =
std::bind(ComputeHarmonicOscillatorAcceleration,
_1, _2, _3, &evaluations);
IntegrationProblem<ODE> problem;
problem.equation = harmonic_oscillator;
ODE::SystemState const initial_state = {{x_initial}, {v_initial}, t_initial};
problem.initial_state = &initial_state;
problem.t_final = t_final;
problem.append_state = [&solution](ODE::SystemState const& state) {
solution.push_back(state);
};
AdaptiveStepSize<ODE> adaptive_step_size;
adaptive_step_size.first_time_step = t_final - t_initial;
adaptive_step_size.safety_factor = 0.9;
adaptive_step_size.tolerance_to_error_ratio =
std::bind(HarmonicOscillatorToleranceRatio,
_1, _2, length_tolerance, speed_tolerance, step_size_callback);
integrator.Solve(problem, adaptive_step_size);
EXPECT_THAT(AbsoluteError(x_initial, solution.back().positions[0].value),
AllOf(Ge(3E-4 * Metre), Le(4E-4 * Metre)));
EXPECT_THAT(AbsoluteError(v_initial, solution.back().velocities[0].value),
AllOf(Ge(2E-3 * Metre / Second), Le(3E-3 * Metre / Second)));
EXPECT_EQ(t_final, solution.back().time.value);
EXPECT_EQ(steps_forward, solution.size());
EXPECT_EQ(
(steps_forward + initial_rejections + subsequent_rejections) * 4,
evaluations);
evaluations = 0;
subsequent_rejections = 0;
initial_rejections = 0;
problem.initial_state = &solution.back();
problem.t_final = t_initial;
adaptive_step_size.first_time_step = t_initial - t_final;
adaptive_step_size.tolerance_to_error_ratio =
std::bind(HarmonicOscillatorToleranceRatio,
_1, _2, 2 * length_tolerance, 2 * speed_tolerance,
step_size_callback);
integrator.Solve(problem, adaptive_step_size);
EXPECT_THAT(AbsoluteError(x_initial, solution.back().positions[0].value),
AllOf(Ge(1E-3 * Metre), Le(2E-3 * Metre)));
EXPECT_THAT(AbsoluteError(v_initial, solution.back().velocities[0].value),
AllOf(Ge(2E-3 * Metre / Second), Le(3E-3 * Metre / Second)));
EXPECT_EQ(t_initial, solution.back().time.value);
EXPECT_EQ(steps_backward, solution.size() - steps_forward);
EXPECT_EQ(
(steps_backward + initial_rejections + subsequent_rejections) * 4,
evaluations);
}
} // namespace integrators
} // namespace principia
|
split initial and subsequent rejections
|
split initial and subsequent rejections
|
C++
|
mit
|
Norgg/Principia,eggrobin/Principia,Norgg/Principia,mockingbirdnest/Principia,eggrobin/Principia,mockingbirdnest/Principia,Norgg/Principia,eggrobin/Principia,mockingbirdnest/Principia,mockingbirdnest/Principia,pleroy/Principia,Norgg/Principia,pleroy/Principia,pleroy/Principia,pleroy/Principia
|
4f679c33c0cb1d3437a352a4727f271ab0a9a133
|
tests/solvers/second_order_unsteady_solver_test.C
|
tests/solvers/second_order_unsteady_solver_test.C
|
// Ignore unused parameter warnings coming from cppunit headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>
#include <libmesh/equation_systems.h>
#include <libmesh/mesh.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/fem_system.h>
#include <libmesh/quadrature.h>
#include <libmesh/diff_solver.h>
#include <libmesh/newmark_solver.h>
#include "test_comm.h"
#include "solvers/time_solver_test_common.h"
// THE CPPUNIT_TEST_SUITE_END macro expands to code that involves
// std::auto_ptr, which in turn produces -Wdeprecated-declarations
// warnings. These can be ignored in GCC as long as we wrap the
// offending code in appropriate pragmas. We can't get away with a
// single ignore_warnings.h inclusion at the beginning of this file,
// since the libmesh headers pull in a restore_warnings.h at some
// point. We also don't bother restoring warnings at the end of this
// file since it's not a header.
#include <libmesh/ignore_warnings.h>
//! Implements ODE: 3.14\ddot{u} = 2.71, u(0) = 0, \dot{u}(0) = 0
template<typename SystemBase>
class ConstantSecondOrderODE : public SystemBase
{
public:
ConstantSecondOrderODE(EquationSystems & es,
const std::string & name_in,
const unsigned int number_in)
: SystemBase(es, name_in, number_in)
{}
virtual Number F( FEMContext & /*context*/, unsigned int /*qp*/ ) libmesh_override
{ return -2.71; }
virtual Number C( FEMContext & /*context*/, unsigned int /*qp*/ ) libmesh_override
{ return 0.0; }
virtual Number M( FEMContext & /*context*/, unsigned int /*qp*/ ) libmesh_override
{ return 3.14; }
virtual Number u( Real t ) libmesh_override
{ return 2.71/3.14*0.5*t*t; }
};
//! Implements ODE: 1.0\ddot{u} = 6.0*t+2.0, u(0) = 0, \dot{u}(0) = 0
template<typename SystemBase>
class LinearTimeSecondOrderODE : public SystemBase
{
public:
LinearTimeSecondOrderODE(EquationSystems & es,
const std::string & name_in,
const unsigned int number_in)
: SystemBase(es, name_in, number_in)
{}
virtual Number F( FEMContext & context, unsigned int /*qp*/ ) libmesh_override
{ return -6.0*context.get_time()-2.0; }
virtual Number C( FEMContext & /*context*/, unsigned int /*qp*/ ) libmesh_override
{ return 0.0; }
virtual Number M( FEMContext & /*context*/, unsigned int /*qp*/ ) libmesh_override
{ return 1.0; }
virtual Number u( Real t ) libmesh_override
{ return t*t*t+t*t; }
};
class NewmarkSolverTestBase : public TimeSolverTestImplementation<NewmarkSolver>
{
public:
NewmarkSolverTestBase()
: TimeSolverTestImplementation<NewmarkSolver>(),
_beta(0.25)
{}
protected:
virtual void aux_time_solver_init( NewmarkSolver & time_solver ) libmesh_override
{ time_solver.set_beta(_beta);
time_solver.compute_initial_accel(); }
void set_beta( Real beta )
{ _beta = beta; }
Real _beta;
};
class NewmarkSolverTest : public CppUnit::TestCase,
public NewmarkSolverTestBase
{
public:
CPPUNIT_TEST_SUITE( NewmarkSolverTest );
CPPUNIT_TEST( testNewmarkSolverConstantSecondOrderODESecondOrderStyle );
CPPUNIT_TEST( testNewmarkSolverLinearTimeSecondOrderODESecondOrderStyle );
CPPUNIT_TEST_SUITE_END();
public:
void testNewmarkSolverConstantSecondOrderODESecondOrderStyle()
{
this->run_test_with_exact_soln<ConstantSecondOrderODE<SecondOrderScalarSystemSecondOrderTimeSolverBase> >(0.5,10);
}
void testNewmarkSolverLinearTimeSecondOrderODESecondOrderStyle()
{
// For \beta = 1/6, we have the "linear acceleration method" for which
// we should be able to exactly integrate linear (in time) acceleration
// functions.
this->set_beta(1.0/6.0);
this->run_test_with_exact_soln<LinearTimeSecondOrderODE<SecondOrderScalarSystemSecondOrderTimeSolverBase> >(0.5,10);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( NewmarkSolverTest );
|
// Ignore unused parameter warnings coming from cppunit headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>
#include <libmesh/equation_systems.h>
#include <libmesh/mesh.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/fem_system.h>
#include <libmesh/quadrature.h>
#include <libmesh/diff_solver.h>
#include <libmesh/newmark_solver.h>
#include "test_comm.h"
#include "solvers/time_solver_test_common.h"
// THE CPPUNIT_TEST_SUITE_END macro expands to code that involves
// std::auto_ptr, which in turn produces -Wdeprecated-declarations
// warnings. These can be ignored in GCC as long as we wrap the
// offending code in appropriate pragmas. We can't get away with a
// single ignore_warnings.h inclusion at the beginning of this file,
// since the libmesh headers pull in a restore_warnings.h at some
// point. We also don't bother restoring warnings at the end of this
// file since it's not a header.
#include <libmesh/ignore_warnings.h>
//! Implements ODE: 3.14\ddot{u} = 2.71, u(0) = 0, \dot{u}(0) = 0
template<typename SystemBase>
class ConstantSecondOrderODE : public SystemBase
{
public:
ConstantSecondOrderODE(EquationSystems & es,
const std::string & name_in,
const unsigned int number_in)
: SystemBase(es, name_in, number_in)
{}
virtual Number F( FEMContext & /*context*/, unsigned int /*qp*/ ) libmesh_override
{ return -2.71; }
virtual Number C( FEMContext & /*context*/, unsigned int /*qp*/ ) libmesh_override
{ return 0.0; }
virtual Number M( FEMContext & /*context*/, unsigned int /*qp*/ ) libmesh_override
{ return 3.14; }
virtual Number u( Real t ) libmesh_override
{ return 2.71/3.14*0.5*t*t; }
};
//! Implements ODE: 1.0\ddot{u} = 6.0*t+2.0, u(0) = 0, \dot{u}(0) = 0
template<typename SystemBase>
class LinearTimeSecondOrderODE : public SystemBase
{
public:
LinearTimeSecondOrderODE(EquationSystems & es,
const std::string & name_in,
const unsigned int number_in)
: SystemBase(es, name_in, number_in)
{}
virtual Number F( FEMContext & context, unsigned int /*qp*/ ) libmesh_override
{ return -6.0*context.get_time()-2.0; }
virtual Number C( FEMContext & /*context*/, unsigned int /*qp*/ ) libmesh_override
{ return 0.0; }
virtual Number M( FEMContext & /*context*/, unsigned int /*qp*/ ) libmesh_override
{ return 1.0; }
virtual Number u( Real t ) libmesh_override
{ return t*t*t+t*t; }
};
class NewmarkSolverTestBase : public TimeSolverTestImplementation<NewmarkSolver>
{
public:
NewmarkSolverTestBase()
: TimeSolverTestImplementation<NewmarkSolver>(),
_beta(0.25)
{}
protected:
virtual void aux_time_solver_init( NewmarkSolver & time_solver ) libmesh_override
{ time_solver.set_beta(_beta);
time_solver.compute_initial_accel(); }
void set_beta( Real beta )
{ _beta = beta; }
Real _beta;
};
class NewmarkSolverTest : public CppUnit::TestCase,
public NewmarkSolverTestBase
{
public:
CPPUNIT_TEST_SUITE( NewmarkSolverTest );
CPPUNIT_TEST( testNewmarkSolverConstantSecondOrderODESecondOrderStyle );
CPPUNIT_TEST( testNewmarkSolverLinearTimeSecondOrderODESecondOrderStyle );
CPPUNIT_TEST( testNewmarkSolverConstantSecondOrderODEFirstOrderStyle );
CPPUNIT_TEST( testNewmarkSolverLinearTimeSecondOrderODEFirstOrderStyle );
CPPUNIT_TEST_SUITE_END();
public:
void testNewmarkSolverConstantSecondOrderODESecondOrderStyle()
{
this->run_test_with_exact_soln<ConstantSecondOrderODE<SecondOrderScalarSystemSecondOrderTimeSolverBase> >(0.5,10);
}
void testNewmarkSolverLinearTimeSecondOrderODESecondOrderStyle()
{
// For \beta = 1/6, we have the "linear acceleration method" for which
// we should be able to exactly integrate linear (in time) acceleration
// functions.
this->set_beta(1.0/6.0);
this->run_test_with_exact_soln<LinearTimeSecondOrderODE<SecondOrderScalarSystemSecondOrderTimeSolverBase> >(0.5,10);
}
void testNewmarkSolverConstantSecondOrderODEFirstOrderStyle()
{
this->run_test_with_exact_soln<ConstantSecondOrderODE<SecondOrderScalarSystemFirstOrderTimeSolverBase> >(0.5,10);
}
void testNewmarkSolverLinearTimeSecondOrderODEFirstOrderStyle()
{
// For \beta = 1/6, we have the "linear acceleration method" for which
// we should be able to exactly integrate linear (in time) acceleration
// functions.
this->set_beta(1.0/6.0);
this->run_test_with_exact_soln<LinearTimeSecondOrderODE<SecondOrderScalarSystemFirstOrderTimeSolverBase> >(0.5,10);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( NewmarkSolverTest );
|
Test Newmark using first order style
|
Test Newmark using first order style
These tests ensure that the new extended API for second order problems
with first order time solvers is also valid when using a second
order time solver.
|
C++
|
lgpl-2.1
|
svallaghe/libmesh,libMesh/libmesh,giorgiobornia/libmesh,BalticPinguin/libmesh,giorgiobornia/libmesh,benkirk/libmesh,hrittich/libmesh,libMesh/libmesh,pbauman/libmesh,capitalaslash/libmesh,roystgnr/libmesh,giorgiobornia/libmesh,90jrong/libmesh,hrittich/libmesh,pbauman/libmesh,jwpeterson/libmesh,vikramvgarg/libmesh,hrittich/libmesh,90jrong/libmesh,BalticPinguin/libmesh,vikramvgarg/libmesh,hrittich/libmesh,pbauman/libmesh,jwpeterson/libmesh,BalticPinguin/libmesh,jwpeterson/libmesh,jwpeterson/libmesh,jwpeterson/libmesh,90jrong/libmesh,pbauman/libmesh,benkirk/libmesh,90jrong/libmesh,benkirk/libmesh,balborian/libmesh,libMesh/libmesh,svallaghe/libmesh,vikramvgarg/libmesh,vikramvgarg/libmesh,svallaghe/libmesh,benkirk/libmesh,libMesh/libmesh,libMesh/libmesh,libMesh/libmesh,svallaghe/libmesh,roystgnr/libmesh,benkirk/libmesh,90jrong/libmesh,giorgiobornia/libmesh,hrittich/libmesh,giorgiobornia/libmesh,BalticPinguin/libmesh,jwpeterson/libmesh,capitalaslash/libmesh,pbauman/libmesh,hrittich/libmesh,vikramvgarg/libmesh,benkirk/libmesh,pbauman/libmesh,90jrong/libmesh,90jrong/libmesh,dschwen/libmesh,dschwen/libmesh,balborian/libmesh,hrittich/libmesh,balborian/libmesh,BalticPinguin/libmesh,balborian/libmesh,svallaghe/libmesh,balborian/libmesh,libMesh/libmesh,dschwen/libmesh,capitalaslash/libmesh,balborian/libmesh,BalticPinguin/libmesh,roystgnr/libmesh,balborian/libmesh,hrittich/libmesh,balborian/libmesh,balborian/libmesh,benkirk/libmesh,capitalaslash/libmesh,svallaghe/libmesh,BalticPinguin/libmesh,pbauman/libmesh,pbauman/libmesh,roystgnr/libmesh,dschwen/libmesh,jwpeterson/libmesh,dschwen/libmesh,BalticPinguin/libmesh,libMesh/libmesh,90jrong/libmesh,benkirk/libmesh,90jrong/libmesh,vikramvgarg/libmesh,benkirk/libmesh,balborian/libmesh,dschwen/libmesh,giorgiobornia/libmesh,svallaghe/libmesh,capitalaslash/libmesh,vikramvgarg/libmesh,giorgiobornia/libmesh,svallaghe/libmesh,roystgnr/libmesh,capitalaslash/libmesh,hrittich/libmesh,roystgnr/libmesh,vikramvgarg/libmesh,svallaghe/libmesh,dschwen/libmesh,roystgnr/libmesh,capitalaslash/libmesh,pbauman/libmesh,vikramvgarg/libmesh,giorgiobornia/libmesh,capitalaslash/libmesh,jwpeterson/libmesh,dschwen/libmesh,roystgnr/libmesh,giorgiobornia/libmesh
|
a5f0f79858e6c41a49b24fff3fbb8bd605d4cd23
|
torchvision/csrc/io/decoder/sync_decoder_test.cpp
|
torchvision/csrc/io/decoder/sync_decoder_test.cpp
|
#include <c10/util/Logging.h>
#include <dirent.h>
#include <gtest/gtest.h>
#include "memory_buffer.h"
#include "sync_decoder.h"
#include "util.h"
using namespace ffmpeg;
namespace {
struct VideoFileStats {
std::string name;
size_t durationPts{0};
int num{0};
int den{0};
int fps{0};
};
void gotAllTestFiles(
const std::string& folder,
std::vector<VideoFileStats>* stats) {
DIR* d = opendir(folder.c_str());
CHECK(d);
struct dirent* dir;
while ((dir = readdir(d))) {
if (dir->d_type != DT_DIR && 0 != strcmp(dir->d_name, "README")) {
VideoFileStats item;
item.name = folder + '/' + dir->d_name;
LOG(INFO) << "Found video file: " << item.name;
stats->push_back(std::move(item));
}
}
closedir(d);
}
void gotFilesStats(std::vector<VideoFileStats>& stats) {
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.seekAccuracy = 100000;
params.formats = {MediaFormat(0)};
params.headerOnly = true;
params.preventStaleness = false;
size_t avgProvUs = 0;
const size_t rounds = 100;
for (auto& item : stats) {
LOG(INFO) << "Decoding video file in memory: " << item.name;
FILE* f = fopen(item.name.c_str(), "rb");
CHECK(f != nullptr);
fseek(f, 0, SEEK_END);
std::vector<uint8_t> buffer(ftell(f));
rewind(f);
TORCH_CHECK_EQ(buffer.size(), fread(buffer.data(), 1, buffer.size(), f));
fclose(f);
for (size_t i = 0; i < rounds; ++i) {
SyncDecoder decoder;
std::vector<DecoderMetadata> metadata;
const auto now = std::chrono::steady_clock::now();
CHECK(decoder.init(
params,
MemoryBuffer::getCallback(buffer.data(), buffer.size()),
&metadata));
const auto then = std::chrono::steady_clock::now();
decoder.shutdown();
avgProvUs +=
std::chrono::duration_cast<std::chrono::microseconds>(then - now)
.count();
TORCH_CHECK_EQ(metadata.size(), 1);
item.num = metadata[0].num;
item.den = metadata[0].den;
item.fps = metadata[0].fps;
item.durationPts =
av_rescale_q(metadata[0].duration, AV_TIME_BASE_Q, {1, item.fps});
}
}
LOG(INFO) << "Probing (us) " << avgProvUs / stats.size() / rounds;
}
size_t measurePerformanceUs(
const std::vector<VideoFileStats>& stats,
size_t rounds,
size_t num,
size_t stride) {
size_t avgClipDecodingUs = 0;
std::srand(time(nullptr));
for (const auto& item : stats) {
FILE* f = fopen(item.name.c_str(), "rb");
CHECK(f != nullptr);
fseek(f, 0, SEEK_END);
std::vector<uint8_t> buffer(ftell(f));
rewind(f);
TORCH_CHECK_EQ(buffer.size(), fread(buffer.data(), 1, buffer.size(), f));
fclose(f);
for (size_t i = 0; i < rounds; ++i) {
// randomy select clip
size_t rOffset = std::rand();
size_t fOffset = rOffset % item.durationPts;
size_t clipFrames = num + (num - 1) * stride;
if (fOffset + clipFrames > item.durationPts) {
fOffset = item.durationPts - clipFrames;
}
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.seekAccuracy = 100000;
params.preventStaleness = false;
for (size_t n = 0; n < num; ++n) {
std::list<DecoderOutputMessage> msgs;
params.startOffset =
av_rescale_q(fOffset, {1, item.fps}, AV_TIME_BASE_Q);
params.endOffset = params.startOffset + 100;
auto now = std::chrono::steady_clock::now();
SyncDecoder decoder;
CHECK(decoder.init(
params,
MemoryBuffer::getCallback(buffer.data(), buffer.size()),
nullptr));
DecoderOutputMessage out;
while (0 == decoder.decode(&out, params.timeoutMs)) {
msgs.push_back(std::move(out));
}
decoder.shutdown();
const auto then = std::chrono::steady_clock::now();
fOffset += 1 + stride;
avgClipDecodingUs +=
std::chrono::duration_cast<std::chrono::microseconds>(then - now)
.count();
}
}
}
return avgClipDecodingUs / rounds / num / stats.size();
}
void runDecoder(SyncDecoder& decoder) {
DecoderOutputMessage out;
size_t audioFrames = 0, videoFrames = 0, totalBytes = 0;
while (0 == decoder.decode(&out, 10000)) {
if (out.header.format.type == TYPE_AUDIO) {
++audioFrames;
} else if (out.header.format.type == TYPE_VIDEO) {
++videoFrames;
} else if (out.header.format.type == TYPE_SUBTITLE && out.payload) {
// deserialize
LOG(INFO) << "Deserializing subtitle";
AVSubtitle sub;
memset(&sub, 0, sizeof(sub));
EXPECT_TRUE(Util::deserialize(*out.payload, &sub));
LOG(INFO) << "Found subtitles"
<< ", num rects: " << sub.num_rects;
for (int i = 0; i < sub.num_rects; ++i) {
std::string text = "picture";
if (sub.rects[i]->type == SUBTITLE_TEXT) {
text = sub.rects[i]->text;
} else if (sub.rects[i]->type == SUBTITLE_ASS) {
text = sub.rects[i]->ass;
}
LOG(INFO) << "Rect num: " << i << ", type:" << sub.rects[i]->type
<< ", text: " << text;
}
avsubtitle_free(&sub);
}
if (out.payload) {
totalBytes += out.payload->length();
}
}
LOG(INFO) << "Decoded audio frames: " << audioFrames
<< ", video frames: " << videoFrames
<< ", total bytes: " << totalBytes;
}
} // namespace
TEST(SyncDecoder, TestSyncDecoderPerformance) {
// Measure the average time of decoding per clip
// 1. list of the videos in testing directory
// 2. for each video got number of frames with timestamps
// 3. randomly select frame offset
// 4. adjust offset for number frames and strides,
// if it's out out upper boundary
// 5. repeat multiple times, measuring and accumulating decoding time
// per clip.
/*
1) 4 x 2
2) 8 x 8
3) 16 x 8
4) 32 x 4
*/
const std::string kFolder = "pytorch/vision/test/assets/videos";
std::vector<VideoFileStats> stats;
gotAllTestFiles(kFolder, &stats);
gotFilesStats(stats);
const size_t kRounds = 10;
auto new4x2 = measurePerformanceUs(stats, kRounds, 4, 2);
auto new8x8 = measurePerformanceUs(stats, kRounds, 8, 8);
auto new16x8 = measurePerformanceUs(stats, kRounds, 16, 8);
auto new32x4 = measurePerformanceUs(stats, kRounds, 32, 4);
LOG(INFO) << "Clip decoding (us)"
<< ", new(4x2): " << new4x2 << ", new(8x8): " << new8x8
<< ", new(16x8): " << new16x8 << ", new(32x4): " << new32x4;
}
TEST(SyncDecoder, Test) {
SyncDecoder decoder;
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.seekAccuracy = 100000;
params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
params.uri = "pytorch/vision/test/assets/videos/R6llTwEh07w.mp4";
CHECK(decoder.init(params, nullptr, nullptr));
runDecoder(decoder);
decoder.shutdown();
}
TEST(SyncDecoder, TestSubtitles) {
SyncDecoder decoder;
DecoderParameters params;
params.timeoutMs = 10000;
params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
params.uri = "vue/synergy/data/robotsub.mp4";
CHECK(decoder.init(params, nullptr, nullptr));
runDecoder(decoder);
decoder.shutdown();
}
TEST(SyncDecoder, TestHeadersOnly) {
SyncDecoder decoder;
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.seekAccuracy = 100000;
params.headerOnly = true;
params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
params.uri = "pytorch/vision/test/assets/videos/R6llTwEh07w.mp4";
CHECK(decoder.init(params, nullptr, nullptr));
runDecoder(decoder);
decoder.shutdown();
params.uri = "pytorch/vision/test/assets/videos/SOX5yA1l24A.mp4";
CHECK(decoder.init(params, nullptr, nullptr));
runDecoder(decoder);
decoder.shutdown();
params.uri = "pytorch/vision/test/assets/videos/WUzgd7C1pWA.mp4";
CHECK(decoder.init(params, nullptr, nullptr));
runDecoder(decoder);
decoder.shutdown();
}
TEST(SyncDecoder, TestHeadersOnlyDownSampling) {
SyncDecoder decoder;
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.seekAccuracy = 100000;
params.headerOnly = true;
MediaFormat format;
format.type = TYPE_AUDIO;
format.format.audio.samples = 8000;
params.formats.insert(format);
format.type = TYPE_VIDEO;
format.format.video.width = 224;
format.format.video.height = 224;
params.formats.insert(format);
params.uri = "pytorch/vision/test/assets/videos/R6llTwEh07w.mp4";
CHECK(decoder.init(params, nullptr, nullptr));
runDecoder(decoder);
decoder.shutdown();
params.uri = "pytorch/vision/test/assets/videos/SOX5yA1l24A.mp4";
CHECK(decoder.init(params, nullptr, nullptr));
runDecoder(decoder);
decoder.shutdown();
params.uri = "pytorch/vision/test/assets/videos/WUzgd7C1pWA.mp4";
CHECK(decoder.init(params, nullptr, nullptr));
runDecoder(decoder);
decoder.shutdown();
}
TEST(SyncDecoder, TestInitOnlyNoShutdown) {
SyncDecoder decoder;
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.seekAccuracy = 100000;
params.headerOnly = false;
params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
params.uri = "pytorch/vision/test/assets/videos/R6llTwEh07w.mp4";
std::vector<DecoderMetadata> metadata;
CHECK(decoder.init(params, nullptr, &metadata));
}
TEST(SyncDecoder, TestMemoryBuffer) {
SyncDecoder decoder;
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.endOffset = 9000000;
params.seekAccuracy = 10000;
params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
FILE* f = fopen(
"pytorch/vision/test/assets/videos/RATRACE_wave_f_nm_np1_fr_goo_37.avi",
"rb");
CHECK(f != nullptr);
fseek(f, 0, SEEK_END);
std::vector<uint8_t> buffer(ftell(f));
rewind(f);
TORCH_CHECK_EQ(buffer.size(), fread(buffer.data(), 1, buffer.size(), f));
fclose(f);
CHECK(decoder.init(
params,
MemoryBuffer::getCallback(buffer.data(), buffer.size()),
nullptr));
LOG(INFO) << "Decoding from memory bytes: " << buffer.size();
runDecoder(decoder);
decoder.shutdown();
}
TEST(SyncDecoder, TestMemoryBufferNoSeekableWithFullRead) {
SyncDecoder decoder;
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.endOffset = 9000000;
params.seekAccuracy = 10000;
params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
FILE* f = fopen("pytorch/vision/test/assets/videos/R6llTwEh07w.mp4", "rb");
CHECK(f != nullptr);
fseek(f, 0, SEEK_END);
std::vector<uint8_t> buffer(ftell(f));
rewind(f);
TORCH_CHECK_EQ(buffer.size(), fread(buffer.data(), 1, buffer.size(), f));
fclose(f);
params.maxSeekableBytes = buffer.size() + 1;
MemoryBuffer object(buffer.data(), buffer.size());
CHECK(decoder.init(
params,
[object](uint8_t* out, int size, int whence, uint64_t timeoutMs) mutable
-> int {
if (out) { // see defs.h file
// read mode
return object.read(out, size);
}
// seek mode
if (!timeoutMs) {
// seek capabilty, yes - no
return -1;
}
return object.seek(size, whence);
},
nullptr));
runDecoder(decoder);
decoder.shutdown();
}
TEST(SyncDecoder, TestMemoryBufferNoSeekableWithPartialRead) {
SyncDecoder decoder;
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.endOffset = 9000000;
params.seekAccuracy = 10000;
params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
FILE* f = fopen("pytorch/vision/test/assets/videos/R6llTwEh07w.mp4", "rb");
CHECK(f != nullptr);
fseek(f, 0, SEEK_END);
std::vector<uint8_t> buffer(ftell(f));
rewind(f);
TORCH_CHECK_EQ(buffer.size(), fread(buffer.data(), 1, buffer.size(), f));
fclose(f);
params.maxSeekableBytes = buffer.size() / 2;
MemoryBuffer object(buffer.data(), buffer.size());
CHECK(!decoder.init(
params,
[object](uint8_t* out, int size, int whence, uint64_t timeoutMs) mutable
-> int {
if (out) { // see defs.h file
// read mode
return object.read(out, size);
}
// seek mode
if (!timeoutMs) {
// seek capabilty, yes - no
return -1;
}
return object.seek(size, whence);
},
nullptr));
}
|
#include <c10/util/Logging.h>
#include <dirent.h>
#include <gtest/gtest.h>
#include "memory_buffer.h"
#include "sync_decoder.h"
#include "util.h"
using namespace ffmpeg;
namespace {
struct VideoFileStats {
std::string name;
size_t durationPts{0};
int num{0};
int den{0};
int fps{0};
};
void gotAllTestFiles(
const std::string& folder,
std::vector<VideoFileStats>* stats) {
DIR* d = opendir(folder.c_str());
CHECK(d);
struct dirent* dir;
while ((dir = readdir(d))) {
if (dir->d_type != DT_DIR && 0 != strcmp(dir->d_name, "README")) {
VideoFileStats item;
item.name = folder + '/' + dir->d_name;
LOG(INFO) << "Found video file: " << item.name;
stats->push_back(std::move(item));
}
}
closedir(d);
}
void gotFilesStats(std::vector<VideoFileStats>& stats) {
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.seekAccuracy = 100000;
params.formats = {MediaFormat(0)};
params.headerOnly = true;
params.preventStaleness = false;
size_t avgProvUs = 0;
const size_t rounds = 100;
for (auto& item : stats) {
LOG(INFO) << "Decoding video file in memory: " << item.name;
FILE* f = fopen(item.name.c_str(), "rb");
CHECK(f != nullptr);
fseek(f, 0, SEEK_END);
std::vector<uint8_t> buffer(ftell(f));
rewind(f);
size_t s = fread(buffer.data(), 1, buffer.size(), f);
TORCH_CHECK_EQ(buffer.size(), s);
fclose(f);
for (size_t i = 0; i < rounds; ++i) {
SyncDecoder decoder;
std::vector<DecoderMetadata> metadata;
const auto now = std::chrono::steady_clock::now();
CHECK(decoder.init(
params,
MemoryBuffer::getCallback(buffer.data(), buffer.size()),
&metadata));
const auto then = std::chrono::steady_clock::now();
decoder.shutdown();
avgProvUs +=
std::chrono::duration_cast<std::chrono::microseconds>(then - now)
.count();
TORCH_CHECK_EQ(metadata.size(), 1);
item.num = metadata[0].num;
item.den = metadata[0].den;
item.fps = metadata[0].fps;
item.durationPts =
av_rescale_q(metadata[0].duration, AV_TIME_BASE_Q, {1, item.fps});
}
}
LOG(INFO) << "Probing (us) " << avgProvUs / stats.size() / rounds;
}
size_t measurePerformanceUs(
const std::vector<VideoFileStats>& stats,
size_t rounds,
size_t num,
size_t stride) {
size_t avgClipDecodingUs = 0;
std::srand(time(nullptr));
for (const auto& item : stats) {
FILE* f = fopen(item.name.c_str(), "rb");
CHECK(f != nullptr);
fseek(f, 0, SEEK_END);
std::vector<uint8_t> buffer(ftell(f));
rewind(f);
size_t s = fread(buffer.data(), 1, buffer.size(), f);
TORCH_CHECK_EQ(buffer.size(), s);
fclose(f);
for (size_t i = 0; i < rounds; ++i) {
// randomy select clip
size_t rOffset = std::rand();
size_t fOffset = rOffset % item.durationPts;
size_t clipFrames = num + (num - 1) * stride;
if (fOffset + clipFrames > item.durationPts) {
fOffset = item.durationPts - clipFrames;
}
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.seekAccuracy = 100000;
params.preventStaleness = false;
for (size_t n = 0; n < num; ++n) {
std::list<DecoderOutputMessage> msgs;
params.startOffset =
av_rescale_q(fOffset, {1, item.fps}, AV_TIME_BASE_Q);
params.endOffset = params.startOffset + 100;
auto now = std::chrono::steady_clock::now();
SyncDecoder decoder;
CHECK(decoder.init(
params,
MemoryBuffer::getCallback(buffer.data(), buffer.size()),
nullptr));
DecoderOutputMessage out;
while (0 == decoder.decode(&out, params.timeoutMs)) {
msgs.push_back(std::move(out));
}
decoder.shutdown();
const auto then = std::chrono::steady_clock::now();
fOffset += 1 + stride;
avgClipDecodingUs +=
std::chrono::duration_cast<std::chrono::microseconds>(then - now)
.count();
}
}
}
return avgClipDecodingUs / rounds / num / stats.size();
}
void runDecoder(SyncDecoder& decoder) {
DecoderOutputMessage out;
size_t audioFrames = 0, videoFrames = 0, totalBytes = 0;
while (0 == decoder.decode(&out, 10000)) {
if (out.header.format.type == TYPE_AUDIO) {
++audioFrames;
} else if (out.header.format.type == TYPE_VIDEO) {
++videoFrames;
} else if (out.header.format.type == TYPE_SUBTITLE && out.payload) {
// deserialize
LOG(INFO) << "Deserializing subtitle";
AVSubtitle sub;
memset(&sub, 0, sizeof(sub));
EXPECT_TRUE(Util::deserialize(*out.payload, &sub));
LOG(INFO) << "Found subtitles"
<< ", num rects: " << sub.num_rects;
for (int i = 0; i < sub.num_rects; ++i) {
std::string text = "picture";
if (sub.rects[i]->type == SUBTITLE_TEXT) {
text = sub.rects[i]->text;
} else if (sub.rects[i]->type == SUBTITLE_ASS) {
text = sub.rects[i]->ass;
}
LOG(INFO) << "Rect num: " << i << ", type:" << sub.rects[i]->type
<< ", text: " << text;
}
avsubtitle_free(&sub);
}
if (out.payload) {
totalBytes += out.payload->length();
}
}
LOG(INFO) << "Decoded audio frames: " << audioFrames
<< ", video frames: " << videoFrames
<< ", total bytes: " << totalBytes;
}
} // namespace
TEST(SyncDecoder, TestSyncDecoderPerformance) {
// Measure the average time of decoding per clip
// 1. list of the videos in testing directory
// 2. for each video got number of frames with timestamps
// 3. randomly select frame offset
// 4. adjust offset for number frames and strides,
// if it's out out upper boundary
// 5. repeat multiple times, measuring and accumulating decoding time
// per clip.
/*
1) 4 x 2
2) 8 x 8
3) 16 x 8
4) 32 x 4
*/
const std::string kFolder = "pytorch/vision/test/assets/videos";
std::vector<VideoFileStats> stats;
gotAllTestFiles(kFolder, &stats);
gotFilesStats(stats);
const size_t kRounds = 10;
auto new4x2 = measurePerformanceUs(stats, kRounds, 4, 2);
auto new8x8 = measurePerformanceUs(stats, kRounds, 8, 8);
auto new16x8 = measurePerformanceUs(stats, kRounds, 16, 8);
auto new32x4 = measurePerformanceUs(stats, kRounds, 32, 4);
LOG(INFO) << "Clip decoding (us)"
<< ", new(4x2): " << new4x2 << ", new(8x8): " << new8x8
<< ", new(16x8): " << new16x8 << ", new(32x4): " << new32x4;
}
TEST(SyncDecoder, Test) {
SyncDecoder decoder;
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.seekAccuracy = 100000;
params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
params.uri = "pytorch/vision/test/assets/videos/R6llTwEh07w.mp4";
CHECK(decoder.init(params, nullptr, nullptr));
runDecoder(decoder);
decoder.shutdown();
}
TEST(SyncDecoder, TestSubtitles) {
SyncDecoder decoder;
DecoderParameters params;
params.timeoutMs = 10000;
params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
params.uri = "vue/synergy/data/robotsub.mp4";
CHECK(decoder.init(params, nullptr, nullptr));
runDecoder(decoder);
decoder.shutdown();
}
TEST(SyncDecoder, TestHeadersOnly) {
SyncDecoder decoder;
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.seekAccuracy = 100000;
params.headerOnly = true;
params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
params.uri = "pytorch/vision/test/assets/videos/R6llTwEh07w.mp4";
CHECK(decoder.init(params, nullptr, nullptr));
runDecoder(decoder);
decoder.shutdown();
params.uri = "pytorch/vision/test/assets/videos/SOX5yA1l24A.mp4";
CHECK(decoder.init(params, nullptr, nullptr));
runDecoder(decoder);
decoder.shutdown();
params.uri = "pytorch/vision/test/assets/videos/WUzgd7C1pWA.mp4";
CHECK(decoder.init(params, nullptr, nullptr));
runDecoder(decoder);
decoder.shutdown();
}
TEST(SyncDecoder, TestHeadersOnlyDownSampling) {
SyncDecoder decoder;
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.seekAccuracy = 100000;
params.headerOnly = true;
MediaFormat format;
format.type = TYPE_AUDIO;
format.format.audio.samples = 8000;
params.formats.insert(format);
format.type = TYPE_VIDEO;
format.format.video.width = 224;
format.format.video.height = 224;
params.formats.insert(format);
params.uri = "pytorch/vision/test/assets/videos/R6llTwEh07w.mp4";
CHECK(decoder.init(params, nullptr, nullptr));
runDecoder(decoder);
decoder.shutdown();
params.uri = "pytorch/vision/test/assets/videos/SOX5yA1l24A.mp4";
CHECK(decoder.init(params, nullptr, nullptr));
runDecoder(decoder);
decoder.shutdown();
params.uri = "pytorch/vision/test/assets/videos/WUzgd7C1pWA.mp4";
CHECK(decoder.init(params, nullptr, nullptr));
runDecoder(decoder);
decoder.shutdown();
}
TEST(SyncDecoder, TestInitOnlyNoShutdown) {
SyncDecoder decoder;
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.seekAccuracy = 100000;
params.headerOnly = false;
params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
params.uri = "pytorch/vision/test/assets/videos/R6llTwEh07w.mp4";
std::vector<DecoderMetadata> metadata;
CHECK(decoder.init(params, nullptr, &metadata));
}
TEST(SyncDecoder, TestMemoryBuffer) {
SyncDecoder decoder;
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.endOffset = 9000000;
params.seekAccuracy = 10000;
params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
FILE* f = fopen(
"pytorch/vision/test/assets/videos/RATRACE_wave_f_nm_np1_fr_goo_37.avi",
"rb");
CHECK(f != nullptr);
fseek(f, 0, SEEK_END);
std::vector<uint8_t> buffer(ftell(f));
rewind(f);
size_t s = fread(buffer.data(), 1, buffer.size(), f);
TORCH_CHECK_EQ(buffer.size(), s);
fclose(f);
CHECK(decoder.init(
params,
MemoryBuffer::getCallback(buffer.data(), buffer.size()),
nullptr));
LOG(INFO) << "Decoding from memory bytes: " << buffer.size();
runDecoder(decoder);
decoder.shutdown();
}
TEST(SyncDecoder, TestMemoryBufferNoSeekableWithFullRead) {
SyncDecoder decoder;
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.endOffset = 9000000;
params.seekAccuracy = 10000;
params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
FILE* f = fopen("pytorch/vision/test/assets/videos/R6llTwEh07w.mp4", "rb");
CHECK(f != nullptr);
fseek(f, 0, SEEK_END);
std::vector<uint8_t> buffer(ftell(f));
rewind(f);
size_t s = fread(buffer.data(), 1, buffer.size(), f);
TORCH_CHECK_EQ(buffer.size(), s);
fclose(f);
params.maxSeekableBytes = buffer.size() + 1;
MemoryBuffer object(buffer.data(), buffer.size());
CHECK(decoder.init(
params,
[object](uint8_t* out, int size, int whence, uint64_t timeoutMs) mutable
-> int {
if (out) { // see defs.h file
// read mode
return object.read(out, size);
}
// seek mode
if (!timeoutMs) {
// seek capabilty, yes - no
return -1;
}
return object.seek(size, whence);
},
nullptr));
runDecoder(decoder);
decoder.shutdown();
}
TEST(SyncDecoder, TestMemoryBufferNoSeekableWithPartialRead) {
SyncDecoder decoder;
DecoderParameters params;
params.timeoutMs = 10000;
params.startOffset = 1000000;
params.endOffset = 9000000;
params.seekAccuracy = 10000;
params.formats = {MediaFormat(), MediaFormat(0), MediaFormat('0')};
FILE* f = fopen("pytorch/vision/test/assets/videos/R6llTwEh07w.mp4", "rb");
CHECK(f != nullptr);
fseek(f, 0, SEEK_END);
std::vector<uint8_t> buffer(ftell(f));
rewind(f);
size_t s = fread(buffer.data(), 1, buffer.size(), f);
TORCH_CHECK_EQ(buffer.size(), s);
fclose(f);
params.maxSeekableBytes = buffer.size() / 2;
MemoryBuffer object(buffer.data(), buffer.size());
CHECK(!decoder.init(
params,
[object](uint8_t* out, int size, int whence, uint64_t timeoutMs) mutable
-> int {
if (out) { // see defs.h file
// read mode
return object.read(out, size);
}
// seek mode
if (!timeoutMs) {
// seek capabilty, yes - no
return -1;
}
return object.seek(size, whence);
},
nullptr));
}
|
Move func calls outside of *CHECK_* (#6357)
|
[FBcode->GH] Move func calls outside of *CHECK_* (#6357)
Summary:
Resolves https://www.internalfb.com/tasks/?t=128004042
Caused by TorchVision's PR at https://github.com/pytorch/vision/pull/6322 which was in response to a change on PyTorch Core at https://github.com/pytorch/pytorch/pull/82032
Reviewed By: fmassa
Differential Revision: D38383266
fbshipit-source-id: 3f0ebd04a610031c4720123d1869a851f76455cd
|
C++
|
bsd-3-clause
|
pytorch/vision,pytorch/vision,pytorch/vision,pytorch/vision,pytorch/vision,pytorch/vision
|
7666c1e752435e365cc18b9b07424a18a24937ef
|
trunk/libmesh/src/numerics/petsc_preconditioner.C
|
trunk/libmesh/src/numerics/petsc_preconditioner.C
|
// $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
#include "libmesh_common.h"
#ifdef LIBMESH_HAVE_PETSC
// C++ includes
// Local Includes
#include "auto_ptr.h"
#include "petsc_preconditioner.h"
#include "petsc_macro.h"
#include "petsc_matrix.h"
#include "petsc_vector.h"
#include "petsc_macro.h"
#include "libmesh_common.h"
template <typename T>
void
PetscPreconditioner<T>::apply(const NumericVector<T> & x, NumericVector<T> & y)
{
PetscVector<T> & x_pvec = libmesh_cast_ref<PetscVector<T>&>(const_cast<NumericVector<T>&>(x));
PetscVector<T> & y_pvec = libmesh_cast_ref<PetscVector<T>&>(const_cast<NumericVector<T>&>(y));
Vec x_vec = x_pvec.vec();
Vec y_vec = y_pvec.vec();
PCApply(_pc,x_vec,y_vec);
}
template <typename T>
void
PetscPreconditioner<T>::init ()
{
if(!this->_matrix)
{
std::cerr << "ERROR: No matrix set for PetscPreconditioner, but init() called" << std::endl;
libmesh_error();
}
//Clear the preconditioner in case it has been created in the past
if(this->_is_initialized)
PCDestroy(_pc);
//Create the preconditioning object
PCCreate(libMesh::COMM_WORLD,&_pc);
//Set the PCType
set_petsc_preconditioner_type(this->_preconditioner_type, _pc);
#ifdef LIBMESH_HAVE_PETSC_HYPRE
if(this->_preconditioner_type == AMG_PRECOND)
PCHYPRESetType(this->_pc, "boomeramg");
#endif
PetscMatrix<T> * pmatrix = libmesh_cast_ptr<PetscMatrix<T>*, SparseMatrix<T> >(this->_matrix);
_mat = pmatrix->mat();
PCSetOperators(_pc,_mat,_mat,SAME_NONZERO_PATTERN);
this->_is_initialized = true;
}
template <typename T>
void
PetscPreconditioner<T>::set_petsc_preconditioner_type (const PreconditionerType & preconditioner_type, PC & pc)
{
int ierr = 0;
switch (preconditioner_type)
{
case IDENTITY_PRECOND:
ierr = PCSetType (pc, (char*) PCNONE); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case CHOLESKY_PRECOND:
ierr = PCSetType (pc, (char*) PCCHOLESKY); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case ICC_PRECOND:
ierr = PCSetType (pc, (char*) PCICC); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case ILU_PRECOND:
ierr = PCSetType (pc, (char*) PCILU); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case LU_PRECOND:
ierr = PCSetType (pc, (char*) PCLU); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case ASM_PRECOND:
ierr = PCSetType (pc, (char*) PCASM); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case JACOBI_PRECOND:
ierr = PCSetType (pc, (char*) PCJACOBI); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case BLOCK_JACOBI_PRECOND:
ierr = PCSetType (pc, (char*) PCBJACOBI); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case SOR_PRECOND:
ierr = PCSetType (pc, (char*) PCSOR); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case EISENSTAT_PRECOND:
ierr = PCSetType (pc, (char*) PCEISENSTAT); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case AMG_PRECOND:
ierr = PCSetType (pc, (char*) PCHYPRE); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
#if !(PETSC_VERSION_LESS_THAN(2,1,2))
// Only available for PETSC >= 2.1.2
case USER_PRECOND:
ierr = PCSetType (pc, (char*) PCMAT); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
#endif
case SHELL_PRECOND:
ierr = PCSetType (pc, (char*) PCSHELL); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
default:
std::cerr << "ERROR: Unsupported PETSC Preconditioner: "
<< preconditioner_type << std::endl
<< "Continuing with PETSC defaults" << std::endl;
}
//Let the commandline override stuff
PCSetFromOptions(pc);
}
//------------------------------------------------------------------
// Explicit instantiations
template class PetscPreconditioner<Number>;
#endif // #ifdef LIBMESH_HAVE_PETSC
|
// $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
#include "libmesh_common.h"
#ifdef LIBMESH_HAVE_PETSC
// C++ includes
// Local Includes
#include "auto_ptr.h"
#include "petsc_preconditioner.h"
#include "petsc_macro.h"
#include "petsc_matrix.h"
#include "petsc_vector.h"
#include "petsc_macro.h"
#include "libmesh_common.h"
template <typename T>
void
PetscPreconditioner<T>::apply(const NumericVector<T> & x, NumericVector<T> & y)
{
PetscVector<T> & x_pvec = libmesh_cast_ref<PetscVector<T>&>(const_cast<NumericVector<T>&>(x));
PetscVector<T> & y_pvec = libmesh_cast_ref<PetscVector<T>&>(const_cast<NumericVector<T>&>(y));
Vec x_vec = x_pvec.vec();
Vec y_vec = y_pvec.vec();
PCApply(_pc,x_vec,y_vec);
}
template <typename T>
void
PetscPreconditioner<T>::init ()
{
if(!this->_matrix)
{
std::cerr << "ERROR: No matrix set for PetscPreconditioner, but init() called" << std::endl;
libmesh_error();
}
//Clear the preconditioner in case it has been created in the past
if(!this->_is_initialized)
{
//Create the preconditioning object
PCCreate(libMesh::COMM_WORLD,&_pc);
//Set the PCType
set_petsc_preconditioner_type(this->_preconditioner_type, _pc);
#ifdef LIBMESH_HAVE_PETSC_HYPRE
if(this->_preconditioner_type == AMG_PRECOND)
PCHYPRESetType(this->_pc, "boomeramg");
#endif
PetscMatrix<T> * pmatrix = libmesh_cast_ptr<PetscMatrix<T>*, SparseMatrix<T> >(this->_matrix);
_mat = pmatrix->mat();
}
PCSetOperators(_pc,_mat,_mat,SAME_NONZERO_PATTERN);
this->_is_initialized = true;
}
template <typename T>
void
PetscPreconditioner<T>::set_petsc_preconditioner_type (const PreconditionerType & preconditioner_type, PC & pc)
{
int ierr = 0;
switch (preconditioner_type)
{
case IDENTITY_PRECOND:
ierr = PCSetType (pc, (char*) PCNONE); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case CHOLESKY_PRECOND:
ierr = PCSetType (pc, (char*) PCCHOLESKY); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case ICC_PRECOND:
ierr = PCSetType (pc, (char*) PCICC); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case ILU_PRECOND:
ierr = PCSetType (pc, (char*) PCILU); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case LU_PRECOND:
ierr = PCSetType (pc, (char*) PCLU); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case ASM_PRECOND:
ierr = PCSetType (pc, (char*) PCASM); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case JACOBI_PRECOND:
ierr = PCSetType (pc, (char*) PCJACOBI); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case BLOCK_JACOBI_PRECOND:
ierr = PCSetType (pc, (char*) PCBJACOBI); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case SOR_PRECOND:
ierr = PCSetType (pc, (char*) PCSOR); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case EISENSTAT_PRECOND:
ierr = PCSetType (pc, (char*) PCEISENSTAT); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
case AMG_PRECOND:
ierr = PCSetType (pc, (char*) PCHYPRE); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
#if !(PETSC_VERSION_LESS_THAN(2,1,2))
// Only available for PETSC >= 2.1.2
case USER_PRECOND:
ierr = PCSetType (pc, (char*) PCMAT); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
#endif
case SHELL_PRECOND:
ierr = PCSetType (pc, (char*) PCSHELL); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;
default:
std::cerr << "ERROR: Unsupported PETSC Preconditioner: "
<< preconditioner_type << std::endl
<< "Continuing with PETSC defaults" << std::endl;
}
//Let the commandline override stuff
if( preconditioner_type != AMG_PRECOND )
PCSetFromOptions(pc);
}
//------------------------------------------------------------------
// Explicit instantiations
template class PetscPreconditioner<Number>;
#endif // #ifdef LIBMESH_HAVE_PETSC
|
allow reinitialization of petsc preconditioner
|
allow reinitialization of petsc preconditioner
git-svn-id: e88a1e38e13faf406e05cc89eca8dd613216f6c4@3423 434f946d-2f3d-0410-ba4c-cb9f52fb0dbf
|
C++
|
lgpl-2.1
|
aeslaughter/libmesh,pbauman/libmesh,vikramvgarg/libmesh,roystgnr/libmesh,hrittich/libmesh,coreymbryant/libmesh,capitalaslash/libmesh,pbauman/libmesh,dschwen/libmesh,roystgnr/libmesh,roystgnr/libmesh,friedmud/libmesh,jwpeterson/libmesh,capitalaslash/libmesh,jwpeterson/libmesh,balborian/libmesh,hrittich/libmesh,dknez/libmesh,90jrong/libmesh,pbauman/libmesh,capitalaslash/libmesh,benkirk/libmesh,vikramvgarg/libmesh,dschwen/libmesh,benkirk/libmesh,coreymbryant/libmesh,capitalaslash/libmesh,roystgnr/libmesh,svallaghe/libmesh,jwpeterson/libmesh,giorgiobornia/libmesh,cahaynes/libmesh,dknez/libmesh,dschwen/libmesh,dmcdougall/libmesh,svallaghe/libmesh,libMesh/libmesh,cahaynes/libmesh,BalticPinguin/libmesh,aeslaughter/libmesh,libMesh/libmesh,90jrong/libmesh,giorgiobornia/libmesh,dmcdougall/libmesh,dmcdougall/libmesh,hrittich/libmesh,giorgiobornia/libmesh,pbauman/libmesh,friedmud/libmesh,90jrong/libmesh,libMesh/libmesh,dschwen/libmesh,libMesh/libmesh,aeslaughter/libmesh,capitalaslash/libmesh,pbauman/libmesh,cahaynes/libmesh,BalticPinguin/libmesh,benkirk/libmesh,pbauman/libmesh,jwpeterson/libmesh,balborian/libmesh,aeslaughter/libmesh,vikramvgarg/libmesh,dmcdougall/libmesh,libMesh/libmesh,aeslaughter/libmesh,vikramvgarg/libmesh,BalticPinguin/libmesh,BalticPinguin/libmesh,aeslaughter/libmesh,balborian/libmesh,balborian/libmesh,friedmud/libmesh,dmcdougall/libmesh,benkirk/libmesh,aeslaughter/libmesh,roystgnr/libmesh,dknez/libmesh,hrittich/libmesh,benkirk/libmesh,vikramvgarg/libmesh,BalticPinguin/libmesh,balborian/libmesh,hrittich/libmesh,friedmud/libmesh,coreymbryant/libmesh,giorgiobornia/libmesh,giorgiobornia/libmesh,dmcdougall/libmesh,balborian/libmesh,dschwen/libmesh,benkirk/libmesh,svallaghe/libmesh,90jrong/libmesh,aeslaughter/libmesh,benkirk/libmesh,svallaghe/libmesh,svallaghe/libmesh,capitalaslash/libmesh,jwpeterson/libmesh,cahaynes/libmesh,giorgiobornia/libmesh,dschwen/libmesh,balborian/libmesh,hrittich/libmesh,coreymbryant/libmesh,svallaghe/libmesh,capitalaslash/libmesh,90jrong/libmesh,jwpeterson/libmesh,vikramvgarg/libmesh,90jrong/libmesh,BalticPinguin/libmesh,coreymbryant/libmesh,BalticPinguin/libmesh,vikramvgarg/libmesh,benkirk/libmesh,svallaghe/libmesh,vikramvgarg/libmesh,dknez/libmesh,dschwen/libmesh,friedmud/libmesh,90jrong/libmesh,jwpeterson/libmesh,dknez/libmesh,dschwen/libmesh,aeslaughter/libmesh,cahaynes/libmesh,BalticPinguin/libmesh,pbauman/libmesh,jwpeterson/libmesh,libMesh/libmesh,90jrong/libmesh,roystgnr/libmesh,friedmud/libmesh,libMesh/libmesh,svallaghe/libmesh,giorgiobornia/libmesh,coreymbryant/libmesh,cahaynes/libmesh,balborian/libmesh,roystgnr/libmesh,giorgiobornia/libmesh,vikramvgarg/libmesh,dknez/libmesh,coreymbryant/libmesh,pbauman/libmesh,balborian/libmesh,friedmud/libmesh,friedmud/libmesh,balborian/libmesh,friedmud/libmesh,cahaynes/libmesh,hrittich/libmesh,coreymbryant/libmesh,dmcdougall/libmesh,hrittich/libmesh,giorgiobornia/libmesh,svallaghe/libmesh,roystgnr/libmesh,benkirk/libmesh,dknez/libmesh,pbauman/libmesh,cahaynes/libmesh,capitalaslash/libmesh,hrittich/libmesh,libMesh/libmesh,dmcdougall/libmesh,dknez/libmesh,90jrong/libmesh
|
ef65861c3a2c14856d22e9dfd69a109fb27b5142
|
modules/planning/tasks/deciders/st_bounds_decider/st_bounds_decider.cc
|
modules/planning/tasks/deciders/st_bounds_decider/st_bounds_decider.cc
|
/******************************************************************************
* Copyright 2019 The Apollo 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 "modules/planning/tasks/deciders/st_bounds_decider/st_bounds_decider.h"
namespace apollo {
namespace planning {}
} // namespace apollo
|
/******************************************************************************
* Copyright 2019 The Apollo 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 "modules/planning/tasks/deciders/st_bounds_decider/st_bounds_decider.h"
namespace apollo {
namespace planning {
// TODO(Planning): Add something or remove file.
} // namespace planning
} // namespace apollo
|
Update st_bounds_decider.cc
|
Update st_bounds_decider.cc
|
C++
|
apache-2.0
|
ycool/apollo,jinghaomiao/apollo,ycool/apollo,xiaoxq/apollo,ApolloAuto/apollo,xiaoxq/apollo,jinghaomiao/apollo,jinghaomiao/apollo,xiaoxq/apollo,ycool/apollo,ApolloAuto/apollo,ycool/apollo,xiaoxq/apollo,ycool/apollo,ycool/apollo,xiaoxq/apollo,ApolloAuto/apollo,ApolloAuto/apollo,ApolloAuto/apollo,ApolloAuto/apollo,jinghaomiao/apollo,jinghaomiao/apollo,xiaoxq/apollo,jinghaomiao/apollo
|
553e88e2ac61beb7758072ae842b485041f4e5db
|
examples/Tooling/ClangCheck.cpp
|
examples/Tooling/ClangCheck.cpp
|
//===- examples/Tooling/ClangCheck.cpp - Clang check tool -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a clang-check tool that runs the
// clang::SyntaxOnlyAction over a number of translation units.
//
// Usage:
// clang-check <cmake-output-dir> <file1> <file2> ...
//
// Where <cmake-output-dir> is a CMake build directory in which a file named
// compile_commands.json exists (enable -DCMAKE_EXPORT_COMPILE_COMMANDS in
// CMake to get this output).
//
// <file1> ... specify the paths of files in the CMake source tree. This path
// is looked up in the compile command database. If the path of a file is
// absolute, it needs to point into CMake's source tree. If the path is
// relative, the current working directory needs to be in the CMake source
// tree and the file must be in a subdirectory of the current working
// directory. "./" prefixes in the relative files will be automatically
// removed, but the rest of a relative path must be a suffix of a path in
// the compile command line database.
//
// For example, to use clang-check on all files in a subtree of the source
// tree, use:
// /path/to/cmake/sources $ find . -name '*.cpp' \
// |xargs clang-check /path/to/cmake/build
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/system_error.h"
/// \brief Returns the absolute path of 'File', by prepending it with
/// 'BaseDirectory' if 'File' is not absolute. Otherwise returns 'File'.
/// If 'File' starts with "./", the returned path will not contain the "./".
/// Otherwise, the returned path will contain the literal path-concatenation of
/// 'BaseDirectory' and 'File'.
///
/// \param File Either an absolute or relative path.
/// \param BaseDirectory An absolute path.
///
/// FIXME: Put this somewhere where it is more generally available.
static std::string GetAbsolutePath(
llvm::StringRef File, llvm::StringRef BaseDirectory) {
assert(llvm::sys::path::is_absolute(BaseDirectory));
if (llvm::sys::path::is_absolute(File)) {
return File;
}
llvm::StringRef RelativePath(File);
if (RelativePath.startswith("./")) {
RelativePath = RelativePath.substr(strlen("./"));
}
llvm::SmallString<1024> AbsolutePath(BaseDirectory);
llvm::sys::path::append(AbsolutePath, RelativePath);
return AbsolutePath.str();
}
int main(int argc, char **argv) {
if (argc < 3) {
llvm::outs() << "Usage: " << argv[0] << " <cmake-output-dir> "
<< "<file1> <file2> ...\n";
return 1;
}
// FIXME: We should pull how to find the database into the Tooling package.
llvm::OwningPtr<llvm::MemoryBuffer> JsonDatabase;
llvm::SmallString<1024> JsonDatabasePath(argv[1]);
llvm::sys::path::append(JsonDatabasePath, "compile_commands.json");
llvm::error_code Result =
llvm::MemoryBuffer::getFile(JsonDatabasePath, JsonDatabase);
if (Result != 0) {
llvm::outs() << "Error while opening JSON database: " << Result.message()
<< "\n";
return 1;
}
llvm::StringRef BaseDirectory(::getenv("PWD"));
for (int I = 2; I < argc; ++I) {
llvm::SmallString<1024> File(GetAbsolutePath(argv[I], BaseDirectory));
llvm::outs() << "Processing " << File << ".\n";
std::string ErrorMessage;
clang::tooling::CompileCommand LookupResult =
clang::tooling::FindCompileArgsInJsonDatabase(
File.str(), JsonDatabase->getBuffer(), ErrorMessage);
if (!LookupResult.CommandLine.empty()) {
if (!clang::tooling::RunToolWithFlags(
new clang::SyntaxOnlyAction,
LookupResult.CommandLine.size(),
clang::tooling::CommandLineToArgv(
&LookupResult.CommandLine).data())) {
llvm::outs() << "Error while processing " << File << ".\n";
}
} else {
llvm::outs() << "Skipping " << File << ". Command line not found.\n";
}
}
return 0;
}
|
//===- examples/Tooling/ClangCheck.cpp - Clang check tool -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a clang-check tool that runs the
// clang::SyntaxOnlyAction over a number of translation units.
//
// Usage:
// clang-check <cmake-output-dir> <file1> <file2> ...
//
// Where <cmake-output-dir> is a CMake build directory in which a file named
// compile_commands.json exists (enable -DCMAKE_EXPORT_COMPILE_COMMANDS in
// CMake to get this output).
//
// <file1> ... specify the paths of files in the CMake source tree. This path
// is looked up in the compile command database. If the path of a file is
// absolute, it needs to point into CMake's source tree. If the path is
// relative, the current working directory needs to be in the CMake source
// tree and the file must be in a subdirectory of the current working
// directory. "./" prefixes in the relative files will be automatically
// removed, but the rest of a relative path must be a suffix of a path in
// the compile command line database.
//
// For example, to use clang-check on all files in a subtree of the source
// tree, use:
//
// /path/in/subtree $ find . -name '*.cpp'| xargs clang-check /path/to/source
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/system_error.h"
/// \brief Returns the absolute path of 'File', by prepending it with
/// 'BaseDirectory' if 'File' is not absolute. Otherwise returns 'File'.
/// If 'File' starts with "./", the returned path will not contain the "./".
/// Otherwise, the returned path will contain the literal path-concatenation of
/// 'BaseDirectory' and 'File'.
///
/// \param File Either an absolute or relative path.
/// \param BaseDirectory An absolute path.
///
/// FIXME: Put this somewhere where it is more generally available.
static std::string GetAbsolutePath(
llvm::StringRef File, llvm::StringRef BaseDirectory) {
assert(llvm::sys::path::is_absolute(BaseDirectory));
if (llvm::sys::path::is_absolute(File)) {
return File;
}
llvm::StringRef RelativePath(File);
if (RelativePath.startswith("./")) {
RelativePath = RelativePath.substr(strlen("./"));
}
llvm::SmallString<1024> AbsolutePath(BaseDirectory);
llvm::sys::path::append(AbsolutePath, RelativePath);
return AbsolutePath.str();
}
int main(int argc, char **argv) {
if (argc < 3) {
llvm::outs() << "Usage: " << argv[0] << " <cmake-output-dir> "
<< "<file1> <file2> ...\n";
return 1;
}
// FIXME: We should pull how to find the database into the Tooling package.
llvm::OwningPtr<llvm::MemoryBuffer> JsonDatabase;
llvm::SmallString<1024> JsonDatabasePath(argv[1]);
llvm::sys::path::append(JsonDatabasePath, "compile_commands.json");
llvm::error_code Result =
llvm::MemoryBuffer::getFile(JsonDatabasePath, JsonDatabase);
if (Result != 0) {
llvm::outs() << "Error while opening JSON database: " << Result.message()
<< "\n";
return 1;
}
llvm::StringRef BaseDirectory(::getenv("PWD"));
for (int I = 2; I < argc; ++I) {
llvm::SmallString<1024> File(GetAbsolutePath(argv[I], BaseDirectory));
llvm::outs() << "Processing " << File << ".\n";
std::string ErrorMessage;
clang::tooling::CompileCommand LookupResult =
clang::tooling::FindCompileArgsInJsonDatabase(
File.str(), JsonDatabase->getBuffer(), ErrorMessage);
if (!LookupResult.CommandLine.empty()) {
if (!clang::tooling::RunToolWithFlags(
new clang::SyntaxOnlyAction,
LookupResult.CommandLine.size(),
clang::tooling::CommandLineToArgv(
&LookupResult.CommandLine).data())) {
llvm::outs() << "Error while processing " << File << ".\n";
}
} else {
llvm::outs() << "Skipping " << File << ". Command line not found.\n";
}
}
return 0;
}
|
Fix gcc 'warning: multi-line comment'.
|
Fix gcc 'warning: multi-line comment'.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@130583 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang
|
e7ae0138477b0f724e0a737feaf3ba118a810ef1
|
dali/internal/text/text-abstraction/bidirectional-support-impl.cpp
|
dali/internal/text/text-abstraction/bidirectional-support-impl.cpp
|
/*
* Copyright (c) 2015 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.
*
*/
// CLASS HEADER
#include <dali/internal/text/text-abstraction/bidirectional-support-impl.h>
// INTERNAL INCLUDES
#include <dali/internal/system/common/singleton-service-impl.h>
// EXTERNAL INCLUDES
#include <memory.h>
#include <fribidi/fribidi.h>
namespace Dali
{
namespace TextAbstraction
{
namespace Internal
{
namespace
{
typedef unsigned char BidiDirection;
// Internal charcter's direction.
const BidiDirection LEFT_TO_RIGHT = 0u;
const BidiDirection NEUTRAL = 1u;
const BidiDirection RIGHT_TO_LEFT = 2u;
/**
* @param[in] paragraphDirection The FriBiDi paragraph's direction.
*
* @return Whether the paragraph is right to left.
*/
bool GetBidiParagraphDirection( FriBidiParType paragraphDirection )
{
switch( paragraphDirection )
{
case FRIBIDI_PAR_RTL: // Right-To-Left paragraph.
case FRIBIDI_PAR_WRTL: // Weak Right To Left paragraph.
{
return true;
}
case FRIBIDI_PAR_LTR: // Left-To-Right paragraph.
case FRIBIDI_PAR_ON: // DirectiOn-Neutral paragraph.
case FRIBIDI_PAR_WLTR: // Weak Left To Right paragraph.
{
return false;
}
}
return false;
}
BidiDirection GetBidiCharacterDirection( FriBidiCharType characterDirection )
{
switch( characterDirection )
{
case FRIBIDI_TYPE_LTR: // Left-To-Right letter.
case FRIBIDI_TYPE_EN: // European Numeral.
case FRIBIDI_TYPE_AN: // Arabic Numeral.
case FRIBIDI_TYPE_ES: // European number Separator.
case FRIBIDI_TYPE_ET: // European number Terminator.
{
return LEFT_TO_RIGHT;
}
case FRIBIDI_TYPE_RTL: // Right-To-Left letter.
case FRIBIDI_TYPE_AL: // Arabic Letter.
{
return RIGHT_TO_LEFT;
}
}
return NEUTRAL;
}
}
struct BidirectionalSupport::Plugin
{
/**
* Stores bidirectional info per paragraph.
*/
struct BidirectionalInfo
{
FriBidiCharType* characterTypes; ///< The type of each character (right, left, neutral, ...)
FriBidiLevel* embeddedLevels; ///< Embedded levels.
FriBidiParType paragraphDirection; ///< The paragraph's direction.
};
Plugin()
: mParagraphBidirectionalInfo(),
mFreeIndices()
{}
~Plugin()
{
// free all resources.
for( Vector<BidirectionalInfo*>::Iterator it = mParagraphBidirectionalInfo.Begin(),
endIt = mParagraphBidirectionalInfo.End();
it != endIt;
++it )
{
BidirectionalInfo* info = *it;
free( info->embeddedLevels );
free( info->characterTypes );
delete info;
}
}
BidiInfoIndex CreateInfo( const Character* const paragraph,
Length numberOfCharacters )
{
// Reserve memory for the paragraph's bidirectional info.
BidirectionalInfo* bidirectionalInfo = new BidirectionalInfo();
bidirectionalInfo->characterTypes = reinterpret_cast<FriBidiCharType*>( malloc( numberOfCharacters * sizeof( FriBidiCharType ) ) );
if( !bidirectionalInfo->characterTypes )
{
delete bidirectionalInfo;
return 0;
}
bidirectionalInfo->embeddedLevels = reinterpret_cast<FriBidiLevel*>( malloc( numberOfCharacters * sizeof( FriBidiLevel ) ) );
if( !bidirectionalInfo->embeddedLevels )
{
free( bidirectionalInfo->characterTypes );
delete bidirectionalInfo;
return 0;
}
// Retrieve the type of each character..
fribidi_get_bidi_types( paragraph, numberOfCharacters, bidirectionalInfo->characterTypes );
// Retrieve the paragraph's direction.
bidirectionalInfo->paragraphDirection = fribidi_get_par_direction( bidirectionalInfo->characterTypes, numberOfCharacters );
// Retrieve the embedding levels.
fribidi_get_par_embedding_levels( bidirectionalInfo->characterTypes, numberOfCharacters, &bidirectionalInfo->paragraphDirection, bidirectionalInfo->embeddedLevels );
// Store the bidirectional info and return the index.
BidiInfoIndex index = 0u;
if( 0u != mFreeIndices.Count() )
{
Vector<BidiInfoIndex>::Iterator it = mFreeIndices.End() - 1u;
index = *it;
mFreeIndices.Remove( it );
*( mParagraphBidirectionalInfo.Begin() + index ) = bidirectionalInfo;
}
else
{
index = static_cast<BidiInfoIndex>( mParagraphBidirectionalInfo.Count() );
mParagraphBidirectionalInfo.PushBack( bidirectionalInfo );
}
return index;
}
void DestroyInfo( BidiInfoIndex bidiInfoIndex )
{
if( bidiInfoIndex >= mParagraphBidirectionalInfo.Count() )
{
return;
}
// Retrieve the paragraph's bidirectional info.
Vector<BidirectionalInfo*>::Iterator it = mParagraphBidirectionalInfo.Begin() + bidiInfoIndex;
BidirectionalInfo* bidirectionalInfo = *it;
if( NULL != bidirectionalInfo )
{
// Free resources and destroy the container.
free( bidirectionalInfo->embeddedLevels );
free( bidirectionalInfo->characterTypes );
delete bidirectionalInfo;
*it = NULL;
}
// Add the index to the free indices vector.
mFreeIndices.PushBack( bidiInfoIndex );
}
void Reorder( BidiInfoIndex bidiInfoIndex,
CharacterIndex firstCharacterIndex,
Length numberOfCharacters,
CharacterIndex* visualToLogicalMap )
{
const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT | FRIBIDI_FLAGS_ARABIC;
// Retrieve the paragraph's bidirectional info.
const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex );
// Initialize the visual to logical mapping table to the identity. Otherwise fribidi_reorder_line fails to retrieve a valid mapping table.
for( CharacterIndex index = 0u; index < numberOfCharacters; ++index )
{
visualToLogicalMap[ index ] = index;
}
// Copy embedded levels as fribidi_reorder_line() may change them.
const uint32_t embeddedLevelsSize = numberOfCharacters * sizeof( FriBidiLevel );
FriBidiLevel* embeddedLevels = reinterpret_cast<FriBidiLevel*>( malloc( embeddedLevelsSize ) );
if( embeddedLevels )
{
memcpy( embeddedLevels, bidirectionalInfo->embeddedLevels + firstCharacterIndex, embeddedLevelsSize );
// Reorder the line.
fribidi_reorder_line( flags,
bidirectionalInfo->characterTypes + firstCharacterIndex,
numberOfCharacters,
0u,
bidirectionalInfo->paragraphDirection,
embeddedLevels,
NULL,
reinterpret_cast<FriBidiStrIndex*>( visualToLogicalMap ) );
// Free resources.
free( embeddedLevels );
}
}
bool GetMirroredText( Character* text,
CharacterDirection* directions,
Length numberOfCharacters ) const
{
bool updated = false;
for( CharacterIndex index = 0u; index < numberOfCharacters; ++index )
{
// Get a reference to the character inside the text.
Character& character = *( text + index );
// Retrieve the mirrored character.
FriBidiChar mirroredCharacter = character;
bool mirrored = false;
if( *( directions + index ) )
{
mirrored = fribidi_get_mirror_char( character, &mirroredCharacter );
}
updated = updated || mirrored;
// Update the character inside the text.
character = mirroredCharacter;
}
return updated;
}
bool GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const
{
// Retrieve the paragraph's bidirectional info.
const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex );
return GetBidiParagraphDirection( bidirectionalInfo->paragraphDirection );
}
void GetCharactersDirection( BidiInfoIndex bidiInfoIndex,
CharacterDirection* directions,
Length numberOfCharacters )
{
const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex );
const CharacterDirection paragraphDirection = GetBidiParagraphDirection( bidirectionalInfo->paragraphDirection );
CharacterDirection previousDirection = paragraphDirection;
for( CharacterIndex index = 0u; index < numberOfCharacters; ++index )
{
CharacterDirection& characterDirection = *( directions + index );
characterDirection = false;
// Get the bidi direction.
const BidiDirection bidiDirection = GetBidiCharacterDirection( *( bidirectionalInfo->characterTypes + index ) );
if( RIGHT_TO_LEFT == bidiDirection )
{
characterDirection = true;
}
else if( NEUTRAL == bidiDirection )
{
// For neutral characters it check's the next and previous directions.
// If they are equals set that direction. If they are not, sets the paragraph's direction.
// If there is no next, sets the paragraph's direction.
CharacterDirection nextDirection = paragraphDirection;
// Look for the next non-neutral character.
Length nextIndex = index + 1u;
for( ; nextIndex < numberOfCharacters; ++nextIndex )
{
BidiDirection nextBidiDirection = GetBidiCharacterDirection( *( bidirectionalInfo->characterTypes + nextIndex ) );
if( nextBidiDirection != NEUTRAL )
{
nextDirection = RIGHT_TO_LEFT == nextBidiDirection;
break;
}
}
// Calculate the direction for all the neutral characters.
characterDirection = previousDirection == nextDirection ? previousDirection : paragraphDirection;
// Set the direction to all the neutral characters.
++index;
for( ; index < nextIndex; ++index )
{
CharacterDirection& nextCharacterDirection = *( directions + index );
nextCharacterDirection = characterDirection;
}
// Set the direction of the next non-neutral character.
if( nextIndex < numberOfCharacters )
{
*( directions + nextIndex ) = nextDirection;
}
}
previousDirection = characterDirection;
}
}
Vector<BidirectionalInfo*> mParagraphBidirectionalInfo; ///< Stores the bidirectional info per paragraph.
Vector<BidiInfoIndex> mFreeIndices; ///< Stores indices of free positions in the bidirectional info vector.
};
BidirectionalSupport::BidirectionalSupport()
: mPlugin( NULL )
{
}
BidirectionalSupport::~BidirectionalSupport()
{
delete mPlugin;
}
TextAbstraction::BidirectionalSupport BidirectionalSupport::Get()
{
TextAbstraction::BidirectionalSupport bidirectionalSupportHandle;
SingletonService service( SingletonService::Get() );
if( service )
{
// Check whether the singleton is already created
BaseHandle handle = service.GetSingleton( typeid( TextAbstraction::BidirectionalSupport ) );
if(handle)
{
// If so, downcast the handle
BidirectionalSupport* impl = dynamic_cast< Internal::BidirectionalSupport* >( handle.GetObjectPtr() );
bidirectionalSupportHandle = TextAbstraction::BidirectionalSupport( impl );
}
else // create and register the object
{
bidirectionalSupportHandle = TextAbstraction::BidirectionalSupport( new BidirectionalSupport );
service.Register( typeid( bidirectionalSupportHandle ), bidirectionalSupportHandle );
}
}
return bidirectionalSupportHandle;
}
BidiInfoIndex BidirectionalSupport::CreateInfo( const Character* const paragraph,
Length numberOfCharacters )
{
CreatePlugin();
return mPlugin->CreateInfo( paragraph,
numberOfCharacters );
}
void BidirectionalSupport::DestroyInfo( BidiInfoIndex bidiInfoIndex )
{
CreatePlugin();
mPlugin->DestroyInfo( bidiInfoIndex );
}
void BidirectionalSupport::Reorder( BidiInfoIndex bidiInfoIndex,
CharacterIndex firstCharacterIndex,
Length numberOfCharacters,
CharacterIndex* visualToLogicalMap )
{
CreatePlugin();
mPlugin->Reorder( bidiInfoIndex,
firstCharacterIndex,
numberOfCharacters,
visualToLogicalMap );
}
bool BidirectionalSupport::GetMirroredText( Character* text,
CharacterDirection* directions,
Length numberOfCharacters )
{
CreatePlugin();
return mPlugin->GetMirroredText( text, directions, numberOfCharacters );
}
bool BidirectionalSupport::GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const
{
if( !mPlugin )
{
return false;
}
return mPlugin->GetParagraphDirection( bidiInfoIndex );
}
void BidirectionalSupport::GetCharactersDirection( BidiInfoIndex bidiInfoIndex,
CharacterDirection* directions,
Length numberOfCharacters )
{
CreatePlugin();
mPlugin->GetCharactersDirection( bidiInfoIndex,
directions,
numberOfCharacters );
}
void BidirectionalSupport::CreatePlugin()
{
if( !mPlugin )
{
mPlugin = new Plugin();
}
}
} // namespace Internal
} // namespace TextAbstraction
} // namespace Dali
|
/*
* Copyright (c) 2015 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.
*
*/
// CLASS HEADER
#include <dali/internal/text/text-abstraction/bidirectional-support-impl.h>
// INTERNAL INCLUDES
#include <dali/internal/system/common/singleton-service-impl.h>
// EXTERNAL INCLUDES
#include <memory.h>
#include <fribidi/fribidi.h>
#include <dali/integration-api/debug.h>
namespace Dali
{
namespace TextAbstraction
{
namespace Internal
{
namespace
{
typedef unsigned char BidiDirection;
// Internal charcter's direction.
const BidiDirection LEFT_TO_RIGHT = 0u;
const BidiDirection NEUTRAL = 1u;
const BidiDirection RIGHT_TO_LEFT = 2u;
/**
* @param[in] paragraphDirection The FriBiDi paragraph's direction.
*
* @return Whether the paragraph is right to left.
*/
bool GetBidiParagraphDirection( FriBidiParType paragraphDirection )
{
switch( paragraphDirection )
{
case FRIBIDI_PAR_RTL: // Right-To-Left paragraph.
case FRIBIDI_PAR_WRTL: // Weak Right To Left paragraph.
{
return true;
}
case FRIBIDI_PAR_LTR: // Left-To-Right paragraph.
case FRIBIDI_PAR_ON: // DirectiOn-Neutral paragraph.
case FRIBIDI_PAR_WLTR: // Weak Left To Right paragraph.
{
return false;
}
}
return false;
}
BidiDirection GetBidiCharacterDirection( FriBidiCharType characterDirection )
{
switch( characterDirection )
{
case FRIBIDI_TYPE_LTR: // Left-To-Right letter.
case FRIBIDI_TYPE_EN: // European Numeral.
case FRIBIDI_TYPE_AN: // Arabic Numeral.
case FRIBIDI_TYPE_ES: // European number Separator.
case FRIBIDI_TYPE_ET: // European number Terminator.
{
return LEFT_TO_RIGHT;
}
case FRIBIDI_TYPE_RTL: // Right-To-Left letter.
case FRIBIDI_TYPE_AL: // Arabic Letter.
{
return RIGHT_TO_LEFT;
}
}
return NEUTRAL;
}
}
struct BidirectionalSupport::Plugin
{
/**
* Stores bidirectional info per paragraph.
*/
struct BidirectionalInfo
{
FriBidiCharType* characterTypes; ///< The type of each character (right, left, neutral, ...)
FriBidiLevel* embeddedLevels; ///< Embedded levels.
FriBidiParType paragraphDirection; ///< The paragraph's direction.
};
Plugin()
: mParagraphBidirectionalInfo(),
mFreeIndices()
{}
~Plugin()
{
// free all resources.
for( Vector<BidirectionalInfo*>::Iterator it = mParagraphBidirectionalInfo.Begin(),
endIt = mParagraphBidirectionalInfo.End();
it != endIt;
++it )
{
BidirectionalInfo* info = *it;
free( info->embeddedLevels );
free( info->characterTypes );
delete info;
}
}
BidiInfoIndex CreateInfo( const Character* const paragraph,
Length numberOfCharacters )
{
// Reserve memory for the paragraph's bidirectional info.
BidirectionalInfo* bidirectionalInfo = new BidirectionalInfo();
bidirectionalInfo->characterTypes = reinterpret_cast<FriBidiCharType*>( malloc( numberOfCharacters * sizeof( FriBidiCharType ) ) );
if( !bidirectionalInfo->characterTypes )
{
delete bidirectionalInfo;
return 0;
}
bidirectionalInfo->embeddedLevels = reinterpret_cast<FriBidiLevel*>( malloc( numberOfCharacters * sizeof( FriBidiLevel ) ) );
if( !bidirectionalInfo->embeddedLevels )
{
free( bidirectionalInfo->characterTypes );
delete bidirectionalInfo;
return 0;
}
// Retrieve the type of each character..
fribidi_get_bidi_types( paragraph, numberOfCharacters, bidirectionalInfo->characterTypes );
// Retrieve the paragraph's direction.
bidirectionalInfo->paragraphDirection = fribidi_get_par_direction( bidirectionalInfo->characterTypes, numberOfCharacters );
// Retrieve the embedding levels.
if (fribidi_get_par_embedding_levels( bidirectionalInfo->characterTypes, numberOfCharacters, &bidirectionalInfo->paragraphDirection, bidirectionalInfo->embeddedLevels ) == 0)
{
free( bidirectionalInfo->characterTypes );
delete bidirectionalInfo;
return 0;
}
// Store the bidirectional info and return the index.
BidiInfoIndex index = 0u;
if( 0u != mFreeIndices.Count() )
{
Vector<BidiInfoIndex>::Iterator it = mFreeIndices.End() - 1u;
index = *it;
mFreeIndices.Remove( it );
*( mParagraphBidirectionalInfo.Begin() + index ) = bidirectionalInfo;
}
else
{
index = static_cast<BidiInfoIndex>( mParagraphBidirectionalInfo.Count() );
mParagraphBidirectionalInfo.PushBack( bidirectionalInfo );
}
return index;
}
void DestroyInfo( BidiInfoIndex bidiInfoIndex )
{
if( bidiInfoIndex >= mParagraphBidirectionalInfo.Count() )
{
return;
}
// Retrieve the paragraph's bidirectional info.
Vector<BidirectionalInfo*>::Iterator it = mParagraphBidirectionalInfo.Begin() + bidiInfoIndex;
BidirectionalInfo* bidirectionalInfo = *it;
if( NULL != bidirectionalInfo )
{
// Free resources and destroy the container.
free( bidirectionalInfo->embeddedLevels );
free( bidirectionalInfo->characterTypes );
delete bidirectionalInfo;
*it = NULL;
}
// Add the index to the free indices vector.
mFreeIndices.PushBack( bidiInfoIndex );
}
void Reorder( BidiInfoIndex bidiInfoIndex,
CharacterIndex firstCharacterIndex,
Length numberOfCharacters,
CharacterIndex* visualToLogicalMap )
{
const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT | FRIBIDI_FLAGS_ARABIC;
// Retrieve the paragraph's bidirectional info.
const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex );
// Initialize the visual to logical mapping table to the identity. Otherwise fribidi_reorder_line fails to retrieve a valid mapping table.
for( CharacterIndex index = 0u; index < numberOfCharacters; ++index )
{
visualToLogicalMap[ index ] = index;
}
// Copy embedded levels as fribidi_reorder_line() may change them.
const uint32_t embeddedLevelsSize = numberOfCharacters * sizeof( FriBidiLevel );
FriBidiLevel* embeddedLevels = reinterpret_cast<FriBidiLevel*>( malloc( embeddedLevelsSize ) );
if( embeddedLevels )
{
memcpy( embeddedLevels, bidirectionalInfo->embeddedLevels + firstCharacterIndex, embeddedLevelsSize );
// Reorder the line.
if (fribidi_reorder_line( flags,
bidirectionalInfo->characterTypes + firstCharacterIndex,
numberOfCharacters,
0u,
bidirectionalInfo->paragraphDirection,
embeddedLevels,
NULL,
reinterpret_cast<FriBidiStrIndex*>( visualToLogicalMap ) ) == 0)
{
DALI_LOG_ERROR("fribidi_reorder_line is failed\n");
}
// Free resources.
free( embeddedLevels );
}
}
bool GetMirroredText( Character* text,
CharacterDirection* directions,
Length numberOfCharacters ) const
{
bool updated = false;
for( CharacterIndex index = 0u; index < numberOfCharacters; ++index )
{
// Get a reference to the character inside the text.
Character& character = *( text + index );
// Retrieve the mirrored character.
FriBidiChar mirroredCharacter = character;
bool mirrored = false;
if( *( directions + index ) )
{
mirrored = fribidi_get_mirror_char( character, &mirroredCharacter );
}
updated = updated || mirrored;
// Update the character inside the text.
character = mirroredCharacter;
}
return updated;
}
bool GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const
{
// Retrieve the paragraph's bidirectional info.
const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex );
return GetBidiParagraphDirection( bidirectionalInfo->paragraphDirection );
}
void GetCharactersDirection( BidiInfoIndex bidiInfoIndex,
CharacterDirection* directions,
Length numberOfCharacters )
{
const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex );
const CharacterDirection paragraphDirection = GetBidiParagraphDirection( bidirectionalInfo->paragraphDirection );
CharacterDirection previousDirection = paragraphDirection;
for( CharacterIndex index = 0u; index < numberOfCharacters; ++index )
{
CharacterDirection& characterDirection = *( directions + index );
characterDirection = false;
// Get the bidi direction.
const BidiDirection bidiDirection = GetBidiCharacterDirection( *( bidirectionalInfo->characterTypes + index ) );
if( RIGHT_TO_LEFT == bidiDirection )
{
characterDirection = true;
}
else if( NEUTRAL == bidiDirection )
{
// For neutral characters it check's the next and previous directions.
// If they are equals set that direction. If they are not, sets the paragraph's direction.
// If there is no next, sets the paragraph's direction.
CharacterDirection nextDirection = paragraphDirection;
// Look for the next non-neutral character.
Length nextIndex = index + 1u;
for( ; nextIndex < numberOfCharacters; ++nextIndex )
{
BidiDirection nextBidiDirection = GetBidiCharacterDirection( *( bidirectionalInfo->characterTypes + nextIndex ) );
if( nextBidiDirection != NEUTRAL )
{
nextDirection = RIGHT_TO_LEFT == nextBidiDirection;
break;
}
}
// Calculate the direction for all the neutral characters.
characterDirection = previousDirection == nextDirection ? previousDirection : paragraphDirection;
// Set the direction to all the neutral characters.
++index;
for( ; index < nextIndex; ++index )
{
CharacterDirection& nextCharacterDirection = *( directions + index );
nextCharacterDirection = characterDirection;
}
// Set the direction of the next non-neutral character.
if( nextIndex < numberOfCharacters )
{
*( directions + nextIndex ) = nextDirection;
}
}
previousDirection = characterDirection;
}
}
Vector<BidirectionalInfo*> mParagraphBidirectionalInfo; ///< Stores the bidirectional info per paragraph.
Vector<BidiInfoIndex> mFreeIndices; ///< Stores indices of free positions in the bidirectional info vector.
};
BidirectionalSupport::BidirectionalSupport()
: mPlugin( NULL )
{
}
BidirectionalSupport::~BidirectionalSupport()
{
delete mPlugin;
}
TextAbstraction::BidirectionalSupport BidirectionalSupport::Get()
{
TextAbstraction::BidirectionalSupport bidirectionalSupportHandle;
SingletonService service( SingletonService::Get() );
if( service )
{
// Check whether the singleton is already created
BaseHandle handle = service.GetSingleton( typeid( TextAbstraction::BidirectionalSupport ) );
if(handle)
{
// If so, downcast the handle
BidirectionalSupport* impl = dynamic_cast< Internal::BidirectionalSupport* >( handle.GetObjectPtr() );
bidirectionalSupportHandle = TextAbstraction::BidirectionalSupport( impl );
}
else // create and register the object
{
bidirectionalSupportHandle = TextAbstraction::BidirectionalSupport( new BidirectionalSupport );
service.Register( typeid( bidirectionalSupportHandle ), bidirectionalSupportHandle );
}
}
return bidirectionalSupportHandle;
}
BidiInfoIndex BidirectionalSupport::CreateInfo( const Character* const paragraph,
Length numberOfCharacters )
{
CreatePlugin();
return mPlugin->CreateInfo( paragraph,
numberOfCharacters );
}
void BidirectionalSupport::DestroyInfo( BidiInfoIndex bidiInfoIndex )
{
CreatePlugin();
mPlugin->DestroyInfo( bidiInfoIndex );
}
void BidirectionalSupport::Reorder( BidiInfoIndex bidiInfoIndex,
CharacterIndex firstCharacterIndex,
Length numberOfCharacters,
CharacterIndex* visualToLogicalMap )
{
CreatePlugin();
mPlugin->Reorder( bidiInfoIndex,
firstCharacterIndex,
numberOfCharacters,
visualToLogicalMap );
}
bool BidirectionalSupport::GetMirroredText( Character* text,
CharacterDirection* directions,
Length numberOfCharacters )
{
CreatePlugin();
return mPlugin->GetMirroredText( text, directions, numberOfCharacters );
}
bool BidirectionalSupport::GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const
{
if( !mPlugin )
{
return false;
}
return mPlugin->GetParagraphDirection( bidiInfoIndex );
}
void BidirectionalSupport::GetCharactersDirection( BidiInfoIndex bidiInfoIndex,
CharacterDirection* directions,
Length numberOfCharacters )
{
CreatePlugin();
mPlugin->GetCharactersDirection( bidiInfoIndex,
directions,
numberOfCharacters );
}
void BidirectionalSupport::CreatePlugin()
{
if( !mPlugin )
{
mPlugin = new Plugin();
}
}
} // namespace Internal
} // namespace TextAbstraction
} // namespace Dali
|
Change for fribidi update
|
Change for fribidi update
In new fribidi version, we should use return of some APIs.
If don't use return values, fribidi makes warning.
So fix to use return values.
Signed-off-by: minho.sun <[email protected]>
Please enter the commit message for your changes. Lines starting
with '#' will be ignored, and an empty message aborts the commit.
On branch devel/master
Change-Id: Iddff19439774090f92739c58c9093ce401c171fc
|
C++
|
apache-2.0
|
dalihub/dali-adaptor,dalihub/dali-adaptor,dalihub/dali-adaptor,dalihub/dali-adaptor,dalihub/dali-adaptor
|
c34734cd3a36290a5a9fedfea5c650dff5307a12
|
vespalib/src/vespa/vespalib/net/crypto_engine.cpp
|
vespalib/src/vespa/vespalib/net/crypto_engine.cpp
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "crypto_engine.h"
#include <vector>
#include <chrono>
#include <thread>
#include <vespa/vespalib/xxhash/xxhash.h>
#include <assert.h>
namespace vespalib {
namespace {
struct HashState {
using clock = std::chrono::high_resolution_clock;
const void *self;
clock::time_point now;
HashState() : self(this), now(clock::now()) {}
};
char gen_key() {
HashState hash_state;
std::this_thread::sleep_for(std::chrono::microseconds(42));
return XXH64(&hash_state, sizeof(hash_state), 0);
}
class NullCryptoSocket : public CryptoSocket
{
private:
SocketHandle _socket;
public:
NullCryptoSocket(SocketHandle socket) : _socket(std::move(socket)) {}
int get_fd() const override { return _socket.get(); }
HandshakeResult handshake() override { return HandshakeResult::DONE; }
size_t min_read_buffer_size() const override { return 1; }
ssize_t read(char *buf, size_t len) override { return _socket.read(buf, len); }
ssize_t drain(char *, size_t) override { return 0; }
ssize_t write(const char *buf, size_t len) override { return _socket.write(buf, len); }
ssize_t flush() override { return 0; }
};
class XorCryptoSocket : public CryptoSocket
{
private:
static constexpr size_t CHUNK_SIZE = 4096;
enum class OP { READ_KEY, WRITE_KEY };
std::vector<OP> _op_stack;
char _my_key;
char _peer_key;
std::vector<char> _readbuf;
std::vector<char> _writebuf;
SocketHandle _socket;
bool is_blocked(ssize_t res, int error) const {
return ((res < 0) && ((error == EWOULDBLOCK) || (error == EAGAIN)));
}
HandshakeResult try_read_key() {
ssize_t res = _socket.read(&_peer_key, 1);
if (is_blocked(res, errno)) {
return HandshakeResult::NEED_READ;
}
return (res == 1)
? HandshakeResult::DONE
: HandshakeResult::FAIL;
}
HandshakeResult try_write_key() {
ssize_t res = _socket.write(&_my_key, 1);
if (is_blocked(res, errno)) {
return HandshakeResult::NEED_WRITE;
}
return (res == 1)
? HandshakeResult::DONE
: HandshakeResult::FAIL;
}
HandshakeResult perform_hs_op(OP op) {
if (op == OP::READ_KEY) {
return try_read_key();
} else {
assert(op == OP::WRITE_KEY);
return try_write_key();
}
}
public:
XorCryptoSocket(SocketHandle socket, bool is_server)
: _op_stack(is_server
? std::vector<OP>({OP::WRITE_KEY, OP::READ_KEY})
: std::vector<OP>({OP::READ_KEY, OP::WRITE_KEY})),
_my_key(gen_key()),
_peer_key(0),
_readbuf(),
_writebuf(),
_socket(std::move(socket)) {}
int get_fd() const override { return _socket.get(); }
HandshakeResult handshake() override {
while (!_op_stack.empty()) {
HandshakeResult partial_result = perform_hs_op(_op_stack.back());
if (partial_result != HandshakeResult::DONE) {
return partial_result;
}
_op_stack.pop_back();
}
return HandshakeResult::DONE;
}
size_t min_read_buffer_size() const override { return 1; }
ssize_t read(char *buf, size_t len) override {
if (_readbuf.empty()) {
_readbuf.resize(CHUNK_SIZE);
ssize_t res = _socket.read(&_readbuf[0], _readbuf.size());
if (res > 0) {
_readbuf.resize(res);
} else {
_readbuf.clear();
return res;
}
}
return drain(buf, len);
}
ssize_t drain(char *buf, size_t len) override {
size_t frame = std::min(len, _readbuf.size());
for (size_t i = 0; i < frame; ++i) {
buf[i] = (_readbuf[i] ^ _my_key);
}
_readbuf.erase(_readbuf.begin(), _readbuf.begin() + frame);
return frame;
}
ssize_t write(const char *buf, size_t len) override {
ssize_t res = flush();
while (res > 0) {
res = flush();
}
if (res < 0) {
return res;
}
size_t frame = std::min(len, CHUNK_SIZE);
for (size_t i = 0; i < frame; ++i) {
_writebuf.push_back(buf[i] ^ _peer_key);
}
return frame;
}
ssize_t flush() override {
if (!_writebuf.empty()) {
ssize_t res = _socket.write(&_writebuf[0], _writebuf.size());
if (res > 0) {
_writebuf.erase(_writebuf.begin(), _writebuf.begin() + res);
} else {
assert(res < 0);
}
return res;
}
return 0;
}
};
CryptoEngine::SP create_default_crypto_engine() {
// TODO: check VESPA_TLS_CONFIG_FILE here
// return std::make_shared<XorCryptoEngine>();
return std::make_shared<NullCryptoEngine>();
}
} // namespace vespalib::<unnamed>
std::mutex CryptoEngine::_shared_lock;
CryptoEngine::SP CryptoEngine::_shared_default(nullptr);
CryptoEngine::~CryptoEngine() = default;
CryptoEngine::SP
CryptoEngine::get_default()
{
std::lock_guard guard(_shared_lock);
if (!_shared_default) {
_shared_default = create_default_crypto_engine();
}
return _shared_default;
}
CryptoSocket::UP
NullCryptoEngine::create_crypto_socket(SocketHandle socket, bool)
{
return std::make_unique<NullCryptoSocket>(std::move(socket));
}
CryptoSocket::UP
XorCryptoEngine::create_crypto_socket(SocketHandle socket, bool is_server)
{
return std::make_unique<XorCryptoSocket>(std::move(socket), is_server);
}
} // namespace vespalib
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "crypto_engine.h"
#include <vector>
#include <chrono>
#include <thread>
#include <vespa/vespalib/xxhash/xxhash.h>
#include <vespa/vespalib/stllike/string.h>
#include <vespa/vespalib/net/tls/transport_security_options.h>
#include <vespa/vespalib/net/tls/transport_security_options_reading.h>
#include <vespa/vespalib/net/tls/tls_crypto_engine.h>
#include <assert.h>
namespace vespalib {
namespace {
struct HashState {
using clock = std::chrono::high_resolution_clock;
const void *self;
clock::time_point now;
HashState() : self(this), now(clock::now()) {}
};
char gen_key() {
HashState hash_state;
std::this_thread::sleep_for(std::chrono::microseconds(42));
return XXH64(&hash_state, sizeof(hash_state), 0);
}
class NullCryptoSocket : public CryptoSocket
{
private:
SocketHandle _socket;
public:
NullCryptoSocket(SocketHandle socket) : _socket(std::move(socket)) {}
int get_fd() const override { return _socket.get(); }
HandshakeResult handshake() override { return HandshakeResult::DONE; }
size_t min_read_buffer_size() const override { return 1; }
ssize_t read(char *buf, size_t len) override { return _socket.read(buf, len); }
ssize_t drain(char *, size_t) override { return 0; }
ssize_t write(const char *buf, size_t len) override { return _socket.write(buf, len); }
ssize_t flush() override { return 0; }
};
class XorCryptoSocket : public CryptoSocket
{
private:
static constexpr size_t CHUNK_SIZE = 4096;
enum class OP { READ_KEY, WRITE_KEY };
std::vector<OP> _op_stack;
char _my_key;
char _peer_key;
std::vector<char> _readbuf;
std::vector<char> _writebuf;
SocketHandle _socket;
bool is_blocked(ssize_t res, int error) const {
return ((res < 0) && ((error == EWOULDBLOCK) || (error == EAGAIN)));
}
HandshakeResult try_read_key() {
ssize_t res = _socket.read(&_peer_key, 1);
if (is_blocked(res, errno)) {
return HandshakeResult::NEED_READ;
}
return (res == 1)
? HandshakeResult::DONE
: HandshakeResult::FAIL;
}
HandshakeResult try_write_key() {
ssize_t res = _socket.write(&_my_key, 1);
if (is_blocked(res, errno)) {
return HandshakeResult::NEED_WRITE;
}
return (res == 1)
? HandshakeResult::DONE
: HandshakeResult::FAIL;
}
HandshakeResult perform_hs_op(OP op) {
if (op == OP::READ_KEY) {
return try_read_key();
} else {
assert(op == OP::WRITE_KEY);
return try_write_key();
}
}
public:
XorCryptoSocket(SocketHandle socket, bool is_server)
: _op_stack(is_server
? std::vector<OP>({OP::WRITE_KEY, OP::READ_KEY})
: std::vector<OP>({OP::READ_KEY, OP::WRITE_KEY})),
_my_key(gen_key()),
_peer_key(0),
_readbuf(),
_writebuf(),
_socket(std::move(socket)) {}
int get_fd() const override { return _socket.get(); }
HandshakeResult handshake() override {
while (!_op_stack.empty()) {
HandshakeResult partial_result = perform_hs_op(_op_stack.back());
if (partial_result != HandshakeResult::DONE) {
return partial_result;
}
_op_stack.pop_back();
}
return HandshakeResult::DONE;
}
size_t min_read_buffer_size() const override { return 1; }
ssize_t read(char *buf, size_t len) override {
if (_readbuf.empty()) {
_readbuf.resize(CHUNK_SIZE);
ssize_t res = _socket.read(&_readbuf[0], _readbuf.size());
if (res > 0) {
_readbuf.resize(res);
} else {
_readbuf.clear();
return res;
}
}
return drain(buf, len);
}
ssize_t drain(char *buf, size_t len) override {
size_t frame = std::min(len, _readbuf.size());
for (size_t i = 0; i < frame; ++i) {
buf[i] = (_readbuf[i] ^ _my_key);
}
_readbuf.erase(_readbuf.begin(), _readbuf.begin() + frame);
return frame;
}
ssize_t write(const char *buf, size_t len) override {
ssize_t res = flush();
while (res > 0) {
res = flush();
}
if (res < 0) {
return res;
}
size_t frame = std::min(len, CHUNK_SIZE);
for (size_t i = 0; i < frame; ++i) {
_writebuf.push_back(buf[i] ^ _peer_key);
}
return frame;
}
ssize_t flush() override {
if (!_writebuf.empty()) {
ssize_t res = _socket.write(&_writebuf[0], _writebuf.size());
if (res > 0) {
_writebuf.erase(_writebuf.begin(), _writebuf.begin() + res);
} else {
assert(res < 0);
}
return res;
}
return 0;
}
};
CryptoEngine::SP create_default_crypto_engine() {
const char *env = getenv("VESPA_TLS_CONFIG_FILE");
vespalib::string cfg_file = env ? env : "";
if (cfg_file.empty()) {
return std::make_shared<NullCryptoEngine>();
}
auto tls_opts = net::tls::read_options_from_json_file(cfg_file);
return std::make_shared<TlsCryptoEngine>(*tls_opts);
}
} // namespace vespalib::<unnamed>
std::mutex CryptoEngine::_shared_lock;
CryptoEngine::SP CryptoEngine::_shared_default(nullptr);
CryptoEngine::~CryptoEngine() = default;
CryptoEngine::SP
CryptoEngine::get_default()
{
std::lock_guard guard(_shared_lock);
if (!_shared_default) {
_shared_default = create_default_crypto_engine();
}
return _shared_default;
}
CryptoSocket::UP
NullCryptoEngine::create_crypto_socket(SocketHandle socket, bool)
{
return std::make_unique<NullCryptoSocket>(std::move(socket));
}
CryptoSocket::UP
XorCryptoEngine::create_crypto_socket(SocketHandle socket, bool is_server)
{
return std::make_unique<XorCryptoSocket>(std::move(socket), is_server);
}
} // namespace vespalib
|
enable tls when VESPA_TLS_CONFIG_FILE is set
|
enable tls when VESPA_TLS_CONFIG_FILE is set
|
C++
|
apache-2.0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
3b6660d8313d8db26832e62e0b2be7eac4c9b591
|
webkit/tools/test_shell/test_shell_webkit_init.cc
|
webkit/tools/test_shell/test_shell_webkit_init.cc
|
// 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 "webkit/tools/test_shell/test_shell_webkit_init.h"
#include "base/path_service.h"
#include "base/stats_counters.h"
#include "media/base/media.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDatabase.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSecurityPolicy.h"
#include "webkit/extensions/v8/gears_extension.h"
#include "webkit/extensions/v8/interval_extension.h"
#include "webkit/tools/test_shell/test_shell.h"
#if defined(OS_WIN)
#include "webkit/tools/test_shell/test_shell_webthemeengine.h"
#endif
TestShellWebKitInit::TestShellWebKitInit(bool layout_test_mode) {
v8::V8::SetCounterFunction(StatsTable::FindLocation);
WebKit::initialize(this);
WebKit::setLayoutTestMode(layout_test_mode);
WebKit::WebSecurityPolicy::registerURLSchemeAsLocal(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebKit::WebSecurityPolicy::registerURLSchemeAsNoAccess(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebKit::WebScriptController::enableV8SingleThreadMode();
WebKit::WebScriptController::registerExtension(
extensions_v8::GearsExtension::Get());
WebKit::WebScriptController::registerExtension(
extensions_v8::IntervalExtension::Get());
WebKit::WebRuntimeFeatures::enableSockets(true);
WebKit::WebRuntimeFeatures::enableApplicationCache(true);
WebKit::WebRuntimeFeatures::enableDatabase(true);
WebKit::WebRuntimeFeatures::enableWebGL(true);
WebKit::WebRuntimeFeatures::enablePushState(true);
WebKit::WebRuntimeFeatures::enableNotifications(true);
WebKit::WebRuntimeFeatures::enableTouch(true);
WebKit::WebRuntimeFeatures::enableIndexedDatabase(true);
WebKit::WebRuntimeFeatures::enableSpeechInput(true);
// TODO(hwennborg): Enable this once the implementation supports it.
WebKit::WebRuntimeFeatures::enableDeviceOrientation(false);
// Load libraries for media and enable the media player.
FilePath module_path;
WebKit::WebRuntimeFeatures::enableMediaPlayer(
PathService::Get(base::DIR_MODULE, &module_path) &&
media::InitializeMediaLibrary(module_path));
WebKit::WebRuntimeFeatures::enableGeolocation(true);
// Construct and initialize an appcache system for this scope.
// A new empty temp directory is created to house any cached
// content during the run. Upon exit that directory is deleted.
// If we can't create a tempdir, we'll use in-memory storage.
if (!appcache_dir_.CreateUniqueTempDir()) {
LOG(WARNING) << "Failed to create a temp dir for the appcache, "
"using in-memory storage.";
DCHECK(appcache_dir_.path().empty());
}
SimpleAppCacheSystem::InitializeOnUIThread(appcache_dir_.path());
WebKit::WebDatabase::setObserver(&database_system_);
file_system_.set_sandbox_enabled(false);
#if defined(OS_WIN)
// Ensure we pick up the default theme engine.
SetThemeEngine(NULL);
#endif
}
TestShellWebKitInit::~TestShellWebKitInit() {
WebKit::shutdown();
}
WebKit::WebClipboard* TestShellWebKitInit::clipboard() {
// Mock out clipboard calls in layout test mode so that tests don't mess
// with each other's copies/pastes when running in parallel.
if (TestShell::layout_test_mode()) {
return &mock_clipboard_;
} else {
return &real_clipboard_;
}
}
WebKit::WebData TestShellWebKitInit::loadResource(const char* name) {
if (!strcmp(name, "deleteButton")) {
// Create a red 30x30 square.
const char red_square[] =
"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52"
"\x00\x00\x00\x1e\x00\x00\x00\x1e\x04\x03\x00\x00\x00\xc9\x1e\xb3"
"\x91\x00\x00\x00\x30\x50\x4c\x54\x45\x00\x00\x00\x80\x00\x00\x00"
"\x80\x00\x80\x80\x00\x00\x00\x80\x80\x00\x80\x00\x80\x80\x80\x80"
"\x80\xc0\xc0\xc0\xff\x00\x00\x00\xff\x00\xff\xff\x00\x00\x00\xff"
"\xff\x00\xff\x00\xff\xff\xff\xff\xff\x7b\x1f\xb1\xc4\x00\x00\x00"
"\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a"
"\x9c\x18\x00\x00\x00\x17\x49\x44\x41\x54\x78\x01\x63\x98\x89\x0a"
"\x18\x50\xb9\x33\x47\xf9\xa8\x01\x32\xd4\xc2\x03\x00\x33\x84\x0d"
"\x02\x3a\x91\xeb\xa5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60"
"\x82";
return WebKit::WebData(red_square, arraysize(red_square));
}
return webkit_glue::WebKitClientImpl::loadResource(name);
}
|
// 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 "webkit/tools/test_shell/test_shell_webkit_init.h"
#include "base/path_service.h"
#include "base/stats_counters.h"
#include "media/base/media.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDatabase.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSecurityPolicy.h"
#include "webkit/extensions/v8/gears_extension.h"
#include "webkit/extensions/v8/interval_extension.h"
#include "webkit/tools/test_shell/test_shell.h"
#if defined(OS_WIN)
#include "webkit/tools/test_shell/test_shell_webthemeengine.h"
#endif
TestShellWebKitInit::TestShellWebKitInit(bool layout_test_mode) {
v8::V8::SetCounterFunction(StatsTable::FindLocation);
WebKit::initialize(this);
WebKit::setLayoutTestMode(layout_test_mode);
WebKit::WebSecurityPolicy::registerURLSchemeAsLocal(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebKit::WebSecurityPolicy::registerURLSchemeAsNoAccess(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebKit::WebScriptController::enableV8SingleThreadMode();
WebKit::WebScriptController::registerExtension(
extensions_v8::GearsExtension::Get());
WebKit::WebScriptController::registerExtension(
extensions_v8::IntervalExtension::Get());
WebKit::WebRuntimeFeatures::enableSockets(true);
WebKit::WebRuntimeFeatures::enableApplicationCache(true);
WebKit::WebRuntimeFeatures::enableDatabase(true);
WebKit::WebRuntimeFeatures::enableWebGL(true);
WebKit::WebRuntimeFeatures::enablePushState(true);
WebKit::WebRuntimeFeatures::enableNotifications(true);
WebKit::WebRuntimeFeatures::enableTouch(true);
WebKit::WebRuntimeFeatures::enableIndexedDatabase(true);
WebKit::WebRuntimeFeatures::enableSpeechInput(true);
// TODO(hwennborg): Enable this once the implementation supports it.
WebKit::WebRuntimeFeatures::enableDeviceMotion(false);
WebKit::WebRuntimeFeatures::enableDeviceOrientation(false);
// Load libraries for media and enable the media player.
FilePath module_path;
WebKit::WebRuntimeFeatures::enableMediaPlayer(
PathService::Get(base::DIR_MODULE, &module_path) &&
media::InitializeMediaLibrary(module_path));
WebKit::WebRuntimeFeatures::enableGeolocation(true);
// Construct and initialize an appcache system for this scope.
// A new empty temp directory is created to house any cached
// content during the run. Upon exit that directory is deleted.
// If we can't create a tempdir, we'll use in-memory storage.
if (!appcache_dir_.CreateUniqueTempDir()) {
LOG(WARNING) << "Failed to create a temp dir for the appcache, "
"using in-memory storage.";
DCHECK(appcache_dir_.path().empty());
}
SimpleAppCacheSystem::InitializeOnUIThread(appcache_dir_.path());
WebKit::WebDatabase::setObserver(&database_system_);
file_system_.set_sandbox_enabled(false);
#if defined(OS_WIN)
// Ensure we pick up the default theme engine.
SetThemeEngine(NULL);
#endif
}
TestShellWebKitInit::~TestShellWebKitInit() {
WebKit::shutdown();
}
WebKit::WebClipboard* TestShellWebKitInit::clipboard() {
// Mock out clipboard calls in layout test mode so that tests don't mess
// with each other's copies/pastes when running in parallel.
if (TestShell::layout_test_mode()) {
return &mock_clipboard_;
} else {
return &real_clipboard_;
}
}
WebKit::WebData TestShellWebKitInit::loadResource(const char* name) {
if (!strcmp(name, "deleteButton")) {
// Create a red 30x30 square.
const char red_square[] =
"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52"
"\x00\x00\x00\x1e\x00\x00\x00\x1e\x04\x03\x00\x00\x00\xc9\x1e\xb3"
"\x91\x00\x00\x00\x30\x50\x4c\x54\x45\x00\x00\x00\x80\x00\x00\x00"
"\x80\x00\x80\x80\x00\x00\x00\x80\x80\x00\x80\x00\x80\x80\x80\x80"
"\x80\xc0\xc0\xc0\xff\x00\x00\x00\xff\x00\xff\xff\x00\x00\x00\xff"
"\xff\x00\xff\x00\xff\xff\xff\xff\xff\x7b\x1f\xb1\xc4\x00\x00\x00"
"\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a"
"\x9c\x18\x00\x00\x00\x17\x49\x44\x41\x54\x78\x01\x63\x98\x89\x0a"
"\x18\x50\xb9\x33\x47\xf9\xa8\x01\x32\xd4\xc2\x03\x00\x33\x84\x0d"
"\x02\x3a\x91\xeb\xa5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60"
"\x82";
return WebKit::WebData(red_square, arraysize(red_square));
}
return webkit_glue::WebKitClientImpl::loadResource(name);
}
|
Disable device motion in test shell.
|
Disable device motion in test shell.
Review URL: http://codereview.chromium.org/3098005
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@55388 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,rogerwang/chromium,ltilve/chromium,dushu1203/chromium.src,dushu1203/chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,Just-D/chromium-1,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,anirudhSK/chromium,M4sse/chromium.src,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,keishi/chromium,keishi/chromium,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,markYoungH/chromium.src,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,anirudhSK/chromium,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,ltilve/chromium,ltilve/chromium,hujiajie/pa-chromium,patrickm/chromium.src,robclark/chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk,littlstar/chromium.src,fujunwei/chromium-crosswalk,Jonekee/chromium.src,ondra-novak/chromium.src,keishi/chromium,dushu1203/chromium.src,markYoungH/chromium.src,littlstar/chromium.src,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,zcbenz/cefode-chromium,keishi/chromium,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,rogerwang/chromium,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,keishi/chromium,Chilledheart/chromium,krieger-od/nwjs_chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,ltilve/chromium,rogerwang/chromium,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,anirudhSK/chromium,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,M4sse/chromium.src,fujunwei/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,ChromiumWebApps/chromium,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,Just-D/chromium-1,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,mogoweb/chromium-crosswalk,rogerwang/chromium,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,littlstar/chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,Just-D/chromium-1,ChromiumWebApps/chromium,dednal/chromium.src,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,keishi/chromium,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,Chilledheart/chromium,anirudhSK/chromium,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,Just-D/chromium-1,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,patrickm/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,patrickm/chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,robclark/chromium,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,jaruba/chromium.src,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,Jonekee/chromium.src,nacl-webkit/chrome_deps,dushu1203/chromium.src,robclark/chromium,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,jaruba/chromium.src,M4sse/chromium.src,robclark/chromium,ltilve/chromium,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,keishi/chromium,jaruba/chromium.src,nacl-webkit/chrome_deps,dednal/chromium.src,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,keishi/chromium,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,anirudhSK/chromium,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,robclark/chromium,hujiajie/pa-chromium,chuan9/chromium-crosswalk,Just-D/chromium-1,dednal/chromium.src,M4sse/chromium.src,jaruba/chromium.src,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,jaruba/chromium.src,Just-D/chromium-1,Chilledheart/chromium,fujunwei/chromium-crosswalk,dushu1203/chromium.src,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,Jonekee/chromium.src,ltilve/chromium,anirudhSK/chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,robclark/chromium,patrickm/chromium.src,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,dushu1203/chromium.src,timopulkkinen/BubbleFish,M4sse/chromium.src,nacl-webkit/chrome_deps,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,robclark/chromium,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,rogerwang/chromium,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,keishi/chromium,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,keishi/chromium,Just-D/chromium-1,Fireblend/chromium-crosswalk,rogerwang/chromium,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,nacl-webkit/chrome_deps,dednal/chromium.src,keishi/chromium,ChromiumWebApps/chromium,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,robclark/chromium,dushu1203/chromium.src,nacl-webkit/chrome_deps,ltilve/chromium,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,zcbenz/cefode-chromium,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,rogerwang/chromium,M4sse/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk,rogerwang/chromium,nacl-webkit/chrome_deps,robclark/chromium,robclark/chromium,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,hujiajie/pa-chromium,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,hujiajie/pa-chromium,nacl-webkit/chrome_deps,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,hujiajie/pa-chromium,jaruba/chromium.src,rogerwang/chromium,nacl-webkit/chrome_deps,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,Chilledheart/chromium,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,littlstar/chromium.src,M4sse/chromium.src
|
ce0d6f5c1d265344b615fe61345bea7e747d255b
|
modules/planning/lattice/trajectory_generation/trajectory_evaluator.cc
|
modules/planning/lattice/trajectory_generation/trajectory_evaluator.cc
|
/******************************************************************************
* Copyright 2017 The Apollo 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.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/lattice/trajectory_generation/trajectory_evaluator.h"
#include <algorithm>
#include <cmath>
#include <functional>
#include <limits>
#include <utility>
#include "modules/common/log.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/constraint_checker/constraint_checker1d.h"
#include "modules/planning/lattice/trajectory1d/piecewise_acceleration_trajectory1d.h"
namespace apollo {
namespace planning {
using Trajectory1d = Curve1d;
TrajectoryEvaluator::TrajectoryEvaluator(
const std::array<double, 3>& init_s, const PlanningTarget& planning_target,
const std::vector<std::shared_ptr<Trajectory1d>>& lon_trajectories,
const std::vector<std::shared_ptr<Trajectory1d>>& lat_trajectories,
std::shared_ptr<PathTimeGraph> path_time_graph)
: path_time_graph_(path_time_graph), init_s_(init_s) {
const double start_time = 0.0;
const double end_time = FLAGS_trajectory_time_length;
path_time_intervals_ = path_time_graph_->GetPathBlockingIntervals(
start_time, end_time, FLAGS_trajectory_time_resolution);
// if we have a stop point along the reference line,
// filter out the lon. trajectories that pass the stop point.
double stop_point = std::numeric_limits<double>::max();
if (planning_target.has_stop_point()) {
stop_point = planning_target.stop_point().s();
}
for (const auto lon_trajectory : lon_trajectories) {
double lon_end_s = lon_trajectory->Evaluate(0, end_time);
if (lon_end_s > stop_point) {
continue;
}
if (!ConstraintChecker1d::IsValidLongitudinalTrajectory(*lon_trajectory)) {
continue;
}
for (const auto lat_trajectory : lat_trajectories) {
/**
if (!ConstraintChecker1d::IsValidLateralTrajectory(*lat_trajectory,
*lon_trajectory)) {
continue;
}
*/
if (!FLAGS_enable_auto_tuning) {
double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory);
cost_queue_.push(PairCost({lon_trajectory, lat_trajectory}, cost));
} else {
std::vector<double> cost_components;
double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory,
&cost_components);
cost_queue_with_components_.push(PairCostWithComponents(
{lon_trajectory, lat_trajectory}, {cost_components, cost}));
}
}
}
if (!FLAGS_enable_auto_tuning) {
ADEBUG << "Number of valid 1d trajectory pairs: " << cost_queue_.size();
} else {
ADEBUG << "Number of valid 1d trajectory pairs: "
<< cost_queue_with_components_.size();
}
}
bool TrajectoryEvaluator::has_more_trajectory_pairs() const {
if (!FLAGS_enable_auto_tuning) {
return !cost_queue_.empty();
} else {
return !cost_queue_with_components_.empty();
}
}
std::size_t TrajectoryEvaluator::num_of_trajectory_pairs() const {
if (!FLAGS_enable_auto_tuning) {
return cost_queue_.size();
} else {
return cost_queue_with_components_.size();
}
}
std::pair<std::shared_ptr<Trajectory1d>, std::shared_ptr<Trajectory1d>>
TrajectoryEvaluator::next_top_trajectory_pair() {
CHECK(has_more_trajectory_pairs() == true);
if (!FLAGS_enable_auto_tuning) {
auto top = cost_queue_.top();
cost_queue_.pop();
return top.first;
} else {
auto top = cost_queue_with_components_.top();
cost_queue_with_components_.pop();
return top.first;
}
}
double TrajectoryEvaluator::top_trajectory_pair_cost() const {
if (!FLAGS_enable_auto_tuning) {
return cost_queue_.top().second;
} else {
return cost_queue_with_components_.top().second.second;
}
}
std::vector<double> TrajectoryEvaluator::top_trajectory_pair_component_cost()
const {
CHECK(FLAGS_enable_auto_tuning);
return cost_queue_with_components_.top().second.first;
}
double TrajectoryEvaluator::Evaluate(
const PlanningTarget& planning_target,
const std::shared_ptr<Trajectory1d>& lon_trajectory,
const std::shared_ptr<Trajectory1d>& lat_trajectory,
std::vector<double>* cost_components) const {
// Costs:
// 1. Cost of missing the objective, e.g., cruise, stop, etc.
// 2. Cost of logitudinal jerk
// 3. Cost of logitudinal collision
// 4. Cost of lateral offsets
// 5. Cost of lateral comfort
// Longitudinal costs
auto reference_s_dot = ComputeLongitudinalGuideVelocity(planning_target);
double lon_objective_cost = LonObjectiveCost(lon_trajectory, planning_target,
reference_s_dot);
double lon_jerk_cost = LonComfortCost(lon_trajectory);
double lon_collision_cost = LonCollisionCost(lon_trajectory);
// decides the longitudinal evaluation horizon for lateral trajectories.
double evaluation_horizon =
std::min(FLAGS_decision_horizon,
lon_trajectory->Evaluate(0, lon_trajectory->ParamLength()));
std::vector<double> s_values;
for (double s = 0.0; s < evaluation_horizon;
s += FLAGS_trajectory_space_resolution) {
s_values.push_back(s);
}
// Lateral costs
double lat_offset_cost = LatOffsetCost(lat_trajectory, s_values);
double lat_comfort_cost = LatComfortCost(lon_trajectory, lat_trajectory);
if (cost_components != nullptr) {
cost_components->push_back(lon_objective_cost);
cost_components->push_back(lon_jerk_cost);
cost_components->push_back(lon_collision_cost);
cost_components->push_back(lat_offset_cost);
}
return lon_objective_cost * FLAGS_weight_lon_travel +
lon_jerk_cost * FLAGS_weight_lon_jerk +
lon_collision_cost * FLAGS_weight_lon_collision +
lat_offset_cost * FLAGS_weight_lat_offset +
lat_comfort_cost * FLAGS_weight_lat_comfort;
}
double TrajectoryEvaluator::LatOffsetCost(
const std::shared_ptr<Trajectory1d>& lat_trajectory,
const std::vector<double>& s_values) const {
double lat_offset_start = lat_trajectory->Evaluate(0, 0.0);
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (const auto& s : s_values) {
double lat_offset = lat_trajectory->Evaluate(0, s);
double cost = lat_offset / FLAGS_lat_offset_bound;
if (lat_offset * lat_offset_start < 0.0) {
cost_sqr_sum += cost * cost * FLAGS_weight_opposite_side_offset;
cost_abs_sum += std::abs(cost) * FLAGS_weight_opposite_side_offset;
} else {
cost_sqr_sum += cost * cost * FLAGS_weight_same_side_offset;
cost_abs_sum += std::abs(cost) * FLAGS_weight_same_side_offset;
}
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
double TrajectoryEvaluator::LatComfortCost(
const std::shared_ptr<Trajectory1d>& lon_trajectory,
const std::shared_ptr<Trajectory1d>& lat_trajectory) const {
double max_cost = 0.0;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
double s = lon_trajectory->Evaluate(0, t);
double s_dot = lon_trajectory->Evaluate(1, t);
double s_dotdot = lon_trajectory->Evaluate(2, t);
double l_prime = lat_trajectory->Evaluate(1, s);
double l_primeprime = lat_trajectory->Evaluate(2, s);
double cost = l_primeprime * s_dot * s_dot + l_prime * s_dotdot;
max_cost = std::max(max_cost, std::abs(cost));
}
return max_cost;
}
double TrajectoryEvaluator::LonComfortCost(
const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
double jerk = lon_trajectory->Evaluate(3, t);
double cost = jerk / FLAGS_longitudinal_jerk_upper_bound;
cost_sqr_sum += cost * cost;
cost_abs_sum += std::abs(cost);
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
double TrajectoryEvaluator::LonObjectiveCost(
const std::shared_ptr<Trajectory1d>& lon_trajectory,
const PlanningTarget& planning_target,
const std::vector<double>& ref_s_dots) const {
double t_max = lon_trajectory->ParamLength();
double dist_s = lon_trajectory->Evaluate(0, t_max)
- lon_trajectory->Evaluate(0, 0.0);
double speed_cost_sqr_sum = 0.0;
double speed_cost_abs_sum = 0.0;
for (std::size_t i = 0; i < ref_s_dots.size(); ++i) {
double t = i * FLAGS_trajectory_time_resolution;
double cost = ref_s_dots[i] - lon_trajectory->Evaluate(1, t);
speed_cost_sqr_sum += cost * cost;
speed_cost_abs_sum += std::abs(cost);
}
double speed_cost =
speed_cost_sqr_sum / (speed_cost_abs_sum + FLAGS_lattice_epsilon);
double dist_travelled_cost = 1.0 / (1.0 + dist_s);
return (speed_cost * FLAGS_weight_target_speed +
dist_travelled_cost * FLAGS_weight_dist_travelled) /
(FLAGS_weight_target_speed + FLAGS_weight_dist_travelled);
}
// TODO(all): consider putting pointer of reference_line_info and frame
// while constructing trajectory evaluator
double TrajectoryEvaluator::LonCollisionCost(
const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (std::size_t i = 0; i < path_time_intervals_.size(); ++i) {
const auto& pt_interval = path_time_intervals_[i];
if (pt_interval.empty()) {
continue;
}
double t = i * FLAGS_trajectory_time_resolution;
double traj_s = lon_trajectory->Evaluate(0, t);
double sigma = FLAGS_lon_collision_cost_std;
for (const auto& m : pt_interval) {
double dist = 0.0;
if (traj_s < m.first - FLAGS_lon_collision_yield_buffer) {
dist = m.first - FLAGS_lon_collision_yield_buffer - traj_s;
} else if (traj_s > m.second + FLAGS_lon_collision_overtake_buffer) {
dist = traj_s - m.second - FLAGS_lon_collision_overtake_buffer;
}
double cost = std::exp(-dist * dist / (2.0 * sigma * sigma));
cost_sqr_sum += cost * cost;
cost_abs_sum += cost;
}
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
std::vector<double> TrajectoryEvaluator::evaluate_per_lonlat_trajectory(
const PlanningTarget& planning_target,
const std::vector<apollo::common::SpeedPoint> st_points,
const std::vector<apollo::common::FrenetFramePoint> sl_points) {
std::vector<double> ret;
return ret;
}
std::vector<double> TrajectoryEvaluator::ComputeLongitudinalGuideVelocity(
const PlanningTarget& planning_target) const {
double comfort_a = FLAGS_longitudinal_acceleration_lower_bound *
FLAGS_comfort_acceleration_factor;
double cruise_s_dot = planning_target.cruise_speed();
ConstantAccelerationTrajectory1d lon_traj(init_s_[0], cruise_s_dot);
if (!planning_target.has_stop_point()) {
lon_traj.AppendSgment(0.0, FLAGS_trajectory_time_length);
} else {
double stop_s = planning_target.stop_point().s();
double dist = stop_s - init_s_[0];
double stop_a = -cruise_s_dot * cruise_s_dot * 0.5 / dist;
if (stop_a > comfort_a) {
double stop_t = cruise_s_dot / (-comfort_a);
double stop_dist = cruise_s_dot * stop_t * 0.5;
double cruise_t = (dist - stop_dist) / cruise_s_dot;
lon_traj.AppendSgment(0.0, cruise_t);
lon_traj.AppendSgment(comfort_a, stop_t);
} else {
double stop_t = cruise_s_dot / (-stop_a);
lon_traj.AppendSgment(stop_a, stop_t);
}
if (lon_traj.ParamLength() < FLAGS_trajectory_time_length) {
lon_traj.AppendSgment(
0.0, FLAGS_trajectory_time_length - lon_traj.ParamLength());
}
}
std::vector<double> reference_s_dot;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
reference_s_dot.push_back(lon_traj.Evaluate(1, t));
}
return reference_s_dot;
}
} // namespace planning
} // namespace apollo
|
/******************************************************************************
* Copyright 2017 The Apollo 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.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/lattice/trajectory_generation/trajectory_evaluator.h"
#include <algorithm>
#include <cmath>
#include <functional>
#include <limits>
#include <utility>
#include "modules/common/log.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/constraint_checker/constraint_checker1d.h"
#include "modules/planning/lattice/trajectory1d/piecewise_acceleration_trajectory1d.h"
namespace apollo {
namespace planning {
using Trajectory1d = Curve1d;
TrajectoryEvaluator::TrajectoryEvaluator(
const std::array<double, 3>& init_s, const PlanningTarget& planning_target,
const std::vector<std::shared_ptr<Trajectory1d>>& lon_trajectories,
const std::vector<std::shared_ptr<Trajectory1d>>& lat_trajectories,
std::shared_ptr<PathTimeGraph> path_time_graph)
: path_time_graph_(path_time_graph), init_s_(init_s) {
const double start_time = 0.0;
const double end_time = FLAGS_trajectory_time_length;
path_time_intervals_ = path_time_graph_->GetPathBlockingIntervals(
start_time, end_time, FLAGS_trajectory_time_resolution);
// if we have a stop point along the reference line,
// filter out the lon. trajectories that pass the stop point.
double stop_point = std::numeric_limits<double>::max();
if (planning_target.has_stop_point()) {
stop_point = planning_target.stop_point().s();
}
for (const auto lon_trajectory : lon_trajectories) {
double lon_end_s = lon_trajectory->Evaluate(0, end_time);
if (lon_end_s > stop_point) {
continue;
}
if (!ConstraintChecker1d::IsValidLongitudinalTrajectory(*lon_trajectory)) {
continue;
}
for (const auto lat_trajectory : lat_trajectories) {
/**
if (!ConstraintChecker1d::IsValidLateralTrajectory(*lat_trajectory,
*lon_trajectory)) {
continue;
}
*/
if (!FLAGS_enable_auto_tuning) {
double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory);
cost_queue_.push(PairCost({lon_trajectory, lat_trajectory}, cost));
} else {
std::vector<double> cost_components;
double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory,
&cost_components);
cost_queue_with_components_.push(PairCostWithComponents(
{lon_trajectory, lat_trajectory}, {cost_components, cost}));
}
}
}
if (!FLAGS_enable_auto_tuning) {
ADEBUG << "Number of valid 1d trajectory pairs: " << cost_queue_.size();
} else {
ADEBUG << "Number of valid 1d trajectory pairs: "
<< cost_queue_with_components_.size();
}
}
bool TrajectoryEvaluator::has_more_trajectory_pairs() const {
if (!FLAGS_enable_auto_tuning) {
return !cost_queue_.empty();
} else {
return !cost_queue_with_components_.empty();
}
}
std::size_t TrajectoryEvaluator::num_of_trajectory_pairs() const {
if (!FLAGS_enable_auto_tuning) {
return cost_queue_.size();
} else {
return cost_queue_with_components_.size();
}
}
std::pair<std::shared_ptr<Trajectory1d>, std::shared_ptr<Trajectory1d>>
TrajectoryEvaluator::next_top_trajectory_pair() {
CHECK(has_more_trajectory_pairs() == true);
if (!FLAGS_enable_auto_tuning) {
auto top = cost_queue_.top();
cost_queue_.pop();
return top.first;
} else {
auto top = cost_queue_with_components_.top();
cost_queue_with_components_.pop();
return top.first;
}
}
double TrajectoryEvaluator::top_trajectory_pair_cost() const {
if (!FLAGS_enable_auto_tuning) {
return cost_queue_.top().second;
} else {
return cost_queue_with_components_.top().second.second;
}
}
std::vector<double> TrajectoryEvaluator::top_trajectory_pair_component_cost()
const {
CHECK(FLAGS_enable_auto_tuning);
return cost_queue_with_components_.top().second.first;
}
double TrajectoryEvaluator::Evaluate(
const PlanningTarget& planning_target,
const std::shared_ptr<Trajectory1d>& lon_trajectory,
const std::shared_ptr<Trajectory1d>& lat_trajectory,
std::vector<double>* cost_components) const {
// Costs:
// 1. Cost of missing the objective, e.g., cruise, stop, etc.
// 2. Cost of logitudinal jerk
// 3. Cost of logitudinal collision
// 4. Cost of lateral offsets
// 5. Cost of lateral comfort
// Longitudinal costs
auto reference_s_dot = ComputeLongitudinalGuideVelocity(planning_target);
double lon_objective_cost = LonObjectiveCost(lon_trajectory, planning_target,
reference_s_dot);
double lon_jerk_cost = LonComfortCost(lon_trajectory);
double lon_collision_cost = LonCollisionCost(lon_trajectory);
// decides the longitudinal evaluation horizon for lateral trajectories.
double evaluation_horizon =
std::min(FLAGS_decision_horizon,
lon_trajectory->Evaluate(0, lon_trajectory->ParamLength()));
std::vector<double> s_values;
for (double s = 0.0; s < evaluation_horizon;
s += FLAGS_trajectory_space_resolution) {
s_values.push_back(s);
}
// Lateral costs
double lat_offset_cost = LatOffsetCost(lat_trajectory, s_values);
double lat_comfort_cost = LatComfortCost(lon_trajectory, lat_trajectory);
if (cost_components != nullptr) {
cost_components->push_back(lon_objective_cost);
cost_components->push_back(lon_jerk_cost);
cost_components->push_back(lon_collision_cost);
cost_components->push_back(lat_offset_cost);
}
return lon_objective_cost * FLAGS_weight_lon_travel +
lon_jerk_cost * FLAGS_weight_lon_jerk +
lon_collision_cost * FLAGS_weight_lon_collision +
lat_offset_cost * FLAGS_weight_lat_offset +
lat_comfort_cost * FLAGS_weight_lat_comfort;
}
double TrajectoryEvaluator::LatOffsetCost(
const std::shared_ptr<Trajectory1d>& lat_trajectory,
const std::vector<double>& s_values) const {
double lat_offset_start = lat_trajectory->Evaluate(0, 0.0);
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (const auto& s : s_values) {
double lat_offset = lat_trajectory->Evaluate(0, s);
double cost = lat_offset / FLAGS_lat_offset_bound;
if (lat_offset * lat_offset_start < 0.0) {
cost_sqr_sum += cost * cost * FLAGS_weight_opposite_side_offset;
cost_abs_sum += std::abs(cost) * FLAGS_weight_opposite_side_offset;
} else {
cost_sqr_sum += cost * cost * FLAGS_weight_same_side_offset;
cost_abs_sum += std::abs(cost) * FLAGS_weight_same_side_offset;
}
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
double TrajectoryEvaluator::LatComfortCost(
const std::shared_ptr<Trajectory1d>& lon_trajectory,
const std::shared_ptr<Trajectory1d>& lat_trajectory) const {
double max_cost = 0.0;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
double s = lon_trajectory->Evaluate(0, t);
double s_dot = lon_trajectory->Evaluate(1, t);
double s_dotdot = lon_trajectory->Evaluate(2, t);
double l_prime = lat_trajectory->Evaluate(1, s);
double l_primeprime = lat_trajectory->Evaluate(2, s);
double cost = l_primeprime * s_dot * s_dot + l_prime * s_dotdot;
max_cost = std::max(max_cost, std::abs(cost));
}
return max_cost;
}
double TrajectoryEvaluator::LonComfortCost(
const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
double jerk = lon_trajectory->Evaluate(3, t);
double cost = jerk / FLAGS_longitudinal_jerk_upper_bound;
cost_sqr_sum += cost * cost;
cost_abs_sum += std::abs(cost);
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
double TrajectoryEvaluator::LonObjectiveCost(
const std::shared_ptr<Trajectory1d>& lon_trajectory,
const PlanningTarget& planning_target,
const std::vector<double>& ref_s_dots) const {
double t_max = lon_trajectory->ParamLength();
double dist_s = lon_trajectory->Evaluate(0, t_max)
- lon_trajectory->Evaluate(0, 0.0);
double speed_cost_sqr_sum = 0.0;
double speed_cost_weight_sum = 0.0;
for (std::size_t i = 0; i < ref_s_dots.size(); ++i) {
double t = i * FLAGS_trajectory_time_resolution;
double cost = ref_s_dots[i] - lon_trajectory->Evaluate(1, t);
speed_cost_sqr_sum += t * t * std::abs(cost);
speed_cost_weight_sum += t * t;
}
double speed_cost =
speed_cost_sqr_sum / (speed_cost_weight_sum + FLAGS_lattice_epsilon);
double dist_travelled_cost = 1.0 / (1.0 + dist_s);
return (speed_cost * FLAGS_weight_target_speed +
dist_travelled_cost * FLAGS_weight_dist_travelled) /
(FLAGS_weight_target_speed + FLAGS_weight_dist_travelled);
}
// TODO(all): consider putting pointer of reference_line_info and frame
// while constructing trajectory evaluator
double TrajectoryEvaluator::LonCollisionCost(
const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (std::size_t i = 0; i < path_time_intervals_.size(); ++i) {
const auto& pt_interval = path_time_intervals_[i];
if (pt_interval.empty()) {
continue;
}
double t = i * FLAGS_trajectory_time_resolution;
double traj_s = lon_trajectory->Evaluate(0, t);
double sigma = FLAGS_lon_collision_cost_std;
for (const auto& m : pt_interval) {
double dist = 0.0;
if (traj_s < m.first - FLAGS_lon_collision_yield_buffer) {
dist = m.first - FLAGS_lon_collision_yield_buffer - traj_s;
} else if (traj_s > m.second + FLAGS_lon_collision_overtake_buffer) {
dist = traj_s - m.second - FLAGS_lon_collision_overtake_buffer;
}
double cost = std::exp(-dist * dist / (2.0 * sigma * sigma));
cost_sqr_sum += cost * cost;
cost_abs_sum += cost;
}
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
std::vector<double> TrajectoryEvaluator::evaluate_per_lonlat_trajectory(
const PlanningTarget& planning_target,
const std::vector<apollo::common::SpeedPoint> st_points,
const std::vector<apollo::common::FrenetFramePoint> sl_points) {
std::vector<double> ret;
return ret;
}
std::vector<double> TrajectoryEvaluator::ComputeLongitudinalGuideVelocity(
const PlanningTarget& planning_target) const {
double comfort_a = FLAGS_longitudinal_acceleration_lower_bound *
FLAGS_comfort_acceleration_factor;
double cruise_s_dot = planning_target.cruise_speed();
ConstantAccelerationTrajectory1d lon_traj(init_s_[0], cruise_s_dot);
if (!planning_target.has_stop_point()) {
lon_traj.AppendSgment(0.0, FLAGS_trajectory_time_length);
} else {
double stop_s = planning_target.stop_point().s();
double dist = stop_s - init_s_[0];
double stop_a = -cruise_s_dot * cruise_s_dot * 0.5 / dist;
if (stop_a > comfort_a) {
double stop_t = cruise_s_dot / (-comfort_a);
double stop_dist = cruise_s_dot * stop_t * 0.5;
double cruise_t = (dist - stop_dist) / cruise_s_dot;
lon_traj.AppendSgment(0.0, cruise_t);
lon_traj.AppendSgment(comfort_a, stop_t);
} else {
double stop_t = cruise_s_dot / (-stop_a);
lon_traj.AppendSgment(stop_a, stop_t);
}
if (lon_traj.ParamLength() < FLAGS_trajectory_time_length) {
lon_traj.AppendSgment(
0.0, FLAGS_trajectory_time_length - lon_traj.ParamLength());
}
}
std::vector<double> reference_s_dot;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
reference_s_dot.push_back(lon_traj.Evaluate(1, t));
}
return reference_s_dot;
}
} // namespace planning
} // namespace apollo
|
adjust lon objective cost in lattice planner
|
Planning: adjust lon objective cost in lattice planner
|
C++
|
apache-2.0
|
msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo
|
d750cae3ffed7a6f51ca75f8b321cbbab3d8acfb
|
modules/phase_field/src/materials/SwitchingFunctionMaterial.C
|
modules/phase_field/src/materials/SwitchingFunctionMaterial.C
|
/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "SwitchingFunctionMaterial.h"
template <>
InputParameters
validParams<SwitchingFunctionMaterial>()
{
InputParameters params = validParams<OrderParameterFunctionMaterial>();
params.addClassDescription("Helper material to provide h(eta) and its derivative in one of two "
"polynomial forms.\nSIMPLE: 3*eta^2-2*eta^3\nHIGH: "
"eta^3*(6*eta^2-15*eta+10)");
MooseEnum h_order("SIMPLE=0 HIGH", "SIMPLE");
params.addParam<MooseEnum>(
"h_order", h_order, "Polynomial order of the switching function h(eta)");
params.set<std::string>("function_name") = std::string("h");
return params;
}
SwitchingFunctionMaterial::SwitchingFunctionMaterial(const InputParameters & parameters)
: OrderParameterFunctionMaterial(parameters), _h_order(getParam<MooseEnum>("h_order"))
{
}
void
SwitchingFunctionMaterial::computeQpProperties()
{
Real n = _eta[_qp];
// n = n > 1 ? 1 : (n < 0 ? 0 : n);
switch (_h_order)
{
case 0: // SIMPLE
_prop_f[_qp] = 3.0 * n * n - 2.0 * n * n * n;
_prop_df[_qp] = 6.0 * n - 6.0 * n * n;
_prop_d2f[_qp] = 6.0 - 12.0 * n;
break;
case 1: // HIGH
_prop_f[_qp] = n * n * n * (6.0 * n * n - 15.0 * n + 10.0);
_prop_df[_qp] = 30.0 * n * n * (n * n - 2.0 * n + 1.0);
_prop_d2f[_qp] = n * (120.0 * n * n - 180.0 * n + 60.0);
break;
default:
mooseError("Internal error");
}
}
|
/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "SwitchingFunctionMaterial.h"
template <>
InputParameters
validParams<SwitchingFunctionMaterial>()
{
InputParameters params = validParams<OrderParameterFunctionMaterial>();
params.addClassDescription("Helper material to provide h(eta) and its derivative in one of two "
"polynomial forms.\nSIMPLE: 3*eta^2-2*eta^3\nHIGH: "
"eta^3*(6*eta^2-15*eta+10)");
MooseEnum h_order("SIMPLE=0 HIGH", "SIMPLE");
params.addParam<MooseEnum>(
"h_order", h_order, "Polynomial order of the switching function h(eta)");
params.set<std::string>("function_name") = std::string("h");
return params;
}
SwitchingFunctionMaterial::SwitchingFunctionMaterial(const InputParameters & parameters)
: OrderParameterFunctionMaterial(parameters), _h_order(getParam<MooseEnum>("h_order"))
{
}
void
SwitchingFunctionMaterial::computeQpProperties()
{
Real n = _eta[_qp];
n = n > 1 ? 1 : (n < 0 ? 0 : n);
switch (_h_order)
{
case 0: // SIMPLE
_prop_f[_qp] = 3.0 * n * n - 2.0 * n * n * n;
_prop_df[_qp] = 6.0 * n - 6.0 * n * n;
_prop_d2f[_qp] = 6.0 - 12.0 * n;
break;
case 1: // HIGH
_prop_f[_qp] = n * n * n * (6.0 * n * n - 15.0 * n + 10.0);
_prop_df[_qp] = 30.0 * n * n * (n * n - 2.0 * n + 1.0);
_prop_d2f[_qp] = n * (120.0 * n * n - 180.0 * n + 60.0);
break;
default:
mooseError("Internal error");
}
}
|
Fix erratic change (#9379)
|
Fix erratic change (#9379)
|
C++
|
lgpl-2.1
|
permcody/moose,liuwenf/moose,lindsayad/moose,bwspenc/moose,liuwenf/moose,andrsd/moose,nuclear-wizard/moose,YaqiWang/moose,permcody/moose,liuwenf/moose,bwspenc/moose,laagesen/moose,SudiptaBiswas/moose,laagesen/moose,idaholab/moose,friedmud/moose,friedmud/moose,Chuban/moose,idaholab/moose,yipenggao/moose,idaholab/moose,YaqiWang/moose,dschwen/moose,nuclear-wizard/moose,laagesen/moose,jessecarterMOOSE/moose,SudiptaBiswas/moose,yipenggao/moose,YaqiWang/moose,permcody/moose,bwspenc/moose,milljm/moose,yipenggao/moose,friedmud/moose,liuwenf/moose,jessecarterMOOSE/moose,lindsayad/moose,SudiptaBiswas/moose,andrsd/moose,andrsd/moose,milljm/moose,dschwen/moose,harterj/moose,sapitts/moose,yipenggao/moose,dschwen/moose,sapitts/moose,harterj/moose,lindsayad/moose,YaqiWang/moose,sapitts/moose,liuwenf/moose,harterj/moose,bwspenc/moose,sapitts/moose,andrsd/moose,SudiptaBiswas/moose,lindsayad/moose,permcody/moose,friedmud/moose,dschwen/moose,andrsd/moose,Chuban/moose,bwspenc/moose,SudiptaBiswas/moose,sapitts/moose,laagesen/moose,liuwenf/moose,milljm/moose,harterj/moose,jessecarterMOOSE/moose,Chuban/moose,Chuban/moose,milljm/moose,idaholab/moose,lindsayad/moose,harterj/moose,jessecarterMOOSE/moose,nuclear-wizard/moose,milljm/moose,idaholab/moose,jessecarterMOOSE/moose,nuclear-wizard/moose,laagesen/moose,dschwen/moose
|
1b9f34543f79de343ebf3b38d1bbf97a577ce263
|
src/import/generic/memory/lib/spd/lrdimm/ddr4/lrdimm_raw_cards.C
|
src/import/generic/memory/lib/spd/lrdimm/ddr4/lrdimm_raw_cards.C
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/spd/lrdimm/ddr4/lrdimm_raw_cards.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file raw_cards.C
/// @brief LRDIMM raw card data structure
/// Contains RCW settings per raw card rev
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
// std lib
#include <vector>
// fapi2
#include <fapi2.H>
// mss lib
#include <generic/memory/lib/spd/lrdimm/ddr4/lrdimm_raw_cards.H>
namespace mss
{
///
/// @brief raw card B0 settings
///
// TODO RTC:160116 Fill in valid RCD data for LRDIMM
rcw_settings lrdimm_rc_b0( 0x00, // RC00
0x00, // RC01 (C might be the right answer)
0x00, // RC02
0x1F, // RC06_7
0x00, // RC09
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6C
0x00, // RC8X
0x00, // RC9X
0x00, // RCAx
0x07);// RCBX
namespace lrdimm
{
// TODO - RTC:160121 Catch all for adding raw card data for DIMMs
const std::vector< std::pair< uint8_t , rcw_settings> > RAW_CARDS =
{
// I expect this to grow as Warren M. expects us to have
// settings for every raw card that JEDEC puts out. Openpower
// can't break due to a missing raw card...
{raw_card_rev::B0, lrdimm_rc_b0},
};
}// lrdimm
}// mss
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/spd/lrdimm/ddr4/lrdimm_raw_cards.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file raw_cards.C
/// @brief LRDIMM raw card data structure
/// Contains RCW settings per raw card rev
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
// std lib
#include <vector>
// fapi2
#include <fapi2.H>
// mss lib
#include <generic/memory/lib/spd/lrdimm/ddr4/lrdimm_raw_cards.H>
namespace mss
{
///
/// @brief raw card B0 settings
///
// TODO RTC:160116 Fill in valid RCD data for LRDIMM
rcw_settings lrdimm_rc_b0( 0x00, // RC00
0x00, // RC01 (C might be the right answer)
0x00, // RC02
0x1F, // RC06_7
0x00, // RC09
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6C
0x00, // RC8X
0x00, // RC9X
0x00); // RCAX
namespace lrdimm
{
// TODO - RTC:160121 Catch all for adding raw card data for DIMMs
const std::vector< std::pair< uint8_t , rcw_settings> > RAW_CARDS =
{
// I expect this to grow as Warren M. expects us to have
// settings for every raw card that JEDEC puts out. Openpower
// can't break due to a missing raw card...
{raw_card_rev::B0, lrdimm_rc_b0},
};
}// lrdimm
}// mss
|
Fix CSID: 2 slave ranks, termination in RCBCX
|
Fix CSID: 2 slave ranks, termination in RCBCX
Change-Id: I26da5fb4fa7c3bc60d00b164d1a01ab6e25b9ffe
Original-Change-Id: Ie19985e858f5d90b7ca74319c080b156d758ec6a
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/41515
Reviewed-by: Louis Stermole <[email protected]>
Tested-by: Jenkins Server <[email protected]>
Tested-by: Hostboot CI <[email protected]>
Reviewed-by: STEPHEN GLANCY <[email protected]>
Reviewed-by: Jennifer A. Stofer <[email protected]>
|
C++
|
apache-2.0
|
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
|
eeb372c349cb3b6428aa2173c8d2e358093e5da6
|
PWG2/FEMTOSCOPY/AliFemtoUser/AliFemtoModelCorrFctnDirectYlm.cxx
|
PWG2/FEMTOSCOPY/AliFemtoUser/AliFemtoModelCorrFctnDirectYlm.cxx
|
////////////////////////////////////////////////////////////////////////////////
/// ///
/// AliFemtoModelCorrFctnDirectYlm - the class for correlation function which ///
/// uses the model framework and weight generation and saves the generated ///
/// emission source ///
/// Authors: Adam Kisiel, [email protected] ///
/// ///
////////////////////////////////////////////////////////////////////////////////
#ifdef __ROOT__
ClassImp(AliFemtoModelCorrFctnDirectYlm, 1)
#endif
#include "AliFemtoModelGausLCMSFreezeOutGenerator.h"
#include "AliFemtoModelHiddenInfo.h"
#include "AliFemtoModelCorrFctnDirectYlm.h"
//_______________________
AliFemtoModelCorrFctnDirectYlm::AliFemtoModelCorrFctnDirectYlm():
AliFemtoModelCorrFctn(),
fCYlmTrue(0),
fCYlmFake(0),
fUseLCMS(0)
{
// default constructor
fCYlmTrue = new AliFemtoCorrFctnDirectYlm();
fCYlmFake = new AliFemtoCorrFctnDirectYlm();
fCYlmTrue->SetUseLCMS(fUseLCMS);
fCYlmFake->SetUseLCMS(fUseLCMS);
}
//_______________________
AliFemtoModelCorrFctnDirectYlm::AliFemtoModelCorrFctnDirectYlm(const char *title, Int_t aMaxL, Int_t aNbins, Double_t aQinvLo, Double_t aQinvHi, int aUseLCMS=0):
AliFemtoModelCorrFctn(title, aNbins, aQinvLo, aQinvHi),
fCYlmTrue(0),
fCYlmFake(0),
fUseLCMS(aUseLCMS)
{
// basic constructor
char fname[1000];
snprintf(fname, 1000, "%s%s", title, "True");
fCYlmTrue = new AliFemtoCorrFctnDirectYlm(fname, aMaxL, aNbins, aQinvLo, aQinvHi, fUseLCMS);
snprintf(fname, 1000, "%s%s", title, "Fake");
fCYlmFake = new AliFemtoCorrFctnDirectYlm(fname, aMaxL, aNbins, aQinvLo, aQinvHi, fUseLCMS);
}
//_______________________
AliFemtoModelCorrFctnDirectYlm::AliFemtoModelCorrFctnDirectYlm(const AliFemtoModelCorrFctnDirectYlm& aCorrFctn):
AliFemtoModelCorrFctn(aCorrFctn),
fCYlmTrue(new AliFemtoCorrFctnDirectYlm(*(aCorrFctn.fCYlmTrue))),
fCYlmFake(new AliFemtoCorrFctnDirectYlm(*(aCorrFctn.fCYlmFake))),
fUseLCMS(0)
{
// copy constructor
fUseLCMS = aCorrFctn.fUseLCMS;
// fCYlmTrue = dynamic_cast<AliFemtoCorrFctnDirectYlm*>(aCorrFctn.fCYlmTrue->Clone());
// fCYlmFake = dynamic_cast<AliFemtoCorrFctnDirectYlm*>(aCorrFctn.fCYlmFake->Clone());
}
//_______________________
AliFemtoModelCorrFctnDirectYlm::~AliFemtoModelCorrFctnDirectYlm()
{
// destructor
if (fCYlmTrue) delete fCYlmTrue;
if (fCYlmFake) delete fCYlmFake;
if (fNumeratorTrue) delete fNumeratorTrue;
if (fNumeratorFake) delete fNumeratorFake;
if (fDenominator) delete fDenominator;
}
//_______________________
AliFemtoModelCorrFctnDirectYlm& AliFemtoModelCorrFctnDirectYlm::operator=(const AliFemtoModelCorrFctnDirectYlm& aCorrFctn)
{
// assignment operator
if (this == &aCorrFctn)
return *this;
fUseLCMS = aCorrFctn.fUseLCMS;
if (aCorrFctn.fCYlmTrue)
fCYlmTrue = dynamic_cast<AliFemtoCorrFctnDirectYlm*>(aCorrFctn.fCYlmTrue->Clone());
else fCYlmTrue = 0;
if (aCorrFctn.fCYlmFake)
fCYlmFake = dynamic_cast<AliFemtoCorrFctnDirectYlm*>(aCorrFctn.fCYlmFake->Clone());
else fCYlmFake = 0;
if (aCorrFctn.fNumeratorTrue)
fNumeratorTrue = new TH1D(*aCorrFctn.fNumeratorTrue);
else
fNumeratorTrue = 0;
if (aCorrFctn.fNumeratorFake)
fNumeratorFake = new TH1D(*aCorrFctn.fNumeratorFake);
else
fNumeratorFake = 0;
if (aCorrFctn.fDenominator)
fDenominator = new TH1D(*aCorrFctn.fDenominator);
else
fDenominator = 0;
return *this;
}
//_______________________
AliFemtoString AliFemtoModelCorrFctnDirectYlm::Report()
{
// construct report
AliFemtoString tStr = "AliFemtoModelCorrFctnDirectYlm report";
return tStr;
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::AddRealPair(AliFemtoPair* aPair)
{
// add real (effect) pair
if (fPairCut)
if (!(fPairCut->Pass(aPair))) return;
Double_t weight = fManager->GetWeight(aPair);
if (fUseLCMS)
fCYlmTrue->AddRealPair(aPair->QOutCMS(), aPair->QSideCMS(), aPair->QLongCMS(), weight);
else
fCYlmTrue->AddRealPair(aPair->KOut(), aPair->KSide(), aPair->KLong(), weight);
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::AddMixedPair(AliFemtoPair* aPair)
{
// add mixed (background) pair
if (fPairCut)
if (!(fPairCut->Pass(aPair))) return;
Double_t weight = fManager->GetWeight(aPair);
if (fUseLCMS) {
fCYlmTrue->AddMixedPair(aPair->QOutCMS(), aPair->QSideCMS(), aPair->QLongCMS(), 1.0);
fCYlmFake->AddRealPair(aPair->QOutCMS(), aPair->QSideCMS(), aPair->QLongCMS(), weight);
fCYlmFake->AddMixedPair(aPair->QOutCMS(), aPair->QSideCMS(), aPair->QLongCMS(), 1.0);
}
else {
fCYlmTrue->AddMixedPair(aPair->KOut(), aPair->KSide(), aPair->KLong(), 1.0);
fCYlmFake->AddRealPair(aPair->KOut(), aPair->KSide(), aPair->KLong(), weight);
fCYlmFake->AddMixedPair(aPair->KOut(), aPair->KSide(), aPair->KLong(), 1.0);
}
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::Write()
{
// write out all the histograms
fCYlmTrue->Write();
fCYlmFake->Write();
}
//_______________________
TList* AliFemtoModelCorrFctnDirectYlm::GetOutputList()
{
// Prepare the list of objects to be written to the output
TList *tOutputList = AliFemtoModelCorrFctn::GetOutputList();
tOutputList->Clear();
TList *tListCfTrue = fCYlmTrue->GetOutputList();
TIter nextListCfTrue(tListCfTrue);
while (TObject *obj = nextListCfTrue()) {
tOutputList->Add(obj);
}
TList *tListCfFake = fCYlmFake->GetOutputList();
TIter nextListCfFake(tListCfFake);
while (TObject *obj = nextListCfFake()) {
tOutputList->Add(obj);
}
// tOutputList->Add(fCYlmTrue->GetOutputList());
// tOutputList->Add(fCYlmFake->GetOutputList());
return tOutputList;
}
//_______________________
AliFemtoModelCorrFctn* AliFemtoModelCorrFctnDirectYlm::Clone()
{
// Clone the correlation function
AliFemtoModelCorrFctnDirectYlm *tCopy = new AliFemtoModelCorrFctnDirectYlm(*this);
return tCopy;
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::Finish()
{
fCYlmTrue->Finish();
fCYlmFake->Finish();
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::SetUseLCMS(int aUseLCMS)
{
fUseLCMS = aUseLCMS;
fCYlmTrue->SetUseLCMS(fUseLCMS);
fCYlmFake->SetUseLCMS(fUseLCMS);
}
//_______________________
int AliFemtoModelCorrFctnDirectYlm::GetUseLCMS()
{
return fUseLCMS;
}
|
////////////////////////////////////////////////////////////////////////////////
/// ///
/// AliFemtoModelCorrFctnDirectYlm - the class for correlation function which ///
/// uses the model framework and weight generation and saves the generated ///
/// emission source ///
/// Authors: Adam Kisiel, [email protected] ///
/// ///
////////////////////////////////////////////////////////////////////////////////
#ifdef __ROOT__
ClassImp(AliFemtoModelCorrFctnDirectYlm, 1)
#endif
#include "AliFemtoModelGausLCMSFreezeOutGenerator.h"
#include "AliFemtoModelHiddenInfo.h"
#include "AliFemtoModelCorrFctnDirectYlm.h"
//_______________________
AliFemtoModelCorrFctnDirectYlm::AliFemtoModelCorrFctnDirectYlm():
AliFemtoModelCorrFctn(),
fCYlmTrue(0),
fCYlmFake(0),
fUseLCMS(0)
{
// default constructor
fCYlmTrue = new AliFemtoCorrFctnDirectYlm();
fCYlmFake = new AliFemtoCorrFctnDirectYlm();
fCYlmTrue->SetUseLCMS(fUseLCMS);
fCYlmFake->SetUseLCMS(fUseLCMS);
}
//_______________________
AliFemtoModelCorrFctnDirectYlm::AliFemtoModelCorrFctnDirectYlm(const char *title, Int_t aMaxL, Int_t aNbins, Double_t aQinvLo, Double_t aQinvHi, int aUseLCMS=0):
AliFemtoModelCorrFctn(title, aNbins, aQinvLo, aQinvHi),
fCYlmTrue(0),
fCYlmFake(0),
fUseLCMS(aUseLCMS)
{
// basic constructor
char fname[1000];
snprintf(fname, 1000, "%s%s", title, "True");
fCYlmTrue = new AliFemtoCorrFctnDirectYlm(fname, aMaxL, aNbins, aQinvLo, aQinvHi, fUseLCMS);
snprintf(fname, 1000, "%s%s", title, "Fake");
fCYlmFake = new AliFemtoCorrFctnDirectYlm(fname, aMaxL, aNbins, aQinvLo, aQinvHi, fUseLCMS);
}
//_______________________
AliFemtoModelCorrFctnDirectYlm::AliFemtoModelCorrFctnDirectYlm(const AliFemtoModelCorrFctnDirectYlm& aCorrFctn):
AliFemtoModelCorrFctn(aCorrFctn),
fCYlmTrue(new AliFemtoCorrFctnDirectYlm(*(aCorrFctn.fCYlmTrue))),
fCYlmFake(new AliFemtoCorrFctnDirectYlm(*(aCorrFctn.fCYlmFake))),
fUseLCMS(0)
{
// copy constructor
fUseLCMS = aCorrFctn.fUseLCMS;
// fCYlmTrue = dynamic_cast<AliFemtoCorrFctnDirectYlm*>(aCorrFctn.fCYlmTrue->Clone());
// fCYlmFake = dynamic_cast<AliFemtoCorrFctnDirectYlm*>(aCorrFctn.fCYlmFake->Clone());
}
//_______________________
AliFemtoModelCorrFctnDirectYlm::~AliFemtoModelCorrFctnDirectYlm()
{
// destructor
if (fCYlmTrue) delete fCYlmTrue;
if (fCYlmFake) delete fCYlmFake;
if (fNumeratorTrue) delete fNumeratorTrue;
if (fNumeratorFake) delete fNumeratorFake;
if (fDenominator) delete fDenominator;
}
//_______________________
AliFemtoModelCorrFctnDirectYlm& AliFemtoModelCorrFctnDirectYlm::operator=(const AliFemtoModelCorrFctnDirectYlm& aCorrFctn)
{
// assignment operator
if (this == &aCorrFctn)
return *this;
fUseLCMS = aCorrFctn.fUseLCMS;
if (aCorrFctn.fCYlmTrue)
fCYlmTrue = new TH1D(*aCorrFctn.fCYlmTrue);
else fCYlmTrue = 0;
if (aCorrFctn.fCYlmFake)
fCYlmFake = new TH1D(*aCorrFctn.fCYlmFake);
else fCYlmFake = 0;
if (aCorrFctn.fNumeratorTrue)
fNumeratorTrue = new TH1D(*aCorrFctn.fNumeratorTrue);
else
fNumeratorTrue = 0;
if (aCorrFctn.fNumeratorFake)
fNumeratorFake = new TH1D(*aCorrFctn.fNumeratorFake);
else
fNumeratorFake = 0;
if (aCorrFctn.fDenominator)
fDenominator = new TH1D(*aCorrFctn.fDenominator);
else
fDenominator = 0;
return *this;
}
//_______________________
AliFemtoString AliFemtoModelCorrFctnDirectYlm::Report()
{
// construct report
AliFemtoString tStr = "AliFemtoModelCorrFctnDirectYlm report";
return tStr;
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::AddRealPair(AliFemtoPair* aPair)
{
// add real (effect) pair
if (fPairCut)
if (!(fPairCut->Pass(aPair))) return;
Double_t weight = fManager->GetWeight(aPair);
if (fUseLCMS)
fCYlmTrue->AddRealPair(aPair->QOutCMS(), aPair->QSideCMS(), aPair->QLongCMS(), weight);
else
fCYlmTrue->AddRealPair(aPair->KOut(), aPair->KSide(), aPair->KLong(), weight);
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::AddMixedPair(AliFemtoPair* aPair)
{
// add mixed (background) pair
if (fPairCut)
if (!(fPairCut->Pass(aPair))) return;
Double_t weight = fManager->GetWeight(aPair);
if (fUseLCMS) {
fCYlmTrue->AddMixedPair(aPair->QOutCMS(), aPair->QSideCMS(), aPair->QLongCMS(), 1.0);
fCYlmFake->AddRealPair(aPair->QOutCMS(), aPair->QSideCMS(), aPair->QLongCMS(), weight);
fCYlmFake->AddMixedPair(aPair->QOutCMS(), aPair->QSideCMS(), aPair->QLongCMS(), 1.0);
}
else {
fCYlmTrue->AddMixedPair(aPair->KOut(), aPair->KSide(), aPair->KLong(), 1.0);
fCYlmFake->AddRealPair(aPair->KOut(), aPair->KSide(), aPair->KLong(), weight);
fCYlmFake->AddMixedPair(aPair->KOut(), aPair->KSide(), aPair->KLong(), 1.0);
}
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::Write()
{
// write out all the histograms
fCYlmTrue->Write();
fCYlmFake->Write();
}
//_______________________
TList* AliFemtoModelCorrFctnDirectYlm::GetOutputList()
{
// Prepare the list of objects to be written to the output
TList *tOutputList = AliFemtoModelCorrFctn::GetOutputList();
tOutputList->Clear();
TList *tListCfTrue = fCYlmTrue->GetOutputList();
TIter nextListCfTrue(tListCfTrue);
while (TObject *obj = nextListCfTrue()) {
tOutputList->Add(obj);
}
TList *tListCfFake = fCYlmFake->GetOutputList();
TIter nextListCfFake(tListCfFake);
while (TObject *obj = nextListCfFake()) {
tOutputList->Add(obj);
}
// tOutputList->Add(fCYlmTrue->GetOutputList());
// tOutputList->Add(fCYlmFake->GetOutputList());
return tOutputList;
}
//_______________________
AliFemtoModelCorrFctn* AliFemtoModelCorrFctnDirectYlm::Clone()
{
// Clone the correlation function
AliFemtoModelCorrFctnDirectYlm *tCopy = new AliFemtoModelCorrFctnDirectYlm(*this);
return tCopy;
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::Finish()
{
fCYlmTrue->Finish();
fCYlmFake->Finish();
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::SetUseLCMS(int aUseLCMS)
{
fUseLCMS = aUseLCMS;
fCYlmTrue->SetUseLCMS(fUseLCMS);
fCYlmFake->SetUseLCMS(fUseLCMS);
}
//_______________________
int AliFemtoModelCorrFctnDirectYlm::GetUseLCMS()
{
return fUseLCMS;
}
|
Fix Coverity
|
Fix Coverity
|
C++
|
bsd-3-clause
|
ALICEHLT/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,jgrosseo/AliRoot,miranov25/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,shahor02/AliRoot,miranov25/AliRoot,mkrzewic/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,miranov25/AliRoot,coppedis/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,miranov25/AliRoot,coppedis/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,miranov25/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,alisw/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,shahor02/AliRoot,coppedis/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,mkrzewic/AliRoot,mkrzewic/AliRoot
|
a55ae1e2de6c25942ea11a0c13df7341b8578666
|
servers/http_fs.cpp
|
servers/http_fs.cpp
|
#include "http_fs.h"
#include <sys/types.h>
#include <unistd.h>
#include <sstream>
#include "lib/fs.h"
namespace servers {
lib::http::HttpResponse HttpFsServer::handleRequest(
const lib::http::HttpRequest& request) {
syslog(LOG_INFO, "Responding to request for: %s", request.uri().c_str());
std::stringstream ss;
try {
lib::fs::Stat stat(request.uri());
if (stat.isDir()) {
lib::fs::Directory d(request.uri());
d.read();
for (const auto& c : d.contents) {
ss << "<a href=\"" << request.uri() << "/" << c << "\">" <<
request.uri() << "/" << c << "</a><br>" << std::endl;
}
} else if (stat.isRegularFile()) {
lib::fs::File f(request.uri());
f.read();
for (const auto& l : f.lines) {
ss << l << "<br>" << std::endl;
}
} else {
throw std::runtime_error("bad file type, not a plain file or dir");
}
} catch (lib::fs::PathNotFoundError& e) {
lib::http::HttpResponse response(404, "Not Found!", "404 LOL");
return response;
} catch (lib::fs::FsError& e) {
lib::http::HttpResponse response(500, "Error with file!", "500 LOL");
return response;
}
lib::http::HttpResponse response(200, "OK", ss.str());
return response;
}
std::string HttpFsServer::handle(const std::string& msg) {
lib::http::HttpRequest req(msg);
return handleRequest(req).format();
}
} //namespace servers
|
#include "http_fs.h"
#include <sys/types.h>
#include <unistd.h>
#include <sstream>
#include "lib/fs.h"
namespace servers {
lib::http::HttpResponse HttpFsServer::handleRequest(
const lib::http::HttpRequest& request) {
syslog(LOG_INFO, "Responding to request for: %s", request.uri().c_str());
std::stringstream ss;
try {
lib::fs::Stat stat(request.uri());
if (stat.isDir()) {
lib::fs::Directory d(request.uri());
d.read();
for (const auto& c : d.contents) {
ss << "<a href=\"" << request.uri() << "/" << c << "\">" <<
request.uri() << "/" << c << "</a><br>\n";
}
} else if (stat.isRegularFile()) {
lib::fs::File f(request.uri());
f.read();
for (const auto& l : f.lines) {
ss << l << "<br>\n";
}
} else {
throw std::runtime_error("bad file type, not a plain file or dir");
}
} catch (lib::fs::PathNotFoundError& e) {
lib::http::HttpResponse response(404, "Not Found!", "404 LOL");
return response;
} catch (lib::fs::FsError& e) {
lib::http::HttpResponse response(500, "Error with file!", "500 LOL");
return response;
}
lib::http::HttpResponse response(200, "OK", ss.str());
return response;
}
std::string HttpFsServer::handle(const std::string& msg) {
lib::http::HttpRequest req(msg);
return handleRequest(req).format();
}
} //namespace servers
|
remove std::endl
|
remove std::endl
|
C++
|
mit
|
boryas/ssfs,boryas/ssfs
|
865d06fcc3038bd4d35ff385e78db464b479765a
|
worker/src/RTC/RtpStreamSend.cpp
|
worker/src/RTC/RtpStreamSend.cpp
|
#define MS_CLASS "RTC::RtpStreamSend"
// #define MS_LOG_DEV
#include "RTC/RtpStreamSend.hpp"
#include "Logger.hpp"
#include "DepLibUV.hpp"
#include "Utils.hpp"
#define RTP_SEQ_MOD (1<<16)
#define MAX_RETRANSMISSION_AGE 1000 // Don't retransmit packets older than this (ms).
#define DEFAULT_RTT 100 // Default RTT if not set (in ms).
namespace RTC
{
/* Instance methods. */
RtpStreamSend::RtpStreamSend(RTC::RtpStream::Params& params, size_t bufferSize) :
RtpStream::RtpStream(params),
storage(bufferSize)
{
MS_TRACE();
}
RtpStreamSend::~RtpStreamSend()
{
MS_TRACE();
// Clear the RTP buffer.
ClearBuffer();
}
Json::Value RtpStreamSend::toJson() const
{
MS_TRACE();
static const Json::StaticString k_params("params");
static const Json::StaticString k_received("received");
static const Json::StaticString k_maxTimestamp("maxTimestamp");
static const Json::StaticString k_receivedBytes("receivedBytes");
static const Json::StaticString k_rtt("rtt");
Json::Value json(Json::objectValue);
json[k_params] = this->params.toJson();
json[k_received] = (Json::UInt)this->received;
json[k_maxTimestamp] = (Json::UInt)this->max_timestamp;
json[k_receivedBytes] = (Json::UInt)this->receivedBytes;
json[k_rtt] = (Json::UInt)this->rtt;
return json;
}
bool RtpStreamSend::ReceivePacket(RTC::RtpPacket* packet)
{
MS_TRACE();
// Call the parent method.
if (!RtpStream::ReceivePacket(packet))
return false;
// If bufferSize was given, store the packet into the buffer.
if (this->storage.size() > 0)
StorePacket(packet);
// Increase packet counters.
this->receivedBytes += packet->GetPayloadLength();
// Record current time and RTP timestamp.
this->lastPacketTimeMs = DepLibUV::GetTime();
this->lastPacketRtpTimestamp = packet->GetTimestamp();
return true;
}
void RtpStreamSend::ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report)
{
MS_TRACE();
/* Calculate RTT. */
// Get the compact NTP representation of the current timestamp.
Utils::Time::Ntp nowNtp;
Utils::Time::CurrentTimeNtp(nowNtp);
uint32_t nowCompactNtp = (nowNtp.seconds & 0x0000FFFF) << 16;
nowCompactNtp |= (nowNtp.fractions & 0xFFFF0000) >> 16;
uint32_t lastSr = report->GetLastSenderReport();
uint32_t dlsr = report->GetDelaySinceLastSenderReport();
// RTT in 1/2^16 seconds.
uint32_t rtt = nowCompactNtp - dlsr - lastSr;
// RTT in milliseconds.
this->rtt = ((rtt >> 16) * 1000);
this->rtt += (static_cast<float>(rtt & 0x0000FFFF) / 65536) * 1000;
}
// This method looks for the requested RTP packets and inserts them into the
// given container (and set to null the next container position).
void RtpStreamSend::RequestRtpRetransmission(uint16_t seq, uint16_t bitmask, std::vector<RTC::RtpPacket*>& container)
{
MS_TRACE();
// 17: 16 bit mask + the initial sequence number.
static size_t maxRequestedPackets = 17;
// Ensure the container's first element is 0.
container[0] = nullptr;
// If NACK is not supported, exit.
if (!this->params.useNack)
{
MS_WARN_TAG(rtx, "NACK not negotiated");
return;
}
// If the buffer is empty just return.
if (this->buffer.size() == 0)
return;
// Convert the given sequence numbers to 32 bits.
uint32_t first_seq32 = (uint32_t)seq + this->cycles;
uint32_t last_seq32 = first_seq32 + maxRequestedPackets - 1;
// Number of requested packets cannot be greater than the container size - 1.
MS_ASSERT(container.size() - 1 >= maxRequestedPackets, "RtpPacket container is too small");
auto buffer_it = this->buffer.begin();
auto buffer_it_r = this->buffer.rbegin();
uint32_t buffer_first_seq32 = (*buffer_it).seq32;
uint32_t buffer_last_seq32 = (*buffer_it_r).seq32;
// Requested packet range not found.
if (first_seq32 > buffer_last_seq32 || last_seq32 < buffer_first_seq32)
{
// Let's try with sequence numbers in the previous 16 cycle.
if (this->cycles > 0)
{
first_seq32 -= RTP_SEQ_MOD;
last_seq32 -= RTP_SEQ_MOD;
// Try again.
if (first_seq32 > buffer_last_seq32 || last_seq32 < buffer_first_seq32)
{
MS_WARN_TAG(rtx, "requested packet range not in the buffer");
return;
}
}
// Otherwise just return.
else
{
MS_WARN_TAG(rtx, "requested packet range not in the buffer");
return;
}
}
// Look for each requested packet.
uint64_t now = DepLibUV::GetTime();
uint32_t rtt = (this->rtt ? this->rtt : DEFAULT_RTT);
uint32_t seq32 = first_seq32;
bool requested = true;
size_t container_idx = 0;
// Some variables for debugging.
uint16_t orig_bitmask = bitmask;
uint16_t sent_bitmask = 0b0000000000000000;
bool is_first_packet = true;
bool first_packet_sent = false;
uint8_t bitmask_counter = 0;
bool too_old_packet_found = false;
MS_DEBUG_DEV("loop [bitmask:" MS_UINT16_TO_BINARY_PATTERN "]", MS_UINT16_TO_BINARY(bitmask));
while (requested || bitmask != 0)
{
bool sent = false;
if (requested)
{
for (; buffer_it != this->buffer.end(); ++buffer_it)
{
auto current_seq32 = (*buffer_it).seq32;
// Found.
if (current_seq32 == seq32)
{
auto current_packet = (*buffer_it).packet;
uint32_t diff = (this->max_timestamp - current_packet->GetTimestamp()) * 1000 / this->params.clockRate;
// Just provide the packet if no older than MAX_RETRANSMISSION_AGE ms.
if (diff > MAX_RETRANSMISSION_AGE)
{
if (!too_old_packet_found)
{
MS_DEBUG_TAG(rtx,
"ignoring retransmission for too old packet [seq:%" PRIu16 ", max_age:%" PRIu32 "ms, packet_age:%" PRIu32 "ms]",
current_packet->GetSequenceNumber(), MAX_RETRANSMISSION_AGE, diff);
too_old_packet_found = true;
}
break;
}
// Don't resent the packet if it was resent in the last RTT ms.
uint32_t resent_at_time = (*buffer_it).resent_at_time;
if (
resent_at_time &&
now - resent_at_time < static_cast<uint64_t>(rtt))
{
MS_DEBUG_TAG(rtx,
"ignoring retransmission for a packet already resent in the last RTT ms [seq:%" PRIu16 ", rtt:%" PRIu32 "]",
current_packet->GetSequenceNumber(), rtt);
break;
}
// Store the packet in the container and then increment its index.
container[container_idx++] = current_packet;
// Save when this packet was resent.
(*buffer_it).resent_at_time = now;
sent = true;
if (is_first_packet)
first_packet_sent = true;
break;
}
// It can not be after this packet.
else if (current_seq32 > seq32)
{
break;
}
}
}
requested = (bitmask & 1) ? true : false;
bitmask >>= 1;
++seq32;
if (!is_first_packet)
{
sent_bitmask |= (sent ? 1 : 0) << bitmask_counter;
++bitmask_counter;
}
else
{
is_first_packet = false;
}
}
// If not all the requested packets was sent, log it.
if (!first_packet_sent || orig_bitmask != sent_bitmask)
{
MS_WARN_TAG(rtx, "not all the requested packet could be sent [first_was_sent:%s, bitmask:" MS_UINT16_TO_BINARY_PATTERN ", sent:" MS_UINT16_TO_BINARY_PATTERN "]",
first_packet_sent ? "yes" : "no",
MS_UINT16_TO_BINARY(orig_bitmask), MS_UINT16_TO_BINARY(sent_bitmask));
}
// Set the next container element to null.
container[container_idx] = nullptr;
}
RTC::RTCP::SenderReport* RtpStreamSend::GetRtcpSenderReport(uint64_t now)
{
MS_TRACE();
if (!received)
return nullptr;
RTC::RTCP::SenderReport* report = new RTC::RTCP::SenderReport();
report->SetPacketCount(this->received);
report->SetOctetCount(this->receivedBytes);
Utils::Time::Ntp ntp;
Utils::Time::CurrentTimeNtp(ntp);
report->SetNtpSec(ntp.seconds);
report->SetNtpFrac(ntp.fractions);
// Calculate RTP timestamp diff between now and last received RTP packet.
uint32_t diffMs = now - this->lastPacketTimeMs;
uint32_t diffRtpTimestamp = diffMs * this->params.clockRate / 1000;
report->SetRtpTs(this->lastPacketRtpTimestamp + diffRtpTimestamp);
return report;
}
void RtpStreamSend::ClearBuffer()
{
MS_TRACE();
// Delete cloned packets.
for (auto& buffer_item : this->buffer)
{
delete buffer_item.packet;
}
// Clear list.
this->buffer.clear();
}
inline
void RtpStreamSend::StorePacket(RTC::RtpPacket* packet)
{
MS_TRACE();
// Sum the packet seq number and the number of 16 bits cycles.
uint32_t packet_seq32 = (uint32_t)packet->GetSequenceNumber() + this->cycles;
BufferItem buffer_item;
buffer_item.seq32 = packet_seq32;
// If empty do it easy.
if (this->buffer.size() == 0)
{
auto store = this->storage[0].store;
buffer_item.packet = packet->Clone(store);
this->buffer.push_back(buffer_item);
return;
}
// Otherwise, do the stuff.
Buffer::iterator new_buffer_it;
uint8_t* store = nullptr;
// Iterate the buffer in reverse order and find the proper place to store the
// packet.
auto buffer_it_r = this->buffer.rbegin();
for (; buffer_it_r != this->buffer.rend(); ++buffer_it_r)
{
auto current_seq32 = (*buffer_it_r).seq32;
if (packet_seq32 > current_seq32)
{
// Get a forward iterator pointing to the same element.
auto it = buffer_it_r.base();
new_buffer_it = this->buffer.insert(it, buffer_item);
// Exit the loop.
break;
}
}
// If the packet was older than anything in the buffer, just ignore it.
// NOTE: This should never happen.
if (buffer_it_r == this->buffer.rend())
{
MS_WARN_TAG(rtp, "ignoring packet older than anything in the buffer [ssrc:%" PRIu32 ", seq:%" PRIu16 "]", packet->GetSsrc(), packet->GetSequenceNumber());
return;
}
// If the buffer is not full use the next free storage item.
if (this->buffer.size() - 1 < this->storage.size())
{
store = this->storage[this->buffer.size() - 1].store;
}
// Otherwise remove the first packet of the buffer and replace its storage area.
else
{
auto& first_buffer_item = *(this->buffer.begin());
auto first_packet = first_buffer_item.packet;
// Store points to the store used by the first packet.
store = (uint8_t*)first_packet->GetData();
// Free the first packet.
delete first_packet;
// Remove the first element in the list.
this->buffer.pop_front();
}
// Update the new buffer item so it points to the cloned packed.
(*new_buffer_it).packet = packet->Clone(store);
}
void RtpStreamSend::onInitSeq()
{
MS_TRACE();
// Clear the RTP buffer.
ClearBuffer();
}
}
|
#define MS_CLASS "RTC::RtpStreamSend"
// #define MS_LOG_DEV
#include "RTC/RtpStreamSend.hpp"
#include "Logger.hpp"
#include "DepLibUV.hpp"
#include "Utils.hpp"
#define RTP_SEQ_MOD (1<<16)
#define MAX_RETRANSMISSION_AGE 1000 // Don't retransmit packets older than this (ms).
#define DEFAULT_RTT 100 // Default RTT if not set (in ms).
namespace RTC
{
/* Instance methods. */
RtpStreamSend::RtpStreamSend(RTC::RtpStream::Params& params, size_t bufferSize) :
RtpStream::RtpStream(params),
storage(bufferSize)
{
MS_TRACE();
}
RtpStreamSend::~RtpStreamSend()
{
MS_TRACE();
// Clear the RTP buffer.
ClearBuffer();
}
Json::Value RtpStreamSend::toJson() const
{
MS_TRACE();
static const Json::StaticString k_params("params");
static const Json::StaticString k_received("received");
static const Json::StaticString k_maxTimestamp("maxTimestamp");
static const Json::StaticString k_receivedBytes("receivedBytes");
static const Json::StaticString k_rtt("rtt");
Json::Value json(Json::objectValue);
json[k_params] = this->params.toJson();
json[k_received] = (Json::UInt)this->received;
json[k_maxTimestamp] = (Json::UInt)this->max_timestamp;
json[k_receivedBytes] = (Json::UInt)this->receivedBytes;
json[k_rtt] = (Json::UInt)this->rtt;
return json;
}
bool RtpStreamSend::ReceivePacket(RTC::RtpPacket* packet)
{
MS_TRACE();
// Call the parent method.
if (!RtpStream::ReceivePacket(packet))
return false;
// If bufferSize was given, store the packet into the buffer.
if (this->storage.size() > 0)
StorePacket(packet);
// Increase packet counters.
this->receivedBytes += packet->GetPayloadLength();
// Record current time and RTP timestamp.
this->lastPacketTimeMs = DepLibUV::GetTime();
this->lastPacketRtpTimestamp = packet->GetTimestamp();
return true;
}
void RtpStreamSend::ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report)
{
MS_TRACE();
/* Calculate RTT. */
// Get the compact NTP representation of the current timestamp.
Utils::Time::Ntp nowNtp;
Utils::Time::CurrentTimeNtp(nowNtp);
uint32_t nowCompactNtp = (nowNtp.seconds & 0x0000FFFF) << 16;
nowCompactNtp |= (nowNtp.fractions & 0xFFFF0000) >> 16;
uint32_t lastSr = report->GetLastSenderReport();
uint32_t dlsr = report->GetDelaySinceLastSenderReport();
// RTT in 1/2^16 seconds.
uint32_t rtt = nowCompactNtp - dlsr - lastSr;
// RTT in milliseconds.
this->rtt = ((rtt >> 16) * 1000);
this->rtt += (static_cast<float>(rtt & 0x0000FFFF) / 65536) * 1000;
}
// This method looks for the requested RTP packets and inserts them into the
// given container (and set to null the next container position).
void RtpStreamSend::RequestRtpRetransmission(uint16_t seq, uint16_t bitmask, std::vector<RTC::RtpPacket*>& container)
{
MS_TRACE();
// 17: 16 bit mask + the initial sequence number.
static size_t maxRequestedPackets = 17;
// Ensure the container's first element is 0.
container[0] = nullptr;
// If NACK is not supported, exit.
if (!this->params.useNack)
{
MS_WARN_TAG(rtx, "NACK not negotiated");
return;
}
// If the buffer is empty just return.
if (this->buffer.size() == 0)
return;
// Convert the given sequence numbers to 32 bits.
uint32_t first_seq32 = (uint32_t)seq + this->cycles;
uint32_t last_seq32 = first_seq32 + maxRequestedPackets - 1;
// Number of requested packets cannot be greater than the container size - 1.
MS_ASSERT(container.size() - 1 >= maxRequestedPackets, "RtpPacket container is too small");
auto buffer_it = this->buffer.begin();
auto buffer_it_r = this->buffer.rbegin();
uint32_t buffer_first_seq32 = (*buffer_it).seq32;
uint32_t buffer_last_seq32 = (*buffer_it_r).seq32;
// Requested packet range not found.
if (first_seq32 > buffer_last_seq32 || last_seq32 < buffer_first_seq32)
{
// Let's try with sequence numbers in the previous 16 cycle.
if (this->cycles > 0)
{
first_seq32 -= RTP_SEQ_MOD;
last_seq32 -= RTP_SEQ_MOD;
// Try again.
if (first_seq32 > buffer_last_seq32 || last_seq32 < buffer_first_seq32)
{
MS_WARN_TAG(rtx, "requested packet range not in the buffer");
return;
}
}
// Otherwise just return.
else
{
MS_WARN_TAG(rtx, "requested packet range not in the buffer");
return;
}
}
// Look for each requested packet.
uint64_t now = DepLibUV::GetTime();
uint32_t rtt = (this->rtt ? this->rtt : DEFAULT_RTT);
uint32_t seq32 = first_seq32;
bool requested = true;
size_t container_idx = 0;
// Some variables for debugging.
uint16_t orig_bitmask = bitmask;
uint16_t sent_bitmask = 0b0000000000000000;
bool is_first_packet = true;
bool first_packet_sent = false;
uint8_t bitmask_counter = 0;
bool too_old_packet_found = false;
MS_DEBUG_DEV("loop [bitmask:" MS_UINT16_TO_BINARY_PATTERN "]", MS_UINT16_TO_BINARY(bitmask));
while (requested || bitmask != 0)
{
bool sent = false;
if (requested)
{
for (; buffer_it != this->buffer.end(); ++buffer_it)
{
auto current_seq32 = (*buffer_it).seq32;
// Found.
if (current_seq32 == seq32)
{
auto current_packet = (*buffer_it).packet;
uint32_t diff = (this->max_timestamp - current_packet->GetTimestamp()) * 1000 / this->params.clockRate;
// Just provide the packet if no older than MAX_RETRANSMISSION_AGE ms.
if (diff > MAX_RETRANSMISSION_AGE)
{
if (!too_old_packet_found)
{
MS_DEBUG_TAG(rtx,
"ignoring retransmission for too old packet [seq:%" PRIu16 ", max_age:%" PRIu32 "ms, packet_age:%" PRIu32 "ms]",
current_packet->GetSequenceNumber(), MAX_RETRANSMISSION_AGE, diff);
too_old_packet_found = true;
}
break;
}
// Don't resent the packet if it was resent in the last RTT ms.
uint32_t resent_at_time = (*buffer_it).resent_at_time;
if (
resent_at_time &&
now - resent_at_time < static_cast<uint64_t>(rtt))
{
MS_DEBUG_TAG(rtx,
"ignoring retransmission for a packet already resent in the last RTT ms [seq:%" PRIu16 ", rtt:%" PRIu32 "]",
current_packet->GetSequenceNumber(), rtt);
break;
}
// Store the packet in the container and then increment its index.
container[container_idx++] = current_packet;
// Save when this packet was resent.
(*buffer_it).resent_at_time = now;
sent = true;
if (is_first_packet)
first_packet_sent = true;
break;
}
// It can not be after this packet.
else if (current_seq32 > seq32)
{
break;
}
}
}
requested = (bitmask & 1) ? true : false;
bitmask >>= 1;
++seq32;
if (!is_first_packet)
{
sent_bitmask |= (sent ? 1 : 0) << bitmask_counter;
++bitmask_counter;
}
else
{
is_first_packet = false;
}
}
// If not all the requested packets was sent, log it.
if (!first_packet_sent || orig_bitmask != sent_bitmask)
{
MS_WARN_TAG(rtx, "could not sent all [seq:%" PRIu16 ", first:%s, bitmask:" MS_UINT16_TO_BINARY_PATTERN ", sent_bitmask:" MS_UINT16_TO_BINARY_PATTERN "]",
seq, first_packet_sent ? "yes" : "no",
MS_UINT16_TO_BINARY(orig_bitmask), MS_UINT16_TO_BINARY(sent_bitmask));
}
// Set the next container element to null.
container[container_idx] = nullptr;
}
RTC::RTCP::SenderReport* RtpStreamSend::GetRtcpSenderReport(uint64_t now)
{
MS_TRACE();
if (!received)
return nullptr;
RTC::RTCP::SenderReport* report = new RTC::RTCP::SenderReport();
report->SetPacketCount(this->received);
report->SetOctetCount(this->receivedBytes);
Utils::Time::Ntp ntp;
Utils::Time::CurrentTimeNtp(ntp);
report->SetNtpSec(ntp.seconds);
report->SetNtpFrac(ntp.fractions);
// Calculate RTP timestamp diff between now and last received RTP packet.
uint32_t diffMs = now - this->lastPacketTimeMs;
uint32_t diffRtpTimestamp = diffMs * this->params.clockRate / 1000;
report->SetRtpTs(this->lastPacketRtpTimestamp + diffRtpTimestamp);
return report;
}
void RtpStreamSend::ClearBuffer()
{
MS_TRACE();
// Delete cloned packets.
for (auto& buffer_item : this->buffer)
{
delete buffer_item.packet;
}
// Clear list.
this->buffer.clear();
}
inline
void RtpStreamSend::StorePacket(RTC::RtpPacket* packet)
{
MS_TRACE();
// Sum the packet seq number and the number of 16 bits cycles.
uint32_t packet_seq32 = (uint32_t)packet->GetSequenceNumber() + this->cycles;
BufferItem buffer_item;
buffer_item.seq32 = packet_seq32;
// If empty do it easy.
if (this->buffer.size() == 0)
{
auto store = this->storage[0].store;
buffer_item.packet = packet->Clone(store);
this->buffer.push_back(buffer_item);
return;
}
// Otherwise, do the stuff.
Buffer::iterator new_buffer_it;
uint8_t* store = nullptr;
// Iterate the buffer in reverse order and find the proper place to store the
// packet.
auto buffer_it_r = this->buffer.rbegin();
for (; buffer_it_r != this->buffer.rend(); ++buffer_it_r)
{
auto current_seq32 = (*buffer_it_r).seq32;
if (packet_seq32 > current_seq32)
{
// Get a forward iterator pointing to the same element.
auto it = buffer_it_r.base();
new_buffer_it = this->buffer.insert(it, buffer_item);
// Exit the loop.
break;
}
}
// If the packet was older than anything in the buffer, just ignore it.
// NOTE: This should never happen.
if (buffer_it_r == this->buffer.rend())
{
MS_WARN_TAG(rtp, "ignoring packet older than anything in the buffer [ssrc:%" PRIu32 ", seq:%" PRIu16 "]", packet->GetSsrc(), packet->GetSequenceNumber());
return;
}
// If the buffer is not full use the next free storage item.
if (this->buffer.size() - 1 < this->storage.size())
{
store = this->storage[this->buffer.size() - 1].store;
}
// Otherwise remove the first packet of the buffer and replace its storage area.
else
{
auto& first_buffer_item = *(this->buffer.begin());
auto first_packet = first_buffer_item.packet;
// Store points to the store used by the first packet.
store = (uint8_t*)first_packet->GetData();
// Free the first packet.
delete first_packet;
// Remove the first element in the list.
this->buffer.pop_front();
}
// Update the new buffer item so it points to the cloned packed.
(*new_buffer_it).packet = packet->Clone(store);
}
void RtpStreamSend::onInitSeq()
{
MS_TRACE();
// Clear the RTP buffer.
ClearBuffer();
}
}
|
make logging nicer
|
RtpStreamSend: make logging nicer
|
C++
|
isc
|
versatica/mediasoup,versatica/mediasoup,versatica/mediasoup,versatica/mediasoup,versatica/mediasoup,ibc/MediaSoup,versatica/mediasoup,versatica/mediasoup,ibc/MediaSoup,ibc/MediaSoup,versatica/mediasoup,versatica/mediasoup
|
8600365d07870567a6feb26d8b6da698dff7caa0
|
plugins/kdepim_sync/src/kdepim_impl.cpp
|
plugins/kdepim_sync/src/kdepim_impl.cpp
|
/***********************************************************************
Actual implementation of the KDE PIM OpenSync plugin
Copyright (C) 2004 Conectiva S. A.
Based on code Copyright (C) 2004 Stewart Heitmann <[email protected]>
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;
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 OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*************************************************************************/
/**
* @autor Eduardo Pereira Habkost <[email protected]>
*/
extern "C"
{
#include <opensync/opensync.h>
}
#include <kabc/stdaddressbook.h>
#include <kabc/vcardconverter.h>
#include <kabc/resource.h>
#include <libkcal/resourcecalendar.h>
#include <kcmdlineargs.h>
#include <kapplication.h>
#include <klocale.h>
#include <qsignal.h>
#include <qfile.h>
#include <dlfcn.h>
#include "osyncbase.h"
#include "kaddrbook.h"
#include "kcal.h"
static
void unfold_vcard(char *vcard, size_t *size)
{
char* in = vcard;
char* out = vcard;
char *end = vcard + *size;
while ( in < end)
{
/* remove any occurrences of "=[CR][LF]" */
/* these denote folded line markers in VCARD format. */
/* Dont know why, but Evolution uses the leading "=" */
/* character to (presumably) denote a control sequence. */
/* This is not quite how I interpret the VCARD RFC2426 */
/* spec (section 2.6 line delimiting and folding). */
/* This seems to work though, so thats the main thing! */
if (in[0]=='=' && in[1]==13 && in[2]==10)
in+=3;
else
*out++ = *in++;
}
*size = out - vcard;
}
static KApplication *applicationptr=NULL;
static char name[] = "kde-opensync-plugin";
static int argc = 0;
static char *argv[] = {name,0};
class KdePluginImplementation: public KdePluginImplementationBase
{
private:
KABC::AddressBook* addressbookptr;
KABC::Ticket* addressbookticket;
QDateTime syncdate, newsyncdate;
KCalDataSource *kcal;
OSyncMember *member;
OSyncHashTable *hashtable;
public:
KdePluginImplementation(OSyncMember *memb)
:member(memb)
{
//osync_debug("kde", 3, "%s(%s)", __FUNCTION__);
KCmdLineArgs::init(argc, argv, "kde-opensync-plugin", i18n("KOpenSync"), "KDE OpenSync plugin", "0.1", false);
applicationptr = new KApplication();
//get a handle to the standard KDE addressbook
addressbookptr = KABC::StdAddressBook::self();
//ensure a NULL Ticket ptr
addressbookticket=NULL;
hashtable = osync_hashtable_new();
osync_hashtable_load(hashtable, member);
/*FIXME: check if synchronizing Calendar data is desired */
kcal = new KCalDataSource(member, hashtable);
}
virtual ~KdePluginImplementation()
{
delete kcal;
kcal = NULL;
if (applicationptr) {
delete applicationptr;
applicationptr = NULL;
}
}
/** Calculate the hash value for an Addressee.
* Should be called before returning/writing the
* data, because the revision of the Addressee
* can be changed.
*/
QString calc_hash(KABC::Addressee &e)
{
//Get the revision date of the KDE addressbook entry.
//Regard entries with invalid revision dates as having just been changed.
QDateTime revdate = e.revision();
if (!revdate.isValid())
{
revdate = newsyncdate; //use date of this sync as the revision date.
e.setRevision(revdate); //update the Addressbook entry for future reference.
}
/*FIXME: not i18ned string */
return revdate.toString();
}
virtual void connect(OSyncContext *ctx)
{
//Lock the addressbook
addressbookticket = addressbookptr->requestSaveTicket();
if (!addressbookticket)
{
osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't lock KDE addressbook");
return;
}
osync_debug("kde", 3, "KDE addressbook locked OK.");
if (!kcal->connect(ctx))
return;
osync_context_report_success(ctx);
}
virtual void disconnect(OSyncContext *ctx)
{
//Unlock the addressbook
addressbookptr->save(addressbookticket);
addressbookticket = NULL;
if (!kcal->disconnect(ctx))
return;
osync_context_report_success(ctx);
}
/*FIXME: move kaddrbook implementation to kaddrbook.cpp */
bool addrbook_get_changeinfo(OSyncContext *ctx)
{
//osync_debug("kde", 3, "kaddrbook::%s(newdbs=%d)", __FUNCTION__, newdbs);
//FIXME: should I detect if slow_sync is necessary?
if (osync_member_get_slow_sync(member, "contact"))
osync_hashtable_set_slow_sync(hashtable, "contact");
//remember when we started this current sync
newsyncdate = QDateTime::currentDateTime();
// We must reload the KDE addressbook in order to retrieve the latest changes.
if (!addressbookptr->load())
{
osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't reload KDE addressbook");
return false;
}
osync_debug("kde", 3, "KDE addressbook reloaded OK.");
KABC::VCardConverter converter;
for (KABC::AddressBook::Iterator it=addressbookptr->begin(); it!=addressbookptr->end(); it++ ) {
QString uid = it->uid();
osync_debug("kde", 3, "new entry, uid: %s", uid.latin1());
QString hash = calc_hash(*it);
// gmalloc a changed_object for this phonebook entry
//FIXME: deallocate it somewhere
OSyncChange *chg= osync_change_new();
osync_change_set_member(chg, member);
osync_change_set_hash(chg, hash);
osync_change_set_uid(chg, uid.latin1());
// Convert the VCARD data into a string
QString card = converter.createVCard(*it);
const char *data = card.latin1();
//FIXME: deallocate data somewhere
osync_change_set_data(chg, strdup(data), strlen(data), 1);
// object type and format
osync_change_set_objtype_string(chg, "contact");
osync_change_set_objformat_string(chg, "vcard");
// Use the hash table to check if the object
// needs to be reported
osync_change_set_hash(chg, hash.data());
if (osync_hashtable_detect_change(hashtable, chg)) {
osync_context_report_change(ctx, chg);
osync_hashtable_update_hash(hashtable, chg);
}
}
// Use the hashtable to report deletions
osync_hashtable_report_deleted(hashtable, ctx, "contact");
return true;
}
virtual void get_changeinfo(OSyncContext *ctx)
{
if (!addrbook_get_changeinfo(ctx))
return;
if (kcal && !kcal->get_changeinfo(ctx))
return;
osync_context_report_success(ctx);
}
void kabc_get_data(OSyncContext *ctx, OSyncChange *chg)
{
QString uid = osync_change_get_uid(chg);
KABC::Addressee a = addressbookptr->findByUid(uid);
KABC::VCardConverter converter;
QString card = converter.createVCard(a);
const char *data = card.latin1();
//FIXME: deallocate data somewhere
osync_change_set_data(chg, strdup(data), strlen(data), 1);
osync_context_report_success(ctx);
}
virtual void get_data(OSyncContext *ctx, OSyncChange *)
{
/*
switch (osync_change_get_objtype(chg)) {
case contact:
kabc_get_data(ctx, chg);
break;
case calendar:
kcal->get_data(ctx, chg);
break;
default:
osync_context_report_error(ctx, OSYNC_ERROR_FILE_NOT_FOUND, "Invalid UID");
return;
}
osync_context_report_success(ctx);
*/
osync_context_report_error(ctx, OSYNC_ERROR_FILE_NOT_FOUND, "Invalid UID");
}
/** Access an object, without returning success
*
* returns 0 on success, < 0 on error.
* If an error occurss, the error will be already reported
* using osync_context_report_error()
*/
int __vcard_access(OSyncContext *ctx, OSyncChange *chg)
{
//osync_debug("kde", 3, "kaddrbook::%s()",__FUNCTION__);
QString uid = osync_change_get_uid(chg);
// Ensure we still have a lock on the KDE addressbook (we ought to)
if (addressbookticket==NULL)
{
//This should never happen, but just in case....
osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Lock on KDE addressbook was lost");
return -1;
}
KABC::VCardConverter converter;
OSyncChangeType chtype = osync_change_get_changetype(chg);
/* treat modified objects without UIDs as if they were newly added objects */
if (chtype == CHANGE_MODIFIED && uid.isEmpty())
chtype = CHANGE_ADDED;
// convert VCARD string from obj->comp into an Addresse object.
char *data;
size_t data_size;
data = (char*)osync_change_get_data(chg);
data_size = osync_change_get_datasize(chg);
switch(chtype)
{
case CHANGE_MODIFIED:
{
unfold_vcard(data, &data_size);
KABC::Addressee addressee = converter.parseVCard(QString::fromLatin1(data, data_size));
// ensure it has the correct UID
addressee.setUid(uid);
QString hash = calc_hash(addressee);
// replace the current addressbook entry (if any) with the new one
addressbookptr->insertAddressee(addressee);
osync_change_set_hash(chg, hash);
osync_debug("kde", 3, "KDE ADDRESSBOOK ENTRY UPDATED (UID=%s)", uid.latin1());
break;
}
case CHANGE_ADDED:
{
// convert VCARD string from obj->comp into an Addresse object
// KABC::VCardConverter doesnt do VCARD unfolding so we must do it ourselves first.
unfold_vcard(data, &data_size);
KABC::Addressee addressee = converter.parseVCard(QString::fromLatin1(data, data_size));
QString hash = calc_hash(addressee);
// add the new address to the addressbook
addressbookptr->insertAddressee(addressee);
osync_change_set_uid(chg, addressee.uid().latin1());
osync_change_set_hash(chg, hash);
osync_debug("kde", 3, "KDE ADDRESSBOOK ENTRY ADDED (UID=%s)", addressee.uid().latin1());
break;
}
case CHANGE_DELETED:
{
if (uid.isEmpty())
{
osync_context_report_error(ctx, OSYNC_ERROR_FILE_NOT_FOUND, "Trying to delete entry with empty UID");
return -1;
}
//find addressbook entry with matching UID and delete it
KABC::Addressee addressee = addressbookptr->findByUid(uid);
if(!addressee.isEmpty())
addressbookptr->removeAddressee(addressee);
osync_debug("kde", 3, "KDE ADDRESSBOOK ENTRY DELETED (UID=%s)", uid.latin1());
break;
}
default:
osync_context_report_error(ctx, OSYNC_ERROR_NOT_SUPPORTED, "Operation not supported");
return -1;
}
//Save the changes without dropping the lock
addressbookticket->resource()->save(addressbookticket);
return 0;
}
virtual bool vcard_access(OSyncContext *ctx, OSyncChange *chg)
{
if (__vcard_access(ctx, chg) < 0)
return false;
osync_context_report_success(ctx);
/*FIXME: What should be returned? */
return true;
}
virtual bool vcard_commit_change(OSyncContext *ctx, OSyncChange *chg)
{
if ( __vcard_access(ctx, chg) < 0)
return false;
osync_hashtable_update_hash(hashtable, chg);
osync_context_report_success(ctx);
/*FIXME: What should be returned? */
return true;
}
};
extern "C" {
KdePluginImplementationBase *new_KdePluginImplementation(OSyncMember *member)
{
return new KdePluginImplementation(member);
}
}// extern "C"
|
/***********************************************************************
Actual implementation of the KDE PIM OpenSync plugin
Copyright (C) 2004 Conectiva S. A.
Based on code Copyright (C) 2004 Stewart Heitmann <[email protected]>
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;
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 OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*************************************************************************/
/**
* @autor Eduardo Pereira Habkost <[email protected]>
*/
extern "C"
{
#include <opensync/opensync.h>
}
#include <kabc/stdaddressbook.h>
#include <kabc/vcardconverter.h>
#include <kabc/resource.h>
#include <libkcal/resourcecalendar.h>
#include <kcmdlineargs.h>
#include <kapplication.h>
#include <klocale.h>
#include <qsignal.h>
#include <qfile.h>
#include <dlfcn.h>
#include "osyncbase.h"
#include "kaddrbook.h"
#include "kcal.h"
static
void unfold_vcard(char *vcard, size_t *size)
{
char* in = vcard;
char* out = vcard;
char *end = vcard + *size;
while ( in < end)
{
/* remove any occurrences of "=[CR][LF]" */
/* these denote folded line markers in VCARD format. */
/* Dont know why, but Evolution uses the leading "=" */
/* character to (presumably) denote a control sequence. */
/* This is not quite how I interpret the VCARD RFC2426 */
/* spec (section 2.6 line delimiting and folding). */
/* This seems to work though, so thats the main thing! */
if (in[0]=='=' && in[1]==13 && in[2]==10)
in+=3;
else
*out++ = *in++;
}
*size = out - vcard;
}
static KApplication *applicationptr=NULL;
static char name[] = "kde-opensync-plugin";
static int argc = 0;
static char *argv[] = {name,0};
class KdePluginImplementation: public KdePluginImplementationBase
{
private:
KABC::AddressBook* addressbookptr;
KABC::Ticket* addressbookticket;
QDateTime syncdate, newsyncdate;
KCalDataSource *kcal;
OSyncMember *member;
OSyncHashTable *hashtable;
public:
KdePluginImplementation(OSyncMember *memb)
:member(memb)
{
//osync_debug("kde", 3, "%s(%s)", __FUNCTION__);
KCmdLineArgs::init(argc, argv, "kde-opensync-plugin", i18n("KOpenSync"), "KDE OpenSync plugin", "0.1", false);
applicationptr = new KApplication();
//get a handle to the standard KDE addressbook
addressbookptr = KABC::StdAddressBook::self();
//ensure a NULL Ticket ptr
addressbookticket=NULL;
hashtable = osync_hashtable_new();
osync_hashtable_load(hashtable, member);
/*TODO: check if synchronizing Calendar data is desired */
//kcal = new KCalDataSource(member, hashtable);
kcal = NULL; // disable kcal change reporting, by now
}
virtual ~KdePluginImplementation()
{
if (kcal) {
delete kcal;
kcal = NULL;
}
if (applicationptr) {
delete applicationptr;
applicationptr = NULL;
}
}
/** Calculate the hash value for an Addressee.
* Should be called before returning/writing the
* data, because the revision of the Addressee
* can be changed.
*/
QString calc_hash(KABC::Addressee &e)
{
//Get the revision date of the KDE addressbook entry.
//Regard entries with invalid revision dates as having just been changed.
QDateTime revdate = e.revision();
if (!revdate.isValid())
{
revdate = newsyncdate; //use date of this sync as the revision date.
e.setRevision(revdate); //update the Addressbook entry for future reference.
}
/*FIXME: not i18ned string */
return revdate.toString();
}
virtual void connect(OSyncContext *ctx)
{
//Lock the addressbook
addressbookticket = addressbookptr->requestSaveTicket();
if (!addressbookticket)
{
osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't lock KDE addressbook");
return;
}
osync_debug("kde", 3, "KDE addressbook locked OK.");
if (kcal && !kcal->connect(ctx))
return;
osync_context_report_success(ctx);
}
virtual void disconnect(OSyncContext *ctx)
{
//Unlock the addressbook
addressbookptr->save(addressbookticket);
addressbookticket = NULL;
if (kcal && !kcal->disconnect(ctx))
return;
osync_context_report_success(ctx);
}
/*FIXME: move kaddrbook implementation to kaddrbook.cpp */
bool addrbook_get_changeinfo(OSyncContext *ctx)
{
//osync_debug("kde", 3, "kaddrbook::%s(newdbs=%d)", __FUNCTION__, newdbs);
//FIXME: should I detect if slow_sync is necessary?
if (osync_member_get_slow_sync(member, "contact"))
osync_hashtable_set_slow_sync(hashtable, "contact");
//remember when we started this current sync
newsyncdate = QDateTime::currentDateTime();
// We must reload the KDE addressbook in order to retrieve the latest changes.
if (!addressbookptr->load())
{
osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't reload KDE addressbook");
return false;
}
osync_debug("kde", 3, "KDE addressbook reloaded OK.");
KABC::VCardConverter converter;
for (KABC::AddressBook::Iterator it=addressbookptr->begin(); it!=addressbookptr->end(); it++ ) {
QString uid = it->uid();
osync_debug("kde", 3, "new entry, uid: %s", uid.latin1());
QString hash = calc_hash(*it);
// gmalloc a changed_object for this phonebook entry
//FIXME: deallocate it somewhere
OSyncChange *chg= osync_change_new();
osync_change_set_member(chg, member);
osync_change_set_hash(chg, hash);
osync_change_set_uid(chg, uid.latin1());
// Convert the VCARD data into a string
QString card = converter.createVCard(*it);
const char *data = card.latin1();
//FIXME: deallocate data somewhere
osync_change_set_data(chg, strdup(data), strlen(data), 1);
// object type and format
osync_change_set_objtype_string(chg, "contact");
osync_change_set_objformat_string(chg, "vcard");
// Use the hash table to check if the object
// needs to be reported
osync_change_set_hash(chg, hash.data());
if (osync_hashtable_detect_change(hashtable, chg)) {
osync_context_report_change(ctx, chg);
osync_hashtable_update_hash(hashtable, chg);
}
}
// Use the hashtable to report deletions
osync_hashtable_report_deleted(hashtable, ctx, "contact");
return true;
}
virtual void get_changeinfo(OSyncContext *ctx)
{
if (!addrbook_get_changeinfo(ctx))
return;
if (kcal && !kcal->get_changeinfo(ctx))
return;
osync_context_report_success(ctx);
}
void kabc_get_data(OSyncContext *ctx, OSyncChange *chg)
{
QString uid = osync_change_get_uid(chg);
KABC::Addressee a = addressbookptr->findByUid(uid);
KABC::VCardConverter converter;
QString card = converter.createVCard(a);
const char *data = card.latin1();
//FIXME: deallocate data somewhere
osync_change_set_data(chg, strdup(data), strlen(data), 1);
osync_context_report_success(ctx);
}
virtual void get_data(OSyncContext *ctx, OSyncChange *)
{
/*
switch (osync_change_get_objtype(chg)) {
case contact:
kabc_get_data(ctx, chg);
break;
case calendar:
kcal->get_data(ctx, chg);
break;
default:
osync_context_report_error(ctx, OSYNC_ERROR_FILE_NOT_FOUND, "Invalid UID");
return;
}
osync_context_report_success(ctx);
*/
osync_context_report_error(ctx, OSYNC_ERROR_FILE_NOT_FOUND, "Invalid UID");
}
/** Access an object, without returning success
*
* returns 0 on success, < 0 on error.
* If an error occurss, the error will be already reported
* using osync_context_report_error()
*/
int __vcard_access(OSyncContext *ctx, OSyncChange *chg)
{
//osync_debug("kde", 3, "kaddrbook::%s()",__FUNCTION__);
QString uid = osync_change_get_uid(chg);
// Ensure we still have a lock on the KDE addressbook (we ought to)
if (addressbookticket==NULL)
{
//This should never happen, but just in case....
osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Lock on KDE addressbook was lost");
return -1;
}
KABC::VCardConverter converter;
OSyncChangeType chtype = osync_change_get_changetype(chg);
/* treat modified objects without UIDs as if they were newly added objects */
if (chtype == CHANGE_MODIFIED && uid.isEmpty())
chtype = CHANGE_ADDED;
// convert VCARD string from obj->comp into an Addresse object.
char *data;
size_t data_size;
data = (char*)osync_change_get_data(chg);
data_size = osync_change_get_datasize(chg);
switch(chtype)
{
case CHANGE_MODIFIED:
{
unfold_vcard(data, &data_size);
KABC::Addressee addressee = converter.parseVCard(QString::fromLatin1(data, data_size));
// ensure it has the correct UID
addressee.setUid(uid);
QString hash = calc_hash(addressee);
// replace the current addressbook entry (if any) with the new one
addressbookptr->insertAddressee(addressee);
osync_change_set_hash(chg, hash);
osync_debug("kde", 3, "KDE ADDRESSBOOK ENTRY UPDATED (UID=%s)", uid.latin1());
break;
}
case CHANGE_ADDED:
{
// convert VCARD string from obj->comp into an Addresse object
// KABC::VCardConverter doesnt do VCARD unfolding so we must do it ourselves first.
unfold_vcard(data, &data_size);
KABC::Addressee addressee = converter.parseVCard(QString::fromLatin1(data, data_size));
QString hash = calc_hash(addressee);
// add the new address to the addressbook
addressbookptr->insertAddressee(addressee);
osync_change_set_uid(chg, addressee.uid().latin1());
osync_change_set_hash(chg, hash);
osync_debug("kde", 3, "KDE ADDRESSBOOK ENTRY ADDED (UID=%s)", addressee.uid().latin1());
break;
}
case CHANGE_DELETED:
{
if (uid.isEmpty())
{
osync_context_report_error(ctx, OSYNC_ERROR_FILE_NOT_FOUND, "Trying to delete entry with empty UID");
return -1;
}
//find addressbook entry with matching UID and delete it
KABC::Addressee addressee = addressbookptr->findByUid(uid);
if(!addressee.isEmpty())
addressbookptr->removeAddressee(addressee);
osync_debug("kde", 3, "KDE ADDRESSBOOK ENTRY DELETED (UID=%s)", uid.latin1());
break;
}
default:
osync_context_report_error(ctx, OSYNC_ERROR_NOT_SUPPORTED, "Operation not supported");
return -1;
}
//Save the changes without dropping the lock
addressbookticket->resource()->save(addressbookticket);
return 0;
}
virtual bool vcard_access(OSyncContext *ctx, OSyncChange *chg)
{
if (__vcard_access(ctx, chg) < 0)
return false;
osync_context_report_success(ctx);
/*FIXME: What should be returned? */
return true;
}
virtual bool vcard_commit_change(OSyncContext *ctx, OSyncChange *chg)
{
if ( __vcard_access(ctx, chg) < 0)
return false;
osync_hashtable_update_hash(hashtable, chg);
osync_context_report_success(ctx);
/*FIXME: What should be returned? */
return true;
}
};
extern "C" {
KdePluginImplementationBase *new_KdePluginImplementation(OSyncMember *member)
{
return new KdePluginImplementation(member);
}
}// extern "C"
|
Disable libkcal implementation, until it is working completely
|
Disable libkcal implementation, until it is working completely
git-svn-id: e31799a7ad59d6ea355ca047c69e0aee8a59fcd3@133 53f5c7ee-bee3-0310-bbc5-ea0e15fffd5e
|
C++
|
lgpl-2.1
|
luizluca/opensync-luizluca,luizluca/opensync-luizluca
|
0f524d3f331043088048cccd3b1821ad8955d760
|
examples/fragmentation_test.cpp
|
examples/fragmentation_test.cpp
|
/*
Copyright (c) 2010, Arvid Norberg
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 author 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 "libtorrent/storage.hpp"
#include "libtorrent/file_pool.hpp"
#include <boost/utility.hpp>
#include <stdlib.h>
using namespace libtorrent;
int main(int argc, char* argv[])
{
if (argc != 3 && argc != 2)
{
fprintf(stderr, "Usage: fragmentation_test torrent-file file-storage-path\n"
" fragmentation_test file\n\n");
return 1;
}
if (argc == 2)
{
error_code ec;
file f(argv[1], file::read_only, ec);
if (ec)
{
fprintf(stderr, "Error opening file %s: %s\n", argv[1], ec.message().c_str());
return 1;
}
size_type off = f.phys_offset(0);
printf("physical offset of file %s: %" PRId64 "\n", argv[1], off);
return 0;
}
error_code ec;
boost::intrusive_ptr<torrent_info> ti(new torrent_info(argv[1], ec));
if (ec)
{
fprintf(stderr, "Error while loading torrent file: %s\n", ec.message().c_str());
return 1;
}
file_pool fp;
boost::shared_ptr<storage_interface> st(default_storage_constructor(ti->files(), 0, argv[2], fp, std::vector<boost::uint8_t>()));
// the first field is the piece index, the second
// one is the physical location of the piece on disk
std::vector<std::pair<int, size_type> > pieces;
// make sure all the files are there
std::vector<std::pair<size_type, std::time_t> > files = get_filesizes(ti->files(), argv[2]);
for (int i = 0; i < ti->num_files(); ++i)
{
if (ti->file_at(i).size == files[i].first) continue;
fprintf(stderr, "Files for this torrent are missing or incomplete: %s was %"PRId64" bytes, expected %"PRId64" bytes\n"
, ti->files().file_path(ti->file_at(i)).c_str(), files[i].first, ti->file_at(i).size);
return 1;
}
for (int i = 0; i < ti->num_pieces(); ++i)
{
pieces.push_back(std::make_pair(i, st->physical_offset(i, 0)));
if (pieces.back().second == size_type(i) * ti->piece_length())
{
// this suggests that the OS doesn't support physical offset
// or that the file doesn't exist, or some other file error
fprintf(stderr, "Your operating system or filesystem "
"does not appear to support querying physical disk offset\n");
return 1;
}
}
FILE* f = fopen("fragmentation.log", "w+");
if (f == 0)
{
fprintf(stderr, "error while opening log file: %s\n", strerror(errno));
return 1;
}
for (int i = 0; i < ti->num_pieces(); ++i)
{
fprintf(f, "%d %"PRId64"\n", pieces[i].first, pieces[i].second);
}
fclose(f);
f = fopen("fragmentation.gnuplot", "w+");
if (f == 0)
{
fprintf(stderr, "error while opening gnuplot file: %s\n", strerror(errno));
return 1;
}
fprintf(f,
"set term png size 1200,800\n"
"set output \"fragmentation.png\"\n"
"set xrange [*:*]\n"
"set xlabel \"piece\"\n"
"set ylabel \"drive offset\"\n"
"set key box\n"
"set title \"fragmentation for '%s'\"\n"
"set tics nomirror\n"
"plot \"fragmentation.log\" using 1:2 with dots lt rgb \"#e07070\" notitle axis x1y1\n"
, ti->name().c_str());
fclose(f);
system("gnuplot fragmentation.gnuplot");
}
|
/*
Copyright (c) 2010, Arvid Norberg
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 author 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 "libtorrent/storage.hpp"
#include "libtorrent/file_pool.hpp"
#include <boost/utility.hpp>
#include <stdlib.h>
using namespace libtorrent;
int main(int argc, char* argv[])
{
if (argc != 3 && argc != 2)
{
fprintf(stderr, "Usage: fragmentation_test torrent-file file-storage-path\n"
" fragmentation_test file\n\n");
return 1;
}
if (argc == 2)
{
error_code ec;
file f(argv[1], file::read_only, ec);
if (ec)
{
fprintf(stderr, "Error opening file %s: %s\n", argv[1], ec.message().c_str());
return 1;
}
size_type off = f.phys_offset(0);
printf("physical offset of file %s: %" PRId64 "\n", argv[1], off);
return 0;
}
error_code ec;
boost::intrusive_ptr<torrent_info> ti(new torrent_info(argv[1], ec));
if (ec)
{
fprintf(stderr, "Error while loading torrent file: %s\n", ec.message().c_str());
return 1;
}
file_pool fp;
boost::shared_ptr<storage_interface> st(default_storage_constructor(ti->files(), 0, argv[2], fp, std::vector<boost::uint8_t>()));
// the first field is the piece index, the second
// one is the physical location of the piece on disk
std::vector<std::pair<int, size_type> > pieces;
// make sure all the files are there
/* std::vector<std::pair<size_type, std::time_t> > files = get_filesizes(ti->files(), argv[2]);
for (int i = 0; i < ti->num_files(); ++i)
{
if (ti->file_at(i).size == files[i].first) continue;
fprintf(stderr, "Files for this torrent are missing or incomplete: %s was %"PRId64" bytes, expected %"PRId64" bytes\n"
, ti->files().file_path(ti->file_at(i)).c_str(), files[i].first, ti->file_at(i).size);
return 1;
}
*/
bool warned = false;
for (int i = 0; i < ti->num_pieces(); ++i)
{
pieces.push_back(std::make_pair(i, st->physical_offset(i, 0)));
if (pieces.back().second == size_type(i) * ti->piece_length())
{
// this suggests that the OS doesn't support physical offset
// or that the file doesn't exist or is incomplete
if (!warned)
{
fprintf(stderr, "The files are incomplete\n");
warned = true;
}
pieces.pop_back();
}
}
if (pieces.empty())
{
fprintf(stderr, "Your operating system or filesystem "
"does not appear to support querying physical disk offset\n");
}
FILE* f = fopen("fragmentation.log", "w+");
if (f == 0)
{
fprintf(stderr, "error while opening log file: %s\n", strerror(errno));
return 1;
}
for (int i = 0; i < pieces.size(); ++i)
{
fprintf(f, "%d %"PRId64"\n", pieces[i].first, pieces[i].second);
}
fclose(f);
f = fopen("fragmentation.gnuplot", "w+");
if (f == 0)
{
fprintf(stderr, "error while opening gnuplot file: %s\n", strerror(errno));
return 1;
}
fprintf(f,
"set term png size 1200,800\n"
"set output \"fragmentation.png\"\n"
"set xrange [*:*]\n"
"set xlabel \"piece\"\n"
"set ylabel \"drive offset\"\n"
"set key box\n"
"set title \"fragmentation for '%s'\"\n"
"set tics nomirror\n"
"plot \"fragmentation.log\" using 1:2 with points lt rgb \"#e07070\" notitle axis x1y1\n"
, ti->name().c_str());
fclose(f);
system("gnuplot fragmentation.gnuplot");
}
|
make fragmentation_test work with incomplete files as well
|
make fragmentation_test work with incomplete files as well
|
C++
|
bsd-3-clause
|
mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent,mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent,mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent,mildred/rasterbar-libtorrent,mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent,mildred/rasterbar-libtorrent,mrmichalis/libtorrent-code,mrmichalis/libtorrent-code
|
7aa0e2a4626b6e9571468017e1b60930942f2b1e
|
clog/src/LogImpl.cpp
|
clog/src/LogImpl.cpp
|
/* Copyright(C)
* For free
* All right reserved
*
*/
/**
* @file LogImpl.cpp
* @brief 日志库接口实现
* @author highway-9, [email protected]
* @version 1.1.0
* @date 2015-12-05
*/
#include "LogImpl.h"
#include "Utils.h"
#include <stdio.h>
#include <iostream>
#define DEFAULT_LOG_PRIORITY (log4cpp::Priority::DEBUG) // 日志文件默认优先级
#define MAX_LOGFILE_SIZE (3*1024*1024) // 日志文件默认大小
#define MAX_BACKUP_LOGFILE_COUNT (30) // 默认保存历史日志数量
LogImpl::LogImpl()
: m_root(NULL),
m_isInitSuccess(false)
{
m_isInitSuccess = init();
if (!m_isInitSuccess)
{
std::cout << "Init log failed" << std::endl;
}
}
LogImpl::~LogImpl()
{
deinit();
}
LogImpl* LogImpl::getInstance()
{
static LogImpl logImpl;
return &logImpl;
}
bool LogImpl::logPrint(unsigned int priorityLevel, const std::string& logContent)
{
if (!m_isInitSuccess)
{
return false;
}
m_root->log(priorityLevel, logContent);
return true;
}
bool LogImpl::init()
{
std::string logFileName = createLogFile();
if (logFileName.empty())
{
std::cout << "Create log file failed" << std::endl;
return false;
}
bool ok = initLogCore(logFileName);
if (!ok)
{
std::cout << "Init log core failed, log file name: " << logFileName << std::endl;
return false;
}
return true;
}
void LogImpl::deinit()
{
log4cpp::Category::shutdown();
}
std::string LogImpl::createLogFile()
{
// 获取当前可执行文件所在路径
std::string exePath = utils::FileSystem::currentExePath();
if (exePath.empty())
{
std::cout << "Get current exe path failed" << std::endl;
return "";
}
// 创建日志路径
std::string logPath = exePath + "/logs";
bool ok = utils::FileSystem::mkdir(logPath);
if (!ok)
{
std::cout << "Create log path failed, log path: " << logPath << std::endl;
return "";
}
// 获取当前可执行文件名
std::string exeName = utils::FileSystem::currentExeName();
if (exeName.empty())
{
std::cout << "Get current exe name failed" << std::endl;
return "";
}
// 日志文件名
std::string logFileName = logPath + "/" + exeName + ".log";
return logFileName;
}
bool LogImpl::initLogCore(const std::string& logFileName)
{
log4cpp::PatternLayout* fileLayout = NULL;
fileLayout = new log4cpp::PatternLayout();
fileLayout->setConversionPattern("%d: [%-5p] %c%x: %m%n");
log4cpp::PatternLayout* consoleLayout = NULL;
consoleLayout = new log4cpp::PatternLayout();
consoleLayout->setConversionPattern("%d: [%-5p] %c%x: %m%n");
log4cpp::RollingFileAppender* rollfileAppender = NULL;
rollfileAppender = new log4cpp::RollingFileAppender("rollfileAppender", logFileName, MAX_LOGFILE_SIZE, 1);
rollfileAppender->setMaxBackupIndex(MAX_BACKUP_LOGFILE_COUNT);
rollfileAppender->setLayout(fileLayout);
log4cpp::OstreamAppender* osAppender = NULL;
osAppender = new log4cpp::OstreamAppender("osAppender", &std::cout);
osAppender->setLayout(consoleLayout);
m_root = &(log4cpp::Category::getRoot().getInstance(""));
// 一个Category可以附加多个Appender
m_root->setAdditivity(true);
m_root->addAppender(rollfileAppender);
m_root->addAppender(osAppender);
m_root->setPriority(DEFAULT_LOG_PRIORITY);
return true;
}
|
/* Copyright(C)
* For free
* All right reserved
*
*/
/**
* @file LogImpl.cpp
* @brief 日志库接口实现
* @author highway-9, [email protected]
* @version 1.1.0
* @date 2015-12-05
*/
#include "LogImpl.h"
#include "Utils.h"
#include <stdio.h>
#include <iostream>
#define DEFAULT_LOG_PRIORITY (log4cpp::Priority::DEBUG) // 日志文件默认优先级
#define MAX_LOGFILE_SIZE (3*1024*1024) // 日志文件默认大小
#define MAX_BACKUP_LOGFILE_COUNT (30) // 默认保存历史日志数量
LogImpl::LogImpl()
: m_root(NULL),
m_isInitSuccess(false)
{
m_isInitSuccess = init();
if (!m_isInitSuccess)
{
std::cout << "Init log failed" << std::endl;
}
}
LogImpl::~LogImpl()
{
deinit();
}
LogImpl* LogImpl::getInstance()
{
static LogImpl logImpl;
return &logImpl;
}
bool LogImpl::logPrint(unsigned int priorityLevel, const std::string& logContent)
{
if (!m_isInitSuccess)
{
return false;
}
m_root->log(priorityLevel, logContent);
return true;
}
bool LogImpl::init()
{
std::string logFileName = createLogFile();
if (logFileName.empty())
{
std::cout << "Create log file failed" << std::endl;
return false;
}
bool ok = initLogCore(logFileName);
if (!ok)
{
std::cout << "Init log core failed, log file name: " << logFileName << std::endl;
return false;
}
return true;
}
void LogImpl::deinit()
{
log4cpp::Category::shutdown();
}
std::string LogImpl::createLogFile()
{
// 获取当前可执行文件所在路径
std::string exePath = utils::FileSystem::currentExePath();
if (exePath.empty())
{
std::cout << "Get current exe path failed" << std::endl;
return "";
}
// 创建日志路径
std::string logPath = exePath + "/logs";
bool ok = utils::FileSystem::mkdir(logPath);
if (!ok)
{
std::cout << "Create log path failed, log path: " << logPath << std::endl;
return "";
}
// 获取当前可执行文件名
std::string exeName = utils::FileSystem::currentExeName();
if (exeName.empty())
{
std::cout << "Get current exe name failed" << std::endl;
return "";
}
// 日志文件名
std::string logFileName = logPath + "/" + exeName + ".log";
return logFileName;
}
bool LogImpl::initLogCore(const std::string& logFileName)
{
log4cpp::PatternLayout* fileLayout = new log4cpp::PatternLayout();
fileLayout->setConversionPattern("%d: [%-5p] %c%x: %m%n");
log4cpp::PatternLayout* consoleLayout = new log4cpp::PatternLayout();
consoleLayout->setConversionPattern("%d: [%-5p] %c%x: %m%n");
log4cpp::RollingFileAppender* rollfileAppender =
new log4cpp::RollingFileAppender("rollfileAppender", logFileName, MAX_LOGFILE_SIZE, 1);
rollfileAppender->setMaxBackupIndex(MAX_BACKUP_LOGFILE_COUNT);
rollfileAppender->setLayout(fileLayout);
log4cpp::OstreamAppender* osAppender = new log4cpp::OstreamAppender("osAppender", &std::cout);
osAppender->setLayout(consoleLayout);
m_root = &(log4cpp::Category::getRoot().getInstance(""));
// 一个Category可以附加多个Appender
m_root->setAdditivity(true);
m_root->addAppender(rollfileAppender);
m_root->addAppender(osAppender);
m_root->setPriority(DEFAULT_LOG_PRIORITY);
return true;
}
|
Update clog
|
Update clog
|
C++
|
mit
|
chxuan/easyrpc,chxuan/easyrpc,chxuan/easyrpc,chxuan/easyrpc
|
c433eae9f669b77929894ff328f5030bfa5be0ae
|
urbackupserver/ChunkPatcher.cpp
|
urbackupserver/ChunkPatcher.cpp
|
#include "ChunkPatcher.h"
#include "../stringtools.h"
#include <assert.h>
ChunkPatcher::ChunkPatcher(void)
: cb(NULL), require_unchanged(true)
{
}
void ChunkPatcher::setCallback(IChunkPatcherCallback *pCb)
{
cb=pCb;
}
bool ChunkPatcher::ApplyPatch(IFile *file, IFile *patch)
{
patch->Seek(0);
file->Seek(0);
_i64 patchf_pos=0;
const unsigned int buffer_size=32768;
char buf[buffer_size];
if(patch->Read((char*)&filesize, sizeof(_i64))!=sizeof(_i64))
{
return false;
}
filesize = little_endian(filesize);
patchf_pos+=sizeof(_i64);
SPatchHeader next_header;
next_header.patch_off=-1;
bool has_header=true;
for(_i64 file_pos=0,size=file->Size(); (file_pos<size && file_pos<filesize) || has_header;)
{
if(has_header && next_header.patch_off==-1)
{
has_header=readNextValidPatch(patch, patchf_pos, &next_header);
}
unsigned int tr=buffer_size;
if(next_header.patch_off!=-1)
{
_i64 hoff=next_header.patch_off-file_pos;
if(hoff>=0 && hoff<tr)
tr=(unsigned int)hoff;
assert(hoff>=0);
}
if(file_pos>=filesize)
{
Server->Log("Patch corrupt file_pos>=filesize. file_pos="+nconvert(file_pos)+" next_header.patch_off="+nconvert(next_header.patch_off)+" next_header.patch_size="+nconvert(next_header.patch_size)+" tr="+nconvert(tr)+" size="+nconvert(size)+" filesize="+nconvert(filesize)+" has_header="+nconvert(has_header), LL_ERROR);
assert(file_pos<filesize);
return false;
}
if(tr==0)
{
assert(file_pos==next_header.patch_off);
file_pos+=next_header.patch_size;
while(next_header.patch_size>0)
{
_u32 r=patch->Read((char*)buf, (std::min)((unsigned int)buffer_size, next_header.patch_size));
patchf_pos+=r;
cb->next_chunk_patcher_bytes(buf, r, true);
next_header.patch_size-=r;
}
if(require_unchanged)
{
file->Seek(file_pos);
}
next_header.patch_off=-1;
}
else if(file_pos<size && file_pos<filesize)
{
while(tr>0 && file_pos<size && file_pos<filesize)
{
if(file_pos+tr>filesize)
{
tr=static_cast<unsigned int>(filesize-file_pos);
}
if(require_unchanged)
{
_u32 r=file->Read((char*)buf, tr);
file_pos+=r;
cb->next_chunk_patcher_bytes(buf, r, false);
tr-=r;
}
else
{
if(file_pos+tr>size)
{
tr=static_cast<unsigned int>(size-file_pos);
}
file_pos+=tr;
cb->next_chunk_patcher_bytes(NULL, tr, false);
tr=0;
}
}
}
else
{
Server->Log("Patch corrupt. file_pos="+nconvert(file_pos)+" next_header.patch_off="+nconvert(next_header.patch_off)+" next_header.patch_size="+nconvert(next_header.patch_size)+" tr="+nconvert(tr)+" size="+nconvert(size)+" filesize="+nconvert(filesize), LL_ERROR);
assert(false);
return false;
}
}
return true;
}
bool ChunkPatcher::readNextValidPatch(IFile *patchf, _i64 &patchf_pos, SPatchHeader *patch_header)
{
const unsigned int to_read=sizeof(_i64)+sizeof(unsigned int);
do
{
_u32 r=patchf->Read((char*)&patch_header->patch_off, to_read);
patchf_pos+=r;
if(r!=to_read)
{
patch_header->patch_off=-1;
patch_header->patch_size=0;
return false;
}
else
{
patch_header->patch_off = little_endian(patch_header->patch_off);
patch_header->patch_size = little_endian(patch_header->patch_size);
}
if(patch_header->patch_off==-1)
{
patchf_pos+=patch_header->patch_size;
patchf->Seek(patchf_pos);
}
}
while(patch_header->patch_off==-1);
return true;
}
_i64 ChunkPatcher::getFilesize(void)
{
return filesize;
}
void ChunkPatcher::setRequireUnchanged( bool b )
{
require_unchanged=b;
}
|
#include "ChunkPatcher.h"
#include "../stringtools.h"
#include <assert.h>
ChunkPatcher::ChunkPatcher(void)
: cb(NULL), require_unchanged(true)
{
}
void ChunkPatcher::setCallback(IChunkPatcherCallback *pCb)
{
cb=pCb;
}
bool ChunkPatcher::ApplyPatch(IFile *file, IFile *patch)
{
patch->Seek(0);
file->Seek(0);
_i64 patchf_pos=0;
const unsigned int buffer_size=32768;
char buf[buffer_size];
if(patch->Read((char*)&filesize, sizeof(_i64))!=sizeof(_i64))
{
return false;
}
filesize = little_endian(filesize);
patchf_pos+=sizeof(_i64);
SPatchHeader next_header;
next_header.patch_off=-1;
bool has_header=true;
for(_i64 file_pos=0,size=file->Size(); (file_pos<size && file_pos<filesize) || has_header;)
{
if(has_header && next_header.patch_off==-1)
{
has_header=readNextValidPatch(patch, patchf_pos, &next_header);
if(!has_header && file_pos>=filesize)
{
break;
}
}
unsigned int tr=buffer_size;
if(next_header.patch_off!=-1)
{
_i64 hoff=next_header.patch_off-file_pos;
if(hoff>=0 && hoff<tr)
tr=(unsigned int)hoff;
assert(hoff>=0);
}
if(file_pos>=filesize)
{
Server->Log("Patch corrupt file_pos>=filesize. file_pos="+nconvert(file_pos)+" next_header.patch_off="+nconvert(next_header.patch_off)+" next_header.patch_size="+nconvert(next_header.patch_size)+" tr="+nconvert(tr)+" size="+nconvert(size)+" filesize="+nconvert(filesize)+" has_header="+nconvert(has_header), LL_ERROR);
assert(file_pos<filesize);
return false;
}
if(tr==0)
{
assert(file_pos==next_header.patch_off);
file_pos+=next_header.patch_size;
while(next_header.patch_size>0)
{
_u32 r=patch->Read((char*)buf, (std::min)((unsigned int)buffer_size, next_header.patch_size));
patchf_pos+=r;
cb->next_chunk_patcher_bytes(buf, r, true);
next_header.patch_size-=r;
}
if(require_unchanged)
{
file->Seek(file_pos);
}
next_header.patch_off=-1;
}
else if(file_pos<size && file_pos<filesize)
{
while(tr>0 && file_pos<size && file_pos<filesize)
{
if(file_pos+tr>filesize)
{
tr=static_cast<unsigned int>(filesize-file_pos);
}
if(require_unchanged)
{
_u32 r=file->Read((char*)buf, tr);
file_pos+=r;
cb->next_chunk_patcher_bytes(buf, r, false);
tr-=r;
}
else
{
if(file_pos+tr>size)
{
tr=static_cast<unsigned int>(size-file_pos);
}
file_pos+=tr;
cb->next_chunk_patcher_bytes(NULL, tr, false);
tr=0;
}
}
}
else
{
Server->Log("Patch corrupt. file_pos="+nconvert(file_pos)+" next_header.patch_off="+nconvert(next_header.patch_off)+" next_header.patch_size="+nconvert(next_header.patch_size)+" tr="+nconvert(tr)+" size="+nconvert(size)+" filesize="+nconvert(filesize), LL_ERROR);
assert(false);
return false;
}
}
return true;
}
bool ChunkPatcher::readNextValidPatch(IFile *patchf, _i64 &patchf_pos, SPatchHeader *patch_header)
{
const unsigned int to_read=sizeof(_i64)+sizeof(unsigned int);
do
{
_u32 r=patchf->Read((char*)&patch_header->patch_off, to_read);
patchf_pos+=r;
if(r!=to_read)
{
patch_header->patch_off=-1;
patch_header->patch_size=0;
return false;
}
else
{
patch_header->patch_off = little_endian(patch_header->patch_off);
patch_header->patch_size = little_endian(patch_header->patch_size);
}
if(patch_header->patch_off==-1)
{
patchf_pos+=patch_header->patch_size;
patchf->Seek(patchf_pos);
}
}
while(patch_header->patch_off==-1);
return true;
}
_i64 ChunkPatcher::getFilesize(void)
{
return filesize;
}
void ChunkPatcher::setRequireUnchanged( bool b )
{
require_unchanged=b;
}
|
Exit if no header was found and file was patched (cherry picked from commit c16fdd0c343d0a58147046a0002992eefecef655)
|
Exit if no header was found and file was patched
(cherry picked from commit c16fdd0c343d0a58147046a0002992eefecef655)
|
C++
|
agpl-3.0
|
uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend
|
904db1100fb9335a8aa4caa450d04bd84b152ce4
|
utils/TableGen/CTagsEmitter.cpp
|
utils/TableGen/CTagsEmitter.cpp
|
//===- CTagsEmitter.cpp - Generate ctags-compatible index ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend emits an index of definitions in ctags(1) format.
// A helper script, utils/TableGen/tdtags, provides an easier-to-use
// interface; run 'tdtags -H' for documentation.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include <algorithm>
#include <string>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "ctags-emitter"
namespace llvm { extern SourceMgr SrcMgr; }
namespace {
class Tag {
private:
const std::string *Id;
SMLoc Loc;
public:
Tag(const std::string &Name, const SMLoc Location)
: Id(&Name), Loc(Location) {}
int operator<(const Tag &B) const { return *Id < *B.Id; }
void emit(raw_ostream &OS) const {
const MemoryBuffer *CurMB =
SrcMgr.getMemoryBuffer(SrcMgr.FindBufferContainingLoc(Loc));
const char *BufferName = CurMB->getBufferIdentifier();
std::pair<unsigned, unsigned> LineAndColumn = SrcMgr.getLineAndColumn(Loc);
OS << *Id << "\t" << BufferName << "\t" << LineAndColumn.first << "\n";
}
};
class CTagsEmitter {
private:
RecordKeeper &Records;
public:
CTagsEmitter(RecordKeeper &R) : Records(R) {}
void run(raw_ostream &OS);
private:
static SMLoc locate(const Record *R);
};
} // End anonymous namespace.
SMLoc CTagsEmitter::locate(const Record *R) {
ArrayRef<SMLoc> Locs = R->getLoc();
if (Locs.empty()) {
SMLoc NullLoc;
return NullLoc;
}
return Locs.front();
}
void CTagsEmitter::run(raw_ostream &OS) {
const auto &Classes = Records.getClasses();
const auto &Defs = Records.getDefs();
std::vector<Tag> Tags;
// Collect tags.
Tags.reserve(Classes.size() + Defs.size());
for (const auto &C : Classes)
Tags.push_back(Tag(C.first, locate(C.second.get())));
for (const auto &D : Defs)
Tags.push_back(Tag(D.first, locate(D.second.get())));
// Emit tags.
std::sort(Tags.begin(), Tags.end());
OS << "!_TAG_FILE_FORMAT\t1\t/original ctags format/\n";
OS << "!_TAG_FILE_SORTED\t1\t/0=unsorted, 1=sorted, 2=foldcase/\n";
for (std::vector<Tag>::const_iterator I = Tags.begin(), E = Tags.end();
I != E; ++I)
I->emit(OS);
}
namespace llvm {
void EmitCTags(RecordKeeper &RK, raw_ostream &OS) { CTagsEmitter(RK).run(OS); }
} // End llvm namespace.
|
//===- CTagsEmitter.cpp - Generate ctags-compatible index ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend emits an index of definitions in ctags(1) format.
// A helper script, utils/TableGen/tdtags, provides an easier-to-use
// interface; run 'tdtags -H' for documentation.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include <algorithm>
#include <string>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "ctags-emitter"
namespace {
class Tag {
private:
const std::string *Id;
SMLoc Loc;
public:
Tag(const std::string &Name, const SMLoc Location)
: Id(&Name), Loc(Location) {}
int operator<(const Tag &B) const { return *Id < *B.Id; }
void emit(raw_ostream &OS) const {
const MemoryBuffer *CurMB =
SrcMgr.getMemoryBuffer(SrcMgr.FindBufferContainingLoc(Loc));
const char *BufferName = CurMB->getBufferIdentifier();
std::pair<unsigned, unsigned> LineAndColumn = SrcMgr.getLineAndColumn(Loc);
OS << *Id << "\t" << BufferName << "\t" << LineAndColumn.first << "\n";
}
};
class CTagsEmitter {
private:
RecordKeeper &Records;
public:
CTagsEmitter(RecordKeeper &R) : Records(R) {}
void run(raw_ostream &OS);
private:
static SMLoc locate(const Record *R);
};
} // End anonymous namespace.
SMLoc CTagsEmitter::locate(const Record *R) {
ArrayRef<SMLoc> Locs = R->getLoc();
if (Locs.empty()) {
SMLoc NullLoc;
return NullLoc;
}
return Locs.front();
}
void CTagsEmitter::run(raw_ostream &OS) {
const auto &Classes = Records.getClasses();
const auto &Defs = Records.getDefs();
std::vector<Tag> Tags;
// Collect tags.
Tags.reserve(Classes.size() + Defs.size());
for (const auto &C : Classes)
Tags.push_back(Tag(C.first, locate(C.second.get())));
for (const auto &D : Defs)
Tags.push_back(Tag(D.first, locate(D.second.get())));
// Emit tags.
std::sort(Tags.begin(), Tags.end());
OS << "!_TAG_FILE_FORMAT\t1\t/original ctags format/\n";
OS << "!_TAG_FILE_SORTED\t1\t/0=unsorted, 1=sorted, 2=foldcase/\n";
for (std::vector<Tag>::const_iterator I = Tags.begin(), E = Tags.end();
I != E; ++I)
I->emit(OS);
}
namespace llvm {
void EmitCTags(RecordKeeper &RK, raw_ostream &OS) { CTagsEmitter(RK).run(OS); }
} // End llvm namespace.
|
Remove unnecessary extern declaration that's already in an included header file.
|
[TableGen] Remove unnecessary extern declaration that's already in an included header file.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@239275 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm
|
9f27bcac22d3ccc6c1f12a59ebc6b191cf230bb8
|
project/src/backend/sdl/SDLApplication.cpp
|
project/src/backend/sdl/SDLApplication.cpp
|
#include "SDLApplication.h"
#include "SDLGamepad.h"
#ifdef HX_MACOS
#include <CoreFoundation/CoreFoundation.h>
#endif
#ifdef EMSCRIPTEN
#include "emscripten.h"
#endif
namespace lime {
AutoGCRoot* Application::callback = 0;
SDLApplication* SDLApplication::currentApplication = 0;
SDLApplication::SDLApplication () {
if (SDL_Init (SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_TIMER) != 0) {
printf ("Could not initialize SDL: %s.\n", SDL_GetError ());
}
currentApplication = this;
framePeriod = 1000.0 / 60.0;
#ifdef EMSCRIPTEN
emscripten_cancel_main_loop ();
emscripten_set_main_loop (UpdateFrame, 0, 0);
emscripten_set_main_loop_timing (EM_TIMING_RAF, 1);
#endif
currentUpdate = 0;
lastUpdate = 0;
nextUpdate = 0;
GamepadEvent gamepadEvent;
KeyEvent keyEvent;
MouseEvent mouseEvent;
RenderEvent renderEvent;
TextEvent textEvent;
TouchEvent touchEvent;
UpdateEvent updateEvent;
WindowEvent windowEvent;
#ifdef HX_MACOS
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL (CFBundleGetMainBundle ());
char path[PATH_MAX];
if (CFURLGetFileSystemRepresentation (resourcesURL, TRUE, (UInt8 *)path, PATH_MAX)) {
chdir (path);
}
CFRelease (resourcesURL);
#endif
}
SDLApplication::~SDLApplication () {
}
int SDLApplication::Exec () {
Init ();
#ifdef EMSCRIPTEN
return 0;
#else
while (active) {
Update ();
}
return Quit ();
#endif
}
void SDLApplication::HandleEvent (SDL_Event* event) {
switch (event->type) {
case SDL_USEREVENT:
currentUpdate = SDL_GetTicks ();
updateEvent.deltaTime = currentUpdate - lastUpdate;
lastUpdate = currentUpdate;
while (nextUpdate <= currentUpdate) {
nextUpdate += framePeriod;
}
UpdateEvent::Dispatch (&updateEvent);
RenderEvent::Dispatch (&renderEvent);
break;
case SDL_APP_WILLENTERBACKGROUND:
windowEvent.type = WINDOW_DEACTIVATE;
WindowEvent::Dispatch (&windowEvent);
break;
case SDL_APP_WILLENTERFOREGROUND:
windowEvent.type = WINDOW_ACTIVATE;
WindowEvent::Dispatch (&windowEvent);
break;
case SDL_CONTROLLERAXISMOTION:
case SDL_CONTROLLERBUTTONDOWN:
case SDL_CONTROLLERBUTTONUP:
case SDL_CONTROLLERDEVICEADDED:
case SDL_CONTROLLERDEVICEREMOVED:
ProcessGamepadEvent (event);
break;
case SDL_JOYAXISMOTION:
case SDL_JOYBALLMOTION:
case SDL_JOYBUTTONDOWN:
case SDL_JOYBUTTONUP:
case SDL_JOYHATMOTION:
case SDL_JOYDEVICEADDED:
case SDL_JOYDEVICEREMOVED:
//joy
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
ProcessKeyEvent (event);
break;
case SDL_MOUSEMOTION:
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
case SDL_MOUSEWHEEL:
ProcessMouseEvent (event);
break;
case SDL_TEXTINPUT:
case SDL_TEXTEDITING:
ProcessTextEvent (event);
break;
case SDL_WINDOWEVENT:
switch (event->window.event) {
case SDL_WINDOWEVENT_ENTER:
case SDL_WINDOWEVENT_LEAVE:
case SDL_WINDOWEVENT_SHOWN:
case SDL_WINDOWEVENT_HIDDEN:
case SDL_WINDOWEVENT_FOCUS_GAINED:
case SDL_WINDOWEVENT_FOCUS_LOST:
case SDL_WINDOWEVENT_MINIMIZED:
case SDL_WINDOWEVENT_MOVED:
case SDL_WINDOWEVENT_RESTORED:
ProcessWindowEvent (event);
break;
case SDL_WINDOWEVENT_EXPOSED:
RenderEvent::Dispatch (&renderEvent);
break;
case SDL_WINDOWEVENT_SIZE_CHANGED:
ProcessWindowEvent (event);
RenderEvent::Dispatch (&renderEvent);
break;
case SDL_WINDOWEVENT_CLOSE:
ProcessWindowEvent (event);
active = false;
break;
}
break;
case SDL_QUIT:
//quit
active = false;
break;
}
}
void SDLApplication::Init () {
active = true;
lastUpdate = SDL_GetTicks ();
nextUpdate = lastUpdate;
}
void SDLApplication::ProcessGamepadEvent (SDL_Event* event) {
if (GamepadEvent::callback) {
switch (event->type) {
case SDL_CONTROLLERAXISMOTION:
gamepadEvent.type = AXIS_MOVE;
gamepadEvent.axis = event->caxis.axis;
gamepadEvent.id = event->caxis.which;
gamepadEvent.axisValue = event->caxis.value / 32768.0;
GamepadEvent::Dispatch (&gamepadEvent);
break;
case SDL_CONTROLLERBUTTONDOWN:
gamepadEvent.type = BUTTON_DOWN;
gamepadEvent.button = event->cbutton.button;
gamepadEvent.id = event->cbutton.which;
GamepadEvent::Dispatch (&gamepadEvent);
break;
case SDL_CONTROLLERBUTTONUP:
gamepadEvent.type = BUTTON_UP;
gamepadEvent.button = event->cbutton.button;
gamepadEvent.id = event->cbutton.which;
GamepadEvent::Dispatch (&gamepadEvent);
break;
case SDL_CONTROLLERDEVICEADDED:
if (SDLGamepad::Connect (event->cdevice.which)) {
gamepadEvent.type = CONNECT;
gamepadEvent.id = SDLGamepad::GetInstanceID (event->cdevice.which);
GamepadEvent::Dispatch (&gamepadEvent);
}
break;
case SDL_CONTROLLERDEVICEREMOVED: {
gamepadEvent.type = DISCONNECT;
gamepadEvent.id = event->cdevice.which;
GamepadEvent::Dispatch (&gamepadEvent);
SDLGamepad::Disconnect (event->cdevice.which);
break;
}
}
}
}
void SDLApplication::ProcessKeyEvent (SDL_Event* event) {
if (KeyEvent::callback) {
switch (event->type) {
case SDL_KEYDOWN: keyEvent.type = KEY_DOWN; break;
case SDL_KEYUP: keyEvent.type = KEY_UP; break;
}
keyEvent.keyCode = event->key.keysym.sym;
keyEvent.modifier = event->key.keysym.mod;
KeyEvent::Dispatch (&keyEvent);
}
}
void SDLApplication::ProcessMouseEvent (SDL_Event* event) {
if (MouseEvent::callback) {
switch (event->type) {
case SDL_MOUSEMOTION:
mouseEvent.type = MOUSE_MOVE;
mouseEvent.x = event->motion.x;
mouseEvent.y = event->motion.y;
mouseEvent.movementX = event->motion.xrel;
mouseEvent.movementY = event->motion.yrel;
break;
case SDL_MOUSEBUTTONDOWN:
mouseEvent.type = MOUSE_DOWN;
mouseEvent.button = event->button.button - 1;
mouseEvent.x = event->button.x;
mouseEvent.y = event->button.y;
break;
case SDL_MOUSEBUTTONUP:
mouseEvent.type = MOUSE_UP;
mouseEvent.button = event->button.button - 1;
mouseEvent.x = event->button.x;
mouseEvent.y = event->button.y;
break;
case SDL_MOUSEWHEEL:
mouseEvent.type = MOUSE_WHEEL;
mouseEvent.x = event->wheel.x;
mouseEvent.y = event->wheel.y;
break;
}
MouseEvent::Dispatch (&mouseEvent);
}
}
void SDLApplication::ProcessTextEvent (SDL_Event* event) {
if (TextEvent::callback) {
switch (event->type) {
case SDL_TEXTINPUT:
textEvent.type = TEXT_INPUT;
break;
case SDL_TEXTEDITING:
textEvent.type = TEXT_EDIT;
textEvent.start = event->edit.start;
textEvent.length = event->edit.length;
break;
}
strcpy (textEvent.text, event->text.text);
TextEvent::Dispatch (&textEvent);
}
}
void SDLApplication::ProcessTouchEvent (SDL_Event* event) {
}
void SDLApplication::ProcessWindowEvent (SDL_Event* event) {
if (WindowEvent::callback) {
switch (event->window.event) {
case SDL_WINDOWEVENT_SHOWN: windowEvent.type = WINDOW_ACTIVATE; break;
case SDL_WINDOWEVENT_CLOSE: windowEvent.type = WINDOW_CLOSE; break;
case SDL_WINDOWEVENT_HIDDEN: windowEvent.type = WINDOW_DEACTIVATE; break;
case SDL_WINDOWEVENT_ENTER: windowEvent.type = WINDOW_ENTER; break;
case SDL_WINDOWEVENT_FOCUS_GAINED: windowEvent.type = WINDOW_FOCUS_IN; break;
case SDL_WINDOWEVENT_FOCUS_LOST: windowEvent.type = WINDOW_FOCUS_OUT; break;
case SDL_WINDOWEVENT_LEAVE: windowEvent.type = WINDOW_LEAVE; break;
case SDL_WINDOWEVENT_MINIMIZED: windowEvent.type = WINDOW_MINIMIZE; break;
case SDL_WINDOWEVENT_MOVED:
windowEvent.type = WINDOW_MOVE;
windowEvent.x = event->window.data1;
windowEvent.y = event->window.data2;
break;
case SDL_WINDOWEVENT_SIZE_CHANGED:
windowEvent.type = WINDOW_RESIZE;
windowEvent.width = event->window.data1;
windowEvent.height = event->window.data2;
break;
case SDL_WINDOWEVENT_RESTORED: windowEvent.type = WINDOW_RESTORE; break;
}
WindowEvent::Dispatch (&windowEvent);
}
}
int SDLApplication::Quit () {
windowEvent.type = WINDOW_DEACTIVATE;
WindowEvent::Dispatch (&windowEvent);
SDL_Quit ();
return 0;
}
void SDLApplication::RegisterWindow (SDLWindow *window) {
#ifdef IPHONE
SDL_iPhoneSetAnimationCallback (window->sdlWindow, 1, UpdateFrame, NULL);
#endif
}
void SDLApplication::SetFrameRate (double frameRate) {
if (frameRate > 0) {
framePeriod = 1000.0 / frameRate;
} else {
framePeriod = 1000.0;
}
}
static SDL_TimerID timerID = 0;
bool timerActive = false;
bool firstTime = true;
Uint32 OnTimer (Uint32 interval, void *) {
SDL_Event event;
SDL_UserEvent userevent;
userevent.type = SDL_USEREVENT;
userevent.code = 0;
userevent.data1 = NULL;
userevent.data2 = NULL;
event.type = SDL_USEREVENT;
event.user = userevent;
timerActive = false;
timerID = 0;
SDL_PushEvent (&event);
return 0;
}
bool SDLApplication::Update () {
SDL_Event event;
event.type = -1;
#if (!defined (IPHONE) && !defined (EMSCRIPTEN))
if (active && (firstTime || SDL_WaitEvent (&event))) {
firstTime = false;
HandleEvent (&event);
event.type = -1;
if (!active)
return active;
#endif
while (SDL_PollEvent (&event)) {
HandleEvent (&event);
event.type = -1;
if (!active)
return active;
}
currentUpdate = SDL_GetTicks ();
#if defined (IPHONE)
if (currentUpdate >= nextUpdate) {
event.type = SDL_USEREVENT;
HandleEvent (&event);
event.type = -1;
}
#elif defined (EMSCRIPTEN)
event.type = SDL_USEREVENT;
HandleEvent (&event);
event.type = -1;
#else
if (currentUpdate >= nextUpdate) {
SDL_RemoveTimer (timerID);
OnTimer (0, 0);
} else if (!timerActive) {
timerActive = true;
timerID = SDL_AddTimer (nextUpdate - currentUpdate, OnTimer, 0);
}
}
#endif
return active;
}
void SDLApplication::UpdateFrame () {
currentApplication->Update ();
}
void SDLApplication::UpdateFrame (void*) {
UpdateFrame ();
}
Application* CreateApplication () {
return new SDLApplication ();
}
}
#ifdef ANDROID
int SDL_main (int argc, char *argv[]) { return 0; }
#endif
|
#include "SDLApplication.h"
#include "SDLGamepad.h"
#ifdef HX_MACOS
#include <CoreFoundation/CoreFoundation.h>
#endif
#ifdef EMSCRIPTEN
#include "emscripten.h"
#endif
namespace lime {
AutoGCRoot* Application::callback = 0;
SDLApplication* SDLApplication::currentApplication = 0;
SDLApplication::SDLApplication () {
if (SDL_Init (SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_TIMER | SDL_INIT_JOYSTICK) != 0) {
printf ("Could not initialize SDL: %s.\n", SDL_GetError ());
}
currentApplication = this;
framePeriod = 1000.0 / 60.0;
#ifdef EMSCRIPTEN
emscripten_cancel_main_loop ();
emscripten_set_main_loop (UpdateFrame, 0, 0);
emscripten_set_main_loop_timing (EM_TIMING_RAF, 1);
#endif
currentUpdate = 0;
lastUpdate = 0;
nextUpdate = 0;
GamepadEvent gamepadEvent;
KeyEvent keyEvent;
MouseEvent mouseEvent;
RenderEvent renderEvent;
TextEvent textEvent;
TouchEvent touchEvent;
UpdateEvent updateEvent;
WindowEvent windowEvent;
#ifdef HX_MACOS
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL (CFBundleGetMainBundle ());
char path[PATH_MAX];
if (CFURLGetFileSystemRepresentation (resourcesURL, TRUE, (UInt8 *)path, PATH_MAX)) {
chdir (path);
}
CFRelease (resourcesURL);
#endif
}
SDLApplication::~SDLApplication () {
}
int SDLApplication::Exec () {
Init ();
#ifdef EMSCRIPTEN
return 0;
#else
while (active) {
Update ();
}
return Quit ();
#endif
}
void SDLApplication::HandleEvent (SDL_Event* event) {
switch (event->type) {
case SDL_USEREVENT:
currentUpdate = SDL_GetTicks ();
updateEvent.deltaTime = currentUpdate - lastUpdate;
lastUpdate = currentUpdate;
while (nextUpdate <= currentUpdate) {
nextUpdate += framePeriod;
}
UpdateEvent::Dispatch (&updateEvent);
RenderEvent::Dispatch (&renderEvent);
break;
case SDL_APP_WILLENTERBACKGROUND:
windowEvent.type = WINDOW_DEACTIVATE;
WindowEvent::Dispatch (&windowEvent);
break;
case SDL_APP_WILLENTERFOREGROUND:
windowEvent.type = WINDOW_ACTIVATE;
WindowEvent::Dispatch (&windowEvent);
break;
case SDL_CONTROLLERAXISMOTION:
case SDL_CONTROLLERBUTTONDOWN:
case SDL_CONTROLLERBUTTONUP:
case SDL_CONTROLLERDEVICEADDED:
case SDL_CONTROLLERDEVICEREMOVED:
ProcessGamepadEvent (event);
break;
case SDL_JOYAXISMOTION:
case SDL_JOYBALLMOTION:
case SDL_JOYBUTTONDOWN:
case SDL_JOYBUTTONUP:
case SDL_JOYHATMOTION:
case SDL_JOYDEVICEADDED:
case SDL_JOYDEVICEREMOVED:
//joy
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
ProcessKeyEvent (event);
break;
case SDL_MOUSEMOTION:
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
case SDL_MOUSEWHEEL:
ProcessMouseEvent (event);
break;
case SDL_TEXTINPUT:
case SDL_TEXTEDITING:
ProcessTextEvent (event);
break;
case SDL_WINDOWEVENT:
switch (event->window.event) {
case SDL_WINDOWEVENT_ENTER:
case SDL_WINDOWEVENT_LEAVE:
case SDL_WINDOWEVENT_SHOWN:
case SDL_WINDOWEVENT_HIDDEN:
case SDL_WINDOWEVENT_FOCUS_GAINED:
case SDL_WINDOWEVENT_FOCUS_LOST:
case SDL_WINDOWEVENT_MINIMIZED:
case SDL_WINDOWEVENT_MOVED:
case SDL_WINDOWEVENT_RESTORED:
ProcessWindowEvent (event);
break;
case SDL_WINDOWEVENT_EXPOSED:
RenderEvent::Dispatch (&renderEvent);
break;
case SDL_WINDOWEVENT_SIZE_CHANGED:
ProcessWindowEvent (event);
RenderEvent::Dispatch (&renderEvent);
break;
case SDL_WINDOWEVENT_CLOSE:
ProcessWindowEvent (event);
active = false;
break;
}
break;
case SDL_QUIT:
//quit
active = false;
break;
}
}
void SDLApplication::Init () {
active = true;
lastUpdate = SDL_GetTicks ();
nextUpdate = lastUpdate;
}
void SDLApplication::ProcessGamepadEvent (SDL_Event* event) {
if (GamepadEvent::callback) {
switch (event->type) {
case SDL_CONTROLLERAXISMOTION:
gamepadEvent.type = AXIS_MOVE;
gamepadEvent.axis = event->caxis.axis;
gamepadEvent.id = event->caxis.which;
gamepadEvent.axisValue = event->caxis.value / 32768.0;
GamepadEvent::Dispatch (&gamepadEvent);
break;
case SDL_CONTROLLERBUTTONDOWN:
gamepadEvent.type = BUTTON_DOWN;
gamepadEvent.button = event->cbutton.button;
gamepadEvent.id = event->cbutton.which;
GamepadEvent::Dispatch (&gamepadEvent);
break;
case SDL_CONTROLLERBUTTONUP:
gamepadEvent.type = BUTTON_UP;
gamepadEvent.button = event->cbutton.button;
gamepadEvent.id = event->cbutton.which;
GamepadEvent::Dispatch (&gamepadEvent);
break;
case SDL_CONTROLLERDEVICEADDED:
if (SDLGamepad::Connect (event->cdevice.which)) {
gamepadEvent.type = CONNECT;
gamepadEvent.id = SDLGamepad::GetInstanceID (event->cdevice.which);
GamepadEvent::Dispatch (&gamepadEvent);
}
break;
case SDL_CONTROLLERDEVICEREMOVED: {
gamepadEvent.type = DISCONNECT;
gamepadEvent.id = event->cdevice.which;
GamepadEvent::Dispatch (&gamepadEvent);
SDLGamepad::Disconnect (event->cdevice.which);
break;
}
}
}
}
void SDLApplication::ProcessKeyEvent (SDL_Event* event) {
if (KeyEvent::callback) {
switch (event->type) {
case SDL_KEYDOWN: keyEvent.type = KEY_DOWN; break;
case SDL_KEYUP: keyEvent.type = KEY_UP; break;
}
keyEvent.keyCode = event->key.keysym.sym;
keyEvent.modifier = event->key.keysym.mod;
KeyEvent::Dispatch (&keyEvent);
}
}
void SDLApplication::ProcessMouseEvent (SDL_Event* event) {
if (MouseEvent::callback) {
switch (event->type) {
case SDL_MOUSEMOTION:
mouseEvent.type = MOUSE_MOVE;
mouseEvent.x = event->motion.x;
mouseEvent.y = event->motion.y;
mouseEvent.movementX = event->motion.xrel;
mouseEvent.movementY = event->motion.yrel;
break;
case SDL_MOUSEBUTTONDOWN:
mouseEvent.type = MOUSE_DOWN;
mouseEvent.button = event->button.button - 1;
mouseEvent.x = event->button.x;
mouseEvent.y = event->button.y;
break;
case SDL_MOUSEBUTTONUP:
mouseEvent.type = MOUSE_UP;
mouseEvent.button = event->button.button - 1;
mouseEvent.x = event->button.x;
mouseEvent.y = event->button.y;
break;
case SDL_MOUSEWHEEL:
mouseEvent.type = MOUSE_WHEEL;
mouseEvent.x = event->wheel.x;
mouseEvent.y = event->wheel.y;
break;
}
MouseEvent::Dispatch (&mouseEvent);
}
}
void SDLApplication::ProcessTextEvent (SDL_Event* event) {
if (TextEvent::callback) {
switch (event->type) {
case SDL_TEXTINPUT:
textEvent.type = TEXT_INPUT;
break;
case SDL_TEXTEDITING:
textEvent.type = TEXT_EDIT;
textEvent.start = event->edit.start;
textEvent.length = event->edit.length;
break;
}
strcpy (textEvent.text, event->text.text);
TextEvent::Dispatch (&textEvent);
}
}
void SDLApplication::ProcessTouchEvent (SDL_Event* event) {
}
void SDLApplication::ProcessWindowEvent (SDL_Event* event) {
if (WindowEvent::callback) {
switch (event->window.event) {
case SDL_WINDOWEVENT_SHOWN: windowEvent.type = WINDOW_ACTIVATE; break;
case SDL_WINDOWEVENT_CLOSE: windowEvent.type = WINDOW_CLOSE; break;
case SDL_WINDOWEVENT_HIDDEN: windowEvent.type = WINDOW_DEACTIVATE; break;
case SDL_WINDOWEVENT_ENTER: windowEvent.type = WINDOW_ENTER; break;
case SDL_WINDOWEVENT_FOCUS_GAINED: windowEvent.type = WINDOW_FOCUS_IN; break;
case SDL_WINDOWEVENT_FOCUS_LOST: windowEvent.type = WINDOW_FOCUS_OUT; break;
case SDL_WINDOWEVENT_LEAVE: windowEvent.type = WINDOW_LEAVE; break;
case SDL_WINDOWEVENT_MINIMIZED: windowEvent.type = WINDOW_MINIMIZE; break;
case SDL_WINDOWEVENT_MOVED:
windowEvent.type = WINDOW_MOVE;
windowEvent.x = event->window.data1;
windowEvent.y = event->window.data2;
break;
case SDL_WINDOWEVENT_SIZE_CHANGED:
windowEvent.type = WINDOW_RESIZE;
windowEvent.width = event->window.data1;
windowEvent.height = event->window.data2;
break;
case SDL_WINDOWEVENT_RESTORED: windowEvent.type = WINDOW_RESTORE; break;
}
WindowEvent::Dispatch (&windowEvent);
}
}
int SDLApplication::Quit () {
windowEvent.type = WINDOW_DEACTIVATE;
WindowEvent::Dispatch (&windowEvent);
SDL_Quit ();
return 0;
}
void SDLApplication::RegisterWindow (SDLWindow *window) {
#ifdef IPHONE
SDL_iPhoneSetAnimationCallback (window->sdlWindow, 1, UpdateFrame, NULL);
#endif
}
void SDLApplication::SetFrameRate (double frameRate) {
if (frameRate > 0) {
framePeriod = 1000.0 / frameRate;
} else {
framePeriod = 1000.0;
}
}
static SDL_TimerID timerID = 0;
bool timerActive = false;
bool firstTime = true;
Uint32 OnTimer (Uint32 interval, void *) {
SDL_Event event;
SDL_UserEvent userevent;
userevent.type = SDL_USEREVENT;
userevent.code = 0;
userevent.data1 = NULL;
userevent.data2 = NULL;
event.type = SDL_USEREVENT;
event.user = userevent;
timerActive = false;
timerID = 0;
SDL_PushEvent (&event);
return 0;
}
bool SDLApplication::Update () {
SDL_Event event;
event.type = -1;
#if (!defined (IPHONE) && !defined (EMSCRIPTEN))
if (active && (firstTime || SDL_WaitEvent (&event))) {
firstTime = false;
HandleEvent (&event);
event.type = -1;
if (!active)
return active;
#endif
while (SDL_PollEvent (&event)) {
HandleEvent (&event);
event.type = -1;
if (!active)
return active;
}
currentUpdate = SDL_GetTicks ();
#if defined (IPHONE)
if (currentUpdate >= nextUpdate) {
event.type = SDL_USEREVENT;
HandleEvent (&event);
event.type = -1;
}
#elif defined (EMSCRIPTEN)
event.type = SDL_USEREVENT;
HandleEvent (&event);
event.type = -1;
#else
if (currentUpdate >= nextUpdate) {
SDL_RemoveTimer (timerID);
OnTimer (0, 0);
} else if (!timerActive) {
timerActive = true;
timerID = SDL_AddTimer (nextUpdate - currentUpdate, OnTimer, 0);
}
}
#endif
return active;
}
void SDLApplication::UpdateFrame () {
currentApplication->Update ();
}
void SDLApplication::UpdateFrame (void*) {
UpdateFrame ();
}
Application* CreateApplication () {
return new SDLApplication ();
}
}
#ifdef ANDROID
int SDL_main (int argc, char *argv[]) { return 0; }
#endif
|
Add joystick initialization to next path, which adds compatibility for PS4 controllers (and many others, most likely)
|
Add joystick initialization to next path, which adds compatibility for PS4 controllers (and many others, most likely)
|
C++
|
mit
|
openfl/lime,openfl/lime,MinoGames/lime,player-03/lime,openfl/lime,openfl/lime,fbricker/lime,madrazo/lime-1,MinoGames/lime,openfl/lime,MinoGames/lime,MinoGames/lime,madrazo/lime-1,player-03/lime,fbricker/lime,madrazo/lime-1,fbricker/lime,MinoGames/lime,madrazo/lime-1,player-03/lime,player-03/lime,MinoGames/lime,madrazo/lime-1,madrazo/lime-1,openfl/lime,openfl/lime,player-03/lime,fbricker/lime,MinoGames/lime,fbricker/lime,madrazo/lime-1,player-03/lime,fbricker/lime,fbricker/lime,player-03/lime
|
8218d03b3770cfd2b8cc40aa0edff2fc62f8ac09
|
project/src/backend/sdl/SDLRenderer.cpp
|
project/src/backend/sdl/SDLRenderer.cpp
|
#include "SDLWindow.h"
#include "SDLRenderer.h"
#include "../../graphics/opengl/OpenGL.h"
#include "../../graphics/opengl/OpenGLBindings.h"
namespace lime {
SDLRenderer::SDLRenderer (Window* window) {
currentWindow = window;
sdlWindow = ((SDLWindow*)window)->sdlWindow;
sdlTexture = 0;
context = 0;
width = 0;
height = 0;
int sdlFlags = 0;
if (window->flags & WINDOW_FLAG_HARDWARE) {
sdlFlags |= SDL_RENDERER_ACCELERATED;
if (window->flags & WINDOW_FLAG_VSYNC) {
sdlFlags |= SDL_RENDERER_PRESENTVSYNC;
}
} else {
sdlFlags |= SDL_RENDERER_SOFTWARE;
}
sdlRenderer = SDL_CreateRenderer (sdlWindow, -1, sdlFlags);
if (sdlFlags & SDL_RENDERER_ACCELERATED) {
if (sdlRenderer) {
bool valid = false;
context = SDL_GL_GetCurrentContext ();
if (context) {
OpenGLBindings::Init ();
#ifndef LIME_GLES
int version = 0;
glGetIntegerv (GL_MAJOR_VERSION, &version);
if (version == 0) {
float versionScan = 0;
sscanf ((const char*)glGetString (GL_VERSION), "%f", &versionScan);
version = versionScan;
}
if (version >= 2 || strstr ((const char*)glGetString (GL_VERSION), "OpenGL ES")) {
valid = true;
}
#else
valid = true;
#endif
}
if (!valid) {
SDL_DestroyRenderer (sdlRenderer);
sdlRenderer = 0;
}
}
if (!sdlRenderer) {
sdlFlags &= ~SDL_RENDERER_ACCELERATED;
sdlFlags &= ~SDL_RENDERER_PRESENTVSYNC;
sdlFlags |= SDL_RENDERER_SOFTWARE;
sdlRenderer = SDL_CreateRenderer (sdlWindow, -1, sdlFlags);
}
}
if (!sdlRenderer) {
printf ("Could not create SDL renderer: %s.\n", SDL_GetError ());
}
}
SDLRenderer::~SDLRenderer () {
if (sdlRenderer) {
SDL_DestroyRenderer (sdlRenderer);
}
}
void SDLRenderer::Flip () {
SDL_RenderPresent (sdlRenderer);
}
void* SDLRenderer::GetContext () {
return context;
}
double SDLRenderer::GetScale () {
int outputWidth;
int outputHeight;
SDL_GetRendererOutputSize (sdlRenderer, &outputWidth, &outputHeight);
int width;
int height;
SDL_GetWindowSize (sdlWindow, &width, &height);
double scale = outputWidth / width;
return scale;
}
value SDLRenderer::Lock () {
int width;
int height;
SDL_GetRendererOutputSize (sdlRenderer, &width, &height);
if (width != this->width || height != this->height) {
if (sdlTexture) {
SDL_DestroyTexture (sdlTexture);
}
sdlTexture = SDL_CreateTexture (sdlRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height);
}
value result = alloc_empty_object ();
void *pixels;
int pitch;
if (SDL_LockTexture (sdlTexture, NULL, &pixels, &pitch) == 0) {
alloc_field (result, val_id ("width"), alloc_int (width));
alloc_field (result, val_id ("height"), alloc_int (height));
alloc_field (result, val_id ("pixels"), alloc_float ((intptr_t)pixels));
alloc_field (result, val_id ("pitch"), alloc_int (pitch));
}
return result;
}
void SDLRenderer::MakeCurrent () {
if (sdlWindow && context) {
SDL_GL_MakeCurrent (sdlWindow, context);
}
}
void SDLRenderer::ReadPixels (ImageBuffer *buffer, Rectangle *rect) {
if (sdlRenderer) {
SDL_Rect bounds = { 0, 0, 0, 0 };
if (rect) {
bounds.x = rect->x;
bounds.y = rect->y;
bounds.w = rect->width;
bounds.h = rect->height;
} else {
SDL_GetWindowSize (sdlWindow, &bounds.w, &bounds.h);
}
buffer->Resize (bounds.w, bounds.h, 32);
SDL_RenderReadPixels (sdlRenderer, &bounds, SDL_PIXELFORMAT_ABGR8888, buffer->data->Data (), buffer->Stride ());
for (unsigned char *it=buffer->data->Data () + 3; it < (buffer->data->Data () + buffer->data->Length ()); it += 4) {
*it = 0xff;
}
}
}
const char* SDLRenderer::Type () {
if (sdlRenderer) {
SDL_RendererInfo info;
SDL_GetRendererInfo (sdlRenderer, &info);
if (info.flags & SDL_RENDERER_SOFTWARE) {
return "software";
} else {
return "opengl";
}
}
return "none";
}
void SDLRenderer::Unlock () {
if (sdlTexture) {
SDL_UnlockTexture (sdlTexture);
SDL_RenderClear (sdlRenderer);
SDL_RenderCopy (sdlRenderer, sdlTexture, NULL, NULL);
}
}
Renderer* CreateRenderer (Window* window) {
return new SDLRenderer (window);
}
}
|
#include "SDLWindow.h"
#include "SDLRenderer.h"
#include "../../graphics/opengl/OpenGL.h"
#include "../../graphics/opengl/OpenGLBindings.h"
namespace lime {
SDLRenderer::SDLRenderer (Window* window) {
currentWindow = window;
sdlWindow = ((SDLWindow*)window)->sdlWindow;
sdlTexture = 0;
context = 0;
width = 0;
height = 0;
int sdlFlags = 0;
if (window->flags & WINDOW_FLAG_HARDWARE) {
sdlFlags |= SDL_RENDERER_ACCELERATED;
if (window->flags & WINDOW_FLAG_VSYNC) {
sdlFlags |= SDL_RENDERER_PRESENTVSYNC;
}
} else {
sdlFlags |= SDL_RENDERER_SOFTWARE;
}
sdlRenderer = SDL_CreateRenderer (sdlWindow, -1, sdlFlags);
if (sdlFlags & SDL_RENDERER_ACCELERATED) {
if (sdlRenderer) {
bool valid = false;
context = SDL_GL_GetCurrentContext ();
if (context) {
OpenGLBindings::Init ();
#ifndef LIME_GLES
int version = 0;
glGetIntegerv (GL_MAJOR_VERSION, &version);
if (version == 0) {
float versionScan = 0;
sscanf ((const char*)glGetString (GL_VERSION), "%f", &versionScan);
version = versionScan;
}
if (version >= 2 || strstr ((const char*)glGetString (GL_VERSION), "OpenGL ES")) {
valid = true;
}
#else
valid = true;
#endif
}
if (!valid) {
SDL_DestroyRenderer (sdlRenderer);
sdlRenderer = 0;
}
}
if (!sdlRenderer) {
sdlFlags &= ~SDL_RENDERER_ACCELERATED;
sdlFlags &= ~SDL_RENDERER_PRESENTVSYNC;
sdlFlags |= SDL_RENDERER_SOFTWARE;
sdlRenderer = SDL_CreateRenderer (sdlWindow, -1, sdlFlags);
}
}
if (!sdlRenderer) {
printf ("Could not create SDL renderer: %s.\n", SDL_GetError ());
}
}
SDLRenderer::~SDLRenderer () {
if (sdlRenderer) {
SDL_DestroyRenderer (sdlRenderer);
}
}
void SDLRenderer::Flip () {
SDL_RenderPresent (sdlRenderer);
}
void* SDLRenderer::GetContext () {
return context;
}
double SDLRenderer::GetScale () {
int outputWidth;
int outputHeight;
SDL_GetRendererOutputSize (sdlRenderer, &outputWidth, &outputHeight);
int width;
int height;
SDL_GetWindowSize (sdlWindow, &width, &height);
double scale = double(outputWidth) / width;
return scale;
}
value SDLRenderer::Lock () {
int width;
int height;
SDL_GetRendererOutputSize (sdlRenderer, &width, &height);
if (width != this->width || height != this->height) {
if (sdlTexture) {
SDL_DestroyTexture (sdlTexture);
}
sdlTexture = SDL_CreateTexture (sdlRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height);
}
value result = alloc_empty_object ();
void *pixels;
int pitch;
if (SDL_LockTexture (sdlTexture, NULL, &pixels, &pitch) == 0) {
alloc_field (result, val_id ("width"), alloc_int (width));
alloc_field (result, val_id ("height"), alloc_int (height));
alloc_field (result, val_id ("pixels"), alloc_float ((intptr_t)pixels));
alloc_field (result, val_id ("pitch"), alloc_int (pitch));
}
return result;
}
void SDLRenderer::MakeCurrent () {
if (sdlWindow && context) {
SDL_GL_MakeCurrent (sdlWindow, context);
}
}
void SDLRenderer::ReadPixels (ImageBuffer *buffer, Rectangle *rect) {
if (sdlRenderer) {
SDL_Rect bounds = { 0, 0, 0, 0 };
if (rect) {
bounds.x = rect->x;
bounds.y = rect->y;
bounds.w = rect->width;
bounds.h = rect->height;
} else {
SDL_GetWindowSize (sdlWindow, &bounds.w, &bounds.h);
}
buffer->Resize (bounds.w, bounds.h, 32);
SDL_RenderReadPixels (sdlRenderer, &bounds, SDL_PIXELFORMAT_ABGR8888, buffer->data->Data (), buffer->Stride ());
for (unsigned char *it=buffer->data->Data () + 3; it < (buffer->data->Data () + buffer->data->Length ()); it += 4) {
*it = 0xff;
}
}
}
const char* SDLRenderer::Type () {
if (sdlRenderer) {
SDL_RendererInfo info;
SDL_GetRendererInfo (sdlRenderer, &info);
if (info.flags & SDL_RENDERER_SOFTWARE) {
return "software";
} else {
return "opengl";
}
}
return "none";
}
void SDLRenderer::Unlock () {
if (sdlTexture) {
SDL_UnlockTexture (sdlTexture);
SDL_RenderClear (sdlRenderer);
SDL_RenderCopy (sdlRenderer, sdlTexture, NULL, NULL);
}
}
Renderer* CreateRenderer (Window* window) {
return new SDLRenderer (window);
}
}
|
Fix SDL renderer scale calculation error
|
Fix SDL renderer scale calculation error
|
C++
|
mit
|
fbricker/lime,MinoGames/lime,madrazo/lime-1,player-03/lime,MinoGames/lime,MinoGames/lime,player-03/lime,MinoGames/lime,madrazo/lime-1,fbricker/lime,openfl/lime,openfl/lime,openfl/lime,fbricker/lime,player-03/lime,MinoGames/lime,player-03/lime,MinoGames/lime,openfl/lime,MinoGames/lime,player-03/lime,openfl/lime,madrazo/lime-1,openfl/lime,player-03/lime,madrazo/lime-1,madrazo/lime-1,fbricker/lime,madrazo/lime-1,madrazo/lime-1,openfl/lime,fbricker/lime,fbricker/lime,player-03/lime,fbricker/lime
|
f239b11a8413c4d7c08d917dff7fa636deaccdf7
|
dht/boot_strapper.cc
|
dht/boot_strapper.cc
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modified by ScyllaDB
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "dht/boot_strapper.hh"
#include "service/storage_service.hh"
#include "dht/range_streamer.hh"
#include "gms/failure_detector.hh"
#include "log.hh"
static logging::logger blogger("boot_strapper");
namespace dht {
future<> boot_strapper::bootstrap() {
blogger.debug("Beginning bootstrap process: sorted_tokens={}", _token_metadata.sorted_tokens());
auto streamer = make_lw_shared<range_streamer>(_db, _token_metadata, _tokens, _address, "Bootstrap");
streamer->add_source_filter(std::make_unique<range_streamer::failure_detector_source_filter>(gms::get_local_failure_detector()));
for (const auto& keyspace_name : _db.local().get_non_system_keyspaces()) {
auto& ks = _db.local().find_keyspace(keyspace_name);
auto& strategy = ks.get_replication_strategy();
dht::token_range_vector ranges = strategy.get_pending_address_ranges(_token_metadata, _tokens, _address);
blogger.debug("Will stream keyspace={}, ranges={}", keyspace_name, ranges);
streamer->add_ranges(keyspace_name, ranges);
}
return streamer->fetch_async().then_wrapped([streamer] (auto&& f) {
try {
auto state = f.get0();
} catch (...) {
throw std::runtime_error(sprint("Error during boostrap: %s", std::current_exception()));
}
service::get_local_storage_service().finish_bootstrapping();
return make_ready_future<>();
});
}
std::unordered_set<token> boot_strapper::get_bootstrap_tokens(token_metadata metadata, database& db) {
auto initial_tokens = db.get_initial_tokens();
// if user specified tokens, use those
if (initial_tokens.size() > 0) {
blogger.debug("tokens manually specified as {}", initial_tokens);
std::unordered_set<token> tokens;
for (auto& token_string : initial_tokens) {
auto token = dht::global_partitioner().from_sstring(token_string);
if (metadata.get_endpoint(token)) {
throw std::runtime_error(sprint("Bootstrapping to existing token %s is not allowed (decommission/removenode the old node first).", token_string));
}
tokens.insert(token);
}
blogger.debug("Get manually specified bootstrap_tokens={}", tokens);
return tokens;
}
size_t num_tokens = db.get_config().num_tokens();
if (num_tokens < 1) {
throw std::runtime_error("num_tokens must be >= 1");
}
if (num_tokens == 1) {
blogger.warn("Picking random token for a single vnode. You should probably add more vnodes; failing that, you should probably specify the token manually");
}
auto tokens = get_random_tokens(metadata, num_tokens);
blogger.debug("Get random bootstrap_tokens={}", tokens);
return tokens;
}
std::unordered_set<token> boot_strapper::get_random_tokens(token_metadata metadata, size_t num_tokens) {
std::unordered_set<token> tokens;
while (tokens.size() < num_tokens) {
auto token = global_partitioner().get_random_token();
auto ep = metadata.get_endpoint(token);
if (!ep) {
tokens.emplace(token);
}
}
return tokens;
}
} // namespace dht
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modified by ScyllaDB
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "dht/boot_strapper.hh"
#include "service/storage_service.hh"
#include "dht/range_streamer.hh"
#include "gms/failure_detector.hh"
#include "log.hh"
static logging::logger blogger("boot_strapper");
namespace dht {
future<> boot_strapper::bootstrap() {
blogger.debug("Beginning bootstrap process: sorted_tokens={}", _token_metadata.sorted_tokens());
auto streamer = make_lw_shared<range_streamer>(_db, _token_metadata, _tokens, _address, "Bootstrap");
streamer->add_source_filter(std::make_unique<range_streamer::failure_detector_source_filter>(gms::get_local_failure_detector()));
for (const auto& keyspace_name : _db.local().get_non_system_keyspaces()) {
auto& ks = _db.local().find_keyspace(keyspace_name);
auto& strategy = ks.get_replication_strategy();
dht::token_range_vector ranges = strategy.get_pending_address_ranges(_token_metadata, _tokens, _address);
blogger.debug("Will stream keyspace={}, ranges={}", keyspace_name, ranges);
streamer->add_ranges(keyspace_name, ranges);
}
return streamer->stream_async().then([streamer] () {
service::get_local_storage_service().finish_bootstrapping();
}).handle_exception([streamer] (std::exception_ptr eptr) {
blogger.warn("Eror during bootstrap: {}", eptr);
return make_exception_future<>(std::move(eptr));
});
}
std::unordered_set<token> boot_strapper::get_bootstrap_tokens(token_metadata metadata, database& db) {
auto initial_tokens = db.get_initial_tokens();
// if user specified tokens, use those
if (initial_tokens.size() > 0) {
blogger.debug("tokens manually specified as {}", initial_tokens);
std::unordered_set<token> tokens;
for (auto& token_string : initial_tokens) {
auto token = dht::global_partitioner().from_sstring(token_string);
if (metadata.get_endpoint(token)) {
throw std::runtime_error(sprint("Bootstrapping to existing token %s is not allowed (decommission/removenode the old node first).", token_string));
}
tokens.insert(token);
}
blogger.debug("Get manually specified bootstrap_tokens={}", tokens);
return tokens;
}
size_t num_tokens = db.get_config().num_tokens();
if (num_tokens < 1) {
throw std::runtime_error("num_tokens must be >= 1");
}
if (num_tokens == 1) {
blogger.warn("Picking random token for a single vnode. You should probably add more vnodes; failing that, you should probably specify the token manually");
}
auto tokens = get_random_tokens(metadata, num_tokens);
blogger.debug("Get random bootstrap_tokens={}", tokens);
return tokens;
}
std::unordered_set<token> boot_strapper::get_random_tokens(token_metadata metadata, size_t num_tokens) {
std::unordered_set<token> tokens;
while (tokens.size() < num_tokens) {
auto token = global_partitioner().get_random_token();
auto ep = metadata.get_endpoint(token);
if (!ep) {
tokens.emplace(token);
}
}
return tokens;
}
} // namespace dht
|
Use the new range_streamer interface for bootstrap
|
storage_service: Use the new range_streamer interface for bootstrap
So that bootstrap operation will now stream small ranges at a time and
restream the failed ranges.
|
C++
|
agpl-3.0
|
scylladb/scylla,scylladb/scylla,avikivity/scylla,duarten/scylla,duarten/scylla,avikivity/scylla,scylladb/scylla,scylladb/scylla,duarten/scylla,avikivity/scylla
|
8c9e48b77555a1cebb48eeea5d796ea570e11fb8
|
Utilities/kwsys/DynamicLoader.cxx
|
Utilities/kwsys/DynamicLoader.cxx
|
/*=========================================================================
Program: KWSys - Kitware System Library
Module: DynamicLoader.cxx
Copyright (c) Kitware, Inc., Insight Consortium. 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 notices for more information.
=========================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(DynamicLoader.hxx)
#include KWSYS_HEADER(Configure.hxx)
#ifdef __APPLE__
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1030
#include <string.h> // for strlen
#endif //MAC_OS_X_VERSION_MIN_REQUIRED < 1030
#endif // __APPLE__
#ifdef __hpux
#include <errno.h>
#endif //__hpux
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "DynamicLoader.hxx.in"
# include "Configure.hxx.in"
#endif
// This file is actually 3 different implementations.
// 1. HP machines which uses shl_load
// 2. Mac OS X 10.2.x and earlier which uses NSLinkModule
// 3. Windows which uses LoadLibrary
// 4. Most unix systems (including Mac OS X 10.3 and later) which use dlopen (default)
// Each part of the ifdef contains a complete implementation for
// the static methods of DynamicLoader.
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::DynamicLoader()
{
}
//----------------------------------------------------------------------------
DynamicLoader::~DynamicLoader()
{
}
}
// ---------------------------------------------------------------
// 1. Implementation for HPUX machines
#ifdef __hpux
#include <dl.h>
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
LibHandle DynamicLoader::OpenLibrary(const char* libname )
{
return shl_load(libname, BIND_DEFERRED | DYNAMIC_PATH, 0L);
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(LibHandle lib)
{
return !shl_unload(lib);
}
//----------------------------------------------------------------------------
DynamicLoaderFunction
DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym)
{
void* addr;
int status;
/* TYPE_PROCEDURE Look for a function or procedure.
* TYPE_DATA Look for a symbol in the data segment (for example, variables).
* TYPE_UNDEFINED Look for any symbol.
*/
status = shl_findsym (&lib, sym, TYPE_UNDEFINED, &addr);
void* result = (status < 0) ? (void*)0 : addr;
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoaderFunction*>(&result);
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibPrefix()
{
return "lib";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibExtension()
{
return ".sl";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
// TODO: Need implementation with errno/strerror
/* If successful, shl_findsym returns an integer (int) value zero. If
* shl_findsym cannot find sym, it returns -1 and sets errno to zero.
* If any other errors occur, shl_findsym returns -1 and sets errno to one
* of these values (defined in <errno.h>):
* ENOEXEC
* A format error was detected in the specified library.
* ENOSYM
* A symbol on which sym depends could not be found.
* EINVAL
* The specified handle is invalid.
*/
if( errno == ENOEXEC
|| errno == ENOSYM
|| errno == EINVAL )
{
return strerror(errno);
}
// else
return 0;
}
} // namespace KWSYS_NAMESPACE
#endif //__hpux
// ---------------------------------------------------------------
// 2. Implementation for Mac OS X 10.2.x and earlier
#ifdef __APPLE__
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1030
#include <mach-o/dyld.h>
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
LibHandle DynamicLoader::OpenLibrary(const char* libname )
{
NSObjectFileImageReturnCode rc;
NSObjectFileImage image = 0;
rc = NSCreateObjectFileImageFromFile(libname, &image);
// rc == NSObjectFileImageInappropriateFile when trying to load a dylib file
if( rc != NSObjectFileImageSuccess )
{
return 0;
}
return NSLinkModule(image, libname,
NSLINKMODULE_OPTION_PRIVATE|NSLINKMODULE_OPTION_BINDNOW);
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary( LibHandle lib)
{
bool success = NSUnLinkModule(lib, NSUNLINKMODULE_OPTION_NONE);
return success;
}
//----------------------------------------------------------------------------
DynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym)
{
void *result=0;
// Need to prepend symbols with '_' on Apple-gcc compilers
size_t len = strlen(sym);
char *rsym = new char[len + 1 + 1];
strcpy(rsym, "_");
strcat(rsym+1, sym);
NSSymbol symbol = NSLookupSymbolInModule(lib, rsym);
if(symbol)
{
result = NSAddressOfSymbol(symbol);
}
delete[] rsym;
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoaderFunction*>(&result);
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibPrefix()
{
return "lib";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibExtension()
{
// NSCreateObjectFileImageFromFile fail when dealing with dylib image
// it returns NSObjectFileImageInappropriateFile
//return ".dylib";
return ".so";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
return 0;
}
} // namespace KWSYS_NAMESPACE
#endif //MAC_OS_X_VERSION_MIN_REQUIRED < 1030
#endif // __APPLE__
// ---------------------------------------------------------------
// 3. Implementation for Windows win32 code
#ifdef _WIN32
#include <windows.h>
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
LibHandle DynamicLoader::OpenLibrary(const char* libname)
{
LibHandle lh;
#ifdef UNICODE
wchar_t libn[MB_CUR_MAX];
mbstowcs(libn, libname, MB_CUR_MAX);
lh = LoadLibrary(libn);
#else
lh = LoadLibrary(libname);
#endif
return lh;
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(LibHandle lib)
{
return (int)FreeLibrary(lib);
}
//----------------------------------------------------------------------------
DynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym)
{
void *result;
#ifdef __BORLANDC__
// Need to prepend symbols with '_' on borland compilers
size_t len = strlen(sym);
char *rsym = new char[len + 1 + 1];
strcpy(rsym, "_");
strcat(rsym+1, sym);
#else
const char *rsym = sym;
#endif
#ifdef UNICODE
wchar_t wsym[MB_CUR_MAX];
mbstowcs(wsym, rsym, MB_CUR_MAX);
result = GetProcAddress(lib, wsym);
#else
result = (void*)GetProcAddress(lib, rsym);
#endif
#ifdef __BORLANDC__
delete[] rsym;
#endif
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoaderFunction*>(&result);
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibPrefix()
{
#ifdef __MINGW32__
return "lib";
#else
return "";
#endif
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibExtension()
{
return ".dll";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
static char* str = 0;
delete [] str;
str = strcpy(new char[strlen((char*)lpMsgBuf)+1], (char*)lpMsgBuf);
// Free the buffer.
LocalFree( lpMsgBuf );
return str;
}
} // namespace KWSYS_NAMESPACE
#endif //_WIN32
// ---------------------------------------------------------------
// 4. Implementation for default UNIX machines.
// if nothing has been defined then use this
#ifndef DYNAMICLOADER_DEFINED
#define DYNAMICLOADER_DEFINED 1
// Setup for most unix machines
#include <dlfcn.h>
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
LibHandle DynamicLoader::OpenLibrary(const char* libname )
{
return dlopen(libname, RTLD_LAZY);
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(LibHandle lib)
{
if (lib)
{
// The function dlclose() returns 0 on success, and non-zero on error.
return !dlclose(lib);
}
// else
return 0;
}
//----------------------------------------------------------------------------
DynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym)
{
void* result = dlsym(lib, sym);
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoaderFunction*>(&result);
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibPrefix()
{
return "lib";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibExtension()
{
#ifdef __CYGWIN__
return ".dll";
#else
return ".so";
#endif
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
return dlerror();
}
} // namespace KWSYS_NAMESPACE
#endif
|
/*=========================================================================
Program: KWSys - Kitware System Library
Module: DynamicLoader.cxx
Copyright (c) Kitware, Inc., Insight Consortium. 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 notices for more information.
=========================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(DynamicLoader.hxx)
#include KWSYS_HEADER(Configure.hxx)
#ifdef __APPLE__
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1030
#include <string.h> // for strlen
#endif //MAC_OS_X_VERSION_MIN_REQUIRED < 1030
#endif // __APPLE__
#ifdef __hpux
#include <errno.h>
#endif //__hpux
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "DynamicLoader.hxx.in"
# include "Configure.hxx.in"
#endif
// This file is actually 3 different implementations.
// 1. HP machines which uses shl_load
// 2. Mac OS X 10.2.x and earlier which uses NSLinkModule
// 3. Windows which uses LoadLibrary
// 4. Most unix systems (including Mac OS X 10.3 and later) which use dlopen (default)
// Each part of the ifdef contains a complete implementation for
// the static methods of DynamicLoader.
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::DynamicLoader()
{
}
//----------------------------------------------------------------------------
DynamicLoader::~DynamicLoader()
{
}
}
// ---------------------------------------------------------------
// 1. Implementation for HPUX machines
#ifdef __hpux
#include <dl.h>
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
LibHandle DynamicLoader::OpenLibrary(const char* libname )
{
return shl_load(libname, BIND_DEFERRED | DYNAMIC_PATH, 0L);
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(LibHandle lib)
{
return !shl_unload(lib);
}
//----------------------------------------------------------------------------
DynamicLoaderFunction
DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym)
{
void* addr;
int status;
/* TYPE_PROCEDURE Look for a function or procedure.
* TYPE_DATA Look for a symbol in the data segment (for example, variables).
* TYPE_UNDEFINED Look for any symbol.
*/
status = shl_findsym (&lib, sym, TYPE_UNDEFINED, &addr);
void* result = (status < 0) ? (void*)0 : addr;
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoaderFunction*>(&result);
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibPrefix()
{
return "lib";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibExtension()
{
return ".sl";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
// TODO: Need implementation with errno/strerror
/* If successful, shl_findsym returns an integer (int) value zero. If
* shl_findsym cannot find sym, it returns -1 and sets errno to zero.
* If any other errors occur, shl_findsym returns -1 and sets errno to one
* of these values (defined in <errno.h>):
* ENOEXEC
* A format error was detected in the specified library.
* ENOSYM
* A symbol on which sym depends could not be found.
* EINVAL
* The specified handle is invalid.
*/
if( errno == ENOEXEC
|| errno == ENOSYM
|| errno == EINVAL )
{
return strerror(errno);
}
// else
return 0;
}
} // namespace KWSYS_NAMESPACE
#endif //__hpux
// ---------------------------------------------------------------
// 2. Implementation for Mac OS X 10.2.x and earlier
#ifdef __APPLE__
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1030
#include <mach-o/dyld.h>
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
LibHandle DynamicLoader::OpenLibrary(const char* libname )
{
NSObjectFileImageReturnCode rc;
NSObjectFileImage image = 0;
rc = NSCreateObjectFileImageFromFile(libname, &image);
// rc == NSObjectFileImageInappropriateFile when trying to load a dylib file
if( rc != NSObjectFileImageSuccess )
{
return 0;
}
return NSLinkModule(image, libname,
NSLINKMODULE_OPTION_PRIVATE|NSLINKMODULE_OPTION_BINDNOW);
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary( LibHandle lib)
{
// Initially this function was written using NSUNLINKMODULE_OPTION_NONE, but when
// the code is compiled with coverage on, one cannot close the library properly
// so instead of not unloading the library. We use a special option:
// NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED
// With this option the memory for the module is not deallocated
// allowing pointers into the module to still be valid.
bool success = NSUnLinkModule(lib, NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED);
return success;
}
//----------------------------------------------------------------------------
DynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym)
{
void *result=0;
// Need to prepend symbols with '_' on Apple-gcc compilers
size_t len = strlen(sym);
char *rsym = new char[len + 1 + 1];
strcpy(rsym, "_");
strcat(rsym+1, sym);
NSSymbol symbol = NSLookupSymbolInModule(lib, rsym);
if(symbol)
{
result = NSAddressOfSymbol(symbol);
}
delete[] rsym;
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoaderFunction*>(&result);
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibPrefix()
{
return "lib";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibExtension()
{
// NSCreateObjectFileImageFromFile fail when dealing with dylib image
// it returns NSObjectFileImageInappropriateFile
//return ".dylib";
return ".so";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
return 0;
}
} // namespace KWSYS_NAMESPACE
#endif //MAC_OS_X_VERSION_MIN_REQUIRED < 1030
#endif // __APPLE__
// ---------------------------------------------------------------
// 3. Implementation for Windows win32 code
#ifdef _WIN32
#include <windows.h>
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
LibHandle DynamicLoader::OpenLibrary(const char* libname)
{
LibHandle lh;
#ifdef UNICODE
wchar_t libn[MB_CUR_MAX];
mbstowcs(libn, libname, MB_CUR_MAX);
lh = LoadLibrary(libn);
#else
lh = LoadLibrary(libname);
#endif
return lh;
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(LibHandle lib)
{
return (int)FreeLibrary(lib);
}
//----------------------------------------------------------------------------
DynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym)
{
void *result;
#ifdef __BORLANDC__
// Need to prepend symbols with '_' on borland compilers
size_t len = strlen(sym);
char *rsym = new char[len + 1 + 1];
strcpy(rsym, "_");
strcat(rsym+1, sym);
#else
const char *rsym = sym;
#endif
#ifdef UNICODE
wchar_t wsym[MB_CUR_MAX];
mbstowcs(wsym, rsym, MB_CUR_MAX);
result = GetProcAddress(lib, wsym);
#else
result = (void*)GetProcAddress(lib, rsym);
#endif
#ifdef __BORLANDC__
delete[] rsym;
#endif
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoaderFunction*>(&result);
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibPrefix()
{
#ifdef __MINGW32__
return "lib";
#else
return "";
#endif
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibExtension()
{
return ".dll";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
static char* str = 0;
delete [] str;
str = strcpy(new char[strlen((char*)lpMsgBuf)+1], (char*)lpMsgBuf);
// Free the buffer.
LocalFree( lpMsgBuf );
return str;
}
} // namespace KWSYS_NAMESPACE
#endif //_WIN32
// ---------------------------------------------------------------
// 4. Implementation for default UNIX machines.
// if nothing has been defined then use this
#ifndef DYNAMICLOADER_DEFINED
#define DYNAMICLOADER_DEFINED 1
// Setup for most unix machines
#include <dlfcn.h>
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
LibHandle DynamicLoader::OpenLibrary(const char* libname )
{
return dlopen(libname, RTLD_LAZY);
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(LibHandle lib)
{
if (lib)
{
// The function dlclose() returns 0 on success, and non-zero on error.
return !dlclose(lib);
}
// else
return 0;
}
//----------------------------------------------------------------------------
DynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym)
{
void* result = dlsym(lib, sym);
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoaderFunction*>(&result);
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibPrefix()
{
return "lib";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibExtension()
{
#ifdef __CYGWIN__
return ".dll";
#else
return ".so";
#endif
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
return dlerror();
}
} // namespace KWSYS_NAMESPACE
#endif
|
Fix dashboard with coverage
|
ENH: Fix dashboard with coverage
|
C++
|
apache-2.0
|
CapeDrew/DCMTK-ITK,rhgong/itk-with-dom,daviddoria/itkHoughTransform,itkvideo/ITK,BRAINSia/ITK,fedral/ITK,cpatrick/ITK-RemoteIO,biotrump/ITK,thewtex/ITK,BRAINSia/ITK,itkvideo/ITK,heimdali/ITK,hendradarwin/ITK,jcfr/ITK,thewtex/ITK,richardbeare/ITK,hendradarwin/ITK,richardbeare/ITK,jmerkow/ITK,zachary-williamson/ITK,LucasGandel/ITK,msmolens/ITK,blowekamp/ITK,heimdali/ITK,biotrump/ITK,atsnyder/ITK,Kitware/ITK,Kitware/ITK,vfonov/ITK,CapeDrew/DCMTK-ITK,paulnovo/ITK,LucHermitte/ITK,wkjeong/ITK,heimdali/ITK,BlueBrain/ITK,ajjl/ITK,PlutoniumHeart/ITK,jcfr/ITK,InsightSoftwareConsortium/ITK,vfonov/ITK,CapeDrew/DITK,ajjl/ITK,heimdali/ITK,thewtex/ITK,LucasGandel/ITK,malaterre/ITK,CapeDrew/DITK,BlueBrain/ITK,wkjeong/ITK,fuentesdt/InsightToolkit-dev,ajjl/ITK,eile/ITK,eile/ITK,jmerkow/ITK,GEHC-Surgery/ITK,richardbeare/ITK,ajjl/ITK,Kitware/ITK,stnava/ITK,fuentesdt/InsightToolkit-dev,blowekamp/ITK,rhgong/itk-with-dom,PlutoniumHeart/ITK,itkvideo/ITK,heimdali/ITK,daviddoria/itkHoughTransform,GEHC-Surgery/ITK,paulnovo/ITK,daviddoria/itkHoughTransform,jcfr/ITK,InsightSoftwareConsortium/ITK,fbudin69500/ITK,wkjeong/ITK,CapeDrew/DITK,itkvideo/ITK,eile/ITK,msmolens/ITK,fedral/ITK,biotrump/ITK,malaterre/ITK,vfonov/ITK,Kitware/ITK,hjmjohnson/ITK,fuentesdt/InsightToolkit-dev,hinerm/ITK,richardbeare/ITK,ajjl/ITK,spinicist/ITK,BlueBrain/ITK,jmerkow/ITK,fedral/ITK,fuentesdt/InsightToolkit-dev,fedral/ITK,blowekamp/ITK,msmolens/ITK,malaterre/ITK,zachary-williamson/ITK,PlutoniumHeart/ITK,spinicist/ITK,hinerm/ITK,BlueBrain/ITK,jcfr/ITK,LucasGandel/ITK,InsightSoftwareConsortium/ITK,atsnyder/ITK,wkjeong/ITK,LucHermitte/ITK,jmerkow/ITK,wkjeong/ITK,jcfr/ITK,rhgong/itk-with-dom,thewtex/ITK,LucasGandel/ITK,cpatrick/ITK-RemoteIO,hendradarwin/ITK,LucasGandel/ITK,cpatrick/ITK-RemoteIO,hinerm/ITK,GEHC-Surgery/ITK,spinicist/ITK,BlueBrain/ITK,eile/ITK,cpatrick/ITK-RemoteIO,GEHC-Surgery/ITK,wkjeong/ITK,LucasGandel/ITK,GEHC-Surgery/ITK,Kitware/ITK,jmerkow/ITK,atsnyder/ITK,fbudin69500/ITK,PlutoniumHeart/ITK,LucHermitte/ITK,LucHermitte/ITK,stnava/ITK,CapeDrew/DCMTK-ITK,stnava/ITK,jmerkow/ITK,malaterre/ITK,BlueBrain/ITK,fedral/ITK,vfonov/ITK,hinerm/ITK,eile/ITK,ajjl/ITK,InsightSoftwareConsortium/ITK,fbudin69500/ITK,hinerm/ITK,zachary-williamson/ITK,fbudin69500/ITK,InsightSoftwareConsortium/ITK,stnava/ITK,stnava/ITK,vfonov/ITK,rhgong/itk-with-dom,GEHC-Surgery/ITK,CapeDrew/DITK,paulnovo/ITK,hendradarwin/ITK,PlutoniumHeart/ITK,zachary-williamson/ITK,zachary-williamson/ITK,heimdali/ITK,fuentesdt/InsightToolkit-dev,daviddoria/itkHoughTransform,msmolens/ITK,hendradarwin/ITK,richardbeare/ITK,malaterre/ITK,cpatrick/ITK-RemoteIO,spinicist/ITK,fbudin69500/ITK,wkjeong/ITK,eile/ITK,jmerkow/ITK,BlueBrain/ITK,fedral/ITK,ajjl/ITK,msmolens/ITK,cpatrick/ITK-RemoteIO,spinicist/ITK,vfonov/ITK,spinicist/ITK,hjmjohnson/ITK,fedral/ITK,eile/ITK,richardbeare/ITK,blowekamp/ITK,biotrump/ITK,fbudin69500/ITK,CapeDrew/DITK,biotrump/ITK,biotrump/ITK,rhgong/itk-with-dom,cpatrick/ITK-RemoteIO,LucasGandel/ITK,hjmjohnson/ITK,daviddoria/itkHoughTransform,itkvideo/ITK,CapeDrew/DCMTK-ITK,itkvideo/ITK,eile/ITK,vfonov/ITK,rhgong/itk-with-dom,CapeDrew/DITK,heimdali/ITK,hinerm/ITK,hinerm/ITK,hjmjohnson/ITK,CapeDrew/DITK,blowekamp/ITK,hjmjohnson/ITK,stnava/ITK,paulnovo/ITK,PlutoniumHeart/ITK,hendradarwin/ITK,CapeDrew/DCMTK-ITK,PlutoniumHeart/ITK,daviddoria/itkHoughTransform,hjmjohnson/ITK,stnava/ITK,daviddoria/itkHoughTransform,atsnyder/ITK,biotrump/ITK,spinicist/ITK,fedral/ITK,richardbeare/ITK,cpatrick/ITK-RemoteIO,fuentesdt/InsightToolkit-dev,daviddoria/itkHoughTransform,malaterre/ITK,zachary-williamson/ITK,heimdali/ITK,paulnovo/ITK,BRAINSia/ITK,jcfr/ITK,LucHermitte/ITK,atsnyder/ITK,itkvideo/ITK,spinicist/ITK,paulnovo/ITK,GEHC-Surgery/ITK,InsightSoftwareConsortium/ITK,msmolens/ITK,thewtex/ITK,blowekamp/ITK,fbudin69500/ITK,InsightSoftwareConsortium/ITK,fuentesdt/InsightToolkit-dev,vfonov/ITK,thewtex/ITK,malaterre/ITK,thewtex/ITK,msmolens/ITK,rhgong/itk-with-dom,CapeDrew/DITK,Kitware/ITK,blowekamp/ITK,daviddoria/itkHoughTransform,CapeDrew/DCMTK-ITK,rhgong/itk-with-dom,jcfr/ITK,paulnovo/ITK,zachary-williamson/ITK,fuentesdt/InsightToolkit-dev,LucHermitte/ITK,wkjeong/ITK,BRAINSia/ITK,BRAINSia/ITK,biotrump/ITK,BRAINSia/ITK,jcfr/ITK,hendradarwin/ITK,atsnyder/ITK,CapeDrew/DCMTK-ITK,hjmjohnson/ITK,atsnyder/ITK,msmolens/ITK,fbudin69500/ITK,CapeDrew/DITK,Kitware/ITK,CapeDrew/DCMTK-ITK,stnava/ITK,LucHermitte/ITK,ajjl/ITK,spinicist/ITK,vfonov/ITK,LucHermitte/ITK,atsnyder/ITK,malaterre/ITK,paulnovo/ITK,zachary-williamson/ITK,fuentesdt/InsightToolkit-dev,itkvideo/ITK,zachary-williamson/ITK,BlueBrain/ITK,LucasGandel/ITK,jmerkow/ITK,BRAINSia/ITK,malaterre/ITK,GEHC-Surgery/ITK,itkvideo/ITK,blowekamp/ITK,eile/ITK,PlutoniumHeart/ITK,hinerm/ITK,stnava/ITK,atsnyder/ITK,hendradarwin/ITK,hinerm/ITK,CapeDrew/DCMTK-ITK
|
ffdb17a1cbfddb604cf2ee2ef16b7ff32fe9c28e
|
core/src/oned/ODCode93Reader.cpp
|
core/src/oned/ODCode93Reader.cpp
|
/*
* Copyright 2016 Nu-book Inc.
* Copyright 2016 ZXing authors
*
* 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 "oned/ODCode93Reader.h"
#include "Result.h"
#include "BitArray.h"
#include "ZXNumeric.h"
#include "TextDecoder.h"
#include "ZXContainerAlgorithms.h"
#include <array>
namespace ZXing {
namespace OneD {
// Note that 'abcd' are dummy characters in place of control characters.
static const char ALPHABET_STRING[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*";
//static final char[] ALPHABET = ALPHABET_STRING.toCharArray();
/**
* These represent the encodings of characters, as patterns of wide and narrow bars.
* The 9 least-significant bits of each int correspond to the pattern of wide and narrow.
*/
static const int CHARACTER_ENCODINGS[] = {
0x114, 0x148, 0x144, 0x142, 0x128, 0x124, 0x122, 0x150, 0x112, 0x10A, // 0-9
0x1A8, 0x1A4, 0x1A2, 0x194, 0x192, 0x18A, 0x168, 0x164, 0x162, 0x134, // A-J
0x11A, 0x158, 0x14C, 0x146, 0x12C, 0x116, 0x1B4, 0x1B2, 0x1AC, 0x1A6, // K-T
0x196, 0x19A, 0x16C, 0x166, 0x136, 0x13A, // U-Z
0x12E, 0x1D4, 0x1D2, 0x1CA, 0x16E, 0x176, 0x1AE, // - - %
0x126, 0x1DA, 0x1D6, 0x132, 0x15E, // Control chars? $-*
};
static_assert(Length(ALPHABET_STRING) - 1 == Length(CHARACTER_ENCODINGS), "table size mismatch");
static const int ASTERISK_ENCODING = CHARACTER_ENCODINGS[47];
typedef std::array<int, 6> CounterContainer;
static int ToPattern(const CounterContainer& counters)
{
int max = static_cast<int>(counters.size());
int sum = Accumulate(counters, 0);
int pattern = 0;
for (int i = 0; i < max; i++) {
int scaled = RoundToNearest(counters[i] * 9.0f / sum);
if (scaled < 1 || scaled > 4) {
return -1;
}
if ((i & 0x01) == 0) {
for (int j = 0; j < scaled; j++) {
pattern = (pattern << 1) | 0x01;
}
}
else {
pattern <<= scaled;
}
}
return pattern;
}
static BitArray::Range
FindAsteriskPattern(const BitArray& row)
{
CounterContainer counters;
return RowReader::FindPattern(
row.getNextSet(row.begin()), row.end(), counters,
[](BitArray::Iterator begin, BitArray::Iterator end, const CounterContainer& counters) {
return ToPattern(counters) == ASTERISK_ENCODING;
});
}
static char
PatternToChar(int pattern)
{
for (int i = 0; i < Length(CHARACTER_ENCODINGS); i++) {
if (CHARACTER_ENCODINGS[i] == pattern) {
return ALPHABET_STRING[i];
}
}
return 0;
}
static DecodeStatus
DecodeExtended(const std::string& encoded, std::string& decoded)
{
size_t length = encoded.length();
decoded.reserve(length);
for (size_t i = 0; i < length; i++) {
char c = encoded[i];
if (c >= 'a' && c <= 'd') {
if (i+1 >= length) {
return DecodeStatus::FormatError;
}
char next = encoded[i + 1];
char decodedChar = '\0';
switch (c) {
case 'd':
// +A to +Z map to a to z
if (next >= 'A' && next <= 'Z') {
decodedChar = (char)(next + 32);
}
else {
return DecodeStatus::FormatError;
}
break;
case 'a':
// $A to $Z map to control codes SH to SB
if (next >= 'A' && next <= 'Z') {
decodedChar = (char)(next - 64);
}
else {
return DecodeStatus::FormatError;
}
break;
case 'b':
if (next >= 'A' && next <= 'E') {
// %A to %E map to control codes ESC to USep
decodedChar = (char)(next - 38);
}
else if (next >= 'F' && next <= 'J') {
// %F to %J map to ; < = > ?
decodedChar = (char)(next - 11);
}
else if (next >= 'K' && next <= 'O') {
// %K to %O map to [ \ ] ^ _
decodedChar = (char)(next + 16);
}
else if (next >= 'P' && next <= 'S') {
// %P to %S map to { | } ~
decodedChar = (char)(next + 43);
}
else if (next >= 'T' && next <= 'Z') {
// %T to %Z all map to DEL (127)
decodedChar = 127;
}
else {
return DecodeStatus::FormatError;
}
break;
case 'c':
// /A to /O map to ! to , and /Z maps to :
if (next >= 'A' && next <= 'O') {
decodedChar = (char)(next - 32);
}
else if (next == 'Z') {
decodedChar = ':';
}
else {
return DecodeStatus::FormatError;
}
break;
}
decoded += decodedChar;
// bump up i again since we read two characters
i++;
}
else {
decoded += c;
}
}
return DecodeStatus::NoError;
}
static int IndexOf(const char* str, char c)
{
auto s = strchr(str, c);
return s != nullptr ? static_cast<int>(s - str) : -1;
}
bool
CheckOneChecksum(const std::string& result, int checkPosition, int weightMax)
{
int weight = 1;
int total = 0;
for (int i = checkPosition - 1; i >= 0; i--) {
total += weight * IndexOf(ALPHABET_STRING, result[i]);
if (++weight > weightMax) {
weight = 1;
}
}
if (total < 0 || result[checkPosition] != ALPHABET_STRING[total % 47]) {
return false;
}
return true;
}
static DecodeStatus
CheckChecksums(const std::string& result)
{
int length = static_cast<int>(result.length());
if (CheckOneChecksum(result, length - 2, 20) && CheckOneChecksum(result, length - 1, 15)) {
return DecodeStatus::NoError;
}
return DecodeStatus::ChecksumError;
}
Result
Code93Reader::decodeRow(int rowNumber, const BitArray& row, std::unique_ptr<DecodingState>& state) const
{
auto range = FindAsteriskPattern(row);
if (!range)
return Result(DecodeStatus::NotFound);
float left = (range.begin - row.begin()) + 0.5f * range.size();
CounterContainer theCounters = {};
std::string result;
result.reserve(20);
do {
// Read off white space
range = RecordPattern(row.getNextSet(range.end), row.end(), theCounters);
if (!range)
return Result(DecodeStatus::NotFound);
int pattern = ToPattern(theCounters);
if (pattern < 0) {
return Result(DecodeStatus::NotFound);
}
char decodedChar = PatternToChar(pattern);
if (decodedChar == 0) {
return Result(DecodeStatus::NotFound);
}
result.push_back(decodedChar);
} while (result.back() != '*');
result.pop_back(); // remove asterisk
// Should be at least one more black module
if (range.end == row.end() || !*range.end) {
return Result(DecodeStatus::NotFound);
}
if (result.length() < 2) {
// false positive -- need at least 2 checksum digits
return Result(DecodeStatus::NotFound);
}
auto status = CheckChecksums(result);
if (StatusIsError(status)) {
return Result(status);
}
// Remove checksum digits
result.resize(result.length() - 2);
std::string resultString;
status = DecodeExtended(result, resultString);
if (StatusIsError(status)) {
return Result(status);
}
float right = (range.begin - row.begin()) + 0.5f * range.size();
float ypos = static_cast<float>(rowNumber);
return Result(TextDecoder::FromLatin1(resultString), ByteArray(), { ResultPoint(left, ypos), ResultPoint(right, ypos) }, BarcodeFormat::CODE_93);
}
} // OneD
} // ZXing
|
/*
* Copyright 2016 Nu-book Inc.
* Copyright 2016 ZXing authors
*
* 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 "oned/ODCode93Reader.h"
#include "Result.h"
#include "BitArray.h"
#include "ZXNumeric.h"
#include "TextDecoder.h"
#include "ZXContainerAlgorithms.h"
#include <array>
namespace ZXing {
namespace OneD {
// Note that 'abcd' are dummy characters in place of control characters.
static const char ALPHABET_STRING[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*";
//static final char[] ALPHABET = ALPHABET_STRING.toCharArray();
/**
* These represent the encodings of characters, as patterns of wide and narrow bars.
* The 9 least-significant bits of each int correspond to the pattern of wide and narrow.
*/
static const int CHARACTER_ENCODINGS[] = {
0x114, 0x148, 0x144, 0x142, 0x128, 0x124, 0x122, 0x150, 0x112, 0x10A, // 0-9
0x1A8, 0x1A4, 0x1A2, 0x194, 0x192, 0x18A, 0x168, 0x164, 0x162, 0x134, // A-J
0x11A, 0x158, 0x14C, 0x146, 0x12C, 0x116, 0x1B4, 0x1B2, 0x1AC, 0x1A6, // K-T
0x196, 0x19A, 0x16C, 0x166, 0x136, 0x13A, // U-Z
0x12E, 0x1D4, 0x1D2, 0x1CA, 0x16E, 0x176, 0x1AE, // - - %
0x126, 0x1DA, 0x1D6, 0x132, 0x15E, // Control chars? $-*
};
static_assert(Length(ALPHABET_STRING) - 1 == Length(CHARACTER_ENCODINGS), "table size mismatch");
static const int ASTERISK_ENCODING = CHARACTER_ENCODINGS[47];
typedef std::array<int, 6> CounterContainer;
static int ToPattern(const CounterContainer& counters)
{
int max = static_cast<int>(counters.size());
int sum = Accumulate(counters, 0);
int pattern = 0;
for (int i = 0; i < max; i++) {
int scaled = RoundToNearest(counters[i] * 9.0f / sum);
if (scaled < 1 || scaled > 4) {
return -1;
}
if ((i & 0x01) == 0) {
for (int j = 0; j < scaled; j++) {
pattern = (pattern << 1) | 0x01;
}
}
else {
pattern <<= scaled;
}
}
return pattern;
}
static BitArray::Range
FindAsteriskPattern(const BitArray& row)
{
CounterContainer counters;
return RowReader::FindPattern(
row.getNextSet(row.begin()), row.end(), counters,
[](BitArray::Iterator begin, BitArray::Iterator end, const CounterContainer& counters) {
return ToPattern(counters) == ASTERISK_ENCODING;
});
}
static char
PatternToChar(int pattern)
{
for (int i = 0; i < Length(CHARACTER_ENCODINGS); i++) {
if (CHARACTER_ENCODINGS[i] == pattern) {
return ALPHABET_STRING[i];
}
}
return 0;
}
static DecodeStatus
DecodeExtended(const std::string& encoded, std::string& decoded)
{
size_t length = encoded.length();
decoded.reserve(length);
for (size_t i = 0; i < length; i++) {
char c = encoded[i];
if (c >= 'a' && c <= 'd') {
if (i+1 >= length) {
return DecodeStatus::FormatError;
}
char next = encoded[i + 1];
char decodedChar = '\0';
switch (c) {
case 'd':
// +A to +Z map to a to z
if (next >= 'A' && next <= 'Z') {
decodedChar = (char)(next + 32);
}
else {
return DecodeStatus::FormatError;
}
break;
case 'a':
// $A to $Z map to control codes SH to SB
if (next >= 'A' && next <= 'Z') {
decodedChar = (char)(next - 64);
}
else {
return DecodeStatus::FormatError;
}
break;
case 'b':
if (next >= 'A' && next <= 'E') {
// %A to %E map to control codes ESC to USep
decodedChar = (char)(next - 38);
}
else if (next >= 'F' && next <= 'J') {
// %F to %J map to ; < = > ?
decodedChar = (char)(next - 11);
}
else if (next >= 'K' && next <= 'O') {
// %K to %O map to [ \ ] ^ _
decodedChar = (char)(next + 16);
}
else if (next >= 'P' && next <= 'S') {
// %P to %S map to { | } ~
decodedChar = (char)(next + 43);
}
else if (next >= 'T' && next <= 'Z') {
// %T to %Z all map to DEL (127)
decodedChar = 127;
}
else {
return DecodeStatus::FormatError;
}
break;
case 'c':
// /A to /O map to ! to , and /Z maps to :
if (next >= 'A' && next <= 'O') {
decodedChar = (char)(next - 32);
}
else if (next == 'Z') {
decodedChar = ':';
}
else {
return DecodeStatus::FormatError;
}
break;
}
decoded += decodedChar;
// bump up i again since we read two characters
i++;
}
else {
decoded += c;
}
}
return DecodeStatus::NoError;
}
static int IndexOf(const char* str, char c)
{
auto s = strchr(str, c);
return s != nullptr ? static_cast<int>(s - str) : -1;
}
bool
CheckOneChecksum(const std::string& result, int checkPosition, int weightMax)
{
int weight = 1;
int total = 0;
for (int i = checkPosition - 1; i >= 0; i--) {
total += weight * IndexOf(ALPHABET_STRING, result[i]);
if (++weight > weightMax) {
weight = 1;
}
}
if (total < 0 || result[checkPosition] != ALPHABET_STRING[total % 47]) {
return false;
}
return true;
}
static DecodeStatus
CheckChecksums(const std::string& result)
{
int length = static_cast<int>(result.length());
if (CheckOneChecksum(result, length - 2, 20) && CheckOneChecksum(result, length - 1, 15)) {
return DecodeStatus::NoError;
}
return DecodeStatus::ChecksumError;
}
Result
Code93Reader::decodeRow(int rowNumber, const BitArray& row, std::unique_ptr<DecodingState>& state) const
{
auto range = FindAsteriskPattern(row);
if (!range)
return Result(DecodeStatus::NotFound);
float left = (range.begin - row.begin()) + 0.5f * range.size();
CounterContainer theCounters = {};
std::string result;
result.reserve(20);
do {
// Read off white space
range = RecordPattern(row.getNextSet(range.end), row.end(), theCounters);
if (!range)
return Result(DecodeStatus::NotFound);
int pattern = ToPattern(theCounters);
if (pattern < 0) {
return Result(DecodeStatus::NotFound);
}
char decodedChar = PatternToChar(pattern);
if (decodedChar == 0) {
return Result(DecodeStatus::NotFound);
}
result.push_back(decodedChar);
} while (result.back() != '*');
result.pop_back(); // remove asterisk
// Should be at least one more black module
if (range.end == row.end() || !*range.end) {
return Result(DecodeStatus::NotFound);
}
if (result.length() < 2) {
// false positive -- need at least 2 checksum digits
return Result(DecodeStatus::NotFound);
}
auto status = CheckChecksums(result);
if (StatusIsError(status)) {
return Result(status);
}
// Remove checksum digits
result.resize(result.length() - 2);
std::string resultString;
status = DecodeExtended(result, resultString);
if (StatusIsError(status)) {
return Result(status);
}
float right = (range.begin - row.begin()) + 0.5f * range.size();
float ypos = static_cast<float>(rowNumber);
return Result(TextDecoder::FromLatin1(resultString), ByteArray(), { ResultPoint(left, ypos), ResultPoint(right, ypos) }, BarcodeFormat::CODE_93);
}
} // OneD
} // ZXing
|
remove trailing whitespace
|
remove trailing whitespace
|
C++
|
apache-2.0
|
nu-book/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp
|
90018df5cdedaed11a7c545936bee9d708ff6c61
|
core/thread/src/TPosixThread.cxx
|
core/thread/src/TPosixThread.cxx
|
// @(#)root/thread:$Id$
// Author: Fons Rademakers 02/07/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. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TPosixThread //
// //
// This class provides an interface to the posix thread routines. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TPosixThread.h"
ClassImp(TPosixThread)
//______________________________________________________________________________
Int_t TPosixThread::Run(TThread *th)
{
// Create a pthread. Returns 0 on success, otherwise an error number will
// be returned.
int det;
pthread_t id;
pthread_attr_t *attr = new pthread_attr_t;
pthread_attr_init(attr);
// Set detach state
det = (th->fDetached) ? PTHREAD_CREATE_DETACHED : PTHREAD_CREATE_JOINABLE;
pthread_attr_setdetachstate(attr, det);
int ierr = pthread_create(&id, attr, &TThread::Function, th);
if (!ierr) th->fId = (Long_t) id;
pthread_attr_destroy(attr);
delete attr;
return ierr;
}
//______________________________________________________________________________
Int_t TPosixThread::Join(TThread *th, void **ret)
{
// Join suspends the execution of the calling thread until the
// thread identified by th terminates, either by calling pthread_exit
// or by being cancelled. Returns 0 on success, otherwise an error number will
// be returned.
return pthread_join((pthread_t) th->fId, ret);
}
//______________________________________________________________________________
Int_t TPosixThread::Exit(void *ret)
{
// Terminates the execution of the calling thread. Return 0.
pthread_exit(ret);
return 0;
}
//______________________________________________________________________________
Int_t TPosixThread::Kill(TThread *th)
{
// Cancellation is the mechanism by which a thread can terminate the
// execution of another thread. Returns 0 on success, otherwise an error
// number will be returned.
return pthread_cancel((pthread_t) th->fId);
}
//______________________________________________________________________________
Int_t TPosixThread::SetCancelOff()
{
// Turn off the cancellation state of the calling thread. Returns 0 on
// success, otherwise an error number will be returned.
return pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0);
}
//______________________________________________________________________________
Int_t TPosixThread::SetCancelOn()
{
// Turn on the cancellation state of the calling thread. Returns 0 on
// success, otherwise an error number will be returned.
return pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
}
//______________________________________________________________________________
Int_t TPosixThread::SetCancelAsynchronous()
{
// Set the cancellation response type of the calling thread to
// asynchronous, i.e. cancel as soon as the cancellation request
// is received.
return pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
}
//______________________________________________________________________________
Int_t TPosixThread::SetCancelDeferred()
{
// Set the cancellation response type of the calling thread to
// deferred, i.e. cancel only at next cancellation point.
// Returns 0 on success, otherwise an error number will be returned.
return pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, 0);
}
//______________________________________________________________________________
Int_t TPosixThread::CancelPoint()
{
// Introduce an explicit cancellation point. Returns 0.
int istate;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &istate);
pthread_testcancel();
pthread_setcancelstate(istate, 0);
return 0;
}
//______________________________________________________________________________
Int_t TPosixThread::CleanUpPush(void **main, void *free, void *arg)
{
// Add thread cleanup function.
// pthread_cleanup_push(free, arg);
if (!free) Error("CleanUpPush", "cleanup rountine = 0");
new TPosixThreadCleanUp(main, free, arg);
return 0;
}
//______________________________________________________________________________
Int_t TPosixThread::CleanUpPop(void **main,Int_t exe)
{
// Pop thread cleanup function from stack.
// pthread_cleanup_pop(exe); // happy pthread future
if (!main || !*main) return 1;
TPosixThreadCleanUp *l = (TPosixThreadCleanUp*)(*main);
if (!l->fRoutine) Error("CleanUpPop", "cleanup routine = 0");
if (exe && l->fRoutine) ((void (*)(void*))(l->fRoutine))(l->fArgument);
*main = l->fNext; delete l;
return 0;
}
//______________________________________________________________________________
Int_t TPosixThread::CleanUp(void **main)
{
// Default thread cleanup routine.
if (gDebug > 0)
Info("Cleanup", "cleanup 0x%lx", (Long_t)*main);
while (!CleanUpPop(main, 1)) { }
return 0;
}
//______________________________________________________________________________
Long_t TPosixThread::SelfId()
{
// Return the thread identifier for the calling thread.
return (Long_t) pthread_self();
}
// Clean Up section. PTHREAD implementations of cleanup after cancel are
// too different and often too bad. Temporary I invent my own bicycle.
// V.Perev.
//______________________________________________________________________________
TPosixThreadCleanUp::TPosixThreadCleanUp(void **main, void *routine, void *arg)
{
//cleanup function
fNext = (TPosixThreadCleanUp*)*main;
fRoutine = routine; fArgument = arg;
*main = this;
}
|
// @(#)root/thread:$Id$
// Author: Fons Rademakers 02/07/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. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TPosixThread //
// //
// This class provides an interface to the posix thread routines. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TPosixThread.h"
ClassImp(TPosixThread)
//______________________________________________________________________________
Int_t TPosixThread::Run(TThread *th)
{
// Create a pthread. Returns 0 on success, otherwise an error number will
// be returned.
int det;
pthread_t id;
pthread_attr_t *attr = new pthread_attr_t;
pthread_attr_init(attr);
// Set detach state
det = (th->fDetached) ? PTHREAD_CREATE_DETACHED : PTHREAD_CREATE_JOINABLE;
pthread_attr_setdetachstate(attr, det);
#ifdef R__MACOSX
// See https://developer.apple.com/library/mac/#qa/qa1419/_index.html
// Linux has 2MB of stack per thread, so use the same:
#define R__REQUIRED_STACK_SIZE 1024*1024*2
size_t stackSize = 0;
if (!pthread_attr_getstacksize(attr, &stackSize)
&& stackSize < R__REQUIRED_STACK_SIZE) {
pthread_attr_setstacksize(attr, R__REQUIRED_STACK_SIZE);
}
#endif
int ierr = pthread_create(&id, attr, &TThread::Function, th);
if (!ierr) th->fId = (Long_t) id;
pthread_attr_destroy(attr);
delete attr;
return ierr;
}
//______________________________________________________________________________
Int_t TPosixThread::Join(TThread *th, void **ret)
{
// Join suspends the execution of the calling thread until the
// thread identified by th terminates, either by calling pthread_exit
// or by being cancelled. Returns 0 on success, otherwise an error number will
// be returned.
return pthread_join((pthread_t) th->fId, ret);
}
//______________________________________________________________________________
Int_t TPosixThread::Exit(void *ret)
{
// Terminates the execution of the calling thread. Return 0.
pthread_exit(ret);
return 0;
}
//______________________________________________________________________________
Int_t TPosixThread::Kill(TThread *th)
{
// Cancellation is the mechanism by which a thread can terminate the
// execution of another thread. Returns 0 on success, otherwise an error
// number will be returned.
return pthread_cancel((pthread_t) th->fId);
}
//______________________________________________________________________________
Int_t TPosixThread::SetCancelOff()
{
// Turn off the cancellation state of the calling thread. Returns 0 on
// success, otherwise an error number will be returned.
return pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0);
}
//______________________________________________________________________________
Int_t TPosixThread::SetCancelOn()
{
// Turn on the cancellation state of the calling thread. Returns 0 on
// success, otherwise an error number will be returned.
return pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
}
//______________________________________________________________________________
Int_t TPosixThread::SetCancelAsynchronous()
{
// Set the cancellation response type of the calling thread to
// asynchronous, i.e. cancel as soon as the cancellation request
// is received.
return pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
}
//______________________________________________________________________________
Int_t TPosixThread::SetCancelDeferred()
{
// Set the cancellation response type of the calling thread to
// deferred, i.e. cancel only at next cancellation point.
// Returns 0 on success, otherwise an error number will be returned.
return pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, 0);
}
//______________________________________________________________________________
Int_t TPosixThread::CancelPoint()
{
// Introduce an explicit cancellation point. Returns 0.
int istate;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &istate);
pthread_testcancel();
pthread_setcancelstate(istate, 0);
return 0;
}
//______________________________________________________________________________
Int_t TPosixThread::CleanUpPush(void **main, void *free, void *arg)
{
// Add thread cleanup function.
// pthread_cleanup_push(free, arg);
if (!free) Error("CleanUpPush", "cleanup rountine = 0");
new TPosixThreadCleanUp(main, free, arg);
return 0;
}
//______________________________________________________________________________
Int_t TPosixThread::CleanUpPop(void **main,Int_t exe)
{
// Pop thread cleanup function from stack.
// pthread_cleanup_pop(exe); // happy pthread future
if (!main || !*main) return 1;
TPosixThreadCleanUp *l = (TPosixThreadCleanUp*)(*main);
if (!l->fRoutine) Error("CleanUpPop", "cleanup routine = 0");
if (exe && l->fRoutine) ((void (*)(void*))(l->fRoutine))(l->fArgument);
*main = l->fNext; delete l;
return 0;
}
//______________________________________________________________________________
Int_t TPosixThread::CleanUp(void **main)
{
// Default thread cleanup routine.
if (gDebug > 0)
Info("Cleanup", "cleanup 0x%lx", (Long_t)*main);
while (!CleanUpPop(main, 1)) { }
return 0;
}
//______________________________________________________________________________
Long_t TPosixThread::SelfId()
{
// Return the thread identifier for the calling thread.
return (Long_t) pthread_self();
}
// Clean Up section. PTHREAD implementations of cleanup after cancel are
// too different and often too bad. Temporary I invent my own bicycle.
// V.Perev.
//______________________________________________________________________________
TPosixThreadCleanUp::TPosixThreadCleanUp(void **main, void *routine, void *arg)
{
//cleanup function
fNext = (TPosixThreadCleanUp*)*main;
fRoutine = routine; fArgument = arg;
*main = this;
}
|
Make pthread stack size at least the same on MacOS (default: 512k) as on Linux (default: 2M). Symmetry and price of RAM being the main reasons.
|
Make pthread stack size at least the same on MacOS (default: 512k) as on Linux (default: 2M). Symmetry and price of RAM being the main reasons.
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@42885 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical
|
8f123675921b7e04eed6560b43ff940123491a32
|
source/core/mining-manager/custom-rank-manager/CustomDocIdConverter.cpp
|
source/core/mining-manager/custom-rank-manager/CustomDocIdConverter.cpp
|
#include "CustomDocIdConverter.h"
#include <common/Utilities.h>
namespace sf1r
{
bool CustomDocIdConverter::convert(
const CustomRankDocStr& customDocStr,
CustomRankDocId& customDocId
)
{
return convertDocIdList_(customDocStr.topIds, customDocId.topIds) &&
convertDocIdList_(customDocStr.excludeIds, customDocId.excludeIds);
}
bool CustomDocIdConverter::convertDocIdList_(
const std::vector<std::string>& docStrList,
std::vector<docid_t>& docIdList
)
{
docid_t docId = 0;
for (std::vector<std::string>::const_iterator it = docStrList.begin();
it != docStrList.end(); ++it)
{
if (! convertDocId_(*it, docId))
return false;
docIdList.push_back(docId);
}
return true;
}
bool CustomDocIdConverter::convertDocId_(
const std::string& docStr,
docid_t& docId
)
{
uint128_t convertId = Utilities::md5ToUint128(docStr);
if (! idManager_.getDocIdByDocName(convertId, docId, false))
{
LOG(WARNING) << "in convertDocId_(), DOCID " << docStr
<< " does not exist";
return false;
}
return true;
}
} // namespace sf1r
|
#include "CustomDocIdConverter.h"
#include <common/Utilities.h>
#include <util/ClockTimer.h>
namespace sf1r
{
bool CustomDocIdConverter::convert(
const CustomRankDocStr& customDocStr,
CustomRankDocId& customDocId
)
{
izenelib::util::ClockTimer timer;
bool result = convertDocIdList_(customDocStr.topIds, customDocId.topIds) &&
convertDocIdList_(customDocStr.excludeIds, customDocId.excludeIds);
LOG(INFO) << "top num: " << customDocId.topIds.size()
<< ", exclude num: " << customDocId.excludeIds.size()
<< ", id conversion costs: " << timer.elapsed() << " seconds";
return result;
}
bool CustomDocIdConverter::convertDocIdList_(
const std::vector<std::string>& docStrList,
std::vector<docid_t>& docIdList
)
{
docid_t docId = 0;
for (std::vector<std::string>::const_iterator it = docStrList.begin();
it != docStrList.end(); ++it)
{
if (! convertDocId_(*it, docId))
return false;
docIdList.push_back(docId);
}
return true;
}
bool CustomDocIdConverter::convertDocId_(
const std::string& docStr,
docid_t& docId
)
{
uint128_t convertId = Utilities::md5ToUint128(docStr);
if (! idManager_.getDocIdByDocName(convertId, docId, false))
{
LOG(WARNING) << "in convertDocId_(), DOCID " << docStr
<< " does not exist";
return false;
}
return true;
}
} // namespace sf1r
|
add log to print time cost by CustomDocIdConverter::convert().
|
add log to print time cost by CustomDocIdConverter::convert().
|
C++
|
apache-2.0
|
izenecloud/sf1r-ad-delivery,izenecloud/sf1r-lite,izenecloud/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-ad-delivery,pombredanne/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-lite,pombredanne/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-lite,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-ad-delivery
|
fea5c08e595ff546a4d24d2796633642ef8d42be
|
HLT/TPCLib/macros/makeTPCFastTransformOCDBObject.C
|
HLT/TPCLib/macros/makeTPCFastTransformOCDBObject.C
|
// $Id$
/**
* @file makeGlobalHistoConfigObject.C
* @brief Creation of Global Histo component configuration objects in OCDB
*
* <pre>
* Usage:
*
* aliroot -b -q $ALICE_ROOT/HLT/TPCLib/macros/makeTPCFastTransformOCDBObject.C'("uri", runmin, runmax)'
*
* </pre>
*
* Create an OCDB entry
* Parameters: <br>
* - uri (opt) the OCDB URI, default $ALICE_ROOT/OCDB
* - runmin (opt) default 0
* - runmax (opt) default 999999999
* @author sergey gorbunov
* @ingroup alihlt_tutorial
*/
/*
aliroot -b -q $ALICE_ROOT/HLT/TPCLib/macros/makeTPCFastTransformOCDBObject.C'("local:///cvmfs/alice.gsi.de/alice/data/2010/OCDB/", 127941)'
//130704 )'
aliroot -q -b "$ALICE_ROOT/HLT/global/physics/macros/testconfigCalib.C"'("GLOBAL-flat-esd-converter","WriteAnalysisToFile=0 TPCcalibConfigString=TPCCalib:CalibTimeDrift EnableDebug=1 -pushback-period=1000")' $ALICE_ROOT/HLT/exa/recraw-local.C'("/hera/alice/local/filtered/alice/data/2010/LHC10e/000130704/raw/merged_highpt_12.root","local:///cvmfs/alice.gsi.de/alice/data/2010/OCDB/",'1', '1', "HLT", "chains=TPC-compression ignore
*/
void makeTPCFastTransformOCDBObject( const Char_t* cdbUri=NULL,
Int_t runMin=0, Int_t runMax=AliCDBRunRange::Infinity()) {
// --------------------------------------
// -- Setup CDB
// --------------------------------------
AliCDBManager* man = AliCDBManager::Instance();
if (!man) {
cerr << "Error : Can not get AliCDBManager" << end;
exit;
}
TString storage;
if (!man->IsDefaultStorageSet()) {
if ( cdbUri ) {
storage = cdbUri;
if ( storage.Contains("://") == 0 ) {
storage = "local://";
storage += cdbUri;
}
}
else {
storage="local://$ALICE_ROOT/OCDB";
}
man->SetDefaultStorage(storage);
}
else {
storage = man->GetDefaultStorage()->GetURI();
}
man->SetRun( runMin );
AliGRPManager grp;
grp.ReadGRPEntry();
grp.SetMagField();
const AliGRPObject *grpObj = grp.GetGRPData();
if( !grpObj ){
Error("No GRP object found!!");
}
if(!AliGeomManager::GetGeometry()){
AliGeomManager::LoadGeometry();
}
AliTPCcalibDB *calib=AliTPCcalibDB::Instance();
if(!calib){
Error("AliTPCcalibDB does not exist");
return -ENOENT;
}
Double_t bz = AliTracker::GetBz();
unsigned int timestamp = grpObj->GetTimeStart();
cout<<"\n\nBz field is set to "<<bz<<", time stamp is set to "<<timestamp<<endl<<endl;
const AliMagF * field = (AliMagF*) TGeoGlobalMagField::Instance()->GetField();
calib->SetExBField(field);
calib->SetRun( runMin );
calib->UpdateRunInformations( runMin );
AliHLTTPCClusterTransformation hltTransform;
TStopwatch timer;
timer.Start();
int err = hltTransform.Init( bz, timestamp, 0 );
timer.Stop();
cout<<"\n\n Initialisation: "<<timer.CpuTime()<<" / "<<timer.RealTime()<<" sec.\n\n"<<endl;
if( err!=0 ){
cerr << Form("Cannot retrieve offline transform from AliTPCcalibDB, AliHLTTPCClusterTransformation returns %d",err).Data()<<endl;
return -1;
}
TString path("HLT/ConfigTPC/TPCFastTransform");
// --------------------------------------
// -- Create Config Object
// --------------------------------------
// here is the actual content of the configuration object
const AliHLTTPCFastTransform &fastTransform = hltTransform.GetFastTransform();
AliHLTTPCFastTransformObject configObj;
Int_t err = fastTransform.WriteToObject( configObj );
if( err ){
Error("Can not create transformation object, error code %d",err);
}
// --------------------------------------
// -- Fill Object
// --------------------------------------
AliCDBPath cdbPath(path);
AliCDBId cdbId(cdbPath, runMin, runMax);
AliCDBMetaData cdbMetaData;
printf("Adding %s type OCDB object to %s [%d,%d] in %s \n",
configObj.ClassName(),
path.Data(),
runMin, runMax, storage.Data());
if(1){ // for test proposes only
storage="local://$ALICE_ROOT/OCDB";
man->SetDefaultStorage(storage);
}
man->Put( (TObject*)&configObj, cdbId, &cdbMetaData);
}
|
// $Id$
/**
* @file makeGlobalHistoConfigObject.C
* @brief Creation of Global Histo component configuration objects in OCDB
*
* <pre>
* Usage:
*
* aliroot -b -q $ALICE_ROOT/HLT/TPCLib/macros/makeTPCFastTransformOCDBObject.C'("uri", runmin, runmax)'
*
* </pre>
*
* Create an OCDB entry
* Parameters: <br>
* - uri (opt) the OCDB URI, default $ALICE_ROOT/OCDB
* - runmin (opt) default 0
* - runmax (opt) default 999999999
* @author sergey gorbunov
* @ingroup alihlt_tutorial
*/
/*
aliroot -b -q $ALICE_ROOT/HLT/TPCLib/macros/makeTPCFastTransformOCDBObject.C'("local:///cvmfs/alice.gsi.de/alice/data/2010/OCDB/", 127941)'
//130704 )'
aliroot -q -b "$ALICE_ROOT/HLT/global/physics/macros/testconfigCalib.C"'("GLOBAL-flat-esd-converter","WriteAnalysisToFile=0 TPCcalibConfigString=TPCCalib:CalibTimeDrift EnableDebug=1 -pushback-period=1000")' $ALICE_ROOT/HLT/exa/recraw-local.C'("/hera/alice/local/filtered/alice/data/2010/LHC10e/000130704/raw/merged_highpt_12.root","local:///cvmfs/alice.gsi.de/alice/data/2010/OCDB/",'1', '1', "HLT", "chains=TPC-compression ignore
*/
void makeTPCFastTransformOCDBObject( const Char_t* cdbUri=NULL,
Int_t runMin=0, Int_t runMax=AliCDBRunRange::Infinity()) {
// --------------------------------------
// -- Setup CDB
// --------------------------------------
AliCDBManager* man = AliCDBManager::Instance();
if (!man) {
cerr << "Error : Can not get AliCDBManager" << end;
exit;
}
TString storage;
if (!man->IsDefaultStorageSet()) {
if ( cdbUri ) {
storage = cdbUri;
if ( storage.Contains("://") == 0 ) {
storage = "local://";
storage += cdbUri;
}
}
else {
storage="local://$ALICE_ROOT/OCDB";
}
man->SetDefaultStorage(storage);
}
else {
storage = man->GetDefaultStorage()->GetURI();
}
man->SetRun( runMin );
AliGRPManager grp;
grp.ReadGRPEntry();
grp.SetMagField();
const AliGRPObject *grpObj = grp.GetGRPData();
if( !grpObj ){
Error("No GRP object found!!");
}
if(!AliGeomManager::GetGeometry()){
AliGeomManager::LoadGeometry();
}
AliTPCcalibDB *calib=AliTPCcalibDB::Instance();
if(!calib){
Error("AliTPCcalibDB does not exist");
return -ENOENT;
}
Double_t bz = AliTracker::GetBz();
unsigned int timestamp = grpObj->GetTimeStart();
cout<<"\n\nBz field is set to "<<bz<<", time stamp is set to "<<timestamp<<endl<<endl;
const AliMagF * field = (AliMagF*) TGeoGlobalMagField::Instance()->GetField();
calib->SetExBField(field);
calib->SetRun( runMin );
calib->UpdateRunInformations( runMin );
AliHLTTPCClusterTransformation hltTransform;
TStopwatch timer;
timer.Start();
int err = hltTransform.Init( bz, timestamp, 0, 0 );
timer.Stop();
cout<<"\n\n Initialisation: "<<timer.CpuTime()<<" / "<<timer.RealTime()<<" sec.\n\n"<<endl;
if( err!=0 ){
cerr << Form("Cannot retrieve offline transform from AliTPCcalibDB, AliHLTTPCClusterTransformation returns %d",err).Data()<<endl;
return -1;
}
TString path("HLT/ConfigTPC/TPCFastTransform");
// --------------------------------------
// -- Create Config Object
// --------------------------------------
// here is the actual content of the configuration object
const AliHLTTPCFastTransform &fastTransform = hltTransform.GetFastTransform();
AliHLTTPCFastTransformObject configObj;
Int_t err = fastTransform.WriteToObject( configObj );
if( err ){
Error("Can not create transformation object, error code %d",err);
}
// --------------------------------------
// -- Fill Object
// --------------------------------------
AliCDBPath cdbPath(path);
AliCDBId cdbId(cdbPath, runMin, runMax);
AliCDBMetaData cdbMetaData;
printf("Adding %s type OCDB object to %s [%d,%d] in %s \n",
configObj.ClassName(),
path.Data(),
runMin, runMax, storage.Data());
if(1){ // for test proposes only
storage="local://$ALICE_ROOT/OCDB";
man->SetDefaultStorage(storage);
}
man->Put( (TObject*)&configObj, cdbId, &cdbMetaData);
}
|
add missing new parameter to init function
|
add missing new parameter to init function
|
C++
|
bsd-3-clause
|
sebaleh/AliRoot,coppedis/AliRoot,alisw/AliRoot,shahor02/AliRoot,alisw/AliRoot,sebaleh/AliRoot,alisw/AliRoot,sebaleh/AliRoot,shahor02/AliRoot,shahor02/AliRoot,coppedis/AliRoot,miranov25/AliRoot,sebaleh/AliRoot,alisw/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,alisw/AliRoot,shahor02/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,alisw/AliRoot,miranov25/AliRoot,coppedis/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,coppedis/AliRoot,miranov25/AliRoot,miranov25/AliRoot,alisw/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,ALICEHLT/AliRoot,ALICEHLT/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,coppedis/AliRoot,shahor02/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,alisw/AliRoot
|
cb6f94609e7c9c4bcbf0194889db754b2546aaa4
|
include/nifty/graph/opt/multicut/multicut_greedy_additive.hxx
|
include/nifty/graph/opt/multicut/multicut_greedy_additive.hxx
|
#pragma once
#include <random>
#include <functional>
#include "nifty/tools/changable_priority_queue.hxx"
#include "nifty/tools/runtime_check.hxx"
#include "nifty/graph/detail/adjacency.hxx"
#include "nifty/graph/opt/multicut/multicut_base.hxx"
#include "nifty/graph/edge_contraction_graph.hxx"
//#include "nifty/graph/detail/contiguous_indices.hxx"
namespace nifty{
namespace graph{
namespace opt{
namespace multicut{
// \cond SUPPRESS_DOXYGEN
namespace detail_multicut_greedy_additive{
template<class OBJECTIVE>
class MulticutGreedyAdditiveCallback{
public:
struct SettingsType{
double weightStopCond{0.0};
double nodeNumStopCond{-1};
int seed {42};
bool addNoise {false};
double sigma{1.0};
int visitNth{1};
};
typedef OBJECTIVE ObjectiveType;
typedef typename ObjectiveType::GraphType GraphType;
typedef nifty::tools::ChangeablePriorityQueue< double ,std::greater<double> > QueueType;
MulticutGreedyAdditiveCallback(
const ObjectiveType & objective,
const SettingsType & settings
)
: objective_(objective),
graph_(objective.graph()),
pq_(objective.graph().edgeIdUpperBound()+1 ),
settings_(settings),
currentNodeNum_(objective.graph().numberOfNodes()),
gen_(settings.seed),
dist_(0.0, settings.sigma){
this->reset();
}
void reset(){
// reset queue in case something is left
while(!pq_.empty())
pq_.pop();
const auto & weights = objective_.weights();
for(const auto edge: graph_.edges()){
if(!settings_.addNoise)
pq_.push(edge, weights[edge]);
else{
pq_.push(edge, weights[edge] + dist_(gen_));
}
}
}
void contractEdge(const uint64_t edgeToContract){
NIFTY_ASSERT(pq_.contains(edgeToContract));
pq_.deleteItem(edgeToContract);
}
void mergeNodes(const uint64_t aliveNode, const uint64_t deadNode){
--currentNodeNum_;
}
void mergeEdges(const uint64_t aliveEdge, const uint64_t deadEdge){
NIFTY_ASSERT(pq_.contains(aliveEdge));
NIFTY_ASSERT(pq_.contains(deadEdge));
const auto wEdgeInAlive = pq_.priority(aliveEdge);
const auto wEdgeInDead = pq_.priority(deadEdge);
pq_.deleteItem(deadEdge);
pq_.changePriority(aliveEdge, wEdgeInAlive + wEdgeInDead);
}
void contractEdgeDone(const uint64_t edgeToContract){
// nothing to do here
}
bool done(){
const auto highestWeight = pq_.topPriority();
const auto nnsc = settings_.nodeNumStopCond;
// exit if weight stop cond kicks in
if(highestWeight <= settings_.weightStopCond){
return true;
}
if(nnsc > 0.0){
uint64_t ns;
if(nnsc >= 1.0){
ns = static_cast<uint64_t>(nnsc);
}
else{
ns = static_cast<uint64_t>(double(graph_.numberOfNodes())*nnsc +0.5);
}
if(currentNodeNum_ <= ns){
return true;
}
}
if(currentNodeNum_<=1){
return true;
}
if(pq_.empty()){
return true;
}
return false;
}
uint64_t edgeToContract(){
return pq_.top();
}
void changeSettings(
const SettingsType & settings
){
settings_ = settings;
}
const QueueType & queue()const{
return pq_;
}
const SettingsType & settings()const{
return settings_;
}
private:
const ObjectiveType & objective_;
const GraphType & graph_;
QueueType pq_;
SettingsType settings_;
uint64_t currentNodeNum_;
std::mt19937 gen_;
std::normal_distribution<> dist_;
};
} // end namespace detail_multicut_greedy_additive
// \endcond
template<class OBJECTIVE>
class MulticutGreedyAdditive : public MulticutBase<OBJECTIVE>
{
public:
typedef OBJECTIVE ObjectiveType;
typedef typename ObjectiveType::GraphType GraphType;
typedef detail_multicut_greedy_additive::MulticutGreedyAdditiveCallback<ObjectiveType> Callback;
typedef MulticutBase<OBJECTIVE> BaseType;
typedef typename BaseType::VisitorBaseType VisitorBaseType;
typedef typename BaseType::NodeLabelsType NodeLabelsType;
public:
typedef typename Callback::SettingsType SettingsType;
virtual ~MulticutGreedyAdditive(){}
MulticutGreedyAdditive(const ObjectiveType & objective, const SettingsType & settings = SettingsType());
virtual void optimize(NodeLabelsType & nodeLabels, VisitorBaseType * visitor);
virtual const ObjectiveType & objective() const;
void reset();
void changeSettings(const SettingsType & settings);
virtual void weightsChanged(){
this->reset();
}
virtual const NodeLabelsType & currentBestNodeLabels( ){
for(auto node : graph_.nodes()){
currentBest_->operator[](node) = edgeContractionGraph_.findRepresentativeNode(node);
}
return *currentBest_;
}
virtual std::string name()const{
return std::string("MulticutGreedyAdditive");
}
private:
const ObjectiveType & objective_;
const GraphType & graph_;
NodeLabelsType * currentBest_;
Callback callback_;
EdgeContractionGraph<GraphType, Callback> edgeContractionGraph_;
};
template<class OBJECTIVE>
MulticutGreedyAdditive<OBJECTIVE>::
MulticutGreedyAdditive(
const ObjectiveType & objective,
const SettingsType & settings
)
: objective_(objective),
graph_(objective.graph()),
currentBest_(nullptr),
callback_(objective, settings),
edgeContractionGraph_(objective.graph(), callback_)
{
// do the setup
this->reset();
}
template<class OBJECTIVE>
void MulticutGreedyAdditive<OBJECTIVE>::
optimize(
NodeLabelsType & nodeLabels, VisitorBaseType * visitor
){
if(visitor!=nullptr){
visitor->addLogNames({"#nodes","topWeight"});
visitor->begin(this);
}
auto c = 1;
if(graph_.numberOfEdges()>0){
currentBest_ = & nodeLabels;
while(!callback_.done() ){
// get the edge
auto edgeToContract = callback_.edgeToContract();
// contract it
edgeContractionGraph_.contractEdge(edgeToContract);
if(c % callback_.settings().visitNth == 0){
if(visitor!=nullptr){
visitor->setLogValue(0, edgeContractionGraph_.numberOfNodes());
visitor->setLogValue(1, callback_.queue().topPriority());
if(!visitor->visit(this)){
std::cout<<"end by visitor\n";
break;
}
}
}
++c;
}
for(auto node : graph_.nodes()){
nodeLabels[node] = edgeContractionGraph_.findRepresentativeNode(node);
}
}
if(visitor!=nullptr)
visitor->end(this);
}
template<class OBJECTIVE>
const typename MulticutGreedyAdditive<OBJECTIVE>::ObjectiveType &
MulticutGreedyAdditive<OBJECTIVE>::
objective()const{
return objective_;
}
template<class OBJECTIVE>
void MulticutGreedyAdditive<OBJECTIVE>::
reset(
){
callback_.reset();
edgeContractionGraph_.reset();
}
template<class OBJECTIVE>
inline void
MulticutGreedyAdditive<OBJECTIVE>::
changeSettings(
const SettingsType & settings
){
callback_.changeSettings(settings);
}
} // namespace nifty::graph::opt::multicut
} // namespace nifty::graph::opt
} // namespace nifty::graph
} // namespace nifty
|
#pragma once
#include <random>
#include <functional>
#include "nifty/tools/changable_priority_queue.hxx"
#include "nifty/tools/runtime_check.hxx"
#include "nifty/graph/detail/adjacency.hxx"
#include "nifty/graph/opt/multicut/multicut_base.hxx"
#include "nifty/graph/edge_contraction_graph.hxx"
//#include "nifty/graph/detail/contiguous_indices.hxx"
namespace nifty{
namespace graph{
namespace opt{
namespace multicut{
// \cond SUPPRESS_DOXYGEN
namespace detail_multicut_greedy_additive{
template<class OBJECTIVE>
class MulticutGreedyAdditiveCallback{
public:
struct SettingsType{
double weightStopCond{0.0};
double nodeNumStopCond{-1};
int seed {42};
bool addNoise {false};
double sigma{1.0};
int visitNth{1};
};
typedef OBJECTIVE ObjectiveType;
typedef typename ObjectiveType::GraphType GraphType;
typedef nifty::tools::ChangeablePriorityQueue< double ,std::greater<double> > QueueType;
MulticutGreedyAdditiveCallback(
const ObjectiveType & objective,
const SettingsType & settings
)
: objective_(objective),
graph_(objective.graph()),
pq_(objective.graph().edgeIdUpperBound()+1 ),
settings_(settings),
currentNodeNum_(objective.graph().numberOfNodes()),
gen_(settings.seed),
dist_(0.0, settings.sigma){
}
void reset(){
// reset queue in case something is left
while(!pq_.empty())
pq_.pop();
// fill it
const auto & weights = objective_.weights();
for(const auto edge: graph_.edges()){
if(!settings_.addNoise)
pq_.push(edge, weights[edge]);
else{
pq_.push(edge, weights[edge] + dist_(gen_));
}
}
}
inline void contractEdge(const uint64_t edgeToContract){
NIFTY_ASSERT(pq_.contains(edgeToContract));
pq_.deleteItem(edgeToContract);
}
inline void mergeNodes(const uint64_t aliveNode, const uint64_t deadNode){
--currentNodeNum_;
}
inline void mergeEdges(const uint64_t aliveEdge, const uint64_t deadEdge){
NIFTY_ASSERT(pq_.contains(aliveEdge));
NIFTY_ASSERT(pq_.contains(deadEdge));
const auto wEdgeInAlive = pq_.priority(aliveEdge);
const auto wEdgeInDead = pq_.priority(deadEdge);
pq_.deleteItem(deadEdge);
pq_.changePriority(aliveEdge, wEdgeInAlive + wEdgeInDead);
}
inline void contractEdgeDone(const uint64_t edgeToContract){
// nothing to do here
}
inline bool done(){
const auto highestWeight = pq_.topPriority();
const auto nnsc = settings_.nodeNumStopCond;
// exit if weight stop cond kicks in
if(highestWeight <= settings_.weightStopCond){
return true;
}
if(nnsc > 0.0){
uint64_t ns;
if(nnsc >= 1.0){
ns = static_cast<uint64_t>(nnsc);
}
else{
ns = static_cast<uint64_t>(double(graph_.numberOfNodes())*nnsc +0.5);
}
if(currentNodeNum_ <= ns){
return true;
}
}
if(currentNodeNum_<=1){
return true;
}
if(pq_.empty()){
return true;
}
return false;
}
inline uint64_t edgeToContract(){
return pq_.top();
}
void changeSettings(
const SettingsType & settings
){
settings_ = settings;
}
const QueueType & queue() const{
return pq_;
}
const SettingsType & settings() const{
return settings_;
}
private:
const ObjectiveType & objective_;
const GraphType & graph_;
QueueType pq_;
SettingsType settings_;
uint64_t currentNodeNum_;
std::mt19937 gen_;
std::normal_distribution<> dist_;
};
} // end namespace detail_multicut_greedy_additive
// \endcond
template<class OBJECTIVE>
class MulticutGreedyAdditive : public MulticutBase<OBJECTIVE>
{
public:
typedef OBJECTIVE ObjectiveType;
typedef typename ObjectiveType::GraphType GraphType;
typedef detail_multicut_greedy_additive::MulticutGreedyAdditiveCallback<ObjectiveType> Callback;
typedef MulticutBase<OBJECTIVE> BaseType;
typedef typename BaseType::VisitorBaseType VisitorBaseType;
typedef typename BaseType::NodeLabelsType NodeLabelsType;
public:
typedef typename Callback::SettingsType SettingsType;
virtual ~MulticutGreedyAdditive(){}
MulticutGreedyAdditive(const ObjectiveType & objective, const SettingsType & settings = SettingsType());
virtual void optimize(NodeLabelsType & nodeLabels, VisitorBaseType * visitor);
virtual const ObjectiveType & objective() const;
void reset();
void changeSettings(const SettingsType & settings);
virtual void weightsChanged(){
this->reset();
}
virtual const NodeLabelsType & currentBestNodeLabels( ){
for(auto node : graph_.nodes()){
currentBest_->operator[](node) = edgeContractionGraph_.findRepresentativeNode(node);
}
return *currentBest_;
}
virtual std::string name()const{
return std::string("MulticutGreedyAdditive");
}
private:
const ObjectiveType & objective_;
const GraphType & graph_;
NodeLabelsType * currentBest_;
Callback callback_;
EdgeContractionGraph<GraphType, Callback> edgeContractionGraph_;
};
template<class OBJECTIVE>
MulticutGreedyAdditive<OBJECTIVE>::
MulticutGreedyAdditive(
const ObjectiveType & objective,
const SettingsType & settings
)
: objective_(objective),
graph_(objective.graph()),
currentBest_(nullptr),
callback_(objective, settings),
edgeContractionGraph_(objective.graph(), callback_)
{
// do the setup
this->reset();
}
template<class OBJECTIVE>
void MulticutGreedyAdditive<OBJECTIVE>::
optimize(
NodeLabelsType & nodeLabels, VisitorBaseType * visitor
){
if(visitor!=nullptr){
visitor->addLogNames({"#nodes","topWeight"});
visitor->begin(this);
}
auto c = 1;
if(graph_.numberOfEdges()>0){
currentBest_ = & nodeLabels;
while(!callback_.done() ){
// get the edge
auto edgeToContract = callback_.edgeToContract();
// contract it
edgeContractionGraph_.contractEdge(edgeToContract);
if(c % callback_.settings().visitNth == 0){
if(visitor!=nullptr){
visitor->setLogValue(0, edgeContractionGraph_.numberOfNodes());
visitor->setLogValue(1, callback_.queue().topPriority());
if(!visitor->visit(this)){
std::cout<<"end by visitor\n";
break;
}
}
}
++c;
}
for(auto node : graph_.nodes()){
nodeLabels[node] = edgeContractionGraph_.findRepresentativeNode(node);
}
}
if(visitor!=nullptr)
visitor->end(this);
}
template<class OBJECTIVE>
const typename MulticutGreedyAdditive<OBJECTIVE>::ObjectiveType &
MulticutGreedyAdditive<OBJECTIVE>::
objective()const{
return objective_;
}
template<class OBJECTIVE>
void MulticutGreedyAdditive<OBJECTIVE>::
reset(
){
callback_.reset();
edgeContractionGraph_.reset();
}
template<class OBJECTIVE>
inline void
MulticutGreedyAdditive<OBJECTIVE>::
changeSettings(
const SettingsType & settings
){
callback_.changeSettings(settings);
}
} // namespace nifty::graph::opt::multicut
} // namespace nifty::graph::opt
} // namespace nifty::graph
} // namespace nifty
|
Fix double pq initialisation in gaec
|
Fix double pq initialisation in gaec
|
C++
|
mit
|
DerThorsten/nifty,DerThorsten/nifty,DerThorsten/nifty,DerThorsten/nifty,DerThorsten/nifty
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.