hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
591801162605b98a3e03e9a4178fa2e6d15ed72a | 2,925 | cc | C++ | Boss2D/addon/webrtc-jumpingyang001_for_boss/rtc_tools/sanitizers_unittest.cc | Yash-Wasalwar-07/Boss2D | 37c5ba0f1c83c89810359a207cabfa0905f803d2 | [
"MIT"
] | null | null | null | Boss2D/addon/webrtc-jumpingyang001_for_boss/rtc_tools/sanitizers_unittest.cc | Yash-Wasalwar-07/Boss2D | 37c5ba0f1c83c89810359a207cabfa0905f803d2 | [
"MIT"
] | null | null | null | Boss2D/addon/webrtc-jumpingyang001_for_boss/rtc_tools/sanitizers_unittest.cc | Yash-Wasalwar-07/Boss2D | 37c5ba0f1c83c89810359a207cabfa0905f803d2 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2017 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 <stddef.h>
#include <stdio.h>
#include <random>
#include BOSS_ABSEILCPP_U_absl__memory__memory_h //original-code:"absl/memory/memory.h"
#include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h"
#include BOSS_WEBRTC_U_rtc_base__nullsocketserver_h //original-code:"rtc_base/nullsocketserver.h"
#include BOSS_WEBRTC_U_rtc_base__thread_h //original-code:"rtc_base/thread.h"
#include "test/gtest.h"
namespace rtc {
namespace {
#if defined(MEMORY_SANITIZER)
void UseOfUninitializedValue() {
int* buf = new int[2];
std::random_device engine;
if (buf[engine() % 2]) { // Non-deterministic conditional.
printf("Externally visible action.");
}
delete[] buf;
}
TEST(SanitizersDeathTest, MemorySanitizer) {
EXPECT_DEATH(UseOfUninitializedValue(), "use-of-uninitialized-value");
}
#endif
#if defined(ADDRESS_SANITIZER)
void HeapUseAfterFree() {
char* buf = new char[2];
delete[] buf;
buf[0] = buf[1];
}
TEST(SanitizersDeathTest, AddressSanitizer) {
EXPECT_DEATH(HeapUseAfterFree(), "heap-use-after-free");
}
#endif
#if defined(UNDEFINED_SANITIZER)
// For ubsan:
void SignedIntegerOverflow() {
int32_t x = 1234567890;
x *= 2;
}
// For ubsan_vptr:
struct Base {
virtual void f() {}
virtual ~Base() {}
};
struct Derived : public Base {};
void InvalidVptr() {
Base b;
auto* d = static_cast<Derived*>(&b); // Bad downcast.
d->f(); // Virtual function call with object of wrong dynamic type.
}
TEST(SanitizersDeathTest, UndefinedSanitizer) {
EXPECT_DEATH(
{
SignedIntegerOverflow();
InvalidVptr();
},
"runtime error");
}
#endif
#if defined(THREAD_SANITIZER)
class IncrementThread : public Thread {
public:
explicit IncrementThread(int* value)
: Thread(absl::make_unique<NullSocketServer>()), value_(value) {}
void Run() override {
++*value_;
Thread::Current()->SleepMs(100);
}
// Un-protect Thread::Join for the test.
void Join() { Thread::Join(); }
private:
int* value_;
RTC_DISALLOW_COPY_AND_ASSIGN(IncrementThread);
};
void DataRace() {
int value = 0;
IncrementThread thread1(&value);
IncrementThread thread2(&value);
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
// TSan seems to mess with gtest's death detection.
// Fail intentionally, and rely on detecting the error message.
RTC_CHECK(false);
}
TEST(SanitizersDeathTest, ThreadSanitizer) {
EXPECT_DEATH(DataRace(), "data race");
}
#endif
} // namespace
} // namespace rtc
| 23.780488 | 97 | 0.70735 | [
"object"
] |
591b9e56aba6a3c5118c4b4ec96ddf0f47abcdc9 | 3,309 | ipp | C++ | include/External/stlib/packages/geom/kernel/Circle3.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | include/External/stlib/packages/geom/kernel/Circle3.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | include/External/stlib/packages/geom/kernel/Circle3.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | // -*- C++ -*-
#if !defined(__geom_kernel_Circle3_ipp__)
#error This file is an implementation detail of the class Circle3.
#endif
namespace geom {
//
// Validity.
//
// Return true if the circle is valid.
template<typename _T>
inline
bool
Circle3<_T>::
isValid() const {
// If the radius is negative.
if (radius < 0) {
// The circle is not valid.
return false;
}
// If the normal is not of unit length.
if (std::abs(magnitude(normal) - 1.0) >
10.0 * std::numeric_limits<_T>::epsilon()) {
// The circle is not valid.
return false;
}
// Otherwise, the circle is valid.
return true;
}
//
// Mathematical functions.
//
// Compute the closest point on the circle.
template<typename _T>
inline
void
computeClosestPoint(const Circle3<_T>& circle,
typename Circle3<_T>::Point x,
typename Circle3<_T>::Point* closestPoint) {
typedef typename Circle3<_T>::Point Point;
// The vector between the point and the circle center.
Point vec = x;
vec -= circle.center;
// Move the point into the plane of the circle.
x -= dot(vec, circle.normal) * circle.normal;
// The vector between the point in the plane and the circle center.
vec = x;
vec -= circle.center;
// Deal with vec near zero length.
if (magnitude(vec) < 10.0 * std::numeric_limits<_T>::epsilon()) {
computeAnOrthogonalVector(circle.normal, &vec);
}
// Change the vector length to the circle radius.
normalize(&vec);
vec *= circle.radius;
// The closest point is center + vec.
*closestPoint = circle.center;
*closestPoint += vec;
}
// Compute the closest point on the circle to the edge.
template<typename _T>
inline
void
computeClosestPoint(const Circle3<_T>& circle,
const typename Circle3<_T>::Point& source,
const typename Circle3<_T>::Point& target,
typename Circle3<_T>::Point* closestPoint,
_T tolerance, std::size_t maximumSteps) {
typedef typename Circle3<_T>::Point Point;
// Make a line segment from the endpoints.
SegmentMath<3, _T> segment(source, target);
// Start with the mid-point of the line segment.
Point pointOnSegment = source;
pointOnSegment = target;
pointOnSegment *= 0.5;
// Compute an initial closest point on the circle.
computeClosestPoint(circle, pointOnSegment, closestPoint);
// Iterate computing the closest point until we achieve convergence.
Point pointOnCircle;
// We have taken one step so far.
std::size_t numberOfSteps = 1;
do {
// Increment the number of steps.
++numberOfSteps;
// Record the old point on the circle.
pointOnCircle = *closestPoint;
// Compute the closest point on the line segment.
computeClosestPoint(segment, pointOnCircle, &pointOnSegment);
// Compute the closest point on the circle to the point on the segment.
computeClosestPoint(circle, pointOnSegment, closestPoint);
}
while (numberOfSteps < maximumSteps &&
euclideanDistance(pointOnCircle, *closestPoint) * circle.radius
> tolerance);
}
} // namespace geom
| 28.282051 | 78 | 0.633726 | [
"vector"
] |
5923f444d1a08714c8f099f4b7c959c0c7aca95a | 70,688 | hpp | C++ | openstudiocore/src/model/mainpage.hpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | 1 | 2019-04-21T15:38:54.000Z | 2019-04-21T15:38:54.000Z | openstudiocore/src/model/mainpage.hpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | null | null | null | openstudiocore/src/model/mainpage.hpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | 1 | 2019-07-18T06:52:29.000Z | 2019-07-18T06:52:29.000Z | namespace openstudio {
namespace model {
/** \mainpage OpenStudio Model
*
* \section overview_model Overview
*
* An OpenStudio Model (\ref introduction_model) represents a single building energy model,
* either complete (simulatable with EnergyPlus) or partial. It is composed of a collection of
* \link ModelObject ModelObjects \endlink (\ref modelobject), which are polymorphic, that is,
* ModelObject is the base class from which more specific object types are derived. Each leaf of
* the inheritance tree wraps a specific data object type that is ultimately defined by the
* OpenStudio.idd file. The following classes form the foundation of the OpenStudio Model:
*
* \li Model
* \li Component
* \li ModelObject
* \li ParentObject
* \li ResourceObject
*
* The specific model object types can largely be broken down into the categories of simulation
* settings; output data; resources; site and location; geometry; building loads; advanced daylighting;
* heating, ventilation and air conditioning (HVAC) systems;
* economics; and standards. We will now list the most important classes in each of these
* categories. The lists are not meant to be exhaustive, but rather to give an intuitive sense
* of what is and is not currently covered by the OpenStudio Model. Throughout, some of the
* classes will be concrete (have a one-to-one mapping with an object in OpenStudio.idd), and
* some will be abstract (provide a higher level interface to multiple Idd objects).
*
* \subsection simulation_settings_classes Simulation Settings
*
* \li Version
* \li YearDescription
* \li SimulationControl
* \li LightingSimulationControl
* \li Timestep
* \li RunPeriod
* \li ConvergenceLimits
* \li SizingParameters
*
* \subsection output_data_classes Output Data
*
* \li Meter
* \li OutputVariable
*
* \subsection resource_classes Resources
*
* \li Schedule
* \li ScheduleTypeLimits
* \li DefaultScheduleSet
* \li Construction
* \li DefaultConstructionSet
* \li OpaqueMaterial
* \li FenestrationMaterial
* \li ModelPartitionMaterial
* \li SpaceType
* \li ElectricEquipmentDefinition
* \li GasEquipmentDefinition
* \li InternalMassDefinition
* \li LightsDefinition
* \li LuminaireDefinition
* \li PeopleDefinition
* \li ExteriorLightsDefinition
* \li ExteriorFuelEquipmentDefinition
* \li ExteriorWaterEquipmentDefinition
*
* \subsection site_location_classes Site and Location
*
* \li Site
* \li DesignDay
* \li LightingDesignDay
* \li WeatherFile
* \li SiteWaterMainsTemperature
*
* \subsection geometry_classes Geometry
*
* \li Facility
* \li Building
* \li BuildingStory
* \li Space
* \li Surface
* \li SubSurface
* \li ShadingSurfaceGroup
* \li ShadingSurface
* \li InteriorPartitionSurfaceGroup
* \li InteriorPartitionSurface
*
* \subsection building_loads_classes Building Loads
*
* \li ElectricEquipment
* \li GasEquipment
* \li InternalMass
* \li Lights
* \li Luminaire
* \li People
* \li SpaceInfiltrationDesignFlowRate
* \li DesignSpecificationOutdoorAir
* \li ExteriorLights
* \li ExteriorFuelEquipment
* \li ExteriorWaterEquipment
*
* \subsection advanced_daylighting_classes Advanced Daylighting
*
* \li DaylightingControl
* \li GlareSensor
* \li IlluminanceMap
* \li DaylightingDeviceShelf
* \li LightingSimulationZone
*
* \subsection hvac_classes HVAC Systems
*
* \li AirLoopHVAC
* \li PlantLoop
* \li ThermalZone
* \li SizingZone
* \li SizingSystem
* \li Splitter
* \li Mixer
* \li Node
* \li HVACComponent
* \li ZoneHVACComponent
* \li StraightComponent
* \li WaterToAirComponent
* \li Curve
* \li ThermostatSetpointDualSetpoint
* \li AvailabilityManagerScheduled
* \li ControllerMechanicalVentilation
* \li ControllerOutdoorAir
* \li ControllerWaterCoil
*
* \subsection economics_classes Economics
*
* This subsection of the model is not fully developed. Classes like ComponentCost_LineItem,
* and UtilityCost_Tariff are available, but we expect to do a full refactor of this area of
* the model as time allows.
*
* \subsection standards_classes Standards
*
* This subsection of the model is not fully developed. BuildingStandardsInformation,
* ConstructionBaseStandardsInformation, and ClimateZones are examples of this type
* of object.
*
* \subsection other_links Other Links
*
* The following links may also be of general interest. Attributes and relationships are a way to
* access simple (no arguments to get, and one argument to set) ModelObject methods using strings,
* rather than directly navigating the inheritance hierarchy.
*
* \li \ref attributes "Attribute"
* \li \ref attributes "Relationship"
* \li \ref components
* \li \link ConcreteModelObjects.hpp Alphabetical List of Concrete ModelObjects \endlink
* \li \ref modelobject_hierachy "Concrete ModelObjects in Parent-Child Tree"
*
* \section introduction_model What is the Openstudio Model?
*
* The OpenStudio Model is a hierarchical, object-oriented model of a partial or complete building
* that exists to support annual energy and other simulations and related analyses. Complete
* building models may be simulated with EnergyPlus, which is developed by the Department of Energy
* and is our primary simulation target (http://apps1.eere.energy.gov/buildings/energyplus/).
* Daylighting simulation with Radiance is also supported, and OpenStudio can conduct some economic
* analyses natively. The OpenStudio Model aims to integrate input and output data into a seamless
* whole. EnergyPlus output data is accessed through the Model by connecting to an appropriate SqlFile (see the
* utilities documentation), which provides a basic interface to the EnergyPlus SQLite output. Once
* the basic connection to an output file is established, intuitive interfaces to specific pieces of
* output data are provided at the object level. For instance, see Facility, ThermalZone,
* and \ref modelobjectOutputDataAccessMethods.
*
* \subsection underlying_data Foundation: Data Model
*
* The underlying input data for Model is adapted from the EnergyPlus IDD/IDF file formats, where
* an IDD (input data definition) file is a data schema, analogous to an XML Schema file, and an
* IDF (input data file) is an instantiation of that schema, analogous to an XML file. The
* OpenStudio IDD has been developed using a subset of objects in the EnergyPlus IDD as a starting point so
* that OpenStudio can directly leverage EnergyPlus's numerous and extensively documented data
* objects. Over time the OpenStudio IDD has grown to include more objects from the EnergyPlus IDD, with a
* focus on including the most important types for energy simulation first. Additionally, new object types
* have been added to the OpenStudio IDD to provide functionalities such as:
*
* <ol>
* <li> File/run management ('OS:WeatherFile', WeatherFile)</li>
* <li> Output data integration ('OS:Facility', Facility)</li>
* <li> Radiance integration ('OS:Luminaire', Luminaire)</li>
* <li> HVAC abstractions ('OS:Node', Node)</li>
* <li> Data sharing ('OS:ComponentData', ComponentData, Component)</li>
* <li> Codes and standards support ('OS:ClimateZones', ClimateZones;
* 'OS:StandardsInforamtion:Building', BuildingStandardsInformation)</li>
* </ol>
*
* Each OpenStudio IDD object is wrapped by a corresponding ModelObject which provides an intelligent API for working
* with that data object in an OpenStudio Model.
*
* \link Model Models\endlink are serialized to files with the extension '.osm', which are
* instance files of the OpenStudio data schema. OSM files are clear text and look very similar
* to IDF.
*
* \subsection object_model Raison D'Etre: Object Model
*
* The last thing the building energy modeling community needs is yet another data model. So why
* did we create the OpenStudio Model?
*
* <b>To harness object-oriented programming techniques to provide a powerful interface for
* building energy modeling at all fidelity levels, for various software development and user
* communities.</b>
*
* By formalizing relationships among data objects (\ref modelobjectRelationships); and by placing
* high-level, big-knob methods in appropriate data objects (\ref modelobjectCompoundMethods); by
* making it possible to access related input and output data from the same location ( \ref
* modelobjectOutputDataAccessMethods); and by supporting multiple types of simulation engines,
* the OpenStudio Model provides a number of advantages over direct manipulation and analysis of
* EnergyPlus input and output formats.
*
* \subsection model_implementation Implementation Details
*
* Model serves as a container for \link ModelObject ModelObjects \endlink and a SqlFile. Model
* inherits its functionality for storing and querying objects from openstudio::Workspace, which is
* essentially an in-memory, custom database for openstudio::WorkspaceObject. The hierarchy of
* object types will be described in full in \ref object_implementation. For now it is important
* to note that all of Workspace's methods (listed in the utilities documentation) are also
* available to Model. Ideally, the underlying Workspace methods should only be called in model .cpp files; Model and ModelObject provides
* methods for adding and removing objects with more built in intelligence. However, the basic
* getters (e.g., getObjectByNameAndReference) and query methods (e.g., numObjects,
* numObjectsOfType) may be of general interest.
*
* Model is implemented using the pImpl (pointer to implementation) idiom. In this pattern, each
* public class (e.g. openstudio::model::Model) holds a pointer to an
* implementation class (e.g.
* openstudio::model::detail::Model_Impl) that actually holds the object data and implements its
* methods. The public classes forward almost all user requests to the implementation class. This
* idiom was adopted because it results in data sharing between copies of public class instances,
* without the need for exposed pointers; and because it provides consistency of interface across
* native C++ and the SWIG bindings. (At this time, the OpenStudio SDK is available in Ruby and
* C#, in addition to C++, by way of SWIG.)
*
* Example of data sharing:
*
* \code
* openstudio::path modelPath = toPath(pathString);
* OptionalModel oModel = Model::load(modelPath);
* if (oModel) {
* Model model = *oModel; // model accesses the same data as *oModel or oModel->
* Model anotherCopy = model; // anotherCopy accesses the same data as model
* Building buildingObject = model.getUniqueModelObject<Building>();
* // now all of these asserts will pass, because every copy of the model public object provides
* // access to the same Building object
* OS_ASSERT(model.numObjects() == 1u);
* OS_ASSERT(model.numObjects() == anotherCopy.numObjects());
* OS_ASSERT(model.numObjects() == oModel->numObjects());
* // the equality operator tests for whether two public objects point to the exact same
* // implementation object
* OS_ASSERT(buildingObject == anotherCopy.getUniqueModelObject<Building>());
* }
* \endcode
*
* \section modelobject What is a ModelObject?
*
* At its most basic, ModelObject is the OpenStudio class that represents an IDF object. Just
* like a text IDF object, it consists of a number of ordered string fields, some of which may be
* in extensible groups, and all of which conform to the corresponding IDD object. Please see the
* utilities IDD and IDF documentation (specifically openstudio::IddObject,
* openstudio::ExtensibleIndex, and openstudio::IdfObject) for more information. \link ModelObject
* ModelObjects \endlink are always owned by/live in a containing Model, which makes it possible
* for \link ModelObject ModelObjects \endlink to point to each other in a meaningful way, even
* when multiple \link Model Models \endlink are being operated on side-by-side.
*
* Although, strictly speaking, ModelObject provides access to its underlying string fields, a user
* of the OpenStudio SDK should not need to resort to that low-level interface in most
* circumstances. ModelObject is the base class for a large inheritance hierarchy, the terminating
* nodes of which each wrap a specific object in the OpenStudio IDD. Each data field that should
* be publicly accessible is wrapped into a getter and a setter method (see \ref
* modelobjectGetSet), several types of \ref modelobjectCompoundMethods and \ref
* modelobjectOutputDataAccessMethods are provided, as are object getters and setters appropriate
* to the various \ref modelobjectRelationships in the Model. Methods for creating and deleting
* data are also provided and available through a uniform interface, see \ref modelobjectKeyBehaviors.
*
* At this time, \link ModelObject ModelObjects \endlink are uniquely identifiable by their
* IddObjectType and name. \link ModelObject ModelObjects \endlink also have a unique handle that
* is available and used in memory, but is currently not serialized to file. A number of objects
* are unique in a given model. Unique objects may or may not have a name, as a name is not strictly
* necessary for identification. For example:
*
* \code
* Model model;
* Building building = model.getUniqueModelObject<Building>();
* OptionalString oName = building.name();
* OS_ASSERT(oName); // passes, because Building has a name
* Version version = model.getUniqueModelObject<Version>();
* oName = version.name();
* OS_ASSERT(!oName); // passes, because Version does not have (and does not need) a name
* \endcode
*
* ModelObjects of different types can share a name as long as they are not be in the same IDD
* reference list; ModelObjects of the same IddObjectType cannot.
*
* \subsection modelobjectGetSet Field Getters and Setters
*
* \todo The OpenStudio development team is currently in the process of fully implementing these
* coding standards.
*
* Every data field that the user should be able to directly manipulate (possibly with side effects,
* as in Lights::setLightingLevel), is exposed through getter and setter methods tailored to the
* specifics of that field as specified by the IDD. For instance, the IDD slash code '\\type real'
* results in getters and setters on double or boost::optional<double>. The name of the field
* is generated off of the IDD field name, keeping the names as close to the same as possible, but
* removing non-word characters, and transforming to lower camel case. Fields that point to other
* objects (\\type object-list) are not exposed in quite the same way, see
* \ref modelobjectRelationships.
*
* By maintaining the field names defined in the IDD, and by listing the name of the IDD object
* wrapped by a given ModelObject in each \link ConcreteModelObjects.hpp concrete object's\endlink
* documentation, we maintain a link with the EnergyPlus Input-Output reference for those \link
* ModelObject ModelObjects \endlink that directly or essentially wrap a particular EnergyPlus IDD
* object. We therefore do not provide detailed documentation for these methods, unless the field
* was introduced by the OpenStudio IDD. However, side effects, like multiple fields being touched
* by one setter, are documented.
*
* Data fields in extensible groups also have getters and setters, but may be exposed in different
* ways, for instance, in a getter that takes the extensible group's index as an argument
* (e.g., GasMixture::getGasType, GasMixture::setGasType), as part of a class that derives from
* ModelExtensibleGroup (e.g. ClimateZone), or through the introduction of a specialized data
* structure (e.g. PlanarSurface::vertices, PlanarSurface::setVertices). Classes that derive from
* ModelExtensibleGroup are generally preferred, as they let the extensible groups be dealt with
* on their own terms as individual objects. An exception to this is the case where there are just
* a few simple pieces of data in the group, then a small struct (like the one used by
* PlanarSurface::vertices) may be preferable. A ModelObject with a companion ModelExtensibleGroup
* should provide a wrapper method for numExtensibleGroups with the name of the ModelExtesibleGroup
* derived class replacing "ExtensibleGroups", and similar wrappers for getExtensibleGroup,
* extensibleGroups, clearExtensibleGroups and pushExtensibleGroup (perhaps replacing "push" with
* "add"), at a minimum.
*
* \todo Streamline the Idf and Workspace-level ExtensibleGroup interface and port any applicable
* changes over to Model.
*
* In general, we make the following translations from IDD slash codes to C++ syntax.
*
* \subsubsection allDataFields All Data Fields
*
* IDD fields that are '\\required' are provided in the object constructors, and are
* always returned by value (double, int, or std::string, as opposed to boost::optional<double>,
* boost::optional<int>, or boost::optional<std::string>, respectively), unless the field can accept
* different data types (as is the case with '\\autocalculatable' and '\\autosizable' fields). IDD
* fields with '\\default' values are also returned by value if the field can only accept one data
* type (e.g. it is not '\\autocalculatable' or '\\autosizable'). Note that some fields in the EnergyPlus
* IDD are marked as '\\required' and '\\default', this is logically inconsistent so these fields are treated
* as if they were marked only as '\\default' and not as '\\required'. It is preferable to mark fields as
* '\\default' in the OpenStudio IDD if there is a suitable default value instead of providing default
* arguments to the ModelObject constructor.
*
* If, the field is not required and does not have a default or the field can contain
* multiple data types (e.g. such as '\\autocalculatable' or '\\autosizable' fields), the return value is wrapped in a boost::optional. If such an optional
* return value evaluates to false, then there is no underlying data, and the user must not
* dereference the optional container. If the return value evaluates to true, the actual returned
* data may be accessed by dereferencing with '*' or '->', for example:
*
* \code
* Model model;
* Lights lights(model); // by default, sets lightingLevel to 0 W
* // OptionalDouble is typedef for boost::optional<double> provided in utilities/core/Optional.hpp
* OptionalDouble oLightingLevel = lights.lightingLevel();
* OS_ASSERT(oLightingLevel);
* double lightingLevel = *oLightingLevel; // or oLightingLevel.get()
* std::cout << "Default lighting level for a new Lights object is " << lightingLevel << " W.";
* \endcode
*
* If the user goes around the Model getter and setter methods by hand editing files or using the
* WorkspaceObject interface directly, it is possible to break the return-by-value getters, in
* which case a fatal error will be logged, and an openstudio::Exception will be thrown. To make it
* clear to a user when a default value is set (the underlying field is empty), fields with default
* values are provided with a query bool [fieldName]IsSetToDefault() const.
*
* If it is possible for a setter to fail, the setter will return a boolean to indicate success
* (true) or failure (false). Otherwise, the return type will be void, and the user can trust that
* the specified action will execute as expected.
*
* \subsubsection numericFields Numeric Fields
*
* Numeric fields are based on the C++ data types double (if '\\type real') or int (if
* '\\type integer'). The getters return a value if the field is required or has a numeric default, and is not
* '\\autocalculatable' or '\\autosizable'; and return an optional otherwise. The setters accept a
* double or int depending on the appropriate type. If the IDD specifies a minimum or maximum value then
* setter may fail and thus returns a bool; otherwise the set operation cannot fail and void is returned.
* If the field has a default, the user can check if the field is defaulted using [fieldName]IsSetToDefault,
* the user can set the field to default value using set[FieldName]ToDefault. If the field has can be autocalculated,
* the user can check if the field is autocalculated using [fieldName]IsSetToAutocalculate,
* the user can set the field to autocalculate using set[FieldName]ToAutocalculate.
*
* \todo Implement autosize/autocalculate getters and setters.
*
* \subsubsection choiceFields Choice Fields
*
* Fields of '\\type choice' are IDD defined enumerations. Originally, enum classes were used for choice fields.
* However, those classes greatly increased the size of the Model library. Therefore, the following rules were
* developed.
*
* If the IddKeys associated with
* a choice field are (case-insensitive) 'Yes'/'No', 'On'/'Off', or 'True'/'False'; then the OpenStudo getters and setters use bool
* values. Two additional methods 'std::string [fieldName]String() const' and 'bool set[FieldName]String(const std::string&)' are provided
* if the user needs to work with the string values. The general rules concerning getter return values, and setter return values apply to
* string versions of the field getters and setters. The general rules concerning default fields apply to the bool version of the getter and setter.
* However the bool setters cannot fail, and so always return void. Finally, if there is no default value and the field is not required
* the bool getter will return a boost::optional<bool> the user must be careful not to confuse whether this optional is initialized with
* the actual value of the field.
*
* Other choice fields operate solely off of std::string. The allowable values are case insensitive,
* defined by the IDD and exposed through static methods like Gas::validGasTypes(). The setters can
* always fail; whether a boost::optional<std::string> is returned by the getter or accepted by the
* setter conforms to the general rules.
*
* \todo Return OptionalString() for unset choice fields (rather than empty strings)?
*
* \subsubsection urlFields URL Fields
*
* The OpenStudio IDD introduces the '\\type url' field to help with locating files other than the
* OSM on which a simulation depends. (See WeatherFile for instance.)
* RunManager provides functionality to normalize url fields at job creation time. RunManager
* looks for the file across all URLSearchPaths (see utilities documentation) passed in to the
* job creation. In this process, if the referenced file can be found, RunManager ensures that the
* file is copied to the local computer running the job and that the url field is set to a valid
* absolute path to that file for all child jobs (the url field is unchanged in the original input
* Model). If the field immediately following a url field is named 'Checksum' and is of type alpha,
* that field contains a checksum (computed by openstudio::checksum()) that RunManager uses to
* verify that the file found is the desired file. External files may be referenced using url
* fields in several ways:
*
* \li The url field may contain a single file name (e.g. 'Chicago.epw'). URLSearchPaths are used
* to look for relative urls and may be specified as relative to the job's working directory
* or to the original input Model.
*
* \li The url field may contain a relative file path (e.g. '../../Chicago.epw'). URLSearchPaths
* are used to look for relative urls and may be specified as relative to the job's working
* directory or to the original input Model.
*
* \li The url field may contain an absolute file path (e.g. 'C:/weatherData/Chicago.epw' or
* '/weatherData/Chicago.epw'). URLSearchPaths are not used to look for absolute file paths.
*
* \li The url field may contain an absolute url (e.g. 'file://C:/weatherData/Chicago.epw' or
* 'http://www.weatherdata.org/Chicago.epw'). URLSearchPaths are not used to look for absolute
* urls.
*
* \li The url field may contain the UUID of a file in a Building Component Library (e.g.
* '{550e8400-e29b-41d4-a716-446655440000}'). (This is not yet implemented).
*
* Url fields are implemented with three overloaded set methods which each return void; one taking
* a string, one taking an openstudio::path, and one taking a QUrl. The get method returns a
* string. Normal rules for required and default fields apply.
*
* \subsubsection otherFields Other Fields
*
* All other types of fields ('\\type alpha' or '\\type external-list') are treated as strings and
* conform to the general rules.
*
* \todo Return OptionalString() for unset string fields (rather than empty strings)?
*
* An extended example of data field getter and setter usage:
*
* \code
* Model model;
* ScheduleCompact scheduleCompact(model);
*
* //the curve
* CurveBiquadratic ccFofT(model);
* CurveBiquadratic eirFofT(model);
* CurveQuadratic ccFofF(model);
* CurveQuadratic eirFofF(model);
* CurveQuadratic plf(model);
*
* ccFofT.setCoefficient1Constant(1.0);
* ccFofT.setCoefficient2x(2.0);
* ccFofT.setCoefficient3xPOW2(3.0);
* ccFofT.setCoefficient4y(4.0);
* ccFofT.setCoefficient5yPOW2(5.0);
* ccFofT.setCoefficient6xTIMESY(6.0);
* ccFofT.setMinimumValueofx(-10.0);
* ccFofT.setMaximumValueofx(100.03);
* ccFofT.setMinimumValueofy(-99999);
* ccFofT.setMaximumValueofy(100232);
* ccFofT.setMinimumCurveOutput(-1000);
* ccFofT.setMaximumCurveOutput(99999);
* ccFofT.setInputUnitTypeforX("Temperature");
* ccFofT.setOutputUnitType("MassFlow");
*
* CoilCoolingDXSingleSpeed cool(model,
* scheduleCompact,
* ccFofT,
* ccFofF,
* eirFofT,
* eirFofF,
* plf);
*
* Schedule s = cool.getAvailabilitySchedule();
* OS_ASSERT(s == scheduleCompact)
* OptionalDouble od;
* cool.setRatedTotalCoolingCapacity(od); // set to "AutoCalculate"
*
* // this passes because the constructor set it to "AirCooled"for you.
* OS_ASSERT(cool.getCondenserType() == "AiRCoolEd")
*
* OptionalSchedule s2 = cool.getBasinHeaterOperatingSchedule();
* OS_ASSERT(!s2)
* // s2 evaluates to false because this schedule is not required and not set
* \endcode
*
* \subsection modelobjectCompoundMethods Compound Methods
*
* OpenStudio \link ModelObject ModelObjects \endlink provide "big knob" compound methods to enable
* high-level modeling and various types of analysis (perturbation, optimization, standards, etc.)
* For example, Space::lightingPowerPerFloorArea calculates lighting power in the space by adding up
* lighting power from all Lights and Luminaire objects directly assigned to the space or it's space type,
* then dividing by the floor area of these space. Furthermore,
* that method, and the Space compound "getter" that corresponds to it are wrapped up together in
* an Attribute named "lightingPowerDensity" available through the ModelObject::getAttribute
* interface.
*
* PlanarSurface::uFactor and PlanarSurface::setUFactor (and the associated Attribute) is another
* example that brings a lot of pieces together to expose a high-level piece of data. Depending on
* the underlying construction type, these methods may operate directly on a SimpleGlazing object;
* may use static film resistance data in conjunction with one or more Material objects, and maybe
* a ConstructionBaseStandardsInformation object (the latter is sometimes needed for the u-factor
* setter); or may query the output data in the SqlFile. If u-factor is available through input and
* output data, the output data is returned, but in the meantime the two values are compared and a
* message is logged if their difference exceeds some tolerance. Related methods are available
* through ConstructionBase.
*
* Several objects include a number of methods (some static) provided to give the user access to
* basic physical information used in EnergyPlus or in building energy standards. The film
* resistances alluded to above are available through PlanarSurface::filmResistance and
* PlanarSurface::stillAirFilmResistance. Physical properties of gases commonly found in
* multi-paned windows are available from FenestrationMaterial.
*
* Overall, the compound methods are difficult to characterize as a whole. We encourage users to
* peruse the documentation for each individual object in which they have an interest. Compound
* methods are generally listed outside of the "Getters" and "Setters" sections, even though some
* methods' functionality will be similar to a get or a set. In general, these methods should be
* well documented since they are native to OpenStudio.
*
* \subsection modelobjectOutputDataAccessMethods Output Data Access Methods
*
* The model.setSqlFile(const SqlFile& sqlFile) method is used to attach a Model to related EnergyPlus
* simulation output. Because the OpenStudio Model must be translated to EnergyPlus IDF for simulation, the
* results of the EnergyPlus simulation will not map exactly to the Model. However, the Model will perform
* some checks to verify that the given SqlFile does relate to the given Model, the setSqlFile operation will
* fail if these checks are not satisfied. If model.sqlFile() evaluates to true, then a given model is hooked
* up to its EnergyPlus simulation output data in the form of a SQLite file, and a number of ways to retrieve output data become
* active.
*
* \li \link Meter Meters \endlink provide access to related data once the SqlFile is attached. Meters
* may be present at the Facility, Building, ThermalZone, System, and Plant levels.
*
* \li Every concrete ModelObject must implement the method \link ModelObject::outputVariables
* outputVariables() \endlink. With the SqlFile attached, the TimeSeries (see the utilities
* documentation) associated with those \link OutputVariable OutputVariables \endlink may be
* retrieved, given an appropriate environment period string (see SimulationControl).
*
* \li High level simulation results are available through methods of appropriate ModelObjects.
*
* \li When possible, calculation of a result (e.g. floorArea) from the input data only is preferred to
* requiring simulation output be attached to the Model. In these cases, the method always
* computes its value from input data alone, the method does not check simulation results.
* At least one unit test ensures that the value calculated from input data matches the value in the
* simulation results.
*
* \li Results which require simulation to report (e.g. annualNetSiteEnergy) return an uninitialized optional value
* unless a valid SqlFile is attached. Results that are not specific to a particular environment period (e.g. u-factor) may be accessed
* without specifying an environment period. Results that are specific to a particular environment period (e.g. totalLightingEnergy) require
* the environment period to report results as an input. Results that presume an annual simulation or some other condition
* (e.g. annualNetSiteEnergy presumes the presence of one and only one annual simulation run period) do not require
* an environment period as an input but return an uninitialized optional value if that condition is not met.
*
* \li Finally some virtual methods may be implemented by some concrete classes to require output data but by other classes
* to not require output data. For instance,
* PlanarSurface::uFactor may require simulation data in order to return an actual value,
* depending on the exact construction type. (And the u-factor may not be available at all if output data is required
* and the surface is not adjacent to the outside environment.) In this case, the operation of any specific class always uses either
* input or output data, the user must refer to the documentation for the specific derived types to understand how the virtual method
* will operate in all situations.
*
* The connection to the SqlFile can be reset using model.resetSqlFile(). Closing the SqlFile connection is necessary in order
* to resimulate the Model using EnergyPlus.
*
* \subsection modelobjectRelationships Relationships
*
* There are three primary types of relationships among \link ModelObject ModelObjects\endlink:
* Parent-Child, Resource-ResourceUser, and (HVAC) Connection.
*
* The Parent-Child relationship is used to represent containment relationships in the building.
* For example, Building parents Space, which parents a number of objects including Lights, People, and
* ElectricEquipment. If a ParentObject is removed,
* its children (and on down the line recursively to grandchildren, etc.) should also
* be removed; and if a ParentObject is cloned (copied), its children (recursively) should also
* be cloned.
*
* In addition to helping define behaviors, the Parent-Child relationship is useful for model
* visualization and navigation. Navigating using ModelObject::parent() and ParentObject::children()
* in a Ruby script, for instance, can give the user intuition about how the various aspects of a
* Model conceptually fit together in OpenStudio and EnergyPlus.
*
* A ResourceObject is a ModelObject that can be used by multiple other data objects. For instance,
* unlike a Lights object which can only be associated with one Space or SpaceType, a Schedule can be used by
* any number of objects, so long as the data type of the Schedule (fractional, on/off,
* temperature, etc.) is appropriate for the context. Every ModelObject can return the \link
* ResourceObject ResourceObjects \endlink that is uses with the method ModelObject::resources().
* \link ResourceObject ResourceObjects \endlink can report their use counts, see
* ResourceObject::directUseCount and ResourceObject::nonResourceObjectUseCount. Unused resources
* can be removed in one fell swoop with Model::purgeUnusedResourceObjects.
*
* Unlike children, resources are meant to be shared, so they are not removed when a user of the
* resource is removed, and they are not automatically cloned when one of their users is cloned
* (see \ref modelobjectKeyBehaviors).
*
* Parents, children and resources are available through generic and typed interfaces. For
* instance, Building::children() will return all of the \link Space Spaces \endlink in a
* std::vector<ModelObject>, and Building also has a method \link Building::spaces() spaces()
* \endlink that returns the same data as a std::vector<Space>. The Schedule associated with a
* Lights object can be found through the std::vector<ResourceObject> returned by
* Schedule::resources(), and also through the method Lights::schedule(). Lights also has the
* method \link Lights::setSchedule setSchedule(const Schedule&) \endlink.
*
* Connections join multiple ModelObjects together via designated points called ports. Connections
* between ModelObjects are directional and they are created by identifying a source ModelObject and port
* as well as a target ModelObject object and port. Once a connection is made, it is easy to access the ModelObject
* connected to a particular port using ModelObject::connectedObject. New Connections are made using the
* openstudio::model::Model::connect function.
*
* ModelObject connections are similar to EnergyPlus nodes, however a connection between ports is
* more general than a node connection in Energyplus. In the OpenStudio model, connections serve
* the same role as nodes in EnergyPlus, but OpenStudio connections can be applied in contexts other
* than the EnergyPlus system nodes. OpenStudio's connections and ports can be used any time one
* ModelObject can be arbitrarily connected to another ModelObject. For example, EnergyPlus EMS
* sensors and actuators could be thought of as source and target ports, and a connection could be
* made between the two.
*
* \subsection modelobject_hierachy Parent-Child Hierarchy
*
* As described above, objects in the OpenStudio Model can be organized into a tree (actually a
* forest) by linking ModelObject types based on their Parent-Child relationships. The following
* is a complete listing of the concrete \link ModelObject ModelObjects \endlink displayed in
* Parent-Child hierarchical form. The immediate base class of each object is listed in
* parentheses. Some object types are listed more than once because they can be the child of
* multiple concrete types (in which case the Parent-Child relationship is often defined by an
* abstract base class). If the class name is somewhat different from the IddObjectType valueName,
* the name of the IDD object is also listed for reference.
*
* <ul>
* <li> Version (ModelObject, unique)
* <li> Site (ParentObject, unique) – wraps 'Site:Location'
* <ul>
* <li> ClimateZones (ModelObject, unique)
* <li> DesignDay (SizingPeriod) – wraps 'SizingPeriod:DesignDay'
* <ul>
* <li> SkyTemperature (ModelObject) – wraps 'OS:WeatherProperty:SkyTemperature'
* </ul>
* <li> LightingDesignDay (ModelObject)
* <li> SkyTemperature (ModelObject) – wraps 'OS:WeatherProperty:SkyTemperature'
* <li> SiteGroundReflectance (ModelObject, unique)
* <li> SiteGroundTemperatureBuildingSurface (ModelObject, unique)
* <li> SiteWaterMainsTemperature (ModelObject, unique)
* <li> WeatherFile (ModelObject, unique)
* <li> WeatherFileConditionType (SizingPeriod)
* <ul>
* <li> SkyTemperature (ModelObject) – wraps 'OS:WeatherProperty:SkyTemperature'
* </ul>
* <li> WeatherFileDays (SizingPeriod)
* <ul>
* <li> SkyTemperature (ModelObject) – wraps 'OS:WeatherProperty:SkyTemperature'
* </ul>
* <li> ShadingSurfaceGroup (PlanarSurfaceGroup)
* <ul>
* <li>ShadingSurface (PlanarSurface)
* </ul>
* </ul>
* <li> YearDescription (ParentObject, unique)
* <ul>
* <li> RunPeriodControlSpecialDays (ModelObject)
* <li> RunPeriodControlDaylightSavingTime (ModelObject, unique)
* </ul>
* <li> SimulationControl (ParentObject, unique)
* <ul>
* <li> Timestep (ModelObject, unique)
* <li> RunPeriod (ParentObject)
* <ul>
* <li> SkyTemperature (ModelObject) – wraps 'OS:WeatherProperty:SkyTemperature'
* </ul>
* <li> ConvergenceLimits (ModelObject, unique)
* <li> ShadowCalculation (ModelObject, unique)
* <li> HeatBalanceAlgorithm (ModelObject, unique)
* <li> InsideSurfaceConvectionAlgorithm (ModelObject, unique)
* <li> OutsideSurfaceConvectionAlgorithm (ModelObject, unique)
* <li> SizingParameters (ModelObject, unique)
* <li> ZoneAirContaminantBalance (ModelObject, unique)
* <li> ZoneAirHeatBalanceAlgorithm (ModelObject, unique)
* <li> ZoneCapacitanceMultiplierResearchSpecial (ModelObject, unique)
* </ul>
* <li> LightingSimulationControl (ModelObject)
* <li> Facility (ParentObject, unique)
* <ul>
* <li> Meter (ModelObject)
* <li> ExteriorLights (ExteriorLoadInstance)
* <li> ExteriorFuelEquipment (ExteriorLoadInstance)
* <li> ExteriorWaterEquipment (ExteriorLoadInstance)
* <li> Building (ParentObject, unique)
* <ul>
* <li> BuildingStandardsInformation (ModelObject, unique)
* <li> Meter (ModelObject)
* <li> BuildingStory (ModelObject)
* <li> ShadingSurfaceGroup (PlanarSurfaceGroup)
* <ul>
* <li> ShadingSurface (PlanarSurface)
* </ul>
* <li> Space (PlanarSurfaceGroup)
* <ul>
* <li> ShadingSurfaceGroup (PlanarSurfaceGroup)
* <ul>
* <li> ShadingSurface (PlanarSurface)
* </ul>
* <li> InteriorPartitionSurfaceGroup (PlanarSurfaceGroup)
* <ul>
* <li> InteriorPartitionSurface (PlanarSurface)
* </ul>
* <li> Surface (PlanarSurface)
* <ul>
* <li> SubSurface (PlanarSurface)
* <ul>
* <li> DaylightingDeviceShelf (ModelObject)
* </ul>
* </ul>
* <li> ElectricEquipment (SpaceLoadInstance)
* <li> GasEquipment (SpaceLoadInstance)
* <li> HotWaterEquipment (SpaceLoadInstance)
* <li> SteamEquipment (SpaceLoadInstance)
* <li> OtherEquipment (SpaceLoadInstance)
* <li> InternalMass (SpaceLoadInstance)
* <li> Lights (SpaceLoadInstance)
* <li> Luminaire (SpaceLoadInstance)
* <li> People (SpaceLoadInstance)
* <li> SpaceInfiltrationDesignFlowRate (SpaceLoad)
* <li> SpaceInfiltrationEffectiveLeakageArea (SpaceLoad)
* <li> DaylightingControl (SpaceItem)
* <li> IlluminanceMap (SpaceItem)
* <li> GlareSensor (SpaceItem)
* </ul>
* <li> ThermalZone (HVACComponent)
* </ul>
* </ul>
* <li> AirLoopHVAC (Loop)
* <li> PlantLoop (Loop)
* <li> AirLoopHVACZoneSplitter (Splitter)
* <li> AirLoopHVACZoneMixer (Mixer)
* <li> ConnectorSplitter (Splitter)
* <li> ConnectorMixer (Mixer)
* <li> Connection (ModelObject)
* <li> SizingZone (ModelObject)
* <li> SizingSystem (ModelObject)
* <li> ThermostatSetpointDualSetpoint (ModelObject)
* <li> AvailabilityManagerScheduled (ParentObject)
* <li> ControllerMechanicalVentilation (ParentObject)
* <li> AirLoopHVACOutdoorAirSystem (HVACComponent)
* <ul>
* <li> ControllerOutdoorAir (ParentObject)
* </ul>
* <li> ControllerWaterCoil (HVACComponent)
* <li> Node (StraightComponent)
* <ul>
* <li> SetpointManagerSingleZoneReheat (HVACComponent)
* <li> SetpointManagerScheduled (HVACComponent)
* <li> SetpointManagerMixedAir (HVACComponent)
* </ul>
* <li> AirLoopHVACUnitaryHeatPumpAirToAir (StraightComponent)
* <ul>
* <li> (HVACComponent)
* </ul>
* <li> AirTerminalSingleDuctParallelPIUReheat (StraightComponent)
* <ul>
* <li> (HVACComponent)
* </ul>
* <li> AirTerminalSingleDuctUncontrolled (StraightComponent)
* <li> AirTerminalSingleDuctVAVReheat (StraightComponent)
* <li> FanConstantVolume (StraightComponent)
* <li> FanVariableVolume (StraightComponent)
* <li> CoilHeatingGas (StraightComponent)
* <li> EvaporativeCoolerDirectResearchSpecial (StraightComponent)
* <li> CoilHeatingDXSingleSpeed (StraightComponent)
* <ul>
* <li> (Curve)
* </ul>
* <li> CoilCoolingDXSingleSpeed (StraightComponent)
* <ul>
* <li> (Curve)
* </ul>
* <li> CoilCoolingDXTwoSpeed (StraightComponent)
* <ul>
* <li> (Curve)
* </ul>
* <li> CoilHeatingElectric (StraightComponent)
* <li> PumpVariableSpeed (StraightComponent)
* <ul>
* <li> (Curve)
* </ul>
* <li> BoilerHotWater (StraightComponent)
* <ul>
* <li> (Curve)
* </ul>
* <li> CoilCoolingWater (WaterToAirComponent)
* <li> CoilHeatingWater (WaterToAirComponent)
* <li> ZoneHVACFourPipeFanCoil (ZoneHVACComponent)
* <ul>
* <li> (HVACComponent)
* </ul>
* <li> ZoneHVACPackagedTerminalAirConditioner (ZoneHVACComponent)
* <ul>
* <li> (HVACComponent)
* </ul>
* <li> ZoneHVACPackagedTerminalHeatPump (ZoneHVACComponent)
* <ul>
* <li> (HVACComponent)
* </ul>
* <li> CurveBicubic (Curve)
* <li> CurveBiquadratic (Curve)
* <li> CurveCubic (Curve)
* <li> CurveDoubleExponentialDecay (Curve)
* <li> CurveExponent (Curve)
* <li> CurveExponentialDecay (Curve)
* <li> CurveExponentialSkewNormal (Curve)
* <li> CurveFanPressureRise (Curve)
* <li> CurveFunctionalPressureDrop (Curve)
* <li> CurveLinear (Curve)
* <li> CurveQuadratic (Curve)
* <li> CurveQuadraticLinear (Curve)
* <li> CurveQuartic (Curve)
* <li> CurveRectangularHyperbola1 (Curve)
* <li> CurveRectangularHyperbola2 (Curve)
* <li> CurveSigmoid (Curve)
* <li> CurveTriquadratic (Curve)
* <li> LightingSimulationZone (ModelObject)
* <li> ScheduleTypeLimits (ResourceObject)
* <li> ScheduleConstant (Schedule)
* <li> ScheduleCompact (Schedule)
* <li> ScheduleRuleset (Schedule)
* <ul>
* <li> ScheduleDay (ScheduleBase)
* <li> ScheduleRule (ParentObject)
* <ul>
* <li> ScheduleDay (ScheduleBase)
* </ul>
* </ul>
* <li> ScheduleYear (Schedule)
* <li> ScheduleWeek (ResourceObject)
* <li> ScheduleDay (ScheduleBase)
* <li> ScheduleVariableInterval (ScheduleInterval)
* <li> ScheduleFixedInterval (ScheduleInterval)
* <li> DefaultScheduleSet (ResourceObject)
* <li> Construction (LayeredConstruction)
* <ul>
* <li> ConstructionBaseStandardsInformation (ModelObject) – wraps 'OS:StandardsInformation:%Construction'
* </ul>
* <li> ConstructionWithInternalSource (LayeredConstruction) – wraps 'OS:%Construction:InternalSource'
* <ul>
* <li> ConstructionBaseStandardsInformation (ModelObject) – wraps 'OS:StandardsInformation:%Construction'
* </ul>
* <li> CFactorUndergroundWallConstruction (ConstructionBase) – wraps 'OS:%Construction:CfactorUndergroundWall'
* <ul>
* <li> ConstructionBaseStandardsInformation (ModelObject) – wraps 'OS:StandardsInformation:%Construction'
* </ul>
* <li> FFactorGroundFloorConstruction (ConstructionBase) – wraps 'OS:%Construction:FfactorGroundFloor'
* <ul>
* <li> ConstructionBaseStandardsInformation (ModelObject) – wraps 'OS:StandardsInformation:%Construction'
* </ul>
* <li> WindowDataFile (ConstructionBase) – wraps 'OS:%Construction:%WindowDataFile'
* <ul>
* <li> ConstructionBaseStandardsInformation (ModelObject) – wraps 'OS:StandardsInformation:%Construction'
* </ul>
* <li> DefaultConstructionSet (ResourceObject)
* <li> DefaultSubSurfaceConstructions (ResourceObject)
* <li> DefaultSurfaceConstructions (ResourceObject)
* <li> StandardOpaqueMaterial (OpaqueMaterial) – wraps 'OS:%Material'
* <li> MasslessOpaqueMaterial (OpaqueMaterial) – wraps 'OS:%Material:NoMass'
* <li> Gas (GasLayer) – wraps 'OS:WindowMaterial:%Gas'
* <li> GasMixture (GasLayer) – wraps 'OS:WindowMaterial:%GasMixture'
* <li> InfraredTransparentMaterial (ModelPartitionMaterial) – wraps 'OS:%Material:InfraredTransparent'
* <li> AirWallMaterial (ModelPartitionMaterial) – wraps 'OS:%Material:AirWall'
* <li> Shade (ShadingMaterial) – wraps 'OS:WindowMaterial:%Shade'
* <li> Screen (ShadingMaterial) – wraps 'OS:WindowMaterial:%Screen'
* <li> Blind (ShadingMaterial) – wraps 'OS:WindowMaterial:%Blind'
* <li> AirGap (OpaqueMaterial) – wraps 'OS:%Material:%AirGap'
* <li> RoofVegetation (OpaqueMaterial) – wraps 'OS:%Material:%RoofVegetation'
* <li> StandardGlazing (Glazing) – wraps 'OS:WindowMaterial:%Glazing'
* <li> SimpleGlazing (Glazing) – wraps 'OS:WindowMaterial:SimpleGlazingSystem'
* <li> ThermochromicGlazing (Glazing) – wraps 'OS:WindowMaterial:GlazingGroup:Thermochromic'
* <li> RefractionExtinctionGlazing (Glazing) – wraps 'OS:WindowMaterial:Glazing:RefractionExtinctionMethod'
* <li> SpaceType (ResourceObject)
* <ul>
* <li> ElectricEquipment (SpaceLoadInstance)
* <li> GasEquipment (SpaceLoadInstance)
* <li> HotWaterEquipment (SpaceLoadInstance)
* <li> SteamEquipment (SpaceLoadInstance)
* <li> OtherEquipment (SpaceLoadInstance)
* <li> InternalMass (SpaceLoadInstance)
* <li> Lights (SpaceLoadInstance)
* <li> Luminaire (SpaceLoadInstance)
* <li> People (SpaceLoadInstance)
* <li> SpaceInfiltrationDesignFlowRate (SpaceLoad)
* <li> SpaceInfiltrationEffectiveLeakageArea (SpaceLoad)
* </ul>
* <li> RenderingColor (ResourceObject)
* <li> ElectricEquipmentDefinition (SpaceLoadDefinition)
* <li> GasEquipmentDefinition (SpaceLoadDefinition)
* <li> HotWaterEquipmentDefinition (SpaceLoadDefinition)
* <li> SteamEquipmentDefinition (SpaceLoadDefinition)
* <li> OtherEquipmentDefinition (SpaceLoadDefinition)
* <li> InternalMassDefinition (SpaceLoadDefinition)
* <li> LightsDefinition (SpaceLoadDefinition)
* <li> LuminaireDefinition (SpaceLoadDefinition)
* <li> PeopleDefinition (SpaceLoadDefinition)
* <li> ExteriorLightsDefinition (ExteriorLoadDefinition)
* <li> ExteriorFuelEquipmentDefinition (ExteriorLoadDefinition)
* <li> ExteriorWaterEquipmentDefinition (ExteriorLoadDefinition)
* <li> DesignSpecificationOutdoorAir (ResourceObject)
* <li> CurrencyType (ParentObject)
* <li> LifeCycleCost_UsePriceEscalation (ParentObject)
* <li> LifeCycleCost_UseAdjustment (ParentObject)
* <li> LifeCycleCost_Parameters (ParentObject)
* <li> ComponentCost_Adjustments (ParentObject)
* <li> ComponentCost_Reference (ParentObject)
* <li> UtilityCost_Tariff (ParentObject)
* <ul>
* <li> UtilityCost_Qualify (ParentObject)
* <li> UtilityCost_Charge_Simple (ParentObject)
* <li> UtilityCost_Charge_Block (ParentObject)
* <li> UtilityCost_Ratchet (ParentObject)
* <li> UtilityCost_Variable (ParentObject)
* <li> UtilityCost_Computation (ParentObject)
* </ul>
* </ul>
*
* Special Cases that can be Parented by many \link ModelObject ModelObjects \endlink
*
* <ul>
* <li> OutputVariable (ModelObject)
* <li> ComponentCost_LineItem (ModelObject)
* <li> LifeCycleCost_RecurringCosts (ParentObject)
* <li> LifeCycleCost_NonrecurringCost (ParentObject)
* </ul>
*
* Special Cases related to the Building Component Library
*
* <ul>
* <li> ComponentData (ParentObject)</li>
* </ul>
*
* \subsection modelobjectKeyBehaviors Key Behaviors
*
* \subsubsection newmodel Create a New Model
*
* There are four constructors available for Model. The default constructor creates a new Model
* with a single Version object in it. Version objects are not returned by Model::objects or
* counted by Model::numObjects.
*
* \code
* Model model;
* OS_ASSERT(model.versionObject());
* OS_ASSERT(model.numObjects() == 0u);
* OS_ASSERT(model.iddFileType() == IddFileType::OpenStudio);
* OS_ASSERT(model.strictnessLevel() == StrictnessLevel::Draft);
* \endcode
*
* The preferred method for creating a Model from an OSM file is
*
* \code
* OptionalModel oModel = Model::load(modelFilePath);
* if (!oModel) { LOG_AND_THROW("Unable to open '" << toString(modelFilePath) << "'."); }
* Model model = *oModel;
* \endcode
*
* UNLESS that OSM file might be from an old version of OpenStudio, in which case the version
* translator should be used:
*
* \code
* osversion::VersionTranslator translator;
* OptionalModel oModel = translator.loadModel(modelFilePath);
* if (!oModel) {
* LOG_AND_THROW("Unable to open and translate '" << toString(modelFilePath) << "'.");
* }
* Model model = *oModel;
* \endcode
*
* The preferred method for creating a Model from IDF file is
*
* \code
* #include <energyplus/ReverseTranslator.hpp>
*
* OptionalModel oModel = energyplus::loadAndTranslateIdf(idfFilePath);
* \endcode
*
* In addition, constructors are provided from IdfFile and Workspace (see the utilities
* documentation). Those constructors will throw if IdfFile or Workspace uses the wrong IDD file.
*
* Because Model is required to support partial (unsimulatable) building models for data
* sharing, and to provide a flexible interface for editing, it is ultimately up to the user to
* ensure that a Model is ready for simulation. Model::validityReport and similar methods (see
* the utilities documentation, especially Workspace::validityReport,
* WorkspaceObject::validityReport, and ValidityEnums.hpp) are provided to help users bring their
* models up to the standard set by the IDD. (And there are a few places in Model where validity
* checking goes beyond the data schema to rules internal to EnergyPlus, see for instance
* LayeredConstruction::layersAreValid, which is used by the virtual implementation of
* validityReport for \link LayeredConstruction LayeredConstructions \endlink.) Beyond that, users
* will sometimes need to go through an iterative process of modeling, trying to run EnergyPlus
* (or another simulation engine), addressing simulation errors, etc.
*
* \subsubsection newmodelobject Create a New ModelObject
*
* Every concrete ModelObject has one or more public constructors, unless
* it is marked unique by the IDD. In this case, there is no public constructor in order to
* prevent the accidental construction of multiple instance of that type in the same model. Instead,
* these objects are made available through Model::getUniqueModelObject and
* Model::getOptionalUniqueModelObject:
*
* \code
* Model model;
*
* // getOptionalUniqueModelObject only returns an object if it is already in the Model.
* // It constructs any new objects.
* OptionalBuilding oBuilding = model.getOptionalUniqueModelObject<Building>();
* OS_ASSERT(!oBuilding);
* OS_ASSERT(model.numObjects() == 0u);
*
* // getUniqueModelObject constructs the object if it is not yet present.
* Building building = model.getUniqueModelObject<Building>();
* OS_ASSERT(model.numObjects() == 1u);
*
* // now getOptionalUniqueModelObject can return the object that was just created
* oBuilding = model.getOptionalUniqueModelObject<Building>();
* OS_ASSERT(oBuilding);
* OS_ASSERT(model.numObjects() == 1u);
* OS_ASSERT(oBuilding.get() == building);
* \endcode
*
* For non-unique objects, all public constructors will ensure that required fields, children,
* and resources are present as a post-condition. Depending on the constructor, the user may be
* required to explicitly provide those objects, or they may be default constructed. For example
* the LightsDefinition object is a required argument to the Lights object constructor. Parents
* are often not required by the public constructors; as appropriate, convenience constructors
* that take the parent as an argument may be provided. (Orphan construction is allowed in order
* to better support data sharing. For instance, if someone wants to create a lighting component
* for the Building Component Library, requiring Lights to be constructed with a Space or
* SpaceType would be inconvenient.)
*
* \subsubsection removemodelobject Delete a ModelObject
*
* ModelObject::remove is used to remove a ModelObject from a Model. When a model object is
* removed, all of its children are also removed. Objects related to the removed object through
* a resource or connection relationship are not deleted. Resources persist so they can be used
* by other objects. Connections are broken by object removal, but the adjacent object is left
* behind, unless it happens to also be a child of the removed object. However, when a resource or
* child object is removed, its user objects or parents may also be removed, if the relationship
* is a required one for the user/parent. For instance, SpaceLoadDefinition::remove also removes
* all of its SpaceLoadDefinition::instances, since a SpaceLoadInstance cannot exist without its
* definition.
*
* For all deleted objects, when all the instances of that object go out of scope and stop
* referencing the shared implementation pointer, the memory will be automatically freed for you.
*
* \subsubsection clonemodelobject Clone a ModelObject
*
* ModelObject::clone is used to duplicate a ModelObject. The clone method may be used to copy
* an object into another model, or to duplicate an object in the same model. The act of cloning
* an object will change the duplicate object's name if an object of the same type and name
* already exists in the target model. Therefore, cloning into the same model will always result
* in name change for the duplicate so as to avoid a name collision with the original object.
* Cloning a ModelObject also clones all of its children (recursively). Resources are cloned as
* necessary (when an equivalent object cannot be located, see IdfObject::dataFieldsEqual and
* IdfObject::managedObjectListFieldsNonConflicting in the utilities documentation) when the
* original and target models are different.
*
* Examples:
* \code
* LightsVector originalLights = space.lights();
* clonedSpace= space.clone(space.model());
* LightsVector clonedLights = clonedSpace.lights();
* OS_ASSERT(originalLights.size() == clonedLights.size())
*
* if (originalLights.size() > 0) {
* LightVector::iterator i = std::find(originalLights.begin(),originalLights.end(),clonedLights[0]);
* OS_ASSERT(i == originalLights.end()); // clonedLights[0] not found in originalLights
* // (std::find uses ==, which for ModelObjects checks
* // to see if the objects point to the exact same
* // implementation object)
* }
* \endcode
*
* The following code would also pass its OS_ASSERTs. Because we cloned into the same model, the
* schedule (a ResourceObject) was NOT cloned.
*
* \code
* // continuing from above
*
* if (originalLights.size() > 0) {
* // originalLights[0] and clonedLights[0] share the exact same schedule ...
* // ... == verifies it.
* OS_ASSERT(originalLights[0].schedule() == clonedLights[0].schedule());
* // ... as does making a change in clonedLights[0].schedule()
* clonedLights[0].schedule().setName("Some Cool Name")
* // ... and then looking for the change in originalLights[0].schedule().
* OS_ASSERT(originalLights[0].schedule().name().get() == "Some Cool Name")
* }
* \endcode
*
* \subsection object_implementation Implementation Details
*
* Similar to Model inheriting from openstudio::Workspace, ModelObject inherits from
* openstudio::WorkspaceObject, which in turn inherits from openstudio::IdfObject. Briefly,
* IdfObject corresponds to a single data object in an IDF file. It has an IddObject, which defines
* its type, and it otherwise consists of a vector (ordered list) of string fields, accessible by
* index and with an optional user comment. (If you never specify an IDF field comment, default
* comments are generated for you from the IddField::name()'s.) WorkspaceObject provides the added
* functionality of turning the '\\type object-list' fields that in clear text point to other data
* objects by name reference into bi-directional, name-independent pointers to particular objects.
* Please see the utilities/idf documentation for more information.
*
* In this way, IdfObject, WorkspaceObject, and Workspace form the underlying data model used by
* OpenStudio to represent a single building (assuming the OpenStudio, rather than the EnergyPlus
* or other, IDD is referenced). Model, ModelObject and everything else in the openstudio::model
* namespace exists to turn that data model into a full-featured object model.
*
* Because Model and ModelObject publicly inherit from Workspace and WorkspaceObject, methods of
* Workspace and WorkspaceObject are directly available for use through Model and ModelObject.
* Use of these methods is discouraged where it is not necessary as these data model-level
* modifications bypass the best-practice logic built into classes derived from ModelObject.
*
* \link ModelObject ModelObjects \endlink (and WorkspaceObjects and IdfObjects) also use the
* pImpl idiom described \ref model_implementation "above". So basic copying
* and assignment results in data sharing, for example:
*
* \code
* Space spaceA(model);
* spaceA.setName("Space A");
* OS_ASSERT(spaceA.name().get() == "Space A");
* Space spaceB = spaceA;
* spaceB.setName("Space B");
* OS_ASSERT(spaceA.name().get() == "Space B"); // may not be the intended behavior ...
* // use clone() to get a deep copy
*
* // Sharing also happens just by passing objects around as arguments.
* // For instance, this function takes a non-const copy, it does not pass by reference.
* void changeName(ModelObject object) {
* object.setName("New Name");
* }
*
* Space spaceC(model);
* // function looks like all changes are local to it ...
* changeName(spaceC);
* // ... but they are not because of pImpl.
* OS_ASSERT(spaceC.name().get() == "New Name");
* \endcode
*
* The pointer to the implementation is managed by a reference counting pointer, so the
* implementation object is destroyed when the last wrapper class goes out of scope. Because the
* implementation is shared between copies of the public class, Qt signal and slot connections will
* remain active after the public object is destroyed provided that another object still references
* the same implementation. Note that at the very least this other object is typically the Model
* of which the ModelObject is a member, as Model (actually Workspace) maintains a map of all of its
* objects' implementation reference counting pointers.
*
* The combined use of template methods such as Model::getModelObjects<T>() with the pImpl idiom
* has led to the unfortunate case where users of a class may need to also include the
* corresponding implementation class, for example:
*
* \code
* // user will have to include Space.hpp and Space_Impl.hpp
* std::vector<Space> spaces = model.getModelObjects<Space>();
* \endcode
*
* Another important detail about the OpenStudio Model is that ModelObjects are only valid when
* they are part of a Model. The benefit of this requirement is that any ModelObject can access the
* entire Model to search for related ModelObjects. For the most part, the Model interface
* enforces this requirement. However, there are some cases where it is possible to break this
* invariant, for example:
*
* \code
*
* // EXAMPLE OF WHAT NOT TO DO
*
* // vector to hold ModelObjects
* std::vector<ModelObject> modelObjects;
*
* { // create new scope
*
* // create new Model
* Model model;
*
* // add some objects
* model.getUniqueModelObject<Building>();
* model.getUniqueModelObject<Facility>();
* Space space1(model);
* Space space2(model);
*
* // get objects, they are valid here
* modelObjects = model.modelObjects();
*
* } // model goes out of scope
*
* // modelObjects now contains invalid ModelObjects
* OS_ASSERT(!modelObjects[0].initialized()); // Model_Impl destructor disconnects objects
*
* \endcode
*
* \section attributes What are Attributes and Relationships?
*
* The concept of Attributes and Relationships have recently been added to ModelObject for generic
* access to object methods for user interface development, constructing (energy-efficiency) measures,
* and writing codes and standards. Attributes and Relationships are both implemented using the Qt
* property system. A Qt property can be read and written using the generic functions without knowing
* anything about the owning class except the property's name. For example, the Space ModelObject has
* a method named floorArea. This method can be accessed through the typed interface as:
*
* \code
* Space space(model);
* double floorArea = space.floorArea();
* \endcode
* This same method can be accessed through attributes as:
*
* \code
* Space space(model);
* boost::optional<Attribute> floorAreaAttribute = space.getAttribute(“floorArea”)
* OS_ASSERT(floorAreaAttribute);
* double floorArea = floorAreaAttribute.valueAsDouble();
* \endcode
*
* Attributes can be read only, or allow read and write access (limited to calling a setter
* function taking a single argument). A list of all attribute names for each ModelObject can be
* accessed using ModelObject::attributeNames, the user can check if the attribute is settable using
* ModelObject::isSettableAttribute(const std::string& name), and the user can check if the
* attribute is optional using isOptionalAttribute(const std::string& name). Relationships are very
* similar to Attributes except that Attributes deal with simple, plain-old-data (POD) values (e.g.
* bool, int, double, OSOptionalQuantity etc.) while Relationships deal with ModelObject values.
* The Attribute class is documented in the utilities sub-project, the Relationship class is
* documented in the model sub-project.
*
* \section components What is a Component?
*
* A Component is a partial Model that can be created from a ModelObject and then shared between
* models or with other modelers. When ModelObject::createComponent is called, ModelObject::clone
* is used to copy that object (the primary object) and related objects (often the children and
* resources of the object, evaluated recursively) into a new, blank Component. A Component is a
* Model that satisfies a few additional constraints.
*
* \link Component Components\endlink always contain one ComponentData object, which
* provides a place to list all the objects in the Component, as well as universal identifiers
* and timestamps used to keep track of the Component as it travels to and from local and remote
* Building Component Libraries (BCLs). The contents list is always headed by the primary object,
* which induces a parent-child tree plus resource and connection relationships on the rest of
* objects. For instance, a Construction Component would have a Construction object as its
* primary object, and would likely also contain a number of Material objects (resources of
* the Construction), and a ComponentCost_LineItem object (child of the Construction).
*
* A component creation example follows:
* \code
* OptionalModel oModel = Model::load(osmFilepath);
* OS_ASSERT(oModel);
* model = *oModel;
* ConstructionVector constructions = model.getModelObjects<Construction>();
* if (constructions.size() > 0) {
* Component constructionComponent = constructions[0].createComponent();
* ModelObject primary = constructionComponent.primaryObject();
* OS_ASSERT(primary.optionalCast<Construction>());
* OS_ASSERT(primary.cast<Construction>().layers().size() == constructions[0].layers().size());
* OS_ASSERT(primary.cast<Construction>() != constructions[0]);
* OS_ASSERT(primary.model() != constructions[0].model());
* }
* \endcode
*
* The Component class disallows some of the non-const operations of Model. In particular, no
* objects can be added to or inserted into a Component. Objects can be removed, except for the
* primary ModelObject and the ComponentData object. If either of those objects are removed, the
* Component is invalidated and throws an exception. Once created, Components can be saved for
* future use, or directly used in another Model. To save a Component for future use, it should be
* added to a local BCL, and/or uploaded to the online %Building %Component Library. (These
* features are currently under development. Please see the documentation for utilities/bcl and
* http://bcl.nrel.gov/.)
*
* To use a Component (either directly, or deserialized from a building component library) in a
* Model, use the method Model::insertComponent(const Component& ). This method first looks to see
* if a copy of the Component is already present in the Model; if not, it clones all of the
* objects into the Model. In either case, if successful, the method returns the resulting
* ComponentData object. After an insertComponent operation, Model watches the contents of the
* inserted Component, changing the ComponentData::versionUUID if data is modified, and deleting
* the ComponentData object (and discontinuing the watching operation) if it is invalidated (by
* removal of the primaryObject, for instance). In this way, Model can be queried to find out what
* \link Component Components \endlink it uses, and one can ascertain whether any data has changed
* as compared to the original version. Therefore, this is a mechanism that can be used to trace
* coherent pieces of input data through a series of related models, between similar research
* project models, or to ensure that the appropriate components are used for building energy
* standards compliance.
*
* An example of using the component created above:
* \code
* if (constructions.size() > 0) {
* Model newModel;
* OptionalComponentData ocd = newModel.insertComponent(constructionComponent);
* OS_ASSERT(ocd);
* unsigned n = newModel.numObjects();
* ComponentData cd = *ocd;
* Construction clonedConstruction = cd.primaryComponentObject().cast<Construction>();
* // now I can make some geometry and assign the construction to a planar surface
* // ... or I can remove the new construction, thereby "destroying" the component:
* clonedConstruction.remove();
* OS_ASSERT(clonedConstruction.handle().isNull()); // clonedConstruction removed from model
* OS_ASSERT(cd.handle().isNull()); // ComponentData object also removed
* OS_ASSERT(newModel.numObjects() < n);
* OS_ASSERT(newModel.getModelObjects<Construction>().empty());
* // there may be some orphaned resources (Materials) still hanging around …
* newModel.purgeUnusedResources();
* OS_ASSERT(newModel.numObjects() == 0u);
* }
* \endcode
*/
} // model
} // openstudio
| 53.632777 | 156 | 0.725017 | [
"geometry",
"object",
"vector",
"model"
] |
592464385a5c1a8bb8708e4db5c169269824179c | 1,692 | hpp | C++ | sycl/test/usm/findplatforms.hpp | elizabethandrews/llvm | 308498236c1c4778fdcba0bfbb556adf8aa333ea | [
"Apache-2.0"
] | 34 | 2020-01-31T17:50:00.000Z | 2022-02-16T20:19:29.000Z | sycl/test/usm/findplatforms.hpp | elizabethandrews/llvm | 308498236c1c4778fdcba0bfbb556adf8aa333ea | [
"Apache-2.0"
] | 14 | 2020-02-03T23:39:51.000Z | 2021-07-20T16:24:25.000Z | sycl/test/usm/findplatforms.hpp | elizabethandrews/llvm | 308498236c1c4778fdcba0bfbb556adf8aa333ea | [
"Apache-2.0"
] | 5 | 2020-07-22T16:56:37.000Z | 2022-01-08T02:50:20.000Z | //==------------------- findplatforms.hpp ----------------------------------==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
bool findPlatformAndDevice(cl_device_type deviceType,
cl_platform_id &platformOut, cl_device_id &deviceOut) {
cl_uint numPlatforms;
cl_int errorCode;
errorCode = clGetPlatformIDs(0, nullptr, &numPlatforms);
if (errorCode != CL_SUCCESS) return false;
std::vector<cl_platform_id> platforms(numPlatforms);
errorCode = clGetPlatformIDs(numPlatforms, platforms.data(), nullptr);
if (errorCode != CL_SUCCESS) return false;
for (auto platform : platforms) {
cl_uint numDevices = 0;
errorCode =
clGetDeviceIDs(platform, deviceType, 0, nullptr, &numDevices);
// This has to check both codes because if a platform has 0 devices
// of deviceType, clGetPlatformIDs returns CL_DEVICE_NOT_FOUND.
// We don't want to bail yet as the next platform might have it.
// We bail out here if we see something other than those two error codes.
if (!(errorCode == CL_SUCCESS || errorCode == CL_DEVICE_NOT_FOUND))
return false;
if (numDevices) {
std::vector<cl_device_id> devices(numDevices);
errorCode = clGetDeviceIDs(platform, deviceType, numDevices,
devices.data(), nullptr);
if (errorCode != CL_SUCCESS) return false;
platformOut = platform;
deviceOut = devices[0];
return true;
}
}
return false;
}
| 36.782609 | 82 | 0.642435 | [
"vector"
] |
59268daedb34a5cd17748585b1472287cc7fea88 | 8,657 | cpp | C++ | src/axom/quest/examples/quest_inout_interface.cpp | ExternalRepositories/axom | 48ba6490ac471191179145e662b81c091a19a83d | [
"BSD-3-Clause"
] | null | null | null | src/axom/quest/examples/quest_inout_interface.cpp | ExternalRepositories/axom | 48ba6490ac471191179145e662b81c091a19a83d | [
"BSD-3-Clause"
] | null | null | null | src/axom/quest/examples/quest_inout_interface.cpp | ExternalRepositories/axom | 48ba6490ac471191179145e662b81c091a19a83d | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and
// other Axom Project Developers. See the top-level LICENSE file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
/*!
* \file quest_inout_interface.cpp
*
* Exercises the C-style quest_inout interface which determines if a point
* is contained within an enclosed volume defined by a surface mesh.
* Supports 3D queries against STL meshes and 2D queries against C2C contour files.
* Note: 2D queries are only supported when Axom is configured with C2C.
*/
// Axom includes
#include "axom/core.hpp"
#include "axom/slic.hpp"
#include "axom/primal.hpp"
#include "fmt/fmt.hpp"
#include "CLI11/CLI11.hpp"
// _quest_inout_interface_include_start
#include "axom/quest/interface/inout.hpp"
#ifdef AXOM_USE_MPI
#include <mpi.h>
#endif
// _quest_inout_interface_include_end
// C/C++ includes
#include <vector>
namespace slic = axom::slic;
namespace primal = axom::primal;
namespace quest = axom::quest;
using Point2D = primal::Point<double, 2>;
using Box2D = primal::BoundingBox<double, 2>;
using Point3D = primal::Point<double, 3>;
using Box3D = primal::BoundingBox<double, 3>;
using CoordsVec = std::vector<Point3D>;
//------------------------------------------------------------------------------
/*!
* \brief Utility function to generate a random set of query points
* within a given bounding box
*
* \param [out] queryPoints The generated set of query points
* \param [in] bbox The bounding box for the query points
* \param [in] numPoints The number of points to generate
* \param [in] dim The number of coordinates to generate per point (2 or 3)
*/
void generateQueryPoints(CoordsVec& queryPoints,
Box3D const& bbox,
int numPoints,
int dim)
{
using axom::utilities::random_real;
queryPoints.clear();
queryPoints.reserve(numPoints);
for(int i = 0; i < numPoints; ++i)
{
double x = random_real(bbox.getMin()[0], bbox.getMax()[0]);
double y = random_real(bbox.getMin()[1], bbox.getMax()[1]);
double z = dim == 3 ? random_real(bbox.getMin()[2], bbox.getMax()[2]) : 0.;
queryPoints.emplace_back(Point3D {x, y, z});
}
}
/*!
* \brief Utility function to initialize the logger
*/
void initializeLogger()
{
// Initialize Logger
slic::initialize();
slic::setLoggingMsgLevel(axom::slic::message::Info);
slic::LogStream* logStream;
#ifdef AXOM_USE_MPI
std::string fmt = "[<RANK>][<LEVEL>]: <MESSAGE>\n";
#ifdef AXOM_USE_LUMBERJACK
const int RLIMIT = 8;
logStream = new slic::LumberjackStream(&std::cout, MPI_COMM_WORLD, RLIMIT, fmt);
#else
logStream = new slic::SynchronizedStream(&std::cout, MPI_COMM_WORLD, fmt);
#endif
#else
std::string fmt = "[<LEVEL>]: <MESSAGE>\n";
logStream = new slic::GenericOutputStream(&std::cout, fmt);
#endif // AXOM_USE_MPI
slic::addStreamToAllMsgLevels(logStream);
}
/*!
* \brief Utility function to finalize the logger
*/
void finalizeLogger()
{
if(slic::isInitialized())
{
slic::flushStreams();
slic::finalize();
}
}
/*!
* \brief Utility function for a clean abort that finalizes
* quest_inout, slic and mpi
*/
void cleanAbort()
{
if(quest::inout_initialized())
{
quest::inout_finalize();
}
finalizeLogger();
axom::utilities::processAbort();
}
/// \brief A simple example illustrating the use of the Quest C-Style interface.
int main(int argc, char** argv)
{
// -- Initialize MPI
#ifdef AXOM_USE_MPI
MPI_Init(&argc, &argv);
int my_rank, num_ranks;
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &num_ranks);
#else
int my_rank = 0;
int num_ranks = 1;
#endif
// -- Initialize logger
initializeLogger();
// -- Set up and parse command line options
std::string fileName;
bool isVerbose = false;
int nQueryPoints = 100000;
int segmentsPerKnotSpan = 25;
double weldThresh = 1E-9;
CLI::App app {"Driver for containment query using inout API"};
app.add_option("-i,--input", fileName)
->description("The input file describing a closed surface in 2D or 3D")
->check(CLI::ExistingFile)
->required();
app.add_flag("-v,--verbose", isVerbose)
->description("Enable/disable verbose output")
->capture_default_str();
app.add_option("-t,--weld-threshold", weldThresh)
->description("Threshold for welding")
->check(CLI::NonNegativeNumber)
->capture_default_str();
app.add_option("-q,--num-query-points", nQueryPoints)
->description("Number of query points")
->check(CLI::NonNegativeNumber)
->capture_default_str();
app.add_option("-n,--segments-per-knot-span", segmentsPerKnotSpan)
->description(
"(2D only) Number of linear segments to generate per NURBS knot span")
->capture_default_str()
->check(CLI::PositiveNumber);
app.get_formatter()->column_width(50);
try
{
app.parse(argc, argv);
}
catch(const CLI::ParseError& e)
{
int retval = -1;
if(my_rank == 0)
{
retval = app.exit(e);
}
finalizeLogger();
#ifdef AXOM_USE_MPI
MPI_Bcast(&retval, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Finalize();
#endif
exit(retval);
}
int rc = quest::QUEST_INOUT_SUCCESS;
// _quest_inout_interface_parameters_start
// -- Set quest_inout parameters
rc = quest::inout_set_verbose(isVerbose);
if(rc != quest::QUEST_INOUT_SUCCESS)
{
cleanAbort();
}
// Note: contour files are only supported when Axom is configured with C2C
using axom::utilities::string::endsWith;
const int dim = endsWith(fileName, ".contour") ? 2 : 3;
rc = quest::inout_set_dimension(dim);
if(rc != quest::QUEST_INOUT_SUCCESS)
{
cleanAbort();
}
rc = quest::inout_set_vertex_weld_threshold(weldThresh);
if(rc != quest::QUEST_INOUT_SUCCESS)
{
cleanAbort();
}
rc = quest::inout_set_segments_per_knot_span(segmentsPerKnotSpan);
if(rc != quest::QUEST_INOUT_SUCCESS)
{
cleanAbort();
}
// _quest_inout_interface_parameters_end
// -- Initialize quest_inout
axom::utilities::Timer timer;
SLIC_INFO("Initializing quest_inout...");
timer.start();
{
// _quest_inout_interface_init_start
#ifdef AXOM_USE_MPI
rc = quest::inout_init(fileName, MPI_COMM_WORLD);
#else
rc = quest::inout_init(fileName);
#endif
// _quest_inout_interface_init_end
}
timer.stop();
if(rc != quest::QUEST_INOUT_SUCCESS)
{
cleanAbort();
}
else
{
SLIC_INFO(" initialization took " << timer.elapsed() << " seconds.");
}
// -- Query mesh bounding box and center of mass
double bbMin[3], bbMax[3], cMass[3];
rc = quest::inout_mesh_min_bounds(bbMin);
if(rc != quest::QUEST_INOUT_SUCCESS)
{
cleanAbort();
}
rc = quest::inout_mesh_max_bounds(bbMax);
if(rc != quest::QUEST_INOUT_SUCCESS)
{
cleanAbort();
}
rc = quest::inout_mesh_center_of_mass(cMass);
if(rc != quest::QUEST_INOUT_SUCCESS)
{
cleanAbort();
}
switch(quest::inout_get_dimension())
{
case 2:
SLIC_INFO("Mesh bounding box: " << Box2D(Point2D(bbMin), Point2D(bbMax)));
SLIC_INFO("Mesh center of mass: " << Point2D(cMass));
break;
case 3:
default:
SLIC_INFO("Mesh bounding box: " << Box3D(Point3D(bbMin), Point3D(bbMax)));
SLIC_INFO("Mesh center of mass: " << Point3D(cMass));
break;
}
slic::flushStreams();
// -- Generate query points
Box3D bbox {Point3D(bbMin), Point3D(bbMax)};
CoordsVec queryPoints;
generateQueryPoints(queryPoints, bbox, nQueryPoints, dim);
// -- Run the queries (the z-coordinate is ignored for 2D queries)
int numInside = 0;
SLIC_INFO(fmt::format("Querying mesh with {} query points...", nQueryPoints));
timer.start();
for(auto& pt : queryPoints)
{
// _quest_inout_interface_test_start
const bool ins = quest::inout_evaluate(pt[0], pt[1], pt[2]);
numInside += ins ? 1 : 0;
// _quest_inout_interface_test_end
}
timer.stop();
// -- Output some query statistics
{
SLIC_INFO(fmt::format(" queries took {} seconds.", timer.elapsed()));
SLIC_INFO(fmt::format(" query rate: {} queries per second.",
queryPoints.size() / timer.elapsed()));
SLIC_INFO(fmt::format(
" {} of {} ({}%) of the query points were contained in the surface.",
numInside,
queryPoints.size(),
(100 * numInside) / static_cast<double>(queryPoints.size())));
}
// -- Finalize quest_inout
// _quest_inout_interface_finalize_start
quest::inout_finalize();
// _quest_inout_interface_finalize_end
// -- Finalize logger
finalizeLogger();
// -- Finalize MPI
#ifdef AXOM_USE_MPI
MPI_Finalize();
#endif
return 0;
}
| 26.154079 | 83 | 0.6694 | [
"mesh",
"vector",
"3d"
] |
593127e518ea159f7171139c78af334b9b082679 | 61,058 | cpp | C++ | compile.cpp | kahveciderin/cornpiler | b6f843eb44e7b79ef74b0943ec9792ab1cb4740c | [
"Unlicense"
] | null | null | null | compile.cpp | kahveciderin/cornpiler | b6f843eb44e7b79ef74b0943ec9792ab1cb4740c | [
"Unlicense"
] | null | null | null | compile.cpp | kahveciderin/cornpiler | b6f843eb44e7b79ef74b0943ec9792ab1cb4740c | [
"Unlicense"
] | null | null | null | #include "compile.hpp"
#include <cstdlib>
#include <functional>
#include <iostream>
#include <vector>
std::string DEBUG_TOKEN_TYPES[] = {"str", "identifier", "number", "decimal",
"bracket", "semi", "sep", "sym"};
entry_bracket::entry_bracket(char f, char s) {
first = f;
second = s;
}
bool check_id_constraints(std::string id, char c) {
bool retval = isalpha(c) || c == '_';
if (!id.empty()) retval |= isdigit(c);
return retval;
}
std::vector<token> tokenize_program(std::string program, int length,
logger::logger *logger) {
class {
public:
int row = 0;
int col = 0;
int chr_c = 0;
std::vector<token> tokens;
std::string full_token = "";
bool number = false;
struct {
bool going = false;
bool escaping = false;
} string;
struct {
bool going = false;
std::string id = "";
} identifier;
bool symbol = false;
bool comment = false;
struct {
bool going = false;
bool escaping = false;
} chr;
void reset() {
full_token = "";
number = false;
string.going = false;
string.escaping = false;
identifier.going = false;
identifier.id = "";
symbol = false;
comment = false;
chr.going = false;
chr.escaping = false;
}
void push(token_type t) {
tokens.push_back(token(t, full_token, row, col, chr_c));
}
} status;
auto error_out = [&](std::string errmsg,
logger::LOG_LEVEL level = logger::LOG_LEVEL::ERROR,
bool _exit = true) {
logger->log(level, errmsg);
std::string line = "";
std::string error_show = "^";
int k = status.chr_c;
while (k >= 0 && program[k] != '\n') {
line = program[k] + line;
error_show = "-" + error_show;
k--;
}
k = status.chr_c + 1;
while (k < length && program[k] != '\n') {
line += program[k];
k++;
}
logger->log(level, "");
logger->log(level, std::to_string(status.row + 1) + " | " + line);
for (int j = 0;
j < std::string(std::to_string(status.row + 1) + " | ").length();
j++) {
error_show = " " + error_show;
}
logger->log(level, error_show);
if (_exit) exit(-1);
};
status.full_token = "{";
status.push(token_type::bracket);
status.reset();
// traverse through the file char by char
for (int i = 0; i < length; i++) {
char c = program[i];
if (c == '\n') {
status.row++;
status.col = 0;
}
auto escape_chr = [&]() {
if (c == '\\') {
status.full_token += '\\';
} else if (c == '"') {
status.full_token += c;
} else if (c == 'n') {
status.full_token += '\n';
} else if (c == 't') {
status.full_token += '\t';
} else if (c == 'r') {
status.full_token += '\r';
} else {
error_out(std::string("Invalid escape character: \\") + (c));
}
};
if (status.comment) {
if (c == '\n') status.comment = false;
continue;
}
std::string old_full_token =
status
.full_token; // set old full token here to check for symbols later
if (status.string.going) {
if (status.string.escaping) {
escape_chr();
status.string.escaping = false;
} else {
if (c == '"') {
status.push(token_type::string);
status.reset();
} else if (c == '\\') {
status.string.escaping = true;
} else {
status.full_token += c;
}
}
} else if (status.chr.going) {
if (status.chr.escaping) {
escape_chr();
status.chr.escaping = false;
} else {
if (c == '\'') {
if (status.full_token.length() != 1) {
error_out("Invalid character literal size: " +
std::to_string(status.full_token.length()));
} else {
status.full_token = std::to_string(status.full_token[0]);
if (status.full_token.find('.') == std::string::npos) {
status.push(token_type::number);
} else {
status.push(token_type::decimal);
}
status.reset();
}
} else if (c == '\\') {
status.chr.escaping = true;
} else {
status.full_token += c;
}
}
} else if (check_id_constraints(status.identifier.id, c)) {
if (status.symbol) {
status.push(token_type::sym);
status.reset();
}
status.identifier.going = true;
status.identifier.id += c;
status.full_token += c;
} else {
if (status.identifier.going) {
status.push(token_type::identifier);
status.reset();
}
if (isdigit(c)) {
if (status.symbol) {
status.push(token_type::sym);
status.reset();
}
status.number = true;
status.full_token += c;
} else {
if (c == '.' && status.number) {
status.full_token += c;
} else {
if (status.number) {
if (status.full_token.find('.') == std::string::npos) {
status.push(token_type::number);
} else {
status.push(token_type::decimal);
}
status.reset();
}
if (c == '"') {
status.string.going = true;
} else if (c == '\'') {
status.chr.going = true;
} else if (std::string("()[]{}").find(c) != std::string::npos) {
status.full_token += c;
status.push(token_type::bracket);
status.reset();
} else if (c == ';') {
status.full_token += c;
status.push(token_type::semi);
status.reset();
} else if (c == ',') {
status.full_token += c;
status.push(token_type::sep);
status.reset();
} else if (c == '#') {
status.reset();
status.comment = true;
} else if (!isspace(c)) {
status.symbol = true;
status.full_token += c;
} else if (status.symbol) {
status.push(token_type::sym);
status.reset();
}
}
}
}
status.chr_c++;
status.col++;
}
status.full_token = "}";
status.push(token_type::bracket);
status.reset();
for (auto &t : status.tokens) {
logger->log(logger::LOG_LEVEL::DEBUG, "Token: " + t.value + "\t\t\tType: " +
DEBUG_TOKEN_TYPES[(int)t.type]);
}
return status.tokens;
}
ast_types::global_scope lex_program(file_object input_file,
std::vector<token> program_tokens,
logger::logger *logger) {
ast_types::global_scope globals;
std::function<int(int, std::vector<scope_element>, parsing_modes,
entry_bracket)>
recursive_lex = [&](int old_itt, std::vector<scope_element> scope,
parsing_modes parsing_mode,
entry_bracket entr) { // returns the new itt
auto error_out = [&](std::string error_message, token tk,
logger::LOG_LEVEL level = logger::LOG_LEVEL::ERROR,
bool _exit = true) {
logger->log(level, error_message);
std::string line = "";
std::string error_show = "^";
int k = tk.chr;
while (k >= 0 && input_file.contents[k] != '\n') {
line = input_file.contents[k] + line;
error_show = "-" + error_show;
k--;
}
k = tk.chr + 1;
while (k < input_file.length && input_file.contents[k] != '\n') {
line += input_file.contents[k];
k++;
}
logger->log(level, "");
logger->log(level, std::to_string(tk.row + 1) + " | " + line);
for (int j = 0;
j < std::string(std::to_string(tk.row + 1) + " | ").length();
j++) {
error_show = " " + error_show;
}
logger->log(level, error_show);
if (_exit) exit(-1);
};
auto goto_ast_scope = [&](std::vector<scope_element> in_scope) {
logger->log(logger::LOG_LEVEL::DEBUG, "Reaching into",
logger::SETTINGS::TYPE);
AST *that_ast = &(globals);
int scope_i = 0;
for (auto s : in_scope) { // copy, do not reference
if ((int)s >= 0) { // int
logger->log(logger::LOG_LEVEL::DEBUG,
" > [" + std::to_string((int)s) + "]",
logger::SETTINGS::NONE);
ast_body *_temp_body = dynamic_cast<ast_body *>(that_ast);
std::vector<AST *> _temp_inhere = _temp_body->body;
that_ast = _temp_inhere[(int)s];
} else {
switch ((scope_element)s) {
case scope_element::global:
that_ast =
&((dynamic_cast<ast_types::global_scope *>(that_ast))
->body);
logger->log(logger::LOG_LEVEL::DEBUG, " > global",
logger::SETTINGS::NONE);
break;
case scope_element::args:
that_ast =
&((dynamic_cast<ast_types::with_args *>(that_ast))->args);
logger->log(logger::LOG_LEVEL::DEBUG, " > args",
logger::SETTINGS::NONE);
break;
case scope_element::body:
that_ast =
&((dynamic_cast<ast_types::with_body *>(that_ast))->body);
logger->log(logger::LOG_LEVEL::DEBUG, " > body",
logger::SETTINGS::NONE);
break;
case scope_element::second_body:
that_ast =
&((dynamic_cast<ast_types::with_second_body *>(that_ast))
->second_body);
logger->log(logger::LOG_LEVEL::DEBUG, " > second_body",
logger::SETTINGS::NONE);
break;
case scope_element::type:
that_ast =
&((dynamic_cast<ast_types::with_type *>(that_ast))->type);
logger->log(logger::LOG_LEVEL::DEBUG, " > type",
logger::SETTINGS::NONE);
break;
case scope_element::return_type:
that_ast =
&((dynamic_cast<ast_types::with_return_type *>(that_ast))
->return_type);
logger->log(logger::LOG_LEVEL::DEBUG, " > return_type",
logger::SETTINGS::NONE);
break;
case scope_element::arr_index:
that_ast =
&((dynamic_cast<ast_types::arrget *>(that_ast))->index);
logger->log(logger::LOG_LEVEL::DEBUG, " > arr_index",
logger::SETTINGS::NONE);
break;
case scope_element::arr_array:
that_ast =
&((dynamic_cast<ast_types::arrget *>(that_ast))->array);
logger->log(logger::LOG_LEVEL::DEBUG, " > arr_array",
logger::SETTINGS::NONE);
break;
case scope_element::argtype:
that_ast = &(
(dynamic_cast<ast_types::with_args_with_type *>(that_ast))
->args);
logger->log(logger::LOG_LEVEL::DEBUG, " > argtype",
logger::SETTINGS::NONE);
break;
case scope_element::out_length:
that_ast = &(
(dynamic_cast<ast_types::out_type *>(that_ast))->length);
logger->log(logger::LOG_LEVEL::DEBUG, " > out_length",
logger::SETTINGS::NONE);
break;
case scope_element::values:
that_ast =
&((dynamic_cast<ast_types::with_values *>(that_ast))
->values);
logger->log(logger::LOG_LEVEL::DEBUG, " > values",
logger::SETTINGS::NONE);
break;
case scope_element::second_args:
that_ast =
&((dynamic_cast<ast_types::with_second_args *>(that_ast))
->second_args);
logger->log(logger::LOG_LEVEL::DEBUG, " > second_args",
logger::SETTINGS::NONE);
break;
default:
logger->log(
logger::LOG_LEVEL::ERROR,
"\nInvalid scope element: " + std::to_string((int)s));
exit(0);
}
}
}
logger->log(logger::LOG_LEVEL::DEBUG, "", logger::SETTINGS::NEWLINE);
return that_ast;
};
auto set_ast_scope = [&](std::vector<scope_element> scope, AST *val) {
*goto_ast_scope(scope) = *val;
};
auto append_ast_scope = [&](std::vector<scope_element> scope,
AST *val) {
int index_inserted;
AST *that_ast = goto_ast_scope(scope);
index_inserted = (dynamic_cast<ast_body *>(that_ast))->body.size();
(dynamic_cast<ast_body *>(that_ast))->body.push_back(val);
return index_inserted;
};
auto get_ast_scope = [&](std::vector<scope_element>
scope) { // returns a pointer to that ast
return goto_ast_scope(scope);
};
auto check_if_operation = [](token kword) {
return (
kword.value == "+" || kword.value == "-" || kword.value == "*" ||
kword.value == "/" || kword.value == ">" || kword.value == "<" ||
kword.value == "==" || kword.value == "<=" ||
kword.value == ">=" || kword.value == "&&" ||
kword.value == "||" || kword.value == "&" || kword.value == "|" ||
kword.value == "^" || kword.value == "!=" || kword.value == "!" ||
kword.value == "%");
};
int itt = old_itt;
while (true) {
bool try_continue = true;
auto look_ahead = [&](int count = 1) {
itt += count;
if (itt >= program_tokens.size()) {
error_out("Premature end-of-file reached",
program_tokens[itt - count]);
}
return program_tokens[itt];
};
auto look_behind = [&](int count = 1) {
itt -= count;
if (itt < 0) {
error_out("Premature end-of-file reached",
program_tokens[itt + count]);
}
return program_tokens[itt];
};
token initial_token = look_ahead(); // get next token
logger->log(logger::LOG_LEVEL::DEBUG,
"recursive lexer loop entry, itt: " +
std::to_string(itt) + " total token amount: " +
std::to_string(program_tokens.size()));
logger->log(logger::LOG_LEVEL::DEBUG,
"Token info: " + initial_token.value + "\t\t\t" +
DEBUG_TOKEN_TYPES[(int)initial_token.type]);
if (parsing_mode == parsing_modes::type) {
if (initial_token.value == "ptr" || initial_token.value == "arr" ||
initial_token.value == "unsigned") {
// outer type
ast_types::out_type *to_append = new ast_types::out_type;
to_append->name = initial_token.value;
int appended_index = append_ast_scope(scope, to_append);
if (initial_token.value == "arr") {
if (look_ahead().value != "[") {
error_out("array type must be followed by [",
program_tokens[itt]);
}
std::vector<scope_element> new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::out_length);
itt = recursive_lex(
itt, new_scope, parsing_modes::type,
entry_bracket('[', ']')); // array length lexing
}
std::vector<scope_element> new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::type);
itt = recursive_lex(itt, new_scope, parsing_modes::type,
entry_bracket('(', ')')); // type lexing
} else if (initial_token.value == "fun") {
ast_types::fun_type *to_append = new ast_types::fun_type;
int appended_index = append_ast_scope(scope, to_append);
look_ahead();
while (program_tokens[itt].value != "=>") {
std::string arg_name = program_tokens[itt].value;
if (look_ahead().value != ":") {
error_out("expected ':' in function argument list",
program_tokens[itt]);
}
std::vector<scope_element> new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::argtype);
ast_types::arg_with_type_t *arg_type_t =
new ast_types::arg_with_type_t;
arg_type_t->name = ast_types::string_t(arg_name);
new_scope.push_back(
(scope_element)append_ast_scope(new_scope, arg_type_t));
new_scope.push_back(scope_element::type);
itt = recursive_lex(itt, new_scope, parsing_modes::type,
entry_bracket('(', ')')); // type lexing
look_ahead();
}
std::vector<scope_element> new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::return_type);
itt = recursive_lex(itt, new_scope, parsing_modes::type,
entry_bracket('(', ')'));
} else {
ast_types::in_type *to_append = new ast_types::in_type;
to_append->type = initial_token.value;
append_ast_scope(scope, to_append);
}
break;
}
switch (initial_token.type) {
case token_type::identifier: {
if (initial_token.value == "for") {
ast_types::statement_with_body *to_append =
new ast_types::statement_with_body;
ast_types::scope *to_append_scope = new ast_types::scope;
int appended_scope_id =
append_ast_scope(scope, to_append_scope);
to_append->name = ast_types::string_t("while");
int appended_index = -1;
look_ahead();
int incr_cnt = 0;
while (program_tokens[itt].value != ")") {
std::vector<scope_element> new_scope = scope;
new_scope.push_back((scope_element)appended_scope_id);
new_scope.push_back(scope_element::body);
if (incr_cnt == 1) {
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::args);
} else if (incr_cnt == 2) {
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::body);
}
itt = recursive_lex(itt, new_scope, parsing_modes::argument,
entry_bracket('(', ')'));
if (incr_cnt == 0) {
appended_index = append_ast_scope(new_scope, to_append);
}
incr_cnt++;
}
if (incr_cnt != 3) {
error_out("Invalid argument count in for loop",
initial_token);
}
look_ahead();
std::vector<scope_element> new_scope = scope;
new_scope.push_back((scope_element)appended_scope_id);
new_scope.push_back(scope_element::body);
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::body);
itt = recursive_lex(itt, new_scope, parsing_modes::statement,
entry_bracket('{', '}'));
} else if (initial_token.value == "if") {
// double body statement
ast_types::statement_with_two_bodies *to_append =
new ast_types::statement_with_two_bodies;
to_append->name = ast_types::string_t("if");
int appended_index = append_ast_scope(scope, to_append);
std::vector<scope_element> new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::args);
while (program_tokens[itt].value != ")") {
itt = recursive_lex(itt, new_scope, parsing_modes::argument,
entry_bracket('(', ')')); // args lexing
}
new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::body);
itt = recursive_lex(itt, new_scope, parsing_modes::statement,
entry_bracket('{', '}')); // body lexing
if (look_ahead().value == "else") {
if (look_ahead().value == "if") {
new_scope = scope;
scope.push_back((scope_element)appended_index);
scope.push_back(scope_element::second_body);
itt = recursive_lex(
--itt, new_scope, parsing_modes::statement,
entry_bracket('{', '}')); // else if body lexing
} else {
new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::second_body);
itt = recursive_lex(
--itt, new_scope, parsing_modes::statement,
entry_bracket('{', '}')); // else body lexing
}
} else {
--itt;
}
} else if (initial_token.value == "while" ||
initial_token.value == "foreach") {
// single body statement
ast_types::statement_with_body *to_append =
new ast_types::statement_with_body;
to_append->name = ast_types::string_t(initial_token.value);
int appended_index = append_ast_scope(scope, to_append);
std::vector<scope_element> new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::args);
while (program_tokens[itt].value != ")") {
itt = recursive_lex(itt, new_scope, parsing_modes::argument,
entry_bracket('(', ')')); // args lexing
}
new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::body);
itt = recursive_lex(itt, new_scope, parsing_modes::statement,
entry_bracket('{', '}')); // body lexing
} else if (initial_token.value == "return" ||
initial_token.value == "break" ||
initial_token.value == "continue" ||
initial_token.value == "deref") {
// statement
ast_types::statement *to_append = new ast_types::statement;
to_append->name = ast_types::string_t(initial_token.value);
int appended_index = append_ast_scope(scope, to_append);
if (look_ahead().value == "(") {
std::vector<scope_element> new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::args);
itt = recursive_lex(--itt, new_scope, parsing_modes::argument,
entry_bracket('(', ')')); // args lexing
} else {
--itt;
}
} else if (initial_token.value == "ref") {
// varop
ast_types::varop *to_append = new ast_types::varop;
to_append->name = ast_types::string_t(initial_token.value);
to_append->var = ast_types::string_t(look_ahead().value);
append_ast_scope(scope, to_append);
} else if (initial_token.value == "var") {
// vardef
AST *to_append;
// = new ast_types::vardef;
if (scope.size() == 1) {
to_append = new ast_types::glbdef;
} else {
to_append = new ast_types::vardef;
}
std::vector<scope_element> new_scope = scope;
int appended_index = append_ast_scope(scope, to_append);
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::type);
itt =
recursive_lex(itt, new_scope, parsing_modes::type,
entry_bracket('(', ')')); // var type lexing
if (scope.size() == 1) {
dynamic_cast<ast_types::glbdef *>(to_append)->name =
ast_types::string_t(look_ahead().value);
} else {
dynamic_cast<ast_types::vardef *>(to_append)->name =
ast_types::string_t(look_ahead().value);
}
if (look_ahead().value == "=") {
new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::args);
itt = recursive_lex(itt, new_scope, parsing_modes::arg_one,
entry_bracket('(', ')'));
} else {
--itt;
}
} else if (initial_token.value == "fun") {
// have FUN! jk function
ast_types::fundef *to_append = new ast_types::fundef;
to_append->name = look_ahead().value;
int appended_index = append_ast_scope(scope, to_append);
look_ahead();
while (program_tokens[itt].value != "=>") {
std::string arg_name = program_tokens[itt].value;
if (look_ahead().value != ":") {
error_out("expected ':' in function argument list",
program_tokens[itt]);
}
std::vector<scope_element> new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::argtype);
ast_types::arg_with_type_t *arg_type_t =
new ast_types::arg_with_type_t;
arg_type_t->name = ast_types::string_t(arg_name);
new_scope.push_back(
(scope_element)append_ast_scope(new_scope, arg_type_t));
new_scope.push_back(scope_element::type);
itt = recursive_lex(itt, new_scope, parsing_modes::type,
entry_bracket('(', ')')); // type lexing
look_ahead();
}
std::vector<scope_element> new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::return_type);
itt = recursive_lex(
itt, new_scope, parsing_modes::type,
entry_bracket('(', ')')); // return type lexing
if (look_ahead().value != "{") {
error_out("expected '{' in function definition",
program_tokens[itt - 1]);
}
new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::body);
itt = recursive_lex(itt, new_scope, parsing_modes::statement,
entry_bracket('{', '}')); // body lexing
} else if (initial_token.value ==
"ext") { // TODO: autodetect and deprecate
// external function
ast_types::extdef *to_append = new ast_types::extdef;
to_append->name = look_ahead().value;
int appended_index = append_ast_scope(scope, to_append);
while (program_tokens[itt].value != "=>") {
std::vector<scope_element> new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::argtype);
ast_types::arg_with_type_t *arg_type_t =
new ast_types::arg_with_type_t;
new_scope.push_back(
(scope_element)append_ast_scope(new_scope, arg_type_t));
new_scope.push_back(scope_element::type);
int tmp_itt =
recursive_lex(itt, new_scope, parsing_modes::type,
entry_bracket('(', ')')); // type lexing
itt = tmp_itt;
}
std::vector<scope_element> new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::return_type);
itt = recursive_lex(
itt, new_scope, parsing_modes::type,
entry_bracket('(', ')')); // return type lexing
} else if (initial_token.value == "class") {
ast_types::class_n *to_append = new ast_types::class_n;
to_append->name = look_ahead().value;
int appended_index = append_ast_scope(scope, to_append);
std::vector<scope_element> new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::values);
look_ahead();
while (look_ahead().value != "}") {
look_behind();
if (look_ahead().value == "fun") {
ast_types::fundef *to_append_fun = new ast_types::fundef;
ast_types::value *to_append_val = new ast_types::value;
ast_types::fun_type *to_append_fun_type =
new ast_types::fun_type;
int appended_index_val =
append_ast_scope(new_scope, to_append_val);
std::vector<scope_element> new_scope_fun_type = new_scope;
new_scope_fun_type.push_back(
(scope_element)appended_index_val);
new_scope_fun_type.push_back(scope_element::type);
int appended_index_fun_type = append_ast_scope(
new_scope_fun_type, to_append_fun_type);
to_append_fun->name = ast_types::string_t(
"__anonymous_lambda_at_" + std::to_string(itt));
to_append_val->name = look_ahead().value;
std::vector<scope_element> new_scope_val_args = new_scope;
new_scope_val_args.push_back(
(scope_element)appended_index_val);
new_scope_val_args.push_back(scope_element::args);
ast_types::varop *to_append_funptr = new ast_types::varop;
to_append_funptr->var = to_append_fun->name;
to_append_funptr->name = ast_types::string_t("funptr");
append_ast_scope(new_scope_val_args, to_append_funptr);
int appended_index_fun = append_ast_scope(
{scope_element::global}, to_append_fun);
look_ahead();
int old_itt = itt;
ast_types::arg_with_type_t *this_arg_type_t =
new ast_types::arg_with_type_t;
this_arg_type_t->name = ast_types::string_t("this");
ast_types::out_type *this_out_type =
new ast_types::out_type;
this_out_type->name = ast_types::string_t("ptr");
ast_types::in_type *this_in_type = new ast_types::in_type;
this_in_type->type = to_append->name;
this_out_type->type.body.push_back(this_in_type);
this_arg_type_t->type.body.push_back(this_out_type);
to_append_fun->args.body.push_back(this_arg_type_t);
while (program_tokens[itt].value != "=>") {
std::string arg_name = program_tokens[itt].value;
if (look_ahead().value != ":") {
error_out("expected ':' in function argument list",
program_tokens[itt]);
}
std::vector<scope_element> new_scope = {
scope_element::global};
new_scope.push_back((scope_element)appended_index_fun);
new_scope.push_back(scope_element::argtype);
ast_types::arg_with_type_t *arg_type_t =
new ast_types::arg_with_type_t;
arg_type_t->name = ast_types::string_t(arg_name);
new_scope.push_back((scope_element)append_ast_scope(
new_scope, arg_type_t));
new_scope.push_back(scope_element::type);
itt = recursive_lex(
itt, new_scope, parsing_modes::type,
entry_bracket('(', ')')); // type lexing
look_ahead();
}
itt = old_itt;
to_append_fun_type->args.body.push_back(this_arg_type_t);
while (program_tokens[itt].value != "=>") {
std::string arg_name = program_tokens[itt].value;
if (look_ahead().value != ":") {
error_out("expected ':' in function argument list",
program_tokens[itt]);
}
std::vector<scope_element> new_scope = new_scope_fun_type;
new_scope.push_back(
(scope_element)appended_index_fun_type);
new_scope.push_back(scope_element::argtype);
ast_types::arg_with_type_t *arg_type_t =
new ast_types::arg_with_type_t;
arg_type_t->name = ast_types::string_t(arg_name);
new_scope.push_back((scope_element)append_ast_scope(
new_scope, arg_type_t));
new_scope.push_back(scope_element::type);
itt = recursive_lex(
itt, new_scope, parsing_modes::type,
entry_bracket('(', ')')); // type lexing
look_ahead();
}
old_itt = itt;
std::vector<scope_element> new_scope = {
scope_element::global};
new_scope.push_back((scope_element)appended_index_fun);
new_scope.push_back(scope_element::return_type);
itt = recursive_lex(itt, new_scope, parsing_modes::type,
entry_bracket('(', ')'));
itt = old_itt;
new_scope = new_scope_fun_type;
new_scope.push_back((scope_element)appended_index_fun_type);
new_scope.push_back(scope_element::return_type);
itt = recursive_lex(itt, new_scope, parsing_modes::type,
entry_bracket('(', ')'));
if (look_ahead().value != "{") {
error_out("expected '{' in function definition",
program_tokens[itt - 1]);
}
new_scope = {scope_element::global};
new_scope.push_back((scope_element)appended_index_fun);
new_scope.push_back(scope_element::body);
itt =
recursive_lex(itt, new_scope, parsing_modes::statement,
entry_bracket('{', '}'));
continue;
}
look_behind();
ast_types::value *to_append_val = new ast_types::value;
int appended_index_val =
append_ast_scope(new_scope, to_append_val);
std::vector<scope_element> new_scope_type = new_scope;
new_scope_type.push_back((scope_element)appended_index_val);
new_scope_type.push_back(scope_element::type);
itt = recursive_lex(itt, new_scope_type, parsing_modes::type,
entry_bracket('(', ')'));
to_append_val->name = ast_types::string_t(look_ahead().value);
if (look_ahead().value == "=") {
std::vector<scope_element> new_scope_val = new_scope;
new_scope_val.push_back((scope_element)appended_index_val);
new_scope_val.push_back(scope_element::args);
itt = recursive_lex(itt, new_scope_val,
parsing_modes::arg_one,
entry_bracket('(', ')'));
} else {
look_behind();
}
}
} else if (initial_token.value == "lambda") {
ast_types::fundef *to_append = new ast_types::fundef;
to_append->name = ast_types::string_t(
" __anonymous_lambda_at_" +
std::to_string(itt)); // the unicode character in the
// function is illegal in the syntax,
// so we use it to make it anonymous
int appended_index =
append_ast_scope({scope_element::global}, to_append);
look_ahead();
while (program_tokens[itt].value != "=>") {
std::string arg_name = program_tokens[itt].value;
if (look_ahead().value != ":") {
error_out("expected ':' in function argument list",
program_tokens[itt]);
}
std::vector<scope_element> new_scope = {
scope_element::global};
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::argtype);
ast_types::arg_with_type_t *arg_type_t =
new ast_types::arg_with_type_t;
arg_type_t->name = ast_types::string_t(arg_name);
new_scope.push_back(
(scope_element)append_ast_scope(new_scope, arg_type_t));
new_scope.push_back(scope_element::type);
itt = recursive_lex(itt, new_scope, parsing_modes::type,
entry_bracket('(', ')')); // type lexing
look_ahead();
}
std::vector<scope_element> new_scope = {scope_element::global};
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::return_type);
itt = recursive_lex(itt, new_scope, parsing_modes::type,
entry_bracket('(', ')'));
if (look_ahead().value != "{") {
error_out("expected '{' in function definition",
program_tokens[itt - 1]);
}
new_scope = {scope_element::global};
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::body);
itt = recursive_lex(itt, new_scope, parsing_modes::statement,
entry_bracket('{', '}')); // body lexing
ast_types::varop *to_append_varop = new ast_types::varop;
to_append_varop->name = ast_types::string_t("funptr");
to_append_varop->var = to_append->name;
append_ast_scope(scope, to_append_varop);
} else {
look_ahead();
if (program_tokens[itt].value == "(") {
// function call
bool class_function = program_tokens[itt - 1].value == ".";
ast_types::call *to_append = new ast_types::call;
to_append->name = ast_types::string_t(initial_token.value);
int appended_index = append_ast_scope(scope, to_append);
if (class_function) {
// to_append->args.body.push_back(); TODO
}
std::vector<scope_element> new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::args);
while (program_tokens[itt].value != ")") {
itt =
recursive_lex(itt, new_scope, parsing_modes::argument,
entry_bracket('(', ')')); // args lexing
}
} else {
// this should be a variable
// since we have already incremented itt, we can check whether
// it is a assignment or a reference right away
if (program_tokens[itt].value == "=" ||
(program_tokens[itt].value[1] == '=' &&
program_tokens[itt].value[0] != '=' &&
program_tokens[itt].value[0] != '!' &&
program_tokens[itt].value[0] != '<' &&
program_tokens[itt].value[0] != '>')) {
// assignment
token operation = program_tokens[itt];
token var_name = program_tokens[itt - 1];
if (operation.value == "=") {
// simple assignment
ast_types::varset *to_append = new ast_types::varset;
to_append->name = var_name.value;
std::vector<scope_element> new_scope = scope;
new_scope.push_back(
(scope_element)append_ast_scope(scope, to_append));
new_scope.push_back(scope_element::args);
itt = recursive_lex(
itt, new_scope, parsing_modes::arg_one,
entry_bracket('(', ')')); // args lexing
} else {
// +=, -=, *=, /=, %=, &=, ^=, |=
ast_types::varset *to_append = new ast_types::varset;
to_append->name = var_name.value;
std::vector<scope_element> new_scope = scope;
new_scope.push_back(
(scope_element)append_ast_scope(scope, to_append));
new_scope.push_back(scope_element::args);
ast_types::oper *opr = new ast_types::oper;
opr->op = ast_types::string_t(operation.value[0]);
new_scope.push_back(
(scope_element)append_ast_scope(new_scope, opr));
new_scope.push_back(scope_element::args);
ast_types::getvar *to_append2 = new ast_types::getvar;
to_append2->name = var_name.value;
append_ast_scope(new_scope, to_append2);
itt = recursive_lex(
itt, new_scope, parsing_modes::arg_one,
entry_bracket('(', ')')); // args lexing
}
} else {
// reference
--itt;
ast_types::getvar *to_append = new ast_types::getvar;
to_append->name = ast_types::string_t(initial_token.value);
append_ast_scope(scope, to_append);
}
}
}
break;
}
case token_type::number: {
// number const
ast_types::const_int *to_append = new ast_types::const_int;
to_append->value = stoi(program_tokens[itt].value);
append_ast_scope(scope, to_append);
break;
}
case token_type::decimal: {
// decimal const
ast_types::const_decimal *to_append =
new ast_types::const_decimal;
to_append->value = stod(program_tokens[itt].value);
append_ast_scope(scope, to_append);
break;
}
case token_type::string: {
// string const
ast_types::const_str *to_append = new ast_types::const_str;
to_append->value = program_tokens[itt].value;
append_ast_scope(scope, to_append);
break;
}
case token_type::bracket: {
// brackets
if (initial_token.value == "(") {
if (old_itt + 1 != itt) {
ast_types::expr *to_append = new ast_types::expr;
std::vector<scope_element> new_scope = scope;
new_scope.push_back(
(scope_element)append_ast_scope(new_scope, to_append));
new_scope.push_back(scope_element::args);
itt = recursive_lex(itt, new_scope, parsing_modes::argument,
entry_bracket('(', ')')); // args lexing
continue;
}
} else if (initial_token.value == "[") {
// defining an array
if (program_tokens[itt - 1].type == token_type::sym) {
ast_types::arrset *to_append = new ast_types::arrset;
std::vector<scope_element> new_scope = scope;
new_scope.push_back(
(scope_element)append_ast_scope(new_scope, to_append));
new_scope.push_back(scope_element::args);
while (program_tokens[itt].value != "]") {
itt = recursive_lex(itt, new_scope, parsing_modes::argument,
entry_bracket('(', ')'));
}
} else {
// indexing an array
AST *old_stat_place =
(AST *)(dynamic_cast<ast_body *>(get_ast_scope(scope))
->body.back());
(dynamic_cast<ast_body *>(get_ast_scope(scope)))
->body.pop_back();
ast_types::arrget *to_append = new ast_types::arrget;
to_append->array.body.push_back(old_stat_place);
std::vector<scope_element> new_scope = scope;
new_scope.push_back(
(scope_element)append_ast_scope(scope, to_append));
new_scope.push_back(scope_element::arr_index);
itt = recursive_lex(itt, new_scope, parsing_modes::argument,
entry_bracket('(', ')')); // args lexing
}
} else if (entr.second == program_tokens[itt].value[0]) {
// scope end
// if (scope.size() == 3) {
// // function end
// ast_types::statement *to_append = new ast_types::statement;
// to_append->name = ast_types::string_t("return");
// append_ast_scope(scope, to_append);
// }
try_continue = false;
} else if (initial_token.value == "{" && itt != 0) {
// user defined scope
ast_types::scope *to_append = new ast_types::scope;
std::vector<scope_element> new_scope = scope;
new_scope.push_back(
(scope_element)append_ast_scope(new_scope, to_append));
new_scope.push_back(scope_element::body);
itt = recursive_lex(itt, new_scope, parsing_modes::statement,
entry_bracket('{', '}'));
}
break;
}
case token_type::sym: {
// symbols
if (check_if_operation(initial_token)) {
if (initial_token.value == "-" &&
dynamic_cast<ast_body *>(get_ast_scope(scope))
->body.size() == 0) {
// unary minus
ast_types::statement *to_append = new ast_types::statement;
to_append->name = ast_types::string_t("neg");
std::vector<scope_element> new_scope = scope;
new_scope.push_back(
(scope_element)append_ast_scope(scope, to_append));
new_scope.push_back(scope_element::args);
itt = recursive_lex(itt, new_scope,
parsing_mode == parsing_modes::statement
? parsing_modes::argument
: parsing_mode,
entry_bracket('(', ')')); // args lexing
} else if (initial_token.value == "!") {
ast_types::statement *to_append = new ast_types::statement;
to_append->name = ast_types::string_t("not");
std::vector<scope_element> new_scope = scope;
new_scope.push_back(
(scope_element)append_ast_scope(scope, to_append));
new_scope.push_back(scope_element::args);
itt = recursive_lex(itt, new_scope,
parsing_mode == parsing_modes::statement
? parsing_modes::argument
: parsing_mode,
entry_bracket('(', ')')); // args lexing
} else {
// operation
AST *old_stat_place =
(AST *)(dynamic_cast<ast_body *>(get_ast_scope(scope))
->body.back());
(dynamic_cast<ast_body *>(get_ast_scope(scope)))
->body.pop_back();
ast_types::oper *to_append = new ast_types::oper;
to_append->args.body.push_back(old_stat_place);
to_append->op = initial_token.value;
std::vector<scope_element> new_scope = scope;
new_scope.push_back(
(scope_element)append_ast_scope(scope, to_append));
new_scope.push_back(scope_element::args);
itt = recursive_lex(itt, new_scope,
parsing_mode == parsing_modes::statement
? parsing_modes::argument
: parsing_mode,
entry_bracket('(', ')')); // args lexing
}
} else if (program_tokens[itt].value == "=" ||
(program_tokens[itt].value[1] == '=' &&
program_tokens[itt].value[0] != '=' &&
program_tokens[itt].value[0] != '!' &&
program_tokens[itt].value[0] != '<' &&
program_tokens[itt].value[0] != '>')) {
// assignment to a dereferenced pointer
token operation = program_tokens[itt];
AST *old_stat_place =
(AST *)(dynamic_cast<ast_body *>(get_ast_scope(scope))
->body.back());
(dynamic_cast<ast_body *>(get_ast_scope(scope)))
->body
.pop_back(); // this is the pointer to be dereferenced
if (operation.value == "=") {
// simple assignment
ast_types::ptrset *to_append = new ast_types::ptrset;
std::vector<scope_element> new_scope = scope;
new_scope.push_back(
(scope_element)append_ast_scope(scope, to_append));
new_scope.push_back(scope_element::second_args);
append_ast_scope(new_scope, old_stat_place);
new_scope.pop_back();
new_scope.push_back(scope_element::args);
itt = recursive_lex(itt, new_scope, parsing_modes::arg_one,
entry_bracket('(', ')')); // args lexing
} else {
ast_types::ptrset *to_append = new ast_types::ptrset;
int appended_index = append_ast_scope(scope, to_append);
std::vector<scope_element> new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::second_args);
append_ast_scope(new_scope, old_stat_place);
new_scope = scope;
new_scope.push_back((scope_element)appended_index);
new_scope.push_back(scope_element::args);
ast_types::oper *opr = new ast_types::oper;
opr->op = ast_types::string_t(operation.value[0]);
new_scope.push_back(
(scope_element)append_ast_scope(new_scope, opr));
new_scope.push_back(scope_element::args);
ast_types::statement *deref_to_append =
new ast_types::statement;
deref_to_append->name = ast_types::string_t("deref");
deref_to_append->args.body.push_back(old_stat_place);
append_ast_scope(new_scope, deref_to_append);
// ast_types::getvar *to_append2 = new ast_types::getvar;
// to_append2->name = var_name.value;
// append_ast_scope(new_scope, to_append2);
itt = recursive_lex(itt, new_scope, parsing_modes::arg_one,
entry_bracket('(', ')')); // args lexing
}
} else if (initial_token.value == ".") {
std::cout << "dot operations" << std::endl;
// classget returns the pointer to the member inside a class
// if we are getting the value, we need to dereference it
// if we are setting the value, we need to dereference it and
// then set the value
ast_types::classget *to_append = new ast_types::classget;
std::vector<scope_element> new_scope = scope;
AST *old_stat_place =
(AST *)(dynamic_cast<ast_body *>(get_ast_scope(scope))
->body.back());
(dynamic_cast<ast_body *>(get_ast_scope(scope)))
->body.pop_back();
new_scope.push_back(
(scope_element)append_ast_scope(scope, to_append));
new_scope.push_back(scope_element::args);
append_ast_scope(new_scope, old_stat_place);
to_append->var = look_ahead().value;
look_ahead();
if ((!(program_tokens[itt].value == "=" ||
(program_tokens[itt].value[1] == '=' &&
program_tokens[itt].value[0] != '=' &&
program_tokens[itt].value[0] != '!' &&
program_tokens[itt].value[0] != '<' &&
program_tokens[itt].value[0] != '>'))) && program_tokens[itt].value != "(") {
// we are getting the value, in which case we need to
// dereference the pointer because classget returns a pointer
ast_types::statement *deref_to_append =
new ast_types::statement;
deref_to_append->name = ast_types::string_t("deref");
AST *old_stat_place =
(AST *)(dynamic_cast<ast_body *>(get_ast_scope(scope))
->body.back());
(dynamic_cast<ast_body *>(get_ast_scope(scope)))
->body.pop_back();
deref_to_append->args.body.push_back(old_stat_place);
append_ast_scope(scope, deref_to_append);
}
if (program_tokens[itt].value == "(") {
// function call to a member function
ast_types::callptr *to_append_call = new ast_types::callptr;
AST *old_stat_place =
(AST *)(dynamic_cast<ast_body *>(get_ast_scope(scope))
->body.back());
(dynamic_cast<ast_body *>(get_ast_scope(scope)))
->body.pop_back();
to_append_call->second_args.body.push_back(old_stat_place);
std::vector<scope_element> new_scope = scope;
new_scope.push_back(
(scope_element)append_ast_scope(scope, to_append_call));
new_scope.push_back(scope_element::args);
to_append_call->args.body.push_back(old_stat_place);
while (program_tokens[itt].value != ")") {
itt =
recursive_lex(itt, new_scope, parsing_modes::argument,
entry_bracket('(', ')')); // args lexing
}
}
look_behind();
}
break;
}
case token_type::sep: {
// error_out("Unnecessary seperator found", program_tokens[itt],
// logger::LOG_LEVEL::WARNING, false);
}
case token_type::semi:
break;
}
if (!try_continue) break;
if (parsing_mode != parsing_modes::statement) {
if (program_tokens[itt].value == "," ||
program_tokens[itt].value == "." ||
program_tokens[itt].value == ")") { // "." could be unnecessary
break;
}
}
if (parsing_mode == parsing_modes::arg_one) {
look_ahead();
itt -= 1; // check for end of file
if ((!check_if_operation(program_tokens[itt])) &&
(!check_if_operation(program_tokens[itt + 1]))) {
break;
}
}
}
return itt;
};
recursive_lex(-1, {scope_element::global}, parsing_modes::statement,
entry_bracket('{', '}'));
return globals;
} | 45.839339 | 100 | 0.482672 | [
"vector"
] |
593295fa5dbc4815dd0a25f3e7dc681aac462641 | 2,333 | hpp | C++ | ReactNativeFrontend/ios/Pods/boost/boost/gil/io/scanline_read_iterator.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 153 | 2015-02-03T06:03:54.000Z | 2022-03-20T15:06:34.000Z | ReactNativeFrontend/ios/Pods/boost/boost/gil/io/scanline_read_iterator.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 429 | 2015-03-22T09:49:04.000Z | 2022-03-28T08:32:08.000Z | ReactNativeFrontend/ios/Pods/boost/boost/gil/io/scanline_read_iterator.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 215 | 2015-03-15T09:20:51.000Z | 2022-03-30T12:40:07.000Z | //
// Copyright 2007-2008 Christian Henning
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#ifndef BOOST_GIL_IO_SCANLINE_READ_ITERATOR_HPP
#define BOOST_GIL_IO_SCANLINE_READ_ITERATOR_HPP
#include <boost/gil/io/error.hpp>
#include <boost/gil/io/typedefs.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <iterator>
#include <memory>
#include <vector>
namespace boost { namespace gil {
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
#pragma warning(push)
#pragma warning(disable:4512) //assignment operator could not be generated
#endif
/// Input iterator to read images.
template <typename Reader>
class scanline_read_iterator
: public boost::iterator_facade<scanline_read_iterator<Reader>, byte_t*, std::input_iterator_tag>
{
private:
using base_t = boost::iterator_facade
<
scanline_read_iterator<Reader>,
byte_t*,
std::input_iterator_tag
>;
public:
scanline_read_iterator(Reader& reader, int pos = 0)
: reader_(reader), pos_(pos)
{
buffer_ = std::make_shared<buffer_t>(buffer_t(reader_._scanline_length));
buffer_start_ = &buffer_->front();
}
private:
friend class boost::iterator_core_access;
void increment()
{
if (skip_scanline_)
{
reader_.skip(buffer_start_, pos_);
}
++pos_;
skip_scanline_ = true;
read_scanline_ = true;
}
bool equal(scanline_read_iterator const& rhs) const
{
return pos_ == rhs.pos_;
}
typename base_t::reference dereference() const
{
if (read_scanline_)
{
reader_.read(buffer_start_, pos_);
}
skip_scanline_ = false;
read_scanline_ = false;
return buffer_start_;
}
private:
Reader& reader_;
mutable int pos_ = 0;
mutable bool read_scanline_ = true;
mutable bool skip_scanline_ = true;
using buffer_t = std::vector<byte_t>;
using buffer_ptr_t = std::shared_ptr<buffer_t>;
buffer_ptr_t buffer_;
mutable byte_t* buffer_start_ = nullptr;
};
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
#pragma warning(pop)
#endif
} // namespace gil
} // namespace boost
#endif
| 23.09901 | 101 | 0.664381 | [
"vector"
] |
5935a630b4063e273cbccac920ed003ced6278b8 | 3,384 | cpp | C++ | lib/CustomTestFramework/CustomTestRunner.cpp | myfreeweb/mull | ac74f0e7b08652037f5e893d06d2aaa38e91ac02 | [
"Apache-2.0"
] | null | null | null | lib/CustomTestFramework/CustomTestRunner.cpp | myfreeweb/mull | ac74f0e7b08652037f5e893d06d2aaa38e91ac02 | [
"Apache-2.0"
] | null | null | null | lib/CustomTestFramework/CustomTestRunner.cpp | myfreeweb/mull | ac74f0e7b08652037f5e893d06d2aaa38e91ac02 | [
"Apache-2.0"
] | null | null | null | #include "CustomTestFramework/CustomTestRunner.h"
#include "CustomTestFramework/CustomTest_Test.h"
#include "Toolchain/Mangler.h"
#include "Toolchain/Resolvers/InstrumentationResolver.h"
#include "Toolchain/Resolvers/NativeResolver.h"
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
using namespace mull;
using namespace llvm;
using namespace llvm::orc;
CustomTestRunner::CustomTestRunner(Mangler &mangler) :
mangler(mangler),
overrides([this](const char *name) {
return this->mangler.getNameWithPrefix(name);
}),
trampoline(new InstrumentationInfo*)
{
}
CustomTestRunner::~CustomTestRunner() {
delete trampoline;
}
void *CustomTestRunner::getConstructorPointer(const llvm::Function &function,
JITEngine &jit) {
return getFunctionPointer(mangler.getNameWithPrefix(function.getName()), jit);
}
void *CustomTestRunner::getFunctionPointer(const std::string &functionName, JITEngine &jit) {
JITSymbol &symbol = jit.getSymbol(functionName);
auto address = llvm_compat::JITSymbolAddress(symbol);
void *fpointer = reinterpret_cast<void *>(static_cast<uintptr_t>(address));
if (fpointer == nullptr) {
errs() << "CustomTestRunner> Can't find pointer to function: "
<< functionName << "\n";
exit(1);
}
return fpointer;
}
void CustomTestRunner::runStaticConstructor(llvm::Function *function,
JITEngine &jit) {
// printf("Init: %s\n", Ctor->getName().str().c_str());
void *CtorPointer = getConstructorPointer(*function, jit);
auto ctor = ((int (*)())(intptr_t)CtorPointer);
ctor();
}
void CustomTestRunner::loadInstrumentedProgram(ObjectFiles &objectFiles,
Instrumentation &instrumentation,
JITEngine &jit) {
InstrumentationResolver resolver(overrides, instrumentation, mangler, trampoline);
jit.addObjectFiles(objectFiles, resolver, make_unique<SectionMemoryManager>());
}
void CustomTestRunner::loadProgram(ObjectFiles &objectFiles,
JITEngine &jit) {
NativeResolver resolver(overrides);
jit.addObjectFiles(objectFiles, resolver, make_unique<SectionMemoryManager>());
}
ExecutionStatus CustomTestRunner::runTest(Test *test, JITEngine &jit) {
*trampoline = &test->getInstrumentationInfo();
CustomTest_Test *customTest = dyn_cast<CustomTest_Test>(test);
for (auto &constructor: customTest->getConstructors()) {
runStaticConstructor(constructor, jit);
}
std::vector<std::string> arguments = customTest->getArguments();
arguments.insert(arguments.begin(), customTest->getProgramName());
int argc = arguments.size();
char **argv = new char*[argc + 1];
for (int i = 0; i < argc; i++) {
std::string &argument = arguments[i];
argv[i] = new char[argument.length() + 1];
strcpy(argv[i], argument.c_str());
}
argv[argc] = nullptr;
void *mainPointer = getFunctionPointer(mangler.getNameWithPrefix("main"),
jit);
auto main = ((int (*)(int, char**))(intptr_t)mainPointer);
int exitStatus = main(argc, argv);
for (int i = 0; i < argc; i++) {
delete[] argv[i];
}
delete[] argv;
overrides.runDestructors();
if (exitStatus == 0) {
return ExecutionStatus::Passed;
}
return ExecutionStatus::Failed;
}
| 30.763636 | 93 | 0.673168 | [
"vector"
] |
593bd887d5b61883edc47844da6ce8135bb7d543 | 13,796 | cpp | C++ | source/polyvec/shortest-path/dijkstra.cpp | ShnitzelKiller/polyfit | 51ddc6365a794db1678459140658211cb78f65b1 | [
"MIT"
] | 27 | 2020-08-17T17:25:59.000Z | 2022-03-01T05:49:12.000Z | source/polyvec/shortest-path/dijkstra.cpp | ShnitzelKiller/polyfit | 51ddc6365a794db1678459140658211cb78f65b1 | [
"MIT"
] | 4 | 2020-08-26T13:54:59.000Z | 2020-09-21T07:19:22.000Z | source/polyvec/shortest-path/dijkstra.cpp | ShnitzelKiller/polyfit | 51ddc6365a794db1678459140658211cb78f65b1 | [
"MIT"
] | 5 | 2020-08-26T23:26:48.000Z | 2021-01-04T09:06:07.000Z | #include <polyvec/shortest-path/dijkstra.hpp>
#include <polyvec/api.hpp>
#include <polyvec/core/log.hpp>
#include <polyvec/utils/matrix.hpp>
#include <cstdlib>
#include <algorithm>
#define DEBUG_CYCLE 0
#define DEBUG_TRAVERSE 0
#define DEBUG_DFS 0
#define DEBUG_BFS 0
#if DEBUG_TRAVERSE
#define TRAVERSE_LOG(fmt, ...) PF_LOGF(fmt, __VA_ARGS__)
#else
#define TRAVERSE_LOG(fmt, ...)
#endif
#if DEBUG_CYCLE
#define CYCLE_LOG(fmt, ...) PF_LOGF(fmt, __VA_ARGS__)
#else
#define CYCLE_LOG(fmt, ...)
#endif
#if DEBUG_DFS
#define DFS_LOG(fmt, ...) PF_LOGF(fmt, __VA_ARGS__)
#else
#define DFS_LOG(fmt, ...)
#endif
#if DEBUG_BFS
#define BFS_LOG(fmt, ...) PF_LOGF(fmt, __VA_ARGS__)
#else
#define BFS_LOG(fmt, ...)
#endif
using namespace std;
NAMESPACE_BEGIN(polyfit)
NAMESPACE_BEGIN(ShortestPath)
void State::reset() {
queue = PriorityQueue();
visits.clear();
visited.clear();
}
double cost(const std::vector<Node>& G, const std::vector<Vertex>& P, bool circular) {
double tot = 0.;
for (size_t i = 0; i < P.size(); ++i) {
const Node& n = G[P[i]];
if (!circular && i == P.size() - 1) {
break;
}
TRAVERSE_LOG("node %lld %s", P[i], n.id.c_str());
int j = 0;
for (; j < n.neighbors.size(); ++j) {
TRAVERSE_LOG("nhb %lld expected %lld", n.nhbs[j], CircularAt(P, i + 1));
auto& edge = n.neighbors[j];
if (edge.to == CircularAt(P, i + 1)) {
tot += edge.cost;
break;
}
}
assert_break(j < n.neighbors.size());
}
return tot;
}
bool find(State& s, const std::vector<Node>& G, Vertex src, Vertex dst, std::vector<Vertex>& P) {
P.clear();
if (G[src].neighbors.empty()) {
return false;
}
// Clearing traverse structures
s.reset();
s.visits.resize(G.size(), State::Visit());
s.visited.resize(G.size(), false);
// circular source/destination
State::Visit visit_dst;
// initializing source node
s.visits[src].cost = 0.;
s.visits[src].prev = -1;
s.queue.push(PriorityQueueEl(s.visits[src].cost, src));
Vertex node_dst = -1;
const bool circular = src == dst;
unsigned int iters = 0;
while (!s.queue.empty()) {
PriorityQueueEl visit_el = s.queue.top();
assert_break(visit_el.first >= 0.); // This should just not happen
// next element
const double node_at_cost = visit_el.first;
const Vertex inode_at = visit_el.second;
const Node & node_at = G[inode_at];
const State::Visit& node_at_visit_info = s.visits[inode_at];
TRAVERSE_LOG("visiting %s", node_at.id.c_str());
// removing it from the queue
s.queue.pop();
// Termination condition
if (inode_at == dst) {
// If it's circular and the dst_visit has never been touched then this is the first iteration
if (!circular || (circular && visit_dst.prev != -1)) {
TRAVERSE_LOG("Terminating circular %d visit-dst-cost %f visit-dst-prev %lld", circular, visit_dst.cost, visit_dst.prev);
break;
}
}
// Marking current as visited
s.visited[inode_at] = true;
TRAVERSE_LOG("node %s neighbors %d", node_at.id.c_str(), node_at.nhbs.size());
// Neighboring nodes outgoing from the current
for(auto& edge : node_at.neighbors) {
const Vertex inode_to = edge.to;
const Node& node_to = G[inode_to];
double edge_cost = edge.cost;
assert_break(edge_cost >= 0.);
const double cost_so_far = node_at_visit_info.cost + edge_cost;
//if (!circular) {
//PF_DEV_F("%s -> %s cost %f", node_at.id.c_str(), node_to.id.c_str(), edge_cost);
//}
TRAVERSE_LOG("neighbor %s cost-to-here %f edge-cost %f cost-so-far %f",
node_to.id.c_str(), node_at_visit_info.cost, edge_cost, cost_so_far);
State::Visit visit_info_to;
visit_info_to.cost = cost_so_far;
visit_info_to.prev = inode_at;
// updating cost if less than what there is right node
State::Visit* visit = nullptr;
if (inode_to == dst && circular) {
visit = &visit_dst;
} else {
visit = &s.visits[inode_to];
}
if (cost_so_far < visit->cost) {
*visit = visit_info_to;
if (!s.visited[inode_to]) {
s.queue.push(PriorityQueueEl(cost_so_far, inode_to));
}
else {
TRAVERSE_LOG("node %s already visited", node_to.id.c_str());
}
}
}
}
// did we reach the destination ?
State::Visit* visit = circular ? &visit_dst : &s.visits[dst];
if (visit->prev == -1) {
TRAVERSE_LOG("shortest path failed, destination %s not reached", G[dst].id.c_str());
return false;
}
TRAVERSE_LOG("destination prev %s", G[visit->prev].id.c_str());
TRAVERSE_LOG("destination reached, reconstructing path");
if (!circular) {
P.emplace_back(dst);
}
P.emplace_back(visit->prev);
Vertex inode_next = visit->prev;
while (inode_next != -1) {
P.emplace_back(s.visits[inode_next].prev);
inode_next = s.visits[inode_next].prev;
}
if (P.back() == -1) {
P.pop_back();
}
std::reverse(P.begin(), P.end());
return true;
}
bool find(State& s, const std::vector<Node>& G, const std::vector<Vertex>& src, const std::vector<Vertex>& dst, std::vector<Vertex>& P) {
if (src.empty() || dst.empty()) {
TRAVERSE_LOG("no source or destination nodes");
return false;
}
P.clear();
// Clearing traverse structures
s.reset();
s.visits.resize(G.size(), State::Visit());
s.visited.resize(G.size(), false);
// circular source/destination
std::vector<State::Visit> visit_dst(dst.size());
// initializing source nodes
for (int i = 0; i < src.size(); ++i) {
s.visits[src[i]].cost = 0.;
s.visits[src[i]].prev = -1;
s.queue.push(PriorityQueueEl(s.visits[src[i]].cost, src[i]));
}
Vertex node_dst = -1;
const bool circular = src == dst;
unsigned int iters = 0;
while (!s.queue.empty()) {
PriorityQueueEl visit_el = s.queue.top();
assert_break(visit_el.first >= 0.); // This should just not happen
// next element
const double node_at_cost = visit_el.first;
const Vertex inode_at = visit_el.second;
const Node & node_at = G[inode_at];
const State::Visit node_at_visit_info = s.visits[inode_at];
TRAVERSE_LOG("visiting %s", node_at.id.c_str());
// removing it from the queue
s.queue.pop();
// Termination condition
bool dst_reached = false;
for (int i = 0; i < dst.size(); ++i) {
if (inode_at == dst[i]) {
if (!circular || visit_dst[i].prev != -1) {
TRAVERSE_LOG("terminating path circular %d visit-dst-cost %f visit-dst-prev %lld", circular, visit_dst[i].cost, visit_dst[i].prev);
dst_reached = true;
break;
}
}
}
if (dst_reached) {
break;
}
// Marking current as visited
s.visited[inode_at] = true;
TRAVERSE_LOG("node %s neighbors %d", node_at.id.c_str(), node_at.nhbs.size());
// Neighboring nodes outgoing from the current
for(auto& edge : node_at.neighbors) {
const Vertex inode_to = edge.to;
const Node& node_to = G[inode_to];
double edge_cost = edge.cost;
assert_break(edge_cost >= 0.);
const double cost_so_far = node_at_visit_info.cost + edge_cost;
TRAVERSE_LOG("neighbor %s cost-to-here %f edge-cost %f cost-so-far %f",
node_to.id.c_str(), node_at_visit_info.cost, edge_cost, cost_so_far);
State::Visit visit_info_to;
visit_info_to.cost = cost_so_far;
visit_info_to.prev = inode_at;
// updating cost if less than what there is right node
State::Visit * visit = nullptr;
for (int j = 0; j < dst.size(); ++j) {
if (circular && inode_to == dst[j]) {
visit = &visit_dst[j];
break;
}
else {
visit = &s.visits[inode_to];
break;
}
}
if (cost_so_far < visit->cost) {
*visit = visit_info_to;
if (!s.visited[inode_to]) {
s.queue.push(PriorityQueueEl(cost_so_far, inode_to));
}
else {
TRAVERSE_LOG("node %s already visited", node_to.id.c_str());
}
}
}
}
// did we reach the destination ?
// picking the destination node with the least cost
State::Visit* visit = nullptr;
for (int i = 0; i < dst.size(); ++i) {
if (circular && visit_dst[i].prev != -1) {
if (!visit || visit->cost > visit_dst[i].cost) {
visit = &visit_dst[i];
}
}
else if (s.visits[dst[i]].prev != -1) {
if (!visit || visit->cost > s.visits[dst[i]].cost) {
visit = &s.visits[dst[i]];
}
P.emplace_back(dst[i]);
}
}
if (!visit) {
TRAVERSE_LOG("no shortest path found");
return false;
}
TRAVERSE_LOG("destination prev %s", G[visit->prev].id.c_str());
TRAVERSE_LOG("destination reached, reconstructing path");
P.emplace_back(visit->prev);
Vertex inode_next = visit->prev;
while (inode_next != -1) {
P.emplace_back(s.visits[inode_next].prev);
inode_next = s.visits[inode_next].prev;
}
if (P.back() == -1) {
P.pop_back();
}
std::reverse(P.begin(), P.end());
return true;
}
bool find_cycle(State& s, const std::vector<Node>& G, const std::vector<Vertex>& srcdst, std::vector<Vertex>& P) {
CYCLE_LOG("find-cycle source nodes");
for (int i = 0; i < srcdst.size(); ++i) {
CYCLE_LOG("\tnode %lld id %s", srcdst[i], G[srcdst[i]].id.c_str());
}
// First, finding the cycle from srcdst which costs the least
std::vector<Vertex> GP0, GP1;
double GP0_cost = INFINITY;
for (int i = 0; i < srcdst.size(); ++i) {
const Vertex v = srcdst[i];
if (::polyfit::ShortestPath::find(s, G, { v }, { v }, GP1)) {
const double GP1_cost = cost(G, GP1);
if (GP1_cost < GP0_cost) {
GP0 = std::move(GP1);
GP0_cost = GP1_cost;
CYCLE_LOG("found a better path from node %lld id %s", v, G[v].id.c_str());
}
}
}
if (GP0.empty()) {
return false;
}
CYCLE_LOG("found initial cycle length %lld", GP0.size());
double e_tot = 0.;
for (int i = 0; i < GP0.size(); ++i) {
CYCLE_LOG("node %lld id %s", GP0[i], G[GP0[i]].id.c_str());
auto ni = G[GP0[i]];
for(auto& edge : ni.neighbors) {
if (CircularAt(GP0, i + 1) == edge.to) {
CYCLE_LOG("cost to next node %f", edge.cost);
e_tot += edge.cost;
}
}
}
CYCLE_LOG("total path cost %f", e_tot);
// not trying to find the cycle from the most distant node
const int iters_min = 3;
const int iters_max = 10;
Vertex v = GP0[GP0.size() / 2];
for (int iter = 0; iter < iters_max; ++iter) {
CYCLE_LOG("find shortest cycle from node %lld id %s", v, G[v].id.c_str());
assert_break(::polyfit::ShortestPath::find(s, G, v, v, GP1));
const double GP1_cost = cost(G, GP1);
CYCLE_LOG("found path cost %f length %llu", GP1_cost, GP1.size());
for (int j = 0; j < GP1.size(); ++j) {
CYCLE_LOG("node %lld id %s", GP1[j], G[GP1[j]].id.c_str());
}
if (GP1_cost < GP0_cost) {
CYCLE_LOG("found a better path length %lld", GP1.size());
CYCLE_LOG("old cost %f new cost %f ", GP0_cost, GP1_cost);
for (int j = 0; j < GP1.size(); ++j) {
CYCLE_LOG("node %lld id %s", GP1[j], G[GP1[j]].id.c_str());
}
v = GP1[GP1.size() / 2];
GP0 = GP1;
GP0_cost = GP1_cost;
}
// let's try some other random node in the path
else {
size_t v_rnd = (size_t)(rand() % GP0.size());
CYCLE_LOG("attempting another random node %lld", v_rnd);
v = GP0[v_rnd];
}
}
// This is not necessary, but allows to diff the files with the tracing results without any knowledge of the content
std::sort(GP0.begin(), GP0.end());
P = std::move(GP0);
return true;
}
bool dfs_traverse_rec(const std::vector<Node>& G, std::vector<bool>& visited, Vertex v, Vertex vdst, std::vector<Vertex>* P) {
if (P) {
P->emplace_back(v);
}
if (visited[v]) {
return false;
}
visited[v] = true;
if (v == vdst) {
return true;
}
for(auto& edge : G[v].neighbors) {
DFS_LOG("dfs %lld(%lld) nhb %lld(%lld)", v, G[v].v, G[v].nhbs[i], G[G[v].nhbs[i]].v);
if (dfs_traverse_rec(G, visited, edge.to, vdst, P) && !visited[edge.to]) {
return true;
}
}
return false;
}
bool find_depth_first(const std::vector<Node>& G, Vertex src, Vertex dst, std::vector<Vertex>* P) {
PF_ASSERT(src >= 0 && src < (Vertex)G.size());
PF_ASSERT(dst >= 0 && dst < (Vertex)G.size());
if (src == dst) {
return true;
}
std::vector<bool> visited(G.size(), false);
if (P) {
P->clear();
}
DFS_LOG("dfs source %lld(%lld) destination %lld(%lld)", src, G[src].v, dst, G[dst].v);
return dfs_traverse_rec(G, visited, src, dst, P);
}
bool find_breadth_first(const std::vector<Node>& G, Vertex src, Vertex dst) {
PF_ASSERT(src >= 0 && src < (Vertex)G.size());
PF_ASSERT(dst >= 0 && dst < (Vertex)G.size());
BFS_LOG("bfs source %lld(%lld) destination %lld(%lld)", src, G[src].v, dst, G[dst].v);
if (src == dst) {
return true;
}
std::vector<bool> visited(G.size(), false);
std::queue<Vertex> queue;
queue.push(src);
while (!queue.empty()) {
Vertex v = queue.front();
queue.pop();
if (visited[v]) {
continue;
}
BFS_LOG("bfs visit %lld(%lld)", v, G[v].v);
visited[v] = true;
if (v == dst) {
return true;
}
for(auto& edge : G[v].neighbors) {
if (!visited[edge.to]) {
queue.push(edge.to);
}
}
}
return false;
}
Vertex find_or_add_node(std::vector<Node>& G, const Vertex v) {
const auto& n_it = std::find_if(G.begin(), G.end(), [v](const Node & n) {
return n.v == v;
});
if (n_it == G.end()) {
G.emplace_back(v);
return G.size() - 1;
}
else {
return distance(G.begin(), n_it);
}
}
void print_graph(const std::vector<Node>& G, FILE *file) {
int id = 0;
for (const Node & node :G ) {
fprintf(file,"# node id \n%d\n", id);
fprintf(file,"# node v \n%d\n", (int)node.v);
fprintf(file,"# node n_neighbours \n%d\n", (int)node.neighbors.size());
fprintf(file,"# node neighbours \n");
for (int i = 0 ; i < node.neighbors.size() ; ++i ) {
fprintf(file,"%d ", (int)node.neighbors[i].to);
}
fprintf(file,"\n");
fprintf(file,"# node n costs \n");
for (int i = 0 ; i < node.neighbors.size() ; ++i ) {
fprintf(file,"%.5g ", node.neighbors[i].cost);
}
fprintf(file,"\n # ------------ \n");
++id;
}
}
NAMESPACE_END(ShortestPath)
NAMESPACE_END(polyfit)
| 24.724014 | 137 | 0.626413 | [
"vector"
] |
86ccffa58aaa365b90d7ef4272fae58422fcfd67 | 275 | cpp | C++ | ARRAYS/find_missing_number.cpp | vsvipul11/Datastructres_CPP | a63c62c424aba805d1a17f6cb1a6036fad42dd68 | [
"MIT"
] | 2 | 2021-01-01T20:36:09.000Z | 2022-03-09T21:11:22.000Z | ARRAYS/find_missing_number.cpp | vsvipul11/Datastructres_CPP | a63c62c424aba805d1a17f6cb1a6036fad42dd68 | [
"MIT"
] | null | null | null | ARRAYS/find_missing_number.cpp | vsvipul11/Datastructres_CPP | a63c62c424aba805d1a17f6cb1a6036fad42dd68 | [
"MIT"
] | 1 | 2021-05-14T15:53:15.000Z | 2021-05-14T15:53:15.000Z | class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = nums.size();
int sum = (n*(n+1))/2;
int s = 0;
for(int i = 0 ; i < n ; i++){
s += nums[i];
}
return sum - s;
}
};
| 18.333333 | 42 | 0.370909 | [
"vector"
] |
86d0c99ad3f975ac3f94845369ed00d4d89723b9 | 4,817 | cpp | C++ | dep/reactphysics3d/src/collision/shapes/SphereShape.cpp | harperkdavis/hkedengine | 4dbb9c5106aa8eaaf4369232f8036a05ce55ab3f | [
"MIT"
] | 1 | 2022-02-14T11:54:13.000Z | 2022-02-14T11:54:13.000Z | dep/reactphysics3d/src/collision/shapes/SphereShape.cpp | harperkdavis/hkedengine | 4dbb9c5106aa8eaaf4369232f8036a05ce55ab3f | [
"MIT"
] | null | null | null | dep/reactphysics3d/src/collision/shapes/SphereShape.cpp | harperkdavis/hkedengine | 4dbb9c5106aa8eaaf4369232f8036a05ce55ab3f | [
"MIT"
] | null | null | null | /********************************************************************************
* ReactPhysics3D physics library, http://www.reactphysics3d.com *
* Copyright (c) 2010-2022 Daniel Chappuis *
*********************************************************************************
* *
* This software is provided 'as-is', without any express or implied warranty. *
* In no event will the authors be held liable for any damages arising from the *
* use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not claim *
* that you wrote the original software. If you use this software in a *
* product, an acknowledgment in the product documentation would be *
* appreciated but is not required. *
* *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* *
* 3. This notice may not be removed or altered from any source distribution. *
* *
********************************************************************************/
// Libraries
#include <reactphysics3d/collision/shapes/SphereShape.h>
#include <reactphysics3d/collision/Collider.h>
#include <reactphysics3d/configuration.h>
#include <reactphysics3d/collision/RaycastInfo.h>
#include <cassert>
using namespace reactphysics3d;
// Constructor
/**
* @param radius Radius of the sphere
*/
SphereShape::SphereShape(decimal radius, MemoryAllocator& allocator)
: ConvexShape(CollisionShapeName::SPHERE, CollisionShapeType::SPHERE, allocator, radius) {
assert(radius > decimal(0.0));
}
// Update the AABB of a body using its collision shape
/**
* @param[out] aabb The axis-aligned bounding box (AABB) of the collision shape
* computed in world-space coordinates
* @param transform Transform used to compute the AABB of the collision shape
*/
void SphereShape::computeAABB(AABB& aabb, const Transform& transform) const {
RP3D_PROFILE("SphereShape::computeAABB()", mProfiler);
// Get the local extents in x,y and z direction
Vector3 extents(mMargin, mMargin, mMargin);
// Update the AABB with the new minimum and maximum coordinates
aabb.setMin(transform.getPosition() - extents);
aabb.setMax(transform.getPosition() + extents);
}
// Raycast method with feedback information
bool SphereShape::raycast(const Ray& ray, RaycastInfo& raycastInfo, Collider* collider, MemoryAllocator& /*allocator*/) const {
const Vector3 m = ray.point1;
decimal c = m.dot(m) - mMargin * mMargin;
// If the origin of the ray is inside the sphere, we return no intersection
if (c < decimal(0.0)) return false;
const Vector3 rayDirection = ray.point2 - ray.point1;
decimal b = m.dot(rayDirection);
// If the origin of the ray is outside the sphere and the ray
// is pointing away from the sphere, there is no intersection
if (b > decimal(0.0)) return false;
decimal raySquareLength = rayDirection.lengthSquare();
// Compute the discriminant of the quadratic equation
decimal discriminant = b * b - raySquareLength * c;
// If the discriminant is negative or the ray length is very small, there is no intersection
if (discriminant < decimal(0.0) || raySquareLength < MACHINE_EPSILON) return false;
// Compute the solution "t" closest to the origin
decimal t = -b - std::sqrt(discriminant);
assert(t >= decimal(0.0));
// If the hit point is withing the segment ray fraction
if (t < ray.maxFraction * raySquareLength) {
// Compute the intersection information
t /= raySquareLength;
raycastInfo.body = collider->getBody();
raycastInfo.collider = collider;
raycastInfo.hitFraction = t;
raycastInfo.worldPoint = ray.point1 + t * rayDirection;
raycastInfo.worldNormal = raycastInfo.worldPoint;
return true;
}
return false;
}
| 45.018692 | 127 | 0.569649 | [
"shape",
"transform"
] |
86d1ce86ecbba05abaf2814e09a8bd98755e7cdf | 13,052 | hpp | C++ | include/range/v3/view/iota.hpp | anders-sjogren/range-v3 | a7583aaf4e446d435867e54d58575d40c0575312 | [
"MIT"
] | null | null | null | include/range/v3/view/iota.hpp | anders-sjogren/range-v3 | a7583aaf4e446d435867e54d58575d40c0575312 | [
"MIT"
] | null | null | null | include/range/v3/view/iota.hpp | anders-sjogren/range-v3 | a7583aaf4e446d435867e54d58575d40c0575312 | [
"MIT"
] | null | null | null | /// \file
// Range v3 library
//
// Copyright Eric Niebler 2013-2014
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/ericniebler/range-v3
//
#ifndef RANGES_V3_VIEW_IOTA_HPP
#define RANGES_V3_VIEW_IOTA_HPP
#include <climits>
#include <cstdint>
#include <limits>
#include <type_traits>
#include <range/v3/range_fwd.hpp>
#include <range/v3/range_concepts.hpp>
#include <range/v3/range_facade.hpp>
#include <range/v3/utility/meta.hpp>
#include <range/v3/utility/concepts.hpp>
#include <range/v3/utility/static_const.hpp>
#include <range/v3/view/take.hpp>
#include <range/v3/view/delimit.hpp>
namespace ranges
{
inline namespace v3
{
namespace concepts
{
struct BidirectionalIncrementable
: refines<Incrementable>
{
template<typename T>
auto requires_(T t) -> decltype(
concepts::valid_expr(
concepts::has_type<T &>(--t),
concepts::has_type<T>(t--)
));
};
struct RandomAccessIncrementable
: refines<BidirectionalIncrementable>
{
template<typename T>
auto requires_(T t) -> decltype(
concepts::valid_expr(
concepts::model_of<Integral>(t - t),
concepts::has_type<T &>(t += (t - t)),
concepts::has_type<T &>(t -= (t - t)),
concepts::convertible_to<T>(t - (t - t)),
concepts::convertible_to<T>(t + (t - t)),
concepts::convertible_to<T>((t - t) + t)
));
};
}
template<typename T>
using BidirectionalIncrementable = concepts::models<concepts::BidirectionalIncrementable, T>;
template<typename T>
using RandomAccessIncrementable = concepts::models<concepts::RandomAccessIncrementable, T>;
template<typename T>
using incrementable_concept =
concepts::most_refined<
meta::list<
concepts::RandomAccessIncrementable,
concepts::BidirectionalIncrementable,
concepts::Incrementable,
concepts::WeaklyIncrementable>, T>;
template<typename T>
using incrementable_concept_t = meta::eval<incrementable_concept<T>>;
/// \cond
namespace detail
{
template<typename Val, typename Iota = incrementable_concept_t<Val>,
bool IsIntegral = std::is_integral<Val>::value>
struct iota_difference_
: ranges::difference_type<Val>
{};
template<typename Val>
struct iota_difference_<Val, concepts::RandomAccessIncrementable, true>
{
private:
using difference_t = decltype(std::declval<Val>() - std::declval<Val>());
static constexpr std::size_t bits = sizeof(difference_t) * CHAR_BIT;
public:
using type =
meta::if_<
meta::not_<std::is_same<Val, difference_t>>,
meta::eval<std::make_signed<difference_t>>,
meta::if_c<
(bits < 8),
std::int_fast8_t,
meta::if_c<
(bits < 16),
std::int_fast16_t,
meta::if_c<
(bits < 32),
std::int_fast32_t,
std::int_fast64_t> > > >;
};
template<typename Val>
struct iota_difference
: iota_difference_<Val>
{};
template<typename Val>
using iota_difference_t = meta::eval<iota_difference<Val>>;
template<typename Val, CONCEPT_REQUIRES_(!Integral<Val>())>
iota_difference_t<Val> iota_minus(Val const &v0, Val const &v1)
{
return v0 - v1;
}
template<typename Val, CONCEPT_REQUIRES_(SignedIntegral<Val>())>
iota_difference_t<Val> iota_minus(Val const &v0, Val const &v1)
{
using D = iota_difference_t<Val>;
return (D) v0 - (D) v1;
}
template<typename Val, CONCEPT_REQUIRES_(UnsignedIntegral<Val>())>
iota_difference_t<Val> iota_minus(Val const &v0, Val const &v1)
{
using D = iota_difference_t<Val>;
return (D) (v0 - v1);
}
}
/// \endcond
/// \addtogroup group-views
/// @{
/// An iota view in a closed range with non-random access iota value type
template<typename Val, typename Val2 /* = void */>
struct iota_view
: range_facade<iota_view<Val, Val2>, true>
{
private:
using incrementable_concept_t = ranges::incrementable_concept<Val>;
friend range_access;
using difference_type_ = detail::iota_difference_t<Val>;
Val from_;
Val2 to_;
bool done_ = false;
Val current() const
{
return from_;
}
void next()
{
if(from_ == to_)
done_ = true;
else
++from_;
}
bool done() const
{
return done_;
}
CONCEPT_REQUIRES(Incrementable<Val>())
bool equal(iota_view const &that) const
{
return that.from_ == from_;
}
CONCEPT_REQUIRES(BidirectionalIncrementable<Val>())
void prev()
{
--from_;
}
CONCEPT_REQUIRES(RandomAccessIncrementable<Val>())
void advance(difference_type_ n)
{
RANGES_ASSERT(detail::iota_minus(to_, from_) >= n);
from_ += n;
}
CONCEPT_REQUIRES(RandomAccessIncrementable<Val>())
difference_type_ distance_to(iota_view const &that) const
{
return detail::iota_minus(that.from_, from_);
}
public:
iota_view() = default;
iota_view(Val from, Val2 to)
: from_(std::move(from)), to_(std::move(to))
{}
};
template<typename Val>
struct iota_view<Val, void>
: range_facade<iota_view<Val, void>, true>
{
private:
using incrementable_concept_t = ranges::incrementable_concept<Val>;
friend range_access;
using difference_type_ = detail::iota_difference_t<Val>;
Val value_;
Val current() const
{
return value_;
}
void next()
{
++value_;
}
constexpr bool done() const
{
return false;
}
CONCEPT_REQUIRES(Incrementable<Val>())
bool equal(iota_view const &that) const
{
return that.value_ == value_;
}
CONCEPT_REQUIRES(BidirectionalIncrementable<Val>())
void prev()
{
--value_;
}
CONCEPT_REQUIRES(RandomAccessIncrementable<Val>())
void advance(difference_type_ n)
{
value_ += n;
}
CONCEPT_REQUIRES(RandomAccessIncrementable<Val>())
difference_type_ distance_to(iota_view const &that) const
{
return detail::iota_minus(that.value_, value_);
}
public:
iota_view() = default;
constexpr explicit iota_view(Val value)
: value_(detail::move(value))
{}
};
namespace view
{
struct iota_fn
{
private:
template<typename Val>
static take_view<iota_view<Val>>
impl(Val from, Val to, concepts::RandomAccessIncrementable *)
{
return {iota_view<Val>{std::move(from)}, detail::iota_minus(to, from) + 1};
}
template<typename Val, typename Val2>
static iota_view<Val, Val2>
impl(Val from, Val2 to, concepts::WeaklyIncrementable *)
{
return {std::move(from), std::move(to)};
}
public:
template<typename Val,
CONCEPT_REQUIRES_(WeaklyIncrementable<Val>())>
iota_view<Val> operator()(Val value) const
{
CONCEPT_ASSERT(WeaklyIncrementable<Val>());
return iota_view<Val>{std::move(value)};
}
template<typename Val, typename Val2,
CONCEPT_REQUIRES_(WeaklyIncrementable<Val>() && EqualityComparable<Val, Val2>())>
meta::if_<
meta::and_<RandomAccessIncrementable<Val>, Same<Val, Val2>>,
take_view<iota_view<Val>>,
iota_view<Val, Val2>>
operator()(Val from, Val2 to) const
{
CONCEPT_ASSERT(EqualityComparable<Val, Val2>());
return iota_fn::impl(std::move(from), std::move(to), incrementable_concept<Val>{});
}
#ifndef RANGES_DOXYGEN_INVOKED
template<typename Val,
CONCEPT_REQUIRES_(!WeaklyIncrementable<Val>())>
void operator()(Val) const
{
CONCEPT_ASSERT_MSG(WeaklyIncrementable<Val>(),
"The object passed to view::iota must model the WeaklyIncrementable concept; "
"that is, it must have pre- and post-increment operators and it must have a "
" difference_type");
}
template<typename Val, typename Val2,
CONCEPT_REQUIRES_(!(WeaklyIncrementable<Val>() && EqualityComparable<Val, Val2>()))>
void operator()(Val, Val2) const
{
CONCEPT_ASSERT_MSG(WeaklyIncrementable<Val>(),
"The object passed to view::iota must model the WeaklyIncrementable concept; "
"that is, it must have pre- and post-increment operators and it must have a "
" difference_type");
CONCEPT_ASSERT_MSG(EqualityComparable<Val, Val2>(),
"The two arguments passed to view::iota must be EqualityComparable with == and !=");
}
#endif
};
/// \relates iota_fn
/// \ingroup group-views
namespace
{
constexpr auto&& iota = static_const<iota_fn>::value;
}
struct ints_fn
: iota_view<int>
{
using iota_view<int>::iota_view;
template<typename Val,
CONCEPT_REQUIRES_(Integral<Val>())>
iota_view<Val> operator()(Val value) const
{
return iota_view<Val>{value};
}
template<typename Val,
CONCEPT_REQUIRES_(Integral<Val>())>
take_view<iota_view<Val>> operator()(Val from, Val to) const
{
return {iota_view<Val>{from}, detail::iota_minus(to, from) + 1};
}
#ifndef RANGES_DOXYGEN_INVOKED
template<typename Val,
CONCEPT_REQUIRES_(!Integral<Val>())>
void operator()(Val) const
{
CONCEPT_ASSERT_MSG(Integral<Val>(),
"The object passed to view::ints must be Integral");
}
template<typename Val,
CONCEPT_REQUIRES_(!Integral<Val>())>
void operator()(Val, Val) const
{
CONCEPT_ASSERT_MSG(Integral<Val>(),
"The object passed to view::ints must be Integral");
}
#endif
};
/// \relates ints_fn
/// \ingroup group-views
namespace
{
constexpr auto&& ints = static_const<ints_fn>::value;
}
}
/// @}
}
}
#endif
| 35.564033 | 108 | 0.488354 | [
"object",
"model"
] |
86d4f7368c0405ce24e4777d4794128f157af8bc | 12,331 | cc | C++ | Pods/gRPC-Core/src/core/ext/filters/client_channel/service_config.cc | siyanhu/covidwatch-ios | c6aafa01a5e4c517432e2f1b4cd074cb0f07193f | [
"Apache-2.0"
] | 201 | 2020-02-24T08:30:38.000Z | 2022-03-23T02:14:46.000Z | Pods/gRPC-Core/src/core/ext/filters/client_channel/service_config.cc | linaalkhodair/SightsApp | 070fa9319220071ce8fa5984ba98c2e719fed32e | [
"MIT"
] | 66 | 2020-03-28T13:56:20.000Z | 2020-05-01T14:21:10.000Z | iosApp/Pods/gRPC-Core/src/core/ext/filters/client_channel/service_config.cc | archiegq21/DroidconKotlin | 8c3ec05448d586037c924f245f77fcd0150f0476 | [
"Apache-2.0"
] | 54 | 2020-02-26T13:15:38.000Z | 2022-03-25T23:47:19.000Z | //
// Copyright 2015 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 <grpc/support/port_platform.h>
#include "src/core/ext/filters/client_channel/service_config.h"
#include <string.h>
#include <grpc/impl/codegen/grpc_types.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/json/json.h"
#include "src/core/lib/slice/slice_hash_table.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/slice/slice_string_helpers.h"
namespace grpc_core {
namespace {
typedef InlinedVector<UniquePtr<ServiceConfig::Parser>,
ServiceConfig::kNumPreallocatedParsers>
ServiceConfigParserList;
ServiceConfigParserList* g_registered_parsers;
} // namespace
RefCountedPtr<ServiceConfig> ServiceConfig::Create(const char* json,
grpc_error** error) {
UniquePtr<char> service_config_json(gpr_strdup(json));
UniquePtr<char> json_string(gpr_strdup(json));
GPR_DEBUG_ASSERT(error != nullptr);
grpc_json* json_tree = grpc_json_parse_string(json_string.get());
if (json_tree == nullptr) {
*error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"failed to parse JSON for service config");
return nullptr;
}
return MakeRefCounted<ServiceConfig>(
std::move(service_config_json), std::move(json_string), json_tree, error);
}
ServiceConfig::ServiceConfig(UniquePtr<char> service_config_json,
UniquePtr<char> json_string, grpc_json* json_tree,
grpc_error** error)
: service_config_json_(std::move(service_config_json)),
json_string_(std::move(json_string)),
json_tree_(json_tree) {
GPR_DEBUG_ASSERT(error != nullptr);
if (json_tree->type != GRPC_JSON_OBJECT || json_tree->key != nullptr) {
*error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"Malformed service Config JSON object");
return;
}
grpc_error* error_list[2];
int error_count = 0;
grpc_error* global_error = ParseGlobalParams(json_tree);
grpc_error* local_error = ParsePerMethodParams(json_tree);
if (global_error != GRPC_ERROR_NONE) {
error_list[error_count++] = global_error;
}
if (local_error != GRPC_ERROR_NONE) {
error_list[error_count++] = local_error;
}
if (error_count > 0) {
*error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
"Service config parsing error", error_list, error_count);
GRPC_ERROR_UNREF(global_error);
GRPC_ERROR_UNREF(local_error);
}
}
grpc_error* ServiceConfig::ParseGlobalParams(const grpc_json* json_tree) {
GPR_DEBUG_ASSERT(json_tree_->type == GRPC_JSON_OBJECT);
GPR_DEBUG_ASSERT(json_tree_->key == nullptr);
InlinedVector<grpc_error*, 4> error_list;
for (size_t i = 0; i < g_registered_parsers->size(); i++) {
grpc_error* parser_error = GRPC_ERROR_NONE;
auto parsed_obj =
(*g_registered_parsers)[i]->ParseGlobalParams(json_tree, &parser_error);
if (parser_error != GRPC_ERROR_NONE) {
error_list.push_back(parser_error);
}
parsed_global_service_config_objects_.push_back(std::move(parsed_obj));
}
return GRPC_ERROR_CREATE_FROM_VECTOR("Global Params", &error_list);
}
grpc_error* ServiceConfig::ParseJsonMethodConfigToServiceConfigObjectsTable(
const grpc_json* json,
SliceHashTable<const ServiceConfigObjectsVector*>::Entry* entries,
size_t* idx) {
auto objs_vector = MakeUnique<ServiceConfigObjectsVector>();
InlinedVector<grpc_error*, 4> error_list;
for (size_t i = 0; i < g_registered_parsers->size(); i++) {
grpc_error* parser_error = GRPC_ERROR_NONE;
auto parsed_obj =
(*g_registered_parsers)[i]->ParsePerMethodParams(json, &parser_error);
if (parser_error != GRPC_ERROR_NONE) {
error_list.push_back(parser_error);
}
objs_vector->push_back(std::move(parsed_obj));
}
service_config_objects_vectors_storage_.push_back(std::move(objs_vector));
const auto* vector_ptr =
service_config_objects_vectors_storage_
[service_config_objects_vectors_storage_.size() - 1]
.get();
// Construct list of paths.
InlinedVector<UniquePtr<char>, 10> paths;
for (grpc_json* child = json->child; child != nullptr; child = child->next) {
if (child->key == nullptr) continue;
if (strcmp(child->key, "name") == 0) {
if (child->type != GRPC_JSON_ARRAY) {
error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:name error:not of type Array"));
goto wrap_error;
}
for (grpc_json* name = child->child; name != nullptr; name = name->next) {
grpc_error* parse_error = GRPC_ERROR_NONE;
UniquePtr<char> path = ParseJsonMethodName(name, &parse_error);
if (path == nullptr) {
error_list.push_back(parse_error);
} else {
GPR_DEBUG_ASSERT(parse_error == GRPC_ERROR_NONE);
paths.push_back(std::move(path));
}
}
}
}
if (paths.size() == 0) {
error_list.push_back(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("No names specified"));
}
// Add entry for each path.
for (size_t i = 0; i < paths.size(); ++i) {
entries[*idx].key = grpc_slice_from_copied_string(paths[i].get());
entries[*idx].value = vector_ptr;
++*idx;
}
wrap_error:
return GRPC_ERROR_CREATE_FROM_VECTOR("methodConfig", &error_list);
}
grpc_error* ServiceConfig::ParsePerMethodParams(const grpc_json* json_tree) {
GPR_DEBUG_ASSERT(json_tree_->type == GRPC_JSON_OBJECT);
GPR_DEBUG_ASSERT(json_tree_->key == nullptr);
SliceHashTable<const ServiceConfigObjectsVector*>::Entry* entries = nullptr;
size_t num_entries = 0;
InlinedVector<grpc_error*, 4> error_list;
for (grpc_json* field = json_tree->child; field != nullptr;
field = field->next) {
if (field->key == nullptr) {
error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"error:Illegal key value - NULL"));
continue;
}
if (strcmp(field->key, "methodConfig") == 0) {
if (entries != nullptr) {
GPR_ASSERT(false);
}
if (field->type != GRPC_JSON_ARRAY) {
error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:methodConfig error:not of type Array"));
}
for (grpc_json* method = field->child; method != nullptr;
method = method->next) {
int count = CountNamesInMethodConfig(method);
if (count <= 0) {
error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:methodConfig error:No names found"));
}
num_entries += static_cast<size_t>(count);
}
entries = static_cast<
SliceHashTable<const ServiceConfigObjectsVector*>::Entry*>(gpr_zalloc(
num_entries *
sizeof(SliceHashTable<const ServiceConfigObjectsVector*>::Entry)));
size_t idx = 0;
for (grpc_json* method = field->child; method != nullptr;
method = method->next) {
grpc_error* error = ParseJsonMethodConfigToServiceConfigObjectsTable(
method, entries, &idx);
if (error != GRPC_ERROR_NONE) {
error_list.push_back(error);
}
}
// idx might not be equal to num_entries due to parsing errors
num_entries = idx;
break;
}
}
if (entries != nullptr) {
parsed_method_service_config_objects_table_ =
SliceHashTable<const ServiceConfigObjectsVector*>::Create(
num_entries, entries, nullptr);
gpr_free(entries);
}
return GRPC_ERROR_CREATE_FROM_VECTOR("Method Params", &error_list);
}
ServiceConfig::~ServiceConfig() { grpc_json_destroy(json_tree_); }
int ServiceConfig::CountNamesInMethodConfig(grpc_json* json) {
int num_names = 0;
for (grpc_json* field = json->child; field != nullptr; field = field->next) {
if (field->key != nullptr && strcmp(field->key, "name") == 0) {
if (field->type != GRPC_JSON_ARRAY) return -1;
for (grpc_json* name = field->child; name != nullptr; name = name->next) {
if (name->type != GRPC_JSON_OBJECT) return -1;
++num_names;
}
}
}
return num_names;
}
UniquePtr<char> ServiceConfig::ParseJsonMethodName(grpc_json* json,
grpc_error** error) {
if (json->type != GRPC_JSON_OBJECT) {
*error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:name error:type is not object");
return nullptr;
}
const char* service_name = nullptr;
const char* method_name = nullptr;
for (grpc_json* child = json->child; child != nullptr; child = child->next) {
if (child->key == nullptr) {
*error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:name error:Child entry with no key");
return nullptr;
}
if (child->type != GRPC_JSON_STRING) {
*error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:name error:Child entry not of type string");
return nullptr;
}
if (strcmp(child->key, "service") == 0) {
if (service_name != nullptr) {
*error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:name error: field:service error:Multiple entries");
return nullptr; // Duplicate.
}
if (child->value == nullptr) {
*error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:name error: field:service error:empty value");
return nullptr;
}
service_name = child->value;
} else if (strcmp(child->key, "method") == 0) {
if (method_name != nullptr) {
*error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:name error: field:method error:multiple entries");
return nullptr; // Duplicate.
}
if (child->value == nullptr) {
*error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:name error: field:method error:empty value");
return nullptr;
}
method_name = child->value;
}
}
if (service_name == nullptr) {
*error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:name error: field:service error:not found");
return nullptr; // Required field.
}
char* path;
gpr_asprintf(&path, "/%s/%s", service_name,
method_name == nullptr ? "*" : method_name);
return UniquePtr<char>(path);
}
const ServiceConfig::ServiceConfigObjectsVector*
ServiceConfig::GetMethodServiceConfigObjectsVector(const grpc_slice& path) {
if (parsed_method_service_config_objects_table_.get() == nullptr) {
return nullptr;
}
const auto* value = parsed_method_service_config_objects_table_->Get(path);
// If we didn't find a match for the path, try looking for a wildcard
// entry (i.e., change "/service/method" to "/service/*").
if (value == nullptr) {
char* path_str = grpc_slice_to_c_string(path);
const char* sep = strrchr(path_str, '/') + 1;
const size_t len = (size_t)(sep - path_str);
char* buf = (char*)gpr_malloc(len + 2); // '*' and NUL
memcpy(buf, path_str, len);
buf[len] = '*';
buf[len + 1] = '\0';
grpc_slice wildcard_path = grpc_slice_from_copied_string(buf);
gpr_free(buf);
value = parsed_method_service_config_objects_table_->Get(wildcard_path);
grpc_slice_unref_internal(wildcard_path);
gpr_free(path_str);
if (value == nullptr) return nullptr;
}
return *value;
}
size_t ServiceConfig::RegisterParser(UniquePtr<Parser> parser) {
g_registered_parsers->push_back(std::move(parser));
return g_registered_parsers->size() - 1;
}
void ServiceConfig::Init() {
GPR_ASSERT(g_registered_parsers == nullptr);
g_registered_parsers = New<ServiceConfigParserList>();
}
void ServiceConfig::Shutdown() {
Delete(g_registered_parsers);
g_registered_parsers = nullptr;
}
} // namespace grpc_core
| 37.141566 | 80 | 0.675776 | [
"object"
] |
86d6cec1049355bc6020aff017ec63487017e36a | 48,803 | cpp | C++ | Cesium3DTilesSelection/src/upgradeBatchTableToFeatureMetadata.cpp | JiangMuWen/cesium-native | 1d9912307336c833b74b7e9b7bc715d0a4e6c7ec | [
"Apache-2.0"
] | 2 | 2021-10-02T17:45:12.000Z | 2021-10-02T17:45:15.000Z | Cesium3DTilesSelection/src/upgradeBatchTableToFeatureMetadata.cpp | JiangMuWen/cesium-native | 1d9912307336c833b74b7e9b7bc715d0a4e6c7ec | [
"Apache-2.0"
] | null | null | null | Cesium3DTilesSelection/src/upgradeBatchTableToFeatureMetadata.cpp | JiangMuWen/cesium-native | 1d9912307336c833b74b7e9b7bc715d0a4e6c7ec | [
"Apache-2.0"
] | null | null | null | #include "upgradeBatchTableToFeatureMetadata.h"
#include "Cesium3DTilesSelection/spdlog-cesium.h"
#include <CesiumGltf/MeshPrimitiveEXT_feature_metadata.h>
#include <CesiumGltf/Model.h>
#include <CesiumGltf/ModelEXT_feature_metadata.h>
#include <CesiumGltf/PropertyType.h>
#include <CesiumGltf/PropertyTypeTraits.h>
#include <CesiumUtility/Tracing.h>
#include <glm/glm.hpp>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <map>
#include <type_traits>
using namespace CesiumGltf;
namespace {
struct MaskedType {
bool isInt8 = true;
bool isUint8 = true;
bool isInt16 = true;
bool isUint16 = true;
bool isInt32 = true;
bool isUint32 = true;
bool isInt64 = true;
bool isUint64 = true;
bool isFloat32 = true;
bool isFloat64 = true;
bool isBool = true;
bool isArray = true;
};
struct CompatibleTypes {
MaskedType type;
std::optional<MaskedType> componentType;
std::optional<uint32_t> minComponentCount;
std::optional<uint32_t> maxComponentCount;
};
struct BinaryProperty {
int64_t b3dmByteOffset;
int64_t gltfByteOffset;
int64_t byteLength;
};
struct GltfFeatureTableType {
std::string typeName;
size_t typeSize;
};
const std::map<std::string, GltfFeatureTableType> b3dmComponentTypeToGltfType =
{
{"BYTE", GltfFeatureTableType{"INT8", sizeof(int8_t)}},
{"UNSIGNED_BYTE", GltfFeatureTableType{"UINT8", sizeof(uint8_t)}},
{"SHORT", GltfFeatureTableType{"INT16", sizeof(int16_t)}},
{"UNSIGNED_SHORT", GltfFeatureTableType{"UINT16", sizeof(uint16_t)}},
{"INT", GltfFeatureTableType{"INT32", sizeof(int32_t)}},
{"UNSIGNED_INT", GltfFeatureTableType{"UINT32", sizeof(uint32_t)}},
{"FLOAT", GltfFeatureTableType{"FLOAT32", sizeof(float)}},
{"DOUBLE", GltfFeatureTableType{"FLOAT64", sizeof(double)}},
};
int64_t roundUp(int64_t num, int64_t multiple) noexcept {
return ((num + multiple - 1) / multiple) * multiple;
}
template <typename T> bool isInRangeForSignedInteger(int64_t value) noexcept {
// this only work if sizeof(T) is smaller than int64_t
static_assert(
!std::is_same_v<T, uint64_t> && !std::is_same_v<T, float> &&
!std::is_same_v<T, double>);
return value >= static_cast<int64_t>(std::numeric_limits<T>::lowest()) &&
value <= static_cast<int64_t>(std::numeric_limits<T>::max());
}
template <typename T>
bool isInRangeForUnsignedInteger(uint64_t value) noexcept {
static_assert(!std::is_signed_v<T>);
return value >= static_cast<uint64_t>(std::numeric_limits<T>::lowest()) &&
value <= static_cast<uint64_t>(std::numeric_limits<T>::max());
}
template <typename OffsetType>
void copyStringBuffer(
const rapidjson::StringBuffer& rapidjsonStrBuffer,
const std::vector<uint64_t>& rapidjsonOffsets,
std::vector<std::byte>& buffer,
std::vector<std::byte>& offsetBuffer) {
buffer.resize(rapidjsonStrBuffer.GetLength());
std::memcpy(buffer.data(), rapidjsonStrBuffer.GetString(), buffer.size());
offsetBuffer.resize(sizeof(OffsetType) * rapidjsonOffsets.size());
OffsetType* offset = reinterpret_cast<OffsetType*>(offsetBuffer.data());
for (size_t i = 0; i < rapidjsonOffsets.size(); ++i) {
offset[i] = static_cast<OffsetType>(rapidjsonOffsets[i]);
}
}
CompatibleTypes findCompatibleTypes(const rapidjson::Value& propertyValue) {
MaskedType type;
std::optional<MaskedType> componentType;
std::optional<uint32_t> minComponentCount;
std::optional<uint32_t> maxComponentCount;
for (auto it = propertyValue.Begin(); it != propertyValue.End(); ++it) {
if (it->IsBool()) {
// Should we allow conversion of bools to numeric 0 or 1? Nah.
type.isInt8 = type.isUint8 = false;
type.isInt16 = type.isUint16 = false;
type.isInt32 = type.isUint32 = false;
type.isInt64 = type.isUint64 = false;
type.isFloat32 = false;
type.isFloat64 = false;
type.isBool = true;
type.isArray = false;
} else if (it->IsInt64()) {
const int64_t value = it->GetInt64();
type.isInt8 &= isInRangeForSignedInteger<int8_t>(value);
type.isUint8 &= isInRangeForSignedInteger<uint8_t>(value);
type.isInt16 &= isInRangeForSignedInteger<int16_t>(value);
type.isUint16 &= isInRangeForSignedInteger<uint16_t>(value);
type.isInt32 &= isInRangeForSignedInteger<int32_t>(value);
type.isUint32 &= isInRangeForSignedInteger<uint32_t>(value);
type.isInt64 &= true;
type.isUint64 &= value >= 0;
type.isFloat32 &= it->IsLosslessFloat();
type.isFloat64 &= it->IsLosslessDouble();
type.isBool = false;
type.isArray = false;
} else if (it->IsUint64()) {
// Only uint64_t can represent a value that fits in a uint64_t but not in
// an int64_t.
type.isInt8 = type.isUint8 = false;
type.isInt16 = type.isUint16 = false;
type.isInt32 = type.isUint32 = false;
type.isInt64 = false;
type.isUint64 = true;
type.isFloat32 = false;
type.isFloat64 = false;
type.isBool = false;
type.isArray = false;
} else if (it->IsLosslessFloat()) {
type.isInt8 = type.isUint8 = false;
type.isInt16 = type.isUint16 = false;
type.isInt32 = type.isUint32 = false;
type.isInt64 = type.isUint64 = false;
type.isFloat32 = true;
type.isFloat64 = true;
type.isBool = false;
type.isArray = false;
} else if (it->IsDouble()) {
type.isInt8 = type.isUint8 = false;
type.isInt16 = type.isUint16 = false;
type.isInt32 = type.isUint32 = false;
type.isInt64 = type.isUint64 = false;
type.isFloat32 = false;
type.isFloat64 = true;
type.isBool = false;
type.isArray = false;
} else if (it->IsArray()) {
type.isInt8 = type.isUint8 = false;
type.isInt16 = type.isUint16 = false;
type.isInt32 = type.isUint32 = false;
type.isInt64 = type.isUint64 = false;
type.isFloat32 = false;
type.isFloat64 = false;
type.isBool = false;
type.isArray &= true;
CompatibleTypes currentComponentType = findCompatibleTypes(*it);
if (!componentType) {
componentType = currentComponentType.type;
} else {
componentType->isInt8 &= currentComponentType.type.isInt8;
componentType->isUint8 &= currentComponentType.type.isUint8;
componentType->isInt16 &= currentComponentType.type.isInt16;
componentType->isUint16 &= currentComponentType.type.isUint16;
componentType->isInt32 &= currentComponentType.type.isInt32;
componentType->isUint32 &= currentComponentType.type.isUint32;
componentType->isInt64 &= currentComponentType.type.isInt64;
componentType->isUint64 &= currentComponentType.type.isUint64;
componentType->isFloat32 &= currentComponentType.type.isFloat32;
componentType->isFloat64 &= currentComponentType.type.isFloat64;
componentType->isBool &= currentComponentType.type.isBool;
componentType->isArray &= currentComponentType.type.isArray;
}
maxComponentCount = maxComponentCount
? glm::max(*maxComponentCount, it->Size())
: it->Size();
minComponentCount = minComponentCount
? glm::min(*minComponentCount, it->Size())
: it->Size();
} else {
// A string, null, or something else.
type.isInt8 = type.isUint8 = false;
type.isInt16 = type.isUint16 = false;
type.isInt32 = type.isUint32 = false;
type.isInt64 = type.isUint64 = false;
type.isFloat32 = false;
type.isFloat64 = false;
type.isBool = false;
type.isArray = false;
}
}
return {type, componentType, minComponentCount, maxComponentCount};
}
void updateExtensionWithJsonStringProperty(
Model& gltf,
ClassProperty& classProperty,
const FeatureTable& featureTable,
FeatureTableProperty& featureTableProperty,
const rapidjson::Value& propertyValue) {
assert(propertyValue.Size() >= featureTable.count);
rapidjson::StringBuffer rapidjsonStrBuffer;
std::vector<uint64_t> rapidjsonOffsets;
rapidjsonOffsets.reserve(static_cast<size_t>(featureTable.count + 1));
rapidjsonOffsets.emplace_back(0);
auto it = propertyValue.Begin();
for (int64_t i = 0; i < featureTable.count; ++i) {
if (!it->IsString()) {
// Everything else that is not string will be serialized by json
rapidjson::Writer<rapidjson::StringBuffer> writer(rapidjsonStrBuffer);
it->Accept(writer);
} else {
// Because serialized string json will add double quotations in the buffer
// which is not needed by us, we will manually add the string to the
// buffer
const auto& rapidjsonStr = it->GetString();
rapidjsonStrBuffer.Reserve(it->GetStringLength());
for (rapidjson::SizeType j = 0; j < it->GetStringLength(); ++j) {
rapidjsonStrBuffer.PutUnsafe(rapidjsonStr[j]);
}
}
rapidjsonOffsets.emplace_back(rapidjsonStrBuffer.GetLength());
++it;
}
const uint64_t totalSize = rapidjsonOffsets.back();
std::vector<std::byte> buffer;
std::vector<std::byte> offsetBuffer;
if (isInRangeForUnsignedInteger<uint8_t>(totalSize)) {
copyStringBuffer<uint8_t>(
rapidjsonStrBuffer,
rapidjsonOffsets,
buffer,
offsetBuffer);
featureTableProperty.offsetType = "UINT8";
} else if (isInRangeForUnsignedInteger<uint16_t>(totalSize)) {
copyStringBuffer<uint16_t>(
rapidjsonStrBuffer,
rapidjsonOffsets,
buffer,
offsetBuffer);
featureTableProperty.offsetType = "UINT16";
} else if (isInRangeForUnsignedInteger<uint32_t>(totalSize)) {
copyStringBuffer<uint32_t>(
rapidjsonStrBuffer,
rapidjsonOffsets,
buffer,
offsetBuffer);
featureTableProperty.offsetType = "UINT32";
} else {
copyStringBuffer<uint64_t>(
rapidjsonStrBuffer,
rapidjsonOffsets,
buffer,
offsetBuffer);
featureTableProperty.offsetType = "UINT64";
}
Buffer& gltfBuffer = gltf.buffers.emplace_back();
gltfBuffer.byteLength = static_cast<int64_t>(buffer.size());
gltfBuffer.cesium.data = std::move(buffer);
BufferView& gltfBufferView = gltf.bufferViews.emplace_back();
gltfBufferView.buffer = static_cast<int32_t>(gltf.buffers.size() - 1);
gltfBufferView.byteOffset = 0;
gltfBufferView.byteLength = static_cast<int64_t>(totalSize);
const int32_t valueBufferViewIdx =
static_cast<int32_t>(gltf.bufferViews.size() - 1);
Buffer& gltfOffsetBuffer = gltf.buffers.emplace_back();
gltfOffsetBuffer.byteLength = static_cast<int64_t>(offsetBuffer.size());
gltfOffsetBuffer.cesium.data = std::move(offsetBuffer);
BufferView& gltfOffsetBufferView = gltf.bufferViews.emplace_back();
gltfOffsetBufferView.buffer = static_cast<int32_t>(gltf.buffers.size() - 1);
gltfOffsetBufferView.byteOffset = 0;
gltfOffsetBufferView.byteLength =
static_cast<int64_t>(gltfOffsetBuffer.cesium.data.size());
const int32_t offsetBufferViewIdx =
static_cast<int32_t>(gltf.bufferViews.size() - 1);
classProperty.type = "STRING";
featureTableProperty.bufferView = valueBufferViewIdx;
featureTableProperty.stringOffsetBufferView = offsetBufferViewIdx;
}
template <typename T, typename TRapidJson = T>
void updateExtensionWithJsonNumericProperty(
Model& gltf,
ClassProperty& classProperty,
const FeatureTable& featureTable,
FeatureTableProperty& featureTableProperty,
const rapidjson::Value& propertyValue,
const std::string& typeName) {
assert(propertyValue.Size() >= featureTable.count);
classProperty.type = typeName;
// Create a new buffer for this property.
const size_t bufferIndex = gltf.buffers.size();
Buffer& buffer = gltf.buffers.emplace_back();
buffer.byteLength =
static_cast<int64_t>(sizeof(T) * static_cast<size_t>(featureTable.count));
buffer.cesium.data.resize(static_cast<size_t>(buffer.byteLength));
const size_t bufferViewIndex = gltf.bufferViews.size();
BufferView& bufferView = gltf.bufferViews.emplace_back();
bufferView.buffer = int32_t(bufferIndex);
bufferView.byteOffset = 0;
bufferView.byteLength = buffer.byteLength;
featureTableProperty.bufferView = int32_t(bufferViewIndex);
T* p = reinterpret_cast<T*>(buffer.cesium.data.data());
auto it = propertyValue.Begin();
for (int64_t i = 0; i < featureTable.count; ++i) {
*p = static_cast<T>(it->Get<TRapidJson>());
++p;
++it;
}
}
void updateExtensionWithJsonBoolProperty(
Model& gltf,
ClassProperty& classProperty,
const FeatureTable& featureTable,
FeatureTableProperty& featureTableProperty,
const rapidjson::Value& propertyValue) {
assert(propertyValue.Size() >= featureTable.count);
std::vector<std::byte> data(static_cast<size_t>(
glm::ceil(static_cast<double>(featureTable.count) / 8.0)));
const auto& jsonArray = propertyValue.GetArray();
for (rapidjson::SizeType i = 0;
i < static_cast<rapidjson::SizeType>(featureTable.count);
++i) {
const bool value = jsonArray[i].GetBool();
const size_t byteIndex = i / 8;
const size_t bitIndex = i % 8;
data[byteIndex] =
static_cast<std::byte>(value << bitIndex) | data[byteIndex];
}
const size_t bufferIndex = gltf.buffers.size();
Buffer& buffer = gltf.buffers.emplace_back();
buffer.byteLength = static_cast<int64_t>(data.size());
buffer.cesium.data = std::move(data);
BufferView& bufferView = gltf.bufferViews.emplace_back();
bufferView.buffer = static_cast<int32_t>(bufferIndex);
bufferView.byteOffset = 0;
bufferView.byteLength = buffer.byteLength;
featureTableProperty.bufferView =
static_cast<int32_t>(gltf.bufferViews.size() - 1);
classProperty.type = "BOOLEAN";
}
template <typename TRapidjson, typename ValueType, typename OffsetType>
void copyNumericDynamicArrayBuffers(
std::vector<std::byte>& valueBuffer,
std::vector<std::byte>& offsetBuffer,
size_t numOfElements,
const FeatureTable& featureTable,
const rapidjson::Value& propertyValue) {
valueBuffer.resize(sizeof(ValueType) * numOfElements);
offsetBuffer.resize(
sizeof(OffsetType) * static_cast<size_t>(featureTable.count + 1));
ValueType* value = reinterpret_cast<ValueType*>(valueBuffer.data());
OffsetType* offsetValue = reinterpret_cast<OffsetType*>(offsetBuffer.data());
OffsetType prevOffset = 0;
const auto& jsonOuterArray = propertyValue.GetArray();
for (int64_t i = 0; i < featureTable.count; ++i) {
const auto& jsonArrayMember =
jsonOuterArray[static_cast<rapidjson::SizeType>(i)];
*offsetValue = prevOffset;
++offsetValue;
for (const auto& valueJson : jsonArrayMember.GetArray()) {
*value = static_cast<ValueType>(valueJson.Get<TRapidjson>());
++value;
}
prevOffset = static_cast<OffsetType>(
prevOffset + jsonArrayMember.Size() * sizeof(ValueType));
}
*offsetValue = prevOffset;
}
template <typename TRapidjson, typename ValueType>
void updateNumericArrayProperty(
Model& gltf,
ClassProperty& classProperty,
FeatureTableProperty& featureTableProperty,
const FeatureTable& featureTable,
const CompatibleTypes& compatibleTypes,
const rapidjson::Value& propertyValue) {
assert(propertyValue.Size() >= featureTable.count);
const auto& jsonOuterArray = propertyValue.GetArray();
// check if it's a fixed array
if (compatibleTypes.minComponentCount == compatibleTypes.maxComponentCount) {
const size_t numOfValues = static_cast<size_t>(featureTable.count) *
*compatibleTypes.minComponentCount;
std::vector<std::byte> valueBuffer(sizeof(ValueType) * numOfValues);
ValueType* value = reinterpret_cast<ValueType*>(valueBuffer.data());
for (int64_t i = 0; i < featureTable.count; ++i) {
const auto& jsonArrayMember =
jsonOuterArray[static_cast<rapidjson::SizeType>(i)];
for (const auto& valueJson : jsonArrayMember.GetArray()) {
*value = static_cast<ValueType>(valueJson.Get<TRapidjson>());
++value;
}
}
Buffer& gltfValueBuffer = gltf.buffers.emplace_back();
gltfValueBuffer.byteLength = static_cast<int64_t>(valueBuffer.size());
gltfValueBuffer.cesium.data = std::move(valueBuffer);
BufferView& gltfValueBufferView = gltf.bufferViews.emplace_back();
gltfValueBufferView.buffer = static_cast<int32_t>(gltf.buffers.size() - 1);
gltfValueBufferView.byteOffset = 0;
gltfValueBufferView.byteLength =
static_cast<int64_t>(gltfValueBuffer.cesium.data.size());
classProperty.type = "ARRAY";
classProperty.componentType = convertPropertyTypeToString(
static_cast<PropertyType>(TypeToPropertyType<ValueType>::value));
classProperty.componentCount = *compatibleTypes.minComponentCount;
featureTableProperty.bufferView =
static_cast<int32_t>(gltf.bufferViews.size() - 1);
return;
}
// total size of value buffer
size_t numOfElements = 0;
for (int64_t i = 0; i < featureTable.count; ++i) {
const auto& jsonArrayMember =
jsonOuterArray[static_cast<rapidjson::SizeType>(i)];
numOfElements += jsonArrayMember.Size();
}
PropertyType offsetType = PropertyType::None;
std::vector<std::byte> valueBuffer;
std::vector<std::byte> offsetBuffer;
const uint64_t maxOffsetValue = numOfElements * sizeof(ValueType);
if (isInRangeForUnsignedInteger<uint8_t>(maxOffsetValue)) {
copyNumericDynamicArrayBuffers<TRapidjson, ValueType, uint8_t>(
valueBuffer,
offsetBuffer,
numOfElements,
featureTable,
propertyValue);
offsetType = PropertyType::Uint8;
} else if (isInRangeForUnsignedInteger<uint16_t>(maxOffsetValue)) {
copyNumericDynamicArrayBuffers<TRapidjson, ValueType, uint16_t>(
valueBuffer,
offsetBuffer,
numOfElements,
featureTable,
propertyValue);
offsetType = PropertyType::Uint16;
} else if (isInRangeForUnsignedInteger<uint32_t>(maxOffsetValue)) {
copyNumericDynamicArrayBuffers<TRapidjson, ValueType, uint32_t>(
valueBuffer,
offsetBuffer,
numOfElements,
featureTable,
propertyValue);
offsetType = PropertyType::Uint32;
} else if (isInRangeForUnsignedInteger<uint64_t>(maxOffsetValue)) {
copyNumericDynamicArrayBuffers<TRapidjson, ValueType, uint64_t>(
valueBuffer,
offsetBuffer,
numOfElements,
featureTable,
propertyValue);
offsetType = PropertyType::Uint64;
}
Buffer& gltfValueBuffer = gltf.buffers.emplace_back();
gltfValueBuffer.byteLength = static_cast<int64_t>(valueBuffer.size());
gltfValueBuffer.cesium.data = std::move(valueBuffer);
BufferView& gltfValueBufferView = gltf.bufferViews.emplace_back();
gltfValueBufferView.buffer = static_cast<int32_t>(gltf.buffers.size() - 1);
gltfValueBufferView.byteOffset = 0;
gltfValueBufferView.byteLength =
static_cast<int64_t>(gltfValueBuffer.cesium.data.size());
const int32_t valueBufferIdx =
static_cast<int32_t>(gltf.bufferViews.size() - 1);
Buffer& gltfOffsetBuffer = gltf.buffers.emplace_back();
gltfOffsetBuffer.byteLength = static_cast<int64_t>(offsetBuffer.size());
gltfOffsetBuffer.cesium.data = std::move(offsetBuffer);
BufferView& gltfOffsetBufferView = gltf.bufferViews.emplace_back();
gltfOffsetBufferView.buffer = static_cast<int32_t>(gltf.buffers.size() - 1);
gltfOffsetBufferView.byteOffset = 0;
gltfOffsetBufferView.byteLength =
static_cast<int64_t>(gltfOffsetBuffer.cesium.data.size());
const int32_t offsetBufferIdx =
static_cast<int32_t>(gltf.bufferViews.size() - 1);
classProperty.type = "ARRAY";
classProperty.componentType = convertPropertyTypeToString(
static_cast<PropertyType>(TypeToPropertyType<ValueType>::value));
featureTableProperty.bufferView = valueBufferIdx;
featureTableProperty.arrayOffsetBufferView = offsetBufferIdx;
featureTableProperty.offsetType = convertPropertyTypeToString(offsetType);
}
template <typename OffsetType>
void copyStringArrayBuffers(
std::vector<std::byte>& valueBuffer,
std::vector<std::byte>& offsetBuffer,
size_t totalByteLength,
size_t numOfString,
const FeatureTable& featureTable,
const rapidjson::Value& propertyValue) {
valueBuffer.resize(totalByteLength);
offsetBuffer.resize((numOfString + 1) * sizeof(OffsetType));
OffsetType offset = 0;
size_t offsetIndex = 0;
const auto& jsonOuterArray = propertyValue.GetArray();
for (int64_t i = 0; i < featureTable.count; ++i) {
const auto& arrayMember =
jsonOuterArray[static_cast<rapidjson::SizeType>(i)];
for (const auto& str : arrayMember.GetArray()) {
OffsetType byteLength = static_cast<OffsetType>(
str.GetStringLength() * sizeof(rapidjson::Value::Ch));
std::memcpy(valueBuffer.data() + offset, str.GetString(), byteLength);
std::memcpy(
offsetBuffer.data() + offsetIndex * sizeof(OffsetType),
&offset,
sizeof(OffsetType));
offset = static_cast<OffsetType>(offset + byteLength);
++offsetIndex;
}
}
std::memcpy(
offsetBuffer.data() + offsetIndex * sizeof(OffsetType),
&offset,
sizeof(OffsetType));
}
template <typename OffsetType>
void copyArrayOffsetBufferForStringArrayProperty(
std::vector<std::byte>& offsetBuffer,
const FeatureTable& featureTable,
const rapidjson::Value& propertyValue) {
OffsetType prevOffset = 0;
offsetBuffer.resize(
static_cast<size_t>(featureTable.count + 1) * sizeof(OffsetType));
OffsetType* offset = reinterpret_cast<OffsetType*>(offsetBuffer.data());
const auto& jsonOuterArray = propertyValue.GetArray();
for (int64_t i = 0; i < featureTable.count; ++i) {
const auto& arrayMember =
jsonOuterArray[static_cast<rapidjson::SizeType>(i)];
*offset = prevOffset;
prevOffset = static_cast<OffsetType>(
prevOffset + arrayMember.Size() * sizeof(OffsetType));
++offset;
}
*offset = prevOffset;
}
void updateStringArrayProperty(
Model& gltf,
ClassProperty& classProperty,
FeatureTableProperty& featureTableProperty,
const FeatureTable& featureTable,
const CompatibleTypes& compatibleTypes,
const rapidjson::Value& propertyValue) {
assert(propertyValue.Size() >= featureTable.count);
size_t numOfString = 0;
size_t totalChars = 0;
const auto& jsonOuterArray = propertyValue.GetArray();
for (int64_t i = 0; i < featureTable.count; ++i) {
const auto& arrayMember =
jsonOuterArray[static_cast<rapidjson::SizeType>(i)];
numOfString += arrayMember.Size();
for (const auto& str : arrayMember.GetArray()) {
totalChars += str.GetStringLength();
}
}
const uint64_t totalByteLength = totalChars * sizeof(rapidjson::Value::Ch);
std::vector<std::byte> valueBuffer;
std::vector<std::byte> offsetBuffer;
PropertyType offsetType = PropertyType::None;
if (isInRangeForUnsignedInteger<uint8_t>(totalByteLength)) {
copyStringArrayBuffers<uint8_t>(
valueBuffer,
offsetBuffer,
totalByteLength,
numOfString,
featureTable,
propertyValue);
offsetType = PropertyType::Uint8;
} else if (isInRangeForUnsignedInteger<uint16_t>(totalByteLength)) {
copyStringArrayBuffers<uint16_t>(
valueBuffer,
offsetBuffer,
totalByteLength,
numOfString,
featureTable,
propertyValue);
offsetType = PropertyType::Uint16;
} else if (isInRangeForUnsignedInteger<uint32_t>(totalByteLength)) {
copyStringArrayBuffers<uint32_t>(
valueBuffer,
offsetBuffer,
totalByteLength,
numOfString,
featureTable,
propertyValue);
offsetType = PropertyType::Uint32;
} else if (isInRangeForUnsignedInteger<uint64_t>(totalByteLength)) {
copyStringArrayBuffers<uint64_t>(
valueBuffer,
offsetBuffer,
totalByteLength,
numOfString,
featureTable,
propertyValue);
offsetType = PropertyType::Uint64;
}
// create gltf value buffer view
Buffer& gltfValueBuffer = gltf.buffers.emplace_back();
gltfValueBuffer.byteLength = static_cast<int64_t>(valueBuffer.size());
gltfValueBuffer.cesium.data = std::move(valueBuffer);
BufferView& gltfValueBufferView = gltf.bufferViews.emplace_back();
gltfValueBufferView.buffer =
static_cast<std::int32_t>(gltf.buffers.size() - 1);
gltfValueBufferView.byteOffset = 0;
gltfValueBufferView.byteLength = gltfValueBuffer.byteLength;
const int32_t valueBufferViewIdx =
static_cast<int32_t>(gltf.bufferViews.size() - 1);
// create gltf string offset buffer view
Buffer& gltfOffsetBuffer = gltf.buffers.emplace_back();
gltfOffsetBuffer.byteLength = static_cast<int64_t>(offsetBuffer.size());
gltfOffsetBuffer.cesium.data = std::move(offsetBuffer);
BufferView& gltfOffsetBufferView = gltf.bufferViews.emplace_back();
gltfOffsetBufferView.buffer = static_cast<int32_t>(gltf.buffers.size() - 1);
gltfOffsetBufferView.byteOffset = 0;
gltfOffsetBufferView.byteLength = gltfOffsetBuffer.byteLength;
const int32_t offsetBufferViewIdx =
static_cast<int32_t>(gltf.bufferViews.size() - 1);
// fixed array of string
if (compatibleTypes.minComponentCount == compatibleTypes.maxComponentCount) {
classProperty.type = "ARRAY";
classProperty.componentCount = compatibleTypes.minComponentCount;
classProperty.componentType = "STRING";
featureTableProperty.bufferView = valueBufferViewIdx;
featureTableProperty.stringOffsetBufferView = offsetBufferViewIdx;
featureTableProperty.offsetType = convertPropertyTypeToString(offsetType);
return;
}
// dynamic array of string needs array offset buffer
std::vector<std::byte> arrayOffsetBuffer;
switch (offsetType) {
case PropertyType::Uint8:
copyArrayOffsetBufferForStringArrayProperty<uint8_t>(
arrayOffsetBuffer,
featureTable,
propertyValue);
break;
case PropertyType::Uint16:
copyArrayOffsetBufferForStringArrayProperty<uint16_t>(
arrayOffsetBuffer,
featureTable,
propertyValue);
break;
case PropertyType::Uint32:
copyArrayOffsetBufferForStringArrayProperty<uint32_t>(
arrayOffsetBuffer,
featureTable,
propertyValue);
break;
case PropertyType::Uint64:
copyArrayOffsetBufferForStringArrayProperty<uint64_t>(
arrayOffsetBuffer,
featureTable,
propertyValue);
break;
default:
break;
}
// create gltf array offset buffer view
Buffer& gltfArrayOffsetBuffer = gltf.buffers.emplace_back();
gltfArrayOffsetBuffer.byteLength =
static_cast<int64_t>(arrayOffsetBuffer.size());
gltfArrayOffsetBuffer.cesium.data = std::move(arrayOffsetBuffer);
BufferView& gltfArrayOffsetBufferView = gltf.bufferViews.emplace_back();
gltfArrayOffsetBufferView.buffer =
static_cast<int32_t>(gltf.buffers.size() - 1);
gltfArrayOffsetBufferView.byteOffset = 0;
gltfArrayOffsetBufferView.byteLength = gltfArrayOffsetBuffer.byteLength;
const int32_t arrayOffsetBufferViewIdx =
static_cast<int32_t>(gltf.bufferViews.size() - 1);
classProperty.type = "ARRAY";
classProperty.componentType = "STRING";
featureTableProperty.bufferView = valueBufferViewIdx;
featureTableProperty.arrayOffsetBufferView = arrayOffsetBufferViewIdx;
featureTableProperty.stringOffsetBufferView = offsetBufferViewIdx;
featureTableProperty.offsetType = convertPropertyTypeToString(offsetType);
}
template <typename OffsetType>
void copyBooleanArrayBuffers(
std::vector<std::byte>& valueBuffer,
std::vector<std::byte>& offsetBuffer,
size_t numOfElements,
const FeatureTable& featureTable,
const rapidjson::Value& propertyValue) {
size_t currentIndex = 0;
const size_t totalByteLength =
static_cast<size_t>(glm::ceil(static_cast<double>(numOfElements) / 8.0));
valueBuffer.resize(totalByteLength);
offsetBuffer.resize(
static_cast<size_t>(featureTable.count + 1) * sizeof(OffsetType));
OffsetType* offset = reinterpret_cast<OffsetType*>(offsetBuffer.data());
OffsetType prevOffset = 0;
const auto& jsonOuterArray = propertyValue.GetArray();
for (int64_t i = 0; i < featureTable.count; ++i) {
const auto& arrayMember =
jsonOuterArray[static_cast<rapidjson::SizeType>(i)];
*offset = prevOffset;
++offset;
prevOffset = static_cast<OffsetType>(prevOffset + arrayMember.Size());
for (const auto& data : arrayMember.GetArray()) {
const bool value = data.GetBool();
const size_t byteIndex = currentIndex / 8;
const size_t bitIndex = currentIndex % 8;
valueBuffer[byteIndex] =
static_cast<std::byte>(value << bitIndex) | valueBuffer[byteIndex];
++currentIndex;
}
}
*offset = prevOffset;
}
void updateBooleanArrayProperty(
Model& gltf,
ClassProperty& classProperty,
FeatureTableProperty& featureTableProperty,
const FeatureTable& featureTable,
const CompatibleTypes& compatibleTypes,
const rapidjson::Value& propertyValue) {
assert(propertyValue.Size() >= featureTable.count);
// fixed array of boolean
if (compatibleTypes.minComponentCount == compatibleTypes.maxComponentCount) {
const size_t numOfElements = static_cast<size_t>(
featureTable.count * compatibleTypes.minComponentCount.value());
const size_t totalByteLength = static_cast<size_t>(
glm::ceil(static_cast<double>(numOfElements) / 8.0));
std::vector<std::byte> valueBuffer(totalByteLength);
size_t currentIndex = 0;
const auto& jsonOuterArray = propertyValue.GetArray();
for (int64_t i = 0; i < featureTable.count; ++i) {
const auto& arrayMember =
jsonOuterArray[static_cast<rapidjson::SizeType>(i)];
for (const auto& data : arrayMember.GetArray()) {
const bool value = data.GetBool();
const size_t byteIndex = currentIndex / 8;
const size_t bitIndex = currentIndex % 8;
valueBuffer[byteIndex] =
static_cast<std::byte>(value << bitIndex) | valueBuffer[byteIndex];
++currentIndex;
}
}
Buffer& gltfValueBuffer = gltf.buffers.emplace_back();
gltfValueBuffer.byteLength = static_cast<int64_t>(valueBuffer.size());
gltfValueBuffer.cesium.data = std::move(valueBuffer);
BufferView& gltfValueBufferView = gltf.bufferViews.emplace_back();
gltfValueBufferView.buffer = static_cast<int32_t>(gltf.buffers.size() - 1);
gltfValueBufferView.byteOffset = 0;
gltfValueBufferView.byteLength = gltfValueBuffer.byteLength;
classProperty.type = "ARRAY";
classProperty.componentCount = compatibleTypes.minComponentCount;
classProperty.componentType = "BOOLEAN";
featureTableProperty.bufferView =
static_cast<int32_t>(gltf.bufferViews.size() - 1);
return;
}
// dynamic array of boolean
size_t numOfElements = 0;
const auto& jsonOuterArray = propertyValue.GetArray();
for (int64_t i = 0; i < featureTable.count; ++i) {
const auto& arrayMember =
jsonOuterArray[static_cast<rapidjson::SizeType>(i)];
numOfElements += arrayMember.Size();
}
std::vector<std::byte> valueBuffer;
std::vector<std::byte> offsetBuffer;
PropertyType offsetType = PropertyType::None;
if (isInRangeForUnsignedInteger<uint8_t>(numOfElements)) {
copyBooleanArrayBuffers<uint8_t>(
valueBuffer,
offsetBuffer,
numOfElements,
featureTable,
propertyValue);
offsetType = PropertyType::Uint8;
} else if (isInRangeForUnsignedInteger<uint16_t>(numOfElements)) {
copyBooleanArrayBuffers<uint16_t>(
valueBuffer,
offsetBuffer,
numOfElements,
featureTable,
propertyValue);
offsetType = PropertyType::Uint16;
} else if (isInRangeForUnsignedInteger<uint32_t>(numOfElements)) {
copyBooleanArrayBuffers<uint32_t>(
valueBuffer,
offsetBuffer,
numOfElements,
featureTable,
propertyValue);
offsetType = PropertyType::Uint32;
} else {
copyBooleanArrayBuffers<uint64_t>(
valueBuffer,
offsetBuffer,
numOfElements,
featureTable,
propertyValue);
offsetType = PropertyType::Uint64;
}
Buffer& gltfValueBuffer = gltf.buffers.emplace_back();
gltfValueBuffer.byteLength = static_cast<int64_t>(valueBuffer.size());
gltfValueBuffer.cesium.data = std::move(valueBuffer);
BufferView& gltfValueBufferView = gltf.bufferViews.emplace_back();
gltfValueBufferView.buffer = static_cast<int32_t>(gltf.buffers.size() - 1);
gltfValueBufferView.byteOffset = 0;
gltfValueBufferView.byteLength =
static_cast<int64_t>(gltfValueBuffer.cesium.data.size());
const int32_t valueBufferIdx =
static_cast<int32_t>(gltf.bufferViews.size() - 1);
Buffer& gltfOffsetBuffer = gltf.buffers.emplace_back();
gltfOffsetBuffer.byteLength = static_cast<int64_t>(offsetBuffer.size());
gltfOffsetBuffer.cesium.data = std::move(offsetBuffer);
BufferView& gltfOffsetBufferView = gltf.bufferViews.emplace_back();
gltfOffsetBufferView.buffer = static_cast<int32_t>(gltf.buffers.size() - 1);
gltfOffsetBufferView.byteOffset = 0;
gltfOffsetBufferView.byteLength =
static_cast<int64_t>(gltfOffsetBuffer.cesium.data.size());
const int32_t offsetBufferIdx =
static_cast<int32_t>(gltf.bufferViews.size() - 1);
classProperty.type = "ARRAY";
classProperty.componentType = "BOOLEAN";
featureTableProperty.bufferView = valueBufferIdx;
featureTableProperty.arrayOffsetBufferView = offsetBufferIdx;
featureTableProperty.offsetType = convertPropertyTypeToString(offsetType);
}
void updateExtensionWithArrayProperty(
Model& gltf,
ClassProperty& classProperty,
const FeatureTable& featureTable,
FeatureTableProperty& featureTableProperty,
const CompatibleTypes& compatibleTypes,
const rapidjson::Value& propertyValue) {
assert(propertyValue.Size() >= featureTable.count);
if (compatibleTypes.componentType->isBool) {
updateBooleanArrayProperty(
gltf,
classProperty,
featureTableProperty,
featureTable,
compatibleTypes,
propertyValue);
} else if (compatibleTypes.componentType->isInt8) {
updateNumericArrayProperty<int32_t, int8_t>(
gltf,
classProperty,
featureTableProperty,
featureTable,
compatibleTypes,
propertyValue);
} else if (compatibleTypes.componentType->isUint8) {
updateNumericArrayProperty<uint32_t, uint8_t>(
gltf,
classProperty,
featureTableProperty,
featureTable,
compatibleTypes,
propertyValue);
} else if (compatibleTypes.componentType->isInt16) {
updateNumericArrayProperty<int32_t, int16_t>(
gltf,
classProperty,
featureTableProperty,
featureTable,
compatibleTypes,
propertyValue);
} else if (compatibleTypes.componentType->isUint16) {
updateNumericArrayProperty<uint32_t, uint16_t>(
gltf,
classProperty,
featureTableProperty,
featureTable,
compatibleTypes,
propertyValue);
} else if (compatibleTypes.componentType->isInt32) {
updateNumericArrayProperty<int32_t, int32_t>(
gltf,
classProperty,
featureTableProperty,
featureTable,
compatibleTypes,
propertyValue);
} else if (compatibleTypes.componentType->isUint32) {
updateNumericArrayProperty<uint32_t, uint32_t>(
gltf,
classProperty,
featureTableProperty,
featureTable,
compatibleTypes,
propertyValue);
} else if (compatibleTypes.componentType->isInt64) {
updateNumericArrayProperty<int64_t, int64_t>(
gltf,
classProperty,
featureTableProperty,
featureTable,
compatibleTypes,
propertyValue);
} else if (compatibleTypes.componentType->isUint64) {
updateNumericArrayProperty<uint64_t, uint64_t>(
gltf,
classProperty,
featureTableProperty,
featureTable,
compatibleTypes,
propertyValue);
} else if (compatibleTypes.componentType->isFloat32) {
updateNumericArrayProperty<float, float>(
gltf,
classProperty,
featureTableProperty,
featureTable,
compatibleTypes,
propertyValue);
} else if (compatibleTypes.componentType->isFloat64) {
updateNumericArrayProperty<double, double>(
gltf,
classProperty,
featureTableProperty,
featureTable,
compatibleTypes,
propertyValue);
} else {
updateStringArrayProperty(
gltf,
classProperty,
featureTableProperty,
featureTable,
compatibleTypes,
propertyValue);
}
}
void updateExtensionWithJsonProperty(
Model& gltf,
ClassProperty& classProperty,
const FeatureTable& featureTable,
FeatureTableProperty& featureTableProperty,
const rapidjson::Value& propertyValue) {
if (propertyValue.Empty() || propertyValue.Size() < featureTable.count) {
// No property to infer the type from, so assume string.
updateExtensionWithJsonStringProperty(
gltf,
classProperty,
featureTable,
featureTableProperty,
propertyValue);
return;
}
// Figure out which types we can use for this data.
// Use the smallest type we can, and prefer signed to unsigned.
const CompatibleTypes compatibleTypes = findCompatibleTypes(propertyValue);
if (compatibleTypes.type.isBool) {
updateExtensionWithJsonBoolProperty(
gltf,
classProperty,
featureTable,
featureTableProperty,
propertyValue);
} else if (compatibleTypes.type.isInt8) {
updateExtensionWithJsonNumericProperty<int8_t, int32_t>(
gltf,
classProperty,
featureTable,
featureTableProperty,
propertyValue,
"INT8");
} else if (compatibleTypes.type.isUint8) {
updateExtensionWithJsonNumericProperty<uint8_t, uint32_t>(
gltf,
classProperty,
featureTable,
featureTableProperty,
propertyValue,
"UINT8");
} else if (compatibleTypes.type.isInt16) {
updateExtensionWithJsonNumericProperty<int16_t, int32_t>(
gltf,
classProperty,
featureTable,
featureTableProperty,
propertyValue,
"INT16");
} else if (compatibleTypes.type.isUint16) {
updateExtensionWithJsonNumericProperty<uint16_t, uint32_t>(
gltf,
classProperty,
featureTable,
featureTableProperty,
propertyValue,
"UINT16");
} else if (compatibleTypes.type.isInt32) {
updateExtensionWithJsonNumericProperty<int32_t>(
gltf,
classProperty,
featureTable,
featureTableProperty,
propertyValue,
"INT32");
} else if (compatibleTypes.type.isUint32) {
updateExtensionWithJsonNumericProperty<uint32_t>(
gltf,
classProperty,
featureTable,
featureTableProperty,
propertyValue,
"UINT32");
} else if (compatibleTypes.type.isInt64) {
updateExtensionWithJsonNumericProperty<int64_t>(
gltf,
classProperty,
featureTable,
featureTableProperty,
propertyValue,
"INT64");
} else if (compatibleTypes.type.isUint64) {
updateExtensionWithJsonNumericProperty<uint64_t>(
gltf,
classProperty,
featureTable,
featureTableProperty,
propertyValue,
"UINT64");
} else if (compatibleTypes.type.isFloat32) {
updateExtensionWithJsonNumericProperty<float>(
gltf,
classProperty,
featureTable,
featureTableProperty,
propertyValue,
"FLOAT32");
} else if (compatibleTypes.type.isFloat64) {
updateExtensionWithJsonNumericProperty<double>(
gltf,
classProperty,
featureTable,
featureTableProperty,
propertyValue,
"FLOAT64");
} else if (compatibleTypes.type.isArray) {
updateExtensionWithArrayProperty(
gltf,
classProperty,
featureTable,
featureTableProperty,
compatibleTypes,
propertyValue);
} else {
updateExtensionWithJsonStringProperty(
gltf,
classProperty,
featureTable,
featureTableProperty,
propertyValue);
}
}
void updateExtensionWithBinaryProperty(
Model& gltf,
int32_t gltfBufferIndex,
int64_t gltfBufferOffset,
BinaryProperty& binaryProperty,
ClassProperty& classProperty,
const FeatureTable& featureTable,
FeatureTableProperty& featureTableProperty,
const std::string& propertyName,
const rapidjson::Value& propertyValue,
const std::shared_ptr<spdlog::logger>& pLogger) {
assert(
gltfBufferIndex >= 0 &&
"gltfBufferIndex is negative. Need to allocate buffer before "
"convert the binary property");
const auto& byteOffsetIt = propertyValue.FindMember("byteOffset");
if (byteOffsetIt == propertyValue.MemberEnd() ||
!byteOffsetIt->value.IsInt64()) {
SPDLOG_LOGGER_WARN(
pLogger,
"Skip convert {}. The binary property doesn't have required "
"byteOffset.",
propertyName);
return;
}
const auto& componentTypeIt = propertyValue.FindMember("componentType");
if (componentTypeIt == propertyValue.MemberEnd() ||
!componentTypeIt->value.IsString()) {
SPDLOG_LOGGER_WARN(
pLogger,
"Skip convert {}. The binary property doesn't have required "
"componentType.",
propertyName);
return;
}
const auto& typeIt = propertyValue.FindMember("type");
if (typeIt == propertyValue.MemberEnd() || !typeIt->value.IsString()) {
SPDLOG_LOGGER_WARN(
pLogger,
"Skip convert {}. The binary property doesn't have required type.",
propertyName);
return;
}
// convert class property
const int64_t byteOffset = byteOffsetIt->value.GetInt64();
const std::string& componentType = componentTypeIt->value.GetString();
const std::string& type = typeIt->value.GetString();
auto convertedTypeIt = b3dmComponentTypeToGltfType.find(componentType);
if (convertedTypeIt == b3dmComponentTypeToGltfType.end()) {
return;
}
const GltfFeatureTableType& gltfType = convertedTypeIt->second;
size_t componentCount = 1;
if (type == "SCALAR") {
classProperty.type = gltfType.typeName;
} else if (type == "VEC2") {
classProperty.type = "ARRAY";
classProperty.componentCount = 2;
classProperty.componentType = gltfType.typeName;
componentCount = 2;
} else if (type == "VEC3") {
classProperty.type = "ARRAY";
classProperty.componentCount = 3;
classProperty.componentType = gltfType.typeName;
componentCount = 3;
} else if (type == "VEC4") {
classProperty.type = "ARRAY";
classProperty.componentCount = 4;
classProperty.componentType = gltfType.typeName;
componentCount = 4;
} else {
return;
}
// convert feature table
const size_t typeSize = gltfType.typeSize;
auto& bufferView = gltf.bufferViews.emplace_back();
bufferView.buffer = gltfBufferIndex;
bufferView.byteOffset = gltfBufferOffset;
bufferView.byteLength = static_cast<int64_t>(
typeSize * componentCount * static_cast<size_t>(featureTable.count));
featureTableProperty.bufferView =
static_cast<int32_t>(gltf.bufferViews.size() - 1);
binaryProperty.b3dmByteOffset = byteOffset;
binaryProperty.gltfByteOffset = gltfBufferOffset;
binaryProperty.byteLength = static_cast<int64_t>(bufferView.byteLength);
}
} // namespace
namespace Cesium3DTilesSelection {
void upgradeBatchTableToFeatureMetadata(
const std::shared_ptr<spdlog::logger>& pLogger,
CesiumGltf::Model& gltf,
const rapidjson::Document& featureTableJson,
const rapidjson::Document& batchTableJson,
const gsl::span<const std::byte>& batchTableBinaryData) {
CESIUM_TRACE("upgradeBatchTableToFeatureMetadata");
// Check to make sure a char of rapidjson is 1 byte
static_assert(
sizeof(rapidjson::Value::Ch) == 1,
"RapidJson::Value::Ch is not 1 byte");
// Parse the b3dm batch table and convert it to the EXT_feature_metadata
// extension.
// If the feature table is missing the BATCH_LENGTH semantic, ignore the batch
// table completely.
const auto batchLengthIt = featureTableJson.FindMember("BATCH_LENGTH");
if (batchLengthIt == featureTableJson.MemberEnd() ||
!batchLengthIt->value.IsInt64()) {
SPDLOG_LOGGER_WARN(
pLogger,
"The B3DM has a batch table, but it is being ignored because there is "
"no BATCH_LENGTH semantic in the feature table or it is not an "
"integer.");
return;
}
const int64_t batchLength = batchLengthIt->value.GetInt64();
// Add the binary part of the batch table - if any - to the glTF as a buffer.
// We will reallign this buffer later on
int32_t gltfBufferIndex = -1;
int64_t gltfBufferOffset = -1;
std::vector<BinaryProperty> binaryProperties;
if (!batchTableBinaryData.empty()) {
gltfBufferIndex = static_cast<int32_t>(gltf.buffers.size());
gltfBufferOffset = 0;
gltf.buffers.emplace_back();
}
ModelEXT_feature_metadata& modelExtension =
gltf.addExtension<ModelEXT_feature_metadata>();
Schema& schema = modelExtension.schema.emplace();
Class& classDefinition =
schema.classes.emplace("default", Class()).first->second;
FeatureTable& featureTable =
modelExtension.featureTables.emplace("default", FeatureTable())
.first->second;
featureTable.count = batchLength;
featureTable.classProperty = "default";
// Convert each regular property in the batch table
for (auto propertyIt = batchTableJson.MemberBegin();
propertyIt != batchTableJson.MemberEnd();
++propertyIt) {
std::string name = propertyIt->name.GetString();
// Don't interpret extensions or extras as a property.
if (name == "extensions" || name == "extras") {
continue;
}
ClassProperty& classProperty =
classDefinition.properties.emplace(name, ClassProperty()).first->second;
classProperty.name = name;
FeatureTableProperty& featureTableProperty =
featureTable.properties.emplace(name, FeatureTableProperty())
.first->second;
const rapidjson::Value& propertyValue = propertyIt->value;
if (propertyValue.IsArray()) {
updateExtensionWithJsonProperty(
gltf,
classProperty,
featureTable,
featureTableProperty,
propertyValue);
} else {
BinaryProperty& binaryProperty = binaryProperties.emplace_back();
updateExtensionWithBinaryProperty(
gltf,
gltfBufferIndex,
gltfBufferOffset,
binaryProperty,
classProperty,
featureTable,
featureTableProperty,
name,
propertyValue,
pLogger);
gltfBufferOffset += roundUp(binaryProperty.byteLength, 8);
}
}
// re-arrange binary property buffer
if (!batchTableBinaryData.empty()) {
Buffer& buffer = gltf.buffers[static_cast<size_t>(gltfBufferIndex)];
buffer.byteLength = gltfBufferOffset;
buffer.cesium.data.resize(static_cast<size_t>(gltfBufferOffset));
for (const BinaryProperty& binaryProperty : binaryProperties) {
std::memcpy(
buffer.cesium.data.data() + binaryProperty.gltfByteOffset,
batchTableBinaryData.data() + binaryProperty.b3dmByteOffset,
static_cast<size_t>(binaryProperty.byteLength));
}
}
// Create an EXT_feature_metadata extension for each primitive with a _BATCHID
// attribute.
for (Mesh& mesh : gltf.meshes) {
for (MeshPrimitive& primitive : mesh.primitives) {
auto batchIDIt = primitive.attributes.find("_BATCHID");
if (batchIDIt == primitive.attributes.end()) {
// This primitive has no batch ID, ignore it.
continue;
}
// Rename the _BATCHID attribute to _FEATURE_ID_0
primitive.attributes["_FEATURE_ID_0"] = batchIDIt->second;
primitive.attributes.erase("_BATCHID");
// Create a feature extension
MeshPrimitiveEXT_feature_metadata& extension =
primitive.addExtension<MeshPrimitiveEXT_feature_metadata>();
FeatureIDAttribute& attribute =
extension.featureIdAttributes.emplace_back();
attribute.featureTable = "default";
attribute.featureIds.attribute = "_FEATURE_ID_0";
}
}
}
} // namespace Cesium3DTilesSelection
| 35.236823 | 80 | 0.699014 | [
"mesh",
"vector",
"model"
] |
86d788871dd04f878d61802ece9cefddbf09fe1d | 14,905 | cpp | C++ | mpr/VXWORKS/thread.cpp | linbc/appweb2-win | ed9b55079cd427751e21ebdf122d5e3a1228f65c | [
"BSD-3-Clause"
] | null | null | null | mpr/VXWORKS/thread.cpp | linbc/appweb2-win | ed9b55079cd427751e21ebdf122d5e3a1228f65c | [
"BSD-3-Clause"
] | null | null | null | mpr/VXWORKS/thread.cpp | linbc/appweb2-win | ed9b55079cd427751e21ebdf122d5e3a1228f65c | [
"BSD-3-Clause"
] | 1 | 2019-12-11T02:29:49.000Z | 2019-12-11T02:29:49.000Z | ///
/// @file UNIX/thread.cpp
/// @brief Primitive multi-threading support for Linux
/// @overview This module provides threading, mutex and condition variable
/// APIs for UNIX. It tracks MprMutex and MprCond allocations and leaks
/// if BLD_DEBUG is defined.
//
////////////////////////////////// Copyright ///////////////////////////////////
//
// @copy default
//
// Copyright (c) Mbedthis Software LLC, 2003-2007. All Rights Reserved.
//
// This software is distributed under commercial and open source licenses.
// You may use the GPL open source license described below or you may acquire
// a commercial license from Mbedthis Software. You agree to be fully bound
// by the terms of either license. Consult the LICENSE.TXT distributed with
// this software for full details.
//
// This software is open source; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2 of the License, or (at your
// option) any later version. See the GNU General Public License for more
// details at: http://www.mbedthis.com/downloads/gplLicense.html
//
// This program is distributed WITHOUT ANY WARRANTY; without even the
// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// This GPL license does NOT permit incorporating this software into
// proprietary programs. If you are unable to comply with the GPL, you must
// acquire a commercial license to use this software. Commercial licenses
// for this software and support services are available from Mbedthis
// Software at http://www.mbedthis.com
//
// @end
//
/////////////////////////////////// Includes ///////////////////////////////////
#include "mpr/mpr.h"
//////////////////////////////////// Locals ////////////////////////////////////
#if BLD_FEATURE_MULTITHREAD
#if BLD_DEBUG
MprList mutexList;
MprList condList;
SEM_ID listLock;
#endif
///////////////////////////// Forward Declarations /////////////////////////////
static int threadProcWrapper(void *data);
///////////////////////////////////// Code /////////////////////////////////////
//
// Initialize the thread service
//
MprThreadService::MprThreadService()
{
#if BLD_DEBUG
listLock = semMCreate(SEM_Q_PRIORITY | SEM_DELETE_SAFE);
#endif
mutex = new MprMutex();
//
// Don't actually create the thread. Just create a thead object for
// this main thread
//
mainThread = new MprThread(MPR_NORMAL_PRIORITY, "main");
mainThread->setId(taskIdSelf());
insertThread(mainThread);
}
////////////////////////////////////////////////////////////////////////////////
//
// Terminate the thread service
//
MprThreadService::~MprThreadService()
{
lock();
//
// We expect users who created the threads to delete them prior to this
//
delete mainThread;
delete mutex;
mutex = 0;
#if BLD_DEBUG
if (threads.getNumItems() > 0) {
mprError(MPR_L, MPR_LOG, "Exiting with %d thread(s) unfreed",
threads.getNumItems());
}
if (condList.getNumItems() > 0) {
mprError(MPR_L, MPR_LOG, "Exiting with %d cond var(s) unfreed",
condList.getNumItems());
}
semTake(listLock, WAIT_FOREVER);
if (mutexList.getNumItems() > 0) {
mprError(MPR_L, MPR_LOG, "Exiting with %d mutex(es) unfreed",
mutexList.getNumItems() - 0);
MprMutex *mp;
mp = (MprMutex*) mutexList.getFirst();
while (mp) {
mprLog(0, "Mutex %x unfreed\n", mp);
mp = (MprMutex*) mutexList.getNext(&mp->link);
}
}
semGive(listLock);
semDelete(listLock);
#endif
}
////////////////////////////////////////////////////////////////////////////////
//
// Add a thread to the list
//
void MprThreadService::insertThread(MprThread *tp)
{
lock();
threads.insert(tp);
unlock();
}
////////////////////////////////////////////////////////////////////////////////
//
// Remove a thread from the list
//
void MprThreadService::removeThread(MprThread *tp)
{
lock();
threads.remove(tp);
unlock();
}
////////////////////////////////////////////////////////////////////////////////
//
// Nothing to do
//
int MprThreadService::start()
{
return 0;
}
////////////////////////////////////////////////////////////////////////////////
//
// Nothing to do. We expect the threads to be self terminating.
//
int MprThreadService::stop(int timeout)
{
//
// Wait until all threads (except main thread) have exited
//
while (threads.getNumItems() > 1 && timeout > 0) {
mprSleep(10);
timeout -= 10;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
//
// Return the current thread object
//
MprThread *MprThreadService::getCurrentThread()
{
MprThread *tp;
int osThreadId;
osThreadId = taskIdSelf();
lock();
tp = (MprThread*) threads.getFirst();
while (tp) {
if (tp->getId() == osThreadId) {
unlock();
return tp;
}
tp = (MprThread*) threads.getNext(tp);
}
unlock();
return 0;
}
////////////////////////////////////////////////////////////////////////////////
//
// Return the current thread id
//
int MprThreadService::getCurrentThreadId()
{
MprThread *tp;
tp = getCurrentThread();
if (tp) {
return tp->getId();
}
return -1;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////// MprThread ///////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Create a main thread
//
MprThread::MprThread(int priority, char *name)
{
pid = osThreadId = 0;
stackSize = mprGetMpr()->getConfigInt("stackSize", MPR_DEFAULT_STACK);
this->priority = priority;
this->name = mprStrdup(name);
entry = 0;
data = 0;
mutex = new MprMutex();
//
// Will be inserted into the thread list in MprThreadService()
//
}
////////////////////////////////////////////////////////////////////////////////
//
// Create a thread
//
MprThread::MprThread(MprThreadProc entry, int priority, void *data,
char *name, int stackSize)
{
mprLog(7, "Create Thread %s\n", name);
pid = osThreadId = 0;
if (stackSize == 0) {
this->stackSize = mprGetMpr()->getConfigInt("stackSize", MPR_DEFAULT_STACK);
} else {
this->stackSize = stackSize;
}
this->priority = priority;
this->name = mprStrdup(name);
this->entry = entry;
this->data = data;
mutex = new MprMutex();
mprGetMpr()->threadService->insertThread(this);
}
////////////////////////////////////////////////////////////////////////////////
//
// Destroy a thread
//
MprThread::~MprThread()
{
lock();
mprFree(name);
mprGetMpr()->threadService->removeThread(this);
delete mutex;
}
////////////////////////////////////////////////////////////////////////////////
//
// Start a thread
//
int MprThread::start()
{
int taskHandle, pri;
taskPriorityGet(taskIdSelf(), &pri);
taskHandle = taskSpawn(name, pri, 0, stackSize,
(FUNCPTR) threadProcWrapper,
(int) this, 0, 0, 0, 0, 0, 0, 0, 0, 0);
if (taskHandle < 0) {
mprError(MPR_L, MPR_FATAL, "Can't create task %s\n", name);
return MPR_ERR_CANT_CREATE;
}
mprLog(MPR_DEBUG, "Started thread %s, taskHandle %x\n", name, taskHandle);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
//
// Must be called before start()
//
void MprThread::setStackSize(int size)
{
stackSize = size;
}
////////////////////////////////////////////////////////////////////////////////
//
// Entry thread function
//
static int threadProcWrapper(void *data)
{
MprThread *tp;
tp = (MprThread*) data;
tp->threadProc();
delete tp;
return 0;
}
////////////////////////////////////////////////////////////////////////////////
//
// Thread procedure
//
void MprThread::threadProc()
{
pid = osThreadId = taskIdSelf();
(entry)(data, this);
}
////////////////////////////////////////////////////////////////////////////////
void MprThread::setOsThread(MprOsThread id)
{
osThreadId = id;
}
////////////////////////////////////////////////////////////////////////////////
//
// Change the thread priority
//
void MprThread::setPriority(int newPriority)
{
int rc, rcGet, osPri, finalOsPri;
lock();
osPri = mapMprPriorityToOs(newPriority);
rc = taskPrioritySet(osThreadId, osPri);
rcGet = taskPriorityGet(osThreadId, &finalOsPri);
if (rc != 0 || rcGet != 0) {
mprLog(0, "ERROR Setting prioority rc %d, rcGet %d\n", rc, rcGet);
}
if (finalOsPri != osPri) {
mprLog(0, "WARNING priority not changed. Wanted %d but got %d, rc %d\n",
osPri, finalOsPri, rc);
rc = taskPrioritySet(osThreadId, osPri);
taskPriorityGet(osThreadId, &finalOsPri);
mprLog(0, "AFTER RETRY. Wanted %d but got %d, rc %d\n",
osPri, finalOsPri, rc);
}
priority = newPriority;
unlock();
}
////////////////////////////////////////////////////////////////////////////////
//
// Map MR priority to VxWorks native priority. VxWorks priorities range from
// 0 to 255 with zero being the highest. Appweb priorities range from 0 to 99
// with 99 being the highest.
//
int MprThread::mapMprPriorityToOs(int mprPriority)
{
int nativePriority;
mprAssert(mprPriority >= 0 && mprPriority < 100);
nativePriority = (100 - mprPriority) * 5 / 2;
if (nativePriority < 10) {
nativePriority = 10;
} else if (nativePriority > 255) {
nativePriority = 255;
}
return nativePriority;
}
////////////////////////////////////////////////////////////////////////////////
//
// Map O/S priority to Mpr priority.
//
int MprThread::mapOsPriorityToMpr(int nativePriority)
{
int priority;
priority = (255 - nativePriority) * 2 / 5;
if (priority < 0) {
priority = 0;
}
if (priority >= 100) {
priority = 99;
}
return priority;
}
////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////// MprMutex ///////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Create a mutex
//
MprMutex::MprMutex()
{
cs = semMCreate(SEM_Q_PRIORITY | SEM_DELETE_SAFE);
if (cs == 0) {
mprAssert(0);
return;
}
#if BLD_DEBUG
semTake(listLock, WAIT_FOREVER);
mutexList.insert(&link);
semGive(listLock);
#endif
}
////////////////////////////////////////////////////////////////////////////////
//
// Destroy a mutex. Must be locked on entrance.
//
MprMutex::~MprMutex()
{
semDelete(cs);
#if BLD_DEBUG
semTake(listLock, WAIT_FOREVER);
mutexList.remove(&link);
semGive(listLock);
#endif
}
////////////////////////////////////////////////////////////////////////////////
//
// Lock a mutex
//
void MprMutex::lock()
{
int rc;
rc = semTake(cs, WAIT_FOREVER);
if (rc == -1) {
mprAssert(0);
mprLog("semTake error %d\n", rc);
}
}
////////////////////////////////////////////////////////////////////////////////
//
// Unlock a mutex
//
void MprMutex::unlock()
{
semGive(cs);
}
////////////////////////////////////////////////////////////////////////////////
//
// Try to lock a mutex. Do not block!
//
int MprMutex::tryLock()
{
int rc;
rc = semTake(cs, NO_WAIT);
if (rc == -1) {
if (rc == S_objLib_OBJ_UNAVAILABLE) {
return MPR_ERR_BUSY;
} else {
return MPR_ERR_CANT_ACCESS;
}
}
// Success
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////// MprCond ////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Create a condition variable for use by single or multiple waiters
//
MprCond::MprCond()
{
memset(&cv, 0, sizeof(cv));
mutex = new MprMutex();
triggered = 0;
cv = semCCreate(SEM_Q_PRIORITY, SEM_EMPTY);
#if BLD_DEBUG
condList.insert(&link);
#endif
}
////////////////////////////////////////////////////////////////////////////////
//
// Destroy a condition variable object
//
MprCond::~MprCond()
{
mutex->lock();
semDelete(cv);
#if BLD_DEBUG
condList.remove(&link);
#endif
delete mutex;
}
////////////////////////////////////////////////////////////////////////////////
//
// Wait for the event to be triggered. Should only be used when there are
// single waiters. If the event is already triggered, then it will return
// immediately. Timeout of -1 means wait forever. Timeout of 0 means no wait.
// Returns 0 if the event was signalled. Returns < 0 if the timeout.
//
int MprCond::waitForCond(long timeout)
{
int rc;
rc = 0;
mutex->lock();
if (triggered == 0) {
mutex->unlock();
if (timeout < 0) {
rc = semTake(cv, WAIT_FOREVER);
} else {
rc = semTake(cv, timeout);
}
mutex->lock();
}
triggered = 0;
mutex->unlock();
if (rc == S_objLib_OBJ_UNAVAILABLE) {
// FUTURE -- should be consistent with return codes in tryLock
return MPR_ERR_TIMEOUT;
} else {
return MPR_ERR_GENERAL;
}
return rc;
}
////////////////////////////////////////////////////////////////////////////////
#if UNUSED
//
// Wait for a condition variable to be signalled. Suitable for when there are
// multiple waiters. It will work for single waiters, but is slower than
// waitForCond() above. Depending on whether signalCond() or signalAll()
// is used, a single waiter or multiple waiters may awake with one invocation
// of signal. If the condition is already triggered, this routine will not
// block for the first waiter. NOTE: the externalMutex must be defined and
// locked on entry to this routine
//
int MprCond::multiWait(MprMutex *externalMutex, long timeout)
{
int rc;
rc = 0;
externalMutex->lock();
if (triggered == 0) {
externalMutex->unlock();
if (timeout < 0) {
rc = semTake(cv, WAIT_FOREVER);
} else {
rc = semTake(cv, timeout);
}
externalMutex->lock();
}
triggered = 0;
externalMutex->unlock();
if (rc == S_objLib_OBJ_UNAVAILABLE) {
// FUTURE -- should be consistent with return codes in tryLock
return MPR_ERR_TIMEOUT;
} else {
return MPR_ERR_GENERAL;
}
return rc;
}
#endif
////////////////////////////////////////////////////////////////////////////////
//
// Signal a condition and wakeup a single waiter. Note: this may be called
// prior to the waiter waiting.
//
void MprCond::signalCond()
{
mutex->lock();
if (triggered) {
mutex->unlock();
return;
}
triggered = 1;
semGive(cv);
mutex->unlock();
}
////////////////////////////////////////////////////////////////////////////////
#if UNUSED
//
// Signal all waiters. Note: this may be called prior to anyone waiting.
//
void MprCond::signalAll()
{
mutex->lock();
triggered = 1;
// WARNING: Not quite right
rc = semGive(cv);
mutex->unlock();
}
///////////////////////////////////////////////////////////////////////////////
void MprCond::reset()
{
mutex->lock();
triggered = 0;
mutex->unlock();
}
#endif
///////////////////////////////////////////////////////////////////////////////
#endif // BLD_FEATURE_MULTITHREAD
//
// Local variables:
// tab-width: 4
// c-basic-offset: 4
// End:
// vim: sw=4 ts=4
//
| 22.18006 | 80 | 0.527004 | [
"object"
] |
86dee37d6f7e2ed076a4a5b2952abf7a6b91add1 | 8,529 | hpp | C++ | include/fibio/stream/streambuf.hpp | mind-owner/fibio | a269f2e0d842bf441ac7d27f70d8bcc1801d7c92 | [
"BSD-2-Clause"
] | 243 | 2015-01-19T07:38:03.000Z | 2022-03-01T07:39:16.000Z | include/fibio/stream/streambuf.hpp | learnerzhang/fibio | a269f2e0d842bf441ac7d27f70d8bcc1801d7c92 | [
"BSD-2-Clause"
] | 3 | 2015-02-11T10:11:58.000Z | 2015-11-08T19:27:04.000Z | include/fibio/stream/streambuf.hpp | learnerzhang/fibio | a269f2e0d842bf441ac7d27f70d8bcc1801d7c92 | [
"BSD-2-Clause"
] | 53 | 2015-01-08T06:35:54.000Z | 2022-02-14T02:38:58.000Z | //
// streambuf.hpp
// fibio
//
// Created by Chen Xu on 14-3-8.
// Copyright (c) 2014 0d0a.com. All rights reserved.
//
#ifndef fibio_stream_streambuf_hpp
#define fibio_stream_streambuf_hpp
#include <streambuf>
#include <chrono>
#include <vector>
#include <boost/system/error_code.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/basic_stream_socket.hpp>
#include <boost/asio/ssl/stream_base.hpp>
#include <fibio/fibers/fiber.hpp>
#include <fibio/fibers/asio/yield.hpp>
namespace boost {
namespace asio {
namespace ssl {
template <typename Stream>
class stream;
} // End of namespace ssl
} // End of namespace asio
} // End of namespace boost
namespace fibio {
namespace stream {
enum duplex_mode
{
full_duplex,
half_duplex,
};
template <typename Stream>
class streambuf_base : public std::streambuf, public Stream
{
typedef Stream base_type;
public:
typedef Stream stream_type;
streambuf_base() : base_type(asio::get_io_service()) { init_buffers(); }
explicit streambuf_base(boost::asio::io_service& iosvc) : base_type(iosvc) { init_buffers(); }
// For SSL stream, construct with ssl::context
template <typename Arg>
streambuf_base(Arg& arg)
: std::streambuf(), base_type(asio::get_io_service(), arg)
{
init_buffers();
}
// For SSL stream, construct with ssl::context
template <typename Arg>
streambuf_base(boost::asio::io_service& iosvc, Arg& arg)
: std::streambuf(), base_type(iosvc, arg)
{
init_buffers();
}
streambuf_base(streambuf_base&& other)
// FIXME: GCC 4.8.1 on Ubuntu, std::streambuf doesn't have move constructor
// and have copy constructor declared as private, that prevents the generation
// of default move constructor, and makes only untouched(newly-created)
// streambuf can be safely moved, as get/put pointers may not be set correctly
// Seems Clang 3.4 doesn't have the issue
: /*std::streambuf(std::move(other)),*/
base_type(std::move(other))
// we can only move newly create streambuf, anyway
//, get_buffer_(std::move(other.get_buffer_))
//, put_buffer_(std::move(other.put_buffer_))
,
unbuffered_(other.unbuffered_),
duplex_mode_(other.duplex_mode_)
{
init_buffers();
}
/// Destructor flushes buffered data.
~streambuf_base()
{
if (pptr() != pbase()) overflow(traits_type::eof());
}
void set_duplex_mode(duplex_mode dm) { duplex_mode_ = dm; }
duplex_mode get_duplex_mode() const { return duplex_mode_; }
protected:
pos_type
seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which) override
{
// Only seeking in input buffer from current pos is allowed
if (which != std::ios_base::in || dir != std::ios_base::cur) return pos_type(off_type(-1));
// Do nothing when off=0
if (off == 0) return pos_type(off_type(0));
char_type* newg = gptr() + off;
// Cannot seek back into put back area
if (newg < eback() + putback_max) return pos_type(off_type(-1));
// Cannot seek beyond end of get area
if (newg >= egptr()) return pos_type(off_type(-1));
setg(eback(), newg, egptr());
return pos_type(off_type(0));
}
virtual std::streamsize showmanyc() override
{
if (gptr() == egptr()) {
underflow();
}
return egptr() - gptr();
}
int_type underflow() override
{
if (duplex_mode_ == half_duplex) sync();
if (gptr() == egptr()) {
boost::system::error_code ec;
// size_t bytes_transferred=base_type::read_some(boost::asio::buffer(&get_buffer_[0]+
// putback_max, buffer_size-putback_max),
// ec);
size_t bytes_transferred = base_type::async_read_some(
boost::asio::buffer(&get_buffer_[0] + putback_max, buffer_size - putback_max),
fibers::asio::yield[ec]);
if (ec || bytes_transferred == 0) {
return traits_type::eof();
}
setg(&get_buffer_[0],
&get_buffer_[0] + putback_max,
&get_buffer_[0] + putback_max + bytes_transferred);
return traits_type::to_int_type(*gptr());
} else {
return traits_type::eof();
}
}
int_type overflow(int_type c) override
{
boost::system::error_code ec;
if (unbuffered_) {
if (traits_type::eq_int_type(c, traits_type::eof())) {
// Nothing to do.
return traits_type::not_eof(c);
} else {
char c_ = c;
// base_type::write_some(boost::asio::buffer(&c_, 1),
// ec);
base_type::async_write_some(boost::asio::buffer(&c_, 1), fibers::asio::yield[ec]);
if (ec) return traits_type::eof();
return c;
}
} else {
char* ptr = pbase();
size_t size = pptr() - pbase();
while (size > 0) {
// size_t bytes_transferred=base_type::write_some(boost::asio::buffer(ptr, size),
// ec);
size_t bytes_transferred = base_type::async_write_some(
boost::asio::buffer(ptr, size), fibers::asio::yield[ec]);
ptr += bytes_transferred;
size -= bytes_transferred;
if (ec) return traits_type::eof();
}
setp(&put_buffer_[0], &put_buffer_[0] + put_buffer_.size());
// If the new character is eof then our work here is done.
if (traits_type::eq_int_type(c, traits_type::eof())) return traits_type::not_eof(c);
// Add the new character to the output buffer.
*pptr() = traits_type::to_char_type(c);
pbump(1);
return c;
}
}
int sync() override { return overflow(traits_type::eof()); }
std::streambuf* setbuf(char_type* s, std::streamsize n) override
{
if (pptr() == pbase() && s == 0 && n == 0) {
unbuffered_ = true;
setp(0, 0);
return this;
}
return 0;
}
private:
void init_buffers()
{
get_buffer_.resize(buffer_size + putback_max);
put_buffer_.resize(buffer_size);
setg(&get_buffer_[0], &get_buffer_[0] + putback_max, &get_buffer_[0] + putback_max);
if (unbuffered_)
setp(0, 0);
else
setp(&put_buffer_[0], &put_buffer_[0] + put_buffer_.size());
}
enum
{
putback_max = 8
};
// A practical MTU size
enum
{
buffer_size = 1500
};
std::vector<char> get_buffer_;
std::vector<char> put_buffer_;
bool unbuffered_ = false;
duplex_mode duplex_mode_ = half_duplex;
};
template <typename Stream>
class streambuf : public streambuf_base<Stream>
{
typedef streambuf_base<Stream> base_type;
public:
using base_type::base_type;
};
template <typename Protocol>
class streambuf<boost::asio::basic_stream_socket<Protocol>>
: public streambuf_base<boost::asio::basic_stream_socket<Protocol>>
{
typedef streambuf_base<boost::asio::basic_stream_socket<Protocol>> base_type;
public:
using base_type::base_type;
template <typename Arg>
boost::system::error_code connect(const Arg& arg)
{
boost::system::error_code ec;
base_type::async_connect(arg, fibers::asio::yield[ec]);
return ec;
}
};
template <typename Stream>
class streambuf<boost::asio::ssl::stream<Stream>>
: public streambuf_base<boost::asio::ssl::stream<Stream>>
{
typedef streambuf_base<boost::asio::ssl::stream<Stream>> base_type;
public:
template <typename Context>
streambuf(Context& ctx)
: base_type(ctx)
{
}
void cancel() { base_type::next_layer().cancel(); }
template <typename Arg>
boost::system::error_code connect(const Arg& arg)
{
boost::system::error_code ec;
base_type::next_layer().async_connect(arg, fibers::asio::yield[ec]);
if (ec) return ec;
base_type::async_handshake(boost::asio::ssl::stream_base::client, fibers::asio::yield[ec]);
return ec;
}
};
} // End of namespace stream
} // End of namespace fibio
#endif
| 30.137809 | 99 | 0.593387 | [
"vector"
] |
86e23ce2d76955d050b81f2a5f18ffaa609e340e | 64,719 | cpp | C++ | Tests/DiligentCoreAPITest/src/ObjectCreationFailure/PSOCreationFailureTest.cpp | AndreyMlashkin/DiligentCore | 20d5d7d2866e831a73437db2dec16bdc61413eb0 | [
"Apache-2.0"
] | null | null | null | Tests/DiligentCoreAPITest/src/ObjectCreationFailure/PSOCreationFailureTest.cpp | AndreyMlashkin/DiligentCore | 20d5d7d2866e831a73437db2dec16bdc61413eb0 | [
"Apache-2.0"
] | null | null | null | Tests/DiligentCoreAPITest/src/ObjectCreationFailure/PSOCreationFailureTest.cpp | AndreyMlashkin/DiligentCore | 20d5d7d2866e831a73437db2dec16bdc61413eb0 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019-2021 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include <array>
#include <limits>
#include "TestingEnvironment.hpp"
#include "GraphicsAccessories.hpp"
#include "gtest/gtest.h"
using namespace Diligent;
using namespace Diligent::Testing;
namespace
{
static constexpr char g_TrivialVSSource[] = R"(
void main(out float4 pos : SV_Position)
{
pos = float4(0.0, 0.0, 0.0, 0.0);
}
)";
static constexpr char g_TrivialPSSource[] = R"(
float4 main() : SV_Target
{
return float4(0.0, 0.0, 0.0, 0.0);
}
)";
static constexpr char g_TexturePSSource[] = R"(
Texture2D g_Texture;
float4 main() : SV_Target
{
return g_Texture.Load(int3(0,0,0));
}
)";
static constexpr char g_TrivialMSSource[] = R"(
struct VertexOut
{
float4 Pos : SV_Position;
};
[numthreads(1,1,1)]
[outputtopology("triangle")]
void main(out indices uint3 tris[1],
out vertices VertexOut verts[3])
{
SetMeshOutputCounts(4, 2);
tris[0] = uint3(0, 1, 2);
verts[0].Pos = float4(0.0, 0.0, 0.0, 1.0);
verts[1].Pos = float4(-1.0, 1.0, 0.0, 1.0);
verts[2].Pos = float4(1.0, 1.0, 0.0, 1.0);
}
)";
static constexpr char g_TrivialCSSource[] = R"(
[numthreads(8,8,1)]
void main()
{
}
)";
static constexpr char g_TrivialRGenSource[] = R"(
[shader("raygeneration")]
void main()
{}
)";
static constexpr char g_TrivialRMissSource[] = R"(
struct RTPayload { float4 Color; };
[shader("miss")]
void main(inout RTPayload payload)
{}
)";
static constexpr char g_TrivialRCHitSource[] = R"(
struct RTPayload { float4 Color; };
[shader("closesthit")]
void main(inout RTPayload payload, in BuiltInTriangleIntersectionAttributes attr)
{}
)";
static constexpr char g_TrivialRAHitSource[] = R"(
struct RTPayload { float4 Color; };
[shader("anyhit")]
void main(inout RTPayload payload, in BuiltInTriangleIntersectionAttributes attr)
{}
)";
static constexpr char g_TrivialRIntSource[] = R"(
[shader("intersection")]
void main()
{}
)";
static constexpr char g_TrivialRCallSource[] = R"(
struct Params { float4 Col; };
[shader("callable")]
void main(inout Params params)
{}
)";
class PSOCreationFailureTest : public ::testing::Test
{
protected:
static void SetUpTestSuite()
{
auto* const pEnv = TestingEnvironment::GetInstance();
auto* const pDevice = pEnv->GetDevice();
const auto& DeviceInfo = pDevice->GetDeviceInfo();
sm_HasMeshShader = DeviceInfo.Features.MeshShaders && pEnv->HasDXCompiler();
sm_HasRayTracing = pEnv->SupportsRayTracing();
ShaderCreateInfo ShaderCI;
ShaderCI.Source = g_TrivialVSSource;
ShaderCI.EntryPoint = "main";
ShaderCI.Desc.ShaderType = SHADER_TYPE_VERTEX;
ShaderCI.Desc.Name = "TrivialVS (PSOCreationFailureTest)";
ShaderCI.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL;
ShaderCI.ShaderCompiler = pEnv->GetDefaultCompiler(ShaderCI.SourceLanguage);
ShaderCI.UseCombinedTextureSamplers = true;
pDevice->CreateShader(ShaderCI, &sm_pTrivialVS);
ASSERT_TRUE(sm_pTrivialVS);
ShaderCI.Source = g_TrivialPSSource;
ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL;
ShaderCI.Desc.Name = "TrivialPS (PSOCreationFailureTest)";
pDevice->CreateShader(ShaderCI, &sm_pTrivialPS);
ASSERT_TRUE(sm_pTrivialPS);
ShaderCI.Source = g_TexturePSSource;
ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL;
ShaderCI.Desc.Name = "TexturePS (PSOCreationFailureTest)";
pDevice->CreateShader(ShaderCI, &sm_pTexturePS);
ASSERT_TRUE(sm_pTexturePS);
ShaderCI.Source = g_TrivialCSSource;
ShaderCI.Desc.ShaderType = SHADER_TYPE_COMPUTE;
ShaderCI.Desc.Name = "TrivialCS (PSOCreationFailureTest)";
pDevice->CreateShader(ShaderCI, &sm_pTrivialCS);
ASSERT_TRUE(sm_pTrivialCS);
sm_DefaultGraphicsPsoCI.PSODesc.Name = "PSOCreationFailureTest - default graphics PSO desc";
sm_DefaultGraphicsPsoCI.GraphicsPipeline.NumRenderTargets = 1;
sm_DefaultGraphicsPsoCI.GraphicsPipeline.RTVFormats[0] = TEX_FORMAT_RGBA8_UNORM;
sm_DefaultGraphicsPsoCI.GraphicsPipeline.DSVFormat = TEX_FORMAT_D32_FLOAT;
sm_DefaultGraphicsPsoCI.pVS = sm_pTrivialVS;
sm_DefaultGraphicsPsoCI.pPS = sm_pTrivialPS;
{
RefCntAutoPtr<IPipelineState> pGraphicsPSO;
pDevice->CreateGraphicsPipelineState(GetGraphicsPSOCreateInfo("PSOCreationFailureTest - OK graphics PSO"), &pGraphicsPSO);
ASSERT_TRUE(pGraphicsPSO);
}
sm_DefaultComputePsoCI.PSODesc.Name = "PSOCreationFailureTest - default compute PSO desc";
sm_DefaultComputePsoCI.pCS = sm_pTrivialCS;
{
RefCntAutoPtr<IPipelineState> pComputePSO;
pDevice->CreateComputePipelineState(GetComputePSOCreateInfo("PSOCreationFailureTest - OK compute PSO"), &pComputePSO);
ASSERT_TRUE(pComputePSO);
}
if (sm_HasMeshShader)
{
ShaderCI.ShaderCompiler = SHADER_COMPILER_DXC;
ShaderCI.Source = g_TrivialMSSource;
ShaderCI.Desc.ShaderType = SHADER_TYPE_MESH;
ShaderCI.Desc.Name = "TrivialMS DXC (PSOCreationFailureTest)";
pDevice->CreateShader(ShaderCI, &sm_pTrivialMS);
ASSERT_TRUE(sm_pTrivialMS);
ShaderCI.Source = g_TrivialPSSource;
ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL;
ShaderCI.Desc.Name = "TrivialPS DXC (PSOCreationFailureTest)";
pDevice->CreateShader(ShaderCI, &sm_pTrivialPS_DXC);
ASSERT_TRUE(sm_pTrivialPS_DXC);
sm_DefaultMeshPsoCI.PSODesc.Name = "PSOCreationFailureTest - default mesh PSO desc";
sm_DefaultMeshPsoCI.GraphicsPipeline.NumRenderTargets = 1;
sm_DefaultMeshPsoCI.GraphicsPipeline.RTVFormats[0] = TEX_FORMAT_RGBA8_UNORM;
sm_DefaultMeshPsoCI.GraphicsPipeline.DSVFormat = TEX_FORMAT_D32_FLOAT;
sm_DefaultMeshPsoCI.PSODesc.PipelineType = PIPELINE_TYPE_MESH;
sm_DefaultMeshPsoCI.pMS = sm_pTrivialMS;
sm_DefaultMeshPsoCI.pPS = sm_pTrivialPS_DXC;
RefCntAutoPtr<IPipelineState> pMeshPSO;
pDevice->CreateGraphicsPipelineState(GetMeshPSOCreateInfo("PSOCreationFailureTest - OK mesh PSO"), &pMeshPSO);
ASSERT_TRUE(pMeshPSO);
}
if (sm_HasRayTracing)
{
ShaderCI.ShaderCompiler = SHADER_COMPILER_DXC;
ShaderCI.Source = g_TrivialRGenSource;
ShaderCI.Desc.ShaderType = SHADER_TYPE_RAY_GEN;
ShaderCI.Desc.Name = "TrivialRGen (PSOCreationFailureTest)";
pDevice->CreateShader(ShaderCI, &sm_pTrivialRG);
ASSERT_TRUE(sm_pTrivialRG);
ShaderCI.Source = g_TrivialRMissSource;
ShaderCI.Desc.ShaderType = SHADER_TYPE_RAY_MISS;
ShaderCI.Desc.Name = "TrivialRMiss (PSOCreationFailureTest)";
pDevice->CreateShader(ShaderCI, &sm_pTrivialRMiss);
ASSERT_TRUE(sm_pTrivialRMiss);
ShaderCI.Source = g_TrivialRCallSource;
ShaderCI.Desc.ShaderType = SHADER_TYPE_CALLABLE;
ShaderCI.Desc.Name = "TrivialRCall (PSOCreationFailureTest)";
pDevice->CreateShader(ShaderCI, &sm_pTrivialRCall);
ASSERT_TRUE(sm_pTrivialRCall);
ShaderCI.Source = g_TrivialRCHitSource;
ShaderCI.Desc.ShaderType = SHADER_TYPE_RAY_CLOSEST_HIT;
ShaderCI.Desc.Name = "TrivialRCHit (PSOCreationFailureTest)";
pDevice->CreateShader(ShaderCI, &sm_pTrivialRCHit);
ASSERT_TRUE(sm_pTrivialRCHit);
ShaderCI.Source = g_TrivialRAHitSource;
ShaderCI.Desc.ShaderType = SHADER_TYPE_RAY_ANY_HIT;
ShaderCI.Desc.Name = "TrivialRAHit (PSOCreationFailureTest)";
pDevice->CreateShader(ShaderCI, &sm_pTrivialRAHit);
ASSERT_TRUE(sm_pTrivialRAHit);
ShaderCI.Source = g_TrivialRIntSource;
ShaderCI.Desc.ShaderType = SHADER_TYPE_RAY_INTERSECTION;
ShaderCI.Desc.Name = "TrivialRInt (PSOCreationFailureTest)";
pDevice->CreateShader(ShaderCI, &sm_pTrivialRInt);
ASSERT_TRUE(sm_pTrivialRInt);
sm_DefaultRayTracingPsoCI.PSODesc.Name = "PSOCreationFailureTest - default ray tracing PSO desc";
sm_DefaultRayTracingPsoCI.PSODesc.PipelineType = PIPELINE_TYPE_RAY_TRACING;
sm_DefaultRayTracingPsoCI.RayTracingPipeline.MaxRecursionDepth = 1;
sm_GeneralGroups[0] = {"Main", sm_pTrivialRG};
sm_DefaultRayTracingPsoCI.pGeneralShaders = sm_GeneralGroups.data();
sm_DefaultRayTracingPsoCI.GeneralShaderCount = static_cast<Uint32>(sm_GeneralGroups.size());
RefCntAutoPtr<IPipelineState> pRayTracingPSO;
pDevice->CreateRayTracingPipelineState(GetRayTracingPSOCreateInfo("PSOCreationFailureTest - OK ray tracing PSO"), &pRayTracingPSO);
ASSERT_TRUE(pRayTracingPSO);
}
RenderPassDesc RPDesc;
RPDesc.Name = "PSOCreationFailureTest - render pass";
RenderPassAttachmentDesc Attachments[2]{};
Attachments[0].Format = TEX_FORMAT_RGBA8_UNORM;
Attachments[0].InitialState = RESOURCE_STATE_RENDER_TARGET;
Attachments[0].FinalState = RESOURCE_STATE_RENDER_TARGET;
Attachments[1].Format = TEX_FORMAT_D32_FLOAT;
Attachments[1].InitialState = RESOURCE_STATE_DEPTH_WRITE;
Attachments[1].FinalState = RESOURCE_STATE_DEPTH_WRITE;
RPDesc.AttachmentCount = _countof(Attachments);
RPDesc.pAttachments = Attachments;
AttachmentReference ColorAttachmentRef{0, RESOURCE_STATE_RENDER_TARGET};
AttachmentReference DepthAttachmentRef{1, RESOURCE_STATE_DEPTH_WRITE};
SubpassDesc Subpasses[1]{};
Subpasses[0].RenderTargetAttachmentCount = 1;
Subpasses[0].pRenderTargetAttachments = &ColorAttachmentRef;
Subpasses[0].pDepthStencilAttachment = &DepthAttachmentRef;
RPDesc.SubpassCount = _countof(Subpasses);
RPDesc.pSubpasses = Subpasses;
pDevice->CreateRenderPass(RPDesc, &sm_pRenderPass);
ASSERT_TRUE(sm_pRenderPass);
{
RefCntAutoPtr<IPipelineState> pGraphicsPSO;
pDevice->CreateGraphicsPipelineState(GetGraphicsPSOCreateInfo("PSOCreationFailureTest - OK PSO with render pass", true), &pGraphicsPSO);
ASSERT_TRUE(pGraphicsPSO);
}
{
PipelineResourceDesc Resources[] = //
{
PipelineResourceDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "g_Texture", 1, SHADER_RESOURCE_TYPE_TEXTURE_SRV, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE} //
};
ImmutableSamplerDesc ImmutableSmplers[] //
{
ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "g_Texture_sampler", SamplerDesc{}} //
};
PipelineResourceSignatureDesc PRSDesc;
PRSDesc.Name = "PRS0";
PRSDesc.NumResources = _countof(Resources);
PRSDesc.Resources = Resources;
PRSDesc.NumImmutableSamplers = _countof(ImmutableSmplers);
PRSDesc.ImmutableSamplers = ImmutableSmplers;
pDevice->CreatePipelineResourceSignature(PRSDesc, &sm_pSignature0);
ASSERT_TRUE(sm_pSignature0);
}
{
PipelineResourceDesc Resources[] = //
{
PipelineResourceDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "g_Texture2", 1, SHADER_RESOURCE_TYPE_TEXTURE_SRV, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE} //
};
PipelineResourceSignatureDesc PRSDesc;
PRSDesc.Name = "PRS0A";
PRSDesc.NumResources = _countof(Resources);
PRSDesc.Resources = Resources;
pDevice->CreatePipelineResourceSignature(PRSDesc, &sm_pSignature0A);
ASSERT_TRUE(sm_pSignature0A);
}
if (DeviceInfo.Features.GeometryShaders)
{
PipelineResourceDesc Resources[] = //
{
PipelineResourceDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_GEOMETRY, "g_Texture", 1, SHADER_RESOURCE_TYPE_TEXTURE_SRV, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE} //
};
PipelineResourceSignatureDesc PRSDesc;
PRSDesc.Name = "PRS1";
PRSDesc.BindingIndex = 1;
PRSDesc.NumResources = _countof(Resources);
PRSDesc.Resources = Resources;
pDevice->CreatePipelineResourceSignature(PRSDesc, &sm_pSignature1);
ASSERT_TRUE(sm_pSignature1);
}
if (DeviceInfo.Features.GeometryShaders)
{
PipelineResourceDesc Resources[] = //
{
PipelineResourceDesc{SHADER_TYPE_GEOMETRY, "g_Texture", 1, SHADER_RESOURCE_TYPE_TEXTURE_SRV, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE} //
};
ImmutableSamplerDesc ImmutableSmplers[] //
{
ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_GEOMETRY, "g_Texture_sampler", SamplerDesc{}} //
};
PipelineResourceSignatureDesc PRSDesc;
PRSDesc.Name = "PRS1A";
PRSDesc.BindingIndex = 1;
PRSDesc.NumResources = _countof(Resources);
PRSDesc.Resources = Resources;
PRSDesc.NumImmutableSamplers = _countof(ImmutableSmplers);
PRSDesc.ImmutableSamplers = ImmutableSmplers;
pDevice->CreatePipelineResourceSignature(PRSDesc, &sm_pSignature1A);
ASSERT_TRUE(sm_pSignature1A);
}
}
static void TearDownTestSuite()
{
sm_pTrivialVS.Release();
sm_pTrivialPS.Release();
sm_pTrivialPS_DXC.Release();
sm_pTexturePS.Release();
sm_pTrivialMS.Release();
sm_pTrivialCS.Release();
sm_pTrivialRG.Release();
sm_pTrivialRMiss.Release();
sm_pTrivialRCall.Release();
sm_pTrivialRCHit.Release();
sm_pTrivialRAHit.Release();
sm_pTrivialRInt.Release();
sm_pRenderPass.Release();
sm_pSignature0.Release();
sm_pSignature0A.Release();
sm_pSignature1.Release();
sm_pSignature1A.Release();
}
static GraphicsPipelineStateCreateInfo GetGraphicsPSOCreateInfo(const char* Name, bool UseRenderPass = false)
{
auto CI{sm_DefaultGraphicsPsoCI};
CI.PSODesc.Name = Name;
if (UseRenderPass)
{
CI.GraphicsPipeline.NumRenderTargets = 0;
CI.GraphicsPipeline.RTVFormats[0] = TEX_FORMAT_UNKNOWN;
CI.GraphicsPipeline.DSVFormat = TEX_FORMAT_UNKNOWN;
CI.GraphicsPipeline.pRenderPass = sm_pRenderPass;
}
return CI;
}
static GraphicsPipelineStateCreateInfo GetMeshPSOCreateInfo(const char* Name, bool UseRenderPass = false)
{
VERIFY_EXPR(HasMeshShader());
auto CI{sm_DefaultMeshPsoCI};
CI.PSODesc.Name = Name;
if (UseRenderPass)
{
CI.GraphicsPipeline.NumRenderTargets = 0;
CI.GraphicsPipeline.RTVFormats[0] = TEX_FORMAT_UNKNOWN;
CI.GraphicsPipeline.DSVFormat = TEX_FORMAT_UNKNOWN;
CI.GraphicsPipeline.pRenderPass = sm_pRenderPass;
}
return CI;
}
static ComputePipelineStateCreateInfo GetComputePSOCreateInfo(const char* Name)
{
auto CI{sm_DefaultComputePsoCI};
CI.PSODesc.Name = Name;
return CI;
}
static RayTracingPipelineStateCreateInfo GetRayTracingPSOCreateInfo(const char* Name)
{
VERIFY_EXPR(HasRayTracing());
auto CI{sm_DefaultRayTracingPsoCI};
CI.PSODesc.Name = Name;
return CI;
}
static IShader* GetVS() { return sm_pTrivialVS; }
static IShader* GetPS() { return sm_pTrivialPS; }
static IShader* GetMS() { return sm_pTrivialMS; }
static IShader* GetTexturePS() { return sm_pTexturePS; }
static IShader* GetRayGen() { return sm_pTrivialRG; }
static IShader* GetRayMiss() { return sm_pTrivialRMiss; }
static IShader* GetCallable() { return sm_pTrivialRCall; }
static IShader* GetRayClosestHit() { return sm_pTrivialRCHit; }
static IShader* GetRayAnyHit() { return sm_pTrivialRAHit; }
static IShader* GetRayIntersection() { return sm_pTrivialRInt; }
static bool HasMeshShader() { return sm_HasMeshShader; }
static bool HasRayTracing() { return sm_HasRayTracing; }
static void TestCreatePSOFailure(GraphicsPipelineStateCreateInfo CI, const char* ExpectedErrorSubstring)
{
auto* const pEnv = TestingEnvironment::GetInstance();
auto* const pDevice = pEnv->GetDevice();
RefCntAutoPtr<IPipelineState> pPSO;
pEnv->SetErrorAllowance(2, "Errors below are expected: testing PSO creation failure\n");
pEnv->PushExpectedErrorSubstring(ExpectedErrorSubstring);
pDevice->CreateGraphicsPipelineState(CI, &pPSO);
ASSERT_FALSE(pPSO);
CI.PSODesc.Name = nullptr;
pEnv->SetErrorAllowance(2);
pEnv->PushExpectedErrorSubstring(ExpectedErrorSubstring);
pDevice->CreateGraphicsPipelineState(CI, &pPSO);
ASSERT_FALSE(pPSO);
pEnv->SetErrorAllowance(0);
}
static void TestCreatePSOFailure(ComputePipelineStateCreateInfo CI, const char* ExpectedErrorSubstring)
{
auto* const pEnv = TestingEnvironment::GetInstance();
auto* const pDevice = pEnv->GetDevice();
RefCntAutoPtr<IPipelineState> pPSO;
pEnv->SetErrorAllowance(2, "Errors below are expected: testing PSO creation failure\n");
pEnv->PushExpectedErrorSubstring(ExpectedErrorSubstring);
pDevice->CreateComputePipelineState(CI, &pPSO);
ASSERT_FALSE(pPSO);
CI.PSODesc.Name = nullptr;
pEnv->SetErrorAllowance(2);
pEnv->PushExpectedErrorSubstring(ExpectedErrorSubstring);
pDevice->CreateComputePipelineState(CI, &pPSO);
ASSERT_FALSE(pPSO);
pEnv->SetErrorAllowance(0);
}
static void TestCreatePSOFailure(RayTracingPipelineStateCreateInfo CI, const char* ExpectedErrorSubstring)
{
auto* const pEnv = TestingEnvironment::GetInstance();
auto* const pDevice = pEnv->GetDevice();
RefCntAutoPtr<IPipelineState> pPSO;
pEnv->SetErrorAllowance(2, "Errors below are expected: testing PSO creation failure\n");
pEnv->PushExpectedErrorSubstring(ExpectedErrorSubstring);
pDevice->CreateRayTracingPipelineState(CI, &pPSO);
ASSERT_FALSE(pPSO);
CI.PSODesc.Name = nullptr;
pEnv->SetErrorAllowance(2);
pEnv->PushExpectedErrorSubstring(ExpectedErrorSubstring);
pDevice->CreateRayTracingPipelineState(CI, &pPSO);
ASSERT_FALSE(pPSO);
pEnv->SetErrorAllowance(0);
}
protected:
static RefCntAutoPtr<IPipelineResourceSignature> sm_pSignature0;
static RefCntAutoPtr<IPipelineResourceSignature> sm_pSignature0A;
static RefCntAutoPtr<IPipelineResourceSignature> sm_pSignature1;
static RefCntAutoPtr<IPipelineResourceSignature> sm_pSignature1A;
private:
static RefCntAutoPtr<IShader> sm_pTrivialVS;
static RefCntAutoPtr<IShader> sm_pTrivialPS;
static RefCntAutoPtr<IShader> sm_pTrivialPS_DXC;
static RefCntAutoPtr<IShader> sm_pTexturePS;
static RefCntAutoPtr<IShader> sm_pTrivialMS;
static RefCntAutoPtr<IShader> sm_pTrivialRG;
static RefCntAutoPtr<IShader> sm_pTrivialRMiss;
static RefCntAutoPtr<IShader> sm_pTrivialRCHit;
static RefCntAutoPtr<IShader> sm_pTrivialRAHit;
static RefCntAutoPtr<IShader> sm_pTrivialRInt;
static RefCntAutoPtr<IShader> sm_pTrivialRCall;
static RefCntAutoPtr<IShader> sm_pTrivialCS;
static RefCntAutoPtr<IRenderPass> sm_pRenderPass;
static GraphicsPipelineStateCreateInfo sm_DefaultGraphicsPsoCI;
static GraphicsPipelineStateCreateInfo sm_DefaultMeshPsoCI;
static ComputePipelineStateCreateInfo sm_DefaultComputePsoCI;
static RayTracingPipelineStateCreateInfo sm_DefaultRayTracingPsoCI;
static std::array<RayTracingGeneralShaderGroup, 1> sm_GeneralGroups;
static bool sm_HasMeshShader;
static bool sm_HasRayTracing;
};
RefCntAutoPtr<IShader> PSOCreationFailureTest::sm_pTrivialVS;
RefCntAutoPtr<IShader> PSOCreationFailureTest::sm_pTrivialPS;
RefCntAutoPtr<IShader> PSOCreationFailureTest::sm_pTexturePS;
RefCntAutoPtr<IShader> PSOCreationFailureTest::sm_pTrivialPS_DXC;
RefCntAutoPtr<IShader> PSOCreationFailureTest::sm_pTrivialMS;
RefCntAutoPtr<IShader> PSOCreationFailureTest::sm_pTrivialCS;
RefCntAutoPtr<IShader> PSOCreationFailureTest::sm_pTrivialRG;
RefCntAutoPtr<IShader> PSOCreationFailureTest::sm_pTrivialRMiss;
RefCntAutoPtr<IShader> PSOCreationFailureTest::sm_pTrivialRCHit;
RefCntAutoPtr<IShader> PSOCreationFailureTest::sm_pTrivialRAHit;
RefCntAutoPtr<IShader> PSOCreationFailureTest::sm_pTrivialRInt;
RefCntAutoPtr<IShader> PSOCreationFailureTest::sm_pTrivialRCall;
RefCntAutoPtr<IRenderPass> PSOCreationFailureTest::sm_pRenderPass;
RefCntAutoPtr<IPipelineResourceSignature> PSOCreationFailureTest::sm_pSignature0;
RefCntAutoPtr<IPipelineResourceSignature> PSOCreationFailureTest::sm_pSignature0A;
RefCntAutoPtr<IPipelineResourceSignature> PSOCreationFailureTest::sm_pSignature1;
RefCntAutoPtr<IPipelineResourceSignature> PSOCreationFailureTest::sm_pSignature1A;
GraphicsPipelineStateCreateInfo PSOCreationFailureTest::sm_DefaultGraphicsPsoCI;
GraphicsPipelineStateCreateInfo PSOCreationFailureTest::sm_DefaultMeshPsoCI;
ComputePipelineStateCreateInfo PSOCreationFailureTest::sm_DefaultComputePsoCI;
RayTracingPipelineStateCreateInfo PSOCreationFailureTest::sm_DefaultRayTracingPsoCI;
std::array<RayTracingGeneralShaderGroup, 1> PSOCreationFailureTest::sm_GeneralGroups;
bool PSOCreationFailureTest::sm_HasMeshShader;
bool PSOCreationFailureTest::sm_HasRayTracing;
TEST_F(PSOCreationFailureTest, InvalidGraphicsPipelineType)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid Graphics Pipeline Type")};
PsoCI.PSODesc.PipelineType = PIPELINE_TYPE_COMPUTE;
TestCreatePSOFailure(PsoCI, "Pipeline type must be GRAPHICS or MESH");
}
TEST_F(PSOCreationFailureTest, NoVS)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - no VS")};
PsoCI.pVS = nullptr;
TestCreatePSOFailure(PsoCI, "Vertex shader must not be null");
}
TEST_F(PSOCreationFailureTest, IncorrectVSType)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - incorrect VS Type")};
PsoCI.pVS = GetPS();
TestCreatePSOFailure(PsoCI, "SHADER_TYPE_PIXEL is not a valid type for vertex shader");
}
TEST_F(PSOCreationFailureTest, IncorrectPSType)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - incorrect PS Type")};
PsoCI.pPS = GetVS();
TestCreatePSOFailure(PsoCI, "SHADER_TYPE_VERTEX is not a valid type for pixel shader");
}
TEST_F(PSOCreationFailureTest, IncorrectGSType)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - incorrect GS Type")};
PsoCI.pGS = GetVS();
TestCreatePSOFailure(PsoCI, "SHADER_TYPE_VERTEX is not a valid type for geometry shader");
}
TEST_F(PSOCreationFailureTest, IncorrectDSType)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - incorrect DS Type")};
PsoCI.pDS = GetVS();
TestCreatePSOFailure(PsoCI, "SHADER_TYPE_VERTEX is not a valid type for domain shader");
}
TEST_F(PSOCreationFailureTest, IncorrectHSType)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - incorrect HS Type")};
PsoCI.pHS = GetVS();
TestCreatePSOFailure(PsoCI, "SHADER_TYPE_VERTEX is not a valid type for hull shader");
}
TEST_F(PSOCreationFailureTest, WrongSubpassIndex)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - wrong subpass index")};
PsoCI.GraphicsPipeline.SubpassIndex = 1;
TestCreatePSOFailure(PsoCI, "Subpass index (1) must be 0");
}
TEST_F(PSOCreationFailureTest, UndefinedFillMode)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Undefined Fill Mode")};
PsoCI.GraphicsPipeline.RasterizerDesc.FillMode = FILL_MODE_UNDEFINED;
TestCreatePSOFailure(PsoCI, "RasterizerDesc.FillMode must not be FILL_MODE_UNDEFINED");
}
TEST_F(PSOCreationFailureTest, UndefinedCullMode)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Undefined Cull Mode")};
PsoCI.GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_UNDEFINED;
TestCreatePSOFailure(PsoCI, "RasterizerDesc.CullMode must not be CULL_MODE_UNDEFINED");
}
TEST_F(PSOCreationFailureTest, InvalidDepthFunc)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid Depth Func")};
PsoCI.GraphicsPipeline.DepthStencilDesc.DepthFunc = COMPARISON_FUNC_UNKNOWN;
TestCreatePSOFailure(PsoCI, "DepthStencilDesc.DepthFunc must not be COMPARISON_FUNC_UNKNOWN");
}
TEST_F(PSOCreationFailureTest, InvalidFrontStencilFailOp)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid Front Face StencilFailOp")};
PsoCI.GraphicsPipeline.DepthStencilDesc.StencilEnable = True;
PsoCI.GraphicsPipeline.DepthStencilDesc.FrontFace.StencilFailOp = STENCIL_OP_UNDEFINED;
TestCreatePSOFailure(PsoCI, "DepthStencilDesc.FrontFace.StencilFailOp must not be STENCIL_OP_UNDEFINED");
}
TEST_F(PSOCreationFailureTest, InvalidBackStencilFailOp)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid Back Face StencilFailOp")};
PsoCI.GraphicsPipeline.DepthStencilDesc.StencilEnable = True;
PsoCI.GraphicsPipeline.DepthStencilDesc.BackFace.StencilFailOp = STENCIL_OP_UNDEFINED;
TestCreatePSOFailure(PsoCI, "DepthStencilDesc.BackFace.StencilFailOp must not be STENCIL_OP_UNDEFINED");
}
TEST_F(PSOCreationFailureTest, InvalidFrontStencilDepthFailOp)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid Front Face StencilDepthFailOp")};
PsoCI.GraphicsPipeline.DepthStencilDesc.StencilEnable = True;
PsoCI.GraphicsPipeline.DepthStencilDesc.FrontFace.StencilDepthFailOp = STENCIL_OP_UNDEFINED;
TestCreatePSOFailure(PsoCI, "DepthStencilDesc.FrontFace.StencilDepthFailOp must not be STENCIL_OP_UNDEFINED");
}
TEST_F(PSOCreationFailureTest, InvalidBackStencilDepthFailOp)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid Back Face StencilDepthFailOp")};
PsoCI.GraphicsPipeline.DepthStencilDesc.StencilEnable = True;
PsoCI.GraphicsPipeline.DepthStencilDesc.BackFace.StencilDepthFailOp = STENCIL_OP_UNDEFINED;
TestCreatePSOFailure(PsoCI, "DepthStencilDesc.BackFace.StencilDepthFailOp must not be STENCIL_OP_UNDEFINED");
}
TEST_F(PSOCreationFailureTest, InvalidFrontStencilPassOp)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid Front Face StencilPassOp")};
PsoCI.GraphicsPipeline.DepthStencilDesc.StencilEnable = True;
PsoCI.GraphicsPipeline.DepthStencilDesc.FrontFace.StencilPassOp = STENCIL_OP_UNDEFINED;
TestCreatePSOFailure(PsoCI, "DepthStencilDesc.FrontFace.StencilPassOp must not be STENCIL_OP_UNDEFINED");
}
TEST_F(PSOCreationFailureTest, InvalidBackStencilPassOp)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid Back Face StencilPassOp")};
PsoCI.GraphicsPipeline.DepthStencilDesc.StencilEnable = True;
PsoCI.GraphicsPipeline.DepthStencilDesc.BackFace.StencilPassOp = STENCIL_OP_UNDEFINED;
TestCreatePSOFailure(PsoCI, "DepthStencilDesc.BackFace.StencilPassOp must not be STENCIL_OP_UNDEFINED");
}
TEST_F(PSOCreationFailureTest, InvalidFrontStencilFunc)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid Front Face StencilFunc")};
PsoCI.GraphicsPipeline.DepthStencilDesc.StencilEnable = True;
PsoCI.GraphicsPipeline.DepthStencilDesc.FrontFace.StencilFunc = COMPARISON_FUNC_UNKNOWN;
TestCreatePSOFailure(PsoCI, "DepthStencilDesc.FrontFace.StencilFunc must not be COMPARISON_FUNC_UNKNOWN");
}
TEST_F(PSOCreationFailureTest, InvalidBackStencilFunc)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid Back Face StencilFunc")};
PsoCI.GraphicsPipeline.DepthStencilDesc.StencilEnable = True;
PsoCI.GraphicsPipeline.DepthStencilDesc.BackFace.StencilFunc = COMPARISON_FUNC_UNKNOWN;
TestCreatePSOFailure(PsoCI, "DepthStencilDesc.BackFace.StencilFunc must not be COMPARISON_FUNC_UNKNOWN");
}
TEST_F(PSOCreationFailureTest, InvalidSrcBlend)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid SrcBlend")};
PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendEnable = True;
PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].SrcBlend = BLEND_FACTOR_UNDEFINED;
TestCreatePSOFailure(PsoCI, "BlendDesc.RenderTargets[0].SrcBlend must not be BLEND_FACTOR_UNDEFINED");
}
TEST_F(PSOCreationFailureTest, InvalidDestBlend)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid DestBlend")};
PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendEnable = True;
PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].DestBlend = BLEND_FACTOR_UNDEFINED;
TestCreatePSOFailure(PsoCI, "BlendDesc.RenderTargets[0].DestBlend must not be BLEND_FACTOR_UNDEFINED");
}
TEST_F(PSOCreationFailureTest, InvalidBlendOp)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid BlendOp")};
PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendEnable = True;
PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendOp = BLEND_OPERATION_UNDEFINED;
TestCreatePSOFailure(PsoCI, "BlendDesc.RenderTargets[0].BlendOp must not be BLEND_OPERATION_UNDEFINED");
}
TEST_F(PSOCreationFailureTest, InvalidSrcBlendAlpha)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid SrcBlendAlpha")};
PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendEnable = True;
PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].SrcBlendAlpha = BLEND_FACTOR_UNDEFINED;
TestCreatePSOFailure(PsoCI, "BlendDesc.RenderTargets[0].SrcBlendAlpha must not be BLEND_FACTOR_UNDEFINED");
}
TEST_F(PSOCreationFailureTest, InvalidDestBlendAlpha)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid DestBlendAlpha")};
PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendEnable = True;
PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].DestBlendAlpha = BLEND_FACTOR_UNDEFINED;
TestCreatePSOFailure(PsoCI, "BlendDesc.RenderTargets[0].DestBlendAlpha must not be BLEND_FACTOR_UNDEFINED");
}
TEST_F(PSOCreationFailureTest, InvalidBlendOpAlpha)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid BlendOpAlpha")};
PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendEnable = True;
PsoCI.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendOpAlpha = BLEND_OPERATION_UNDEFINED;
TestCreatePSOFailure(PsoCI, "BlendDesc.RenderTargets[0].BlendOpAlpha must not be BLEND_OPERATION_UNDEFINED");
}
TEST_F(PSOCreationFailureTest, NullVariableName)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - null variable name")};
ShaderResourceVariableDesc Variables[] //
{
ShaderResourceVariableDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "g_Texture", SHADER_RESOURCE_VARIABLE_TYPE_STATIC},
ShaderResourceVariableDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, nullptr, SHADER_RESOURCE_VARIABLE_TYPE_STATIC} //
};
PsoCI.PSODesc.ResourceLayout.Variables = Variables;
PsoCI.PSODesc.ResourceLayout.NumVariables = _countof(Variables);
TestCreatePSOFailure(PsoCI, "ResourceLayout.Variables[1].Name must not be null");
}
TEST_F(PSOCreationFailureTest, EmptyVariableName)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - empty variable name")};
ShaderResourceVariableDesc Variables[] //
{
ShaderResourceVariableDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "g_Texture", SHADER_RESOURCE_VARIABLE_TYPE_STATIC},
ShaderResourceVariableDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "", SHADER_RESOURCE_VARIABLE_TYPE_STATIC} //
};
PsoCI.PSODesc.ResourceLayout.Variables = Variables;
PsoCI.PSODesc.ResourceLayout.NumVariables = _countof(Variables);
TestCreatePSOFailure(PsoCI, "ResourceLayout.Variables[1].Name must not be empty");
}
TEST_F(PSOCreationFailureTest, UnknownVariableShaderStage)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - unknown variable shader stage")};
ShaderResourceVariableDesc Variables[] //
{
ShaderResourceVariableDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "g_Texture", SHADER_RESOURCE_VARIABLE_TYPE_STATIC},
ShaderResourceVariableDesc{SHADER_TYPE_UNKNOWN, "g_Texture2", SHADER_RESOURCE_VARIABLE_TYPE_STATIC} //
};
PsoCI.PSODesc.ResourceLayout.Variables = Variables;
PsoCI.PSODesc.ResourceLayout.NumVariables = _countof(Variables);
TestCreatePSOFailure(PsoCI, "ResourceLayout.Variables[1].ShaderStages must not be SHADER_TYPE_UNKNOWN");
}
TEST_F(PSOCreationFailureTest, OverlappingVariableStages)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Overlapping Variable Stages")};
ShaderResourceVariableDesc Variables[] //
{
ShaderResourceVariableDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "g_Texture", SHADER_RESOURCE_VARIABLE_TYPE_STATIC},
ShaderResourceVariableDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_GEOMETRY, "g_Texture", SHADER_RESOURCE_VARIABLE_TYPE_STATIC} //
};
PsoCI.PSODesc.ResourceLayout.Variables = Variables;
PsoCI.PSODesc.ResourceLayout.NumVariables = _countof(Variables);
TestCreatePSOFailure(PsoCI, "'g_Texture' is defined in overlapping shader stages (SHADER_TYPE_VERTEX, SHADER_TYPE_GEOMETRY and SHADER_TYPE_VERTEX, SHADER_TYPE_PIXEL)");
}
TEST_F(PSOCreationFailureTest, NullImmutableSamplerName)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - null immutable sampler name")};
ImmutableSamplerDesc ImtblSamplers[] //
{
ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "g_Texture_sampler", SamplerDesc{}},
ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, nullptr, SamplerDesc{}} //
};
PsoCI.PSODesc.ResourceLayout.ImmutableSamplers = ImtblSamplers;
PsoCI.PSODesc.ResourceLayout.NumImmutableSamplers = _countof(ImtblSamplers);
TestCreatePSOFailure(PsoCI, "ResourceLayout.ImmutableSamplers[1].SamplerOrTextureName must not be null");
}
TEST_F(PSOCreationFailureTest, EmptyImmutableSamplerName)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - empty immutable sampler name")};
ImmutableSamplerDesc ImtblSamplers[] //
{
ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "g_Texture_sampler", SamplerDesc{}},
ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "", SamplerDesc{}} //
};
PsoCI.PSODesc.ResourceLayout.ImmutableSamplers = ImtblSamplers;
PsoCI.PSODesc.ResourceLayout.NumImmutableSamplers = _countof(ImtblSamplers);
TestCreatePSOFailure(PsoCI, "ResourceLayout.ImmutableSamplers[1].SamplerOrTextureName must not be empty");
}
TEST_F(PSOCreationFailureTest, UndefinedImmutableSamplerShaderStages)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - undefined immutable sampler shader stages")};
ImmutableSamplerDesc ImtblSamplers[] //
{
ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "g_Texture_sampler", SamplerDesc{}},
ImmutableSamplerDesc{SHADER_TYPE_UNKNOWN, "g_Texture_sampler2", SamplerDesc{}} //
};
PsoCI.PSODesc.ResourceLayout.ImmutableSamplers = ImtblSamplers;
PsoCI.PSODesc.ResourceLayout.NumImmutableSamplers = _countof(ImtblSamplers);
TestCreatePSOFailure(PsoCI, "ResourceLayout.ImmutableSamplers[1].ShaderStages must not be SHADER_TYPE_UNKNOWN");
}
TEST_F(PSOCreationFailureTest, OverlappingImmutableSamplerStages)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Overlapping Immutable Sampler Stages")};
ImmutableSamplerDesc ImtblSamplers[] //
{
ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "g_Texture_sampler", SamplerDesc{}},
ImmutableSamplerDesc{SHADER_TYPE_VERTEX | SHADER_TYPE_GEOMETRY, "g_Texture_sampler", SamplerDesc{}} //
};
PsoCI.PSODesc.ResourceLayout.ImmutableSamplers = ImtblSamplers;
PsoCI.PSODesc.ResourceLayout.NumImmutableSamplers = _countof(ImtblSamplers);
TestCreatePSOFailure(PsoCI, "'g_Texture_sampler' is defined in overlapping shader stages (SHADER_TYPE_VERTEX, SHADER_TYPE_GEOMETRY and SHADER_TYPE_VERTEX, SHADER_TYPE_PIXEL)");
}
TEST_F(PSOCreationFailureTest, RenderPassWithNonZeroNumRenderTargets)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Render Pass With non-zero NumRenderTargets", true)};
PsoCI.GraphicsPipeline.NumRenderTargets = 1;
TestCreatePSOFailure(PsoCI, "NumRenderTargets must be 0");
}
TEST_F(PSOCreationFailureTest, RenderPassWithDSVFormat)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Render Pass With defined DSV format", true)};
PsoCI.GraphicsPipeline.DSVFormat = TEX_FORMAT_D32_FLOAT;
TestCreatePSOFailure(PsoCI, "DSVFormat must be TEX_FORMAT_UNKNOWN");
}
TEST_F(PSOCreationFailureTest, RenderPassWithRTVFormat)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Render Pass With defined RTV format", true)};
PsoCI.GraphicsPipeline.RTVFormats[1] = TEX_FORMAT_RGBA8_UNORM;
TestCreatePSOFailure(PsoCI, "RTVFormats[1] must be TEX_FORMAT_UNKNOWN");
}
TEST_F(PSOCreationFailureTest, RenderPassWithInvalidSubpassIndex)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Render Pass With invalid Subpass index", true)};
PsoCI.GraphicsPipeline.SubpassIndex = 2;
TestCreatePSOFailure(PsoCI, "Subpass index (2) exceeds the number of subpasses (1)");
}
TEST_F(PSOCreationFailureTest, NullResourceSignatures)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Null Resource Signatures", true)};
PsoCI.ResourceSignaturesCount = 2;
TestCreatePSOFailure(PsoCI, "ppResourceSignatures is null, but ResourceSignaturesCount (2) is not zero");
}
TEST_F(PSOCreationFailureTest, ZeroResourceSignaturesCount)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Zero Resource Signatures Count", true)};
IPipelineResourceSignature* pSignatures[] = {sm_pSignature0};
PsoCI.ppResourceSignatures = pSignatures;
PsoCI.ResourceSignaturesCount = 0;
TestCreatePSOFailure(PsoCI, "ppResourceSignatures is not null, but ResourceSignaturesCount is zero.");
}
TEST_F(PSOCreationFailureTest, SignatureWithNonZeroNumVariables)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Resource Signature With non-zero NumVariables", true)};
IPipelineResourceSignature* pSignatures[] = {sm_pSignature0};
PsoCI.ppResourceSignatures = pSignatures;
PsoCI.ResourceSignaturesCount = _countof(pSignatures);
PsoCI.PSODesc.ResourceLayout.NumVariables = 3;
TestCreatePSOFailure(PsoCI, "The number of variables defined through resource layout (3) must be zero");
}
TEST_F(PSOCreationFailureTest, SignatureWithNonZeroNumImmutableSamplers)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Resource Signature With non-zero NumImmutableSamplers", true)};
IPipelineResourceSignature* pSignatures[] = {sm_pSignature0};
PsoCI.ppResourceSignatures = pSignatures;
PsoCI.ResourceSignaturesCount = _countof(pSignatures);
PsoCI.PSODesc.ResourceLayout.NumImmutableSamplers = 4;
TestCreatePSOFailure(PsoCI, "The number of immutable samplers defined through resource layout (4) must be zero");
}
TEST_F(PSOCreationFailureTest, NullSignature)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Null Signature", true)};
IPipelineResourceSignature* pSignatures[] = {sm_pSignature0, nullptr};
PsoCI.ppResourceSignatures = pSignatures;
PsoCI.ResourceSignaturesCount = _countof(pSignatures);
TestCreatePSOFailure(PsoCI, "signature at index 1 is null");
}
TEST_F(PSOCreationFailureTest, ConflictingSignatureBindIndex)
{
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Conflicting Signature Bind Index", true)};
IPipelineResourceSignature* pSignatures[] = {sm_pSignature0, sm_pSignature0A};
PsoCI.ppResourceSignatures = pSignatures;
PsoCI.ResourceSignaturesCount = _countof(pSignatures);
TestCreatePSOFailure(PsoCI, "'PRS0A' at binding index 0 conflicts with another resource signature 'PRS0'");
}
TEST_F(PSOCreationFailureTest, ConflictingSignatureResourceStages)
{
if (!sm_pSignature1)
GTEST_SKIP();
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - conflicting signature resource stages", true)};
IPipelineResourceSignature* pSignatures[] = {sm_pSignature0, sm_pSignature1};
PsoCI.ppResourceSignatures = pSignatures;
PsoCI.ResourceSignaturesCount = _countof(pSignatures);
TestCreatePSOFailure(PsoCI, "Shader resource 'g_Texture' is found in more than one resource signature ('PRS1' and 'PRS0')");
}
TEST_F(PSOCreationFailureTest, ConflictingImmutableSamplerStages)
{
if (!sm_pSignature1A)
GTEST_SKIP();
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - conflicting signature immutable sampler stages", true)};
IPipelineResourceSignature* pSignatures[] = {sm_pSignature0, sm_pSignature1A};
PsoCI.ppResourceSignatures = pSignatures;
PsoCI.ResourceSignaturesCount = _countof(pSignatures);
// In case of non-separable programs, there is another error - a resource ("g_Texture") is found in different signatures
const auto* ExpectedError = TestingEnvironment::GetInstance()->GetDevice()->GetDeviceInfo().Features.SeparablePrograms ?
"Immutable sampler 'g_Texture_sampler' is found in more than one resource signature ('PRS1A' and 'PRS0')" :
"shader resource 'g_Texture' is found in more than one resource signature ('PRS1A' and 'PRS0')";
TestCreatePSOFailure(PsoCI, ExpectedError);
}
TEST_F(PSOCreationFailureTest, InvalidComputePipelineType)
{
auto PsoCI{GetComputePSOCreateInfo("PSO Create Failure - Invalid Compute Pipeline Type")};
PsoCI.PSODesc.PipelineType = PIPELINE_TYPE_GRAPHICS;
TestCreatePSOFailure(PsoCI, "Pipeline type must be COMPUTE");
}
TEST_F(PSOCreationFailureTest, NoCS)
{
auto PsoCI{GetComputePSOCreateInfo("PSO Create Failure - no CS")};
PsoCI.pCS = nullptr;
TestCreatePSOFailure(PsoCI, "Compute shader must not be null");
}
TEST_F(PSOCreationFailureTest, InvalidCS)
{
auto PsoCI{GetComputePSOCreateInfo("PSO Create Failure - invalid CS")};
PsoCI.pCS = GetPS();
TestCreatePSOFailure(PsoCI, "SHADER_TYPE_PIXEL is not a valid type for compute shader");
}
TEST_F(PSOCreationFailureTest, NullMS)
{
if (!HasMeshShader())
GTEST_SKIP();
auto PsoCI{GetMeshPSOCreateInfo("PSO Create Failure - null MS")};
PsoCI.pMS = nullptr;
TestCreatePSOFailure(PsoCI, "Mesh shader must not be null");
}
TEST_F(PSOCreationFailureTest, InvalidMS)
{
if (!HasMeshShader())
GTEST_SKIP();
auto PsoCI{GetMeshPSOCreateInfo("PSO Create Failure - Invalid MS")};
PsoCI.pMS = GetPS();
TestCreatePSOFailure(PsoCI, "SHADER_TYPE_PIXEL is not a valid type for mesh shader");
}
TEST_F(PSOCreationFailureTest, NullRG)
{
if (!HasRayTracing())
GTEST_SKIP();
auto PsoCI{GetRayTracingPSOCreateInfo("PSO Create Failure - NUll ray-gen shader")};
PsoCI.pGeneralShaders = nullptr;
PsoCI.GeneralShaderCount = 0;
TestCreatePSOFailure(PsoCI, "At least one shader with type SHADER_TYPE_RAY_GEN must be provided");
}
TEST_F(PSOCreationFailureTest, InvalidRTPipelineType)
{
if (!HasRayTracing())
GTEST_SKIP();
auto PsoCI{GetRayTracingPSOCreateInfo("PSO Create Failure - Invalid RT pipeline type")};
PsoCI.PSODesc.PipelineType = PIPELINE_TYPE_COMPUTE;
TestCreatePSOFailure(PsoCI, "Pipeline type must be RAY_TRACING");
}
TEST_F(PSOCreationFailureTest, InvalidShaderRecord)
{
if (!HasRayTracing() || !TestingEnvironment::GetInstance()->GetDevice()->GetDeviceInfo().IsD3DDevice())
GTEST_SKIP();
auto PsoCI{GetRayTracingPSOCreateInfo("PSO Create Failure - Invalid shader record")};
PsoCI.pShaderRecordName = "ShaderRecord";
PsoCI.RayTracingPipeline.ShaderRecordSize = 0;
TestCreatePSOFailure(PsoCI, "pShaderRecordName must not be null if RayTracingPipeline.ShaderRecordSize is not zero");
}
TEST_F(PSOCreationFailureTest, TooBigRayRecursionDepth)
{
if (!HasRayTracing())
GTEST_SKIP();
auto PsoCI{GetRayTracingPSOCreateInfo("PSO Create Failure - too big ray recursion depth")};
PsoCI.RayTracingPipeline.MaxRecursionDepth = std::numeric_limits<decltype(PsoCI.RayTracingPipeline.MaxRecursionDepth)>::max();
TestCreatePSOFailure(PsoCI, "MaxRecursionDepth (255) exceeds device limit");
}
TEST_F(PSOCreationFailureTest, NullShaderGroupName)
{
if (!HasRayTracing())
GTEST_SKIP();
const RayTracingGeneralShaderGroup GeneralGroups[] = {{"Main", GetRayGen()}, {nullptr, GetRayMiss()}};
auto PsoCI{GetRayTracingPSOCreateInfo("PSO Create Failure - null shader group name")};
PsoCI.pGeneralShaders = GeneralGroups;
PsoCI.GeneralShaderCount = _countof(GeneralGroups);
TestCreatePSOFailure(PsoCI, "pGeneralShaders[1].Name must not be null");
}
TEST_F(PSOCreationFailureTest, EmptyShaderGroupName)
{
if (!HasRayTracing())
GTEST_SKIP();
const RayTracingGeneralShaderGroup GeneralGroups[] = {{"Main", GetRayGen()}, {"", GetRayMiss()}};
auto PsoCI{GetRayTracingPSOCreateInfo("PSO Create Failure - empty shader group name")};
PsoCI.pGeneralShaders = GeneralGroups;
PsoCI.GeneralShaderCount = _countof(GeneralGroups);
TestCreatePSOFailure(PsoCI, "pGeneralShaders[1].Name must not be empty");
}
TEST_F(PSOCreationFailureTest, NonUniqueShaderGroupName)
{
if (!HasRayTracing())
GTEST_SKIP();
const RayTracingGeneralShaderGroup GeneralGroups[] = {{"Main", GetRayGen()}, {"Main", GetRayMiss()}};
auto PsoCI{GetRayTracingPSOCreateInfo("PSO Create Failure - non-unique shader group name")};
PsoCI.pGeneralShaders = GeneralGroups;
PsoCI.GeneralShaderCount = _countof(GeneralGroups);
TestCreatePSOFailure(PsoCI, "pGeneralShaders[1].Name ('Main') has already been assigned to another group. All group names must be unique.");
}
TEST_F(PSOCreationFailureTest, NullGeneralShader)
{
if (!HasRayTracing())
GTEST_SKIP();
const RayTracingGeneralShaderGroup GeneralGroups[] = {{"Main", GetRayGen()}, {"Entry", nullptr}};
auto PsoCI{GetRayTracingPSOCreateInfo("PSO Create Failure - null general shader")};
PsoCI.pGeneralShaders = GeneralGroups;
PsoCI.GeneralShaderCount = _countof(GeneralGroups);
TestCreatePSOFailure(PsoCI, "pGeneralShaders[1].pShader must not be null");
}
TEST_F(PSOCreationFailureTest, NullTriHitShader)
{
if (!HasRayTracing())
GTEST_SKIP();
const RayTracingTriangleHitShaderGroup HitGroups[] = {{"ClosestHit", nullptr}};
auto PsoCI{GetRayTracingPSOCreateInfo("PSO Create Failure - null triangle closest hit shader")};
PsoCI.pTriangleHitShaders = HitGroups;
PsoCI.TriangleHitShaderCount = _countof(HitGroups);
TestCreatePSOFailure(PsoCI, "pTriangleHitShaders[0].pClosestHitShader must not be null");
}
TEST_F(PSOCreationFailureTest, NullProcHitShader)
{
if (!HasRayTracing())
GTEST_SKIP();
const RayTracingProceduralHitShaderGroup HitGroups[] = {{"Intersection", nullptr}};
auto PsoCI{GetRayTracingPSOCreateInfo("PSO Create Failure - null procedural intersection shader")};
PsoCI.pProceduralHitShaders = HitGroups;
PsoCI.ProceduralHitShaderCount = _countof(HitGroups);
TestCreatePSOFailure(PsoCI, "pProceduralHitShaders[0].pIntersectionShader must not be null");
}
TEST_F(PSOCreationFailureTest, InvalidShaderinGeneralGroup)
{
if (!HasRayTracing())
GTEST_SKIP();
const RayTracingGeneralShaderGroup GeneralGroups[] = {{"Main", GetRayGen()}, {"Miss", GetRayMiss()}, {"Call", GetCallable()}, {"Hit", GetRayClosestHit()}};
auto PsoCI{GetRayTracingPSOCreateInfo("PSO Create Failure - invalid shader in general group")};
PsoCI.pGeneralShaders = GeneralGroups;
PsoCI.GeneralShaderCount = _countof(GeneralGroups);
TestCreatePSOFailure(PsoCI, "SHADER_TYPE_RAY_CLOSEST_HIT is not a valid type for ray tracing general shader");
}
TEST_F(PSOCreationFailureTest, InvalidShaderinTriangleHitGroup1)
{
if (!HasRayTracing())
GTEST_SKIP();
const RayTracingTriangleHitShaderGroup HitGroups[] = {
{"CHit", GetRayClosestHit(), nullptr},
{"CHit-AHit", GetRayClosestHit(), GetRayAnyHit()},
{"Miss", GetRayMiss()} //
};
auto PsoCI{GetRayTracingPSOCreateInfo("PSO Create Failure - invalid shader in triangle hit group - 1")};
PsoCI.pTriangleHitShaders = HitGroups;
PsoCI.TriangleHitShaderCount = _countof(HitGroups);
TestCreatePSOFailure(PsoCI, "SHADER_TYPE_RAY_MISS is not a valid type for ray tracing triangle closest hit");
}
TEST_F(PSOCreationFailureTest, InvalidShaderinTriangleHitGroup2)
{
if (!HasRayTracing())
GTEST_SKIP();
const RayTracingTriangleHitShaderGroup HitGroups[] = {
{"CHit", GetRayClosestHit(), nullptr},
{"CHit-AHit", GetRayClosestHit(), GetRayAnyHit()},
{"CHit-Miss", GetRayClosestHit(), GetRayIntersection()} //
};
auto PsoCI{GetRayTracingPSOCreateInfo("PSO Create Failure - invalid shader in triangle hit group - 2")};
PsoCI.pTriangleHitShaders = HitGroups;
PsoCI.TriangleHitShaderCount = _countof(HitGroups);
TestCreatePSOFailure(PsoCI, "SHADER_TYPE_RAY_INTERSECTION is not a valid type for ray tracing triangle any hit");
}
TEST_F(PSOCreationFailureTest, InvalidShaderinProceduralHitGroup1)
{
if (!HasRayTracing())
GTEST_SKIP();
const RayTracingProceduralHitShaderGroup HitGroups[] = {
{"Int", GetRayIntersection(), nullptr, nullptr},
{"Int-CHit", GetRayIntersection(), GetRayClosestHit(), nullptr},
{"Int-CHit-AHit", GetRayIntersection(), GetRayClosestHit(), GetRayAnyHit()},
{"Call", GetCallable(), nullptr, nullptr} //
};
auto PsoCI{GetRayTracingPSOCreateInfo("PSO Create Failure - invalid shader in procedural hit group - 1")};
PsoCI.pProceduralHitShaders = HitGroups;
PsoCI.ProceduralHitShaderCount = _countof(HitGroups);
TestCreatePSOFailure(PsoCI, "SHADER_TYPE_CALLABLE is not a valid type for ray tracing procedural intersection");
}
TEST_F(PSOCreationFailureTest, InvalidShaderinProceduralHitGroup2)
{
if (!HasRayTracing())
GTEST_SKIP();
const RayTracingProceduralHitShaderGroup HitGroups[] = {
{"Int", GetRayIntersection(), nullptr, nullptr},
{"Int-CHit", GetRayIntersection(), GetRayClosestHit(), nullptr},
{"Int-CHit-AHit", GetRayIntersection(), GetRayClosestHit(), GetRayAnyHit()},
{"Int-RG", GetRayIntersection(), GetRayGen(), nullptr} //
};
auto PsoCI{GetRayTracingPSOCreateInfo("PSO Create Failure - invalid shader in procedural hit group - 2")};
PsoCI.pProceduralHitShaders = HitGroups;
PsoCI.ProceduralHitShaderCount = _countof(HitGroups);
TestCreatePSOFailure(PsoCI, "SHADER_TYPE_RAY_GEN is not a valid type for ray tracing procedural closest hit");
}
TEST_F(PSOCreationFailureTest, InvalidShaderinProceduralHitGroup3)
{
if (!HasRayTracing())
GTEST_SKIP();
const RayTracingProceduralHitShaderGroup HitGroups[] = {
{"Int", GetRayIntersection(), nullptr, nullptr},
{"Int-CHit", GetRayIntersection(), GetRayClosestHit(), nullptr},
{"Int-CHit-AHit", GetRayIntersection(), GetRayClosestHit(), GetRayAnyHit()},
{"Int-CHit-CHit", GetRayIntersection(), GetRayClosestHit(), GetRayClosestHit()} //
};
auto PsoCI{GetRayTracingPSOCreateInfo("PSO Create Failure - invalid shader in procedural hit group - 3")};
PsoCI.pProceduralHitShaders = HitGroups;
PsoCI.ProceduralHitShaderCount = _countof(HitGroups);
TestCreatePSOFailure(PsoCI, "SHADER_TYPE_RAY_CLOSEST_HIT is not a valid type for ray tracing procedural any hit");
}
TEST_F(PSOCreationFailureTest, MissingResource)
{
PipelineResourceSignatureDesc PRSDesc;
PRSDesc.Name = "PSO Create Failure - missing resource";
PipelineResourceDesc Resources[]{
{SHADER_TYPE_PIXEL, "g_AnotherTexture", 1, SHADER_RESOURCE_TYPE_TEXTURE_SRV, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE}};
PRSDesc.UseCombinedTextureSamplers = true;
PRSDesc.Resources = Resources;
PRSDesc.NumResources = _countof(Resources);
auto* pDevice = TestingEnvironment::GetInstance()->GetDevice();
RefCntAutoPtr<IPipelineResourceSignature> pPRS;
pDevice->CreatePipelineResourceSignature(PRSDesc, &pPRS);
ASSERT_NE(pPRS, nullptr);
IPipelineResourceSignature* ppSignatures[] = {pPRS};
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - missing resource")};
PsoCI.ppResourceSignatures = ppSignatures;
PsoCI.ResourceSignaturesCount = _countof(ppSignatures);
PsoCI.pPS = GetTexturePS();
std::string ExpectedErrorString = "contains resource 'g_Texture' that is not present in any pipeline resource signature";
if (pDevice->GetDeviceInfo().Features.SeparablePrograms)
ExpectedErrorString = std::string{"Shader 'TexturePS (PSOCreationFailureTest)' "} + ExpectedErrorString;
// In non-separable programs case, PSO name is used instead of the shader name
TestCreatePSOFailure(PsoCI, ExpectedErrorString.c_str());
}
TEST_F(PSOCreationFailureTest, InvalidResourceType)
{
PipelineResourceSignatureDesc PRSDesc;
PRSDesc.Name = "PSO Create Failure - Invalid Resource Type";
PipelineResourceDesc Resources[]{
{SHADER_TYPE_PIXEL, "g_Texture", 1, SHADER_RESOURCE_TYPE_BUFFER_SRV, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE}};
PRSDesc.UseCombinedTextureSamplers = true;
PRSDesc.Resources = Resources;
PRSDesc.NumResources = _countof(Resources);
auto* pDevice = TestingEnvironment::GetInstance()->GetDevice();
RefCntAutoPtr<IPipelineResourceSignature> pPRS;
pDevice->CreatePipelineResourceSignature(PRSDesc, &pPRS);
ASSERT_NE(pPRS, nullptr);
IPipelineResourceSignature* ppSignatures[] = {pPRS};
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid Resource Type")};
PsoCI.ppResourceSignatures = ppSignatures;
PsoCI.ResourceSignaturesCount = _countof(ppSignatures);
PsoCI.pPS = GetTexturePS();
std::string ExpectedErrorString = "contains resource with name 'g_Texture' and type 'texture SRV' that is not compatible with type 'buffer SRV'";
if (pDevice->GetDeviceInfo().Features.SeparablePrograms)
ExpectedErrorString = std::string{"Shader 'TexturePS (PSOCreationFailureTest)' "} + ExpectedErrorString;
// In non-separable programs case, PSO name is used of the shader name
TestCreatePSOFailure(PsoCI, ExpectedErrorString.c_str());
}
TEST_F(PSOCreationFailureTest, InvalidArraySize)
{
static constexpr char PSSource[] = R"(
Texture2D g_Texture[3];
float4 main() : SV_Target
{
return g_Texture[0].Load(int3(0,0,0)) + g_Texture[1].Load(int3(0,0,0)) + g_Texture[2].Load(int3(0,0,0));
}
)";
auto* const pEnv = TestingEnvironment::GetInstance();
auto* const pDevice = pEnv->GetDevice();
ShaderCreateInfo ShaderCI;
ShaderCI.Source = PSSource;
ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL;
ShaderCI.Desc.Name = "Invalid Array Size (PSOCreationFailureTest)";
ShaderCI.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL;
ShaderCI.ShaderCompiler = pEnv->GetDefaultCompiler(ShaderCI.SourceLanguage);
ShaderCI.UseCombinedTextureSamplers = true;
RefCntAutoPtr<IShader> pPS;
pDevice->CreateShader(ShaderCI, &pPS);
PipelineResourceSignatureDesc PRSDesc;
PRSDesc.Name = "PSO Create Failure - Invalid Array Size";
PipelineResourceDesc Resources[]{
{SHADER_TYPE_PIXEL, "g_Texture", 2, SHADER_RESOURCE_TYPE_TEXTURE_SRV, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE}};
PRSDesc.UseCombinedTextureSamplers = true;
PRSDesc.Resources = Resources;
PRSDesc.NumResources = _countof(Resources);
RefCntAutoPtr<IPipelineResourceSignature> pPRS;
pDevice->CreatePipelineResourceSignature(PRSDesc, &pPRS);
ASSERT_NE(pPRS, nullptr);
IPipelineResourceSignature* ppSignatures[] = {pPRS};
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid Array Size")};
PsoCI.ppResourceSignatures = ppSignatures;
PsoCI.ResourceSignaturesCount = _countof(ppSignatures);
PsoCI.pPS = pPS;
std::string ExpectedErrorString = "contains resource 'g_Texture' whose array size (3) is greater than the array size (2)";
if (pDevice->GetDeviceInfo().Features.SeparablePrograms)
ExpectedErrorString = std::string{"Shader 'Invalid Array Size (PSOCreationFailureTest)' "} + ExpectedErrorString;
// In non-separable programs case, PSO name is used
TestCreatePSOFailure(PsoCI, ExpectedErrorString.c_str());
}
TEST_F(PSOCreationFailureTest, InvalidRunTimeArray)
{
auto* const pEnv = TestingEnvironment::GetInstance();
auto* const pDevice = pEnv->GetDevice();
const auto& DeviceInfo = pDevice->GetDeviceInfo();
if (!DeviceInfo.Features.ShaderResourceRuntimeArray)
{
GTEST_SKIP();
}
static constexpr char PSSource_HLSL[] = R"(
Texture2D g_Texture[];
cbuffer ConstBuffer
{
uint Index;
}
float4 main() : SV_Target
{
return g_Texture[Index].Load(int3(0,0,0));
}
)";
static constexpr char PSSource_GLSL[] = R"(
#version 460 core
#extension GL_EXT_nonuniform_qualifier : require
#extension GL_EXT_samplerless_texture_functions : require
uniform texture2D g_Texture[];
layout(std140) uniform ConstBuffer
{
uint Index;
};
layout(location=0) out vec4 out_Color;
void main()
{
out_Color = texelFetch(g_Texture[nonuniformEXT(Index)], ivec2(0,0), 0);
}
)";
ShaderCreateInfo ShaderCI;
ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL;
ShaderCI.Desc.Name = "Invalid Run-Time Array (PSOCreationFailureTest)";
ShaderCI.ShaderCompiler = pEnv->GetDefaultCompiler(ShaderCI.SourceLanguage);
if (DeviceInfo.IsD3DDevice())
{
ShaderCI.Source = PSSource_HLSL;
ShaderCI.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL;
}
else
{
ShaderCI.Source = PSSource_GLSL;
ShaderCI.SourceLanguage = SHADER_SOURCE_LANGUAGE_GLSL_VERBATIM;
}
ShaderCI.UseCombinedTextureSamplers = true;
ShaderCI.CompileFlags = SHADER_COMPILE_FLAG_ENABLE_UNBOUNDED_ARRAYS;
RefCntAutoPtr<IShader> pPS;
pDevice->CreateShader(ShaderCI, &pPS);
PipelineResourceSignatureDesc PRSDesc;
PRSDesc.Name = "PSO Create Failure - Invalid Run-Time Array";
PipelineResourceDesc Resources[]{
{SHADER_TYPE_PIXEL, "ConstBuffer", 1, SHADER_RESOURCE_TYPE_CONSTANT_BUFFER, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE},
{SHADER_TYPE_PIXEL, "g_Texture", 2, SHADER_RESOURCE_TYPE_TEXTURE_SRV, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE}};
PRSDesc.UseCombinedTextureSamplers = true;
PRSDesc.Resources = Resources;
PRSDesc.NumResources = _countof(Resources);
RefCntAutoPtr<IPipelineResourceSignature> pPRS;
pDevice->CreatePipelineResourceSignature(PRSDesc, &pPRS);
ASSERT_NE(pPRS, nullptr);
IPipelineResourceSignature* ppSignatures[] = {pPRS};
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Invalid Run-Time Array")};
PsoCI.ppResourceSignatures = ppSignatures;
PsoCI.ResourceSignaturesCount = _countof(ppSignatures);
PsoCI.pPS = pPS;
TestCreatePSOFailure(PsoCI, "Shader 'Invalid Run-Time Array (PSOCreationFailureTest)' contains resource 'g_Texture' that is a runtime-sized array, "
"but in the resource signature 'PSO Create Failure - Invalid Run-Time Array' the resource is defined without the PIPELINE_RESOURCE_FLAG_RUNTIME_ARRAY flag.");
}
TEST_F(PSOCreationFailureTest, NonSeparablePrograms_SeparateResources)
{
if (TestingEnvironment::GetInstance()->GetDevice()->GetDeviceInfo().Features.SeparablePrograms)
{
GTEST_SKIP();
}
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Non Separable Programs - Separate Resources")};
ShaderResourceVariableDesc Variables[] //
{
ShaderResourceVariableDesc{SHADER_TYPE_VERTEX, "g_Texture", SHADER_RESOURCE_VARIABLE_TYPE_STATIC},
ShaderResourceVariableDesc{SHADER_TYPE_PIXEL, "g_Texture", SHADER_RESOURCE_VARIABLE_TYPE_STATIC} //
};
PsoCI.PSODesc.ResourceLayout.Variables = Variables;
PsoCI.PSODesc.ResourceLayout.NumVariables = _countof(Variables);
TestCreatePSOFailure(PsoCI, "there are separate resources with the name 'g_Texture' in shader stages SHADER_TYPE_PIXEL and SHADER_TYPE_VERTEX");
}
TEST_F(PSOCreationFailureTest, NonSeparablePrograms_SeparateImmutableSamplers)
{
if (TestingEnvironment::GetInstance()->GetDevice()->GetDeviceInfo().Features.SeparablePrograms)
{
GTEST_SKIP();
}
auto PsoCI{GetGraphicsPSOCreateInfo("PSO Create Failure - Non Separable Programs - Separate Immutable Samplers")};
ImmutableSamplerDesc ImtblSamplers[] //
{
ImmutableSamplerDesc{SHADER_TYPE_VERTEX, "g_Texture_sampler", SamplerDesc{}},
ImmutableSamplerDesc{SHADER_TYPE_PIXEL, "g_Texture_sampler", SamplerDesc{}} //
};
PsoCI.PSODesc.ResourceLayout.ImmutableSamplers = ImtblSamplers;
PsoCI.PSODesc.ResourceLayout.NumImmutableSamplers = _countof(ImtblSamplers);
TestCreatePSOFailure(PsoCI, "there are separate immutable samplers with the name 'g_Texture_sampler' in shader stages SHADER_TYPE_PIXEL and SHADER_TYPE_VERTEX");
}
} // namespace
| 42.690633 | 190 | 0.723435 | [
"mesh",
"geometry",
"render"
] |
86e81ed4afa9fd710469b79fdc3dee953d5e978f | 23,673 | cpp | C++ | src/game/BattleGround/BattleGroundAB.cpp | H0zen/M3-server | 5143cec7ef9daa87c10c7b01ad7fe9ad709fa47d | [
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null | src/game/BattleGround/BattleGroundAB.cpp | H0zen/M3-server | 5143cec7ef9daa87c10c7b01ad7fe9ad709fa47d | [
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null | src/game/BattleGround/BattleGroundAB.cpp | H0zen/M3-server | 5143cec7ef9daa87c10c7b01ad7fe9ad709fa47d | [
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null | /**
* MaNGOS is a full featured server for World of Warcraft, supporting
* the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
*
* Copyright (C) 2005-2017 MaNGOS project <https://getmangos.eu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
#include "Object.h"
#include "Player.h"
#include "BattleGround.h"
#include "BattleGroundAB.h"
#include "GameObject.h"
#include "BattleGroundMgr.h"
#include "Language.h"
#include "WorldPacket.h"
#include "DBCStores.h" // TODO REMOVE this when graveyard handling for pvp is updated
/// <summary>
/// Initializes a new instance of the <see cref="BattleGroundAB"/> class.
/// </summary>
BattleGroundAB::BattleGroundAB()
{
m_StartMessageIds[BG_STARTING_EVENT_FIRST] = 0;
m_StartMessageIds[BG_STARTING_EVENT_SECOND] = LANG_BG_AB_START_ONE_MINUTE;
m_StartMessageIds[BG_STARTING_EVENT_THIRD] = LANG_BG_AB_START_HALF_MINUTE;
m_StartMessageIds[BG_STARTING_EVENT_FOURTH] = LANG_BG_AB_HAS_BEGUN;
}
/// <summary>
/// Finalizes an instance of the <see cref="BattleGroundAB"/> class.
/// </summary>
BattleGroundAB::~BattleGroundAB()
{
}
/// <summary>
/// Updates the specified diff.
/// </summary>
/// <param name="diff">The diff.</param>
void BattleGroundAB::Update(uint32 diff)
{
BattleGround::Update(diff);
if (GetStatus() == STATUS_IN_PROGRESS)
{
int team_points[PVP_TEAM_COUNT] = { 0, 0 };
for (uint8 node = 0; node < BG_AB_NODES_MAX; ++node)
{
// 3 sec delay to spawn new banner instead previous despawned one
if (m_BannerTimers[node].timer)
{
if (m_BannerTimers[node].timer > diff)
{ m_BannerTimers[node].timer -= diff; }
else
{
m_BannerTimers[node].timer = 0;
_CreateBanner(node, m_BannerTimers[node].type, m_BannerTimers[node].teamIndex, false);
}
}
// 1-minute to occupy a node from contested state
if (m_NodeTimers[node])
{
if (m_NodeTimers[node] > diff)
{ m_NodeTimers[node] -= diff; }
else
{
m_NodeTimers[node] = 0;
// Change from contested to occupied !
uint8 teamIndex = m_Nodes[node] - 1;
m_prevNodes[node] = m_Nodes[node];
m_Nodes[node] += 2;
// create new occupied banner
_CreateBanner(node, BG_AB_NODE_TYPE_OCCUPIED, teamIndex, true);
_SendNodeUpdate(node);
_NodeOccupied(node, (teamIndex == 0) ? ALLIANCE : HORDE);
// Message to chatlog
if (teamIndex == 0)
{
SendMessage2ToAll(LANG_BG_AB_NODE_TAKEN, CHAT_MSG_BG_SYSTEM_ALLIANCE, NULL, LANG_BG_ALLY, _GetNodeNameId(node));
PlaySoundToAll(BG_AB_SOUND_NODE_CAPTURED_ALLIANCE);
}
else
{
SendMessage2ToAll(LANG_BG_AB_NODE_TAKEN, CHAT_MSG_BG_SYSTEM_HORDE, NULL, LANG_BG_HORDE, _GetNodeNameId(node));
PlaySoundToAll(BG_AB_SOUND_NODE_CAPTURED_HORDE);
}
}
}
for (uint8 team = 0; team < PVP_TEAM_COUNT; ++team)
if (m_Nodes[node] == team + BG_AB_NODE_TYPE_OCCUPIED)
{ ++team_points[team]; }
}
// Accumulate points
for (uint8 team = 0; team < PVP_TEAM_COUNT; ++team)
{
int points = team_points[team];
if (!points)
{ continue; }
m_lastTick[team] += diff;
if (m_lastTick[team] > BG_AB_TickIntervals[points])
{
m_lastTick[team] -= BG_AB_TickIntervals[points];
m_TeamScores[team] += BG_AB_TickPoints[points];
m_honorScoreTicks[team] += BG_AB_TickPoints[points];
m_ReputationScoreTics[team] += BG_AB_TickPoints[points];
if (m_ReputationScoreTics[team] >= m_ReputationTics)
{
(team == TEAM_INDEX_ALLIANCE) ? RewardReputationToTeam(509, 10, ALLIANCE) : RewardReputationToTeam(510, 10, HORDE);
m_ReputationScoreTics[team] -= m_ReputationTics;
}
if (m_honorScoreTicks[team] >= m_honorTicks)
{
RewardHonorToTeam(GetBonusHonorFromKill(1), (team == TEAM_INDEX_ALLIANCE) ? ALLIANCE : HORDE);
m_honorScoreTicks[team] -= m_honorTicks;
}
if (!m_IsInformedNearVictory && m_TeamScores[team] > BG_AB_WARNING_NEAR_VICTORY_SCORE)
{
if (team == TEAM_INDEX_ALLIANCE)
{ SendMessageToAll(LANG_BG_AB_A_NEAR_VICTORY, CHAT_MSG_BG_SYSTEM_NEUTRAL); }
else
{ SendMessageToAll(LANG_BG_AB_H_NEAR_VICTORY, CHAT_MSG_BG_SYSTEM_NEUTRAL); }
PlaySoundToAll(BG_AB_SOUND_NEAR_VICTORY);
m_IsInformedNearVictory = true;
}
if (m_TeamScores[team] > BG_AB_MAX_TEAM_SCORE)
{ m_TeamScores[team] = BG_AB_MAX_TEAM_SCORE; }
if (team == TEAM_INDEX_ALLIANCE)
{ UpdateWorldState(BG_AB_OP_RESOURCES_ALLY, m_TeamScores[team]); }
if (team == TEAM_INDEX_HORDE)
{ UpdateWorldState(BG_AB_OP_RESOURCES_HORDE, m_TeamScores[team]); }
// update achievement flags
// we increased m_TeamScores[team] so we just need to check if it is 500 more than other teams resources
// horde will be a bit disadvantaged, but we can assume that points aren't updated for both team in same Update() call
uint8 otherTeam = (team + 1) % PVP_TEAM_COUNT;
if (m_TeamScores[team] > m_TeamScores[otherTeam] + 500)
m_TeamScores500Disadvantage[otherTeam] = true;
}
}
// Test win condition
if (m_TeamScores[TEAM_INDEX_ALLIANCE] >= BG_AB_MAX_TEAM_SCORE)
{ EndBattleGround(ALLIANCE); }
if (m_TeamScores[TEAM_INDEX_HORDE] >= BG_AB_MAX_TEAM_SCORE)
{ EndBattleGround(HORDE); }
}
}
/// <summary>
/// Startings the event open doors.
/// </summary>
void BattleGroundAB::StartingEventOpenDoors()
{
OpenDoorEvent(BG_EVENT_DOOR);
// Players that join battleground after start are not eligible to get achievement.
StartTimedAchievement(ACHIEVEMENT_CRITERIA_TYPE_WIN_BG, AB_EVENT_START_BATTLE);
}
/// <summary>
/// Adds the player.
/// </summary>
/// <param name="plr">The PLR.</param>
void BattleGroundAB::AddPlayer(Player* plr)
{
BattleGround::AddPlayer(plr);
// create score and add it to map, default values are set in the constructor
BattleGroundABScore* sc = new BattleGroundABScore;
m_PlayerScores[plr->GetObjectGuid()] = sc;
}
/// <summary>
/// Removes the player.
/// </summary>
/// <param name="">The .</param>
/// <param name="">The .</param>
void BattleGroundAB::RemovePlayer(Player * /*plr*/, ObjectGuid /*guid*/)
{
}
/// <summary>
/// Handles the area trigger.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="trigger">The trigger.</param>
bool BattleGroundAB::HandleAreaTrigger(Player* source, uint32 trigger)
{
switch (trigger)
{
case 3948: // Arathi Basin Alliance Exit.
if (source->GetTeam() != ALLIANCE)
{ source->GetSession()->SendNotification(LANG_BATTLEGROUND_ONLY_ALLIANCE_USE); }
else
{ source->LeaveBattleground(); }
break;
case 3949: // Arathi Basin Horde Exit.
if (source->GetTeam() != HORDE)
{ source->GetSession()->SendNotification(LANG_BATTLEGROUND_ONLY_HORDE_USE); }
else
{ source->LeaveBattleground(); }
break;
default:
return false;
}
return true;
}
/// <summary>
/// Creates the banner.
/// </summary>
/// <param name="node">The node.</param>
/// <param name="type">The type. 0-neutral, 1-contested, 3-occupied</param>
/// <param name="teamIndex">Index of the team. 0-ally, 1-horde</param>
/// <param name="delay">The delay.</param>
void BattleGroundAB::_CreateBanner(uint8 node, uint8 type, uint8 teamIndex, bool delay)
{
// Just put it into the queue
if (delay)
{
m_BannerTimers[node].timer = 2000;
m_BannerTimers[node].type = type;
m_BannerTimers[node].teamIndex = teamIndex;
return;
}
// cause the node-type is in the generic form
// please see in the headerfile for the ids
if (type != BG_AB_NODE_TYPE_NEUTRAL)
{ type += teamIndex; }
SpawnEvent(node, type, true); // will automaticly despawn other events
}
/// <summary>
/// _s the get node name id.
/// </summary>
/// <param name="node">The node.</param>
/// <returns></returns>
int32 BattleGroundAB::_GetNodeNameId(uint8 node)
{
switch (node)
{
case BG_AB_NODE_STABLES: return LANG_BG_AB_NODE_STABLES;
case BG_AB_NODE_BLACKSMITH: return LANG_BG_AB_NODE_BLACKSMITH;
case BG_AB_NODE_FARM: return LANG_BG_AB_NODE_FARM;
case BG_AB_NODE_LUMBER_MILL: return LANG_BG_AB_NODE_LUMBER_MILL;
case BG_AB_NODE_GOLD_MINE: return LANG_BG_AB_NODE_GOLD_MINE;
default:
MANGOS_ASSERT(0);
}
return 0;
}
/// <summary>
/// Fills the initial world states.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="count">The count.</param>
void BattleGroundAB::FillInitialWorldStates(WorldPacket& data, uint32& count)
{
const uint8 plusArray[] = {0, 2, 3, 0, 1};
// Node icons
for (uint8 node = 0; node < BG_AB_NODES_MAX; ++node)
{ FillInitialWorldState(data, count, BG_AB_OP_NODEICONS[node], m_Nodes[node] == 0); }
// Node occupied states
for (uint8 node = 0; node < BG_AB_NODES_MAX; ++node)
for (uint8 i = 1; i < BG_AB_NODES_MAX; ++i)
{ FillInitialWorldState(data, count, BG_AB_OP_NODESTATES[node] + plusArray[i], m_Nodes[node] == i); }
// How many bases each team owns
uint8 ally = 0, horde = 0;
for (uint8 node = 0; node < BG_AB_NODES_MAX; ++node)
if (m_Nodes[node] == BG_AB_NODE_STATUS_ALLY_OCCUPIED)
{ ++ally; }
else if (m_Nodes[node] == BG_AB_NODE_STATUS_HORDE_OCCUPIED)
{ ++horde; }
FillInitialWorldState(data, count, BG_AB_OP_OCCUPIED_BASES_ALLY, ally);
FillInitialWorldState(data, count, BG_AB_OP_OCCUPIED_BASES_HORDE, horde);
// Team scores
FillInitialWorldState(data, count, BG_AB_OP_RESOURCES_MAX, BG_AB_MAX_TEAM_SCORE);
FillInitialWorldState(data, count, BG_AB_OP_RESOURCES_WARNING, BG_AB_WARNING_NEAR_VICTORY_SCORE);
FillInitialWorldState(data, count, BG_AB_OP_RESOURCES_ALLY, m_TeamScores[TEAM_INDEX_ALLIANCE]);
FillInitialWorldState(data, count, BG_AB_OP_RESOURCES_HORDE, m_TeamScores[TEAM_INDEX_HORDE]);
// other unknown
FillInitialWorldState(data, count, 0x745, 0x2); // 37 1861 unk
}
/// <summary>
/// _s the send node update.
/// </summary>
/// <param name="node">The node.</param>
void BattleGroundAB::_SendNodeUpdate(uint8 node)
{
// Send node owner state update to refresh map icons on client
const uint8 plusArray[] = {0, 2, 3, 0, 1};
if (m_prevNodes[node])
{ UpdateWorldState(BG_AB_OP_NODESTATES[node] + plusArray[m_prevNodes[node]], WORLD_STATE_REMOVE); }
else
{ UpdateWorldState(BG_AB_OP_NODEICONS[node], WORLD_STATE_REMOVE); }
UpdateWorldState(BG_AB_OP_NODESTATES[node] + plusArray[m_Nodes[node]], WORLD_STATE_ADD);
// How many bases each team owns
uint8 ally = 0, horde = 0;
for (uint8 i = 0; i < BG_AB_NODES_MAX; ++i)
if (m_Nodes[i] == BG_AB_NODE_STATUS_ALLY_OCCUPIED)
{ ++ally; }
else if (m_Nodes[i] == BG_AB_NODE_STATUS_HORDE_OCCUPIED)
{ ++horde; }
UpdateWorldState(BG_AB_OP_OCCUPIED_BASES_ALLY, ally);
UpdateWorldState(BG_AB_OP_OCCUPIED_BASES_HORDE, horde);
}
/// <summary>
/// _s the node occupied.
/// </summary>
/// <param name="node">The node.</param>
/// <param name="team">The team.</param>
void BattleGroundAB::_NodeOccupied(uint8 node, Team team)
{
uint8 capturedNodes = 0;
for (uint8 i = 0; i < BG_AB_NODES_MAX; ++i)
{
if (m_Nodes[node] == GetTeamIndexByTeamId(team) + BG_AB_NODE_TYPE_OCCUPIED && !m_NodeTimers[i])
{ ++capturedNodes; }
}
if (capturedNodes >= 5)
{ CastSpellOnTeam(SPELL_AB_QUEST_REWARD_5_BASES, team); }
if (capturedNodes >= 4)
{ CastSpellOnTeam(SPELL_AB_QUEST_REWARD_4_BASES, team); }
}
/* Invoked if a player used a banner as a gameobject */
/// <summary>
/// Events the player clicked on flag.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="target_obj">The target_obj.</param>
void BattleGroundAB::EventPlayerClickedOnFlag(Player* source, GameObject* target_obj)
{
if (GetStatus() != STATUS_IN_PROGRESS)
{ return; }
uint8 event = (sBattleGroundMgr.GetGameObjectEventIndex(target_obj->GetGUIDLow())).event1;
if (event >= BG_AB_NODES_MAX) // not a node
{ return; }
BG_AB_Nodes node = BG_AB_Nodes(event);
PvpTeamIndex teamIndex = GetTeamIndexByTeamId(source->GetTeam());
// Check if player really could use this banner, not cheated
if (!(m_Nodes[node] == 0 || teamIndex == m_Nodes[node] % 2))
{ return; }
source->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
uint32 sound = 0;
// TODO in the following code we should restructure a bit to avoid
// duplication (or maybe write functions?)
// If node is neutral, change to contested
if (m_Nodes[node] == BG_AB_NODE_TYPE_NEUTRAL)
{
UpdatePlayerScore(source, SCORE_BASES_ASSAULTED, 1);
m_prevNodes[node] = m_Nodes[node];
m_Nodes[node] = teamIndex + 1;
// create new contested banner
_CreateBanner(node, BG_AB_NODE_TYPE_CONTESTED, teamIndex, true);
_SendNodeUpdate(node);
m_NodeTimers[node] = BG_AB_FLAG_CAPTURING_TIME;
if (teamIndex == 0)
{ SendMessage2ToAll(LANG_BG_AB_NODE_CLAIMED, CHAT_MSG_BG_SYSTEM_ALLIANCE, source, _GetNodeNameId(node), LANG_BG_ALLY); }
else
{ SendMessage2ToAll(LANG_BG_AB_NODE_CLAIMED, CHAT_MSG_BG_SYSTEM_HORDE, source, _GetNodeNameId(node), LANG_BG_HORDE); }
sound = BG_AB_SOUND_NODE_CLAIMED;
}
// If node is contested
else if ((m_Nodes[node] == BG_AB_NODE_STATUS_ALLY_CONTESTED) || (m_Nodes[node] == BG_AB_NODE_STATUS_HORDE_CONTESTED))
{
// If last state is NOT occupied, change node to enemy-contested
if (m_prevNodes[node] < BG_AB_NODE_TYPE_OCCUPIED)
{
UpdatePlayerScore(source, SCORE_BASES_ASSAULTED, 1);
m_prevNodes[node] = m_Nodes[node];
m_Nodes[node] = teamIndex + BG_AB_NODE_TYPE_CONTESTED;
// create new contested banner
_CreateBanner(node, BG_AB_NODE_TYPE_CONTESTED, teamIndex, true);
_SendNodeUpdate(node);
m_NodeTimers[node] = BG_AB_FLAG_CAPTURING_TIME;
if (teamIndex == TEAM_INDEX_ALLIANCE)
{ SendMessage2ToAll(LANG_BG_AB_NODE_ASSAULTED, CHAT_MSG_BG_SYSTEM_ALLIANCE, source, _GetNodeNameId(node)); }
else
{ SendMessage2ToAll(LANG_BG_AB_NODE_ASSAULTED, CHAT_MSG_BG_SYSTEM_HORDE, source, _GetNodeNameId(node)); }
}
// If contested, change back to occupied
else
{
UpdatePlayerScore(source, SCORE_BASES_DEFENDED, 1);
m_prevNodes[node] = m_Nodes[node];
m_Nodes[node] = teamIndex + BG_AB_NODE_TYPE_OCCUPIED;
// create new occupied banner
_CreateBanner(node, BG_AB_NODE_TYPE_OCCUPIED, teamIndex, true);
_SendNodeUpdate(node);
m_NodeTimers[node] = 0;
_NodeOccupied(node, (teamIndex == TEAM_INDEX_ALLIANCE) ? ALLIANCE : HORDE);
if (teamIndex == TEAM_INDEX_ALLIANCE)
{ SendMessage2ToAll(LANG_BG_AB_NODE_DEFENDED, CHAT_MSG_BG_SYSTEM_ALLIANCE, source, _GetNodeNameId(node)); }
else
{ SendMessage2ToAll(LANG_BG_AB_NODE_DEFENDED, CHAT_MSG_BG_SYSTEM_HORDE, source, _GetNodeNameId(node)); }
}
sound = (teamIndex == TEAM_INDEX_ALLIANCE) ? BG_AB_SOUND_NODE_ASSAULTED_ALLIANCE : BG_AB_SOUND_NODE_ASSAULTED_HORDE;
}
// If node is occupied, change to enemy-contested
else
{
UpdatePlayerScore(source, SCORE_BASES_ASSAULTED, 1);
m_prevNodes[node] = m_Nodes[node];
m_Nodes[node] = teamIndex + BG_AB_NODE_TYPE_CONTESTED;
// create new contested banner
_CreateBanner(node, BG_AB_NODE_TYPE_CONTESTED, teamIndex, true);
_SendNodeUpdate(node);
m_NodeTimers[node] = BG_AB_FLAG_CAPTURING_TIME;
if (teamIndex == TEAM_INDEX_ALLIANCE)
{ SendMessage2ToAll(LANG_BG_AB_NODE_ASSAULTED, CHAT_MSG_BG_SYSTEM_ALLIANCE, source, _GetNodeNameId(node)); }
else
{ SendMessage2ToAll(LANG_BG_AB_NODE_ASSAULTED, CHAT_MSG_BG_SYSTEM_HORDE, source, _GetNodeNameId(node)); }
sound = (teamIndex == TEAM_INDEX_ALLIANCE) ? BG_AB_SOUND_NODE_ASSAULTED_ALLIANCE : BG_AB_SOUND_NODE_ASSAULTED_HORDE;
}
// If node is occupied again, send "X has taken the Y" msg.
if (m_Nodes[node] >= BG_AB_NODE_TYPE_OCCUPIED)
{
if (teamIndex == TEAM_INDEX_ALLIANCE)
{ SendMessage2ToAll(LANG_BG_AB_NODE_TAKEN, CHAT_MSG_BG_SYSTEM_ALLIANCE, NULL, LANG_BG_ALLY, _GetNodeNameId(node)); }
else
{ SendMessage2ToAll(LANG_BG_AB_NODE_TAKEN, CHAT_MSG_BG_SYSTEM_HORDE, NULL, LANG_BG_HORDE, _GetNodeNameId(node)); }
}
PlaySoundToAll(sound);
}
/// <summary>
/// Resets this instance.
/// </summary>
void BattleGroundAB::Reset()
{
// call parent's class reset
BattleGround::Reset();
for (uint8 i = 0; i < PVP_TEAM_COUNT; ++i)
{
m_TeamScores[i] = 0;
m_lastTick[i] = 0;
m_honorScoreTicks[i] = 0;
m_ReputationScoreTics[i] = 0;
m_TeamScores500Disadvantage[i] = false;
}
m_IsInformedNearVictory = false;
bool isBGWeekend = BattleGroundMgr::IsBGWeekend(GetTypeID());
m_honorTicks = isBGWeekend ? AB_WEEKEND_HONOR_INTERVAL : AB_NORMAL_HONOR_INTERVAL;
m_ReputationTics = isBGWeekend ? AB_WEEKEND_REPUTATION_INTERVAL : AB_NORMAL_REPUTATION_INTERVAL;
for (uint8 i = 0; i < BG_AB_NODES_MAX; ++i)
{
m_Nodes[i] = 0;
m_prevNodes[i] = 0;
m_NodeTimers[i] = 0;
m_BannerTimers[i].timer = 0;
// all nodes owned by neutral team at beginning
m_ActiveEvents[i] = BG_AB_NODE_TYPE_NEUTRAL;
}
}
/// <summary>
/// Ends the battle ground.
/// </summary>
/// <param name="winner">The winner.</param>
void BattleGroundAB::EndBattleGround(Team winner)
{
// win reward
if (winner == ALLIANCE)
RewardHonorToTeam(GetBonusHonorFromKill(1), ALLIANCE);
if (winner == HORDE)
RewardHonorToTeam(GetBonusHonorFromKill(1), HORDE);
// complete map_end rewards (even if no team wins)
RewardHonorToTeam(GetBonusHonorFromKill(1), HORDE);
RewardHonorToTeam(GetBonusHonorFromKill(1), ALLIANCE);
BattleGround::EndBattleGround(winner);
}
/// <summary>
/// Gets the closest grave yard.
/// </summary>
/// <param name="player">The player.</param>
/// <returns></returns>
WorldSafeLocsEntry const* BattleGroundAB::GetClosestGraveYard(Player* player)
{
PvpTeamIndex teamIndex = GetTeamIndexByTeamId(player->GetTeam());
// Is there any occupied node for this team?
std::vector<uint8> nodes;
for (uint8 i = 0; i < BG_AB_NODES_MAX; ++i)
if (m_Nodes[i] == teamIndex + 3)
{ nodes.push_back(i); }
WorldSafeLocsEntry const* good_entry = NULL;
// If so, select the closest node to place ghost on
if (!nodes.empty())
{
float plr_x = player->GetPositionX();
float plr_y = player->GetPositionY();
float mindist = 999999.0f;
for (uint8 i = 0; i < nodes.size(); ++i)
{
WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(BG_AB_GraveyardIds[nodes[i]]);
if (!entry)
{ continue; }
float dist = (entry->x - plr_x) * (entry->x - plr_x) + (entry->y - plr_y) * (entry->y - plr_y);
if (mindist > dist)
{
mindist = dist;
good_entry = entry;
}
}
nodes.clear();
}
// If not, place ghost on starting location
if (!good_entry)
{ good_entry = sWorldSafeLocsStore.LookupEntry(BG_AB_GraveyardIds[teamIndex + 5]); }
return good_entry;
}
/// <summary>
/// Updates the player score.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="type">The type.</param>
/// <param name="value">The value.</param>
void BattleGroundAB::UpdatePlayerScore(Player* source, uint32 type, uint32 value)
{
BattleGroundScoreMap::iterator itr = m_PlayerScores.find(source->GetObjectGuid());
if (itr == m_PlayerScores.end()) // player not found...
{ return; }
switch (type)
{
case SCORE_BASES_ASSAULTED:
((BattleGroundABScore*)itr->second)->BasesAssaulted += value;
break;
case SCORE_BASES_DEFENDED:
((BattleGroundABScore*)itr->second)->BasesDefended += value;
break;
default:
BattleGround::UpdatePlayerScore(source, type, value);
break;
}
}
bool BattleGroundAB::IsAllNodesControlledByTeam(Team team) const
{
for (uint8 i = 0; i < BG_AB_NODES_MAX; ++i)
if ((team == ALLIANCE && m_Nodes[i] != BG_AB_NODE_STATUS_ALLY_OCCUPIED) ||
(team == HORDE && m_Nodes[i] != BG_AB_NODE_STATUS_HORDE_OCCUPIED))
return false;
return true;
}
/// <summary>
/// Gets the premature finish winning team.
/// </summary>
Team BattleGroundAB::GetPrematureWinner()
{
int32 hordeScore = m_TeamScores[TEAM_INDEX_HORDE];
int32 allianceScore = m_TeamScores[TEAM_INDEX_ALLIANCE];
if (hordeScore > allianceScore)
{ return HORDE; }
if (allianceScore > hordeScore)
{ return ALLIANCE; }
// If the values are equal, fall back to number of players on each team
return BattleGround::GetPrematureWinner();
}
| 37.816294 | 136 | 0.630676 | [
"object",
"vector"
] |
86f155394de515dc9e8b8d63e053bf4e77cf7858 | 23,812 | cpp | C++ | src/mongo/db/commands/find_and_modify.cpp | Tokutek/tokumxse | 9d0d92b45dfd75ecacb08feeb477dd4f4a6d430d | [
"Apache-2.0"
] | 29 | 2015-01-13T02:34:23.000Z | 2022-01-30T16:57:10.000Z | src/mongo/db/commands/find_and_modify.cpp | Tokutek/tokumxse | 9d0d92b45dfd75ecacb08feeb477dd4f4a6d430d | [
"Apache-2.0"
] | null | null | null | src/mongo/db/commands/find_and_modify.cpp | Tokutek/tokumxse | 9d0d92b45dfd75ecacb08feeb477dd4f4a6d430d | [
"Apache-2.0"
] | 12 | 2015-01-24T08:40:28.000Z | 2017-10-04T17:23:39.000Z | /**
* Copyright (C) 2012-2014 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kCommand
#include "mongo/platform/basic.h"
#include "mongo/db/commands/find_and_modify.h"
#include <boost/scoped_ptr.hpp>
#include "mongo/db/commands.h"
#include "mongo/db/concurrency/write_conflict_exception.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/dbhelpers.h"
#include "mongo/db/exec/update.h"
#include "mongo/db/exec/working_set_common.h"
#include "mongo/db/global_environment_experiment.h"
#include "mongo/db/op_observer.h"
#include "mongo/db/ops/delete.h"
#include "mongo/db/ops/update.h"
#include "mongo/db/ops/update_lifecycle_impl.h"
#include "mongo/db/projection.h"
#include "mongo/db/query/get_executor.h"
#include "mongo/db/repl/replication_coordinator_global.h"
#include "mongo/db/write_concern.h"
#include "mongo/util/log.h"
namespace mongo {
using boost::scoped_ptr;
using std::endl;
using std::string;
using std::stringstream;
/* Find and Modify an object returning either the old (default) or new value*/
class CmdFindAndModify : public Command {
public:
virtual void help( stringstream &help ) const {
help <<
"{ findAndModify: \"collection\", query: {processed:false}, update: {$set: {processed:true}}, new: true}\n"
"{ findAndModify: \"collection\", query: {processed:false}, remove: true, sort: {priority:-1}}\n"
"Either update or remove is required, all other fields have default values.\n"
"Output is in the \"value\" field\n";
}
CmdFindAndModify() : Command("findAndModify", false, "findandmodify") { }
virtual bool slaveOk() const { return false; }
virtual bool isWriteCommandForConfigServer() const { return true; }
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
find_and_modify::addPrivilegesRequiredForFindAndModify(this, dbname, cmdObj, out);
}
virtual bool run(OperationContext* txn,
const string& dbname,
BSONObj& cmdObj,
int options,
string& errmsg,
BSONObjBuilder& result,
bool fromRepl) {
const std::string ns = parseNsCollectionRequired(dbname, cmdObj);
const BSONObj query = cmdObj.getObjectField("query");
const BSONObj fields = cmdObj.getObjectField("fields");
const BSONObj update = cmdObj.getObjectField("update");
const BSONObj sort = cmdObj.getObjectField("sort");
bool upsert = cmdObj["upsert"].trueValue();
bool returnNew = cmdObj["new"].trueValue();
bool remove = cmdObj["remove"].trueValue();
if ( remove ) {
if ( upsert ) {
errmsg = "remove and upsert can't co-exist";
return false;
}
if ( !update.isEmpty() ) {
errmsg = "remove and update can't co-exist";
return false;
}
if ( returnNew ) {
errmsg = "remove and returnNew can't co-exist";
return false;
}
}
else if ( !cmdObj.hasField("update") ) {
errmsg = "need remove or update";
return false;
}
StatusWith<WriteConcernOptions> wcResult = extractWriteConcern(cmdObj);
if (!wcResult.isOK()) {
return appendCommandStatus(result, wcResult.getStatus());
}
txn->setWriteConcern(wcResult.getValue());
setupSynchronousCommit(txn);
bool ok = false;
MONGO_WRITE_CONFLICT_RETRY_LOOP_BEGIN {
errmsg = "";
// We can always retry because we only ever modify one document
ok = runImpl(txn,
dbname,
ns,
query,
fields,
update,
sort,
upsert,
returnNew,
remove,
result,
errmsg);
} MONGO_WRITE_CONFLICT_RETRY_LOOP_END(txn, "findAndModify", ns);
if ( !ok && errmsg == "no-collection" ) {
// Take X lock so we can create collection, then re-run operation.
ScopedTransaction transaction(txn, MODE_IX);
Lock::DBLock lk(txn->lockState(), dbname, MODE_X);
OldClientContext ctx(txn, ns, false /* don't check version */);
if (!fromRepl &&
!repl::getGlobalReplicationCoordinator()->canAcceptWritesForDatabase(dbname)) {
return appendCommandStatus(result, Status(ErrorCodes::NotMaster, str::stream()
<< "Not primary while creating collection " << ns
<< " during findAndModify"));
}
Database* db = ctx.db();
if ( db->getCollection( ns ) ) {
// someone else beat us to it, that's ok
// we might race while we unlock if someone drops
// but that's ok, we'll just do nothing and error out
}
else {
MONGO_WRITE_CONFLICT_RETRY_LOOP_BEGIN {
WriteUnitOfWork wuow(txn);
uassertStatusOK( userCreateNS( txn, db,
ns, BSONObj(),
!fromRepl ) );
wuow.commit();
} MONGO_WRITE_CONFLICT_RETRY_LOOP_END(txn, "findAndModify", ns);
}
errmsg = "";
ok = runImpl(txn,
dbname,
ns,
query,
fields,
update,
sort,
upsert,
returnNew,
remove,
result,
errmsg);
}
WriteConcernResult res;
Status waitStatus = waitForWriteConcern(txn, txn->getClient()->getLastOp(), &res);
appendCommandWCStatus(result, waitStatus);
return ok;
}
static void _appendHelper(BSONObjBuilder& result,
const BSONObj& doc,
bool found,
const BSONObj& fields,
const MatchExpressionParser::WhereCallback& whereCallback) {
if ( ! found ) {
result.appendNull( "value" );
return;
}
if ( fields.isEmpty() ) {
result.append( "value" , doc );
return;
}
Projection p;
p.init(fields, whereCallback);
result.append( "value" , p.transform( doc ) );
}
static bool runImpl(OperationContext* txn,
const string& dbname,
const string& ns,
const BSONObj& query,
const BSONObj& fields,
const BSONObj& update,
const BSONObj& sort,
bool upsert,
bool returnNew,
bool remove ,
BSONObjBuilder& result,
string& errmsg) {
AutoGetOrCreateDb autoDb(txn, dbname, MODE_IX);
Lock::CollectionLock collLock(txn->lockState(), ns, MODE_IX);
OldClientContext ctx(txn, ns, autoDb.getDb(), autoDb.justCreated());
if (!repl::getGlobalReplicationCoordinator()->canAcceptWritesForDatabase(dbname)) {
return appendCommandStatus(result, Status(ErrorCodes::NotMaster, str::stream()
<< "Not primary while running findAndModify in " << ns));
}
Collection* collection = ctx.db()->getCollection(ns);
const WhereCallbackReal whereCallback(txn, StringData(ns));
if ( !collection ) {
if ( !upsert ) {
// no collectio and no upsert, so can't possible do anything
_appendHelper( result, BSONObj(), false, fields, whereCallback );
return true;
}
// no collection, but upsert, so we want to create it
// problem is we only have IX on db and collection :(
// so we tell our caller who can do it
errmsg = "no-collection";
return false;
}
Snapshotted<BSONObj> snapshotDoc;
RecordId loc;
bool found = false;
{
CanonicalQuery* cq;
const BSONObj projection;
const long long skip = 0;
const long long limit = -1; // 1 document requested; negative indicates hard limit.
uassertStatusOK(CanonicalQuery::canonicalize(ns,
query,
sort,
projection,
skip,
limit,
&cq,
whereCallback));
PlanExecutor* rawExec;
uassertStatusOK(getExecutor(txn,
collection,
cq,
PlanExecutor::YIELD_AUTO,
&rawExec,
QueryPlannerParams::DEFAULT));
scoped_ptr<PlanExecutor> exec(rawExec);
PlanExecutor::ExecState state = exec->getNextSnapshotted(&snapshotDoc, &loc);
if (PlanExecutor::ADVANCED == state) {
found = true;
}
else if (PlanExecutor::FAILURE == state || PlanExecutor::DEAD == state) {
if (PlanExecutor::FAILURE == state &&
WorkingSetCommon::isValidStatusMemberObject(snapshotDoc.value())) {
const Status errorStatus =
WorkingSetCommon::getMemberObjectStatus(snapshotDoc.value());
invariant(!errorStatus.isOK());
uasserted(errorStatus.code(), errorStatus.reason());
}
uasserted(ErrorCodes::OperationFailed,
str::stream() << "executor returned " << PlanExecutor::statestr(state)
<< " while finding document to update");
}
else {
invariant(PlanExecutor::IS_EOF == state);
}
}
WriteUnitOfWork wuow(txn);
if (found) {
// We found a doc, but it might not be associated with the active snapshot.
// If the doc has changed or is no longer in the collection, we will throw a
// write conflict exception and start again from the beginning.
if (txn->recoveryUnit()->getSnapshotId() != snapshotDoc.snapshotId()) {
BSONObj oldObj = snapshotDoc.value();
if (!collection->findDoc(txn, loc, &snapshotDoc)) {
// Got deleted in the new snapshot.
throw WriteConflictException();
}
if (!oldObj.binaryEqual(snapshotDoc.value())) {
// Got updated in the new snapshot.
throw WriteConflictException();
}
}
// If we get here without throwing, then we should have the copy of the doc from
// the latest snapshot.
invariant(txn->recoveryUnit()->getSnapshotId() == snapshotDoc.snapshotId());
}
BSONObj doc = snapshotDoc.value();
BSONObj queryModified = query;
if (found && !doc["_id"].eoo() && !CanonicalQuery::isSimpleIdQuery(query)) {
// we're going to re-write the query to be more efficient
// we have to be a little careful because of positional operators
// maybe we can pass this all through eventually, but right now isn't an easy way
bool hasPositionalUpdate = false;
{
// if the update has a positional piece ($)
// then we need to pull all query parts in
// so here we check for $
// a little hacky
BSONObjIterator i( update );
while ( i.more() ) {
const BSONElement& elem = i.next();
if ( elem.fieldName()[0] != '$' || elem.type() != Object )
continue;
BSONObjIterator j( elem.Obj() );
while ( j.more() ) {
if ( str::contains( j.next().fieldName(), ".$" ) ) {
hasPositionalUpdate = true;
break;
}
}
}
}
BSONObjBuilder b(query.objsize() + 10);
b.append( doc["_id"] );
bool addedAtomic = false;
BSONObjIterator i(query);
while ( i.more() ) {
const BSONElement& elem = i.next();
if ( str::equals( "_id" , elem.fieldName() ) ) {
// we already do _id
continue;
}
if ( ! hasPositionalUpdate ) {
// if there is a dotted field, accept we may need more query parts
continue;
}
if ( ! addedAtomic ) {
b.appendBool( "$atomic" , true );
addedAtomic = true;
}
b.append( elem );
}
queryModified = b.obj();
}
if ( remove ) {
_appendHelper(result, doc, found, fields, whereCallback);
if ( found ) {
deleteObjects(txn, ctx.db(), ns, queryModified, PlanExecutor::YIELD_MANUAL,
true, true);
// Committing the WUOW can close the current snapshot. Until this happens, the
// snapshot id should not have changed.
invariant(txn->recoveryUnit()->getSnapshotId() == snapshotDoc.snapshotId());
// Must commit the write before doing anything that could throw.
wuow.commit();
BSONObjBuilder le( result.subobjStart( "lastErrorObject" ) );
le.appendNumber( "n" , 1 );
le.done();
}
}
else {
// update
if (!found) {
if (!upsert) {
// Didn't have it, and not upserting.
_appendHelper(result, doc, found, fields, whereCallback);
}
else {
// Do an insert.
BSONObj newDoc;
{
CanonicalQuery* rawCq;
uassertStatusOK(CanonicalQuery::canonicalize(ns, queryModified, &rawCq,
WhereCallbackNoop()));
boost::scoped_ptr<CanonicalQuery> cq(rawCq);
UpdateDriver::Options opts;
UpdateDriver driver(opts);
uassertStatusOK(driver.parse(update));
mutablebson::Document doc(newDoc,
mutablebson::Document::kInPlaceDisabled);
const bool ignoreVersion = false;
UpdateLifecycleImpl updateLifecycle(ignoreVersion, collection->ns());
UpdateStats stats;
const bool isInternalRequest = false;
uassertStatusOK(UpdateStage::applyUpdateOpsForInsert(cq.get(),
queryModified,
&driver,
&updateLifecycle,
&doc,
isInternalRequest,
&stats,
&newDoc));
}
const bool enforceQuota = true;
uassertStatusOK(collection->insertDocument(txn, newDoc, enforceQuota)
.getStatus());
// This is the last thing we do before the WriteUnitOfWork commits (except
// for some BSON manipulation).
getGlobalEnvironment()->getOpObserver()->onInsert(txn,
collection->ns().ns(),
newDoc);
// Must commit the write and logOp() before doing anything that could throw.
wuow.commit();
// The third argument indicates whether or not we have something for the
// 'value' field returned by a findAndModify command.
//
// Since we did an insert, we have a doc only if the user asked us to
// return the new copy. We return a value of 'null' if we inserted and
// the user asked for the old copy.
_appendHelper(result, newDoc, returnNew, fields, whereCallback);
BSONObjBuilder le(result.subobjStart("lastErrorObject"));
le.appendBool("updatedExisting", false);
le.appendNumber("n", 1);
le.appendAs(newDoc["_id"], kUpsertedFieldName);
le.done();
}
}
else {
// we found it or we're updating
if ( ! returnNew ) {
_appendHelper(result, doc, found, fields, whereCallback);
}
const NamespaceString requestNs(ns);
UpdateRequest request(requestNs);
request.setQuery(queryModified);
request.setUpdates(update);
request.setUpsert(upsert);
request.setUpdateOpLog();
request.setStoreResultDoc(returnNew);
request.setYieldPolicy(PlanExecutor::YIELD_MANUAL);
// TODO(greg) We need to send if we are ignoring
// the shard version below, but for now no
UpdateLifecycleImpl updateLifecycle(false, requestNs);
request.setLifecycle(&updateLifecycle);
UpdateResult res = mongo::update(txn,
ctx.db(),
request,
&txn->getCurOp()->debug());
invariant(collection);
invariant(res.existing);
LOG(3) << "update result: " << res;
// Committing the WUOW can close the current snapshot. Until this happens, the
// snapshot id should not have changed.
invariant(txn->recoveryUnit()->getSnapshotId() == snapshotDoc.snapshotId());
// Must commit the write before doing anything that could throw.
wuow.commit();
if (returnNew) {
dassert(!res.newObj.isEmpty());
_appendHelper(result, res.newObj, true, fields, whereCallback);
}
BSONObjBuilder le( result.subobjStart( "lastErrorObject" ) );
le.appendBool( "updatedExisting" , res.existing );
le.appendNumber( "n" , res.numMatched );
if ( !res.upserted.isEmpty() ) {
le.append( res.upserted[kUpsertedFieldName] );
}
le.done();
}
}
return true;
}
} cmdFindAndModify;
}
| 45.098485 | 124 | 0.456661 | [
"object",
"vector",
"transform"
] |
86f16339f7f522d01b9072b127b05e4858109af6 | 9,170 | cc | C++ | extensions/renderer/set_icon_natives.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | extensions/renderer/set_icon_natives.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | extensions/renderer/set_icon_natives.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // 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 "extensions/renderer/set_icon_natives.h"
#include <stddef.h>
#include <stdint.h>
#include <limits>
#include <memory>
#include "base/bind.h"
#include "base/strings/string_number_conversions.h"
#include "extensions/renderer/script_context.h"
#include "gin/data_object_builder.h"
#include "skia/public/mojom/bitmap.mojom.h"
#include "third_party/blink/public/web/web_array_buffer_converter.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "v8/include/v8-context.h"
#include "v8/include/v8-exception.h"
#include "v8/include/v8-function-callback.h"
#include "v8/include/v8-isolate.h"
#include "v8/include/v8-object.h"
#include "v8/include/v8-primitive.h"
// TODO(devlin): Looks like there are lots of opportunities to use gin helpers
// like gin::Dictionary and gin::DataObjectBuilder here.
namespace {
const char kInvalidDimensions[] = "ImageData has invalid dimensions.";
const char kInvalidData[] = "ImageData data length does not match dimensions.";
const char kNoMemory[] = "Chrome was unable to initialize icon.";
void ThrowException(v8::Isolate* isolate, const char* error_message) {
isolate->ThrowException(v8::Exception::Error(
v8::String::NewFromUtf8(isolate, error_message,
v8::NewStringType::kInternalized)
.ToLocalChecked()));
}
int GetIntPropertyFromV8Object(v8::Local<v8::Object> v8_object,
v8::Local<v8::Context> v8_context,
const char* property_name) {
v8::Local<v8::Value> v8_property_value;
if (!v8_object
->Get(v8_context, v8::String::NewFromUtf8(
v8_context->GetIsolate(), property_name,
v8::NewStringType::kInternalized)
.ToLocalChecked())
.ToLocal(&v8_property_value)) {
return 0;
}
return v8_property_value->Int32Value(v8_context).FromMaybe(0);
}
int GetIntPropertyFromV8Object(v8::Local<v8::Object> v8_object,
v8::Local<v8::Context> v8_context,
int index) {
v8::Local<v8::Value> v8_property_value;
if (!v8_object
->Get(v8_context, v8::Integer::New(v8_context->GetIsolate(), index))
.ToLocal(&v8_property_value)) {
return 0;
}
return v8_property_value->Int32Value(v8_context).FromMaybe(0);
}
} // namespace
namespace extensions {
SetIconNatives::SetIconNatives(ScriptContext* context)
: ObjectBackedNativeHandler(context) {}
void SetIconNatives::AddRoutes() {
RouteHandlerFunction("IsInServiceWorker",
base::BindRepeating(&SetIconNatives::IsInServiceWorker,
base::Unretained(this)));
RouteHandlerFunction("SetIconCommon",
base::BindRepeating(&SetIconNatives::SetIconCommon,
base::Unretained(this)));
}
bool SetIconNatives::ConvertImageDataToBitmapValue(
const v8::Local<v8::Object> image_data,
v8::Local<v8::Value>* image_data_bitmap) {
v8::Local<v8::Context> v8_context = context()->v8_context();
v8::Isolate* isolate = v8_context->GetIsolate();
v8::Local<v8::Value> value;
if (!image_data
->Get(v8_context,
v8::String::NewFromUtf8(isolate, "data",
v8::NewStringType::kInternalized)
.ToLocalChecked())
.ToLocal(&value)) {
ThrowException(isolate, kInvalidData);
return false;
}
v8::Local<v8::Object> data;
if (!value->ToObject(v8_context).ToLocal(&data)) {
ThrowException(isolate, kInvalidData);
return false;
}
int width = GetIntPropertyFromV8Object(image_data, v8_context, "width");
int height = GetIntPropertyFromV8Object(image_data, v8_context, "height");
if (width <= 0 || height <= 0) {
ThrowException(isolate, kInvalidDimensions);
return false;
}
// We need to be able to safely check |data_length| == 4 * width * height
// without overflowing below.
int max_width = (std::numeric_limits<int>::max() / 4) / height;
if (width > max_width) {
ThrowException(isolate, kInvalidDimensions);
return false;
}
int data_length = GetIntPropertyFromV8Object(data, v8_context, "length");
if (data_length != 4 * width * height) {
ThrowException(isolate, kInvalidData);
return false;
}
SkBitmap bitmap;
if (!bitmap.tryAllocN32Pixels(width, height)) {
ThrowException(isolate, kNoMemory);
return false;
}
bitmap.eraseARGB(0, 0, 0, 0);
uint32_t* pixels = bitmap.getAddr32(0, 0);
for (int t = 0; t < width * height; t++) {
// |data| is RGBA, pixels is ARGB.
pixels[t] = SkPreMultiplyColor(
((GetIntPropertyFromV8Object(data, v8_context, 4 * t + 3) & 0xFF)
<< 24) |
((GetIntPropertyFromV8Object(data, v8_context, 4 * t + 0) & 0xFF)
<< 16) |
((GetIntPropertyFromV8Object(data, v8_context, 4 * t + 1) & 0xFF)
<< 8) |
((GetIntPropertyFromV8Object(data, v8_context, 4 * t + 2) & 0xFF)
<< 0));
}
// Construct the Value object.
std::vector<uint8_t> s = skia::mojom::InlineBitmap::Serialize(&bitmap);
blink::WebArrayBuffer buffer = blink::WebArrayBuffer::Create(s.size(), 1);
memcpy(buffer.Data(), s.data(), s.size());
*image_data_bitmap = blink::WebArrayBufferConverter::ToV8Value(
&buffer, context()->v8_context()->Global(), isolate);
return true;
}
bool SetIconNatives::ConvertImageDataSetToBitmapValueSet(
v8::Local<v8::Object>& details,
v8::Local<v8::Object>* bitmap_set_value) {
v8::Local<v8::Context> v8_context = context()->v8_context();
v8::Isolate* isolate = v8_context->GetIsolate();
v8::Local<v8::Value> v8_value;
if (!details
->Get(v8_context,
v8::String::NewFromUtf8(isolate, "imageData",
v8::NewStringType::kInternalized)
.ToLocalChecked())
.ToLocal(&v8_value)) {
return false;
}
v8::Local<v8::Object> image_data_set;
if (!v8_value->ToObject(v8_context).ToLocal(&image_data_set)) {
return false;
}
DCHECK(bitmap_set_value);
v8::Local<v8::Array> property_names(
image_data_set->GetOwnPropertyNames(v8_context)
.FromMaybe(v8::Local<v8::Array>()));
for (size_t i = 0; i < property_names->Length(); ++i) {
v8::Local<v8::Value> key =
property_names->Get(v8_context, i).ToLocalChecked();
v8::String::Utf8Value utf8_key(isolate, key);
int size;
if (!base::StringToInt(std::string(*utf8_key), &size))
continue;
v8::Local<v8::Value> v8_image_value;
if (!image_data_set->Get(v8_context, key).ToLocal(&v8_image_value)) {
return false;
}
v8::Local<v8::Object> image_data;
if (!v8_image_value->ToObject(v8_context).ToLocal(&image_data)) {
return false;
}
v8::Local<v8::Value> image_data_bitmap;
if (!ConvertImageDataToBitmapValue(image_data, &image_data_bitmap))
return false;
(*bitmap_set_value)
->Set(v8_context, key, image_data_bitmap)
.FromMaybe(false);
}
return true;
}
void SetIconNatives::IsInServiceWorker(
const v8::FunctionCallbackInfo<v8::Value>& args) {
CHECK_EQ(0, args.Length());
const bool is_in_service_worker = context()->IsForServiceWorker();
args.GetReturnValue().Set(
v8::Boolean::New(args.GetIsolate(), is_in_service_worker));
}
void SetIconNatives::SetIconCommon(
const v8::FunctionCallbackInfo<v8::Value>& args) {
CHECK_EQ(1, args.Length());
CHECK(args[0]->IsObject());
v8::Local<v8::Context> v8_context = context()->v8_context();
v8::Isolate* isolate = args.GetIsolate();
v8::Local<v8::Object> details = args[0].As<v8::Object>();
v8::Local<v8::Object> bitmap_set_value(v8::Object::New(isolate));
auto set_null_prototype = [v8_context, isolate](v8::Local<v8::Object> obj) {
// Avoid any pesky Object.prototype manipulation.
bool succeeded =
obj->SetPrototype(v8_context, v8::Null(isolate)).ToChecked();
CHECK(succeeded);
};
set_null_prototype(bitmap_set_value);
if (!ConvertImageDataSetToBitmapValueSet(details, &bitmap_set_value))
return;
gin::DataObjectBuilder dict_builder(isolate);
dict_builder.Set("imageData", bitmap_set_value);
v8::Local<v8::String> tab_id_key =
v8::String::NewFromUtf8(isolate, "tabId",
v8::NewStringType::kInternalized)
.ToLocalChecked();
bool has_tab_id = false;
if (!details->HasOwnProperty(v8_context, tab_id_key).To(&has_tab_id))
return; // HasOwnProperty() threw - bail.
if (has_tab_id) {
v8::Local<v8::Value> tab_id;
if (!details->Get(v8_context, tab_id_key).ToLocal(&tab_id)) {
return; // Get() threw - bail.
}
dict_builder.Set("tabId", tab_id);
}
v8::Local<v8::Object> dict = dict_builder.Build();
set_null_prototype(dict);
args.GetReturnValue().Set(dict);
}
} // namespace extensions
| 35 | 79 | 0.651472 | [
"object",
"vector"
] |
86f2cee6510e7e89e01bb36fd2db0a72abff1f46 | 952 | hpp | C++ | hittable_list.hpp | nna774/rio | 1f9dd8b7357b6c323cb888eef32670e53a3b9d53 | [
"Apache-2.0"
] | null | null | null | hittable_list.hpp | nna774/rio | 1f9dd8b7357b6c323cb888eef32670e53a3b9d53 | [
"Apache-2.0"
] | null | null | null | hittable_list.hpp | nna774/rio | 1f9dd8b7357b6c323cb888eef32670e53a3b9d53 | [
"Apache-2.0"
] | null | null | null | #ifndef HITTABLE_LIST_H
#define HITTABLE_LIST_H
#include <memory>
#include <vector>
#include "hittable.hpp"
class HittableList : public Hittable {
public:
HittableList() {}
HittableList(std::shared_ptr<Hittable> object) { add(object); }
void clear() { objects.clear(); }
void add(std::shared_ptr<Hittable> object) { objects.push_back(object); }
virtual bool hit(const Ray& r, Float t_min, Float t_max,
HitRecord& rec) const override;
public:
std::vector<std::shared_ptr<Hittable>> objects;
};
bool HittableList::hit(const Ray& r, Float t_min, Float t_max,
HitRecord& rec) const {
HitRecord temp_rec;
bool hit_anything = false;
auto closest_so_far = t_max;
for (const auto& object : objects) {
if (object->hit(r, t_min, closest_so_far, temp_rec)) {
hit_anything = true;
closest_so_far = temp_rec.t;
rec = temp_rec;
}
}
return hit_anything;
}
#endif
| 22.666667 | 75 | 0.665966 | [
"object",
"vector"
] |
86f68dd91c5ab33adcecfae2e309b52e6196cd0c | 932 | hpp | C++ | src/Tetris/States/GameState.hpp | emersonmx/tetris-sfml | badb834cd59f30cd3dd75115f1e7a67865c1703e | [
"MIT"
] | null | null | null | src/Tetris/States/GameState.hpp | emersonmx/tetris-sfml | badb834cd59f30cd3dd75115f1e7a67865c1703e | [
"MIT"
] | 7 | 2016-06-23T00:50:17.000Z | 2016-07-05T01:55:12.000Z | src/Tetris/States/GameState.hpp | emersonmx/tetris-sfml | badb834cd59f30cd3dd75115f1e7a67865c1703e | [
"MIT"
] | null | null | null | #ifndef TETRIS_STATES_GAMESTATE_HPP_
#define TETRIS_STATES_GAMESTATE_HPP_
#include "Tetris/States/DefaultState.hpp"
namespace tetris {
namespace states {
class GameState : public DefaultState {
public:
using DefaultState::DefaultState;
GameState(App& app);
virtual ~GameState();
void create() override;
void destroy() override;
void restart();
protected:
void beginTick() override;
void processEvent(const sf::Event& event) override;
void update() override;
void render(sf::RenderTarget& renderTarget) override;
void endTick() override;
private:
void setupGameMenu();
void setupGameOver();
void setupScores();
void setupBlockRenderers();
struct Impl;
std::unique_ptr<Impl> impl_;
};
} /* namespace states */
} /* namespace tetris */
#endif /* TETRIS_STATES_GAMESTATE_HPP_ */
| 23.3 | 61 | 0.648069 | [
"render"
] |
86f96aad5d60ba6dfc72645efd2d3b94ac22aca7 | 18,266 | cxx | C++ | windows/core/ntgdi/kdexts2/region.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | windows/core/ntgdi/kdexts2/region.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | windows/core/ntgdi/kdexts2/region.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 2001 Microsoft Corporation
Module Name:
region.cxx
Abstract:
This file contains the routines to debug regions.
Author:
Jason Hartman (JasonHa) 2001-04-30
Environment:
User Mode
--*/
#include "precomp.hxx"
/******************************Public*Routine******************************\
* DECLARE_API( dr )
*
* Debugger extension to dump a region
*
* 21-Feb-1995 -by- Lingyun Wang [lingyunw]
* Wrote it.
\**************************************************************************/
DECLARE_API( dr )
{
OutputControl OutCtl(Client);
OutCtl.Output("Obsolete: Use 'region hrgn|prgn'.\n");
return S_OK;
}
/******************************Public*Routine******************************\
* DECLARE_API( cr )
*
* Debugger extension to check a region
*
* 21-Feb-1995 -by- Lingyun Wang [lingyunw]
* Wrote it.
\**************************************************************************/
DECLARE_API( cr )
{
OutputControl OutCtl(Client);
OutCtl.Output("Obsolete: Use 'region -c hrgn|prgn'\n");
return S_OK;
}
/******************************Public*Routine******************************\
* DECLARE_API( region )
*
* Debugger extension to dump and validate a region
*
* 22-May-2000 -by- Jason Hartman [jasonha]
* Converted from old dr & cr
*
\**************************************************************************/
DECLARE_API( region )
{
ULONG64 RgnAddr;
ULONG error;
ULONG Flags = 0;
#define REGION_CSCANS 0
#define REGION_SCAN_ADDRESS 1
#define REGION_SCAN_TAIL 2
#define REGION_SIZEOBJ 3
#define NUM_REGION_BASEOBJ_FIELDS 3
FIELD_INFO RegionFields[] = {
{ DbgStr("cScans"), DbgStr("cScans :"), 0, DBG_DUMP_FIELD_FULL_NAME, 0, NULL}, // REGION_CSCANS
{ DbgStr("scan"), DbgStr("scan <- pscnHead :"), 0, DBG_DUMP_FIELD_RETURN_ADDRESS | DBG_DUMP_FIELD_FULL_NAME, 0, AddressPrintCallback}, // REGION_SCAN_ADDRESS
{ DbgStr("pscnTail"), DbgStr("pscnTail :"), 0, DBG_DUMP_FIELD_FULL_NAME, 0, NULL}, // REGION_SCAN_TAIL
{ DbgStr("sizeObj"), DbgStr("sizeObj :"), 0, DBG_DUMP_FIELD_FULL_NAME, 0, NULL}, // REGION_SIZEOBJ
{ DbgStr("sizeRgn"), DbgStr("sizeRgn :"), 0, DBG_DUMP_FIELD_FULL_NAME, 0, NULL},
{ DbgStr("cRefs"), DbgStr("cRefs :"), 0, DBG_DUMP_FIELD_FULL_NAME, 0, NULL},
{ DbgStr("rcl"), DbgStr("rcl :"), 0, DBG_DUMP_FIELD_RETURN_ADDRESS | DBG_DUMP_FIELD_FULL_NAME, 0, RECTLCallback},
{ DbgStr("hHmgr"), DbgStr("hHmgr :"), 0, DBG_DUMP_FIELD_FULL_NAME, 0, NULL},
{ DbgStr("cExclusiveLock"), DbgStr("cExclusiveLock :"), 0, DBG_DUMP_FIELD_FULL_NAME, 0, NULL},
{ DbgStr("Tid"), DbgStr("Tid :"), 0, DBG_DUMP_FIELD_FULL_NAME, 0, NULL},
};
SYM_DUMP_PARAM RegionSym = {
sizeof (SYM_DUMP_PARAM), DbgStr(GDIType(REGION)), DBG_DUMP_COMPACT_OUT, 0/*RgnAddr*/,
NULL, &RegionSym, NewlineCallback, sizeof(RegionFields)/sizeof(RegionFields[0]), RegionFields
};
PrepareCallbacks(TRUE);
INIT_API();
PARSE_POINTER(region_help);
if (ntok > 1)
{
if (parse_iFindSwitch(tokens, ntok, 'c')!=-1)
{
Flags |= SCAN_DUMPER_NO_PRINT;
}
else if (parse_iFindSwitch(tokens, ntok, 'f')!=-1)
{
Flags |= SCAN_DUMPER_FORCE;
}
if (parse_iFindSwitch(tokens, ntok, 'r')!=-1)
{
Flags |= SCAN_DUMPER_FROM_TAIL;
}
}
// get pointer to object from handle or use param as pointer
if ((GetObjectAddress(Client,arg,&RgnAddr,RGN_TYPE,TRUE,TRUE) != S_OK) ||
(RgnAddr == 0))
{
ULONG64 ObjHandle;
ULONG64 RgnAddrFromHmgr;
RgnAddr = arg;
if (error = GetFieldValue(RgnAddr, GDIType(REGION), "hHmgr", ObjHandle))
{
ExtErr("Unable to get contents of REGION::hHmgr\n");
ExtErr(" (Ioctl returned %s)\n", pszWinDbgError(error));
ExtErr(" %#p is neither an HRGN nor valid REGION address\n", arg);
EXIT_API(S_OK);
}
if (!ObjHandle)
{
ExtOut("\tREGION is reserved for system use (no handle manger entry).\n");
RegionSym.nFields -= NUM_REGION_BASEOBJ_FIELDS;
}
else if (GetObjectAddress(Client,ObjHandle,&RgnAddrFromHmgr,
RGN_TYPE,TRUE,FALSE) == S_OK &&
RgnAddrFromHmgr != RgnAddr)
{
ExtOut("\tNote: REGION may not be valid.\n\t It does not have a valid handle manager entry.\n");
}
}
ExtOut("REGION @ %#p\n ", RgnAddr);
RegionSym.addr = RgnAddr;
error = Ioctl( IG_DUMP_SYMBOL_INFO, &RegionSym, RegionSym.size );
if (error)
{
ExtErr("Unable to get contents of REGION\n");
ExtErr(" (Ioctl returned %s)\n", pszWinDbgError(error));
}
else
{
ScanDumper Dumper(RegionFields[REGION_SCAN_ADDRESS].address,
RegionFields[REGION_SCAN_TAIL].address,
(ULONG)RegionFields[REGION_CSCANS].address,
RegionFields[REGION_SCAN_ADDRESS].address,
RgnAddr+RegionFields[REGION_SIZEOBJ].address,
Flags
);
BOOL Valid;
if ((Flags & SCAN_DUMPER_FROM_TAIL) != 0 && !Dumper.Reverse)
{
// We rquested a reverse dump, but Dumper wouldn't allow it.
EXIT_API(S_OK);
}
Valid = Dumper.DumpScans((ULONG)RegionFields[REGION_CSCANS].address);
if (Dumper.Reverse)
{
if (Dumper.ScanAddr != RegionFields[REGION_SCAN_ADDRESS].address)
{
ExtOut(" * Final ScanAddr (%#p) is not at head address (%#p)\n",
Dumper.ScanAddr, RegionFields[REGION_SCAN_ADDRESS].address);
Valid = FALSE;
}
}
else
{
if (Dumper.ScanAddr != RegionFields[REGION_SCAN_TAIL].address)
{
ExtOut(" * Final ScanAddr (%#p) is not at tail address (%#p)\n",
Dumper.ScanAddr, RegionFields[REGION_SCAN_TAIL].address);
Valid = FALSE;
}
}
if (Valid)
{
ExtOut(" Region is valid.\n");
}
else
{
ExtOut(" Region is NOT valid.\n");
}
}
EXIT_API(S_OK);
region_help:
ExtOut("Usage: region [-?cfr] hrgn|prgn\n");
ExtOut(" dumps/validates a region\n");
ExtOut(" c - doesn't print scans; validation only\n");
ExtOut(" f - continue printing even if an error is found\n");
ExtOut(" r - read scans in reverse order\n");
EXIT_API(S_OK);
}
/**************************************************************************\
*
\**************************************************************************/
BOOL bStrInStr(CHAR *pchTrg, CHAR *pchSrc)
{
BOOL bRes = 0;
int c = strlen(pchSrc);
//CHECKLOOP umm? This could be difficult to detect
while (TRUE)
{
// find the first character
pchTrg = strchr(pchTrg,*pchSrc);
// didn't find it?, fail!
if (pchTrg == NULL)
return(FALSE);
// did we find the string? succeed
if (strncmp(pchTrg,pchSrc,c) == 0)
return(TRUE);
// go get the next one.
pchTrg++;
}
}
/******************************Public*Routine******************************\
* rgnlog
*
\**************************************************************************/
#define MAXSEARCH 4
DECLARE_API( rgnlog )
{
#if 1
HRESULT hr = S_OK;
BOOL BadArg = FALSE;
ULONG RemainingArgIndex;
DEBUG_VALUE DumpCount = { 0, DEBUG_VALUE_INVALID };
CHAR EmptySearchString[] = "";
PSTR SearchStringList = EmptySearchString;
PSTR SearchString = SearchStringList;
OutputControl OutCtl(Client);
while (!BadArg && hr == S_OK)
{
while (isspace(*args)) args++;
if (*args == '-')
{
args++;
if (*args == '\0' || isspace(*args))
{
BadArg = TRUE;
}
else if (DumpCount.Type == DEBUG_VALUE_INVALID &&
args[0] == '1' && (args[1] == '\0' || isspace(args[1])))
{
DumpCount.I32 = -1;
DumpCount.Type = DEBUG_VALUE_INT32;
}
else
{
while (*args != '\0' && !isspace(*args))
{
switch (*args)
{
case '?':
default:
BadArg = TRUE;
break;
}
if (BadArg) break;
args++;
}
}
}
else
{
if (DumpCount.Type == DEBUG_VALUE_INVALID)
{
if (Evaluate(Client, args, DEBUG_VALUE_INT32, EVALUATE_DEFAULT_RADIX,
&DumpCount, &RemainingArgIndex, NULL, EVALUATE_COMPACT_EXPR) != S_OK ||
DumpCount.I32 == 0)
{
BadArg = TRUE;
}
else
{
args += RemainingArgIndex;
}
}
else
{
if (SearchStringList == EmptySearchString)
{
SearchStringList = (PSTR)HeapAlloc(GetProcessHeap(), 0,
sizeof(*SearchStringList)*(strlen(args)+2));
if (SearchStringList == NULL)
{
hr = E_OUTOFMEMORY;
}
else
{
SearchString = SearchStringList;
*SearchString = '\0';
}
}
if (hr == S_OK)
{
if (*args == '`' || *args == '\'' || *args == '\"')
{
CHAR StringEnd = *args;
if (args[1] == StringEnd || args[1] == '\0')
{
BadArg = TRUE;
}
else
{
while (*args != StringEnd && *args != '\0')
{
*SearchString++ = *args++;
}
if (*args == StringEnd) args++;
if (!isspace(*args) || *args != '\0')
{
OutCtl.Output("Malformed Search String at '%s'.\n",
args);
BadArg = TRUE;
}
else
{
*SearchString++ = '\0';
}
}
}
else
{
while (!isspace(*args) && *args != '\0')
{
*SearchString++ = *args++;
}
*SearchString++ = '\0';
}
}
}
}
}
if (hr == S_OK)
{
if (BadArg)
{
if (*args == '?') OutCtl.Output("rgnlog - dump/search rgnlog from checked builds.\n");
OutCtl.Output("Usage: rgnlog [-?] <Entries> [<Search Strings>]\n"
"\n"
" Entries - Number of tailing entries to dump/search\n"
" Search Strings - Dump only logs contain one of strings specified\n");
}
else
{
// Mark end of search string list with a NULL string.
*SearchString = '\0';
LONG iLog, iPass;
ULONG LogArraySize, LogLength, LogEntrySize;
CHAR SymName[80];
sprintf(SymName, "%s!iLog", GDIKM_Module.Name);
hr = ReadSymbolData(Client, SymName, &iLog, sizeof(iLog), NULL);
if (hr != S_OK) OutCtl.OutErr("Unable to get contents of %s\n", SymName);
if (hr == S_OK)
{
sprintf(SymName, "%s!iPass", GDIKM_Module.Name);
hr = ReadSymbolData(Client, SymName, &iPass, sizeof(iPass), NULL);
if (hr != S_OK) OutCtl.OutErr("Unable to get contents of %s\n", SymName);
}
if (hr == S_OK)
{
sprintf(SymName, "%s!argnlog", GDIKM_Module.Name);
hr = GetArrayDimensions(Client, SymName, NULL,
&LogArraySize, &LogLength, &LogEntrySize);
if (hr != S_OK) OutCtl.OutErr("Unable to get dimensions of %s\n", SymName);
}
if (hr == S_OK)
{
}
if (hr == S_OK)
{
if (*SearchStringList != '\0')
{
OutCtl.Output("Searching last %ld entries for:\n",
DumpCount.I32);
for (SearchString = SearchStringList;
*SearchString != '\0';
*SearchString += strlen(SearchString)+1)
{
OutCtl.Output(" \"%s\"\n", SearchString);
}
}
else
{
OutCtl.Output("Dumping last %ld entries.\n",
DumpCount.I32);
}
// To Do
}
}
}
if (SearchStringList != EmptySearchString)
{
HeapFree(GetProcessHeap(), 0, SearchStringList);
}
return hr;
#else
dprintf("Extension 'rgnlog' is not converted.\n");
#if ENABLE_OLD_EXTS // DOES NOT SUPPORT API64
LONG cDump;
LONG iCurrent;
RGNLOGENTRY rl;
RGNLOGENTRY *prl;
LONG gml; // gMaxRgnLog
int i, j;
PVOID pv;
CHAR achTmp[30];
CHAR achBuf[256];
PCHAR pchS[MAXSEARCH];
int cSearch;
BOOL bPrint;
PARSE_ARGUMENTS(rgnlog_help);
if(ntok<1) { goto rgnlog_help; }
tok_pos = parse_FindNonSwitch(tokens, ntok);
if(tok_pos==-1) { goto rgnlog_help; }
//check that this supports decimal
cDump = (LONG)GetExpression(tokens[tok_pos]);
if(cDump==0) { goto rgnlog_help; }
cSearch = 0;
while(cSearch<MAXSEARCH) {
tok_pos = parse_FindNonSwitch(tokens, ntok, tok_pos+1);
if(tok_pos==-1) {break;}
pchS[cSearch]=tokens[tok_pos];
cSearch++;
}
for (i = 0; i < cSearch; ++i)
dprintf("search[%s]\n",pchS[i]);
// get some stuff
GetAddress(pv, "&win32k!iLog");
dprintf("&iLog = %lx\n",pv);
if (pv == NULL)
{
dprintf("iCurrent was NULL\n");
return;
}
move(iCurrent, pv);
GetAddress(i,"&win32k!iPass");
if (pv == NULL)
{
dprintf("iPass was NULL\n");
return;
}
move(i,i);
dprintf("--------------------------------------------------\n");
dprintf("rgn log list, cDump = %ld, iCur = %ld, iPass = %ld\n", cDump,iCurrent,i);
dprintf("%5s-%4s:%8s,%8s,(%8s),%8s,%8s,%4s\n",
"TEB ","i","hrgn","prgn","return","arg1","arg2","arg3");
dprintf("--------------------------------------------------\n");
// Dereference the handle via the engine's handle manager.
GetAddress(prl, "win32k!argnlog");
if (!prl)
{
dprintf("prl was NULL\n");
return;
}
GetAddress(gml, "&win32k!gMaxRgnLog");
if (!gml)
{
dprintf("gml was NULL\n");
return;
}
move(gml,gml);
// set iCurrent to the first thing to dump
if (cDump > gml)
cDump = gml;
if (cDump > iCurrent)
iCurrent += gml;
iCurrent -= cDump;
dprintf("prl = %lx, gml = %ld, cDump = %ld, iCurrent = %ld\n",prl,gml,cDump,iCurrent);
//CHECKLOOP add exit/more support
for (i = 0; i < cDump; ++i)
{
move(rl,&prl[iCurrent]);
if (rl.pszOperation != NULL)
{
move2(achTmp,rl.pszOperation,30);
}
else
achTmp[0] = 0;
sprintf(achBuf,"%5lx-%4ld:%p,%p,(%8lx),%p, %p,%p, %s, %p, %p\n",
(ULONG_PTR)rl.teb >> 12,iCurrent,rl.hrgn,rl.prgn,rl.lRes,rl.lParm1,
rl.lParm2,rl.lParm3,achTmp,rl.pvCaller,rl.pvCallersCaller);
bPrint = (cSearch == 0);
for (j = 0; (j < cSearch) && !bPrint; ++j)
bPrint |= bStrInStr(achBuf,pchS[j]);
if (bPrint)
{
dprintf(achBuf);
}
if (++iCurrent >= gml)
iCurrent = 0;
if (CheckControlC())
return;
}
return;
rgnlog_help:
dprintf("\n rgnlog nnn [search1] [search2] [search3] [search4]\n");
dprintf("\t nnn - dumps the last n entries of the rgn log\n");
dprintf("\t search[n] - displays only entries containing one of n strings\n");
dprintf("\t NOTE: only works on checked builds. you must set bLogRgn at run time\n");
#endif // DOES NOT SUPPORT API64
EXIT_API(S_OK);
#endif
}
| 30.494157 | 179 | 0.440929 | [
"object"
] |
86fa7ab970f928c3fb6f05b9ef20c5f5e6354bcd | 2,188 | cpp | C++ | CesiumAsync/test/TestResponseCacheControl.cpp | zy6p/cesium-native | d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b | [
"Apache-2.0"
] | 1 | 2021-05-27T04:47:23.000Z | 2021-05-27T04:47:23.000Z | CesiumAsync/test/TestResponseCacheControl.cpp | zy6p/cesium-native | d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b | [
"Apache-2.0"
] | null | null | null | CesiumAsync/test/TestResponseCacheControl.cpp | zy6p/cesium-native | d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b | [
"Apache-2.0"
] | null | null | null | #include "ResponseCacheControl.h"
#include "catch2/catch.hpp"
using namespace CesiumAsync;
TEST_CASE("Test parsing cache-control header") {
SECTION("Header has no cache-control header") {
HttpHeaders responseHeader{
{"Response-Header-1", "Response-Value-1"},
{"Response-Header-2", "Response-Value-2"},
};
std::optional<ResponseCacheControl> cacheControl =
ResponseCacheControl::parseFromResponseHeaders(responseHeader);
REQUIRE(cacheControl == std::nullopt);
}
SECTION("Header has cache-control header") {
HttpHeaders responseHeader{
{"Cache-Control",
"Must-Revalidate, No-Cache, No-Store, No-Transform, Public, Private, "
"Proxy-Revalidate, Max-Age = 1000, S-Maxage = 10"},
};
std::optional<ResponseCacheControl> cacheControl =
ResponseCacheControl::parseFromResponseHeaders(responseHeader);
REQUIRE(cacheControl != std::nullopt);
REQUIRE(cacheControl->mustRevalidate());
REQUIRE(cacheControl->noCache());
REQUIRE(cacheControl->noStore());
REQUIRE(cacheControl->noTransform());
REQUIRE(cacheControl->accessControlPublic());
REQUIRE(cacheControl->accessControlPrivate());
REQUIRE(cacheControl->proxyRevalidate());
REQUIRE(cacheControl->maxAge() == 1000);
REQUIRE(cacheControl->sharedMaxAge() == 10);
}
SECTION("Header has cache-control header with only some directive") {
HttpHeaders responseHeader{
{"Cache-Control",
"Must-Revalidate, No-Cache, No-Store, Public, Private, Max-Age = "
"1000, S-Maxage = 10"},
};
std::optional<ResponseCacheControl> cacheControl =
ResponseCacheControl::parseFromResponseHeaders(responseHeader);
REQUIRE(cacheControl != std::nullopt);
REQUIRE(cacheControl->mustRevalidate());
REQUIRE(cacheControl->noCache());
REQUIRE(cacheControl->noStore());
REQUIRE(cacheControl->noTransform() == false);
REQUIRE(cacheControl->accessControlPublic());
REQUIRE(cacheControl->accessControlPrivate());
REQUIRE(cacheControl->proxyRevalidate() == false);
REQUIRE(cacheControl->maxAge() == 1000);
REQUIRE(cacheControl->sharedMaxAge() == 10);
}
}
| 37.084746 | 79 | 0.69287 | [
"transform"
] |
86fdbbfdbac42936da4c203f7d2652df3b95e727 | 1,984 | cc | C++ | runtime_probe/utils/edid.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 4 | 2020-07-24T06:54:16.000Z | 2021-06-16T17:13:53.000Z | runtime_probe/utils/edid.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2021-04-02T17:35:07.000Z | 2021-04-02T17:35:07.000Z | runtime_probe/utils/edid.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2020-11-04T22:31:45.000Z | 2020-11-04T22:31:45.000Z | // Copyright 2020 The Chromium OS 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 <algorithm>
#include <numeric>
#include <base/logging.h>
#include "runtime_probe/utils/edid.h"
namespace {
constexpr int kSize = sizeof(runtime_probe::EdidRaw);
constexpr int kVersion = 0x01;
constexpr uint8_t kMagic[] = "\x00\xff\xff\xff\xff\xff\xff\x00";
constexpr int kMagicLen = 8;
constexpr int kManufacturerIdBits = 5;
} // namespace
namespace runtime_probe {
std::unique_ptr<Edid> Edid::From(const std::vector<uint8_t>& blob) {
auto edid = std::make_unique<Edid>();
if (blob.size() < kSize) {
LOG(ERROR) << "Edid::From: length too small. (" << blob.size() << ")";
return nullptr;
}
EdidRaw edid_raw;
std::copy(blob.begin(), blob.begin() + kSize,
reinterpret_cast<uint8_t*>(&edid_raw));
if (!std::equal(kMagic, kMagic + kMagicLen, edid_raw.header)) {
LOG(ERROR) << "Edid::From: incorrect header.";
return nullptr;
}
if (edid_raw.version != kVersion) {
LOG(ERROR) << "Edid::From: unsupported EDID version.";
return nullptr;
}
if ((std::accumulate(blob.begin(), blob.begin() + kSize, 0) & 0xff) != 0) {
LOG(ERROR) << "Edid::From: checksum error.";
return nullptr;
}
if (!edid_raw.pixel_clock) {
LOG(ERROR) << "Edid::From: non-pixel clock format is not supported yet.";
return nullptr;
}
int vendor_code = (edid_raw.mfg_id[0] << 8) | edid_raw.mfg_id[1];
edid->product_id = (edid_raw.prod_code[1] << 8) | edid_raw.prod_code[0];
edid->width = ((edid_raw.hactive_hblank_hi >> 4) << 8) | edid_raw.hactive_lo;
edid->height = ((edid_raw.vactive_vblank_hi >> 4) << 8) | edid_raw.vactive_lo;
edid->vendor = "";
for (int i = 2; i >= 0; i--) {
char vendor_char = (vendor_code >> (i * kManufacturerIdBits)) & 0x1f;
edid->vendor += vendor_char + 'A' - 1;
}
return edid;
}
} // namespace runtime_probe
| 31 | 80 | 0.654738 | [
"vector"
] |
86fe3a904ffec1ccd779c4449c052dc360fe7d15 | 13,157 | cc | C++ | pmlc/conversion/pxa_to_affine/pxa_to_affine.cc | hfp/plaidml | c86852a910e68181781b3045f5a306d2f41a775f | [
"Apache-2.0"
] | null | null | null | pmlc/conversion/pxa_to_affine/pxa_to_affine.cc | hfp/plaidml | c86852a910e68181781b3045f5a306d2f41a775f | [
"Apache-2.0"
] | null | null | null | pmlc/conversion/pxa_to_affine/pxa_to_affine.cc | hfp/plaidml | c86852a910e68181781b3045f5a306d2f41a775f | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 Intel Corporation
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/IntegerSet.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Support/DebugStringHelper.h"
#include "mlir/Transforms/DialectConversion.h"
#include "pmlc/conversion/pxa_to_affine/pass_detail.h"
#include "pmlc/conversion/pxa_to_affine/passes.h"
#include "pmlc/dialect/pxa/ir/ops.h"
#include "pmlc/dialect/stdx/ir/ops.h"
#include "pmlc/util/logging.h"
#include "pmlc/util/tags.h"
#include "pmlc/util/util.h"
using namespace mlir; // NOLINT
namespace pmlc::conversion::pxa_to_affine {
namespace pxa = dialect::pxa;
namespace stdx = dialect::stdx;
namespace {
struct AffineParallelOpConversion
: public OpConversionPattern<AffineParallelOp> {
using OpConversionPattern<AffineParallelOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(AffineParallelOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final {
// Make a map for induction variable
llvm::SmallVector<Value, 8> ivs;
auto steps = op.getSteps();
// If it's tagged, leave as a parallel
if (hasTags(op)) {
// Make a new affine parallel with no return values
AffineParallelOp newOp;
if (op.getIVs().size() == 0) {
// If it's empty, add a dummy index (since some affine / scf things
// don't like 0 index affine.parallel
newOp = rewriter.create<AffineParallelOp>(
op.getLoc(), //
ArrayRef<Type>{}, ArrayRef<AtomicRMWKind>{}, //
AffineMap::getConstantMap(0, op.getContext()), ValueRange(), //
AffineMap::getConstantMap(1, op.getContext()), ValueRange(), //
ArrayRef<int64_t>{1});
} else {
// Normal case for parallels with IVs
newOp = rewriter.create<AffineParallelOp>(
op.getLoc(), //
ArrayRef<Type>{}, ArrayRef<AtomicRMWKind>{}, //
op.lowerBoundsMap(), op.getLowerBoundsOperands(), //
op.upperBoundsMap(), op.getUpperBoundsOperands(), //
steps);
for (Value iv : newOp.getIVs()) {
ivs.push_back(iv);
}
}
copyTags(newOp, op);
rewriter.setInsertionPointToStart(newOp.getBody());
} else {
// Otherwise unroll into serial loops
for (unsigned int i = 0; i < op.lowerBoundsMap().getNumResults(); i++) {
auto forOp = rewriter.create<AffineForOp>(
op.getLoc(), op.getLowerBoundsOperands(),
op.lowerBoundsMap().getSubMap({i}), op.getUpperBoundsOperands(),
op.upperBoundsMap().getSubMap({i}), steps[i]);
rewriter.setInsertionPointToStart(forOp.getBody());
ivs.push_back(forOp.getInductionVar());
}
}
// Move ParallelOp's operations across to the new op
auto &oldBodyOps = op.getBody()->getOperations();
auto &newBodyOps = rewriter.getInsertionBlock()->getOperations();
newBodyOps.splice(std::prev(newBodyOps.end()), oldBodyOps,
oldBodyOps.begin(), std::prev(oldBodyOps.end()));
// Replace all uses of old values
size_t idx = 0;
for (auto arg : op.getBody()->getArguments()) {
arg.replaceAllUsesWith(ivs[idx++]);
}
// Replace outputs with values from yield
auto termIt = std::prev(oldBodyOps.end());
for (size_t i = 0; i < op.getNumResults(); i++) {
op.getResult(i).replaceAllUsesWith(termIt->getOperand(i));
}
// We are done. Remove original op.
rewriter.eraseOp(op);
return success();
}
};
struct AffineIfOpConversion : public OpConversionPattern<AffineIfOp> {
using OpConversionPattern<AffineIfOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(AffineIfOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final {
// Make a new if value
auto newIf = rewriter.create<AffineIfOp>(op.getLoc(), op.getIntegerSet(),
op.getOperands(), op.hasElse());
// Move 'then' operations over, ignoring terminator
auto &newThenOps = newIf.getThenBlock()->getOperations();
auto &oldThenOps = op.getThenBlock()->getOperations();
newThenOps.splice(std::prev(newThenOps.end()), oldThenOps,
oldThenOps.begin(), std::prev(oldThenOps.end()));
// Replace outputs with values from yield (based on the then clause)
auto termIt = std::prev(oldThenOps.end());
for (size_t i = 0; i < op.getNumResults(); i++) {
op.getResult(i).replaceAllUsesWith(termIt->getOperand(i));
}
// Move 'else' operations over, ignoring terminator
auto &newElseOps = newIf.getElseBlock()->getOperations();
auto &oldElseOps = op.getElseBlock()->getOperations();
newElseOps.splice(std::prev(newElseOps.end()), oldElseOps,
oldElseOps.begin(), std::prev(oldElseOps.end()));
// Erase original
rewriter.eraseOp(op);
return success();
}
};
struct PxaLoadOpConversion : public OpConversionPattern<pxa::PxaLoadOp> {
using OpConversionPattern<pxa::PxaLoadOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(pxa::PxaLoadOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final {
rewriter.replaceOpWithNewOp<AffineLoadOp>(op, op.memref(),
op.getAffineMap(), op.indices());
return success();
}
};
struct PxaVectorLoadOpConversion
: public OpConversionPattern<pxa::PxaVectorLoadOp> {
using OpConversionPattern<pxa::PxaVectorLoadOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(pxa::PxaVectorLoadOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final {
rewriter.replaceOpWithNewOp<AffineVectorLoadOp>(
op, op.getVectorType(), op.memref(), op.getAffineMap(), op.indices());
return success();
}
};
static Value createReduction(ConversionPatternRewriter &rewriter, Location loc,
AtomicRMWKind agg, Value source, Value val) {
switch (agg) {
case AtomicRMWKind::assign:
return val;
case AtomicRMWKind::addf:
return rewriter.create<AddFOp>(loc, source, val);
case AtomicRMWKind::addi:
return rewriter.create<AddIOp>(loc, source, val);
case AtomicRMWKind::maxf: {
auto cmp = rewriter.create<CmpFOp>(loc, CmpFPredicate::OGT, val, source);
return rewriter.create<SelectOp>(loc, cmp, val, source);
}
case AtomicRMWKind::maxu: {
auto cmp = rewriter.create<CmpIOp>(loc, CmpIPredicate::ugt, val, source);
return rewriter.create<SelectOp>(loc, cmp, val, source);
}
case AtomicRMWKind::maxs: {
auto cmp = rewriter.create<CmpIOp>(loc, CmpIPredicate::sgt, val, source);
return rewriter.create<SelectOp>(loc, cmp, val, source);
}
case AtomicRMWKind::minf: {
auto cmp = rewriter.create<CmpFOp>(loc, CmpFPredicate::OLT, val, source);
return rewriter.create<SelectOp>(loc, cmp, val, source);
}
case AtomicRMWKind::minu: {
auto cmp = rewriter.create<CmpIOp>(loc, CmpIPredicate::ult, val, source);
return rewriter.create<SelectOp>(loc, cmp, val, source);
}
case AtomicRMWKind::mins: {
auto cmp = rewriter.create<CmpIOp>(loc, CmpIPredicate::slt, val, source);
return rewriter.create<SelectOp>(loc, cmp, val, source);
}
case AtomicRMWKind::mulf:
return rewriter.create<MulFOp>(loc, source, val);
case AtomicRMWKind::muli:
return rewriter.create<MulIOp>(loc, source, val);
default:
llvm_unreachable("Unsupported aggregation for "
"PxaReduceOpConversion::createReduction");
}
}
struct PxaReduceOpConversion : public OpConversionPattern<pxa::PxaReduceOp> {
using OpConversionPattern<pxa::PxaReduceOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(pxa::PxaReduceOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final {
auto source = rewriter.create<AffineLoadOp>(op.getLoc(), op.memref(),
op.map(), op.idxs());
auto reduce =
createReduction(rewriter, op.getLoc(), op.agg(), source, op.val());
rewriter.create<AffineStoreOp>(op.getLoc(), reduce, op.memref(), op.map(),
op.idxs());
op.replaceAllUsesWith(op.memref());
rewriter.eraseOp(op);
return success();
}
};
struct PxaVectorReduceOpConversion
: public OpConversionPattern<pxa::PxaVectorReduceOp> {
using OpConversionPattern<pxa::PxaVectorReduceOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(pxa::PxaVectorReduceOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final {
auto source = rewriter.create<AffineVectorLoadOp>(
op.getLoc(), op.getVectorType(), op.memref(), op.getAffineMap(),
op.idxs());
auto reduce =
createReduction(rewriter, op.getLoc(), op.agg(), source, op.vector());
rewriter.create<AffineVectorStoreOp>(op.getLoc(), reduce, op.memref(),
op.getAffineMap(), op.idxs());
op.replaceAllUsesWith(op.memref());
rewriter.eraseOp(op);
return success();
}
};
struct FuncOpConversion : public OpConversionPattern<FuncOp> {
using OpConversionPattern<FuncOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(FuncOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final {
FunctionType type = op.getType();
if (op.isExternal()) {
return success();
}
IVLOG(2, "FuncOpConversion::rewrite> " << debugString(type));
// Convert the function signature
TypeConverter::SignatureConversion result(type.getNumInputs());
for (unsigned i = 0; i < type.getNumInputs(); ++i) {
result.addInputs(i, {type.getInput(i)});
}
SmallVector<Type, 1> resultTypes;
for (unsigned i = 0; i < type.getNumResults(); ++i) {
if (type.getResult(i).isa<stdx::ArgpackType>()) {
resultTypes.push_back(type.getResult(i));
}
}
// Create a new function with an updated signature.
auto newOp = rewriter.cloneWithoutRegions(op);
rewriter.inlineRegionBefore(op.getBody(), newOp.getBody(), newOp.end());
newOp.setType(FunctionType::get(op.getContext(), result.getConvertedTypes(),
resultTypes));
// Tell the rewriter to convert the region signature.
rewriter.applySignatureConversion(&newOp.getBody(), result);
// Finally cause the old func op to be erased
rewriter.eraseOp(op);
return success();
}
};
struct ReturnOpConversion : public OpConversionPattern<ReturnOp> {
using OpConversionPattern<ReturnOp>::OpConversionPattern;
LogicalResult
matchAndRewrite(ReturnOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final {
IVLOG(2, "ReturnOpConversion::matchAndRewrite>");
SmallVector<Value, 1> results;
for (auto val : operands) {
if (val.getType().isa<stdx::ArgpackType>()) {
results.push_back(val);
}
}
rewriter.replaceOpWithNewOp<ReturnOp>(op, results);
return success();
}
};
struct LowerPXAToAffinePass
: public LowerPXAToAffineBase<LowerPXAToAffinePass> {
void runOnOperation() final {
auto &ctx = getContext();
PXAToAffineConversionTarget target(ctx);
OwningRewritePatternList patterns;
populatePXAToAffineConversionPatterns(patterns, &ctx);
if (failed(applyPartialConversion(getOperation(), target,
std::move(patterns)))) {
getOperation().dump();
emitError(UnknownLoc::get(&ctx), "Error lowering pxa -> affine\n");
signalPassFailure();
}
}
};
} // namespace
PXAToAffineConversionTarget::PXAToAffineConversionTarget(MLIRContext &ctx)
: ConversionTarget(ctx) {
addLegalDialect<AffineDialect>();
addLegalDialect<StandardOpsDialect>();
addIllegalDialect<pxa::PXADialect>();
addDynamicallyLegalOp<AffineParallelOp>([](AffineParallelOp op) {
return op.getNumResults() == 0 && hasTags(op);
});
addDynamicallyLegalOp<AffineIfOp>(
[](AffineIfOp op) { return op.getNumResults() == 0; });
addDynamicallyLegalOp<FuncOp>([](FuncOp op) {
return op.isExternal() || op.getType().getNumResults() == 0;
});
addDynamicallyLegalOp<ReturnOp>(
[](ReturnOp op) { return op.getNumOperands() == 0; });
}
void populatePXAToAffineConversionPatterns(OwningRewritePatternList &patterns,
MLIRContext *ctx) {
patterns.insert< //
AffineIfOpConversion, //
AffineParallelOpConversion, //
FuncOpConversion, //
PxaLoadOpConversion, //
PxaReduceOpConversion, //
PxaVectorLoadOpConversion, //
PxaVectorReduceOpConversion, //
ReturnOpConversion>(ctx);
}
std::unique_ptr<Pass> createLowerPXAToAffinePass() {
return std::make_unique<LowerPXAToAffinePass>();
}
} // namespace pmlc::conversion::pxa_to_affine
| 38.136232 | 80 | 0.657141 | [
"vector"
] |
810054a54bf51d1afd2a598003f5519dde7c63e9 | 10,493 | cpp | C++ | src/utils/image.cpp | jonesholger/lbann | 3214f189a1438565d695542e076c4fa8e7332d34 | [
"Apache-2.0"
] | 194 | 2016-07-19T15:40:21.000Z | 2022-03-19T08:06:10.000Z | src/utils/image.cpp | jonesholger/lbann | 3214f189a1438565d695542e076c4fa8e7332d34 | [
"Apache-2.0"
] | 1,021 | 2016-07-19T12:56:31.000Z | 2022-03-29T00:41:47.000Z | src/utils/image.cpp | jonesholger/lbann | 3214f189a1438565d695542e076c4fa8e7332d34 | [
"Apache-2.0"
] | 74 | 2016-07-28T18:24:00.000Z | 2022-01-24T19:41:04.000Z | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2016, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the LBANN Research Team (B. Van Essen, et al.) listed in
// the CONTRIBUTORS file. <lbann-dev@llnl.gov>
//
// LLNL-CODE-697807.
// All rights reserved.
//
// This file is part of LBANN: Livermore Big Artificial Neural Network
// Toolkit. For details, see http://software.llnl.gov/LBANN or
// https://github.com/LLNL/LBANN.
//
// Licensed under the Apache License, Version 2.0 (the "Licensee"); 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 <arpa/inet.h>
#include <opencv2/imgcodecs.hpp>
#include "lbann/utils/image.hpp"
#include "lbann/utils/exception.hpp"
#include "lbann/utils/opencv.hpp"
namespace lbann {
namespace {
// Read filename into buf.
void read_file_to_buf(const std::string& filename, El::Matrix<uint8_t>& buf,
size_t& size) {
FILE* f = fopen(filename.c_str(), "r");
if (f == nullptr) {
LBANN_ERROR("Could not open file " + filename);
}
// Determine the length.
if (fseeko(f, 0, SEEK_END) != 0) {
LBANN_ERROR("Could not seek to end of file " + filename);
}
off_t size_ = ftello(f);
if (size_ == -1) {
LBANN_ERROR("Could not get offset in file " + filename);
}
size = static_cast<size_t>(size_);
rewind(f);
// Allocate sufficient space and read.
buf.Resize(size, 1);
if (fread(buf.Buffer(), 1, size, f) != size) {
LBANN_ERROR("Could not real file " + filename);
}
fclose(f);
}
// There are other SOFs, but these are the common ones.
const bool is_jpg_sof[16] = {
true, true, true, true, false, true, true, true,
false, true, true, true, false, true, true, true};
// Attempt to guess the decoded size of an image.
// May not return the actual size (and may just return 0), so treat this as a
// hint.
void guess_image_size(const El::Matrix<uint8_t>& buf_, size_t size,
size_t& height, size_t& width, size_t& channels) {
height = 0;
width = 0;
channels = 0;
const uint8_t* buf = buf_.LockedBuffer();
if (size >= 2 && // Size
buf[0] == 0xFF && buf[1] == 0xD8) { // Signature
// JPEG image.
// See: https://en.wikipedia.org/wiki/JPEG#Syntax_and_structure
// and https://stackoverflow.com/questions/15800704/get-image-size-without-loading-image-into-memory
// and https://github.com/python-pillow/Pillow/blob/master/src/PIL/JpegImagePlugin.py
// JPEG is complicated, this will probably not work for every image.
// Try to find a start-of-frame marker, and then get the size.
for (size_t cur_pos = 2; cur_pos < size;) {
uint8_t b = buf[cur_pos];
if (b == 0xFF) {
if (cur_pos + 1 >= size) { return; } // Shouldn't happen.
uint8_t marker = buf[cur_pos + 1];
if (marker >= 0xC0 && marker <= 0xCF && is_jpg_sof[marker - 0xC0]) {
// Found the SOF.
// 2 for the marker, 2 for the frame header length, 1 for the precision.
cur_pos += 5;
if (cur_pos + 4 >= size) { return; } // Shouldn't happen.
uint16_t h_w[2];
memcpy(h_w, &buf[cur_pos], 4);
height = ntohs(h_w[0]);
width = ntohs(h_w[1]);
channels = 3; // Assume color.
return;
} else {
cur_pos += 2;
if (cur_pos + 2 >= size) { return; } // Shouldn't happen.
// Skip ahead by the length of this segment.
uint16_t l;
memcpy(&l, &buf[cur_pos], 2);
cur_pos += ntohs(l);
}
} else {
// Skip non-0xFFs.
cur_pos += 1;
}
}
} else if (size >= 24 && // Size
// Check signature
buf[0] == 0x89 && buf[1] == 0x50 &&
buf[2] == 0x4E && buf[3] == 0x47 &&
buf[4] == 0x0D && buf[5] == 0x0A &&
buf[6] == 0x1A && buf[7] == 0x0A &&
// Need IHDR chunk.
buf[12] == 'I' && buf[13] == 'H' &&
buf[14] == 'D' && buf[15] == 'R') {
// PNG image
// See: https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
uint32_t h_w[2];
memcpy(h_w, buf + 16, 8);
// Convert from network byte order and get size.
width = ntohl(h_w[0]);
height = ntohl(h_w[1]);
channels = 3; // Assume color.
}
// Give up.
}
// Decode an image from a buffer using OpenCV.
void opencv_decode(El::Matrix<uint8_t>& buf, El::Matrix<uint8_t>& dst,
std::vector<size_t>& dims, const std::string filename) {
const size_t encoded_size = buf.Height() * buf.Width();
std::vector<size_t> buf_dims = {1, encoded_size, 1};
cv::Mat cv_encoded = utils::get_opencv_mat(buf, buf_dims);
// Attempt to guess the decoded size.
// Warning: These may be wrong.
size_t height, width, channels;
guess_image_size(buf, encoded_size, height, width, channels);
if (height != 0) {
// We have a guess.
dst.Resize(height*width*channels, 1);
std::vector<size_t> guessed_dims = {channels, height, width};
// Decode the image.
cv::Mat cv_dst = utils::get_opencv_mat(dst, guessed_dims);
cv::Mat real_decoded = cv::imdecode(cv_encoded,
cv::IMREAD_ANYCOLOR | cv::IMREAD_ANYDEPTH,
&cv_dst);
// For now we only support 8-bit 1- or 3-channel images.
if (real_decoded.type() != CV_8UC1 && real_decoded.type() != CV_8UC3) {
LBANN_ERROR("Only support 8-bit 1- or 3-channel images, cannot load " + filename);
}
dims = {real_decoded.type() == CV_8UC1 ? 1ull : 3ull,
static_cast<size_t>(real_decoded.rows),
static_cast<size_t>(real_decoded.cols)};
// If we did not guess the size right, need to copy.
if (real_decoded.ptr() != dst.Buffer()) {
dst.Resize(utils::get_linearized_size(dims), 1);
cv_dst = utils::get_opencv_mat(dst, dims);
real_decoded.copyTo(cv_dst);
}
} else {
cv::Mat decoded = cv::imdecode(cv_encoded,
cv::IMREAD_ANYCOLOR | cv::IMREAD_ANYDEPTH);
if (decoded.type() != CV_8UC1 && decoded.type() != CV_8UC3) {
LBANN_ERROR("Only support 8-bit 1- or 3-channel images, cannot load " + filename);
}
dims = {decoded.type() == CV_8UC1 ? 1ull : 3ull,
static_cast<size_t>(decoded.rows),
static_cast<size_t>(decoded.cols)};
// Copy to dst.
dst.Resize(utils::get_linearized_size(dims), 1);
cv::Mat cv_dst = utils::get_opencv_mat(dst, dims);
decoded.copyTo(cv_dst);
}
}
} // anonymous namespace
void load_image(const std::string& filename, El::Matrix<uint8_t>& dst,
std::vector<size_t>& dims) {
// Load the encoded image.
El::Matrix<uint8_t> buf;
size_t encoded_size;
read_file_to_buf(filename, buf, encoded_size);
opencv_decode(buf, dst, dims, filename);
}
void decode_image(El::Matrix<uint8_t>& src, El::Matrix<uint8_t>& dst,
std::vector<size_t>& dims) {
opencv_decode(src, dst, dims, "encoded image");
}
void save_image(const std::string& filename, El::Matrix<uint8_t>& src,
const std::vector<size_t>& dims) {
cv::Mat cv_src = utils::get_opencv_mat(src, dims);
if (!cv::imwrite(filename, cv_src)) {
LBANN_ERROR("Could not save image to " + filename);
}
}
void save_image(const std::string& filename, const CPUMat& src,
const std::vector<size_t>& dims) {
if (dims.size() != 3 || (dims[0] != 1 && dims[0] != 3)) {
LBANN_ERROR("Unsupported dimensions for saving an image.");
}
El::Matrix<uint8_t> cv_mat = get_uint8_t_image(src, dims);
save_image(filename, cv_mat, dims);
}
std::string encode_image(const El::Matrix<uint8_t>& image,
const std::vector<size_t>& dims,
std::string const& img_format)
{
cv::Mat Mat_img = utils::get_opencv_mat(
const_cast<El::Matrix<uint8_t>&>(image), dims);
std::vector<uint8_t> encoded_img;
// Default IMWRITE_JPEG_QUALITY is 95. Can lower if files are too large
cv::imencode(img_format, Mat_img, encoded_img);
return std::string{encoded_img.begin(), encoded_img.end()};
}
El::Matrix<uint8_t> get_uint8_t_image(const CPUMat& image,
const std::vector<size_t>& dims) {
// Create the output matrix
size_t const size = utils::get_linearized_size(dims);
El::Matrix<uint8_t> output_mat(size, 1);
// Create views into the source and destination matrices
cv::Mat source(dims[1], dims[2], dims[0] == 1 ? CV_32FC1 : CV_32FC3,
const_cast<CPUMat&>(image).Buffer());
cv::Mat target(dims[1], dims[2], dims[0] == 1 ? CV_8UC1 : CV_8UC3,
output_mat.Buffer());
// Create the scaling parameters:
auto minmax_elements =
std::minmax_element(image.LockedBuffer(), image.LockedBuffer() + size);
DataType const& smallest = *(minmax_elements.first);
DataType const& largest = *(minmax_elements.second);
double scaling_factor =
(largest > smallest
? static_cast<double>(256 / (largest - smallest))
: 1.0);
double beta = -smallest * scaling_factor;
if (dims[0] == 1)
{
source.convertTo(target, target.type(), scaling_factor, beta);
}
else
{
auto* image_data = image.LockedBuffer();
size_t offset = dims[1]*dims[2]; // size of the image
for (size_t col = 0; col < dims[2]; ++col)
for (size_t row = 0; row < dims[1]; ++row)
{
size_t const idx = row + col*dims[1];
cv::Vec3b pixel;
pixel[0] = cv::saturate_cast<uchar>(scaling_factor*image_data[idx] + beta);
pixel[1] = cv::saturate_cast<uchar>(scaling_factor*image_data[idx+offset] + beta);
pixel[2] = cv::saturate_cast<uchar>(scaling_factor*image_data[idx+2*offset] + beta);
target.at<cv::Vec3b>(row, col) = pixel;
}
}
return output_mat;
}
} // namespace lbann
| 38.018116 | 104 | 0.60831 | [
"vector"
] |
8102c622ecb84d8adfe155a183b28c99cb673b7b | 6,515 | cpp | C++ | executor/operator/ref/ref_priorbox.cpp | huangwgang/Tengine | 1345e20cd76d3cd14dcce4f0ffb7d843d227622c | [
"Apache-2.0"
] | 2 | 2021-01-18T04:46:52.000Z | 2021-11-18T23:11:10.000Z | executor/operator/ref/ref_priorbox.cpp | huangwgang/Tengine | 1345e20cd76d3cd14dcce4f0ffb7d843d227622c | [
"Apache-2.0"
] | 1 | 2021-07-31T08:07:21.000Z | 2021-07-31T08:07:21.000Z | executor/operator/ref/ref_priorbox.cpp | huangwgang/Tengine | 1345e20cd76d3cd14dcce4f0ffb7d843d227622c | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2017, Open AI Lab
* Author: ruizhang@openailab.com
*/
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <math.h>
#include <cmath>
#include "logger.hpp"
#include "node_ops.hpp"
#include "tensor_mem.hpp"
#include "data_type.hpp"
#include "kernel_registry.hpp"
#include "tengine_errno.hpp"
#include "graph.hpp"
#include "operator/priorbox.hpp"
#include "kernel/priorbox/ref_priorbox_kernel.h"
namespace TEngine {
namespace RefPriorBoxOps {
struct RefPriorbox : public MTNodeOps
{
bool Prerun(Node* node) override;
bool Run(Node* node) override;
void InitRegistry(void);
priorbox_ref_param op_param;
ref_priorbox_kernel_t kernel_run;
KernelRegistry<ref_priorbox_kernel_t> kernel_registry;
RefPriorbox(void)
{
kernel_run = nullptr;
InitRegistry();
}
};
void RefPriorbox::InitRegistry(void)
{
#ifdef CONFIG_KERNEL_FP32
kernel_registry.Register(( ref_priorbox_kernel_t )ref_priorbox_fp32, TENGINE_LAYOUT_NCHW, TENGINE_DT_FP32);
kernel_registry.Register(( ref_priorbox_kernel_t )ref_priorbox_fp32, TENGINE_LAYOUT_NHWC, TENGINE_DT_FP32);
#endif
#ifdef CONFIG_KERNEL_FP16
kernel_registry.Register(( ref_priorbox_kernel_t )ref_priorbox_fp16, TENGINE_LAYOUT_NCHW, TENGINE_DT_FP16);
kernel_registry.Register(( ref_priorbox_kernel_t )ref_priorbox_fp16, TENGINE_LAYOUT_NHWC, TENGINE_DT_FP16);
#endif
#ifdef CONFIG_KERNEL_INT8
kernel_registry.Register(( ref_priorbox_kernel_t )ref_priorbox_int8, TENGINE_LAYOUT_NCHW, TENGINE_DT_INT8);
kernel_registry.Register(( ref_priorbox_kernel_t )ref_priorbox_int8, TENGINE_LAYOUT_NHWC, TENGINE_DT_INT8);
#endif
#ifdef CONFIG_KERNEL_UINT8
kernel_registry.Register(( ref_priorbox_kernel_t )ref_priorbox_uint8, TENGINE_LAYOUT_NCHW, TENGINE_DT_UINT8);
kernel_registry.Register(( ref_priorbox_kernel_t )ref_priorbox_uint8, TENGINE_LAYOUT_NHWC, TENGINE_DT_UINT8);
#endif
}
bool RefPriorbox::Prerun(Node* node)
{
int layout = exec_attr->graph_layout;
Tensor* input_tensor = node->GetInputTensor(0);
if(!kernel_registry.GetKernel(kernel_run, layout, input_tensor->GetDataType()))
{
set_tengine_errno(ENOENT);
return false;
}
return true;
}
bool RefPriorbox::Run(Node* node)
{
const Tensor* featmap_tensor = node->GetInputTensor(0);
const Tensor* data_tensor = node->GetInputTensor(1);
Tensor* output_tensor = node->GetOutputTensor(0);
PriorBox* priorbox_op = dynamic_cast<PriorBox*>(node->GetOp());
PriorBoxParam* param_ = priorbox_op->GetParam();
const TShape& data_shape = data_tensor->GetShape();
const int data_height = data_shape.GetH();
const int data_width = data_shape.GetW();
const TShape& featmap_shape = featmap_tensor->GetShape();
const int feat_height = featmap_shape.GetH();
const int feat_width = featmap_shape.GetW();
if(param_->img_h == 0 || param_->img_w == 0)
{
op_param.image_h = data_height;
op_param.image_w = data_width;
}
else
{
op_param.image_h = param_->img_h;
op_param.image_w = param_->img_w;
}
if(param_->step_h == 0 || param_->step_w == 0)
{
op_param.step_w = ( float )(op_param.image_w) / feat_width;
op_param.step_h = ( float )(op_param.image_h) / feat_height;
}
else
{
op_param.step_w = param_->step_w;
op_param.step_h = param_->step_h;
}
op_param.offset = param_->offset;
op_param.num_priors = param_->num_priors_;
op_param.out_dim = param_->out_dim_;
op_param.max_size_num = ( int )param_->max_size.size();
if(!param_->max_size.empty())
{
op_param.max_size = &(param_->max_size[0]);
}
op_param.min_size_num = ( int )param_->min_size.size();
op_param.aspect_ratio_size = ( int )param_->aspect_ratio.size();
if(!param_->aspect_ratio.empty())
{
op_param.aspect_ratio = &(param_->aspect_ratio[0]);
}
if(!param_->min_size.empty())
{
op_param.min_size = &(param_->min_size[0]);
}
if(!param_->variance.empty())
{
op_param.variance = &(param_->variance[0]);
}
op_param.clip = param_->clip;
op_param.flip = param_->flip;
op_param.image_size = param_->img_size;
op_param.feature_h = feat_height;
op_param.feature_w = feat_width;
if(TENGINE_DT_UINT8 == output_tensor->GetDataType())
{
auto* out_quant = output_tensor->GetQuantParam();
if(!out_quant->size())
{
op_param.out_scale = (*out_quant)[0].scale;
op_param.out_zero = (*out_quant)[0].zero_point;
}
}
void* output = ( void* )get_tensor_mem(output_tensor);
// int elem_size=DataType::GetTypeSize(output_tensor->GetDataType());
TShape& outShape = output_tensor->GetShape();
std::vector<int> outDims = outShape.GetDim();
int elem_size = outDims[0] * outDims[1] * outDims[2] * outDims[3];
int ret = kernel_run(output, &(this->op_param), elem_size);
if(ret < 0)
return false;
if(TENGINE_DT_INT8 == output_tensor->GetDataType())
{
auto* out_quant = output_tensor->GetQuantParam();
QuantParam q_param;
q_param.scale = op_param.out_scale;
q_param.zero_point = 0;
out_quant->resize(0);
out_quant->push_back(q_param);
}
return true;
}
NodeOps* SelectFunc(const CPUInfo* cpu_info, Node* node)
{
RefPriorbox* ops = new RefPriorbox();
return ops;
}
} // namespace RefPriorBoxOps
using namespace RefPriorBoxOps;
void RegisterRefPriorBox(void)
{
NodeOpsRegistryManager::RegisterOPImplementor(REF_REGISTRY_NAME, "PriorBox", RefPriorBoxOps::SelectFunc, 2000);
}
} // namespace TEngine
| 32.093596 | 115 | 0.700844 | [
"vector"
] |
8104a812ddaf1488d325432674f6f831b56dd824 | 18,023 | cpp | C++ | backends/analysis/DataDependencies.cpp | dragosdmtrsc/bf4 | 2e15e50acc4314737d99093b3d900fa44d795958 | [
"Apache-2.0"
] | 10 | 2020-08-05T12:52:37.000Z | 2021-05-20T02:15:04.000Z | backends/analysis/DataDependencies.cpp | shellqiqi/bf4 | 6c99c8f5b0dc61cf2cb7602c9f13ada7b651703f | [
"Apache-2.0"
] | 4 | 2020-09-28T12:17:50.000Z | 2021-11-23T12:23:38.000Z | backends/analysis/DataDependencies.cpp | shellqiqi/bf4 | 6c99c8f5b0dc61cf2cb7602c9f13ada7b651703f | [
"Apache-2.0"
] | 2 | 2020-10-13T07:59:42.000Z | 2021-12-08T21:35:05.000Z | //
// Created by dragos on 30.05.2019.
//
#include "DataDependencies.h"
void analysis::HasUses::add(const ProgramPoints *points) {
for (auto e : *points) {
auto last = e.last();
if (last != nullptr) {
LOG3("Found use for " << dbp(last) << " "
<< (last->is<IR::Statement>() ? last : nullptr));
auto it = used.find(last);
if (it == used.end())
used.emplace(last, 1);
else
used.emplace(last, it->second + 1);
}
}
}
void analysis::HasUses::remove(const ProgramPoint point) {
auto last = point.last();
auto it = used.find(last);
if (it->second == 1)
used.erase(it);
else
used.emplace(last, it->second - 1);
}
bool analysis::HasUses::hasUses(const IR::Node *node) const {
return used.find(node) != used.end();
}
void analysis::HasUses::add(const ProgramPoints *points,
const ProgramPoint readFrom) {
for (auto e : *points) {
auto last = e.last();
if (last != nullptr) {
LOG3("Found use for " << dbp(last) << " "
<< (last->is<IR::Statement>() ? last : nullptr)
<< " at " << readFrom.last());
usages[last].emplace(readFrom.last());
}
}
}
const LocationSet *
analysis::FindUninitialized::getReads(const IR::Expression *expression,
bool nonNull) const {
auto result = ::get(readLocations, expression);
if (nonNull)
BUG_CHECK(result != nullptr, "no locations known for %1%", dbp(expression));
return result;
}
void analysis::FindUninitialized::reads(const IR::Expression *expression,
const LocationSet *loc) {
LOG3(expression << " reads " << loc);
CHECK_NULL(expression);
CHECK_NULL(loc);
readLocations.emplace(expression, loc);
}
bool analysis::FindUninitialized::preorder(const IR::ParserState *state) {
LOG3("FU Visiting state " << state->name.name);
context = ProgramPoint(state);
currentPoint = ProgramPoint(state); // point before the first statement
visit(state->components, "components");
if (state->selectExpression != nullptr)
visit(state->selectExpression);
context = ProgramPoint();
return false;
}
Definitions *analysis::FindUninitialized::getCurrentDefinitions() const {
LOG3("FU Current point is (after) " << currentPoint);
auto defs = definitions->getDefinitions(currentPoint, true);
return defs;
}
void analysis::FindUninitialized::checkOutParameters(
const IR::IDeclaration *block, const IR::ParameterList *parameters,
Definitions *defs, bool checkReturn) {
for (auto p : parameters->parameters) {
if (p->direction == IR::Direction::Out ||
p->direction == IR::Direction::InOut) {
auto storage = definitions->storageMap->getStorage(p);
if (storage == nullptr)
continue;
const LocationSet *loc = new LocationSet(storage);
auto points = defs->getPoints(loc);
hasUses->add(points);
// Check uninitialized non-headers (headers can be invalid).
// inout parameters can never match here, so we could skip them.
loc = storage->removeHeaders();
points = defs->getPoints(loc);
if (points->containsBeforeStart())
DIAGNOSE_WARN("uninitialized_out_param",
"out parameter %1% may be uninitialized when "
"%2% terminates",
p, block->getName());
}
}
if (checkReturn) {
// check returned value
auto storage = definitions->storageMap->getRetVal();
if (storage != nullptr && defs->hasLocation(storage))
// If this definition is "live" it means that we have
// not returned on all paths; returns kill this definition.
::error("Function %1% does not return a value on all paths", block);
}
}
bool analysis::FindUninitialized::preorder(const IR::P4Control *control) {
LOG3("FU Visiting control " << control->name.name << "[" << control->id << "]");
// don't really understand this check
// BUG_CHECK(context.isBeforeStart(),
// "non-empty context in FindUnitialized::P4Control");
currentPoint = ProgramPoint(control);
for (auto d : control->controlLocals)
if (d->is<IR::Declaration_Instance>())
// visit virtual Function implementation if any
visit(d);
visit(control->body);
checkOutParameters(control, control->getApplyMethodType()->parameters,
getCurrentDefinitions());
return false;
}
bool analysis::FindUninitialized::preorder(const IR::Function *func) {
LOG3("FU Visiting function " << func->name.name << "[" << func->id << "]");
LOG5(func);
// FIXME -- this throws away the context of the current point, which seems
// wrong,
// FIXME -- but otherwise analysis fails
currentPoint = ProgramPoint(func);
visit(func->body);
bool checkReturn = !func->type->returnType->is<IR::Type_Void>();
checkOutParameters(func, func->type->parameters, getCurrentDefinitions(),
checkReturn);
return false;
}
bool analysis::FindUninitialized::preorder(const IR::P4Parser *parser) {
LOG3("FU Visiting parser " << parser->name.name << "[" << parser->id << "]");
visit(parser->states, "states");
auto accept =
ProgramPoint(parser->getDeclByName(IR::ParserState::accept)->getNode());
auto acceptdefs = definitions->getDefinitions(accept, true);
if (!acceptdefs->empty())
// acceptdefs is empty when the accept state is unreachable
checkOutParameters(parser, parser->getApplyMethodType()->parameters,
acceptdefs);
return false;
}
bool analysis::FindUninitialized::preorder(
const IR::AssignmentStatement *statement) {
LOG3("FU Visiting " << dbp(statement) << " " << statement);
auto assign = statement->to<IR::AssignmentStatement>();
lhs = true;
visit(assign->left);
lhs = false;
visit(assign->right);
return setCurrent(statement);
}
bool analysis::FindUninitialized::preorder(
const IR::ReturnStatement *statement) {
LOG3("FU Visiting " << statement);
if (statement->expression != nullptr)
visit(statement->expression);
return setCurrent(statement);
}
bool analysis::FindUninitialized::preorder(
const IR::MethodCallStatement *statement) {
LOG3("FU Visiting " << statement);
visit(statement->methodCall);
return setCurrent(statement);
}
bool analysis::FindUninitialized::preorder(
const IR::BlockStatement *statement) {
LOG3("FU Visiting " << statement);
visit(statement->components, "components");
return setCurrent(statement);
}
bool analysis::FindUninitialized::preorder(const IR::IfStatement *statement) {
LOG3("FU Visiting " << statement);
visit(statement->condition);
auto saveCurrent = currentPoint;
visit(statement->ifTrue);
if (statement->ifFalse != nullptr) {
currentPoint = saveCurrent;
visit(statement->ifFalse);
}
return setCurrent(statement);
}
bool analysis::FindUninitialized::preorder(
const IR::SwitchStatement *statement) {
LOG3("FU Visiting " << statement);
visit(statement->expression);
currentPoint =
ProgramPoint(context, statement->expression); // CTD -- added context
auto saveCurrent = currentPoint;
for (auto c : statement->cases) {
if (c->statement != nullptr) {
LOG3("Visiting " << c);
currentPoint = saveCurrent;
visit(c);
}
}
return setCurrent(statement);
}
bool analysis::FindUninitialized::preorder(const IR::Literal *expression) {
reads(expression, LocationSet::empty);
return false;
}
bool analysis::FindUninitialized::preorder(
const IR::TypeNameExpression *expression) {
reads(expression, LocationSet::empty);
return false;
}
bool analysis::FindUninitialized::isFinalRead(
const Visitor::Context *ctx, const IR::Expression *expression) {
if (ctx == nullptr)
return true;
// If this expression is a child of a Member of a left
// child of an ArrayIndex then we don't report it here, only
// in the parent.
auto parentexp = ctx->node->to<IR::Expression>();
if (parentexp != nullptr) {
if (parentexp->is<IR::Member>())
return false;
if (parentexp->is<IR::ArrayIndex>()) {
// Since we are doing the visit using a custom order,
// ctx->child_index is not accurate, so we check
// manually whether this is the left child.
auto ai = parentexp->to<IR::ArrayIndex>();
if (ai->left == expression)
return false;
}
}
return true;
}
void analysis::FindUninitialized::registerUses(const IR::Expression *expression,
bool reportUninitialized) {
if (!isFinalRead(getContext(), expression))
return;
const LocationSet *read = getReads(expression);
if (read == nullptr || read->isEmpty())
return;
auto currentDefinitions = getCurrentDefinitions();
auto points = currentDefinitions->getPoints(read);
if (reportUninitialized && !lhs && points->containsBeforeStart()) {
// Do not report uninitialized values on the LHS.
// This could happen if we are writing to an array element
// with an unknown index.
auto type = typeMap->getType(expression, true);
cstring message;
if (type->is<IR::Type_Base>())
message = "%1% may be uninitialized";
else
message = "%1% may not be completely initialized";
DIAGNOSE_WARN("uninitialized_use", message, expression);
}
hasUses->add(points, getExecuting());
}
bool analysis::FindUninitialized::preorder(
const IR::PathExpression *expression) {
LOG3("FU Visiting [" << expression->id << "]: " << expression);
if (lhs) {
reads(expression, LocationSet::empty);
return false;
}
auto decl = refMap->getDeclaration(expression->path, true);
auto storage = definitions->storageMap->getStorage(decl);
const LocationSet *result;
if (storage != nullptr)
result = new LocationSet(storage);
else
result = LocationSet::empty;
reads(expression, result);
registerUses(expression);
return false;
}
bool analysis::FindUninitialized::preorder(const IR::P4Action *action) {
LOG3("FU Visiting " << action);
currentPoint = ProgramPoint(context, action);
visit(action->body);
checkOutParameters(action, action->parameters, getCurrentDefinitions());
return false;
}
bool analysis::FindUninitialized::preorder(const IR::P4Table *table) {
LOG3("FU Visiting " << table->name.name);
auto savePoint = ProgramPoint(context, table);
currentPoint = savePoint;
auto key = table->getKey();
visit(key);
auto actions = table->getActionList();
for (auto ale : actions->actionList) {
BUG_CHECK(ale->expression->is<IR::MethodCallExpression>(),
"%1%: unexpected entry in action list", ale);
visit(ale->expression);
currentPoint = savePoint; // restore the current point
// it is modified by the inter-procedural analysis
}
return false;
}
bool analysis::FindUninitialized::preorder(
const IR::MethodCallExpression *expression) {
LOG3("FU Visiting [" << expression->id << "]: " << expression);
visit(expression->method);
auto mi = MethodInstance::resolve(expression, refMap, typeMap);
if (auto bim = mi->to<BuiltInMethod>()) {
auto base = getReads(bim->appliedTo, true);
cstring name = bim->name.name;
if (name == IR::Type_Stack::push_front ||
name == IR::Type_Stack::pop_front) {
// Reads all array fields
reads(expression, base);
registerUses(expression, false);
return false;
} else if (name == IR::Type_Header::isValid) {
auto storage = base->getField(StorageFactory::validFieldName);
reads(expression, storage);
registerUses(expression);
return false;
}
}
// Symbolically call some methods (actions and tables, extern methods)
std::vector<const IR::IDeclaration *> callee = callees(mi);
if (!callee.empty()) {
LOG3("Analyzing " << callee);
ProgramPoint pt(context, expression);
auto pfu = clone(pt);
for (auto c : callee)
(void)c->getNode()->apply(*pfu);
}
for (auto p : *mi->substitution.getParametersInArgumentOrder()) {
auto expr = mi->substitution.lookup(p);
if (p->direction == IR::Direction::Out) {
// out parameters are not read; they behave as if they are on
// the LHS of an assignment
bool save = lhs;
lhs = true;
visit(expr);
lhs = save;
} else {
visit(expr);
}
}
reads(expression, LocationSet::empty);
return false;
}
bool analysis::FindUninitialized::preorder(const IR::Member *expression) {
LOG3("FU Visiting [" << expression->id << "]: " << expression);
visit(expression->expr);
if (expression->expr->is<IR::TypeNameExpression>()) {
// this is a constant
reads(expression, LocationSet::empty);
return false;
}
if (TableApplySolver::isHit(expression, refMap, typeMap) ||
TableApplySolver::isActionRun(expression, refMap, typeMap))
return false;
auto type = typeMap->getType(expression, true);
if (type->is<IR::Type_Method>())
// dealt within the parent
return false;
auto storage = getReads(expression->expr, true);
auto basetype = typeMap->getType(expression->expr, true);
if (basetype->is<IR::Type_Stack>()) {
if (expression->member.name == IR::Type_Stack::next ||
expression->member.name == IR::Type_Stack::last) {
reads(expression, storage);
registerUses(expression, false);
if (!lhs && expression->member.name == IR::Type_Stack::next)
::warning(ErrorType::WARN_UNINITIALIZED,
"%1%: reading uninitialized value", expression);
return false;
} else if (expression->member.name == IR::Type_Stack::lastIndex) {
auto index = storage->getArrayLastIndex();
reads(expression, index);
registerUses(expression, false);
return false;
}
}
auto fields = storage->getField(expression->member);
reads(expression, fields);
registerUses(expression);
return false;
}
bool analysis::FindUninitialized::preorder(const IR::Slice *expression) {
LOG3("FU Visiting [" << expression->id << "]: " << expression);
bool save = lhs;
lhs = false; // slices on the LHS also read the data
visit(expression->e0);
auto storage = getReads(expression->e0, true);
reads(expression, storage); // true even in LHS
registerUses(expression);
lhs = save;
return false;
}
bool analysis::FindUninitialized::preorder(const IR::ArrayIndex *expression) {
LOG3("FU Visiting [" << expression->id << "]: " << expression);
if (expression->right->is<IR::Constant>()) {
if (lhs) {
reads(expression, LocationSet::empty);
} else {
auto cst = expression->right->to<IR::Constant>();
auto index = cst->asInt();
visit(expression->left);
auto storage = getReads(expression->left, true);
auto result = storage->getIndex(index);
reads(expression, result);
}
} else {
// We model a write with an unknown index as a read/write
// to the whole array.
auto save = lhs;
lhs = false;
visit(expression->right);
visit(expression->left);
auto storage = getReads(expression->left, true);
lhs = save;
reads(expression, storage);
}
registerUses(expression);
return false;
}
bool analysis::FindUninitialized::preorder(
const IR::Operation_Unary *expression) {
BUG_CHECK(!lhs, "%1%: Unary operation on LHS?", expression);
visit(expression->expr);
// This expression in fact reads the result of the operation,
// which is a temporary storage location, which we do not model
// in the def-use analysis.
reads(expression, LocationSet::empty);
registerUses(expression);
return false;
}
bool analysis::FindUninitialized::preorder(
const IR::Operation_Binary *expression) {
BUG_CHECK(!lhs, "%1%: Binary operation on LHS?", expression);
visit(expression->left);
visit(expression->right);
// This expression in fact reads the result of the operation,
// which is a temporary storage location, which we do not model
// in the def-use analysis.
reads(expression, LocationSet::empty);
registerUses(expression);
return false;
}
analysis::FindUninitialized::FindUninitialized(
analysis::FindUninitialized *parent, ProgramPoint context)
: context(context), refMap(parent->definitions->storageMap->refMap),
typeMap(parent->definitions->storageMap->typeMap),
definitions(parent->definitions), lhs(false), currentPoint(context),
hasUses(parent->hasUses) {
visitDagOnce = false;
}
analysis::FindUninitialized::FindUninitialized(AllDefinitions *definitions,
analysis::HasUses *hasUses)
: refMap(definitions->storageMap->refMap),
typeMap(definitions->storageMap->typeMap), definitions(definitions),
lhs(false), currentPoint(), hasUses(hasUses) {
CHECK_NULL(refMap);
CHECK_NULL(typeMap);
CHECK_NULL(definitions);
CHECK_NULL(hasUses);
visitDagOnce = false;
}
bool analysis::FindUninitialized::setCurrent(const IR::Statement *statement) {
currentPoint = ProgramPoint(context, statement);
return false;
}
ProgramPoint analysis::FindUninitialized::getExecuting() {
auto stat = findContext<IR::Statement>();
const IR::Node *theNode = stat;
if (auto ifs = stat->to<IR::IfStatement>()) {
theNode = ifs->condition;
} else if (auto ss = stat->to<IR::SwitchStatement>()) {
theNode = ss->expression;
}
return ProgramPoint(currentPoint, theNode);
}
std::vector<const IR::IDeclaration *>
analysis::FindUninitialized::callees(const P4::MethodInstance *mi) {
std::vector<const IR::IDeclaration *> callee;
if (auto ac = mi->to<ActionCall>()) {
callee.push_back(ac->action);
} else if (mi->isApply()) {
auto am = mi->to<ApplyMethod>();
if (am->isTableApply()) {
auto table = am->object->to<IR::P4Table>();
callee.push_back(table);
}
// skip control apply calls...
} else if (auto em = mi->to<ExternMethod>()) {
LOG4("##call to extern " << mi->expr);
callee = em->mayCall();
}
return callee;
}
| 33.625 | 82 | 0.659047 | [
"object",
"vector",
"model"
] |
81063302fdf79d752e419bc5599c515800a77b78 | 22,162 | cpp | C++ | DemoApps/Vulkan/Screenshot/source/Screenshot.cpp | alexvonduar/gtec-demo-framework | 6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | DemoApps/Vulkan/Screenshot/source/Screenshot.cpp | alexvonduar/gtec-demo-framework | 6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | DemoApps/Vulkan/Screenshot/source/Screenshot.cpp | alexvonduar/gtec-demo-framework | 6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | /****************************************************************************************************************************************************
* Copyright 2019 NXP
* 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 NXP. nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************************************************************************************/
#include "Screenshot.hpp"
#include <FslBase/Log/Log3Fmt.hpp>
#include <FslBase/UncheckedNumericCast.hpp>
#include <FslGraphics/PixelFormatUtil.hpp>
#include <FslSimpleUI/Base/Control/BackgroundNineSlice.hpp>
#include <FslSimpleUI/Base/Event/WindowSelectEvent.hpp>
#include <FslSimpleUI/Base/IWindowManager.hpp>
#include <FslSimpleUI/Base/Layout/StackLayout.hpp>
#include <FslSimpleUI/Base/Layout/FillLayout.hpp>
#include <FslSimpleUI/Base/WindowContext.hpp>
#include <FslSimpleUI/Theme/Basic/BasicThemeFactory.hpp>
#include <FslUtil/Vulkan1_0/Exceptions.hpp>
#include <FslUtil/Vulkan1_0/Util/VulkanConvert.hpp>
#include <FslUtil/Vulkan1_0/VUScopedMapMemory.hpp>
#include <RapidVulkan/Check.hpp>
#include <RapidVulkan/CommandBuffer.hpp>
#include <RapidVulkan/Debug/Strings/VkFormat.hpp>
#include <vulkan/vulkan.h>
#include <cassert>
#include <limits>
#include <utility>
namespace Fsl
{
namespace
{
// timeout in nanoseconds
constexpr uint64_t FENCE_TIMEOUT = 1000000000ull * 10;
VulkanBasic::DemoAppVulkanSetup CreateSetup()
{
VulkanBasic::DemoAppVulkanSetup setup;
// Needed for our screenshot method
setup.DesiredSwapchainImageUsageFlags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
return setup;
}
struct ImageRecord
{
RapidVulkan::Image TheImage;
RapidVulkan::Memory TheMemory;
VkDeviceSize AllocationSize{0};
VkExtent2D Extent{};
};
ImageRecord PrepareDstImage(const Vulkan::VUDevice& device, const VkExtent2D& imageExtent, const VkFormat imageFormat)
{
// Create the linear dst image
VkImageCreateInfo dstImageCreateInfo{};
dstImageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
dstImageCreateInfo.imageType = VK_IMAGE_TYPE_2D;
dstImageCreateInfo.format = imageFormat;
dstImageCreateInfo.extent = {imageExtent.width, imageExtent.height, 1};
dstImageCreateInfo.mipLevels = 1;
dstImageCreateInfo.arrayLayers = 1;
dstImageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
dstImageCreateInfo.tiling = VK_IMAGE_TILING_LINEAR;
dstImageCreateInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;
dstImageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
RapidVulkan::Image dstImage(device.Get(), dstImageCreateInfo);
// Get memory requirements
VkMemoryRequirements memRequirements{};
vkGetImageMemoryRequirements(device.Get(), dstImage.Get(), &memRequirements);
// Allocate memory
VkMemoryAllocateInfo dstImageMemoryAllocateInfo{};
dstImageMemoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
dstImageMemoryAllocateInfo.allocationSize = memRequirements.size;
dstImageMemoryAllocateInfo.memoryTypeIndex = device.GetPhysicalDevice().GetMemoryTypeIndex(
memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
RapidVulkan::Memory dstImageMemory(device.Get(), dstImageMemoryAllocateInfo);
// Bind the memory and image
RapidVulkan::CheckError(vkBindImageMemory(device.Get(), dstImage.Get(), dstImageMemory.Get(), 0), "vkBindImageMemory", __FILE__, __LINE__);
ImageRecord result;
result.TheImage = std::move(dstImage);
result.TheMemory = std::move(dstImageMemory);
result.AllocationSize = dstImageMemoryAllocateInfo.allocationSize;
result.Extent = imageExtent;
return result;
}
Bitmap ExtractToBitmap(const ImageRecord& image, const VkFormat imageFormat)
{
const auto pixelFormat = Vulkan::VulkanConvert::ToPixelFormat(imageFormat);
const VkDevice device = image.TheImage.GetDevice();
// Get information about the image layout
VkImageSubresource subResource{VK_IMAGE_ASPECT_COLOR_BIT, 0, 0};
VkSubresourceLayout subResourceLayout{};
vkGetImageSubresourceLayout(device, image.TheImage.Get(), &subResource, &subResourceLayout);
if (subResourceLayout.offset > image.AllocationSize)
{
throw NotSupportedException("invalid sub resource layout detected");
}
if (subResourceLayout.rowPitch > std::numeric_limits<uint32_t>::max())
{
throw NotSupportedException("rowPitch size is unsupported");
}
// Do the extraction
void* pImage = nullptr;
// We use the scoped map class here since it will since its exception safe
Vulkan::VUScopedMapMemory scopedMap(device, image.TheMemory.Get(), 0, VK_WHOLE_SIZE, 0, &pImage);
assert(pImage != nullptr);
assert(subResourceLayout.offset <= image.AllocationSize);
const uint8_t* pImageMemory = static_cast<const uint8_t*>(pImage) + subResourceLayout.offset;
const PxExtent2D extent(image.Extent.width, image.Extent.height);
// Calculate the content size adjusting for the offset
assert(subResourceLayout.rowPitch <= std::numeric_limits<uint32_t>::max());
const auto stride = UncheckedNumericCast<uint32_t>(subResourceLayout.rowPitch);
// Extract the bitmap data
return Bitmap(pImageMemory, subResourceLayout.size, extent, pixelFormat, stride, BitmapOrigin::UpperLeft);
}
void TransitionImagesToTransferLayout(const VkCommandBuffer commandBuffer, const VkImage dstImage, const VkImage srcImage)
{
constexpr VkImageSubresourceRange imageSubresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
{
VkImageMemoryBarrier imageMemoryBarrier{};
imageMemoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
imageMemoryBarrier.srcAccessMask = 0;
imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageMemoryBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
imageMemoryBarrier.image = dstImage;
imageMemoryBarrier.subresourceRange = imageSubresourceRange;
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1,
&imageMemoryBarrier);
}
// Transition source image to transfer source layout
{
VkImageMemoryBarrier imageMemoryBarrier{};
imageMemoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
imageMemoryBarrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT;
imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
imageMemoryBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
imageMemoryBarrier.image = srcImage;
imageMemoryBarrier.subresourceRange = imageSubresourceRange;
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1,
&imageMemoryBarrier);
}
}
void TransitionFromTransferLayout(const VkCommandBuffer commandBuffer, const VkImage dstImage, const VkImage srcImage)
{
constexpr VkImageSubresourceRange imageSubresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
// Transition source image back to source format
{
VkImageMemoryBarrier imageMemoryBarrier{};
imageMemoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
imageMemoryBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
imageMemoryBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
imageMemoryBarrier.image = srcImage;
imageMemoryBarrier.subresourceRange = imageSubresourceRange;
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1,
&imageMemoryBarrier);
}
// Transition destination image to a CPU readable layout
{
VkImageMemoryBarrier imageMemoryBarrier{};
imageMemoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
imageMemoryBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
imageMemoryBarrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
imageMemoryBarrier.image = dstImage;
imageMemoryBarrier.subresourceRange = imageSubresourceRange;
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1,
&imageMemoryBarrier);
}
}
}
Screenshot::Screenshot(const DemoAppConfig& config)
: VulkanBasic::DemoAppVulkanBasic(config, CreateSetup())
, m_graphicsService(config.DemoServiceProvider.Get<IGraphicsService>())
, m_nativeBatch(std::dynamic_pointer_cast<Vulkan::NativeBatch2D>(m_graphicsService->GetNativeBatch2D()))
, m_uiEventListener(this) // The UI listener forwards call to 'this' object
, m_uiExtension(
std::make_shared<UIDemoAppExtension>(config, m_uiEventListener.GetListener(), "UIAtlas/UIAtlas_160dpi")) // Prepare the extension
{
// Give the UI a chance to intercept the various DemoApp events.
RegisterExtension(m_uiExtension);
auto contentManager = GetContentManager();
{
Fsl::Bitmap bitmap;
contentManager->Read(bitmap, "Test.png", PixelFormat::R8G8B8A8_UNORM);
m_texture.Reset(m_graphicsService->GetNativeGraphics(), bitmap, Texture2DFilterHint::Nearest);
}
// Next up we prepare the actual UI
auto context = m_uiExtension->GetContext();
UI::Theme::BasicThemeFactory uiFactory(context, m_uiExtension->GetSpriteResourceManager(), m_uiExtension->GetDefaultMaterialId());
// Allocate the screenshot button
m_btnScreenshot = uiFactory.CreateTextButton(UI::Theme::ButtonType::Contained, "Screenshot");
m_btnScreenshot->SetAlignmentX(UI::ItemAlignment::Center);
// Create a label to write stuff into when a button is pressed
m_label = uiFactory.CreateLabel("");
m_label->SetAlignmentX(UI::ItemAlignment::Center);
m_label->SetAlignmentY(UI::ItemAlignment::Center);
// Create a horizontal stack layout and add the UI elements
auto uiStack = std::make_shared<UI::StackLayout>(context);
uiStack->SetLayoutOrientation(UI::LayoutOrientation::Vertical);
uiStack->SetAlignmentX(UI::ItemAlignment::Center);
uiStack->SetAlignmentY(UI::ItemAlignment::Far);
uiStack->AddChild(m_label);
uiStack->AddChild(m_btnScreenshot);
auto bottomBar = uiFactory.CreateBottomBar();
bottomBar->SetContent(uiStack);
// Finally add everything to the window manager (to ensure its seen)
auto windowManager = m_uiExtension->GetWindowManager();
windowManager->Add(bottomBar);
}
void Screenshot::OnSelect(const UI::RoutedEventArgs& /*args*/, const std::shared_ptr<UI::WindowSelectEvent>& theEvent)
{
if (theEvent->GetSource() == m_btnScreenshot)
{
m_screenshotRequested = true;
}
}
void Screenshot::Update(const DemoTime& /*demoTime*/)
{
}
void Screenshot::VulkanDraw(const DemoTime& /*demoTime*/, RapidVulkan::CommandBuffers& rCmdBuffers, const VulkanBasic::DrawContext& drawContext)
{
const uint32_t currentSwapBufferIndex = drawContext.CurrentSwapBufferIndex;
const VkCommandBuffer hCmdBuffer = rCmdBuffers[currentSwapBufferIndex];
rCmdBuffers.Begin(currentSwapBufferIndex, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, VK_NULL_HANDLE, 0, VK_NULL_HANDLE, VK_FALSE, 0, 0);
{
std::array<VkClearValue, 1> clearValues{};
clearValues[0].color = {{0.5f, 0.5f, 0.5f, 1.0f}};
VkRenderPassBeginInfo renderPassBeginInfo{};
renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassBeginInfo.renderPass = m_dependentResources.MainRenderPass.Get();
renderPassBeginInfo.framebuffer = drawContext.Framebuffer;
renderPassBeginInfo.renderArea.offset.x = 0;
renderPassBeginInfo.renderArea.offset.y = 0;
renderPassBeginInfo.renderArea.extent = drawContext.SwapchainImageExtent;
renderPassBeginInfo.clearValueCount = UncheckedNumericCast<uint32_t>(clearValues.size());
renderPassBeginInfo.pClearValues = clearValues.data();
rCmdBuffers.CmdBeginRenderPass(currentSwapBufferIndex, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
{
m_nativeBatch->Begin();
m_nativeBatch->Draw(m_texture, Vector2(), Color::White());
m_nativeBatch->End();
// Calling this last allows the UI to draw on top of everything.
m_uiExtension->Draw();
// Remember to call this as the last operation in your renderPass
AddSystemUI(hCmdBuffer, currentSwapBufferIndex);
}
rCmdBuffers.CmdEndRenderPass(currentSwapBufferIndex);
}
rCmdBuffers.End(currentSwapBufferIndex);
}
AppDrawResult Screenshot::TrySwapBuffers(const DemoTime& demoTime)
{
auto result = VulkanBasic::DemoAppVulkanBasic::TrySwapBuffers(demoTime);
if (result != AppDrawResult::Completed)
{
return result;
}
if (m_screenshotRequested)
{
m_screenshotRequested = false;
// Bitmap bitmap;
// m_graphicsService->Capture(bitmap, PixelFormat::R8G8B8A8_UINT);
auto bitmap = TryCaptureScreenshot();
if (bitmap.IsValid())
{
auto manager = GetPersistentDataManager();
manager->Write("screenshot.png", bitmap);
m_label->SetContent("Screenshot saved");
}
else
{
m_label->SetContent("Screenshot failed");
}
}
return AppDrawResult::Completed;
}
VkRenderPass Screenshot::OnBuildResources(const VulkanBasic::BuildResourcesContext& /*context*/)
{
// Since we only draw using the NativeBatch we just create the most basic render pass that is compatible
m_dependentResources.MainRenderPass = CreateBasicRenderPass();
return m_dependentResources.MainRenderPass.Get();
}
void Screenshot::OnFreeResources()
{
m_dependentResources = {};
}
Bitmap Screenshot::TryCaptureScreenshot()
{
// Check blit support for source and destination
// Check if the device supports blitting from optimal images (the swapchain images are in optimal format)
VulkanBasic::SwapchainInfo swapchainInfo;
if (!TryGetSwapchainInfo(swapchainInfo))
{
FSLLOG3_WARNING("Failed to get swapchain info, capture cancelled");
return Bitmap();
}
if (swapchainInfo.CurrentImage == VK_NULL_HANDLE)
{
FSLLOG3_WARNING("Invalid swapchain image, capture cancelled");
return Bitmap();
}
if ((swapchainInfo.ImageUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) == 0u)
{
FSLLOG3_INFO("Swapchain did not support VK_IMAGE_USAGE_TRANSFER_SRC_BIT, capture cancelled");
return Bitmap();
}
VkFormat srcImageFormat = swapchainInfo.ImageFormat;
if (srcImageFormat == VK_FORMAT_UNDEFINED)
{
FSLLOG3_WARNING("Invalid swapchain image format, capture cancelled");
return Bitmap();
}
auto srcPixelFormat = Vulkan::VulkanConvert::ToPixelFormat(srcImageFormat);
if (PixelFormatUtil::IsCompressed(srcPixelFormat))
{
FSLLOG3_WARNING("srcPixelFormat is compressed, capture cancelled");
return Bitmap();
}
VkFormat dstImageFormat = VK_FORMAT_R8G8B8A8_UNORM;
VkFormatProperties formatProperties{};
vkGetPhysicalDeviceFormatProperties(m_physicalDevice.Device, srcImageFormat, &formatProperties);
// Check if the device supports 'blit' from the source format
const bool allowSrcBlit = (formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT) != 0u;
// Check if the device supports 'blit' to the dst linear format
const bool allowDstBlit = (formatProperties.linearTilingFeatures & VK_FORMAT_FEATURE_BLIT_DST_BIT) != 0u;
FSLLOG3_VERBOSE_IF(!allowSrcBlit, "Device does not support blitting from src format: {}", RapidVulkan::Debug::ToString(srcImageFormat));
FSLLOG3_VERBOSE_IF(!allowDstBlit, "Device does not support blitting to dst format: {}", RapidVulkan::Debug::ToString(dstImageFormat));
// if (allowSrcBlit && allowDstBlit)
//{
// return TryCaptureScreenshotViaBlit(swapchainInfo, dstImageFormat);
//}
return TryCaptureScreenshotViaCopy(swapchainInfo);
}
Bitmap Screenshot::TryCaptureScreenshotViaBlit(const VulkanBasic::SwapchainInfo& /*swapchainInfo*/, const VkFormat /*dstImageFormat*/)
{
FSLLOG3_VERBOSE("Capturing via blit");
// We wait for the device to be idle before we start capturing
SafeWaitForDeviceIdle();
FSLLOG3_ERROR("CaptureScreenshotViaBlit not implemented");
return Bitmap();
}
// The swapchain image must have VK_IMAGE_USAGE_TRANSFER_SRC_BIT set for this to work
Bitmap Screenshot::TryCaptureScreenshotViaCopy(const VulkanBasic::SwapchainInfo& swapchainInfo)
{
FSLLOG3_VERBOSE("Capturing via copy");
assert(swapchainInfo.CurrentImage != VK_NULL_HANDLE);
assert((swapchainInfo.ImageUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) != 0u);
assert(swapchainInfo.ImageFormat != VK_FORMAT_UNDEFINED);
VkImage srcImage = swapchainInfo.CurrentImage;
// We use the same format as the source as the copy command dont convert it for us
VkFormat dstImageFormat = swapchainInfo.ImageFormat;
// We wait for the device to be idle before we start capturing
SafeWaitForDeviceIdle();
// Prepare the image that we will 'transfer' the screenshot to
auto dstImage = PrepareDstImage(m_device, swapchainInfo.ImageExtent, dstImageFormat);
VkCommandPoolCreateInfo commandPoolCreateInfo{};
commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
commandPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
commandPoolCreateInfo.queueFamilyIndex = m_deviceQueue.QueueFamilyIndex;
RapidVulkan::CommandPool commandPool(m_device.Get(), commandPoolCreateInfo);
VkCommandBufferAllocateInfo commandBufferAllocateInfo{};
commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
commandBufferAllocateInfo.commandPool = commandPool.Get();
commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
commandBufferAllocateInfo.commandBufferCount = 1;
RapidVulkan::CommandBuffer commandBuffer(m_device.Get(), commandBufferAllocateInfo);
VkCommandBufferBeginInfo commandBufferBeginInfo{};
commandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
commandBuffer.Begin(commandBufferBeginInfo);
{
TransitionImagesToTransferLayout(commandBuffer.Get(), dstImage.TheImage.Get(), srcImage);
// Copy the current content of the swapchain image to the dst buffer
{
VkImageCopy imageCopyRegion{};
imageCopyRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
imageCopyRegion.srcSubresource.layerCount = 1;
// imageCopyRegion.srcOffset;
imageCopyRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
imageCopyRegion.dstSubresource.layerCount = 1;
// imageCopyRegion.dstOffset;
imageCopyRegion.extent = {swapchainInfo.ImageExtent.width, swapchainInfo.ImageExtent.height, 1};
// Schedule copy
vkCmdCopyImage(commandBuffer.Get(), srcImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dstImage.TheImage.Get(),
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &imageCopyRegion);
}
TransitionFromTransferLayout(commandBuffer.Get(), dstImage.TheImage.Get(), srcImage);
}
commandBuffer.End();
RapidVulkan::Fence fence;
fence.Reset(m_device.Get(), 0);
// Submit to the queue
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = commandBuffer.GetPointer();
m_deviceQueue.Submit(1, &submitInfo, fence.Get());
// Wait for the fence to signal that command buffer has finished executing
fence.WaitForFence(FENCE_TIMEOUT);
// The dst image now contains the content
return ExtractToBitmap(dstImage, dstImageFormat);
}
}
| 43.20078 | 150 | 0.733057 | [
"render",
"object"
] |
8106f74cd7ee0c0fb1a64b836e1efdac8296bbb8 | 1,903 | cpp | C++ | console/src/boost_1_78_0/libs/spirit/test/qi/stream.cpp | vany152/FilesHash | 39f282807b7f1abc56dac389e8259ee3bb557a8d | [
"MIT"
] | 1 | 2019-10-27T21:15:52.000Z | 2019-10-27T21:15:52.000Z | console/src/boost_1_78_0/libs/spirit/test/qi/stream.cpp | vany152/FilesHash | 39f282807b7f1abc56dac389e8259ee3bb557a8d | [
"MIT"
] | null | null | null | console/src/boost_1_78_0/libs/spirit/test/qi/stream.cpp | vany152/FilesHash | 39f282807b7f1abc56dac389e8259ee3bb557a8d | [
"MIT"
] | 1 | 2021-08-24T08:49:34.000Z | 2021-08-24T08:49:34.000Z | /*=============================================================================
Copyright (c) 2001-2011 Hartmut Kaiser
Copyright (c) 2011 Brian O'Kennedy
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#include <boost/spirit/include/qi_stream.hpp>
#include <boost/spirit/include/qi_char.hpp>
#include <boost/spirit/include/qi_numeric.hpp>
#include <boost/spirit/include/qi_operator.hpp>
#include "test.hpp"
struct complex
{
complex (double a = 0.0, double b = 0.0) : a(a), b(b) {}
double a, b;
};
std::istream& operator>> (std::istream& is, complex& z)
{
char lbrace = '\0', comma = '\0', rbrace = '\0';
is >> lbrace >> z.a >> comma >> z.b >> rbrace;
if (lbrace != '{' || comma != ',' || rbrace != '}')
is.setstate(std::ios_base::failbit);
return is;
}
int main()
{
using spirit_test::test_attr;
{
using boost::spirit::qi::blank;
using boost::spirit::qi::double_;
using boost::spirit::qi::stream;
using boost::spirit::qi::stream_parser;
using boost::fusion::at_c;
complex c;
BOOST_TEST(test_attr("{1.0,2.5}",
stream_parser<char, complex>(), c, blank) &&
c.a == 1.0 && c.b == 2.5);
boost::variant<complex, double> cd;
BOOST_TEST(test_attr("{1.0",
stream_parser<char, complex>() | "{" >> double_, cd, blank) &&
boost::get<double>(cd) == 1.0);
boost::fusion::vector<complex, double> d;
BOOST_TEST(test_attr("{1.0,2.5},123.456",
stream >> ',' >> double_, d, blank) &&
at_c<0>(d).a == 1.0 && at_c<0>(d).b == 2.5 && at_c<1>(d) == 123.456);
}
return boost::report_errors();
}
| 30.206349 | 81 | 0.520231 | [
"vector"
] |
81096566bd13d0199be991e97a52fe91cc693fa3 | 6,556 | cpp | C++ | bzhi/main.cpp | Matsuyanagi/bzhi | 1e0b8bfa7d4573f97292b3828288018302923822 | [
"MIT"
] | null | null | null | bzhi/main.cpp | Matsuyanagi/bzhi | 1e0b8bfa7d4573f97292b3828288018302923822 | [
"MIT"
] | null | null | null | bzhi/main.cpp | Matsuyanagi/bzhi | 1e0b8bfa7d4573f97292b3828288018302923822 | [
"MIT"
] | null | null | null | #include <intrin.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <vector>
#include "binstr.h"
/*
0 : 0000000000000000 : 00000000-00000000-00000000-00000000-00000000-00000000-00000000-00000000
1 : 0000000000000001 : 00000000-00000000-00000000-00000000-00000000-00000000-00000000-00000001
2 : 0000000000000003 : 00000000-00000000-00000000-00000000-00000000-00000000-00000000-00000011
3 : 0000000000000007 : 00000000-00000000-00000000-00000000-00000000-00000000-00000000-00000111
4 : 000000000000000f : 00000000-00000000-00000000-00000000-00000000-00000000-00000000-00001111
5 : 000000000000001f : 00000000-00000000-00000000-00000000-00000000-00000000-00000000-00011111
6 : 000000000000003f : 00000000-00000000-00000000-00000000-00000000-00000000-00000000-00111111
7 : 000000000000007f : 00000000-00000000-00000000-00000000-00000000-00000000-00000000-01111111
8 : 00000000000000ff : 00000000-00000000-00000000-00000000-00000000-00000000-00000000-11111111
9 : 00000000000001ff : 00000000-00000000-00000000-00000000-00000000-00000000-00000001-11111111
10 : 00000000000003ff : 00000000-00000000-00000000-00000000-00000000-00000000-00000011-11111111
11 : 00000000000007ff : 00000000-00000000-00000000-00000000-00000000-00000000-00000111-11111111
12 : 0000000000000fff : 00000000-00000000-00000000-00000000-00000000-00000000-00001111-11111111
13 : 0000000000001fff : 00000000-00000000-00000000-00000000-00000000-00000000-00011111-11111111
14 : 0000000000003fff : 00000000-00000000-00000000-00000000-00000000-00000000-00111111-11111111
15 : 0000000000007fff : 00000000-00000000-00000000-00000000-00000000-00000000-01111111-11111111
16 : 000000000000ffff : 00000000-00000000-00000000-00000000-00000000-00000000-11111111-11111111
17 : 000000000001ffff : 00000000-00000000-00000000-00000000-00000000-00000001-11111111-11111111
18 : 000000000003ffff : 00000000-00000000-00000000-00000000-00000000-00000011-11111111-11111111
19 : 000000000007ffff : 00000000-00000000-00000000-00000000-00000000-00000111-11111111-11111111
20 : 00000000000fffff : 00000000-00000000-00000000-00000000-00000000-00001111-11111111-11111111
21 : 00000000001fffff : 00000000-00000000-00000000-00000000-00000000-00011111-11111111-11111111
22 : 00000000003fffff : 00000000-00000000-00000000-00000000-00000000-00111111-11111111-11111111
23 : 00000000007fffff : 00000000-00000000-00000000-00000000-00000000-01111111-11111111-11111111
24 : 0000000000ffffff : 00000000-00000000-00000000-00000000-00000000-11111111-11111111-11111111
25 : 0000000001ffffff : 00000000-00000000-00000000-00000000-00000001-11111111-11111111-11111111
26 : 0000000003ffffff : 00000000-00000000-00000000-00000000-00000011-11111111-11111111-11111111
27 : 0000000007ffffff : 00000000-00000000-00000000-00000000-00000111-11111111-11111111-11111111
28 : 000000000fffffff : 00000000-00000000-00000000-00000000-00001111-11111111-11111111-11111111
29 : 000000001fffffff : 00000000-00000000-00000000-00000000-00011111-11111111-11111111-11111111
30 : 000000003fffffff : 00000000-00000000-00000000-00000000-00111111-11111111-11111111-11111111
31 : 000000007fffffff : 00000000-00000000-00000000-00000000-01111111-11111111-11111111-11111111
32 : 00000000ffffffff : 00000000-00000000-00000000-00000000-11111111-11111111-11111111-11111111
33 : 00000001ffffffff : 00000000-00000000-00000000-00000001-11111111-11111111-11111111-11111111
34 : 00000003ffffffff : 00000000-00000000-00000000-00000011-11111111-11111111-11111111-11111111
35 : 00000007ffffffff : 00000000-00000000-00000000-00000111-11111111-11111111-11111111-11111111
36 : 0000000fffffffff : 00000000-00000000-00000000-00001111-11111111-11111111-11111111-11111111
37 : 0000001fffffffff : 00000000-00000000-00000000-00011111-11111111-11111111-11111111-11111111
38 : 0000003fffffffff : 00000000-00000000-00000000-00111111-11111111-11111111-11111111-11111111
39 : 0000007fffffffff : 00000000-00000000-00000000-01111111-11111111-11111111-11111111-11111111
40 : 000000ffffffffff : 00000000-00000000-00000000-11111111-11111111-11111111-11111111-11111111
41 : 000001ffffffffff : 00000000-00000000-00000001-11111111-11111111-11111111-11111111-11111111
42 : 000003ffffffffff : 00000000-00000000-00000011-11111111-11111111-11111111-11111111-11111111
43 : 000007ffffffffff : 00000000-00000000-00000111-11111111-11111111-11111111-11111111-11111111
44 : 00000fffffffffff : 00000000-00000000-00001111-11111111-11111111-11111111-11111111-11111111
45 : 00001fffffffffff : 00000000-00000000-00011111-11111111-11111111-11111111-11111111-11111111
46 : 00003fffffffffff : 00000000-00000000-00111111-11111111-11111111-11111111-11111111-11111111
47 : 00007fffffffffff : 00000000-00000000-01111111-11111111-11111111-11111111-11111111-11111111
48 : 0000ffffffffffff : 00000000-00000000-11111111-11111111-11111111-11111111-11111111-11111111
49 : 0001ffffffffffff : 00000000-00000001-11111111-11111111-11111111-11111111-11111111-11111111
50 : 0003ffffffffffff : 00000000-00000011-11111111-11111111-11111111-11111111-11111111-11111111
51 : 0007ffffffffffff : 00000000-00000111-11111111-11111111-11111111-11111111-11111111-11111111
52 : 000fffffffffffff : 00000000-00001111-11111111-11111111-11111111-11111111-11111111-11111111
53 : 001fffffffffffff : 00000000-00011111-11111111-11111111-11111111-11111111-11111111-11111111
54 : 003fffffffffffff : 00000000-00111111-11111111-11111111-11111111-11111111-11111111-11111111
55 : 007fffffffffffff : 00000000-01111111-11111111-11111111-11111111-11111111-11111111-11111111
56 : 00ffffffffffffff : 00000000-11111111-11111111-11111111-11111111-11111111-11111111-11111111
57 : 01ffffffffffffff : 00000001-11111111-11111111-11111111-11111111-11111111-11111111-11111111
58 : 03ffffffffffffff : 00000011-11111111-11111111-11111111-11111111-11111111-11111111-11111111
59 : 07ffffffffffffff : 00000111-11111111-11111111-11111111-11111111-11111111-11111111-11111111
60 : 0fffffffffffffff : 00001111-11111111-11111111-11111111-11111111-11111111-11111111-11111111
61 : 1fffffffffffffff : 00011111-11111111-11111111-11111111-11111111-11111111-11111111-11111111
62 : 3fffffffffffffff : 00111111-11111111-11111111-11111111-11111111-11111111-11111111-11111111
63 : 7fffffffffffffff : 01111111-11111111-11111111-11111111-11111111-11111111-11111111-11111111
*/
int main() {
uint64_t a = 0xFFFF'FFFF'FFFF'FFFF;
for ( size_t i = 0; i < 64; i++ ) {
uint64_t result = _bzhi_u64( a, i );
std::string result_str = binstr( result );
printf( "%2d : %016llx : %s\n", i, result, result_str.c_str() );
}
}
| 72.844444 | 95 | 0.837553 | [
"vector"
] |
810bffbdd7bb8d0dcfdefc135898e7b34620dbc5 | 9,632 | cc | C++ | src/operator/image/image_random.cc | tomz/incubator-mxnet | 0a2419ffbc7b94448110bf20e52d83557ccf441f | [
"Apache-2.0"
] | 37 | 2018-03-16T23:36:33.000Z | 2021-07-09T07:48:51.000Z | src/operator/image/image_random.cc | PaulGureghian1/MXNet | 0a2419ffbc7b94448110bf20e52d83557ccf441f | [
"Apache-2.0"
] | 187 | 2018-03-16T23:44:43.000Z | 2021-12-14T21:19:54.000Z | src/operator/image/image_random.cc | PaulGureghian1/MXNet | 0a2419ffbc7b94448110bf20e52d83557ccf441f | [
"Apache-2.0"
] | 5 | 2019-07-01T02:27:56.000Z | 2019-11-05T18:14:23.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file image_random.cc
* \brief
* \author
*/
#include <mxnet/base.h>
#include "./image_random-inl.h"
#include "../operator_common.h"
#include "../elemwise_op_common.h"
namespace mxnet {
namespace op {
namespace image {
DMLC_REGISTER_PARAMETER(NormalizeParam);
DMLC_REGISTER_PARAMETER(RandomEnhanceParam);
DMLC_REGISTER_PARAMETER(AdjustLightingParam);
DMLC_REGISTER_PARAMETER(RandomLightingParam);
DMLC_REGISTER_PARAMETER(RandomColorJitterParam);
NNVM_REGISTER_OP(_image_to_tensor)
.describe(R"code(Converts an image NDArray of shape (H x W x C) or (N x H x W x C)
with values in the range [0, 255] to a tensor NDArray of shape (C x H x W) or (N x C x H x W)
with values in the range [0, 1)
Example:
.. code-block:: python
image = mx.nd.random.uniform(0, 255, (4, 2, 3)).astype(dtype=np.uint8)
to_tensor(image)
[[[ 0.85490197 0.72156864]
[ 0.09019608 0.74117649]
[ 0.61960787 0.92941177]
[ 0.96470588 0.1882353 ]]
[[ 0.6156863 0.73725492]
[ 0.46666667 0.98039216]
[ 0.44705883 0.45490196]
[ 0.01960784 0.8509804 ]]
[[ 0.39607844 0.03137255]
[ 0.72156864 0.52941179]
[ 0.16470589 0.7647059 ]
[ 0.05490196 0.70588237]]]
<NDArray 3x4x2 @cpu(0)>
image = mx.nd.random.uniform(0, 255, (2, 4, 2, 3)).astype(dtype=np.uint8)
to_tensor(image)
[[[[0.11764706 0.5803922 ]
[0.9411765 0.10588235]
[0.2627451 0.73333335]
[0.5647059 0.32156864]]
[[0.7176471 0.14117648]
[0.75686276 0.4117647 ]
[0.18431373 0.45490196]
[0.13333334 0.6156863 ]]
[[0.6392157 0.5372549 ]
[0.52156866 0.47058824]
[0.77254903 0.21568628]
[0.01568628 0.14901961]]]
[[[0.6117647 0.38431373]
[0.6784314 0.6117647 ]
[0.69411767 0.96862745]
[0.67058825 0.35686275]]
[[0.21960784 0.9411765 ]
[0.44705883 0.43529412]
[0.09803922 0.6666667 ]
[0.16862746 0.1254902 ]]
[[0.6156863 0.9019608 ]
[0.35686275 0.9019608 ]
[0.05882353 0.6509804 ]
[0.20784314 0.7490196 ]]]]
<NDArray 2x3x4x2 @cpu(0)>
)code" ADD_FILELINE)
.set_num_inputs(1)
.set_num_outputs(1)
.set_attr<nnvm::FListInputNames>("FListInputNames",
[](const NodeAttrs& attrs) {
return std::vector<std::string>{"data"};
})
.set_attr<nnvm::FInferShape>("FInferShape", ToTensorShape)
.set_attr<nnvm::FInferType>("FInferType", ToTensorType)
.set_attr<FCompute>("FCompute<cpu>", ToTensorOpForward<cpu>)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseNone{ "_copy" })
.add_argument("data", "NDArray-or-Symbol", "Input ndarray");
NNVM_REGISTER_OP(_image_normalize)
.describe(R"code(Normalize an tensor of shape (C x H x W) or (N x C x H x W) with mean and
standard deviation.
Given mean `(m1, ..., mn)` and std `(s\ :sub:`1`\ , ..., s\ :sub:`n`)` for `n` channels,
this transform normalizes each channel of the input tensor with:
.. math::
output[i] = (input[i] - m\ :sub:`i`\ ) / s\ :sub:`i`
If mean or std is scalar, the same value will be applied to all channels.
Default value for mean is 0.0 and stand deviation is 1.0.
Example:
.. code-block:: python
image = mx.nd.random.uniform(0, 1, (3, 4, 2))
normalize(image, mean=(0, 1, 2), std=(3, 2, 1))
[[[ 0.18293785 0.19761486]
[ 0.23839645 0.28142193]
[ 0.20092112 0.28598186]
[ 0.18162774 0.28241724]]
[[-0.2881726 -0.18821815]
[-0.17705294 -0.30780914]
[-0.2812064 -0.3512327 ]
[-0.05411351 -0.4716435 ]]
[[-1.0363373 -1.7273437 ]
[-1.6165586 -1.5223348 ]
[-1.208275 -1.1878313 ]
[-1.4711051 -1.5200229 ]]]
<NDArray 3x4x2 @cpu(0)>
image = mx.nd.random.uniform(0, 1, (2, 3, 4, 2))
normalize(image, mean=(0, 1, 2), std=(3, 2, 1))
[[[[ 0.18934818 0.13092826]
[ 0.3085322 0.27869293]
[ 0.02367868 0.11246539]
[ 0.0290431 0.2160573 ]]
[[-0.4898908 -0.31587923]
[-0.08369008 -0.02142242]
[-0.11092162 -0.42982462]
[-0.06499392 -0.06495637]]
[[-1.0213816 -1.526392 ]
[-1.2008414 -1.1990893 ]
[-1.5385206 -1.4795225 ]
[-1.2194707 -1.3211205 ]]]
[[[ 0.03942481 0.24021089]
[ 0.21330701 0.1940066 ]
[ 0.04778443 0.17912441]
[ 0.31488964 0.25287187]]
[[-0.23907584 -0.4470462 ]
[-0.29266903 -0.2631998 ]
[-0.3677222 -0.40683383]
[-0.11288315 -0.13154092]]
[[-1.5438497 -1.7834496 ]
[-1.431566 -1.8647819 ]
[-1.9812102 -1.675859 ]
[-1.3823645 -1.8503251 ]]]]
<NDArray 2x3x4x2 @cpu(0)>
)code" ADD_FILELINE)
.set_attr_parser(ParamParser<NormalizeParam>)
.set_num_inputs(1)
.set_num_outputs(1)
.set_attr<nnvm::FListInputNames>("FListInputNames",
[](const NodeAttrs& attrs) {
return std::vector<std::string>{"data"};
})
.set_attr<nnvm::FInferShape>("FInferShape", NormalizeOpShape)
.set_attr<nnvm::FInferType>("FInferType", NormalizeOpType)
.set_attr<FCompute>("FCompute<cpu>", NormalizeOpForward<cpu>)
.set_attr<nnvm::FInplaceOption>("FInplaceOption",
[](const NodeAttrs& attrs) {
return std::vector<std::pair<int, int> >{{0, 0}};
})
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_image_normalize"})
.add_argument("data", "NDArray-or-Symbol", "Input ndarray")
.add_arguments(NormalizeParam::__FIELDS__());
NNVM_REGISTER_OP(_backward_image_normalize)
.set_attr_parser(ParamParser<NormalizeParam>)
.set_num_inputs(1)
.set_num_outputs(1)
.set_attr<nnvm::TIsBackward>("TIsBackward", true)
.set_attr<FCompute>("FCompute<cpu>", NormalizeOpBackward<cpu>);
MXNET_REGISTER_IMAGE_AUG_OP(_image_flip_left_right)
.describe(R"code()code" ADD_FILELINE)
.set_attr<FCompute>("FCompute<cpu>", FlipLeftRight);
MXNET_REGISTER_IMAGE_RND_AUG_OP(_image_random_flip_left_right)
.describe(R"code()code" ADD_FILELINE)
.set_attr<FCompute>("FCompute<cpu>", RandomFlipLeftRight);
MXNET_REGISTER_IMAGE_AUG_OP(_image_flip_top_bottom)
.describe(R"code()code" ADD_FILELINE)
.set_attr<FCompute>("FCompute<cpu>", FlipTopBottom);
MXNET_REGISTER_IMAGE_RND_AUG_OP(_image_random_flip_top_bottom)
.describe(R"code()code" ADD_FILELINE)
.set_attr<FCompute>("FCompute<cpu>", RandomFlipTopBottom);
MXNET_REGISTER_IMAGE_RND_AUG_OP(_image_random_brightness)
.describe(R"code()code" ADD_FILELINE)
.set_attr_parser(ParamParser<RandomEnhanceParam>)
.set_attr<FCompute>("FCompute<cpu>", RandomBrightness)
.add_arguments(RandomEnhanceParam::__FIELDS__());
MXNET_REGISTER_IMAGE_RND_AUG_OP(_image_random_contrast)
.describe(R"code()code" ADD_FILELINE)
.set_attr_parser(ParamParser<RandomEnhanceParam>)
.set_attr<FCompute>("FCompute<cpu>", RandomContrast)
.add_arguments(RandomEnhanceParam::__FIELDS__());
MXNET_REGISTER_IMAGE_RND_AUG_OP(_image_random_saturation)
.describe(R"code()code" ADD_FILELINE)
.set_attr_parser(ParamParser<RandomEnhanceParam>)
.set_attr<FCompute>("FCompute<cpu>", RandomSaturation)
.add_arguments(RandomEnhanceParam::__FIELDS__());
MXNET_REGISTER_IMAGE_RND_AUG_OP(_image_random_hue)
.describe(R"code()code" ADD_FILELINE)
.set_attr_parser(ParamParser<RandomEnhanceParam>)
.set_attr<FCompute>("FCompute<cpu>", RandomHue)
.add_arguments(RandomEnhanceParam::__FIELDS__());
MXNET_REGISTER_IMAGE_RND_AUG_OP(_image_random_color_jitter)
.describe(R"code()code" ADD_FILELINE)
.set_attr_parser(ParamParser<RandomColorJitterParam>)
.set_attr<FCompute>("FCompute<cpu>", RandomColorJitter)
.add_arguments(RandomColorJitterParam::__FIELDS__());
MXNET_REGISTER_IMAGE_AUG_OP(_image_adjust_lighting)
.describe(R"code(Adjust the lighting level of the input. Follow the AlexNet style.)code" ADD_FILELINE)
.set_attr_parser(ParamParser<AdjustLightingParam>)
.set_attr<FCompute>("FCompute<cpu>", AdjustLighting)
.add_arguments(AdjustLightingParam::__FIELDS__());
MXNET_REGISTER_IMAGE_RND_AUG_OP(_image_random_lighting)
.describe(R"code(Randomly add PCA noise. Follow the AlexNet style.)code" ADD_FILELINE)
.set_attr_parser(ParamParser<RandomLightingParam>)
.set_attr<FCompute>("FCompute<cpu>", RandomLighting)
.add_arguments(RandomLightingParam::__FIELDS__());
} // namespace image
} // namespace op
} // namespace mxnet
| 37.478599 | 102 | 0.653135 | [
"shape",
"vector",
"transform"
] |
810c656b54e30f88f2e6025cdfec5632b4dadf3f | 3,191 | cpp | C++ | src/resources/graphics/glx.cpp | dudu3107/cpp-life-of-boids | 89b1edcd35aa7c957e61d7131a06025f6cdbc71f | [
"Apache-2.0"
] | null | null | null | src/resources/graphics/glx.cpp | dudu3107/cpp-life-of-boids | 89b1edcd35aa7c957e61d7131a06025f6cdbc71f | [
"Apache-2.0"
] | null | null | null | src/resources/graphics/glx.cpp | dudu3107/cpp-life-of-boids | 89b1edcd35aa7c957e61d7131a06025f6cdbc71f | [
"Apache-2.0"
] | null | null | null | #include "glx.hpp"
#include <GLFW/glfw3.h>
#include <glad/glad.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core/mat.hpp>
#include <opencv2/imgcodecs.hpp>
#include <vector>
VertexArray VertexArray_new() {
GLuint vertex_array{};
glGenVertexArrays(1, &vertex_array);
glBindVertexArray(vertex_array);
return VertexArray{vertex_array};
}
void VertexArray_bind(VertexArray& vertexArray) {
glBindVertexArray(vertexArray.vertex_array);
}
Buffer Buffer_new() {
GLuint vertex_buffer{};
glGenBuffers(1, &vertex_buffer);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
return Buffer{vertex_buffer};
}
void Buffer_bind(Buffer& buffer, GLenum target) {
glBindBuffer(target, buffer.vertex_buffer);
}
ShaderProgram ShaderProgram_new(const char* vertex_shader_text, const char* fragment_shader_text) {
// TODO Manage errors
const GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_text, nullptr);
glCompileShader(vertex_shader);
const GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_text, nullptr);
glCompileShader(fragment_shader);
const GLuint program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
return ShaderProgram{program};
}
void ShaderProgram_activate(ShaderProgram& shaderProgram) {
glUseProgram(shaderProgram.program);
}
GLint ShaderProgram_getAttribLocation(ShaderProgram& shaderProgram, const char* name) {
const GLint loc = glGetAttribLocation(shaderProgram.program, name);
return loc;
}
GLint ShaderProgram_getUniformLocation(ShaderProgram& shaderProgram, const char* name) {
const GLint loc = glGetUniformLocation(shaderProgram.program, name);
return loc;
}
void saveImage(char* filepath, GLFWwindow* w) {
int width{}, height{};
glfwGetFramebufferSize(w, &width, &height);
GLsizei nrChannels = 3;
GLsizei stride = nrChannels * width;
// Most image file formats require the number of bytes used to store a single row of an image to be a multiple of 4.
// As a default, OpenGL also “likes” packing image data in this way since the default value of GL_PACK_ALIGNMENT is 4.
// I assume that this may enable OpenGL to do parallel computations more easily.
//
// Anyway it could be ok without the update of the stride (then GL_PACK_ALIGNMENT should be 1)
stride += (stride % 4) ? (4 - stride % 4) : 0;
GLsizei bufferSize = stride * height;
std::vector<char> buffer(bufferSize);
glPixelStorei(GL_PACK_ALIGNMENT, 4);
glReadBuffer(GL_FRONT);
glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer.data());
cv::Mat img(height, width, CV_8UC3, cv::Scalar(0, 0, 0)); // 8 bits unsigned integer with 3 color channels (BGR)
for (int y = 0; y < img.rows; y++) {
std::size_t pos = y * stride;
for (int x = 0; x < img.cols; x++) {
cv::Vec3b& color = img.at<cv::Vec3b>(height-1-y, x); // vertical flip of OpenGL buffer
color[2] = buffer[pos++]; // reorder BGR colors
color[1] = buffer[pos++];
color[0] = buffer[pos++];
}
}
imwrite(filepath, img);
}
| 33.946809 | 120 | 0.73676 | [
"vector"
] |
811584c181607e0b8f97d50fdf7125db6247fd71 | 11,270 | cpp | C++ | multiview/multiview_cpp/src/perceive/utils/eigen-helpers.cpp | prcvlabs/multiview | 1a03e14855292967ffb0c0ec7fff855c5abbc9d2 | [
"Apache-2.0"
] | 5 | 2021-09-03T23:12:08.000Z | 2022-03-04T21:43:32.000Z | multiview/multiview_cpp/src/perceive/utils/eigen-helpers.cpp | prcvlabs/multiview | 1a03e14855292967ffb0c0ec7fff855c5abbc9d2 | [
"Apache-2.0"
] | 3 | 2021-09-08T02:57:46.000Z | 2022-02-26T05:33:02.000Z | multiview/multiview_cpp/src/perceive/utils/eigen-helpers.cpp | prcvlabs/multiview | 1a03e14855292967ffb0c0ec7fff855c5abbc9d2 | [
"Apache-2.0"
] | 2 | 2021-09-26T03:14:40.000Z | 2022-01-26T06:42:52.000Z |
#include "eigen-helpers.hpp"
#include "perceive/geometry/rotation.hpp"
#include <Eigen/SVD>
using std::stringstream;
namespace perceive
{
// ------------------------------------------------------------------- Is finite
// Checks that an Eigen Matrix is finite
template<typename T> bool is_finiteT(const T& M)
{
int n_rows = int(M.rows());
int n_cols = int(M.cols());
for(int i = 0; i < n_rows; ++i)
for(int j = 0; j < n_cols; ++j)
if(!std::isfinite(M(i, j))) return false;
return true;
}
bool is_finite(const Vector2r& M) { return is_finiteT(M); }
bool is_finite(const Vector3r& M) { return is_finiteT(M); }
bool is_finite(const Vector4r& M) { return is_finiteT(M); }
bool is_finite(const Matrix3r& M) { return is_finiteT(M); }
bool is_finite(const Matrix34r& M) { return is_finiteT(M); }
bool is_finite(const MatrixXr& M) { return is_finiteT(M); }
// -------------------------------------------------------------------- str(...)
std::string str(const Vector2r& M) { return format("[{}, {}]", M(0), M(1)); }
std::string str(const Vector3r& M)
{
return format("[{}, {}, {}]", M(0), M(1), M(2));
}
std::string str(const Vector4r& M)
{
return format("[{}, {}, {}, {}]", M(0), M(1), M(2), M(3));
}
std::string str(const Matrix3r& M)
{
stringstream ss("");
ss << M;
return ss.str();
}
std::string str(const Matrix34r& M)
{
stringstream ss("");
ss << M;
return ss.str();
}
std::string str(const MatrixXr& M)
{
stringstream ss("");
ss << M;
return ss.str();
}
std::string str(std::string name, const Matrix3r& M)
{
stringstream ss("");
ss << name << " = \n" << M << "\n";
return ss.str();
}
std::string str(std::string name, const Matrix34r& M)
{
stringstream ss("");
ss << name << " = \n" << M << "\n";
return ss.str();
}
std::string str(std::string name, const MatrixXr& M)
{
stringstream ss("");
ss << name << " = \n" << M << "\n";
return ss.str();
}
// ------------------------------------------------------------------------- SVD
// -- Thin
real svd_thin(const MatrixXr& M, VectorXr& out)
{
Eigen::JacobiSVD<MatrixXr> svd(M, Eigen::ComputeThinV);
out = svd.matrixV().col(M.cols() - 1);
return svd.singularValues()(M.cols() - 1);
}
real svd_thin(const Matrix3r& M, Vector3r& out)
{
Eigen::JacobiSVD<MatrixXr> svd(M, Eigen::ComputeThinV);
out = svd.matrixV().col(M.cols() - 1);
return svd.singularValues()(M.cols() - 1);
}
// real svd_thin(const Matrix3d& M, Vector3d& out)
// {
// Eigen::JacobiSVD<MatrixXd> svd(M, Eigen::ComputeThinV);
// out = svd.matrixV().col(M.cols() - 1);
// return svd.singularValues()(M.cols() - 1);
// }
// real svd_thin(const MatrixXd& M, VectorXd& out)
// {
// Eigen::JacobiSVD<MatrixXd> svd(M, Eigen::ComputeThinV);
// out = svd.matrixV().col(M.cols() - 1);
// return svd.singularValues()(M.cols() - 1);
// }
real svd_thin(const MatrixXr& M, Vector6r& out)
{
Eigen::JacobiSVD<MatrixXr> svd(M, Eigen::ComputeThinV);
out = svd.matrixV().col(M.cols() - 1);
return svd.singularValues()(M.cols() - 1);
}
// -- UD
void svd_UV(const MatrixXr& M, MatrixXr& U, MatrixXr& V)
{
Eigen::JacobiSVD<MatrixXr> svd(M, Eigen::ComputeThinU | Eigen::ComputeThinV);
U = svd.matrixU();
V = svd.matrixV();
}
void svd_UV(const Matrix3r& M, Matrix3r& U, Matrix3r& V)
{
Eigen::JacobiSVD<MatrixXr> svd(M, Eigen::ComputeThinU | Eigen::ComputeThinV);
U = svd.matrixU();
V = svd.matrixV();
}
// void svd_UV(const MatrixXd& M, MatrixXd& U, MatrixXd& V)
// {
// Eigen::JacobiSVD<MatrixXd> svd(M,
// Eigen::ComputeThinU|Eigen::ComputeThinV); U = svd.matrixU(); V =
// svd.matrixV();
// }
// -- UDV
void svd_UDV(const MatrixXr& M, MatrixXr& U, VectorXr& D, MatrixXr& V)
{
Eigen::JacobiSVD<MatrixXr> svd(M, Eigen::ComputeThinU | Eigen::ComputeThinV);
U = svd.matrixU();
V = svd.matrixV();
auto s = svd.singularValues();
auto n = s.rows();
D.resize(n);
for(uint i = 0; i < n; ++i) D(i) = s(i);
}
void svd_UDV(const Matrix3r& M, Matrix3r& U, Vector3r& D, Matrix3r& V)
{
Eigen::JacobiSVD<MatrixXr> svd(M, Eigen::ComputeThinU | Eigen::ComputeThinV);
U = svd.matrixU();
V = svd.matrixV();
auto s = svd.singularValues();
for(uint i = 0; i < 3; ++i) D(i) = s(i);
}
void svd_UDV(const Matrix3r& M, Matrix3r& U, Matrix3r& D, Matrix3r& V)
{
Vector3r d;
svd_UDV(M, U, d, V);
D = Matrix3r::Zero();
for(auto i = 0; i < 3; ++i) D(i, i) = d(i);
}
// void svd_UDV(const MatrixXd& M, MatrixXd& U, VectorXd& D, MatrixXd& V)
// {
// Eigen::JacobiSVD<MatrixXd> svd(M,
// Eigen::ComputeThinU|Eigen::ComputeThinV); U = svd.matrixU(); V =
// svd.matrixV(); auto s = svd.singularValues(); auto n = s.rows();
// D.resize(n);
// for(uint i = 0; i < n; ++i)
// D(i) = s(i);
// }
Matrix3r SVD3DRet::Dm() const noexcept
{
Matrix3r X = Matrix3r::Identity();
for(auto i = 0; i < 3; ++i) X(i, i) = D(i);
return X;
}
string SVD3DRet::to_string() const noexcept
{
std::stringstream ss{""};
ss << format("U = \n") << U << "\n\n"
<< format("D = \n") << Dm() << "\n\n"
<< format("V = \n") << V << "\n\n";
return ss.str();
}
Vector3r SVD3DRet::eigen_vector(int ind) const noexcept
{
Expects(ind >= 0 && ind < 3);
return Vector3r(V(ind, 0), V(ind, 1), V(ind, 2));
}
Quaternion SVD3DRet::rot_vec() const noexcept
{
return rot3x3_to_quaternion(V.transpose());
}
template<typename J>
using MatrixXc_J
= Eigen::Matrix<std::complex<J>, Eigen::Dynamic, Eigen::Dynamic>;
template<typename J>
using VectorXc_J = Eigen::Matrix<std::complex<J>, Eigen::Dynamic, 1>;
template<typename T>
void svd_UDV_T(const MatrixXc_J<T>& M,
MatrixXc_J<T>& U,
VectorXc_J<T>& D,
MatrixXc_J<T>& V)
{
using MatrixXc = MatrixXc_J<T>;
// using VectorXc = VectorXc_J<T>;
Eigen::JacobiSVD<MatrixXc> svd(M, Eigen::ComputeThinU | Eigen::ComputeThinV);
U = svd.matrixU();
V = svd.matrixV();
auto s = svd.singularValues();
auto n = s.rows();
D.resize(n, 1);
for(uint i = 0; i < n; ++i) D(i) = s(i);
}
void svd_UDV(const MatrixXc_J<long double>& M,
MatrixXc_J<long double>& U,
VectorXc_J<long double>& D,
MatrixXc_J<long double>& V)
{
svd_UDV_T<long double>(M, U, D, V);
}
void svd_UDV(const MatrixXc_J<double>& M,
MatrixXc_J<double>& U,
VectorXc_J<double>& D,
MatrixXc_J<double>& V)
{
svd_UDV_T<double>(M, U, D, V);
}
void svd_UDV(const MatrixXc_J<float>& M,
MatrixXc_J<float>& U,
VectorXc_J<float>& D,
MatrixXc_J<float>& V)
{
svd_UDV_T<float>(M, U, D, V);
}
template<typename T>
void svd_UDV_T(const Eigen::Matrix<std::complex<T>, 3, 3>& M,
Eigen::Matrix<std::complex<T>, 3, 3>& U,
Eigen::Matrix<std::complex<T>, 3, 1>& D,
Eigen::Matrix<std::complex<T>, 3, 3>& V)
{
using MatrixXc = MatrixXc_J<T>;
// using VectorXc = VectorXc_J<T>;
Eigen::JacobiSVD<MatrixXc> svd(M, Eigen::ComputeThinU | Eigen::ComputeThinV);
U = svd.matrixU();
V = svd.matrixV();
auto s = svd.singularValues();
auto n = s.rows();
D.resize(n, 1);
for(uint i = 0; i < n; ++i) D(i) = s(i);
}
void svd_UDV(const Eigen::Matrix<std::complex<long double>, 3, 3>& M,
Eigen::Matrix<std::complex<long double>, 3, 3>& U,
Eigen::Matrix<std::complex<long double>, 3, 1>& D,
Eigen::Matrix<std::complex<long double>, 3, 3>& V)
{
svd_UDV_T(M, U, D, V);
}
void svd_UDV(const Eigen::Matrix<std::complex<double>, 3, 3>& M,
Eigen::Matrix<std::complex<double>, 3, 3>& U,
Eigen::Matrix<std::complex<double>, 3, 1>& D,
Eigen::Matrix<std::complex<double>, 3, 3>& V)
{
svd_UDV_T(M, U, D, V);
}
void svd_UDV(const Eigen::Matrix<std::complex<float>, 3, 3>& M,
Eigen::Matrix<std::complex<float>, 3, 3>& U,
Eigen::Matrix<std::complex<float>, 3, 1>& D,
Eigen::Matrix<std::complex<float>, 3, 3>& V)
{
svd_UDV_T(M, U, D, V);
}
template<typename T, typename S> double bdcsvd_thin_TS(const T& M, S& out)
{
Eigen::BDCSVD<T> svd(M, Eigen::ComputeThinV);
out = svd.matrixV().col(M.cols() - 1);
return svd.singularValues()(M.cols() - 1);
}
// double bdcsvd_thin(const MatrixXd& M, VectorXd& out)
// { return bdcsvd_thin_TS(M, out); }
real bdcsvd_thin(const MatrixXr& M, VectorXr& out)
{
return bdcsvd_thin_TS(M, out);
}
// ------------------------------------------------------------ condition-number
template<typename T> real condition_number_T(const T& M)
{
Eigen::JacobiSVD<T> svd(M);
auto vals = svd.singularValues();
return vals(0) / vals(vals.rows() - 1);
}
real condition_number(const MatrixXr& M) { return condition_number_T(M); }
real condition_number(const Matrix3r& M) { return condition_number_T(M); }
// -------------------------------------------------------- Cross-product Matrix
template<typename T> void to_cross_product_matrix_T(const T& X, Matrix3r& M)
{
M(0, 0) = M(1, 1) = M(2, 2) = 0.0;
M(0, 1) = -X(2);
M(1, 0) = X(2);
M(0, 2) = X(1);
M(2, 0) = -X(1);
M(1, 2) = -X(0);
M(2, 1) = X(0);
}
void to_cross_product_matrix(const Vector3r& X, Matrix3r& M)
{
to_cross_product_matrix_T(X, M);
}
void to_cross_product_matrix(const Vector3& X, Matrix3r& M)
{
to_cross_product_matrix_T(X, M);
}
Matrix3r make_cross_product_matrix(const Vector3& X)
{
Matrix3r M;
to_cross_product_matrix_T(X, M);
return M;
}
Matrix3r make_cross_product_matrix(const Vector3r& X)
{
Matrix3r M;
to_cross_product_matrix_T(X, M);
return M;
}
// --------------------------------------------------- Quadratic with Constraint
// Minimize xGtGx such that Hx = h
// * G must have more rows than columns.
// * G.cols() == H.cols()
MatrixXr minimize_with_constraint(const MatrixXr& G, const MatrixXr& H, real h)
{
const unsigned n_vars = unsigned(G.cols());
const unsigned n_equations = unsigned(G.rows());
MatrixXr sol = MatrixXr::Zero(n_vars, 1);
if(G.rows() < G.cols()) {
LOG_ERR(format("Must have more equations than unknowns!"));
return sol;
}
if(H.rows() != n_vars) {
LOG_ERR(format("G and H must have the same number of columns!"));
return sol;
}
MatrixXr A = MatrixXr::Zero(n_vars + 1, n_vars + 1);
MatrixXr b = MatrixXr::Zero(n_vars + 1, 1); // Ax - b = 0
b(n_vars) = h;
for(unsigned row = 0; row < n_vars; ++row) {
A(row, n_vars) = H(row);
A(n_vars, row) = H(row);
}
A.block(0, 0, n_vars, n_vars) = G.transpose() * G;
if(false) {
MatrixXr U, V;
VectorXr D;
svd_UDV(A, U, D, V);
cout << str("A\n") << A << endl << endl;
cout << str("U\n") << U << endl << endl;
cout << str("D\n") << D << endl << endl;
cout << str("V\n") << V << endl << endl;
}
MatrixXr Ainv = A.inverse();
MatrixXr sol_lambda = Ainv * b;
sol = sol_lambda.block(0, 0, n_vars, 1);
return sol;
}
} // namespace perceive
| 27.354369 | 80 | 0.563709 | [
"geometry"
] |
811b39b57365620107a4ae01b2e8270fdca80347 | 19,918 | hpp | C++ | rocprim/include/rocprim/device/device_partition_hip.hpp | arsenm/rocPRIM | 02d6006a7951c53ecfd245200d58809d3eee0b48 | [
"MIT"
] | null | null | null | rocprim/include/rocprim/device/device_partition_hip.hpp | arsenm/rocPRIM | 02d6006a7951c53ecfd245200d58809d3eee0b48 | [
"MIT"
] | null | null | null | rocprim/include/rocprim/device/device_partition_hip.hpp | arsenm/rocPRIM | 02d6006a7951c53ecfd245200d58809d3eee0b48 | [
"MIT"
] | null | null | null | // Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
//
// 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 ROCPRIM_DEVICE_DEVICE_PARTITION_HIP_HPP_
#define ROCPRIM_DEVICE_DEVICE_PARTITION_HIP_HPP_
#include <type_traits>
#include <iterator>
#include "../config.hpp"
#include "../functional.hpp"
#include "../type_traits.hpp"
#include "../detail/various.hpp"
#include "../detail/match_result_type.hpp"
#include "device_select_config.hpp"
#include "detail/device_partition.hpp"
BEGIN_ROCPRIM_NAMESPACE
/// \addtogroup devicemodule_hip
/// @{
namespace detail
{
template<
select_method SelectMethod,
bool OnlySelected,
class Config,
class ResultType,
class InputIterator,
class FlagIterator,
class OutputIterator,
class SelectedCountOutputIterator,
class UnaryPredicate,
class InequalityOp,
class OffsetLookbackScanState
>
__global__
void partition_kernel(InputIterator input,
FlagIterator flags,
OutputIterator output,
SelectedCountOutputIterator selected_count_output,
const size_t size,
UnaryPredicate predicate,
InequalityOp inequality_op,
OffsetLookbackScanState offset_scan_state,
const unsigned int number_of_blocks,
ordered_block_id<unsigned int> ordered_bid)
{
partition_kernel_impl<SelectMethod, OnlySelected, Config, ResultType>(
input, flags, output, selected_count_output, size, predicate,
inequality_op, offset_scan_state, number_of_blocks, ordered_bid
);
}
template<class OffsetLookBackScanState>
__global__
void init_offset_scan_state_kernel(OffsetLookBackScanState offset_scan_state,
const unsigned int number_of_blocks,
ordered_block_id<unsigned int> ordered_bid)
{
init_lookback_scan_state_kernel_impl(
offset_scan_state, number_of_blocks, ordered_bid
);
}
#define ROCPRIM_DETAIL_HIP_SYNC(name, size, start) \
if(debug_synchronous) \
{ \
std::cout << name << "(" << size << ")"; \
auto error = hipStreamSynchronize(stream); \
if(error != hipSuccess) return error; \
auto end = std::chrono::high_resolution_clock::now(); \
auto d = std::chrono::duration_cast<std::chrono::duration<double>>(end - start); \
std::cout << " " << d.count() * 1000 << " ms" << '\n'; \
}
#define ROCPRIM_DETAIL_HIP_SYNC_AND_RETURN_ON_ERROR(name, size, start) \
{ \
auto error = hipPeekAtLastError(); \
if(error != hipSuccess) return error; \
if(debug_synchronous) \
{ \
std::cout << name << "(" << size << ")"; \
auto error = hipStreamSynchronize(stream); \
if(error != hipSuccess) return error; \
auto end = std::chrono::high_resolution_clock::now(); \
auto d = std::chrono::duration_cast<std::chrono::duration<double>>(end - start); \
std::cout << " " << d.count() * 1000 << " ms" << '\n'; \
} \
}
template<
// Method of selection: flag, predicate, unique
select_method SelectMethod,
// if true, it doesn't copy rejected values to output
bool OnlySelected,
class Config,
class InputIterator,
class FlagIterator,
class OutputIterator,
class UnaryPredicate,
class InequalityOp,
class SelectedCountOutputIterator
>
inline
hipError_t partition_impl(void * temporary_storage,
size_t& storage_size,
InputIterator input,
FlagIterator flags,
OutputIterator output,
SelectedCountOutputIterator selected_count_output,
const size_t size,
UnaryPredicate predicate,
InequalityOp inequality_op,
const hipStream_t stream,
bool debug_synchronous)
{
using offset_type = unsigned int;
using input_type = typename std::iterator_traits<InputIterator>::value_type;
using output_type = typename std::iterator_traits<OutputIterator>::value_type;
// Fix for cases when output_type is void (there's no sizeof(void)), it's
// a tuple which contains an item of type void, or is not convertible to
// input_type which is used in InequalityOp
static constexpr bool is_output_type_voidlike =
std::is_same<void, output_type>::value || tuple_contains_type<void, output_type>::value;
// If output_type is voidlike we don't want std::is_convertible<output_type, input_type> to
// be evaluated, it leads to errors if input_type is a tuple
using is_output_type_convertible = typename std::conditional<
is_output_type_voidlike, std::false_type, std::is_convertible<output_type, input_type>
>::type;
static constexpr bool is_output_type_invalid =
is_output_type_voidlike || !(is_output_type_convertible::value);
using value_type = typename std::conditional<
is_output_type_invalid, input_type, output_type
>::type;
// Use smaller type for private storage
using result_type = typename std::conditional<
(sizeof(value_type) > sizeof(input_type)), input_type, value_type
>::type;
// Get default config if Config is default_config
using config = default_or_custom_config<
Config,
default_select_config<ROCPRIM_TARGET_ARCH, result_type>
>;
using offset_scan_state_type = detail::lookback_scan_state<offset_type>;
using ordered_block_id_type = detail::ordered_block_id<unsigned int>;
constexpr unsigned int block_size = config::block_size;
constexpr unsigned int items_per_thread = config::items_per_thread;
constexpr auto items_per_block = block_size * items_per_thread;
const unsigned int number_of_blocks =
std::max(1u, static_cast<unsigned int>((size + items_per_block - 1)/items_per_block));
// Calculate required temporary storage
size_t offset_scan_state_bytes = ::rocprim::detail::align_size(
offset_scan_state_type::get_storage_size(number_of_blocks)
);
size_t ordered_block_id_bytes = ordered_block_id_type::get_storage_size();
if(temporary_storage == nullptr)
{
// storage_size is never zero
storage_size = offset_scan_state_bytes + ordered_block_id_bytes;
return hipSuccess;
}
// Start point for time measurements
std::chrono::high_resolution_clock::time_point start;
if(debug_synchronous)
{
std::cout << "size " << size << '\n';
std::cout << "block_size " << block_size << '\n';
std::cout << "number of blocks " << number_of_blocks << '\n';
std::cout << "items_per_block " << items_per_block << '\n';
}
// Create and initialize lookback_scan_state obj
auto offset_scan_state = offset_scan_state_type::create(
temporary_storage, number_of_blocks
);
// Create ad initialize ordered_block_id obj
auto ptr = reinterpret_cast<char*>(temporary_storage);
auto ordered_bid = ordered_block_id_type::create(
reinterpret_cast<ordered_block_id_type::id_type*>(ptr + offset_scan_state_bytes)
);
if(debug_synchronous) start = std::chrono::high_resolution_clock::now();
auto grid_size = (number_of_blocks + block_size - 1)/block_size;
hipLaunchKernelGGL(
HIP_KERNEL_NAME(init_offset_scan_state_kernel<offset_scan_state_type>),
dim3(grid_size), dim3(block_size), 0, stream,
offset_scan_state, number_of_blocks, ordered_bid
);
ROCPRIM_DETAIL_HIP_SYNC_AND_RETURN_ON_ERROR("init_offset_scan_state_kernel", size, start)
if(debug_synchronous) start = std::chrono::high_resolution_clock::now();
grid_size = number_of_blocks;
hipLaunchKernelGGL(
HIP_KERNEL_NAME(partition_kernel<
SelectMethod, OnlySelected, config, result_type,
InputIterator, FlagIterator, OutputIterator, SelectedCountOutputIterator,
UnaryPredicate, decltype(inequality_op), offset_scan_state_type
>),
dim3(grid_size), dim3(block_size), 0, stream,
input, flags, output, selected_count_output, size, predicate,
inequality_op, offset_scan_state, number_of_blocks, ordered_bid
);
ROCPRIM_DETAIL_HIP_SYNC_AND_RETURN_ON_ERROR("partition_kernel", size, start)
return hipSuccess;
}
#undef ROCPRIM_DETAIL_HIP_SYNC_AND_RETURN_ON_ERROR
#undef ROCPRIM_DETAIL_HIP_SYNC
} // end of detail namespace
/// \brief HIP parallel select primitive for device level using range of flags.
///
/// Performs a device-wide partition based on input \p flags. Partition copies
/// the values from \p input to \p output in such a way that all values for which the corresponding
/// items from /p flags are \p true (or can be implicitly converted to \p true) precede
/// the elements for which the corresponding items from /p flags are \p false.
///
/// \par Overview
/// * Returns the required size of \p temporary_storage in \p storage_size
/// if \p temporary_storage in a null pointer.
/// * Ranges specified by \p input, \p flags and \p output must have at least \p size elements.
/// * Range specified by \p selected_count_output must have at least 1 element.
/// * Values of \p flag range should be implicitly convertible to `bool` type.
/// * Relative order is preserved for the elements for which the corresponding values from \p flags
/// are \p true. Other elements are copied in reverse order.
///
/// \tparam Config - [optional] configuration of the primitive. It can be \p select_config or
/// a custom class with the same members.
/// \tparam InputIterator - random-access iterator type of the input range. It can be
/// a simple pointer type.
/// \tparam FlagIterator - random-access iterator type of the flag range. It can be
/// a simple pointer type.
/// \tparam OutputIterator - random-access iterator type of the output range. It can be
/// a simple pointer type.
/// \tparam SelectedCountOutputIterator - random-access iterator type of the selected_count_output
/// value. It can be a simple pointer type.
///
/// \param [in] temporary_storage - pointer to a device-accessible temporary storage. When
/// a null pointer is passed, the required allocation size (in bytes) is written to
/// \p storage_size and function returns without performing the select operation.
/// \param [in,out] storage_size - reference to a size (in bytes) of \p temporary_storage.
/// \param [in] input - iterator to the first element in the range to select values from.
/// \param [in] flags - iterator to the selection flag corresponding to the first element from \p input range.
/// \param [out] output - iterator to the first element in the output range.
/// \param [out] selected_count_output - iterator to the total number of selected values (length of \p output).
/// \param [in] size - number of element in the input range.
/// \param [in] stream - [optional] HIP stream object. The default is \p 0 (default stream).
/// \param [in] debug_synchronous - [optional] If true, synchronization after every kernel
/// launch is forced in order to check for errors. The default value is \p false.
///
/// \par Example
/// \parblock
/// In this example a device-level partition operation is performed on an array of
/// integer values with array of <tt>char</tt>s used as flags.
///
/// \code{.cpp}
/// #include <rocprim/rocprim.hpp>
///
/// // Prepare input and output (declare pointers, allocate device memory etc.)
/// size_t input_size; // e.g., 8
/// int * input; // e.g., [1, 2, 3, 4, 5, 6, 7, 8]
/// char * flags; // e.g., [0, 1, 1, 0, 0, 1, 0, 1]
/// int * output; // empty array of 8 elements
/// size_t * output_count; // empty array of 1 element
///
/// size_t temporary_storage_size_bytes;
/// void * temporary_storage_ptr = nullptr;
/// // Get required size of the temporary storage
/// rocprim::partition(
/// temporary_storage_ptr, temporary_storage_size_bytes,
/// input, flags,
/// output, output_count,
/// input_size
/// );
///
/// // allocate temporary storage
/// hipMalloc(&temporary_storage_ptr, temporary_storage_size_bytes);
///
/// // perform partition
/// rocprim::partition(
/// temporary_storage_ptr, temporary_storage_size_bytes,
/// input, flags,
/// output, output_count,
/// input_size
/// );
/// // output: [2, 3, 6, 8, 7, 5, 4, 1]
/// // output_count: 4
/// \endcode
/// \endparblock
template<
class Config = default_config,
class InputIterator,
class FlagIterator,
class OutputIterator,
class SelectedCountOutputIterator
>
inline
hipError_t partition(void * temporary_storage,
size_t& storage_size,
InputIterator input,
FlagIterator flags,
OutputIterator output,
SelectedCountOutputIterator selected_count_output,
const size_t size,
const hipStream_t stream = 0,
const bool debug_synchronous = false)
{
// Dummy unary predicate
using unary_predicate_type = ::rocprim::empty_type;
// Dummy inequality operation
using inequality_op_type = ::rocprim::empty_type;
return detail::partition_impl<detail::select_method::flag, false, Config>(
temporary_storage, storage_size, input, flags, output, selected_count_output,
size, unary_predicate_type(), inequality_op_type(), stream, debug_synchronous
);
}
/// \brief HIP parallel select primitive for device level using selection predicate.
///
/// Performs a device-wide partition using selection predicate. Partition copies
/// the values from \p input to \p output in such a way that all values for which
/// the \p predicate returns \p true precede the elements for which it returns \p false.
///
/// \par Overview
/// * Returns the required size of \p temporary_storage in \p storage_size
/// if \p temporary_storage in a null pointer.
/// * Ranges specified by \p input, \p flags and \p output must have at least \p size elements.
/// * Range specified by \p selected_count_output must have at least 1 element.
/// * Relative order is preserved for the elements for which the \p predicate returns \p true. Other
/// elements are copied in reverse order.
///
/// \tparam Config - [optional] configuration of the primitive. It can be \p select_config or
/// a custom class with the same members.
/// \tparam InputIterator - random-access iterator type of the input range. It can be
/// a simple pointer type.
/// \tparam OutputIterator - random-access iterator type of the output range. It can be
/// a simple pointer type.
/// \tparam SelectedCountOutputIterator - random-access iterator type of the selected_count_output
/// value. It can be a simple pointer type.
/// \tparam UnaryPredicate - type of a unary selection predicate.
///
/// \param [in] temporary_storage - pointer to a device-accessible temporary storage. When
/// a null pointer is passed, the required allocation size (in bytes) is written to
/// \p storage_size and function returns without performing the select operation.
/// \param [in,out] storage_size - reference to a size (in bytes) of \p temporary_storage.
/// \param [in] input - iterator to the first element in the range to select values from.
/// \param [out] output - iterator to the first element in the output range.
/// \param [out] selected_count_output - iterator to the total number of selected values (length of \p output).
/// \param [in] size - number of element in the input range.
/// \param [in] predicate - unary function object which returns /p true if the element should be
/// ordered before other elements.
/// The signature of the function should be equivalent to the following:
/// <tt>bool f(const T &a);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the object passed to it.
/// \param [in] stream - [optional] HIP stream object. The default is \p 0 (default stream).
/// \param [in] debug_synchronous - [optional] If true, synchronization after every kernel
/// launch is forced in order to check for errors. The default value is \p false.
///
/// \par Example
/// \parblock
/// In this example a device-level partition operation is performed on an array of
/// integer values, even values are copied before odd values.
///
/// \code{.cpp}
/// #include <rocprim/rocprim.hpp>///
///
/// auto predicate =
/// [] __device__ (int a) -> bool
/// {
/// return (a%2) == 0;
/// };
///
/// // Prepare input and output (declare pointers, allocate device memory etc.)
/// size_t input_size; // e.g., 8
/// int * input; // e.g., [1, 2, 3, 4, 5, 6, 7, 8]
/// int * output; // empty array of 8 elements
/// size_t * output_count; // empty array of 1 element
///
/// size_t temporary_storage_size_bytes;
/// void * temporary_storage_ptr = nullptr;
/// // Get required size of the temporary storage
/// rocprim::partition(
/// temporary_storage_ptr, temporary_storage_size_bytes,
/// input,
/// output, output_count,
/// input_size,
/// predicate
/// );
///
/// // allocate temporary storage
/// hipMalloc(&temporary_storage_ptr, temporary_storage_size_bytes);
///
/// // perform partition
/// rocprim::partition(
/// temporary_storage_ptr, temporary_storage_size_bytes,
/// input,
/// output, output_count,
/// input_size,
/// predicate
/// );
/// // output: [2, 4, 6, 8, 7, 5, 3, 1]
/// // output_count: 4
/// \endcode
/// \endparblock
template<
class Config = default_config,
class InputIterator,
class OutputIterator,
class SelectedCountOutputIterator,
class UnaryPredicate
>
inline
hipError_t partition(void * temporary_storage,
size_t& storage_size,
InputIterator input,
OutputIterator output,
SelectedCountOutputIterator selected_count_output,
const size_t size,
UnaryPredicate predicate,
const hipStream_t stream = 0,
const bool debug_synchronous = false)
{
// Dummy flag type
using flag_type = ::rocprim::empty_type;
flag_type * flags = nullptr;
// Dummy inequality operation
using inequality_op_type = ::rocprim::empty_type;
return detail::partition_impl<detail::select_method::predicate, false, Config>(
temporary_storage, storage_size, input, flags, output, selected_count_output,
size, predicate, inequality_op_type(), stream, debug_synchronous
);
}
/// @}
// end of group devicemodule_hip
END_ROCPRIM_NAMESPACE
#endif // ROCPRIM_DEVICE_DEVICE_PARTITION_HIP_HPP_
| 42.378723 | 111 | 0.68526 | [
"object"
] |
81259284fa6647e3ec4fcb9d0301555978cb04ba | 8,775 | cpp | C++ | extras/elemlist/elemlist.cpp | dillionhacker/python222 | 205414c33fba8166167fd8a6a03eda1a68f16316 | [
"Apache-2.0"
] | 1 | 2022-03-17T13:55:02.000Z | 2022-03-17T13:55:02.000Z | extras/elemlist/elemlist.cpp | tuankien2601/python222 | 205414c33fba8166167fd8a6a03eda1a68f16316 | [
"Apache-2.0"
] | null | null | null | extras/elemlist/elemlist.cpp | tuankien2601/python222 | 205414c33fba8166167fd8a6a03eda1a68f16316 | [
"Apache-2.0"
] | null | null | null | /* Portions Copyright (c) 2005 Nokia Corporation
A simple extension used in the Porting an Extension example.
*/
/*
This extension module implements a new native type, the "cons
cell", that is very similar to the cons cells used in Lisp.
This code illustrates some of the issues that arise when creating
extensions for Python for Series 60. The code is derived from the
example extension written by Alex Martelli for the Python
Cookbook. The original code is licensed under the Python license,
which is available at http://www.python.org/license.
All parts that had to be modified from the original have
been clearly marked. A summary of modifications:
- Since Symbian DLL's don't (properly) support global writable
data, the type object is allocated dynamically and filled in from a
const template. Also, the function table for the module has been
declared const.
- The macro versions of memory allocation routines (PyObject_NEW,
PyObject_DEL and others) are not supported in Python for Series 60
1.0, so the non-macro versions, PyObject_New, PyObject_Del must be
used instead.
- The file has been compiled with the C++ compiler, to make it
possible to include Symbian headers.
*/
#include "Python.h"
/*******************************************************
This include file declares the SPyGetGlobalString and
SPySetGlobalString functions: */
#include "symbian_python_ext_util.h"
/* Standard Symbian definitions: */
#include <e32std.h>
/*******************************************************/
/* type-definition & utility-macros */
typedef struct {
PyObject_HEAD
PyObject *car, *cdr;
} cons_cell;
/*******************************************************
Original definition:
staticforward PyTypeObject cons_type;
Symbian doesn't support writable global data in DLL's, so
this type object has to be stored in another way. We
choose to allocate it dynamically in the module init
function and to bind it to a global name, so that we can
access it with the SPyGetGlobalString function. For
convenience, we define a macro that encapsulates the use
of that function. Naming a macro in all lowercase
violates the standard naming convention for macros, but
allows you to keep the code that handles the type
unchanged, which may be convenient if the same source
code is used on multiple platforms. You will have to
decide for yourself if this is too unsavoury for your
tastes. */
#define cons_type (*(PyTypeObject *)SPyGetGlobalString("consType"))
/*******************************************************/
/* a typetesting macro (we don't use it here) */
#define is_cons(v) ((v)->ob_type == &cons_type)
/* macros to access car & cdr, both as lvalues & rvalues */
#define carof(v) (((cons_cell*)(v))->car)
#define cdrof(v) (((cons_cell*)(v))->cdr)
/* ctor (factory-function) and dtor */
static cons_cell*
cons_new(PyObject *car, PyObject *cdr)
{
/*******************************************************
Original code:
cons_cell *cons = PyObject_NEW(cons_cell, &cons_type);
The macro versions of memory allocation routines
(PyObject_NEW, PyObject_DEL and others) are not supported
in Python for Series 60 1.0, so the non-macro versions,
PyObject_New, PyObject_Del must be used instead.
The Python documentation states that the use of these macros in
extensions is bad practice in any case, since it ties the
extension to the behaviour of the interpreter in unpredictable
ways. */
cons_cell *cons = PyObject_New(cons_cell, &cons_type);
/*******************************************************/
if(cons) {
cons->car = car; Py_INCREF(car); /* INCREF when holding a PyObject* */
cons->cdr = cdr; Py_INCREF(cdr); /* ditto */
}
return cons;
}
static void
cons_dealloc(cons_cell* cons)
{
/* DECREF when releasing previously-held PyObject*'s */
Py_DECREF(carof(cons)); Py_DECREF(cdrof(cons));
/*******************************************************
Original code:
PyObject_DEL(cons);
See the note on PyObject_NEW.*/
PyObject_Del(cons);
/*******************************************************/
}
/* Python type-object */
/*******************************************************
Original definition:
statichere PyTypeObject cons_type = {
As mentioned above, Symbian doesn't support _writable_
global data in DLL's, so we store this partially
initialized type object as constant data. In the module
init function this is copied to a dynamically allocated,
writable memory region. Note the name change to avoid
clashing with the macro cons_type defined above. */
static const PyTypeObject cons_type_template = {
/*******************************************************/
PyObject_HEAD_INIT(0) /* initialize to 0 to ensure Win32 portability */
0, /*ob_size*/
"cons", /*tp_name*/
sizeof(cons_cell), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)cons_dealloc, /*tp_dealloc*/
/* implied by ISO C: all zeros thereafter */
};
/* module-functions */
static PyObject*
cons(PyObject *self, PyObject *args) /* the exposed factory-function */
{
PyObject *car, *cdr;
if(!PyArg_ParseTuple(args, "OO", &car, &cdr))
return 0;
return (PyObject*)cons_new(car, cdr);
}
static PyObject*
car(PyObject *self, PyObject *args) /* car-accessor */
{
PyObject *cons;
if(!PyArg_ParseTuple(args, "O!", &cons_type, &cons)) /* type-checked */
return 0;
return Py_BuildValue("O", carof(cons));
}
static PyObject*
cdr(PyObject *self, PyObject *args) /* cdr-accessor */
{
PyObject *cons;
if(!PyArg_ParseTuple(args, "O!", &cons_type, &cons)) /* type-checked */
return 0;
return Py_BuildValue("O", cdrof(cons));
}
/*******************************************************
Original definition:
static PyMethodDef elemlist_methods[] = {
Since no one needs to write to this particular array,
we can make the code work simply by adding "const".
There's no need to copy the data. */
static const PyMethodDef elemlist_methods[] = {
/*******************************************************/
{"cons", cons, METH_VARARGS},
{"car", car, METH_VARARGS},
{"cdr", cdr, METH_VARARGS},
{0, 0}
};
/* module entry-point (module-initialization) function */
/*******************************************************
Original definition:
void initelemlist(void)
We have to explicitly state that this function must be
included in the public function list of the DLL. Symbian
DLL's don't include names of the exported functions; the
program that loads a DLL has to know the the index of the
function in the function table, commonly known as the
ordinal of the function, to call the functions in the
DLL.
The initialization function for a Python module _must_ be
exported at ordinal 1. If the module exports just the
initializer function, then there is nothing to worry
about. If you also export a module finalizer function,
you will have to make sure that the initializer is
exported at ordinal 1 and the finalizer at ordinal 2.
This module has just the initializer function.
Also, the function has to be declared extern "C":*/
extern "C" {
DL_EXPORT(void) initelemlist(void)
/*******************************************************/
{
/* Create the module and add the functions */
/*******************************************************
Original code:
PyObject *m = Py_InitModule("elemlist", elemlist_methods);
The Python/C API is unfortunately not quite const-correct, so
we need to add a cast here to make the compiler happy:*/
PyObject *m = Py_InitModule("elemlist", (PyMethodDef*)elemlist_methods);
/*******************************************************/
/* Finish initializing the type-objects */
/*******************************************************
Allocate storage for the type object, fill it in
from the constant template and bind it to a name in the
module namespace: */
PyTypeObject *consTypeObject=PyObject_New(PyTypeObject, &PyType_Type);
*consTypeObject=cons_type_template;
SPyAddGlobalString("consType", (PyObject *)consTypeObject);
/*******************************************************/
cons_type.ob_type = &PyType_Type;
}
}
/*******************************************************
This function is mandatory in Symbian DLL's. */
GLDEF_C TInt E32Dll(TDllReason)
{
return KErrNone;
}
/*******************************************************/
| 37.182203 | 79 | 0.608205 | [
"object"
] |
8125f55fa1c514c90146fc668ed2a66de532d218 | 519 | cpp | C++ | src/training_batch.cpp | shibii/nn | 2022ec423c3bfe179997630d6ba705aeaabdd918 | [
"MIT"
] | 1 | 2020-11-17T14:25:28.000Z | 2020-11-17T14:25:28.000Z | src/training_batch.cpp | shibii/nn | 2022ec423c3bfe179997630d6ba705aeaabdd918 | [
"MIT"
] | null | null | null | src/training_batch.cpp | shibii/nn | 2022ec423c3bfe179997630d6ba705aeaabdd918 | [
"MIT"
] | null | null | null | #include "training_batch.hpp"
namespace nn {
TrainingBatch::TrainingBatch(std::vector<float> sample_data,
DataShape sample_dim,
std::vector<float> target_data,
DataShape target_dim) {
samples_ = af::array(sample_dim, sample_data.data());
targets_ = af::array(target_dim, target_data.data());
}
TrainingBatch::TrainingBatch(af::array samples, af::array targets) {
samples_ = samples;
targets_ = targets;
}
} // namespace nn | 34.6 | 68 | 0.624277 | [
"vector"
] |
8126ff941d0c0946637f473cca504b392aa2ec92 | 58,212 | cpp | C++ | src/streamer.cpp | theSpool/samp-streamer-plugin | 02f4b15318471f57061349aebbc63a13eb72e1e9 | [
"Apache-2.0"
] | null | null | null | src/streamer.cpp | theSpool/samp-streamer-plugin | 02f4b15318471f57061349aebbc63a13eb72e1e9 | [
"Apache-2.0"
] | null | null | null | src/streamer.cpp | theSpool/samp-streamer-plugin | 02f4b15318471f57061349aebbc63a13eb72e1e9 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2017 Incognito
*
* 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 "precompiled.h"
#include "streamer.h"
#include "core.h"
Streamer::Streamer()
{
averageElapsedTime = 0.0f;
lastUpdateTime = 0.0f;
tickCount = 0;
tickRate = 50;
velocityBoundaries = boost::make_tuple(0.25f, 7.5f);
}
void Streamer::calculateAverageElapsedTime()
{
boost::chrono::steady_clock::time_point currentTime = boost::chrono::steady_clock::now();
static boost::chrono::steady_clock::time_point lastRecordedTime;
static Eigen::Array<float, 5, 1> recordedTimes = Eigen::Array<float, 5, 1>::Zero();
if (lastRecordedTime.time_since_epoch().count())
{
if (!(recordedTimes > 0).all())
{
boost::chrono::duration<float> elapsedTime = currentTime - lastRecordedTime;
recordedTimes[(recordedTimes > 0).count()] = elapsedTime.count();
}
else
{
averageElapsedTime = recordedTimes.mean() * 50.0f;
recordedTimes.setZero();
}
}
lastRecordedTime = currentTime;
}
void Streamer::startAutomaticUpdate()
{
if (!core->getData()->interfaces.empty())
{
boost::chrono::steady_clock::time_point currentTime = boost::chrono::steady_clock::now();
if (!core->getData()->players.empty())
{
bool updatedActiveItems = false;
for (boost::unordered_map<int, Player>::iterator p = core->getData()->players.begin(); p != core->getData()->players.end(); ++p)
{
if (core->getChunkStreamer()->getChunkStreamingEnabled() && p->second.processingChunks.any())
{
core->getChunkStreamer()->performPlayerChunkUpdate(p->second, true);
}
else
{
if (++p->second.tickCount >= p->second.tickRate)
{
if (!updatedActiveItems)
{
processActiveItems();
updatedActiveItems = true;
}
if (!p->second.delayedUpdate)
{
performPlayerUpdate(p->second, true);
}
else
{
startManualUpdate(p->second, p->second.delayedUpdateType);
}
p->second.tickCount = 0;
}
}
}
}
else
{
processActiveItems();
}
if (++tickCount >= tickRate)
{
for (boost::unordered_map<int, Player>::iterator p = core->getData()->players.begin(); p != core->getData()->players.end(); ++p)
{
std::vector<SharedCell> cells;
core->getGrid()->findMinimalCellsForPlayer(p->second, cells);
for (std::vector<int>::const_iterator t = core->getData()->typePriority.begin(); t != core->getData()->typePriority.end(); ++t)
{
switch (*t)
{
case STREAMER_TYPE_PICKUP:
{
if (!core->getData()->pickups.empty() && p->second.enabledItems[STREAMER_TYPE_PICKUP])
{
discoverPickups(p->second, cells);
}
break;
}
case STREAMER_TYPE_ACTOR:
{
if (!core->getData()->actors.empty() && p->second.enabledItems[STREAMER_TYPE_ACTOR])
{
discoverActors(p->second, cells);
}
break;
}
}
}
}
for (std::vector<int>::const_iterator t = core->getData()->typePriority.begin(); t != core->getData()->typePriority.end(); ++t)
{
switch (*t)
{
case STREAMER_TYPE_PICKUP:
{
streamPickups();
break;
}
case STREAMER_TYPE_ACTOR:
{
Utility::processPendingDestroyedActors();
streamActors();
break;
}
}
}
executeCallbacks();
tickCount = 0;
}
calculateAverageElapsedTime();
lastUpdateTime = boost::chrono::duration<float, boost::milli>(boost::chrono::steady_clock::now() - currentTime).count();
}
}
void Streamer::startManualUpdate(Player &player, int type)
{
std::bitset<STREAMER_MAX_TYPES> enabledItems = player.enabledItems;
if (player.delayedUpdate)
{
if (player.delayedUpdateTime.time_since_epoch() <= boost::chrono::steady_clock::now().time_since_epoch())
{
if (player.delayedUpdateFreeze)
{
sampgdk::TogglePlayerControllable(player.playerId, true);
}
player.delayedUpdate = false;
}
}
if (type >= 0 && type < STREAMER_MAX_TYPES)
{
if (core->getChunkStreamer()->getChunkStreamingEnabled())
{
switch (type)
{
case STREAMER_TYPE_OBJECT:
{
player.discoveredObjects.clear();
player.existingObjects.clear();
player.processingChunks.reset(STREAMER_TYPE_OBJECT);
break;
}
case STREAMER_TYPE_MAP_ICON:
{
player.discoveredMapIcons.clear();
player.existingMapIcons.clear();
player.processingChunks.reset(STREAMER_TYPE_MAP_ICON);
break;
}
case STREAMER_TYPE_3D_TEXT_LABEL:
{
player.discoveredTextLabels.clear();
player.existingTextLabels.clear();
player.processingChunks.reset(STREAMER_TYPE_3D_TEXT_LABEL);
break;
}
}
}
player.enabledItems.reset();
player.enabledItems.set(type);
}
else if (core->getChunkStreamer()->getChunkStreamingEnabled())
{
player.discoveredMapIcons.clear();
player.discoveredObjects.clear();
player.discoveredTextLabels.clear();
player.existingMapIcons.clear();
player.existingObjects.clear();
player.existingTextLabels.clear();
player.processingChunks.reset();
}
processActiveItems();
performPlayerUpdate(player, false);
if (core->getChunkStreamer()->getChunkStreamingEnabled())
{
core->getChunkStreamer()->performPlayerChunkUpdate(player, false);
}
player.enabledItems = enabledItems;
}
void Streamer::performPlayerUpdate(Player &player, bool automatic)
{
Eigen::Vector3f delta = Eigen::Vector3f::Zero(), position = player.position;
bool update = true;
if (automatic)
{
player.interiorId = sampgdk::GetPlayerInterior(player.playerId);
player.worldId = sampgdk::GetPlayerVirtualWorld(player.playerId);
if (!player.updateUsingCameraPosition)
{
int state = sampgdk::GetPlayerState(player.playerId);
sampgdk::logprintf("the state: %d of playerid %d", state, player.playerId);
if ((state != PLAYER_STATE_NONE && state != PLAYER_STATE_WASTED) || (state == PLAYER_STATE_SPECTATING && !player.requestingClass))
{
if (!sampgdk::IsPlayerInAnyVehicle(player.playerId))
{
sampgdk::GetPlayerPos(player.playerId, &player.position[0], &player.position[1], &player.position[2]);
sampgdk::logprintf("position: %f %f %f", player.position[0], player.position[1], player.position[2]);
}
else
{
sampgdk::GetVehiclePos(sampgdk::GetPlayerVehicleID(player.playerId), &player.position[0], &player.position[1], &player.position[2]);
}
if (player.position != position)
{
position = player.position;
Eigen::Vector3f velocity = Eigen::Vector3f::Zero();
if (state == PLAYER_STATE_ONFOOT)
{
sampgdk::GetPlayerVelocity(player.playerId, &velocity[0], &velocity[1], &velocity[2]);
}
else if (state == PLAYER_STATE_DRIVER || state == PLAYER_STATE_PASSENGER)
{
sampgdk::GetVehicleVelocity(sampgdk::GetPlayerVehicleID(player.playerId), &velocity[0], &velocity[1], &velocity[2]);
}
float velocityNorm = velocity.squaredNorm();
if (velocityNorm > velocityBoundaries.get<0>() && velocityNorm < velocityBoundaries.get<1>())
{
delta = velocity * averageElapsedTime;
}
}
else
{
update = player.updateWhenIdle;
sampgdk::logprintf("update to false 1");
}
}
else
{
update = false;
sampgdk::logprintf("update to false 2");
}
}
else
{
sampgdk::GetPlayerCameraPos(player.playerId, &player.position[0], &player.position[1], &player.position[2]);
}
if (player.delayedCheckpoint)
{
boost::unordered_map<int, Item::SharedCheckpoint>::iterator c = core->getData()->checkpoints.find(player.delayedCheckpoint);
if (c != core->getData()->checkpoints.end())
{
sampgdk::SetPlayerCheckpoint(player.playerId, c->second->position[0], c->second->position[1], c->second->position[2], c->second->size);
if (c->second->streamCallbacks)
{
streamInCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_CP, c->first, player.playerId));
}
player.visibleCheckpoint = c->first;
}
player.delayedCheckpoint = 0;
}
else if (player.delayedRaceCheckpoint)
{
boost::unordered_map<int, Item::SharedRaceCheckpoint>::iterator r = core->getData()->raceCheckpoints.find(player.delayedRaceCheckpoint);
if (r != core->getData()->raceCheckpoints.end())
{
sampgdk::SetPlayerRaceCheckpoint(player.playerId, r->second->type, r->second->position[0], r->second->position[1], r->second->position[2], r->second->next[0], r->second->next[1], r->second->next[2], r->second->size);
if (r->second->streamCallbacks)
{
streamInCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_RACE_CP, r->first, player.playerId));
}
player.visibleRaceCheckpoint = r->first;
}
player.delayedRaceCheckpoint = 0;
}
}
std::vector<SharedCell> cells;
if (update)
{
core->getGrid()->findAllCellsForPlayer(player, cells);
}
else
{
core->getGrid()->findMinimalCellsForPlayer(player, cells);
}
if (!cells.empty())
{
if (!delta.isZero())
{
player.position += delta;
}
for (std::vector<int>::const_iterator t = core->getData()->typePriority.begin(); t != core->getData()->typePriority.end(); ++t)
{
sampgdk::logprintf("123 update = %d", update);
if (update)
{
switch (*t)
{
case STREAMER_TYPE_OBJECT:
{
if (!core->getData()->objects.empty() && player.enabledItems[STREAMER_TYPE_OBJECT])
{
if (core->getChunkStreamer()->getChunkStreamingEnabled())
{
core->getChunkStreamer()->discoverObjects(player, cells);
}
else
{
processObjects(player, cells);
}
}
break;
}
case STREAMER_TYPE_CP:
{
if (!core->getData()->checkpoints.empty() && player.enabledItems[STREAMER_TYPE_CP])
{
processCheckpoints(player, cells);
}
break;
}
case STREAMER_TYPE_RACE_CP:
{
if (!core->getData()->raceCheckpoints.empty() && player.enabledItems[STREAMER_TYPE_RACE_CP])
{
processRaceCheckpoints(player, cells);
}
break;
}
case STREAMER_TYPE_MAP_ICON:
{
if (!core->getData()->mapIcons.empty() && player.enabledItems[STREAMER_TYPE_MAP_ICON])
{
if (core->getChunkStreamer()->getChunkStreamingEnabled())
{
core->getChunkStreamer()->discoverMapIcons(player, cells);
}
else
{
processMapIcons(player, cells);
}
}
break;
}
case STREAMER_TYPE_3D_TEXT_LABEL:
{
sampgdk::logprintf("stream 3d labels");
if (!core->getData()->textLabels.empty() && player.enabledItems[STREAMER_TYPE_3D_TEXT_LABEL])
{
if (core->getChunkStreamer()->getChunkStreamingEnabled())
{
core->getChunkStreamer()->discoverTextLabels(player, cells);
}
else
{
processTextLabels(player, cells);
}
}
break;
}
case STREAMER_TYPE_AREA:
{
if (!core->getData()->areas.empty() && player.enabledItems[STREAMER_TYPE_AREA])
{
if (!delta.isZero())
{
player.position = position;
}
processAreas(player, cells);
if (!delta.isZero())
{
player.position += delta;
}
}
break;
}
}
}
}
if (!delta.isZero())
{
player.position = position;
}
}
}
void Streamer::executeCallbacks()
{
if (!areaLeaveCallbacks.empty())
{
std::multimap<int, boost::tuple<int, int> > callbacks;
std::swap(areaLeaveCallbacks, callbacks);
for (std::multimap<int, boost::tuple<int, int> >::reverse_iterator c = callbacks.rbegin(); c != callbacks.rend(); ++c)
{
boost::unordered_map<int, Item::SharedArea>::iterator a = core->getData()->areas.find(c->second.get<0>());
if (a != core->getData()->areas.end())
{
for (std::set<AMX*>::iterator i = core->getData()->interfaces.begin(); i != core->getData()->interfaces.end(); ++i)
{
int amxIndex = 0;
if (!amx_FindPublic(*i, "OnPlayerLeaveDynamicArea", &amxIndex))
{
amx_Push(*i, static_cast<cell>(c->second.get<0>()));
amx_Push(*i, static_cast<cell>(c->second.get<1>()));
amx_Exec(*i, NULL, amxIndex);
}
}
}
}
}
if (!areaEnterCallbacks.empty())
{
std::multimap<int, boost::tuple<int, int> > callbacks;
std::swap(areaEnterCallbacks, callbacks);
for (std::multimap<int, boost::tuple<int, int> >::reverse_iterator c = callbacks.rbegin(); c != callbacks.rend(); ++c)
{
boost::unordered_map<int, Item::SharedArea>::iterator a = core->getData()->areas.find(c->second.get<0>());
if (a != core->getData()->areas.end())
{
for (std::set<AMX*>::iterator i = core->getData()->interfaces.begin(); i != core->getData()->interfaces.end(); ++i)
{
int amxIndex = 0;
if (!amx_FindPublic(*i, "OnPlayerEnterDynamicArea", &amxIndex))
{
amx_Push(*i, static_cast<cell>(c->second.get<0>()));
amx_Push(*i, static_cast<cell>(c->second.get<1>()));
amx_Exec(*i, NULL, amxIndex);
}
}
}
}
}
if (!objectMoveCallbacks.empty())
{
std::vector<int> callbacks;
std::swap(objectMoveCallbacks, callbacks);
for (std::vector<int>::const_iterator c = callbacks.begin(); c != callbacks.end(); ++c)
{
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(*c);
if (o != core->getData()->objects.end())
{
for (std::set<AMX*>::iterator i = core->getData()->interfaces.begin(); i != core->getData()->interfaces.end(); ++i)
{
int amxIndex = 0;
if (!amx_FindPublic(*i, "OnDynamicObjectMoved", &amxIndex))
{
amx_Push(*i, static_cast<cell>(*c));
amx_Exec(*i, NULL, amxIndex);
}
}
}
}
}
if (!streamInCallbacks.empty())
{
std::vector<boost::tuple<int, int, int> > callbacks;
std::swap(streamInCallbacks, callbacks);
for (std::vector<boost::tuple<int, int, int> >::const_iterator c = callbacks.begin(); c != callbacks.end(); ++c)
{
switch (c->get<0>())
{
case STREAMER_TYPE_OBJECT:
{
if (core->getData()->objects.find(c->get<1>()) == core->getData()->objects.end())
{
continue;
}
break;
}
case STREAMER_TYPE_PICKUP:
{
if (core->getData()->pickups.find(c->get<1>()) == core->getData()->pickups.end())
{
continue;
}
break;
}
case STREAMER_TYPE_CP:
{
if (core->getData()->checkpoints.find(c->get<1>()) == core->getData()->checkpoints.end())
{
continue;
}
break;
}
case STREAMER_TYPE_RACE_CP:
{
if (core->getData()->raceCheckpoints.find(c->get<1>()) == core->getData()->raceCheckpoints.end())
{
continue;
}
break;
}
case STREAMER_TYPE_MAP_ICON:
{
if (core->getData()->mapIcons.find(c->get<1>()) == core->getData()->mapIcons.end())
{
continue;
}
break;
}
case STREAMER_TYPE_3D_TEXT_LABEL:
{
if (core->getData()->textLabels.find(c->get<1>()) == core->getData()->textLabels.end())
{
continue;
}
break;
}
}
for (std::set<AMX*>::iterator i = core->getData()->interfaces.begin(); i != core->getData()->interfaces.end(); ++i)
{
int amxIndex = 0;
if (!amx_FindPublic(*i, "Streamer_OnItemStreamIn", &amxIndex))
{
amx_Push(*i, static_cast<cell>(c->get<2>()));
amx_Push(*i, static_cast<cell>(c->get<1>()));
amx_Push(*i, static_cast<cell>(c->get<0>()));
amx_Exec(*i, NULL, amxIndex);
}
}
}
}
if (!streamOutCallbacks.empty())
{
std::vector<boost::tuple<int, int, int> > callbacks;
std::swap(streamOutCallbacks, callbacks);
for (std::vector<boost::tuple<int, int, int> >::const_iterator c = callbacks.begin(); c != callbacks.end(); ++c)
{
switch (c->get<0>())
{
case STREAMER_TYPE_OBJECT:
{
if (core->getData()->objects.find(c->get<1>()) == core->getData()->objects.end())
{
continue;
}
break;
}
case STREAMER_TYPE_PICKUP:
{
if (core->getData()->pickups.find(c->get<1>()) == core->getData()->pickups.end())
{
continue;
}
break;
}
case STREAMER_TYPE_CP:
{
if (core->getData()->checkpoints.find(c->get<1>()) == core->getData()->checkpoints.end())
{
continue;
}
break;
}
case STREAMER_TYPE_RACE_CP:
{
if (core->getData()->raceCheckpoints.find(c->get<1>()) == core->getData()->raceCheckpoints.end())
{
continue;
}
break;
}
case STREAMER_TYPE_MAP_ICON:
{
if (core->getData()->mapIcons.find(c->get<1>()) == core->getData()->mapIcons.end())
{
continue;
}
break;
}
case STREAMER_TYPE_3D_TEXT_LABEL:
{
if (core->getData()->textLabels.find(c->get<1>()) == core->getData()->textLabels.end())
{
continue;
}
break;
}
}
for (std::set<AMX*>::iterator i = core->getData()->interfaces.begin(); i != core->getData()->interfaces.end(); ++i)
{
int amxIndex = 0;
if (!amx_FindPublic(*i, "Streamer_OnItemStreamOut", &amxIndex))
{
amx_Push(*i, static_cast<cell>(c->get<2>()));
amx_Push(*i, static_cast<cell>(c->get<1>()));
amx_Push(*i, static_cast<cell>(c->get<0>()));
amx_Exec(*i, NULL, amxIndex);
}
}
}
}
}
void Streamer::discoverActors(Player &player, const std::vector<SharedCell> &cells)
{
if (!sampgdk::IsPlayerNPC(player.playerId))
{
for (std::vector<SharedCell>::const_iterator c = cells.begin(); c != cells.end(); ++c)
{
for (boost::unordered_map<int, Item::SharedActor>::const_iterator a = (*c)->actors.begin(); a != (*c)->actors.end(); ++a)
{
boost::unordered_set<int> worlds = a->second->worlds;
if (worlds.empty())
{
worlds.insert(-1);
}
for (boost::unordered_set<int>::const_iterator w = worlds.begin(); w != worlds.end(); ++w)
{
if (player.worldId != *w && *w != -1)
{
continue;
}
boost::unordered_map<std::pair<int, int>, Item::SharedActor>::iterator d = core->getData()->discoveredActors.find(std::make_pair(a->first, *w));
if (d == core->getData()->discoveredActors.end())
{
const int playerWorldId = *w == -1 ? -1 : player.worldId;
if (doesPlayerSatisfyConditions(a->second->players, player.playerId, a->second->interiors, player.interiorId, a->second->worlds, playerWorldId, a->second->areas, player.internalAreas, a->second->inverseAreaChecking))
{
if (a->second->comparableStreamDistance < STREAMER_STATIC_DISTANCE_CUTOFF || boost::geometry::comparable_distance(player.position, Eigen::Vector3f(a->second->position + a->second->positionOffset)) < (a->second->comparableStreamDistance * player.radiusMultipliers[STREAMER_TYPE_ACTOR]))
{
core->getData()->discoveredActors.insert(std::make_pair(std::make_pair(a->first, *w), a->second));
}
}
}
}
}
}
}
}
void Streamer::streamActors()
{
boost::unordered_map<std::pair<int, int>, int>::iterator i = core->getData()->internalActors.begin();
while (i != core->getData()->internalActors.end())
{
boost::unordered_map<std::pair<int, int>, Item::SharedActor>::iterator d = core->getData()->discoveredActors.find(i->first);
if (d == core->getData()->discoveredActors.end())
{
sampgdk::DestroyActor(i->second);
i = core->getData()->internalActors.erase(i);
}
else
{
core->getData()->discoveredActors.erase(d);
++i;
}
}
std::multimap<int, std::pair<int, Item::SharedActor> > sortedActors;
for (boost::unordered_map<std::pair<int, int>, Item::SharedActor>::iterator d = core->getData()->discoveredActors.begin(); d != core->getData()->discoveredActors.end(); ++d)
{
sortedActors.insert(std::make_pair(d->second->priority, std::make_pair(d->first.second, d->second)));
}
core->getData()->discoveredActors.clear();
for (std::multimap<int, std::pair<int, Item::SharedActor> >::iterator s = sortedActors.begin(); s != sortedActors.end(); ++s)
{
if (core->getData()->internalActors.size() == core->getData()->getGlobalMaxVisibleItems(STREAMER_TYPE_ACTOR))
{
break;
}
int internalId = sampgdk::CreateActor(s->second.second->modelId, s->second.second->position[0], s->second.second->position[1], s->second.second->position[2], s->second.second->rotation);
if (internalId == INVALID_ACTOR_ID)
{
break;
}
sampgdk::SetActorInvulnerable(internalId, s->second.second->invulnerable);
sampgdk::SetActorHealth(internalId, s->second.second->health);
sampgdk::SetActorVirtualWorld(internalId, s->second.first);
if (s->second.second->anim)
{
sampgdk::ApplyActorAnimation(internalId, s->second.second->anim->lib.c_str(), s->second.second->anim->name.c_str(), s->second.second->anim->delta, s->second.second->anim->loop, s->second.second->anim->lockx, s->second.second->anim->locky, s->second.second->anim->freeze, s->second.second->anim->time);
}
core->getData()->internalActors.insert(std::make_pair(std::make_pair(s->second.second->actorId, s->second.first), internalId));
}
}
void Streamer::processAreas(Player &player, const std::vector<SharedCell> &cells)
{
int state = sampgdk::GetPlayerState(player.playerId);
for (std::vector<SharedCell>::const_iterator c = cells.begin(); c != cells.end(); ++c)
{
for (boost::unordered_map<int, Item::SharedArea>::const_iterator a = (*c)->areas.begin(); a != (*c)->areas.end(); ++a)
{
Streamer::processPlayerArea(player, a->second, state);
}
}
}
bool Streamer::processPlayerArea(Player &player, const Item::SharedArea &a, const int state)
{
bool inArea = false;
if (doesPlayerSatisfyConditions(a->players, player.playerId, a->interiors, player.interiorId, a->worlds, player.worldId) && ((!a->spectateMode && state != PLAYER_STATE_SPECTATING) || a->spectateMode))
{
inArea = Utility::isPointInArea(player.position, a);
}
boost::unordered_set<int>::iterator foundArea = player.internalAreas.find(a->areaId);
if (inArea)
{
if (foundArea == player.internalAreas.end())
{
player.internalAreas.insert(a->areaId);
areaEnterCallbacks.insert(std::make_pair(a->priority, boost::make_tuple(a->areaId, player.playerId)));
}
if (a->cell)
{
player.visibleCell->areas.insert(std::make_pair(a->areaId, a));
}
}
else
{
if (foundArea != player.internalAreas.end())
{
player.internalAreas.erase(foundArea);
areaLeaveCallbacks.insert(std::make_pair(a->priority, boost::make_tuple(a->areaId, player.playerId)));
}
}
return inArea;
}
void Streamer::processCheckpoints(Player &player, const std::vector<SharedCell> &cells)
{
std::multimap<std::pair<int, float>, Item::SharedCheckpoint, Item::PairCompare> discoveredCheckpoints;
for (std::vector<SharedCell>::const_iterator c = cells.begin(); c != cells.end(); ++c)
{
for (boost::unordered_map<int, Item::SharedCheckpoint>::const_iterator d = (*c)->checkpoints.begin(); d != (*c)->checkpoints.end(); ++d)
{
float distance = std::numeric_limits<float>::infinity();
if (doesPlayerSatisfyConditions(d->second->players, player.playerId, d->second->interiors, player.interiorId, d->second->worlds, player.worldId, d->second->areas, player.internalAreas, d->second->inverseAreaChecking))
{
if (d->second->comparableStreamDistance < STREAMER_STATIC_DISTANCE_CUTOFF)
{
distance = std::numeric_limits<float>::infinity() * -1.0f;
}
else
{
distance = static_cast<float>(boost::geometry::comparable_distance(player.position, Eigen::Vector3f(d->second->position + d->second->positionOffset)));
}
}
if (distance < (d->second->comparableStreamDistance * player.radiusMultipliers[STREAMER_TYPE_CP]))
{
discoveredCheckpoints.insert(std::make_pair(std::make_pair(d->second->priority, distance), d->second));
}
else
{
if (d->first == player.visibleCheckpoint)
{
sampgdk::DisablePlayerCheckpoint(player.playerId);
if (d->second->streamCallbacks)
{
streamOutCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_CP, d->second->checkpointId, player.playerId));
}
player.activeCheckpoint = 0;
player.visibleCheckpoint = 0;
}
}
}
}
if (!discoveredCheckpoints.empty())
{
std::multimap<std::pair<int, float>, Item::SharedCheckpoint, Item::PairCompare>::iterator d = discoveredCheckpoints.begin();
if (d->second->checkpointId != player.visibleCheckpoint)
{
if (player.visibleCheckpoint)
{
sampgdk::DisablePlayerCheckpoint(player.playerId);
if (d->second->streamCallbacks)
{
streamOutCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_CP, d->second->checkpointId, player.playerId));
}
player.activeCheckpoint = 0;
}
player.delayedCheckpoint = d->second->checkpointId;
}
if (d->second->cell)
{
player.visibleCell->checkpoints.insert(std::make_pair(d->second->checkpointId, d->second));
}
}
}
void Streamer::processMapIcons(Player &player, const std::vector<SharedCell> &cells)
{
std::multimap<std::pair<int, float>, Item::SharedMapIcon, Item::PairCompare> discoveredMapIcons, existingMapIcons;
for (std::vector<SharedCell>::const_iterator c = cells.begin(); c != cells.end(); ++c)
{
for (boost::unordered_map<int, Item::SharedMapIcon>::const_iterator m = (*c)->mapIcons.begin(); m != (*c)->mapIcons.end(); ++m)
{
float distance = std::numeric_limits<float>::infinity();
if (doesPlayerSatisfyConditions(m->second->players, player.playerId, m->second->interiors, player.interiorId, m->second->worlds, player.worldId, m->second->areas, player.internalAreas, m->second->inverseAreaChecking))
{
if (m->second->comparableStreamDistance < STREAMER_STATIC_DISTANCE_CUTOFF)
{
distance = std::numeric_limits<float>::infinity() * -1.0f;
}
else
{
distance = static_cast<float>(boost::geometry::comparable_distance(player.position, Eigen::Vector3f(m->second->position + m->second->positionOffset)));
}
}
boost::unordered_map<int, int>::iterator i = player.internalMapIcons.find(m->first);
if (distance < (m->second->comparableStreamDistance * player.radiusMultipliers[STREAMER_TYPE_MAP_ICON]))
{
if (i == player.internalMapIcons.end())
{
discoveredMapIcons.insert(std::make_pair(std::make_pair(m->second->priority, distance), m->second));
}
else
{
if (m->second->cell)
{
player.visibleCell->mapIcons.insert(*m);
}
existingMapIcons.insert(std::make_pair(std::make_pair(m->second->priority, distance), m->second));
}
}
else
{
if (i != player.internalMapIcons.end())
{
sampgdk::RemovePlayerMapIcon(player.playerId, i->second);
if (m->second->streamCallbacks)
{
streamOutCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_MAP_ICON, m->first, player.playerId));
}
player.mapIconIdentifier.remove(i->second, player.internalMapIcons.size());
player.internalMapIcons.erase(i);
}
}
}
}
for (std::multimap<std::pair<int, float>, Item::SharedMapIcon, Item::PairCompare>::iterator d = discoveredMapIcons.begin(); d != discoveredMapIcons.end(); ++d)
{
boost::unordered_map<int, int>::iterator i = player.internalMapIcons.find(d->second->mapIconId);
if (i != player.internalMapIcons.end())
{
continue;
}
if (player.internalMapIcons.size() == player.maxVisibleMapIcons)
{
std::multimap<std::pair<int, float>, Item::SharedMapIcon, Item::PairCompare>::reverse_iterator e = existingMapIcons.rbegin();
if (e != existingMapIcons.rend())
{
if (e->first.first < d->first.first || (e->first.second > STREAMER_STATIC_DISTANCE_CUTOFF && d->first.second < e->first.second))
{
boost::unordered_map<int, int>::iterator j = player.internalMapIcons.find(e->second->mapIconId);
if (j != player.internalMapIcons.end())
{
sampgdk::RemovePlayerMapIcon(player.playerId, j->second);
if (e->second->streamCallbacks)
{
streamOutCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_MAP_ICON, e->second->mapIconId, player.playerId));
}
player.mapIconIdentifier.remove(j->second, player.internalMapIcons.size());
player.internalMapIcons.erase(j);
}
if (e->second->cell)
{
player.visibleCell->mapIcons.erase(e->second->mapIconId);
}
existingMapIcons.erase(--e.base());
}
}
if (player.internalMapIcons.size() == player.maxVisibleMapIcons)
{
break;
}
}
int internalId = player.mapIconIdentifier.get();
sampgdk::SetPlayerMapIcon(player.playerId, internalId, d->second->position[0], d->second->position[1], d->second->position[2], d->second->type, d->second->color, d->second->style);
if (d->second->streamCallbacks)
{
streamInCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_MAP_ICON, d->second->mapIconId, player.playerId));
}
player.internalMapIcons.insert(std::make_pair(d->second->mapIconId, internalId));
if (d->second->cell)
{
player.visibleCell->mapIcons.insert(std::make_pair(d->second->mapIconId, d->second));
}
}
}
void Streamer::processObjects(Player &player, const std::vector<SharedCell> &cells)
{
std::multimap<std::pair<int, float>, Item::SharedObject, Item::PairCompare> discoveredObjects, existingObjects;
for (std::vector<SharedCell>::const_iterator c = cells.begin(); c != cells.end(); ++c)
{
for (boost::unordered_map<int, Item::SharedObject>::const_iterator o = (*c)->objects.begin(); o != (*c)->objects.end(); ++o)
{
float distance = std::numeric_limits<float>::infinity();
if (doesPlayerSatisfyConditions(o->second->players, player.playerId, o->second->interiors, player.interiorId, o->second->attach ? o->second->attach->worlds : o->second->worlds, player.worldId, o->second->areas, player.internalAreas, o->second->inverseAreaChecking))
{
if (o->second->comparableStreamDistance < STREAMER_STATIC_DISTANCE_CUTOFF)
{
distance = std::numeric_limits<float>::infinity() * -1.0f;
}
else
{
if (o->second->attach)
{
distance = static_cast<float>(boost::geometry::comparable_distance(player.position, o->second->attach->position)) + std::numeric_limits<float>::epsilon();
}
else
{
distance = static_cast<float>(boost::geometry::comparable_distance(player.position, Eigen::Vector3f(o->second->position + o->second->positionOffset)));
}
}
}
boost::unordered_map<int, int>::iterator i = player.internalObjects.find(o->first);
if (distance < (o->second->comparableStreamDistance * player.radiusMultipliers[STREAMER_TYPE_OBJECT]))
{
if (i == player.internalObjects.end())
{
discoveredObjects.insert(std::make_pair(std::make_pair(o->second->priority, distance), o->second));
}
else
{
if (o->second->cell)
{
player.visibleCell->objects.insert(*o);
}
existingObjects.insert(std::make_pair(std::make_pair(o->second->priority, distance), o->second));
}
}
else
{
if (i != player.internalObjects.end())
{
sampgdk::DestroyPlayerObject(player.playerId, i->second);
if (o->second->streamCallbacks)
{
streamOutCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_OBJECT, o->first, player.playerId));
}
player.internalObjects.erase(i);
}
}
}
}
for (std::multimap<std::pair<int, float>, Item::SharedObject, Item::PairCompare>::iterator d = discoveredObjects.begin(); d != discoveredObjects.end(); ++d)
{
boost::unordered_map<int, int>::iterator i = player.internalObjects.find(d->second->objectId);
if (i != player.internalObjects.end())
{
continue;
}
int internalBaseId = INVALID_STREAMER_ID;
if (d->second->attach)
{
if (d->second->attach->object != INVALID_STREAMER_ID)
{
boost::unordered_map<int, int>::iterator j = player.internalObjects.find(d->second->attach->object);
if (j == player.internalObjects.end())
{
continue;
}
internalBaseId = j->second;
}
}
if (player.internalObjects.size() == player.currentVisibleObjects)
{
std::multimap<std::pair<int, float>, Item::SharedObject, Item::PairCompare>::reverse_iterator e = existingObjects.rbegin();
if (e != existingObjects.rend())
{
if (e->first.first < d->first.first || (e->first.second > STREAMER_STATIC_DISTANCE_CUTOFF && d->first.second < e->first.second))
{
boost::unordered_map<int, int>::iterator j = player.internalObjects.find(e->second->objectId);
if (j != player.internalObjects.end())
{
sampgdk::DestroyPlayerObject(player.playerId, j->second);
if (e->second->streamCallbacks)
{
streamOutCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_OBJECT, e->second->objectId, player.playerId));
}
player.internalObjects.erase(j);
}
if (e->second->cell)
{
player.visibleCell->objects.erase(e->second->objectId);
}
existingObjects.erase(--e.base());
}
}
}
if (player.internalObjects.size() == player.maxVisibleObjects)
{
player.currentVisibleObjects = player.internalObjects.size();
break;
}
int internalId = sampgdk::CreatePlayerObject(player.playerId, d->second->modelId, d->second->position[0], d->second->position[1], d->second->position[2], d->second->rotation[0], d->second->rotation[1], d->second->rotation[2], d->second->drawDistance);
if (internalId == INVALID_OBJECT_ID)
{
player.currentVisibleObjects = player.internalObjects.size();
break;
}
if (d->second->streamCallbacks)
{
streamInCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_OBJECT, d->second->objectId, player.playerId));
}
if (d->second->attach)
{
if (internalBaseId != INVALID_STREAMER_ID)
{
static AMX_NATIVE native = sampgdk::FindNative("AttachPlayerObjectToObject");
if (native != NULL)
{
sampgdk::InvokeNative(native, "dddffffffb", player.playerId, internalId, internalBaseId, d->second->attach->positionOffset[0], d->second->attach->positionOffset[1], d->second->attach->positionOffset[2], d->second->attach->rotation[0], d->second->attach->rotation[1], d->second->attach->rotation[2], d->second->attach->syncRotation);
}
}
else if (d->second->attach->player != INVALID_PLAYER_ID)
{
static AMX_NATIVE native = sampgdk::FindNative("AttachPlayerObjectToPlayer");
if (native != NULL)
{
sampgdk::InvokeNative(native, "dddffffffd", player.playerId, internalId, d->second->attach->player, d->second->attach->positionOffset[0], d->second->attach->positionOffset[1], d->second->attach->positionOffset[2], d->second->attach->rotation[0], d->second->attach->rotation[1], d->second->attach->rotation[2], 1);
}
}
else if (d->second->attach->vehicle != INVALID_VEHICLE_ID)
{
sampgdk::AttachPlayerObjectToVehicle(player.playerId, internalId, d->second->attach->vehicle, d->second->attach->positionOffset[0], d->second->attach->positionOffset[1], d->second->attach->positionOffset[2], d->second->attach->rotation[0], d->second->attach->rotation[1], d->second->attach->rotation[2]);
}
}
else if (d->second->move)
{
sampgdk::MovePlayerObject(player.playerId, internalId, d->second->move->position.get<0>()[0], d->second->move->position.get<0>()[1], d->second->move->position.get<0>()[2], d->second->move->speed, d->second->move->rotation.get<0>()[0], d->second->move->rotation.get<0>()[1], d->second->move->rotation.get<0>()[2]);
}
for (boost::unordered_map<int, Item::Object::Material>::iterator m = d->second->materials.begin(); m != d->second->materials.end(); ++m)
{
if (m->second.main)
{
sampgdk::SetPlayerObjectMaterial(player.playerId, internalId, m->first, m->second.main->modelId, m->second.main->txdFileName.c_str(), m->second.main->textureName.c_str(), m->second.main->materialColor);
}
else if (m->second.text)
{
sampgdk::SetPlayerObjectMaterialText(player.playerId, internalId, m->second.text->materialText.c_str(), m->first, m->second.text->materialSize, m->second.text->fontFace.c_str(), m->second.text->fontSize, m->second.text->bold, m->second.text->fontColor, m->second.text->backColor, m->second.text->textAlignment);
}
}
if (d->second->noCameraCollision)
{
sampgdk::SetPlayerObjectNoCameraCol(player.playerId, internalId);
}
player.internalObjects.insert(std::make_pair(d->second->objectId, internalId));
if (d->second->cell)
{
player.visibleCell->objects.insert(std::make_pair(d->second->objectId, d->second));
}
}
}
void Streamer::discoverPickups(Player &player, const std::vector<SharedCell> &cells)
{
for (std::vector<SharedCell>::const_iterator c = cells.begin(); c != cells.end(); ++c)
{
for (boost::unordered_map<int, Item::SharedPickup>::const_iterator p = (*c)->pickups.begin(); p != (*c)->pickups.end(); ++p)
{
boost::unordered_set<int> worlds = p->second->worlds;
if (worlds.empty())
{
worlds.insert(-1);
}
for (boost::unordered_set<int>::const_iterator w = worlds.begin(); w != worlds.end(); ++w)
{
if (player.worldId != *w && *w != -1)
{
continue;
}
boost::unordered_map<std::pair<int, int>, Item::SharedPickup>::iterator d = core->getData()->discoveredPickups.find(std::make_pair(p->first, *w));
if (d == core->getData()->discoveredPickups.end())
{
const int playerWorldId = *w == -1 ? -1 : player.worldId;
if (doesPlayerSatisfyConditions(p->second->players, player.playerId, p->second->interiors, player.interiorId, p->second->worlds, playerWorldId, p->second->areas, player.internalAreas, p->second->inverseAreaChecking))
{
if (p->second->comparableStreamDistance < STREAMER_STATIC_DISTANCE_CUTOFF || boost::geometry::comparable_distance(player.position, Eigen::Vector3f(p->second->position + p->second->positionOffset)) < (p->second->comparableStreamDistance * player.radiusMultipliers[STREAMER_TYPE_PICKUP]))
{
core->getData()->discoveredPickups.insert(std::make_pair(std::make_pair(p->first, *w), p->second));
}
}
}
}
}
}
}
void Streamer::streamPickups()
{
boost::unordered_map<std::pair<int, int>, int>::iterator i = core->getData()->internalPickups.begin();
while (i != core->getData()->internalPickups.end())
{
boost::unordered_map<std::pair<int, int>, Item::SharedPickup>::iterator d = core->getData()->discoveredPickups.find(i->first);
if (d == core->getData()->discoveredPickups.end())
{
sampgdk::DestroyPickup(i->second);
boost::unordered_map<int, Item::SharedPickup>::iterator p = core->getData()->pickups.find(i->first.first);
if (p != core->getData()->pickups.end())
{
if (p->second->streamCallbacks)
{
streamOutCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_PICKUP, i->first.first, INVALID_PLAYER_ID));
}
}
i = core->getData()->internalPickups.erase(i);
}
else
{
core->getData()->discoveredPickups.erase(d);
++i;
}
}
std::multimap<int, std::pair<int, Item::SharedPickup> > sortedPickups;
for (boost::unordered_map<std::pair<int, int>, Item::SharedPickup>::iterator d = core->getData()->discoveredPickups.begin(); d != core->getData()->discoveredPickups.end(); ++d)
{
sortedPickups.insert(std::make_pair(d->second->priority, std::make_pair(d->first.second, d->second)));
}
core->getData()->discoveredPickups.clear();
for (std::multimap<int, std::pair<int, Item::SharedPickup> >::iterator s = sortedPickups.begin(); s != sortedPickups.end(); ++s)
{
if (core->getData()->internalPickups.size() == core->getData()->getGlobalMaxVisibleItems(STREAMER_TYPE_PICKUP))
{
break;
}
int internalId = sampgdk::CreatePickup(s->second.second->modelId, s->second.second->type, s->second.second->position[0], s->second.second->position[1], s->second.second->position[2], s->second.first);
if (internalId == INVALID_PICKUP_ID)
{
break;
}
if (s->second.second->streamCallbacks)
{
streamInCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_PICKUP, s->second.second->pickupId, INVALID_PLAYER_ID));
}
core->getData()->internalPickups.insert(std::make_pair(std::make_pair(s->second.second->pickupId, s->second.first), internalId));
}
}
void Streamer::processRaceCheckpoints(Player &player, const std::vector<SharedCell> &cells)
{
std::multimap<std::pair<int, float>, Item::SharedRaceCheckpoint, Item::PairCompare> discoveredRaceCheckpoints;
for (std::vector<SharedCell>::const_iterator c = cells.begin(); c != cells.end(); ++c)
{
for (boost::unordered_map<int, Item::SharedRaceCheckpoint>::const_iterator r = (*c)->raceCheckpoints.begin(); r != (*c)->raceCheckpoints.end(); ++r)
{
float distance = std::numeric_limits<float>::infinity();
if (doesPlayerSatisfyConditions(r->second->players, player.playerId, r->second->interiors, player.interiorId, r->second->worlds, player.worldId, r->second->areas, player.internalAreas, r->second->inverseAreaChecking))
{
if (r->second->comparableStreamDistance < STREAMER_STATIC_DISTANCE_CUTOFF)
{
distance = std::numeric_limits<float>::infinity() * -1.0f;
}
else
{
distance = static_cast<float>(boost::geometry::comparable_distance(player.position, Eigen::Vector3f(r->second->position + r->second->positionOffset)));
}
}
if (distance < (r->second->comparableStreamDistance * player.radiusMultipliers[STREAMER_TYPE_RACE_CP]))
{
discoveredRaceCheckpoints.insert(std::make_pair(std::make_pair(r->second->priority, distance), r->second));
}
else
{
if (r->first == player.visibleRaceCheckpoint)
{
sampgdk::DisablePlayerRaceCheckpoint(player.playerId);
if (r->second->streamCallbacks)
{
streamOutCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_RACE_CP, r->second->raceCheckpointId, player.playerId));
}
player.activeRaceCheckpoint = 0;
player.visibleRaceCheckpoint = 0;
}
}
}
}
if (!discoveredRaceCheckpoints.empty())
{
std::multimap<std::pair<int, float>, Item::SharedRaceCheckpoint, Item::PairCompare>::iterator d = discoveredRaceCheckpoints.begin();
if (d->second->raceCheckpointId != player.visibleRaceCheckpoint)
{
if (player.visibleRaceCheckpoint)
{
sampgdk::DisablePlayerRaceCheckpoint(player.playerId);
if (d->second->streamCallbacks)
{
streamOutCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_RACE_CP, d->second->raceCheckpointId, player.playerId));
}
player.activeRaceCheckpoint = 0;
}
player.delayedRaceCheckpoint = d->second->raceCheckpointId;
}
if (d->second->cell)
{
player.visibleCell->raceCheckpoints.insert(std::make_pair(d->second->raceCheckpointId, d->second));
}
}
}
void Streamer::processTextLabels(Player &player, const std::vector<SharedCell> &cells)
{
std::multimap<std::pair<int, float>, Item::SharedTextLabel, Item::PairCompare> discoveredTextLabels, existingTextLabels;
for (std::vector<SharedCell>::const_iterator c = cells.begin(); c != cells.end(); ++c)
{
for (boost::unordered_map<int, Item::SharedTextLabel>::const_iterator t = (*c)->textLabels.begin(); t != (*c)->textLabels.end(); ++t)
{
float distance = std::numeric_limits<float>::infinity();
if (doesPlayerSatisfyConditions(t->second->players, player.playerId, t->second->interiors, player.interiorId, t->second->attach ? t->second->attach->worlds : t->second->worlds, player.worldId, t->second->areas, player.internalAreas, t->second->inverseAreaChecking))
{
if (t->second->comparableStreamDistance < STREAMER_STATIC_DISTANCE_CUTOFF)
{
distance = std::numeric_limits<float>::infinity() * -1.0f;
}
else
{
if (t->second->attach)
{
distance = static_cast<float>(boost::geometry::comparable_distance(player.position, t->second->attach->position));
}
else
{
distance = static_cast<float>(boost::geometry::comparable_distance(player.position, Eigen::Vector3f(t->second->position + t->second->positionOffset)));
}
}
}
boost::unordered_map<int, int>::iterator i = player.internalTextLabels.find(t->first);
if (distance < (t->second->comparableStreamDistance * player.radiusMultipliers[STREAMER_TYPE_3D_TEXT_LABEL]))
{
if (i == player.internalTextLabels.end())
{
discoveredTextLabels.insert(std::make_pair(std::make_pair(t->second->priority, distance), t->second));
}
else
{
if (t->second->cell)
{
player.visibleCell->textLabels.insert(*t);
}
existingTextLabels.insert(std::make_pair(std::make_pair(t->second->priority, distance), t->second));
}
}
else
{
if (i != player.internalTextLabels.end())
{
sampgdk::DeletePlayer3DTextLabel(player.playerId, i->second);
if (t->second->streamCallbacks)
{
streamOutCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_3D_TEXT_LABEL, t->first, player.playerId));
}
player.internalTextLabels.erase(i);
}
}
}
}
for (std::multimap<std::pair<int, float>, Item::SharedTextLabel, Item::PairCompare>::iterator d = discoveredTextLabels.begin(); d != discoveredTextLabels.end(); ++d)
{
boost::unordered_map<int, int>::iterator i = player.internalTextLabels.find(d->second->textLabelId);
if (i != player.internalTextLabels.end())
{
continue;
}
if (player.internalTextLabels.size() == player.currentVisibleTextLabels)
{
std::multimap<std::pair<int, float>, Item::SharedTextLabel, Item::PairCompare>::reverse_iterator e = existingTextLabels.rbegin();
if (e != existingTextLabels.rend())
{
if (e->first.first < d->first.first || (e->first.second > STREAMER_STATIC_DISTANCE_CUTOFF && d->first.second < e->first.second))
{
boost::unordered_map<int, int>::iterator j = player.internalTextLabels.find(e->second->textLabelId);
if (j != player.internalTextLabels.end())
{
sampgdk::DeletePlayer3DTextLabel(player.playerId, j->second);
if (e->second->streamCallbacks)
{
streamOutCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_3D_TEXT_LABEL, e->second->textLabelId, player.playerId));
}
player.internalTextLabels.erase(j);
}
if (e->second->cell)
{
player.visibleCell->textLabels.erase(e->second->textLabelId);
}
existingTextLabels.erase(--e.base());
}
}
}
if (player.internalTextLabels.size() == player.maxVisibleTextLabels)
{
player.currentVisibleTextLabels = player.internalTextLabels.size();
break;
}
int internalId = sampgdk::CreatePlayer3DTextLabel(player.playerId, d->second->text.c_str(), d->second->color, d->second->position[0], d->second->position[1], d->second->position[2], d->second->drawDistance, d->second->attach ? d->second->attach->player : INVALID_PLAYER_ID, d->second->attach ? d->second->attach->vehicle : INVALID_VEHICLE_ID, d->second->testLOS);
if (internalId == INVALID_3DTEXT_ID)
{
player.currentVisibleTextLabels = player.internalTextLabels.size();
break;
}
if (d->second->streamCallbacks)
{
streamInCallbacks.push_back(boost::make_tuple(STREAMER_TYPE_3D_TEXT_LABEL, d->second->textLabelId, player.playerId));
}
player.internalTextLabels.insert(std::make_pair(d->second->textLabelId, internalId));
if (d->second->cell)
{
player.visibleCell->textLabels.insert(std::make_pair(d->second->textLabelId, d->second));
}
}
}
void Streamer::processActiveItems()
{
if (!movingObjects.empty())
{
processMovingObjects();
}
if (!attachedAreas.empty())
{
processAttachedAreas();
}
if (!attachedObjects.empty())
{
processAttachedObjects();
}
if (!attachedTextLabels.empty())
{
processAttachedTextLabels();
}
}
void Streamer::processMovingObjects()
{
boost::unordered_set<Item::SharedObject>::iterator o = movingObjects.begin();
while (o != movingObjects.end())
{
bool objectFinishedMoving = false;
if ((*o)->move)
{
boost::chrono::duration<float, boost::milli> elapsedTime = boost::chrono::steady_clock::now() - (*o)->move->time;
if (boost::chrono::duration_cast<boost::chrono::milliseconds>(elapsedTime).count() < (*o)->move->duration)
{
(*o)->position = (*o)->move->position.get<1>() + ((*o)->move->position.get<2>() * elapsedTime.count());
if (!Utility::almostEquals((*o)->move->rotation.get<0>().maxCoeff(), -1000.0f))
{
(*o)->rotation = (*o)->move->rotation.get<1>() + ((*o)->move->rotation.get<2>() * elapsedTime.count());
}
}
else
{
(*o)->position = (*o)->move->position.get<0>();
if (!Utility::almostEquals((*o)->move->rotation.get<0>().maxCoeff(), -1000.0f))
{
(*o)->rotation = (*o)->move->rotation.get<0>();
}
(*o)->move.reset();
objectMoveCallbacks.push_back((*o)->objectId);
objectFinishedMoving = true;
}
if ((*o)->cell)
{
core->getGrid()->removeObject(*o, true);
}
}
if (objectFinishedMoving)
{
o = movingObjects.erase(o);
}
else
{
++o;
}
}
}
void Streamer::processAttachedAreas()
{
for (boost::unordered_set<Item::SharedArea>::iterator a = attachedAreas.begin(); a != attachedAreas.end(); ++a)
{
if ((*a)->attach)
{
bool adjust = false;
if (((*a)->attach->object.get<0>() != INVALID_OBJECT_ID && (*a)->attach->object.get<1>() != STREAMER_OBJECT_TYPE_DYNAMIC) || ((*a)->attach->object.get<0>() != INVALID_STREAMER_ID && (*a)->attach->object.get<1>() == STREAMER_OBJECT_TYPE_DYNAMIC))
{
switch ((*a)->attach->object.get<1>())
{
case STREAMER_OBJECT_TYPE_GLOBAL:
{
Eigen::Vector3f position = Eigen::Vector3f::Zero(), rotation = Eigen::Vector3f::Zero();
adjust = sampgdk::GetObjectPos((*a)->attach->object.get<0>(), &position[0], &position[1], &position[2]);
sampgdk::GetObjectRot((*a)->attach->object.get<0>(), &rotation[0], &rotation[1], &rotation[2]);
Utility::constructAttachedArea(*a, boost::variant<float, Eigen::Vector3f, Eigen::Vector4f>(rotation), position);
break;
}
case STREAMER_OBJECT_TYPE_PLAYER:
{
Eigen::Vector3f position = Eigen::Vector3f::Zero(), rotation = Eigen::Vector3f::Zero();
adjust = sampgdk::GetPlayerObjectPos((*a)->attach->object.get<2>(), (*a)->attach->object.get<0>(), &position[0], &position[1], &position[2]);
sampgdk::GetPlayerObjectRot((*a)->attach->object.get<2>(), (*a)->attach->object.get<0>(), &rotation[0], &rotation[1], &rotation[2]);
Utility::constructAttachedArea(*a, boost::variant<float, Eigen::Vector3f, Eigen::Vector4f>(rotation), position);
break;
}
case STREAMER_OBJECT_TYPE_DYNAMIC:
{
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find((*a)->attach->object.get<0>());
if (o != core->getData()->objects.end())
{
Utility::constructAttachedArea(*a, boost::variant<float, Eigen::Vector3f, Eigen::Vector4f>(o->second->rotation), o->second->position);
adjust = true;
}
break;
}
}
}
else if ((*a)->attach->player != INVALID_PLAYER_ID)
{
float heading = 0.0f;
Eigen::Vector3f position = Eigen::Vector3f::Zero();
adjust = sampgdk::GetPlayerPos((*a)->attach->player, &position[0], &position[1], &position[2]);
sampgdk::GetPlayerFacingAngle((*a)->attach->player, &heading);
Utility::constructAttachedArea(*a, boost::variant<float, Eigen::Vector3f, Eigen::Vector4f>(heading), position);
}
else if ((*a)->attach->vehicle != INVALID_VEHICLE_ID)
{
bool occupied = false;
for (boost::unordered_map<int, Player>::iterator p = core->getData()->players.begin(); p != core->getData()->players.end(); ++p)
{
if (sampgdk::GetPlayerState(p->first) == PLAYER_STATE_DRIVER)
{
if (sampgdk::GetPlayerVehicleID(p->first) == (*a)->attach->vehicle)
{
occupied = true;
break;
}
}
}
Eigen::Vector3f position = Eigen::Vector3f::Zero();
adjust = sampgdk::GetVehiclePos((*a)->attach->vehicle, &position[0], &position[1], &position[2]);
if (!occupied)
{
float heading = 0.0f;
sampgdk::GetVehicleZAngle((*a)->attach->vehicle, &heading);
Utility::constructAttachedArea(*a, boost::variant<float, Eigen::Vector3f, Eigen::Vector4f>(heading), position);
}
else
{
Eigen::Vector4f quaternion = Eigen::Vector4f::Zero();
sampgdk::GetVehicleRotationQuat((*a)->attach->vehicle, &quaternion[0], &quaternion[1], &quaternion[2], &quaternion[3]);
Utility::constructAttachedArea(*a, boost::variant<float, Eigen::Vector3f, Eigen::Vector4f>(quaternion), position);
}
}
if (adjust)
{
if ((*a)->cell)
{
core->getGrid()->removeArea(*a, true);
}
}
else
{
switch ((*a)->type)
{
case STREAMER_AREA_TYPE_CIRCLE:
case STREAMER_AREA_TYPE_CYLINDER:
{
boost::get<Eigen::Vector2f>((*a)->attach->position).fill(std::numeric_limits<float>::infinity());
break;
}
case STREAMER_AREA_TYPE_SPHERE:
{
boost::get<Eigen::Vector3f>((*a)->attach->position).fill(std::numeric_limits<float>::infinity());
break;
}
case STREAMER_AREA_TYPE_RECTANGLE:
{
boost::get<Box2d>((*a)->attach->position).min_corner().fill(std::numeric_limits<float>::infinity());
boost::get<Box2d>((*a)->attach->position).max_corner().fill(std::numeric_limits<float>::infinity());
break;
}
case STREAMER_AREA_TYPE_CUBOID:
{
boost::get<Box3d>((*a)->attach->position).min_corner().fill(std::numeric_limits<float>::infinity());
boost::get<Box3d>((*a)->attach->position).max_corner().fill(std::numeric_limits<float>::infinity());
break;
}
case STREAMER_AREA_TYPE_POLYGON:
{
boost::get<Polygon2d>((*a)->attach->position).clear();
break;
}
}
}
}
}
}
void Streamer::processAttachedObjects()
{
for (boost::unordered_set<Item::SharedObject>::iterator o = attachedObjects.begin(); o != attachedObjects.end(); ++o)
{
if ((*o)->attach)
{
bool adjust = false;
Eigen::Vector3f position = (*o)->attach->position;
if ((*o)->attach->object != INVALID_STREAMER_ID)
{
boost::unordered_map<int, Item::SharedObject>::iterator p = core->getData()->objects.find((*o)->attach->object);
if (p != core->getData()->objects.end())
{
(*o)->attach->position = p->second->position;
(*o)->attach->worlds = p->second->worlds;
adjust = true;
}
}
else if ((*o)->attach->player != INVALID_PLAYER_ID)
{
adjust = sampgdk::GetPlayerPos((*o)->attach->player, &(*o)->attach->position[0], &(*o)->attach->position[1], &(*o)->attach->position[2]);
Utility::setFirstValueInContainer((*o)->attach->worlds, sampgdk::GetPlayerVirtualWorld((*o)->attach->player));
}
else if ((*o)->attach->vehicle != INVALID_VEHICLE_ID)
{
adjust = sampgdk::GetVehiclePos((*o)->attach->vehicle, &(*o)->attach->position[0], &(*o)->attach->position[1], &(*o)->attach->position[2]);
Utility::setFirstValueInContainer((*o)->attach->worlds, sampgdk::GetVehicleVirtualWorld((*o)->attach->vehicle));
}
if (adjust)
{
if ((*o)->cell && !(*o)->attach->position.isApprox(position))
{
core->getGrid()->removeObject(*o, true);
}
}
else
{
(*o)->attach->position.fill(std::numeric_limits<float>::infinity());
}
}
}
}
void Streamer::processAttachedTextLabels()
{
for (boost::unordered_set<Item::SharedTextLabel>::iterator t = attachedTextLabels.begin(); t != attachedTextLabels.end(); ++t)
{
bool adjust = false;
Eigen::Vector3f position = (*t)->attach->position;
if ((*t)->attach)
{
if ((*t)->attach->player != INVALID_PLAYER_ID)
{
adjust = sampgdk::GetPlayerPos((*t)->attach->player, &(*t)->attach->position[0], &(*t)->attach->position[1], &(*t)->attach->position[2]);
Utility::setFirstValueInContainer((*t)->attach->worlds, sampgdk::GetPlayerVirtualWorld((*t)->attach->player));
}
else if ((*t)->attach->vehicle != INVALID_VEHICLE_ID)
{
adjust = sampgdk::GetVehiclePos((*t)->attach->vehicle, &(*t)->attach->position[0], &(*t)->attach->position[1], &(*t)->attach->position[2]);
Utility::setFirstValueInContainer((*t)->attach->worlds, sampgdk::GetVehicleVirtualWorld((*t)->attach->vehicle));
}
if (adjust)
{
if ((*t)->cell && !(*t)->attach->position.isApprox(position))
{
core->getGrid()->removeTextLabel(*t, true);
}
}
else
{
(*t)->attach->position.fill(std::numeric_limits<float>::infinity());
}
}
}
}
| 36.565327 | 366 | 0.637635 | [
"geometry",
"object",
"vector",
"3d"
] |
81270bb00a8091a2752529074ca4482b6bd3a515 | 32,947 | cc | C++ | src/view_correction/mesh_renderer.cc | puzzlepaint/viewcorrection | ab42cab505879fc1235389fae50c23410079c938 | [
"BSD-3-Clause"
] | 8 | 2018-10-24T11:06:55.000Z | 2021-01-25T03:50:24.000Z | src/view_correction/mesh_renderer.cc | puzzlepaint/viewcorrection | ab42cab505879fc1235389fae50c23410079c938 | [
"BSD-3-Clause"
] | null | null | null | src/view_correction/mesh_renderer.cc | puzzlepaint/viewcorrection | ab42cab505879fc1235389fae50c23410079c938 | [
"BSD-3-Clause"
] | 3 | 2020-01-14T17:09:16.000Z | 2021-05-02T08:17:24.000Z | // Copyright 2018 ETH Zürich
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "view_correction/mesh_renderer.h"
#include "view_correction/cuda_util.h"
#include "view_correction/opengl_util.h"
#include "view_correction/util.h"
namespace view_correction {
MeshRenderer::MeshRenderer(int width, int height, Type type) {
CHECK_OPENGL_NO_ERROR();
width_ = width;
height_ = height;
type_ = type;
CreateFrameBufferObject(type);
if (type == kRenderDepthOnly) {
CreateDepthVertexShader();
CreateDepthFragmentShader();
CreateDepthProgram();
} else if (type == kRenderDepthAndIntensity) {
CreateVertexShader();
CreateFragmentShader();
CreateProgram();
} else if (type == kRenderDepthAndColor) {
CreateDepthAndColorVertexShader();
CreateDepthAndColorFragmentShader();
CreateDepthAndColorProgram();
}
}
MeshRenderer::~MeshRenderer() {
CUDA_CHECKED_CALL(cudaGraphicsUnregisterResource(rendertarget_0_resource_cuda_));
if (type_ != kRenderDepthOnly) {
CUDA_CHECKED_CALL(cudaGraphicsUnregisterResource(rendertarget_1_resource_cuda_));
}
if (type_ == kRenderDepthOnly) {
glDetachShader(depth_shader_program_, depth_vertex_shader_);
glDetachShader(depth_shader_program_, depth_fragment_shader_);
glDeleteShader(depth_vertex_shader_);
glDeleteShader(depth_fragment_shader_);
glDeleteProgram(depth_shader_program_);
} else if (type_ == kRenderDepthAndIntensity) {
glDetachShader(shader_program_, vertex_shader_);
glDetachShader(shader_program_, fragment_shader_);
glDeleteShader(vertex_shader_);
glDeleteShader(fragment_shader_);
glDeleteProgram(shader_program_);
} else if (type_ == kRenderDepthAndColor) {
glDetachShader(depth_color_shader_program_, depth_color_vertex_shader_);
glDetachShader(depth_color_shader_program_, depth_color_fragment_shader_);
glDeleteShader(depth_color_vertex_shader_);
glDeleteShader(depth_color_fragment_shader_);
glDeleteProgram(depth_color_shader_program_);
}
glDeleteTextures(1, &rendertarget_0_texture_);
if (type_ != kRenderDepthOnly) {
glDeleteTextures(1, &rendertarget_1_texture_);
}
glDeleteRenderbuffers(1, &depth_buffer_);
glDeleteFramebuffers(1, &frame_buffer_object_);
CHECK_OPENGL_NO_ERROR();
}
void MeshRenderer::RenderMesh(
GLuint vertex_buffer, GLuint color_buffer, GLuint index_buffer,
int num_indices,
const Sophus::SE3f& transformation,
const float fx, const float fy, const float cx, const float cy,
float min_depth, float max_depth) {
CHECK_EQ(type_, kRenderDepthAndIntensity);
CHECK_OPENGL_NO_ERROR();
// Set states.
glClearColor(0.0, 0.0, 0.0, 0.0);
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
// TODO(puzzlepaint): enable culling?
glDisable(GL_CULL_FACE);
CHECK_OPENGL_NO_ERROR();
// Setup framebuffer and shaders.
glBindFramebuffer(GL_FRAMEBUFFER, frame_buffer_object_);
CHECK_OPENGL_NO_ERROR();
GLenum buffers[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1};
glDrawBuffers(2, buffers);
CHECK_OPENGL_NO_ERROR();
// Clear buffers.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Render geometry.
glUseProgram(shader_program_);
SetupProjection(transformation, fx, fy, cx, cy, min_depth, max_depth,
u_projection_matrix_location_,
u_model_view_matrix_location_);
CHECK_OPENGL_NO_ERROR();
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
glEnableVertexAttribArray(a_position_location_);
glVertexAttribPointer(a_position_location_, 3, GL_FLOAT, GL_FALSE,
3 * sizeof(float), // NOLINT
reinterpret_cast<char*>(0) + 0);
CHECK_OPENGL_NO_ERROR();
glBindBuffer(GL_ARRAY_BUFFER, color_buffer);
CHECK_OPENGL_NO_ERROR();
glEnableVertexAttribArray(a_intensity_location_);
CHECK_OPENGL_NO_ERROR();
glVertexAttribPointer(a_intensity_location_, 1, GL_UNSIGNED_BYTE, GL_TRUE,
1 * sizeof(uint8_t), // NOLINT
reinterpret_cast<char*>(0) + 0);
CHECK_OPENGL_NO_ERROR();
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer);
CHECK_OPENGL_NO_ERROR();
glDrawElements(GL_TRIANGLE_STRIP, num_indices, GL_UNSIGNED_INT,
reinterpret_cast<char*>(0) + 0);
CHECK_OPENGL_NO_ERROR();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glDisableVertexAttribArray(a_intensity_location_);
glDisableVertexAttribArray(a_position_location_);
CHECK_OPENGL_NO_ERROR();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
CHECK_OPENGL_NO_ERROR();
}
void MeshRenderer::BeginRenderingMeshesDepth(
const Sophus::SE3f& transformation, const float fx,
const float fy, const float cx, const float cy, float min_depth,
float max_depth) {
CHECK_EQ(type_, kRenderDepthOnly);
// Set states.
glClearColor(0.0, 0.0, 0.0, 0.0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CW);
CHECK_OPENGL_NO_ERROR();
// Setup framebuffer and shaders.
glBindFramebuffer(GL_FRAMEBUFFER, frame_buffer_object_);
GLenum buffers[] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, buffers);
glUseProgram(depth_shader_program_);
CHECK_OPENGL_NO_ERROR();
// Clear buffers.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Setup projection.
SetupProjection(transformation, fx, fy, cx, cy, min_depth, max_depth,
depth_u_projection_matrix_location_,
depth_u_model_view_matrix_location_);
// Setup input source.
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(depth_a_position_location_);
}
void MeshRenderer::RenderMeshDepth(
const void* vertex_data, const void* face_data, int num_faces) {
CHECK_EQ(type_, kRenderDepthOnly);
// Render from CPU memory.
glVertexAttribPointer(depth_a_position_location_, 3, GL_FLOAT, GL_FALSE,
3 * sizeof(float), // NOLINT
vertex_data);
glDrawElements(GL_TRIANGLES, 3 * num_faces, GL_UNSIGNED_INT,
face_data);
}
void MeshRenderer::EndRenderingMeshesDepth() {
CHECK_EQ(type_, kRenderDepthOnly);
glDisableVertexAttribArray(depth_a_position_location_);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
CHECK_OPENGL_NO_ERROR();
// // DEBUG: display result.
// glBindFramebuffer(GL_FRAMEBUFFER, frame_buffer_object_);
// cv::Mat_<float> texture_buffer(height_, width_);
// glReadPixels(0, 0, width_, height_, GL_RED, GL_FLOAT,
// texture_buffer.data);
// CHECK_OPENGL_NO_ERROR();
// glBindFramebuffer(GL_FRAMEBUFFER, 0);
// util::DisplayDepthmapInvDepthColored(
// texture_buffer, 0.8f,
// 50.f, "reprojected depth", false);
// cv::waitKey(1);
}
void MeshRenderer::BeginRenderingMeshesDepthAndColor(
const Sophus::SE3f& transformation, const float fx,
const float fy, const float cx, const float cy, float min_depth,
float max_depth) {
CHECK_EQ(type_, kRenderDepthAndColor);
// Set states.
glClearColor(0.0, 0.0, 0.0, 0.0);
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CW);
CHECK_OPENGL_NO_ERROR();
// Setup framebuffer and shaders.
glBindFramebuffer(GL_FRAMEBUFFER, frame_buffer_object_);
GLenum buffers[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1};
glDrawBuffers(2, buffers);
glUseProgram(depth_color_shader_program_);
CHECK_OPENGL_NO_ERROR();
// Clear buffers.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Setup projection.
SetupProjection(transformation, fx, fy, cx, cy, min_depth, max_depth,
depth_color_u_projection_matrix_location_,
depth_color_u_model_view_matrix_location_);
// Setup input source.
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(depth_color_a_position_location_);
glEnableVertexAttribArray(depth_color_a_color_location_);
CHECK_OPENGL_NO_ERROR();
}
void MeshRenderer::RenderMeshDepthAndColor(
const void* vertex_data, const void* color_data, const void* face_data, int num_faces) {
CHECK_EQ(type_, kRenderDepthAndColor);
// Render from CPU memory.
glVertexAttribPointer(depth_color_a_position_location_, 3, GL_FLOAT, GL_FALSE,
3 * sizeof(float), // NOLINT
vertex_data);
glVertexAttribPointer(depth_color_a_color_location_, 3, GL_UNSIGNED_BYTE, GL_TRUE,
4 * sizeof(uint8_t), // NOLINT
color_data);
glDrawElements(GL_TRIANGLES, 3 * num_faces, GL_UNSIGNED_INT,
face_data);
}
void MeshRenderer::EndRenderingMeshesDepthAndColor() {
CHECK_EQ(type_, kRenderDepthAndColor);
glDisableVertexAttribArray(depth_color_a_position_location_);
glDisableVertexAttribArray(depth_color_a_color_location_);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
CHECK_OPENGL_NO_ERROR();
}
cudaGraphicsResource_t MeshRenderer::result_resource_depth() const {
return rendertarget_0_resource_cuda_;
}
cudaGraphicsResource_t MeshRenderer::result_resource_intensity() const {
return rendertarget_1_resource_cuda_;
}
cudaTextureObject_t MeshRenderer::MapDepthResultAsTexture(
cudaTextureAddressMode address_mode_x,
cudaTextureAddressMode address_mode_y, cudaTextureFilterMode filter_mode,
bool normalized_coordinate_access, cudaStream_t stream) {
// Map the resource.
cudaArray_t warped_depth_array;
CUDA_CHECKED_CALL(cudaGraphicsMapResources(1, &rendertarget_0_resource_cuda_, stream));
CUDA_CHECKED_CALL(cudaGraphicsSubResourceGetMappedArray(
&warped_depth_array, rendertarget_0_resource_cuda_, 0, 0));
// Create resource description.
struct cudaResourceDesc warped_depth_resource_description;
memset(&warped_depth_resource_description, 0,
sizeof(warped_depth_resource_description));
warped_depth_resource_description.resType = cudaResourceTypeArray;
warped_depth_resource_description.res.array.array = warped_depth_array;
// Create texture object.
struct cudaTextureDesc warped_depth_texture_description;
memset(&warped_depth_texture_description, 0,
sizeof(warped_depth_texture_description));
warped_depth_texture_description.addressMode[0] = address_mode_x;
warped_depth_texture_description.addressMode[1] = address_mode_y;
warped_depth_texture_description.filterMode = filter_mode;
warped_depth_texture_description.readMode = cudaReadModeElementType;
warped_depth_texture_description.normalizedCoords =
normalized_coordinate_access ? 1 : 0;
cudaTextureObject_t warped_depth_texture;
CUDA_CHECKED_CALL(cudaCreateTextureObject(
&warped_depth_texture, &warped_depth_resource_description,
&warped_depth_texture_description, NULL));
return warped_depth_texture;
}
cudaTextureObject_t MeshRenderer::MapIntensityResultAsTexture(
cudaTextureAddressMode address_mode_x,
cudaTextureAddressMode address_mode_y, cudaTextureFilterMode filter_mode,
cudaTextureReadMode read_mode,
bool normalized_coordinate_access, cudaStream_t stream) {
// Map the resource.
cudaArray_t result_array;
CUDA_CHECKED_CALL(cudaGraphicsMapResources(1, &rendertarget_1_resource_cuda_, stream));
CUDA_CHECKED_CALL(cudaGraphicsSubResourceGetMappedArray(
&result_array, rendertarget_1_resource_cuda_, 0, 0));
// Create resource description.
struct cudaResourceDesc result_resource_description;
memset(&result_resource_description, 0,
sizeof(result_resource_description));
result_resource_description.resType = cudaResourceTypeArray;
result_resource_description.res.array.array = result_array;
// Create texture object.
struct cudaTextureDesc result_texture_description;
memset(&result_texture_description, 0,
sizeof(result_texture_description));
result_texture_description.addressMode[0] = address_mode_x;
result_texture_description.addressMode[1] = address_mode_y;
result_texture_description.filterMode = filter_mode;
result_texture_description.readMode = read_mode;
result_texture_description.normalizedCoords =
normalized_coordinate_access ? 1 : 0;
cudaTextureObject_t result_texture;
CUDA_CHECKED_CALL(cudaCreateTextureObject(
&result_texture, &result_resource_description,
&result_texture_description, NULL));
return result_texture;
}
cudaTextureObject_t MeshRenderer::MapColorResultAsTexture(
cudaTextureAddressMode address_mode_x,
cudaTextureAddressMode address_mode_y,
cudaTextureFilterMode filter_mode,
cudaTextureReadMode read_mode,
bool normalized_coordinate_access,
cudaStream_t stream) {
// Map the resource.
cudaArray_t result_array;
CUDA_CHECKED_CALL(cudaGraphicsMapResources(1, &rendertarget_1_resource_cuda_, stream));
CUDA_CHECKED_CALL(cudaGraphicsSubResourceGetMappedArray(
&result_array, rendertarget_1_resource_cuda_, 0, 0));
// Create resource description.
struct cudaResourceDesc result_resource_description;
memset(&result_resource_description, 0,
sizeof(result_resource_description));
result_resource_description.resType = cudaResourceTypeArray;
result_resource_description.res.array.array = result_array;
// Create texture object.
struct cudaTextureDesc result_texture_description;
memset(&result_texture_description, 0,
sizeof(result_texture_description));
result_texture_description.addressMode[0] = address_mode_x;
result_texture_description.addressMode[1] = address_mode_y;
result_texture_description.filterMode = filter_mode;
result_texture_description.readMode = read_mode;
result_texture_description.normalizedCoords =
normalized_coordinate_access ? 1 : 0;
cudaTextureObject_t result_texture;
CUDA_CHECKED_CALL(cudaCreateTextureObject(
&result_texture, &result_resource_description,
&result_texture_description, NULL));
return result_texture;
}
void MeshRenderer::UnmapDepthResult(
cudaTextureObject_t texture, cudaStream_t stream) {
CUDA_CHECKED_CALL(cudaDestroyTextureObject(texture));
CUDA_CHECKED_CALL(
cudaGraphicsUnmapResources(1, &rendertarget_0_resource_cuda_, stream));
}
void MeshRenderer::UnmapIntensityResult(
cudaTextureObject_t texture, cudaStream_t stream) {
CUDA_CHECKED_CALL(cudaDestroyTextureObject(texture));
CUDA_CHECKED_CALL(
cudaGraphicsUnmapResources(1, &rendertarget_1_resource_cuda_, stream));
}
void MeshRenderer::UnmapColorResult(cudaTextureObject_t texture, cudaStream_t stream) {
CUDA_CHECKED_CALL(cudaDestroyTextureObject(texture));
CUDA_CHECKED_CALL(
cudaGraphicsUnmapResources(1, &rendertarget_1_resource_cuda_, stream));
}
void MeshRenderer::CreateFrameBufferObject(Type type) {
glGenFramebuffers(1, &frame_buffer_object_);
CHECK_OPENGL_NO_ERROR();
glBindFramebuffer(GL_FRAMEBUFFER, frame_buffer_object_);
CHECK_OPENGL_NO_ERROR();
// Add a depth buffer to the frame buffer object.
glGenRenderbuffers(1, &depth_buffer_);
glBindRenderbuffer(GL_RENDERBUFFER, depth_buffer_);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width_, height_);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER, depth_buffer_);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
CHECK_OPENGL_NO_ERROR();
// Add a color texture to the frame buffer object.
// This class renders the depth to this color texture in addition to the depth
// buffer because reading out the depth buffer did not seem to be supported in
// OpenGL ES 2.0. This might have changed in later versions and
// efficiency might benefit from removing the additional color texture.
glGenTextures(1, &rendertarget_0_texture_);
glBindTexture(GL_TEXTURE_2D, rendertarget_0_texture_);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, width_, height_, 0, GL_RED, GL_FLOAT,
0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
CHECK_OPENGL_NO_ERROR();
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
rendertarget_0_texture_, 0);
if (type == kRenderDepthAndIntensity) {
glGenTextures(1, &rendertarget_1_texture_);
glBindTexture(GL_TEXTURE_2D, rendertarget_1_texture_);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width_, height_, 0, GL_RED,
GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
CHECK_OPENGL_NO_ERROR();
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D,
rendertarget_1_texture_, 0);
} else if (type == kRenderDepthAndColor) {
glGenTextures(1, &rendertarget_1_texture_);
glBindTexture(GL_TEXTURE_2D, rendertarget_1_texture_);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width_, height_, 0, GL_RGBA,
GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
CHECK_OPENGL_NO_ERROR();
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D,
rendertarget_1_texture_, 0);
}
// Verify frame buffer object creation.
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
CHECK_EQ(static_cast<int>(status), GL_FRAMEBUFFER_COMPLETE);
CHECK_OPENGL_NO_ERROR();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// Prepare for CUDA interop.
CUDA_CHECKED_CALL(cudaGraphicsGLRegisterImage(
&rendertarget_0_resource_cuda_, rendertarget_0_texture_, GL_TEXTURE_2D,
cudaGraphicsRegisterFlagsReadOnly));
if (type != kRenderDepthOnly) {
CUDA_CHECKED_CALL(cudaGraphicsGLRegisterImage(
&rendertarget_1_resource_cuda_, rendertarget_1_texture_, GL_TEXTURE_2D,
cudaGraphicsRegisterFlagsReadOnly));
}
}
void MeshRenderer::CreateVertexShader() {
const std::string vertex_shader_src =
"#version 300 es\n"
"uniform mat4 u_model_view_matrix;\n"
"uniform mat4 u_projection_matrix;\n"
"in vec4 in_position;\n"
"in float in_intensity;\n"
"out float var_depth;\n"
"out float var_intensity;\n"
"void main() {\n"
" var_intensity = in_intensity;\n"
" vec4 local_point = u_model_view_matrix * in_position;\n"
" local_point.xyz /= local_point.w;\n"
" var_depth = local_point.z;\n"
" local_point.w = 1.0;\n"
" gl_Position = u_projection_matrix * local_point;\n"
"}\n";
vertex_shader_ = glCreateShader(GL_VERTEX_SHADER);
const GLchar* vertex_shader_src_ptr =
static_cast<const GLchar*>(vertex_shader_src.c_str());
glShaderSource(vertex_shader_, 1, &vertex_shader_src_ptr, NULL);
glCompileShader(vertex_shader_);
GLint compiled;
glGetShaderiv(vertex_shader_, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
GLint length;
glGetShaderiv(vertex_shader_, GL_INFO_LOG_LENGTH, &length);
std::unique_ptr<GLchar[]> log(
reinterpret_cast<GLchar*>(new uint8_t[length]));
glGetShaderInfoLog(vertex_shader_, length, &length, log.get());
LOG(FATAL) << "GL Shader Compilation Error: " << log.get();
}
}
void MeshRenderer::CreateFragmentShader() {
const std::string fragment_shader_src =
"#version 300 es\n"
"in highp float var_depth;\n"
"in lowp float var_intensity;\n"
"layout(location = 0) out highp float out_depth;\n"
"layout(location = 1) out lowp float out_intensity;\n"
"void main()\n"
"{\n"
" out_depth = var_depth;\n"
" out_intensity = (var_intensity > 0.0) ? 1.0 : 0.0;\n"
"}\n";
fragment_shader_ = glCreateShader(GL_FRAGMENT_SHADER);
const GLchar* fragment_shader_src_ptr =
static_cast<const GLchar*>(fragment_shader_src.c_str());
glShaderSource(fragment_shader_, 1, &fragment_shader_src_ptr, NULL);
glCompileShader(fragment_shader_);
GLint compiled;
glGetShaderiv(fragment_shader_, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
GLint length;
glGetShaderiv(fragment_shader_, GL_INFO_LOG_LENGTH, &length);
std::unique_ptr<GLchar[]> log(
reinterpret_cast<GLchar*>(new uint8_t[length]));
glGetShaderInfoLog(fragment_shader_, length, &length, log.get());
LOG(FATAL) << "GL Shader Compilation Error: " << log.get();
}
}
void MeshRenderer::CreateProgram() {
shader_program_ = glCreateProgram();
glAttachShader(shader_program_, fragment_shader_);
glAttachShader(shader_program_, vertex_shader_);
glLinkProgram(shader_program_);
GLint linked;
glGetProgramiv(shader_program_, GL_LINK_STATUS, &linked);
if (!linked) {
GLint length;
glGetProgramiv(shader_program_, GL_INFO_LOG_LENGTH, &length);
std::unique_ptr<GLchar[]> log(
reinterpret_cast<GLchar*>(new uint8_t[length]));
glGetProgramInfoLog(shader_program_, length, &length, log.get());
LOG(FATAL) << "GL Program Linker Error: " << log.get();
}
glUseProgram(shader_program_);
CHECK_OPENGL_NO_ERROR();
// Get attributes.
a_position_location_ = glGetAttribLocation(shader_program_, "in_position");
CHECK_OPENGL_NO_ERROR();
CHECK_GE(a_position_location_, 0) << "Attribute needs to be used";
a_intensity_location_ = glGetAttribLocation(shader_program_, "in_intensity");
CHECK_OPENGL_NO_ERROR();
CHECK_GE(a_intensity_location_, 0) << "Attribute needs to be used";
u_model_view_matrix_location_ =
glGetUniformLocation(shader_program_, "u_model_view_matrix");
CHECK_OPENGL_NO_ERROR();
u_projection_matrix_location_ =
glGetUniformLocation(shader_program_, "u_projection_matrix");
CHECK_OPENGL_NO_ERROR();
}
void MeshRenderer::CreateDepthVertexShader() {
const std::string depth_vertex_shader_src =
"#version 300 es\n"
"uniform mat4 u_model_view_matrix;\n"
"uniform mat4 u_projection_matrix;\n"
"in vec4 in_position;\n"
"out float var_depth;\n"
"void main() {\n"
" vec4 local_point = u_model_view_matrix * in_position;\n"
" local_point.xyz /= local_point.w;\n"
" var_depth = local_point.z;\n"
" local_point.w = 1.0;\n"
" gl_Position = u_projection_matrix * local_point;\n"
"}\n";
depth_vertex_shader_ = glCreateShader(GL_VERTEX_SHADER);
const GLchar* depth_vertex_shader_src_ptr =
static_cast<const GLchar*>(depth_vertex_shader_src.c_str());
glShaderSource(depth_vertex_shader_, 1, &depth_vertex_shader_src_ptr, NULL);
glCompileShader(depth_vertex_shader_);
GLint compiled;
glGetShaderiv(depth_vertex_shader_, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
GLint length;
glGetShaderiv(depth_vertex_shader_, GL_INFO_LOG_LENGTH, &length);
std::unique_ptr<GLchar[]> log(
reinterpret_cast<GLchar*>(new uint8_t[length]));
glGetShaderInfoLog(depth_vertex_shader_, length, &length, log.get());
LOG(FATAL) << "GL Shader Compilation Error: " << log.get();
}
}
void MeshRenderer::CreateDepthFragmentShader() {
const std::string depth_fragment_shader_src =
"#version 300 es\n"
"in highp float var_depth;\n"
"layout(location = 0) out highp float out_depth;\n"
"void main()\n"
"{\n"
" out_depth = var_depth;\n"
"}\n";
depth_fragment_shader_ = glCreateShader(GL_FRAGMENT_SHADER);
const GLchar* depth_fragment_shader_src_ptr =
static_cast<const GLchar*>(depth_fragment_shader_src.c_str());
glShaderSource(depth_fragment_shader_, 1, &depth_fragment_shader_src_ptr, NULL);
glCompileShader(depth_fragment_shader_);
GLint compiled;
glGetShaderiv(depth_fragment_shader_, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
GLint length;
glGetShaderiv(depth_fragment_shader_, GL_INFO_LOG_LENGTH, &length);
std::unique_ptr<GLchar[]> log(
reinterpret_cast<GLchar*>(new uint8_t[length]));
glGetShaderInfoLog(depth_fragment_shader_, length, &length, log.get());
LOG(FATAL) << "GL Shader Compilation Error: " << log.get();
}
}
void MeshRenderer::CreateDepthProgram() {
depth_shader_program_ = glCreateProgram();
glAttachShader(depth_shader_program_, depth_fragment_shader_);
glAttachShader(depth_shader_program_, depth_vertex_shader_);
glLinkProgram(depth_shader_program_);
GLint linked;
glGetProgramiv(depth_shader_program_, GL_LINK_STATUS, &linked);
if (!linked) {
GLint length;
glGetProgramiv(depth_shader_program_, GL_INFO_LOG_LENGTH, &length);
std::unique_ptr<GLchar[]> log(
reinterpret_cast<GLchar*>(new uint8_t[length]));
glGetProgramInfoLog(depth_shader_program_, length, &length, log.get());
LOG(FATAL) << "GL Program Linker Error: " << log.get();
}
glUseProgram(depth_shader_program_);
CHECK_OPENGL_NO_ERROR();
// Get attributes.
depth_a_position_location_ = glGetAttribLocation(depth_shader_program_, "in_position");
CHECK_OPENGL_NO_ERROR();
CHECK_GE(depth_a_position_location_, 0) << "Attribute needs to be defined, used and of attribute type.";
depth_u_model_view_matrix_location_ =
glGetUniformLocation(depth_shader_program_, "u_model_view_matrix");
CHECK_OPENGL_NO_ERROR();
depth_u_projection_matrix_location_ =
glGetUniformLocation(depth_shader_program_, "u_projection_matrix");
CHECK_OPENGL_NO_ERROR();
}
void MeshRenderer::CreateDepthAndColorVertexShader() {
const std::string vertex_shader_src =
"#version 300 es\n"
"uniform mat4 u_model_view_matrix;\n"
"uniform mat4 u_projection_matrix;\n"
"in vec4 in_position;\n"
"in vec3 in_color;\n"
"out float var_depth;\n"
"out vec3 var_color;\n"
"void main() {\n"
" var_color = in_color;\n"
" vec4 local_point = u_model_view_matrix * in_position;\n"
" local_point.xyz /= local_point.w;\n"
" var_depth = local_point.z;\n"
" local_point.w = 1.0;\n"
" gl_Position = u_projection_matrix * local_point;\n"
"}\n";
depth_color_vertex_shader_ = glCreateShader(GL_VERTEX_SHADER);
const GLchar* vertex_shader_src_ptr =
static_cast<const GLchar*>(vertex_shader_src.c_str());
glShaderSource(depth_color_vertex_shader_, 1, &vertex_shader_src_ptr, NULL);
glCompileShader(depth_color_vertex_shader_);
GLint compiled;
glGetShaderiv(depth_color_vertex_shader_, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
GLint length;
glGetShaderiv(depth_color_vertex_shader_, GL_INFO_LOG_LENGTH, &length);
std::unique_ptr<GLchar[]> log(
reinterpret_cast<GLchar*>(new uint8_t[length]));
glGetShaderInfoLog(depth_color_vertex_shader_, length, &length, log.get());
LOG(FATAL) << "GL Shader Compilation Error: " << log.get();
}
}
void MeshRenderer::CreateDepthAndColorFragmentShader() {
const std::string fragment_shader_src =
"#version 300 es\n"
"in highp float var_depth;\n"
"in lowp vec3 var_color;\n"
"layout(location = 0) out highp float out_depth;\n"
"layout(location = 1) out lowp vec4 out_color;\n"
"void main()\n"
"{\n"
" out_depth = var_depth;\n"
" out_color = vec4(var_color, 1);\n"
"}\n";
depth_color_fragment_shader_ = glCreateShader(GL_FRAGMENT_SHADER);
const GLchar* fragment_shader_src_ptr =
static_cast<const GLchar*>(fragment_shader_src.c_str());
glShaderSource(depth_color_fragment_shader_, 1, &fragment_shader_src_ptr, NULL);
glCompileShader(depth_color_fragment_shader_);
GLint compiled;
glGetShaderiv(depth_color_fragment_shader_, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
GLint length;
glGetShaderiv(depth_color_fragment_shader_, GL_INFO_LOG_LENGTH, &length);
std::unique_ptr<GLchar[]> log(
reinterpret_cast<GLchar*>(new uint8_t[length]));
glGetShaderInfoLog(depth_color_fragment_shader_, length, &length, log.get());
LOG(FATAL) << "GL Shader Compilation Error: " << log.get();
}
}
void MeshRenderer::CreateDepthAndColorProgram() {
depth_color_shader_program_ = glCreateProgram();
glAttachShader(depth_color_shader_program_, depth_color_fragment_shader_);
glAttachShader(depth_color_shader_program_, depth_color_vertex_shader_);
glLinkProgram(depth_color_shader_program_);
GLint linked;
glGetProgramiv(depth_color_shader_program_, GL_LINK_STATUS, &linked);
if (!linked) {
GLint length;
glGetProgramiv(depth_color_shader_program_, GL_INFO_LOG_LENGTH, &length);
std::unique_ptr<GLchar[]> log(
reinterpret_cast<GLchar*>(new uint8_t[length]));
glGetProgramInfoLog(depth_color_shader_program_, length, &length, log.get());
LOG(FATAL) << "GL Program Linker Error: " << log.get();
}
glUseProgram(depth_color_shader_program_);
CHECK_OPENGL_NO_ERROR();
// Get attributes.
depth_color_a_position_location_ = glGetAttribLocation(depth_color_shader_program_, "in_position");
CHECK_OPENGL_NO_ERROR();
CHECK_GE(depth_color_a_position_location_, 0) << "Attribute needs to be used";
depth_color_a_color_location_ = glGetAttribLocation(depth_color_shader_program_, "in_color");
CHECK_OPENGL_NO_ERROR();
CHECK_GE(depth_color_a_color_location_, 0) << "Attribute needs to be used";
depth_color_u_model_view_matrix_location_ =
glGetUniformLocation(depth_color_shader_program_, "u_model_view_matrix");
CHECK_OPENGL_NO_ERROR();
depth_color_u_projection_matrix_location_ =
glGetUniformLocation(depth_color_shader_program_, "u_projection_matrix");
CHECK_OPENGL_NO_ERROR();
}
void MeshRenderer::SetupProjection(
const Sophus::SE3f& transformation,
const float fx, const float fy, const float cx, const float cy,
float min_depth, float max_depth, GLint u_projection_matrix_location,
GLint u_model_view_matrix_location) {
CHECK_GT(max_depth, min_depth);
CHECK_GT(min_depth, 0);
// Row-wise projection matrix construction.
float matrix[16];
matrix[0] = (2 * fx) / width_;
matrix[4] = 0;
matrix[8] = 2 * (0.5f + cx) / width_ - 1.0f;
matrix[12] = 0;
matrix[1] = 0;
matrix[5] = (2 * fy) / height_;
matrix[9] = 2 * (0.5f + cy) / height_ - 1.0f;
matrix[13] = 0;
matrix[2] = 0;
matrix[6] = 0;
matrix[10] = (max_depth + min_depth) / (max_depth - min_depth);
matrix[14] = -(2 * max_depth * min_depth) / (max_depth - min_depth);
matrix[3] = 0;
matrix[7] = 0;
matrix[11] = 1;
matrix[15] = 0;
glUniformMatrix4fv(u_projection_matrix_location, 1, GL_FALSE, matrix);
CHECK_OPENGL_NO_ERROR();
// Model-view matrix construction.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
matrix[i + j * 4] = transformation.rotationMatrix()(i, j);
}
matrix[i + 12] = transformation.translation()(i);
}
matrix[3] = 0;
matrix[7] = 0;
matrix[11] = 0;
matrix[15] = 1;
glUniformMatrix4fv(u_model_view_matrix_location, 1, GL_FALSE, matrix);
CHECK_OPENGL_NO_ERROR();
// Set viewport.
glViewport(0, 0, width_, height_);
CHECK_OPENGL_NO_ERROR();
}
int MeshRenderer::GetIndexCount(int width, int height) {
constexpr int kStartIndexCount = 2;
const int newline_index_count = (height - 2) * 4;
const int quad_index_count = (width - 1) * (height - 1) * 4;
return quad_index_count + newline_index_count + kStartIndexCount;
}
} // namespace view_correction
| 37.783257 | 106 | 0.746077 | [
"geometry",
"render",
"object",
"model"
] |
8127ec6b3910edd368d346243ee05a581c6ddec2 | 30,455 | cpp | C++ | src/slg/film/filmoutput.cpp | mbrukman/LuxCore | 49a243f441785c9ba7ec1efcbd82fc0bf2595bfe | [
"Apache-2.0"
] | null | null | null | src/slg/film/filmoutput.cpp | mbrukman/LuxCore | 49a243f441785c9ba7ec1efcbd82fc0bf2595bfe | [
"Apache-2.0"
] | null | null | null | src/slg/film/filmoutput.cpp | mbrukman/LuxCore | 49a243f441785c9ba7ec1efcbd82fc0bf2595bfe | [
"Apache-2.0"
] | null | null | null | /***************************************************************************
* Copyright 1998-2020 by authors (see AUTHORS.txt) *
* *
* This file is part of LuxCoreRender. *
* *
* 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 <limits>
#include <algorithm>
#include <exception>
#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/imagebuf.h>
#include "luxrays/core/geometry/point.h"
#include "luxrays/utils/properties.h"
#include "luxrays/utils/safesave.h"
#include "luxrays/utils/fileext.h"
#include "slg/editaction.h"
#include "slg/film/film.h"
#include "slg/film/sampleresult.h"
using namespace std;
using namespace luxrays;
using namespace slg;
OIIO_NAMESPACE_USING
typedef unsigned char BYTE;
//------------------------------------------------------------------------------
// Film
//------------------------------------------------------------------------------
size_t Film::GetOutputSize(const FilmOutputs::FilmOutputType type) const {
switch (type) {
case FilmOutputs::RGB:
return 3 * pixelCount;
case FilmOutputs::RGBA:
return 4 * pixelCount;
case FilmOutputs::RGB_IMAGEPIPELINE:
return 3 * pixelCount;
case FilmOutputs::RGBA_IMAGEPIPELINE:
return 4 * pixelCount;
case FilmOutputs::ALPHA:
return pixelCount;
case FilmOutputs::DEPTH:
return pixelCount;
case FilmOutputs::POSITION:
return 3 * pixelCount;
case FilmOutputs::GEOMETRY_NORMAL:
return 3 * pixelCount;
case FilmOutputs::SHADING_NORMAL:
return 3 * pixelCount;
case FilmOutputs::MATERIAL_ID:
return pixelCount;
case FilmOutputs::DIRECT_DIFFUSE:
return 3 * pixelCount;
case FilmOutputs::DIRECT_GLOSSY:
return 3 * pixelCount;
case FilmOutputs::EMISSION:
return 3 * pixelCount;
case FilmOutputs::INDIRECT_DIFFUSE:
return 3 * pixelCount;
case FilmOutputs::INDIRECT_GLOSSY:
return 3 * pixelCount;
case FilmOutputs::INDIRECT_SPECULAR:
return 3 * pixelCount;
case FilmOutputs::MATERIAL_ID_MASK:
return pixelCount;
case FilmOutputs::DIRECT_SHADOW_MASK:
return pixelCount;
case FilmOutputs::INDIRECT_SHADOW_MASK:
return pixelCount;
case FilmOutputs::RADIANCE_GROUP:
return 3 * pixelCount;
case FilmOutputs::UV:
return 2 * pixelCount;
case FilmOutputs::RAYCOUNT:
return pixelCount;
case FilmOutputs::BY_MATERIAL_ID:
return 3 * pixelCount;
case FilmOutputs::IRRADIANCE:
return 3 * pixelCount;
case FilmOutputs::OBJECT_ID:
return pixelCount;
case FilmOutputs::OBJECT_ID_MASK:
return pixelCount;
case FilmOutputs::BY_OBJECT_ID:
return 3 * pixelCount;
case FilmOutputs::SAMPLECOUNT:
return pixelCount;
case FilmOutputs::CONVERGENCE:
return pixelCount;
case FilmOutputs::MATERIAL_ID_COLOR:
return 3 * pixelCount;
case FilmOutputs::ALBEDO:
return 3 * pixelCount;
case FilmOutputs::AVG_SHADING_NORMAL:
return 3 * pixelCount;
case FilmOutputs::NOISE:
return pixelCount;
case FilmOutputs::USER_IMPORTANCE:
return pixelCount;
default:
throw runtime_error("Unknown FilmOutputType in Film::GetOutputSize(): " + ToString(type));
}
}
bool Film::HasOutput(const FilmOutputs::FilmOutputType type) const {
switch (type) {
case FilmOutputs::RGB:
return HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) || HasChannel(RADIANCE_PER_SCREEN_NORMALIZED);
case FilmOutputs::RGB_IMAGEPIPELINE:
return HasChannel(IMAGEPIPELINE);
case FilmOutputs::RGBA:
return (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) || HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) && HasChannel(ALPHA);
case FilmOutputs::RGBA_IMAGEPIPELINE:
return HasChannel(IMAGEPIPELINE) && HasChannel(ALPHA);
case FilmOutputs::ALPHA:
return HasChannel(ALPHA);
case FilmOutputs::DEPTH:
return HasChannel(DEPTH);
case FilmOutputs::POSITION:
return HasChannel(POSITION);
case FilmOutputs::GEOMETRY_NORMAL:
return HasChannel(GEOMETRY_NORMAL);
case FilmOutputs::SHADING_NORMAL:
return HasChannel(SHADING_NORMAL);
case FilmOutputs::MATERIAL_ID:
return HasChannel(MATERIAL_ID);
case FilmOutputs::DIRECT_DIFFUSE:
return HasChannel(DIRECT_DIFFUSE);
case FilmOutputs::DIRECT_GLOSSY:
return HasChannel(DIRECT_GLOSSY);
case FilmOutputs::EMISSION:
return HasChannel(EMISSION);
case FilmOutputs::INDIRECT_DIFFUSE:
return HasChannel(INDIRECT_DIFFUSE);
case FilmOutputs::INDIRECT_GLOSSY:
return HasChannel(INDIRECT_GLOSSY);
case FilmOutputs::INDIRECT_SPECULAR:
return HasChannel(INDIRECT_SPECULAR);
case FilmOutputs::MATERIAL_ID_MASK:
return HasChannel(MATERIAL_ID_MASK);
case FilmOutputs::DIRECT_SHADOW_MASK:
return HasChannel(DIRECT_SHADOW_MASK);
case FilmOutputs::INDIRECT_SHADOW_MASK:
return HasChannel(INDIRECT_SHADOW_MASK);
case FilmOutputs::RADIANCE_GROUP:
return true;
case FilmOutputs::UV:
return HasChannel(UV);
case FilmOutputs::RAYCOUNT:
return HasChannel(RAYCOUNT);
case FilmOutputs::BY_MATERIAL_ID:
return HasChannel(BY_MATERIAL_ID);
case FilmOutputs::IRRADIANCE:
return HasChannel(IRRADIANCE);
case FilmOutputs::OBJECT_ID:
return HasChannel(OBJECT_ID);
case FilmOutputs::OBJECT_ID_MASK:
return HasChannel(OBJECT_ID_MASK);
case FilmOutputs::BY_OBJECT_ID:
return HasChannel(BY_OBJECT_ID);
case FilmOutputs::SAMPLECOUNT:
return HasChannel(SAMPLECOUNT);
case FilmOutputs::CONVERGENCE:
return HasChannel(CONVERGENCE);
case FilmOutputs::SERIALIZED_FILM:
return filmOutputs.HasType(FilmOutputs::SERIALIZED_FILM);
case FilmOutputs::MATERIAL_ID_COLOR:
return HasChannel(MATERIAL_ID_COLOR);
case FilmOutputs::ALBEDO:
return HasChannel(ALBEDO);
case FilmOutputs::AVG_SHADING_NORMAL:
return HasChannel(AVG_SHADING_NORMAL);
case FilmOutputs::NOISE:
return HasChannel(NOISE);
case FilmOutputs::USER_IMPORTANCE:
return HasChannel(USER_IMPORTANCE);
default:
throw runtime_error("Unknown film output type in Film::HasOutput(): " + ToString(type));
}
}
void Film::Output() {
for (u_int i = 0; i < filmOutputs.GetCount(); ++i)
Output(filmOutputs.GetFileName(i), filmOutputs.GetType(i),&filmOutputs.GetProperties(i));
}
void Film::Output(const string &fileName,const FilmOutputs::FilmOutputType type,
const Properties *props, const bool executeImagePipeline) {
// Handle the special case of the serialized film output
if (type == FilmOutputs::SERIALIZED_FILM) {
if (!filmOutputs.HasType(FilmOutputs::SERIALIZED_FILM))
throw runtime_error("SERIALIZED_FILM has not been configured as output in Film::Output()");
SLG_LOG("Outputting film: " << fileName << " type: " << ToString(type));
if (filmOutputs.UseSafeSave()) {
SafeSave safeSave(fileName);
Film::SaveSerialized(safeSave.GetSaveFileName(), this);
safeSave.Process();
} else
Film::SaveSerialized(fileName, this);
return;
}
u_int maskMaterialIDsIndex = 0;
u_int byMaterialIDsIndex = 0;
u_int maskObjectIDsIndex = 0;
u_int byObjectIDsIndex = 0;
u_int radianceGroupIndex = 0;
u_int imagePipelineIndex = 0;
u_int channelCount = 3;
switch (type) {
case FilmOutputs::RGB:
if (!HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) && !HasChannel(RADIANCE_PER_SCREEN_NORMALIZED))
return;
break;
case FilmOutputs::RGB_IMAGEPIPELINE:
if (!HasChannel(IMAGEPIPELINE))
return;
imagePipelineIndex = props ? props->Get(Property("index")(0)).Get<u_int>() : 0;
if (imagePipelineIndex >= imagePipelines.size())
return;
if (executeImagePipeline)
ExecuteImagePipeline(imagePipelineIndex);
break;
case FilmOutputs::RGBA:
if ((!HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) && !HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) || !HasChannel(ALPHA))
return;
channelCount = 4;
break;
case FilmOutputs::RGBA_IMAGEPIPELINE:
if (!HasChannel(IMAGEPIPELINE) || !HasChannel(ALPHA))
return;
imagePipelineIndex = props ? props->Get(Property("index")(0)).Get<u_int>() : 0;
if (imagePipelineIndex >= imagePipelines.size())
return;
if (executeImagePipeline)
ExecuteImagePipeline(imagePipelineIndex);
channelCount = 4;
break;
case FilmOutputs::ALPHA:
if (!HasChannel(ALPHA))
return;
channelCount = 1;
break;
case FilmOutputs::DEPTH:
if (!HasChannel(DEPTH))
return;
channelCount = 1;
break;
case FilmOutputs::POSITION:
if (!HasChannel(POSITION))
return;
break;
case FilmOutputs::GEOMETRY_NORMAL:
if (!HasChannel(GEOMETRY_NORMAL))
return;
break;
case FilmOutputs::SHADING_NORMAL:
if (!HasChannel(SHADING_NORMAL))
return;
break;
case FilmOutputs::MATERIAL_ID:
if (!HasChannel(MATERIAL_ID))
return;
break;
case FilmOutputs::DIRECT_DIFFUSE:
if (!HasChannel(DIRECT_DIFFUSE))
return;
break;
case FilmOutputs::DIRECT_GLOSSY:
if (!HasChannel(DIRECT_GLOSSY))
return;
break;
case FilmOutputs::EMISSION:
if (!HasChannel(EMISSION))
return;
break;
case FilmOutputs::INDIRECT_DIFFUSE:
if (!HasChannel(INDIRECT_DIFFUSE))
return;
break;
case FilmOutputs::INDIRECT_GLOSSY:
if (!HasChannel(INDIRECT_GLOSSY))
return;
break;
case FilmOutputs::INDIRECT_SPECULAR:
if (!HasChannel(INDIRECT_SPECULAR))
return;
break;
case FilmOutputs::MATERIAL_ID_MASK:
if (HasChannel(MATERIAL_ID_MASK) && props) {
channelCount = 1;
// Look for the material mask ID index
const u_int id = props->Get(Property("id")(255)).Get<u_int>();
bool found = false;
for (u_int i = 0; i < maskMaterialIDs.size(); ++i) {
if (maskMaterialIDs[i] == id) {
maskMaterialIDsIndex = i;
found = true;
break;
}
}
if (!found)
return;
} else
return;
break;
case FilmOutputs::DIRECT_SHADOW_MASK:
if (!HasChannel(DIRECT_SHADOW_MASK))
return;
channelCount = 1;
break;
case FilmOutputs::INDIRECT_SHADOW_MASK:
if (!HasChannel(INDIRECT_SHADOW_MASK))
return;
channelCount = 1;
break;
case FilmOutputs::RADIANCE_GROUP:
if (!props)
return;
radianceGroupIndex = props->Get(Property("id")(0)).Get<u_int>();
if (radianceGroupIndex >= radianceGroupCount)
return;
break;
case FilmOutputs::UV:
if (!HasChannel(UV))
return;
break;
case FilmOutputs::RAYCOUNT:
if (!HasChannel(RAYCOUNT))
return;
channelCount = 1;
break;
case FilmOutputs::BY_MATERIAL_ID:
if (HasChannel(BY_MATERIAL_ID) && props) {
// Look for the material mask ID index
const u_int id = props->Get(Property("id")(255)).Get<u_int>();
bool found = false;
for (u_int i = 0; i < byMaterialIDs.size(); ++i) {
if (byMaterialIDs[i] == id) {
byMaterialIDsIndex = i;
found = true;
break;
}
}
if (!found)
return;
} else
return;
break;
case FilmOutputs::IRRADIANCE:
if (!HasChannel(IRRADIANCE))
return;
break;
case FilmOutputs::OBJECT_ID:
if (!HasChannel(OBJECT_ID))
return;
break;
case FilmOutputs::OBJECT_ID_MASK:
if (HasChannel(OBJECT_ID_MASK) && props) {
channelCount = 1;
// Look for the object mask ID index
const u_int id = props->Get(Property("id")(255)).Get<u_int>();
bool found = false;
for (u_int i = 0; i < maskObjectIDs.size(); ++i) {
if (maskObjectIDs[i] == id) {
maskObjectIDsIndex = i;
found = true;
break;
}
}
if (!found)
return;
} else
return;
break;
case FilmOutputs::BY_OBJECT_ID:
if (HasChannel(BY_OBJECT_ID) && props) {
// Look for the object mask ID index
const u_int id = props->Get(Property("id")(255)).Get<u_int>();
bool found = false;
for (u_int i = 0; i < byObjectIDs.size(); ++i) {
if (byObjectIDs[i] == id) {
byObjectIDsIndex = i;
found = true;
break;
}
}
if (!found)
return;
} else
return;
break;
case FilmOutputs::SAMPLECOUNT:
if (!HasChannel(SAMPLECOUNT))
return;
channelCount = 1;
break;
case FilmOutputs::CONVERGENCE:
if (!HasChannel(CONVERGENCE))
return;
channelCount = 1;
break;
case FilmOutputs::MATERIAL_ID_COLOR:
if (!HasChannel(MATERIAL_ID_COLOR))
return;
break;
case FilmOutputs::ALBEDO:
if (!HasChannel(ALBEDO))
return;
break;
case FilmOutputs::AVG_SHADING_NORMAL:
if (!HasChannel(AVG_SHADING_NORMAL))
return;
break;
case FilmOutputs::NOISE:
if (!HasChannel(NOISE))
return;
channelCount = 1;
break;
case FilmOutputs::USER_IMPORTANCE:
if (!HasChannel(USER_IMPORTANCE))
return;
channelCount = 1;
break;
default:
throw runtime_error("Unknown film output type in Film::Output(): " + ToString(type));
}
ImageBuf buffer;
SLG_LOG("Outputting film: " << fileName << " type: " << ToString(type));
bool hdrImage = false;
const string fileExtension = GetFileNameExt(fileName);
if (fileExtension == ".exr" || fileExtension == ".hdr")
hdrImage = true;
if ((type == FilmOutputs::MATERIAL_ID) || (type == FilmOutputs::OBJECT_ID) ||
((type == FilmOutputs::SAMPLECOUNT) && (!hdrImage))) {
// For IDs we must copy into int buffer first or risk screwing up the IDs
ImageSpec spec(width, height, channelCount, TypeDesc::UINT8);
buffer.reset(spec);
GenericFrameBuffer<1, 0, u_int> *channel;
switch (type) {
case FilmOutputs::MATERIAL_ID:
channel = channel_MATERIAL_ID;
break;
case FilmOutputs::OBJECT_ID:
channel = channel_OBJECT_ID;
break;
case FilmOutputs::SAMPLECOUNT:
channel = channel_SAMPLECOUNT;
break;
default:
throw runtime_error("Unknown film output type in Film::Output(): " + ToString(type));
}
for (ImageBuf::ConstIterator<BYTE> it(buffer); !it.done(); ++it) {
u_int x = it.x();
u_int y = it.y();
BYTE *pixel = (BYTE *)buffer.pixeladdr(x, y, 0);
y = height - y - 1;
if (pixel == NULL)
throw runtime_error("Error while unpacking film data, could not address buffer!");
const u_int src = *(channel->GetPixel(x, y));
pixel[0] = (BYTE)(src & 0x0000ffu);
pixel[1] = (BYTE)((src & 0x00ff00u) >> 8);
pixel[2] = (BYTE)((src & 0xff0000u) >> 16);
}
} else {
// OIIO 1 channel EXR output is apparently not working, I write 3 channels as
// temporary workaround
//
// Note: they are working is just that 1 channel EXR is supposed to be alpha
// and not grey so it is not shown by some program like exrdisplay
// For all others copy into float buffer first and let OIIO figure out the conversion on write
ImageSpec spec(width, height, (channelCount == 1) ? 3 : channelCount, TypeDesc::FLOAT);
buffer.reset(spec);
const double RADIANCE_PER_SCREEN_NORMALIZED_SampleCount = samplesCounts.GetSampleCount_RADIANCE_PER_SCREEN_NORMALIZED();
for (ImageBuf::ConstIterator<float> it(buffer); !it.done(); ++it) {
u_int x = it.x();
u_int y = it.y();
float *pixel = (float *)buffer.pixeladdr(x, y, 0);
y = height - y - 1;
if (pixel == NULL)
throw runtime_error("Error while unpacking film data, could not address buffer!");
switch (type) {
case FilmOutputs::RGB: {
// Accumulate all light groups
GetPixelFromMergedSampleBuffers(0, RADIANCE_PER_SCREEN_NORMALIZED_SampleCount,
x, y, pixel);
break;
}
case FilmOutputs::RGB_IMAGEPIPELINE: {
channel_IMAGEPIPELINEs[imagePipelineIndex]->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::RGBA: {
// Accumulate all light groups
GetPixelFromMergedSampleBuffers(0, RADIANCE_PER_SCREEN_NORMALIZED_SampleCount,
x, y, pixel);
channel_ALPHA->GetWeightedPixel(x, y, &pixel[3]);
break;
}
case FilmOutputs::RGBA_IMAGEPIPELINE: {
channel_IMAGEPIPELINEs[imagePipelineIndex]->GetWeightedPixel(x, y, pixel);
channel_ALPHA->GetWeightedPixel(x, y, &pixel[3]);
break;
}
case FilmOutputs::ALPHA: {
channel_ALPHA->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::DEPTH: {
channel_DEPTH->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::POSITION: {
channel_POSITION->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::GEOMETRY_NORMAL: {
channel_GEOMETRY_NORMAL->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::SHADING_NORMAL: {
channel_SHADING_NORMAL->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::DIRECT_DIFFUSE: {
channel_DIRECT_DIFFUSE->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::DIRECT_GLOSSY: {
channel_DIRECT_GLOSSY->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::EMISSION: {
channel_EMISSION->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::INDIRECT_DIFFUSE: {
channel_INDIRECT_DIFFUSE->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::INDIRECT_GLOSSY: {
channel_INDIRECT_GLOSSY->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::INDIRECT_SPECULAR: {
channel_INDIRECT_SPECULAR->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::MATERIAL_ID_MASK: {
channel_MATERIAL_ID_MASKs[maskMaterialIDsIndex]->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::DIRECT_SHADOW_MASK: {
channel_DIRECT_SHADOW_MASK->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::INDIRECT_SHADOW_MASK: {
channel_INDIRECT_SHADOW_MASK->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::RADIANCE_GROUP: {
// Clear the pixel
pixel[0] = 0.f;
pixel[1] = 0.f;
pixel[2] = 0.f;
// Accumulate all light groups
if (radianceGroupIndex < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size()) {
channel_RADIANCE_PER_SCREEN_NORMALIZEDs[radianceGroupIndex]->AccumulateWeightedPixel(x, y, pixel);
// Normalize the value
const float factor = RADIANCE_PER_SCREEN_NORMALIZED_SampleCount / pixelCount;
pixel[0] *= factor;
pixel[1] *= factor;
pixel[2] *= factor;
}
if (radianceGroupIndex < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size())
channel_RADIANCE_PER_PIXEL_NORMALIZEDs[radianceGroupIndex]->AccumulateWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::UV: {
channel_UV->GetWeightedPixel(x, y, pixel);
pixel[2] = 0.f;
break;
}
case FilmOutputs::RAYCOUNT: {
channel_RAYCOUNT->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::BY_MATERIAL_ID: {
channel_BY_MATERIAL_IDs[byMaterialIDsIndex]->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::IRRADIANCE: {
channel_IRRADIANCE->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::OBJECT_ID_MASK: {
channel_OBJECT_ID_MASKs[maskObjectIDsIndex]->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::BY_OBJECT_ID: {
channel_BY_OBJECT_IDs[byObjectIDsIndex]->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::SAMPLECOUNT: {
u_int val;
channel_SAMPLECOUNT->GetWeightedPixel(x, y, &val);
pixel[0] = val;
break;
}
case FilmOutputs::CONVERGENCE: {
channel_CONVERGENCE->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::MATERIAL_ID_COLOR: {
channel_MATERIAL_ID_COLOR->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::ALBEDO: {
channel_ALBEDO->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::AVG_SHADING_NORMAL: {
channel_AVG_SHADING_NORMAL->GetWeightedPixel(x, y, pixel);
// Normalize the value (should I ?)
/*const float length2 = pixel[0] * pixel[0] + pixel[1] * pixel[1] + pixel[2] * pixel[2];
if (length2 > 0.f) {
const float k = 1.f / sqrtf(length2);
pixel[0] *= k;
pixel[1] *= k;
pixel[2] *= k;
}*/
break;
}
case FilmOutputs::NOISE: {
channel_NOISE->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::USER_IMPORTANCE: {
channel_USER_IMPORTANCE->GetWeightedPixel(x, y, pixel);
break;
}
default:
throw runtime_error("Unknown film output type in Film::Output(): " + ToString(type));
}
// OIIO 1 channel EXR output is apparently not working, I write 3 channels as
// temporary workaround
if (channelCount == 1) {
pixel[1] = pixel[0];
pixel[2] = pixel[0];
}
}
}
if (filmOutputs.UseSafeSave()) {
SafeSave safeSave(fileName);
if (!buffer.write(safeSave.GetSaveFileName()))
throw runtime_error("Error while writing an output type in Film::Output(): " +
safeSave.GetSaveFileName() + " (error = " + geterror() + ")");
safeSave.Process();
} else {
if (!buffer.write(fileName))
throw runtime_error("Error while writing an output type in Film::Output(): " +
fileName + " (error = " + geterror() + ")");
}
}
u_int Film::GetOutputCount(const FilmOutputs::FilmOutputType type) const {
switch (type) {
case FilmOutputs::RGB_IMAGEPIPELINE:
return channel_IMAGEPIPELINEs.size();
case FilmOutputs::RGBA_IMAGEPIPELINE:
return channel_IMAGEPIPELINEs.size();
case FilmOutputs::MATERIAL_ID_MASK:
return channel_MATERIAL_ID_MASKs.size();
case FilmOutputs::RADIANCE_GROUP:
return channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size();
case FilmOutputs::BY_MATERIAL_ID:
return channel_BY_MATERIAL_IDs.size();
case FilmOutputs::OBJECT_ID_MASK:
return channel_OBJECT_ID_MASKs.size();
case FilmOutputs::BY_OBJECT_ID:
return channel_BY_OBJECT_IDs.size();
default:
if (HasOutput(type))
return 1;
else
return 0;
}
}
template<> void Film::GetOutput<float>(const FilmOutputs::FilmOutputType type, float *buffer,
const u_int index, const bool executeImagePipeline) {
if (!HasOutput(type))
throw runtime_error("Film output not defined in Film::GetOutput<float>(): " + ToString(type));
if (index > GetOutputCount(type))
throw runtime_error("Film output index not defined in Film::GetOutput<float>(): " + ToString(type) + "/" + ToString(index));
switch (type) {
case FilmOutputs::RGB: {
const double RADIANCE_PER_SCREEN_NORMALIZED_SampleCount = samplesCounts.GetSampleCount_RADIANCE_PER_SCREEN_NORMALIZED();
for (u_int i = 0; i < pixelCount; ++i)
GetPixelFromMergedSampleBuffers(0,
RADIANCE_PER_SCREEN_NORMALIZED_SampleCount,
i, &buffer[i * 3]);
break;
}
case FilmOutputs::RGB_IMAGEPIPELINE:
if (executeImagePipeline)
ExecuteImagePipeline(index);
copy(channel_IMAGEPIPELINEs[index]->GetPixels(), channel_IMAGEPIPELINEs[index]->GetPixels() + pixelCount * 3, buffer);
break;
case FilmOutputs::RGBA: {
const double RADIANCE_PER_SCREEN_NORMALIZED_SampleCount = samplesCounts.GetSampleCount_RADIANCE_PER_SCREEN_NORMALIZED();
for (u_int i = 0; i < pixelCount; ++i) {
const u_int offset = i * 4;
GetPixelFromMergedSampleBuffers(0,
RADIANCE_PER_SCREEN_NORMALIZED_SampleCount,
i, &buffer[offset]);
channel_ALPHA->GetWeightedPixel(i, &buffer[offset + 3]);
}
break;
}
case FilmOutputs::RGBA_IMAGEPIPELINE: {
if (executeImagePipeline)
ExecuteImagePipeline(index);
float *srcRGB = channel_IMAGEPIPELINEs[index]->GetPixels();
float *dst = buffer;
for (u_int i = 0; i < pixelCount; ++i) {
*dst++ = *srcRGB++;
*dst++ = *srcRGB++;
*dst++ = *srcRGB++;
channel_ALPHA->GetWeightedPixel(i, dst++);
}
break;
}
case FilmOutputs::ALPHA: {
for (u_int i = 0; i < pixelCount; ++i)
channel_ALPHA->GetWeightedPixel(i, &buffer[i]);
break;
}
case FilmOutputs::DEPTH:
copy(channel_DEPTH->GetPixels(), channel_DEPTH->GetPixels() + pixelCount, buffer);
break;
case FilmOutputs::POSITION:
copy(channel_POSITION->GetPixels(), channel_POSITION->GetPixels() + pixelCount * 3, buffer);
break;
case FilmOutputs::GEOMETRY_NORMAL:
copy(channel_GEOMETRY_NORMAL->GetPixels(), channel_GEOMETRY_NORMAL->GetPixels() + pixelCount * 3, buffer);
break;
case FilmOutputs::SHADING_NORMAL:
copy(channel_SHADING_NORMAL->GetPixels(), channel_SHADING_NORMAL->GetPixels() + pixelCount * 3, buffer);
break;
case FilmOutputs::DIRECT_DIFFUSE: {
for (u_int i = 0; i < pixelCount; ++i)
channel_DIRECT_DIFFUSE->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::DIRECT_GLOSSY: {
for (u_int i = 0; i < pixelCount; ++i)
channel_DIRECT_GLOSSY->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::EMISSION: {
for (u_int i = 0; i < pixelCount; ++i)
channel_EMISSION->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::INDIRECT_DIFFUSE: {
for (u_int i = 0; i < pixelCount; ++i)
channel_INDIRECT_DIFFUSE->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::INDIRECT_GLOSSY: {
for (u_int i = 0; i < pixelCount; ++i)
channel_INDIRECT_GLOSSY->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::INDIRECT_SPECULAR: {
for (u_int i = 0; i < pixelCount; ++i)
channel_INDIRECT_SPECULAR->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::MATERIAL_ID_MASK: {
for (u_int i = 0; i < pixelCount; ++i)
channel_MATERIAL_ID_MASKs[index]->GetWeightedPixel(i, &buffer[i]);
break;
}
case FilmOutputs::DIRECT_SHADOW_MASK: {
for (u_int i = 0; i < pixelCount; ++i)
channel_DIRECT_SHADOW_MASK->GetWeightedPixel(i, &buffer[i]);
break;
}
case FilmOutputs::INDIRECT_SHADOW_MASK: {
for (u_int i = 0; i < pixelCount; ++i)
channel_INDIRECT_SHADOW_MASK->GetWeightedPixel(i, &buffer[i]);
break;
}
case FilmOutputs::RADIANCE_GROUP: {
fill(buffer, buffer + 3 * pixelCount, 0.f);
if (index < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size()) {
const ImagePipeline *ip = (imagePipelines.size() > 0) ? imagePipelines[0] : NULL;
float *dst = buffer;
for (u_int i = 0; i < pixelCount; ++i) {
float c[3];
channel_RADIANCE_PER_PIXEL_NORMALIZEDs[index]->GetWeightedPixel(i, c);
if (ip)
ip->radianceChannelScales[index].Scale(c);
*dst++ += c[0];
*dst++ += c[1];
*dst++ += c[2];
}
}
if (index < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size()) {
const ImagePipeline *ip = (imagePipelines.size() > 0) ? imagePipelines[0] : NULL;
float *dst = buffer;
for (u_int i = 0; i < pixelCount; ++i) {
float c[3];
channel_RADIANCE_PER_SCREEN_NORMALIZEDs[index]->GetWeightedPixel(i, c);
if (ip)
ip->radianceChannelScales[index].Scale(c);
*dst++ += c[0];
*dst++ += c[1];
*dst++ += c[2];
}
}
break;
}
case FilmOutputs::UV:
copy(channel_UV->GetPixels(), channel_UV->GetPixels() + pixelCount * 2, buffer);
break;
case FilmOutputs::RAYCOUNT:
copy(channel_RAYCOUNT->GetPixels(), channel_RAYCOUNT->GetPixels() + pixelCount, buffer);
break;
case FilmOutputs::BY_MATERIAL_ID: {
for (u_int i = 0; i < pixelCount; ++i)
channel_BY_MATERIAL_IDs[index]->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::IRRADIANCE: {
for (u_int i = 0; i < pixelCount; ++i)
channel_IRRADIANCE->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::OBJECT_ID_MASK: {
for (u_int i = 0; i < pixelCount; ++i)
channel_OBJECT_ID_MASKs[index]->GetWeightedPixel(i, &buffer[i]);
break;
}
case FilmOutputs::BY_OBJECT_ID: {
for (u_int i = 0; i < pixelCount; ++i)
channel_BY_OBJECT_IDs[index]->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::CONVERGENCE:
copy(channel_CONVERGENCE->GetPixels(), channel_CONVERGENCE->GetPixels() + pixelCount, buffer);
break;
case FilmOutputs::MATERIAL_ID_COLOR: {
for (u_int i = 0; i < pixelCount; ++i)
channel_MATERIAL_ID_COLOR->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::ALBEDO: {
for (u_int i = 0; i < pixelCount; ++i)
channel_ALBEDO->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::AVG_SHADING_NORMAL: {
for (u_int i = 0; i < pixelCount; ++i)
channel_AVG_SHADING_NORMAL->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::NOISE:
copy(channel_NOISE->GetPixels(), channel_NOISE->GetPixels() + pixelCount, buffer);
break;
case FilmOutputs::USER_IMPORTANCE:
copy(channel_USER_IMPORTANCE->GetPixels(), channel_USER_IMPORTANCE->GetPixels() + pixelCount, buffer);
break;
default:
throw runtime_error("Unknown film output type in Film::GetOutput<float>(): " + ToString(type));
}
}
template<> void Film::GetOutput<u_int>(const FilmOutputs::FilmOutputType type, u_int *buffer,
const u_int index, const bool executeImagePipeline) {
if (!HasOutput(type))
throw runtime_error("Film output not defined in Film::GetOutput<u_int>(): " + ToString(type));
if (index > GetOutputCount(type))
throw runtime_error("Film output index not defined in Film::GetOutput<float>(): " + ToString(type) + "/" + ToString(index));
switch (type) {
case FilmOutputs::MATERIAL_ID:
copy(channel_MATERIAL_ID->GetPixels(), channel_MATERIAL_ID->GetPixels() + pixelCount, buffer);
break;
case FilmOutputs::OBJECT_ID:
copy(channel_OBJECT_ID->GetPixels(), channel_OBJECT_ID->GetPixels() + pixelCount, buffer);
break;
case FilmOutputs::SAMPLECOUNT:
copy(channel_SAMPLECOUNT->GetPixels(), channel_SAMPLECOUNT->GetPixels() + pixelCount, buffer);
break;
default:
throw runtime_error("Unknown film output type in Film::GetOutput<u_int>(): " + ToString(type));
}
}
| 31.790188 | 126 | 0.671581 | [
"geometry",
"object"
] |
812861c969962a3d4aeb288550ec2b8a29d20a35 | 3,647 | cpp | C++ | libs/mesh/meshPhysicalNodesHex3D.cpp | noelchalmers/streamparanumal | 12d15b7f2f0404dfe66f3ac330a33b8b7fd890d7 | [
"MIT"
] | null | null | null | libs/mesh/meshPhysicalNodesHex3D.cpp | noelchalmers/streamparanumal | 12d15b7f2f0404dfe66f3ac330a33b8b7fd890d7 | [
"MIT"
] | null | null | null | libs/mesh/meshPhysicalNodesHex3D.cpp | noelchalmers/streamparanumal | 12d15b7f2f0404dfe66f3ac330a33b8b7fd890d7 | [
"MIT"
] | 4 | 2021-09-03T20:23:19.000Z | 2022-03-10T05:12:33.000Z | /*
The MIT License (MIT)
Copyright (c) 2020 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus
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 "mesh.hpp"
#include "mesh/mesh3D.hpp"
void meshHex3D::PhysicalNodes(){
x = (dfloat*) calloc((Nelements+totalHaloPairs)*Np,sizeof(dfloat));
y = (dfloat*) calloc((Nelements+totalHaloPairs)*Np,sizeof(dfloat));
z = (dfloat*) calloc((Nelements+totalHaloPairs)*Np,sizeof(dfloat));
dlong cnt = 0;
for(dlong e=0;e<Nelements;++e){ /* for each element */
dlong id = e*Nverts;
dfloat xe1 = EX[id+0]; /* x-coordinates of vertices */
dfloat xe2 = EX[id+1];
dfloat xe3 = EX[id+2];
dfloat xe4 = EX[id+3];
dfloat xe5 = EX[id+4];
dfloat xe6 = EX[id+5];
dfloat xe7 = EX[id+6];
dfloat xe8 = EX[id+7];
dfloat ye1 = EY[id+0]; /* y-coordinates of vertices */
dfloat ye2 = EY[id+1];
dfloat ye3 = EY[id+2];
dfloat ye4 = EY[id+3];
dfloat ye5 = EY[id+4];
dfloat ye6 = EY[id+5];
dfloat ye7 = EY[id+6];
dfloat ye8 = EY[id+7];
dfloat ze1 = EZ[id+0]; /* z-coordinates of vertices */
dfloat ze2 = EZ[id+1];
dfloat ze3 = EZ[id+2];
dfloat ze4 = EZ[id+3];
dfloat ze5 = EZ[id+4];
dfloat ze6 = EZ[id+5];
dfloat ze7 = EZ[id+6];
dfloat ze8 = EZ[id+7];
for(int n=0;n<Np;++n){ /* for each node */
/* (r,s,t) coordinates of interpolation nodes*/
dfloat rn = r[n];
dfloat sn = s[n];
dfloat tn = t[n];
/* physical coordinate of interpolation node */
x[cnt] =
+0.125*(1-rn)*(1-sn)*(1-tn)*xe1
+0.125*(1+rn)*(1-sn)*(1-tn)*xe2
+0.125*(1+rn)*(1+sn)*(1-tn)*xe3
+0.125*(1-rn)*(1+sn)*(1-tn)*xe4
+0.125*(1-rn)*(1-sn)*(1+tn)*xe5
+0.125*(1+rn)*(1-sn)*(1+tn)*xe6
+0.125*(1+rn)*(1+sn)*(1+tn)*xe7
+0.125*(1-rn)*(1+sn)*(1+tn)*xe8;
y[cnt] =
+0.125*(1-rn)*(1-sn)*(1-tn)*ye1
+0.125*(1+rn)*(1-sn)*(1-tn)*ye2
+0.125*(1+rn)*(1+sn)*(1-tn)*ye3
+0.125*(1-rn)*(1+sn)*(1-tn)*ye4
+0.125*(1-rn)*(1-sn)*(1+tn)*ye5
+0.125*(1+rn)*(1-sn)*(1+tn)*ye6
+0.125*(1+rn)*(1+sn)*(1+tn)*ye7
+0.125*(1-rn)*(1+sn)*(1+tn)*ye8;
z[cnt] =
+0.125*(1-rn)*(1-sn)*(1-tn)*ze1
+0.125*(1+rn)*(1-sn)*(1-tn)*ze2
+0.125*(1+rn)*(1+sn)*(1-tn)*ze3
+0.125*(1-rn)*(1+sn)*(1-tn)*ze4
+0.125*(1-rn)*(1-sn)*(1+tn)*ze5
+0.125*(1+rn)*(1-sn)*(1+tn)*ze6
+0.125*(1+rn)*(1+sn)*(1+tn)*ze7
+0.125*(1-rn)*(1+sn)*(1+tn)*ze8;
++cnt;
}
}
halo->Exchange(x, Np, ogs_dfloat);
halo->Exchange(y, Np, ogs_dfloat);
halo->Exchange(z, Np, ogs_dfloat);
}
| 31.991228 | 78 | 0.594187 | [
"mesh"
] |
812877b1fe531908cf0c0a3b8d02a1e67d4aaa6a | 5,112 | cpp | C++ | modules/gapi/src/api/gkernel.cpp | PWhiddy/opencv | 29e88e50ffaa8393eacd8343f09fbf2388535161 | [
"BSD-3-Clause"
] | null | null | null | modules/gapi/src/api/gkernel.cpp | PWhiddy/opencv | 29e88e50ffaa8393eacd8343f09fbf2388535161 | [
"BSD-3-Clause"
] | null | null | null | modules/gapi/src/api/gkernel.cpp | PWhiddy/opencv | 29e88e50ffaa8393eacd8343f09fbf2388535161 | [
"BSD-3-Clause"
] | 1 | 2019-10-12T04:45:03.000Z | 2019-10-12T04:45:03.000Z | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2018 Intel Corporation
#include <iostream> // cerr
#include <functional> // hash
#include <numeric> // accumulate
#include <ade/util/algorithm.hpp>
#include "opencv2/core/cvdef.h"
#include "logger.hpp"
#include "opencv2/gapi/gkernel.hpp"
#include "api/gbackend_priv.hpp"
// GKernelPackage public implementation ////////////////////////////////////////
void cv::gapi::GKernelPackage::remove(const cv::gapi::GBackend& backend)
{
m_backend_kernels.erase(backend);
}
bool cv::gapi::GKernelPackage::includesAPI(const std::string &id) const
{
// In current form not very efficient (n * log n)
auto it = std::find_if(m_backend_kernels.begin(),
m_backend_kernels.end(),
[&id](const M::value_type &p) {
return ade::util::contains(p.second, id);
});
return (it != m_backend_kernels.end());
}
std::size_t cv::gapi::GKernelPackage::size() const
{
return std::accumulate(m_backend_kernels.begin(),
m_backend_kernels.end(),
static_cast<std::size_t>(0u),
[](std::size_t acc, const M::value_type& v) {
return acc + v.second.size();
});
}
cv::gapi::GKernelPackage cv::gapi::combine(const GKernelPackage &lhs,
const GKernelPackage &rhs,
const cv::unite_policy policy)
{
if (policy == cv::unite_policy::REPLACE)
{
// REPLACE policy: if there is a collision, prefer RHS
// to LHS
// since OTHER package has a prefernece, start with its copy
GKernelPackage result(rhs);
// now iterate over LHS package and put kernel if and only
// if there's no such one
for (const auto &backend : lhs.m_backend_kernels)
{
for (const auto &kimpl : backend.second)
{
if (!result.includesAPI(kimpl.first))
result.m_backend_kernels[backend.first].insert(kimpl);
}
}
return result;
}
else if (policy == cv::unite_policy::KEEP)
{
// KEEP policy: if there is a collision, just keep two versions
// of a kernel
GKernelPackage result(lhs);
for (const auto &p : rhs.m_backend_kernels)
{
result.m_backend_kernels[p.first].insert(p.second.begin(),
p.second.end());
}
return result;
}
else GAPI_Assert(false);
return GKernelPackage();
}
std::pair<cv::gapi::GBackend, cv::GKernelImpl>
cv::gapi::GKernelPackage::lookup(const std::string &id,
const GLookupOrder &order) const
{
if (order.empty())
{
// If order is empty, return what comes first
auto it = std::find_if(m_backend_kernels.begin(),
m_backend_kernels.end(),
[&id](const M::value_type &p) {
return ade::util::contains(p.second, id);
});
if (it != m_backend_kernels.end())
{
// FIXME: Two lookups!
return std::make_pair(it->first, it->second.find(id)->second);
}
}
else
{
// There is order, so:
// 1. Limit search scope only to specified backends
// FIXME: Currently it is not configurable if search can fall-back
// to other backends (not listed in order) if kernel hasn't been found
// in the look-up list
// 2. Query backends in the specified order
for (const auto &selected_backend : order)
{
const auto kernels_it = m_backend_kernels.find(selected_backend);
if (kernels_it == m_backend_kernels.end())
{
GAPI_LOG_WARNING(NULL,
"Backend "
<< &selected_backend.priv() // FIXME: name instead
<< " was listed in lookup list but was not found "
"in the package");
continue;
}
if (ade::util::contains(kernels_it->second, id))
{
// FIXME: two lookups!
return std::make_pair(selected_backend, kernels_it->second.find(id)->second);
}
}
}
// If reached here, kernel was not found among selected backends.
util::throw_error(std::logic_error("Kernel " + id + " was not found"));
}
std::vector<cv::gapi::GBackend> cv::gapi::GKernelPackage::backends() const
{
std::vector<cv::gapi::GBackend> result;
for (const auto &p : m_backend_kernels) result.emplace_back(p.first);
return result;
}
| 36 | 93 | 0.536776 | [
"vector"
] |
8131f94fe2fac7c103831f471b630f2284dc5654 | 10,098 | cxx | C++ | plugins/examples/gradient_viewer.cxx | IXDdev/IXD_engine | 497c1fee90e486c19debc5347b740b56b1fef416 | [
"BSD-3-Clause"
] | 11 | 2017-09-30T12:21:55.000Z | 2021-04-29T21:31:57.000Z | plugins/examples/gradient_viewer.cxx | IXDdev/IXD_engine | 497c1fee90e486c19debc5347b740b56b1fef416 | [
"BSD-3-Clause"
] | 2 | 2017-07-11T11:20:08.000Z | 2018-03-27T12:09:02.000Z | plugins/examples/gradient_viewer.cxx | IXDdev/IXD_engine | 497c1fee90e486c19debc5347b740b56b1fef416 | [
"BSD-3-Clause"
] | 24 | 2018-03-27T11:46:16.000Z | 2021-05-01T20:28:34.000Z | #include "gradient_viewer.h"
#include <cgv/defines/quote.h>
#include <cgv/math/ftransform.h>
#include <cgv/gui/trigger.h>
#include <cgv/gui/key_event.h>
#include <cgv/gui/mouse_event.h>
#include <cgv/reflect/reflect_enum.h>
#include <cgv/signal/rebind.h>
#include <cgv_gl/gl/gl.h>
#include <cgv_gl/gl/gl_tools.h>
#include <cgv/media/image/image_reader.h>
namespace cgv {
namespace reflect {
}
}
gradient_viewer::gradient_viewer ()
// configure texture format, filtering and wrapping (no context necessary)
: tf_tex("[R,G,B,A]"), volume_tex("flt32[R]"), gradient_tex("flt32[R,G,B,A]")
{
tf_tex.set_min_filter(cgv::render::TextureFilter::TF_LINEAR);
tf_tex.set_mag_filter(cgv::render::TextureFilter::TF_LINEAR);
tf_tex.set_wrap_s(cgv::render::TextureWrap::TW_CLAMP_TO_EDGE);
tf_tex.set_wrap_t(cgv::render::TextureWrap::TW_CLAMP_TO_EDGE);
volume_tex.set_min_filter(cgv::render::TF_LINEAR_MIPMAP_LINEAR);
volume_tex.set_mag_filter(cgv::render::TF_LINEAR);
volume_tex.set_wrap_s(cgv::render::TW_CLAMP_TO_BORDER);
volume_tex.set_wrap_t(cgv::render::TW_CLAMP_TO_BORDER);
volume_tex.set_wrap_r(cgv::render::TW_CLAMP_TO_BORDER);
volume_tex.set_border_color(0.0f, 0.0f, 0.0f, 0.0f);
gradient_tex.set_min_filter(cgv::render::TF_LINEAR);
gradient_tex.set_mag_filter(cgv::render::TF_LINEAR);
gradient_tex.set_wrap_s(cgv::render::TW_CLAMP_TO_EDGE);
gradient_tex.set_wrap_t(cgv::render::TW_CLAMP_TO_EDGE);
gradient_tex.set_wrap_r(cgv::render::TW_CLAMP_TO_EDGE);
set_name("Gradient Viewer");
show_volume = true;
show_gradients = true;
shape = S_ELLIPSOID;
gradient_mode = GM_SOBEL_OPTIMIZED;
vres = uvec3(128, 64, 29); // odd shaped resolution to show the shader is not limited to nice power-of-two resolutions
do_calculate_gradients = false;
astyle.length_scale = 0.05f;
astyle.radius_relative_to_length = 0.05f;
view_ptr = nullptr;
}
void gradient_viewer::stream_stats(std::ostream& os)
{
os << "gradient_viewer: resolution=" << vres[0] << "x" << vres[1] << "x" << vres[2] << std::endl;
}
bool gradient_viewer::self_reflect(cgv::reflect::reflection_handler& rh)
{
return
rh.reflect_member("show_gradients", show_gradients)&&
rh.reflect_member("show_volume", show_volume);
}
void gradient_viewer::stream_help(std::ostream& os)
{
os << "gradient_viewer: toggle <G>radient, toggle <V>olume\n";
}
bool gradient_viewer::handle(cgv::gui::event& e)
{
if (e.get_kind() != cgv::gui::EID_KEY)
return false;
auto& ke = static_cast<cgv::gui::key_event&>(e);
if (ke.get_action() == cgv::gui::KA_RELEASE)
return false;
switch (ke.get_key()) {
case 'V': show_volume = !show_volume; on_set(&show_volume); return true;
case 'G': show_gradients = !show_gradients; on_set(&show_gradients); return true;
default: break;
}
return false;
}
void gradient_viewer::on_set(void* member_ptr)
{
if (member_ptr == &gradient_mode)
do_calculate_gradients = true;
update_member(member_ptr);
post_redraw();
}
void gradient_viewer::create_test_volume(cgv::render::context& ctx)
{
// destruct previous textures
volume_tex.destruct(ctx);
gradient_tex.destruct(ctx);
// configure extents
int min_ext_axis = cgv::math::min_index(vres);
float min_ext = (float)vres[min_ext_axis];
vec3 vbox_ext = vec3(vres) / vec3(min_ext);
vec3 vbox_min = -0.5f * vbox_ext;
vec3 half_vres = 0.5f * vec3(vres);
// compute volume data
std::vector<float> vol_data(vres[0] * vres[1] * vres[2]);
uvec3 voxel;
unsigned i;
for (i = 0, voxel[2] = 0; voxel[2] < vres[2]; ++voxel[2])
for (voxel[1] = 0; voxel[1] < vres[1]; ++voxel[1])
for (voxel[0] = 0; voxel[0] < vres[0]; ++voxel[0], ++i) {
vec3 p = (vec3(voxel) - half_vres) / half_vres;
if (shape == S_ELLIPSOID) {
float dist = length(p);
if (dist >= 0.5f && dist <= 1.0f && p[1] < 0.4f)
vol_data[i] = 1.0;
}
else {
if (p[0] > -0.5f && p[0] < 0.5f && p[1] > -0.5f && p[1] < 0.5f && p[2] > -0.5f && p[2] < 0.5f)
vol_data[i] = 1.0f;
}
}
// transfer volume data into volume texture and compute mipmaps
cgv::data::data_format vol_df(vres[0], vres[1], vres[2], cgv::type::info::TypeId::TI_FLT32, cgv::data::ComponentFormat::CF_R);
cgv::data::const_data_view vol_dv(&vol_df, &vol_data.front());
volume_tex.create(ctx, vol_dv, 0);
volume_tex.generate_mipmaps(ctx);
// set transformation in volume rendering style
vstyle.transformation_matrix = cgv::math::translate4(vbox_min) * cgv::math::scale4(vbox_ext);
// make sure gradient texture is recomputed
do_calculate_gradients = true;
}
void gradient_viewer::calculate_gradient_texture(cgv::render::context& ctx)
{
//********** compute gradient texture with compute shader *************
unsigned group_size = 4;
uvec3 num_groups = ceil(vec3(vres) / (float)group_size);
if (!gradient_tex.is_created())
gradient_tex.create(ctx, cgv::render::TT_3D, vres[0], vres[1], vres[2]);
// bind textures as 3D images (compare uniform declarations in compute shader gradient_3d.glcs)
const int volume_tex_handle = (const int&)volume_tex.handle - 1;
const int gradient_tex_handle = (const int&)gradient_tex.handle - 1;
glBindImageTexture(0, volume_tex_handle, 0, GL_TRUE, 0, GL_READ_ONLY, GL_R32F);
glBindImageTexture(1, gradient_tex_handle, 0, GL_TRUE, 0, GL_WRITE_ONLY, GL_RGBA32F);
// enable, configure, run and disable program
gradient_3d_prog.enable(ctx);
gradient_3d_prog.set_uniform(ctx, "resolution", vres);
gradient_3d_prog.set_uniform(ctx, "gradient_mode", (int)gradient_mode);
glDispatchCompute(num_groups[0], num_groups[1], num_groups[2]);
// do something else
glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
gradient_3d_prog.disable(ctx);
// clear 3D image bindings
glBindImageTexture(0, 0, 0, GL_TRUE, 0, GL_READ_ONLY, GL_R32F);
glBindImageTexture(1, 0, 0, GL_TRUE, 0, GL_WRITE_ONLY, GL_RGBA32F);
// read texture into memory
std::vector<vec4> gradient_data(vres[0] * vres[1] * vres[2], vec4(0.0f));
gradient_tex.enable(ctx, 0);
glGetTexImage(GL_TEXTURE_3D, 0, GL_RGBA, GL_FLOAT, (void*)gradient_data.data());
gradient_tex.disable(ctx);
//************** construct geometry data for arrow rendering
// clear previous data
positions.clear();
directions.clear();
colors.clear();
// configure extents
int min_ext_axis = cgv::math::min_index(vres);
float min_ext = (float)vres[min_ext_axis];
vec3 vbox_ext = vec3(vres) / vec3(min_ext);
vec3 vbox_min = -0.5f * vbox_ext;
vec3 half_vres = 0.5f * vec3(vres);
vec3 inv_vres = vec3(1.0f) / vec3(vres);
// Loop over all voxels and place arrows to visualize the gradients
uvec3 voxel;
unsigned i;
for (i = 0, voxel[2] = 0; voxel[2] < vres[2]; ++voxel[2])
for (voxel[1] = 0; voxel[1] < vres[1]; ++voxel[1])
for (voxel[0] = 0; voxel[0] < vres[0]; ++voxel[0], ++i) {
vec3 p = 0.5f * vbox_ext * (vec3(voxel) - half_vres) / half_vres;
vec3 grad3 = reinterpret_cast<const vec3&>(gradient_data[i]);
if (grad3.sqr_length() > 0.0f) {
positions.push_back(p);
vec3 grad = normalize(grad3);
directions.push_back(grad);
grad = 0.5f * grad + 0.5f;
colors.push_back(rgb(grad[0], grad[1], grad[2]));
}
}
do_calculate_gradients = false;
}
void gradient_viewer::clear(cgv::render::context& ctx)
{
cgv::render::ref_volume_renderer(ctx, -1);
cgv::render::ref_arrow_renderer(ctx, -1);
}
bool gradient_viewer::init(cgv::render::context& ctx)
{
cgv::render::ref_volume_renderer(ctx, 1);
cgv::render::ref_arrow_renderer(ctx, 1);
view_ptr = find_view_as_node();
if (!view_ptr)
return false;
// construct compute shader program
if (!gradient_3d_prog.build_program(ctx, "gradient_3d.glpr", true)) {
std::cerr << "ERROR in gradient_viewer ::init() ... could not build program " << name << ".glpr" << std::endl;
return false;
}
// load image data of transfer function to texture
cgv::data::data_format format;
cgv::media::image::image_reader image(format);
cgv::data::data_view tf_data;
//if (!image.read_image(QUOTE_SYMBOL_VALUE(INPUT_DIR) "/res/inferno.bmp", tf_data) &&
if (!image.read_image("res://inferno.bmp", tf_data))
abort();
tf_tex.create(ctx, tf_data, 0);
create_test_volume(ctx);
return true;
}
void gradient_viewer::init_frame(cgv::render::context& ctx) {
if(do_calculate_gradients) {
calculate_gradient_texture(ctx);
update_member(&do_calculate_gradients);
}
}
void gradient_viewer::draw(cgv::render::context& ctx)
{
if (show_gradients && !positions.empty()) {
cgv::render::arrow_renderer& ar = cgv::render::ref_arrow_renderer(ctx);
ar.set_render_style(astyle);
ar.set_position_array(ctx, positions);
ar.set_direction_array(ctx, directions);
ar.set_color_array(ctx, colors);
ar.render(ctx, 0, positions.size());
}
}
void gradient_viewer::after_finish(cgv::render::context& ctx)
{
if (!view_ptr)
return;
vec3 eye_pos = view_ptr->get_eye();
vec3 view_dir = view_ptr->get_view_dir();
if (show_volume) {
vstyle.transfer_function_texture_unit = 1;
auto& vr = cgv::render::ref_volume_renderer(ctx);
vr.set_volume_texture(&volume_tex);
//vr.set_volume_texture(&gradient_tex);
vr.set_eye_position(eye_pos);
vr.set_render_style(vstyle);
tf_tex.enable(ctx, vstyle.transfer_function_texture_unit);
vr.render(ctx, 0, 0);
tf_tex.disable(ctx);
}
}
void gradient_viewer::create_gui()
{
add_decorator("Gradient Viewer", "heading", "level=2");
add_member_control(this, "show volume", show_volume, "check");
add_member_control(this, "show gradients", show_gradients, "check");
add_member_control(this, "gradient mode", gradient_mode, "dropdown", "enums='central differences,Sobel,optimized Sobel'");
add_member_control(this, "calculate gradients", do_calculate_gradients, "toggle", "");
if(begin_tree_node("Volume rendering", vstyle, false)) {
align("\a");
add_gui("vstyle", vstyle);
align("\b");
end_tree_node(vstyle);
}
if(begin_tree_node("Arrow rendering", astyle, false)) {
align("\a");
add_gui("astyle", astyle);
align("\b");
end_tree_node(astyle);
}
}
#include <cgv/base/register.h>
cgv::base::factory_registration<gradient_viewer> gradient_viewer_fac("new/GPGPU/gradient_viewer", 'G');
| 31.754717 | 127 | 0.710438 | [
"geometry",
"render",
"shape",
"vector",
"3d"
] |
81352bdede33850b00ecbd12272c5b7382d616e9 | 2,340 | cpp | C++ | components/srp/math.cpp | NeilBetham/rollk | e82026397c892b5f0d3b53891d5efa51d941fd9d | [
"MIT"
] | 4 | 2018-06-12T21:48:01.000Z | 2021-04-01T15:18:50.000Z | components/srp/math.cpp | NeilBetham/rollk | e82026397c892b5f0d3b53891d5efa51d941fd9d | [
"MIT"
] | null | null | null | components/srp/math.cpp | NeilBetham/rollk | e82026397c892b5f0d3b53891d5efa51d941fd9d | [
"MIT"
] | 1 | 2018-08-18T13:05:31.000Z | 2018-08-18T13:05:31.000Z | #include "srp/math.hpp"
#include <cstdint>
#include "srp/utils.hpp"
using namespace std;
namespace SRP {
BigNum Math::hash(const vector<BigNum>& h, bool pad) {
uint64_t safe_prime_size = _prime.export_raw().size(); // TODO: Optimize
string to_hash;
for(auto& val : h) {
string val_to_pad = val.export_raw();
if(pad) {
for(int i = val_to_pad.size(); i < safe_prime_size; i++) {
val_to_pad.insert(val_to_pad.begin(), 0);
}
}
to_hash += val_to_pad;
}
return BigNum::from_raw(_hash_fn.hash(to_hash)); // % prime_n;
}
// a^n (mod m)
BigNum Math::mod_pow(const BigNum& b, const BigNum& e){
return SRP::mod_pow(b, e, _prime);
}
// k = H(n, g)
BigNum Math::get_k() {
return hash({_prime, _generator});
}
// x = H(salt | H(username | ':' | password))
BigNum Math::get_x(const std::string& username, const std::string& password, const BigNum& salt) {
string up_hash = _hash_fn.hash(username + ":" + password);
string hash_val = _hash_fn.hash(salt.export_raw() + up_hash);
return BigNum::from_raw(hash_val);
}
// u = H(A, B)
BigNum Math::get_u(const BigNum& A, const BigNum& B) {
return hash({A, B});
}
// v = g^x (mod n)
BigNum Math::get_v(const BigNum& x) {
return mod_pow(_generator, x);
}
// A = g^a (mod n)
BigNum Math::get_A(const BigNum& a) {
return mod_pow(_generator, a);
}
// B = g^b + k v (mod N)
BigNum Math::get_B(const BigNum& b, const BigNum& k, const BigNum& v) {
return (k * v + SRP::mod_pow(_generator, b, _prime)) % _prime;
}
// Server S = (A * v^u) ^ b % n
BigNum Math::get_S_host(const BigNum& A, const BigNum& v, const BigNum& u, const BigNum& b) {
return mod_pow(A * mod_pow(v, u), b);
}
// K = H(S)
BigNum Math::get_K(const BigNum& S) {
return hash({S});
}
// Client M = H(H(N) xor H(g), H(I), s, A, B, K)
BigNum Math::get_M_client(const string& username, const BigNum& s, const BigNum& A, const BigNum& B, const BigNum& K) {
BigNum hn = BigNum::from_raw(_hash_fn.hash(_prime.export_raw()));
BigNum hg = BigNum::from_raw(_hash_fn.hash(_generator.export_raw()));
BigNum hu = BigNum::from_raw(_hash_fn.hash(username));
return hash({hn ^ hg, hu, s, A, B, K}, false);
}
// Host M = H(A, M, K)
BigNum Math::get_M_host(const BigNum& A, const BigNum& M, const BigNum& K) {
return hash({A, M, K}, false);
}
} // namespace SRP
| 23.168317 | 119 | 0.634615 | [
"vector"
] |
813b57a0e7438332de49bb6132b7f6c5380f3ae4 | 26,665 | hpp | C++ | include/seqan3/core/algorithm/configuration.hpp | kloetzl/seqan3 | 96216a1917d4234cd11a48cdbebbee34abe086f4 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | include/seqan3/core/algorithm/configuration.hpp | kloetzl/seqan3 | 96216a1917d4234cd11a48cdbebbee34abe086f4 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | include/seqan3/core/algorithm/configuration.hpp | kloetzl/seqan3 | 96216a1917d4234cd11a48cdbebbee34abe086f4 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | // -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
/*!\file
* \brief Provides seqan3::detail::configuration and utility functions.
* \author Rene Rahn <rene.rahn AT fu-berlin.de>
*/
#pragma once
#include <tuple>
#include <meta/meta.hpp>
#include <seqan3/core/algorithm/concept.hpp>
#include <seqan3/core/algorithm/configuration_utility.hpp>
#include <seqan3/core/algorithm/pipeable_config_element.hpp>
#include <seqan3/core/type_list/traits.hpp>
#include <seqan3/core/tuple_utility.hpp>
#include <seqan3/core/type_list/type_list.hpp>
#include <seqan3/std/concepts>
namespace seqan3
{
//!\cond
// Forward declaration for friend declaration definitions below.
template <detail::config_element_specialisation ... configs_t>
class configuration;
template <typename lhs_derived_t, typename lhs_value_t, typename rhs_derived_t, typename rhs_value_t>
constexpr auto operator|(pipeable_config_element<lhs_derived_t, lhs_value_t> && lhs,
pipeable_config_element<rhs_derived_t, rhs_value_t> && rhs)
{
return configuration{static_cast<lhs_derived_t &&>(lhs)}.push_back(static_cast<rhs_derived_t &&>(rhs));
}
template <typename lhs_derived_t, typename lhs_value_t, typename rhs_derived_t, typename rhs_value_t>
constexpr auto operator|(pipeable_config_element<lhs_derived_t, lhs_value_t> && lhs,
pipeable_config_element<rhs_derived_t, rhs_value_t> const & rhs)
{
return configuration{static_cast<lhs_derived_t &&>(lhs)}.push_back(static_cast<rhs_derived_t const &>(rhs));
}
template <typename lhs_derived_t, typename lhs_value_t, typename rhs_derived_t, typename rhs_value_t>
constexpr auto operator|(pipeable_config_element<lhs_derived_t, lhs_value_t> const & lhs,
pipeable_config_element<rhs_derived_t, rhs_value_t> && rhs)
{
return configuration{static_cast<lhs_derived_t const &>(lhs)}.push_back(static_cast<rhs_derived_t &&>(rhs));
}
template <typename lhs_derived_t, typename lhs_value_t, typename rhs_derived_t, typename rhs_value_t>
constexpr auto operator|(pipeable_config_element<lhs_derived_t, lhs_value_t> const & lhs,
pipeable_config_element<rhs_derived_t, rhs_value_t> const & rhs)
{
return configuration{static_cast<lhs_derived_t const &>(lhs)}.push_back(static_cast<rhs_derived_t const &>(rhs));
}
//!\endcond
// ----------------------------------------------------------------------------
// configuration
// ----------------------------------------------------------------------------
/*!\brief Collection of elements to configure an algorithm.
* \ingroup algorithm
*
* \tparam configs_t Template parameter pack containing all configuration elements; Must model
* seqan3::detail::config_element_specialisation
*
* \details
*
* This class provides a unified interface to create and query such
* configurations for a specific algorithm. It extends the standard tuple interface with some useful functions to modify
* and query the user configurations.
*/
template <detail::config_element_specialisation ... configs_t>
class configuration : public std::tuple<configs_t...>
{
//!\brief Friend declaration for other instances of the configuration.
template <detail::config_element_specialisation ... _configs_t>
friend class configuration;
public:
//!\privatesection
//!\brief A type alias for the base class.
using base_type = std::tuple<configs_t...>;
//!\publicsection
/*!\name Constructor, destructor and assignment
* \{
*/
constexpr configuration() = default; //!< Defaulted.
constexpr configuration(configuration const &) = default; //!< Defaulted.
constexpr configuration(configuration &&) = default; //!< Defaulted.
constexpr configuration & operator=(configuration const &) = default; //!< Defaulted.
constexpr configuration & operator=(configuration &&) = default; //!< Defaulted.
~configuration() = default; //!< Defaulted.
/*!\brief Constructs a configuration from a single configuration element.
* \param elem The element to store.
*/
template <typename derived_t, typename value_t>
constexpr configuration(pipeable_config_element<derived_t, value_t> && elem) :
base_type{static_cast<derived_t &&>(std::move(elem))}
{}
/*!\brief Constructs a configuration from a single configuration element.
* \param elem The element to store.
*/
template <typename derived_t, typename value_t>
constexpr configuration(pipeable_config_element<derived_t, value_t> const & elem) :
base_type{static_cast<derived_t const &>(elem)}
{}
//!\}
/*!\name Capacity
* \{
*/
//!\brief Returns the number of contained config elements.
constexpr size_t size() const noexcept
{
return std::tuple_size_v<base_type>;
}
/*!\name Observers
* \{
*/
/*!\brief Returns the stored configuration element if present otherwise the given alternative.
* \tparam alternative_t The type of the configuration element that is queried.
*
* \param[in] alternative The alternative whose type is used to check for an existing configuration element.
*
* \details
*
* Uses the type `alternative_t` of the given alternative to check if such an configuration element was already
* stored inside of the configuration. If no suitable candidate can be found the passed value `alternative` will
* be returned. If `alternative_t` is a class template, then any specialisation of this alternative type will be
* searched and returned if present.
*
* \returns The stored configuration element identified by `alternative_t` or the alternative if not present.
*
* ### Example
*
* \include test/snippet/core/algorithm/configuration_get_or.cpp
*
* ### Exception
*
* no-throw guarantee.
*
* ### Complexity
*
* Constant time.
*/
template <typename alternative_t>
constexpr decltype(auto) get_or(alternative_t && alternative) & noexcept
{
return get_or_impl(*this, alternative, std::forward<alternative_t>(alternative));
}
//!\overload
template <typename alternative_t>
constexpr decltype(auto) get_or(alternative_t && alternative) const & noexcept
{
return get_or_impl(*this, alternative, std::forward<alternative_t>(alternative));
}
//!\overload
template <typename alternative_t>
constexpr decltype(auto) get_or(alternative_t && alternative) && noexcept
{
return get_or_impl(std::move(*this), alternative, std::forward<alternative_t>(alternative));
}
//!\overload
template <typename alternative_t>
constexpr decltype(auto) get_or(alternative_t && alternative) const && noexcept
{
return get_or_impl(std::move(*this), alternative, std::forward<alternative_t>(alternative));
}
//!\brief Checks if the given type exists in the tuple.
template <typename query_t>
static constexpr bool exists() noexcept
{
return pack_traits::contains<query_t, configs_t...>;
}
//!\brief Checks if the given type exists in the tuple.
template <template <typename ...> typename query_t>
static constexpr bool exists() noexcept
{
return (pack_traits::find_if<detail::is_same_configuration_f<query_t>::template invoke, configs_t...> > -1);
}
//!\}
/*!\name Modifiers
* \{
*/
/*!\brief Remove a config element from the configuration.
* \tparam query_t The config element type to remove from the configuration.
* \returns A new configuration object without the config element identified by `query_t`.
*/
template <typename query_t>
[[nodiscard]] constexpr auto remove() const
//!\cond
#if !SEQAN3_WORKAROUND_GCC_95371
requires (exists<query_t>())
#endif // !SEQAN3_WORKAROUND_GCC_95371
//!\endcond
{
constexpr int index = pack_traits::find<query_t, configs_t...>;
return remove_at<index>();
}
//!\overload
template <template <typename ...> typename query_t>
[[nodiscard]] constexpr auto remove() const
//!\cond
#if !SEQAN3_WORKAROUND_GCC_95371
requires (exists<query_t>())
#endif // !SEQAN3_WORKAROUND_GCC_95371
//!\endcond
{
constexpr int index = pack_traits::find_if<detail::is_same_configuration_f<query_t>::template invoke,
configs_t...>;
return remove_at<index>();
}
//!\}
/*!\name Pipe operator
* \{
*/
/*!\brief Combines two seqan3::pipeable_config_element objects to a seqan3::configuration.
* \tparam lhs_derived_t The derived type of the left hand side operand.
* \tparam lhs_value_t The value type of the left hand side operand.
* \tparam rhs_derived_t The derived type of the right hand side operand.
* \tparam rhs_value_t The value type of the right hand side operand.
* \param[in] lhs The left hand operand.
* \param[in] rhs The right hand operand.
* \returns A new seqan3::configuration containing `lhs` and `rhs`.
*/
template <typename lhs_derived_t, typename lhs_value_t, typename rhs_derived_t, typename rhs_value_t>
friend constexpr auto operator|(pipeable_config_element<lhs_derived_t, lhs_value_t> && lhs,
pipeable_config_element<rhs_derived_t, rhs_value_t> && rhs);
//!\overload
template <typename lhs_derived_t, typename lhs_value_t, typename rhs_derived_t, typename rhs_value_t>
friend constexpr auto operator|(pipeable_config_element<lhs_derived_t, lhs_value_t> && lhs,
pipeable_config_element<rhs_derived_t, rhs_value_t> const & rhs);
//!\overload
template <typename lhs_derived_t, typename lhs_value_t, typename rhs_derived_t, typename rhs_value_t>
friend constexpr auto operator|(pipeable_config_element<lhs_derived_t, lhs_value_t> const & lhs,
pipeable_config_element<rhs_derived_t, rhs_value_t> && rhs);
//!\overload
template <typename lhs_derived_t, typename lhs_value_t, typename rhs_derived_t, typename rhs_value_t>
friend constexpr auto operator|(pipeable_config_element<lhs_derived_t, lhs_value_t> const & lhs,
pipeable_config_element<rhs_derived_t, rhs_value_t> const & rhs);
/*!\brief Combines a seqan3::configuration with a seqan3::pipeable_config_element.
* \tparam rhs_derived_t The derived type of the right hand side operand.
* \tparam rhs_value_t The value type of the right hand side operand.
* \param[in] lhs The left hand operand.
* \param[in] rhs The right hand operand.
* \returns A new seqan3::configuration adding `rhs` to the passed `lhs` object.
*/
template <typename rhs_derived_t, typename rhs_value_t>
friend constexpr auto operator|(configuration && lhs,
pipeable_config_element<rhs_derived_t, rhs_value_t> && rhs)
{
return std::move(lhs).push_back(static_cast<rhs_derived_t &&>(rhs));
}
//!\overload
template <typename rhs_derived_t, typename rhs_value_t>
friend constexpr auto operator|(configuration const & lhs,
pipeable_config_element<rhs_derived_t, rhs_value_t> && rhs)
{
return lhs.push_back(static_cast<rhs_derived_t &&>(rhs));
}
//!\overload
template <typename rhs_derived_t, typename rhs_value_t>
friend constexpr auto operator|(configuration && lhs,
pipeable_config_element<rhs_derived_t, rhs_value_t> const & rhs)
{
return std::move(lhs).push_back(static_cast<rhs_derived_t const &>(rhs));
}
//!\overload
template <typename rhs_derived_t, typename rhs_value_t>
friend constexpr auto operator|(configuration const & lhs,
pipeable_config_element<rhs_derived_t, rhs_value_t> const & rhs)
{
return lhs.push_back(static_cast<rhs_derived_t const &>(rhs));
}
/*!\brief Combines two seqan3::configuration objects.
* \tparam rhs_configs_t A template parameter pack for the second seqan3::configuration operand.
* \param[in] lhs The left hand operand.
* \param[in] rhs The right hand operand.
* \returns A new seqan3::configuration as the result of concatenating `lhs` and `rhs`.
*/
template <typename ...rhs_configs_t>
friend constexpr auto operator|(configuration && lhs,
configuration<rhs_configs_t...> && rhs)
{
using lhs_base_t = typename configuration::base_type;
using rhs_base_t = typename configuration<rhs_configs_t...>::base_type;
return make_configuration(std::tuple_cat(static_cast<lhs_base_t>(std::move(lhs)),
static_cast<rhs_base_t>(std::move(rhs))));
}
//!\overload
template <typename ...rhs_configs_t>
friend constexpr auto operator|(configuration const & lhs,
configuration<rhs_configs_t...> && rhs)
{
using lhs_base_t = typename configuration::base_type;
using rhs_base_t = typename configuration<rhs_configs_t...>::base_type;
return make_configuration(std::tuple_cat(static_cast<lhs_base_t>(lhs),
static_cast<rhs_base_t>(std::move(rhs))));
}
//!\overload
template <typename ...rhs_configs_t>
friend constexpr auto operator|(configuration && lhs,
configuration<rhs_configs_t...> const & rhs)
{
using lhs_base_t = typename configuration::base_type;
using rhs_base_t = typename configuration<rhs_configs_t...>::base_type;
return make_configuration(std::tuple_cat(static_cast<lhs_base_t>(std::move(lhs)),
static_cast<rhs_base_t>(rhs)));
}
//!\overload
template <typename ...rhs_configs_t>
friend constexpr auto operator|(configuration const & lhs,
configuration<rhs_configs_t...> const & rhs)
{
using lhs_base_t = typename configuration::base_type;
using rhs_base_t = typename configuration<rhs_configs_t...>::base_type;
return make_configuration(std::tuple_cat(static_cast<lhs_base_t>(lhs),
static_cast<rhs_base_t>(rhs)));
}
//!\}
private:
/*!\name Internal constructor
* \{
*/
//!\brief Constructs from std::tuple.
template <typename ..._configs_t>
explicit constexpr configuration(std::tuple<_configs_t...> const & cfg) : base_type{cfg}
{}
//!\brief Constructs from std::tuple.
template <typename ..._configs_t>
explicit constexpr configuration(std::tuple<_configs_t...> && cfg) : base_type{std::move(cfg)}
{}
//!\}
/*!\brief Creates a new configuration object by recursively adding the configs from the tuple.
* \tparam tuple_t The tuple from which to create a new configuration object; must model seqan3::tuple_like.
* \param[in] tpl The tuple to create the configuration from.
* \returns A new configuration object.
*/
template <tuple_like tuple_t>
static constexpr auto make_configuration(tuple_t && tpl)
{
if constexpr (std::tuple_size_v<remove_cvref_t<tuple_t>> == 0)
{
return configuration<>{};
}
else
{
auto impl = [](auto & impl_ref, auto && config, auto && head, auto && tail)
{
using cfg_t = decltype(config);
if constexpr (std::tuple_size_v<remove_cvref_t<decltype(tail)>> == 0)
{
return std::forward<cfg_t>(config).push_back(std::get<0>(std::forward<decltype(head)>(head)));
}
else
{
auto [_head, _tail] = tuple_split<1>(std::forward<decltype(tail)>(tail));
auto tmp = std::forward<cfg_t>(config).push_back(std::get<0>(std::forward<decltype(head)>(head)));
return impl_ref(impl_ref, std::move(tmp), std::move(_head), std::move(_tail));
}
};
auto [head, tail] = tuple_split<1>(std::forward<decltype(tpl)>(tpl));
return impl(impl, configuration<>{}, std::move(head), std::move(tail));
}
}
/*!\name Modifiers
* \brief Note that modifications return new configurations and do not modify `this`.
* \{
*/
/*!\brief Adds a new config element to the end of the configuration.
*
* \param[in] elem The configuration element to add.
*
* \returns A new seqan3::detail::configuration containing the added element.
*
* \details
*
* Creates a new seqan3::detail::configuration from `this` and appends the passed config element.
* Note, that `this` is not modified by this operation.
* Further the configuration checks for an invalid configuration using an algorithm specific lookup table
* for the configuration elements and tests whether configuration elements are from the same algorithm.
*
* ### Complexity
*
* Linear in the number of elements.
*
* ### Exception
*
* Strong exception guarantee.
*/
template <detail::config_element_specialisation config_element_t>
constexpr auto push_back(config_element_t elem) const &
{
static_assert(detail::is_configuration_valid_v<remove_cvref_t<config_element_t>,
configs_t...>,
"Configuration error: The passed element cannot be combined with one or more elements in the "
"current configuration.");
return configuration<configs_t..., std::remove_reference_t<config_element_t>>{
std::tuple_cat(static_cast<base_type>(*this),
std::tuple{std::move(elem)})};
}
//!\copydoc push_back
template <detail::config_element_specialisation config_element_t>
constexpr auto push_back(config_element_t elem) &&
{
static_assert(detail::is_configuration_valid_v<remove_cvref_t<config_element_t>,
configs_t...>,
"Configuration error: The passed element cannot be combined with one or more elements in the "
"current configuration.");
return configuration<configs_t..., std::remove_reference_t<config_element_t>>{
std::tuple_cat(std::move(static_cast<base_type>(*this)),
std::tuple{std::move(elem)})};
}
/*!\brief Remove a config element from the configuration.
* \tparam index The config element at `index` is removed from the config.
* \returns A new configuration object without the config element at `index`.
*/
template <int index>
[[nodiscard]] constexpr auto remove_at() const
{
static_assert((index >= 0) && (index < sizeof...(configs_t)), "Index to remove from config is out of bounds.");
auto [head, middle] = tuple_split<index>(static_cast<base_type>(*this));
auto tail = tuple_pop_front(middle);
return make_configuration(std::tuple_cat(head, tail));
}
//!\}
/*!\brief Internal implementation of the get_or interace.
*
* \tparam this_t The type of this.
* \tparam query_t The type of the configuration element to query.
* \tparam alternative_t The type of the alternative.
*
* \param[in] me The perfectly forwarded instance of `*this`.
* \param[in] query The queried configuration element [only the type is needed].
* \param[in] alternative The alternative configuration element to return if the query_t is not present.
*
* \details
*
* Use the type `query_t` to check if such a configuration element is stored in `me`. If this is `true` then
* the stored configuration element is returned using perfect forwarding. If this evaluates to `false` the
* given alternative is returned. If `query_t` is a class template then it is checked if any
* specialisation of this class template is stored.
*/
template <typename this_t, typename query_t, typename alternative_t>
static constexpr decltype(auto) get_or_impl(this_t && me,
query_t const & SEQAN3_DOXYGEN_ONLY(query),
alternative_t && alternative) noexcept
{
if constexpr (exists<query_t>())
{
return get<query_t>(std::forward<this_t>(me));
}
else
{
using ret_type = remove_rvalue_reference_t<decltype(alternative)>;
return static_cast<ret_type>(alternative);
}
}
//!\overload
template <typename this_t,
template <typename ...> typename query_template_t, typename ...parameters_t,
typename alternative_t>
static constexpr decltype(auto) get_or_impl(this_t && me,
query_template_t<parameters_t...> const &,
alternative_t && alternative) noexcept
{
if constexpr (exists<query_template_t>())
{
return get<query_template_t>(std::forward<this_t>(me));
}
else
{
using ret_type = remove_rvalue_reference_t<decltype(alternative)>;
return static_cast<ret_type>(alternative);
}
}
};
/*!\name Type deduction guides
* \{
*/
/*!\brief Deduces the correct configuration element type from the passed seqan3::pipeable_config_element.
* \relates seqan3::configuration
*/
template <typename derived_t, typename value_t>
configuration(pipeable_config_element<derived_t, value_t> &&) -> configuration<remove_cvref_t<derived_t>>;
/*!\brief Deduces the correct configuration element type from the passed seqan3::pipeable_config_element.
* \relates seqan3::configuration
*/
template <typename derived_t, typename value_t>
configuration(pipeable_config_element<derived_t, value_t> const &) -> configuration<remove_cvref_t<derived_t>>;
//!\}
/*!\name Tuple interface
* \{
*/
/*!\brief Returns the stored element.
* \ingroup algorithm
* \relates seqan3::configuration
*
* \tparam query_t A template template.
* \param[in] config The configuration to get the element for.
*
* \details
*
* Extends the position-based and type based `get` interface for the configuration type, with a version
* that also accepts template-template types (types that are itself templates), such that the exact template definition
* must not be known.
*
* ### Example
*
* The following snippet demonstrates the various versions of get that can be used.
*
* \include test/snippet/core/algorithm/configuration_get.cpp
*
* ### Exception
*
* no-throw guarantee.
*
* ### Complexity
*
* Constant time.
*/
template <template <typename ...> class query_t, typename ...configs_t>
constexpr auto & get(configuration<configs_t...> & config) noexcept
{
constexpr auto pos = pack_traits::find_if<detail::is_same_configuration_f<query_t>::template invoke, configs_t...>;
static_assert(pos > -1, "Access error: The requested type is not contained.");
return get<pos>(config);
}
//!\overload
template <template <typename ...> class query_t, typename ...configs_t>
constexpr auto const & get(configuration<configs_t...> const & config) noexcept
{
constexpr auto pos = pack_traits::find_if<detail::is_same_configuration_f<query_t>::template invoke, configs_t...>;
static_assert(pos > -1, "Access error: The requested type is not contained.");
return get<pos>(config);
}
//!\overload
template <template <typename ...> class query_t, typename ...configs_t>
constexpr auto && get(configuration<configs_t...> && config) noexcept
{
constexpr auto pos = pack_traits::find_if<detail::is_same_configuration_f<query_t>::template invoke, configs_t...>;
static_assert(pos > -1, "Access error: The requested type is not contained.");
return get<pos>(std::move(config));
}
//!\overload
template <template <typename ...> class query_t, typename ...configs_t>
constexpr auto const && get(configuration<configs_t...> const && config) noexcept
{
constexpr auto pos = pack_traits::find_if<detail::is_same_configuration_f<query_t>::template invoke, configs_t...>;
static_assert(pos > -1, "Access error: The requested type is not contained.");
// TODO: change after GCC-7 bug with const && version of get in std::tuple is fixed.
// return get<pos>(std::move(config));
return std::move(get<pos>(config));
}
//!\}
} // namespace seqan3::detail
namespace std
{
//!\cond DEV
/*!\brief Returns the number of elements stored in seqan3::detail::configuration.
* \implements seqan3::unary_type_trait
* \see std::tuple_size_v
* \ingroup algorithm
*/
template <seqan3::detail::config_element_specialisation ... configs_t>
struct tuple_size<seqan3::configuration<configs_t...>>
{
//!\brief The number of elements.
static constexpr size_t value = std::tuple_size_v<typename seqan3::configuration<configs_t...>::base_type>;
};
/*!\brief Returns the type of the element at the specified position within seqan3::configuration.
* \implements seqan3::transformation_trait
* \see [std::tuple_element](https://en.cppreference.com/w/cpp/utility/tuple/tuple_element)
* \ingroup algorithm
*/
template <size_t pos, seqan3::detail::config_element_specialisation ... configs_t>
struct tuple_element<pos, seqan3::configuration<configs_t...>>
{
//!\brief The type of the config at position `pos`
using type = std::tuple_element_t<pos, typename seqan3::configuration<configs_t...>::base_type>;
};
//!\endcond
} //namespace std
| 40.960061 | 120 | 0.653403 | [
"object",
"model"
] |
813e401d06045602d59e6d024941fbbc7b6b888d | 21,125 | cpp | C++ | sourceCode/gui/dialogs/qdlgjointdyn.cpp | mdecourse/CoppeliaSimLib | 934e65b4b6ea5a07d08919ae35c50fd3ae960ef2 | [
"RSA-MD"
] | null | null | null | sourceCode/gui/dialogs/qdlgjointdyn.cpp | mdecourse/CoppeliaSimLib | 934e65b4b6ea5a07d08919ae35c50fd3ae960ef2 | [
"RSA-MD"
] | null | null | null | sourceCode/gui/dialogs/qdlgjointdyn.cpp | mdecourse/CoppeliaSimLib | 934e65b4b6ea5a07d08919ae35c50fd3ae960ef2 | [
"RSA-MD"
] | null | null | null | #include "qdlgjointdyn.h"
#include "ui_qdlgjointdyn.h"
#include "tt.h"
#include "gV.h"
#include "propBrowser_engineProp_joint.h"
#include "qdlgjoints.h"
#include "app.h"
#include "simStringTable.h"
#include "vMessageBox.h"
CQDlgJointDyn::CQDlgJointDyn(QWidget *parent) :
CDlgEx(parent),
ui(new Ui::CQDlgJointDyn)
{
_dlgType=JOINT_DYN_DLG;
ui->setupUi(this);
}
CQDlgJointDyn::~CQDlgJointDyn()
{
delete ui;
}
void CQDlgJointDyn::cancelEvent()
{ // no cancel event allowed
CQDlgJoints::showDynamicWindow=false;
CDlgEx::cancelEvent();
App::setFullDialogRefreshFlag();
}
void CQDlgJointDyn::refresh()
{
QLineEdit* lineEditToSelect=getSelectedLineEdit();
bool noEditModeNoSim=(App::getEditModeType()==NO_EDIT_MODE)&&App::currentWorld->simulation->isSimulationStopped();
bool sel=App::currentWorld->sceneObjects->isLastSelectionAJoint();
bool bigSel=(App::currentWorld->sceneObjects->isLastSelectionAJoint()&&(App::currentWorld->sceneObjects->getJointCountInSelection()>1));
bool revolute=false;
bool prismatic=false;
bool spherical=false;
bool dynamic=false;
bool dynamicMotControlAllowed=false;
bool motorEnabled=false;
bool ctrlEnabled=false;
bool pidCtrlEnabled=true;
bool springCtrlEnabled=false;
CJoint* it=nullptr;
if (sel)
{
it=App::currentWorld->sceneObjects->getLastSelectionJoint();
revolute=(it->getJointType()==sim_joint_revolute_subtype);
prismatic=(it->getJointType()==sim_joint_prismatic_subtype);
spherical=(it->getJointType()==sim_joint_spherical_subtype);
dynamic=((it->getJointMode()==sim_jointmode_force)||it->getHybridFunctionality() );
dynamicMotControlAllowed=(dynamic&&(!spherical));
motorEnabled=dynamic&&it->getEnableDynamicMotor();
ctrlEnabled=motorEnabled&&it->getEnableDynamicMotorControlLoop();
pidCtrlEnabled=ctrlEnabled&&(!it->getEnableTorqueModulation());
springCtrlEnabled=ctrlEnabled&&it->getEnableTorqueModulation();
}
if (sel&&prismatic)
{
ui->qqTargetVelocityLabel->setText("Target velocity [m/s]");
ui->qqMaxForceLabel->setText("Maximum force [N]");
ui->qqTargetPositionLabel->setText("Target position [m]");
ui->qqUpperVelocityLabel->setText("Upper velocity limit [m/s]");
ui->qqKLabel->setText("Spring constant K [N/m]");
ui->qqCLabel->setText("Damping coefficient C [N*s/m]");
}
else
{
ui->qqTargetVelocityLabel->setText("Target velocity [deg/s]");
ui->qqMaxForceLabel->setText("Maximum torque [N*m]");
ui->qqTargetPositionLabel->setText("Target position [deg]");
ui->qqUpperVelocityLabel->setText("Upper velocity limit [deg/s]");
ui->qqKLabel->setText("Spring constant K [N*m/deg]");
ui->qqCLabel->setText("Damping coefficient C [N*s*m/deg]");
}
ui->qqMotorEnabled->setEnabled(dynamicMotControlAllowed&&(!it->getHybridFunctionality()));
ui->qqTargetVelocity->setEnabled(dynamicMotControlAllowed&&motorEnabled&&((!ctrlEnabled)||(!pidCtrlEnabled)));
ui->qqMotorLockEnabled->setEnabled(dynamicMotControlAllowed&&motorEnabled&&(!ctrlEnabled));
ui->qqMaxForce->setEnabled(dynamicMotControlAllowed&&motorEnabled);
ui->qqAdjustEngineProperties->setEnabled(dynamic&&noEditModeNoSim);
ui->qqApplyDynamicProperties->setEnabled(dynamic&&bigSel&&noEditModeNoSim);
ui->qqControlEnabled->setEnabled(dynamicMotControlAllowed&&motorEnabled&&(!it->getHybridFunctionality()));
ui->qqPositionControl->setEnabled(dynamicMotControlAllowed&&ctrlEnabled&&noEditModeNoSim);
ui->qqSpringControl->setEnabled(dynamicMotControlAllowed&&ctrlEnabled&&noEditModeNoSim);
ui->qqVelocityUpperLimit->setEnabled(dynamicMotControlAllowed&&ctrlEnabled&&noEditModeNoSim&&(!springCtrlEnabled));
ui->qqTargetPosition->setEnabled(dynamicMotControlAllowed&&ctrlEnabled&&(!it->getHybridFunctionality()));
ui->qqP->setEnabled(dynamicMotControlAllowed&&ctrlEnabled&&pidCtrlEnabled);
ui->qqI->setEnabled(dynamicMotControlAllowed&&ctrlEnabled&&pidCtrlEnabled);
ui->qqD->setEnabled(dynamicMotControlAllowed&&ctrlEnabled&&pidCtrlEnabled);
ui->qqK->setEnabled(dynamicMotControlAllowed&&ctrlEnabled&&springCtrlEnabled);
ui->qqC->setEnabled(dynamicMotControlAllowed&&ctrlEnabled&&springCtrlEnabled);
ui->qqApplyControlParameters->setEnabled(dynamicMotControlAllowed&&bigSel&&noEditModeNoSim);
ui->qqMotorEnabled->setChecked(dynamic&&it->getEnableDynamicMotor());
ui->qqControlEnabled->setChecked(dynamic&&it->getEnableDynamicMotorControlLoop());
if (dynamicMotControlAllowed)
{
if (ctrlEnabled)
{
if (!pidCtrlEnabled)
{
if (it->getJointType()==sim_joint_revolute_subtype)
ui->qqTargetVelocity->setText(tt::getAngleEString(true,it->getDynamicMotorTargetVelocity(),4).c_str());
else
ui->qqTargetVelocity->setText(tt::getEString(true,it->getDynamicMotorTargetVelocity(),4).c_str());
}
else
ui->qqTargetVelocity->setText("");
ui->qqMotorLockEnabled->setChecked(false);
}
else
{
if (it->getJointType()==sim_joint_revolute_subtype)
ui->qqTargetVelocity->setText(tt::getAngleEString(true,it->getDynamicMotorTargetVelocity(),4).c_str());
else
ui->qqTargetVelocity->setText(tt::getEString(true,it->getDynamicMotorTargetVelocity(),4).c_str());
ui->qqMotorLockEnabled->setChecked(it->getDynamicMotorLockModeWhenInVelocityControl());
}
if (it->getJointType()==sim_joint_revolute_subtype)
{
ui->qqMaxForce->setText(tt::getEString(false,it->getDynamicMotorMaximumForce(),4).c_str());
if (ctrlEnabled&&(!springCtrlEnabled))
ui->qqVelocityUpperLimit->setText(tt::getAngleEString(false,it->getDynamicMotorUpperLimitVelocity(),4).c_str());
else
ui->qqVelocityUpperLimit->setText("");
if (it->getHybridFunctionality())
ui->qqTargetPosition->setText("");
else
ui->qqTargetPosition->setText(tt::getAngleEString(true,it->getDynamicMotorPositionControlTargetPosition(),4).c_str());
}
else
{
ui->qqMaxForce->setText(tt::getEString(false,it->getDynamicMotorMaximumForce(),4).c_str());
if (ctrlEnabled&&(!springCtrlEnabled))
ui->qqVelocityUpperLimit->setText(tt::getEString(false,it->getDynamicMotorUpperLimitVelocity(),4).c_str());
else
ui->qqVelocityUpperLimit->setText("");
if (it->getHybridFunctionality())
ui->qqTargetPosition->setText("");
else
ui->qqTargetPosition->setText(tt::getEString(true,it->getDynamicMotorPositionControlTargetPosition(),4).c_str());
}
float pp,ip,dp;
it->getDynamicMotorPositionControlParameters(pp,ip,dp);
ui->qqP->setText(tt::getFString(false,pp,3).c_str());
ui->qqI->setText(tt::getFString(false,ip,3).c_str());
ui->qqD->setText(tt::getFString(false,dp,3).c_str());
float kp,cp;
it->getDynamicMotorSpringControlParameters(kp,cp);
ui->qqK->setText(tt::getEString(false,kp,3).c_str());
ui->qqC->setText(tt::getEString(false,cp,3).c_str());
ui->qqPositionControl->setChecked(pidCtrlEnabled);
ui->qqSpringControl->setChecked(springCtrlEnabled);
}
else
{
ui->qqTargetVelocity->setText("");
ui->qqMotorLockEnabled->setChecked(false);
ui->qqMaxForce->setText("");
ui->qqVelocityUpperLimit->setText("");
ui->qqTargetPosition->setText("");
ui->qqP->setText("");
ui->qqI->setText("");
ui->qqD->setText("");
ui->qqK->setText("");
ui->qqC->setText("");
}
selectLineEdit(lineEditToSelect);
}
void CQDlgJointDyn::on_qqMotorEnabled_clicked()
{
IF_UI_EVENT_CAN_READ_DATA
{
App::appendSimulationThreadCommand(TOGGLE_MOTORENABLED_JOINTDYNGUITRIGGEREDCMD,App::currentWorld->sceneObjects->getLastSelectionHandle());
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
void CQDlgJointDyn::on_qqTargetVelocity_editingFinished()
{
if (!ui->qqTargetVelocity->isModified())
return;
IF_UI_EVENT_CAN_READ_DATA
{
CJoint* it=App::currentWorld->sceneObjects->getLastSelectionJoint();
bool ok;
float newVal=ui->qqTargetVelocity->text().toFloat(&ok);
if (ok&&(it!=nullptr))
{
if (it->getJointType()!=sim_joint_prismatic_subtype)
newVal*=gv::userToAngularVel;
App::appendSimulationThreadCommand(SET_TARGETVELOCITY_JOINTDYNGUITRIGGEREDCMD,App::currentWorld->sceneObjects->getLastSelectionHandle(),-1,newVal);
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
}
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
void CQDlgJointDyn::on_qqAdjustEngineProperties_clicked()
{
IF_UI_EVENT_CAN_WRITE_DATA
{
CJoint* it=App::currentWorld->sceneObjects->getLastSelectionJoint();
if (it!=nullptr)
{
CPropBrowserEngineJoint dlg(this);// App::mainWindow);
dlg.setModal(true);
dlg.exec(); // items are set in here
// We however still need to modify the sim thread resources:
SSimulationThreadCommand cmd;
cmd.cmdId=SET_ALLENGINEPARAMS_JOINTDYNGUITRIGGEREDCMD;
cmd.intParams.push_back(it->getObjectHandle());
std::vector<int> iParams;
std::vector<float> fParams;
it->getBulletIntParams(iParams);
it->getBulletFloatParams(fParams);
cmd.intVectorParams.push_back(iParams);
cmd.floatVectorParams.push_back(fParams);
iParams.clear();
fParams.clear();
it->getOdeIntParams(iParams);
it->getOdeFloatParams(fParams);
cmd.intVectorParams.push_back(iParams);
cmd.floatVectorParams.push_back(fParams);
iParams.clear();
fParams.clear();
it->getVortexIntParams(iParams);
it->getVortexFloatParams(fParams);
cmd.intVectorParams.push_back(iParams);
cmd.floatVectorParams.push_back(fParams);
iParams.clear();
fParams.clear();
it->getNewtonIntParams(iParams);
it->getNewtonFloatParams(fParams);
cmd.intVectorParams.push_back(iParams);
cmd.floatVectorParams.push_back(fParams);
iParams.clear();
fParams.clear();
App::appendSimulationThreadCommand(cmd);
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
}
void CQDlgJointDyn::on_qqMaxForce_editingFinished()
{
if (!ui->qqMaxForce->isModified())
return;
IF_UI_EVENT_CAN_READ_DATA
{
bool ok;
float newVal=ui->qqMaxForce->text().toFloat(&ok);
if (ok)
{
App::appendSimulationThreadCommand(SET_MAXFORCE_JOINTDYNGUITRIGGEREDCMD,App::currentWorld->sceneObjects->getLastSelectionHandle(),-1,newVal);
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
}
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
void CQDlgJointDyn::on_qqApplyDynamicProperties_clicked()
{
IF_UI_EVENT_CAN_READ_DATA
{
SSimulationThreadCommand cmd;
cmd.cmdId=APPLY_MOTORPARAMS_JOINTDYNGUITRIGGEREDCMD;
cmd.intParams.push_back(App::currentWorld->sceneObjects->getLastSelectionHandle());
for (size_t i=0;i<App::currentWorld->sceneObjects->getSelectionCount()-1;i++)
cmd.intParams.push_back(App::currentWorld->sceneObjects->getObjectHandleFromSelectionIndex(i));
App::appendSimulationThreadCommand(cmd);
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
void CQDlgJointDyn::on_qqControlEnabled_clicked()
{
IF_UI_EVENT_CAN_READ_DATA
{
App::appendSimulationThreadCommand(TOGGLE_CTRLLOOP_JOINTDYNGUITRIGGEREDCMD,App::currentWorld->sceneObjects->getLastSelectionHandle());
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
void CQDlgJointDyn::on_qqVelocityUpperLimit_editingFinished()
{
if (!ui->qqVelocityUpperLimit->isModified())
return;
IF_UI_EVENT_CAN_READ_DATA
{
CJoint* it=App::currentWorld->sceneObjects->getLastSelectionJoint();
bool ok;
float newVal=ui->qqVelocityUpperLimit->text().toFloat(&ok);
if (ok&&(it!=nullptr))
{
if (it->getJointType()!=sim_joint_prismatic_subtype)
newVal*=gv::userToRad;
App::appendSimulationThreadCommand(SET_UPPERVELLIMIT_JOINTDYNGUITRIGGEREDCMD,App::currentWorld->sceneObjects->getLastSelectionHandle(),-1,newVal);
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
}
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
void CQDlgJointDyn::on_qqTargetPosition_editingFinished()
{
if (!ui->qqTargetPosition->isModified())
return;
IF_UI_EVENT_CAN_READ_DATA
{
CJoint* it=App::currentWorld->sceneObjects->getLastSelectionJoint();
bool ok;
float newVal=ui->qqTargetPosition->text().toFloat(&ok);
if (ok&&(it!=nullptr))
{
if (it->getJointType()!=sim_joint_prismatic_subtype)
newVal*=gv::userToRad;
App::appendSimulationThreadCommand(SET_TARGETPOSITION_JOINTDYNGUITRIGGEREDCMD,App::currentWorld->sceneObjects->getLastSelectionHandle(),-1,newVal);
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
}
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
void CQDlgJointDyn::on_qqP_editingFinished()
{
if (!ui->qqP->isModified())
return;
IF_UI_EVENT_CAN_READ_DATA
{
bool ok;
float newVal=ui->qqP->text().toFloat(&ok);
CJoint* it=App::currentWorld->sceneObjects->getLastSelectionJoint();
if (ok&&(it!=nullptr))
{
float pp,ip,dp;
it->getDynamicMotorPositionControlParameters(pp,ip,dp);
SSimulationThreadCommand cmd;
cmd.cmdId=SET_PIDVALUES_JOINTDYNGUITRIGGEREDCMD;
cmd.intParams.push_back(it->getObjectHandle());
cmd.floatParams.push_back(newVal);
cmd.floatParams.push_back(ip);
cmd.floatParams.push_back(dp);
App::appendSimulationThreadCommand(cmd);
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
}
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
void CQDlgJointDyn::on_qqI_editingFinished()
{
if (!ui->qqI->isModified())
return;
IF_UI_EVENT_CAN_READ_DATA
{
bool ok;
float newVal=ui->qqI->text().toFloat(&ok);
CJoint* it=App::currentWorld->sceneObjects->getLastSelectionJoint();
if (ok&&(it!=nullptr))
{
float pp,ip,dp;
it->getDynamicMotorPositionControlParameters(pp,ip,dp);
SSimulationThreadCommand cmd;
cmd.cmdId=SET_PIDVALUES_JOINTDYNGUITRIGGEREDCMD;
cmd.intParams.push_back(it->getObjectHandle());
cmd.floatParams.push_back(pp);
cmd.floatParams.push_back(newVal);
cmd.floatParams.push_back(dp);
App::appendSimulationThreadCommand(cmd);
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
}
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
void CQDlgJointDyn::on_qqD_editingFinished()
{
if (!ui->qqD->isModified())
return;
IF_UI_EVENT_CAN_READ_DATA
{
bool ok;
float newVal=ui->qqD->text().toFloat(&ok);
CJoint* it=App::currentWorld->sceneObjects->getLastSelectionJoint();
if (ok&&(it!=nullptr))
{
float pp,ip,dp;
it->getDynamicMotorPositionControlParameters(pp,ip,dp);
SSimulationThreadCommand cmd;
cmd.cmdId=SET_PIDVALUES_JOINTDYNGUITRIGGEREDCMD;
cmd.intParams.push_back(it->getObjectHandle());
cmd.floatParams.push_back(pp);
cmd.floatParams.push_back(ip);
cmd.floatParams.push_back(newVal);
App::appendSimulationThreadCommand(cmd);
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
}
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
void CQDlgJointDyn::on_qqApplyControlParameters_clicked()
{
IF_UI_EVENT_CAN_READ_DATA
{
SSimulationThreadCommand cmd;
cmd.cmdId=APPLY_CTRLPARAMS_JOINTDYNGUITRIGGEREDCMD;
cmd.intParams.push_back(App::currentWorld->sceneObjects->getLastSelectionHandle());
for (size_t i=0;i<App::currentWorld->sceneObjects->getSelectionCount()-1;i++)
cmd.intParams.push_back(App::currentWorld->sceneObjects->getObjectHandleFromSelectionIndex(i));
App::appendSimulationThreadCommand(cmd);
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
void CQDlgJointDyn::on_qqPositionControl_clicked()
{
IF_UI_EVENT_CAN_READ_DATA
{
CJoint* it=App::currentWorld->sceneObjects->getLastSelectionJoint();
if (it!=nullptr)
{
App::appendSimulationThreadCommand(SELECT_PIDCTRL_JOINTDYNGUITRIGGEREDCMD,it->getObjectHandle());
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
}
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
void CQDlgJointDyn::on_qqSpringControl_clicked()
{
IF_UI_EVENT_CAN_READ_DATA
{
CJoint* it=App::currentWorld->sceneObjects->getLastSelectionJoint();
if (it!=nullptr)
{
App::appendSimulationThreadCommand(SELECT_SPRINGDAMPERCTRL_JOINTDYNGUITRIGGEREDCMD,it->getObjectHandle());
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
}
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
void CQDlgJointDyn::on_qqK_editingFinished()
{
if (!ui->qqK->isModified())
return;
IF_UI_EVENT_CAN_READ_DATA
{
CJoint* it=App::currentWorld->sceneObjects->getLastSelectionJoint();
bool ok;
float newVal=ui->qqK->text().toFloat(&ok);
if (ok&&(it!=nullptr))
{
float kp,cp;
it->getDynamicMotorSpringControlParameters(kp,cp);
App::appendSimulationThreadCommand(SET_KCVALUES_JOINTDYNGUITRIGGEREDCMD,it->getObjectHandle(),-1,newVal,cp);
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
}
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
void CQDlgJointDyn::on_qqC_editingFinished()
{
if (!ui->qqC->isModified())
return;
IF_UI_EVENT_CAN_READ_DATA
{
CJoint* it=App::currentWorld->sceneObjects->getLastSelectionJoint();
bool ok;
float newVal=ui->qqC->text().toFloat(&ok);
if (ok&&(it!=nullptr))
{
float kp,cp;
it->getDynamicMotorSpringControlParameters(kp,cp);
App::appendSimulationThreadCommand(SET_KCVALUES_JOINTDYNGUITRIGGEREDCMD,it->getObjectHandle(),-1,kp,newVal);
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
}
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
void CQDlgJointDyn::on_qqMotorLockEnabled_clicked()
{
IF_UI_EVENT_CAN_READ_DATA
{
App::appendSimulationThreadCommand(TOGGLE_LOCKMOTOR_JOINTDYNGUITRIGGEREDCMD,App::currentWorld->sceneObjects->getLastSelectionHandle());
App::appendSimulationThreadCommand(POST_SCENE_CHANGED_ANNOUNCEMENT_GUITRIGGEREDCMD);
App::appendSimulationThreadCommand(FULLREFRESH_ALL_DIALOGS_GUITRIGGEREDCMD);
}
}
| 40.860735 | 159 | 0.685822 | [
"vector"
] |
81416296a9bf8cdc7bbd0f3431fe5de0e91198cd | 3,085 | cpp | C++ | iRODS/server/api/src/rsAuthPluginRequest.cpp | iychoi/cyverse-irods | 0070b8677a82e763f1d940ae6537b1c8839a628a | [
"BSD-3-Clause"
] | null | null | null | iRODS/server/api/src/rsAuthPluginRequest.cpp | iychoi/cyverse-irods | 0070b8677a82e763f1d940ae6537b1c8839a628a | [
"BSD-3-Clause"
] | 7 | 2019-12-02T17:55:49.000Z | 2019-12-02T17:55:59.000Z | iRODS/server/api/src/rsAuthPluginRequest.cpp | benlazarine/cyverse-irods | 2bf9cfae4c3a1062ffe2af92b1f086ddc5fce025 | [
"BSD-3-Clause"
] | 1 | 2015-02-19T18:30:33.000Z | 2015-02-19T18:30:33.000Z | // =-=-=-=-=-=-=-
#include "authPluginRequest.h"
#include "irods_native_auth_object.hpp"
#include "irods_auth_object.hpp"
#include "irods_auth_factory.hpp"
#include "irods_auth_plugin.hpp"
#include "irods_auth_manager.hpp"
#include "irods_auth_constants.hpp"
#include "irods_pluggable_auth_scheme.hpp"
void _rsSetAuthRequestGetChallenge( const char* );
/// =-=-=-=-=-=-=-
/// @brief auth request api call which will delegate the
/// request to the correct plugin given the requested
/// auth scheme in the input struct
int rsAuthPluginRequest(
rsComm_t* _comm,
authPluginReqInp_t* _req_inp,
authPluginReqOut_t** _req_out ) {
// =-=-=-=-=-=-=-
// check our incoming params
if ( !_comm ) {
rodsLog( LOG_ERROR, "rsAuthPluginRequest - null comm pointer" );
return SYS_INVALID_INPUT_PARAM;
}
else if ( !_req_inp ) {
rodsLog( LOG_ERROR, "rsAuthPluginRequest - null input pointer" );
return SYS_INVALID_INPUT_PARAM;
}
// =-=-=-=-=-=-=-
// check the auth scheme
std::string auth_scheme = irods::AUTH_NATIVE_SCHEME;
if ( strlen( _req_inp->auth_scheme_ ) > 0 ) {
auth_scheme = _req_inp->auth_scheme_;
}
// set the auth_scheme in the comm
if ( _comm->auth_scheme != NULL ) {
free( _comm->auth_scheme );
}
_comm->auth_scheme = strdup( auth_scheme.c_str() );
// =-=-=-=-=-=-=-
// store the scheme in a singleton for use in the following rsAuthResponse call
irods::pluggable_auth_scheme& plug_a = irods::pluggable_auth_scheme::get_instance();
plug_a.set( auth_scheme );
// =-=-=-=-=-=-=-
// handle old school memory allocation
( *_req_out ) = ( authPluginReqOut_t* )malloc( sizeof( authPluginReqOut_t ) );
// =-=-=-=-=-=-=-
// construct an auth object given the native scheme
irods::auth_object_ptr auth_obj;
irods::error ret = irods::auth_factory( auth_scheme, &_comm->rError, auth_obj );
if ( !ret.ok() ) {
irods::log( PASS( ret ) );
return ret.code();
}
// =-=-=-=-=-=-=-
// set the context of the auth object for communication
// to the plugin itself
auth_obj->context( _req_inp->context_ );
// =-=-=-=-=-=-=-
// resolve an auth plugin given the auth object
irods::plugin_ptr ptr;
ret = auth_obj->resolve( irods::AUTH_INTERFACE, ptr );
if ( !ret.ok() ) {
irods::log( PASS( ret ) );
return ret.code();
}
irods::auth_ptr auth_plugin = boost::dynamic_pointer_cast <
irods::auth > ( ptr );
// =-=-=-=-=-=-=-
// call client side init - 'establish creds'
ret = auth_plugin->call( _comm, irods::AUTH_AGENT_AUTH_REQUEST, auth_obj );
if ( !ret.ok() ) {
irods::log( PASS( ret ) );
return ret.code();
}
// =-=-=-=-=-=-=-
// send back the results
strncpy( ( *_req_out )->result_, auth_obj->request_result().c_str(), auth_obj->request_result().size() + 1 );
// =-=-=-=-=-=-=-
// win!
return 0;
} // rsAuthPluginRequest
| 30.544554 | 113 | 0.597083 | [
"object"
] |
81429baf3dd2d65e17c79b29be17fd49a7fc5b26 | 1,687 | cpp | C++ | REDSI_1160929_1161573/boost_1_67_0/libs/hof/test/static_def/static_def2.cpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | 32 | 2019-02-27T06:57:07.000Z | 2021-08-29T10:56:19.000Z | REDSI_1160929_1161573/boost_1_67_0/libs/hof/test/static_def/static_def2.cpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | 1 | 2019-04-04T18:00:00.000Z | 2019-04-04T18:00:00.000Z | REDSI_1160929_1161573/boost_1_67_0/libs/hof/test/static_def/static_def2.cpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | 5 | 2019-08-20T13:45:04.000Z | 2022-03-01T18:23:49.000Z | /*=============================================================================
Copyright (c) 2017 Paul Fultz II
static_def2.cpp
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#include <cstdio>
#include "static_def.hpp"
extern void* f_sum_lambda_addr();
extern void* f_sum_fo_addr();
extern void* sum_lambda_addr();
extern void* sum_fo_addr();
extern void* f_sum_var_addr();
extern void* f_sum_constexpr_fo_addr();
extern void* sum_var_addr();
extern void* sum_constexpr_fo_addr();
void* f_sum_lambda_addr()
{
return (void*)&fit_test::fit_sum_lambda;
}
void* f_sum_fo_addr()
{
return (void*)&fit_test::fit_sum_fo;
}
void* f_sum_var_addr()
{
return (void*)&fit_test::fit_sum_var;
}
void* f_sum_constexpr_fo_addr()
{
return (void*)&fit_test::fit_sum_constexpr_fo;
}
int f()
{
if (fit_test::fit_sum_fo(1, 2) != 3) printf("FAILED\n");
if (fit_test::fit_sum_lambda(1, 2) != 3) printf("FAILED\n");
if (fit_test::fit_sum(1, 2) != 3) printf("FAILED\n");
#if BOOST_HOF_HAS_UNIQUE_STATIC_LAMBDA_FUNCTION_ADDR
if (sum_lambda_addr() != f_sum_lambda_addr()) printf("FAILED: Lambda\n");
if (sum_fo_addr() != f_sum_fo_addr()) printf("FAILED: Function object\n");
#endif
#if BOOST_HOF_HAS_UNIQUE_STATIC_VAR
if (sum_var_addr() != f_sum_var_addr()) printf("FAILED: Lambda\n");
if (sum_constexpr_fo_addr() != f_sum_constexpr_fo_addr()) printf("FAILED: Function object\n");
#endif
return 0;
}
| 28.59322 | 99 | 0.619443 | [
"object"
] |
814414aefbdb76b6ac48b82b7091453854ae027d | 3,116 | cpp | C++ | NNet/NNetModel/UPSigGenList.cpp | pk1954/solutions | 02cd67fc1e6299e9fe56ce04dce2515d6f30df92 | [
"MIT"
] | null | null | null | NNet/NNetModel/UPSigGenList.cpp | pk1954/solutions | 02cd67fc1e6299e9fe56ce04dce2515d6f30df92 | [
"MIT"
] | null | null | null | NNet/NNetModel/UPSigGenList.cpp | pk1954/solutions | 02cd67fc1e6299e9fe56ce04dce2515d6f30df92 | [
"MIT"
] | null | null | null | // UPSigGenList.cpp
//
// NNetModel
#include "stdafx.h"
#include "SignalGenerator.h"
#include "UPSigGenList.h"
UPSigGenList::UPSigGenList()
{
UPSigGen upSigGen { NewSigGen() };
upSigGen->SetName(STD_SIG_GEN_NAME);
PushSigGen(move(upSigGen));
SetActive(SigGenId(0));
}
UPSigGen UPSigGenList::removeSigGen(vector<UPSigGen>::iterator it)
{
if (it == m_list.end())
return UPSigGen(nullptr);
else
{
UPSigGen upSigGen = move(*it);
m_list.erase(it);
return move(upSigGen);
}
}
vector<UPSigGen>::iterator UPSigGenList::getSigGen(wstring const & name)
{
return find_if(m_list, [&name](auto & it){ return it->GetName() == name; });
}
vector<UPSigGen>::const_iterator UPSigGenList::getSigGen(wstring const & name) const
{
return find_if(m_list, [&name](auto & it){ return it->GetName() == name; });
}
vector<UPSigGen>::iterator UPSigGenList::getSigGen(SigGenId const id)
{
return m_list.begin() + id.GetValue();
}
vector<UPSigGen>::const_iterator UPSigGenList::getSigGen(SigGenId const id) const
{
return m_list.begin() + id.GetValue();
}
void UPSigGenList::InsertSigGen(UPSigGen upSigGen, SigGenId const id)
{
m_list.insert(getSigGen(id), move(upSigGen));
}
SigGenId UPSigGenList::FindSigGen(wstring const & name) const
{
auto it { getSigGen(name) };
return static_cast<SigGenId>(it - m_list.begin());
}
SignalGenerator const * UPSigGenList::GetSigGen(SigGenId const id) const
{
return m_list.at(id.GetValue()).get();
}
SignalGenerator * UPSigGenList::GetSigGen(SigGenId const id)
{
return m_list.at(id.GetValue()).get();
}
SignalGenerator * UPSigGenList::GetSigGen(wstring const & name)
{
auto it { getSigGen(name) };
return (it == m_list.end()) ? nullptr : it->get();
}
SignalGenerator const * UPSigGenList::GetSigGen(wstring const & name) const
{
auto it { getSigGen(name) };
return (it == m_list.end()) ? nullptr : it->get();
}
bool UPSigGenList::IsInList(wstring const & name) const
{
return FindSigGen(name).GetValue() < m_list.size();
}
UPSigGen UPSigGenList::NewSigGen()
{
return move(make_unique<SignalGenerator>(GenerateUniqueName()));
}
UPSigGen UPSigGenList::NewSigGen(wstring const & name)
{
return move(make_unique<SignalGenerator>(name));
}
SigGenId UPSigGenList::PushSigGen(UPSigGen upSigGen)
{
m_list.push_back(move(upSigGen));
return static_cast<SigGenId>(m_list.size()-1);
}
UPSigGen UPSigGenList::PopSigGen()
{
unique_ptr upSigGen { move(m_list.back()) };
m_list.pop_back();
return move(upSigGen);
}
UPSigGen UPSigGenList::RemoveSigGen(SigGenId const id)
{
return move(removeSigGen(getSigGen(id)));
}
UPSigGen UPSigGenList::RemoveSigGen(wstring const & name)
{
return move(removeSigGen(getSigGen(name)));
}
UPSigGen UPSigGenList::RemoveSigGen()
{
return move(RemoveSigGen(m_sigGenIdActive));
}
wstring UPSigGenList::GenerateUniqueName() const
{
int iNr { 0 };
wstring candidate;
do
candidate = L"SigGen " + to_wstring(++iNr);
while (GetSigGen(candidate) != nullptr);
return candidate;
}
| 23.253731 | 84 | 0.692875 | [
"vector"
] |
8145bdcd37c477cbdcd66dadb1183b12f3986002 | 26,512 | cc | C++ | extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-11-28T10:46:52.000Z | 2019-11-28T10:46:52.000Z | extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-27T11:15:39.000Z | 2016-08-17T14:19:56.000Z | // 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 "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.h"
#include "base/bind.h"
#include "base/lazy_instance.h"
#include "base/strings/stringprintf.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/api/bluetooth_low_energy/utils.h"
#include "extensions/browser/event_router.h"
#include "extensions/common/api/bluetooth/bluetooth_manifest_data.h"
#include "extensions/common/api/bluetooth_low_energy.h"
#include "extensions/common/permissions/permissions_data.h"
using content::BrowserContext;
using content::BrowserThread;
namespace apibtle = extensions::core_api::bluetooth_low_energy;
namespace extensions {
namespace {
const char kErrorAdapterNotInitialized[] =
"Could not initialize Bluetooth adapter";
const char kErrorAlreadyConnected[] = "Already connected";
const char kErrorAlreadyNotifying[] = "Already notifying";
const char kErrorAuthenticationFailed[] = "Authentication failed";
const char kErrorCanceled[] = "Request canceled";
const char kErrorGattNotSupported[] = "Operation not supported by this service";
const char kErrorHigherSecurity[] = "Higher security needed";
const char kErrorInProgress[] = "In progress";
const char kErrorInsufficientAuthorization[] = "Insufficient authorization";
const char kErrorInvalidLength[] = "Invalid attribute value length";
const char kErrorNotConnected[] = "Not connected";
const char kErrorNotFound[] = "Instance not found";
const char kErrorNotNotifying[] = "Not notifying";
const char kErrorOperationFailed[] = "Operation failed";
const char kErrorPermissionDenied[] = "Permission denied";
const char kErrorPlatformNotSupported[] =
"This operation is not supported on the current platform";
const char kErrorTimeout[] = "Operation timed out";
const char kErrorUnsupportedDevice[] =
"This device is not supported on the current platform";
// Returns the correct error string based on error status |status|. This is used
// to set the value of |chrome.runtime.lastError.message| and should not be
// passed |BluetoothLowEnergyEventRouter::kStatusSuccess|.
std::string StatusToString(BluetoothLowEnergyEventRouter::Status status) {
switch (status) {
case BluetoothLowEnergyEventRouter::kStatusErrorPermissionDenied:
return kErrorPermissionDenied;
case BluetoothLowEnergyEventRouter::kStatusErrorNotFound:
return kErrorNotFound;
case BluetoothLowEnergyEventRouter::kStatusErrorAlreadyConnected:
return kErrorAlreadyConnected;
case BluetoothLowEnergyEventRouter::kStatusErrorAlreadyNotifying:
return kErrorAlreadyNotifying;
case BluetoothLowEnergyEventRouter::kStatusErrorNotConnected:
return kErrorNotConnected;
case BluetoothLowEnergyEventRouter::kStatusErrorInsufficientAuthorization:
return kErrorInsufficientAuthorization;
case BluetoothLowEnergyEventRouter::kStatusErrorNotNotifying:
return kErrorNotNotifying;
case BluetoothLowEnergyEventRouter::kStatusErrorInProgress:
return kErrorInProgress;
case BluetoothLowEnergyEventRouter::kStatusErrorAuthenticationFailed:
return kErrorAuthenticationFailed;
case BluetoothLowEnergyEventRouter::kStatusErrorHigherSecurity:
return kErrorHigherSecurity;
case BluetoothLowEnergyEventRouter::kStatusErrorCanceled:
return kErrorCanceled;
case BluetoothLowEnergyEventRouter::kStatusErrorTimeout:
return kErrorTimeout;
case BluetoothLowEnergyEventRouter::kStatusErrorUnsupportedDevice:
return kErrorUnsupportedDevice;
case BluetoothLowEnergyEventRouter::kStatusErrorInvalidLength:
return kErrorInvalidLength;
case BluetoothLowEnergyEventRouter::kStatusErrorGattNotSupported:
return kErrorGattNotSupported;
case BluetoothLowEnergyEventRouter::kStatusSuccess:
NOTREACHED();
break;
default:
return kErrorOperationFailed;
}
return "";
}
extensions::BluetoothLowEnergyEventRouter* GetEventRouter(
BrowserContext* context) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
return extensions::BluetoothLowEnergyAPI::Get(context)->event_router();
}
void DoWorkCallback(const base::Callback<bool()>& callback) {
DCHECK(!callback.is_null());
callback.Run();
}
} // namespace
static base::LazyInstance<BrowserContextKeyedAPIFactory<BluetoothLowEnergyAPI> >
g_factory = LAZY_INSTANCE_INITIALIZER;
// static
BrowserContextKeyedAPIFactory<BluetoothLowEnergyAPI>*
BluetoothLowEnergyAPI::GetFactoryInstance() {
return g_factory.Pointer();
}
// static
BluetoothLowEnergyAPI* BluetoothLowEnergyAPI::Get(BrowserContext* context) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
return GetFactoryInstance()->Get(context);
}
BluetoothLowEnergyAPI::BluetoothLowEnergyAPI(BrowserContext* context)
: event_router_(new BluetoothLowEnergyEventRouter(context)),
browser_context_(context) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
BluetoothLowEnergyAPI::~BluetoothLowEnergyAPI() {
}
void BluetoothLowEnergyAPI::Shutdown() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
namespace core_api {
BluetoothLowEnergyExtensionFunction::BluetoothLowEnergyExtensionFunction() {
}
BluetoothLowEnergyExtensionFunction::~BluetoothLowEnergyExtensionFunction() {
}
bool BluetoothLowEnergyExtensionFunction::RunAsync() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!BluetoothManifestData::CheckLowEnergyPermitted(extension())) {
error_ = kErrorPermissionDenied;
return false;
}
BluetoothLowEnergyEventRouter* event_router =
GetEventRouter(browser_context());
if (!event_router->IsBluetoothSupported()) {
SetError(kErrorPlatformNotSupported);
return false;
}
// It is safe to pass |this| here as ExtensionFunction is refcounted.
if (!event_router->InitializeAdapterAndInvokeCallback(base::Bind(
&DoWorkCallback,
base::Bind(&BluetoothLowEnergyExtensionFunction::DoWork, this)))) {
SetError(kErrorAdapterNotInitialized);
return false;
}
return true;
}
bool BluetoothLowEnergyConnectFunction::DoWork() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BluetoothLowEnergyEventRouter* event_router =
GetEventRouter(browser_context());
// The adapter must be initialized at this point, but return an error instead
// of asserting.
if (!event_router->HasAdapter()) {
SetError(kErrorAdapterNotInitialized);
SendResponse(false);
return false;
}
scoped_ptr<apibtle::Connect::Params> params(
apibtle::Connect::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
bool persistent = false; // Not persistent by default.
apibtle::ConnectProperties* properties = params.get()->properties.get();
if (properties)
persistent = properties->persistent;
event_router->Connect(
persistent,
extension(),
params->device_address,
base::Bind(&BluetoothLowEnergyConnectFunction::SuccessCallback, this),
base::Bind(&BluetoothLowEnergyConnectFunction::ErrorCallback, this));
return true;
}
void BluetoothLowEnergyConnectFunction::SuccessCallback() {
SendResponse(true);
}
void BluetoothLowEnergyConnectFunction::ErrorCallback(
BluetoothLowEnergyEventRouter::Status status) {
SetError(StatusToString(status));
SendResponse(false);
}
bool BluetoothLowEnergyDisconnectFunction::DoWork() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BluetoothLowEnergyEventRouter* event_router =
GetEventRouter(browser_context());
// The adapter must be initialized at this point, but return an error instead
// of asserting.
if (!event_router->HasAdapter()) {
SetError(kErrorAdapterNotInitialized);
SendResponse(false);
return false;
}
scoped_ptr<apibtle::Disconnect::Params> params(
apibtle::Disconnect::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
event_router->Disconnect(
extension(),
params->device_address,
base::Bind(&BluetoothLowEnergyDisconnectFunction::SuccessCallback, this),
base::Bind(&BluetoothLowEnergyDisconnectFunction::ErrorCallback, this));
return true;
}
void BluetoothLowEnergyDisconnectFunction::SuccessCallback() {
SendResponse(true);
}
void BluetoothLowEnergyDisconnectFunction::ErrorCallback(
BluetoothLowEnergyEventRouter::Status status) {
SetError(StatusToString(status));
SendResponse(false);
}
bool BluetoothLowEnergyGetServiceFunction::DoWork() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BluetoothLowEnergyEventRouter* event_router =
GetEventRouter(browser_context());
// The adapter must be initialized at this point, but return an error instead
// of asserting.
if (!event_router->HasAdapter()) {
SetError(kErrorAdapterNotInitialized);
SendResponse(false);
return false;
}
scoped_ptr<apibtle::GetService::Params> params(
apibtle::GetService::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
apibtle::Service service;
BluetoothLowEnergyEventRouter::Status status =
event_router->GetService(params->service_id, &service);
if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) {
SetError(StatusToString(status));
SendResponse(false);
return false;
}
results_ = apibtle::GetService::Results::Create(service);
SendResponse(true);
return true;
}
bool BluetoothLowEnergyGetServicesFunction::DoWork() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BluetoothLowEnergyEventRouter* event_router =
GetEventRouter(browser_context());
// The adapter must be initialized at this point, but return an error instead
// of asserting.
if (!event_router->HasAdapter()) {
SetError(kErrorAdapterNotInitialized);
SendResponse(false);
return false;
}
scoped_ptr<apibtle::GetServices::Params> params(
apibtle::GetServices::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
BluetoothLowEnergyEventRouter::ServiceList service_list;
if (!event_router->GetServices(params->device_address, &service_list)) {
SetError(kErrorNotFound);
SendResponse(false);
return false;
}
results_ = apibtle::GetServices::Results::Create(service_list);
SendResponse(true);
return true;
}
bool BluetoothLowEnergyGetCharacteristicFunction::DoWork() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BluetoothLowEnergyEventRouter* event_router =
GetEventRouter(browser_context());
// The adapter must be initialized at this point, but return an error instead
// of asserting.
if (!event_router->HasAdapter()) {
SetError(kErrorAdapterNotInitialized);
SendResponse(false);
return false;
}
scoped_ptr<apibtle::GetCharacteristic::Params> params(
apibtle::GetCharacteristic::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
apibtle::Characteristic characteristic;
BluetoothLowEnergyEventRouter::Status status =
event_router->GetCharacteristic(
extension(), params->characteristic_id, &characteristic);
if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) {
SetError(StatusToString(status));
SendResponse(false);
return false;
}
// Manually construct the result instead of using
// apibtle::GetCharacteristic::Result::Create as it doesn't convert lists of
// enums correctly.
SetResult(apibtle::CharacteristicToValue(&characteristic).release());
SendResponse(true);
return true;
}
bool BluetoothLowEnergyGetCharacteristicsFunction::DoWork() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BluetoothLowEnergyEventRouter* event_router =
GetEventRouter(browser_context());
// The adapter must be initialized at this point, but return an error instead
// of asserting.
if (!event_router->HasAdapter()) {
SetError(kErrorAdapterNotInitialized);
SendResponse(false);
return false;
}
scoped_ptr<apibtle::GetCharacteristics::Params> params(
apibtle::GetCharacteristics::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
BluetoothLowEnergyEventRouter::CharacteristicList characteristic_list;
BluetoothLowEnergyEventRouter::Status status =
event_router->GetCharacteristics(
extension(), params->service_id, &characteristic_list);
if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) {
SetError(StatusToString(status));
SendResponse(false);
return false;
}
// Manually construct the result instead of using
// apibtle::GetCharacteristics::Result::Create as it doesn't convert lists of
// enums correctly.
scoped_ptr<base::ListValue> result(new base::ListValue());
for (BluetoothLowEnergyEventRouter::CharacteristicList::iterator iter =
characteristic_list.begin();
iter != characteristic_list.end();
++iter)
result->Append(apibtle::CharacteristicToValue(iter->get()).release());
SetResult(result.release());
SendResponse(true);
return true;
}
bool BluetoothLowEnergyGetIncludedServicesFunction::DoWork() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BluetoothLowEnergyEventRouter* event_router =
GetEventRouter(browser_context());
// The adapter must be initialized at this point, but return an error instead
// of asserting.
if (!event_router->HasAdapter()) {
SetError(kErrorAdapterNotInitialized);
SendResponse(false);
return false;
}
scoped_ptr<apibtle::GetIncludedServices::Params> params(
apibtle::GetIncludedServices::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
BluetoothLowEnergyEventRouter::ServiceList service_list;
BluetoothLowEnergyEventRouter::Status status =
event_router->GetIncludedServices(params->service_id, &service_list);
if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) {
SetError(StatusToString(status));
SendResponse(false);
return false;
}
results_ = apibtle::GetIncludedServices::Results::Create(service_list);
SendResponse(true);
return true;
}
bool BluetoothLowEnergyGetDescriptorFunction::DoWork() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BluetoothLowEnergyEventRouter* event_router =
GetEventRouter(browser_context());
// The adapter must be initialized at this point, but return an error instead
// of asserting.
if (!event_router->HasAdapter()) {
SetError(kErrorAdapterNotInitialized);
SendResponse(false);
return false;
}
scoped_ptr<apibtle::GetDescriptor::Params> params(
apibtle::GetDescriptor::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
apibtle::Descriptor descriptor;
BluetoothLowEnergyEventRouter::Status status = event_router->GetDescriptor(
extension(), params->descriptor_id, &descriptor);
if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) {
SetError(StatusToString(status));
SendResponse(false);
return false;
}
// Manually construct the result instead of using
// apibtle::GetDescriptor::Result::Create as it doesn't convert lists of enums
// correctly.
SetResult(apibtle::DescriptorToValue(&descriptor).release());
SendResponse(true);
return true;
}
bool BluetoothLowEnergyGetDescriptorsFunction::DoWork() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BluetoothLowEnergyEventRouter* event_router =
GetEventRouter(browser_context());
// The adapter must be initialized at this point, but return an error instead
// of asserting.
if (!event_router->HasAdapter()) {
SetError(kErrorAdapterNotInitialized);
SendResponse(false);
return false;
}
scoped_ptr<apibtle::GetDescriptors::Params> params(
apibtle::GetDescriptors::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
BluetoothLowEnergyEventRouter::DescriptorList descriptor_list;
BluetoothLowEnergyEventRouter::Status status = event_router->GetDescriptors(
extension(), params->characteristic_id, &descriptor_list);
if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) {
SetError(StatusToString(status));
SendResponse(false);
return false;
}
// Manually construct the result instead of using
// apibtle::GetDescriptors::Result::Create as it doesn't convert lists of
// enums correctly.
scoped_ptr<base::ListValue> result(new base::ListValue());
for (BluetoothLowEnergyEventRouter::DescriptorList::iterator iter =
descriptor_list.begin();
iter != descriptor_list.end();
++iter)
result->Append(apibtle::DescriptorToValue(iter->get()).release());
SetResult(result.release());
SendResponse(true);
return true;
}
bool BluetoothLowEnergyReadCharacteristicValueFunction::DoWork() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BluetoothLowEnergyEventRouter* event_router =
GetEventRouter(browser_context());
// The adapter must be initialized at this point, but return an error instead
// of asserting.
if (!event_router->HasAdapter()) {
SetError(kErrorAdapterNotInitialized);
SendResponse(false);
return false;
}
scoped_ptr<apibtle::ReadCharacteristicValue::Params> params(
apibtle::ReadCharacteristicValue::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
instance_id_ = params->characteristic_id;
event_router->ReadCharacteristicValue(
extension(),
instance_id_,
base::Bind(
&BluetoothLowEnergyReadCharacteristicValueFunction::SuccessCallback,
this),
base::Bind(
&BluetoothLowEnergyReadCharacteristicValueFunction::ErrorCallback,
this));
return true;
}
void BluetoothLowEnergyReadCharacteristicValueFunction::SuccessCallback() {
// Obtain info on the characteristic and see whether or not the characteristic
// is still around.
apibtle::Characteristic characteristic;
BluetoothLowEnergyEventRouter::Status status =
GetEventRouter(browser_context())
->GetCharacteristic(extension(), instance_id_, &characteristic);
if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) {
SetError(StatusToString(status));
SendResponse(false);
return;
}
// Manually construct the result instead of using
// apibtle::GetCharacteristic::Result::Create as it doesn't convert lists of
// enums correctly.
SetResult(apibtle::CharacteristicToValue(&characteristic).release());
SendResponse(true);
}
void BluetoothLowEnergyReadCharacteristicValueFunction::ErrorCallback(
BluetoothLowEnergyEventRouter::Status status) {
SetError(StatusToString(status));
SendResponse(false);
}
bool BluetoothLowEnergyWriteCharacteristicValueFunction::DoWork() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BluetoothLowEnergyEventRouter* event_router =
GetEventRouter(browser_context());
// The adapter must be initialized at this point, but return an error instead
// of asserting.
if (!event_router->HasAdapter()) {
SetError(kErrorAdapterNotInitialized);
SendResponse(false);
return false;
}
scoped_ptr<apibtle::WriteCharacteristicValue::Params> params(
apibtle::WriteCharacteristicValue::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
std::vector<uint8> value(params->value.begin(), params->value.end());
event_router->WriteCharacteristicValue(
extension(),
params->characteristic_id,
value,
base::Bind(
&BluetoothLowEnergyWriteCharacteristicValueFunction::SuccessCallback,
this),
base::Bind(
&BluetoothLowEnergyWriteCharacteristicValueFunction::ErrorCallback,
this));
return true;
}
void BluetoothLowEnergyWriteCharacteristicValueFunction::SuccessCallback() {
results_ = apibtle::WriteCharacteristicValue::Results::Create();
SendResponse(true);
}
void BluetoothLowEnergyWriteCharacteristicValueFunction::ErrorCallback(
BluetoothLowEnergyEventRouter::Status status) {
SetError(StatusToString(status));
SendResponse(false);
}
bool BluetoothLowEnergyStartCharacteristicNotificationsFunction::DoWork() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BluetoothLowEnergyEventRouter* event_router =
GetEventRouter(browser_context());
// The adapter must be initialized at this point, but return an error instead
// of asserting.
if (!event_router->HasAdapter()) {
SetError(kErrorAdapterNotInitialized);
SendResponse(false);
return false;
}
scoped_ptr<apibtle::StartCharacteristicNotifications::Params> params(
apibtle::StartCharacteristicNotifications::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
bool persistent = false; // Not persistent by default.
apibtle::NotificationProperties* properties = params.get()->properties.get();
if (properties)
persistent = properties->persistent;
event_router->StartCharacteristicNotifications(
persistent,
extension(),
params->characteristic_id,
base::Bind(&BluetoothLowEnergyStartCharacteristicNotificationsFunction::
SuccessCallback,
this),
base::Bind(&BluetoothLowEnergyStartCharacteristicNotificationsFunction::
ErrorCallback,
this));
return true;
}
void
BluetoothLowEnergyStartCharacteristicNotificationsFunction::SuccessCallback() {
SendResponse(true);
}
void BluetoothLowEnergyStartCharacteristicNotificationsFunction::ErrorCallback(
BluetoothLowEnergyEventRouter::Status status) {
SetError(StatusToString(status));
SendResponse(false);
}
bool BluetoothLowEnergyStopCharacteristicNotificationsFunction::DoWork() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BluetoothLowEnergyEventRouter* event_router =
GetEventRouter(browser_context());
// The adapter must be initialized at this point, but return an error instead
// of asserting.
if (!event_router->HasAdapter()) {
SetError(kErrorAdapterNotInitialized);
SendResponse(false);
return false;
}
scoped_ptr<apibtle::StopCharacteristicNotifications::Params> params(
apibtle::StopCharacteristicNotifications::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
event_router->StopCharacteristicNotifications(
extension(),
params->characteristic_id,
base::Bind(&BluetoothLowEnergyStopCharacteristicNotificationsFunction::
SuccessCallback,
this),
base::Bind(&BluetoothLowEnergyStopCharacteristicNotificationsFunction::
ErrorCallback,
this));
return true;
}
void
BluetoothLowEnergyStopCharacteristicNotificationsFunction::SuccessCallback() {
SendResponse(true);
}
void BluetoothLowEnergyStopCharacteristicNotificationsFunction::ErrorCallback(
BluetoothLowEnergyEventRouter::Status status) {
SetError(StatusToString(status));
SendResponse(false);
}
bool BluetoothLowEnergyReadDescriptorValueFunction::DoWork() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BluetoothLowEnergyEventRouter* event_router =
GetEventRouter(browser_context());
// The adapter must be initialized at this point, but return an error instead
// of asserting.
if (!event_router->HasAdapter()) {
SetError(kErrorAdapterNotInitialized);
SendResponse(false);
return false;
}
scoped_ptr<apibtle::ReadDescriptorValue::Params> params(
apibtle::ReadDescriptorValue::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
instance_id_ = params->descriptor_id;
event_router->ReadDescriptorValue(
extension(),
instance_id_,
base::Bind(
&BluetoothLowEnergyReadDescriptorValueFunction::SuccessCallback,
this),
base::Bind(&BluetoothLowEnergyReadDescriptorValueFunction::ErrorCallback,
this));
return true;
}
void BluetoothLowEnergyReadDescriptorValueFunction::SuccessCallback() {
// Obtain info on the descriptor and see whether or not the descriptor is
// still around.
apibtle::Descriptor descriptor;
BluetoothLowEnergyEventRouter::Status status =
GetEventRouter(browser_context())
->GetDescriptor(extension(), instance_id_, &descriptor);
if (status != BluetoothLowEnergyEventRouter::kStatusSuccess) {
SetError(StatusToString(status));
SendResponse(false);
return;
}
// Manually construct the result instead of using
// apibtle::GetDescriptor::Results::Create as it doesn't convert lists of
// enums correctly.
SetResult(apibtle::DescriptorToValue(&descriptor).release());
SendResponse(true);
}
void BluetoothLowEnergyReadDescriptorValueFunction::ErrorCallback(
BluetoothLowEnergyEventRouter::Status status) {
SetError(StatusToString(status));
SendResponse(false);
}
bool BluetoothLowEnergyWriteDescriptorValueFunction::DoWork() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BluetoothLowEnergyEventRouter* event_router =
GetEventRouter(browser_context());
// The adapter must be initialized at this point, but return an error instead
// of asserting.
if (!event_router->HasAdapter()) {
SetError(kErrorAdapterNotInitialized);
SendResponse(false);
return false;
}
scoped_ptr<apibtle::WriteDescriptorValue::Params> params(
apibtle::WriteDescriptorValue::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);
std::vector<uint8> value(params->value.begin(), params->value.end());
event_router->WriteDescriptorValue(
extension(),
params->descriptor_id,
value,
base::Bind(
&BluetoothLowEnergyWriteDescriptorValueFunction::SuccessCallback,
this),
base::Bind(&BluetoothLowEnergyWriteDescriptorValueFunction::ErrorCallback,
this));
return true;
}
void BluetoothLowEnergyWriteDescriptorValueFunction::SuccessCallback() {
results_ = apibtle::WriteDescriptorValue::Results::Create();
SendResponse(true);
}
void BluetoothLowEnergyWriteDescriptorValueFunction::ErrorCallback(
BluetoothLowEnergyEventRouter::Status status) {
SetError(StatusToString(status));
SendResponse(false);
}
} // namespace core_api
} // namespace extensions
| 33.181477 | 81 | 0.75381 | [
"vector"
] |
8148df6d25f712259f915a3e282ad75110ce2a6b | 7,473 | cpp | C++ | ODFAEG/src/odfaeg/BoundingAreas/boundingEllipse.cpp | Cwc-Test/ODFAEG | 5e5bd13e3145764c3d0182225aad591040691481 | [
"Zlib"
] | 5 | 2015-06-13T13:11:59.000Z | 2020-04-17T23:10:23.000Z | ODFAEG/src/odfaeg/BoundingAreas/boundingEllipse.cpp | Cwc-Test/ODFAEG | 5e5bd13e3145764c3d0182225aad591040691481 | [
"Zlib"
] | 4 | 2019-01-07T11:46:21.000Z | 2020-02-14T15:04:15.000Z | ODFAEG/src/odfaeg/BoundingAreas/boundingEllipse.cpp | Cwc-Test/ODFAEG | 5e5bd13e3145764c3d0182225aad591040691481 | [
"Zlib"
] | 4 | 2016-01-05T09:54:57.000Z | 2021-01-06T18:52:26.000Z | #include "../../../include/odfaeg/BoundingAreas/boundingEllipse.h"
#include "../../../include/odfaeg/BoundingAreas/boundingCircle.h"
#include "../../../include/odfaeg/BoundingAreas/boundingRectangle.h"
#include "../../../include/odfaeg/BoundingAreas/orientedBoundingRect.h"
#include "../../../include/odfaeg/BoundingAreas/boundingPolygon.h"
#include "../../../include/odfaeg/math/Matrix4.h"
namespace odfaeg {
BoundingEllipsoid::BoundingEllipsoid(Vec3f center, int a, int b, int c) {
this->center = center;
radius = Vec3f(a, b, c);
}
bool BoundingEllipsoid::intersects(BoundingSphere &bs) {
//We do the same for check the collision with a circle, except taht the circle have only 1 ray.
//The equation for the circle is then a bit different.
Vec3f d = bs.getCenter() - center;
float m = center.computeDist(bs.getCenter());
Vec3f near, far;
Ray r(bs.getCenter(), center);
intersectsWhere(r, near, far);
Vec3f d2 = near - center;
int ray1 = d.projOnAxis(d2);
d = center - bs.getCenter();
bs.intersectsWhere(r,near,far);
d2 = near - bs.getCenter();
int ray2 = d.projOnAxis(d2);
float rSum = ray1 + ray2;
if (m - rSum > 0)
return false;
return true;
}
bool BoundingEllipsoid::intersects(BoundingEllipsoid &be) {
//The distance between the 2 centers.
Vec3f d = be.getCenter() - center;
float m = center.computeDist(be.getCenter());
Vec3f near, far;
Ray r(be.getCenter(), center);
intersectsWhere(r, near, far);
Vec3f d2 = near - center;
int ray1 = d.projOnAxis(d2);
d = center - be.getCenter();
r = Ray(center, be.getCenter());
be.intersectsWhere(r,near,far);
d2 = near - be.getCenter();
int ray2 = d.projOnAxis(d2);
float rSum = ray1 + ray2;
if (m - rSum > 0)
return false;
return true;
}
bool BoundingEllipsoid::intersects(BoundingBox &bx) {
Vec3f d = bx.getCenter() - center;
float m = center.computeDist(bx.getCenter());
Vec3f near, far;
Ray r(bx.getCenter(), center);
intersectsWhere(r, near, far);
Vec3f d2 = near - center;
int ray = d.projOnAxis(d2);
float hi[3];
hi[0] = bx.getWidth() * 0.5f;
hi[1] = bx.getHeight() * 0.5f;
hi[2] = bx.getDepth() * 0.5f;
for (unsigned int i = 0; i < 3; i++) {
//Do the sum of the 2 rays of our bounding volumes.
float rSum = ray + hi[i];
/*If the distance between the two centers is shorter than the sum of the rays,
* it means that our two bouding volumes are in collision.
*(Separator axis theorem)
*/
if (m - rSum > 0)
return false;
}
return true;
}
bool BoundingEllipsoid::intersects(OrientedBoundingBox &obx) {
//The direction of the straigth between the two centers.
Vec3f d = obx.getCenter() - center;
float m = center.computeDist(obx.getCenter());
Vec3f near, far;
Ray r(obx.getCenter(), center);
intersectsWhere(r, near, far);
Vec3f d2 = near - center;
int ray1 = d.projOnAxis(d2);
Vec3f bi[3];
//Vectors between the center of the oriented bounding rectangle, and the halfs of the edges.
bi[0] = obx.getBX() * obx.getWidth() * 0.5f;
bi[1] = obx.getBY() * obx.getHeight() * 0.5f;
bi[2] = obx.getBZ() * obx.getDepth() * 0.5f;
for (unsigned int i = 0; i < 3; i++) {
//Projection of the ray of our oriented bouding rect from d to the x and y axis.
float ray2 = d.projOnAxis(bi[i]);
//Do the sum of the 2 rays of our bounding volumes.
float rSum = ray1 + ray2;
/*If the distance between the two centers is shorter than the sum of the rays,
* it means that our two bouding volumes are in collision.
*(Separator axis theorem)
*/
if (m - rSum > 0)
return false;
}
return true;
}
bool BoundingEllipsoid::intersects(BoundingPolyhedron &bp) {
//The direction of the straigth between the two centers.
Vec3f d = bp.getCenter() - center;
//The distance between the 2 centers.
float m = center.computeDist(bp.getCenter());
Vec3f near, far;
Ray r(bp.getCenter(), center);
intersectsWhere(r, near, far);
Vec3f d2 = near - center;
int ray1 = d.projOnAxis(d2);
Vec3f a = bp.getPoint(0);
Vec3f b = bp.getPoint(1);
Vec3f mid = a + (b - a) * 0.5f;
Vec3f bi = mid - bp.getCenter();
float proj = d.projOnAxis(bi);
int min = proj;
int max = proj;
for (unsigned int j = 1; j < bp.nbPoints(); j++) {
a = bp.getPoint(j);
if (j != bp.nbPoints() - 1)
b = bp.getPoint(j+1);
else
b = bp.getPoint(0);
mid = a + (b - a) * 0.5f;
bi = (mid - bp.getCenter()) * 0.5f;
proj = d.projOnAxis(bi);
if (proj < min)
min = proj;
if (proj > max)
max = proj;
}
int ray2 = max - min;
int rSum = ray1 + ray2;
if (m - rSum > 0.f)
return false;
return false;
}
bool BoundingEllipsoid::intersects (Ray &r) {
Matrix4f scale (radius.x, 0, 0, 0,
0, radius.y, 0, 0,
0, 0, radius.z, 0,
0, 0, 0, 1);
Matrix4f rotation (1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
Matrix4f translation (1, 0, 0, center.x,
0, 1, 0, center.y,
0, 0, 1, center.z,
0, 0, 0, 1);
Matrix4f transform = scale * rotation * translation;
Matrix4f invTransform = transform.inverse();
Vec3f orig = invTransform * r.getOrig();
Vec3f ext = invTransform * r.getOrig();
Ray tRay (orig, ext);
for (unsigned int i = 0; i < 3; i++) {
BoundingSphere bs(Vec3f(0, 0, 0), radius[i]);
if (!bs.intersects(tRay))
return false;
}
return true;
}
bool BoundingEllipsoid::intersectsWhere(Ray& r, Vec3f& near, Vec3f& far) {
Matrix4f scale (radius.x, 0, 0, 0,
0, radius.y, 0, 0,
0, 0, radius.z, 0,
0, 0, 0, 1);
Matrix4f rotation (1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
Matrix4f translation (1, 0, 0, center.x,
0, 1, 0, center.y,
0, 0, 1, center.z,
0, 0, 0, 1);
Matrix4f transform = scale * rotation * translation;
Matrix4f invTransform = transform.inverse();
Vec3f orig = invTransform * r.getOrig();
Vec3f ext = invTransform * r.getOrig();
Ray tRay (orig, ext);
Vec3f i1, i2;
for (unsigned int i = 0; i < 3; i++) {
BoundingSphere bs(Vec3f(0, 0, 0), radius[i]);
Vec3f tmpi1, tmpi2;
if (!bs.intersectsWhere(tRay, tmpi1, tmpi2))
return false;
i1[i] = tmpi1[i];
i2[i] = tmpi2[i];
}
near = transform * i1;
far = transform * i2;
return true;
}
bool BoundingEllipsoid::isPointInside (Vec3f point) {
Ray r (center, point);
if (!intersects(r))
return false;
return true;
}
Vec3f BoundingEllipsoid::getCenter() {
return center;
}
Vec3f BoundingEllipsoid::getRadius() {
return radius;
}
}
| 35.927885 | 100 | 0.548374 | [
"transform"
] |
8148fbc96c14050f6e8e30b639462bbad01034ce | 12,645 | cc | C++ | weblayer/browser/browser_context_impl.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | weblayer/browser/browser_context_impl.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | weblayer/browser/browser_context_impl.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2019 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 "weblayer/browser/browser_context_impl.h"
#include "base/threading/thread_restrictions.h"
#include "components/background_sync/background_sync_controller_impl.h"
#include "components/blocked_content/safe_browsing_triggered_popup_blocker.h"
#include "components/client_hints/browser/client_hints.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/download/public/common/in_progress_download_manager.h"
#include "components/embedder_support/pref_names.h"
#include "components/heavy_ad_intervention/heavy_ad_service.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/language/core/browser/language_prefs.h"
#include "components/payments/core/payment_prefs.h"
#include "components/permissions/permission_manager.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/in_memory_pref_store.h"
#include "components/prefs/json_pref_store.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/pref_service_factory.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "components/security_interstitials/content/stateful_ssl_host_state_delegate.h"
#include "components/site_isolation/pref_names.h"
#include "components/site_isolation/site_isolation_policy.h"
#include "components/translate/core/browser/translate_pref_names.h"
#include "components/translate/core/browser/translate_prefs.h"
#include "components/user_prefs/user_prefs.h"
#include "components/variations/proto/study.pb.h"
#include "components/variations/variations.mojom.h"
#include "components/variations/variations_client.h"
#include "components/variations/variations_ids_provider.h"
#include "content/public/browser/device_service.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/resource_context.h"
#include "content/public/browser/storage_partition.h"
#include "weblayer/browser/background_fetch/background_fetch_delegate_factory.h"
#include "weblayer/browser/background_fetch/background_fetch_delegate_impl.h"
#include "weblayer/browser/background_sync/background_sync_controller_factory.h"
#include "weblayer/browser/browsing_data_remover_delegate.h"
#include "weblayer/browser/browsing_data_remover_delegate_factory.h"
#include "weblayer/browser/client_hints_factory.h"
#include "weblayer/browser/default_search_engine.h"
#include "weblayer/browser/heavy_ad_service_factory.h"
#include "weblayer/browser/permissions/permission_manager_factory.h"
#include "weblayer/browser/stateful_ssl_host_state_delegate_factory.h"
#include "weblayer/public/common/switches.h"
#if defined(OS_ANDROID)
#include "base/android/path_utils.h"
#include "components/cdm/browser/media_drm_storage_impl.h" // nogncheck
#include "components/permissions/contexts/geolocation_permission_context_android.h"
#include "components/unified_consent/pref_names.h"
#elif defined(OS_WIN)
#include <KnownFolders.h>
#include <shlobj.h>
#include "base/win/scoped_co_mem.h"
#elif defined(OS_POSIX)
#include "base/nix/xdg_util.h"
#endif
namespace weblayer {
namespace {
// Ignores origin security check. DownloadManagerImpl will provide its own
// implementation when InProgressDownloadManager object is passed to it.
bool IgnoreOriginSecurityCheck(const GURL& url) {
return true;
}
void BindWakeLockProvider(
mojo::PendingReceiver<device::mojom::WakeLockProvider> receiver) {
content::GetDeviceService().BindWakeLockProvider(std::move(receiver));
}
} // namespace
namespace prefs {
// Used to persist the public SettingType::NETWORK_PREDICTION_ENABLED API.
const char kNoStatePrefetchEnabled[] = "weblayer.network_prediction_enabled";
// Used to persist the public SettingType::UKM_ENABLED API.
const char kUkmEnabled[] = "weblayer.ukm_enabled";
} // namespace prefs
class ResourceContextImpl : public content::ResourceContext {
public:
ResourceContextImpl() = default;
~ResourceContextImpl() override = default;
private:
DISALLOW_COPY_AND_ASSIGN(ResourceContextImpl);
};
BrowserContextImpl::BrowserContextImpl(ProfileImpl* profile_impl,
const base::FilePath& path)
: profile_impl_(profile_impl),
path_(path),
simple_factory_key_(path, path.empty()),
resource_context_(new ResourceContextImpl()),
download_delegate_(BrowserContext::GetDownloadManager(this)) {
CreateUserPrefService();
BrowserContextDependencyManager::GetInstance()->CreateBrowserContextServices(
this);
auto* heavy_ad_service = HeavyAdServiceFactory::GetForBrowserContext(this);
if (IsOffTheRecord()) {
heavy_ad_service->InitializeOffTheRecord();
} else {
heavy_ad_service->Initialize(GetPath());
}
site_isolation::SiteIsolationPolicy::ApplyPersistedIsolatedOrigins(this);
// Set the DSE permissions every time the browser context is created for
// simplicity. These permissions are not editable in site settings, so should
// not ever be changed by the user. The site settings entry will link to the
// client app's system level permissions page to handle these.
ResetDsePermissions(this);
}
BrowserContextImpl::~BrowserContextImpl() {
NotifyWillBeDestroyed(this);
BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
this);
}
base::FilePath BrowserContextImpl::GetDefaultDownloadDirectory() {
// Note: if we wanted to productionize this on Windows/Linux, refactor
// src/chrome's GetDefaultDownloadDirectory.
base::FilePath download_dir;
#if defined(OS_ANDROID)
base::android::GetDownloadsDirectory(&download_dir);
#elif defined(OS_WIN)
base::win::ScopedCoMem<wchar_t> path_buf;
if (SUCCEEDED(
SHGetKnownFolderPath(FOLDERID_Downloads, 0, nullptr, &path_buf))) {
download_dir = base::FilePath(path_buf.get());
} else {
NOTREACHED();
}
#else
download_dir = base::nix::GetXDGUserDirectory("DOWNLOAD", "Downloads");
#endif
return download_dir;
}
#if !defined(OS_ANDROID)
std::unique_ptr<content::ZoomLevelDelegate>
BrowserContextImpl::CreateZoomLevelDelegate(const base::FilePath&) {
return nullptr;
}
#endif // !defined(OS_ANDROID)
base::FilePath BrowserContextImpl::GetPath() {
return path_;
}
bool BrowserContextImpl::IsOffTheRecord() {
return path_.empty();
}
content::DownloadManagerDelegate*
BrowserContextImpl::GetDownloadManagerDelegate() {
return &download_delegate_;
}
content::ResourceContext* BrowserContextImpl::GetResourceContext() {
return resource_context_.get();
}
content::BrowserPluginGuestManager* BrowserContextImpl::GetGuestManager() {
return nullptr;
}
storage::SpecialStoragePolicy* BrowserContextImpl::GetSpecialStoragePolicy() {
return nullptr;
}
content::PushMessagingService* BrowserContextImpl::GetPushMessagingService() {
return nullptr;
}
content::StorageNotificationService*
BrowserContextImpl::GetStorageNotificationService() {
return nullptr;
}
content::SSLHostStateDelegate* BrowserContextImpl::GetSSLHostStateDelegate() {
return StatefulSSLHostStateDelegateFactory::GetForBrowserContext(this);
}
content::PermissionControllerDelegate*
BrowserContextImpl::GetPermissionControllerDelegate() {
return PermissionManagerFactory::GetForBrowserContext(this);
}
content::ClientHintsControllerDelegate*
BrowserContextImpl::GetClientHintsControllerDelegate() {
return ClientHintsFactory::GetForBrowserContext(this);
}
content::BackgroundFetchDelegate*
BrowserContextImpl::GetBackgroundFetchDelegate() {
return BackgroundFetchDelegateFactory::GetForBrowserContext(this);
}
content::BackgroundSyncController*
BrowserContextImpl::GetBackgroundSyncController() {
return BackgroundSyncControllerFactory::GetForBrowserContext(this);
}
content::BrowsingDataRemoverDelegate*
BrowserContextImpl::GetBrowsingDataRemoverDelegate() {
return BrowsingDataRemoverDelegateFactory::GetForBrowserContext(this);
}
download::InProgressDownloadManager*
BrowserContextImpl::RetriveInProgressDownloadManager() {
// Override this to provide a connection to the wake lock service.
auto* download_manager = new download::InProgressDownloadManager(
nullptr, path_,
path_.empty()
? nullptr
: GetDefaultStoragePartition(this)->GetProtoDatabaseProvider(),
base::BindRepeating(&IgnoreOriginSecurityCheck),
base::BindRepeating(&content::DownloadRequestUtils::IsURLSafe),
base::BindRepeating(&BindWakeLockProvider));
#if defined(OS_ANDROID)
download_manager->set_default_download_dir(GetDefaultDownloadDirectory());
#endif
return download_manager;
}
content::ContentIndexProvider* BrowserContextImpl::GetContentIndexProvider() {
return nullptr;
}
void BrowserContextImpl::CreateUserPrefService() {
auto pref_registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>();
RegisterPrefs(pref_registry.get());
PrefServiceFactory pref_service_factory;
if (IsOffTheRecord()) {
pref_service_factory.set_user_prefs(
base::MakeRefCounted<InMemoryPrefStore>());
} else {
pref_service_factory.set_user_prefs(base::MakeRefCounted<JsonPrefStore>(
path_.Append(FILE_PATH_LITERAL("Preferences"))));
}
{
// Creating the prefs service may require reading the preferences from disk.
base::ScopedAllowBlocking allow_io;
user_pref_service_ = pref_service_factory.Create(pref_registry);
}
// Note: UserPrefs::Set also ensures that the user_pref_service_ has not
// been set previously.
user_prefs::UserPrefs::Set(this, user_pref_service_.get());
}
void BrowserContextImpl::RegisterPrefs(
user_prefs::PrefRegistrySyncable* pref_registry) {
pref_registry->RegisterBooleanPref(prefs::kNoStatePrefetchEnabled, true);
pref_registry->RegisterBooleanPref(prefs::kUkmEnabled, false);
// This pref is used by captive_portal::CaptivePortalService (as well as other
// potential use cases in the future, as it is used for various purposes
// through //chrome).
pref_registry->RegisterBooleanPref(
embedder_support::kAlternateErrorPagesEnabled, false);
pref_registry->RegisterListPref(
site_isolation::prefs::kUserTriggeredIsolatedOrigins);
StatefulSSLHostStateDelegate::RegisterProfilePrefs(pref_registry);
HostContentSettingsMap::RegisterProfilePrefs(pref_registry);
safe_browsing::RegisterProfilePrefs(pref_registry);
language::LanguagePrefs::RegisterProfilePrefs(pref_registry);
translate::TranslatePrefs::RegisterProfilePrefs(pref_registry);
blocked_content::SafeBrowsingTriggeredPopupBlocker::RegisterProfilePrefs(
pref_registry);
payments::RegisterProfilePrefs(pref_registry);
pref_registry->RegisterBooleanPref(
::prefs::kOfferTranslateEnabled, true,
user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
#if defined(OS_ANDROID)
cdm::MediaDrmStorageImpl::RegisterProfilePrefs(pref_registry);
permissions::GeolocationPermissionContextAndroid::RegisterProfilePrefs(
pref_registry);
pref_registry->RegisterBooleanPref(
unified_consent::prefs::kUrlKeyedAnonymizedDataCollectionEnabled, false);
#endif
BrowserContextDependencyManager::GetInstance()
->RegisterProfilePrefsForServices(pref_registry);
}
class BrowserContextImpl::WebLayerVariationsClient
: public variations::VariationsClient {
public:
explicit WebLayerVariationsClient(content::BrowserContext* browser_context)
: browser_context_(browser_context) {}
~WebLayerVariationsClient() override = default;
bool IsOffTheRecord() const override {
return browser_context_->IsOffTheRecord();
}
variations::mojom::VariationsHeadersPtr GetVariationsHeaders()
const override {
return variations::VariationsIdsProvider::GetInstance()
->GetClientDataHeaders(IsSignedIn());
}
private:
// Signed-in state shouldn't control the set of variations for WebLayer,
// so this always returns true. This is particularly experiment for
// registering external experiment ids, which are registered assuming
// signed-in.
// TODO(sky): this is rather misleading, and needs to be resolved. Figure
// out right long term solution.
bool IsSignedIn() const { return true; }
content::BrowserContext* browser_context_;
};
variations::VariationsClient* BrowserContextImpl::GetVariationsClient() {
if (!weblayer_variations_client_) {
weblayer_variations_client_ =
std::make_unique<WebLayerVariationsClient>(this);
}
return weblayer_variations_client_.get();
}
} // namespace weblayer
| 36.865889 | 87 | 0.796679 | [
"object"
] |
814bc8eb19dd7d2cea90d319122a094d347de5a8 | 1,257 | cc | C++ | src/stack/rlc/am/packet/LteRlcAmPdu.cc | talal00/Simu5G | ffbdda3e4cd873b49d7022912fe25e39d1a503e8 | [
"Intel"
] | 58 | 2021-04-15T09:20:26.000Z | 2022-03-31T08:52:23.000Z | src/stack/rlc/am/packet/LteRlcAmPdu.cc | talal00/Simu5G | ffbdda3e4cd873b49d7022912fe25e39d1a503e8 | [
"Intel"
] | 34 | 2021-05-14T15:05:36.000Z | 2022-03-31T20:51:33.000Z | src/stack/rlc/am/packet/LteRlcAmPdu.cc | talal00/Simu5G | ffbdda3e4cd873b49d7022912fe25e39d1a503e8 | [
"Intel"
] | 30 | 2021-04-16T05:46:13.000Z | 2022-03-28T15:26:29.000Z | //
// Simu5G
//
// Authors: Giovanni Nardini, Giovanni Stea, Antonio Virdis (University of Pisa)
//
// This file is part of a software released under the license included in file
// "license.pdf". Please read LICENSE and README files before using it.
// The above files and the present reference are part of the software itself,
// and cannot be removed from it.
//
#include "stack/rlc/am/packet/LteRlcAmPdu.h"
void
LteRlcAmPdu::setBitmapArraySize(size_t size)
{
this->bitmap_.resize(size);
}
size_t
LteRlcAmPdu::getBitmapArraySize() const
{
return this->bitmap_.size();
}
bool
LteRlcAmPdu::getBitmap(size_t k) const
{
return this->bitmap_.at(k);
}
void
LteRlcAmPdu::setBitmap(size_t k, bool bitmap_)
{
this->bitmap_[k] = bitmap_;
}
void
LteRlcAmPdu::setBitmapVec(std::vector<bool> bitmap_vec)
{
this->bitmap_ = bitmap_vec;
}
std::vector<bool>
LteRlcAmPdu::getBitmapVec()
{
return this->bitmap_;
}
bool
LteRlcAmPdu::isWhole() const
{
return (firstSn == lastSn);
}
bool
LteRlcAmPdu::isFirst() const
{
return (firstSn == snoFragment);
}
bool
LteRlcAmPdu::isMiddle() const
{
return ((!isFirst()) && (!isLast()));
}
bool
LteRlcAmPdu::isLast() const
{
return (lastSn == snoFragment);
}
| 17.219178 | 80 | 0.687351 | [
"vector"
] |
814bcd33d33398d0984cfabe48c2b081ad2b5197 | 29,965 | cc | C++ | mash/browser/browser.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | mash/browser/browser.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | mash/browser/browser.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2016 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 "mash/browser/browser.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/timer/timer.h"
#include "components/mus/public/cpp/window.h"
#include "components/mus/public/cpp/window_tree_client.h"
#include "mash/browser/debug_view.h"
#include "mash/public/interfaces/launchable.mojom.h"
#include "mojo/public/c/system/main.h"
#include "services/navigation/public/cpp/view.h"
#include "services/navigation/public/cpp/view_delegate.h"
#include "services/navigation/public/cpp/view_observer.h"
#include "services/navigation/public/interfaces/view.mojom.h"
#include "services/shell/public/cpp/application_runner.h"
#include "services/shell/public/cpp/connector.h"
#include "services/shell/public/cpp/shell_client.h"
#include "services/tracing/public/cpp/tracing_impl.h"
#include "ui/aura/mus/mus_util.h"
#include "ui/base/models/menu_model.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/paint_throbber.h"
#include "ui/gfx/text_constants.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/background.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/menu/menu_model_adapter.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/controls/textfield/textfield_controller.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/mus/aura_init.h"
#include "ui/views/mus/window_manager_connection.h"
#include "ui/views/widget/widget_delegate.h"
#include "url/gurl.h"
namespace mash {
namespace browser {
void EnableButton(views::CustomButton* button, bool enabled) {
button->SetState(enabled ? views::Button::STATE_NORMAL
: views::Button::STATE_DISABLED);
}
class Tab;
class TabStripObserver {
public:
virtual void OnTabAdded(Tab* added) {}
virtual void OnTabRemoved(Tab* removed) {}
virtual void OnTabSelected(Tab* selected) {}
};
class Tab : public views::LabelButton,
public navigation::ViewObserver,
public TabStripObserver {
public:
class Background : public views::Background {
public:
explicit Background(Tab* tab) : tab_(tab) {}
~Background() override {}
private:
// views::Background:
void Paint(gfx::Canvas* canvas, views::View* view) const override {
DCHECK_EQ(view, tab_);
SkColor bg = tab_->selected() ? SK_ColorGRAY : SK_ColorLTGRAY;
gfx::Rect lb = view->GetLocalBounds();
canvas->FillRect(lb, bg);
if (!tab_->selected()) {
lb.set_y(lb.bottom() - 1);
lb.set_height(1);
canvas->FillRect(lb, SK_ColorGRAY);
}
}
Tab* tab_;
DISALLOW_COPY_AND_ASSIGN(Background);
};
Tab(std::unique_ptr<navigation::View> view,
views::ButtonListener* listener)
: views::LabelButton(listener, base::ASCIIToUTF16("Blank")),
view_(std::move(view)) {
view_->AddObserver(this);
set_background(new Background(this));
}
~Tab() override {
view_->RemoveObserver(this);
}
bool selected() const { return selected_; }
mus::Window* window() { return window_; }
void SetWindow(mus::Window* window) {
window_ = window;
window_->SetVisible(selected_);
view_->EmbedInWindow(window_);
}
navigation::View* view() { return view_.get(); }
private:
// views::View:
gfx::Size GetPreferredSize() const override {
gfx::Size ps = views::LabelButton::GetPreferredSize();
ps.set_width(180);
return ps;
}
// navigation::ViewObserver:
void NavigationStateChanged(navigation::View* view) override {
if (!view->title().empty())
SetText(view->title());
}
// TabStripObserver:
void OnTabSelected(Tab* selected) override {
selected_ = selected == this;
SetTextColor(views::Button::STATE_NORMAL,
selected_ ? SK_ColorWHITE : SK_ColorBLACK);
SetTextColor(views::Button::STATE_HOVERED,
selected_ ? SK_ColorWHITE : SK_ColorBLACK);
SetTextColor(views::Button::STATE_PRESSED,
selected_ ? SK_ColorWHITE : SK_ColorBLACK);
if (window_)
window_->SetVisible(selected_);
}
mus::Window* window_ = nullptr;
std::unique_ptr<navigation::View> view_;
bool selected_ = false;
DISALLOW_COPY_AND_ASSIGN(Tab);
};
class TabStrip : public views::View,
public views::ButtonListener {
public:
class Delegate {
public:
virtual void NewTab() = 0;
};
explicit TabStrip(Delegate* delegate)
: delegate_(delegate),
tab_container_(new views::View),
new_tab_button_(
new views::LabelButton(this, base::ASCIIToUTF16("+"))) {
views::BoxLayout* layout =
new views::BoxLayout(views::BoxLayout::kHorizontal, 5, 0, 0);
layout->set_main_axis_alignment(
views::BoxLayout::MAIN_AXIS_ALIGNMENT_START);
layout->set_cross_axis_alignment(
views::BoxLayout::CROSS_AXIS_ALIGNMENT_STRETCH);
layout->SetDefaultFlex(0);
SetLayoutManager(layout);
views::BoxLayout* tab_container_layout =
new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0, 0);
tab_container_layout->set_main_axis_alignment(
views::BoxLayout::MAIN_AXIS_ALIGNMENT_START);
tab_container_layout->set_cross_axis_alignment(
views::BoxLayout::CROSS_AXIS_ALIGNMENT_STRETCH);
tab_container_layout->SetDefaultFlex(0);
tab_container_->SetLayoutManager(tab_container_layout);
AddChildView(tab_container_);
layout->SetFlexForView(tab_container_, 1);
AddChildView(new_tab_button_);
}
~TabStrip() override {
for (auto* tab : tabs_)
RemoveObserver(tab);
}
void SetContainerWindow(mus::Window* container) {
DCHECK(!container_);
container_ = container;
for (auto* tab : tabs_) {
mus::Window* window = container_->window_tree()->NewWindow();
container_->AddChild(window);
tab->SetWindow(window);
}
}
void AddTab(std::unique_ptr<navigation::View> view) {
selected_index_ = static_cast<int>(tabs_.size());
Tab* tab = new Tab(std::move(view), this);
// We won't have a WindowTree until we're added to a view hierarchy.
if (container_) {
mus::Window* window = container_->window_tree()->NewWindow();
container_->AddChild(window);
tab->SetWindow(window);
}
AddObserver(tab);
tabs_.push_back(tab);
tab_container_->AddChildView(tab);
FOR_EACH_OBSERVER(TabStripObserver, observers_, OnTabAdded(tab));
SelectTab(tab);
}
void CloseTabForView(navigation::View* view) {
for (auto it = tabs_.begin(); it != tabs_.end(); ++it) {
Tab* tab = *it;
if (tab->view() == view) {
CloseTab(tab);
break;
}
}
}
void CloseTab(Tab* tab) {
auto it = std::find(tabs_.begin(), tabs_.end(), tab);
int tab_index = static_cast<int>(it - tabs_.begin());
if (tab_index < selected_index_)
--selected_index_;
DCHECK(it != tabs_.end());
tabs_.erase(it);
RemoveObserver(tab);
tab_container_->RemoveChildView(tab);
if (tab->selected()) {
int next_selected_index = selected_index_;
if (selected_index_ == static_cast<int>(tabs_.size()))
--next_selected_index;
if (next_selected_index >= 0)
SelectTab(tabs_[next_selected_index]);
}
Layout();
FOR_EACH_OBSERVER(TabStripObserver, observers_, OnTabRemoved(tab));
delete tab;
}
bool empty() const { return tabs_.empty(); }
void SelectTab(Tab* tab) {
auto it = std::find(tabs_.begin(), tabs_.end(), tab);
DCHECK(it != tabs_.end());
selected_index_ = it - tabs_.begin();
FOR_EACH_OBSERVER(TabStripObserver, observers_, OnTabSelected(tab));
}
Tab* selected_tab() {
return selected_index_ != -1 ? tabs_[selected_index_] : nullptr;
}
void AddObserver(TabStripObserver* observer) {
observers_.AddObserver(observer);
}
void RemoveObserver(TabStripObserver* observer) {
observers_.RemoveObserver(observer);
}
private:
// views::View:
void OnPaint(gfx::Canvas* canvas) override {
gfx::Rect lb = GetLocalBounds();
lb.set_y(lb.bottom() - 1);
lb.set_height(1);
canvas->FillRect(lb, SK_ColorGRAY);
}
// views::ButtonListener:
void ButtonPressed(views::Button* sender, const ui::Event& event) override {
auto it = std::find(tabs_.begin(), tabs_.end(), sender);
if (it != tabs_.end()) {
if (event.IsControlDown())
CloseTab(*it);
else
SelectTab(*it);
}
else if (sender == new_tab_button_ && delegate_)
delegate_->NewTab();
}
Delegate* delegate_;
views::View* tab_container_;
views::LabelButton* new_tab_button_;
std::vector<Tab*> tabs_;
int selected_index_ = -1;
base::ObserverList<TabStripObserver> observers_;
mus::Window* container_ = nullptr;
DISALLOW_COPY_AND_ASSIGN(TabStrip);
};
class NavMenuModel : public ui::MenuModel {
public:
class Delegate {
public:
virtual void NavigateToOffset(int offset) = 0;
};
NavMenuModel(const std::vector<navigation::NavigationListItem>& entries,
Delegate* delegate)
: navigation_delegate_(delegate), entries_(entries) {}
~NavMenuModel() override {}
private:
bool HasIcons() const override { return false; }
int GetItemCount() const override {
return static_cast<int>(entries_.size());
}
ui::MenuModel::ItemType GetTypeAt(int index) const override {
return ui::MenuModel::TYPE_COMMAND;
}
ui::MenuSeparatorType GetSeparatorTypeAt(int index) const override {
return ui::NORMAL_SEPARATOR;
}
int GetCommandIdAt(int index) const override {
return index;
}
base::string16 GetLabelAt(int index) const override {
return entries_[index].title;
}
base::string16 GetSublabelAt(int index) const override {
return base::string16();
}
base::string16 GetMinorTextAt(int index) const override {
return base::string16();
}
bool IsItemDynamicAt(int index) const override { return false; }
bool GetAcceleratorAt(int index,
ui::Accelerator* accelerator) const override {
return false;
}
bool IsItemCheckedAt(int index) const override { return false; }
int GetGroupIdAt(int index) const override { return -1; }
bool GetIconAt(int index, gfx::Image* icon) override { return false; }
ui::ButtonMenuItemModel* GetButtonMenuItemAt(int index) const override {
return nullptr;
}
bool IsEnabledAt(int index) const override { return true; }
bool IsVisibleAt(int index) const override { return true; }
ui::MenuModel* GetSubmenuModelAt(int index) const override { return nullptr; }
void HighlightChangedTo(int index) override {}
void ActivatedAt(int index) override {
ActivatedAt(index, 0);
}
void ActivatedAt(int index, int event_flags) override {
navigation_delegate_->NavigateToOffset(entries_[index].offset);
}
void SetMenuModelDelegate(ui::MenuModelDelegate* delegate) override {
delegate_ = delegate;
}
ui::MenuModelDelegate* GetMenuModelDelegate() const override {
return delegate_;
}
ui::MenuModelDelegate* delegate_ = nullptr;
Delegate* navigation_delegate_;
std::vector<navigation::NavigationListItem> entries_;
DISALLOW_COPY_AND_ASSIGN(NavMenuModel);
};
class NavButton : public views::LabelButton {
public:
enum class Type {
BACK,
FORWARD
};
class ModelProvider {
public:
virtual std::unique_ptr<ui::MenuModel> CreateMenuModel(Type type) = 0;
};
NavButton(Type type,
ModelProvider* model_provider,
views::ButtonListener* listener,
const base::string16& label)
: views::LabelButton(listener, label),
type_(type),
model_provider_(model_provider),
show_menu_factory_(this) {}
~NavButton() override {}
private:
// views::LabelButton overrides:
bool OnMousePressed(const ui::MouseEvent& event) override {
if (IsTriggerableEvent(event) && enabled() &&
HitTestPoint(event.location())) {
y_pos_on_lbuttondown_ = event.y();
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&NavButton::ShowMenu, show_menu_factory_.GetWeakPtr(),
ui::GetMenuSourceTypeForEvent(event)),
base::TimeDelta::FromMilliseconds(500));
}
return LabelButton::OnMousePressed(event);
}
bool OnMouseDragged(const ui::MouseEvent& event) override {
bool result = LabelButton::OnMouseDragged(event);
if (show_menu_factory_.HasWeakPtrs()) {
if (event.y() > y_pos_on_lbuttondown_ + GetHorizontalDragThreshold()) {
show_menu_factory_.InvalidateWeakPtrs();
ShowMenu(ui::GetMenuSourceTypeForEvent(event));
}
}
return result;
}
void OnMouseReleased(const ui::MouseEvent& event) override {
if (IsTriggerableEvent(event))
show_menu_factory_.InvalidateWeakPtrs();
LabelButton::OnMouseReleased(event);
}
void ShowMenu(ui::MenuSourceType source_type) {
gfx::Rect local = GetLocalBounds();
gfx::Point menu_position(local.origin());
menu_position.Offset(0, local.height() - 1);
View::ConvertPointToScreen(this, &menu_position);
model_ = model_provider_->CreateMenuModel(type_);
menu_model_adapter_.reset(new views::MenuModelAdapter(
model_.get(),
base::Bind(&NavButton::OnMenuClosed, base::Unretained(this))));
menu_model_adapter_->set_triggerable_event_flags(triggerable_event_flags());
menu_runner_.reset(new views::MenuRunner(
menu_model_adapter_->CreateMenu(),
views::MenuRunner::HAS_MNEMONICS | views::MenuRunner::ASYNC));
ignore_result(menu_runner_->RunMenuAt(
GetWidget(), nullptr, gfx::Rect(menu_position, gfx::Size(0, 0)),
views::MENU_ANCHOR_TOPLEFT, source_type));
}
void OnMenuClosed() {
SetMouseHandler(nullptr);
model_.reset();
menu_runner_.reset();
menu_model_adapter_.reset();
}
Type type_;
ModelProvider* model_provider_;
int y_pos_on_lbuttondown_ = 0;
std::unique_ptr<ui::MenuModel> model_;
std::unique_ptr<views::MenuModelAdapter> menu_model_adapter_;
std::unique_ptr<views::MenuRunner> menu_runner_;
base::WeakPtrFactory<NavButton> show_menu_factory_;
DISALLOW_COPY_AND_ASSIGN(NavButton);
};
class ProgressBar : public views::View {
public:
ProgressBar() {}
~ProgressBar() override {}
void SetProgress(double progress) {
progress_ = progress;
SchedulePaint();
}
private:
void OnPaint(gfx::Canvas* canvas) override {
gfx::Rect stroke_rect = GetLocalBounds();
stroke_rect.set_y(stroke_rect.bottom() - 1);
stroke_rect.set_height(1);
canvas->FillRect(stroke_rect, SK_ColorGRAY);
if (progress_ != 0.f) {
gfx::Rect progress_rect = GetLocalBounds();
progress_rect.set_width(progress_rect.width() * progress_);
canvas->FillRect(progress_rect, SK_ColorRED);
}
}
double progress_ = 0.f;
DISALLOW_COPY_AND_ASSIGN(ProgressBar);
};
class Throbber : public views::View {
public:
Throbber() : timer_(false, true), weak_factory_(this) {}
~Throbber() override {}
void Start() {
throbbing_ = true;
start_time_ = base::TimeTicks::Now();
SchedulePaint();
timer_.Start(
FROM_HERE, base::TimeDelta::FromMilliseconds(30),
base::Bind(&Throbber::SchedulePaint, weak_factory_.GetWeakPtr()));
}
void Stop() {
throbbing_ = false;
if (timer_.IsRunning())
timer_.Stop();
SchedulePaint();
}
private:
void OnPaint(gfx::Canvas* canvas) override {
if (!throbbing_)
return;
gfx::PaintThrobberSpinning(
canvas, GetLocalBounds(),
GetNativeTheme()->GetSystemColor(
ui::NativeTheme::kColorId_ThrobberSpinningColor),
base::TimeTicks::Now() - start_time_);
}
bool throbbing_ = false;
base::TimeTicks start_time_;
base::Timer timer_;
base::WeakPtrFactory<Throbber> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(Throbber);
};
class UI : public views::WidgetDelegateView,
public views::ButtonListener,
public views::TextfieldController,
public TabStrip::Delegate,
public TabStripObserver,
public navigation::ViewDelegate,
public navigation::ViewObserver,
public NavButton::ModelProvider,
public NavMenuModel::Delegate {
public:
enum class Type { WINDOW, POPUP };
UI(Browser* browser, Type type, std::unique_ptr<navigation::View> view)
: browser_(browser),
type_(type),
tab_strip_(new TabStrip(this)),
back_button_(new NavButton(NavButton::Type::BACK, this, this,
base::ASCIIToUTF16("Back"))),
forward_button_(new NavButton(NavButton::Type::FORWARD, this, this,
base::ASCIIToUTF16("Forward"))),
reload_button_(
new views::LabelButton(this, base::ASCIIToUTF16("Reload"))),
prompt_(new views::Textfield),
debug_button_(new views::LabelButton(this, base::ASCIIToUTF16("DV"))),
throbber_(new Throbber),
progress_bar_(new ProgressBar),
debug_view_(new DebugView) {
set_background(views::Background::CreateStandardPanelBackground());
prompt_->set_controller(this);
back_button_->set_request_focus_on_press(false);
forward_button_->set_request_focus_on_press(false);
reload_button_->set_request_focus_on_press(false);
AddChildView(tab_strip_);
AddChildView(back_button_);
AddChildView(forward_button_);
AddChildView(reload_button_);
AddChildView(prompt_);
AddChildView(debug_button_);
AddChildView(throbber_);
AddChildView(progress_bar_);
AddChildView(debug_view_);
tab_strip_->AddObserver(this);
tab_strip_->AddTab(std::move(view));
}
~UI() override {
browser_->RemoveWindow(GetWidget());
}
void NavigateTo(const GURL& url) {
selected_view()->NavigateToURL(url);
}
private:
// Overridden from views::WidgetDelegate:
views::View* GetContentsView() override { return this; }
base::string16 GetWindowTitle() const override {
// TODO(beng): use resources.
if (selected_view()->title().empty())
return base::ASCIIToUTF16("Browser");
base::string16 format = base::ASCIIToUTF16("%s - Browser");
base::ReplaceFirstSubstringAfterOffset(&format, 0, base::ASCIIToUTF16("%s"),
selected_view()->title());
return format;
}
bool CanResize() const override { return true; }
bool CanMaximize() const override { return true; }
bool CanMinimize() const override { return true; }
// views::ButtonListener:
void ButtonPressed(views::Button* sender, const ui::Event& event) override {
if (sender == back_button_) {
selected_view()->GoBack();
} else if (sender == forward_button_) {
selected_view()->GoForward();
} else if (sender == reload_button_) {
if (selected_view()->is_loading())
selected_view()->Stop();
else
selected_view()->Reload(false);
} else if (sender == debug_button_) {
ToggleDebugView();
}
}
// Overridden from views::View:
void Layout() override {
gfx::Rect local_bounds = GetLocalBounds();
gfx::Size ps = tab_strip_->GetPreferredSize();
tab_strip_->SetBoundsRect(
gfx::Rect(0, 5, local_bounds.width(), ps.height()));
gfx::Rect bounds = local_bounds;
bounds.set_y(tab_strip_->bounds().bottom());
bounds.Inset(5, 5);
ps = back_button_->GetPreferredSize();
back_button_->SetBoundsRect(
gfx::Rect(bounds.x(), bounds.y(), ps.width(), ps.height()));
ps = forward_button_->GetPreferredSize();
forward_button_->SetBoundsRect(gfx::Rect(back_button_->bounds().right() + 5,
bounds.y(), ps.width(),
ps.height()));
ps = reload_button_->GetPreferredSize();
reload_button_->SetBoundsRect(
gfx::Rect(forward_button_->bounds().right() + 5, bounds.y(), ps.width(),
ps.height()));
ps = prompt_->GetPreferredSize();
int throbber_size = ps.height();
gfx::Size debug_ps = debug_button_->GetPreferredSize();
int prompt_y =
bounds.y() + (reload_button_->bounds().height() - ps.height()) / 2;
int width =
bounds.width() - reload_button_->bounds().right() - throbber_size - 15 -
debug_ps.width();
prompt_->SetBoundsRect(gfx::Rect(reload_button_->bounds().right() + 5,
prompt_y, width, ps.height()));
debug_button_->SetBoundsRect(
gfx::Rect(prompt_->bounds().right() + 5,
prompt_->bounds().y(), debug_ps.width(), debug_ps.height()));
throbber_->SetBoundsRect(gfx::Rect(debug_button_->bounds().right() + 5,
prompt_->bounds().y(), throbber_size,
throbber_size));
gfx::Rect progress_bar_rect(local_bounds.x(),
back_button_->bounds().bottom() + 5,
local_bounds.width(), 2);
progress_bar_->SetBoundsRect(progress_bar_rect);
int debug_view_height = 0;
if (showing_debug_view_)
debug_view_height = debug_view_->GetPreferredSize().height();
debug_view_->SetBoundsRect(
gfx::Rect(local_bounds.x(), local_bounds.height() - debug_view_height,
local_bounds.width(), debug_view_height));
if (content_area_) {
int x = local_bounds.x();
int y = type_ == Type::POPUP ? 0 : progress_bar_->bounds().bottom();
gfx::Point offset(x, y);
ConvertPointToWidget(this, &offset);
int width = local_bounds.width();
int height = local_bounds.height() - y - debug_view_height;
content_area_->SetBounds(
gfx::Rect(offset.x(), offset.y(), width, height));
for (auto* child : content_area_->children())
child->SetBounds(gfx::Rect(0, 0, width, height));
}
}
void ViewHierarchyChanged(
const views::View::ViewHierarchyChangedDetails& details) override {
if (details.is_add && GetWidget() && !content_area_) {
mus::Window* window = aura::GetMusWindow(GetWidget()->GetNativeWindow());
content_area_ = window->window_tree()->NewWindow(nullptr);
content_area_->SetVisible(true);
window->AddChild(content_area_);
tab_strip_->SetContainerWindow(content_area_);
}
}
// Overridden from views::TextFieldController:
bool HandleKeyEvent(views::Textfield* sender,
const ui::KeyEvent& key_event) override {
if (key_event.type() == ui::ET_KEY_PRESSED &&
key_event.key_code() == ui::VKEY_RETURN)
selected_view()->NavigateToURL(GURL(prompt_->text()));
return false;
}
// TabStrip::Delegate:
void NewTab() override {
tab_strip_->AddTab(browser_->CreateView());
tab_strip_->selected_tab()->view()->NavigateToURL(GURL("about:blank"));
}
// TabStripObserver:
void OnTabAdded(Tab* added) override {
added->view()->AddObserver(this);
added->view()->set_delegate(this);
}
void OnTabSelected(Tab* selected) override {
debug_view_->set_view(selected->view());
prompt_->SetText(base::UTF8ToUTF16(selected->view()->url().spec()));
if (GetWidget())
GetWidget()->UpdateWindowTitle();
}
// navigation::ViewDelegate:
void ViewCreated(navigation::View* source,
std::unique_ptr<navigation::View> view,
bool is_popup,
const gfx::Rect& initial_rect,
bool user_gesture) override {
if (is_popup)
CreateNewWindow(std::move(view), initial_rect, is_popup);
else
tab_strip_->AddTab(std::move(view));
}
void Close(navigation::View* source) override {
tab_strip_->CloseTabForView(source);
if (tab_strip_->empty())
GetWidget()->Close();
}
void OpenURL(navigation::View* source,
navigation::mojom::OpenURLParamsPtr params) override {
switch (params->disposition) {
case navigation::mojom::WindowOpenDisposition::CURRENT_TAB:
selected_view()->NavigateToURL(params->url);
break;
case navigation::mojom::WindowOpenDisposition::NEW_FOREGROUND_TAB:
tab_strip_->AddTab(browser_->CreateView());
tab_strip_->selected_tab()->view()->NavigateToURL(params->url);
break;
case navigation::mojom::WindowOpenDisposition::NEW_POPUP:
case navigation::mojom::WindowOpenDisposition::NEW_WINDOW: {
std::unique_ptr<navigation::View> view = browser_->CreateView();
view->NavigateToURL(params->url);
CreateNewWindow(
std::move(view), gfx::Rect(),
params->disposition ==
navigation::mojom::WindowOpenDisposition::NEW_POPUP);
break;
}
default:
break;
}
}
// navigation::ViewObserver:
void LoadingStateChanged(navigation::View* view) override {
if (view->is_loading()) {
reload_button_->SetText(base::ASCIIToUTF16("Stop"));
throbber_->Start();
} else {
reload_button_->SetText(base::ASCIIToUTF16("Reload"));
throbber_->Stop();
progress_bar_->SetProgress(0.f);
}
}
void LoadProgressChanged(navigation::View* view, double progress) override {
progress_bar_->SetProgress(progress);
}
void NavigationStateChanged(navigation::View* view) override {
EnableButton(back_button_, view->can_go_back());
EnableButton(forward_button_, view->can_go_forward());
prompt_->SetText(base::UTF8ToUTF16(view->url().spec()));
GetWidget()->UpdateWindowTitle();
}
void HoverTargetURLChanged(navigation::View* view, const GURL& url) override {
if (url.is_valid())
prompt_->SetText(base::UTF8ToUTF16(url.spec()));
else
prompt_->SetText(base::UTF8ToUTF16(selected_view()->url().spec()));
}
// NavButton::ModelProvider:
std::unique_ptr<ui::MenuModel> CreateMenuModel(
NavButton::Type type) override {
std::vector<navigation::NavigationListItem> entries;
if (type == NavButton::Type::BACK) {
selected_view()->GetBackMenuItems(&entries);
} else {
selected_view()->GetForwardMenuItems(&entries);
}
return base::WrapUnique(new NavMenuModel(entries, this));
}
// NavMenuModel::Delegate:
void NavigateToOffset(int offset) override {
selected_view()->NavigateToOffset(offset);
}
navigation::View* selected_view() {
return const_cast<navigation::View*>(
static_cast<const UI*>(this)->selected_view());
}
const navigation::View* selected_view() const {
return tab_strip_->selected_tab()->view();
}
void CreateNewWindow(std::unique_ptr<navigation::View> view,
const gfx::Rect& initial_bounds,
bool is_popup) {
gfx::Rect bounds = initial_bounds;
if (bounds.IsEmpty())
bounds = gfx::Rect(10, 10, 400, 300);
views::Widget* window = views::Widget::CreateWindowWithContextAndBounds(
new UI(browser_, is_popup ? UI::Type::POPUP : UI::Type::WINDOW,
std::move(view)),
nullptr, bounds);
window->Show();
browser_->AddWindow(window);
}
void ToggleDebugView() {
showing_debug_view_ = !showing_debug_view_;
Layout();
}
Browser* browser_;
Type type_;
TabStrip* tab_strip_;
views::LabelButton* back_button_;
views::LabelButton* forward_button_;
views::LabelButton* reload_button_;
views::Textfield* prompt_;
views::LabelButton* debug_button_;
Throbber* throbber_;
ProgressBar* progress_bar_;
mus::Window* content_area_ = nullptr;
DebugView* debug_view_;
bool showing_debug_view_ = false;
DISALLOW_COPY_AND_ASSIGN(UI);
};
Browser::Browser() {}
Browser::~Browser() {}
void Browser::AddWindow(views::Widget* window) {
windows_.push_back(window);
}
void Browser::RemoveWindow(views::Widget* window) {
auto it = std::find(windows_.begin(), windows_.end(), window);
DCHECK(it != windows_.end());
windows_.erase(it);
if (windows_.empty())
base::MessageLoop::current()->QuitWhenIdle();
}
std::unique_ptr<navigation::View> Browser::CreateView() {
navigation::mojom::ViewFactoryPtr factory;
connector_->ConnectToInterface("exe:navigation", &factory);
return base::WrapUnique(new navigation::View(std::move(factory)));
}
void Browser::Initialize(shell::Connector* connector,
const shell::Identity& identity,
uint32_t id) {
connector_ = connector;
tracing_.Initialize(connector, identity.name());
aura_init_.reset(new views::AuraInit(connector, "views_mus_resources.pak"));
window_manager_connection_ =
views::WindowManagerConnection::Create(connector, identity);
}
bool Browser::AcceptConnection(shell::Connection* connection) {
connection->AddInterface<mojom::Launchable>(this);
return true;
}
void Browser::Launch(uint32_t what, mojom::LaunchMode how) {
bool reuse =
how == mojom::LaunchMode::REUSE || how == mojom::LaunchMode::DEFAULT;
if (reuse && !windows_.empty()) {
windows_.back()->Activate();
return;
}
UI* ui = new UI(this, UI::Type::WINDOW, CreateView());
views::Widget* window = views::Widget::CreateWindowWithContextAndBounds(
ui, nullptr, gfx::Rect(10, 10, 1024, 600));
ui->NavigateTo(GURL("http://www.google.com/"));
window->Show();
AddWindow(window);
}
void Browser::Create(shell::Connection* connection,
mojom::LaunchableRequest request) {
bindings_.AddBinding(this, std::move(request));
}
} // namespace browser
} // namespace mash
| 33.037486 | 80 | 0.668046 | [
"vector"
] |
814be8258e46b187215270fb93de4303204f3523 | 973 | hpp | C++ | libs/image/impl/include/sge/image/impl/view/sub_impl.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/image/impl/include/sge/image/impl/view/sub_impl.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/image/impl/include/sge/image/impl/view/sub_impl.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_IMAGE_IMPL_VIEW_SUB_IMPL_HPP_INCLUDED
#define SGE_IMAGE_IMPL_VIEW_SUB_IMPL_HPP_INCLUDED
#include <sge/image/box_fwd.hpp>
#include <sge/image/impl/view/sub_any.hpp>
#include <sge/image/view/const_object_fwd.hpp>
#include <sge/image/view/object_fwd.hpp>
#include <sge/image/view/sub.hpp>
template <typename Tag>
sge::image::view::object<Tag>
sge::image::view::sub(sge::image::view::object<Tag> const &_view, sge::image::box<Tag> const &_box)
{
return sge::image::impl::view::sub_any(_view, _box);
}
template <typename Tag>
sge::image::view::const_object<Tag> sge::image::view::sub(
sge::image::view::const_object<Tag> const &_view, sge::image::box<Tag> const &_box)
{
return sge::image::impl::view::sub_any(_view, _box);
}
#endif
| 32.433333 | 99 | 0.726619 | [
"object"
] |
814d7493fcc4ae9035b16fbc372f4264d90f38c4 | 3,331 | cc | C++ | tensorflow_text/core/kernels/sentence_breaking_kernels_v2.cc | nluehr/text | 1fd2039412faf537473e31f25df7ebe972475018 | [
"Apache-2.0"
] | 2 | 2021-10-31T03:30:37.000Z | 2022-02-16T06:59:02.000Z | tensorflow_text/core/kernels/sentence_breaking_kernels_v2.cc | nluehr/text | 1fd2039412faf537473e31f25df7ebe972475018 | [
"Apache-2.0"
] | null | null | null | tensorflow_text/core/kernels/sentence_breaking_kernels_v2.cc | nluehr/text | 1fd2039412faf537473e31f25df7ebe972475018 | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 TF.Text 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 <string>
#include <vector>
#include "absl/strings/str_cat.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow_text/core/kernels/sentence_fragmenter_v2.h"
using ::tensorflow::tstring;
namespace tensorflow {
namespace text {
class SentenceFragmentsOpV2 : public OpKernel {
public:
explicit SentenceFragmentsOpV2(OpKernelConstruction* context)
: OpKernel(context) {}
void Compute(::tensorflow::OpKernelContext* context) override {
const Tensor* document_tensor;
OP_REQUIRES_OK(context, context->input("doc", &document_tensor));
const auto& document = document_tensor->vec<tstring>();
std::vector<int64> fragment_start;
std::vector<int64> fragment_end;
std::vector<int64> fragment_properties;
std::vector<int64> terminal_punc_token;
std::vector<int64> output_row_lengths;
// Iterate through all the documents and find fragments.
for (int i = 0; i < document.size(); ++i) {
// Find fragments.
SentenceFragmenterV2 fragmenter(document(i));
std::vector<SentenceFragment> frags;
OP_REQUIRES_OK(context, fragmenter.FindFragments(&frags));
for (const auto& f : frags) {
fragment_start.push_back(f.start);
fragment_end.push_back(f.limit);
fragment_properties.push_back(f.properties);
terminal_punc_token.push_back(f.terminal_punc_token);
}
output_row_lengths.push_back(frags.size());
}
#define DECLARE_ALLOCATE_AND_FILL_OUTPUT_TENSOR(name, dtype) \
int64 name##_size = name.size(); \
Tensor* name##_tensor = nullptr; \
OP_REQUIRES_OK(context, \
context->allocate_output(#name, TensorShape({name##_size}), \
&name##_tensor)); \
auto name##_data = name##_tensor->flat<dtype>().data(); \
memcpy(name##_data, name.data(), name##_size * sizeof(dtype));
DECLARE_ALLOCATE_AND_FILL_OUTPUT_TENSOR(fragment_start, int64);
DECLARE_ALLOCATE_AND_FILL_OUTPUT_TENSOR(fragment_end, int64);
DECLARE_ALLOCATE_AND_FILL_OUTPUT_TENSOR(fragment_properties, int64);
DECLARE_ALLOCATE_AND_FILL_OUTPUT_TENSOR(terminal_punc_token, int64);
DECLARE_ALLOCATE_AND_FILL_OUTPUT_TENSOR(output_row_lengths, int64);
#undef DECLARE_ALLOCATE_AND_FILL_OUTPUT_TENSOR
}
};
REGISTER_KERNEL_BUILDER(Name("SentenceFragmentsV2").Device(DEVICE_CPU),
SentenceFragmentsOpV2);
} // namespace text
} // namespace tensorflow
| 38.732558 | 78 | 0.683278 | [
"vector"
] |
814f07dae8625fa4971c2e365ee496f0d0601349 | 638 | hpp | C++ | src/Interface/WinAPI/StdAfx.hpp | 1nUrF4c3/Project-X | a7203d0f21a39a6df5904399bba9e88aae56a313 | [
"MIT"
] | 8 | 2019-11-04T12:43:19.000Z | 2022-03-10T17:47:15.000Z | src/Interface/WinAPI/StdAfx.hpp | SteepCheat/Project-X | a7203d0f21a39a6df5904399bba9e88aae56a313 | [
"MIT"
] | 2 | 2020-03-31T04:18:34.000Z | 2022-03-23T06:19:46.000Z | src/Interface/WinAPI/StdAfx.hpp | SteepCheat/Project-X | a7203d0f21a39a6df5904399bba9e88aae56a313 | [
"MIT"
] | 5 | 2021-12-04T18:51:30.000Z | 2022-03-10T17:51:24.000Z | #pragma once
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#pragma warning(disable : 4995)
#include <Windows.h>
#include <windowsx.h>
#include <Psapi.h>
#include <CommCtrl.h>
#include <commdlg.h>
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
#include <strsafe.h>
#include <stdint.h>
#include <wchar.h>
#include <vector>
#include <string>
#include <map>
#pragma comment(linker, \
"\"/manifestdependency:type='Win32' "\
"name='Microsoft.Windows.Common-Controls' "\
"version='6.0.0.0' "\
"processorArchitecture='*' "\
"publicKeyToken='6595b64144ccf1df' "\
"language='*'\"") | 19.333333 | 46 | 0.700627 | [
"vector"
] |
8150df60815dcf319accf6996e038978852d7c33 | 1,526 | hh | C++ | include/NeuGeometryMessenger.hh | kwierman/Argon40Conversion | 3c94209cd8036f846f7e3903bb41d35bcd85c2c0 | [
"MIT"
] | null | null | null | include/NeuGeometryMessenger.hh | kwierman/Argon40Conversion | 3c94209cd8036f846f7e3903bb41d35bcd85c2c0 | [
"MIT"
] | null | null | null | include/NeuGeometryMessenger.hh | kwierman/Argon40Conversion | 3c94209cd8036f846f7e3903bb41d35bcd85c2c0 | [
"MIT"
] | null | null | null |
#ifndef NeuGeometryMessenger_hh_
#define NeuGeometryMessenger_hh_
#include "globals.hh"
#include "G4UImessenger.hh"
#include "G4UIdirectory.hh"
#include "G4UIcmdWithADoubleAndUnit.hh"
#include "G4UIcmdWithoutParameter.hh"
namespace NeuFlux
{
class NeuWorldGeometry;
/*!
\class NeuGeometryMessenger
\ingroup NeuFlux
\brief Messenger Class for the geometry
\note Defaults to a small Geometry
\author Kevin Wierman
\version 1.0
\date Oct 1, 2013
Contact: kwierman@email.unc.edu
*/
class NeuGeometryMessenger : public G4UImessenger
{
public:
NeuGeometryMessenger(NeuWorldGeometry*);
virtual ~ NeuGeometryMessenger();
virtual void SetNewValue(G4UIcommand *, G4String);
private:
NeuWorldGeometry* fGeometry;
G4UIdirectory* fNeuFluxDir;
G4UIdirectory* fGeometryDir;
G4UIcmdWithoutParameter* fDumpGeometry;
G4UIdirectory* fWorldDir;
G4UIcmdWithADoubleAndUnit* fWorldX;
G4UIcmdWithADoubleAndUnit* fWorldY;
G4UIcmdWithADoubleAndUnit* fWorldZ;
G4UIdirectory* fRockDir;
G4UIcmdWithADoubleAndUnit* fRockX;
G4UIcmdWithADoubleAndUnit* fRockY;
G4UIcmdWithADoubleAndUnit* fRockZ;
G4UIdirectory* fConcreteDir;
G4UIcmdWithADoubleAndUnit* fConcreteX;
G4UIcmdWithADoubleAndUnit* fConcreteY;
G4UIcmdWithADoubleAndUnit* fConcreteZ;
G4UIdirectory* fDetectorDir;
G4UIcmdWithADoubleAndUnit* fDetectorX;
G4UIcmdWithADoubleAndUnit* fDetectorY;
G4UIcmdWithADoubleAndUnit* fDetectorZ;
};
}
#endif
| 22.115942 | 52 | 0.757536 | [
"geometry"
] |
81530fa820e4d004b032fbbdd21d4d959ef2c2a0 | 2,421 | cc | C++ | components/mus/ws/window_coordinate_conversions.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | components/mus/ws/window_coordinate_conversions.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | components/mus/ws/window_coordinate_conversions.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // 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 "components/mus/ws/window_coordinate_conversions.h"
#include "components/mus/ws/server_window.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/geometry/vector2d_f.h"
namespace mus {
namespace ws {
namespace {
gfx::Vector2dF CalculateOffsetToAncestor(const ServerWindow* window,
const ServerWindow* ancestor) {
DCHECK(ancestor->Contains(window));
gfx::Vector2d result;
for (const ServerWindow* v = window; v != ancestor; v = v->parent())
result += v->bounds().OffsetFromOrigin();
return gfx::Vector2dF(result.x(), result.y());
}
} // namespace
gfx::Point ConvertPointBetweenWindows(const ServerWindow* from,
const ServerWindow* to,
const gfx::Point& point) {
return gfx::ToFlooredPoint(
ConvertPointFBetweenWindows(from, to, gfx::PointF(point.x(), point.y())));
}
gfx::PointF ConvertPointFBetweenWindows(const ServerWindow* from,
const ServerWindow* to,
const gfx::PointF& point) {
DCHECK(from);
DCHECK(to);
if (from == to)
return point;
if (from->Contains(to)) {
const gfx::Vector2dF offset(CalculateOffsetToAncestor(to, from));
return point - offset;
}
DCHECK(to->Contains(from));
const gfx::Vector2dF offset(CalculateOffsetToAncestor(from, to));
return point + offset;
}
gfx::Rect ConvertRectBetweenWindows(const ServerWindow* from,
const ServerWindow* to,
const gfx::Rect& rect) {
DCHECK(from);
DCHECK(to);
if (from == to)
return rect;
const gfx::Point top_left(
ConvertPointBetweenWindows(from, to, rect.origin()));
const gfx::Point bottom_right(gfx::ToCeiledPoint(ConvertPointFBetweenWindows(
from, to, gfx::PointF(rect.right(), rect.bottom()))));
return gfx::Rect(top_left.x(), top_left.y(), bottom_right.x() - top_left.x(),
bottom_right.y() - top_left.y());
}
} // namespace ws
} // namespace mus
| 32.28 | 80 | 0.632796 | [
"geometry"
] |
8156d02714aa7a539e93000d15d1412b722424f2 | 3,486 | cpp | C++ | Utilities/Poco/XML/src/NamePool.cpp | nocnokneo/MITK | 2902dcaed2ebf83b08c29d73608e8c70ead9e602 | [
"BSD-3-Clause"
] | null | null | null | Utilities/Poco/XML/src/NamePool.cpp | nocnokneo/MITK | 2902dcaed2ebf83b08c29d73608e8c70ead9e602 | [
"BSD-3-Clause"
] | null | null | null | Utilities/Poco/XML/src/NamePool.cpp | nocnokneo/MITK | 2902dcaed2ebf83b08c29d73608e8c70ead9e602 | [
"BSD-3-Clause"
] | null | null | null | //
// NamePool.cpp
//
// $Id$
//
// Library: XML
// Package: XML
// Module: NamePool
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/XML/NamePool.h"
#include "Poco/Exception.h"
namespace Poco {
namespace XML {
class NamePoolItem
{
public:
NamePoolItem(): _used(false)
{
}
~NamePoolItem()
{
}
bool set(const XMLString& qname, const XMLString& namespaceURI, const XMLString& localName)
{
if (!_used)
{
_name.assign(qname, namespaceURI, localName);
_used = true;
return true;
}
else return _name.equals(qname, namespaceURI, localName);
}
const Name& get() const
{
return _name;
}
bool used() const
{
return _used;
}
private:
Name _name;
bool _used;
};
NamePool::NamePool(unsigned long size):
_size(size),
_rc(1)
{
poco_assert (size > 1);
_pItems = new NamePoolItem[size];
}
NamePool::~NamePool()
{
delete [] _pItems;
}
void NamePool::duplicate()
{
++_rc;
}
void NamePool::release()
{
if (--_rc == 0)
delete this;
}
const Name& NamePool::insert(const XMLString& qname, const XMLString& namespaceURI, const XMLString& localName)
{
unsigned long i = 0;
unsigned long n = hash(qname, namespaceURI, localName) % _size;
while (!_pItems[n].set(qname, namespaceURI, localName) && i++ < _size)
n = (n + 1) % _size;
if (i > _size) throw Poco::PoolOverflowException("XML name pool");
return _pItems[n].get();
}
const Name& NamePool::insert(const Name& name)
{
return insert(name.qname(), name.namespaceURI(), name.localName());
}
unsigned long NamePool::hash(const XMLString& qname, const XMLString& namespaceURI, const XMLString& localName)
{
unsigned long h = 0;
XMLString::const_iterator it = qname.begin();
XMLString::const_iterator end = qname.end();
while (it != end) h = (h << 5) + h + (unsigned long) *it++;
it = namespaceURI.begin();
end = namespaceURI.end();
while (it != end) h = (h << 5) + h + (unsigned long) *it++;
it = localName.begin();
end = localName.end();
while (it != end) h = (h << 5) + h + (unsigned long) *it++;
return h;
}
} } // namespace Poco::XML
| 23.395973 | 111 | 0.697935 | [
"object"
] |
815de466aaffbd35078ad9ff2fa0e13145facce7 | 2,587 | hpp | C++ | slice.hpp | lukasz-wiecaszek/h264iframedecoder | 184f97a454a0b449be3a4768e645b3690436ef97 | [
"IJG"
] | null | null | null | slice.hpp | lukasz-wiecaszek/h264iframedecoder | 184f97a454a0b449be3a4768e645b3690436ef97 | [
"IJG"
] | null | null | null | slice.hpp | lukasz-wiecaszek/h264iframedecoder | 184f97a454a0b449be3a4768e645b3690436ef97 | [
"IJG"
] | null | null | null | /**
* @file slice.hpp
*
* Definition of H.264 (ISO/IEC 14496-10) slice structure.
*
* @author Lukasz Wiecaszek <lukasz.wiecaszek@gmail.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*/
#ifndef _SLICE_HPP_
#define _SLICE_HPP_
/*===========================================================================*\
* system header files
\*===========================================================================*/
/*===========================================================================*\
* project header files
\*===========================================================================*/
/*===========================================================================*\
* preprocessor #define constants and macros
\*===========================================================================*/
/*===========================================================================*\
* global type definitions
\*===========================================================================*/
namespace ymn
{
namespace h264
{
class slice
{
public:
explicit slice();
~slice();
std::string to_string() const
{
std::ostringstream stream;
stream << std::endl;
return stream.str();
}
operator std::string () const
{
return to_string();
}
private:
};
} /* end of namespace h264 */
} /* end of namespace ymn */
/*===========================================================================*\
* inline function/variable definitions
\*===========================================================================*/
namespace ymn
{
namespace h264
{
} /* end of namespace h264 */
} /* end of namespace ymn */
/*===========================================================================*\
* global object declarations
\*===========================================================================*/
namespace ymn
{
} /* end of namespace ymn */
/*===========================================================================*\
* function forward declarations
\*===========================================================================*/
namespace ymn
{
} /* end of namespace ymn */
#endif /* _SLICE_HPP_ */
| 27.231579 | 79 | 0.387708 | [
"object"
] |
8160766f7cb6509c249f23665392b8414324fc56 | 2,503 | hpp | C++ | Opal Prospect/OpenGL/Buffers/VertexUVIndexVAO.hpp | swbengs/OpalProspect | 5f77dd07c1bb4197673589ac3f42546a4d0329b3 | [
"MIT"
] | 2 | 2018-06-06T02:01:08.000Z | 2020-07-25T18:10:32.000Z | Opal Prospect/OpenGL/Buffers/VertexUVIndexVAO.hpp | swbengs/OpalProspect | 5f77dd07c1bb4197673589ac3f42546a4d0329b3 | [
"MIT"
] | 10 | 2018-07-27T01:56:45.000Z | 2019-02-23T01:49:36.000Z | Opal Prospect/OpenGL/Buffers/VertexUVIndexVAO.hpp | swbengs/OpalProspect | 5f77dd07c1bb4197673589ac3f42546a4d0329b3 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include "FloatVBO.hpp"
#include "IntVBO.hpp"
#include "VAO.hpp"
/*
MIT License
Copyright (c) 2018 Scott Bengs
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.
*/
/*
This class pairs up float buffers, int buffers, and a VAO class for easy use.
*/
class VertexUVIndexVAO
{
public:
void bind() const;
void unBind() const;
void bindVertex() const;
void bindUV() const;
void bindIndex() const;
void bufferVertex(size_t start, const std::vector<float> &vector);
void bufferUV(size_t start, const std::vector<float> &vector);
void bufferIndex(size_t start, const std::vector<unsigned int> &vector);
void create();
void destroy();
//gets
unsigned int getID() const;
int getObjectCount() const;
int getObjectVertexSize() const;
int getObjectUVSize() const;
int getObjectIndexSize() const;
//sets
void setObjectCount(int count); //so 10 objects means enter 10
void setObjectVertexSize(int size); //vertex are floats so say 96 floats for a box
void setObjectUVSize(int size); //same as vertex but different number
void setObjectIndexSize(int size);
private:
VAO vao;
FloatVBO vertex; //xy
FloatVBO uv; //rgba
IntVBO index; //indices
int object_count; //how many to store
int object_vertex_size; //size of a single object's vertex data
int object_uv_size; //size of a single object's uv. also known as texture coordinates
int object_index_size; //size of a single object's index
};
| 33.373333 | 89 | 0.741111 | [
"object",
"vector"
] |
8162932b68a1451cc57421071320f2f71452ac59 | 431 | cpp | C++ | src/object/component.cpp | Robzz/troll_engine | 24c9a944e41afad8c7b03921395da116575cb60e | [
"MIT"
] | null | null | null | src/object/component.cpp | Robzz/troll_engine | 24c9a944e41afad8c7b03921395da116575cb60e | [
"MIT"
] | null | null | null | src/object/component.cpp | Robzz/troll_engine | 24c9a944e41afad8c7b03921395da116575cb60e | [
"MIT"
] | null | null | null | #include "object/component.h"
namespace Engine {
ComponentBase::ComponentBase() { }
ComponentBase::~ComponentBase() { }
ComponentBase::ComponentBase(ComponentBase const& other) { }
ComponentBase::ComponentBase(ComponentBase&& other) { }
ComponentBase& ComponentBase::operator=(ComponentBase const& other) { return *this; }
ComponentBase& ComponentBase::operator=(ComponentBase&& other) { return *this; }
} // namespace Engine
| 28.733333 | 85 | 0.758701 | [
"object"
] |
8165c1ac68209aa27cfb525a74dbeaeb9b6361a0 | 30,633 | cc | C++ | third_party/boringssl-with-bazel/src/crypto/dh/dh_test.cc | miyachu/grpc | a06ea3c3162c10ff90a1578bf82bbbff95dc799d | [
"BSD-3-Clause"
] | 91 | 2018-11-24T05:33:58.000Z | 2022-03-16T05:58:05.000Z | third_party/boringssl-with-bazel/src/crypto/dh/dh_test.cc | miyachu/grpc | a06ea3c3162c10ff90a1578bf82bbbff95dc799d | [
"BSD-3-Clause"
] | 11 | 2019-06-02T23:50:17.000Z | 2022-02-04T23:58:56.000Z | third_party/boringssl-with-bazel/src/crypto/dh/dh_test.cc | miyachu/grpc | a06ea3c3162c10ff90a1578bf82bbbff95dc799d | [
"BSD-3-Clause"
] | 18 | 2018-11-24T10:35:29.000Z | 2021-04-22T07:22:10.000Z | /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 AUTHOR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.] */
#include <openssl/dh.h>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <openssl/bn.h>
#include <openssl/bytestring.h>
#include <openssl/crypto.h>
#include <openssl/dh.h>
#include <openssl/err.h>
#include <openssl/mem.h>
#include "../internal.h"
static bool RunBasicTests();
static bool RunRFC5114Tests();
static bool TestBadY();
static bool TestASN1();
static bool TestRFC3526();
int main() {
CRYPTO_library_init();
if (!RunBasicTests() ||
!RunRFC5114Tests() ||
!TestBadY() ||
!TestASN1() ||
!TestRFC3526()) {
ERR_print_errors_fp(stderr);
return 1;
}
printf("PASS\n");
return 0;
}
static int GenerateCallback(int p, int n, BN_GENCB *arg) {
char c = '*';
if (p == 0) {
c = '.';
} else if (p == 1) {
c = '+';
} else if (p == 2) {
c = '*';
} else if (p == 3) {
c = '\n';
}
FILE *out = reinterpret_cast<FILE*>(arg->arg);
fputc(c, out);
fflush(out);
return 1;
}
static bool RunBasicTests() {
BN_GENCB cb;
BN_GENCB_set(&cb, &GenerateCallback, stdout);
bssl::UniquePtr<DH> a(DH_new());
if (!a || !DH_generate_parameters_ex(a.get(), 64, DH_GENERATOR_5, &cb)) {
return false;
}
int check_result;
if (!DH_check(a.get(), &check_result)) {
return false;
}
if (check_result & DH_CHECK_P_NOT_PRIME) {
printf("p value is not prime\n");
}
if (check_result & DH_CHECK_P_NOT_SAFE_PRIME) {
printf("p value is not a safe prime\n");
}
if (check_result & DH_CHECK_UNABLE_TO_CHECK_GENERATOR) {
printf("unable to check the generator value\n");
}
if (check_result & DH_CHECK_NOT_SUITABLE_GENERATOR) {
printf("the g value is not a generator\n");
}
printf("\np = ");
BN_print_fp(stdout, a->p);
printf("\ng = ");
BN_print_fp(stdout, a->g);
printf("\n");
bssl::UniquePtr<DH> b(DH_new());
if (!b) {
return false;
}
b->p = BN_dup(a->p);
b->g = BN_dup(a->g);
if (b->p == nullptr || b->g == nullptr) {
return false;
}
if (!DH_generate_key(a.get())) {
return false;
}
printf("pri1 = ");
BN_print_fp(stdout, a->priv_key);
printf("\npub1 = ");
BN_print_fp(stdout, a->pub_key);
printf("\n");
if (!DH_generate_key(b.get())) {
return false;
}
printf("pri2 = ");
BN_print_fp(stdout, b->priv_key);
printf("\npub2 = ");
BN_print_fp(stdout, b->pub_key);
printf("\n");
std::vector<uint8_t> key1(DH_size(a.get()));
int ret = DH_compute_key(key1.data(), b->pub_key, a.get());
if (ret < 0) {
return false;
}
key1.resize(ret);
printf("key1 = ");
for (size_t i = 0; i < key1.size(); i++) {
printf("%02x", key1[i]);
}
printf("\n");
std::vector<uint8_t> key2(DH_size(b.get()));
ret = DH_compute_key(key2.data(), a->pub_key, b.get());
if (ret < 0) {
return false;
}
key2.resize(ret);
printf("key2 = ");
for (size_t i = 0; i < key2.size(); i++) {
printf("%02x", key2[i]);
}
printf("\n");
if (key1.size() < 4 || key1 != key2) {
fprintf(stderr, "Error in DH routines\n");
return false;
}
return true;
}
/* Test data from RFC 5114 */
static const uint8_t kDHTest1024_160_xA[] = {
0xB9, 0xA3, 0xB3, 0xAE, 0x8F, 0xEF, 0xC1, 0xA2, 0x93, 0x04,
0x96, 0x50, 0x70, 0x86, 0xF8, 0x45, 0x5D, 0x48, 0x94, 0x3E};
static const uint8_t kDHTest1024_160_yA[] = {
0x2A, 0x85, 0x3B, 0x3D, 0x92, 0x19, 0x75, 0x01, 0xB9, 0x01, 0x5B, 0x2D,
0xEB, 0x3E, 0xD8, 0x4F, 0x5E, 0x02, 0x1D, 0xCC, 0x3E, 0x52, 0xF1, 0x09,
0xD3, 0x27, 0x3D, 0x2B, 0x75, 0x21, 0x28, 0x1C, 0xBA, 0xBE, 0x0E, 0x76,
0xFF, 0x57, 0x27, 0xFA, 0x8A, 0xCC, 0xE2, 0x69, 0x56, 0xBA, 0x9A, 0x1F,
0xCA, 0x26, 0xF2, 0x02, 0x28, 0xD8, 0x69, 0x3F, 0xEB, 0x10, 0x84, 0x1D,
0x84, 0xA7, 0x36, 0x00, 0x54, 0xEC, 0xE5, 0xA7, 0xF5, 0xB7, 0xA6, 0x1A,
0xD3, 0xDF, 0xB3, 0xC6, 0x0D, 0x2E, 0x43, 0x10, 0x6D, 0x87, 0x27, 0xDA,
0x37, 0xDF, 0x9C, 0xCE, 0x95, 0xB4, 0x78, 0x75, 0x5D, 0x06, 0xBC, 0xEA,
0x8F, 0x9D, 0x45, 0x96, 0x5F, 0x75, 0xA5, 0xF3, 0xD1, 0xDF, 0x37, 0x01,
0x16, 0x5F, 0xC9, 0xE5, 0x0C, 0x42, 0x79, 0xCE, 0xB0, 0x7F, 0x98, 0x95,
0x40, 0xAE, 0x96, 0xD5, 0xD8, 0x8E, 0xD7, 0x76};
static const uint8_t kDHTest1024_160_xB[] = {
0x93, 0x92, 0xC9, 0xF9, 0xEB, 0x6A, 0x7A, 0x6A, 0x90, 0x22,
0xF7, 0xD8, 0x3E, 0x72, 0x23, 0xC6, 0x83, 0x5B, 0xBD, 0xDA};
static const uint8_t kDHTest1024_160_yB[] = {
0x71, 0x7A, 0x6C, 0xB0, 0x53, 0x37, 0x1F, 0xF4, 0xA3, 0xB9, 0x32, 0x94,
0x1C, 0x1E, 0x56, 0x63, 0xF8, 0x61, 0xA1, 0xD6, 0xAD, 0x34, 0xAE, 0x66,
0x57, 0x6D, 0xFB, 0x98, 0xF6, 0xC6, 0xCB, 0xF9, 0xDD, 0xD5, 0xA5, 0x6C,
0x78, 0x33, 0xF6, 0xBC, 0xFD, 0xFF, 0x09, 0x55, 0x82, 0xAD, 0x86, 0x8E,
0x44, 0x0E, 0x8D, 0x09, 0xFD, 0x76, 0x9E, 0x3C, 0xEC, 0xCD, 0xC3, 0xD3,
0xB1, 0xE4, 0xCF, 0xA0, 0x57, 0x77, 0x6C, 0xAA, 0xF9, 0x73, 0x9B, 0x6A,
0x9F, 0xEE, 0x8E, 0x74, 0x11, 0xF8, 0xD6, 0xDA, 0xC0, 0x9D, 0x6A, 0x4E,
0xDB, 0x46, 0xCC, 0x2B, 0x5D, 0x52, 0x03, 0x09, 0x0E, 0xAE, 0x61, 0x26,
0x31, 0x1E, 0x53, 0xFD, 0x2C, 0x14, 0xB5, 0x74, 0xE6, 0xA3, 0x10, 0x9A,
0x3D, 0xA1, 0xBE, 0x41, 0xBD, 0xCE, 0xAA, 0x18, 0x6F, 0x5C, 0xE0, 0x67,
0x16, 0xA2, 0xB6, 0xA0, 0x7B, 0x3C, 0x33, 0xFE};
static const uint8_t kDHTest1024_160_Z[] = {
0x5C, 0x80, 0x4F, 0x45, 0x4D, 0x30, 0xD9, 0xC4, 0xDF, 0x85, 0x27, 0x1F,
0x93, 0x52, 0x8C, 0x91, 0xDF, 0x6B, 0x48, 0xAB, 0x5F, 0x80, 0xB3, 0xB5,
0x9C, 0xAA, 0xC1, 0xB2, 0x8F, 0x8A, 0xCB, 0xA9, 0xCD, 0x3E, 0x39, 0xF3,
0xCB, 0x61, 0x45, 0x25, 0xD9, 0x52, 0x1D, 0x2E, 0x64, 0x4C, 0x53, 0xB8,
0x07, 0xB8, 0x10, 0xF3, 0x40, 0x06, 0x2F, 0x25, 0x7D, 0x7D, 0x6F, 0xBF,
0xE8, 0xD5, 0xE8, 0xF0, 0x72, 0xE9, 0xB6, 0xE9, 0xAF, 0xDA, 0x94, 0x13,
0xEA, 0xFB, 0x2E, 0x8B, 0x06, 0x99, 0xB1, 0xFB, 0x5A, 0x0C, 0xAC, 0xED,
0xDE, 0xAE, 0xAD, 0x7E, 0x9C, 0xFB, 0xB3, 0x6A, 0xE2, 0xB4, 0x20, 0x83,
0x5B, 0xD8, 0x3A, 0x19, 0xFB, 0x0B, 0x5E, 0x96, 0xBF, 0x8F, 0xA4, 0xD0,
0x9E, 0x34, 0x55, 0x25, 0x16, 0x7E, 0xCD, 0x91, 0x55, 0x41, 0x6F, 0x46,
0xF4, 0x08, 0xED, 0x31, 0xB6, 0x3C, 0x6E, 0x6D};
static const uint8_t kDHTest2048_224_xA[] = {
0x22, 0xE6, 0x26, 0x01, 0xDB, 0xFF, 0xD0, 0x67, 0x08, 0xA6,
0x80, 0xF7, 0x47, 0xF3, 0x61, 0xF7, 0x6D, 0x8F, 0x4F, 0x72,
0x1A, 0x05, 0x48, 0xE4, 0x83, 0x29, 0x4B, 0x0C};
static const uint8_t kDHTest2048_224_yA[] = {
0x1B, 0x3A, 0x63, 0x45, 0x1B, 0xD8, 0x86, 0xE6, 0x99, 0xE6, 0x7B, 0x49,
0x4E, 0x28, 0x8B, 0xD7, 0xF8, 0xE0, 0xD3, 0x70, 0xBA, 0xDD, 0xA7, 0xA0,
0xEF, 0xD2, 0xFD, 0xE7, 0xD8, 0xF6, 0x61, 0x45, 0xCC, 0x9F, 0x28, 0x04,
0x19, 0x97, 0x5E, 0xB8, 0x08, 0x87, 0x7C, 0x8A, 0x4C, 0x0C, 0x8E, 0x0B,
0xD4, 0x8D, 0x4A, 0x54, 0x01, 0xEB, 0x1E, 0x87, 0x76, 0xBF, 0xEE, 0xE1,
0x34, 0xC0, 0x38, 0x31, 0xAC, 0x27, 0x3C, 0xD9, 0xD6, 0x35, 0xAB, 0x0C,
0xE0, 0x06, 0xA4, 0x2A, 0x88, 0x7E, 0x3F, 0x52, 0xFB, 0x87, 0x66, 0xB6,
0x50, 0xF3, 0x80, 0x78, 0xBC, 0x8E, 0xE8, 0x58, 0x0C, 0xEF, 0xE2, 0x43,
0x96, 0x8C, 0xFC, 0x4F, 0x8D, 0xC3, 0xDB, 0x08, 0x45, 0x54, 0x17, 0x1D,
0x41, 0xBF, 0x2E, 0x86, 0x1B, 0x7B, 0xB4, 0xD6, 0x9D, 0xD0, 0xE0, 0x1E,
0xA3, 0x87, 0xCB, 0xAA, 0x5C, 0xA6, 0x72, 0xAF, 0xCB, 0xE8, 0xBD, 0xB9,
0xD6, 0x2D, 0x4C, 0xE1, 0x5F, 0x17, 0xDD, 0x36, 0xF9, 0x1E, 0xD1, 0xEE,
0xDD, 0x65, 0xCA, 0x4A, 0x06, 0x45, 0x5C, 0xB9, 0x4C, 0xD4, 0x0A, 0x52,
0xEC, 0x36, 0x0E, 0x84, 0xB3, 0xC9, 0x26, 0xE2, 0x2C, 0x43, 0x80, 0xA3,
0xBF, 0x30, 0x9D, 0x56, 0x84, 0x97, 0x68, 0xB7, 0xF5, 0x2C, 0xFD, 0xF6,
0x55, 0xFD, 0x05, 0x3A, 0x7E, 0xF7, 0x06, 0x97, 0x9E, 0x7E, 0x58, 0x06,
0xB1, 0x7D, 0xFA, 0xE5, 0x3A, 0xD2, 0xA5, 0xBC, 0x56, 0x8E, 0xBB, 0x52,
0x9A, 0x7A, 0x61, 0xD6, 0x8D, 0x25, 0x6F, 0x8F, 0xC9, 0x7C, 0x07, 0x4A,
0x86, 0x1D, 0x82, 0x7E, 0x2E, 0xBC, 0x8C, 0x61, 0x34, 0x55, 0x31, 0x15,
0xB7, 0x0E, 0x71, 0x03, 0x92, 0x0A, 0xA1, 0x6D, 0x85, 0xE5, 0x2B, 0xCB,
0xAB, 0x8D, 0x78, 0x6A, 0x68, 0x17, 0x8F, 0xA8, 0xFF, 0x7C, 0x2F, 0x5C,
0x71, 0x64, 0x8D, 0x6F};
static const uint8_t kDHTest2048_224_xB[] = {
0x4F, 0xF3, 0xBC, 0x96, 0xC7, 0xFC, 0x6A, 0x6D, 0x71, 0xD3,
0xB3, 0x63, 0x80, 0x0A, 0x7C, 0xDF, 0xEF, 0x6F, 0xC4, 0x1B,
0x44, 0x17, 0xEA, 0x15, 0x35, 0x3B, 0x75, 0x90};
static const uint8_t kDHTest2048_224_yB[] = {
0x4D, 0xCE, 0xE9, 0x92, 0xA9, 0x76, 0x2A, 0x13, 0xF2, 0xF8, 0x38, 0x44,
0xAD, 0x3D, 0x77, 0xEE, 0x0E, 0x31, 0xC9, 0x71, 0x8B, 0x3D, 0xB6, 0xC2,
0x03, 0x5D, 0x39, 0x61, 0x18, 0x2C, 0x3E, 0x0B, 0xA2, 0x47, 0xEC, 0x41,
0x82, 0xD7, 0x60, 0xCD, 0x48, 0xD9, 0x95, 0x99, 0x97, 0x06, 0x22, 0xA1,
0x88, 0x1B, 0xBA, 0x2D, 0xC8, 0x22, 0x93, 0x9C, 0x78, 0xC3, 0x91, 0x2C,
0x66, 0x61, 0xFA, 0x54, 0x38, 0xB2, 0x07, 0x66, 0x22, 0x2B, 0x75, 0xE2,
0x4C, 0x2E, 0x3A, 0xD0, 0xC7, 0x28, 0x72, 0x36, 0x12, 0x95, 0x25, 0xEE,
0x15, 0xB5, 0xDD, 0x79, 0x98, 0xAA, 0x04, 0xC4, 0xA9, 0x69, 0x6C, 0xAC,
0xD7, 0x17, 0x20, 0x83, 0xA9, 0x7A, 0x81, 0x66, 0x4E, 0xAD, 0x2C, 0x47,
0x9E, 0x44, 0x4E, 0x4C, 0x06, 0x54, 0xCC, 0x19, 0xE2, 0x8D, 0x77, 0x03,
0xCE, 0xE8, 0xDA, 0xCD, 0x61, 0x26, 0xF5, 0xD6, 0x65, 0xEC, 0x52, 0xC6,
0x72, 0x55, 0xDB, 0x92, 0x01, 0x4B, 0x03, 0x7E, 0xB6, 0x21, 0xA2, 0xAC,
0x8E, 0x36, 0x5D, 0xE0, 0x71, 0xFF, 0xC1, 0x40, 0x0A, 0xCF, 0x07, 0x7A,
0x12, 0x91, 0x3D, 0xD8, 0xDE, 0x89, 0x47, 0x34, 0x37, 0xAB, 0x7B, 0xA3,
0x46, 0x74, 0x3C, 0x1B, 0x21, 0x5D, 0xD9, 0xC1, 0x21, 0x64, 0xA7, 0xE4,
0x05, 0x31, 0x18, 0xD1, 0x99, 0xBE, 0xC8, 0xEF, 0x6F, 0xC5, 0x61, 0x17,
0x0C, 0x84, 0xC8, 0x7D, 0x10, 0xEE, 0x9A, 0x67, 0x4A, 0x1F, 0xA8, 0xFF,
0xE1, 0x3B, 0xDF, 0xBA, 0x1D, 0x44, 0xDE, 0x48, 0x94, 0x6D, 0x68, 0xDC,
0x0C, 0xDD, 0x77, 0x76, 0x35, 0xA7, 0xAB, 0x5B, 0xFB, 0x1E, 0x4B, 0xB7,
0xB8, 0x56, 0xF9, 0x68, 0x27, 0x73, 0x4C, 0x18, 0x41, 0x38, 0xE9, 0x15,
0xD9, 0xC3, 0x00, 0x2E, 0xBC, 0xE5, 0x31, 0x20, 0x54, 0x6A, 0x7E, 0x20,
0x02, 0x14, 0x2B, 0x6C};
static const uint8_t kDHTest2048_224_Z[] = {
0x34, 0xD9, 0xBD, 0xDC, 0x1B, 0x42, 0x17, 0x6C, 0x31, 0x3F, 0xEA, 0x03,
0x4C, 0x21, 0x03, 0x4D, 0x07, 0x4A, 0x63, 0x13, 0xBB, 0x4E, 0xCD, 0xB3,
0x70, 0x3F, 0xFF, 0x42, 0x45, 0x67, 0xA4, 0x6B, 0xDF, 0x75, 0x53, 0x0E,
0xDE, 0x0A, 0x9D, 0xA5, 0x22, 0x9D, 0xE7, 0xD7, 0x67, 0x32, 0x28, 0x6C,
0xBC, 0x0F, 0x91, 0xDA, 0x4C, 0x3C, 0x85, 0x2F, 0xC0, 0x99, 0xC6, 0x79,
0x53, 0x1D, 0x94, 0xC7, 0x8A, 0xB0, 0x3D, 0x9D, 0xEC, 0xB0, 0xA4, 0xE4,
0xCA, 0x8B, 0x2B, 0xB4, 0x59, 0x1C, 0x40, 0x21, 0xCF, 0x8C, 0xE3, 0xA2,
0x0A, 0x54, 0x1D, 0x33, 0x99, 0x40, 0x17, 0xD0, 0x20, 0x0A, 0xE2, 0xC9,
0x51, 0x6E, 0x2F, 0xF5, 0x14, 0x57, 0x79, 0x26, 0x9E, 0x86, 0x2B, 0x0F,
0xB4, 0x74, 0xA2, 0xD5, 0x6D, 0xC3, 0x1E, 0xD5, 0x69, 0xA7, 0x70, 0x0B,
0x4C, 0x4A, 0xB1, 0x6B, 0x22, 0xA4, 0x55, 0x13, 0x53, 0x1E, 0xF5, 0x23,
0xD7, 0x12, 0x12, 0x07, 0x7B, 0x5A, 0x16, 0x9B, 0xDE, 0xFF, 0xAD, 0x7A,
0xD9, 0x60, 0x82, 0x84, 0xC7, 0x79, 0x5B, 0x6D, 0x5A, 0x51, 0x83, 0xB8,
0x70, 0x66, 0xDE, 0x17, 0xD8, 0xD6, 0x71, 0xC9, 0xEB, 0xD8, 0xEC, 0x89,
0x54, 0x4D, 0x45, 0xEC, 0x06, 0x15, 0x93, 0xD4, 0x42, 0xC6, 0x2A, 0xB9,
0xCE, 0x3B, 0x1C, 0xB9, 0x94, 0x3A, 0x1D, 0x23, 0xA5, 0xEA, 0x3B, 0xCF,
0x21, 0xA0, 0x14, 0x71, 0xE6, 0x7E, 0x00, 0x3E, 0x7F, 0x8A, 0x69, 0xC7,
0x28, 0xBE, 0x49, 0x0B, 0x2F, 0xC8, 0x8C, 0xFE, 0xB9, 0x2D, 0xB6, 0xA2,
0x15, 0xE5, 0xD0, 0x3C, 0x17, 0xC4, 0x64, 0xC9, 0xAC, 0x1A, 0x46, 0xE2,
0x03, 0xE1, 0x3F, 0x95, 0x29, 0x95, 0xFB, 0x03, 0xC6, 0x9D, 0x3C, 0xC4,
0x7F, 0xCB, 0x51, 0x0B, 0x69, 0x98, 0xFF, 0xD3, 0xAA, 0x6D, 0xE7, 0x3C,
0xF9, 0xF6, 0x38, 0x69};
static const uint8_t kDHTest2048_256_xA[] = {
0x08, 0x81, 0x38, 0x2C, 0xDB, 0x87, 0x66, 0x0C, 0x6D, 0xC1, 0x3E,
0x61, 0x49, 0x38, 0xD5, 0xB9, 0xC8, 0xB2, 0xF2, 0x48, 0x58, 0x1C,
0xC5, 0xE3, 0x1B, 0x35, 0x45, 0x43, 0x97, 0xFC, 0xE5, 0x0E};
static const uint8_t kDHTest2048_256_yA[] = {
0x2E, 0x93, 0x80, 0xC8, 0x32, 0x3A, 0xF9, 0x75, 0x45, 0xBC, 0x49, 0x41,
0xDE, 0xB0, 0xEC, 0x37, 0x42, 0xC6, 0x2F, 0xE0, 0xEC, 0xE8, 0x24, 0xA6,
0xAB, 0xDB, 0xE6, 0x6C, 0x59, 0xBE, 0xE0, 0x24, 0x29, 0x11, 0xBF, 0xB9,
0x67, 0x23, 0x5C, 0xEB, 0xA3, 0x5A, 0xE1, 0x3E, 0x4E, 0xC7, 0x52, 0xBE,
0x63, 0x0B, 0x92, 0xDC, 0x4B, 0xDE, 0x28, 0x47, 0xA9, 0xC6, 0x2C, 0xB8,
0x15, 0x27, 0x45, 0x42, 0x1F, 0xB7, 0xEB, 0x60, 0xA6, 0x3C, 0x0F, 0xE9,
0x15, 0x9F, 0xCC, 0xE7, 0x26, 0xCE, 0x7C, 0xD8, 0x52, 0x3D, 0x74, 0x50,
0x66, 0x7E, 0xF8, 0x40, 0xE4, 0x91, 0x91, 0x21, 0xEB, 0x5F, 0x01, 0xC8,
0xC9, 0xB0, 0xD3, 0xD6, 0x48, 0xA9, 0x3B, 0xFB, 0x75, 0x68, 0x9E, 0x82,
0x44, 0xAC, 0x13, 0x4A, 0xF5, 0x44, 0x71, 0x1C, 0xE7, 0x9A, 0x02, 0xDC,
0xC3, 0x42, 0x26, 0x68, 0x47, 0x80, 0xDD, 0xDC, 0xB4, 0x98, 0x59, 0x41,
0x06, 0xC3, 0x7F, 0x5B, 0xC7, 0x98, 0x56, 0x48, 0x7A, 0xF5, 0xAB, 0x02,
0x2A, 0x2E, 0x5E, 0x42, 0xF0, 0x98, 0x97, 0xC1, 0xA8, 0x5A, 0x11, 0xEA,
0x02, 0x12, 0xAF, 0x04, 0xD9, 0xB4, 0xCE, 0xBC, 0x93, 0x7C, 0x3C, 0x1A,
0x3E, 0x15, 0xA8, 0xA0, 0x34, 0x2E, 0x33, 0x76, 0x15, 0xC8, 0x4E, 0x7F,
0xE3, 0xB8, 0xB9, 0xB8, 0x7F, 0xB1, 0xE7, 0x3A, 0x15, 0xAF, 0x12, 0xA3,
0x0D, 0x74, 0x6E, 0x06, 0xDF, 0xC3, 0x4F, 0x29, 0x0D, 0x79, 0x7C, 0xE5,
0x1A, 0xA1, 0x3A, 0xA7, 0x85, 0xBF, 0x66, 0x58, 0xAF, 0xF5, 0xE4, 0xB0,
0x93, 0x00, 0x3C, 0xBE, 0xAF, 0x66, 0x5B, 0x3C, 0x2E, 0x11, 0x3A, 0x3A,
0x4E, 0x90, 0x52, 0x69, 0x34, 0x1D, 0xC0, 0x71, 0x14, 0x26, 0x68, 0x5F,
0x4E, 0xF3, 0x7E, 0x86, 0x8A, 0x81, 0x26, 0xFF, 0x3F, 0x22, 0x79, 0xB5,
0x7C, 0xA6, 0x7E, 0x29};
static const uint8_t kDHTest2048_256_xB[] = {
0x7D, 0x62, 0xA7, 0xE3, 0xEF, 0x36, 0xDE, 0x61, 0x7B, 0x13, 0xD1,
0xAF, 0xB8, 0x2C, 0x78, 0x0D, 0x83, 0xA2, 0x3B, 0xD4, 0xEE, 0x67,
0x05, 0x64, 0x51, 0x21, 0xF3, 0x71, 0xF5, 0x46, 0xA5, 0x3D};
static const uint8_t kDHTest2048_256_yB[] = {
0x57, 0x5F, 0x03, 0x51, 0xBD, 0x2B, 0x1B, 0x81, 0x74, 0x48, 0xBD, 0xF8,
0x7A, 0x6C, 0x36, 0x2C, 0x1E, 0x28, 0x9D, 0x39, 0x03, 0xA3, 0x0B, 0x98,
0x32, 0xC5, 0x74, 0x1F, 0xA2, 0x50, 0x36, 0x3E, 0x7A, 0xCB, 0xC7, 0xF7,
0x7F, 0x3D, 0xAC, 0xBC, 0x1F, 0x13, 0x1A, 0xDD, 0x8E, 0x03, 0x36, 0x7E,
0xFF, 0x8F, 0xBB, 0xB3, 0xE1, 0xC5, 0x78, 0x44, 0x24, 0x80, 0x9B, 0x25,
0xAF, 0xE4, 0xD2, 0x26, 0x2A, 0x1A, 0x6F, 0xD2, 0xFA, 0xB6, 0x41, 0x05,
0xCA, 0x30, 0xA6, 0x74, 0xE0, 0x7F, 0x78, 0x09, 0x85, 0x20, 0x88, 0x63,
0x2F, 0xC0, 0x49, 0x23, 0x37, 0x91, 0xAD, 0x4E, 0xDD, 0x08, 0x3A, 0x97,
0x8B, 0x88, 0x3E, 0xE6, 0x18, 0xBC, 0x5E, 0x0D, 0xD0, 0x47, 0x41, 0x5F,
0x2D, 0x95, 0xE6, 0x83, 0xCF, 0x14, 0x82, 0x6B, 0x5F, 0xBE, 0x10, 0xD3,
0xCE, 0x41, 0xC6, 0xC1, 0x20, 0xC7, 0x8A, 0xB2, 0x00, 0x08, 0xC6, 0x98,
0xBF, 0x7F, 0x0B, 0xCA, 0xB9, 0xD7, 0xF4, 0x07, 0xBE, 0xD0, 0xF4, 0x3A,
0xFB, 0x29, 0x70, 0xF5, 0x7F, 0x8D, 0x12, 0x04, 0x39, 0x63, 0xE6, 0x6D,
0xDD, 0x32, 0x0D, 0x59, 0x9A, 0xD9, 0x93, 0x6C, 0x8F, 0x44, 0x13, 0x7C,
0x08, 0xB1, 0x80, 0xEC, 0x5E, 0x98, 0x5C, 0xEB, 0xE1, 0x86, 0xF3, 0xD5,
0x49, 0x67, 0x7E, 0x80, 0x60, 0x73, 0x31, 0xEE, 0x17, 0xAF, 0x33, 0x80,
0xA7, 0x25, 0xB0, 0x78, 0x23, 0x17, 0xD7, 0xDD, 0x43, 0xF5, 0x9D, 0x7A,
0xF9, 0x56, 0x8A, 0x9B, 0xB6, 0x3A, 0x84, 0xD3, 0x65, 0xF9, 0x22, 0x44,
0xED, 0x12, 0x09, 0x88, 0x21, 0x93, 0x02, 0xF4, 0x29, 0x24, 0xC7, 0xCA,
0x90, 0xB8, 0x9D, 0x24, 0xF7, 0x1B, 0x0A, 0xB6, 0x97, 0x82, 0x3D, 0x7D,
0xEB, 0x1A, 0xFF, 0x5B, 0x0E, 0x8E, 0x4A, 0x45, 0xD4, 0x9F, 0x7F, 0x53,
0x75, 0x7E, 0x19, 0x13};
static const uint8_t kDHTest2048_256_Z[] = {
0x86, 0xC7, 0x0B, 0xF8, 0xD0, 0xBB, 0x81, 0xBB, 0x01, 0x07, 0x8A, 0x17,
0x21, 0x9C, 0xB7, 0xD2, 0x72, 0x03, 0xDB, 0x2A, 0x19, 0xC8, 0x77, 0xF1,
0xD1, 0xF1, 0x9F, 0xD7, 0xD7, 0x7E, 0xF2, 0x25, 0x46, 0xA6, 0x8F, 0x00,
0x5A, 0xD5, 0x2D, 0xC8, 0x45, 0x53, 0xB7, 0x8F, 0xC6, 0x03, 0x30, 0xBE,
0x51, 0xEA, 0x7C, 0x06, 0x72, 0xCA, 0xC1, 0x51, 0x5E, 0x4B, 0x35, 0xC0,
0x47, 0xB9, 0xA5, 0x51, 0xB8, 0x8F, 0x39, 0xDC, 0x26, 0xDA, 0x14, 0xA0,
0x9E, 0xF7, 0x47, 0x74, 0xD4, 0x7C, 0x76, 0x2D, 0xD1, 0x77, 0xF9, 0xED,
0x5B, 0xC2, 0xF1, 0x1E, 0x52, 0xC8, 0x79, 0xBD, 0x95, 0x09, 0x85, 0x04,
0xCD, 0x9E, 0xEC, 0xD8, 0xA8, 0xF9, 0xB3, 0xEF, 0xBD, 0x1F, 0x00, 0x8A,
0xC5, 0x85, 0x30, 0x97, 0xD9, 0xD1, 0x83, 0x7F, 0x2B, 0x18, 0xF7, 0x7C,
0xD7, 0xBE, 0x01, 0xAF, 0x80, 0xA7, 0xC7, 0xB5, 0xEA, 0x3C, 0xA5, 0x4C,
0xC0, 0x2D, 0x0C, 0x11, 0x6F, 0xEE, 0x3F, 0x95, 0xBB, 0x87, 0x39, 0x93,
0x85, 0x87, 0x5D, 0x7E, 0x86, 0x74, 0x7E, 0x67, 0x6E, 0x72, 0x89, 0x38,
0xAC, 0xBF, 0xF7, 0x09, 0x8E, 0x05, 0xBE, 0x4D, 0xCF, 0xB2, 0x40, 0x52,
0xB8, 0x3A, 0xEF, 0xFB, 0x14, 0x78, 0x3F, 0x02, 0x9A, 0xDB, 0xDE, 0x7F,
0x53, 0xFA, 0xE9, 0x20, 0x84, 0x22, 0x40, 0x90, 0xE0, 0x07, 0xCE, 0xE9,
0x4D, 0x4B, 0xF2, 0xBA, 0xCE, 0x9F, 0xFD, 0x4B, 0x57, 0xD2, 0xAF, 0x7C,
0x72, 0x4D, 0x0C, 0xAA, 0x19, 0xBF, 0x05, 0x01, 0xF6, 0xF1, 0x7B, 0x4A,
0xA1, 0x0F, 0x42, 0x5E, 0x3E, 0xA7, 0x60, 0x80, 0xB4, 0xB9, 0xD6, 0xB3,
0xCE, 0xFE, 0xA1, 0x15, 0xB2, 0xCE, 0xB8, 0x78, 0x9B, 0xB8, 0xA3, 0xB0,
0xEA, 0x87, 0xFE, 0xBE, 0x63, 0xB6, 0xC8, 0xF8, 0x46, 0xEC, 0x6D, 0xB0,
0xC2, 0x6C, 0x5D, 0x7C};
struct RFC5114TestData {
DH *(*get_param)(const ENGINE *engine);
const uint8_t *xA;
size_t xA_len;
const uint8_t *yA;
size_t yA_len;
const uint8_t *xB;
size_t xB_len;
const uint8_t *yB;
size_t yB_len;
const uint8_t *Z;
size_t Z_len;
};
#define MAKE_RFC5114_TEST_DATA(pre) \
{ \
DH_get_##pre, kDHTest##pre##_xA, sizeof(kDHTest##pre##_xA), \
kDHTest##pre##_yA, sizeof(kDHTest##pre##_yA), kDHTest##pre##_xB, \
sizeof(kDHTest##pre##_xB), kDHTest##pre##_yB, \
sizeof(kDHTest##pre##_yB), kDHTest##pre##_Z, sizeof(kDHTest##pre##_Z) \
}
static const RFC5114TestData kRFCTestData[] = {
MAKE_RFC5114_TEST_DATA(1024_160),
MAKE_RFC5114_TEST_DATA(2048_224),
MAKE_RFC5114_TEST_DATA(2048_256),
};
static bool RunRFC5114Tests() {
for (unsigned i = 0; i < sizeof(kRFCTestData) / sizeof(RFC5114TestData); i++) {
const RFC5114TestData *td = kRFCTestData + i;
/* Set up DH structures setting key components */
bssl::UniquePtr<DH> dhA(td->get_param(nullptr));
bssl::UniquePtr<DH> dhB(td->get_param(nullptr));
if (!dhA || !dhB) {
fprintf(stderr, "Initialisation error RFC5114 set %u\n", i + 1);
return false;
}
dhA->priv_key = BN_bin2bn(td->xA, td->xA_len, nullptr);
dhA->pub_key = BN_bin2bn(td->yA, td->yA_len, nullptr);
dhB->priv_key = BN_bin2bn(td->xB, td->xB_len, nullptr);
dhB->pub_key = BN_bin2bn(td->yB, td->yB_len, nullptr);
if (!dhA->priv_key || !dhA->pub_key || !dhB->priv_key || !dhB->pub_key) {
fprintf(stderr, "BN_bin2bn error RFC5114 set %u\n", i + 1);
return false;
}
if ((td->Z_len != (size_t)DH_size(dhA.get())) ||
(td->Z_len != (size_t)DH_size(dhB.get()))) {
return false;
}
std::vector<uint8_t> Z1(DH_size(dhA.get()));
std::vector<uint8_t> Z2(DH_size(dhB.get()));
/* Work out shared secrets using both sides and compare
* with expected values. */
int ret1 = DH_compute_key(Z1.data(), dhB->pub_key, dhA.get());
int ret2 = DH_compute_key(Z2.data(), dhA->pub_key, dhB.get());
if (ret1 < 0 || ret2 < 0) {
fprintf(stderr, "DH_compute_key error RFC5114 set %u\n", i + 1);
return false;
}
if (static_cast<size_t>(ret1) != td->Z_len ||
OPENSSL_memcmp(Z1.data(), td->Z, td->Z_len) != 0 ||
static_cast<size_t>(ret2) != td->Z_len ||
OPENSSL_memcmp(Z2.data(), td->Z, td->Z_len) != 0) {
fprintf(stderr, "Test failed RFC5114 set %u\n", i + 1);
return false;
}
printf("RFC5114 parameter test %u OK\n", i + 1);
}
return 1;
}
// kRFC5114_2048_224BadY is a bad y-coordinate for RFC 5114's 2048-bit MODP
// Group with 224-bit Prime Order Subgroup (section 2.2).
static const uint8_t kRFC5114_2048_224BadY[] = {
0x45, 0x32, 0x5f, 0x51, 0x07, 0xe5, 0xdf, 0x1c, 0xd6, 0x02, 0x82, 0xb3,
0x32, 0x8f, 0xa4, 0x0f, 0x87, 0xb8, 0x41, 0xfe, 0xb9, 0x35, 0xde, 0xad,
0xc6, 0x26, 0x85, 0xb4, 0xff, 0x94, 0x8c, 0x12, 0x4c, 0xbf, 0x5b, 0x20,
0xc4, 0x46, 0xa3, 0x26, 0xeb, 0xa4, 0x25, 0xb7, 0x68, 0x8e, 0xcc, 0x67,
0xba, 0xea, 0x58, 0xd0, 0xf2, 0xe9, 0xd2, 0x24, 0x72, 0x60, 0xda, 0x88,
0x18, 0x9c, 0xe0, 0x31, 0x6a, 0xad, 0x50, 0x6d, 0x94, 0x35, 0x8b, 0x83,
0x4a, 0x6e, 0xfa, 0x48, 0x73, 0x0f, 0x83, 0x87, 0xff, 0x6b, 0x66, 0x1f,
0xa8, 0x82, 0xc6, 0x01, 0xe5, 0x80, 0xb5, 0xb0, 0x52, 0xd0, 0xe9, 0xd8,
0x72, 0xf9, 0x7d, 0x5b, 0x8b, 0xa5, 0x4c, 0xa5, 0x25, 0x95, 0x74, 0xe2,
0x7a, 0x61, 0x4e, 0xa7, 0x8f, 0x12, 0xe2, 0xd2, 0x9d, 0x8c, 0x02, 0x70,
0x34, 0x44, 0x32, 0xc7, 0xb2, 0xf3, 0xb9, 0xfe, 0x17, 0x2b, 0xd6, 0x1f,
0x8b, 0x7e, 0x4a, 0xfa, 0xa3, 0xb5, 0x3e, 0x7a, 0x81, 0x9a, 0x33, 0x66,
0x62, 0xa4, 0x50, 0x18, 0x3e, 0xa2, 0x5f, 0x00, 0x07, 0xd8, 0x9b, 0x22,
0xe4, 0xec, 0x84, 0xd5, 0xeb, 0x5a, 0xf3, 0x2a, 0x31, 0x23, 0xd8, 0x44,
0x22, 0x2a, 0x8b, 0x37, 0x44, 0xcc, 0xc6, 0x87, 0x4b, 0xbe, 0x50, 0x9d,
0x4a, 0xc4, 0x8e, 0x45, 0xcf, 0x72, 0x4d, 0xc0, 0x89, 0xb3, 0x72, 0xed,
0x33, 0x2c, 0xbc, 0x7f, 0x16, 0x39, 0x3b, 0xeb, 0xd2, 0xdd, 0xa8, 0x01,
0x73, 0x84, 0x62, 0xb9, 0x29, 0xd2, 0xc9, 0x51, 0x32, 0x9e, 0x7a, 0x6a,
0xcf, 0xc1, 0x0a, 0xdb, 0x0e, 0xe0, 0x62, 0x77, 0x6f, 0x59, 0x62, 0x72,
0x5a, 0x69, 0xa6, 0x5b, 0x70, 0xca, 0x65, 0xc4, 0x95, 0x6f, 0x9a, 0xc2,
0xdf, 0x72, 0x6d, 0xb1, 0x1e, 0x54, 0x7b, 0x51, 0xb4, 0xef, 0x7f, 0x89,
0x93, 0x74, 0x89, 0x59,
};
static bool TestBadY() {
bssl::UniquePtr<DH> dh(DH_get_2048_224(nullptr));
bssl::UniquePtr<BIGNUM> pub_key(
BN_bin2bn(kRFC5114_2048_224BadY, sizeof(kRFC5114_2048_224BadY), nullptr));
if (!dh || !pub_key || !DH_generate_key(dh.get())) {
return false;
}
int flags;
if (!DH_check_pub_key(dh.get(), pub_key.get(), &flags)) {
return false;
}
if (!(flags & DH_CHECK_PUBKEY_INVALID)) {
fprintf(stderr, "DH_check_pub_key did not reject the key.\n");
return false;
}
std::vector<uint8_t> result(DH_size(dh.get()));
if (DH_compute_key(result.data(), pub_key.get(), dh.get()) >= 0) {
fprintf(stderr, "DH_compute_key unexpectedly succeeded.\n");
return false;
}
ERR_clear_error();
return true;
}
static bool BIGNUMEqualsHex(const BIGNUM *bn, const char *hex) {
BIGNUM *hex_bn = NULL;
if (!BN_hex2bn(&hex_bn, hex)) {
return false;
}
bssl::UniquePtr<BIGNUM> free_hex_bn(hex_bn);
return BN_cmp(bn, hex_bn) == 0;
}
static bool TestASN1() {
// kParams are a set of Diffie-Hellman parameters generated with
// openssl dhparam 256
static const uint8_t kParams[] = {
0x30, 0x26, 0x02, 0x21, 0x00, 0xd7, 0x20, 0x34, 0xa3, 0x27,
0x4f, 0xdf, 0xbf, 0x04, 0xfd, 0x24, 0x68, 0x25, 0xb6, 0x56,
0xd8, 0xab, 0x2a, 0x41, 0x2d, 0x74, 0x0a, 0x52, 0x08, 0x7c,
0x40, 0x71, 0x4e, 0xd2, 0x57, 0x93, 0x13, 0x02, 0x01, 0x02,
};
CBS cbs;
CBS_init(&cbs, kParams, sizeof(kParams));
bssl::UniquePtr<DH> dh(DH_parse_parameters(&cbs));
if (!dh || CBS_len(&cbs) != 0 ||
!BIGNUMEqualsHex(
dh->p,
"d72034a3274fdfbf04fd246825b656d8ab2a412d740a52087c40714ed2579313") ||
!BIGNUMEqualsHex(dh->g, "2") || dh->priv_length != 0) {
return false;
}
bssl::ScopedCBB cbb;
uint8_t *der;
size_t der_len;
if (!CBB_init(cbb.get(), 0) ||
!DH_marshal_parameters(cbb.get(), dh.get()) ||
!CBB_finish(cbb.get(), &der, &der_len)) {
return false;
}
bssl::UniquePtr<uint8_t> free_der(der);
if (der_len != sizeof(kParams) ||
OPENSSL_memcmp(der, kParams, der_len) != 0) {
return false;
}
// kParamsDSA are a set of Diffie-Hellman parameters generated with
// openssl dhparam 256 -dsaparam
static const uint8_t kParamsDSA[] = {
0x30, 0x81, 0x89, 0x02, 0x41, 0x00, 0x93, 0xf3, 0xc1, 0x18, 0x01, 0xe6,
0x62, 0xb6, 0xd1, 0x46, 0x9a, 0x2c, 0x72, 0xea, 0x31, 0xd9, 0x18, 0x10,
0x30, 0x28, 0x63, 0xe2, 0x34, 0x7d, 0x80, 0xca, 0xee, 0x82, 0x2b, 0x19,
0x3c, 0x19, 0xbb, 0x42, 0x83, 0x02, 0x70, 0xdd, 0xdb, 0x8c, 0x03, 0xab,
0xe9, 0x9c, 0xc4, 0x00, 0x4d, 0x70, 0x5f, 0x52, 0x03, 0x31, 0x2c, 0xa4,
0x67, 0x34, 0x51, 0x95, 0x2a, 0xac, 0x11, 0xe2, 0x6a, 0x55, 0x02, 0x40,
0x44, 0xc8, 0x10, 0x53, 0x44, 0x32, 0x31, 0x63, 0xd8, 0xd1, 0x8c, 0x75,
0xc8, 0x98, 0x53, 0x3b, 0x5b, 0x4a, 0x2a, 0x0a, 0x09, 0xe7, 0xd0, 0x3c,
0x53, 0x72, 0xa8, 0x6b, 0x70, 0x41, 0x9c, 0x26, 0x71, 0x44, 0xfc, 0x7f,
0x08, 0x75, 0xe1, 0x02, 0xab, 0x74, 0x41, 0xe8, 0x2a, 0x3d, 0x3c, 0x26,
0x33, 0x09, 0xe4, 0x8b, 0xb4, 0x41, 0xec, 0xa6, 0xa8, 0xba, 0x1a, 0x07,
0x8a, 0x77, 0xf5, 0x5f, 0x02, 0x02, 0x00, 0xa0,
};
CBS_init(&cbs, kParamsDSA, sizeof(kParamsDSA));
dh.reset(DH_parse_parameters(&cbs));
if (!dh || CBS_len(&cbs) != 0 ||
!BIGNUMEqualsHex(dh->p,
"93f3c11801e662b6d1469a2c72ea31d91810302863e2347d80caee8"
"22b193c19bb42830270dddb8c03abe99cc4004d705f5203312ca467"
"3451952aac11e26a55") ||
!BIGNUMEqualsHex(dh->g,
"44c8105344323163d8d18c75c898533b5b4a2a0a09e7d03c5372a86"
"b70419c267144fc7f0875e102ab7441e82a3d3c263309e48bb441ec"
"a6a8ba1a078a77f55f") ||
dh->priv_length != 160) {
return false;
}
if (!CBB_init(cbb.get(), 0) ||
!DH_marshal_parameters(cbb.get(), dh.get()) ||
!CBB_finish(cbb.get(), &der, &der_len)) {
return false;
}
bssl::UniquePtr<uint8_t> free_der2(der);
if (der_len != sizeof(kParamsDSA) ||
OPENSSL_memcmp(der, kParamsDSA, der_len) != 0) {
return false;
}
return true;
}
static bool TestRFC3526() {
bssl::UniquePtr<BIGNUM> bn(BN_get_rfc3526_prime_1536(nullptr));
if (!bn) {
return false;
}
static const uint8_t kPrime1536[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2,
0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1,
0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6,
0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd,
0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d,
0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45,
0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9,
0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed,
0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11,
0x7c, 0x4b, 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d,
0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, 0x98, 0xda, 0x48, 0x36,
0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, 0xfd, 0x24, 0xcf, 0x5f,
0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56,
0x20, 0x85, 0x52, 0xbb, 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d,
0x67, 0x0c, 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, 0xf1, 0x74, 0x6c, 0x08,
0xca, 0x23, 0x73, 0x27, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
};
uint8_t buffer[sizeof(kPrime1536)];
if (BN_num_bytes(bn.get()) != sizeof(kPrime1536) ||
BN_bn2bin(bn.get(), buffer) != sizeof(kPrime1536) ||
OPENSSL_memcmp(buffer, kPrime1536, sizeof(kPrime1536)) != 0) {
fprintf(stderr, "1536-bit MODP prime did not match.\n");
return false;
}
return true;
}
| 45.926537 | 81 | 0.638233 | [
"vector"
] |
81674d9b6a215112a56a755871a41eb9dd81c5e3 | 4,102 | cpp | C++ | pepTalker.cpp | james-a-ware/pepTalker | c481a9b0aaed1397cd44f92dae1ef4a9c3b3eafb | [
"MIT"
] | null | null | null | pepTalker.cpp | james-a-ware/pepTalker | c481a9b0aaed1397cd44f92dae1ef4a9c3b3eafb | [
"MIT"
] | null | null | null | pepTalker.cpp | james-a-ware/pepTalker | c481a9b0aaed1397cd44f92dae1ef4a9c3b3eafb | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <ctime>
using namespace std;
int main(){
int max {19}; //upper limit of the randomiser
srand(time(NULL)); //proper random?
vector <string> listA;
listA.push_back("oi ");
listA.push_back("Champ, ");
listA.push_back("Fact: ");
listA.push_back("Everybody says");
listA.push_back("Dang... ");
listA.push_back("Check it: ");
listA.push_back("Just saying... ");
listA.push_back("Superstar, ");
listA.push_back("Tiger, ");
listA.push_back("Self, ");
listA.push_back("Know this: ");
listA.push_back("News alert: ");
listA.push_back("Girl, ");
listA.push_back("Ace, ");
listA.push_back("Excuse me but ");
listA.push_back("Experts agree: ");
listA.push_back("In my opinion, ");
listA.push_back("Hear ye, hear ye: ");
listA.push_back("Okay, listen up: ");
vector <string> listB;
listB.push_back("your breath today ");
listB.push_back("the mere idea of you ");
listB.push_back("your soul ");
listB.push_back("your hair today ");
listB.push_back("everything you do ");
listB.push_back("your personal style ");
listB.push_back("every thought you have ");
listB.push_back("that sparkle in your eye ");
listB.push_back("your presence here ");
listB.push_back("what you got going on ");
listB.push_back("the essential you ");
listB.push_back("your life's journey ");
listB.push_back("that saucy personality ");
listB.push_back("your DNA ");
listB.push_back("that brain of yours ");
listB.push_back("your choice of attire ");
listB.push_back("the way you roll ");
listB.push_back("whatever your secret is ");
listB.push_back("all of you all ");
vector <string> listC;
listC.push_back("has serious game, ");
listC.push_back("can kill a Rhino, from 100 ft ");
listC.push_back("rains magic, ");
listC.push_back("deserves the Nobel prize, ");
listC.push_back("raises the roof, ");
listC.push_back("breeds miracles, ");
listC.push_back("is paying off big time, ");
listC.push_back("shows mad skills, ");
listC.push_back("just shimmers, ");
listC.push_back("is a national treasure, ");
listC.push_back("gets the party going, ");
listC.push_back("is the next big thing, ");
listC.push_back("roars like a Lion, ");
listC.push_back("is a rainbow factory, ");
listC.push_back("is made of diamonds, ");
listC.push_back("makes birds sing, ");
listC.push_back("should be taught in school, ");
listC.push_back("makes the world go round, ");
listC.push_back("is 100% legit, ");
vector <string> listD;
listD.push_back("24/7.");
listD.push_back("theres the door");
listD.push_back("can I get an amen?");
listD.push_back("and that's a fact.");
listD.push_back("so treat yourself.");
listD.push_back("you feel me?");
listD.push_back("that's just science.");
listD.push_back("would I lie?");
listD.push_back("for reals.");
listD.push_back("mic drop.");
listD.push_back("you hidden gem.");
listD.push_back("snuggle bear.");
listD.push_back("period.");
listD.push_back("can I get an amn?");
listD.push_back("now lets dance.");
listD.push_back("high five.");
listD.push_back("say it again!");
listD.push_back("according to the BBC.");
listD.push_back("so get used to it.");
string partA, partB, partC, partD;
partA = listA.at(rand()%max);
partB = listB.at(rand()%max);
partC = listC.at(rand()%max);
partD = listD.at(rand()%max);
cout << "*************************************" << endl;
cout << " _______ " << endl;
cout << " / / , "<<partA<<partB<<" " << endl;
cout << " / / / "<<partC<<partD<<" " << endl;
cout << " /______/ / " << endl;
cout << " (______(/ " << endl;
cout << endl;
cout << "*************************************" << endl;
cout << endl;
return 0;
} | 35.982456 | 67 | 0.590444 | [
"vector"
] |
8167abff89ff1cc9e2160f2bb6961968af752f69 | 741 | hpp | C++ | trunk/src/kernel/srs_kernel_balance.hpp | cysk003/srs | d117145b9576292060387c18e0502c47a987d158 | [
"MIT"
] | null | null | null | trunk/src/kernel/srs_kernel_balance.hpp | cysk003/srs | d117145b9576292060387c18e0502c47a987d158 | [
"MIT"
] | null | null | null | trunk/src/kernel/srs_kernel_balance.hpp | cysk003/srs | d117145b9576292060387c18e0502c47a987d158 | [
"MIT"
] | null | null | null | //
// Copyright (c) 2013-2022 The SRS Authors
//
// SPDX-License-Identifier: MIT or MulanPSL-2.0
//
#ifndef SRS_KERNEL_BALANCE_HPP
#define SRS_KERNEL_BALANCE_HPP
#include <srs_core.hpp>
#include <vector>
#include <string>
/**
* the round-robin load balance algorithm,
* used for edge pull and other multiple server feature.
*/
class SrsLbRoundRobin
{
private:
// current selected index.
int index;
// total scheduled count.
uint32_t count;
// current selected server.
std::string elem;
public:
SrsLbRoundRobin();
virtual ~SrsLbRoundRobin();
public:
virtual uint32_t current();
virtual std::string selected();
virtual std::string select(const std::vector<std::string>& servers);
};
#endif
| 19 | 72 | 0.697706 | [
"vector"
] |
81696eb73a2beeea1e25f8efdaaf18e9e0de33a9 | 1,944 | hh | C++ | TFM/click-2.0.1/elements/grid/radiosim.hh | wangyang2013/TFM | cabca56229a7e4dafc76da8d631980fc453c9493 | [
"BSD-3-Clause"
] | 3 | 2018-04-14T14:43:31.000Z | 2019-12-06T13:09:58.000Z | TFM/click-2.0.1/elements/grid/radiosim.hh | nfvproject/TFM | cabca56229a7e4dafc76da8d631980fc453c9493 | [
"BSD-3-Clause"
] | null | null | null | TFM/click-2.0.1/elements/grid/radiosim.hh | nfvproject/TFM | cabca56229a7e4dafc76da8d631980fc453c9493 | [
"BSD-3-Clause"
] | null | null | null | #ifndef RADIOSIM_HH
#define RADIOSIM_HH
/*
* =c
* RadioSim([keywords,] [lat1 lon1, lat2 lon2, ...])
* =s Grid
* simulates reachability and broadcast in an 802.11-like radio network
* =d
* RadioSim simulates reachability and broadcast in an 802.11-like
* radio network.
*
* Each corresponding input/output pair corresponds to one node.
* Each node has a latitude/longitude, given by the <i>th
* configuration argument.
*
* When node <i> sends a packet into RadioSim's input <i>,
* RadioSim sends a copy to each output whose node is
* within 250 meters of node <i>.
*
* Inputs are pull, outputs are push. Services inputs in round
* robin order.
*
* Keyword:
*
* =over 8
*
* =item USE_XY
*
* Boolean. Defaults to false. Use x,y coordinates in metres instead
* of lat,lon in degrees. lat is treated as x, and lon is treated as
* y.
*
* =back
*
* The loc read/write handler format is
* node-index latitude longitude */
#include <click/element.hh>
#include <click/vector.hh>
#include "grid.hh"
#include <click/task.hh>
CLICK_DECLS
class RadioSim : public Element {
public:
RadioSim();
~RadioSim();
const char *class_name() const { return "RadioSim"; }
const char *port_count() const { return "-/-"; }
const char *processing() const { return PULL_TO_PUSH; }
int configure(Vector<String> &, ErrorHandler *);
int initialize(ErrorHandler *errh);
void add_handlers();
bool run_task(Task *);
private:
struct Node {
double _lat;
double _lon;
Node(double la, double lo) : _lat(la), _lon(lo) { }
Node() : _lat(0), _lon(0) { }
};
Node get_node_loc(int i);
void set_node_loc(int i, double lat, double lon);
int nnodes() { return(_nodes.size()); }
static int rs_write_handler(const String &, Element *, void *, ErrorHandler *);
static String rs_read_handler(Element *, void *);
Vector<Node> _nodes;
Task _task;
bool _use_xy;
};
CLICK_ENDDECLS
#endif
| 22.344828 | 81 | 0.675926 | [
"vector"
] |
816ae1d628da4b57a71f725c3164484289b4dd60 | 48,097 | hpp | C++ | src/base/AFStringUtils.hpp | ArkGame/ArkGameFrame | a7f8413dd416cd1ac5b12adbdd84f010f59f11e2 | [
"Apache-2.0"
] | 168 | 2016-08-18T07:24:48.000Z | 2018-02-06T06:40:45.000Z | src/base/AFStringUtils.hpp | Mu-L/ARK | a7f8413dd416cd1ac5b12adbdd84f010f59f11e2 | [
"Apache-2.0"
] | 11 | 2019-05-27T12:26:02.000Z | 2021-05-12T02:45:16.000Z | src/base/AFStringUtils.hpp | ArkGame/ArkGameFrame | a7f8413dd416cd1ac5b12adbdd84f010f59f11e2 | [
"Apache-2.0"
] | 51 | 2016-09-01T10:17:38.000Z | 2018-02-06T10:45:25.000Z | /*
* This source file is part of ARK
* For the latest info, see https://github.com/ArkNX
*
* Copyright (c) 2013-2020 ArkNX 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.
*
*/
#pragma once
#include "base/AFPlatform.hpp"
#include "base/AFMacros.hpp"
namespace ark {
namespace detail {
inline void dbg(const char* s, std::string& fs)
{
//fs << '\"' << s << '\"';
fs = ARK_FORMAT("{}{}{}{}", fs, '\"', s, '\"');
}
inline void dbg(const std::string& s, std::string& fs)
{
//fs << '\"' << s << '\"';
fs = ARK_FORMAT("{}{}{}{}", fs, '\"', s, '\"');
}
template<typename T>
inline void dbg(const T& t, std::string& fs)
{
//fs << t;
fs = ARK_FORMAT("{}{}", fs, t);
}
template<typename K, typename V>
inline void dbg(const std::pair<K, V>& x, std::string& fs)
{
dbg(x.first, fs);
//fs << ':';
fs = ARK_FORMAT("{}{}", fs, ':');
dbg(x.second, fs);
}
template<typename T>
void dbg(const T& beg, const T& end, char c1, char c2, std::string& fs)
{
if (beg == end)
{
//fs << c1 << c2;
fs = ARK_FORMAT("{}{}{}", fs, c1, c2);
return;
}
//fs << c1;
fs = ARK_FORMAT("{}{}", fs, c1);
for (T it = beg; it != end; ++it)
{
dbg(*it, fs);
//fs << ',';
fs = ARK_FORMAT("{}{}", fs, ',');
}
fs.back() = c2;
}
} // namespace detail
class AFStringUtils
{
public:
// split("x y z", ' '); -> [ "x", "y", "z" ]
// split("|x|y|", '|'); -> [ "", "x", "y" ]
// split("xooy", "oo"); -> [ "x", "y"]
// split("xooy", 'o', 1); -> [ "x", "oy" ]
static inline void split(std::vector<std::string>& v, const char* s, char c, uint32_t max_split = 0)
{
const char* p;
const char* from = s;
while ((p = strchr(from, c)))
{
v.emplace_back(std::string_view(from, p - from));
from = p + 1;
if (v.size() == max_split)
{
break;
}
}
if (from < s + strlen(s))
{
v.emplace_back(std::string_view(from));
}
}
static inline void split(std::vector<std::string>& v, const std::string& s, char c, uint32_t max_split = 0)
{
const char* p;
const char* from = s.data();
const char* end = from + s.size();
while ((p = static_cast<const char*>(memchr(from, c, end - from))))
{
v.emplace_back(std::string_view(from, p - from));
from = p + 1;
if (v.size() == max_split)
{
break;
}
}
if (from < end)
{
v.emplace_back(std::string_view(from, end - from));
}
}
static inline void split(std::vector<std::string>& v, const char* s, const char* c, uint32_t max_split = 0)
{
const char* p;
const char* from = s;
size_t n = strlen(c);
while ((p = strstr(from, c)))
{
v.emplace_back(std::string(from, p - from));
from = p + n;
if (v.size() == max_split)
{
break;
}
}
if (from < s + strlen(s))
{
v.emplace_back(std::string_view(from));
}
}
static inline void split(std::vector<std::string>& v, const std::string& s, const char* c, uint32_t max_split = 0)
{
split(v, s.c_str(), c, max_split);
}
// replace("xooxoox", "oo", "ee"); -> "xeexeex"
// replace("xooxoox", "oo", "ee", 1); -> "xeexoox"
static inline auto replace(const char* s, const char* sub, const char* to, uint32_t max_replace = 0) -> std::string
{
const char* p;
const char* from = s;
size_t n = strlen(sub);
size_t m = strlen(to);
std::string x;
while ((p = strstr(from, sub)))
{
x.append(from, p - from);
x.append(to, m);
from = p + n;
if (--max_replace == 0)
{
break;
}
}
if (from < s + strlen(s))
{
x.append(from);
}
return x;
}
static inline auto replace(const std::string& s, const char* sub, const char* to, uint32_t max_replace = 0)
-> std::string
{
const char* from = s.c_str();
const char* p = strstr(from, sub);
if (p == nullptr)
{
return s;
}
size_t n = strlen(sub);
size_t m = strlen(to);
std::string x;
x.reserve(s.size());
do
{
x.append(from, p - from).append(to, m);
from = p + n;
if (--max_replace == 0)
{
break;
}
} while ((p = strstr(from, sub)));
if (from < s.data() + s.size())
{
x.append(from);
}
return x;
}
// strip("abxxa", "ab") -> "xx" strip both left and right.
// strip("abxxa", "ab", 'l') -> "xxa" strip left only.
// strip("abxxa", "ab", 'r') -> "abxx" strip right only.
static inline auto strip(const char* s, const char* c = " \t\r\n", char d = 'b') -> std::string
{
if (!*s)
{
return std::string();
}
std::array<char, 256> bs = {0};
while (*c)
{
bs[static_cast<uint8_t>(*c++)] = 1;
}
if (d == 'l' || d == 'L')
{
while (bs[static_cast<uint8_t>(*s)])
{
++s;
}
return std::string(s);
}
else if (d == 'r' || d == 'R')
{
const char* e = s + strlen(s) - 1;
while (e >= s && bs[static_cast<uint8_t>(*e)])
{
--e;
}
return std::string(s, e + 1 - s);
}
else
{
while (bs[static_cast<uint8_t>(*s)])
{
++s;
}
const char* e = s + strlen(s) - 1;
while (e >= s && bs[static_cast<uint8_t>(*e)])
{
--e;
}
return std::string(s, e + 1 - s);
}
}
static inline auto strip(const char* s, char c, char d = 'b') -> std::string
{
if (!*s)
{
return std::string();
}
if (d == 'l' || d == 'L')
{
while (*s == c)
{
++s;
}
return std::string(s);
}
else if (d == 'r' || d == 'R')
{
const char* e = s + strlen(s) - 1;
while (e >= s && *e == c)
{
--e;
}
return std::string(s, e + 1 - s);
}
else
{
while (*s == c)
{
++s;
}
const char* e = s + strlen(s) - 1;
while (e >= s && *e == c)
{
--e;
}
return std::string(s, e + 1 - s);
}
}
static inline auto strip(const std::string& s, const char* c = " \t\r\n", char d = 'b') -> std::string
{
if (s.empty())
{
return std::string();
}
std::array<char, 256> bs = {0};
while (*c)
{
bs[static_cast<uint8_t>(*c++)] = 1;
}
if (d == 'l' || d == 'L')
{
size_t b = 0;
while (b < s.size() && bs[static_cast<uint8_t>(s[b])])
{
++b;
}
return b == 0 ? s : s.substr(b);
}
else if (d == 'r' || d == 'R')
{
size_t e = s.size();
while (e > 0 && bs[static_cast<uint8_t>(s[e - 1])])
{
--e;
}
return e == s.size() ? s : s.substr(0, e);
}
else
{
size_t b = 0, e = s.size();
while (b < s.size() && bs[static_cast<uint8_t>(s[b])])
{
++b;
}
if (b == s.size())
{
return std::string();
}
while (e > 0 && bs[static_cast<uint8_t>(s[e - 1])])
{
--e;
}
return (e - b == s.size()) ? s : s.substr(b, e - b);
}
}
static inline auto strip(const std::string& s, char c, char d = 'b') -> std::string
{
if (s.empty())
{
return std::string();
}
if (d == 'l' || d == 'L')
{
size_t b = 0;
while (b < s.size() && s[b] == c)
{
++b;
}
return b == 0 ? s : s.substr(b);
}
else if (d == 'r' || d == 'R')
{
size_t e = s.size();
while (e > 0 && s[e - 1] == c)
{
--e;
}
return e == s.size() ? s : s.substr(0, e);
}
else
{
size_t b = 0, e = s.size();
while (b < s.size() && s[b] == c)
{
++b;
}
if (b == s.size())
{
return std::string();
}
while (e > 0 && s[e - 1] == c)
{
--e;
}
return (e - b == s.size()) ? s : s.substr(b, e - b);
}
}
static inline auto strip(const std::string& s, const std::string& c, char d = 'b') -> std::string
{
if (s.empty())
{
return std::string();
}
std::array<char, 256> bs = {0};
for (char i : c)
{
bs[static_cast<uint8_t>(i)] = 1;
}
if (d == 'l' || d == 'L')
{
size_t b = 0;
while (b < s.size() && bs[static_cast<uint8_t>(s[b])])
{
++b;
}
return b == 0 ? s : s.substr(b);
}
else if (d == 'r' || d == 'R')
{
size_t e = s.size();
while (e > 0 && bs[static_cast<uint8_t>(s[e - 1])])
{
--e;
}
return e == s.size() ? s : s.substr(0, e);
}
else
{
size_t b = 0, e = s.size();
while (b < s.size() && bs[static_cast<uint8_t>(s[b])])
{
++b;
}
if (b == s.size())
{
return std::string();
}
while (e > 0 && bs[static_cast<uint8_t>(s[e - 1])])
{
--e;
}
return (e - b == s.size()) ? s : s.substr(b, e - b);
}
}
static inline auto to_lower(std::string& str)
{
std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { return tolower(c); });
}
static inline auto to_lower(std::wstring& str)
{
std::transform(str.begin(), str.end(), str.begin(), [](wchar_t c) { return towlower(c); });
}
template<typename K, typename V>
inline auto dbg(const std::pair<K, V>& x) -> std::string
{
std::string fs;
fs.reserve(64);
detail::dbg(x, fs);
return fs;
}
template<typename T>
inline auto dbg(const T& beg, const T& end, char c1, char c2) -> std::string
{
std::string fs;
fs.reserve(128);
detail::dbg(beg, end, c1, c2, fs);
return fs;
}
template<typename T>
inline auto dbg(const std::vector<T>& v) -> std::string
{
return dbg(v.begin(), v.end(), '[', ']');
}
template<typename T>
inline auto dbg(const std::set<T>& v) -> std::string
{
return dbg(v.begin(), v.end(), '{', '}');
}
template<typename K, typename V>
inline auto dbg(const std::map<K, V>& v) -> std::string
{
return dbg(v.begin(), v.end(), '{', '}');
}
template<typename T>
inline auto dbg(const std::unordered_set<T>& v) -> std::string
{
return dbg(v.begin(), v.end(), '{', '}');
}
template<typename K, typename V>
inline auto dbg(const std::unordered_map<K, V>& v) -> std::string
{
return dbg(v.begin(), v.end(), '{', '}');
}
};
} // namespace ark
//namespace {
//// internal functions
//struct NoCaseCompareChar
//{
// bool operator()(char l, char r) const
// {
// bool bEqual = (l == r);
// if (bEqual)
// {
// return true;
// }
// if (isalpha(static_cast<unsigned char>(l)))
// {
// if (isupper(static_cast<unsigned char>(l)))
// {
// return l == toupper(r);
// }
// else
// {
// return l == tolower(r);
// }
// }
//
// return bEqual;
// }
// bool operator()(wchar_t l, wchar_t r) const
// {
// bool bEqual = (l == r);
//
// if (bEqual)
// {
// return true;
// }
//
// if (iswalpha(l))
// {
// if (iswupper(l))
// {
// return l == static_cast<wchar_t>(towupper(r));
// }
// else
// {
// return l == static_cast<wchar_t>(towlower(r));
// }
// }
//
// return bEqual;
// }
//} no_case_compare_char;
//
//template<typename T>
//inline bool stringUtil_StartsWith(const T& str, const T& pattern, bool case_sensitive)
//{
// // H_ASSERT( str.length() >= pattern.length() );
// if (str.length() < pattern.length())
// {
// return false;
// }
//
// if (case_sensitive)
// {
// return std::equal(pattern.begin(), pattern.end(), str.begin());
// }
// else
// {
// return std::equal(pattern.begin(), pattern.end(), str.begin(), no_case_compare_char);
// }
//}
//
//template<typename T>
//bool stringUtil_EndsWith(const T& str, const T& pattern, bool case_sensitive)
//{
// // H_ASSERT( str.length() >= pattern.length() );
// if (str.length() < pattern.length())
// {
// return false;
// }
//
// if (case_sensitive)
// {
// return equal(pattern.rbegin(), pattern.rend(), str.rbegin());
// }
// else
// {
// return equal(pattern.rbegin(), pattern.rend(), str.rbegin(), no_case_compare_char);
// }
//}
//
//template<typename T>
//struct nocase_equal_char
//{
// T m_c;
// nocase_equal_char(T c)
// : m_c(c)
// {
// }
// bool operator()(T c)
// {
// return no_case_compare_char(m_c, c);
// }
//};
//
//template<typename T>
//inline bool stringUtil_contains(const T& str, typename T::value_type c, bool case_sensitive)
//{
// if (case_sensitive)
// {
// return str.find(c, 0) != T::npos;
// }
// else
// {
// return str.end() != std::find_if(str.begin(), str.end(), nocase_equal_char<typename T::value_type>(c));
// }
//}
//template<typename T>
//inline bool stringUtil_contains(const T& strL, const T& strR, bool case_sensitive)
//{
// if (case_sensitive)
// {
// return strL.end() != std::search(strL.begin(), strL.end(), strR.begin(), strR.end());
// }
// else
// {
// return strL.end() != std::search(strL.begin(), strL.end(), strR.begin(), strR.end(), no_case_compare_char);
// }
//}
//
//template<typename _StringType>
//inline void stringUtil_trim_charptr(_StringType& str, typename _StringType::const_pointer delims, bool left, bool right)
//{
// if (str.empty())
// {
// return;
// }
//
// size_t stop_pos = (size_t)str.size() - 1; // included
// if (right)
// {
// stop_pos = str.find_last_not_of(delims);
// }
//
// if (stop_pos == _StringType::npos)
// {
// str = _StringType();
// return;
// }
//
// size_t start_pos = 0; // included
// if (left)
// {
// start_pos = str.find_first_not_of(delims);
// }
//
// if (start_pos == 0 && stop_pos == str.size() - 1)
// {
// return;
// }
//
// str = _StringType(str.data() + start_pos, stop_pos + 1 - start_pos);
//}
//
//template<typename _StringType>
//inline void stringUtil_trim_string(_StringType& str, const _StringType& delims, bool left, bool right)
//{
// if (str.empty())
// {
// return;
// }
//
// if (str.empty())
// {
// return;
// }
//
// size_t stop_pos = (size_t)str.size() - 1; // included
// if (right)
// {
// stop_pos = str.find_last_not_of(delims);
// }
//
// if (stop_pos == _StringType::npos)
// {
// str = _StringType();
// return;
// }
//
// size_t start_pos = 0; // included
// if (left)
// {
// start_pos = str.find_first_not_of(delims);
// }
//
// if (start_pos == 0 && stop_pos == str.size() - 1)
// {
// return;
// }
//
// str = _StringType(str.data() + start_pos, stop_pos + 1 - start_pos);
//}
//
//template<typename _StringVector, typename StringType, typename _DelimType>
//inline void _stringUtilSplit(
// _StringVector& ret, const StringType& str, const _DelimType& delims, unsigned int maxSplits)
//{
// unsigned int numSplits = 0;
//
// // Use STL methods
// size_t start, pos;
// start = 0;
//
// do
// {
// pos = str.find_first_of(delims, start);
//
// if (pos == start)
// {
// ret.push_back(StringType());
// start = pos + 1;
// }
// else if (pos == StringType::npos || (maxSplits && numSplits + 1 == maxSplits))
// {
// // Copy the rest of the std::string
// ret.push_back(StringType());
// *(ret.rbegin()) = StringType(str.data() + start, str.size() - start);
// break;
// }
// else
// {
// // Copy up to delimiter
// // ret.push_back( str.substr( start, pos - start ) );
// ret.push_back(StringType());
// *(ret.rbegin()) = StringType(str.data() + start, pos - start);
// start = pos + 1;
// }
//
// ++numSplits;
//
// } while (pos != StringType::npos);
//}
//
//template<typename _SliceVector, typename StringType, typename _DelimType>
//void _stringUtilSplitStringToSliceVector(
// _SliceVector& ret, const StringType& str, const _DelimType& delims, unsigned int maxSplits)
//{
// unsigned int numSplits = 0;
//
// // Use STL methods
// size_t start, pos;
// start = 0;
//
// do
// {
// pos = str.find_first_of(delims, start);
//
// if (pos == start)
// {
// ret.push_back(ark::AFSlice());
// start = pos + 1;
// }
// else if (pos == StringType::npos || (maxSplits && numSplits + 1 == maxSplits))
// {
// // Copy the rest of the std::string
// ret.push_back(ark::AFSlice(str.data() + start, str.size() - start));
// break;
// }
// else
// {
// // Copy up to delimiter
// // ret.push_back( str.substr( start, pos - start ) );
// ret.push_back(ark::AFSlice(str.data() + start, pos - start));
// start = pos + 1;
// }
//
// ++numSplits;
//
// } while (pos != StringType::npos);
//}
//
//template<typename StringType, typename _DelimType>
//inline void _stringUtilSplitStringToSlice(
// const StringType& str, const _DelimType& delims, ark::AFSlice* ret, size_t& slices_count)
//{
// unsigned int numSplits = 0;
//
// // Use STL methods
// size_t start, pos;
// start = 0;
//
// do
// {
// pos = str.find_first_of(delims, start);
//
// if (pos == start)
// {
// ret[numSplits++] = ark::AFSlice();
// start = pos + 1;
// }
// else if (pos == StringType::npos || ((numSplits + 1) == slices_count))
// {
// // Copy the rest of the std::string
// ret[numSplits++] = (ark::AFSlice(str.data() + start, str.size() - start));
// break;
// }
// else
// {
// // Copy up to delimiter
// // ret.push_back( str.substr( start, pos - start ) );
// ret[numSplits++] = (ark::AFSlice(str.data() + start, pos - start));
// start = pos + 1;
// }
// } while (pos != StringType::npos);
//
// slices_count = numSplits;
//}
//
//inline void _stringUtilSplitSliceToSlice(
// const ark::AFSlice& str, const char& delim, std::vector<ark::AFSlice>& ret, unsigned int maxSplits)
//{
// // Use STL methods
// size_t start, pos;
// start = 0;
//
// const char* p = NULL;
// do
// {
// // fix strchr compile warning
//#ifdef ARK_PLATFORM_WIN
// p = (const char*)memchr(start + const_cast<char*>(str.data()), delim, str.size() - start);
//#else
// p = (const char*)memchr(start + str.data(), delim, str.size() - start);
//#endif
//
// if (!p || p >= str.data() + str.size() || ((maxSplits) && (ret.size() + 1 == maxSplits)))
// {
// ret.push_back(ark::AFSlice(str.data() + start, str.size() - start));
// break;
// }
//
// pos = p - str.data();
//
// if (pos == start)
// {
// ret.push_back(ark::AFSlice());
// start = pos + 1;
// }
// else
// {
// ret.push_back(ark::AFSlice(str.data() + start, pos - start));
// start = pos + 1;
// }
// } while (p);
//}
//
//inline void _stringUtilSplitSliceToSlice(
// const ark::AFSlice& str, const char& delim, ark::AFSlice* ret, size_t& slices_count)
//{
// unsigned int numSplits = 0;
//
// // Use STL methods
// size_t start, pos;
// start = 0;
//
// const char* p = NULL;
// do
// {
// // fix strchr compile warning
//#ifdef ARK_PLATFORM_WIN
// p = (const char*)memchr(start + const_cast<char*>(str.data()), delim, str.size() - start);
//#else
// p = (const char*)memchr(start + str.data(), delim, str.size() - start);
//#endif
// if (!p || p >= str.data() + str.size() || (numSplits == slices_count - 1))
// {
// ret[numSplits++] = (ark::AFSlice(str.data() + start, str.size() - start));
// break;
// }
//
// pos = p - str.data();
//
// if (pos == start)
// {
// ret[numSplits++] = ark::AFSlice();
// start = pos + 1;
// }
// else
// {
// ret[numSplits++] = (ark::AFSlice(str.data() + start, pos - start));
// start = pos + 1;
// }
// } while (p);
//
// slices_count = numSplits;
//}
//
//template<typename StringType>
//inline void stringUtil_Split(const StringType& src, StringType& left, StringType& right,
// typename StringType::const_pointer pDelims, size_t nDelimsLength)
//{
// typename StringType::const_iterator iter = find_first_of(src.begin(), src.end(), pDelims, pDelims + nDelimsLength);
// if (src.end() == iter)
// {
// return;
// }
//
// left.assign(src.begin(), iter);
// iter++;
// right.assign(iter, src.end());
//}
//
//template<typename _String>
//inline void _replace(_String& str, const _String& needle, const _String& new_value, size_t start_pos /* = 0*/,
// int replace_count /* = -1*/)
//{
// if (0 == replace_count)
// {
// return;
// }
//
// size_t i = 0;
// size_t pos = str.find(needle, start_pos);
// while (pos != _String::npos)
// {
// str.replace(pos, needle.size(), new_value);
// pos = str.find(needle, pos);
// if (++i >= (size_t)(replace_count))
// {
// break;
// }
// }
//}
//
//inline int php_htoi(const char* s)
//{
// int value;
// int c;
//
// c = ((const unsigned char*)s)[0];
// if (isupper(c))
// {
// c = tolower(c);
// }
// value = (c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10) * 16;
//
// c = ((const unsigned char*)s)[1];
// if (isupper(c))
// {
// c = tolower(c);
// }
// value += c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10;
//
// return (value);
//}
//
//} // namespace
//
//namespace ark {
//
//// Copy from Qihoo360/simcc project
//// @see https://github.com/Qihoo360/simcc/blob/master/simcc/string_util.h
//
//class AFStringUtils
//{
//public:
// static void Trim(std::string& str, bool left = true, bool right = true)
// {
// static const std::string delims("\0 \t\r\n\v", 6);
// Trim(str, delims, left, right);
// }
//
// static void Trim(std::wstring& str, bool left = true, bool right = true)
// {
// static const std::wstring delims(L"\0 \t\r\n\v", 6);
// Trim(str, delims, left, right);
// }
//
// static void Trim(std::string& str, const std::string& delims, bool left = true, bool right = true)
// {
// stringUtil_trim_string(str, delims, left, right);
// }
//
// static void Trim(std::wstring& str, const std::wstring& delims, bool left = true, bool right = true)
// {
// stringUtil_trim_string(str, delims, left, right);
// }
//
// static void Trim(std::string& str, const char* delims, bool left = true, bool right = true)
// {
// stringUtil_trim_charptr(str, delims, left, right);
// }
// static void Trim(std::wstring& str, const wchar_t* delims, bool left = true, bool right = true)
// {
// stringUtil_trim_charptr(str, delims, left, right);
// }
//
// static void TrimLeft(std::string& str)
// {
// Trim(str, true, false);
// }
//
// static void TrimLeft(std::wstring& str)
// {
// Trim(str, true, false);
// }
//
// static void TrimLeft(std::string& str, const std::string& delims)
// {
// Trim(str, delims, true, false);
// }
//
// static void TrimLeft(std::wstring& str, const std::wstring& delims)
// {
// Trim(str, delims, true, false);
// }
//
// static void TrimLeft(std::string& str, const char* delims)
// {
// Trim(str, delims, true, false);
// }
//
// static void TrimLeft(std::wstring& str, const wchar_t* delims)
// {
// Trim(str, delims, true, false);
// }
//
// static void TrimRight(std::string& str)
// {
// Trim(str, false, true);
// }
//
// static void TrimRight(std::wstring& str)
// {
// Trim(str, false, true);
// }
//
// static void TrimRight(std::string& str, const std::string& delims)
// {
// Trim(str, delims, false, true);
// }
//
// static void TrimRight(std::wstring& str, const std::wstring& delims)
// {
// Trim(str, delims, false, true);
// }
//
// static void TrimRight(std::string& str, const char* delims)
// {
// Trim(str, delims, false, true);
// }
//
// static void TrimRight(std::wstring& str, const wchar_t* delims)
// {
// Trim(str, delims, false, true);
// }
//
// // @brief trim a char
// template<typename _StringType>
// static void Trim(_StringType& str, char c, bool left = true, bool right = true)
// {
// if (str.empty())
// {
// return;
// }
//
// int stop_pos = (int)str.size() - 1; // included
// if (right)
// {
// for (; stop_pos >= 0; --stop_pos)
// {
// if (str[stop_pos] != c)
// {
// break;
// }
// }
// }
//
// if (stop_pos < 0)
// {
// str = _StringType();
// return;
// }
//
// int start_pos = 0; // included
// if (left)
// {
// for (; start_pos <= stop_pos; ++start_pos)
// {
// if (str[start_pos] != c)
// {
// break;
// }
// }
// }
//
// if (start_pos == 0 && stop_pos == (int)str.size() - 1)
// {
// return;
// }
//
// str = _StringType(str.data() + start_pos, stop_pos + 1 - start_pos);
// }
//
// template<typename _StringType>
// static void TrimLeft(_StringType& str, char c)
// {
// Trim(str, c, true, false);
// }
//
// template<typename _StringType>
// static void TrimRight(_StringType& str, char c)
// {
// Trim(str, c, false, true);
// }
//
// // @brief Replaces a section equaling to <code>needle</code> of the current string with the new substring
// // <code>new_value</code>
// // @param string & str [in,out], -
// // @param const string & needle -
// // @param const string & new_value -
// // @param string::size_type start_pos -
// // @param int replace_count - If it is -1, replaces all the <code>needle</code> by <code>new_value</code>
// // @return void -
// static void Replace(std::string& str, const std::string& needle, const std::string& new_value, size_t start_pos = 0,
// int replace_count = -1)
// {
// return _replace(str, needle, new_value, start_pos, replace_count);
// }
//
// static void Replace(std::wstring& str, const std::wstring& needle, const std::wstring& new_value,
// size_t start_pos = 0, int replace_count = -1)
// {
// return _replace(str, needle, new_value, start_pos, replace_count);
// }
//
// // Returns a StringVector that contains all the substrings delimited
// // by any of the characters in the passed <code>delims</code> argument.
// // @param vec[out], the result substrings are stored here.
// // @param delims A list of delimiter characters to split by
// // @param max_splits The maximum number of splits to perform (0 for unlimited splits). If this
// // parameters is > 0, the splitting process will stop after this many splits, left to right.
// static void Split(std::vector<std::string>& ret, const std::string& str, const std::string& delims = "\t\n ",
// unsigned int max_splits = 0)
// {
// _stringUtilSplit(ret, str, delims, max_splits);
// }
//
// static void Split(std::vector<std::wstring>& ret, const std::wstring& str, const std::wstring& delims = L"\t\n ",
// unsigned int max_splits = 0)
// {
// _stringUtilSplit(ret, str, delims, max_splits);
// }
//
// static void Split(std::vector<std::string>& ret, const std::string& str, const std::string::value_type& delims,
// unsigned int max_splits = 0)
// {
// _stringUtilSplit(ret, str, delims, max_splits);
// }
//
// static void Split(std::vector<std::wstring>& ret, const std::wstring& str, const std::wstring::value_type& delims,
// unsigned int max_splits = 0)
// {
// _stringUtilSplit(ret, str, delims, max_splits);
// }
//
// static void Split(std::vector<AFSlice>& ret, const std::string& str, int delims, unsigned int max_splits = 0)
// {
// _stringUtilSplitStringToSliceVector(ret, str, delims, max_splits);
// }
//
// static void Split(std::vector<AFSlice>& ret, const std::string& str, const std::string& delims = "\t\n ",
// unsigned int max_splits = 0)
// {
// _stringUtilSplitStringToSliceVector(ret, str, delims, max_splits);
// }
//
// // @brief
// // <code>
// // std::string s = "a|b|c|d|e";
// // AFSlice v[2];
// // Split(s, '|', v, 2); //after Split, v[0]=="a", v[1] == "b|c|d|e", vc == 2
// // </code>
// //
// // <code>
// // std::string s = "a|b|c";
// // AFSlice v[8];
// // Split(s, '|', v, 8); //after Split, v[0]=="a", v[1] == "b", v[2] == "c", vc == 3
// // </code>
// // @param const std::string & str -
// // @param int delims -
// // @param[out] AFSlice slices[] -
// // @param[in,out] size_t & slice_count -
// // @return void -
// static void Split(const std::string& str, int delims, AFSlice slices[], size_t& slice_count)
// {
// _stringUtilSplitStringToSlice(str, delims, slices, slice_count);
// }
//
// static void Split(const std::string& str, const std::string& delims, AFSlice slices[], size_t& slice_count)
// {
// _stringUtilSplitStringToSlice(str, delims, slices, slice_count);
// }
//
// static void Split(const AFSlice& str, int delims, AFSlice slices[], size_t& slice_count)
// {
// _stringUtilSplitSliceToSlice(str, delims, slices, slice_count);
// }
//
// static void Split(const AFSlice& str, int delims, std::vector<AFSlice>& slices, unsigned int max_splits = 0)
// {
// _stringUtilSplitSliceToSlice(str, delims, slices, max_splits);
// }
//
// /**
// * Split a std::string into tow strings using the special characters .
// * e.g. src="abc, hello world " if cutset="," then left="abc", right=" hello world "
// * @warning If any of delimiters was found, we just return, left std::string and right std::string will not be
// * changed.
// * @param src The source std::string
// * @param left The left std::string separated by cutset
// * @param left The right std::string separated by cutset
// * @param cutset A list of delimiter characters to split by. We only use the first one when come up against a
// * delimiter
// */
// static void Split(
// const std::string& src, std::string& left, std::string& right, const std::string& delims = "\t\n ")
// {
// Split(src, left, right, delims.c_str());
// }
//
// static void Split(
// const std::wstring& src, std::wstring& left, std::wstring& right, const std::wstring& delims = L"\t\n ")
// {
// Split(src, left, right, delims.c_str());
// }
//
// static void Split(const std::string& src, std::string& left, std::string& right, const char* delims = "\t\n ")
// {
// stringUtil_Split(src, left, right, delims, strlen(delims));
// }
//
// static void Split(
// const std::wstring& src, std::wstring& left, std::wstring& right, const wchar_t* delims = L"\t\n ")
// {
// stringUtil_Split(src, left, right, delims, wcslen(delims));
// }
//
// template<typename _SourceStringType, typename _SubStringType>
// static void Explode(const _SourceStringType& source, const _SourceStringType& cutset,
// std::vector<_SubStringType>& return_value, int limit = -1)
// {
// // TODO
// }
// static void ToUpper(std::string& str)
// {
// std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { return toupper(c); });
// }
//
// static void ToUpper(std::wstring& str)
// {
// std::transform(str.begin(), str.end(), str.begin(), [](wchar_t c) { return towupper(c); });
// }
//
// // std::string compare
// // @param case_sensitive true If we compare the std::string with case sensitively
// static bool Equals(const std::string& str1, const std::string& str2, bool case_sensitive = true)
// {
// if (case_sensitive)
// {
// return (str1 == str2) ? true : false;
// }
// else
// {
// return EqualsIgnoreCase(str1, str2);
// }
// }
//
// // @brief std::string compare ignoring case sensitively
// static bool EqualsIgnoreCase(const std::string& str1, const std::string& str2)
// {
// if (str1.length() == str2.length())
// {
// return std::equal(str1.begin(), str1.end(), str2.begin(), no_case_compare_char);
// }
// return false;
// }
//
// // @brief Returns whether the std::string begins with the pattern passed in.
// // @param[in] pattern The pattern to compare with.
// // @param[in] case_sensitive true case sensitive, false ignore the case
// static bool StartsWith(const std::string& str, const std::string& pattern, bool case_sensitive = true)
// {
// return stringUtil_StartsWith(str, pattern, case_sensitive);
// }
//
// static bool StartsWith(const std::wstring& str, const std::wstring& pattern, bool case_sensitive = true)
// {
// return stringUtil_StartsWith(str, pattern, case_sensitive);
// }
//
// // @brief Returns whether the std::string ends with the pattern passed in.
// // @param[in] pattern The pattern to compare with.
// // @param[in] case_sensitive true case sensitive, false ignore the case
// static bool EndsWith(const std::string& str, const std::string& pattern, bool case_sensitive = true)
// {
// return stringUtil_EndsWith(str, pattern, case_sensitive);
// }
//
// static bool EndsWith(const std::wstring& str, const std::wstring& pattern, bool case_sensitive = true)
// {
// return stringUtil_EndsWith(str, pattern, case_sensitive);
// }
//
// // Simple pattern-matching routine allowing a wild card pattern.
// // @param str String to test
// // @param pattern Pattern to match against; which can include simple '*' wildcards
// // @param case_sensitive Whether the match is case sensitive or not
// static bool Match(const std::string& str, const std::string& pattern, bool case_sensitive = true)
// {
// std::string tmpStr = str;
// std::string tmpPattern = pattern;
//
// if (!case_sensitive)
// {
// AFStringUtils::ToLower(tmpStr);
// AFStringUtils::ToLower(tmpPattern);
// }
//
// std::string::const_iterator strIt = tmpStr.begin();
// std::string::const_iterator patIt = tmpPattern.begin();
// std::string::const_iterator lastWildCardIt = tmpPattern.end();
//
// while (strIt != tmpStr.end() && patIt != tmpPattern.end())
// {
// if (*patIt == '*')
// {
// lastWildCardIt = patIt;
// // Skip over looking for next character
// ++patIt;
//
// if (patIt == tmpPattern.end())
// {
// // Skip right to the end since * matches the entire rest of the std::string
// strIt = tmpStr.end();
// }
// else
// {
// // scan until we find next pattern character
// while (strIt != tmpStr.end() && *strIt != *patIt)
// {
// ++strIt;
// }
// }
// }
// else
// {
// if (*patIt != *strIt)
// {
// if (lastWildCardIt != tmpPattern.end())
// {
// // The last wildcard can match this incorrect sequence
// // rewind pattern to wildcard and keep searching
// patIt = lastWildCardIt;
// lastWildCardIt = tmpPattern.end();
// }
// else
// {
// // no wildwards left
// return false;
// }
// }
// else
// {
// ++patIt;
// ++strIt;
// }
// }
// }
//
// // If we reached the end of both the pattern and the std::string, we succeeded
// if (patIt == tmpPattern.end() && strIt == tmpStr.end())
// {
// return true;
// }
// else
// {
// return false;
// }
// }
//
// static bool Match(const std::wstring& str, const std::wstring& pattern, bool case_sensitive = true)
// {
// std::wstring tmpStr = str;
// std::wstring tmpPattern = pattern;
//
// if (!case_sensitive)
// {
// AFStringUtils::ToLower(tmpStr);
// AFStringUtils::ToLower(tmpPattern);
// }
//
// std::wstring::const_iterator strIt = tmpStr.begin();
// std::wstring::const_iterator patIt = tmpPattern.begin();
// std::wstring::const_iterator lastWildCardIt = tmpPattern.end();
//
// while (strIt != tmpStr.end() && patIt != tmpPattern.end())
// {
// if (*patIt == L'*')
// {
// lastWildCardIt = patIt;
// // Skip over looking for next character
// ++patIt;
//
// if (patIt == tmpPattern.end())
// {
// // Skip right to the end since * matches the entire rest of the std::string
// strIt = tmpStr.end();
// }
// else
// {
// // scan until we find next pattern character
// while (strIt != tmpStr.end() && *strIt != *patIt)
// {
// ++strIt;
// }
// }
// }
// else
// {
// if (*patIt != *strIt)
// {
// if (lastWildCardIt != tmpPattern.end())
// {
// // The last wildcard can match this incorrect sequence
// // rewind pattern to wildcard and keep searching
// patIt = lastWildCardIt;
// lastWildCardIt = tmpPattern.end();
// }
// else
// {
// // no wildwards left
// return false;
// }
// }
// else
// {
// ++patIt;
// ++strIt;
// }
// }
// }
//
// // If we reached the end of both the pattern and the std::string, we succeeded
// if (patIt == tmpPattern.end() && strIt == tmpStr.end())
// {
// return true;
// }
// else
// {
// return false;
// }
// }
//
// // @brief Reports whether a char or a substr is within mother
// // @param mother, the mother std::string to test
// // @param pattern, the pattern std::string or char to find
// // @param[in] case_sensitive true case sensitive, false ignore the case
// // @return bool, return true if the occurrence of pattern within the motherStr or false
// static bool Contains(const std::string& mother, char pattern, bool case_sensitive = true)
// {
// return stringUtil_contains(mother, pattern, case_sensitive);
// }
//
// static bool Contains(const std::wstring& mother, wchar_t pattern, bool case_sensitive = true)
// {
// return stringUtil_contains(mother, pattern, case_sensitive);
// }
//
// static bool Contains(const std::string& mother, const std::string& pattern, bool case_sensitive = true)
// {
// return stringUtil_contains(mother, pattern, case_sensitive);
// }
//
// static bool Contains(const std::wstring& mother, const std::wstring& pattern, bool case_sensitive = true)
// {
// return stringUtil_contains(mother, pattern, case_sensitive);
// }
//
// // query whether parameter std::string is a float number std::string or not.
// static bool IsFloatNumber(std::string& s)
// {
// if (s.find('.') != std::string::npos || s.find('e') != std::string::npos || s.find('E') != std::string::npos)
// {
// return true;
// }
//
// return false;
// }
//
// static bool IsDigit(const std::string& str)
// {
// if (str.empty())
// {
// return false;
// }
//
// std::string::const_iterator start = str.begin();
// if (*start == '-')
// {
// ++start;
// }
//
// return (std::all_of(start, str.end(), [](unsigned char c) { return isdigit(c); }));
// }
//
// // URL encode & decode
// static bool URLEncode(const char* url, size_t url_len, char* edcoded_url, size_t& edcoded_url_len)
// {
// static unsigned char hexchars[] = "0123456789ABCDEF";
//
// unsigned char c;
// unsigned char *to, *start, *to_end;
// unsigned char const *from, *end;
//
// start = to = (unsigned char*)(edcoded_url);
// to_end = to + edcoded_url_len;
//
// from = (unsigned char const*)url;
// end = from + url_len;
//
// while (from < end)
// {
// c = *from++;
//
// if (c == ' ')
// {
// if (to < to_end)
// {
// *to++ = '+';
// }
// else
// {
// return false;
// }
// }
// else if ((c < '0' && c != '-' && c != '.') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a' && c != '_') ||
// (c > 'z'))
// {
// if (to + 2 < to_end)
// {
// to[0] = '%';
// to[1] = hexchars[c >> 4];
// to[2] = hexchars[c & 15];
// to += 3;
// }
// else
// {
// return false;
// }
// }
// else
// {
// if (to < to_end)
// {
// *to++ = c;
// }
// else
// {
// return false;
// }
// }
// }
// *to = 0;
// edcoded_url_len = (to - start);
// return true;
// }
//
// static std::string URLEncode(const std::string& str)
// {
// std::string out;
// URLEncode(str, out);
// return out;
// }
//
// static void URLEncode(const std::string& str, std::string& out)
// {
// URLEncode(str.data(), str.size(), out);
// }
//
// static void URLEncode(const char* url, size_t url_len, std::string& out)
// {
// size_t encoded_url_len = url_len * 3;
// out.resize(encoded_url_len);
// URLEncode(url, url_len, &out[0], encoded_url_len);
// out.resize(encoded_url_len);
// }
//
// static std::string URLDecode(const std::string& str)
// {
// std::string out;
// URLDecode(str, out);
// return out;
// }
//
// static void URLDecode(const std::string& str, std::string& out)
// {
// URLDecode(str.data(), str.size(), out);
// }
//
// static void URLDecode(const char* encoded_url, size_t encoded_url_len, std::string& out)
// {
// out.resize(encoded_url_len);
// size_t decoded_url_len = encoded_url_len;
// URLDecode(encoded_url, encoded_url_len, &out[0], decoded_url_len);
// out.resize(decoded_url_len);
// }
//
// static void URLDecode(const char* encoded_url, size_t encoded_url_len, char* decoded_url, size_t& decoded_url_len)
// {
// char* dest = decoded_url;
// const char* data = encoded_url;
// int len = (int)encoded_url_len;
// while (len--)
// {
// if (*data == '+')
// {
// *dest = ' ';
// }
// else if (*data == '%' && len >= 2 && isxdigit((int)*(data + 1)) && isxdigit((int)*(data + 2)))
// {
// *dest = (char)php_htoi(data + 1);
// data += 2;
// len -= 2;
// }
// else
// {
// *dest = *data;
// }
// data++;
// dest++;
// }
//
// decoded_url_len = dest - decoded_url;
// }
//
// static void URLDecode(std::string& str)
// {
// URLDecode(str, str);
// }
//};
//
//} // namespace ark
| 28.800599 | 122 | 0.474084 | [
"vector",
"transform"
] |
816c02f084c333ba248788e497dd446abc6bb8f5 | 14,847 | hpp | C++ | wood.hpp | r-lyeh/wood | 8607088f2d13e87b6ab2f4f8fae9a92f47a6d5bf | [
"Zlib"
] | null | null | null | wood.hpp | r-lyeh/wood | 8607088f2d13e87b6ab2f4f8fae9a92f47a6d5bf | [
"Zlib"
] | null | null | null | wood.hpp | r-lyeh/wood | 8607088f2d13e87b6ab2f4f8fae9a92f47a6d5bf | [
"Zlib"
] | null | null | null | /*
* XML DOM parser/XPath queries/tree builder class
* Copyright (c) 2010 Mario 'rlyeh' Rodriguez
*
* 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.
* To do:
* - SAX parser
* - subtree insertion, removal and reallocation (doable thru XPath syntax?)
* - rlyeh ~~ listening to The Cure / A forest (live 1984)
*/
#pragma once
#include <algorithm>
#include <sstream>
#include <string>
#include <vector>
#include "kptree/tree.hh"
#include "kptree/tree_util.hh"
#include "pugixml/pugixml.hpp"
namespace wood
{
template< class T >
class tree : public kptree::tree<T>
{
public:
typedef typename kptree::tree<T>::iterator iterator;
//typedef typename kptree::tree<T>::const_iterator const_iterator;
typedef typename kptree::tree<T>::sibling_iterator sibling_iterator;
//typedef typename kptree::tree<T>::const_sibling_iterator const_sibling_iterator;
protected:
iterator root, cursor;
std::vector< iterator > depth;
public:
tree( const T &root_item = T() )
{
root = this->insert( this->begin(), root_item );
depth.push_back( root );
cursor = root;
}
bool find( const T &name )
{
return ( cursor = std::find( this->begin(), this->end(), name ) ) != this->end();
}
typename tree<T>::iterator found() const
{
return cursor;
}
typename tree<T>::iterator at( const T &name )
{
return std::find( this->begin(), this->end(), name );
}
tree<T>& push( const T &name )
{
depth.push_back( this->append_child( depth.back(), name ) );
return *this;
}
tree<T>& node( const T &name )
{
this->append_child( depth.back(), name );
return *this;
}
tree<T>& back()
{
if( depth.size() > 1 ) depth.pop_back();
return *this;
}
void move( const T &from_id, const T &to_id )
{
iterator from = std::find( this->begin(), this->end(), from_id );
iterator to = std::find( this->begin(), this->end(), to_id );
if( parent(from) == to )
return; // already there
iterator temp = this->append_child( to );
this->move_ontop( temp, from );
}
std::string str() const
{
std::ostringstream oss;
kptree::print_tree_bracketed( *this, oss );
return oss.str();
}
// apply function to all nodes, including children
// example:
// tree<node> scene;
// scene.apply( [](node &n){ render(n); } );
template< typename FUNC >
void apply( const FUNC &f )
{
if( !this->empty() )
for( sibling_iterator it = this->begin(), end = this->end(); it != end; ++it )
apply_subtree( it, f );
}
protected:
template< typename FUNC >
void apply_subtree( const typename tree<T>::sibling_iterator &iRoot, const FUNC &f )
{
f( (*iRoot) );
if( this->number_of_children(iRoot) != 0 )
for( sibling_iterator it = this->begin(iRoot), end = this->end(iRoot); it != end; ++it )
apply_subtree( it, f );
}
};
namespace
{
template< typename T >
inline T as( const std::string &self ) {
T t;
if( std::istringstream(self) >> t )
return t;
bool is_true = self.size() && (self != "0") && (self != "false");
return (T)(is_true);
}
template<>
inline char as( const std::string &self ) {
return self.size() == 1 ? (char)(self[0]) : (char)(as<int>(self));
}
template<>
inline signed char as( const std::string &self ) {
return self.size() == 1 ? (signed char)(self[0]) : (signed char)(as<int>(self));
}
template<>
inline unsigned char as( const std::string &self ) {
return self.size() == 1 ? (unsigned char)(self[0]) : (unsigned char)(as<int>(self));
}
template<>
inline const char *as( const std::string &self ) {
return self.c_str();
}
template<>
inline std::string as( const std::string &self ) {
return self;
}
}
class string : public std::string
{
public:
// basic constructors
string() : std::string()
{}
string( const std::string &s ) : std::string( s )
{}
string( const char &c ) : std::string( 1, c )
{}
string( const char *cstr ) : std::string( cstr ? cstr : "" )
{}
template<size_t N>
string( const char (&cstr)[N] ) : std::string( cstr )
{}
string( const bool &val ) : std::string( val ? "true" : "false" )
{}
// constructor sugars
template< typename T >
string( const T &t ) : std::string() {
std::stringstream ss;
if( ss << /* std::boolalpha << */ t )
this->assign( ss.str() );
}
string( const float &t ) : std::string() {
std::stringstream ss;
if( ss << (long double)(t) )
this->assign( ss.str() );
}
string( const double &t ) : std::string() {
std::stringstream ss;
if( ss << (long double)(t) )
this->assign( ss.str() );
}
string( const long double &t ) : std::string() {
std::stringstream ss;
if( ss << (long double)(t) )
this->assign( ss.str() );
}
// conversion
template< typename T >
T as() const
{
return wood::as<T>(*this);
}
template< typename T >
operator T() const
{
return wood::as<T>(*this);
}
// assignment sugars
template< typename T >
string &operator=( const T &t ) {
this->assign( string(t) );
return *this;
}
};
class xml
{
public:
enum { verbose = false };
xml();
xml( const xml &t );
xml( const std::string &t );
xml &operator=( const xml &t );
// declarative construction
// push a level of depth, then set node
xml &push( const wood::string &key, const wood::string &text = wood::string(), const wood::string &comment = wood::string() );
xml &push( const pugi::xml_node &node );
// set node at current depth
xml &set( const wood::string &key, const wood::string &text = wood::string(), const wood::string &comment = wood::string() );
xml &set( const pugi::xml_node &node );
// set attribute for current node
xml &attrib( const wood::string &key, const wood::string &value );
xml &attrib( /*const*/ pugi::xml_attribute &attribute );
// pop a level of depth back
xml &back();
// XPath query api
template <typename T>
bool get( T &t, const std::string &XPath ) const
{
#ifdef PUGIXML_NO_EXCEPTIONS
wood::string result = pugi::xpath_query( XPath.c_str() ).evaluate_string( doc );
t = result.as<T>();
return true;
#else
try
{
std::string result = pugi::xpath_query( XPath.c_str() ).evaluate_string( doc );
t = result.as<T>();
return true;
}
catch( const pugi::xpath_exception &e )
{
std::cerr << "<wood/xml.hpp> says: error! Select failed: " << e.what() << std::endl;
}
catch( ... )
{
std::cerr << "<wood/xml.hpp> says: error! Exception raised!" << std::endl;
}
t = T();
return false;
#endif
}
template <typename T>
T get( const std::string &XPath ) const {
T t;
return get(t, XPath) ? t : T();
}
// XPath select api
typedef pugi::xpath_node_set selection;
selection select( const std::string &xpath ) const {
return doc.select_nodes( xpath.c_str() );
}
// serialization
std::string str() const;
void str( const std::string &data );
// iteration
// iterators
typedef pugi::xml_node node;
typedef std::vector<node> nodes;
typedef pugi::xml_node_iterator iterator; //iterators
typedef pugi::xml_attribute attribute; //attributes
typedef pugi::xml_attribute_iterator attribute_iterator; //attribute_iterators
iterator begin() const;
iterator end() const;
attribute_iterator attribute_begin() const;
attribute_iterator attribute_end() const;
#if 0
template< typename FUNC >
void apply( const FUNC &f ) const
{
auto root = doc.root();
for( auto it = root.first_child(); it; it = it.next_sibling() )
apply_subtree( it, f );
}
template< typename FUNC >
void apply( const FUNC &f )
{
auto root = doc.root();
for( auto it = root.first_child(); it; it = it.next_sibling() )
apply_subtree( it, f );
}
protected:
template< typename FUNC >
void apply_subtree( node &it, const FUNC &f ) const
{
f( it );
// auto node = it;
// int number_of_children = std::distance(node.begin(), node.end()));
for( auto jt = it.first_child(); jt; jt = jt.next_sibling() )
apply_subtree( jt, f );
}
template< typename FUNC >
void apply_subtree( node &it, const FUNC &f )
{
f( it );
// auto node = it;
// int number_of_children = std::distance(node.begin(), node.end()));
for( auto jt = it.first_child(); jt; jt = jt.next_sibling() )
apply_subtree( jt, f );
}
#endif
#if 1
public:
// xpath examples:
// "//*" whole tree
// "/Profile/Tools/Tool[@AllowRemote='true' and @DeriveCaptionFrom='lastparam']"
// "//Tool[contains(Description, 'build system')]"
// "//book[position()<=3]" Selects the first three book elements
// "//book[last()]" Selects the last book element
/*
<root>
<Dev>
<Emp>1</Emp>
<Floor>1</Floor>
<Salary>1200.4</Salary>
</Dev>
<Dev>
<Emp>2</Emp>
<Salary>3100.8</Salary>
</Dev>
<Dev>
<Emp>3</Emp>
<Floor>1</Floor>
</Dev>
</root>
*/
// "sum(/*/Dev/Salary[number(.) = number(.)])" sums all /dev/salary that are numeric
// Apply a lambda top-down to a region selected by xpath query
template< typename FUNC >
void forward( const std::string &xpath, const FUNC &fn ) const
{
auto selected = select( xpath );
for( auto &it : selected )
fn( it.node() );
}
template< typename FUNC >
void forward( const std::string &xpath, const FUNC &fn )
{
auto selected = select( xpath );
for( auto &it : selected )
fn( it.node() );
}
// Apply a lambda bottom-up to a region selected by xpath query
template< typename FUNC >
void backward( const std::string &xpath, const FUNC &fn ) const
{
auto selected = select( xpath );
for( size_t i = selected.size(); i-- > 0; )
fn( selected[i].node() );
}
template< typename FUNC >
void backward( const std::string &xpath, const FUNC &fn )
{
auto selected = select( xpath );
for( size_t i = selected.size(); i-- > 0; )
fn( selected[i].node() );
}
#endif
protected:
//details:
public:
pugi::xml_document doc;
protected:
pugi::xml_node latest;
std::vector< pugi::xml_node > parent;
void update_node( pugi::xml_node &node, const std::string &key, const std::string &text, const std::string &comment);
void update_node( pugi::xml_node &node, const pugi::xml_node &content );
};
bool is_empty( const xml::node &node );
bool is_null( const xml::node &node );
bool has_parent( const xml::node &node );
size_t has_children( const xml::node &node );
size_t has_siblings( const xml::node &node );
xml::nodes get_children( const xml::node &node );
xml::nodes get_siblings( const xml::node &node );
} //namespace wood
namespace
{
template <typename T>
inline std::ostream &operator<<( std::ostream &oss, const wood::tree<T> &scene ) {
return oss << scene.str(), oss;
}
}
| 30.115619 | 135 | 0.501718 | [
"render",
"vector"
] |
816c1b0fd72f1b61ef0420a96cd840f1e3d3172c | 6,307 | cpp | C++ | POMDPSolver/Despot/despot-master/examples/cpp_models/bridge/src/bridge.cpp | nesl/EngagementService | bb8dc5a58d2038ace6467bfbcf4d253680628f67 | [
"BSD-3-Clause"
] | null | null | null | POMDPSolver/Despot/despot-master/examples/cpp_models/bridge/src/bridge.cpp | nesl/EngagementService | bb8dc5a58d2038ace6467bfbcf4d253680628f67 | [
"BSD-3-Clause"
] | null | null | null | POMDPSolver/Despot/despot-master/examples/cpp_models/bridge/src/bridge.cpp | nesl/EngagementService | bb8dc5a58d2038ace6467bfbcf4d253680628f67 | [
"BSD-3-Clause"
] | null | null | null | #include "bridge.h"
#include <despot/solver/pomcp.h>
using namespace std;
namespace despot {
/* =============================================================================
* BridgeState class
* =============================================================================*/
BridgeState::BridgeState() :
position(0) {
}
BridgeState::BridgeState(int _position) :
position(_position) {
}
string BridgeState::text() const {
return "Man at " + to_string(position);
}
/* =============================================================================
* Bridge class
* =============================================================================*/
Bridge::Bridge() {
}
int Bridge::LEFT = 0;
int Bridge::RIGHT = 1;
int Bridge::HELP = 2;
int Bridge::BRIDGELENGTH = 10;
bool Bridge::Step(State& s, double random_num, int action, double& reward,
OBS_TYPE& obs) const {
BridgeState& state = static_cast<BridgeState&>(s);
bool terminal = false;
int& position = state.position;
obs = 1;
if (action == LEFT) {
reward = -1;
if (position > 0)
position--;
} else if (action == RIGHT) {
if (position < BRIDGELENGTH - 1) {
reward = -1;
position++;
} else {
reward = 0;
terminal = true;
}
} else { // HELP
reward = -20 - position;
terminal = true;
}
return terminal;
}
int Bridge::NumStates() const {
return BRIDGELENGTH;
}
int Bridge::NumActions() const {
return 3;
}
double Bridge::ObsProb(OBS_TYPE obs, const State& s, int a) const {
return obs == 1;
}
State* Bridge::CreateStartState(string type) const {
// return new BridgeState(Random::RANDOM.NextInt(2));
return new BridgeState(0); // Always start at the left end
}
Belief* Bridge::InitialBelief(const State* start, string type) const {
vector<State*> particles;
for (int pos = 0; pos <= 1; pos++) {
for (int i = 0; i < 100; i++) {
BridgeState* state = static_cast<BridgeState*>(Allocate(pos, 0.005));
state->position = pos;
particles.push_back(state);
}
}
return new ParticleBelief(particles, this);
}
void Bridge::PrintState(const State& state, ostream& out) const {
out << state.text() << endl;
}
void Bridge::PrintBelief(const Belief& belief, ostream& out) const {
}
void Bridge::PrintObs(const State& state, OBS_TYPE obs, ostream& out) const {
out << obs << endl;
}
;
void Bridge::PrintAction(int action, ostream& out) const {
if (action == LEFT) {
cout << "Move left" << endl;
} else if (action == RIGHT) {
cout << "Move right" << endl;
} else {
cout << "Call for help" << endl;
}
}
ScenarioLowerBound* Bridge::CreateScenarioLowerBound(string name,
string particle_bound_name) const {
if (name == "TRIVIAL") {
return new TrivialParticleLowerBound(this);
} else if (name == "RANDOM") {
return new RandomPolicy(this,
CreateParticleLowerBound(particle_bound_name));
} else if (name == "CALL_FOR_HELP" || name == "DEFAULT") {
return new BlindPolicy(this, HELP,
CreateParticleLowerBound(particle_bound_name));
} else {
cerr << "Unsupported lower bound algorithm: " << name << endl;
exit(1);
}
}
State* Bridge::Allocate(int state_id, double weight) const {
BridgeState* particle = memory_pool_.Allocate();
particle->state_id = state_id;
particle->weight = weight;
return particle;
}
State* Bridge::Copy(const State* particle) const {
BridgeState* new_particle = memory_pool_.Allocate();
*new_particle = *static_cast<const BridgeState*>(particle);
new_particle->SetAllocated();
return new_particle;
}
void Bridge::Free(State* particle) const {
memory_pool_.Free(static_cast<BridgeState*>(particle));
}
int Bridge::NumActiveParticles() const {
return memory_pool_.num_allocated();
}
Belief* Bridge::Tau(const Belief* belief, int action, OBS_TYPE obs) const {
static vector<double> probs = vector<double>(NumStates());
const vector<State*>& particles =
static_cast<const ParticleBelief*>(belief)->particles();
double sum = 0;
for (int i = 0; i < particles.size(); i++) {
BridgeState* state = static_cast<BridgeState*>(particles[i]);
int next_pos = state->position;
if (action == LEFT) {
next_pos--;
if (next_pos < 0)
next_pos = 0;
} else if (action == RIGHT) {
if (next_pos < BRIDGELENGTH - 1)
next_pos++;
else
continue;
}
double p = state->weight * (obs == 1);
probs[next_pos] += p;
sum += p;
}
vector<State*> new_particles;
for (int i = 0; i < NumStates(); i++) {
if (probs[i] > 0) {
BridgeState* new_particle = static_cast<BridgeState*>(Allocate(i));
new_particle->position = i;
new_particle->weight = probs[i] / sum;
new_particles.push_back(new_particle);
probs[i] = 0;
}
}
return new ParticleBelief(new_particles, this, NULL, false);
}
void Bridge::Observe(const Belief* belief, int action,
map<OBS_TYPE, double>& obss) const {
const vector<State*>& particles =
static_cast<const ParticleBelief*>(belief)->particles();
if (action == HELP)
return;
for (int i = 0; i < particles.size(); i++) {
State* particle = particles[i];
BridgeState* state = static_cast<BridgeState*>(particle);
if (!(state->position == BRIDGELENGTH - 1 && action == RIGHT)) {
obss[1] = 1.0;
break;
}
}
}
double Bridge::StepReward(const Belief* belief, int action) const {
const vector<State*>& particles =
static_cast<const ParticleBelief*>(belief)->particles();
double sum = 0;
for (int i = 0; i < particles.size(); i++) {
State* particle = particles[i];
BridgeState* state = static_cast<BridgeState*>(particle);
double reward = -1;
if (action == RIGHT && state->position == BRIDGELENGTH - 1) {
reward = 0;
} else if (action == HELP) {
reward = -20 - state->position;
}
sum += state->weight * reward;
}
return sum;
}
class BridgePOMCPPrior: public POMCPPrior {
public:
BridgePOMCPPrior(const DSPOMDP* model) :
POMCPPrior(model) {
}
void ComputePreference(const State& state) {
for (int a = 0; a < 3; a++) {
legal_actions_.push_back(a);
}
preferred_actions_.push_back(2);
}
};
POMCPPrior* Bridge::CreatePOMCPPrior(string name) const {
if (name == "UNIFORM") {
return new UniformPOMCPPrior(this);
} else if (name == "DEFAULT" || name == "HELP") {
return new BridgePOMCPPrior(this);
} else {
cerr << "Unsupported POMCP prior: " << name << endl;
exit(1);
return NULL;
}
}
} // namespace despot
| 24.351351 | 82 | 0.632472 | [
"vector",
"model"
] |
816ce50aae0fc8ba636480bc39e40603095b4e00 | 1,445 | hh | C++ | src/net/netevent.hh | nilium/snow | 296466e49fd5ebd8d4d40dbf96b14903daa705a8 | [
"Zlib",
"BSD-2-Clause"
] | 4 | 2015-10-01T20:10:20.000Z | 2021-08-28T23:43:33.000Z | src/net/netevent.hh | nilium/snow | 296466e49fd5ebd8d4d40dbf96b14903daa705a8 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | src/net/netevent.hh | nilium/snow | 296466e49fd5ebd8d4d40dbf96b14903daa705a8 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | /*
netevent.hh -- Copyright (c) 2013 Noel Cower. All rights reserved.
See COPYING under the project root for the source code license. If this file
is not present, refer to <https://raw.github.com/nilium/snow/master/COPYING>.
*/
#ifndef __SNOW__NETEVENT_HH__
#define __SNOW__NETEVENT_HH__
#include "../config.hh"
#include <enet/enet.h>
#include <vector>
namespace snow {
struct netevent_t
{
using charbuf_t = std::vector<uint8_t>;
void set_sender(uint16_t sender);
void set_message(uint16_t message);
void set_time(double time);
void set_buffer(charbuf_t &&buf);
void set_buffer(const charbuf_t &buf);
uint16_t sender() const;
uint16_t message() const;
double time() const;
const charbuf_t & buffer() const;
charbuf_t & buffer();
size_t data_length() const;
void read_from(const ENetPacket *const packet);
void write_to(ENetPacket *packet);
// Creates packets and sends them over the given medium
bool send(ENetPeer *peer, enet_uint8 channel,
int flags = ENET_PACKET_FLAG_RELIABLE);
void broadcast(ENetHost *host, enet_uint8 channel,
int flags = ENET_PACKET_FLAG_RELIABLE);
private:
uint16_t sender_ = 0;
uint16_t message_ = 0;
double time_ = 0;
charbuf_t buffer_ { };
};
} // namespace snow
#endif /* end __SNOW__NETEVENT_HH__ include guard */
| 27.264151 | 79 | 0.663668 | [
"vector"
] |
816dca22a21b918479e0d5fc52d1137125ff80f0 | 4,198 | hpp | C++ | include/fl/filter/gaussian/update_policy/sigma_point_update_policy.hpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 17 | 2015-07-03T06:53:05.000Z | 2021-05-15T20:55:12.000Z | include/fl/filter/gaussian/update_policy/sigma_point_update_policy.hpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 3 | 2015-02-20T12:48:17.000Z | 2019-12-18T08:45:13.000Z | include/fl/filter/gaussian/update_policy/sigma_point_update_policy.hpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 15 | 2015-02-20T11:34:14.000Z | 2021-05-15T20:55:13.000Z | /*
* This is part of the fl library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2015 Max Planck Society,
* Autonomous Motion Department,
* Institute for Intelligent Systems
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file sigma_point_update_policy.hpp
* \date July 2015
* \author Jan Issac (jan.issac@gmail.com)
*/
#pragma once
#include <Eigen/Dense>
#include <fl/util/meta.hpp>
#include <fl/util/traits.hpp>
#include <fl/util/descriptor.hpp>
#include <fl/filter/gaussian/transform/point_set.hpp>
#include <fl/filter/gaussian/quadrature/sigma_point_quadrature.hpp>
namespace fl
{
// Forward declarations
template <typename...> class SigmaPointUpdatePolicy;
template <
typename SigmaPointQuadrature,
typename SensorFunction
>
class SigmaPointUpdatePolicy<
SigmaPointQuadrature,
SensorFunction>
: public SigmaPointUpdatePolicy<
SigmaPointQuadrature,
NonAdditive<SensorFunction>>
{ };
template <
typename SigmaPointQuadrature,
typename SensorFunction
>
class SigmaPointUpdatePolicy<
SigmaPointQuadrature,
NonAdditive<SensorFunction>>
: public Descriptor
{
public:
typedef typename SensorFunction::State State;
typedef typename SensorFunction::Obsrv Obsrv;
typedef typename SensorFunction::Noise Noise;
enum : signed int
{
NumberOfPoints = SigmaPointQuadrature::number_of_points(
JoinSizes<
SizeOf<State>::Value,
SizeOf<Noise>::Value
>::Size)
};
typedef PointSet<State, NumberOfPoints> StatePointSet;
typedef PointSet<Noise, NumberOfPoints> NoisePointSet;
typedef PointSet<Obsrv, NumberOfPoints> ObsrvPointSet;
template <
typename Belief
>
void operator()(const SensorFunction& obsrv_function,
const SigmaPointQuadrature& quadrature,
const Belief& prior_belief,
const Obsrv& obsrv,
Belief& posterior_belief)
{
// static_assert() is non-additive
noise_distr_.dimension(obsrv_function.noise_dimension());
auto&& h = [&](const State& x, const Noise& w)
{
return obsrv_function.observation(x, w);
};
quadrature.propergate_gaussian(h, prior_belief, noise_distr_, X, Y, Z);
auto&& prediction = Z.center();
auto&& Z_c = Z.points();
auto&& W = X.covariance_weights_vector();
auto&& X_c = X.centered_points();
auto innovation = (obsrv - prediction).eval();
auto cov_xx = (X_c * W.asDiagonal() * X_c.transpose()).eval();
auto cov_yy = (Z_c * W.asDiagonal() * Z_c.transpose()).eval();
auto cov_xy = (X_c * W.asDiagonal() * Z_c.transpose()).eval();
auto cov_yx = cov_xy.transpose().eval();
auto x_updated = (X.mean() + cov_xy * solve(cov_yy, innovation)).eval();
auto cov_xx_updated = (cov_xx - cov_xy * solve(cov_yy, cov_yx)).eval();
posterior_belief.dimension(prior_belief.dimension());
posterior_belief.mean(x_updated);
posterior_belief.covariance(cov_xx_updated);
// auto K = (cov_xy * cov_yy.inverse()).eval();
// posterior_belief.mean(X.mean() + K * innovation);
// posterior_belief.covariance(cov_xx - K * cov_yy * K.transpose());
}
virtual std::string name() const
{
return "SigmaPointUpdatePolicy<"
+ this->list_arguments(
"SigmaPointQuadrature",
"NonAdditive<SensorFunction>")
+ ">";
}
virtual std::string description() const
{
return "Sigma Point based filter update policy for observation model"
" with non-additive noise";
}
protected:
StatePointSet X;
NoisePointSet Y;
ObsrvPointSet Z;
Gaussian<Noise> noise_distr_;
};
}
| 28.557823 | 83 | 0.620057 | [
"model",
"transform"
] |
816f8014aaf0202d8481af886d9b9ebe1be3f061 | 1,754 | cc | C++ | chrome/browser/profiles/avatar_menu_model_browsertest.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-05-03T06:33:56.000Z | 2021-11-14T18:39:42.000Z | chrome/browser/profiles/avatar_menu_model_browsertest.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/profiles/avatar_menu_model_browsertest.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 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/profiles/avatar_menu_model.h"
#include "base/path_service.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/testing_browser_process.h"
#include "content/public/test/test_utils.h"
namespace {
typedef InProcessBrowserTest AvatarMenuModelTest;
IN_PROC_BROWSER_TEST_F(AvatarMenuModelTest, SignOut) {
if (!ProfileManager::IsMultipleProfilesEnabled())
return;
ProfileManager* profile_manager = g_browser_process->profile_manager();
Profile* current_profile = browser()->profile();
ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
size_t index = cache.GetIndexOfProfileWithPath(current_profile->GetPath());
AvatarMenuModel model(&cache, NULL, browser());
BrowserList* browser_list =
BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_NATIVE);
EXPECT_EQ(1U, browser_list->size());
content::WindowedNotificationObserver window_close_observer(
chrome::NOTIFICATION_BROWSER_CLOSED,
content::Source<Browser>(browser()));
EXPECT_FALSE(cache.ProfileIsSigninRequiredAtIndex(index));
model.SetLogoutURL("about:blank");
model.BeginSignOut();
EXPECT_TRUE(cache.ProfileIsSigninRequiredAtIndex(index));
window_close_observer.Wait(); // rely on test time-out for failure indication
EXPECT_EQ(0U, browser_list->size());
}
} // namespace
| 35.795918 | 80 | 0.781642 | [
"model"
] |
81754c1030eb6f16214bcc9c9815482a09be6fbc | 229,023 | cpp | C++ | src/gausskernel/runtime/executor/execQual.cpp | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | null | null | null | src/gausskernel/runtime/executor/execQual.cpp | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | null | null | null | src/gausskernel/runtime/executor/execQual.cpp | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | null | null | null | /* -------------------------------------------------------------------------
*
* execQual.cpp
* Routines to evaluate qualification and targetlist expressions
*
* Portions Copyright (c) 2020 Huawei Technologies Co.,Ltd.
* Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/gausskernel/runtime/executor/execQual.cpp
*
* -------------------------------------------------------------------------
*/
/*
* INTERFACE ROUTINES
* ExecEvalExpr - (now a macro) evaluate an expression, return a datum
* ExecEvalExprSwitchContext - same, but switch into eval memory context
* ExecQual - return true/false if qualification is satisfied
* ExecProject - form a new tuple by projecting the given tuple
*
* NOTES
* The more heavily used ExecEvalExpr routines, such as ExecEvalScalarVar,
* are hotspots. Making these faster will speed up the entire system.
*
* ExecProject() is used to make tuple projections. Rather then
* trying to speed it up, the execution plan should be pre-processed
* to facilitate attribute sharing between nodes wherever possible,
* instead of doing needless copying. -cim 5/31/91
*
* During expression evaluation, we check_stack_depth only in
* ExecMakeFunctionResult (and substitute routines) rather than at every
* single node. This is a compromise that trades off precision of the
* stack limit setting to gain speed.
*/
#include "postgres.h"
#include "knl/knl_variable.h"
#include "access/nbtree.h"
#include "access/tupconvert.h"
#include "access/tableam.h"
#include "catalog/pg_cast.h"
#include "catalog/pg_type.h"
#include "commands/typecmds.h"
#include "executor/execdebug.h"
#include "executor/nodeSubplan.h"
#include "executor/nodeAgg.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/planner.h"
#include "parser/parse_coerce.h"
#include "pgstat.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/typcache.h"
#include "utils/xml.h"
#include "access/hash.h"
#include "access/transam.h"
#ifdef PGXC
#include "pgxc/groupmgr.h"
#include "pgxc/pgxc.h"
#endif
#include "optimizer/streamplan.h"
#include "gstrace/gstrace_infra.h"
#include "gstrace/executer_gstrace.h"
#include "commands/trigger.h"
#include "db4ai/gd.h"
/* static function decls */
static Datum ExecEvalArrayRef(ArrayRefExprState* astate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static bool isAssignmentIndirectionExpr(ExprState* exprstate);
static Datum ExecEvalAggref(AggrefExprState* aggref, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalWindowFunc(WindowFuncExprState* wfunc, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalScalarVar(ExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalScalarVarFast(ExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalWholeRowVar(
WholeRowVarExprState* wrvstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalWholeRowFast(
WholeRowVarExprState* wrvstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalWholeRowSlow(
WholeRowVarExprState* wrvstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalConst(ExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalParamExec(ExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalParamExtern(ExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
template <bool vectorized>
static void init_fcache(
Oid foid, Oid input_collation, FuncExprState* fcache, MemoryContext fcacheCxt, bool needDescForSets);
static void ShutdownFuncExpr(Datum arg);
static TupleDesc get_cached_rowtype(Oid type_id, int32 typmod, TupleDesc* cache_field, ExprContext* econtext);
static void ShutdownTupleDescRef(Datum arg);
template <bool has_refcursor>
static ExprDoneCond ExecEvalFuncArgs(
FunctionCallInfo fcinfo, List* argList, ExprContext* econtext, int* plpgsql_var_dno = NULL);
static void ExecPrepareTuplestoreResult(
FuncExprState* fcache, ExprContext* econtext, Tuplestorestate* resultStore, TupleDesc resultDesc);
static void tupledesc_match(TupleDesc dst_tupdesc, TupleDesc src_tupdesc);
template <bool has_refcursor, bool has_cursor_return, bool isSetReturnFunc>
static Datum ExecMakeFunctionResult(FuncExprState* fcache, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
template <bool has_refcursor, bool has_cursor_return>
static Datum ExecMakeFunctionResultNoSets(
FuncExprState* fcache, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalFunc(FuncExprState* fcache, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalOper(FuncExprState* fcache, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalDistinct(FuncExprState* fcache, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalScalarArrayOp(
ScalarArrayOpExprState* sstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalNot(BoolExprState* notclause, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalOr(BoolExprState* orExpr, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalAnd(BoolExprState* andExpr, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalConvertRowtype(
ConvertRowtypeExprState* cstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalCase(CaseExprState* caseExpr, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalCaseTestExpr(ExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalArray(ArrayExprState* astate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalRow(RowExprState* rstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalRowCompare(RowCompareExprState* rstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalCoalesce(
CoalesceExprState* coalesceExpr, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalMinMax(MinMaxExprState* minmaxExpr, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalXml(XmlExprState* xmlExpr, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalNullIf(FuncExprState* nullIfExpr, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalNullTest(NullTestState* nstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalHashFilter(HashFilterState* hstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalBooleanTest(GenericExprState* bstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalCoerceToDomain(
CoerceToDomainState* cstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalCoerceToDomainValue(
ExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalFieldSelect(FieldSelectState* fstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalFieldStore(FieldStoreState* fstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalRelabelType(
GenericExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalCoerceViaIO(CoerceViaIOState* iostate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalArrayCoerceExpr(
ArrayCoerceExprState* astate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalCurrentOfExpr(ExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalGroupingFuncExpr(
GroupingFuncExprState* gstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static Datum ExecEvalGroupingIdExpr(
GroupingIdExprState* gstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
static bool func_has_refcursor_args(Oid Funcid, FunctionCallInfoData* fcinfo);
extern Datum ExecEvalGradientDescent(GradientDescentExprState* mlstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone);
THR_LOCAL PLpgSQL_execstate* plpgsql_estate = NULL;
/* ----------------------------------------------------------------
* ExecEvalExpr routines
*
* Recursively evaluate a targetlist or qualification expression.
*
* Each of the following routines having the signature
* Datum ExecEvalFoo(ExprState *expression,
* ExprContext *econtext,
* bool *isNull,
* ExprDoneCond *isDone);
* is responsible for evaluating one type or subtype of ExprState node.
* They are normally called via the ExecEvalExpr macro, which makes use of
* the function pointer set up when the ExprState node was built by
* ExecInitExpr. (In some cases, we change this pointer later to avoid
* re-executing one-time overhead.)
*
* Note: for notational simplicity we declare these functions as taking the
* specific type of ExprState that they work on. This requires casting when
* assigning the function pointer in ExecInitExpr. Be careful that the
* function signature is declared correctly, because the cast suppresses
* automatic checking!
*
*
* All these functions share this calling convention:
*
* Inputs:
* expression: the expression state tree to evaluate
* econtext: evaluation context information
*
* Outputs:
* return value: Datum value of result
* *isNull: set to TRUE if result is NULL (actual return value is
* meaningless if so); set to FALSE if non-null result
* *isDone: set to indicator of set-result status
*
* A caller that can only accept a singleton (non-set) result should pass
* NULL for isDone; if the expression computes a set result then an error
* will be reported via ereport. If the caller does pass an isDone pointer
* then *isDone is set to one of these three states:
* ExprSingleResult singleton result (not a set)
* ExprMultipleResult return value is one element of a set
* ExprEndResult there are no more elements in the set
* When ExprMultipleResult is returned, the caller should invoke
* ExecEvalExpr() repeatedly until ExprEndResult is returned. ExprEndResult
* is returned after the last real set element. For convenience isNull will
* always be set TRUE when ExprEndResult is returned, but this should not be
* taken as indicating a NULL element of the set. Note that these return
* conventions allow us to distinguish among a singleton NULL, a NULL element
* of a set, and an empty set.
*
* The caller should already have switched into the temporary memory
* context econtext->ecxt_per_tuple_memory. The convenience entry point
* ExecEvalExprSwitchContext() is provided for callers who don't prefer to
* do the switch in an outer loop. We do not do the switch in these routines
* because it'd be a waste of cycles during nested expression evaluation.
* ----------------------------------------------------------------
*/
/* ----------
* ExecEvalArrayRef
*
* This function takes an ArrayRef and returns the extracted Datum
* if it's a simple reference, or the modified array value if it's
* an array assignment (i.e., array element or slice insertion).
*
* NOTE: if we get a NULL result from a subscript expression, we return NULL
* when it's an array reference, or raise an error when it's an assignment.
*
* NOTE: we deliberately refrain from applying DatumGetArrayTypeP() here,
* even though that might seem natural, because this code needs to support
* both varlena arrays and fixed-length array types. DatumGetArrayTypeP()
* only works for the varlena kind. The routines we call in arrayfuncs.c
* have to know the difference (that's what they need refattrlength for).
* ----------
*/
static Datum ExecEvalArrayRef(ArrayRefExprState* astate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
ArrayRef* arrayRef = (ArrayRef*)astate->xprstate.expr;
ArrayType* array_source = NULL;
ArrayType* resultArray = NULL;
bool isAssignment = (arrayRef->refassgnexpr != NULL);
bool eisnull = false;
ListCell* l = NULL;
int i = 0;
int j = 0;
IntArray upper, lower;
int* lIndex = NULL;
array_source = (ArrayType*)DatumGetPointer(ExecEvalExpr(astate->refexpr, econtext, isNull, isDone));
/*
* If refexpr yields NULL, and it's a fetch, then result is NULL. In the
* assignment case, we'll cons up something below.
*/
if (*isNull) {
if (isDone && *isDone == ExprEndResult)
return (Datum)NULL; /* end of set result */
if (!isAssignment)
return (Datum)NULL;
}
foreach (l, astate->refupperindexpr) {
ExprState* eltstate = (ExprState*)lfirst(l);
if (i >= MAXDIM)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)", i + 1, MAXDIM)));
upper.indx[i++] = DatumGetInt32(ExecEvalExpr(eltstate, econtext, &eisnull, NULL));
/* If any index expr yields NULL, result is NULL or error */
if (eisnull) {
if (isAssignment)
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("array subscript in assignment must not be null")));
*isNull = true;
return (Datum)NULL;
}
}
if (astate->reflowerindexpr != NIL) {
foreach (l, astate->reflowerindexpr) {
ExprState* eltstate = (ExprState*)lfirst(l);
if (j >= MAXDIM)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)", j + 1, MAXDIM)));
lower.indx[j++] = DatumGetInt32(ExecEvalExpr(eltstate, econtext, &eisnull, NULL));
/* If any index expr yields NULL, result is NULL or error */
if (eisnull) {
if (isAssignment)
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("array subscript in assignment must not be null")));
*isNull = true;
return (Datum)NULL;
}
}
/* this can't happen unless parser messed up */
if (i != j)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmodule(MOD_EXECUTOR),
(errmsg("upper and lower index lists are not same length (%d, %d)", i, j))));
lIndex = lower.indx;
} else
lIndex = NULL;
if (isAssignment) {
Datum sourceData;
Datum save_datum;
bool save_isNull = false;
/*
* We might have a nested-assignment situation, in which the
* refassgnexpr is itself a FieldStore or ArrayRef that needs to
* obtain and modify the previous value of the array element or slice
* being replaced. If so, we have to extract that value from the
* array and pass it down via the econtext's caseValue. It's safe to
* reuse the CASE mechanism because there cannot be a CASE between
* here and where the value would be needed, and an array assignment
* can't be within a CASE either. (So saving and restoring the
* caseValue is just paranoia, but let's do it anyway.)
*
* Since fetching the old element might be a nontrivial expense, do it
* only if the argument appears to actually need it.
*/
save_datum = econtext->caseValue_datum;
save_isNull = econtext->caseValue_isNull;
if (isAssignmentIndirectionExpr(astate->refassgnexpr)) {
if (*isNull) {
/* whole array is null, so any element or slice is too */
econtext->caseValue_datum = (Datum)0;
econtext->caseValue_isNull = true;
} else if (lIndex == NULL) {
econtext->caseValue_datum = array_ref(array_source,
i,
upper.indx,
astate->refattrlength,
astate->refelemlength,
astate->refelembyval,
astate->refelemalign,
&econtext->caseValue_isNull);
} else {
resultArray = array_get_slice(array_source,
i,
upper.indx,
lower.indx,
astate->refattrlength,
astate->refelemlength,
astate->refelembyval,
astate->refelemalign);
econtext->caseValue_datum = PointerGetDatum(resultArray);
econtext->caseValue_isNull = false;
}
} else {
/* argument shouldn't need caseValue, but for safety set it null */
econtext->caseValue_datum = (Datum)0;
econtext->caseValue_isNull = true;
}
/*
* Evaluate the value to be assigned into the array.
*/
sourceData = ExecEvalExpr(astate->refassgnexpr, econtext, &eisnull, NULL);
econtext->caseValue_datum = save_datum;
econtext->caseValue_isNull = save_isNull;
/*
* For an assignment to a fixed-length array type, both the original
* array and the value to be assigned into it must be non-NULL, else
* we punt and return the original array.
*/
if (astate->refattrlength > 0) /* fixed-length array? */
if (eisnull || *isNull)
return PointerGetDatum(array_source);
/*
* For assignment to varlena arrays, we handle a NULL original array
* by substituting an empty (zero-dimensional) array; insertion of the
* new element will result in a singleton array value. It does not
* matter whether the new element is NULL.
*/
if (*isNull) {
array_source = construct_empty_array(arrayRef->refelemtype);
*isNull = false;
}
if (lIndex == NULL)
resultArray = array_set(array_source,
i,
upper.indx,
sourceData,
eisnull,
astate->refattrlength,
astate->refelemlength,
astate->refelembyval,
astate->refelemalign);
else
resultArray = array_set_slice(array_source,
i,
upper.indx,
lower.indx,
(ArrayType*)DatumGetPointer(sourceData),
eisnull,
astate->refattrlength,
astate->refelemlength,
astate->refelembyval,
astate->refelemalign);
return PointerGetDatum(resultArray);
}
if (lIndex == NULL)
return array_ref(array_source,
i,
upper.indx,
astate->refattrlength,
astate->refelemlength,
astate->refelembyval,
astate->refelemalign,
isNull);
else {
resultArray = array_get_slice(array_source,
i,
upper.indx,
lower.indx,
astate->refattrlength,
astate->refelemlength,
astate->refelembyval,
astate->refelemalign);
return PointerGetDatum(resultArray);
}
}
/*
* Helper for ExecEvalArrayRef: is expr a nested FieldStore or ArrayRef
* that might need the old element value passed down?
*
* (We could use this in ExecEvalFieldStore too, but in that case passing
* the old value is so cheap there's no need.)
*/
static bool isAssignmentIndirectionExpr(ExprState* exprstate)
{
if (exprstate == NULL)
return false; /* just paranoia */
if (IsA(exprstate, FieldStoreState)) {
FieldStore* fstore = (FieldStore*)exprstate->expr;
if (fstore->arg && IsA(fstore->arg, CaseTestExpr))
return true;
} else if (IsA(exprstate, ArrayRefExprState)) {
ArrayRef* arrayRef = (ArrayRef*)exprstate->expr;
if (arrayRef->refexpr && IsA(arrayRef->refexpr, CaseTestExpr))
return true;
}
return false;
}
/* ----------------------------------------------------------------
* ExecEvalAggref
*
* Returns a Datum whose value is the value of the precomputed
* aggregate found in the given expression context.
* ----------------------------------------------------------------
*/
static Datum ExecEvalAggref(AggrefExprState* aggref, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
if (isDone != NULL)
*isDone = ExprSingleResult;
if (econtext->ecxt_aggvalues == NULL) /* safety check */
ereport(ERROR,
(errcode(ERRCODE_INVALID_AGG),
errmodule(MOD_EXECUTOR),
errmsg("no aggregates in this expression context")));
*isNull = econtext->ecxt_aggnulls[aggref->aggno];
return econtext->ecxt_aggvalues[aggref->aggno];
}
/* ----------------------------------------------------------------
* ExecEvalWindowFunc
*
* Returns a Datum whose value is the value of the precomputed
* window function found in the given expression context.
* ----------------------------------------------------------------
*/
static Datum ExecEvalWindowFunc(WindowFuncExprState* wfunc, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
if (isDone != NULL)
*isDone = ExprSingleResult;
if (econtext->ecxt_aggvalues == NULL) /* safety check */
ereport(ERROR,
(errcode(ERRCODE_WINDOWING_ERROR),
errmodule(MOD_EXECUTOR),
errmsg("no window functions in this expression context")));
*isNull = econtext->ecxt_aggnulls[wfunc->wfuncno];
return econtext->ecxt_aggvalues[wfunc->wfuncno];
}
/* ----------------------------------------------------------------
* ExecEvalScalarVar
*
* Returns a Datum whose value is the value of a scalar (not whole-row)
* range variable with respect to given expression context.
*
* Note: ExecEvalScalarVar is executed only the first time through in a given
* plan; it changes the ExprState's function pointer to pass control directly
* to ExecEvalScalarVarFast after making one-time checks.
* ----------------------------------------------------------------
*/
static Datum ExecEvalScalarVar(ExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
Var* variable = (Var*)exprstate->expr;
TupleTableSlot* slot = NULL;
AttrNumber attnum;
if (isDone != NULL)
*isDone = ExprSingleResult;
/* Get the input slot and attribute number we want */
switch (variable->varno) {
case INNER_VAR: /* get the tuple from the inner node */
slot = econtext->ecxt_innertuple;
break;
case OUTER_VAR: /* get the tuple from the outer node */
slot = econtext->ecxt_outertuple;
break;
/* INDEX_VAR is handled by default case */
default: /* get the tuple from the relation being scanned */
slot = econtext->ecxt_scantuple;
break;
}
Assert(slot != NULL);
attnum = variable->varattno;
/* This was checked by ExecInitExpr */
Assert(attnum != InvalidAttrNumber);
/*
* If it's a user attribute, check validity (bogus system attnums will be
* caught inside table's getattr). What we have to check for here is the
* possibility of an attribute having been changed in type since the plan
* tree was created. Ideally the plan will get invalidated and not
* re-used, but just in case, we keep these defenses. Fortunately it's
* sufficient to check once on the first time through.
*
* Note: we allow a reference to a dropped attribute. table's getattr will
* force a NULL result in such cases.
*
* Note: ideally we'd check typmod as well as typid, but that seems
* impractical at the moment: in many cases the tupdesc will have been
* generated by ExecTypeFromTL(), and that can't guarantee to generate an
* accurate typmod in all cases, because some expression node types don't
* carry typmod.
*/
if (attnum > 0) {
TupleDesc slot_tupdesc = slot->tts_tupleDescriptor;
Form_pg_attribute attr;
if (attnum > slot_tupdesc->natts) /* should never happen */
ereport(ERROR,
(errcode(ERRCODE_INVALID_ATTRIBUTE),
errmodule(MOD_EXECUTOR),
errmsg("attribute number %d exceeds number of columns %d", attnum, slot_tupdesc->natts)));
attr = slot_tupdesc->attrs[attnum - 1];
/* can't check type if dropped, since atttypid is probably 0 */
if (!attr->attisdropped) {
if (variable->vartype != attr->atttypid)
ereport(ERROR,
(errcode(ERRCODE_INVALID_ATTRIBUTE),
errmodule(MOD_EXECUTOR),
errmsg("attribute %d has wrong type", attnum),
errdetail("Table has type %s, but query expects %s.",
format_type_be(attr->atttypid),
format_type_be(variable->vartype))));
}
}
/* Skip the checking on future executions of node */
exprstate->evalfunc = ExecEvalScalarVarFast;
/* Fetch the value from the slot */
return tableam_tslot_getattr(slot, attnum, isNull);
}
/* ----------------------------------------------------------------
* ExecEvalScalarVarFast
*
* Returns a Datum for a scalar variable.
* ----------------------------------------------------------------
*/
static Datum ExecEvalScalarVarFast(ExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
Var* variable = (Var*)exprstate->expr;
TupleTableSlot* slot = NULL;
AttrNumber attnum;
if (isDone != NULL)
*isDone = ExprSingleResult;
/* Get the input slot and attribute number we want */
switch (variable->varno) {
case INNER_VAR: /* get the tuple from the inner node */
slot = econtext->ecxt_innertuple;
break;
case OUTER_VAR: /* get the tuple from the outer node */
slot = econtext->ecxt_outertuple;
break;
/* INDEX_VAR is handled by default case */
default: /* get the tuple from the relation being scanned */
slot = econtext->ecxt_scantuple;
break;
}
attnum = variable->varattno;
Assert(slot != NULL);
/* Fetch the value from the slot */
return tableam_tslot_getattr(slot, attnum, isNull);
}
/* ----------------------------------------------------------------
* ExecEvalWholeRowVar
*
* Returns a Datum whose value is the value of a whole-row range
* variable with respect to given expression context.
*
* Note: ExecEvalWholeRowVar is executed only the first time through in a
* given plan; it changes the ExprState's function pointer to pass control
* directly to ExecEvalWholeRowFast or ExecEvalWholeRowSlow after making
* one-time checks.
* ----------------------------------------------------------------
*/
static Datum ExecEvalWholeRowVar(
WholeRowVarExprState* wrvstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
Var* variable = (Var*)wrvstate->xprstate.expr;
TupleTableSlot* slot = NULL;
TupleDesc slot_tupdesc;
bool needslow = false;
if (isDone != NULL)
*isDone = ExprSingleResult;
/* This was checked by ExecInitExpr */
Assert(variable->varattno == InvalidAttrNumber);
/* Get the input slot we want */
switch (variable->varno) {
case INNER_VAR: /* get the tuple from the inner node */
slot = econtext->ecxt_innertuple;
break;
case OUTER_VAR: /* get the tuple from the outer node */
slot = econtext->ecxt_outertuple;
break;
/* INDEX_VAR is handled by default case */
default: /* get the tuple from the relation being scanned */
slot = econtext->ecxt_scantuple;
break;
}
/*
* If the input tuple came from a subquery, it might contain "resjunk"
* columns (such as GROUP BY or ORDER BY columns), which we don't want to
* keep in the whole-row result. We can get rid of such columns by
* passing the tuple through a JunkFilter --- but to make one, we have to
* lay our hands on the subquery's targetlist. Fortunately, there are not
* very many cases where this can happen, and we can identify all of them
* by examining our parent PlanState. We assume this is not an issue in
* standalone expressions that don't have parent plans. (Whole-row Vars
* can occur in such expressions, but they will always be referencing
* table rows.)
*/
if (wrvstate->parent) {
PlanState* subplan = NULL;
switch (nodeTag(wrvstate->parent)) {
case T_SubqueryScanState:
subplan = ((SubqueryScanState*)wrvstate->parent)->subplan;
break;
case T_CteScanState:
subplan = ((CteScanState*)wrvstate->parent)->cteplanstate;
break;
default:
break;
}
if (subplan != NULL) {
bool junk_filter_needed = false;
ListCell* tlist = NULL;
/* Detect whether subplan tlist actually has any junk columns */
foreach (tlist, subplan->plan->targetlist) {
TargetEntry* tle = (TargetEntry*)lfirst(tlist);
if (tle->resjunk) {
junk_filter_needed = true;
break;
}
}
/* If so, build the junkfilter in the query memory context */
if (junk_filter_needed) {
MemoryContext oldcontext;
oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
wrvstate->wrv_junkFilter = ExecInitJunkFilter(subplan->plan->targetlist,
ExecGetResultType(subplan)->tdhasoid,
ExecInitExtraTupleSlot(wrvstate->parent->state));
MemoryContextSwitchTo(oldcontext);
}
}
}
/* Apply the junkfilter if any */
if (wrvstate->wrv_junkFilter != NULL)
slot = ExecFilterJunk(wrvstate->wrv_junkFilter, slot);
slot_tupdesc = slot->tts_tupleDescriptor;
/*
* If it's a RECORD Var, we'll use the slot's type ID info. It's likely
* that the slot's type is also RECORD; if so, make sure it's been
* "blessed", so that the Datum can be interpreted later.
*
* If the Var identifies a named composite type, we must check that the
* actual tuple type is compatible with it.
*/
if (variable->vartype == RECORDOID) {
if (slot_tupdesc->tdtypeid == RECORDOID && slot_tupdesc->tdtypmod < 0)
assign_record_type_typmod(slot_tupdesc);
} else {
TupleDesc var_tupdesc;
int i;
/*
* We really only care about numbers of attributes and data types.
* Also, we can ignore type mismatch on columns that are dropped in
* the destination type, so long as (1) the physical storage matches
* or (2) the actual column value is NULL. Case (1) is helpful in
* some cases involving out-of-date cached plans, while case (2) is
* expected behavior in situations such as an INSERT into a table with
* dropped columns (the planner typically generates an INT4 NULL
* regardless of the dropped column type). If we find a dropped
* column and cannot verify that case (1) holds, we have to use
* ExecEvalWholeRowSlow to check (2) for each row.
*/
var_tupdesc = lookup_rowtype_tupdesc(variable->vartype, -1);
if (var_tupdesc->natts != slot_tupdesc->natts)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("table row type and query-specified row type do not match"),
errdetail_plural("Table row contains %d attribute, but query expects %d.",
"Table row contains %d attributes, but query expects %d.",
slot_tupdesc->natts,
slot_tupdesc->natts,
var_tupdesc->natts)));
for (i = 0; i < var_tupdesc->natts; i++) {
Form_pg_attribute vattr = var_tupdesc->attrs[i];
Form_pg_attribute sattr = slot_tupdesc->attrs[i];
if (vattr->atttypid == sattr->atttypid)
continue; /* no worries */
if (!vattr->attisdropped)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("table row type and query-specified row type do not match"),
errdetail("Table has type %s at ordinal position %d, but query expects %s.",
format_type_be(sattr->atttypid),
i + 1,
format_type_be(vattr->atttypid))));
if (vattr->attlen != sattr->attlen || vattr->attalign != sattr->attalign)
needslow = true; /* need runtime check for null */
}
ReleaseTupleDesc(var_tupdesc);
}
/* Skip the checking on future executions of node */
if (needslow)
wrvstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalWholeRowSlow;
else
wrvstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalWholeRowFast;
/* Fetch the value */
return (*wrvstate->xprstate.evalfunc)((ExprState*)wrvstate, econtext, isNull, isDone);
}
/* ----------------------------------------------------------------
* ExecEvalWholeRowFast
*
* Returns a Datum for a whole-row variable.
* ----------------------------------------------------------------
*/
static Datum ExecEvalWholeRowFast(
WholeRowVarExprState* wrvstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
Var* variable = (Var*)wrvstate->xprstate.expr;
TupleTableSlot* slot = NULL;
HeapTuple tuple;
TupleDesc tupleDesc;
HeapTupleHeader dtuple;
errno_t rc = EOK;
if (isDone != NULL)
*isDone = ExprSingleResult;
*isNull = false;
/* Get the input slot we want */
switch (variable->varno) {
case INNER_VAR: /* get the tuple from the inner node */
slot = econtext->ecxt_innertuple;
break;
case OUTER_VAR: /* get the tuple from the outer node */
slot = econtext->ecxt_outertuple;
break;
/* INDEX_VAR is handled by default case */
default: /* get the tuple from the relation being scanned */
slot = econtext->ecxt_scantuple;
break;
}
/* Apply the junkfilter if any */
if (wrvstate->wrv_junkFilter != NULL)
slot = ExecFilterJunk(wrvstate->wrv_junkFilter, slot);
tuple = ExecFetchSlotTuple(slot);
tupleDesc = slot->tts_tupleDescriptor;
/*
* We have to make a copy of the tuple so we can safely insert the Datum
* overhead fields, which are not set in on-disk tuples.
*/
dtuple = (HeapTupleHeader)palloc(tuple->t_len);
rc = memcpy_s((char*)dtuple, tuple->t_len, (char*)tuple->t_data, tuple->t_len);
securec_check(rc, "\0", "\0");
HeapTupleHeaderSetDatumLength(dtuple, tuple->t_len);
/*
* If the Var identifies a named composite type, label the tuple with that
* type; otherwise use what is in the tupleDesc.
*/
if (variable->vartype != RECORDOID) {
HeapTupleHeaderSetTypeId(dtuple, variable->vartype);
HeapTupleHeaderSetTypMod(dtuple, variable->vartypmod);
} else {
HeapTupleHeaderSetTypeId(dtuple, tupleDesc->tdtypeid);
HeapTupleHeaderSetTypMod(dtuple, tupleDesc->tdtypmod);
}
return PointerGetDatum(dtuple);
}
/* ----------------------------------------------------------------
* ExecEvalWholeRowSlow
*
* Returns a Datum for a whole-row variable, in the "slow" case where
* we can't just copy the subplan's output.
* ----------------------------------------------------------------
*/
static Datum ExecEvalWholeRowSlow(
WholeRowVarExprState* wrvstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
Var* variable = (Var*)wrvstate->xprstate.expr;
TupleTableSlot* slot = NULL;
HeapTuple tuple;
TupleDesc tupleDesc;
TupleDesc var_tupdesc;
HeapTupleHeader dtuple;
int i;
errno_t rc = EOK;
if (isDone != NULL)
*isDone = ExprSingleResult;
*isNull = false;
/* Get the input slot we want */
switch (variable->varno) {
case INNER_VAR: /* get the tuple from the inner node */
slot = econtext->ecxt_innertuple;
break;
case OUTER_VAR: /* get the tuple from the outer node */
slot = econtext->ecxt_outertuple;
break;
/* INDEX_VAR is handled by default case */
default: /* get the tuple from the relation being scanned */
slot = econtext->ecxt_scantuple;
break;
}
/* Apply the junkfilter if any */
if (wrvstate->wrv_junkFilter != NULL)
slot = ExecFilterJunk(wrvstate->wrv_junkFilter, slot);
tuple = ExecFetchSlotTuple(slot);
tupleDesc = slot->tts_tupleDescriptor;
Assert(variable->vartype != RECORDOID);
var_tupdesc = lookup_rowtype_tupdesc(variable->vartype, -1);
/* Check to see if any dropped attributes are non-null */
for (i = 0; i < var_tupdesc->natts; i++) {
Form_pg_attribute vattr = var_tupdesc->attrs[i];
Form_pg_attribute sattr = tupleDesc->attrs[i];
if (!vattr->attisdropped)
continue; /* already checked non-dropped cols */
if (tableam_tops_tuple_attisnull(tuple, i + 1, tupleDesc))
continue; /* null is always okay */
if (vattr->attlen != sattr->attlen || vattr->attalign != sattr->attalign)
ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("table row type and query-specified row type do not match"),
errdetail("Physical storage mismatch on dropped attribute at ordinal position %d.", i + 1)));
}
/*
* We have to make a copy of the tuple so we can safely insert the Datum
* overhead fields, which are not set in on-disk tuples.
*/
dtuple = (HeapTupleHeader)palloc(tuple->t_len);
rc = memcpy_s((char*)dtuple, tuple->t_len, (char*)tuple->t_data, tuple->t_len);
securec_check(rc, "\0", "\0");
HeapTupleHeaderSetDatumLength(dtuple, tuple->t_len);
HeapTupleHeaderSetTypeId(dtuple, variable->vartype);
HeapTupleHeaderSetTypMod(dtuple, variable->vartypmod);
ReleaseTupleDesc(var_tupdesc);
return PointerGetDatum(dtuple);
}
/* ----------------------------------------------------------------
* ExecEvalConst
*
* Returns the value of a constant.
*
* Note that for pass-by-ref datatypes, we return a pointer to the
* actual constant node. This is one of the reasons why functions
* must treat their input arguments as read-only.
* ----------------------------------------------------------------
*/
static Datum ExecEvalConst(ExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
Const* con = (Const*)exprstate->expr;
if (isDone != NULL)
*isDone = ExprSingleResult;
*isNull = con->constisnull;
/* if a const cursor, copy cursor option data to econtext */
if (econtext->is_cursor && con->consttype == REFCURSOROID) {
CopyCursorInfoData(&econtext->cursor_data, &con->cursor_data);
econtext->dno = con->cursor_data.cur_dno;
}
return con->constvalue;
}
/* ----------------------------------------------------------------
* ExecEvalRownum: Returns the rownum
* ----------------------------------------------------------------
*/
static Datum ExecEvalRownum(RownumState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
if (isDone != NULL)
*isDone = ExprSingleResult;
*isNull = false;
return Int64GetDatum(exprstate->ps->ps_rownum + 1);
}
/* ----------------------------------------------------------------
* ExecEvalParamExec
*
* Returns the value of a PARAM_EXEC parameter.
* ----------------------------------------------------------------
*/
static Datum ExecEvalParamExec(ExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
Param* expression = (Param*)exprstate->expr;
int thisParamId = expression->paramid;
ParamExecData* prm = NULL;
if (isDone != NULL)
*isDone = ExprSingleResult;
/*
* PARAM_EXEC params (internal executor parameters) are stored in the
* ecxt_param_exec_vals array, and can be accessed by array index.
*/
prm = &(econtext->ecxt_param_exec_vals[thisParamId]);
if (prm->execPlan != NULL) {
/* Parameter not evaluated yet, so go do it */
ExecSetParamPlan((SubPlanState*)prm->execPlan, econtext);
/* ExecSetParamPlan should have processed this param... */
Assert(prm->execPlan == NULL);
prm->isConst = true;
prm->valueType = expression->paramtype;
}
*isNull = prm->isnull;
prm->isChanged = true;
return prm->value;
}
/* ----------------------------------------------------------------
* ExecEvalParamExtern
*
* Returns the value of a PARAM_EXTERN parameter.
* ----------------------------------------------------------------
*/
static Datum ExecEvalParamExtern(ExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
Param* expression = (Param*)exprstate->expr;
int thisParamId = expression->paramid;
ParamListInfo paramInfo = econtext->ecxt_param_list_info;
if (isDone != NULL)
*isDone = ExprSingleResult;
/*
* PARAM_EXTERN parameters must be sought in ecxt_param_list_info.
*/
if (paramInfo && thisParamId > 0 && thisParamId <= paramInfo->numParams) {
ParamExternData* prm = ¶mInfo->params[thisParamId - 1];
/* give hook a chance in case parameter is dynamic */
if (!OidIsValid(prm->ptype) && paramInfo->paramFetch != NULL)
(*paramInfo->paramFetch)(paramInfo, thisParamId);
if (OidIsValid(prm->ptype)) {
/* safety check in case hook did something unexpected */
if (prm->ptype != expression->paramtype)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("type of parameter %d (%s) does not match that when preparing the plan (%s)",
thisParamId,
format_type_be(prm->ptype),
format_type_be(expression->paramtype))));
*isNull = prm->isnull;
/* copy cursor option from param to econtext */
if (econtext->is_cursor && prm->ptype == REFCURSOROID) {
CopyCursorInfoData(&econtext->cursor_data, &prm->cursor_data);
econtext->dno = thisParamId - 1;
}
return prm->value;
}
}
ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("no value found for parameter %d", thisParamId)));
return (Datum)0; /* keep compiler quiet */
}
/* ----------------------------------------------------------------
* ExecEvalOper / ExecEvalFunc support routines
* ----------------------------------------------------------------
*/
/*
* GetAttributeByName
* GetAttributeByNum
*
* These functions return the value of the requested attribute
* out of the given tuple Datum.
* C functions which take a tuple as an argument are expected
* to use these. Ex: overpaid(EMP) might call GetAttributeByNum().
* Note: these are actually rather slow because they do a typcache
* lookup on each call.
*/
Datum GetAttributeByNum(HeapTupleHeader tuple, AttrNumber attrno, bool* isNull)
{
Datum result;
Oid tupType;
int32 tupTypmod;
TupleDesc tupDesc;
HeapTupleData tmptup;
if (!AttributeNumberIsValid(attrno))
ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("invalid attribute number %d", attrno)));
if (isNull == NULL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("a NULL isNull pointer was passed when get attribute by number.")));
if (tuple == NULL) {
/* Kinda bogus but compatible with old behavior... */
*isNull = true;
return (Datum)0;
}
tupType = HeapTupleHeaderGetTypeId(tuple);
tupTypmod = HeapTupleHeaderGetTypMod(tuple);
tupDesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
/*
* heap_getattr needs a HeapTuple not a bare HeapTupleHeader. We set all
* the fields in the struct just in case user tries to inspect system
* columns.
*/
tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
ItemPointerSetInvalid(&(tmptup.t_self));
tmptup.t_tableOid = InvalidOid;
tmptup.t_bucketId = InvalidBktId;
HeapTupleSetZeroBase(&tmptup);
#ifdef PGXC
tmptup.t_xc_node_id = 0;
#endif
tmptup.t_data = tuple;
if (attrno == -3 || attrno == -5) {
elog(WARNING, "system attribute xmin or xmax, the results about this attribute are untrustworthy.");
}
result = tableam_tops_tuple_getattr(&tmptup, attrno, tupDesc, isNull);
ReleaseTupleDesc(tupDesc);
return result;
}
Datum GetAttributeByName(HeapTupleHeader tuple, const char* attname, bool* isNull)
{
AttrNumber attrno;
Datum result;
Oid tupType;
int32 tupTypmod;
TupleDesc tupDesc;
HeapTupleData tmptup;
int i;
if (attname == NULL)
ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("invalid null attribute name")));
if (isNull == NULL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("a NULL isNull pointer was passed when get attribute by name.")));
if (tuple == NULL) {
/* Kinda bogus but compatible with old behavior... */
*isNull = true;
return (Datum)0;
}
tupType = HeapTupleHeaderGetTypeId(tuple);
tupTypmod = HeapTupleHeaderGetTypMod(tuple);
tupDesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
attrno = InvalidAttrNumber;
for (i = 0; i < tupDesc->natts; i++) {
if (namestrcmp(&(tupDesc->attrs[i]->attname), attname) == 0) {
attrno = tupDesc->attrs[i]->attnum;
break;
}
}
if (attrno == InvalidAttrNumber)
ereport(ERROR,
(errcode(ERRCODE_INVALID_ATTRIBUTE),
errmodule(MOD_EXECUTOR),
errmsg("attribute \"%s\" does not exist", attname)));
/*
* heap_getattr needs a HeapTuple not a bare HeapTupleHeader. We set all
* the fields in the struct just in case user tries to inspect system
* columns.
*/
tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
ItemPointerSetInvalid(&(tmptup.t_self));
tmptup.t_tableOid = InvalidOid;
tmptup.t_bucketId = InvalidBktId;
HeapTupleSetZeroBase(&tmptup);
#ifdef PGXC
tmptup.t_xc_node_id = 0;
#endif
tmptup.t_data = tuple;
if (attrno == -3 || attrno == -5) {
elog(WARNING, "system attribute \"%s\", the results about this attribute are untrustworthy.", attname);
}
result = tableam_tops_tuple_getattr(&tmptup, attrno, tupDesc, isNull);
ReleaseTupleDesc(tupDesc);
return result;
}
/*
* Find the real function return type based on the actual func args' types.
* @inPara arg_num: the number of func's args.
* @inPara actual_arg_types: the type array of actual func args'.
* @inPara fcache: the FuncExprState of this functin.
* @return Oid: the real func return type.
*/
static Oid getRealFuncRetype(int arg_num, Oid* actual_arg_types, FuncExprState* fcache)
{
Oid funcid = fcache->func.fn_oid;
Oid rettype = fcache->func.fn_rettype;
/* Find the declared arg types in PROCOID by funcid. */
HeapTuple proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
if (!HeapTupleIsValid(proctup))
ereport(ERROR,
(errcode(ERRCODE_CACHE_LOOKUP_FAILED),
errmodule(MOD_EXECUTOR),
errmsg("cache lookup failed for function %u", funcid)));
Form_pg_proc procform = (Form_pg_proc)GETSTRUCT(proctup);
Oid* declared_arg_types = procform->proargtypes.values;
/* Find the real return type based on the declared arg types and actual arg types.*/
rettype = enforce_generic_type_consistency(actual_arg_types, declared_arg_types, arg_num, rettype, false);
ReleaseSysCache(proctup);
return rettype;
}
/*
* init_fcache - initialize a FuncExprState node during first use
*/
template <bool vectorized>
static void init_fcache(
Oid foid, Oid input_collation, FuncExprState* fcache, MemoryContext fcacheCxt, bool needDescForSets)
{
AclResult aclresult;
MemoryContext oldcontext;
/* Check permission to call function */
aclresult = pg_proc_aclcheck(foid, GetUserId(), ACL_EXECUTE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_PROC, get_func_name(foid));
/*
* Safety check on nargs. Under normal circumstances this should never
* fail, as parser should check sooner. But possibly it might fail if
* server has been compiled with FUNC_MAX_ARGS smaller than some functions
* declared in pg_proc?
*/
if (list_length(fcache->args) > FUNC_MAX_ARGS)
ereport(ERROR,
(errcode(ERRCODE_TOO_MANY_ARGUMENTS),
errmsg_plural("cannot pass more than %d argument to a function",
"cannot pass more than %d arguments to a function",
FUNC_MAX_ARGS,
FUNC_MAX_ARGS)));
/* Set up the primary fmgr lookup information */
fmgr_info_cxt(foid, &(fcache->func), fcacheCxt);
fmgr_info_set_expr((Node*)fcache->xprstate.expr, &(fcache->func));
/* palloc args in fcache's context */
oldcontext = MemoryContextSwitchTo(fcacheCxt);
/* Initialize the function call parameter struct as well */
if (vectorized)
InitVecFunctionCallInfoData(
&fcache->fcinfo_data, &(fcache->func), list_length(fcache->args), input_collation, NULL, NULL);
else
InitFunctionCallInfoData(
fcache->fcinfo_data, &(fcache->func), list_length(fcache->args), input_collation, NULL, NULL);
if (vectorized) {
int nargs = list_length(fcache->args);
ListCell* cell = NULL;
GenericFunRuntime* genericRuntime = NULL;
errno_t rc;
if (fcache->fcinfo_data.flinfo->genericRuntime == NULL) {
genericRuntime = (GenericFunRuntime*)palloc0(sizeof(GenericFunRuntime));
InitGenericFunRuntimeInfo(*genericRuntime, nargs);
fcache->fcinfo_data.flinfo->genericRuntime = genericRuntime;
} else {
genericRuntime = fcache->fcinfo_data.flinfo->genericRuntime;
/* if internalFinfo is not null, release the internalFinfo's memory and set the pointer to null */
if (genericRuntime->internalFinfo != NULL) {
FreeFunctionCallInfoData(*(genericRuntime->internalFinfo));
genericRuntime->internalFinfo = NULL;
}
/* reset the memory for reuse */
rc = memset_s(genericRuntime->args,
sizeof(GenericFunRuntimeArg) * genericRuntime->compacity,
0,
sizeof(GenericFunRuntimeArg) * genericRuntime->compacity);
securec_check(rc, "\0", "\0");
rc = memset_s(genericRuntime->inputargs,
sizeof(Datum) * genericRuntime->compacity,
0,
sizeof(Datum) * genericRuntime->compacity);
securec_check(rc, "\0", "\0");
rc = memset_s(genericRuntime->nulls,
sizeof(bool) * genericRuntime->compacity,
0,
sizeof(bool) * genericRuntime->compacity);
securec_check(rc, "\0", "\0");
/* we have to adjust the GenericFunRuntimeArg when
* a) nargs is larger than genericRuntime->compacity, which means the allocated memory is not enough to hold
* all the argumnets here, we should enlarge the memory.
* b) nargs is less than VECTOR_GENERIC_FUNCTION_PREALLOCED_ARGS while the allocated memory is much more
* than that. As VECTOR_GENERIC_FUNCTION_PREALLOCED_ARGS is already enough in most senerios, we should
* reduce the memory.
*
* NOTE: To avoid memory wasting and memory fragments, we free and initilized a new GenericFunRuntimeArg.
*/
if (unlikely(nargs > genericRuntime->compacity) ||
(unlikely(genericRuntime->compacity > VECTOR_GENERIC_FUNCTION_PREALLOCED_ARGS) &&
nargs <= VECTOR_GENERIC_FUNCTION_PREALLOCED_ARGS)) {
FreeGenericFunRuntimeInfo(*genericRuntime);
InitGenericFunRuntimeInfo(*genericRuntime, nargs);
}
}
ScalarVector* pVector = New(CurrentMemoryContext) ScalarVector[nargs];
int i = 0;
if (fcache->args && fcache->args->length > 0) {
Oid* actual_arg_types = (Oid*)palloc0(fcache->args->length * sizeof(Oid));
foreach (cell, fcache->args) {
ExprState* argstate = (ExprState*)lfirst(cell);
Oid funcrettype;
TupleDesc tupdesc;
ScalarDesc desc;
(void)get_expr_result_type((Node*)argstate->expr, &funcrettype, &tupdesc);
desc.typeId = funcrettype;
desc.encoded = COL_IS_ENCODE(funcrettype);
fcache->fcinfo_data.flinfo->genericRuntime->args[i].argType = funcrettype;
pVector[i].init(CurrentMemoryContext, desc);
/* Record the real arg types from sub functions. */
actual_arg_types[i] = funcrettype;
i++;
}
/* Find the real return type for func with return type like ANYELEMENT. */
fcache->fcinfo_data.flinfo->fn_rettype = getRealFuncRetype(i, actual_arg_types, fcache);
pfree_ext(actual_arg_types);
}
fcache->fcinfo_data.argVector = pVector;
}
(void)MemoryContextSwitchTo(oldcontext);
if (vectorized) {
if (fcache->func.fn_retset == true) {
if (fcache->func.fn_oid != OID_REGEXP_SPLIT_TO_TABLE &&
fcache->func.fn_oid != OID_REGEXP_SPLIT_TO_TABLE_NO_FLAG) {
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmodule(MOD_EXECUTOR),
errmsg("set-return function not supported in vector eninge")));
}
}
fcache->funcResultDesc = NULL;
} else {
/* If function returns set, prepare expected tuple descriptor */
if (fcache->func.fn_retset && needDescForSets) {
TypeFuncClass functypclass;
Oid funcrettype;
TupleDesc tupdesc;
MemoryContext oldmemcontext;
functypclass = get_expr_result_type(fcache->func.fn_expr, &funcrettype, &tupdesc);
/* Must save tupdesc in fcache's context */
oldmemcontext = MemoryContextSwitchTo(fcacheCxt);
if (functypclass == TYPEFUNC_COMPOSITE) {
/* Composite data type, e.g. a table's row type */
Assert(tupdesc);
/* Must copy it out of typcache for safety */
fcache->funcResultDesc = CreateTupleDescCopy(tupdesc);
fcache->funcReturnsTuple = true;
} else if (functypclass == TYPEFUNC_SCALAR) {
/* Base data type, i.e. scalar */
tupdesc = CreateTemplateTupleDesc(1, false, TAM_HEAP);
TupleDescInitEntry(tupdesc, (AttrNumber)1, NULL, funcrettype, -1, 0);
fcache->funcResultDesc = tupdesc;
fcache->funcReturnsTuple = false;
} else if (functypclass == TYPEFUNC_RECORD) {
/* This will work if function doesn't need an expectedDesc */
fcache->funcResultDesc = NULL;
fcache->funcReturnsTuple = true;
} else {
/* Else, we will fail if function needs an expectedDesc */
fcache->funcResultDesc = NULL;
}
MemoryContextSwitchTo(oldmemcontext);
} else
fcache->funcResultDesc = NULL;
}
/* Initialize additional state */
fcache->funcResultStore = NULL;
fcache->funcResultSlot = NULL;
fcache->setArgsValid = false;
fcache->shutdown_reg = false;
}
void initVectorFcache(Oid foid, Oid input_collation, FuncExprState* fcache, MemoryContext fcacheCxt)
{
init_fcache<true>(foid, input_collation, fcache, fcacheCxt, false);
}
/*
* callback function in case a FuncExpr returning a set needs to be shut down
* before it has been run to completion
*/
static void ShutdownFuncExpr(Datum arg)
{
FuncExprState* fcache = (FuncExprState*)DatumGetPointer(arg);
/* If we have a slot, make sure it's let go of any tuplestore pointer */
if (fcache->funcResultSlot)
(void)ExecClearTuple(fcache->funcResultSlot);
/* Release any open tuplestore */
if (fcache->funcResultStore)
tuplestore_end(fcache->funcResultStore);
fcache->funcResultStore = NULL;
/* Clear any active set-argument state */
fcache->setArgsValid = false;
/* execUtils will deregister the callback... */
fcache->shutdown_reg = false;
}
/*
* get_cached_rowtype: utility function to lookup a rowtype tupdesc
*
* type_id, typmod: identity of the rowtype
* cache_field: where to cache the TupleDesc pointer in expression state node
* (field must be initialized to NULL)
* econtext: expression context we are executing in
*
* NOTE: because the shutdown callback will be called during plan rescan,
* must be prepared to re-do this during any node execution; cannot call
* just once during expression initialization
*/
static TupleDesc get_cached_rowtype(Oid type_id, int32 typmod, TupleDesc* cache_field, ExprContext* econtext)
{
TupleDesc tupDesc = *cache_field;
/* Do lookup if no cached value or if requested type changed */
if (tupDesc == NULL || type_id != tupDesc->tdtypeid || typmod != tupDesc->tdtypmod) {
tupDesc = lookup_rowtype_tupdesc(type_id, typmod);
if (*cache_field) {
/* Release old tupdesc; but callback is already registered */
ReleaseTupleDesc(*cache_field);
} else {
/* Need to register shutdown callback to release tupdesc */
RegisterExprContextCallback(econtext, ShutdownTupleDescRef, PointerGetDatum(cache_field));
}
*cache_field = tupDesc;
}
return tupDesc;
}
/*
* Callback function to release a tupdesc refcount at expression tree shutdown
*/
static void ShutdownTupleDescRef(Datum arg)
{
TupleDesc* cache_field = (TupleDesc*)DatumGetPointer(arg);
if (*cache_field)
ReleaseTupleDesc(*cache_field);
*cache_field = NULL;
}
/*
* Evaluate arguments for a function.
*/
template <bool has_refcursor>
static ExprDoneCond ExecEvalFuncArgs(
FunctionCallInfo fcinfo, List* argList, ExprContext* econtext, int* plpgsql_var_dno)
{
ExprDoneCond argIsDone;
int i;
ListCell* arg = NULL;
argIsDone = ExprSingleResult; /* default assumption */
i = 0;
econtext->is_cursor = false;
foreach (arg, argList) {
ExprState* argstate = (ExprState*)lfirst(arg);
ExprDoneCond thisArgIsDone;
if (has_refcursor && argstate->resultType == REFCURSOROID)
econtext->is_cursor = true;
fcinfo->arg[i] = ExecEvalExpr(argstate, econtext, &fcinfo->argnull[i], &thisArgIsDone);
if (has_refcursor && econtext->is_cursor && plpgsql_var_dno != NULL) {
plpgsql_var_dno[i] = econtext->dno;
CopyCursorInfoData(&fcinfo->refcursor_data.argCursor[i], &econtext->cursor_data);
}
fcinfo->argTypes[i] = argstate->resultType;
econtext->is_cursor = false;
if (thisArgIsDone != ExprSingleResult) {
/*
* We allow only one argument to have a set value; we'd need much
* more complexity to keep track of multiple set arguments (cf.
* ExecTargetList) and it doesn't seem worth it.
*/
if (argIsDone != ExprSingleResult)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("functions and operators can take at most one set argument")));
argIsDone = thisArgIsDone;
}
i++;
}
Assert(i == fcinfo->nargs);
return argIsDone;
}
/*
* ExecPrepareTuplestoreResult
*
* Subroutine for ExecMakeFunctionResult: prepare to extract rows from a
* tuplestore function result. We must set up a funcResultSlot (unless
* already done in a previous call cycle) and verify that the function
* returned the expected tuple descriptor.
*/
static void ExecPrepareTuplestoreResult(
FuncExprState* fcache, ExprContext* econtext, Tuplestorestate* resultStore, TupleDesc resultDesc)
{
fcache->funcResultStore = resultStore;
if (fcache->funcResultSlot == NULL) {
/* Create a slot so we can read data out of the tuplestore */
TupleDesc slotDesc;
MemoryContext oldcontext;
oldcontext = MemoryContextSwitchTo(fcache->func.fn_mcxt);
/*
* If we were not able to determine the result rowtype from context,
* and the function didn't return a tupdesc, we have to fail.
*/
if (fcache->funcResultDesc)
slotDesc = fcache->funcResultDesc;
else if (resultDesc) {
/* don't assume resultDesc is long-lived */
slotDesc = CreateTupleDescCopy(resultDesc);
} else {
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning setof record called in context that cannot accept type record")));
slotDesc = NULL; /* keep compiler quiet */
}
fcache->funcResultSlot = MakeSingleTupleTableSlot(slotDesc);
MemoryContextSwitchTo(oldcontext);
}
/*
* If function provided a tupdesc, cross-check it. We only really need to
* do this for functions returning RECORD, but might as well do it always.
*/
if (resultDesc) {
if (fcache->funcResultDesc)
tupledesc_match(fcache->funcResultDesc, resultDesc);
/*
* If it is a dynamically-allocated TupleDesc, free it: it is
* typically allocated in a per-query context, so we must avoid
* leaking it across multiple usages.
*/
if (resultDesc->tdrefcount == -1)
FreeTupleDesc(resultDesc);
}
/* Register cleanup callback if we didn't already */
if (!fcache->shutdown_reg) {
RegisterExprContextCallback(econtext, ShutdownFuncExpr, PointerGetDatum(fcache));
fcache->shutdown_reg = true;
}
}
/*
* Check that function result tuple type (src_tupdesc) matches or can
* be considered to match what the query expects (dst_tupdesc). If
* they don't match, ereport.
*
* We really only care about number of attributes and data type.
* Also, we can ignore type mismatch on columns that are dropped in the
* destination type, so long as the physical storage matches. This is
* helpful in some cases involving out-of-date cached plans.
*/
static void tupledesc_match(TupleDesc dst_tupdesc, TupleDesc src_tupdesc)
{
int i;
if (dst_tupdesc->natts != src_tupdesc->natts)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("function return row and query-specified return row do not match"),
errdetail_plural("Returned row contains %d attribute, but query expects %d.",
"Returned row contains %d attributes, but query expects %d.",
src_tupdesc->natts,
src_tupdesc->natts,
dst_tupdesc->natts)));
for (i = 0; i < dst_tupdesc->natts; i++) {
Form_pg_attribute dattr = dst_tupdesc->attrs[i];
Form_pg_attribute sattr = src_tupdesc->attrs[i];
if (IsBinaryCoercible(sattr->atttypid, dattr->atttypid))
continue; /* no worries */
if (!dattr->attisdropped)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("function return row and query-specified return row do not match"),
errdetail("Returned type %s at ordinal position %d, but query expects %s.",
format_type_be(sattr->atttypid),
i + 1,
format_type_be(dattr->atttypid))));
if (dattr->attlen != sattr->attlen || dattr->attalign != sattr->attalign)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("function return row and query-specified return row do not match"),
errdetail("Physical storage mismatch on dropped attribute at ordinal position %d.", i + 1)));
}
}
/*
* ExecMakeFunctionResult
*
* Evaluate the arguments to a function and then the function itself.
* init_fcache is presumed already run on the FuncExprState.
*
* This function handles the most general case, wherein the function or
* one of its arguments can return a set.
*
* Note: This function use template parameter can compile different function,
* reduce the assembly instructions so as to improve performance.
*
* Template parameter:
* @bool has_cursor_return - need store out-args cursor info.
* @bool has_refcursor - need store in-args cursor info.
* @bool isSetReturnFunc - indicate function returns a set.
*/
template <bool has_refcursor, bool has_cursor_return, bool isSetReturnFunc>
static Datum ExecMakeFunctionResult(FuncExprState* fcache, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
List* arguments = NIL;
Datum result;
FunctionCallInfo fcinfo;
PgStat_FunctionCallUsage fcusage;
ReturnSetInfo rsinfo; /* for functions returning sets */
ExprDoneCond argDone;
bool hasSetArg = false;
int i;
int* var_dno = NULL;
econtext->plpgsql_estate = plpgsql_estate;
plpgsql_estate = NULL;
restart:
/* Guard against stack overflow due to overly complex expressions */
check_stack_depth();
/*
* If a previous call of the function returned a set result in the form of
* a tuplestore, continue reading rows from the tuplestore until it's
* empty.
*/
if (fcache->funcResultStore) {
/* it was provided before ... */
if (unlikely(isDone == NULL)) {
ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("set-valued function called in context that cannot accept a set")));
}
if (tuplestore_gettupleslot(fcache->funcResultStore, true, false, fcache->funcResultSlot)) {
*isDone = ExprMultipleResult;
if (fcache->funcReturnsTuple) {
/* We must return the whole tuple as a Datum. */
*isNull = false;
return ExecFetchSlotTupleDatum(fcache->funcResultSlot);
} else {
/* Extract the first column and return it as a scalar. */
Assert(fcache->funcResultSlot != NULL);
/* Get the Table Accessor Method*/
return tableam_tslot_getattr(fcache->funcResultSlot, 1, isNull);
}
}
/* Exhausted the tuplestore, so clean up */
tuplestore_end(fcache->funcResultStore);
fcache->funcResultStore = NULL;
/* We are done unless there was a set-valued argument */
if (!fcache->setHasSetArg) {
*isDone = ExprEndResult;
*isNull = true;
return (Datum)0;
}
/* If there was, continue evaluating the argument values */
Assert(!fcache->setArgsValid);
}
/*
* arguments is a list of expressions to evaluate before passing to the
* function manager. We skip the evaluation if it was already done in the
* previous call (ie, we are continuing the evaluation of a set-valued
* function). Otherwise, collect the current argument values into fcinfo.
*/
fcinfo = &fcache->fcinfo_data;
if (has_cursor_return) {
/* init returnCursor to store out-args cursor info on ExprContext*/
fcinfo->refcursor_data.returnCursor =
(Cursor_Data*)palloc0(sizeof(Cursor_Data) * fcinfo->refcursor_data.return_number);
} else {
fcinfo->refcursor_data.returnCursor = NULL;
}
if (has_refcursor) {
/* init argCursor to store in-args cursor info on ExprContext*/
fcinfo->refcursor_data.argCursor = (Cursor_Data*)palloc0(sizeof(Cursor_Data) * fcinfo->nargs);
var_dno = (int*)palloc0(sizeof(int) * fcinfo->nargs);
for (i = 0; i < fcinfo->nargs; i++) {
var_dno[i] = -1;
}
}
arguments = fcache->args;
if (!fcache->setArgsValid) {
if (has_refcursor)
argDone = ExecEvalFuncArgs<true>(fcinfo, arguments, econtext, var_dno);
else
argDone = ExecEvalFuncArgs<false>(fcinfo, arguments, econtext);
if (argDone == ExprEndResult) {
/* input is an empty set, so return an empty set. */
*isNull = true;
if (isDone != NULL)
*isDone = ExprEndResult;
else
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("set-valued function called in context that cannot accept a set")));
return (Datum)0;
}
hasSetArg = (argDone != ExprSingleResult);
} else {
/* Re-use callinfo from previous evaluation */
hasSetArg = fcache->setHasSetArg;
/* Reset flag (we may set it again below) */
fcache->setArgsValid = false;
}
/*
* Now call the function, passing the evaluated parameter values.
*/
if (fcache->func.fn_retset || hasSetArg) {
/*
* We need to return a set result. Complain if caller not ready to
* accept one.
*/
if (isDone == NULL)
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("set-valued function called in context that cannot accept a set")));
/*
* Prepare a resultinfo node for communication. If the function
* doesn't itself return set, we don't pass the resultinfo to the
* function, but we need to fill it in anyway for internal use.
*/
if (fcache->func.fn_retset)
fcinfo->resultinfo = (Node*)&rsinfo;
rsinfo.type = T_ReturnSetInfo;
rsinfo.econtext = econtext;
rsinfo.expectedDesc = fcache->funcResultDesc;
rsinfo.allowedModes = (int)(SFRM_ValuePerCall | SFRM_Materialize);
/* note we do not set SFRM_Materialize_Random or _Preferred */
rsinfo.returnMode = SFRM_ValuePerCall;
/* isDone is filled below */
rsinfo.setResult = NULL;
rsinfo.setDesc = NULL;
/*
* This loop handles the situation where we have both a set argument
* and a set-valued function. Once we have exhausted the function's
* value(s) for a particular argument value, we have to get the next
* argument value and start the function over again. We might have to
* do it more than once, if the function produces an empty result set
* for a particular input value.
*/
for (;;) {
/*
* If function is strict, and there are any NULL arguments, skip
* calling the function (at least for this set of args).
*/
bool callit = true;
if (fcache->func.fn_strict) {
for (i = 0; i < fcinfo->nargs; i++) {
if (fcinfo->argnull[i]) {
callit = false;
break;
}
}
}
if (callit) {
pgstat_init_function_usage(fcinfo, &fcusage);
fcinfo->isnull = false;
rsinfo.isDone = ExprSingleResult;
result = FunctionCallInvoke(fcinfo);
*isNull = fcinfo->isnull;
*isDone = rsinfo.isDone;
pgstat_end_function_usage(&fcusage, rsinfo.isDone != ExprMultipleResult);
} else if (isSetReturnFunc) {
/*
* For a strict SRF, result for NULL is an empty set
* If SRF is strict and has any NULL arguments, this SRF
* need return empty set, so such rows were omitted entirely
* from the result set.
*/
result = (Datum)0;
*isNull = true;
*isDone = ExprEndResult;
} else {
/*
* For a strict non-SRF, result for NULL is a NULL.
* This branch in order to deal strict nested functions
* like "select plain_function(set_returning_function(...))".
* If some of the SRF outputs are NULL, and the plain function
* is strict, we expect to get NULL results for such rows
*/
result = (Datum)0;
*isNull = true;
*isDone = ExprSingleResult;
}
if (has_refcursor && econtext->plpgsql_estate != NULL) {
PLpgSQL_execstate* estate = econtext->plpgsql_estate;
/* copy in-args cursor option info */
for (i = 0; i < fcinfo->nargs; i++) {
if (var_dno[i] >= 0) {
int dno = var_dno[i];
Cursor_Data* cursor_data = &fcinfo->refcursor_data.argCursor[i];
#ifdef USE_ASSERT_CHECKING
PLpgSQL_datum* datum = estate->datums[dno];
#endif
Assert(datum->dtype == PLPGSQL_DTYPE_VAR);
Assert(((PLpgSQL_var*)datum)->datatype->typoid == REFCURSOROID);
ExecCopyDataToDatum(estate->datums, dno, cursor_data);
}
}
if (fcinfo->refcursor_data.return_number > 0) {
/* copy function returns cursor option info.
* for simple expr in exec_eval_expr, we can not get the result type,
* so cursor_return_data mallocs here.
*/
if (estate->cursor_return_data == NULL && estate->tuple_store_cxt != NULL) {
MemoryContext oldcontext = MemoryContextSwitchTo(estate->tuple_store_cxt);
estate->cursor_return_data =
(Cursor_Data*)palloc0(sizeof(Cursor_Data) * fcinfo->refcursor_data.return_number);
(void)MemoryContextSwitchTo(oldcontext);
}
if (estate->cursor_return_data != NULL) {
for (i = 0; i < fcinfo->refcursor_data.return_number; i++) {
int rc = memcpy_s(&estate->cursor_return_data[i], sizeof(Cursor_Data),
&fcinfo->refcursor_data.returnCursor[i], sizeof(Cursor_Data));
securec_check(rc, "\0", "\0");
}
}
}
}
/* Which protocol does function want to use? */
if (rsinfo.returnMode == SFRM_ValuePerCall) {
if (*isDone != ExprEndResult) {
/*
* Got a result from current argument. If function itself
* returns set, save the current argument values to re-use
* on the next call.
*/
if (fcache->func.fn_retset && *isDone == ExprMultipleResult) {
fcache->setHasSetArg = hasSetArg;
fcache->setArgsValid = true;
/* Register cleanup callback if we didn't already */
if (!fcache->shutdown_reg) {
RegisterExprContextCallback(econtext, ShutdownFuncExpr, PointerGetDatum(fcache));
fcache->shutdown_reg = true;
}
}
/*
* Make sure we say we are returning a set, even if the
* function itself doesn't return sets.
*/
if (hasSetArg) {
*isDone = ExprMultipleResult;
}
break;
}
} else if (rsinfo.returnMode == SFRM_Materialize) {
/* check we're on the same page as the function author */
if (rsinfo.isDone != ExprSingleResult)
ereport(ERROR, (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
errmsg("table-function protocol for materialize mode was not followed")));
if (rsinfo.setResult != NULL) {
/* prepare to return values from the tuplestore */
ExecPrepareTuplestoreResult(fcache, econtext, rsinfo.setResult, rsinfo.setDesc);
/* remember whether we had set arguments */
fcache->setHasSetArg = hasSetArg;
/* loop back to top to start returning from tuplestore */
goto restart;
}
/* if setResult was left null, treat it as empty set */
*isDone = ExprEndResult;
*isNull = true;
result = (Datum)0;
} else {
ereport(ERROR, (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
errmsg("unrecognized table-function returnMode: %d", (int)rsinfo.returnMode)));
}
/* Else, done with this argument */
if (!hasSetArg) {
break; /* input not a set, so done */
}
/* Re-eval args to get the next element of the input set */
if (has_refcursor) {
argDone = ExecEvalFuncArgs<true>(fcinfo, arguments, econtext, var_dno);
} else {
argDone = ExecEvalFuncArgs<false>(fcinfo, arguments, econtext);
}
if (argDone != ExprMultipleResult) {
/* End of argument set, so we're done. */
*isNull = true;
*isDone = ExprEndResult;
result = (Datum)0;
break;
}
/*
* If we reach here, loop around to run the function on the new
* argument.
*/
}
} else {
/*
* Non-set case: much easier.
*
* In common cases, this code path is unreachable because we'd have
* selected ExecMakeFunctionResultNoSets instead. However, it's
* possible to get here if an argument sometimes produces set results
* and sometimes scalar results. For example, a CASE expression might
* call a set-returning function in only some of its arms.
*/
if (isDone != NULL)
*isDone = ExprSingleResult;
/*
* If function is strict, and there are any NULL arguments, skip
* calling the function and return NULL.
*/
if (fcache->func.fn_strict) {
for (i = 0; i < fcinfo->nargs; i++) {
if (fcinfo->argnull[i]) {
*isNull = true;
return (Datum)0;
}
}
}
pgstat_init_function_usage(fcinfo, &fcusage);
fcinfo->isnull = false;
result = FunctionCallInvoke(fcinfo);
*isNull = fcinfo->isnull;
pgstat_end_function_usage(&fcusage, true);
}
if (has_refcursor) {
pfree_ext(fcinfo->refcursor_data.argCursor);
pfree_ext(var_dno);
}
return result;
}
/*
* ExecMakeFunctionResultNoSets
*
* Simplified version of ExecMakeFunctionResult that can only handle
* non-set cases. Hand-tuned for speed.
*
* Note: This function use template parameter can compile different function,
* reduce the assembly instructions so as to improve performance.
*
* Template parameter:
* @bool has_cursor_return - need store out-args cursor info.
* @bool has_refcursor - need store in-args cursor info.
*/
template <bool has_refcursor, bool has_cursor_return>
static Datum ExecMakeFunctionResultNoSets(
FuncExprState* fcache, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
ListCell* arg = NULL;
Datum result;
FunctionCallInfo fcinfo;
PgStat_FunctionCallUsage fcusage;
int i;
int* var_dno = NULL;
FunctionScanState *node = NULL;
FuncExpr *fexpr = NULL;
bool savedIsSTP = u_sess->SPI_cxt.is_stp;
bool savedProConfigIsSet = u_sess->SPI_cxt.is_proconfig_set;
bool proIsProcedure = false;
bool supportTranaction = false;
#ifdef ENABLE_MULTIPLE_NODES
if (IS_PGXC_COORDINATOR && (t_thrd.proc->workingVersionNum >= STP_SUPPORT_COMMIT_ROLLBACK)) {
supportTranaction = true;
}
#else
supportTranaction = true;
#endif
bool needResetErrMsg = (u_sess->SPI_cxt.forbidden_commit_rollback_err_msg[0] == '\0');
/* Only allow commit at CN, therefore only need to set atomic and
* relevant check at CN level.
*/
if (supportTranaction && IsA(fcache->xprstate.expr, FuncExpr)) {
fexpr = (FuncExpr *) fcache->xprstate.expr;
node = makeNode(FunctionScanState);
if (!u_sess->SPI_cxt.is_allow_commit_rollback) {
node->atomic = true;
}
else if (IsAfterTriggerBegin()) {
node->atomic = true;
stp_set_commit_rollback_err_msg(STP_XACT_AFTER_TRIGGER_BEGIN);
}
proIsProcedure = PROC_IS_PRO(fcache->prokind);
if (u_sess->SPI_cxt.is_proconfig_set) {
node->atomic = true;
}
/* if proIsProcedure is ture means it was a stored procedure */
u_sess->SPI_cxt.is_stp = savedIsSTP && proIsProcedure;
}
/* Guard against stack overflow due to overly complex expressions */
check_stack_depth();
if (isDone != NULL)
*isDone = ExprSingleResult;
econtext->plpgsql_estate = plpgsql_estate;
plpgsql_estate = NULL;
/* inlined, simplified version of ExecEvalFuncArgs */
fcinfo = &fcache->fcinfo_data;
/* init the number of arguments to a function*/
InitFunctionCallInfoArgs(*fcinfo, list_length(fcache->args), 1);
/* Only allow commit at CN, therefore need to set callcontext in CN only */
if (supportTranaction) {
fcinfo->context = (Node *)node;
}
if (has_cursor_return) {
/* init returnCursor to store out-args cursor info on ExprContext*/
fcinfo->refcursor_data.returnCursor =
(Cursor_Data*)palloc0(sizeof(Cursor_Data) * fcinfo->refcursor_data.return_number);
} else {
fcinfo->refcursor_data.returnCursor = NULL;
}
if (has_refcursor) {
/* init argCursor to store in-args cursor info on ExprContext */
fcinfo->refcursor_data.argCursor = (Cursor_Data*)palloc0(sizeof(Cursor_Data) * fcinfo->nargs);
var_dno = (int*)palloc0(sizeof(int) * fcinfo->nargs);
for (i = 0; i < fcinfo->nargs; i++) {
var_dno[i] = -1;
}
}
i = 0;
econtext->is_cursor = false;
foreach (arg, fcache->args) {
ExprState* argstate = (ExprState*)lfirst(arg);
fcinfo->argTypes[i] = argstate->resultType;
if (has_refcursor && fcinfo->argTypes[i] == REFCURSOROID)
econtext->is_cursor = true;
fcinfo->arg[i] = ExecEvalExpr(argstate, econtext, &fcinfo->argnull[i], NULL);
if (has_refcursor && econtext->is_cursor) {
var_dno[i] = econtext->dno;
CopyCursorInfoData(&fcinfo->refcursor_data.argCursor[i], &econtext->cursor_data);
}
econtext->is_cursor = false;
i++;
}
/*
* If function is strict, and there are any NULL arguments, skip calling
* the function and return NULL.
*/
if (fcache->func.fn_strict) {
while (--i >= 0) {
if (fcinfo->argnull[i]) {
*isNull = true;
u_sess->SPI_cxt.is_stp = savedIsSTP;
u_sess->SPI_cxt.is_proconfig_set = savedProConfigIsSet;
if (needResetErrMsg) {
stp_reset_commit_rolback_err_msg();
}
return (Datum)0;
}
}
}
pgstat_init_function_usage(fcinfo, &fcusage);
fcinfo->isnull = false;
if (u_sess->instr_cxt.global_instr != NULL && fcinfo->flinfo->fn_addr == plpgsql_call_handler) {
StreamInstrumentation* save_global_instr = u_sess->instr_cxt.global_instr;
u_sess->instr_cxt.global_instr = NULL;
result = FunctionCallInvoke(fcinfo);
u_sess->instr_cxt.global_instr = save_global_instr;
}
else {
result = FunctionCallInvoke(fcinfo);
}
*isNull = fcinfo->isnull;
if (has_refcursor && econtext->plpgsql_estate != NULL) {
PLpgSQL_execstate* estate = econtext->plpgsql_estate;
for (i = 0; i < fcinfo->nargs; i++) {
/* copy in-args cursor option info */
if (var_dno[i] >= 0) {
int dno = var_dno[i];
Cursor_Data* cursor_data = &fcinfo->refcursor_data.argCursor[i];
#ifdef USE_ASSERT_CHECKING
PLpgSQL_datum* datum = estate->datums[dno];
#endif
Assert(datum->dtype == PLPGSQL_DTYPE_VAR);
Assert(((PLpgSQL_var*)datum)->datatype->typoid == REFCURSOROID);
ExecCopyDataToDatum(estate->datums, dno, cursor_data);
}
}
if (fcinfo->flinfo->fn_rettype == REFCURSOROID) {
/* copy function returns cursor option info.
* for simple expr in exec_eval_expr, we can not get the result type,
* so cursor_return_data mallocs here.
*/
if (estate->cursor_return_data == NULL) {
estate->cursor_return_data = (Cursor_Data*)palloc0(sizeof(Cursor_Data));
}
int rc = memcpy_s(estate->cursor_return_data,
sizeof(Cursor_Data),
fcinfo->refcursor_data.returnCursor,
sizeof(Cursor_Data));
securec_check(rc, "\0", "\0");
}
}
pgstat_end_function_usage(&fcusage, true);
if (has_refcursor) {
if (fcinfo->refcursor_data.argCursor != NULL)
pfree_ext(fcinfo->refcursor_data.argCursor);
if (var_dno != NULL)
pfree_ext(var_dno);
}
if(node != NULL)
pfree_ext(node);
u_sess->SPI_cxt.is_stp = savedIsSTP;
u_sess->SPI_cxt.is_proconfig_set = savedProConfigIsSet;
if (needResetErrMsg) {
stp_reset_commit_rolback_err_msg();
}
return result;
}
/*
* @Description: jugde function has parameter that is refcursor or return type is refcursor
* @in Funcid - function oid
* @in fcinfo - function call info
* @return - has refcursor
*/
static bool func_has_refcursor_args(Oid Funcid, FunctionCallInfoData* fcinfo)
{
HeapTuple proctup = NULL;
Form_pg_proc procStruct;
int allarg;
Oid* p_argtypes = NULL;
char** p_argnames = NULL;
char* p_argmodes = NULL;
bool use_cursor = false;
bool return_refcursor = false;
int out_count = 0; /* out arg count */
proctup = SearchSysCache(PROCOID, ObjectIdGetDatum(Funcid), 0, 0, 0);
/*
* function may be deleted after clist be searched.
*/
if (!HeapTupleIsValid(proctup)) {
ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), errmsg("function doesn't exist ")));
}
/* get the all args informations, only "in" parameters if p_argmodes is null */
allarg = get_func_arg_info(proctup, &p_argtypes, &p_argnames, &p_argmodes);
procStruct = (Form_pg_proc)GETSTRUCT(proctup);
fcinfo->refcursor_data.return_number = 0;
fcinfo->refcursor_data.returnCursor = NULL;
for (int i = 0; i < allarg; i++) {
if (p_argmodes != NULL && (p_argmodes[i] == 'o' || p_argmodes[i] == 'b')) {
out_count++;
if (p_argtypes[i] == REFCURSOROID)
return_refcursor = true;
} else {
if (p_argtypes[i] == REFCURSOROID)
use_cursor = true;
}
}
if (procStruct->prorettype == REFCURSOROID) {
use_cursor = true;
fcinfo->refcursor_data.return_number = 1;
} else if (return_refcursor) {
fcinfo->refcursor_data.return_number = out_count;
}
ReleaseSysCache(proctup);
return use_cursor;
}
/*
* ExecMakeTableFunctionResult
*
* Evaluate a table function, producing a materialized result in a Tuplestore
* object.
*/
Tuplestorestate* ExecMakeTableFunctionResult(
ExprState* funcexpr, ExprContext* econtext, TupleDesc expectedDesc, bool randomAccess, FunctionScanState* node)
{
Tuplestorestate* tupstore = NULL;
TupleDesc tupdesc = NULL;
Oid funcrettype;
bool returnsTuple = false;
bool returnsSet = false;
FunctionCallInfoData fcinfo;
PgStat_FunctionCallUsage fcusage;
ReturnSetInfo rsinfo;
HeapTupleData tmptup;
MemoryContext callerContext;
MemoryContext oldcontext;
bool direct_function_call = false;
bool first_time = true;
int* var_dno = NULL;
bool has_refcursor = false;
FuncExpr *fexpr = NULL;
bool savedIsSTP = u_sess->SPI_cxt.is_stp;
bool savedProConfigIsSet = u_sess->SPI_cxt.is_proconfig_set;
bool proIsProcedure = false;
bool supportTranaction = false;
#ifdef ENABLE_MULTIPLE_NODES
if (IS_PGXC_COORDINATOR && (t_thrd.proc->workingVersionNum >= STP_SUPPORT_COMMIT_ROLLBACK)) {
supportTranaction = true;
}
#else
supportTranaction = true;
#endif
bool needResetErrMsg = (u_sess->SPI_cxt.forbidden_commit_rollback_err_msg[0] == '\0');
/* Only allow commit at CN, therefore only need to set atomic and relevant check at CN level. */
if (supportTranaction && IsA(funcexpr->expr, FuncExpr)) {
fexpr = (FuncExpr*)funcexpr->expr;
if (!u_sess->SPI_cxt.is_allow_commit_rollback) {
node->atomic = true;
}
else if (IsAfterTriggerBegin()) {
node->atomic = true;
stp_set_commit_rollback_err_msg(STP_XACT_AFTER_TRIGGER_BEGIN);
}
char prokind = (reinterpret_cast<FuncExprState*>(funcexpr))->prokind;
proIsProcedure = PROC_IS_PRO(prokind);
if (u_sess->SPI_cxt.is_proconfig_set) {
node->atomic = true;
}
/* if proIsProcedure means it was a stored procedure */
u_sess->SPI_cxt.is_stp = savedIsSTP && proIsProcedure;
}
callerContext = CurrentMemoryContext;
if (unlikely(funcexpr == NULL)) {
ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("The input function expression is NULL.")));
}
funcrettype = exprType((Node*)funcexpr->expr);
returnsTuple = type_is_rowtype(funcrettype);
econtext->plpgsql_estate = plpgsql_estate;
plpgsql_estate = NULL;
/*
* Prepare a resultinfo node for communication. We always do this even if
* not expecting a set result, so that we can pass expectedDesc. In the
* generic-expression case, the expression doesn't actually get to see the
* resultinfo, but set it up anyway because we use some of the fields as
* our own state variables.
*/
rsinfo.type = T_ReturnSetInfo;
rsinfo.econtext = econtext;
rsinfo.expectedDesc = expectedDesc;
rsinfo.allowedModes = (int)(SFRM_ValuePerCall | SFRM_Materialize | SFRM_Materialize_Preferred);
if (randomAccess)
rsinfo.allowedModes |= (int)SFRM_Materialize_Random;
rsinfo.returnMode = SFRM_ValuePerCall;
/* isDone is filled below */
rsinfo.setResult = NULL;
rsinfo.setDesc = NULL;
/*
* Normally the passed expression tree will be a FuncExprState, since the
* grammar only allows a function call at the top level of a table
* function reference. However, if the function doesn't return set then
* the planner might have replaced the function call via constant-folding
* or inlining. So if we see any other kind of expression node, execute
* it via the general ExecEvalExpr() code; the only difference is that we
* don't get a chance to pass a special ReturnSetInfo to any functions
* buried in the expression.
*/
if (funcexpr && IsA(funcexpr, FuncExprState) && IsA(funcexpr->expr, FuncExpr)) {
FuncExprState* fcache = (FuncExprState*)funcexpr;
ExprDoneCond argDone;
/*
* This path is similar to ExecMakeFunctionResult.
*/
direct_function_call = true;
/*
* Initialize function cache if first time through
*/
if (fcache->func.fn_oid == InvalidOid) {
FuncExpr* func = (FuncExpr*)fcache->xprstate.expr;
init_fcache<false>(func->funcid, func->inputcollid, fcache, econtext->ecxt_per_query_memory, false);
}
returnsSet = fcache->func.fn_retset;
InitFunctionCallInfoData(fcinfo,
&(fcache->func),
list_length(fcache->args),
fcache->fcinfo_data.fncollation,
(Node*)node,
(Node*)&rsinfo);
has_refcursor = func_has_refcursor_args(fcinfo.flinfo->fn_oid, &fcinfo);
int cursor_return_number = fcinfo.refcursor_data.return_number;
if (cursor_return_number > 0) {
/* init returnCursor to store out-args cursor info on FunctionScan context*/
fcinfo.refcursor_data.returnCursor = (Cursor_Data*)palloc0(sizeof(Cursor_Data) * cursor_return_number);
} else {
fcinfo.refcursor_data.returnCursor = NULL;
}
if (has_refcursor) {
/* init argCursor to store in-args cursor info on FunctionScan context*/
fcinfo.refcursor_data.argCursor = (Cursor_Data*)palloc0(sizeof(Cursor_Data) * fcinfo.nargs);
var_dno = (int*)palloc0(sizeof(int) * fcinfo.nargs);
int rc = memset_s(var_dno, sizeof(int) * fcinfo.nargs, -1, sizeof(int) * fcinfo.nargs);
securec_check(rc, "\0", "\0");
}
/*
* Evaluate the function's argument list.
*
* Note: ideally, we'd do this in the per-tuple context, but then the
* argument values would disappear when we reset the context in the
* inner loop. So do it in caller context. Perhaps we should make a
* separate context just to hold the evaluated arguments?
*/
if (has_refcursor)
argDone = ExecEvalFuncArgs<true>(&fcinfo, fcache->args, econtext, var_dno);
else
argDone = ExecEvalFuncArgs<false>(&fcinfo, fcache->args, econtext);
/* We don't allow sets in the arguments of the table function */
if (argDone != ExprSingleResult)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("set-valued function called in context that cannot accept a set")));
/*
* If function is strict, and there are any NULL arguments, skip
* calling the function and act like it returned NULL (or an empty
* set, in the returns-set case).
*/
if (fcache->func.fn_strict) {
int i;
for (i = 0; i < fcinfo.nargs; i++) {
if (fcinfo.argnull[i])
goto no_function_result;
}
}
} else {
/* Treat funcexpr as a generic expression */
direct_function_call = false;
InitFunctionCallInfoData(fcinfo, NULL, 0, InvalidOid, (Node*)node, NULL);
}
/*
* Switch to short-lived context for calling the function or expression.
*/
MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
/*
* Loop to handle the ValuePerCall protocol (which is also the same
* behavior needed in the generic ExecEvalExpr path).
*/
for (;;) {
Datum result;
CHECK_FOR_INTERRUPTS();
/*
* reset per-tuple memory context before each call of the function or
* expression. This cleans up any local memory the function may leak
* when called.
*/
ResetExprContext(econtext);
/* Call the function or expression one time */
if (direct_function_call) {
pgstat_init_function_usage(&fcinfo, &fcusage);
fcinfo.isnull = false;
rsinfo.isDone = ExprSingleResult;
result = FunctionCallInvoke(&fcinfo);
if (econtext->plpgsql_estate != NULL) {
PLpgSQL_execstate* estate = econtext->plpgsql_estate;
if (fcinfo.refcursor_data.return_number > 0 && estate->cursor_return_data != NULL &&
fcinfo.refcursor_data.returnCursor != NULL) {
for (int i = 0; i < fcinfo.refcursor_data.return_number; i++) {
CopyCursorInfoData(&estate->cursor_return_data[i], &fcinfo.refcursor_data.returnCursor[i]);
}
}
if (var_dno != NULL) {
for (int i = 0; i < fcinfo.nargs; i++) {
if (var_dno[i] >= 0) {
int dno = var_dno[i];
Cursor_Data* cursor_data = &fcinfo.refcursor_data.argCursor[i];
PLpgSQL_execstate* execstate = econtext->plpgsql_estate;
#ifdef USE_ASSERT_CHECKING
PLpgSQL_datum* datum = execstate->datums[dno];
#endif
Assert(datum->dtype == PLPGSQL_DTYPE_VAR);
Assert(((PLpgSQL_var*)datum)->datatype->typoid == REFCURSOROID);
ExecCopyDataToDatum(execstate->datums, dno, cursor_data);
}
}
}
}
pgstat_end_function_usage(&fcusage, rsinfo.isDone != ExprMultipleResult);
} else {
result = ExecEvalExpr(funcexpr, econtext, &fcinfo.isnull, &rsinfo.isDone);
}
/* Which protocol does function want to use? */
if (rsinfo.returnMode == SFRM_ValuePerCall) {
/*
* Check for end of result set.
*/
if (rsinfo.isDone == ExprEndResult) {
break;
}
/*
* Can't do anything very useful with NULL rowtype values. For a
* function returning set, we consider this a protocol violation
* (but another alternative would be to just ignore the result and
* "continue" to get another row). For a function not returning
* set, we fall out of the loop; we'll cons up an all-nulls result
* row below.
*/
if (returnsTuple && fcinfo.isnull) {
if (!returnsSet) {
break;
}
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("function returning set of rows cannot return null value")));
}
/*
* If first time through, build tupdesc and tuplestore for result
*/
if (first_time) {
oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
if (returnsTuple) {
/*
* Use the type info embedded in the rowtype Datum to look
* up the needed tupdesc. Make a copy for the query.
*/
HeapTupleHeader td;
td = DatumGetHeapTupleHeader(result);
if (IsA(funcexpr->expr, Const)) {
tupdesc = lookup_rowtype_tupdesc_copy(
((Const*)funcexpr->expr)->consttype, HeapTupleHeaderGetTypMod(td));
} else {
tupdesc =
lookup_rowtype_tupdesc_copy(HeapTupleHeaderGetTypeId(td), HeapTupleHeaderGetTypMod(td));
}
} else {
/*
* Scalar type, so make a single-column descriptor
*/
tupdesc = CreateTemplateTupleDesc(1, false, TAM_HEAP);
TupleDescInitEntry(tupdesc, (AttrNumber)1, "column", funcrettype, -1, 0);
}
tupstore = tuplestore_begin_heap(randomAccess, false, u_sess->attr.attr_memory.work_mem);
MemoryContextSwitchTo(oldcontext);
rsinfo.setResult = tupstore;
rsinfo.setDesc = tupdesc;
}
/*
* Store current resultset item.
*/
if (returnsTuple) {
HeapTupleHeader td;
td = DatumGetHeapTupleHeader(result);
/*
* Verify all returned rows have same subtype; necessary in
* case the type is RECORD.
*/
if ((HeapTupleHeaderGetTypeId(td) != tupdesc->tdtypeid ||
HeapTupleHeaderGetTypMod(td) != tupdesc->tdtypmod) &&
nodeTag(funcexpr->expr) != T_Const) {
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("rows returned by function are not all of the same row type"),
errdetail("return type id %u, tuple decription id %u, return typmod %d "
"tuple decription, typmod %d",
HeapTupleHeaderGetTypeId(td),
tupdesc->tdtypeid,
HeapTupleHeaderGetTypMod(td),
tupdesc->tdtypmod)));
}
/*
* tuplestore_puttuple needs a HeapTuple not a bare
* HeapTupleHeader, but it doesn't need all the fields.
*/
tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
tmptup.t_data = td;
tuplestore_puttuple(tupstore, &tmptup);
} else {
tuplestore_putvalues(tupstore, tupdesc, &result, &fcinfo.isnull);
}
/*
* Are we done?
*/
if (rsinfo.isDone != ExprMultipleResult) {
break;
}
} else if (rsinfo.returnMode == SFRM_Materialize) {
/* check we're on the same page as the function author */
if (!first_time || rsinfo.isDone != ExprSingleResult) {
ereport(ERROR,
(errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
errmsg("table-function protocol for materialize mode was not followed")));
}
/* Done evaluating the set result */
break;
} else {
ereport(ERROR,
(errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
errmsg("unrecognized table-function returnMode: %d", (int)rsinfo.returnMode)));
}
first_time = false;
}
no_function_result:
/*
* If we got nothing from the function (ie, an empty-set or NULL result),
* we have to create the tuplestore to return, and if it's a
* non-set-returning function then insert a single all-nulls row.
*/
if (rsinfo.setResult == NULL) {
MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
tupstore = tuplestore_begin_heap(randomAccess, false, u_sess->attr.attr_memory.work_mem);
rsinfo.setResult = tupstore;
if (!returnsSet) {
int natts = expectedDesc->natts;
Datum* nulldatums = NULL;
bool* nullflags = NULL;
errno_t rc = EOK;
MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
nulldatums = (Datum*)palloc0(natts * sizeof(Datum));
nullflags = (bool*)palloc(natts * sizeof(bool));
rc = memset_s(nullflags, natts * sizeof(bool), true, natts * sizeof(bool));
securec_check(rc, "\0", "\0");
MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
tuplestore_putvalues(tupstore, expectedDesc, nulldatums, nullflags);
}
}
/*
* If function provided a tupdesc, cross-check it. We only really need to
* do this for functions returning RECORD, but might as well do it always.
*/
if (rsinfo.setDesc) {
tupledesc_match(expectedDesc, rsinfo.setDesc);
/*
* If it is a dynamically-allocated TupleDesc, free it: it is
* typically allocated in a per-query context, so we must avoid
* leaking it across multiple usages.
*/
if (rsinfo.setDesc->tdrefcount == -1)
FreeTupleDesc(rsinfo.setDesc);
}
MemoryContextSwitchTo(callerContext);
econtext->plpgsql_estate = NULL;
if (has_refcursor) {
if (fcinfo.refcursor_data.argCursor != NULL)
pfree_ext(fcinfo.refcursor_data.argCursor);
if (fcinfo.refcursor_data.returnCursor != NULL)
pfree_ext(fcinfo.refcursor_data.returnCursor);
if (var_dno != NULL)
pfree_ext(var_dno);
}
/* reset the u_sess->SPI_cxt.is_stp, u_sess->SPI_cxt.is_proconfig_set
and error message value */
u_sess->SPI_cxt.is_stp = savedIsSTP;
u_sess->SPI_cxt.is_proconfig_set = savedProConfigIsSet;
if (needResetErrMsg) {
stp_reset_commit_rolback_err_msg();
}
/* All done, pass back the tuplestore */
return rsinfo.setResult;
}
/* ----------------------------------------------------------------
* ExecEvalFunc
* ExecEvalOper
*
* Evaluate the functional result of a list of arguments by calling the
* function manager.
* ----------------------------------------------------------------
*/
/* ----------------------------------------------------------------
* ExecEvalFunc
* ----------------------------------------------------------------
*/
static Datum ExecEvalFunc(FuncExprState* fcache, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
/* This is called only the first time through */
FuncExpr* func = (FuncExpr*)fcache->xprstate.expr;
Oid target_type = InvalidOid;
Oid source_type = InvalidOid;
/* Initialize function lookup info */
init_fcache<false>(func->funcid, func->inputcollid, fcache, econtext->ecxt_per_query_memory, true);
bool has_refcursor = func_has_refcursor_args(func->funcid, &fcache->fcinfo_data);
int cursor_return_number = fcache->fcinfo_data.refcursor_data.return_number;
if (func->funcformat == COERCE_EXPLICIT_CAST || func->funcformat == COERCE_IMPLICIT_CAST) {
target_type = func->funcresulttype;
source_type = fcache->fcinfo_data.argTypes[0];
HeapTuple proc_tuple = SearchSysCache(PROCOID, ObjectIdGetDatum(func->funcid), 0, 0, 0);
if (HeapTupleIsValid(proc_tuple)) {
Form_pg_proc proc_struct = (Form_pg_proc)GETSTRUCT(proc_tuple);
source_type = proc_struct->proargtypes.values[0];
ReleaseSysCache(proc_tuple);
}
HeapTuple cast_tuple = SearchSysCache2(CASTSOURCETARGET, ObjectIdGetDatum(source_type),
ObjectIdGetDatum(target_type));
if (HeapTupleIsValid(cast_tuple)) {
Relation cast_rel = heap_open(CastRelationId, AccessShareLock);
int castowner_Anum = Anum_pg_cast_castowner;
if (castowner_Anum <= (int)HeapTupleHeaderGetNatts(cast_tuple->t_data, cast_rel->rd_att)) {
bool isnull = true;
Datum datum = fastgetattr(cast_tuple, Anum_pg_cast_castowner, cast_rel->rd_att, &isnull);
if (!isnull) {
u_sess->exec_cxt.cast_owner = DatumGetObjectId(datum);
} else {
u_sess->exec_cxt.cast_owner = InvalidCastOwnerId;
}
}
heap_close(cast_rel, AccessShareLock);
ReleaseSysCache(cast_tuple);
}
}
/*
* We need to invoke ExecMakeFunctionResult if either the function itself
* or any of its input expressions can return a set. Otherwise, invoke
* ExecMakeFunctionResultNoSets. In either case, change the evalfunc
* pointer to go directly there on subsequent uses.
*/
if (fcache->func.fn_retset) {
if (has_refcursor) {
if (cursor_return_number > 0) {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResult<true, true, true>;
return ExecMakeFunctionResult<true, true, true>(fcache, econtext, isNull, isDone);
} else {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResult<true, false, true>;
return ExecMakeFunctionResult<true, false, true>(fcache, econtext, isNull, isDone);
}
} else {
if (cursor_return_number > 0) {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResult<false, true, true>;
return ExecMakeFunctionResult<false, true, true>(fcache, econtext, isNull, isDone);
} else {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResult<false, false, true>;
return ExecMakeFunctionResult<false, false, true>(fcache, econtext, isNull, isDone);
}
}
} else if (expression_returns_set((Node*)func->args)) {
if (has_refcursor) {
if (cursor_return_number > 0) {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResult<true, true, false>;
return ExecMakeFunctionResult<true, true, false>(fcache, econtext, isNull, isDone);
} else {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResult<true, false, false>;
return ExecMakeFunctionResult<true, false, false>(fcache, econtext, isNull, isDone);
}
} else {
if (cursor_return_number > 0) {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResult<false, true, false>;
return ExecMakeFunctionResult<false, true, false>(fcache, econtext, isNull, isDone);
} else {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResult<false, false, false>;
return ExecMakeFunctionResult<false, false, false>(fcache, econtext, isNull, isDone);
}
}
} else {
if (has_refcursor) {
if (cursor_return_number > 0) {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResultNoSets<true, true>;
return ExecMakeFunctionResultNoSets<true, true>(fcache, econtext, isNull, isDone);
} else {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResultNoSets<true, false>;
return ExecMakeFunctionResultNoSets<true, false>(fcache, econtext, isNull, isDone);
}
} else {
if (cursor_return_number > 0) {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResultNoSets<false, true>;
return ExecMakeFunctionResultNoSets<false, true>(fcache, econtext, isNull, isDone);
} else {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResultNoSets<false, false>;
return ExecMakeFunctionResultNoSets<false, false>(fcache, econtext, isNull, isDone);
}
}
}
}
/* ----------------------------------------------------------------
* ExecEvalOper
* ----------------------------------------------------------------
*/
static Datum ExecEvalOper(FuncExprState* fcache, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
/* This is called only the first time through */
OpExpr* op = (OpExpr*)fcache->xprstate.expr;
bool has_refcursor = false;
/* Initialize function lookup info */
init_fcache<false>(op->opfuncid, op->inputcollid, fcache, econtext->ecxt_per_query_memory, true);
has_refcursor = func_has_refcursor_args(op->opfuncid, &fcache->fcinfo_data);
int cursor_return_number = fcache->fcinfo_data.refcursor_data.return_number;
/*
* We need to invoke ExecMakeFunctionResult if either the function itself
* or any of its input expressions can return a set. Otherwise, invoke
* ExecMakeFunctionResultNoSets. In either case, change the evalfunc
* pointer to go directly there on subsequent uses.
*/
if (fcache->func.fn_retset) {
if (has_refcursor) {
if (cursor_return_number > 0) {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResult<true, true, true>;
return ExecMakeFunctionResult<true, true, true>(fcache, econtext, isNull, isDone);
} else {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResult<true, false, true>;
return ExecMakeFunctionResult<true, false, true>(fcache, econtext, isNull, isDone);
}
} else {
if (cursor_return_number > 0) {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResult<false, true, true>;
return ExecMakeFunctionResult<false, true, true>(fcache, econtext, isNull, isDone);
} else {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResult<false, false, true>;
return ExecMakeFunctionResult<false, false, true>(fcache, econtext, isNull, isDone);
}
}
} else if (expression_returns_set((Node*)op->args)) {
if (has_refcursor) {
if (cursor_return_number > 0) {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResult<true, true, false>;
return ExecMakeFunctionResult<true, true, false>(fcache, econtext, isNull, isDone);
} else {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResult<true, false, false>;
return ExecMakeFunctionResult<true, false, false>(fcache, econtext, isNull, isDone);
}
} else {
if (cursor_return_number > 0) {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResult<false, true, false>;
return ExecMakeFunctionResult<false, true, false>(fcache, econtext, isNull, isDone);
} else {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResult<false, false, false>;
return ExecMakeFunctionResult<false, false, false>(fcache, econtext, isNull, isDone);
}
}
} else {
if (has_refcursor) {
if (cursor_return_number > 0) {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResultNoSets<true, true>;
return ExecMakeFunctionResultNoSets<true, true>(fcache, econtext, isNull, isDone);
} else {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResultNoSets<true, false>;
return ExecMakeFunctionResultNoSets<true, false>(fcache, econtext, isNull, isDone);
}
} else {
if (cursor_return_number > 0) {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResultNoSets<false, true>;
return ExecMakeFunctionResultNoSets<false, true>(fcache, econtext, isNull, isDone);
} else {
fcache->xprstate.evalfunc = (ExprStateEvalFunc)ExecMakeFunctionResultNoSets<false, false>;
return ExecMakeFunctionResultNoSets<false, false>(fcache, econtext, isNull, isDone);
}
}
}
}
/* ----------------------------------------------------------------
* ExecEvalDistinct
*
* IS DISTINCT FROM must evaluate arguments to determine whether
* they are NULL; if either is NULL then the result is already
* known. If neither is NULL, then proceed to evaluate the
* function. Note that this is *always* derived from the equals
* operator, but since we need special processing of the arguments
* we can not simply reuse ExecEvalOper() or ExecEvalFunc().
* ----------------------------------------------------------------
*/
static Datum ExecEvalDistinct(FuncExprState* fcache, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
Datum result;
FunctionCallInfo fcinfo;
ExprDoneCond argDone;
/* Set default values for result flags: non-null, not a set result */
*isNull = false;
if (isDone != NULL)
*isDone = ExprSingleResult;
/*
* Initialize function cache if first time through
*/
if (fcache->func.fn_oid == InvalidOid) {
DistinctExpr* op = (DistinctExpr*)fcache->xprstate.expr;
init_fcache<false>(op->opfuncid, op->inputcollid, fcache, econtext->ecxt_per_query_memory, true);
Assert(!fcache->func.fn_retset);
}
/*
* Evaluate arguments
*/
fcinfo = &fcache->fcinfo_data;
argDone = ExecEvalFuncArgs<false>(fcinfo, fcache->args, econtext);
if (argDone != ExprSingleResult)
ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("IS DISTINCT FROM does not support set arguments")));
Assert(fcinfo->nargs == 2);
if (fcinfo->argnull[0] && fcinfo->argnull[1]) {
/* Both NULL? Then is not distinct... */
result = BoolGetDatum(FALSE);
} else if (fcinfo->argnull[0] || fcinfo->argnull[1]) {
/* Only one is NULL? Then is distinct... */
result = BoolGetDatum(TRUE);
} else {
fcinfo->isnull = false;
result = FunctionCallInvoke(fcinfo);
*isNull = fcinfo->isnull;
/* Must invert result of "=" */
result = BoolGetDatum(!DatumGetBool(result));
}
return result;
}
/*
* ExecEvalScalarArrayOp
*
* Evaluate "scalar op ANY/ALL (array)". The operator always yields boolean,
* and we combine the results across all array elements using OR and AND
* (for ANY and ALL respectively). Of course we short-circuit as soon as
* the result is known.
*/
static Datum ExecEvalScalarArrayOp(
ScalarArrayOpExprState* sstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
ScalarArrayOpExpr* opexpr = (ScalarArrayOpExpr*)sstate->fxprstate.xprstate.expr;
bool useOr = opexpr->useOr;
ArrayType* arr = NULL;
int nitems;
Datum result;
bool resultnull = false;
FunctionCallInfo fcinfo;
ExprDoneCond argDone;
int i;
int16 typlen;
bool typbyval = false;
char typalign;
char* s = NULL;
bits8* bitmap = NULL;
int bitmask;
/* Set default values for result flags: non-null, not a set result */
*isNull = false;
if (isDone != NULL)
*isDone = ExprSingleResult;
/*
* Initialize function cache if first time through
*/
if (sstate->fxprstate.func.fn_oid == InvalidOid) {
init_fcache<false>(
opexpr->opfuncid, opexpr->inputcollid, &sstate->fxprstate, econtext->ecxt_per_query_memory, true);
Assert(!sstate->fxprstate.func.fn_retset);
}
/*
* Evaluate arguments
*/
fcinfo = &sstate->fxprstate.fcinfo_data;
/* init the number of arguments to a function. */
InitFunctionCallInfoArgs(*fcinfo, 2, 1);
argDone = ExecEvalFuncArgs<false>(fcinfo, sstate->fxprstate.args, econtext);
if (argDone != ExprSingleResult)
ereport(
ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("op ANY/ALL (array) does not support set arguments")));
Assert(fcinfo->nargs == 2);
/*
* If the array is NULL then we return NULL --- it's not very meaningful
* to do anything else, even if the operator isn't strict.
*/
if (fcinfo->argnull[1]) {
*isNull = true;
return (Datum)0;
}
/* Else okay to fetch and detoast the array */
arr = DatumGetArrayTypeP(fcinfo->arg[1]);
/*
* If the array is empty, we return either FALSE or TRUE per the useOr
* flag. This is correct even if the scalar is NULL; since we would
* evaluate the operator zero times, it matters not whether it would want
* to return NULL.
*/
nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
if (nitems <= 0)
return BoolGetDatum(!useOr);
/*
* If the scalar is NULL, and the function is strict, return NULL; no
* point in iterating the loop.
*/
if (fcinfo->argnull[0] && sstate->fxprstate.func.fn_strict) {
*isNull = true;
return (Datum)0;
}
/*
* We arrange to look up info about the element type only once per series
* of calls, assuming the element type doesn't change underneath us.
*/
if (sstate->element_type != ARR_ELEMTYPE(arr)) {
get_typlenbyvalalign(ARR_ELEMTYPE(arr), &sstate->typlen, &sstate->typbyval, &sstate->typalign);
sstate->element_type = ARR_ELEMTYPE(arr);
}
typlen = sstate->typlen;
typbyval = sstate->typbyval;
typalign = sstate->typalign;
result = BoolGetDatum(!useOr);
resultnull = false;
/* Loop over the array elements */
s = (char*)ARR_DATA_PTR(arr);
bitmap = ARR_NULLBITMAP(arr);
bitmask = 1;
for (i = 0; i < nitems; i++) {
Datum elt;
Datum thisresult;
/* Get array element, checking for NULL */
if (bitmap && (*bitmap & bitmask) == 0) {
fcinfo->arg[1] = (Datum)0;
fcinfo->argnull[1] = true;
} else {
elt = fetch_att(s, typbyval, typlen);
s = att_addlength_pointer(s, typlen, s);
s = (char*)att_align_nominal(s, typalign);
fcinfo->arg[1] = elt;
fcinfo->argnull[1] = false;
}
/* Call comparison function */
if (fcinfo->argnull[1] && sstate->fxprstate.func.fn_strict) {
fcinfo->isnull = true;
thisresult = (Datum)0;
} else {
fcinfo->isnull = false;
thisresult = FunctionCallInvoke(fcinfo);
}
/* Combine results per OR or AND semantics */
if (fcinfo->isnull)
resultnull = true;
else if (useOr) {
if (DatumGetBool(thisresult)) {
result = BoolGetDatum(true);
resultnull = false;
break; /* needn't look at any more elements */
}
} else {
if (!DatumGetBool(thisresult)) {
result = BoolGetDatum(false);
resultnull = false;
break; /* needn't look at any more elements */
}
}
/* advance bitmap pointer if any */
if (bitmap != NULL) {
bitmask <<= 1;
if (bitmask == 0x100) {
bitmap++;
bitmask = 1;
}
}
}
*isNull = resultnull;
return result;
}
/* ----------------------------------------------------------------
* ExecEvalNot
* ExecEvalOr
* ExecEvalAnd
*
* Evaluate boolean expressions, with appropriate short-circuiting.
*
* The query planner reformulates clause expressions in the
* qualification to conjunctive normal form. If we ever get
* an AND to evaluate, we can be sure that it's not a top-level
* clause in the qualification, but appears lower (as a function
* argument, for example), or in the target list. Not that you
* need to know this, mind you...
* ----------------------------------------------------------------
*/
static Datum ExecEvalNot(BoolExprState* notclause, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
ExprState* clause = (ExprState*)linitial(notclause->args);
Datum expr_value;
if (isDone != NULL)
*isDone = ExprSingleResult;
expr_value = ExecEvalExpr(clause, econtext, isNull, NULL);
/*
* if the expression evaluates to null, then we just cascade the null back
* to whoever called us.
*/
if (*isNull)
return expr_value;
/*
* evaluation of 'not' is simple.. expr is false, then return 'true' and
* vice versa.
*/
return BoolGetDatum(!DatumGetBool(expr_value));
}
/* ----------------------------------------------------------------
* ExecEvalOr
* ----------------------------------------------------------------
*/
static Datum ExecEvalOr(BoolExprState* orExpr, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
List* clauses = orExpr->args;
ListCell* clause = NULL;
bool AnyNull = false;
if (isDone != NULL)
*isDone = ExprSingleResult;
AnyNull = false;
/*
* If any of the clauses is TRUE, the OR result is TRUE regardless of the
* states of the rest of the clauses, so we can stop evaluating and return
* TRUE immediately. If none are TRUE and one or more is NULL, we return
* NULL; otherwise we return FALSE. This makes sense when you interpret
* NULL as "don't know": if we have a TRUE then the OR is TRUE even if we
* aren't sure about some of the other inputs. If all the known inputs are
* FALSE, but we have one or more "don't knows", then we have to report
* that we "don't know" what the OR's result should be --- perhaps one of
* the "don't knows" would have been TRUE if we'd known its value. Only
* when all the inputs are known to be FALSE can we state confidently that
* the OR's result is FALSE.
*/
foreach (clause, clauses) {
ExprState* clausestate = (ExprState*)lfirst(clause);
Datum clause_value;
clause_value = ExecEvalExpr(clausestate, econtext, isNull, NULL);
/*
* if we have a non-null true result, then return it.
*/
if (*isNull)
AnyNull = true; /* remember we got a null */
else if (DatumGetBool(clause_value))
return clause_value;
}
/* AnyNull is true if at least one clause evaluated to NULL */
*isNull = AnyNull;
return BoolGetDatum(false);
}
/* ----------------------------------------------------------------
* ExecEvalAnd
* ----------------------------------------------------------------
*/
static Datum ExecEvalAnd(BoolExprState* andExpr, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
List* clauses = andExpr->args;
ListCell* clause = NULL;
bool AnyNull = false;
if (isDone != NULL)
*isDone = ExprSingleResult;
AnyNull = false;
/*
* If any of the clauses is FALSE, the AND result is FALSE regardless of
* the states of the rest of the clauses, so we can stop evaluating and
* return FALSE immediately. If none are FALSE and one or more is NULL,
* we return NULL; otherwise we return TRUE. This makes sense when you
* interpret NULL as "don't know", using the same sort of reasoning as for
* OR, above.
*/
foreach (clause, clauses) {
ExprState* clausestate = (ExprState*)lfirst(clause);
Datum clause_value;
clause_value = ExecEvalExpr(clausestate, econtext, isNull, NULL);
/*
* if we have a non-null false result, then return it.
*/
if (*isNull)
AnyNull = true; /* remember we got a null */
else if (!DatumGetBool(clause_value))
return clause_value;
}
/* AnyNull is true if at least one clause evaluated to NULL */
*isNull = AnyNull;
return BoolGetDatum(!AnyNull);
}
/* ----------------------------------------------------------------
* ExecEvalConvertRowtype
*
* Evaluate a rowtype coercion operation. This may require
* rearranging field positions.
* ----------------------------------------------------------------
*/
static Datum ExecEvalConvertRowtype(
ConvertRowtypeExprState* cstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
ConvertRowtypeExpr* convert = (ConvertRowtypeExpr*)cstate->xprstate.expr;
HeapTuple result;
Datum tupDatum;
HeapTupleHeader tuple;
HeapTupleData tmptup;
tupDatum = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
/* this test covers the isDone exception too: */
if (*isNull)
return tupDatum;
tuple = DatumGetHeapTupleHeader(tupDatum);
/* Lookup tupdescs if first time through or after rescan */
if (cstate->indesc == NULL) {
get_cached_rowtype(exprType((Node*)convert->arg), -1, &cstate->indesc, econtext);
cstate->initialized = false;
}
if (cstate->outdesc == NULL) {
get_cached_rowtype(convert->resulttype, -1, &cstate->outdesc, econtext);
cstate->initialized = false;
}
Assert(HeapTupleHeaderGetTypeId(tuple) == cstate->indesc->tdtypeid);
Assert(HeapTupleHeaderGetTypMod(tuple) == cstate->indesc->tdtypmod);
/* if first time through, initialize conversion map */
if (!cstate->initialized) {
MemoryContext old_cxt;
/* allocate map in long-lived memory context */
old_cxt = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
/* prepare map from old to new attribute numbers */
cstate->map =
convert_tuples_by_name(cstate->indesc, cstate->outdesc, gettext_noop("could not convert row type"));
cstate->initialized = true;
MemoryContextSwitchTo(old_cxt);
}
/*
* No-op if no conversion needed (not clear this can happen here).
*/
if (cstate->map == NULL)
return tupDatum;
/*
* do_convert_tuple needs a HeapTuple not a bare HeapTupleHeader.
*/
tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
tmptup.t_data = tuple;
result = do_convert_tuple(&tmptup, cstate->map);
return HeapTupleGetDatum(result);
}
/* ----------------------------------------------------------------
* ExecEvalCase
*
* Evaluate a CASE clause. Will have boolean expressions
* inside the WHEN clauses, and will have expressions
* for results.
* - thomas 1998-11-09
* ----------------------------------------------------------------
*/
static Datum ExecEvalCase(CaseExprState* caseExpr, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
List* clauses = caseExpr->args;
ListCell* clause = NULL;
Datum save_datum;
bool save_isNull = false;
if (isDone != NULL)
*isDone = ExprSingleResult;
/*
* If there's a test expression, we have to evaluate it and save the value
* where the CaseTestExpr placeholders can find it. We must save and
* restore prior setting of econtext's caseValue fields, in case this node
* is itself within a larger CASE.Furthermore, don't assign to the
* econtext fields until after returning from evaluation of the test
* expression. We used to pass &econtext->caseValue_isNull to the
* recursive call, but that leads to aliasing that variable within said
* call, which can (and did) produce bugs when the test expression itself
* contains a CASE.
*
* If there's no test expression, we don't actually need to save and
* restore these fields; but it's less code to just do so unconditionally.
*/
save_datum = econtext->caseValue_datum;
save_isNull = econtext->caseValue_isNull;
if (caseExpr->arg) {
bool arg_isNull = false;
econtext->caseValue_datum = ExecEvalExpr(caseExpr->arg, econtext, &arg_isNull, NULL);
econtext->caseValue_isNull = arg_isNull;
}
/*
* we evaluate each of the WHEN clauses in turn, as soon as one is true we
* return the corresponding result. If none are true then we return the
* value of the default clause, or NULL if there is none.
*/
foreach (clause, clauses) {
CaseWhenState* wclause = (CaseWhenState*)lfirst(clause);
Datum clause_value;
bool clause_isNull = false;
clause_value = ExecEvalExpr(wclause->expr, econtext, &clause_isNull, NULL);
/*
* if we have a true test, then we return the result, since the case
* statement is satisfied. A NULL result from the test is not
* considered true.
*/
if (DatumGetBool(clause_value) && !clause_isNull) {
econtext->caseValue_datum = save_datum;
econtext->caseValue_isNull = save_isNull;
return ExecEvalExpr(wclause->result, econtext, isNull, isDone);
}
}
econtext->caseValue_datum = save_datum;
econtext->caseValue_isNull = save_isNull;
if (caseExpr->defresult) {
return ExecEvalExpr(caseExpr->defresult, econtext, isNull, isDone);
}
*isNull = true;
return (Datum)0;
}
/*
* ExecEvalCaseTestExpr
*
* Return the value stored by CASE.
*/
static Datum ExecEvalCaseTestExpr(ExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
if (isDone != NULL)
*isDone = ExprSingleResult;
*isNull = econtext->caseValue_isNull;
return econtext->caseValue_datum;
}
/*
* ExecEvalGroupingFuncExpr
*
* Return a bitmask with a bit for each (unevaluated) argument expression
* (rightmost arg is least significant bit).
*
* A bit is set if the corresponding expression is NOT part of the set of
* grouping expressions in the current grouping set.
*/
static Datum ExecEvalGroupingFuncExpr(
GroupingFuncExprState* gstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
int result = 0;
int attnum = 0;
Bitmapset* grouped_cols = gstate->aggstate->grouped_cols;
ListCell* lc = NULL;
if (isDone != NULL)
*isDone = ExprSingleResult;
*isNull = false;
foreach (lc, (gstate->clauses)) {
attnum = lfirst_int(lc);
result = (uint32)result << 1;
if (!bms_is_member(attnum, grouped_cols))
result = (uint32)result | 1;
}
return (Datum)result;
}
/* ----------------------------------------------------------------
* ExecEvalArray - ARRAY[] expressions
* ----------------------------------------------------------------
*/
static Datum ExecEvalArray(ArrayExprState* astate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
ArrayExpr* arrayExpr = (ArrayExpr*)astate->xprstate.expr;
ArrayType* result = NULL;
ListCell* element = NULL;
Oid element_type = arrayExpr->element_typeid;
int ndims = 0;
int dims[MAXDIM];
int lbs[MAXDIM];
/* Set default values for result flags: non-null, not a set result */
*isNull = false;
if (isDone != NULL)
*isDone = ExprSingleResult;
if (!arrayExpr->multidims) {
/* Elements are presumably of scalar type */
int nelems;
Datum* dvalues = NULL;
bool* dnulls = NULL;
int i = 0;
ndims = 1;
nelems = list_length(astate->elements);
/* Shouldn't happen here, but if length is 0, return empty array */
if (nelems == 0)
return PointerGetDatum(construct_empty_array(element_type));
dvalues = (Datum*)palloc(nelems * sizeof(Datum));
dnulls = (bool*)palloc(nelems * sizeof(bool));
/* loop through and build array of datums */
foreach (element, astate->elements) {
ExprState* e = (ExprState*)lfirst(element);
dvalues[i] = ExecEvalExpr(e, econtext, &dnulls[i], NULL);
i++;
}
/* setup for 1-D array of the given length */
dims[0] = nelems;
lbs[0] = 1;
result = construct_md_array(
dvalues, dnulls, ndims, dims, lbs, element_type, astate->elemlength, astate->elembyval, astate->elemalign);
} else {
/* Must be nested array expressions */
int nbytes = 0;
int nitems = 0;
int outer_nelems = 0;
int elem_ndims = 0;
int* elem_dims = NULL;
int* elem_lbs = NULL;
bool firstone = true;
bool havenulls = false;
bool haveempty = false;
char** subdata;
bits8** subbitmaps;
int* subbytes = NULL;
int* subnitems = NULL;
int i;
int32 dataoffset;
char* dat = NULL;
int iitem;
errno_t rc = 0;
i = list_length(astate->elements);
subdata = (char**)palloc(i * sizeof(char*));
subbitmaps = (bits8**)palloc(i * sizeof(bits8*));
subbytes = (int*)palloc(i * sizeof(int));
subnitems = (int*)palloc(i * sizeof(int));
/* loop through and get data area from each element */
foreach (element, astate->elements) {
ExprState* e = (ExprState*)lfirst(element);
bool eisnull = false;
Datum arraydatum;
ArrayType* array = NULL;
int this_ndims;
arraydatum = ExecEvalExpr(e, econtext, &eisnull, NULL);
/* temporarily ignore null subarrays */
if (eisnull) {
haveempty = true;
continue;
}
array = DatumGetArrayTypeP(arraydatum);
/* run-time double-check on element type */
if (element_type != ARR_ELEMTYPE(array))
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("cannot merge incompatible arrays"),
errdetail("Array with element type %s cannot be "
"included in ARRAY construct with element type %s.",
format_type_be(ARR_ELEMTYPE(array)),
format_type_be(element_type))));
this_ndims = ARR_NDIM(array);
/* temporarily ignore zero-dimensional subarrays */
if (this_ndims <= 0) {
haveempty = true;
continue;
}
if (firstone) {
/* Get sub-array details from first member */
elem_ndims = this_ndims;
ndims = elem_ndims + 1;
if (ndims <= 0 || ndims > MAXDIM)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("number of array dimensions (%d) exceeds "
"the maximum allowed (%d)",
ndims,
MAXDIM)));
elem_dims = (int*)palloc(elem_ndims * sizeof(int));
rc = memcpy_s(elem_dims, elem_ndims * sizeof(int), ARR_DIMS(array), elem_ndims * sizeof(int));
securec_check(rc, "\0", "\0");
elem_lbs = (int*)palloc(elem_ndims * sizeof(int));
rc = memcpy_s(elem_lbs, elem_ndims * sizeof(int), ARR_LBOUND(array), elem_ndims * sizeof(int));
securec_check(rc, "\0", "\0");
firstone = false;
} else {
/* Check other sub-arrays are compatible */
if (elem_ndims != this_ndims || memcmp(elem_dims, ARR_DIMS(array), elem_ndims * sizeof(int)) != 0 ||
memcmp(elem_lbs, ARR_LBOUND(array), elem_ndims * sizeof(int)) != 0)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("multidimensional arrays must have array expressions with matching dimensions")));
}
subdata[outer_nelems] = ARR_DATA_PTR(array);
subbitmaps[outer_nelems] = ARR_NULLBITMAP(array);
subbytes[outer_nelems] = ARR_SIZE(array) - ARR_DATA_OFFSET(array);
nbytes += subbytes[outer_nelems];
subnitems[outer_nelems] = ArrayGetNItems(this_ndims, ARR_DIMS(array));
nitems += subnitems[outer_nelems];
if (ARR_HASNULL(array))
havenulls = true;
outer_nelems++;
}
/*
* If all items were null or empty arrays, return an empty array;
* otherwise, if some were and some weren't, raise error. (Note: we
* must special-case this somehow to avoid trying to generate a 1-D
* array formed from empty arrays. It's not ideal...)
*/
if (haveempty) {
if (ndims == 0) /* didn't find any nonempty array */
return PointerGetDatum(construct_empty_array(element_type));
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("multidimensional arrays must have array expressions with matching dimensions")));
}
/* setup for multi-D array */
dims[0] = outer_nelems;
lbs[0] = 1;
for (i = 1; i < ndims; i++) {
dims[i] = elem_dims[i - 1];
lbs[i] = elem_lbs[i - 1];
}
if (havenulls) {
dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);
nbytes += dataoffset;
} else {
dataoffset = 0; /* marker for no null bitmap */
nbytes += ARR_OVERHEAD_NONULLS(ndims);
}
result = (ArrayType*)palloc(nbytes);
SET_VARSIZE(result, nbytes);
result->ndim = ndims;
result->dataoffset = dataoffset;
result->elemtype = element_type;
rc = memcpy_s(ARR_DIMS(result), ndims * sizeof(int), dims, ndims * sizeof(int));
securec_check(rc, "\0", "\0");
rc = memcpy_s(ARR_LBOUND(result), ndims * sizeof(int), lbs, ndims * sizeof(int));
securec_check(rc, "\0", "\0");
dat = ARR_DATA_PTR(result);
int len = (nbytes - ARR_DATA_OFFSET(result));
iitem = 0;
for (i = 0; i < outer_nelems; i++) {
/* make sure the destMax of memcpy_s should never be zero. */
if (subbytes[i] != 0) {
rc = memcpy_s(dat, len, subdata[i], subbytes[i]);
securec_check(rc, "\0", "\0");
}
dat += subbytes[i];
len -= subbytes[i];
if (havenulls)
array_bitmap_copy(ARR_NULLBITMAP(result), iitem, subbitmaps[i], 0, subnitems[i]);
iitem += subnitems[i];
}
}
return PointerGetDatum(result);
}
/* ----------------------------------------------------------------
* ExecEvalRow - ROW() expressions
* ----------------------------------------------------------------
*/
static Datum ExecEvalRow(RowExprState* rstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
HeapTuple tuple;
Datum* values = NULL;
bool* isnull = NULL;
int natts;
ListCell* arg = NULL;
int i;
errno_t rc = EOK;
/* Set default values for result flags: non-null, not a set result */
*isNull = false;
if (isDone != NULL)
*isDone = ExprSingleResult;
/* Allocate workspace */
natts = rstate->tupdesc->natts;
values = (Datum*)palloc0(natts * sizeof(Datum));
isnull = (bool*)palloc(natts * sizeof(bool));
/* preset to nulls in case rowtype has some later-added columns */
rc = memset_s(isnull, natts * sizeof(bool), true, natts * sizeof(bool));
securec_check(rc, "\0", "\0");
/* Evaluate field values */
i = 0;
foreach (arg, rstate->args) {
ExprState* e = (ExprState*)lfirst(arg);
values[i] = ExecEvalExpr(e, econtext, &isnull[i], NULL);
i++;
}
tuple = (HeapTuple)tableam_tops_form_tuple(rstate->tupdesc, values, isnull, HEAP_TUPLE);
pfree_ext(values);
pfree_ext(isnull);
return HeapTupleGetDatum(tuple);
}
/* ----------------------------------------------------------------
* ExecEvalRowCompare - ROW() comparison-op ROW()
* ----------------------------------------------------------------
*/
static Datum ExecEvalRowCompare(RowCompareExprState* rstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
bool result = false;
RowCompareType rctype = ((RowCompareExpr*)rstate->xprstate.expr)->rctype;
int32 cmpresult = 0;
ListCell* l = NULL;
ListCell* r = NULL;
int i;
if (isDone != NULL)
*isDone = ExprSingleResult;
*isNull = true; /* until we get a result */
i = 0;
forboth(l, rstate->largs, r, rstate->rargs)
{
ExprState* le = (ExprState*)lfirst(l);
ExprState* re = (ExprState*)lfirst(r);
FunctionCallInfoData locfcinfo;
InitFunctionCallInfoData(locfcinfo, &(rstate->funcs[i]), 2, rstate->collations[i], NULL, NULL);
locfcinfo.arg[0] = ExecEvalExpr(le, econtext, &locfcinfo.argnull[0], NULL);
locfcinfo.arg[1] = ExecEvalExpr(re, econtext, &locfcinfo.argnull[1], NULL);
if (rstate->funcs[i].fn_strict && (locfcinfo.argnull[0] || locfcinfo.argnull[1]))
return (Datum)0; /* force NULL result */
locfcinfo.isnull = false;
cmpresult = DatumGetInt32(FunctionCallInvoke(&locfcinfo));
if (locfcinfo.isnull)
return (Datum)0; /* force NULL result */
if (cmpresult != 0)
break; /* no need to compare remaining columns */
i++;
}
switch (rctype) {
/* EQ and NE cases aren't allowed here */
case ROWCOMPARE_LT:
result = (cmpresult < 0);
break;
case ROWCOMPARE_LE:
result = (cmpresult <= 0);
break;
case ROWCOMPARE_GE:
result = (cmpresult >= 0);
break;
case ROWCOMPARE_GT:
result = (cmpresult > 0);
break;
default:
ereport(ERROR,
(errcode(ERRCODE_UNRECOGNIZED_NODE_TYPE),
errmodule(MOD_EXECUTOR),
errmsg("unrecognized RowCompareType: %d", (int)rctype)));
result = 0; /* keep compiler quiet */
break;
}
*isNull = false;
return BoolGetDatum(result);
}
/* ----------------------------------------------------------------
* ExecEvalCoalesce
* ----------------------------------------------------------------
*/
static Datum ExecEvalCoalesce(
CoalesceExprState* coalesceExpr, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
ListCell* arg = NULL;
if (isDone != NULL)
*isDone = ExprSingleResult;
/* Simply loop through until something NOT NULL is found */
foreach (arg, coalesceExpr->args) {
ExprState* e = (ExprState*)lfirst(arg);
Datum value;
value = ExecEvalExpr(e, econtext, isNull, NULL);
if (!*isNull)
return value;
}
/* Else return NULL */
*isNull = true;
return (Datum)0;
}
/* ----------------------------------------------------------------
* ExecEvalMinMax
* ----------------------------------------------------------------
*/
static Datum ExecEvalMinMax(MinMaxExprState* minmaxExpr, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
Datum result = (Datum)0;
MinMaxExpr* minmax = (MinMaxExpr*)minmaxExpr->xprstate.expr;
Oid collation = minmax->inputcollid;
MinMaxOp op = minmax->op;
FunctionCallInfoData locfcinfo;
ListCell* arg = NULL;
if (isDone != NULL)
*isDone = ExprSingleResult;
*isNull = true; /* until we get a result */
InitFunctionCallInfoData(locfcinfo, &minmaxExpr->cfunc, 2, collation, NULL, NULL);
locfcinfo.argnull[0] = false;
locfcinfo.argnull[1] = false;
foreach (arg, minmaxExpr->args) {
ExprState* e = (ExprState*)lfirst(arg);
Datum value;
bool valueIsNull = false;
int32 cmpresult;
value = ExecEvalExpr(e, econtext, &valueIsNull, NULL);
if (valueIsNull)
continue; /* ignore NULL inputs */
if (*isNull) {
/* first nonnull input, adopt value */
result = value;
*isNull = false;
} else {
/* apply comparison function */
locfcinfo.arg[0] = result;
locfcinfo.arg[1] = value;
locfcinfo.isnull = false;
cmpresult = DatumGetInt32(FunctionCallInvoke(&locfcinfo));
if (locfcinfo.isnull) /* probably should not happen */
continue;
if (cmpresult > 0 && op == IS_LEAST)
result = value;
else if (cmpresult < 0 && op == IS_GREATEST)
result = value;
}
}
return result;
}
/* ----------------------------------------------------------------
* ExecEvalXml
* ----------------------------------------------------------------
*/
static Datum ExecEvalXml(XmlExprState* xmlExpr, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
XmlExpr* xexpr = (XmlExpr*)xmlExpr->xprstate.expr;
Datum value;
bool isnull = false;
ListCell* arg = NULL;
ListCell* narg = NULL;
if (isDone != NULL)
*isDone = ExprSingleResult;
*isNull = true; /* until we get a result */
switch (xexpr->op) {
case IS_XMLCONCAT: {
List* values = NIL;
foreach (arg, xmlExpr->args) {
ExprState* e = (ExprState*)lfirst(arg);
value = ExecEvalExpr(e, econtext, &isnull, NULL);
if (!isnull)
values = lappend(values, DatumGetPointer(value));
}
if (list_length(values) > 0) {
*isNull = false;
return PointerGetDatum(xmlconcat(values));
} else
return (Datum)0;
} break;
case IS_XMLFOREST: {
StringInfoData buf;
initStringInfo(&buf);
forboth(arg, xmlExpr->named_args, narg, xexpr->arg_names)
{
ExprState* e = (ExprState*)lfirst(arg);
char* argname = strVal(lfirst(narg));
value = ExecEvalExpr(e, econtext, &isnull, NULL);
if (!isnull) {
appendStringInfo(&buf,
"<%s>%s</%s>",
argname,
map_sql_value_to_xml_value(value, exprType((Node*)e->expr), true),
argname);
*isNull = false;
}
}
if (*isNull) {
pfree_ext(buf.data);
return (Datum)0;
} else {
text* result = NULL;
result = cstring_to_text_with_len(buf.data, buf.len);
pfree_ext(buf.data);
return PointerGetDatum(result);
}
} break;
case IS_XMLELEMENT:
*isNull = false;
return PointerGetDatum(xmlelement(xmlExpr, econtext));
break;
case IS_XMLPARSE: {
ExprState* e = NULL;
text* data = NULL;
bool preserve_whitespace = false;
/* arguments are known to be text, bool */
Assert(list_length(xmlExpr->args) == 2);
e = (ExprState*)linitial(xmlExpr->args);
value = ExecEvalExpr(e, econtext, &isnull, NULL);
if (isnull)
return (Datum)0;
data = DatumGetTextP(value);
e = (ExprState*)lsecond(xmlExpr->args);
value = ExecEvalExpr(e, econtext, &isnull, NULL);
if (isnull) /* probably can't happen */
return (Datum)0;
preserve_whitespace = DatumGetBool(value);
*isNull = false;
return PointerGetDatum(xmlparse(data, xexpr->xmloption, preserve_whitespace));
} break;
case IS_XMLPI: {
ExprState* e = NULL;
text* argument = NULL;
/* optional argument is known to be text */
Assert(list_length(xmlExpr->args) <= 1);
if (xmlExpr->args) {
e = (ExprState*)linitial(xmlExpr->args);
value = ExecEvalExpr(e, econtext, &isnull, NULL);
if (isnull)
argument = NULL;
else
argument = DatumGetTextP(value);
} else {
argument = NULL;
isnull = false;
}
return PointerGetDatum(xmlpi(xexpr->name, argument, isnull, isNull));
} break;
case IS_XMLROOT: {
ExprState* e = NULL;
xmltype* data = NULL;
text* version = NULL;
int standalone;
/* arguments are known to be xml, text, int */
Assert(list_length(xmlExpr->args) == 3);
e = (ExprState*)linitial(xmlExpr->args);
value = ExecEvalExpr(e, econtext, &isnull, NULL);
if (isnull)
return (Datum)0;
data = DatumGetXmlP(value);
e = (ExprState*)lsecond(xmlExpr->args);
value = ExecEvalExpr(e, econtext, &isnull, NULL);
if (isnull)
version = NULL;
else
version = DatumGetTextP(value);
e = (ExprState*)lthird(xmlExpr->args);
value = ExecEvalExpr(e, econtext, &isnull, NULL);
standalone = DatumGetInt32(value);
*isNull = false;
return PointerGetDatum(xmlroot(data, version, standalone));
} break;
case IS_XMLSERIALIZE: {
ExprState* e = NULL;
/* argument type is known to be xml */
Assert(list_length(xmlExpr->args) == 1);
e = (ExprState*)linitial(xmlExpr->args);
value = ExecEvalExpr(e, econtext, &isnull, NULL);
if (isnull)
return (Datum)0;
*isNull = false;
return PointerGetDatum(xmltotext_with_xmloption(DatumGetXmlP(value), xexpr->xmloption));
} break;
case IS_DOCUMENT: {
ExprState* e = NULL;
/* optional argument is known to be xml */
Assert(list_length(xmlExpr->args) == 1);
e = (ExprState*)linitial(xmlExpr->args);
value = ExecEvalExpr(e, econtext, &isnull, NULL);
if (isnull)
return (Datum)0;
else {
*isNull = false;
return BoolGetDatum(xml_is_document(DatumGetXmlP(value)));
}
} break;
default:
break;
}
ereport(ERROR,
(errcode(ERRCODE_UNRECOGNIZED_NODE_TYPE),
errmodule(MOD_EXECUTOR),
errmsg("unrecognized XML operation %d", xexpr->op)));
return (Datum)0;
}
/* ----------------------------------------------------------------
* ExecEvalNullIf
*
* Note that this is *always* derived from the equals operator,
* but since we need special processing of the arguments
* we can not simply reuse ExecEvalOper() or ExecEvalFunc().
* ----------------------------------------------------------------
*/
static Datum ExecEvalNullIf(FuncExprState* nullIfExpr, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
Datum result;
FunctionCallInfo fcinfo;
ExprDoneCond argDone;
if (isDone != NULL)
*isDone = ExprSingleResult;
/*
* Initialize function cache if first time through
*/
if (nullIfExpr->func.fn_oid == InvalidOid) {
NullIfExpr* op = (NullIfExpr*)nullIfExpr->xprstate.expr;
init_fcache<false>(op->opfuncid, op->inputcollid, nullIfExpr, econtext->ecxt_per_query_memory, true);
Assert(!nullIfExpr->func.fn_retset);
}
/*
* Evaluate arguments
*/
fcinfo = &nullIfExpr->fcinfo_data;
argDone = ExecEvalFuncArgs<false>(fcinfo, nullIfExpr->args, econtext);
if (argDone != ExprSingleResult)
ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("NULLIF does not support set arguments")));
Assert(fcinfo->nargs == 2);
/* if either argument is NULL they can't be equal */
if (!fcinfo->argnull[0] && !fcinfo->argnull[1]) {
fcinfo->isnull = false;
result = FunctionCallInvoke(fcinfo);
/* if the arguments are equal return null */
if (!fcinfo->isnull && DatumGetBool(result)) {
*isNull = true;
return (Datum)0;
}
}
/* else return first argument */
*isNull = fcinfo->argnull[0];
return fcinfo->arg[0];
}
/* ----------------------------------------------------------------
* ExecEvalNullTest
*
* Evaluate a NullTest node.
* ----------------------------------------------------------------
*/
static Datum ExecEvalNullTest(NullTestState* nstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
NullTest* ntest = (NullTest*)nstate->xprstate.expr;
Datum result;
result = ExecEvalExpr(nstate->arg, econtext, isNull, isDone);
if (isDone && *isDone == ExprEndResult)
return result; /* nothing to check */
if (ntest->argisrow && !(*isNull)) {
HeapTupleHeader tuple;
Oid tupType;
int32 tupTypmod;
TupleDesc tupDesc;
HeapTupleData tmptup;
int att;
tuple = DatumGetHeapTupleHeader(result);
tupType = HeapTupleHeaderGetTypeId(tuple);
tupTypmod = HeapTupleHeaderGetTypMod(tuple);
/* Lookup tupdesc if first time through or if type changes */
tupDesc = get_cached_rowtype(tupType, tupTypmod, &nstate->argdesc, econtext);
/*
* heap_attisnull needs a HeapTuple not a bare HeapTupleHeader.
*/
tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
tmptup.t_data = tuple;
for (att = 1; att <= tupDesc->natts; att++) {
/* ignore dropped columns */
if (tupDesc->attrs[att - 1]->attisdropped)
continue;
if (tableam_tops_tuple_attisnull(&tmptup, att, tupDesc)) {
/* null field disproves IS NOT NULL */
if (ntest->nulltesttype == IS_NOT_NULL)
return BoolGetDatum(false);
} else {
/* non-null field disproves IS NULL */
if (ntest->nulltesttype == IS_NULL)
return BoolGetDatum(false);
}
}
return BoolGetDatum(true);
} else {
/* Simple scalar-argument case, or a null rowtype datum */
switch (ntest->nulltesttype) {
case IS_NULL:
if (*isNull) {
*isNull = false;
return BoolGetDatum(true);
} else
return BoolGetDatum(false);
case IS_NOT_NULL:
if (*isNull) {
*isNull = false;
return BoolGetDatum(false);
} else
return BoolGetDatum(true);
default:
ereport(ERROR,
(errcode(ERRCODE_UNRECOGNIZED_NODE_TYPE),
errmodule(MOD_EXECUTOR),
errmsg("unrecognized nulltesttype: %d", (int)ntest->nulltesttype)));
return (Datum)0; /* keep compiler quiet */
}
}
}
/* ----------------------------------------------------------------
* ExecEvalHashFilter
*
* Evaluate a HashFilter node.
* ----------------------------------------------------------------
*/
static Datum ExecEvalHashFilter(HashFilterState* hstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
HashFilter* htest = (HashFilter*)hstate->xprstate.expr;
Datum result = 0;
Datum value = 0;
uint64 hashValue = 0;
int modulo = 0;
int nodeIndex = 0;
ListCell *distkey = NULL;
ListCell *vartypes = NULL;
bool isFirst = true;
bool hasNonNullValue = false;
if (isDone != NULL)
*isDone = ExprSingleResult;
*isNull = true; /* until we get a result */
/* Get every distribute key in arg and compute hash value */
forboth(distkey, hstate->arg, vartypes, htest->typeOids)
{
ExprState* e = (ExprState*)lfirst(distkey);
Oid vartype = (Oid)lfirst_oid(vartypes);
value = ExecEvalExpr(e, econtext, isNull, isDone);
int null_value_dn_index = (hstate->nodelist != NULL) ? hstate->nodelist[0]
: /* fetch first dn in group's dn list */
0; /* fetch first dn index */
if (*isNull) {
if (null_value_dn_index == u_sess->pgxc_cxt.PGXCNodeId) {
*isNull = false;
result = BoolGetDatum(true);
} else
result = BoolGetDatum(false);
} else {
if (isFirst) {
hashValue = compute_hash(vartype, value, LOCATOR_TYPE_HASH);
isFirst = false;
} else {
hashValue = (hashValue << 1) | ((hashValue & 0x80000000) ? 1 : 0);
hashValue ^= compute_hash(vartype, value, LOCATOR_TYPE_HASH);
}
hasNonNullValue = true;
}
}
#ifdef ENABLE_MULTIPLE_NODES
CheckBucketMapLenValid();
#endif
/* If has non null value, it should get nodeId and deside if need filter the value or not. */
if (hasNonNullValue) {
modulo = hstate->bucketMap[abs((int)hashValue) & (BUCKETDATALEN - 1)];
nodeIndex = hstate->nodelist[modulo];
/* If there are null value and non null value, and the last value in distkey is null,
we should set isNull is false. */
*isNull = false;
/* Look into the handles and return correct position in array */
if (nodeIndex == u_sess->pgxc_cxt.PGXCNodeId)
return BoolGetDatum(true);
else
return BoolGetDatum(false);
} else /* If all the value is null, return result. */
return result;
}
/* ----------------------------------------------------------------
* ExecEvalBooleanTest
*
* Evaluate a BooleanTest node.
* ----------------------------------------------------------------
*/
static Datum ExecEvalBooleanTest(GenericExprState* bstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
BooleanTest* btest = (BooleanTest*)bstate->xprstate.expr;
Datum result;
result = ExecEvalExpr(bstate->arg, econtext, isNull, isDone);
if (isDone && *isDone == ExprEndResult)
return result; /* nothing to check */
switch (btest->booltesttype) {
case IS_TRUE:
if (*isNull) {
*isNull = false;
return BoolGetDatum(false);
} else if (DatumGetBool(result))
return BoolGetDatum(true);
else
return BoolGetDatum(false);
case IS_NOT_TRUE:
if (*isNull) {
*isNull = false;
return BoolGetDatum(true);
} else if (DatumGetBool(result))
return BoolGetDatum(false);
else
return BoolGetDatum(true);
case IS_FALSE:
if (*isNull) {
*isNull = false;
return BoolGetDatum(false);
} else if (DatumGetBool(result))
return BoolGetDatum(false);
else
return BoolGetDatum(true);
case IS_NOT_FALSE:
if (*isNull) {
*isNull = false;
return BoolGetDatum(true);
} else if (DatumGetBool(result))
return BoolGetDatum(true);
else
return BoolGetDatum(false);
case IS_UNKNOWN:
if (*isNull) {
*isNull = false;
return BoolGetDatum(true);
} else
return BoolGetDatum(false);
case IS_NOT_UNKNOWN:
if (*isNull) {
*isNull = false;
return BoolGetDatum(false);
} else
return BoolGetDatum(true);
default:
ereport(ERROR,
(errcode(ERRCODE_UNRECOGNIZED_NODE_TYPE),
errmodule(MOD_EXECUTOR),
errmsg("unrecognized booltesttype: %d", (int)btest->booltesttype)));
return (Datum)0; /* keep compiler quiet */
}
}
/*
* ExecEvalCoerceToDomain
*
* Test the provided data against the domain constraint(s). If the data
* passes the constraint specifications, pass it through (return the
* datum) otherwise throw an error.
*/
static Datum ExecEvalCoerceToDomain(
CoerceToDomainState* cstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
CoerceToDomain* ctest = (CoerceToDomain*)cstate->xprstate.expr;
Datum result;
ListCell* l = NULL;
result = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
if (isDone && *isDone == ExprEndResult)
return result; /* nothing to check */
foreach (l, cstate->constraints) {
DomainConstraintState* con = (DomainConstraintState*)lfirst(l);
switch (con->constrainttype) {
case DOM_CONSTRAINT_NOTNULL:
if (*isNull)
ereport(ERROR,
(errcode(ERRCODE_NOT_NULL_VIOLATION),
errmsg("domain %s does not allow null values", format_type_be(ctest->resulttype))));
break;
case DOM_CONSTRAINT_CHECK: {
Datum conResult;
bool conIsNull = false;
Datum save_datum;
bool save_isNull = false;
/*
* Set up value to be returned by CoerceToDomainValue
* nodes. We must save and restore prior setting of
* econtext's domainValue fields, in case this node is
* itself within a check expression for another domain.
*/
save_datum = econtext->domainValue_datum;
save_isNull = econtext->domainValue_isNull;
econtext->domainValue_datum = result;
econtext->domainValue_isNull = *isNull;
conResult = ExecEvalExpr(con->check_expr, econtext, &conIsNull, NULL);
if (!conIsNull && !DatumGetBool(conResult))
ereport(ERROR,
(errcode(ERRCODE_CHECK_VIOLATION),
errmsg("value for domain %s violates check constraint \"%s\"",
format_type_be(ctest->resulttype),
con->name)));
econtext->domainValue_datum = save_datum;
econtext->domainValue_isNull = save_isNull;
break;
}
default:
ereport(ERROR,
(errcode(ERRCODE_UNRECOGNIZED_NODE_TYPE),
errmodule(MOD_EXECUTOR),
errmsg("unrecognized constraint type: %d", (int)con->constrainttype)));
break;
}
}
/* If all has gone well (constraints did not fail) return the datum */
return result;
}
/*
* ExecEvalCoerceToDomainValue
*
* Return the value stored by CoerceToDomain.
*/
static Datum ExecEvalCoerceToDomainValue(
ExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
if (isDone != NULL)
*isDone = ExprSingleResult;
*isNull = econtext->domainValue_isNull;
return econtext->domainValue_datum;
}
/* ----------------------------------------------------------------
* ExecEvalFieldSelect
*
* Evaluate a FieldSelect node.
* ----------------------------------------------------------------
*/
static Datum ExecEvalFieldSelect(FieldSelectState* fstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
FieldSelect* fselect = (FieldSelect*)fstate->xprstate.expr;
AttrNumber fieldnum = fselect->fieldnum;
Datum result;
Datum tupDatum;
HeapTupleHeader tuple;
Oid tupType;
int32 tupTypmod;
TupleDesc tupDesc;
Form_pg_attribute attr;
HeapTupleData tmptup;
tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
/* this test covers the isDone exception too: */
if (*isNull)
return tupDatum;
tuple = DatumGetHeapTupleHeader(tupDatum);
tupType = HeapTupleHeaderGetTypeId(tuple);
tupTypmod = HeapTupleHeaderGetTypMod(tuple);
/* Lookup tupdesc if first time through or if type changes */
tupDesc = get_cached_rowtype(tupType, tupTypmod, &fstate->argdesc, econtext);
/*
* Find field's attr record. Note we don't support system columns here: a
* datum tuple doesn't have valid values for most of the interesting
* system columns anyway.
*/
if (fieldnum <= 0) /* should never happen */
ereport(ERROR,
(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
errmodule(MOD_EXECUTOR),
errmsg("unsupported reference to system column %d in FieldSelect", fieldnum)));
if (fieldnum > tupDesc->natts) /* should never happen */
ereport(ERROR,
(errcode(ERRCODE_INVALID_ATTRIBUTE),
errmodule(MOD_EXECUTOR),
errmsg("attribute number %d exceeds number of columns %d", fieldnum, tupDesc->natts)));
attr = tupDesc->attrs[fieldnum - 1];
/* Check for dropped column, and force a NULL result if so */
if (attr->attisdropped) {
*isNull = true;
return (Datum)0;
}
/* Check for type mismatch --- possible after ALTER COLUMN TYPE? */
/* As in ExecEvalScalarVar, we should but can't check typmod */
if (fselect->resulttype != attr->atttypid)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("attribute %d has wrong type", fieldnum),
errdetail("Table has type %s, but query expects %s.",
format_type_be(attr->atttypid),
format_type_be(fselect->resulttype))));
/* heap_getattr needs a HeapTuple not a bare HeapTupleHeader */
tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
tmptup.t_data = tuple;
result = tableam_tops_tuple_getattr(&tmptup, fieldnum, tupDesc, isNull);
return result;
}
/* ----------------------------------------------------------------
* ExecEvalFieldStore
*
* Evaluate a FieldStore node.
* ----------------------------------------------------------------
*/
static Datum ExecEvalFieldStore(FieldStoreState* fstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
FieldStore* fstore = (FieldStore*)fstate->xprstate.expr;
HeapTuple tuple;
Datum tupDatum;
TupleDesc tupDesc;
Datum* values = NULL;
bool* isnull = NULL;
Datum save_datum;
bool save_isNull = false;
ListCell* l1 = NULL;
ListCell* l2 = NULL;
errno_t rc = EOK;
tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
if (isDone != NULL && *isDone == ExprEndResult)
return tupDatum;
/* Lookup tupdesc if first time through or after rescan */
tupDesc = get_cached_rowtype(fstore->resulttype, -1, &fstate->argdesc, econtext);
/* Allocate workspace */
values = (Datum*)palloc(tupDesc->natts * sizeof(Datum));
isnull = (bool*)palloc(tupDesc->natts * sizeof(bool));
if (!*isNull) {
/*
* heap_deform_tuple needs a HeapTuple not a bare HeapTupleHeader. We
* set all the fields in the struct just in case.
*/
HeapTupleHeader tuphdr;
HeapTupleData tmptup;
tuphdr = DatumGetHeapTupleHeader(tupDatum);
tmptup.t_len = HeapTupleHeaderGetDatumLength(tuphdr);
ItemPointerSetInvalid(&(tmptup.t_self));
tmptup.t_tableOid = InvalidOid;
tmptup.t_bucketId = InvalidBktId;
#ifdef PGXC
tmptup.t_xc_node_id = 0;
#endif
HeapTupleSetZeroBase(&tmptup);
tmptup.t_data = tuphdr;
tableam_tops_deform_tuple(&tmptup, tupDesc, values, isnull);
} else {
/* Convert null input tuple into an all-nulls row */
rc = memset_s(isnull, tupDesc->natts * sizeof(bool), true, tupDesc->natts * sizeof(bool));
securec_check(rc, "\0", "\0");
}
/* Result is never null */
*isNull = false;
save_datum = econtext->caseValue_datum;
save_isNull = econtext->caseValue_isNull;
forboth(l1, fstate->newvals, l2, fstore->fieldnums)
{
ExprState* newval = (ExprState*)lfirst(l1);
AttrNumber fieldnum = lfirst_int(l2);
Assert(fieldnum > 0 && fieldnum <= tupDesc->natts);
/*
* Use the CaseTestExpr mechanism to pass down the old value of the
* field being replaced; this is needed in case the newval is itself a
* FieldStore or ArrayRef that has to obtain and modify the old value.
* It's safe to reuse the CASE mechanism because there cannot be a
* CASE between here and where the value would be needed, and a field
* assignment can't be within a CASE either. (So saving and restoring
* the caseValue is just paranoia, but let's do it anyway.)
*/
econtext->caseValue_datum = values[fieldnum - 1];
econtext->caseValue_isNull = isnull[fieldnum - 1];
values[fieldnum - 1] = ExecEvalExpr(newval, econtext, &isnull[fieldnum - 1], NULL);
}
econtext->caseValue_datum = save_datum;
econtext->caseValue_isNull = save_isNull;
tuple = (HeapTuple)tableam_tops_form_tuple(tupDesc, values, isnull, HEAP_TUPLE);
pfree_ext(values);
pfree_ext(isnull);
return HeapTupleGetDatum(tuple);
}
/* ----------------------------------------------------------------
* ExecEvalRelabelType
*
* Evaluate a RelabelType node.
* ----------------------------------------------------------------
*/
static Datum ExecEvalRelabelType(GenericExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
return ExecEvalExpr(exprstate->arg, econtext, isNull, isDone);
}
/* ----------------------------------------------------------------
* ExecEvalCoerceViaIO
*
* Evaluate a CoerceViaIO node.
* ----------------------------------------------------------------
*/
static Datum ExecEvalCoerceViaIO(CoerceViaIOState* iostate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
Datum result;
Datum inputval;
char* string = NULL;
inputval = ExecEvalExpr(iostate->arg, econtext, isNull, isDone);
if (isDone && *isDone == ExprEndResult)
return inputval; /* nothing to do */
if (*isNull)
string = NULL; /* output functions are not called on nulls */
else
string = OutputFunctionCall(&iostate->outfunc, inputval);
result = InputFunctionCall(&iostate->infunc, string, iostate->intypioparam, -1);
/* The input function cannot change the null/not-null status */
return result;
}
/* ----------------------------------------------------------------
* ExecEvalArrayCoerceExpr
*
* Evaluate an ArrayCoerceExpr node.
* ----------------------------------------------------------------
*/
static Datum ExecEvalArrayCoerceExpr(
ArrayCoerceExprState* astate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
ArrayCoerceExpr* acoerce = (ArrayCoerceExpr*)astate->xprstate.expr;
Datum result;
ArrayType* array = NULL;
FunctionCallInfoData locfcinfo;
result = ExecEvalExpr(astate->arg, econtext, isNull, isDone);
if (isDone && *isDone == ExprEndResult)
return result; /* nothing to do */
if (*isNull)
return result; /* nothing to do */
/*
* If it's binary-compatible, modify the element type in the array header,
* but otherwise leave the array as we received it.
*/
if (!OidIsValid(acoerce->elemfuncid)) {
/* Detoast input array if necessary, and copy in any case */
array = DatumGetArrayTypePCopy(result);
ARR_ELEMTYPE(array) = astate->resultelemtype;
PG_RETURN_ARRAYTYPE_P(array);
}
/* Detoast input array if necessary, but don't make a useless copy */
array = DatumGetArrayTypeP(result);
/* Initialize function cache if first time through */
if (astate->elemfunc.fn_oid == InvalidOid) {
AclResult aclresult;
/* Check permission to call function */
aclresult = pg_proc_aclcheck(acoerce->elemfuncid, GetUserId(), ACL_EXECUTE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_PROC, get_func_name(acoerce->elemfuncid));
/* Set up the primary fmgr lookup information */
fmgr_info_cxt(acoerce->elemfuncid, &(astate->elemfunc), econtext->ecxt_per_query_memory);
fmgr_info_set_expr((Node*)acoerce, &(astate->elemfunc));
}
/*
* Use array_map to apply the function to each array element.
*
* We pass on the desttypmod and isExplicit flags whether or not the
* function wants them.
*
* Note: coercion functions are assumed to not use collation.
*/
InitFunctionCallInfoData(locfcinfo, &(astate->elemfunc), 3, InvalidOid, NULL, NULL);
locfcinfo.arg[0] = PointerGetDatum(array);
locfcinfo.arg[1] = Int32GetDatum(acoerce->resulttypmod);
locfcinfo.arg[2] = BoolGetDatum(acoerce->isExplicit);
locfcinfo.argnull[0] = false;
locfcinfo.argnull[1] = false;
locfcinfo.argnull[2] = false;
return array_map(&locfcinfo, ARR_ELEMTYPE(array), astate->resultelemtype, astate->amstate);
}
/* ----------------------------------------------------------------
* ExecEvalCurrentOfExpr
*
* The planner must convert CURRENT OF into a TidScan qualification.
* So, we have to be able to do ExecInitExpr on a CurrentOfExpr,
* but we shouldn't ever actually execute it.
* ----------------------------------------------------------------
*/
static Datum ExecEvalCurrentOfExpr(ExprState* exprstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmodule(MOD_EXECUTOR), errmsg("CURRENT OF cannot be executed")));
return 0; /* keep compiler quiet */
}
/*
* ExecEvalExprSwitchContext
*
* Same as ExecEvalExpr, but get into the right allocation context explicitly.
*/
Datum ExecEvalExprSwitchContext(ExprState* expression, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
Datum retDatum;
MemoryContext oldContext;
oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
retDatum = ExecEvalExpr(expression, econtext, isNull, isDone);
MemoryContextSwitchTo(oldContext);
return retDatum;
}
/*
* ExecInitExpr: prepare an expression tree for execution
*
* This function builds and returns an ExprState tree paralleling the given
* Expr node tree. The ExprState tree can then be handed to ExecEvalExpr
* for execution. Because the Expr tree itself is read-only as far as
* ExecInitExpr and ExecEvalExpr are concerned, several different executions
* of the same plan tree can occur concurrently.
*
* This must be called in a memory context that will last as long as repeated
* executions of the expression are needed. Typically the context will be
* the same as the per-query context of the associated ExprContext.
*
* Any Aggref, WindowFunc, or SubPlan nodes found in the tree are added to the
* lists of such nodes held by the parent PlanState. Otherwise, we do very
* little initialization here other than building the state-node tree. Any
* nontrivial work associated with initializing runtime info for a node should
* happen during the first actual evaluation of that node. (This policy lets
* us avoid work if the node is never actually evaluated.)
*
* Note: there is no ExecEndExpr function; we assume that any resource
* cleanup needed will be handled by just releasing the memory context
* in which the state tree is built. Functions that require additional
* cleanup work can register a shutdown callback in the ExprContext.
*
* 'node' is the root of the expression tree to examine
* 'parent' is the PlanState node that owns the expression.
*
* 'parent' may be NULL if we are preparing an expression that is not
* associated with a plan tree. (If so, it can't have aggs or subplans.)
* This case should usually come through ExecPrepareExpr, not directly here.
*/
ExprState* ExecInitExpr(Expr* node, PlanState* parent)
{
ExprState* state = NULL;
gstrace_entry(GS_TRC_ID_ExecInitExpr);
if (node == NULL) {
gstrace_exit(GS_TRC_ID_ExecInitExpr);
return NULL;
}
/* Guard against stack overflow due to overly complex expressions */
check_stack_depth();
switch (nodeTag(node)) {
case T_Var:
/* varattno == InvalidAttrNumber means it's a whole-row Var */
if (((Var*)node)->varattno == InvalidAttrNumber) {
WholeRowVarExprState* wstate = makeNode(WholeRowVarExprState);
wstate->parent = parent;
wstate->wrv_junkFilter = NULL;
state = (ExprState*)wstate;
state->evalfunc = (ExprStateEvalFunc)ExecEvalWholeRowVar;
} else {
state = (ExprState*)makeNode(ExprState);
state->evalfunc = ExecEvalScalarVar;
}
break;
case T_Const:
state = (ExprState*)makeNode(ExprState);
state->evalfunc = ExecEvalConst;
break;
case T_Param:
state = (ExprState*)makeNode(ExprState);
switch (((Param*)node)->paramkind) {
case PARAM_EXEC:
state->evalfunc = ExecEvalParamExec;
break;
case PARAM_EXTERN:
state->evalfunc = ExecEvalParamExtern;
break;
default:
ereport(ERROR,
(errcode(ERRCODE_UNRECOGNIZED_NODE_TYPE),
errmodule(MOD_EXECUTOR),
errmsg("unrecognized paramkind: %d", (int)((Param*)node)->paramkind)));
break;
}
break;
case T_CoerceToDomainValue:
state = (ExprState*)makeNode(ExprState);
state->evalfunc = ExecEvalCoerceToDomainValue;
break;
case T_CaseTestExpr:
state = (ExprState*)makeNode(ExprState);
state->evalfunc = ExecEvalCaseTestExpr;
break;
case T_Aggref: {
Aggref* aggref = (Aggref*)node;
AggrefExprState* astate = makeNode(AggrefExprState);
astate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalAggref;
if (parent && (IsA(parent, AggState) || IsA(parent, VecAggState))) {
AggState* aggstate = (AggState*)parent;
int naggs;
aggstate->aggs = lcons(astate, aggstate->aggs);
naggs = ++aggstate->numaggs;
astate->aggdirectargs = (List*)ExecInitExpr((Expr*)aggref->aggdirectargs, parent);
astate->args = (List*)ExecInitExpr((Expr*)aggref->args, parent);
/*
* Complain if the aggregate's arguments contain any
* aggregates; nested agg functions are semantically
* nonsensical. (This should have been caught earlier,
* but we defend against it here anyway.)
*/
if (naggs != aggstate->numaggs)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("aggregate function calls cannot be nested")));
} else {
/* planner messed up */
ereport(ERROR,
(errcode(ERRCODE_INVALID_AGG), errmodule(MOD_OPT), errmsg("Aggref found in non-Agg plan node")));
}
state = (ExprState*)astate;
} break;
case T_GroupingFunc: {
GroupingFunc* grp_node = (GroupingFunc*)node;
GroupingFuncExprState* grp_state = makeNode(GroupingFuncExprState);
Agg* agg = NULL;
if (parent && (IsA(parent, AggState) || IsA(parent, VecAggState))) {
grp_state->aggstate = (AggState*)parent;
agg = (Agg*)(parent->plan);
if (agg->groupingSets)
grp_state->clauses = grp_node->cols;
else
grp_state->clauses = NIL;
state = (ExprState*)grp_state;
state->evalfunc = (ExprStateEvalFunc)ExecEvalGroupingFuncExpr;
} else
ereport(ERROR,
(errcode(ERRCODE_PLAN_PARENT_NOT_FOUND),
errmodule(MOD_OPT),
errmsg("parent of GROUPING is not Agg node")));
} break;
case T_GroupingId: {
GroupingIdExprState* grp_id_state = makeNode(GroupingIdExprState);
if (parent == NULL || !IsA(parent, AggState) || !IsA(parent->plan, Agg)) {
ereport(ERROR,
(errcode(ERRCODE_PLAN_PARENT_NOT_FOUND),
errmodule(MOD_OPT),
errmsg("parent of GROUPINGID is not Agg node")));
}
grp_id_state->aggstate = (AggState*)parent;
state = (ExprState*)grp_id_state;
state->evalfunc = (ExprStateEvalFunc)ExecEvalGroupingIdExpr;
} break;
case T_WindowFunc: {
WindowFunc* wfunc = (WindowFunc*)node;
WindowFuncExprState* wfstate = makeNode(WindowFuncExprState);
wfstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalWindowFunc;
if (parent && (IsA(parent, WindowAggState) || IsA(parent, VecWindowAggState))) {
WindowAggState* winstate = (WindowAggState*)parent;
int nfuncs;
winstate->funcs = lcons(wfstate, winstate->funcs);
nfuncs = ++winstate->numfuncs;
if (wfunc->winagg)
winstate->numaggs++;
wfstate->args = (List*)ExecInitExpr((Expr*)wfunc->args, parent);
/*
* Complain if the windowfunc's arguments contain any
* windowfuncs; nested window functions are semantically
* nonsensical. (This should have been caught earlier,
* but we defend against it here anyway.)
*/
if (nfuncs != winstate->numfuncs)
ereport(
ERROR, (errcode(ERRCODE_WINDOWING_ERROR), errmsg("window function calls cannot be nested")));
} else {
/* planner messed up */
ereport(
ERROR, (errcode(ERRCODE_WINDOWING_ERROR), errmsg("WindowFunc found in non-WindowAgg plan node")));
}
state = (ExprState*)wfstate;
} break;
case T_ArrayRef: {
ArrayRef* aref = (ArrayRef*)node;
ArrayRefExprState* astate = makeNode(ArrayRefExprState);
astate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalArrayRef;
astate->refupperindexpr = (List*)ExecInitExpr((Expr*)aref->refupperindexpr, parent);
astate->reflowerindexpr = (List*)ExecInitExpr((Expr*)aref->reflowerindexpr, parent);
astate->refexpr = ExecInitExpr(aref->refexpr, parent);
astate->refassgnexpr = ExecInitExpr(aref->refassgnexpr, parent);
/* do one-time catalog lookups for type info */
astate->refattrlength = get_typlen(aref->refarraytype);
get_typlenbyvalalign(
aref->refelemtype, &astate->refelemlength, &astate->refelembyval, &astate->refelemalign);
state = (ExprState*)astate;
} break;
case T_FuncExpr: {
FuncExpr* funcexpr = (FuncExpr*)node;
FuncExprState* fstate = makeNode(FuncExprState);
bool isnull = true;
fstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalFunc;
fstate->args = (List*)ExecInitExpr((Expr*)funcexpr->args, parent);
fstate->func.fn_oid = InvalidOid; /* not initialized */
HeapTuple proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcexpr->funcid));
if (!HeapTupleIsValid(proctup)) {
ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("cache lookup failed for function %u", funcexpr->funcid)));
}
/*
* If proconfig is set we can't allow transaction commands because of the
* way the GUC stacking works: The transaction boundary would have to pop
* the proconfig setting off the stack. That restriction could be lifted
* by redesigning the GUC nesting mechanism a bit.
*/
if (!heap_attisnull(proctup, Anum_pg_proc_proconfig, NULL) || u_sess->SPI_cxt.is_proconfig_set) {
u_sess->SPI_cxt.is_proconfig_set = true;
stp_set_commit_rollback_err_msg(STP_XACT_GUC_IN_OPT_CLAUSE);
}
Datum datum = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prokind, &isnull);
fstate->prokind = CharGetDatum(datum);
ReleaseSysCache(proctup);
state = (ExprState*)fstate;
} break;
case T_OpExpr: {
OpExpr* opexpr = (OpExpr*)node;
FuncExprState* fstate = makeNode(FuncExprState);
fstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalOper;
fstate->args = (List*)ExecInitExpr((Expr*)opexpr->args, parent);
fstate->func.fn_oid = InvalidOid; /* not initialized */
state = (ExprState*)fstate;
} break;
case T_DistinctExpr: {
DistinctExpr* distinctexpr = (DistinctExpr*)node;
FuncExprState* fstate = makeNode(FuncExprState);
fstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalDistinct;
fstate->args = (List*)ExecInitExpr((Expr*)distinctexpr->args, parent);
fstate->func.fn_oid = InvalidOid; /* not initialized */
state = (ExprState*)fstate;
} break;
case T_NullIfExpr: {
NullIfExpr* nullifexpr = (NullIfExpr*)node;
FuncExprState* fstate = makeNode(FuncExprState);
fstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalNullIf;
fstate->args = (List*)ExecInitExpr((Expr*)nullifexpr->args, parent);
fstate->func.fn_oid = InvalidOid; /* not initialized */
state = (ExprState*)fstate;
} break;
case T_ScalarArrayOpExpr: {
ScalarArrayOpExpr* opexpr = (ScalarArrayOpExpr*)node;
ScalarArrayOpExprState* sstate = makeNode(ScalarArrayOpExprState);
sstate->fxprstate.xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalScalarArrayOp;
sstate->fxprstate.args = (List*)ExecInitExpr((Expr*)opexpr->args, parent);
sstate->fxprstate.func.fn_oid = InvalidOid; /* not initialized */
sstate->element_type = InvalidOid; /* ditto */
state = (ExprState*)sstate;
} break;
case T_BoolExpr: {
BoolExpr* boolexpr = (BoolExpr*)node;
BoolExprState* bstate = makeNode(BoolExprState);
switch (boolexpr->boolop) {
case AND_EXPR:
bstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalAnd;
break;
case OR_EXPR:
bstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalOr;
break;
case NOT_EXPR:
bstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalNot;
break;
default:
ereport(ERROR,
(errcode(ERRCODE_UNRECOGNIZED_NODE_TYPE),
errmodule(MOD_OPT),
errmsg("unrecognized boolop: %d", (int)boolexpr->boolop)));
break;
}
bstate->args = (List*)ExecInitExpr((Expr*)boolexpr->args, parent);
state = (ExprState*)bstate;
} break;
case T_SubPlan: {
SubPlan* subplan = (SubPlan*)node;
SubPlanState* sstate = NULL;
if (parent == NULL)
ereport(ERROR,
(errcode(ERRCODE_PLAN_PARENT_NOT_FOUND),
errmodule(MOD_OPT),
errmsg("SubPlan found with no parent plan")));
sstate = ExecInitSubPlan(subplan, parent);
/* Add SubPlanState nodes to parent->subPlan */
parent->subPlan = lappend(parent->subPlan, sstate);
state = (ExprState*)sstate;
} break;
case T_AlternativeSubPlan: {
AlternativeSubPlan* asplan = (AlternativeSubPlan*)node;
AlternativeSubPlanState* asstate = NULL;
if (parent == NULL)
ereport(ERROR,
(errcode(ERRCODE_PLAN_PARENT_NOT_FOUND),
errmodule(MOD_OPT),
errmsg("AlternativeSubPlan found with no parent plan")));
asstate = ExecInitAlternativeSubPlan(asplan, parent);
state = (ExprState*)asstate;
} break;
case T_FieldSelect: {
FieldSelect* fselect = (FieldSelect*)node;
FieldSelectState* fstate = makeNode(FieldSelectState);
fstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalFieldSelect;
fstate->arg = ExecInitExpr(fselect->arg, parent);
fstate->argdesc = NULL;
state = (ExprState*)fstate;
} break;
case T_FieldStore: {
FieldStore* fstore = (FieldStore*)node;
FieldStoreState* fstate = makeNode(FieldStoreState);
fstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalFieldStore;
fstate->arg = ExecInitExpr(fstore->arg, parent);
fstate->newvals = (List*)ExecInitExpr((Expr*)fstore->newvals, parent);
fstate->argdesc = NULL;
state = (ExprState*)fstate;
} break;
case T_RelabelType: {
RelabelType* relabel = (RelabelType*)node;
GenericExprState* gstate = makeNode(GenericExprState);
gstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalRelabelType;
gstate->arg = ExecInitExpr(relabel->arg, parent);
state = (ExprState*)gstate;
} break;
case T_CoerceViaIO: {
CoerceViaIO* iocoerce = (CoerceViaIO*)node;
CoerceViaIOState* iostate = makeNode(CoerceViaIOState);
Oid iofunc;
bool typisvarlena = false;
iostate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalCoerceViaIO;
iostate->arg = ExecInitExpr(iocoerce->arg, parent);
/* lookup the result type's input function */
getTypeInputInfo(iocoerce->resulttype, &iofunc, &iostate->intypioparam);
fmgr_info(iofunc, &iostate->infunc);
/* lookup the input type's output function */
getTypeOutputInfo(exprType((Node*)iocoerce->arg), &iofunc, &typisvarlena);
fmgr_info(iofunc, &iostate->outfunc);
state = (ExprState*)iostate;
} break;
case T_ArrayCoerceExpr: {
ArrayCoerceExpr* acoerce = (ArrayCoerceExpr*)node;
ArrayCoerceExprState* astate = makeNode(ArrayCoerceExprState);
astate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalArrayCoerceExpr;
astate->arg = ExecInitExpr(acoerce->arg, parent);
astate->resultelemtype = get_element_type(acoerce->resulttype);
if (astate->resultelemtype == InvalidOid)
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("target type is not an array")));
/* Arrays over domains aren't supported yet */
Assert(getBaseType(astate->resultelemtype) == astate->resultelemtype);
astate->elemfunc.fn_oid = InvalidOid; /* not initialized */
astate->amstate = (ArrayMapState*)palloc0(sizeof(ArrayMapState));
state = (ExprState*)astate;
} break;
case T_ConvertRowtypeExpr: {
ConvertRowtypeExpr* convert = (ConvertRowtypeExpr*)node;
ConvertRowtypeExprState* cstate = makeNode(ConvertRowtypeExprState);
cstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalConvertRowtype;
cstate->arg = ExecInitExpr(convert->arg, parent);
state = (ExprState*)cstate;
} break;
case T_CaseExpr: {
CaseExpr* caseexpr = (CaseExpr*)node;
CaseExprState* cstate = makeNode(CaseExprState);
List* outlist = NIL;
ListCell* l = NULL;
cstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalCase;
cstate->arg = ExecInitExpr(caseexpr->arg, parent);
foreach (l, caseexpr->args) {
CaseWhen* when = (CaseWhen*)lfirst(l);
CaseWhenState* wstate = makeNode(CaseWhenState);
Assert(IsA(when, CaseWhen));
wstate->xprstate.evalfunc = NULL; /* not used */
wstate->xprstate.expr = (Expr*)when;
wstate->expr = ExecInitExpr(when->expr, parent);
wstate->result = ExecInitExpr(when->result, parent);
outlist = lappend(outlist, wstate);
}
cstate->args = outlist;
cstate->defresult = ExecInitExpr(caseexpr->defresult, parent);
state = (ExprState*)cstate;
} break;
case T_ArrayExpr: {
ArrayExpr* arrayexpr = (ArrayExpr*)node;
ArrayExprState* astate = makeNode(ArrayExprState);
List* outlist = NIL;
ListCell* l = NULL;
astate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalArray;
foreach (l, arrayexpr->elements) {
Expr* e = (Expr*)lfirst(l);
ExprState* estate = NULL;
estate = ExecInitExpr(e, parent);
outlist = lappend(outlist, estate);
}
astate->elements = outlist;
/* do one-time catalog lookup for type info */
get_typlenbyvalalign(
arrayexpr->element_typeid, &astate->elemlength, &astate->elembyval, &astate->elemalign);
state = (ExprState*)astate;
} break;
case T_RowExpr: {
RowExpr* rowexpr = (RowExpr*)node;
RowExprState* rstate = makeNode(RowExprState);
Form_pg_attribute* attrs = NULL;
List* outlist = NIL;
ListCell* l = NULL;
int i;
rstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalRow;
/* Build tupdesc to describe result tuples */
if (rowexpr->row_typeid == RECORDOID) {
/* generic record, use runtime type assignment */
rstate->tupdesc = ExecTypeFromExprList(rowexpr->args, rowexpr->colnames, TAM_HEAP);
BlessTupleDesc(rstate->tupdesc);
/* we won't need to redo this at runtime */
} else {
/* it's been cast to a named type, use that */
rstate->tupdesc = lookup_rowtype_tupdesc_copy(rowexpr->row_typeid, -1);
}
/* Set up evaluation, skipping any deleted columns */
Assert(list_length(rowexpr->args) <= rstate->tupdesc->natts);
attrs = rstate->tupdesc->attrs;
i = 0;
foreach (l, rowexpr->args) {
Expr* e = (Expr*)lfirst(l);
ExprState* estate = NULL;
if (!attrs[i]->attisdropped) {
/*
* Guard against ALTER COLUMN TYPE on rowtype since
* the RowExpr was created. XXX should we check
* typmod too? Not sure we can be sure it'll be the
* same.
*/
if (exprType((Node*)e) != attrs[i]->atttypid)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("ROW() column has type %s instead of type %s",
format_type_be(exprType((Node*)e)),
format_type_be(attrs[i]->atttypid))));
} else {
/*
* Ignore original expression and insert a NULL. We
* don't really care what type of NULL it is, so
* always make an int4 NULL.
*/
e = (Expr*)makeNullConst(INT4OID, -1, InvalidOid);
}
estate = ExecInitExpr(e, parent);
outlist = lappend(outlist, estate);
i++;
}
rstate->args = outlist;
state = (ExprState*)rstate;
} break;
case T_RowCompareExpr: {
RowCompareExpr* rcexpr = (RowCompareExpr*)node;
RowCompareExprState* rstate = makeNode(RowCompareExprState);
int nopers = list_length(rcexpr->opnos);
List* outlist = NIL;
ListCell* l = NULL;
ListCell* l2 = NULL;
ListCell* l3 = NULL;
int i;
rstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalRowCompare;
Assert(list_length(rcexpr->largs) == nopers);
outlist = NIL;
foreach (l, rcexpr->largs) {
Expr* e = (Expr*)lfirst(l);
ExprState* estate = NULL;
estate = ExecInitExpr(e, parent);
outlist = lappend(outlist, estate);
}
rstate->largs = outlist;
Assert(list_length(rcexpr->rargs) == nopers);
outlist = NIL;
foreach (l, rcexpr->rargs) {
Expr* e = (Expr*)lfirst(l);
ExprState* estate = NULL;
estate = ExecInitExpr(e, parent);
outlist = lappend(outlist, estate);
}
rstate->rargs = outlist;
Assert(list_length(rcexpr->opfamilies) == nopers);
rstate->funcs = (FmgrInfo*)palloc(nopers * sizeof(FmgrInfo));
rstate->collations = (Oid*)palloc(nopers * sizeof(Oid));
i = 0;
forthree(l, rcexpr->opnos, l2, rcexpr->opfamilies, l3, rcexpr->inputcollids)
{
Oid opno = lfirst_oid(l);
Oid opfamily = lfirst_oid(l2);
Oid inputcollid = lfirst_oid(l3);
int strategy;
Oid lefttype;
Oid righttype;
Oid proc;
get_op_opfamily_properties(opno, opfamily, false, &strategy, &lefttype, &righttype);
proc = get_opfamily_proc(opfamily, lefttype, righttype, BTORDER_PROC);
/*
* If we enforced permissions checks on index support
* functions, we'd need to make a check here. But the
* index support machinery doesn't do that, and neither
* does this code.
*/
fmgr_info(proc, &(rstate->funcs[i]));
rstate->collations[i] = inputcollid;
i++;
}
state = (ExprState*)rstate;
} break;
case T_CoalesceExpr: {
CoalesceExpr* coalesceexpr = (CoalesceExpr*)node;
CoalesceExprState* cstate = makeNode(CoalesceExprState);
List* outlist = NIL;
ListCell* l = NULL;
cstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalCoalesce;
foreach (l, coalesceexpr->args) {
Expr* e = (Expr*)lfirst(l);
ExprState* estate = NULL;
estate = ExecInitExpr(e, parent);
outlist = lappend(outlist, estate);
}
cstate->args = outlist;
state = (ExprState*)cstate;
} break;
case T_MinMaxExpr: {
MinMaxExpr* minmaxexpr = (MinMaxExpr*)node;
MinMaxExprState* mstate = makeNode(MinMaxExprState);
List* outlist = NIL;
ListCell* l = NULL;
TypeCacheEntry* typentry = NULL;
mstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalMinMax;
foreach (l, minmaxexpr->args) {
Expr* e = (Expr*)lfirst(l);
ExprState* estate = NULL;
estate = ExecInitExpr(e, parent);
outlist = lappend(outlist, estate);
}
mstate->args = outlist;
/* Look up the btree comparison function for the datatype */
typentry = lookup_type_cache(minmaxexpr->minmaxtype, TYPECACHE_CMP_PROC);
if (!OidIsValid(typentry->cmp_proc))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("could not identify a comparison function for type %s",
format_type_be(minmaxexpr->minmaxtype))));
/*
* If we enforced permissions checks on index support
* functions, we'd need to make a check here. But the index
* support machinery doesn't do that, and neither does this
* code.
*/
fmgr_info(typentry->cmp_proc, &(mstate->cfunc));
state = (ExprState*)mstate;
} break;
case T_XmlExpr: {
XmlExpr* xexpr = (XmlExpr*)node;
XmlExprState* xstate = makeNode(XmlExprState);
List* outlist = NIL;
ListCell* arg = NULL;
xstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalXml;
outlist = NIL;
foreach (arg, xexpr->named_args) {
Expr* e = (Expr*)lfirst(arg);
ExprState* estate = NULL;
estate = ExecInitExpr(e, parent);
outlist = lappend(outlist, estate);
}
xstate->named_args = outlist;
outlist = NIL;
foreach (arg, xexpr->args) {
Expr* e = (Expr*)lfirst(arg);
ExprState* estate = NULL;
estate = ExecInitExpr(e, parent);
outlist = lappend(outlist, estate);
}
xstate->args = outlist;
state = (ExprState*)xstate;
} break;
case T_NullTest: {
NullTest* ntest = (NullTest*)node;
NullTestState* nstate = makeNode(NullTestState);
nstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalNullTest;
nstate->arg = ExecInitExpr(ntest->arg, parent);
nstate->argdesc = NULL;
state = (ExprState*)nstate;
} break;
case T_HashFilter: {
HashFilter* htest = (HashFilter*)node;
HashFilterState* hstate = makeNode(HashFilterState);
List* outlist = NIL;
ListCell* l = NULL;
int idx = 0;
hstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalHashFilter;
foreach (l, htest->arg) {
Expr* e = (Expr*)lfirst(l);
ExprState* estate = NULL;
estate = ExecInitExpr(e, parent);
outlist = lappend(outlist, estate);
}
hstate->arg = outlist;
hstate->bucketMap = get_bucketmap_by_execnode(parent->plan->exec_nodes, parent->state->es_plannedstmt);
hstate->nodelist = (uint2*)palloc(list_length(htest->nodeList) * sizeof(uint2));
foreach (l, htest->nodeList)
hstate->nodelist[idx++] = lfirst_int(l);
state = (ExprState*)hstate;
} break;
case T_BooleanTest: {
BooleanTest* btest = (BooleanTest*)node;
GenericExprState* gstate = makeNode(GenericExprState);
gstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalBooleanTest;
gstate->arg = ExecInitExpr(btest->arg, parent);
state = (ExprState*)gstate;
} break;
case T_CoerceToDomain: {
CoerceToDomain* ctest = (CoerceToDomain*)node;
CoerceToDomainState* cstate = makeNode(CoerceToDomainState);
cstate->xprstate.evalfunc = (ExprStateEvalFunc)ExecEvalCoerceToDomain;
cstate->arg = ExecInitExpr(ctest->arg, parent);
cstate->constraints = GetDomainConstraints(ctest->resulttype);
state = (ExprState*)cstate;
} break;
case T_CurrentOfExpr:
state = (ExprState*)makeNode(ExprState);
state->evalfunc = ExecEvalCurrentOfExpr;
break;
case T_TargetEntry: {
TargetEntry* tle = (TargetEntry*)node;
GenericExprState* gstate = makeNode(GenericExprState);
gstate->xprstate.evalfunc = NULL; /* not used */
gstate->arg = ExecInitExpr(tle->expr, parent);
state = (ExprState*)gstate;
} break;
case T_List: {
List* outlist = NIL;
ListCell* l = NULL;
foreach (l, (List*)node) {
outlist = lappend(outlist, ExecInitExpr((Expr*)lfirst(l), parent));
}
/* Don't fall through to the "common" code below */
gstrace_exit(GS_TRC_ID_ExecInitExpr);
return (ExprState*)outlist;
}
case T_Rownum: {
RownumState* rnstate = (RownumState*)makeNode(RownumState);
rnstate->ps = parent;
state = (ExprState*)rnstate;
state->evalfunc = (ExprStateEvalFunc)ExecEvalRownum;
} break;
case T_GradientDescentExpr: {
GradientDescentExprState* ml_state = (GradientDescentExprState*)makeNode(GradientDescentExprState);
ml_state->ps = parent;
ml_state->xpr = (GradientDescentExpr*)node;
state = (ExprState*)ml_state;
if (IsA(parent, GradientDescentState)) {
state->evalfunc = (ExprStateEvalFunc)ExecEvalGradientDescent;
} else {
ereport(ERROR,
(errmodule(MOD_DB4AI),
errcode(ERRCODE_INVALID_OPERATION),
errmsg("unrecognized state %d for GradientDescentExpr", parent->type)));
}
} break;
default:
ereport(ERROR,
(errcode(ERRCODE_UNRECOGNIZED_NODE_TYPE),
errmsg("unrecognized node type: %d when initializing expression.", (int)nodeTag(node))));
state = NULL; /* keep compiler quiet */
break;
}
/* Common code for all state-node types */
state->expr = node;
if (nodeTag(node) != T_TargetEntry)
state->resultType = exprType((Node*)node);
gstrace_exit(GS_TRC_ID_ExecInitExpr);
return state;
}
/*
* ExecPrepareExpr --- initialize for expression execution outside a normal
* Plan tree context.
*
* This differs from ExecInitExpr in that we don't assume the caller is
* already running in the EState's per-query context. Also, we run the
* passed expression tree through expression_planner() to prepare it for
* execution. (In ordinary Plan trees the regular planning process will have
* made the appropriate transformations on expressions, but for standalone
* expressions this won't have happened.)
*/
ExprState* ExecPrepareExpr(Expr* node, EState* estate)
{
ExprState* result = NULL;
MemoryContext oldcontext;
oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
node = expression_planner(node);
result = ExecInitExpr(node, NULL);
MemoryContextSwitchTo(oldcontext);
return result;
}
/* ----------------------------------------------------------------
* ExecQual / ExecTargetList / ExecProject
* ----------------------------------------------------------------
*/
/* ----------------------------------------------------------------
* ExecQual
*
* Evaluates a conjunctive boolean expression (qual list) and
* returns true iff none of the subexpressions are false.
* (We also return true if the list is empty.)
*
* If some of the subexpressions yield NULL but none yield FALSE,
* then the result of the conjunction is NULL (ie, unknown)
* according to three-valued boolean logic. In this case,
* we return the value specified by the "resultForNull" parameter.
*
* Callers evaluating WHERE clauses should pass resultForNull=FALSE,
* since SQL specifies that tuples with null WHERE results do not
* get selected. On the other hand, callers evaluating constraint
* conditions should pass resultForNull=TRUE, since SQL also specifies
* that NULL constraint conditions are not failures.
*
* NOTE: it would not be correct to use this routine to evaluate an
* AND subclause of a boolean expression; for that purpose, a NULL
* result must be returned as NULL so that it can be properly treated
* in the next higher operator (cf. ExecEvalAnd and ExecEvalOr).
* This routine is only used in contexts where a complete expression
* is being evaluated and we know that NULL can be treated the same
* as one boolean result or the other.
*
* ----------------------------------------------------------------
*/
bool ExecQual(List* qual, ExprContext* econtext, bool resultForNull)
{
bool result = false;
MemoryContext oldContext;
ListCell* l = NULL;
/*
* debugging stuff
*/
EV_printf("ExecQual: qual is ");
EV_nodeDisplay(qual);
EV_printf("\n");
/*
* Run in short-lived per-tuple context while computing expressions.
*/
oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
/*
* Evaluate the qual conditions one at a time. If we find a FALSE result,
* we can stop evaluating and return FALSE --- the AND result must be
* FALSE. Also, if we find a NULL result when resultForNull is FALSE, we
* can stop and return FALSE --- the AND result must be FALSE or NULL in
* that case, and the caller doesn't care which.
*
* If we get to the end of the list, we can return TRUE. This will happen
* when the AND result is indeed TRUE, or when the AND result is NULL (one
* or more NULL subresult, with all the rest TRUE) and the caller has
* specified resultForNull = TRUE.
*/
result = true;
foreach (l, qual) {
ExprState* clause = (ExprState*)lfirst(l);
Datum expr_value;
bool isNull = false;
expr_value = ExecEvalExpr(clause, econtext, &isNull, NULL);
if (isNull) {
if (resultForNull == false) {
result = false; /* treat NULL as FALSE */
break;
}
} else {
if (!DatumGetBool(expr_value)) {
result = false; /* definitely FALSE */
break;
}
}
}
MemoryContextSwitchTo(oldContext);
return result;
}
/*
* Number of items in a tlist (including any resjunk items!)
*/
int ExecTargetListLength(List* targetlist)
{
/* This used to be more complex, but fjoins are dead */
return list_length(targetlist);
}
/*
* Number of items in a tlist, not including any resjunk items
*/
int ExecCleanTargetListLength(List* targetlist)
{
int len = 0;
ListCell* tl = NULL;
foreach (tl, targetlist) {
TargetEntry* curTle = (TargetEntry*)lfirst(tl);
Assert(IsA(curTle, TargetEntry));
if (!curTle->resjunk)
len++;
}
return len;
}
/*
* ExecTargetList
* Evaluates a targetlist with respect to the given
* expression context. Returns TRUE if we were able to create
* a result, FALSE if we have exhausted a set-valued expression.
*
* Results are stored into the passed values and isnull arrays.
* The caller must provide an itemIsDone array that persists across calls.
*
* As with ExecEvalExpr, the caller should pass isDone = NULL if not
* prepared to deal with sets of result tuples. Otherwise, a return
* of *isDone = ExprMultipleResult signifies a set element, and a return
* of *isDone = ExprEndResult signifies end of the set of tuple.
* We assume that *isDone has been initialized to ExprSingleResult by caller.
*/
static bool ExecTargetList(List* targetlist, ExprContext* econtext, Datum* values, bool* isnull,
ExprDoneCond* itemIsDone, ExprDoneCond* isDone)
{
MemoryContext oldContext;
ListCell* tl = NULL;
bool haveDoneSets = false;
/*
* Run in short-lived per-tuple context while computing expressions.
*/
oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
/*
* evaluate all the expressions in the target list
*/
haveDoneSets = false; /* any exhausted set exprs in tlist? */
foreach (tl, targetlist) {
GenericExprState* gstate = (GenericExprState*)lfirst(tl);
TargetEntry* tle = (TargetEntry*)gstate->xprstate.expr;
AttrNumber resind = tle->resno - 1;
ELOG_FIELD_NAME_START(tle->resname);
values[resind] = ExecEvalExpr(gstate->arg, econtext, &isnull[resind], &itemIsDone[resind]);
ELOG_FIELD_NAME_END;
if (itemIsDone[resind] != ExprSingleResult) {
/* We have a set-valued expression in the tlist */
if (isDone == NULL)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("set-valued function called in context when calculate targetlist that cannot accept a "
"set")));
if (itemIsDone[resind] == ExprMultipleResult) {
/* we have undone sets in the tlist, set flag */
*isDone = ExprMultipleResult;
} else {
/* we have done sets in the tlist, set flag for that */
haveDoneSets = true;
}
}
}
if (haveDoneSets) {
/*
* note: can't get here unless we verified isDone != NULL
*/
if (*isDone == ExprSingleResult) {
/*
* all sets are done, so report that tlist expansion is complete.
*/
*isDone = ExprEndResult;
MemoryContextSwitchTo(oldContext);
return false;
} else {
/*
* We have some done and some undone sets. Restart the done ones
* so that we can deliver a tuple (if possible).
*/
foreach (tl, targetlist) {
GenericExprState* gstate = (GenericExprState*)lfirst(tl);
TargetEntry* tle = (TargetEntry*)gstate->xprstate.expr;
AttrNumber resind = tle->resno - 1;
if (itemIsDone[resind] == ExprEndResult) {
values[resind] = ExecEvalExpr(gstate->arg, econtext, &isnull[resind], &itemIsDone[resind]);
if (itemIsDone[resind] == ExprEndResult) {
/*
* Oh dear, this item is returning an empty set. Guess
* we can't make a tuple after all.
*/
*isDone = ExprEndResult;
break;
}
}
}
/*
* If we cannot make a tuple because some sets are empty, we still
* have to cycle the nonempty sets to completion, else resources
* will not be released from subplans etc.
*
* XXX is that still necessary?
*/
if (*isDone == ExprEndResult) {
foreach (tl, targetlist) {
GenericExprState* gstate = (GenericExprState*)lfirst(tl);
TargetEntry* tle = (TargetEntry*)gstate->xprstate.expr;
AttrNumber resind = tle->resno - 1;
while (itemIsDone[resind] == ExprMultipleResult) {
values[resind] = ExecEvalExpr(gstate->arg, econtext, &isnull[resind], &itemIsDone[resind]);
}
}
MemoryContextSwitchTo(oldContext);
return false;
}
}
}
/* Report success */
MemoryContextSwitchTo(oldContext);
return true;
}
/*
* ExecProject
*
* projects a tuple based on projection info and stores
* it in the previously specified tuple table slot.
*
* Note: the result is always a virtual tuple; therefore it
* may reference the contents of the exprContext's scan tuples
* and/or temporary results constructed in the exprContext.
* If the caller wishes the result to be valid longer than that
* data will be valid, he must call ExecMaterializeSlot on the
* result slot.
*/
TupleTableSlot* ExecProject(ProjectionInfo* projInfo, ExprDoneCond* isDone)
{
/*
* sanity checks
*/
Assert(projInfo != NULL);
/*
* get the projection info we want
*/
TupleTableSlot *slot = projInfo->pi_slot;
ExprContext *econtext = projInfo->pi_exprContext;
/* Assume single result row until proven otherwise */
if (isDone != NULL)
*isDone = ExprSingleResult;
/*
* Clear any former contents of the result slot. This makes it safe for
* us to use the slot's Datum/isnull arrays as workspace. (Also, we can
* return the slot as-is if we decide no rows can be projected.)
*/
(void)ExecClearTuple(slot);
/*
* Force extraction of all input values that we'll need. The
* Var-extraction loops below depend on this, and we are also prefetching
* all attributes that will be referenced in the generic expressions.
*/
if (projInfo->pi_lastInnerVar > 0) {
tableam_tslot_getsomeattrs(econtext->ecxt_innertuple, projInfo->pi_lastInnerVar);
}
if (projInfo->pi_lastOuterVar > 0) {
tableam_tslot_getsomeattrs(econtext->ecxt_outertuple, projInfo->pi_lastOuterVar);
}
if (projInfo->pi_lastScanVar > 0) {
tableam_tslot_getsomeattrs(econtext->ecxt_scantuple, projInfo->pi_lastScanVar);
}
/*
* Assign simple Vars to result by direct extraction of fields from source
* slots ... a mite ugly, but fast ...
*/
int numSimpleVars = projInfo->pi_numSimpleVars;
if (numSimpleVars > 0) {
Datum* values = slot->tts_values;
bool* isnull = slot->tts_isnull;
int* varSlotOffsets = projInfo->pi_varSlotOffsets;
int* varNumbers = projInfo->pi_varNumbers;
int i;
if (projInfo->pi_directMap) {
/* especially simple case where vars go to output in order */
for (i = 0; i < numSimpleVars; i++) {
char* slotptr = ((char*)econtext) + varSlotOffsets[i];
TupleTableSlot* varSlot = *((TupleTableSlot**)slotptr);
int varNumber = varNumbers[i] - 1;
Assert (varNumber < varSlot->tts_tupleDescriptor->natts);
Assert (i < slot->tts_tupleDescriptor->natts);
values[i] = varSlot->tts_values[varNumber];
isnull[i] = varSlot->tts_isnull[varNumber];
}
} else {
/* we have to pay attention to varOutputCols[] */
int* varOutputCols = projInfo->pi_varOutputCols;
for (i = 0; i < numSimpleVars; i++) {
char* slotptr = ((char*)econtext) + varSlotOffsets[i];
TupleTableSlot* varSlot = *((TupleTableSlot**)slotptr);
int varNumber = varNumbers[i] - 1;
int varOutputCol = varOutputCols[i] - 1;
Assert (varNumber < varSlot->tts_tupleDescriptor->natts);
Assert (varOutputCol < slot->tts_tupleDescriptor->natts);
values[varOutputCol] = varSlot->tts_values[varNumber];
isnull[varOutputCol] = varSlot->tts_isnull[varNumber];
}
}
}
/*
* If there are any generic expressions, evaluate them. It's possible
* that there are set-returning functions in such expressions; if so and
* we have reached the end of the set, we return the result slot, which we
* already marked empty.
*/
if (projInfo->pi_targetlist) {
if (!ExecTargetList(
projInfo->pi_targetlist, econtext, slot->tts_values, slot->tts_isnull, projInfo->pi_itemIsDone, isDone))
return slot; /* no more result rows, return empty slot */
}
/*
* Successfully formed a result row. Mark the result slot as containing a
* valid virtual tuple.
*/
return ExecStoreVirtualTuple(slot);
}
static Datum ExecEvalGroupingIdExpr(
GroupingIdExprState* gstate, ExprContext* econtext, bool* isNull, ExprDoneCond* isDone)
{
int groupingId = 0;
if (isDone != NULL) {
*isDone = ExprSingleResult;
}
*isNull = false;
for (int i = 0; i < gstate->aggstate->current_phase; i++) {
groupingId += gstate->aggstate->phases[i].numsets;
}
groupingId += gstate->aggstate->projected_set + 1;
return (Datum)groupingId;
}
/*
* @Description: copy cursor data from estate->datums to target_cursor
* @in datums - estate->datums
* @in dno - varno in datums
* @in target_cursor - target cursor data
* @return -void
*/
void ExecCopyDataFromDatum(PLpgSQL_datum** datums, int dno, Cursor_Data* target_cursor)
{
PLpgSQL_var *cursor_var = (PLpgSQL_var *)(datums[dno]);
/* only copy cursor option to refcursor */
if (cursor_var->datatype->typoid != REFCURSOROID) {
return;
}
cursor_var = (PLpgSQL_var*)(datums[dno + CURSOR_ISOPEN]);
target_cursor->is_open = DatumGetBool(cursor_var->value);
cursor_var = (PLpgSQL_var*)(datums[dno + CURSOR_FOUND]);
target_cursor->found = DatumGetBool(cursor_var->value);
target_cursor->null_fetch = cursor_var->isnull;
cursor_var = (PLpgSQL_var*)(datums[dno + CURSOR_NOTFOUND]);
target_cursor->not_found = DatumGetBool(cursor_var->value);
cursor_var = (PLpgSQL_var*)(datums[dno + CURSOR_ROWCOUNT]);
target_cursor->row_count = DatumGetInt32(cursor_var->value);
target_cursor->null_open = cursor_var->isnull;
target_cursor->cur_dno = dno;
}
/*
* @Description: copy cursor data to estate->datums
* @in datums - estate->datums
* @in dno - varno in datums
* @in target_cursor - source cursor data
* @return -void
*/
void ExecCopyDataToDatum(PLpgSQL_datum** datums, int dno, Cursor_Data* source_cursor)
{
PLpgSQL_var *cursor_var = (PLpgSQL_var *)(datums[dno]);
/* only copy cursor option to refcursor */
if (cursor_var->datatype->typoid != REFCURSOROID) {
return;
}
cursor_var = (PLpgSQL_var*)(datums[dno + CURSOR_ISOPEN]);
cursor_var->value = BoolGetDatum(source_cursor->is_open);
cursor_var = (PLpgSQL_var*)(datums[dno + CURSOR_FOUND]);
cursor_var->value = BoolGetDatum(source_cursor->found);
cursor_var->isnull = source_cursor->null_fetch;
cursor_var = (PLpgSQL_var*)(datums[dno + CURSOR_NOTFOUND]);
cursor_var->value = BoolGetDatum(source_cursor->not_found);
cursor_var->isnull = source_cursor->null_fetch;
cursor_var = (PLpgSQL_var*)(datums[dno + CURSOR_ROWCOUNT]);
cursor_var->value = Int32GetDatum(source_cursor->row_count);
cursor_var->isnull = source_cursor->null_open;
}
| 38.738667 | 131 | 0.593172 | [
"object",
"vector"
] |
40bd26a193ab6a667fafca88bf1506aa59388721 | 5,759 | cpp | C++ | superneurons/src/layer/dropout_layer.cpp | Phaeton-lang/baselines | 472c248047fbb55b5fa0e620758047b7f0a1d041 | [
"MIT"
] | null | null | null | superneurons/src/layer/dropout_layer.cpp | Phaeton-lang/baselines | 472c248047fbb55b5fa0e620758047b7f0a1d041 | [
"MIT"
] | null | null | null | superneurons/src/layer/dropout_layer.cpp | Phaeton-lang/baselines | 472c248047fbb55b5fa0e620758047b7f0a1d041 | [
"MIT"
] | null | null | null | #include <layer/dropout_layer.h>
namespace SuperNeurons {
template <class value_type>
void dropout_layer_t<value_type>::forward_setup(registry_t<value_type>* reg, cudnnHandle_t* cudnn_h) {
//hook the output of previous layer
int input_l = this->get_input_layer_id();
int curt_l = this->get_id();
tensor_t<value_type>* input = reg->get_reg_output(input_l, curt_l);
assert( input != NULL );
printf("======>setup the forward drop out layer:%d\n", this->get_id());
checkCUDNN( cudnnDropoutGetStatesSize(*cudnn_h, &state_size_bytes) );
size_t state_size = state_size_bytes / sizeof(value_type);
dropout_state = new tensor_t<value_type>( state_size, 1, 1, 1, reg->get_vector(), PARAM, this->get_id());
unsigned long seed = (unsigned long) rand();
checkCUDNN( cudnnSetDropoutDescriptor(dropout_desc,
*cudnn_h,
dropout_rate,
dropout_state->get_gpu_ptr(),
state_size_bytes,
seed) );
checkCUDNN( cudnnDropoutGetReserveSpaceSize(input->get_tensor_desc(),
&buff_size_bytes ) );
size_t buff_size = buff_size_bytes / sizeof(value_type);
dropout_buff = new tensor_t<value_type>(buff_size, 1, 1, 1, reg->get_vector(), PARAM, this->get_id());
tensor_t<value_type>* f_out = new tensor_t<value_type>( input->get_N(), input->get_C(), input->get_H(), input->get_W(), reg->get_vector(), DATA, this->get_id());
//setup the output tensor
this->set_f_out( f_out, reg );
//forward hookup check
assert( this->get_f_out() != NULL );
assert( dropout_state != NULL );
assert( dropout_buff != NULL );
// register the forward dependency
reg->register_forward_dependency(this->get_id(), input);
reg->register_forward_dependency(this->get_id(), dropout_state);
reg->register_forward_dependency(this->get_id(), dropout_buff);
reg->register_forward_dependency(this->get_id(), f_out);
}
template <class value_type>
void dropout_layer_t<value_type>::backward_setup(registry_t<value_type>* reg, cudnnHandle_t* cudnn_h) {
//setup the backward data
printf("======>setup the backward dropout layer:%d\n", this->get_id());
int curt_l_id = this->get_id();
int prev_l_id = this->get_input_layer_id();
int output_l_id = this->get_output_layer_id();
tensor_t<value_type>* f_in = reg->get_reg_output(prev_l_id, curt_l_id);
assert( f_in != NULL );
tensor_t<value_type>* b_data = new tensor_t<value_type>(f_in->get_N(), f_in->get_C(), f_in->get_H(), f_in->get_W(), reg->get_vector(), DATA, this->get_id());
this->set_b_data( b_data, reg );
assert( this->get_b_data() != NULL );
// register the backward dependency
tensor_t<value_type>* dEdD = reg->get_reg_b_data(output_l_id, curt_l_id);
reg->register_backward_dependency(this->get_id(), b_data);
reg->register_backward_dependency(this->get_id(), dropout_buff);
reg->register_backward_dependency(this->get_id(), dEdD);
}
template <class value_type>
std::vector<value_type> dropout_layer_t<value_type>::forward(network_stage stage, cublasHandle_t* cublas_h, cudnnHandle_t* cudnn_h, registry_t<value_type>* reg) {
int input_l = this->get_input_layer_id();
int curt_l = this->get_id();
tensor_t<value_type>* input = reg->get_reg_output(input_l, curt_l);
tensor_t<value_type>* output = this->get_f_out();
#ifdef DEBUG
printf("@ dropout layer input tensor from %d to %d\n", input_l, curt_l);
#endif
assert(dropout_state->get_gpu_ptr() != NULL);
if (stage == NET_INFER) {
output->copy(input);
} else {
checkCUDNN( cudnnDropoutForward(*cudnn_h,
dropout_desc,
input->get_tensor_desc(),
input->get_gpu_ptr(),
output->get_tensor_desc(),
output->get_gpu_ptr(),
dropout_buff->get_gpu_ptr(),
buff_size_bytes)
);
}
#ifdef DEBUG
this->get_f_out()->printTensor("output of dropout layer");
#endif
return std::vector<value_type>();
}
template <class value_type>
void dropout_layer_t<value_type>::backward(network_stage stage, cublasHandle_t* cublas_h, cudnnHandle_t* cudnn_h, registry_t<value_type>* reg) {
int curt_l_id = this->get_id();
int output_l_id = this->get_output_layer_id();
int input_l_id = this->get_input_layer_id();
// tensor_t<value_type>* f_out = this->get_f_out();
tensor_t<value_type>* b_data = this->get_b_data();
// tensor_t<value_type>* f_in = reg->get_reg_output(input_l_id, curt_l_id);
tensor_t<value_type>* dEdD = reg->get_reg_b_data(output_l_id, curt_l_id);
checkCUDNN( cudnnDropoutBackward(*cudnn_h,
dropout_desc,
dEdD->get_tensor_desc(),
dEdD->get_gpu_ptr(),
b_data->get_tensor_desc(),
b_data->get_gpu_ptr(),
dropout_buff->get_gpu_ptr(),
buff_size_bytes)
);
#ifdef DEBUG
printf( "@%d prev %d next %d\n", curt_l_id, input_l_id, output_l_id );
this->get_b_data()->printTensor("backward dropout results");
#endif
}
INSTANTIATE_CLASS(dropout_layer_t);
} //SuperNeurons namespace
| 43.961832 | 166 | 0.604272 | [
"vector"
] |
40bd42a8738ccc02803c213959ac4f2d1f0fc5db | 4,958 | cpp | C++ | higra/interop/py_scipy.cpp | deisemaia/Higra | 82cb78b606a383f3961faa882457a9a987f802e0 | [
"CECILL-B"
] | null | null | null | higra/interop/py_scipy.cpp | deisemaia/Higra | 82cb78b606a383f3961faa882457a9a987f802e0 | [
"CECILL-B"
] | null | null | null | higra/interop/py_scipy.cpp | deisemaia/Higra | 82cb78b606a383f3961faa882457a9a987f802e0 | [
"CECILL-B"
] | null | null | null | /***************************************************************************
* Copyright ESIEE Paris (2018) *
* *
* Contributor(s) : Benjamin Perret *
* *
* Distributed under the terms of the CECILL-B License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include "py_scipy.hpp"
#include "../py_common.hpp"
#include "higra/image/graph_image.hpp"
#include "xtensor-python/pyarray.hpp"
#include "xtensor-python/pytensor.hpp"
#include "xtensor/xview.hpp"
template<typename T>
using pyarray = xt::pyarray<T>;
namespace py = pybind11;
using namespace hg;
template<typename tree_t, typename T1, typename T2, typename value_t=double>
auto binary_hierarchy_to_scipy_linkage_matrix(const tree_t &tree,
const xt::xexpression<T1> &xaltitudes,
const xt::xexpression<T2> &xarea) {
auto &altitudes = xaltitudes.derived_cast();
auto &area = xarea.derived_cast();
hg_assert_node_weights(tree, altitudes);
hg_assert_node_weights(tree, area);
hg::index_t n_leaves = num_leaves(tree);
hg::array_2d<value_t> M = xt::empty<value_t>({(size_t) n_leaves - 1, (size_t) 4});
for (auto i: hg::leaves_to_root_iterator(tree, hg::leaves_it::exclude)) {
hg::index_t n = i - n_leaves;
hg_assert(hg::num_children(i, tree) == 2, "Input hierarchy must be a binary hierarchy.");
M(n, 0) = (value_t)hg::child(0, i, tree);
M(n, 1) = (value_t)hg::child(1, i, tree);
M(n, 2) = (value_t)altitudes(i);
M(n, 3) = (value_t)area(i);
}
return M;
};
template<typename T, typename value_t=typename T::value_type>
auto scipy_linkage_matrix_to_binary_hierarchy(const xt::xexpression<T> &xlinkage_matrix) {
auto &linkage_matrix = xlinkage_matrix.derived_cast();
hg_assert(linkage_matrix.dimension() == 2, "Linkage matrix must be a 2d array.");
hg_assert(linkage_matrix.shape()[1] == 4, "Linkage matrix second dimension must be of size 4.");
index_t n_leaves = linkage_matrix.shape()[0] + 1;
index_t n_nodes = n_leaves * 2 - 1;
array_1d<index_t> parents = xt::empty<index_t>({n_nodes});
array_1d<value_t> altitudes = xt::empty<index_t>({n_nodes});
array_1d<index_t> area = xt::empty<index_t>({n_nodes});
xt::view(altitudes, xt::range(0, n_leaves)) = 0;
xt::view(area, xt::range(0, n_leaves)) = 1;
parents(n_nodes - 1) = n_nodes - 1;
for (index_t i = 0; i < n_leaves - 1; i++) {
index_t n = i + n_leaves;
parents(static_cast<index_t>(linkage_matrix(i, 0))) = n;
parents(static_cast<index_t>(linkage_matrix(i, 1))) = n;
altitudes(n) = linkage_matrix(i, 2);
area(n) = static_cast<index_t>(linkage_matrix(i, 3));
}
return std::make_tuple(hg::tree(parents), std::move(altitudes), std::move(area));
};
struct def_scipy_linkage_matrix_to_binary_hierarchy {
template<typename value_t>
static
void def(pybind11::module &m, const char *doc) {
m.def("_scipy_linkage_matrix_to_binary_hierarchy", [](
const pyarray<value_t> &linkage_matrix) {
auto res = scipy_linkage_matrix_to_binary_hierarchy(linkage_matrix);
return py::make_tuple(std::move(std::get<0>(res)), std::move(std::get<1>(res)),
std::move(std::get<2>(res)));
},
doc,
py::arg("linkage_matrix"));
}
};
template<typename tree_t>
struct def_binary_hierarchy_to_scipy_linkage_matrix {
template<typename value_t>
static
void def(pybind11::module &m, const char *doc) {
m.def("_binary_hierarchy_to_scipy_linkage_matrix", [](
const tree_t &tree,
const pyarray<value_t> &altitudes,
const pyarray<hg::index_t> &area) {
return binary_hierarchy_to_scipy_linkage_matrix(tree, altitudes, area);
},
doc,
py::arg("tree"),
py::arg("altitudes"),
py::arg("area"));
}
};
void py_init_scipy(pybind11::module &m) {
add_type_overloads<def_binary_hierarchy_to_scipy_linkage_matrix<hg::tree>, HG_TEMPLATE_FLOAT_TYPES>
(m,
"Converts an Higra binary hierarchy to a SciPy linkage matrix."
);
add_type_overloads<def_scipy_linkage_matrix_to_binary_hierarchy, double>
(m,
"Converts a SciPy linkage matrix to an Higra binary hierarchy."
);
}
| 42.016949 | 103 | 0.564139 | [
"shape"
] |
40beb316bafd056654a5d496163807f6c4c9876a | 7,937 | cc | C++ | runtime/browser/ui/native_app_window_tizen.cc | junmin-zhu/crosswalk | 6c2ab70dcdbdda99da85fa6c8f79b5371aafbb1d | [
"BSD-3-Clause"
] | 3 | 2018-05-13T07:02:56.000Z | 2019-10-29T19:34:10.000Z | runtime/browser/ui/native_app_window_tizen.cc | junmin-zhu/crosswalk | 6c2ab70dcdbdda99da85fa6c8f79b5371aafbb1d | [
"BSD-3-Clause"
] | null | null | null | runtime/browser/ui/native_app_window_tizen.cc | junmin-zhu/crosswalk | 6c2ab70dcdbdda99da85fa6c8f79b5371aafbb1d | [
"BSD-3-Clause"
] | 4 | 2016-01-03T10:14:09.000Z | 2019-11-22T02:33:03.000Z | // Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/runtime/browser/ui/native_app_window_tizen.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "ui/aura/window.h"
#include "ui/gfx/transform.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/screen.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "xwalk/runtime/browser/ui/splash_screen_tizen.h"
#include "xwalk/runtime/browser/ui/top_view_layout_views.h"
#include "xwalk/runtime/browser/xwalk_browser_main_parts_tizen.h"
namespace {
static gfx::Display::Rotation ToDisplayRotation(gfx::Display display,
blink::WebScreenOrientationType orientation) {
gfx::Display::Rotation rot = gfx::Display::ROTATE_0;
switch (orientation) {
case blink::WebScreenOrientationUndefined:
case blink::WebScreenOrientationPortraitPrimary:
rot = gfx::Display::ROTATE_0;
break;
case blink::WebScreenOrientationLandscapeSecondary:
rot = gfx::Display::ROTATE_90;
break;
case blink::WebScreenOrientationPortraitSecondary:
rot = gfx::Display::ROTATE_180;
break;
case blink::WebScreenOrientationLandscapePrimary:
rot = gfx::Display::ROTATE_270;
break;
default:
NOTREACHED();
}
if (display.bounds().width() > display.bounds().height()) {
// Landscape devices have landscape-primary as default.
rot = static_cast<gfx::Display::Rotation>((rot - 1) % 4);
}
return rot;
}
static void SetWindowRotation(aura::Window* window, gfx::Display display) {
// This methods assumes that window is fullscreen.
#if defined(OS_TIZEN_MOBILE)
// Assumes portrait display; shows overlay indicator in landscape only.
bool useOverlay = display.rotation() == gfx::Display::ROTATE_90 ||
display.rotation() == gfx::Display::ROTATE_180);
top_view_layout()->SetUseOverlay(enableOverlay);
indicator_widget_->SetDisplay(display);
#endif
// As everything is calculated from the fixed position we do
// not update the display bounds after rotation change.
gfx::Transform rotate;
float one_pixel = 1.0f / display.device_scale_factor();
switch (display.rotation()) {
case gfx::Display::ROTATE_0:
break;
case gfx::Display::ROTATE_90:
rotate.Translate(display.bounds().width() - one_pixel, 0);
rotate.Rotate(90);
break;
case gfx::Display::ROTATE_270:
rotate.Translate(0, display.bounds().height() - one_pixel);
rotate.Rotate(270);
break;
case gfx::Display::ROTATE_180:
rotate.Translate(display.bounds().width() - one_pixel,
display.bounds().height() - one_pixel);
rotate.Rotate(180);
break;
}
window->SetTransform(rotate);
}
} // namespace.
namespace xwalk {
NativeAppWindowTizen::NativeAppWindowTizen(
const NativeAppWindow::CreateParams& create_params)
: NativeAppWindowViews(create_params),
#if defined(OS_TIZEN_MOBILE)
indicator_widget_(new TizenSystemIndicatorWidget()),
indicator_container_(new WidgetContainerView(indicator_widget_)),
#endif
orientation_lock_(blink::WebScreenOrientationLockAny) {}
void NativeAppWindowTizen::Initialize() {
NativeAppWindowViews::Initialize();
const base::FilePath& splash_screen_path = create_params().splash_screen_path;
if (!splash_screen_path.empty()) {
splash_screen_.reset(new SplashScreenTizen(
GetWidget(), splash_screen_path, create_params().web_contents));
splash_screen_->Start();
}
// Get display info such as device_scale_factor, and current
// rotation (orientation).
// NOTE: This is a local copy of the info.
display_ = gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();
aura::Window* root_window = GetNativeWindow()->GetRootWindow();
DCHECK(root_window);
root_window->AddObserver(this);
if (SensorProvider* sensor = SensorProvider::GetInstance()) {
sensor->AddObserver(this);
OnScreenOrientationChanged(sensor->GetScreenOrientation());
}
}
NativeAppWindowTizen::~NativeAppWindowTizen() {
if (SensorProvider::GetInstance())
SensorProvider::GetInstance()->RemoveObserver(this);
}
void NativeAppWindowTizen::LockOrientation(
blink::WebScreenOrientationLockType lock) {
orientation_lock_ = lock;
if (SensorProvider* sensor = SensorProvider::GetInstance())
OnScreenOrientationChanged(sensor->GetScreenOrientation());
}
void NativeAppWindowTizen::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
if (details.is_add && details.child == this) {
NativeAppWindowViews::ViewHierarchyChanged(details);
#if defined(OS_TIZEN_MOBILE)
indicator_widget_->Initialize(GetNativeWindow());
top_view_layout()->set_top_view(indicator_container_.get());
AddChildView(indicator_container_.get());
#endif
}
}
void NativeAppWindowTizen::OnWindowBoundsChanged(
aura::Window* window,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds) {
aura::Window* root_window = GetNativeWindow()->GetRootWindow();
DCHECK_EQ(root_window, window);
// Change the bounds of child windows to make touch work correctly.
GetNativeWindow()->parent()->SetBounds(new_bounds);
GetNativeWindow()->SetBounds(new_bounds);
GetWidget()->GetRootView()->SetSize(new_bounds.size());
}
void NativeAppWindowTizen::OnWindowDestroying(aura::Window* window) {
// Must be removed here and not in the destructor, as the aura::Window is
// already destroyed when our destructor runs.
window->RemoveObserver(this);
}
void NativeAppWindowTizen::OnWindowVisibilityChanging(
aura::Window* window, bool visible) {
if (!visible)
return;
SetDisplayRotation(display_);
}
blink::WebScreenOrientationType
NativeAppWindowTizen::FindNearestAllowedOrientation(
blink::WebScreenOrientationType orientation) const {
switch (orientation_lock_) {
case blink::WebScreenOrientationLockDefault:
case blink::WebScreenOrientationLockAny:
return orientation;
case blink::WebScreenOrientationLockLandscape: {
switch (orientation) {
case blink::WebScreenOrientationLandscapePrimary:
case blink::WebScreenOrientationLandscapeSecondary:
return orientation;
default:
return blink::WebScreenOrientationLandscapePrimary;
}
break;
}
case blink::WebScreenOrientationLockPortrait: {
switch (orientation) {
case blink::WebScreenOrientationPortraitPrimary:
case blink::WebScreenOrientationPortraitSecondary:
return orientation;
default:
return blink::WebScreenOrientationPortraitPrimary;
}
break;
}
case blink::WebScreenOrientationLockPortraitPrimary:
return blink::WebScreenOrientationPortraitPrimary;
case blink::WebScreenOrientationLockPortraitSecondary:
return blink::WebScreenOrientationPortraitSecondary;
case blink::WebScreenOrientationLockLandscapePrimary:
return blink::WebScreenOrientationLandscapePrimary;
case blink::WebScreenOrientationLockLandscapeSecondary:
return blink::WebScreenOrientationLandscapeSecondary;
default:
NOTREACHED();
}
return orientation;
}
void NativeAppWindowTizen::OnScreenOrientationChanged(
blink::WebScreenOrientationType orientation) {
// We always store the current sensor position, even if we do not
// apply it in case the window is invisible.
gfx::Display::Rotation rot = ToDisplayRotation(display_,
FindNearestAllowedOrientation(orientation));
if (display_.rotation() == rot)
return;
display_.set_rotation(rot);
SetDisplayRotation(display_);
}
void NativeAppWindowTizen::SetDisplayRotation(gfx::Display display) {
aura::Window* window = GetNativeWindow()->GetRootWindow();
if (!window->IsVisible())
return;
SetWindowRotation(window, display);
}
} // namespace xwalk
| 33.070833 | 80 | 0.733779 | [
"transform"
] |
40c56d03cae632ffade11f3e1878b7e333155354 | 1,559 | cpp | C++ | Two Pointers/next-permutation-31.cpp | devangi2000/Data-Structures-Algorithms-Handbook | ce0f00de89af5da7f986e65089402dc6908a09b5 | [
"MIT"
] | 38 | 2021-10-14T09:36:53.000Z | 2022-01-27T02:36:19.000Z | Two Pointers/next-permutation-31.cpp | devangi2000/Data-Structures-Algorithms-Handbook | ce0f00de89af5da7f986e65089402dc6908a09b5 | [
"MIT"
] | null | null | null | Two Pointers/next-permutation-31.cpp | devangi2000/Data-Structures-Algorithms-Handbook | ce0f00de89af5da7f986e65089402dc6908a09b5 | [
"MIT"
] | 4 | 2021-12-06T15:47:12.000Z | 2022-02-04T04:25:00.000Z | // Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
// If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).
// The replacement must be in place and use only constant extra memory.
// Example 1:
// Input: nums = [1,2,3]
// Output: [1,3,2]
// Example 2:
// Input: nums = [3,2,1]
// Output: [1,2,3]
// Example 3:
// Input: nums = [1,1,5]
// Output: [1,5,1]
// Example 4:
// Input: nums = [1]
// Output: [1]
// DO NOT DO THIS in an interview * Facepalm *
/*
class Solution {
public:
void nextPermutation(vector<int>& nums) {
next_permutation(nums.begin(), nums.end());
}
};
*/
// DO THIS:
class Solution {
public:
void nextPermutation(vector<int>& nums) {
if(nums.size() == 0 || nums.size() <= 1) return;
int n = nums.size(), k, l, idx=-1;
// finding the break point of the array
for(int k = n-1; k>0; k--){
if(nums[k] > nums[k-1]) {
idx= k;
break;}
}
if(idx<0){
reverse(nums.begin(), nums.end());
}
else{
int prev = idx;
for(int i=idx+1; i<n; i++){
if(nums[i] > nums[idx-1] and nums[i]<=nums[prev]){
prev = i;
}
}
swap(nums[idx-1], nums[prev]);
reverse(nums.begin()+idx, nums.end());
}
}
};
| 25.145161 | 128 | 0.503528 | [
"vector"
] |
40c6b8a37581a46da6887b92e1f1f1832b017bb1 | 7,652 | cpp | C++ | deps/src/gropt/src/WeightedLowRank.cpp | JuliaPackageMirrors/ElasticFDA.jl | fe9852231d04672c0792f2ca7adf754da0874f0a | [
"MIT"
] | null | null | null | deps/src/gropt/src/WeightedLowRank.cpp | JuliaPackageMirrors/ElasticFDA.jl | fe9852231d04672c0792f2ca7adf754da0874f0a | [
"MIT"
] | null | null | null | deps/src/gropt/src/WeightedLowRank.cpp | JuliaPackageMirrors/ElasticFDA.jl | fe9852231d04672c0792f2ca7adf754da0874f0a | [
"MIT"
] | null | null | null |
#include "WeightedLowRank.h"
WeightedLowRank::WeightedLowRank(double *inA, double *inW, integer inm, integer inn, integer inr)
{
A = inA;
W = inW;
m = inm;
n = inn;
r = inr;
};
WeightedLowRank::~WeightedLowRank(void)
{
};
double WeightedLowRank::f(Variable *x) const
{
ProductElement *ProdxxM = dynamic_cast<ProductElement *>(x);
const double *Uptr = ProdxxM->GetElement(0)->ObtainReadData();
const double *Dptr = ProdxxM->GetElement(1)->ObtainReadData();
const double *Vptr = ProdxxM->GetElement(2)->ObtainReadData();
char *transn = const_cast<char *> ("n");
char *transt = const_cast<char *> ("t");
char *uplo = const_cast<char *> ("u");
double one = 1, zero = 0, neg_one = -1;
integer inc = 1, M = m, R = r, N = n, MN = m * n, MR = m * r;
double *UDptr = new double[MR];
dgemm_(transn, transn, &M, &R, &R, &one, const_cast<double *> (Uptr), &M, const_cast<double *> (Dptr), &R, &zero, UDptr, &M);
SharedSpace *Temp1 = new SharedSpace(2, m, n);
double *Xptr = Temp1->ObtainWriteEntireData();
dgemm_(transn, transt, &M, &N, &R, &one, UDptr, &M, const_cast<double *> (Vptr), &N, &zero, Xptr, &M);
delete [] UDptr;
SharedSpace *Temp2 = new SharedSpace(2, m, n);
double *Errptr = Temp2->ObtainWriteEntireData();
dcopy_(&MN, A, &inc, Errptr, &inc);
daxpy_(&MN, &neg_one, Xptr, &inc, Errptr, &inc);
SharedSpace *Temp3 = new SharedSpace(2, m, n);
double *QXptr = Temp3->ObtainWriteEntireData();
dsymv_(uplo, &MN, &one, W, &MN, Errptr, &inc, &zero, QXptr, &inc);
double result = 0;
result = ddot_(&MN, Errptr, &inc, QXptr, &inc);
if(UseGrad)
{
x->AddToTempData("X", Temp1);
x->AddToTempData("err", Temp2);
x->AddToTempData("QX", Temp3);
}
else
{
delete Temp1;
delete Temp2;
delete Temp3;
}
return result;
};
//
//void WeightedLowRank::EucGrad(Variable *x, Vector *egf) const
//{
// ProductElement *ProdxxM = dynamic_cast<ProductElement *>(x);
// double *Uptr = const_cast<double *> (ProdxxM->GetElement(0)->ObtainReadData());
// double *Dptr = const_cast<double *> (ProdxxM->GetElement(1)->ObtainReadData());
// double *Vptr = const_cast<double *> (ProdxxM->GetElement(2)->ObtainReadData());
// char *transn = const_cast<char *> ("n");
// char *transt = const_cast<char *> ("t");
// double one = 1, zero = 0, neg_one = -1.0, neg_two = -2.0;
// integer inc = 1, M = m, R = r, N = n, MN = m * n, MR = m * r, NR = n * r;
//
// const SharedSpace *Temp = x->ObtainReadTempData("QX");
// const double *QXptr = Temp->ObtainReadData();
// double *fullgrad = new double[MN];
// dcopy_(&MN, const_cast<double *> (QXptr), &inc, fullgrad, &inc);
// dscal_(&MN, &neg_two, fullgrad, &inc);
//
// double *XiVptr = new double[MR];
// dgemm_(transn, transn, &M, &R, &N, &one, fullgrad, &M, Vptr, &N, &zero, XiVptr, &M);
// double *XiUptr = new double[NR];
// dgemm_(transt, transn, &N, &R, &M, &one, fullgrad, &M, Uptr, &M, &zero, XiUptr, &N);
// delete [] fullgrad;
//
// double *egfTV = egf->ObtainWriteEntireData();
// double *Udotptr = egfTV;
// double *Ddotptr = egfTV + m * r;
// double *Vdotptr = Ddotptr + r * r;
// dgemm_(transn, transt, &M, &R, &R, &one, XiVptr, &M, Dptr, &R, &zero, Udotptr, &M);
// dgemm_(transt, transn, &R, &R, &M, &one, Uptr, &M, XiVptr, &M, &zero, Ddotptr, &R);
// dgemm_(transn, transn, &N, &R, &R, &one, XiUptr, &N, Dptr, &R, &zero, Vdotptr, &N);
// delete [] XiUptr;
// delete [] XiVptr;
//};
//
//void WeightedLowRank::EucHessianEta(Variable *x, Vector *etax, Vector *exix) const
//{
// etax->CopyTo(exix);
//};
void WeightedLowRank::RieGrad(Variable *x, Vector *gf) const
{
ProductElement *ProdxxM = dynamic_cast<ProductElement *>(x);
const double *Uptr = ProdxxM->GetElement(0)->ObtainReadData();
const double *Dptr = ProdxxM->GetElement(1)->ObtainReadData();
const double *Vptr = ProdxxM->GetElement(2)->ObtainReadData();
char *transn = const_cast<char *> ("n");
char *transt = const_cast<char *> ("t");
double one = 1, zero = 0, neg_one = -1.0, neg_two = -2.0;
integer inc = 1, M = m, R = r, N = n, MN = m * n, MR = m * r, NR = n * r, RR = r * r;
const SharedSpace *Temp = x->ObtainReadTempData("QX");
const double *QXptr = Temp->ObtainReadData();
double *fullgrad = new double[MN];
dcopy_(&MN, const_cast<double *> (QXptr), &inc, fullgrad, &inc);
dscal_(&MN, &neg_two, fullgrad, &inc);
//x->Print("x");//----
//ForDebug::Print("fullgrad:", fullgrad, m, n);//----
double *XiVptr = new double[MR];
dgemm_(transn, transn, &M, &R, &N, &one, fullgrad, &M, const_cast<double *> (Vptr), &N, &zero, XiVptr, &M);
double *XiUptr = new double[NR];
dgemm_(transt, transn, &N, &R, &M, &one, fullgrad, &M, const_cast<double *> (Uptr), &M, &zero, XiUptr, &N);
delete [] fullgrad;
// compute inverse of D
integer info;
integer *IPIV = new integer[R+1];
double *WORK = new double[RR];
double *Dinv = new double[RR];
dcopy_(&RR, const_cast<double *> (Dptr), &inc, Dinv, &inc);
dgetrf_(&R, &R, Dinv, &R, IPIV, &info);
dgetri_(&R, Dinv, &R, IPIV, WORK, &RR, &info);
delete [] IPIV;
delete [] WORK;
double *gfTV = gf->ObtainWriteEntireData();
double *Udotptr = gfTV;
double *Ddotptr = gfTV + m * r;
double *Vdotptr = Ddotptr + r * r;
dgemm_(transt, transn, &R, &R, &M, &one, const_cast<double *> (Uptr), &M, XiVptr, &M, &zero, Ddotptr, &R);
dgemm_(transn, transn, &M, &R, &R, &one, const_cast<double *> (Uptr), &M, Ddotptr, &R, &zero, Udotptr, &M);
dscal_(&MR, &neg_one, Udotptr, &inc);
daxpy_(&MR, &one, XiVptr, &inc, Udotptr, &inc);
dgemm_(transn, transt, &N, &R, &R, &one, const_cast<double *> (Vptr), &N, Ddotptr, &R, &zero, Vdotptr, &N);
dscal_(&NR, &neg_one, Vdotptr, &inc);
daxpy_(&NR, &one, XiUptr, &inc, Vdotptr, &inc);
double *Udottemp = new double[MR];
double *Vdottemp = new double[NR];
dgemm_(transn, transn, &M, &R, &R, &one, Udotptr, &M, Dinv, &R, &zero, Udottemp, &M);
dgemm_(transn, transt, &N, &R, &R, &one, Vdotptr, &N, Dinv, &R, &zero, Vdottemp, &N);
dcopy_(&MR, Udottemp, &inc, Udotptr, &inc);
dcopy_(&NR, Vdottemp, &inc, Vdotptr, &inc);
//gf->Print("gf");//---
delete [] Udottemp;
delete [] Vdottemp;
delete [] Dinv;
delete [] XiUptr;
delete [] XiVptr;
};
void WeightedLowRank::RieHessianEta(Variable *x, Vector *etax, Vector *xix) const
{
etax->CopyTo(xix);
/*ProductElement *ProdxxM = dynamic_cast<ProductElement *>(x);
double *Uptr = const_cast<double *> (ProdxxM->GetElement(0)->ObtainReadData());
double *Dptr = const_cast<double *> (ProdxxM->GetElement(1)->ObtainReadData());
double *Vptr = const_cast<double *> (ProdxxM->GetElement(2)->ObtainReadData());
char *transn = const_cast<char *> ("n");
char *transt = const_cast<char *> ("t");
double one = 1, zero = 0, neg_one = -1.0, neg_two = -2.0;
integer inc = 1, M = m, R = r, N = n, MN = m * n, MR = m * r, NR = n * r;
const SharedSpace *Temp = x->ObtainReadTempData("QX");
const double *QXptr = Temp->ObtainReadData();
double *gfTV = etax->ObtainWriteEntireData();
double *Udotptr = gfTV;
double *Ddotptr = gfTV + m * r;
double *Vdotptr = Ddotptr + r * r;
double *UDdot = new double[MR];
dgemm_(transn, transn, &M, &R, &R, &one, Uptr, &M, Ddotptr, &R, &zero, UDdot, &M);
double *Qeta = new double[MN];
dgemm_(transn, transt, &M, &N, &R, &one, Udotptr, &M, Vptr, &N, &zero, Qeta, &M);*/
};
| 38.26 | 130 | 0.591741 | [
"vector"
] |
40ca1b7f9c33b705cbd0e7015efe1d9ec23c53f3 | 20,093 | hpp | C++ | blast/include/objmgr/data_loader.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/include/objmgr/data_loader.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/include/objmgr/data_loader.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | #ifndef OBJECTS_OBJMGR___DATA_LOADER__HPP
#define OBJECTS_OBJMGR___DATA_LOADER__HPP
/* $Id: data_loader.hpp 610968 2020-06-26 12:55:17Z grichenk $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Aleksey Grichenko, Michael Kimelman, Eugene Vasilchenko
*
* File Description:
* Data loader base class for object manager
*
*/
#include <corelib/ncbiobj.hpp>
#include <util/range.hpp>
#include <objmgr/object_manager.hpp>
#include <objmgr/annot_name.hpp>
#include <objmgr/annot_type_selector.hpp>
#include <objmgr/impl/tse_lock.hpp>
#include <objmgr/blob_id.hpp>
#include <objects/seq/seq_id_handle.hpp>
#include <objects/seq/Seq_inst.hpp>
#include <corelib/plugin_manager.hpp>
#include <set>
#include <map>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects)
/** @addtogroup ObjectManagerCore
*
* @{
*/
// fwd decl
class CDataSource;
class CTSE_Info;
class CTSE_Chunk_Info;
class CBioseq_Info;
class IEditSaver;
struct SAnnotSelector;
class CScope_Impl;
/////////////////////////////////////////////////////////////////////////////
// structure to describe required data set
//
struct SRequestDetails
{
typedef CRange<TSeqPos> TRange;
typedef set<SAnnotTypeSelector> TAnnotTypesSet;
typedef map<CAnnotName, TAnnotTypesSet> TAnnotSet;
enum FAnnotBlobType {
fAnnotBlobNone = 0,
fAnnotBlobInternal = 1<<0,
fAnnotBlobExternal = 1<<1,
fAnnotBlobOrphan = 1<<2,
fAnnotBlobAll = (fAnnotBlobInternal |
fAnnotBlobExternal |
fAnnotBlobOrphan)
};
typedef int TAnnotBlobType;
SRequestDetails(void)
: m_NeedSeqMap(TRange::GetEmpty()),
m_NeedSeqData(TRange::GetEmpty()),
m_AnnotBlobType(fAnnotBlobNone)
{
}
TRange m_NeedSeqMap;
TRange m_NeedSeqData;
TAnnotSet m_NeedAnnots;
TAnnotBlobType m_AnnotBlobType;
};
/////////////////////////////////////////////////////////////////////////////
// Template for data loader construction.
class CLoaderMaker_Base
{
public:
// Virtual method for creating an instance of the data loader
virtual CDataLoader* CreateLoader(void) const = 0;
virtual ~CLoaderMaker_Base(void) {}
protected:
typedef SRegisterLoaderInfo<CDataLoader> TRegisterInfo_Base;
string m_Name;
TRegisterInfo_Base m_RegisterInfo;
friend class CObjectManager;
};
// Construction of data loaders without arguments
template <class TDataLoader>
class CSimpleLoaderMaker : public CLoaderMaker_Base
{
public:
CSimpleLoaderMaker(void)
{
m_Name = TDataLoader::GetLoaderNameFromArgs();
}
virtual ~CSimpleLoaderMaker(void) {}
virtual CDataLoader* CreateLoader(void) const
{
return new TDataLoader(m_Name);
}
typedef SRegisterLoaderInfo<TDataLoader> TRegisterInfo;
TRegisterInfo GetRegisterInfo(void)
{
TRegisterInfo info;
info.Set(m_RegisterInfo.GetLoader(), m_RegisterInfo.IsCreated());
return info;
}
};
// Construction of data loaders with an argument. A structure
// may be used to create loaders with multiple arguments.
template <class TDataLoader, class TParam>
class CParamLoaderMaker : public CLoaderMaker_Base
{
public:
typedef TParam TParamType;
public:
// TParam should have copy method.
CParamLoaderMaker(TParam param)
: m_Param(param)
{
m_Name = TDataLoader::GetLoaderNameFromArgs(param);
}
virtual ~CParamLoaderMaker(void) {}
virtual CDataLoader* CreateLoader(void) const
{
return new TDataLoader(m_Name, m_Param);
}
typedef SRegisterLoaderInfo<TDataLoader> TRegisterInfo;
TRegisterInfo GetRegisterInfo(void)
{
TRegisterInfo info;
info.Set(m_RegisterInfo.GetLoader(), m_RegisterInfo.IsCreated());
return info;
}
protected:
TParam m_Param;
};
////////////////////////////////////////////////////////////////////
//
// CDataLoader --
//
// Load data from different sources
//
// There are three types of blobs (top-level Seq-entries) related to
// any Seq-id:
// 1. main (eBioseq/eBioseqCore/eSequence):
// Seq-entry containing Bioseq with Seq-id.
// 2. external (eExtAnnot):
// Seq-entry doesn't contain Bioseq but contains annotations on Seq-id,
// provided this data source contain some blob with Bioseq.
// 3. orphan (eOrphanAnnot):
// Seq-entry contains only annotations and this data source doesn't
// contain Bioseq with specified Seq-id at all.
class NCBI_XOBJMGR_EXPORT CDataLoader : public CObject
{
protected:
CDataLoader(void);
CDataLoader(const string& loader_name);
public:
virtual ~CDataLoader(void);
public:
/// main blob is blob with sequence
/// all other blobs are external and contain external annotations
enum EChoice {
eBlob, ///< whole main
eBioseq, ///< main blob with complete bioseq
eCore, ///< ?only seq-entry core?
eBioseqCore, ///< main blob with bioseq core (no seqdata and annots)
eSequence, ///< seq data
eFeatures, ///< features from main blob
eGraph, ///< graph annotations from main blob
eAlign, ///< aligns from main blob
eAnnot, ///< all annotations from main blob
eExtFeatures, ///< external features
eExtGraph, ///< external graph annotations
eExtAlign, ///< external aligns
eExtAnnot, ///< all external annotations
eOrphanAnnot, ///< all external annotations if no Bioseq exists
eAll ///< all blobs (main and external)
};
typedef CTSE_Lock TTSE_Lock;
typedef set<TTSE_Lock> TTSE_LockSet;
typedef CRef<CTSE_Chunk_Info> TChunk;
typedef vector<TChunk> TChunkSet;
typedef set<string> TProcessedNAs;
static bool IsRequestedAnyNA(const SAnnotSelector* sel);
static bool IsRequestedNA(const string& na, const SAnnotSelector* sel);
static bool IsProcessedNA(const string& na, const TProcessedNAs* processed_nas);
static void SetProcessedNA(const string& na, TProcessedNAs* processed_nas);
/// Request from a datasource using handles and ranges instead of seq-loc
/// The TSEs loaded in this call will be added to the tse_set.
/// The GetRecords() may throw CBlobStateException if the sequence
/// is not available (not known or disabled), and blob state
/// is different from minimal fState_no_data.
/// The actual blob state can be read from the exception in this case.
virtual TTSE_LockSet GetRecords(const CSeq_id_Handle& idh,
EChoice choice);
/// The same as GetRecords() but always returns empty TSE lock set
/// instead of throwing CBlobStateException.
TTSE_LockSet GetRecordsNoBlobState(const CSeq_id_Handle& idh,
EChoice choice);
/// Request from a datasource using handles and ranges instead of seq-loc
/// The TSEs loaded in this call will be added to the tse_set.
/// Default implementation will call GetRecords().
virtual TTSE_LockSet GetDetailedRecords(const CSeq_id_Handle& idh,
const SRequestDetails& details);
/// Request from a datasource set of blobs with external annotations.
/// CDataLoader has reasonable default implementation.
virtual TTSE_LockSet GetExternalRecords(const CBioseq_Info& bioseq);
/// old Get*AnnotRecords() methods
virtual TTSE_LockSet GetOrphanAnnotRecords(const CSeq_id_Handle& idh,
const SAnnotSelector* sel);
virtual TTSE_LockSet GetExternalAnnotRecords(const CSeq_id_Handle& idh,
const SAnnotSelector* sel);
virtual TTSE_LockSet GetExternalAnnotRecords(const CBioseq_Info& bioseq,
const SAnnotSelector* sel);
typedef set<CSeq_id_Handle> TSeq_idSet;
/// new Get*AnnotRecords() methods
virtual TTSE_LockSet GetOrphanAnnotRecordsNA(const CSeq_id_Handle& idh,
const SAnnotSelector* sel,
TProcessedNAs* processed_nas);
virtual TTSE_LockSet GetOrphanAnnotRecordsNA(const TSeq_idSet& ids,
const SAnnotSelector* sel,
TProcessedNAs* processed_nas);
virtual TTSE_LockSet GetExternalAnnotRecordsNA(const CSeq_id_Handle& idh,
const SAnnotSelector* sel,
TProcessedNAs* processed_nas);
virtual TTSE_LockSet GetExternalAnnotRecordsNA(const CBioseq_Info& bioseq,
const SAnnotSelector* sel,
TProcessedNAs* processed_nas);
typedef vector<CSeq_id_Handle> TIds;
/// Request for a list of all Seq-ids of a sequence.
/// The result container should not change if sequence with requested id
/// is not known.
/// The result must be non-empty for existing sequences
virtual void GetIds(const CSeq_id_Handle& idh, TIds& ids);
/// helper function to check if sequence exists, uses GetIds()
bool SequenceExists(const CSeq_id_Handle& idh);
/// Request for a accession.version Seq-id of a sequence.
/// Returns null CSeq_id_Handle if sequence with requested id is not known,
/// or if existing sequence doesn't have an accession
/// @sa GetAccVerFound()
virtual CSeq_id_Handle GetAccVer(const CSeq_id_Handle& idh);
/// Better replacement of GetAccVer(), this method should be defined in
/// data loaders, GetAccVer() is left for compatibility.
/// @sa GetAccVer()
struct SAccVerFound {
bool sequence_found; // true if the sequence is found by data loader
CSeq_id_Handle acc_ver; // may be null even for existing sequence
SAccVerFound() : sequence_found(false) {}
};
virtual SAccVerFound GetAccVerFound(const CSeq_id_Handle& idh);
/// Request for a gi of a sequence.
/// Returns zero gi if sequence with requested id is not known,
/// or if existing sequence doesn't have a gi
/// @sa GetGiFound()
virtual TGi GetGi(const CSeq_id_Handle& idh);
/// Better replacement of GetGi(), this method should be defined in
/// data loaders, GetGi() is left for compatibility.
/// @sa GetGi()
struct SGiFound {
bool sequence_found; // true if the sequence is found by data loader
TGi gi; // may be 0 even for existing sequence
SGiFound() : sequence_found(false), gi(ZERO_GI) {}
};
virtual SGiFound GetGiFound(const CSeq_id_Handle& idh);
/// Request for a label string of a sequence.
/// Returns empty string if sequence with requested id is not known.
/// The result must be non-empty for existing sequences
virtual string GetLabel(const CSeq_id_Handle& idh);
/// Request for a taxonomy id of a sequence.
/// Returns -1 if sequence with requested id is not known.
/// Returns 0 if existing sequence doesn't have TaxID
virtual TTaxId GetTaxId(const CSeq_id_Handle& idh);
/// Request for a length of a sequence.
/// Returns kInvalidSeqPos if sequence with requested id is not known.
/// The result must not be kInvalidSeqPos for existing sequences
virtual TSeqPos GetSequenceLength(const CSeq_id_Handle& idh);
/// Request for a type of a sequence
/// Returns CSeq_inst::eMol_not_set if sequence is not known
/// @sa GetSequenceTypeFound()
virtual CSeq_inst::TMol GetSequenceType(const CSeq_id_Handle& idh);
/// Better replacement of GetSequenceType(), this method should be
/// defined in data loaders, GetSequenceType() is left for compatibility.
/// @sa GetSequenceType()
struct STypeFound {
bool sequence_found; // true if the sequence is found by data loader
CSeq_inst::TMol type; // may be eMol_not_set even for existing sequence
STypeFound() : sequence_found(false), type(CSeq_inst::eMol_not_set) {}
};
virtual STypeFound GetSequenceTypeFound(const CSeq_id_Handle& idh);
/// Request for a state of a sequence.
/// Returns CBioseq_Handle::fState_not_found|fState_no_data if sequence
/// with requested id is not known.
/// Result mustn't be fState_not_found|fState_no_data if sequence exists
virtual int GetSequenceState(const CSeq_id_Handle& idh);
/// Request for a sequence hash.
/// Returns 0 if the sequence or its hash is not known.
/// @sa GetSequenceHashFound()
virtual int GetSequenceHash(const CSeq_id_Handle& idh);
/// Better replacement of GetSequenceHash(), this method should be
/// defined in data loaders, GetSequenceHash() is left for compatibility.
/// @sa GetSequenceHash()
struct SHashFound {
bool sequence_found; // true if the sequence is found by data loader
bool hash_known; // true if sequence exists and hash value is set
int hash; // may be 0 even for existing sequence
SHashFound()
: sequence_found(false),
hash_known(false),
hash(0)
{
}
};
virtual SHashFound GetSequenceHashFound(const CSeq_id_Handle& idh);
/// Bulk loading interface for a small pieces of information per id.
/// The 'loaded' bit set (in/out) marks ids that already processed.
/// If an element in 'loaded' is set on input then bulk methods
/// should skip corresponding id, as it's already processed.
/// Othewise, if the id is known and processed, the 'loaded' element
/// will be set to true.
/// Othewise, the 'loaded' element will remain false.
typedef vector<bool> TLoaded;
typedef vector<TGi> TGis;
typedef vector<string> TLabels;
typedef vector<TTaxId> TTaxIds;
typedef vector<TSeqPos> TSequenceLengths;
typedef vector<CSeq_inst::TMol> TSequenceTypes;
typedef vector<int> TSequenceStates;
typedef vector<int> TSequenceHashes;
typedef vector<bool> THashKnown;
/// Bulk request for accession.version Seq-ids of a set of sequences.
virtual void GetAccVers(const TIds& ids, TLoaded& loaded, TIds& ret);
/// Bulk request for gis of a set of sequences.
virtual void GetGis(const TIds& ids, TLoaded& loaded, TGis& ret);
/// Bulk request for label strings of a set of sequences.
virtual void GetLabels(const TIds& ids, TLoaded& loaded, TLabels& ret);
/// Bulk request for taxonomy ids of a set of sequences.
virtual void GetTaxIds(const TIds& ids, TLoaded& loaded, TTaxIds& ret);
/// Bulk request for lengths of a set of sequences.
virtual void GetSequenceLengths(const TIds& ids, TLoaded& loaded,
TSequenceLengths& ret);
/// Bulk request for types of a set of sequences.
virtual void GetSequenceTypes(const TIds& ids, TLoaded& loaded,
TSequenceTypes& ret);
/// Bulk request for states of a set of sequences.
virtual void GetSequenceStates(const TIds& ids, TLoaded& loaded,
TSequenceStates& ret);
/// Bulk request for hashes of a set of sequences.
virtual void GetSequenceHashes(const TIds& ids, TLoaded& loaded,
TSequenceHashes& ret, THashKnown& known);
// Load multiple seq-ids. Same as GetRecords() for multiple ids
// with choise set to eBlob. The map should be initialized with
// the id handles to be loaded.
typedef map<CSeq_id_Handle, TTSE_LockSet> TTSE_LockSets;
virtual void GetBlobs(TTSE_LockSets& tse_sets);
// blob operations
typedef CBlobIdKey TBlobId;
typedef int TBlobVersion;
virtual TBlobId GetBlobId(const CSeq_id_Handle& idh);
virtual TBlobId GetBlobIdFromString(const string& str) const;
virtual TBlobVersion GetBlobVersion(const TBlobId& id);
virtual bool CanGetBlobById(void) const;
virtual TTSE_Lock GetBlobById(const TBlobId& blob_id);
virtual SRequestDetails ChoiceToDetails(EChoice choice) const;
virtual EChoice DetailsToChoice(const SRequestDetails::TAnnotSet& annots) const;
virtual EChoice DetailsToChoice(const SRequestDetails& details) const;
virtual void GetChunk(TChunk chunk_info);
virtual void GetChunks(const TChunkSet& chunks);
//
virtual void DropTSE(CRef<CTSE_Info> tse_info);
/// Specify datasource to send loaded data to.
void SetTargetDataSource(CDataSource& data_source);
string GetName(void) const;
/// Resolve TSE conflict
/// *select the best TSE from the set of dead TSEs.
/// *select the live TSE from the list of live TSEs
/// and mark the others one as dead.
virtual TTSE_Lock ResolveConflict(const CSeq_id_Handle& id,
const TTSE_LockSet& tse_set);
virtual void GC(void);
typedef CRef<IEditSaver> TEditSaver;
virtual TEditSaver GetEditSaver() const;
virtual CObjectManager::TPriority GetDefaultPriority(void) const;
virtual Uint4 EstimateLoadBytes(const CTSE_Chunk_Info& chunk) const;
virtual double EstimateLoadSeconds(const CTSE_Chunk_Info& chunk, Uint4 bytes) const;
virtual unsigned GetDefaultBlobCacheSizeLimit() const;
protected:
/// Register the loader only if the name is not yet
/// registered in the object manager
static void RegisterInObjectManager(
CObjectManager& om,
CLoaderMaker_Base& loader_maker,
CObjectManager::EIsDefault is_default,
CObjectManager::TPriority priority);
void SetName(const string& loader_name);
CDataSource* GetDataSource(void) const;
friend class CGBReaderRequestResult;
friend class CScope_Impl;
private:
CDataLoader(const CDataLoader&);
CDataLoader& operator=(const CDataLoader&);
string m_Name;
CDataSource* m_DataSource;
friend class CObjectManager;
};
/* @} */
END_SCOPE(objects)
NCBI_DECLARE_INTERFACE_VERSION(objects::CDataLoader, "xloader", 6, 0, 0);
template<>
class CDllResolver_Getter<objects::CDataLoader>
{
public:
CPluginManager_DllResolver* operator()(void)
{
CPluginManager_DllResolver* resolver =
new CPluginManager_DllResolver
(CInterfaceVersion<objects::CDataLoader>::GetName(),
kEmptyStr,
CVersionInfo::kAny,
CDll::eAutoUnload);
resolver->SetDllNamePrefix("ncbi");
return resolver;
}
};
END_NCBI_SCOPE
#endif // OBJECTS_OBJMGR___DATA_LOADER__HPP
| 38.789575 | 88 | 0.659782 | [
"object",
"vector"
] |
40cebfcb6a069b548592cbcee40d057d843fa8ba | 72,634 | cpp | C++ | dev/Code/Sandbox/Editor/Mannequin/Controls/TransitionEditorPage.cpp | crazyskateface/lumberyard | 164512f8d415d6bdf37e195af319ffe5f96a8f0b | [
"AML"
] | 5 | 2018-08-17T21:05:55.000Z | 2021-04-17T10:48:26.000Z | dev/Code/Sandbox/Editor/Mannequin/Controls/TransitionEditorPage.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | null | null | null | dev/Code/Sandbox/Editor/Mannequin/Controls/TransitionEditorPage.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | 5 | 2017-12-05T16:36:00.000Z | 2021-04-27T06:33:54.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "TransitionEditorPage.h"
#include <ICryMannequinEditor.h>
#include <IGameFramework.h>
#include "../FragmentEditor.h"
#include "../MannKeyPropertiesDlgFE.h"
#include "../MannequinDialog.h"
#include "../MannequinModelViewport.h"
#include "../MannequinNodes.h"
#include "../SequencerSequence.h"
#include "../MannequinPlayback.h"
#include "../FragmentTrack.h"
#include "../SequenceAnalyzerNodes.h"
#include "../MannDebugOptionsDialog.h"
#include "QtUtilWin.h"
#include "QShortcut.h"
#include <QMessageBox>
namespace
{
static const float TRANSITION_MIN_TIME_RANGE = 100.0f;
static const int TRANSITION_CHAR_BUFFER_SIZE = 512;
};
// returns a game root relative path like "/C3/Animations/FragmentSequences/"
QString GetFragmentSequenceFolder();
#define SEQUENCE_FILE_FILTER "Sequence XML Files (*.xml)|*.xml"
//////////////////////////////////////////////////////////////////////////
CTransitionEditorPage::CTransitionEditorPage(QWidget* pParent)
: CMannequinEditorPage(pParent)
, m_ui(new Ui::TransitionEditorPage)
, m_playShortcut(new QShortcut(QKeySequence(Qt::Key_Space), this))
, m_goToStartShortcut(new QShortcut(QKeySequence(Qt::Key_Home), this))
, m_contexts(NULL)
, m_modelViewport(NULL)
, m_sequence(NULL)
, m_seed(0)
, m_fromID(FRAGMENT_ID_INVALID)
, m_toID(FRAGMENT_ID_INVALID)
, m_fromFragTag()
, m_toFragTag()
, m_scopeMaskFrom(ACTION_SCOPES_NONE)
, m_scopeMaskTo(ACTION_SCOPES_NONE)
{
OnInitDialog();
}
CTransitionEditorPage::~CTransitionEditorPage()
{
QSettings settings;
settings.beginGroup("Settings");
settings.beginGroup("Mannequin");
settings.beginGroup("TransitionEditorLayout");
settings.setValue("TimelineUnits", m_ui->m_wndTrackPanel->GetTickDisplayMode());
}
void CTransitionEditorPage::OnInitDialog()
{
m_ui->setupUi(this);
m_ui->m_tagsPanel->Setup();
m_contexts = CMannequinDialog::GetCurrentInstance()->Contexts();
m_fTime = 0.0f;
m_fMaxTime = 0.0f;
m_playSpeed = 1.0f;
m_bPlay = false;
m_bLoop = false;
m_draggingTime = false;
m_bRefreshingTagCtrl = false;
m_sequencePlayback = NULL;
m_tagVars.reset(new CVarBlock());
setWindowTitle(tr("TransitionEditor Page"));
const char* SEQUENCE_NAME = "Transition Preview";
m_sequence = new CSequencerSequence();
m_sequence->SetName(SEQUENCE_NAME);
// Model viewport
m_modelViewport = new CMannequinModelViewport(eMEM_TransitionEditor, this);
m_ui->m_modelViewportFrame->layout()->addWidget(m_modelViewport);
m_modelViewport->SetType(ET_ViewportModel);
// Track view
//m_wndTrackPanel.SetDragAndDrop(false);
m_ui->m_wndTrackPanel->SetTimeRange(0, m_fMaxTime);
m_ui->m_wndTrackPanel->SetTimeScale(100, 0);
m_ui->m_wndTrackPanel->SetCurrTime(0);
m_ui->m_wndTrackPanel->SetSequence(m_sequence.get());
// Nodes tree view
m_ui->m_wndNodes->SetKeyListCtrl(m_ui->m_wndTrackPanel);
m_ui->m_wndNodes->SetSequence(m_sequence.get());
// Properties panel
m_ui->m_wndKeyProperties->SetKeysCtrl(m_ui->m_wndTrackPanel);
m_ui->m_wndKeyProperties->SetSequence(m_sequence.get());
// Tags panel
m_ui->m_tagsPanel->SetTitle(tr("Preview Filter Tags"));
// Toolbar
InitToolbar();
connect(m_playShortcut.data(), &QShortcut::activated, this, &CTransitionEditorPage::OnPlay);
connect(m_goToStartShortcut.data(), &QShortcut::activated, this, &CTransitionEditorPage::OnGoToStart);
connect(m_ui->buttonTvJumpStart, &QToolButton::clicked, this, &CTransitionEditorPage::OnGoToStart);
connect(m_ui->buttonTvJumpEnd, &QToolButton::clicked, this, &CTransitionEditorPage::OnGoToEnd);
connect(m_ui->buttonTvPlay, &QToolButton::clicked, this, &CTransitionEditorPage::OnPlay);
connect(m_ui->buttonPlayLoop, &QToolButton::clicked, this, &CTransitionEditorPage::OnLoop);
connect(m_ui->buttonToggle1P, &QToolButton::clicked, this, &CTransitionEditorPage::OnToggle1P);
connect(m_ui->buttonShowDebugOptions, &QToolButton::clicked, this, &CTransitionEditorPage::OnShowDebugOptions);
connect(m_ui->buttonTogglePreviewUnits, &QToolButton::clicked, this, &CTransitionEditorPage::OnToggleTimelineUnits);
connect(m_ui->buttonMannReloadAnims, &QToolButton::clicked, this, &CTransitionEditorPage::OnReloadAnimations);
connect(m_ui->buttonMannLookAtToggle, &QToolButton::clicked, this, &CTransitionEditorPage::OnToggleLookat);
connect(m_ui->buttonMannRotateLocator, &QToolButton::clicked, this, &CTransitionEditorPage::OnClickRotateLocator);
connect(m_ui->buttonMannTranslateLocator, &QToolButton::clicked, this, &CTransitionEditorPage::OnClickTranslateLocator);
connect(m_ui->buttonMannAttachToEntity, &QToolButton::clicked, this, &CTransitionEditorPage::OnToggleAttachToEntity);
connect(m_ui->buttonMannShowSceneRoots, &QToolButton::clicked, this, &CTransitionEditorPage::OnToggleShowSceneRoots);
connect(m_ui->m_cDlgToolBar, &CSequencerDopeSheetToolbar::TimeChanged, this, &CTransitionEditorPage::OnTimeChanged);
OnUpdateTimeEdit();
}
void CTransitionEditorPage::InitToolbar()
{
QMenu* playMenu = new QMenu(m_ui->buttonTvPlay);
m_ui->buttonTvPlay->setMenu(playMenu);
connect(playMenu, &QMenu::aboutToShow, this, &CTransitionEditorPage::OnPlayMenu);
m_ui->m_cDlgToolBar->SetTime(m_fTime, m_ui->m_wndTrackPanel->GetSnapFps());
ValidateToolbarButtonsState();
}
void CTransitionEditorPage::ValidateToolbarButtonsState()
{
m_ui->buttonMannLookAtToggle->setChecked(m_modelViewport->IsLookingAtCamera());
m_ui->buttonMannRotateLocator->setChecked(!m_modelViewport->IsTranslateLocatorMode());
m_ui->buttonMannTranslateLocator->setChecked(m_modelViewport->IsTranslateLocatorMode());
m_ui->buttonMannAttachToEntity->setChecked(m_modelViewport->IsAttachedToEntity());
m_ui->buttonMannShowSceneRoots->setChecked(m_modelViewport->IsShowingSceneRoots());
m_ui->buttonToggle1P->setChecked(m_modelViewport->IsCameraAttached());
}
void CTransitionEditorPage::SaveLayout()
{
const QString strSection = QStringLiteral("Settings\\Mannequin\\TransitionEditorLayout");
MannUtils::SaveSplitterToRegistry(strSection, QStringLiteral("SequencerSplitter"), m_ui->m_wndSplitterTracks);
MannUtils::SaveSplitterToRegistry(strSection, QStringLiteral("VerticalSplitter"), m_ui->m_wndSplitterVert);
MannUtils::SaveSplitterToRegistry(strSection, QStringLiteral("HorizontalSplitter"), m_ui->m_wndSplitterHorz);
}
void CTransitionEditorPage::LoadLayout()
{
const QString strSection = QStringLiteral("Settings\\Mannequin\\TransitionEditorLayout");
MannUtils::LoadSplitterFromRegistry(strSection, QStringLiteral("SequencerSplitter"), m_ui->m_wndSplitterTracks, CMannequinDialog::s_minPanelSize);
MannUtils::LoadSplitterFromRegistry(strSection, QStringLiteral("VerticalSplitter"), m_ui->m_wndSplitterVert, CMannequinDialog::s_minPanelSize);
MannUtils::LoadSplitterFromRegistry(strSection, QStringLiteral("HorizontalSplitter"), m_ui->m_wndSplitterHorz, CMannequinDialog::s_minPanelSize);
}
void CTransitionEditorPage::slotVisibilityChanged(bool visible)
{
if (!visible)
{
return;
}
if (auto pMannequinDialog = CMannequinDialog::GetCurrentInstance())
{
m_ui->m_wndNodes->SyncKeyCtrl();
pMannequinDialog->ShowPane<CTransitionBrowser*>();
}
}
float CTransitionEditorPage::GetMarkerTimeStart() const
{
return m_ui->m_wndTrackPanel->GetMarkedTime().start;
}
float CTransitionEditorPage::GetMarkerTimeEnd() const
{
return m_ui->m_wndTrackPanel->GetMarkedTime().end;
}
void CTransitionEditorPage::Update()
{
bool isDraggingTime = m_ui->m_wndTrackPanel->IsDraggingTime();
float dsTime = m_ui->m_wndTrackPanel->GetTime();
float effectiveSpeed = m_playSpeed;
if (isDraggingTime)
{
if (m_sequencePlayback)
{
m_sequencePlayback->SetTime(dsTime);
}
m_fTime = dsTime;
effectiveSpeed = 0.0f;
}
else if (m_draggingTime)
{
}
if (!m_bPlay)
{
effectiveSpeed = 0.0f;
}
m_ui->m_cDlgToolBar->SetTime(m_fTime, m_ui->m_wndTrackPanel->GetSnapFps());
m_modelViewport->SetPlaybackMultiplier(effectiveSpeed);
m_draggingTime = isDraggingTime;
float endTime = GetMarkerTimeEnd();
if (endTime <= 0.0f)
{
endTime = m_fMaxTime;
}
if (m_sequencePlayback)
{
m_sequencePlayback->Update(gEnv->pTimer->GetFrameTime() * effectiveSpeed, m_modelViewport);
m_fTime = m_sequencePlayback->GetTime();
if (m_fTime > endTime)
{
if (m_bLoop)
{
const float startTime = GetMarkerTimeStart();
m_fTime = startTime;
m_sequencePlayback->SetTime(startTime);
// Set silent mode off.
m_bRestartingSequence = false;
}
else
{
m_bPlay = false;
OnUpdatePlay();
}
}
}
m_ui->m_wndTrackPanel->SetCurrTime(m_fTime);
if (MannUtils::IsSequenceDirty(m_contexts, m_sequence.get(), m_lastChange, eMEM_TransitionEditor))
{
if (!TrackPanel()->IsDragging())
{
OnUpdateTV();
}
}
m_ui->m_wndKeyProperties->OnUpdate();
m_bRestartingSequence = false;
// Clean up any removed tracks from history.
// A ref count of 1 means history is the only remaining holder of the track.
auto trackIter = m_fragmentHistory->m_tracks.begin();
while (trackIter != m_fragmentHistory->m_tracks.end())
{
const _smart_ptr<CSequencerTrack>& track = *trackIter;
if (1 == track->NumRefs())
{
trackIter = m_fragmentHistory->m_tracks.erase(trackIter);
}
else
{
++trackIter;
}
}
// update the button logic
ValidateToolbarButtonsState();
OnUpdatePlay();
OnUpdateLoop();
OnUpdateGoToStart();
OnUpdateGoToEnd();
OnUpdateReloadAnimations();
OnUpdateTimeEdit();
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnGoToStart()
{
m_fTime = 0.0f;
m_bPlay = false;
OnUpdatePlay();
if (m_sequencePlayback)
{
m_sequencePlayback->SetTime(0.0f);
}
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnGoToEnd()
{
m_fTime = m_fMaxTime;
m_bPlay = false;
OnUpdatePlay();
if (m_sequencePlayback)
{
m_sequencePlayback->SetTime(m_sequence->GetTimeRange().end);
}
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnPlay()
{
m_bPlay = !m_bPlay;
OnUpdatePlay();
if (m_bPlay)
{
float endTime = GetMarkerTimeEnd();
if (endTime <= 0.0f)
{
endTime = m_fMaxTime;
}
if (m_fTime > endTime)
{
const float startTime = GetMarkerTimeStart();
m_fTime = startTime;
if (m_sequencePlayback)
{
m_sequencePlayback->SetTime(startTime);
}
}
}
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnLoop()
{
m_bLoop = !m_bLoop;
OnUpdateLoop();
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnPlayMenu()
{
struct SScales
{
const char* pszText;
float fScale;
};
SScales Scales[] = {
{" 2 ", 2.0f},
{" 1 ", 1.0f},
{"1/2", 0.5f},
{"1/4", 0.25f},
{"1/8", 0.125f},
};
QMenu* menu = m_ui->buttonTvPlay->menu();
if (menu->actions().isEmpty())
{
int nScales = sizeof(Scales) / sizeof(SScales);
for (int i = 0; i < nScales; i++)
{
QAction* action = menu->addAction(QString::fromLatin1(Scales[i].pszText));
action->setCheckable(true);
action->setData(Scales[i].fScale);
}
connect(menu, &QMenu::triggered, [&](QAction* action){ m_playSpeed = action->data().toDouble(); });
}
for (QAction* action : menu->actions())
{
action->setChecked(action->data().toDouble() == m_playSpeed);
}
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnUpdateGoToStart()
{
m_ui->buttonTvJumpStart->setEnabled(CMannequinDialog::GetCurrentInstance()->PreviewFileLoaded());
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnUpdateGoToEnd()
{
m_ui->buttonTvJumpEnd->setEnabled(CMannequinDialog::GetCurrentInstance()->PreviewFileLoaded());
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnUpdatePlay()
{
m_ui->buttonTvPlay->setEnabled(CMannequinDialog::GetCurrentInstance()->PreviewFileLoaded());
m_ui->buttonTvPlay->setChecked(m_bPlay);
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnUpdateLoop()
{
m_ui->buttonPlayLoop->setEnabled(CMannequinDialog::GetCurrentInstance()->PreviewFileLoaded());
m_ui->buttonPlayLoop->setChecked(m_bLoop);
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnUpdateReloadAnimations()
{
m_ui->buttonMannReloadAnims->setEnabled(CMannequinDialog::GetCurrentInstance()->PreviewFileLoaded());
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnUpdateTimeEdit()
{
m_ui->m_cDlgToolBar->setEnabled(CMannequinDialog::GetCurrentInstance()->PreviewFileLoaded());
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnToggle1P()
{
m_modelViewport->ToggleCamera();
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnShowDebugOptions()
{
CMannequinDebugOptionsDialog dialog(m_modelViewport, this);
dialog.exec();
ValidateToolbarButtonsState();
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnToggleTimelineUnits()
{
// Enum has 2 states, so (oldMode + 1) % 2
m_ui->m_wndTrackPanel->SetTickDisplayMode((ESequencerTickMode)((m_ui->m_wndTrackPanel->GetTickDisplayMode() + 1) & 1));
if (m_modelViewport)
{
m_modelViewport->SetTimelineUnits(m_ui->m_wndTrackPanel->GetTickDisplayMode());
}
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnReloadAnimations()
{
if (m_modelViewport == NULL)
{
return;
}
CSequencerUtils::SelectedKeys selectedKeys;
CSequencerUtils::GetAllKeys(m_ui->m_wndTrackPanel->GetSequence(), selectedKeys);
for (int i = 0; i < selectedKeys.keys.size(); ++i)
{
CSequencerUtils::SelectedKey& selectedKey = selectedKeys.keys[i];
const ESequencerParamType paramType = selectedKey.pTrack->GetParameterType();
if (paramType == SEQUENCER_PARAM_ANIMLAYER)
{
IEntity* pEntity = selectedKey.pNode->GetEntity();
CRY_ASSERT(pEntity != NULL);
ICharacterInstance* pCharInstance = pEntity->GetCharacter(0);
CRY_ASSERT(pCharInstance != NULL);
pCharInstance->GetISkeletonAnim()->StopAnimationsAllLayers();
pCharInstance->ReloadCHRPARAMS();
}
}
OnSequenceRestart(0.0f);
SetTime(0.0f);
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnToggleLookat()
{
ValidateToolbarButtonsState();
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnClickRotateLocator()
{
m_modelViewport->SetLocatorRotateMode();
ValidateToolbarButtonsState();
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnClickTranslateLocator()
{
m_modelViewport->SetLocatorTranslateMode();
ValidateToolbarButtonsState();
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnToggleShowSceneRoots()
{
m_modelViewport->SetShowSceneRoots(!m_modelViewport->IsShowingSceneRoots());
ValidateToolbarButtonsState();
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnToggleAttachToEntity()
{
if (m_modelViewport->IsAttachedToEntity())
{
m_modelViewport->DetachFromEntity();
}
else
{
m_modelViewport->AttachToEntity();
}
ValidateToolbarButtonsState();
}
//////////////////////////////////////////////////////////////////////////
float CTransitionEditorPage::PopulateClipTracks(CSequencerNode* node, const int scopeID)
{
IActionController* pActionController = m_contexts->viewData[eMEM_TransitionEditor].m_pActionController;
IScope* scope = pActionController->GetScope(scopeID);
// Find which keys are selected to restore later
int numTracks = node->GetTrackCount();
std::vector<std::vector<int> > selectedKeys;
selectedKeys.reserve(numTracks);
for (int trackID = 0; trackID < numTracks; ++trackID)
{
std::vector<int> tracksSelectedKeys;
CSequencerTrack* pTrack = node->GetTrackByIndex(trackID);
int numKeys = pTrack->GetNumKeys();
tracksSelectedKeys.reserve(numKeys);
for (int keyID = 0; keyID < numKeys; ++keyID)
{
const CSequencerKey* key = pTrack->GetKey(keyID);
if (pTrack->IsKeySelected(keyID))
{
tracksSelectedKeys.push_back(keyID);
}
}
selectedKeys.push_back(tracksSelectedKeys);
}
for (uint32 l = 0; l < node->GetTrackCount(); )
{
CSequencerTrack* track = node->GetTrackByIndex(l);
switch (track->GetParameterType())
{
case SEQUENCER_PARAM_ANIMLAYER:
case SEQUENCER_PARAM_PROCLAYER:
node->RemoveTrack(track);
break;
default:
l++;
break;
}
}
CFragmentTrack* fragTrack = (CFragmentTrack*)node->GetTrackForParameter(SEQUENCER_PARAM_FRAGMENTID);
CTransitionPropertyTrack* propsTrack = (CTransitionPropertyTrack*)node->GetTrackForParameter(SEQUENCER_PARAM_TRANSITIONPROPS);
//--- Strip transition properties track
const int numPropKeysInitial = propsTrack->GetNumKeys();
for (int i = numPropKeysInitial - 1; i >= 0; i--)
{
propsTrack->RemoveKey(i);
}
const ActionScopes scopeFlag = (1 << scopeID);
float maxTime = TRANSITION_MIN_TIME_RANGE;
SClipTrackContext trackContext;
trackContext.tagState.globalTags = m_tagState;
trackContext.context = m_contexts->m_scopeData[scopeID].context[eMEM_TransitionEditor];
const TagState additionalTags = m_contexts->m_controllerDef->m_scopeDef[scopeID].additionalTags;
const CTagDefinition& tagDef = m_contexts->m_controllerDef->m_tags;
const uint32 contextID = scope->GetContextID();
FragmentID lastfragment = FRAGMENT_ID_INVALID;
SFragTagState lastTagState;
float lastTime = 0.0f; // last fragment's insertion time, in 'track time'
float lastFragmentDuration = 0.0f;
bool lastPrimaryInstall = false;
float motionParams[eMotionParamID_COUNT];
memset(motionParams, 0, sizeof(motionParams));
for (uint32 h = 0; h < m_fragmentHistory->m_history.m_items.size(); h++)
{
CFragmentHistory::SHistoryItem& item = m_fragmentHistory->m_history.m_items[h];
if (item.type == CFragmentHistory::SHistoryItem::Tag)
{
trackContext.tagState.globalTags = tagDef.GetUnion(m_tagState, item.tagState.globalTags);
trackContext.context = m_contexts->GetContextDataForID(trackContext.tagState.globalTags, contextID, eMEM_TransitionEditor);
}
else if (item.type == CFragmentHistory::SHistoryItem::Param)
{
EMotionParamID paramID = MannUtils::GetMotionParam(item.paramName.toLatin1().data());
if (paramID != eMotionParamID_COUNT)
{
motionParams[paramID] = item.param.value.q.v.x;
}
}
else if (item.type == CFragmentHistory::SHistoryItem::Fragment)
{
SFragmentQuery fragQuery(tagDef, item.fragment, SFragTagState(trackContext.tagState.globalTags, item.tagState.fragmentTags), additionalTags, item.fragOptionIdxSel);
ActionScopes scopeMask = m_contexts->potentiallyActiveScopes & item.installedScopeMask;
if (scopeMask & (1 << scopeID))
{
const int numFragKeys = fragTrack->GetNumKeys();
for (int i = 0; i < numFragKeys; i++)
{
CFragmentKey fragKey;
fragTrack->GetKey(i, &fragKey);
if (fragKey.historyItem == h)
{
fragKey.scopeMask = item.installedScopeMask;
fragTrack->SetKey(i, &fragKey);
}
}
if (trackContext.context && trackContext.context->database)
{
float nextTime = -1.0f;
for (uint32 n = h + 1; n < m_fragmentHistory->m_history.m_items.size(); n++)
{
const CFragmentHistory::SHistoryItem& nextItem = m_fragmentHistory->m_history.m_items[n];
if (nextItem.installedScopeMask & item.installedScopeMask)
{
//--- This fragment collides with the current one and so will force a flush of it
nextTime = nextItem.time - m_fragmentHistory->m_history.m_firstTime;
break;
}
}
trackContext.historyItem = h;
trackContext.scopeID = scopeID;
const float time = item.time - m_fragmentHistory->m_history.m_firstTime;
uint32 rootScope = 0;
for (uint32 i = 0; i <= scopeID; i++)
{
if (((1 << i) & scopeMask) != 0)
{
rootScope = i;
break;
}
}
bool primaryInstall = true;
//--- If this is not the root scope on a cross-scope fragment
if (rootScope != scopeID)
{
if (additionalTags == TAG_STATE_EMPTY)
{
//--- Check to see if it should go on an earlier context
const uint32 numScopes = pActionController->GetTotalScopes();
const uint32 contextID = pActionController->GetScope(scopeID)->GetContextID();
for (uint32 i = 0; (i < scopeID) && primaryInstall; i++)
{
const uint32 altContextID = pActionController->GetScope(i)->GetContextID();
primaryInstall = (contextID != altContextID);
}
}
}
else
{
item.fragOptionIdxSel = item.fragOptionIdx;
if (item.fragOptionIdx == OPTION_IDX_RANDOM)
{
item.fragOptionIdxSel = m_contexts->viewData[eMEM_TransitionEditor].m_pAnimContext->randGenerator.GenerateUint32();
}
}
trackContext.tagState.fragmentTags = item.tagState.fragmentTags;
CClipKey lastClipKey;
CSequencerTrack* pSeqTrack = node->GetTrackForParameter(SEQUENCER_PARAM_ANIMLAYER, 0);
if (pSeqTrack)
{
const int numKeys = pSeqTrack->GetNumKeys();
if (numKeys > 0)
{
pSeqTrack->GetKey(numKeys - 1, &lastClipKey);
}
}
FragmentID installFragID = item.fragment;
const float fragmentTime = item.time - lastTime; // how much time has passed relative to the last fragment's insertion time, so 'fragment time'
SBlendQuery blendQuery;
blendQuery.fragmentFrom = lastfragment;
blendQuery.fragmentTo = installFragID;
blendQuery.tagStateFrom = lastTagState;
blendQuery.tagStateTo = fragQuery.tagState;
blendQuery.fragmentTime = fragmentTime;
blendQuery.prevNormalisedTime = blendQuery.normalisedTime = lastClipKey.ConvertTimeToNormalisedTime(time);
blendQuery.additionalTags = additionalTags;
blendQuery.SetFlag(SBlendQuery::fromInstalled, lastPrimaryInstall);
blendQuery.SetFlag(SBlendQuery::toInstalled, primaryInstall);
blendQuery.SetFlag(SBlendQuery::higherPriority, item.trumpsPrevious);
blendQuery.SetFlag(SBlendQuery::noTransitions, !lastPrimaryInstall);
blendQuery.forceBlendUid = m_forcedBlendUid;
SFragmentSelection fragmentSelection;
SFragmentData fragData;
const bool hasFragment = trackContext.context->database->Query(fragData, blendQuery, item.fragOptionIdxSel, trackContext.context->animSet, &fragmentSelection);
MannUtils::AdjustFragDataForVEGs(fragData, *trackContext.context, eMEM_TransitionEditor, motionParams);
SBlendQueryResult blend1, blend2;
if (lastPrimaryInstall)
{
trackContext.context->database->FindBestBlends(blendQuery, blend1, blend2);
}
const SFragmentBlend* pFirstBlend = blend1.pFragmentBlend;
const bool hasTransition = (pFirstBlend != NULL);
//ADD STUFF
float blendStartTime = 0.0f; // in 'track time'
float blendSelectTime = 0.0f; // in 'track time'
float transitionStartTime = m_fragmentHistory->m_history.m_startTime;
float cycleIncrement = 0.0f;
if (rootScope == scopeID)
{
if (!item.trumpsPrevious)
{
// by default the blendStartTime is at the 'end' of the previous fragment
// (for oneshots lastFragmentDuration is at the end of the fragment,
// for looping frags it's at the end of the next-to-last clip)
blendStartTime = lastTime + lastFragmentDuration;
if (hasTransition)
{
if (pFirstBlend->flags & SFragmentBlend::Cyclic)
{
// In a cyclic transition treat selectTime as normalised time
// (we assume it's in the first cycle here and adjust it lateron in the CycleLocked case)
blendSelectTime = lastClipKey.ConvertUnclampedNormalisedTimeToTime(pFirstBlend->selectTime);
if (pFirstBlend->flags & SFragmentBlend::CycleLocked)
{
// Treat the startTime as normalised time.
// Figure out which cycle we are currently in, and move
// startTime & selectTime into the same cycle.
blendStartTime = lastClipKey.ConvertUnclampedNormalisedTimeToTime(pFirstBlend->startTime);
const float lastPrimeClipDuration = lastClipKey.GetOneLoopDuration();
for (; blendStartTime + cycleIncrement <= time; cycleIncrement += lastPrimeClipDuration)
{
;
}
if (blendSelectTime + cycleIncrement > time)
{
cycleIncrement = max(cycleIncrement - lastPrimeClipDuration, 0.0f);
}
blendStartTime += cycleIncrement;
blendSelectTime += cycleIncrement;
}
}
else
{
blendStartTime += pFirstBlend->startTime;
blendSelectTime = lastTime + pFirstBlend->selectTime;
}
transitionStartTime = pFirstBlend->startTime;
}
}
item.startTime = blendStartTime + fragData.duration[0]; // in 'track time' (duration[0] should probably be the total time of the transition instead)
}
else
{
blendStartTime = item.startTime - fragData.duration[0];
}
const float insertionTime = max(time, blendStartTime); // in 'track time'
float lastInsertedClipEndTime = 0.0f;
const bool isLooping = MannUtils::InsertClipTracksToNode(node, fragData, insertionTime, nextTime, lastInsertedClipEndTime, trackContext);
maxTime = max(maxTime, lastInsertedClipEndTime);
float firstBlendDuration = 0.0f;
bool foundReferenceBlend = false;
if (fragData.animLayers.size() > 0)
{
const uint32 numClips = fragData.animLayers[0].size();
for (uint32 c = 0; c < numClips; c++)
{
const SAnimClip& animClip = fragData.animLayers[0][c];
if (animClip.part != animClip.blendPart)
{
firstBlendDuration = animClip.blend.duration;
foundReferenceBlend = true;
}
}
}
if ((fragData.procLayers.size() > 0) && !foundReferenceBlend)
{
const uint32 numClips = fragData.procLayers[0].size();
for (uint32 c = 0; c < numClips; c++)
{
const SProceduralEntry& procClip = fragData.procLayers[0][c];
if (procClip.part != procClip.blendPart)
{
firstBlendDuration = procClip.blend.duration;
foundReferenceBlend = true;
}
}
}
float transitionTime = insertionTime;
const float transitionClipEffectiveStartTime = lastClipKey.GetEffectiveAssetStartTime();
const float transitionLastClipDuration = lastClipKey.GetOneLoopDuration();
int partID = 0;
if (blend1.pFragmentBlend)
{
const float duration = fragData.duration[partID];
const int id = propsTrack->CreateKey(transitionTime);
CTransitionPropertyKey transitionKey;
propsTrack->GetKey(id, &transitionKey);
transitionKey.duration = duration;
if (!blend2.pFragmentBlend)
{
transitionKey.duration += firstBlendDuration;
}
transitionKey.blend = blend1;
transitionKey.prop = CTransitionPropertyKey::eTP_Transition;
transitionKey.prevClipStart = lastTime;
transitionKey.prevClipDuration = transitionLastClipDuration;
transitionKey.tranFlags = blend1.pFragmentBlend->flags;
transitionKey.toHistoryItem = h;
transitionKey.toFragIndex = partID;
transitionKey.sharedId = 0;
propsTrack->SetKey(id, &transitionKey);
const int idSelect = propsTrack->CreateKey(blendSelectTime);
CTransitionPropertyKey selectKey;
propsTrack->GetKey(idSelect, &selectKey);
selectKey.blend = blend1;
selectKey.prop = CTransitionPropertyKey::eTP_Select;
selectKey.refTime = lastTime;
selectKey.prevClipStart = lastTime;
selectKey.prevClipDuration = transitionLastClipDuration;
selectKey.tranFlags = blend1.pFragmentBlend->flags;
selectKey.toHistoryItem = h;
selectKey.toFragIndex = partID;
selectKey.sharedId = 0;
propsTrack->SetKey(idSelect, &selectKey);
CTransitionPropertyKey startKey;
const int idStart = propsTrack->CreateKey(cycleIncrement + lastTime + lastFragmentDuration + transitionStartTime);
propsTrack->GetKey(idStart, &startKey);
startKey.blend = blend1;
startKey.prop = CTransitionPropertyKey::eTP_Start;
startKey.refTime = lastTime + lastFragmentDuration;
startKey.duration = transitionTime - startKey.time;
startKey.prevClipStart = lastTime;
startKey.prevClipDuration = transitionLastClipDuration;
startKey.tranFlags = blend1.pFragmentBlend->flags;
startKey.toHistoryItem = h;
startKey.toFragIndex = partID;
startKey.sharedId = 0;
propsTrack->SetKey(idStart, &startKey);
transitionTime += duration;
++partID;
}
if (blend2.pFragmentBlend)
{
const float duration = fragData.duration[partID];
const int id = propsTrack->CreateKey(transitionTime);
CTransitionPropertyKey transitionKey;
propsTrack->GetKey(id, &transitionKey);
transitionKey.duration = duration + firstBlendDuration;
transitionKey.blend = blend2;
transitionKey.prop = CTransitionPropertyKey::eTP_Transition;
transitionKey.prevClipStart = lastTime;
transitionKey.prevClipDuration = transitionLastClipDuration;
transitionKey.tranFlags = blend2.pFragmentBlend->flags;
transitionKey.toHistoryItem = h;
transitionKey.toFragIndex = partID;
transitionKey.sharedId = 1;
propsTrack->SetKey(id, &transitionKey);
const int idSelect = propsTrack->CreateKey(blendSelectTime);
CTransitionPropertyKey selectKey;
propsTrack->GetKey(idSelect, &selectKey);
selectKey.blend = blend2;
selectKey.prop = CTransitionPropertyKey::eTP_Select;
selectKey.refTime = lastTime;
selectKey.prevClipStart = lastTime;
selectKey.prevClipDuration = transitionLastClipDuration;
selectKey.tranFlags = blend2.pFragmentBlend->flags;
selectKey.toHistoryItem = h;
selectKey.toFragIndex = partID;
selectKey.sharedId = 1;
propsTrack->SetKey(idSelect, &selectKey);
const int idStart = propsTrack->CreateKey(cycleIncrement + lastTime + lastFragmentDuration + transitionStartTime);
CTransitionPropertyKey startKey;
propsTrack->GetKey(idStart, &startKey);
startKey.blend = blend2;
startKey.prop = CTransitionPropertyKey::eTP_Start;
startKey.refTime = lastTime + lastFragmentDuration;
startKey.duration = transitionTime - startKey.time;
startKey.prevClipStart = lastTime;
startKey.prevClipDuration = transitionLastClipDuration;
startKey.tranFlags = blend2.pFragmentBlend->flags;
startKey.toHistoryItem = h;
startKey.toFragIndex = partID;
startKey.sharedId = 1;
propsTrack->SetKey(idStart, &startKey);
transitionTime += duration;
++partID;
}
lastFragmentDuration = ((fragData.duration[partID] + transitionTime) - insertionTime);
const float fragmentClipDuration = lastInsertedClipEndTime - insertionTime;
for (int i = 0; i < numFragKeys; i++)
{
CFragmentKey fragKey;
fragTrack->GetKey(i, &fragKey);
if (fragKey.historyItem == trackContext.historyItem)
{
const float duration = fragData.duration[partID];
fragKey.transitionTime = firstBlendDuration;
fragKey.tagState = fragmentSelection.tagState;
fragKey.tagStateFull = fragQuery.tagState;
fragKey.context = trackContext.context;
fragKey.clipDuration = fragmentClipDuration;
fragKey.tranStartTime = blendStartTime;
fragKey.hasFragment = hasFragment;
fragKey.isLooping = isLooping;
fragKey.scopeMask = item.installedScopeMask;
fragKey.fragIndex = partID;
fragKey.tranStartTimeValue = transitionStartTime;
fragTrack->SetKey(i, &fragKey);
}
}
lastPrimaryInstall = primaryInstall;
lastfragment = installFragID;
lastTagState = fragQuery.tagState;
lastTime = insertionTime;
}
}
}
}
// Reselect the new keys
for (uint32 trackID = 0; trackID < selectedKeys.size(); ++trackID)
{
CSequencerTrack* pTrack = node->GetTrackByIndex(trackID);
if (pTrack == NULL)
{
continue;
}
// Sort keys
pTrack->SortKeys();
// Restore selection
for (uint32 keyID = 0; keyID < selectedKeys[trackID].size(); ++keyID)
{
pTrack->SelectKey(selectedKeys[trackID][keyID], true);
}
}
return maxTime;
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnTimeChanged(float fTime)
{
m_sequencePlayback->SetTime(fTime);
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::PopulateAllClipTracks()
{
if (!m_fragmentHistory.get())
{
return;
}
m_contexts->viewData[eMEM_TransitionEditor].m_pAnimContext->randGenerator.seed(m_seed);
uint32 numScopes = m_contexts->m_scopeData.size();
float maxTime = TRANSITION_MIN_TIME_RANGE;
for (uint32 i = 0; i < numScopes; i++)
{
CSequencerNode* animNode = m_contexts->m_scopeData[i].animNode[eMEM_TransitionEditor];
if (animNode)
{
const float maxTimeCur = PopulateClipTracks(animNode, i);
maxTime = max(maxTime, maxTimeCur);
}
}
maxTime += 1.0f;
maxTime = max(maxTime, (m_fragmentHistory->m_history.m_endTime - m_fragmentHistory->m_history.m_firstTime));
Range timeRange(0.0f, maxTime);
m_sequence->SetTimeRange(timeRange);
m_ui->m_wndTrackPanel->SetTimeRange(0.0f, maxTime);
m_fMaxTime = maxTime;
//--- Create locators
m_modelViewport->ClearLocators();
const CFragmentHistory& history = m_fragmentHistory->m_history;
const uint32 numHistoryItems = history.m_items.size();
for (uint32 h = 0; h < numHistoryItems; h++)
{
const CFragmentHistory::SHistoryItem& item = history.m_items[h];
if ((item.type == CFragmentHistory::SHistoryItem::Param) && item.isLocation)
{
m_modelViewport->AddLocator(h, item.paramName.toLatin1().data(), item.param.value);
}
}
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::InsertContextHistoryItems(const SScopeData& scopeData, const float keyTime)
{
for (uint32 h = 0; h < m_contextHistory->m_history.m_items.size(); h++)
{
const CFragmentHistory::SHistoryItem& item = m_contextHistory->m_history.m_items[h];
if (item.type == CFragmentHistory::SHistoryItem::Fragment)
{
ActionScopes scopeMask = item.installedScopeMask;
scopeMask &= scopeData.mannContexts->potentiallyActiveScopes;
uint32 rootScope = ACTION_SCOPES_ALL;
for (uint32 i = 0; i <= scopeData.scopeID; i++)
{
if (((1 << i) & scopeMask) != 0)
{
rootScope = i;
break;
}
}
if (scopeData.scopeID == rootScope)
{
CFragmentHistory::SHistoryItem newItem(item);
newItem.time = keyTime;
m_fragmentHistory->m_history.m_items.push_back(newItem);
}
}
}
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::SetUIFromHistory()
{
if (!m_fragmentHistory.get())
{
return;
}
float transitionStartTime = 3.0f; // Default transition start time
uint32 numScopes = m_contexts->m_scopeData.size();
m_sequence->RemoveAll();
m_fragmentHistory->m_tracks.clear();
if (m_contexts->m_controllerDef)
{
CRootNode* rootNode = new CRootNode(m_sequence.get(), *m_contexts->m_controllerDef);
rootNode->SetName("Globals");
CTagTrack* tagTrack = (CTagTrack*)rootNode->CreateTrack(SEQUENCER_PARAM_TAGS);
m_sequence->AddNode(rootNode);
CParamTrack* paramTrack = (CParamTrack*)rootNode->CreateTrack(SEQUENCER_PARAM_PARAMS);
m_fragmentHistory->m_tracks.push_back(tagTrack);
m_fragmentHistory->m_tracks.push_back(paramTrack);
const uint32 numHistoryItems = m_fragmentHistory->m_history.m_items.size();
for (uint32 h = 0; h < numHistoryItems; h++)
{
const CFragmentHistory::SHistoryItem& item = m_fragmentHistory->m_history.m_items[h];
if (item.type == CFragmentHistory::SHistoryItem::Tag)
{
float time = item.time - m_fragmentHistory->m_history.m_firstTime;
int newKeyID = tagTrack->CreateKey(time);
CTagKey newKey;
newKey.time = time;
newKey.tagState = item.tagState.globalTags;
tagTrack->SetKey(newKeyID, &newKey);
if (newKeyID > 0)
{
// Store this tag's time as the start of the transition, there should only ever be two tags
transitionStartTime = time;
}
}
else if (item.type == CFragmentHistory::SHistoryItem::Param)
{
float time = item.time - m_fragmentHistory->m_history.m_firstTime;
int newKeyID = paramTrack->CreateKey(time);
CParamKey newKey;
newKey.time = time;
newKey.name = item.paramName;
newKey.parameter = item.param;
newKey.isLocation = item.isLocation;
newKey.historyItem = h;
paramTrack->SetKey(newKeyID, &newKey);
}
}
}
for (uint32 i = 0; i < numScopes; i++)
{
SScopeData& scopeData = m_contexts->m_scopeData[i];
if (!(m_scopeMaskFrom & (1 << i)))
{
InsertContextHistoryItems(scopeData, 0.0f);
}
else if (!(m_scopeMaskTo & (1 << i))) // If scope was in "from" then it is already applied - we don't want duplicates
{
InsertContextHistoryItems(scopeData, transitionStartTime);
}
CScopeNode* animNode = new CScopeNode(m_sequence.get(), &scopeData, eMEM_TransitionEditor);
m_sequence->AddNode(animNode);
if (scopeData.context[eMEM_TransitionEditor])
{
animNode->SetName((scopeData.name + " (" + scopeData.context[eMEM_TransitionEditor]->name + ")").toLatin1().data());
}
else
{
animNode->SetName((scopeData.name + " (none)").toLatin1().data());
}
float maxTime = TRANSITION_MIN_TIME_RANGE;
MannUtils::InsertFragmentTrackFromHistory(animNode, *m_fragmentHistory, 0.0f, 0.0f, maxTime, scopeData);
scopeData.fragTrack[eMEM_TransitionEditor] = (CFragmentTrack*)animNode->GetTrackForParameter(SEQUENCER_PARAM_FRAGMENTID);
scopeData.animNode[eMEM_TransitionEditor] = animNode;
}
PopulateAllClipTracks();
m_ui->m_wndNodes->SetSequence(m_sequence.get());
if (m_sequencePlayback)
{
m_sequencePlayback->SetTime(m_fTime);
}
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::SetHistoryFromUI()
{
if (!m_fragmentHistory.get())
{
return;
}
MannUtils::GetHistoryFromTracks(*m_fragmentHistory);
m_fragmentHistory->m_history.UpdateScopeMasks(m_contexts, m_tagState);
Range range = m_sequence->GetTimeRange();
m_fragmentHistory->m_history.m_startTime = range.start;
m_fragmentHistory->m_history.m_endTime = range.end;
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnUpdateTV(bool forceUpdate)
{
IMannequin& mannequinSys = gEnv->pGame->GetIGameFramework()->GetMannequinInterface();
bool anyChanges = false;
const uint32 numScopes = m_contexts->m_scopeData.size();
for (uint32 i = 0; i < numScopes; i++)
{
uint32 clipChangeCount = 0;
uint32 fragChangeCount = 0;
uint32 propChangeCount = 0;
const SScopeData& scopeData = m_contexts->m_scopeData[i];
CFragmentTrack* pFragTrack = NULL;
CTransitionPropertyTrack* pPropsTrack = NULL;
if (scopeData.animNode[eMEM_TransitionEditor])
{
const uint32 numTracks = scopeData.animNode[eMEM_TransitionEditor]->GetTrackCount();
for (uint32 t = 0; t < numTracks; t++)
{
CSequencerTrack* seqTrack = scopeData.animNode[eMEM_TransitionEditor]->GetTrackByIndex(t);
switch (seqTrack->GetParameterType())
{
case SEQUENCER_PARAM_ANIMLAYER:
case SEQUENCER_PARAM_PROCLAYER:
clipChangeCount += seqTrack->GetChangeCount();
break;
case SEQUENCER_PARAM_FRAGMENTID:
pFragTrack = (CFragmentTrack*)seqTrack;
fragChangeCount = pFragTrack->GetChangeCount();
break;
case SEQUENCER_PARAM_TRANSITIONPROPS:
pPropsTrack = (CTransitionPropertyTrack*)seqTrack;
propChangeCount = pPropsTrack->GetChangeCount();
break;
}
}
}
// If there have been changes this time, take note
if (forceUpdate || clipChangeCount || fragChangeCount || propChangeCount)
{
anyChanges = true;
}
//--- Transition properties have changed, rebuild any transitions
if ((clipChangeCount || propChangeCount) && pPropsTrack)
{
std::vector<int> overriddenBlends;
const int numKeys = pPropsTrack->GetNumKeys();
for (uint32 k = 0; k < numKeys; ++k)
{
CTransitionPropertyKey key;
pPropsTrack->GetKey(k, &key);
if (std::find(overriddenBlends.begin(), overriddenBlends.end(), key.sharedId) != overriddenBlends.end())
{
// Have hit a key pointing at this blend which is overriding the other properties
continue;
}
const SFragmentBlend* blend = pPropsTrack->GetBlendForKey(k);
if (blend)
{
bool updated = false;
SFragmentBlend blendCopy = *blend;
if (propChangeCount)
{
if (key.overrideProps)
{
// This key was updated from the properties panel
// Copy properties from it then ignore other keys for the same blend
updated = true;
overriddenBlends.push_back(key.sharedId);
key.overrideProps = false;
// Copy values directly from the key
blendCopy.flags = key.tranFlags;
blendCopy.selectTime = max(0.f, key.overrideSelectTime);
if (key.tranFlags & SFragmentBlend::Cyclic)
{
blendCopy.startTime = key.overrideStartTime - (float)(int)key.overrideStartTime;
}
else
{
blendCopy.startTime = min(0.f, key.overrideStartTime);
}
CryLogAlways("Set times from GUI: %f %f", blendCopy.selectTime, blendCopy.startTime);
}
else if (key.prop == CTransitionPropertyKey::eTP_Select)
{
// This is a select time key, calculate new select time from the key position
updated = true;
if (key.tranFlags & SFragmentBlend::Cyclic)
{
//clipSelectTime = (fragKey.tranSelectTime - fragKey.tranLastClipEffectiveStart) / fragKey.tranLastClipDuration;
blendCopy.selectTime = (key.time - key.prevClipStart) / key.prevClipDuration;
CryLogAlways("Pre-clip select time: %f", blendCopy.selectTime);
blendCopy.selectTime -= (float)(int)blendCopy.selectTime;
CryLogAlways("Set select time from key %f (%f - %f) / %f", blendCopy.selectTime, key.time, key.prevClipStart, key.prevClipDuration);
}
else
{
blendCopy.selectTime = key.time - key.prevClipStart;
CryLogAlways("Set select time from key %f (%f - %f)", blendCopy.selectTime, key.time, key.prevClipStart);
}
}
else if (key.prop == CTransitionPropertyKey::eTP_Start)
{
// This is a start time key, calculate new start time from the key position
updated = true;
if (key.tranFlags & SFragmentBlend::Cyclic)
{
//clipStartTime = (tranStartTime - fragKey.tranLastClipEffectiveStart) / fragKey.tranLastClipDuration;
blendCopy.startTime = (key.time - key.refTime) / key.prevClipDuration;
CryLogAlways("Pre-clip start time: %f", blendCopy.startTime);
blendCopy.startTime -= (float)(int)blendCopy.startTime;
CryLogAlways("Set start time from key %f (%f - %f) / %f", blendCopy.startTime, key.refTime, key.time, key.prevClipDuration);
}
else
{
blendCopy.startTime = min(0.0f, key.time - key.refTime);
CryLogAlways("Set start time from key %f (%f - %f)", blendCopy.startTime, key.time, key.refTime);
}
}
}
CFragment fragmentNew;
if (clipChangeCount && key.prop == CTransitionPropertyKey::eTP_Transition)
{
MannUtils::GetFragmentFromClipTracks(fragmentNew, scopeData.animNode[eMEM_TransitionEditor], key.toHistoryItem, key.time, key.toFragIndex);
blendCopy.pFragment = &fragmentNew;
updated = true;
}
if (updated)
{
pPropsTrack->UpdateBlendForKey(k, blendCopy);
}
}
CRY_ASSERT(blend);
}
}
//--- Clip has changed, rebuild any transition fragments
if ((clipChangeCount || fragChangeCount) && pFragTrack)
{
const int numKeys = pFragTrack->GetNumKeys();
float lastTime = 0.0f;
for (uint32 k = 0; k < numKeys; k++)
{
CFragmentKey fragKey;
pFragTrack->GetKey(k, &fragKey);
if (fragKey.transition)
{
CRY_ASSERT(fragKey.context);
bool alreadyDoneTransition = false;
if (fragKey.sharedID != 0)
{
for (uint32 s = 0, mask = 1; s < i; s++, mask <<= 1)
{
if (fragKey.scopeMask & mask)
{
alreadyDoneTransition = true;
break;
}
}
}
const float tranStartTime = fragKey.time;
int prevKeyID = pFragTrack->GetPrecedingFragmentKey(k, true);
const bool hasPrevClip = (prevKeyID >= 0);
const SFragmentBlend* pFragmentBlend = fragKey.context->database->GetBlend(fragKey.tranFragFrom, fragKey.tranFragTo, fragKey.tranTagFrom, fragKey.tranTagTo, fragKey.tranBlendUid);
if (pFragmentBlend)
{
float clipSelectTime, clipStartTime;
if (hasPrevClip && !alreadyDoneTransition)
{
CFragmentKey prevFragKey;
pFragTrack->GetKey(prevKeyID, &prevFragKey);
if (fragKey.tranFlags & SFragmentBlend::Cyclic)
{
clipSelectTime = (fragKey.tranSelectTime - fragKey.tranLastClipEffectiveStart) / fragKey.tranLastClipDuration;
clipStartTime = (tranStartTime - fragKey.tranLastClipEffectiveStart) / fragKey.tranLastClipDuration;
clipSelectTime -= (float)(int)clipSelectTime;
clipStartTime -= (float)(int)clipStartTime;
}
else
{
clipSelectTime = fragKey.tranSelectTime - prevFragKey.time;
clipStartTime = min(tranStartTime - prevFragKey.clipDuration - max(prevFragKey.tranStartTime, prevFragKey.time), 0.0f);
}
}
else
{
clipSelectTime = pFragmentBlend->selectTime;
clipStartTime = pFragmentBlend->startTime;
}
clipStartTime -= fragKey.tranStartTimeRelative;
if (clipChangeCount)
{
CFragment fragmentNew;
MannUtils::GetFragmentFromClipTracks(fragmentNew, scopeData.animNode[eMEM_TransitionEditor], fragKey.historyItem, tranStartTime, fragKey.fragIndex);
SFragmentBlend fragBlend;
fragBlend.pFragment = &fragmentNew;
fragBlend.enterTime = 0.0f;
fragBlend.selectTime = clipSelectTime;
fragBlend.startTime = clipStartTime;
fragBlend.flags = fragKey.tranFlags;
MannUtils::GetMannequinEditorManager().SetBlend(fragKey.context->database, fragKey.tranFragFrom, fragKey.tranFragTo, fragKey.tranTagFrom, fragKey.tranTagTo, fragKey.tranBlendUid, fragBlend);
CMannequinDialog& mannDialog = *CMannequinDialog::GetCurrentInstance();
mannDialog.TransitionBrowser()->Refresh();
}
else if (hasPrevClip)
{
SFragmentBlend fragBlendNew = *pFragmentBlend;
fragBlendNew.selectTime = clipSelectTime;
fragBlendNew.startTime = clipStartTime;
fragBlendNew.flags = fragKey.tranFlags;
MannUtils::GetMannequinEditorManager().SetBlend(fragKey.context->database, fragKey.tranFragFrom, fragKey.tranFragTo, fragKey.tranTagFrom, fragKey.tranTagTo, fragKey.tranBlendUid, fragBlendNew);
CMannequinDialog& mannDialog = *CMannequinDialog::GetCurrentInstance();
mannDialog.TransitionBrowser()->Refresh();
}
}
}
}
}
}
if (anyChanges)
{
SetHistoryFromUI();
PopulateAllClipTracks();
}
if (m_sequence.get())
{
m_ui->m_wndNodes->SetSequence(m_sequence.get());
}
if (m_sequencePlayback)
{
m_sequencePlayback->SetTime(m_fTime, true);
}
//--- Reset the track based change counts
const uint32 numNodes = m_sequence->GetNodeCount();
for (uint32 i = 0; i < numNodes; i++)
{
CSequencerNode* seqNode = m_sequence->GetNode(i);
const uint32 numTracks = seqNode->GetTrackCount();
for (uint32 t = 0; t < numTracks; t++)
{
CSequencerTrack* seqTrack = seqNode->GetTrackByIndex(t);
seqTrack->ResetChangeCount();
}
}
}
void CTransitionEditorPage::LoadSequence(const int scopeContextIdx, const FragmentID fromID, const FragmentID toID, const SFragTagState fromFragTag, const SFragTagState toFragTag, const SFragmentBlendUid blendUid)
{
m_fromID = fromID;
m_toID = toID;
m_fromFragTag = fromFragTag;
m_toFragTag = toFragTag;
m_scopeMaskFrom = m_contexts->m_controllerDef->GetScopeMask(fromID, fromFragTag);
m_scopeMaskTo = m_contexts->m_controllerDef->GetScopeMask(toID, toFragTag);
m_forcedBlendUid = blendUid;
// load the blend into the history
m_fragmentHistory->m_history.LoadSequence(scopeContextIdx, fromID, toID, fromFragTag, toFragTag, blendUid, m_tagState);
// this sets the keys onto each scope (track?)
m_fragmentHistory->m_history.UpdateScopeMasks(m_contexts, m_tagState);
if (m_sequencePlayback)
{
m_sequencePlayback->SetTime(0.0f);
}
// this goes away and populates everything like magic
SetUIFromHistory();
m_ui->m_wndNodes->SetSequence(m_sequence.get());
m_ui->m_wndKeyProperties->SetSequence(m_sequence.get());
PopulateTagList();
OnUpdateTV(true);
SelectFirstKey();
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::ClearSequence()
{
if (m_sequencePlayback != NULL)
{
m_sequencePlayback->SetTime(0.0f);
}
m_ui->m_wndNodes->SetSequence(NULL);
m_ui->m_wndKeyProperties->SetSequence(NULL);
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnSequenceRestart(float newTime)
{
m_modelViewport->OnSequenceRestart(newTime);
m_bRestartingSequence = true;
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::PopulateTagList()
{
// Make all tags that are used in the transition (from or to) non-zero
SFragTagState transitionTags;
transitionTags.globalTags = m_fromFragTag.globalTags | m_toFragTag.globalTags;
transitionTags.fragmentTags = m_fromFragTag.fragmentTags | m_toFragTag.fragmentTags;
// Store the current preview tag state
const CTagDefinition& tagDefs = m_contexts->m_controllerDef->m_tags;
const TagState globalTags = m_contexts->viewData[eMEM_TransitionEditor].m_pAnimContext->state.GetMask();
SFragTagState usedTags(TAG_STATE_EMPTY, TAG_STATE_EMPTY);
// Subtract scope tags from the transition tags
const uint32 numScopes = m_contexts->m_controllerDef->m_scopeDef.size();
SFragTagState queryGlobalTags = transitionTags;
for (uint32 i = 0; i < numScopes; i++)
{
queryGlobalTags.globalTags = m_contexts->m_controllerDef->m_tags.GetDifference(queryGlobalTags.globalTags, m_contexts->m_controllerDef->m_scopeDef[i].additionalTags);
}
// Determine which tags are used in the history
const CFragmentHistory& history = m_fragmentHistory->m_history;
const uint32 numItems = history.m_items.size();
for (uint32 i = 0; i < numItems; i++)
{
const CFragmentHistory::SHistoryItem& item = history.m_items[i];
FragmentID fragID = item.fragment;
if (fragID != FRAGMENT_ID_INVALID)
{
const uint32 numContexts = m_contexts->m_contextData.size();
for (uint32 c = 0; c < numContexts; c++)
{
const SScopeContextData& context = m_contexts->m_contextData[c];
if (context.database)
{
SFragTagState contextUsedTags;
context.database->QueryUsedTags(fragID, queryGlobalTags, contextUsedTags);
usedTags.globalTags = m_contexts->m_controllerDef->m_tags.GetUnion(usedTags.globalTags, contextUsedTags.globalTags);
}
}
}
}
// Enable tags that are used in the history but not forced by the transition tags
TagState enabledControls = m_contexts->m_controllerDef->m_tags.GetDifference(usedTags.globalTags, transitionTags.globalTags, true);
// Update the properties pane with the relevant tags
m_tagVars->DeleteAllVariables();
m_tagControls.Init(m_tagVars, m_contexts->viewData[eMEM_TransitionEditor].m_pAnimContext->state.GetDef(), enabledControls);
RefreshTagsPanel();
// set this up with the initial values we've already got
SFragTagState fragTagState;
fragTagState.globalTags = m_tagState;
SetTagStateOnCtrl(fragTagState);
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::RefreshTagsPanel()
{
m_ui->m_tagsPanel->DeleteVars();
m_ui->m_tagsPanel->SetVarBlock(m_tagVars.get(), functor(*this, &CTransitionEditorPage::OnInternalVariableChange));
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnTagRenamed(const CTagDefinition* tagDef, TagID tagID, const QString& name)
{
if (tagDef == &m_contexts->viewData[eMEM_TransitionEditor].m_pAnimContext->state.GetDef())
{
m_tagControls.RenameTag(tagID, name);
RefreshTagsPanel();
}
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnTagRemoved(const CTagDefinition* tagDef, TagID tagID)
{
if (tagDef == &m_contexts->viewData[eMEM_TransitionEditor].m_pAnimContext->state.GetDef())
{
m_tagControls.RemoveTag(m_tagVars, tagID);
RefreshTagsPanel();
}
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnTagAdded(const CTagDefinition* tagDef, const QString& name)
{
if (tagDef == &m_contexts->viewData[eMEM_TransitionEditor].m_pAnimContext->state.GetDef())
{
m_tagControls.AddTag(m_tagVars, name);
RefreshTagsPanel();
}
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::OnInternalVariableChange(IVariable* pVar)
{
if (!m_bRefreshingTagCtrl)
{
SFragTagState tagState = GetTagStateFromCtrl();
const uint32 numContexts = m_contexts->m_controllerDef->m_scopeContexts.GetNum();
for (uint32 i = 0; i < numContexts; i++)
{
const SScopeContextData* contextData = m_contexts->GetContextDataForID(tagState.globalTags, i, eMEM_TransitionEditor);
if (contextData)
{
const bool res = CMannequinDialog::GetCurrentInstance()->EnableContextData(eMEM_TransitionEditor, contextData->dataID);
if (!res)
{
// Write out error msg via MessageBox
QMessageBox::critical(this, tr("Mannequin Error"), tr("Cannot set that value as it has no parent context.\nIs it a scope/barrel attachment that needs a gun tag setting first?"));
// reset the displayed info?
CMannequinDialog::GetCurrentInstance()->ClearContextData(eMEM_TransitionEditor, i);
tagState.globalTags = m_tagState;
SetTagStateOnCtrl(tagState);
}
}
else
{
CMannequinDialog::GetCurrentInstance()->ClearContextData(eMEM_TransitionEditor, i);
}
}
SetUIFromHistory();
m_tagState = tagState.globalTags;
m_contexts->viewData[eMEM_TransitionEditor].m_pAnimContext->state = tagState.globalTags;
OnUpdateTV();
}
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::ResetForcedBlend()
{
m_forcedBlendUid = SFragmentBlendUid();
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::SelectFirstKey()
{
if (!m_ui->m_wndTrackPanel->SelectFirstKey(SEQUENCER_PARAM_TRANSITIONPROPS))
{
if (!m_ui->m_wndTrackPanel->SelectFirstKey(SEQUENCER_PARAM_ANIMLAYER))
{
if (!m_ui->m_wndTrackPanel->SelectFirstKey(SEQUENCER_PARAM_PROCLAYER))
{
m_ui->m_wndTrackPanel->SelectFirstKey();
}
}
}
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::SetTagStateOnCtrl(const SFragTagState& tagState)
{
m_bRefreshingTagCtrl = true;
m_tagControls.Set(tagState.globalTags);
m_bRefreshingTagCtrl = false;
}
//////////////////////////////////////////////////////////////////////////
SFragTagState CTransitionEditorPage::GetTagStateFromCtrl() const
{
SFragTagState ret;
ret.globalTags = m_tagControls.Get();
return ret;
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::InitialiseToPreviewFile(const XmlNodeRef& xmlSequenceRoot)
{
ResetForcedBlend();
m_modelViewport->SetActionController(m_contexts->viewData[eMEM_TransitionEditor].m_pActionController);
m_contextHistory.reset(new SFragmentHistoryContext(*m_contexts->viewData[eMEM_TransitionEditor].m_pActionController));
m_contextHistory->m_history.LoadSequence(xmlSequenceRoot);
m_contextHistory->m_history.UpdateScopeMasks(m_contexts, m_tagState);
m_fragmentHistory.reset(new SFragmentHistoryContext(*m_contexts->viewData[eMEM_TransitionEditor].m_pActionController));
m_tagState = m_contexts->viewData[eMEM_TransitionEditor].m_pAnimContext->state.GetMask();
m_fMaxTime = m_fragmentHistory->m_history.m_endTime - m_fragmentHistory->m_history.m_firstTime;
m_sequencePlayback = new CFragmentSequencePlayback(m_fragmentHistory->m_history, *m_contexts->viewData[eMEM_TransitionEditor].m_pActionController, eMEM_TransitionEditor);
//m_sequencePlayback = new CActionSequencePlayback(ACTPreviewFileION_SCOPES_ALL, 0, 0, m_fragmentHistory->m_history, true);
//m_sequencePlayback->SetMaxTime(m_fMaxTime);
//m_contexts->viewData[eMEM_TransitionEditor].m_pActionController->Queue(m_sequencePlayback);
SetUIFromHistory();
PopulateTagList();
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::SetTagState(const TagState& tagState)
{
const CTagDefinition& tagDef = m_contexts->m_controllerDef->m_tags;
TagState tsNew = tagDef.GetUnion(m_tagState, tagState);
m_contexts->viewData[eMEM_TransitionEditor].m_pAnimContext->state = tsNew;
//--- Updated associated contexts
const uint32 numContexts = m_contexts->m_controllerDef->m_scopeContexts.GetNum();
for (uint32 i = 0; i < numContexts; i++)
{
const SScopeContextData* contextData = m_contexts->GetContextDataForID(tsNew, i, eMEM_TransitionEditor);
if (contextData)
{
CMannequinDialog::GetCurrentInstance()->EnableContextData(eMEM_TransitionEditor, contextData->dataID);
}
else
{
CMannequinDialog::GetCurrentInstance()->ClearContextData(eMEM_TransitionEditor, i);
}
}
}
//////////////////////////////////////////////////////////////////////////
void CTransitionEditorPage::SetTime(float fTime)
{
if (m_sequencePlayback != NULL)
{
m_sequencePlayback->SetTime(fTime, true);
}
m_ui->m_wndTrackPanel->SetCurrTime(fTime, true);
}
#include <Mannequin/Controls/TransitionEditorPage.moc>
| 40.920563 | 221 | 0.560867 | [
"vector",
"model"
] |
40cf216dc8bf1a9be7845802b2c0310e505c7c2a | 29,643 | hpp | C++ | pywraps/py_custview.hpp | triumphyuan/idapython | 081b988a03b88867786ad4131269db6930637a5b | [
"BSD-3-Clause"
] | 25 | 2016-06-07T15:41:57.000Z | 2021-12-17T11:03:42.000Z | pywraps/py_custview.hpp | triumphyuan/idapython | 081b988a03b88867786ad4131269db6930637a5b | [
"BSD-3-Clause"
] | 1 | 2018-01-23T05:39:50.000Z | 2018-01-23T05:39:50.000Z | pywraps/py_custview.hpp | triumphyuan/idapython | 081b988a03b88867786ad4131269db6930637a5b | [
"BSD-3-Clause"
] | 9 | 2016-07-27T13:13:35.000Z | 2022-03-25T09:14:52.000Z | #ifndef __PYWRAPS_CUSTVIEWER__
#define __PYWRAPS_CUSTVIEWER__
//<code(py_custviewer)>
//---------------------------------------------------------------------------
// Base class for all custviewer place_t providers
class custviewer_data_t
{
public:
virtual void *get_ud() = 0;
virtual place_t *get_min() = 0;
virtual place_t *get_max() = 0;
};
//---------------------------------------------------------------------------
class cvdata_simpleline_t: public custviewer_data_t
{
private:
strvec_t lines;
simpleline_place_t pl_min, pl_max;
public:
void *get_ud()
{
return &lines;
}
place_t *get_min()
{
return &pl_min;
}
place_t *get_max()
{
return &pl_max;
}
strvec_t &get_lines()
{
return lines;
}
void set_minmax(size_t start=0, size_t end=size_t(-1))
{
if ( start == 0 && end == size_t(-1) )
{
end = lines.size();
pl_min.n = 0;
pl_max.n = end == 0 ? 0 : end - 1;
}
else
{
pl_min.n = start;
pl_max.n = end;
}
}
bool set_line(size_t nline, simpleline_t &sl)
{
if ( nline >= lines.size() )
return false;
lines[nline] = sl;
return true;
}
bool del_line(size_t nline)
{
if ( nline >= lines.size() )
return false;
lines.erase(lines.begin()+nline);
return true;
}
void add_line(simpleline_t &line)
{
lines.push_back(line);
}
void add_line(const char *str)
{
lines.push_back(simpleline_t(str));
}
bool insert_line(size_t nline, simpleline_t &line)
{
if ( nline >= lines.size() )
return false;
lines.insert(lines.begin()+nline, line);
return true;
}
bool patch_line(size_t nline, size_t offs, int value)
{
if ( nline >= lines.size() )
return false;
qstring &L = lines[nline].line;
L[offs] = (uchar) value & 0xFF;
return true;
}
const size_t to_lineno(place_t *pl) const
{
return ((simpleline_place_t *)pl)->n;
}
bool curline(place_t *pl, size_t *n)
{
if ( pl == NULL )
return false;
*n = to_lineno(pl);
return true;
}
simpleline_t *get_line(size_t nline)
{
return nline >= lines.size() ? NULL : &lines[nline];
}
simpleline_t *get_line(place_t *pl)
{
return pl == NULL ? NULL : get_line(((simpleline_place_t *)pl)->n);
}
const size_t count() const
{
return lines.size();
}
void clear_lines()
{
lines.clear();
set_minmax();
}
};
//---------------------------------------------------------------------------
// FIXME: This should inherit py_view_base.hpp's py_customidamemo_t,
// just like py_graph.hpp's py_graph_t does.
// There should be a way to "merge" the two mechanisms; they are similar.
class customviewer_t
{
protected:
qstring _title;
TForm *_form;
TCustomControl *_cv;
custviewer_data_t *_data;
int _features;
enum
{
HAVE_HINT = 0x0001,
HAVE_KEYDOWN = 0x0002,
HAVE_POPUP = 0x0004,
HAVE_DBLCLICK = 0x0008,
HAVE_CURPOS = 0x0010,
HAVE_CLICK = 0x0020,
HAVE_CLOSE = 0x0040
};
private:
struct cvw_popupctx_t
{
size_t menu_id;
customviewer_t *cv;
cvw_popupctx_t(): menu_id(0), cv(NULL) { }
cvw_popupctx_t(size_t mid, customviewer_t *v): menu_id(mid), cv(v) { }
};
typedef std::map<unsigned int, cvw_popupctx_t> cvw_popupmap_t;
static cvw_popupmap_t _global_popup_map;
static size_t _global_popup_id;
qstring _curline;
intvec_t _installed_popups;
static bool idaapi s_popup_menu_cb(void *ud)
{
size_t mid = (size_t)ud;
cvw_popupmap_t::iterator it = _global_popup_map.find(mid);
if ( it == _global_popup_map.end() )
return false;
PYW_GIL_GET;
return it->second.cv->on_popup_menu(it->second.menu_id);
}
static bool idaapi s_cv_keydown(
TCustomControl * /*cv*/,
int vk_key,
int shift,
void *ud)
{
PYW_GIL_GET;
customviewer_t *_this = (customviewer_t *)ud;
return _this->on_keydown(vk_key, shift);
}
// The popup menu is being constructed
static void idaapi s_cv_popup(TCustomControl * /*cv*/, void *ud)
{
PYW_GIL_GET;
customviewer_t *_this = (customviewer_t *)ud;
_this->on_popup();
}
// The user clicked
static bool idaapi s_cv_click(TCustomControl * /*cv*/, int shift, void *ud)
{
PYW_GIL_GET;
customviewer_t *_this = (customviewer_t *)ud;
return _this->on_click(shift);
}
// The user double clicked
static bool idaapi s_cv_dblclick(TCustomControl * /*cv*/, int shift, void *ud)
{
PYW_GIL_GET;
customviewer_t *_this = (customviewer_t *)ud;
return _this->on_dblclick(shift);
}
// Cursor position has been changed
static void idaapi s_cv_curpos(TCustomControl * /*cv*/, void *ud)
{
PYW_GIL_GET;
customviewer_t *_this = (customviewer_t *)ud;
_this->on_curpos_changed();
}
//--------------------------------------------------------------------------
static int idaapi s_ui_cb(void *ud, int code, va_list va)
{
// This hook gets called from the kernel. Ensure we hold the GIL.
PYW_GIL_GET;
customviewer_t *_this = (customviewer_t *)ud;
switch ( code )
{
case ui_get_custom_viewer_hint:
{
TCustomControl *viewer = va_arg(va, TCustomControl *);
place_t *place = va_arg(va, place_t *);
int *important_lines = va_arg(va, int *);
qstring &hint = *va_arg(va, qstring *);
if ( (_this->_features & HAVE_HINT) == 0 || place == NULL || _this->_cv != viewer )
return 0;
else
return _this->on_hint(place, important_lines, hint) ? 1 : 0;
}
case ui_tform_invisible:
{
TForm *form = va_arg(va, TForm *);
if ( _this->_form != form )
break;
}
// fallthrough...
case ui_term:
unhook_from_notification_point(HT_UI, s_ui_cb, _this);
_this->on_close();
_this->on_post_close();
break;
}
return 0;
}
void on_post_close()
{
init_vars();
clear_popup_menu();
}
public:
inline TForm *get_tform() { return _form; }
inline TCustomControl *get_tcustom_control() { return _cv; }
//
// All the overridable callbacks
//
// OnClick
virtual bool on_click(int /*shift*/) { return false; }
// OnDblClick
virtual bool on_dblclick(int /*shift*/) { return false; }
// OnCurorPositionChanged
virtual void on_curpos_changed() { }
// OnHostFormClose
virtual void on_close() { }
// OnKeyDown
virtual bool on_keydown(int /*vk_key*/, int /*shift*/) { return false; }
// OnPopupShow
virtual bool on_popup() { return false; }
// OnHint
virtual bool on_hint(place_t * /*place*/, int * /*important_lines*/, qstring &/*hint*/) { return false; }
// OnPopupMenuClick
virtual bool on_popup_menu(size_t menu_id) { return false; }
void init_vars()
{
_data = NULL;
_features = 0;
_curline.clear();
_cv = NULL;
_form = NULL;
}
customviewer_t()
{
init_vars();
}
~customviewer_t()
{
}
//--------------------------------------------------------------------------
void close()
{
if ( _form != NULL )
close_tform(_form, FORM_SAVE | FORM_CLOSE_LATER);
}
//--------------------------------------------------------------------------
bool set_range(
const place_t *minplace = NULL,
const place_t *maxplace = NULL)
{
if ( _cv == NULL )
return false;
set_custom_viewer_range(
_cv,
minplace == NULL ? _data->get_min() : minplace,
maxplace == NULL ? _data->get_max() : maxplace);
return true;
}
place_t *get_place(
bool mouse = false,
int *x = 0,
int *y = 0)
{
return _cv == NULL ? NULL : get_custom_viewer_place(_cv, mouse, x, y);
}
//--------------------------------------------------------------------------
bool refresh()
{
if ( _cv == NULL )
return false;
refresh_custom_viewer(_cv);
return true;
}
//--------------------------------------------------------------------------
bool refresh_current()
{
int x, y;
place_t *pl = get_place(false, &x, &y);
if ( pl == NULL )
return false;
return jumpto(pl, x, y);
}
//--------------------------------------------------------------------------
bool get_current_word(bool mouse, qstring &word)
{
// query the cursor position
int x, y;
if ( get_place(mouse, &x, &y) == NULL )
return false;
// query the line at the cursor
const char *line = get_current_line(mouse, true);
if ( line == NULL )
return false;
if ( x >= (int)strlen(line) )
return false;
// find the beginning of the word
const char *ptr = line + x;
while ( ptr > line && !qisspace(ptr[-1]) )
ptr--;
// find the end of the word
const char *begin = ptr;
ptr = line + x;
while ( !qisspace(*ptr) && *ptr != '\0' )
ptr++;
word.qclear();
word.append(begin, ptr-begin);
return true;
}
//--------------------------------------------------------------------------
const char *get_current_line(bool mouse, bool notags)
{
const char *r = get_custom_viewer_curline(_cv, mouse);
if ( r == NULL || !notags )
return r;
size_t sz = strlen(r);
if ( sz == 0 )
return r;
_curline.resize(sz + 5, '\0');
tag_remove(r, &_curline[0], sz + 1);
return _curline.c_str();
}
//--------------------------------------------------------------------------
bool is_focused()
{
return get_current_viewer() == _cv;
}
//--------------------------------------------------------------------------
bool jumpto(place_t *place, int x, int y)
{
return ::jumpto(_cv, place, x, y);
}
//--------------------------------------------------------------------------
void clear_popup_menu()
{
if ( _cv != NULL )
set_custom_viewer_popup_menu(_cv, NULL);
for (intvec_t::iterator it=_installed_popups.begin(), it_end=_installed_popups.end();
it != it_end;
++it)
{
_global_popup_map.erase(*it);
}
_installed_popups.clear();
}
//--------------------------------------------------------------------------
size_t add_popup_menu(
const char *title,
const char *hotkey)
{
size_t menu_id = _global_popup_id + 1;
// Overlap / already exists?
if (_cv == NULL || // No custviewer?
// Overlap?
menu_id == 0 ||
// Already exists?
_global_popup_map.find(menu_id) != _global_popup_map.end())
{
return 0;
}
add_custom_viewer_popup_item(_cv, title, hotkey, s_popup_menu_cb, (void *)menu_id);
// Save global association
_global_popup_map[menu_id] = cvw_popupctx_t(menu_id, this);
_global_popup_id = menu_id;
// Remember what menu IDs are set with this form
_installed_popups.push_back(menu_id);
return menu_id;
}
//--------------------------------------------------------------------------
bool create(const char *title, int features, custviewer_data_t *data)
{
// Already created? (in the instance)
if ( _form != NULL )
return true;
// Already created? (in IDA windows list)
HWND hwnd(NULL);
TForm *form = create_tform(title, &hwnd);
if ( hwnd == NULL )
return false;
_title = title;
_data = data;
_form = form;
_features = features;
// Create the viewer
_cv = create_custom_viewer(
title,
(TWinControl *)_form,
_data->get_min(),
_data->get_max(),
_data->get_min(),
0,
_data->get_ud());
// Set user-data
set_custom_viewer_handler(_cv, CVH_USERDATA, (void *)this);
//
// Set other optional callbacks
//
if ( (features & HAVE_KEYDOWN) != 0 )
set_custom_viewer_handler(_cv, CVH_KEYDOWN, (void *)s_cv_keydown);
if ( (features & HAVE_POPUP) != 0 )
set_custom_viewer_handler(_cv, CVH_POPUP, (void *)s_cv_popup);
if ( (features & HAVE_DBLCLICK) != 0 )
set_custom_viewer_handler(_cv, CVH_DBLCLICK, (void *)s_cv_dblclick);
if ( (features & HAVE_CURPOS) != 0 )
set_custom_viewer_handler(_cv, CVH_CURPOS, (void *)s_cv_curpos);
if ( (features & HAVE_CLICK) != 0 )
set_custom_viewer_handler(_cv, CVH_CLICK, (void *)s_cv_click);
// Hook to UI notifications (for TForm close event)
hook_to_notification_point(HT_UI, s_ui_cb, this);
return true;
}
//--------------------------------------------------------------------------
bool show()
{
// Closed already?
if ( _form == NULL )
return false;
open_tform(_form, FORM_TAB|FORM_MENU|FORM_RESTORE|FORM_QWIDGET);
return true;
}
};
customviewer_t::cvw_popupmap_t customviewer_t::_global_popup_map;
size_t customviewer_t::_global_popup_id = 0;
//---------------------------------------------------------------------------
class py_simplecustview_t: public customviewer_t
{
private:
cvdata_simpleline_t data;
PyObject *py_self, *py_this, *py_last_link;
int features;
//--------------------------------------------------------------------------
// Convert a tuple (String, [color, [bgcolor]]) to a simpleline_t
static bool py_to_simpleline(PyObject *py, simpleline_t &sl)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
if ( PyString_Check(py) )
{
sl.line = PyString_AsString(py);
return true;
}
Py_ssize_t sz;
if ( !PyTuple_Check(py) || (sz = PyTuple_Size(py)) <= 0 )
return false;
PyObject *py_val = PyTuple_GetItem(py, 0);
if ( !PyString_Check(py_val) )
return false;
sl.line = PyString_AsString(py_val);
if ( (sz > 1) && (py_val = PyTuple_GetItem(py, 1)) && PyLong_Check(py_val) )
sl.color = color_t(PyLong_AsUnsignedLong(py_val));
if ( (sz > 2) && (py_val = PyTuple_GetItem(py, 2)) && PyLong_Check(py_val) )
sl.bgcolor = PyLong_AsUnsignedLong(py_val);
return true;
}
//
// Callbacks
//
virtual bool on_click(int shift)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
newref_t py_result(PyObject_CallMethod(py_self, (char *)S_ON_CLICK, "i", shift));
PyW_ShowCbErr(S_ON_CLICK);
return py_result != NULL && PyObject_IsTrue(py_result.o);
}
//--------------------------------------------------------------------------
// OnDblClick
virtual bool on_dblclick(int shift)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
newref_t py_result(PyObject_CallMethod(py_self, (char *)S_ON_DBL_CLICK, "i", shift));
PyW_ShowCbErr(S_ON_DBL_CLICK);
return py_result != NULL && PyObject_IsTrue(py_result.o);
}
//--------------------------------------------------------------------------
// OnCurorPositionChanged
virtual void on_curpos_changed()
{
PYW_GIL_CHECK_LOCKED_SCOPE();
newref_t py_result(PyObject_CallMethod(py_self, (char *)S_ON_CURSOR_POS_CHANGED, NULL));
PyW_ShowCbErr(S_ON_CURSOR_POS_CHANGED);
}
//--------------------------------------------------------------------------
// OnHostFormClose
virtual void on_close()
{
// Call the close method if it is there and the object is still bound
if ( (features & HAVE_CLOSE) != 0 && py_self != NULL )
{
PYW_GIL_CHECK_LOCKED_SCOPE();
newref_t py_result(PyObject_CallMethod(py_self, (char *)S_ON_CLOSE, NULL));
PyW_ShowCbErr(S_ON_CLOSE);
// Cleanup
Py_DECREF(py_self);
py_self = NULL;
}
}
//--------------------------------------------------------------------------
// OnKeyDown
virtual bool on_keydown(int vk_key, int shift)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
newref_t py_result(
PyObject_CallMethod(
py_self,
(char *)S_ON_KEYDOWN,
"ii",
vk_key,
shift));
PyW_ShowCbErr(S_ON_KEYDOWN);
return py_result != NULL && PyObject_IsTrue(py_result.o);
}
//--------------------------------------------------------------------------
// OnPopupShow
virtual bool on_popup()
{
PYW_GIL_CHECK_LOCKED_SCOPE();
newref_t py_result(
PyObject_CallMethod(
py_self,
(char *)S_ON_POPUP,
NULL));
PyW_ShowCbErr(S_ON_POPUP);
return py_result != NULL && PyObject_IsTrue(py_result.o);
}
//--------------------------------------------------------------------------
// OnHint
virtual bool on_hint(place_t *place, int *important_lines, qstring &hint)
{
size_t ln = data.to_lineno(place);
PYW_GIL_CHECK_LOCKED_SCOPE();
newref_t py_result(
PyObject_CallMethod(
py_self,
(char *)S_ON_HINT,
PY_FMT64,
pyul_t(ln)));
PyW_ShowCbErr(S_ON_HINT);
bool ok = py_result != NULL && PyTuple_Check(py_result.o) && PyTuple_Size(py_result.o) == 2;
if ( ok )
{
if ( important_lines != NULL )
*important_lines = PyInt_AsLong(PyTuple_GetItem(py_result.o, 0));
hint = PyString_AsString(PyTuple_GetItem(py_result.o, 1));
}
return ok;
}
//--------------------------------------------------------------------------
// OnPopupMenuClick
virtual bool on_popup_menu(size_t menu_id)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
newref_t py_result(
PyObject_CallMethod(
py_self,
(char *)S_ON_POPUP_MENU,
PY_FMT64,
pyul_t(menu_id)));
PyW_ShowCbErr(S_ON_POPUP_MENU);
return py_result != NULL && PyObject_IsTrue(py_result.o);
}
//--------------------------------------------------------------------------
void refresh_range()
{
data.set_minmax();
set_range();
}
public:
py_simplecustview_t()
{
py_this = py_self = py_last_link = NULL;
}
~py_simplecustview_t()
{
}
//--------------------------------------------------------------------------
// Edits an existing line
bool edit_line(size_t nline, PyObject *py_sl)
{
simpleline_t sl;
if ( !py_to_simpleline(py_sl, sl) )
return false;
return data.set_line(nline, sl);
}
// Low level: patches a line string directly
bool patch_line(size_t nline, size_t offs, int value)
{
return data.patch_line(nline, offs, value);
}
// Insert a line
bool insert_line(size_t nline, PyObject *py_sl)
{
simpleline_t sl;
if ( !py_to_simpleline(py_sl, sl) )
return false;
return data.insert_line(nline, sl);
}
// Adds a line tuple
bool add_line(PyObject *py_sl)
{
simpleline_t sl;
if ( !py_to_simpleline(py_sl, sl) )
return false;
data.add_line(sl);
refresh_range();
return true;
}
//--------------------------------------------------------------------------
bool del_line(size_t nline)
{
bool ok = data.del_line(nline);
if ( ok )
refresh_range();
return ok;
}
//--------------------------------------------------------------------------
// Gets the position and returns a tuple (lineno, x, y)
PyObject *get_pos(bool mouse)
{
place_t *pl;
int x, y;
pl = get_place(mouse, &x, &y);
PYW_GIL_CHECK_LOCKED_SCOPE();
if ( pl == NULL )
Py_RETURN_NONE;
return Py_BuildValue("(" PY_FMT64 "ii)", pyul_t(data.to_lineno(pl)), x, y);
}
//--------------------------------------------------------------------------
// Returns the line tuple
PyObject *get_line(size_t nline)
{
simpleline_t *r = data.get_line(nline);
PYW_GIL_CHECK_LOCKED_SCOPE();
if ( r == NULL )
Py_RETURN_NONE;
return Py_BuildValue("(sII)", r->line.c_str(), (unsigned int)r->color, (unsigned int)r->bgcolor);
}
// Returns the count of lines
const size_t count() const
{
return data.count();
}
// Clears lines
void clear()
{
data.clear_lines();
refresh_range();
}
//--------------------------------------------------------------------------
bool jumpto(size_t ln, int x, int y)
{
simpleline_place_t l(ln);
return customviewer_t::jumpto(&l, x, y);
}
//--------------------------------------------------------------------------
// Initializes and links the Python object to this class
bool init(PyObject *py_link, const char *title)
{
// Already created?
if ( _form != NULL )
return true;
// Probe callbacks
features = 0;
static struct
{
const char *cb_name;
int feature;
} const cbtable[] =
{
{S_ON_CLICK, HAVE_CLICK},
{S_ON_CLOSE, HAVE_CLOSE},
{S_ON_HINT, HAVE_HINT},
{S_ON_KEYDOWN, HAVE_KEYDOWN},
{S_ON_POPUP, HAVE_POPUP},
{S_ON_DBL_CLICK, HAVE_DBLCLICK},
{S_ON_CURSOR_POS_CHANGED, HAVE_CURPOS}
};
PYW_GIL_CHECK_LOCKED_SCOPE();
for ( size_t i=0; i<qnumber(cbtable); i++ )
{
if ( PyObject_HasAttrString(py_link, cbtable[i].cb_name) )
features |= cbtable[i].feature;
}
if ( !create(title, features, &data) )
return false;
// Hold a reference to this object
py_last_link = py_self = py_link;
Py_INCREF(py_self);
// Return a reference to the C++ instance (only once)
if ( py_this == NULL )
py_this = PyCObject_FromVoidPtr(this, NULL);
return true;
}
//--------------------------------------------------------------------------
bool show()
{
// Form was closed, but object already linked?
if ( _form == NULL && py_last_link != NULL )
{
// Re-create the view (with same previous parameters)
if ( !init(py_last_link, _title.c_str()) )
return false;
}
return customviewer_t::show();
}
//--------------------------------------------------------------------------
bool get_selection(size_t *x1, size_t *y1, size_t *x2, size_t *y2)
{
if ( _cv == NULL )
return false;
twinpos_t p1, p2;
if ( !::readsel2(_cv, &p1, &p2) )
return false;
if ( y1 != NULL )
*y1 = data.to_lineno(p1.at);
if ( y2 != NULL )
*y2 = data.to_lineno(p2.at);
if ( x1 != NULL )
*x1 = size_t(p1.x);
if ( x2 != NULL )
*x2 = p2.x;
return true;
}
PyObject *py_get_selection()
{
size_t x1, y1, x2, y2;
PYW_GIL_CHECK_LOCKED_SCOPE();
if ( !get_selection(&x1, &y1, &x2, &y2) )
Py_RETURN_NONE;
return Py_BuildValue("(" PY_FMT64 PY_FMT64 PY_FMT64 PY_FMT64 ")", pyul_t(x1), pyul_t(y1), pyul_t(x2), pyul_t(y2));
}
static py_simplecustview_t *get_this(PyObject *py_this)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
return PyCObject_Check(py_this) ? (py_simplecustview_t *) PyCObject_AsVoidPtr(py_this) : NULL;
}
PyObject *get_pythis()
{
return py_this;
}
};
//</code(py_custviewer)>
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//<inline(py_custviewer)>
//
// Pywraps Simple Custom Viewer functions
//
PyObject *pyscv_init(PyObject *py_link, const char *title)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
py_simplecustview_t *_this = new py_simplecustview_t();
bool ok = _this->init(py_link, title);
if ( !ok )
{
delete _this;
Py_RETURN_NONE;
}
return _this->get_pythis();
}
#define DECL_THIS py_simplecustview_t *_this = py_simplecustview_t::get_this(py_this)
//--------------------------------------------------------------------------
bool pyscv_refresh(PyObject *py_this)
{
DECL_THIS;
if ( _this == NULL )
return false;
return _this->refresh();
}
//--------------------------------------------------------------------------
bool pyscv_delete(PyObject *py_this)
{
DECL_THIS;
if ( _this == NULL )
return false;
_this->close();
delete _this;
return true;
}
//--------------------------------------------------------------------------
bool pyscv_refresh_current(PyObject *py_this)
{
DECL_THIS;
if ( _this == NULL )
return false;
return _this->refresh_current();
}
//--------------------------------------------------------------------------
PyObject *pyscv_get_current_line(PyObject *py_this, bool mouse, bool notags)
{
DECL_THIS;
PYW_GIL_CHECK_LOCKED_SCOPE();
const char *line;
if ( _this == NULL || (line = _this->get_current_line(mouse, notags)) == NULL )
Py_RETURN_NONE;
return PyString_FromString(line);
}
//--------------------------------------------------------------------------
bool pyscv_is_focused(PyObject *py_this)
{
DECL_THIS;
if ( _this == NULL )
return false;
return _this->is_focused();
}
void pyscv_clear_popup_menu(PyObject *py_this)
{
DECL_THIS;
if ( _this != NULL )
_this->clear_popup_menu();
}
size_t pyscv_add_popup_menu(PyObject *py_this, const char *title, const char *hotkey)
{
DECL_THIS;
return _this == NULL ? 0 : _this->add_popup_menu(title, hotkey);
}
size_t pyscv_count(PyObject *py_this)
{
DECL_THIS;
return _this == NULL ? 0 : _this->count();
}
bool pyscv_show(PyObject *py_this)
{
DECL_THIS;
return _this == NULL ? false : _this->show();
}
void pyscv_close(PyObject *py_this)
{
DECL_THIS;
if ( _this != NULL )
_this->close();
}
bool pyscv_jumpto(PyObject *py_this, size_t ln, int x, int y)
{
DECL_THIS;
if ( _this == NULL )
return false;
return _this->jumpto(ln, x, y);
}
// Returns the line tuple
PyObject *pyscv_get_line(PyObject *py_this, size_t nline)
{
DECL_THIS;
if ( _this == NULL )
{
PYW_GIL_CHECK_LOCKED_SCOPE();
Py_RETURN_NONE;
}
return _this->get_line(nline);
}
//--------------------------------------------------------------------------
// Gets the position and returns a tuple (lineno, x, y)
PyObject *pyscv_get_pos(PyObject *py_this, bool mouse)
{
DECL_THIS;
if ( _this == NULL )
{
PYW_GIL_CHECK_LOCKED_SCOPE();
Py_RETURN_NONE;
}
return _this->get_pos(mouse);
}
//--------------------------------------------------------------------------
PyObject *pyscv_clear_lines(PyObject *py_this)
{
DECL_THIS;
if ( _this != NULL )
_this->clear();
PYW_GIL_CHECK_LOCKED_SCOPE();
Py_RETURN_NONE;
}
//--------------------------------------------------------------------------
// Adds a line tuple
bool pyscv_add_line(PyObject *py_this, PyObject *py_sl)
{
DECL_THIS;
return _this == NULL ? false : _this->add_line(py_sl);
}
//--------------------------------------------------------------------------
bool pyscv_insert_line(PyObject *py_this, size_t nline, PyObject *py_sl)
{
DECL_THIS;
return _this == NULL ? false : _this->insert_line(nline, py_sl);
}
//--------------------------------------------------------------------------
bool pyscv_patch_line(PyObject *py_this, size_t nline, size_t offs, int value)
{
DECL_THIS;
return _this == NULL ? false : _this->patch_line(nline, offs, value);
}
//--------------------------------------------------------------------------
bool pyscv_del_line(PyObject *py_this, size_t nline)
{
DECL_THIS;
return _this == NULL ? false : _this->del_line(nline);
}
//--------------------------------------------------------------------------
PyObject *pyscv_get_selection(PyObject *py_this)
{
DECL_THIS;
if ( _this == NULL )
{
PYW_GIL_CHECK_LOCKED_SCOPE();
Py_RETURN_NONE;
}
return _this->py_get_selection();
}
//--------------------------------------------------------------------------
PyObject *pyscv_get_current_word(PyObject *py_this, bool mouse)
{
DECL_THIS;
PYW_GIL_CHECK_LOCKED_SCOPE();
if ( _this != NULL )
{
qstring word;
if ( _this->get_current_word(mouse, word) )
return PyString_FromString(word.c_str());
}
Py_RETURN_NONE;
}
//--------------------------------------------------------------------------
// Edits an existing line
bool pyscv_edit_line(PyObject *py_this, size_t nline, PyObject *py_sl)
{
DECL_THIS;
return _this == NULL ? false : _this->edit_line(nline, py_sl);
}
//-------------------------------------------------------------------------
TForm *pyscv_get_tform(PyObject *py_this)
{
DECL_THIS;
return _this == NULL ? NULL : _this->get_tform();
}
//-------------------------------------------------------------------------
TCustomControl *pyscv_get_tcustom_control(PyObject *py_this)
{
DECL_THIS;
return _this == NULL ? NULL : _this->get_tcustom_control();
}
#undef DECL_THIS
//</inline(py_custviewer)>
//---------------------------------------------------------------------------
#endif // __PYWRAPS_CUSTVIEWER__
| 26.140212 | 119 | 0.513949 | [
"object"
] |
40cf650f6900e79af79ac6b54e73b1714456bcb1 | 7,796 | cpp | C++ | src/Storages/VirtualColumnUtils.cpp | zzachimed/ClickHouse | a403f1cd1b2655a60ca196d209ef443ef6d91b39 | [
"Apache-2.0"
] | 8,629 | 2016-06-14T21:03:01.000Z | 2019-09-23T07:46:38.000Z | src/Storages/VirtualColumnUtils.cpp | zzachimed/ClickHouse | a403f1cd1b2655a60ca196d209ef443ef6d91b39 | [
"Apache-2.0"
] | 4,335 | 2016-06-15T12:58:31.000Z | 2019-09-23T11:18:43.000Z | src/Storages/VirtualColumnUtils.cpp | zzachimed/ClickHouse | a403f1cd1b2655a60ca196d209ef443ef6d91b39 | [
"Apache-2.0"
] | 1,700 | 2016-06-15T09:25:11.000Z | 2019-09-23T11:16:38.000Z | #include <Core/NamesAndTypes.h>
#include <Interpreters/Context.h>
#include <Interpreters/TreeRewriter.h>
#include <Interpreters/ExpressionAnalyzer.h>
#include <Interpreters/ExpressionActions.h>
#include <Interpreters/IdentifierSemantic.h>
#include <Interpreters/misc.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTExpressionList.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTSelectQuery.h>
#include <Parsers/ASTSubquery.h>
#include <Columns/ColumnConst.h>
#include <Columns/ColumnsNumber.h>
#include <Columns/ColumnsCommon.h>
#include <Columns/FilterDescription.h>
#include <Storages/VirtualColumnUtils.h>
#include <IO/WriteHelpers.h>
#include <Common/typeid_cast.h>
#include <Interpreters/ActionsVisitor.h>
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
}
namespace
{
/// Verifying that the function depends only on the specified columns
bool isValidFunction(const ASTPtr & expression, const std::function<bool(const ASTPtr &)> & is_constant)
{
const auto * function = expression->as<ASTFunction>();
if (function && functionIsInOrGlobalInOperator(function->name))
{
// Second argument of IN can be a scalar subquery
return isValidFunction(function->arguments->children[0], is_constant);
}
else
return is_constant(expression);
}
/// Extract all subfunctions of the main conjunction, but depending only on the specified columns
bool extractFunctions(const ASTPtr & expression, const std::function<bool(const ASTPtr &)> & is_constant, std::vector<ASTPtr> & result)
{
const auto * function = expression->as<ASTFunction>();
if (function && (function->name == "and" || function->name == "indexHint"))
{
bool ret = true;
for (const auto & child : function->arguments->children)
ret &= extractFunctions(child, is_constant, result);
return ret;
}
else if (isValidFunction(expression, is_constant))
{
result.push_back(expression->clone());
return true;
}
else
return false;
}
/// Construct a conjunction from given functions
ASTPtr buildWhereExpression(const ASTs & functions)
{
if (functions.empty())
return nullptr;
if (functions.size() == 1)
return functions[0];
return makeASTFunction("and", functions);
}
void buildSets(const ASTPtr & expression, ExpressionAnalyzer & analyzer)
{
const auto * func = expression->as<ASTFunction>();
if (func && functionIsInOrGlobalInOperator(func->name))
{
const IAST & args = *func->arguments;
const ASTPtr & arg = args.children.at(1);
if (arg->as<ASTSubquery>() || arg->as<ASTTableIdentifier>())
{
analyzer.tryMakeSetForIndexFromSubquery(arg);
}
}
else
{
for (const auto & child : expression->children)
buildSets(child, analyzer);
}
}
}
namespace VirtualColumnUtils
{
void rewriteEntityInAst(ASTPtr ast, const String & column_name, const Field & value, const String & func)
{
auto & select = ast->as<ASTSelectQuery &>();
if (!select.with())
select.setExpression(ASTSelectQuery::Expression::WITH, std::make_shared<ASTExpressionList>());
if (func.empty())
{
auto literal = std::make_shared<ASTLiteral>(value);
literal->alias = column_name;
literal->prefer_alias_to_column_name = true;
select.with()->children.push_back(literal);
}
else
{
auto literal = std::make_shared<ASTLiteral>(value);
literal->prefer_alias_to_column_name = true;
auto function = makeASTFunction(func, literal);
function->alias = column_name;
function->prefer_alias_to_column_name = true;
select.with()->children.push_back(function);
}
}
bool prepareFilterBlockWithQuery(const ASTPtr & query, ContextPtr context, Block block, ASTPtr & expression_ast)
{
if (block.rows() == 0)
throw Exception("Cannot prepare filter with empty block", ErrorCodes::LOGICAL_ERROR);
/// Take the first row of the input block to build a constant block
auto columns = block.getColumns();
Columns const_columns(columns.size());
for (size_t i = 0; i < columns.size(); ++i)
{
if (isColumnConst(*columns[i]))
const_columns[i] = columns[i]->cloneResized(1);
else
const_columns[i] = ColumnConst::create(columns[i]->cloneResized(1), 1);
}
block.setColumns(const_columns);
bool unmodified = true;
const auto & select = query->as<ASTSelectQuery &>();
if (!select.where() && !select.prewhere())
return unmodified;
// Provide input columns as constant columns to check if an expression is constant.
std::function<bool(const ASTPtr &)> is_constant = [&block, &context](const ASTPtr & node)
{
auto actions = std::make_shared<ActionsDAG>(block.getColumnsWithTypeAndName());
PreparedSets prepared_sets;
SubqueriesForSets subqueries_for_sets;
const NamesAndTypesList source_columns;
const NamesAndTypesList aggregation_keys;
const ColumnNumbersList grouping_set_keys;
ActionsVisitor::Data visitor_data(
context, SizeLimits{}, 1, source_columns, std::move(actions), prepared_sets, subqueries_for_sets, true, true, true, false,
{ aggregation_keys, grouping_set_keys, GroupByKind::NONE });
ActionsVisitor(visitor_data).visit(node);
actions = visitor_data.getActions();
auto expression_actions = std::make_shared<ExpressionActions>(actions);
auto block_with_constants = block;
expression_actions->execute(block_with_constants);
auto column_name = node->getColumnName();
return block_with_constants.has(column_name) && isColumnConst(*block_with_constants.getByName(column_name).column);
};
/// Create an expression that evaluates the expressions in WHERE and PREWHERE, depending only on the existing columns.
std::vector<ASTPtr> functions;
if (select.where())
unmodified &= extractFunctions(select.where(), is_constant, functions);
if (select.prewhere())
unmodified &= extractFunctions(select.prewhere(), is_constant, functions);
expression_ast = buildWhereExpression(functions);
return unmodified;
}
void filterBlockWithQuery(const ASTPtr & query, Block & block, ContextPtr context, ASTPtr expression_ast)
{
if (block.rows() == 0)
return;
if (!expression_ast)
prepareFilterBlockWithQuery(query, context, block, expression_ast);
if (!expression_ast)
return;
/// Let's analyze and calculate the prepared expression.
auto syntax_result = TreeRewriter(context).analyze(expression_ast, block.getNamesAndTypesList());
ExpressionAnalyzer analyzer(expression_ast, syntax_result, context);
buildSets(expression_ast, analyzer);
ExpressionActionsPtr actions = analyzer.getActions(false /* add alises */, true /* project result */, CompileExpressions::yes);
Block block_with_filter = block;
actions->execute(block_with_filter);
/// Filter the block.
String filter_column_name = expression_ast->getColumnName();
ColumnPtr filter_column = block_with_filter.getByName(filter_column_name).column->convertToFullColumnIfConst();
ConstantFilterDescription constant_filter(*filter_column);
if (constant_filter.always_true)
{
return;
}
if (constant_filter.always_false)
{
block = block.cloneEmpty();
return;
}
FilterDescription filter(*filter_column);
for (size_t i = 0; i < block.columns(); ++i)
{
ColumnPtr & column = block.safeGetByPosition(i).column;
column = column->filter(*filter.data, -1);
}
}
}
}
| 33.174468 | 135 | 0.6892 | [
"vector"
] |
40d1f463aa3fff44cfa48010679582935738040c | 24,075 | cpp | C++ | deps/lld/COFF/DLL.cpp | shiimizu/zig | 7277670843d259d19093c8900b1f8445e41202ae | [
"MIT"
] | 1 | 2020-02-27T05:17:53.000Z | 2020-02-27T05:17:53.000Z | deps/lld/COFF/DLL.cpp | shiimizu/zig | 7277670843d259d19093c8900b1f8445e41202ae | [
"MIT"
] | 2 | 2019-12-29T21:15:40.000Z | 2020-06-15T11:21:10.000Z | deps/lld/COFF/DLL.cpp | shiimizu/zig | 7277670843d259d19093c8900b1f8445e41202ae | [
"MIT"
] | 3 | 2019-12-21T06:35:35.000Z | 2020-06-07T23:18:58.000Z | //===- DLL.cpp ------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines various types of chunks for the DLL import or export
// descriptor tables. They are inherently Windows-specific.
// You need to read Microsoft PE/COFF spec to understand details
// about the data structures.
//
// If you are not particularly interested in linking against Windows
// DLL, you can skip this file, and you should still be able to
// understand the rest of the linker.
//
//===----------------------------------------------------------------------===//
#include "DLL.h"
#include "Chunks.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Path.h"
using namespace llvm;
using namespace llvm::object;
using namespace llvm::support::endian;
using namespace llvm::COFF;
namespace lld {
namespace coff {
namespace {
// Import table
// A chunk for the import descriptor table.
class HintNameChunk : public NonSectionChunk {
public:
HintNameChunk(StringRef n, uint16_t h) : name(n), hint(h) {}
size_t getSize() const override {
// Starts with 2 byte Hint field, followed by a null-terminated string,
// ends with 0 or 1 byte padding.
return alignTo(name.size() + 3, 2);
}
void writeTo(uint8_t *buf) const override {
memset(buf, 0, getSize());
write16le(buf, hint);
memcpy(buf + 2, name.data(), name.size());
}
private:
StringRef name;
uint16_t hint;
};
// A chunk for the import descriptor table.
class LookupChunk : public NonSectionChunk {
public:
explicit LookupChunk(Chunk *c) : hintName(c) {
setAlignment(config->wordsize);
}
size_t getSize() const override { return config->wordsize; }
void writeTo(uint8_t *buf) const override {
if (config->is64())
write64le(buf, hintName->getRVA());
else
write32le(buf, hintName->getRVA());
}
Chunk *hintName;
};
// A chunk for the import descriptor table.
// This chunk represent import-by-ordinal symbols.
// See Microsoft PE/COFF spec 7.1. Import Header for details.
class OrdinalOnlyChunk : public NonSectionChunk {
public:
explicit OrdinalOnlyChunk(uint16_t v) : ordinal(v) {
setAlignment(config->wordsize);
}
size_t getSize() const override { return config->wordsize; }
void writeTo(uint8_t *buf) const override {
// An import-by-ordinal slot has MSB 1 to indicate that
// this is import-by-ordinal (and not import-by-name).
if (config->is64()) {
write64le(buf, (1ULL << 63) | ordinal);
} else {
write32le(buf, (1ULL << 31) | ordinal);
}
}
uint16_t ordinal;
};
// A chunk for the import descriptor table.
class ImportDirectoryChunk : public NonSectionChunk {
public:
explicit ImportDirectoryChunk(Chunk *n) : dllName(n) {}
size_t getSize() const override { return sizeof(ImportDirectoryTableEntry); }
void writeTo(uint8_t *buf) const override {
memset(buf, 0, getSize());
auto *e = (coff_import_directory_table_entry *)(buf);
e->ImportLookupTableRVA = lookupTab->getRVA();
e->NameRVA = dllName->getRVA();
e->ImportAddressTableRVA = addressTab->getRVA();
}
Chunk *dllName;
Chunk *lookupTab;
Chunk *addressTab;
};
// A chunk representing null terminator in the import table.
// Contents of this chunk is always null bytes.
class NullChunk : public NonSectionChunk {
public:
explicit NullChunk(size_t n) : size(n) { hasData = false; }
size_t getSize() const override { return size; }
void writeTo(uint8_t *buf) const override {
memset(buf, 0, size);
}
private:
size_t size;
};
static std::vector<std::vector<DefinedImportData *>>
binImports(const std::vector<DefinedImportData *> &imports) {
// Group DLL-imported symbols by DLL name because that's how
// symbols are layed out in the import descriptor table.
auto less = [](const std::string &a, const std::string &b) {
return config->dllOrder[a] < config->dllOrder[b];
};
std::map<std::string, std::vector<DefinedImportData *>,
bool(*)(const std::string &, const std::string &)> m(less);
for (DefinedImportData *sym : imports)
m[sym->getDLLName().lower()].push_back(sym);
std::vector<std::vector<DefinedImportData *>> v;
for (auto &kv : m) {
// Sort symbols by name for each group.
std::vector<DefinedImportData *> &syms = kv.second;
std::sort(syms.begin(), syms.end(),
[](DefinedImportData *a, DefinedImportData *b) {
return a->getName() < b->getName();
});
v.push_back(std::move(syms));
}
return v;
}
// Export table
// See Microsoft PE/COFF spec 4.3 for details.
// A chunk for the delay import descriptor table etnry.
class DelayDirectoryChunk : public NonSectionChunk {
public:
explicit DelayDirectoryChunk(Chunk *n) : dllName(n) {}
size_t getSize() const override {
return sizeof(delay_import_directory_table_entry);
}
void writeTo(uint8_t *buf) const override {
memset(buf, 0, getSize());
auto *e = (delay_import_directory_table_entry *)(buf);
e->Attributes = 1;
e->Name = dllName->getRVA();
e->ModuleHandle = moduleHandle->getRVA();
e->DelayImportAddressTable = addressTab->getRVA();
e->DelayImportNameTable = nameTab->getRVA();
}
Chunk *dllName;
Chunk *moduleHandle;
Chunk *addressTab;
Chunk *nameTab;
};
// Initial contents for delay-loaded functions.
// This code calls __delayLoadHelper2 function to resolve a symbol
// and then overwrites its jump table slot with the result
// for subsequent function calls.
static const uint8_t thunkX64[] = {
0x48, 0x8D, 0x05, 0, 0, 0, 0, // lea rax, [__imp_<FUNCNAME>]
0xE9, 0, 0, 0, 0, // jmp __tailMerge_<lib>
};
static const uint8_t tailMergeX64[] = {
0x51, // push rcx
0x52, // push rdx
0x41, 0x50, // push r8
0x41, 0x51, // push r9
0x48, 0x83, 0xEC, 0x48, // sub rsp, 48h
0x66, 0x0F, 0x7F, 0x04, 0x24, // movdqa xmmword ptr [rsp], xmm0
0x66, 0x0F, 0x7F, 0x4C, 0x24, 0x10, // movdqa xmmword ptr [rsp+10h], xmm1
0x66, 0x0F, 0x7F, 0x54, 0x24, 0x20, // movdqa xmmword ptr [rsp+20h], xmm2
0x66, 0x0F, 0x7F, 0x5C, 0x24, 0x30, // movdqa xmmword ptr [rsp+30h], xmm3
0x48, 0x8B, 0xD0, // mov rdx, rax
0x48, 0x8D, 0x0D, 0, 0, 0, 0, // lea rcx, [___DELAY_IMPORT_...]
0xE8, 0, 0, 0, 0, // call __delayLoadHelper2
0x66, 0x0F, 0x6F, 0x04, 0x24, // movdqa xmm0, xmmword ptr [rsp]
0x66, 0x0F, 0x6F, 0x4C, 0x24, 0x10, // movdqa xmm1, xmmword ptr [rsp+10h]
0x66, 0x0F, 0x6F, 0x54, 0x24, 0x20, // movdqa xmm2, xmmword ptr [rsp+20h]
0x66, 0x0F, 0x6F, 0x5C, 0x24, 0x30, // movdqa xmm3, xmmword ptr [rsp+30h]
0x48, 0x83, 0xC4, 0x48, // add rsp, 48h
0x41, 0x59, // pop r9
0x41, 0x58, // pop r8
0x5A, // pop rdx
0x59, // pop rcx
0xFF, 0xE0, // jmp rax
};
static const uint8_t thunkX86[] = {
0xB8, 0, 0, 0, 0, // mov eax, offset ___imp__<FUNCNAME>
0xE9, 0, 0, 0, 0, // jmp __tailMerge_<lib>
};
static const uint8_t tailMergeX86[] = {
0x51, // push ecx
0x52, // push edx
0x50, // push eax
0x68, 0, 0, 0, 0, // push offset ___DELAY_IMPORT_DESCRIPTOR_<DLLNAME>_dll
0xE8, 0, 0, 0, 0, // call ___delayLoadHelper2@8
0x5A, // pop edx
0x59, // pop ecx
0xFF, 0xE0, // jmp eax
};
static const uint8_t thunkARM[] = {
0x40, 0xf2, 0x00, 0x0c, // mov.w ip, #0 __imp_<FUNCNAME>
0xc0, 0xf2, 0x00, 0x0c, // mov.t ip, #0 __imp_<FUNCNAME>
0x00, 0xf0, 0x00, 0xb8, // b.w __tailMerge_<lib>
};
static const uint8_t tailMergeARM[] = {
0x2d, 0xe9, 0x0f, 0x48, // push.w {r0, r1, r2, r3, r11, lr}
0x0d, 0xf2, 0x10, 0x0b, // addw r11, sp, #16
0x2d, 0xed, 0x10, 0x0b, // vpush {d0, d1, d2, d3, d4, d5, d6, d7}
0x61, 0x46, // mov r1, ip
0x40, 0xf2, 0x00, 0x00, // mov.w r0, #0 DELAY_IMPORT_DESCRIPTOR
0xc0, 0xf2, 0x00, 0x00, // mov.t r0, #0 DELAY_IMPORT_DESCRIPTOR
0x00, 0xf0, 0x00, 0xd0, // bl #0 __delayLoadHelper2
0x84, 0x46, // mov ip, r0
0xbd, 0xec, 0x10, 0x0b, // vpop {d0, d1, d2, d3, d4, d5, d6, d7}
0xbd, 0xe8, 0x0f, 0x48, // pop.w {r0, r1, r2, r3, r11, lr}
0x60, 0x47, // bx ip
};
static const uint8_t thunkARM64[] = {
0x11, 0x00, 0x00, 0x90, // adrp x17, #0 __imp_<FUNCNAME>
0x31, 0x02, 0x00, 0x91, // add x17, x17, #0 :lo12:__imp_<FUNCNAME>
0x00, 0x00, 0x00, 0x14, // b __tailMerge_<lib>
};
static const uint8_t tailMergeARM64[] = {
0xfd, 0x7b, 0xb3, 0xa9, // stp x29, x30, [sp, #-208]!
0xfd, 0x03, 0x00, 0x91, // mov x29, sp
0xe0, 0x07, 0x01, 0xa9, // stp x0, x1, [sp, #16]
0xe2, 0x0f, 0x02, 0xa9, // stp x2, x3, [sp, #32]
0xe4, 0x17, 0x03, 0xa9, // stp x4, x5, [sp, #48]
0xe6, 0x1f, 0x04, 0xa9, // stp x6, x7, [sp, #64]
0xe0, 0x87, 0x02, 0xad, // stp q0, q1, [sp, #80]
0xe2, 0x8f, 0x03, 0xad, // stp q2, q3, [sp, #112]
0xe4, 0x97, 0x04, 0xad, // stp q4, q5, [sp, #144]
0xe6, 0x9f, 0x05, 0xad, // stp q6, q7, [sp, #176]
0xe1, 0x03, 0x11, 0xaa, // mov x1, x17
0x00, 0x00, 0x00, 0x90, // adrp x0, #0 DELAY_IMPORT_DESCRIPTOR
0x00, 0x00, 0x00, 0x91, // add x0, x0, #0 :lo12:DELAY_IMPORT_DESCRIPTOR
0x00, 0x00, 0x00, 0x94, // bl #0 __delayLoadHelper2
0xf0, 0x03, 0x00, 0xaa, // mov x16, x0
0xe6, 0x9f, 0x45, 0xad, // ldp q6, q7, [sp, #176]
0xe4, 0x97, 0x44, 0xad, // ldp q4, q5, [sp, #144]
0xe2, 0x8f, 0x43, 0xad, // ldp q2, q3, [sp, #112]
0xe0, 0x87, 0x42, 0xad, // ldp q0, q1, [sp, #80]
0xe6, 0x1f, 0x44, 0xa9, // ldp x6, x7, [sp, #64]
0xe4, 0x17, 0x43, 0xa9, // ldp x4, x5, [sp, #48]
0xe2, 0x0f, 0x42, 0xa9, // ldp x2, x3, [sp, #32]
0xe0, 0x07, 0x41, 0xa9, // ldp x0, x1, [sp, #16]
0xfd, 0x7b, 0xcd, 0xa8, // ldp x29, x30, [sp], #208
0x00, 0x02, 0x1f, 0xd6, // br x16
};
// A chunk for the delay import thunk.
class ThunkChunkX64 : public NonSectionChunk {
public:
ThunkChunkX64(Defined *i, Chunk *tm) : imp(i), tailMerge(tm) {}
size_t getSize() const override { return sizeof(thunkX64); }
void writeTo(uint8_t *buf) const override {
memcpy(buf, thunkX64, sizeof(thunkX64));
write32le(buf + 3, imp->getRVA() - rva - 7);
write32le(buf + 8, tailMerge->getRVA() - rva - 12);
}
Defined *imp = nullptr;
Chunk *tailMerge = nullptr;
};
class TailMergeChunkX64 : public NonSectionChunk {
public:
TailMergeChunkX64(Chunk *d, Defined *h) : desc(d), helper(h) {}
size_t getSize() const override { return sizeof(tailMergeX64); }
void writeTo(uint8_t *buf) const override {
memcpy(buf, tailMergeX64, sizeof(tailMergeX64));
write32le(buf + 39, desc->getRVA() - rva - 43);
write32le(buf + 44, helper->getRVA() - rva - 48);
}
Chunk *desc = nullptr;
Defined *helper = nullptr;
};
class ThunkChunkX86 : public NonSectionChunk {
public:
ThunkChunkX86(Defined *i, Chunk *tm) : imp(i), tailMerge(tm) {}
size_t getSize() const override { return sizeof(thunkX86); }
void writeTo(uint8_t *buf) const override {
memcpy(buf, thunkX86, sizeof(thunkX86));
write32le(buf + 1, imp->getRVA() + config->imageBase);
write32le(buf + 6, tailMerge->getRVA() - rva - 10);
}
void getBaserels(std::vector<Baserel> *res) override {
res->emplace_back(rva + 1);
}
Defined *imp = nullptr;
Chunk *tailMerge = nullptr;
};
class TailMergeChunkX86 : public NonSectionChunk {
public:
TailMergeChunkX86(Chunk *d, Defined *h) : desc(d), helper(h) {}
size_t getSize() const override { return sizeof(tailMergeX86); }
void writeTo(uint8_t *buf) const override {
memcpy(buf, tailMergeX86, sizeof(tailMergeX86));
write32le(buf + 4, desc->getRVA() + config->imageBase);
write32le(buf + 9, helper->getRVA() - rva - 13);
}
void getBaserels(std::vector<Baserel> *res) override {
res->emplace_back(rva + 4);
}
Chunk *desc = nullptr;
Defined *helper = nullptr;
};
class ThunkChunkARM : public NonSectionChunk {
public:
ThunkChunkARM(Defined *i, Chunk *tm) : imp(i), tailMerge(tm) {}
size_t getSize() const override { return sizeof(thunkARM); }
void writeTo(uint8_t *buf) const override {
memcpy(buf, thunkARM, sizeof(thunkARM));
applyMOV32T(buf + 0, imp->getRVA() + config->imageBase);
applyBranch24T(buf + 8, tailMerge->getRVA() - rva - 12);
}
void getBaserels(std::vector<Baserel> *res) override {
res->emplace_back(rva + 0, IMAGE_REL_BASED_ARM_MOV32T);
}
Defined *imp = nullptr;
Chunk *tailMerge = nullptr;
};
class TailMergeChunkARM : public NonSectionChunk {
public:
TailMergeChunkARM(Chunk *d, Defined *h) : desc(d), helper(h) {}
size_t getSize() const override { return sizeof(tailMergeARM); }
void writeTo(uint8_t *buf) const override {
memcpy(buf, tailMergeARM, sizeof(tailMergeARM));
applyMOV32T(buf + 14, desc->getRVA() + config->imageBase);
applyBranch24T(buf + 22, helper->getRVA() - rva - 26);
}
void getBaserels(std::vector<Baserel> *res) override {
res->emplace_back(rva + 14, IMAGE_REL_BASED_ARM_MOV32T);
}
Chunk *desc = nullptr;
Defined *helper = nullptr;
};
class ThunkChunkARM64 : public NonSectionChunk {
public:
ThunkChunkARM64(Defined *i, Chunk *tm) : imp(i), tailMerge(tm) {}
size_t getSize() const override { return sizeof(thunkARM64); }
void writeTo(uint8_t *buf) const override {
memcpy(buf, thunkARM64, sizeof(thunkARM64));
applyArm64Addr(buf + 0, imp->getRVA(), rva + 0, 12);
applyArm64Imm(buf + 4, imp->getRVA() & 0xfff, 0);
applyArm64Branch26(buf + 8, tailMerge->getRVA() - rva - 8);
}
Defined *imp = nullptr;
Chunk *tailMerge = nullptr;
};
class TailMergeChunkARM64 : public NonSectionChunk {
public:
TailMergeChunkARM64(Chunk *d, Defined *h) : desc(d), helper(h) {}
size_t getSize() const override { return sizeof(tailMergeARM64); }
void writeTo(uint8_t *buf) const override {
memcpy(buf, tailMergeARM64, sizeof(tailMergeARM64));
applyArm64Addr(buf + 44, desc->getRVA(), rva + 44, 12);
applyArm64Imm(buf + 48, desc->getRVA() & 0xfff, 0);
applyArm64Branch26(buf + 52, helper->getRVA() - rva - 52);
}
Chunk *desc = nullptr;
Defined *helper = nullptr;
};
// A chunk for the import descriptor table.
class DelayAddressChunk : public NonSectionChunk {
public:
explicit DelayAddressChunk(Chunk *c) : thunk(c) {
setAlignment(config->wordsize);
}
size_t getSize() const override { return config->wordsize; }
void writeTo(uint8_t *buf) const override {
if (config->is64()) {
write64le(buf, thunk->getRVA() + config->imageBase);
} else {
uint32_t bit = 0;
// Pointer to thumb code must have the LSB set, so adjust it.
if (config->machine == ARMNT)
bit = 1;
write32le(buf, (thunk->getRVA() + config->imageBase) | bit);
}
}
void getBaserels(std::vector<Baserel> *res) override {
res->emplace_back(rva);
}
Chunk *thunk;
};
// Export table
// Read Microsoft PE/COFF spec 5.3 for details.
// A chunk for the export descriptor table.
class ExportDirectoryChunk : public NonSectionChunk {
public:
ExportDirectoryChunk(int i, int j, Chunk *d, Chunk *a, Chunk *n, Chunk *o)
: maxOrdinal(i), nameTabSize(j), dllName(d), addressTab(a), nameTab(n),
ordinalTab(o) {}
size_t getSize() const override {
return sizeof(export_directory_table_entry);
}
void writeTo(uint8_t *buf) const override {
memset(buf, 0, getSize());
auto *e = (export_directory_table_entry *)(buf);
e->NameRVA = dllName->getRVA();
e->OrdinalBase = 0;
e->AddressTableEntries = maxOrdinal + 1;
e->NumberOfNamePointers = nameTabSize;
e->ExportAddressTableRVA = addressTab->getRVA();
e->NamePointerRVA = nameTab->getRVA();
e->OrdinalTableRVA = ordinalTab->getRVA();
}
uint16_t maxOrdinal;
uint16_t nameTabSize;
Chunk *dllName;
Chunk *addressTab;
Chunk *nameTab;
Chunk *ordinalTab;
};
class AddressTableChunk : public NonSectionChunk {
public:
explicit AddressTableChunk(size_t maxOrdinal) : size(maxOrdinal + 1) {}
size_t getSize() const override { return size * 4; }
void writeTo(uint8_t *buf) const override {
memset(buf, 0, getSize());
for (const Export &e : config->exports) {
uint8_t *p = buf + e.ordinal * 4;
uint32_t bit = 0;
// Pointer to thumb code must have the LSB set, so adjust it.
if (config->machine == ARMNT && !e.data)
bit = 1;
if (e.forwardChunk) {
write32le(p, e.forwardChunk->getRVA() | bit);
} else {
write32le(p, cast<Defined>(e.sym)->getRVA() | bit);
}
}
}
private:
size_t size;
};
class NamePointersChunk : public NonSectionChunk {
public:
explicit NamePointersChunk(std::vector<Chunk *> &v) : chunks(v) {}
size_t getSize() const override { return chunks.size() * 4; }
void writeTo(uint8_t *buf) const override {
for (Chunk *c : chunks) {
write32le(buf, c->getRVA());
buf += 4;
}
}
private:
std::vector<Chunk *> chunks;
};
class ExportOrdinalChunk : public NonSectionChunk {
public:
explicit ExportOrdinalChunk(size_t i) : size(i) {}
size_t getSize() const override { return size * 2; }
void writeTo(uint8_t *buf) const override {
for (Export &e : config->exports) {
if (e.noname)
continue;
write16le(buf, e.ordinal);
buf += 2;
}
}
private:
size_t size;
};
} // anonymous namespace
void IdataContents::create() {
std::vector<std::vector<DefinedImportData *>> v = binImports(imports);
// Create .idata contents for each DLL.
for (std::vector<DefinedImportData *> &syms : v) {
// Create lookup and address tables. If they have external names,
// we need to create hintName chunks to store the names.
// If they don't (if they are import-by-ordinals), we store only
// ordinal values to the table.
size_t base = lookups.size();
for (DefinedImportData *s : syms) {
uint16_t ord = s->getOrdinal();
if (s->getExternalName().empty()) {
lookups.push_back(make<OrdinalOnlyChunk>(ord));
addresses.push_back(make<OrdinalOnlyChunk>(ord));
continue;
}
auto *c = make<HintNameChunk>(s->getExternalName(), ord);
lookups.push_back(make<LookupChunk>(c));
addresses.push_back(make<LookupChunk>(c));
hints.push_back(c);
}
// Terminate with null values.
lookups.push_back(make<NullChunk>(config->wordsize));
addresses.push_back(make<NullChunk>(config->wordsize));
for (int i = 0, e = syms.size(); i < e; ++i)
syms[i]->setLocation(addresses[base + i]);
// Create the import table header.
dllNames.push_back(make<StringChunk>(syms[0]->getDLLName()));
auto *dir = make<ImportDirectoryChunk>(dllNames.back());
dir->lookupTab = lookups[base];
dir->addressTab = addresses[base];
dirs.push_back(dir);
}
// Add null terminator.
dirs.push_back(make<NullChunk>(sizeof(ImportDirectoryTableEntry)));
}
std::vector<Chunk *> DelayLoadContents::getChunks() {
std::vector<Chunk *> v;
v.insert(v.end(), dirs.begin(), dirs.end());
v.insert(v.end(), names.begin(), names.end());
v.insert(v.end(), hintNames.begin(), hintNames.end());
v.insert(v.end(), dllNames.begin(), dllNames.end());
return v;
}
std::vector<Chunk *> DelayLoadContents::getDataChunks() {
std::vector<Chunk *> v;
v.insert(v.end(), moduleHandles.begin(), moduleHandles.end());
v.insert(v.end(), addresses.begin(), addresses.end());
return v;
}
uint64_t DelayLoadContents::getDirSize() {
return dirs.size() * sizeof(delay_import_directory_table_entry);
}
void DelayLoadContents::create(Defined *h) {
helper = h;
std::vector<std::vector<DefinedImportData *>> v = binImports(imports);
// Create .didat contents for each DLL.
for (std::vector<DefinedImportData *> &syms : v) {
// Create the delay import table header.
dllNames.push_back(make<StringChunk>(syms[0]->getDLLName()));
auto *dir = make<DelayDirectoryChunk>(dllNames.back());
size_t base = addresses.size();
Chunk *tm = newTailMergeChunk(dir);
for (DefinedImportData *s : syms) {
Chunk *t = newThunkChunk(s, tm);
auto *a = make<DelayAddressChunk>(t);
addresses.push_back(a);
thunks.push_back(t);
StringRef extName = s->getExternalName();
if (extName.empty()) {
names.push_back(make<OrdinalOnlyChunk>(s->getOrdinal()));
} else {
auto *c = make<HintNameChunk>(extName, 0);
names.push_back(make<LookupChunk>(c));
hintNames.push_back(c);
}
}
thunks.push_back(tm);
// Terminate with null values.
addresses.push_back(make<NullChunk>(8));
names.push_back(make<NullChunk>(8));
for (int i = 0, e = syms.size(); i < e; ++i)
syms[i]->setLocation(addresses[base + i]);
auto *mh = make<NullChunk>(8);
mh->setAlignment(8);
moduleHandles.push_back(mh);
// Fill the delay import table header fields.
dir->moduleHandle = mh;
dir->addressTab = addresses[base];
dir->nameTab = names[base];
dirs.push_back(dir);
}
// Add null terminator.
dirs.push_back(make<NullChunk>(sizeof(delay_import_directory_table_entry)));
}
Chunk *DelayLoadContents::newTailMergeChunk(Chunk *dir) {
switch (config->machine) {
case AMD64:
return make<TailMergeChunkX64>(dir, helper);
case I386:
return make<TailMergeChunkX86>(dir, helper);
case ARMNT:
return make<TailMergeChunkARM>(dir, helper);
case ARM64:
return make<TailMergeChunkARM64>(dir, helper);
default:
llvm_unreachable("unsupported machine type");
}
}
Chunk *DelayLoadContents::newThunkChunk(DefinedImportData *s,
Chunk *tailMerge) {
switch (config->machine) {
case AMD64:
return make<ThunkChunkX64>(s, tailMerge);
case I386:
return make<ThunkChunkX86>(s, tailMerge);
case ARMNT:
return make<ThunkChunkARM>(s, tailMerge);
case ARM64:
return make<ThunkChunkARM64>(s, tailMerge);
default:
llvm_unreachable("unsupported machine type");
}
}
EdataContents::EdataContents() {
uint16_t maxOrdinal = 0;
for (Export &e : config->exports)
maxOrdinal = std::max(maxOrdinal, e.ordinal);
auto *dllName = make<StringChunk>(sys::path::filename(config->outputFile));
auto *addressTab = make<AddressTableChunk>(maxOrdinal);
std::vector<Chunk *> names;
for (Export &e : config->exports)
if (!e.noname)
names.push_back(make<StringChunk>(e.exportName));
std::vector<Chunk *> forwards;
for (Export &e : config->exports) {
if (e.forwardTo.empty())
continue;
e.forwardChunk = make<StringChunk>(e.forwardTo);
forwards.push_back(e.forwardChunk);
}
auto *nameTab = make<NamePointersChunk>(names);
auto *ordinalTab = make<ExportOrdinalChunk>(names.size());
auto *dir = make<ExportDirectoryChunk>(maxOrdinal, names.size(), dllName,
addressTab, nameTab, ordinalTab);
chunks.push_back(dir);
chunks.push_back(dllName);
chunks.push_back(addressTab);
chunks.push_back(nameTab);
chunks.push_back(ordinalTab);
chunks.insert(chunks.end(), names.begin(), names.end());
chunks.insert(chunks.end(), forwards.begin(), forwards.end());
}
} // namespace coff
} // namespace lld
| 32.666214 | 80 | 0.629408 | [
"object",
"vector"
] |
40d330e30a7e0481b869827f8b32ffcec7626b7f | 2,534 | cc | C++ | kaldifeat/python/csrc/feature-mfcc.cc | EmreOzkose/kaldifeat | 4544a4e9f1d09af7797575f2e31156897f3dddab | [
"Apache-2.0"
] | 59 | 2021-02-26T17:10:12.000Z | 2022-03-29T02:25:36.000Z | kaldifeat/python/csrc/feature-mfcc.cc | EmreOzkose/kaldifeat | 4544a4e9f1d09af7797575f2e31156897f3dddab | [
"Apache-2.0"
] | 10 | 2021-10-15T11:07:51.000Z | 2022-03-09T16:44:38.000Z | kaldifeat/python/csrc/feature-mfcc.cc | EmreOzkose/kaldifeat | 4544a4e9f1d09af7797575f2e31156897f3dddab | [
"Apache-2.0"
] | 12 | 2021-07-18T20:21:49.000Z | 2022-03-15T09:00:38.000Z | // kaldifeat/python/csrc/feature-mfcc.cc
//
// Copyright (c) 2021 Xiaomi Corporation (authors: Fangjun Kuang)
#include "kaldifeat/python/csrc/feature-mfcc.h"
#include <memory>
#include <string>
#include "kaldifeat/csrc/feature-mfcc.h"
#include "kaldifeat/python/csrc/utils.h"
namespace kaldifeat {
void PybindMfccOptions(py::module &m) {
using PyClass = MfccOptions;
py::class_<PyClass>(m, "MfccOptions")
.def(py::init<>())
.def_readwrite("frame_opts", &PyClass::frame_opts)
.def_readwrite("mel_opts", &PyClass::mel_opts)
.def_readwrite("num_ceps", &PyClass::num_ceps)
.def_readwrite("use_energy", &PyClass::use_energy)
.def_readwrite("energy_floor", &PyClass::energy_floor)
.def_readwrite("raw_energy", &PyClass::raw_energy)
.def_readwrite("cepstral_lifter", &PyClass::cepstral_lifter)
.def_readwrite("htk_compat", &PyClass::htk_compat)
.def_property(
"device",
[](const PyClass &self) -> py::object {
py::object ans = py::module_::import("torch").attr("device");
return ans(self.device.str());
},
[](PyClass &self, py::object obj) -> void {
std::string s = static_cast<py::str>(obj);
self.device = torch::Device(s);
})
.def("__str__",
[](const PyClass &self) -> std::string { return self.ToString(); })
.def("as_dict",
[](const PyClass &self) -> py::dict { return AsDict(self); })
.def_static(
"from_dict",
[](py::dict dict) -> PyClass { return MfccOptionsFromDict(dict); })
.def(py::pickle(
[](const PyClass &self) -> py::dict { return AsDict(self); },
[](py::dict dict) -> PyClass { return MfccOptionsFromDict(dict); }));
}
static void PybindMfcc(py::module &m) {
using PyClass = Mfcc;
py::class_<PyClass>(m, "Mfcc")
.def(py::init<const MfccOptions &>(), py::arg("opts"))
.def("dim", &PyClass::Dim)
.def_property_readonly("options", &PyClass::GetOptions)
.def("compute_features", &PyClass::ComputeFeatures, py::arg("wave"),
py::arg("vtln_warp"))
.def(py::pickle(
[](const PyClass &self) -> py::dict {
return AsDict(self.GetOptions());
},
[](py::dict dict) -> std::unique_ptr<PyClass> {
return std::make_unique<PyClass>(MfccOptionsFromDict(dict));
}));
}
void PybindFeatureMfcc(py::module &m) {
PybindMfccOptions(m);
PybindMfcc(m);
}
} // namespace kaldifeat
| 35.194444 | 79 | 0.60221 | [
"object"
] |
40d5ef478fd52639ef66b7cfbf15d4d5a387a841 | 3,032 | cpp | C++ | src/cmd_vel_subscribers.cpp | MNowickixBerry/yocs_cmd_vel_mux | a5a1b32285d5d836382fcf3756c86dbc11319e9f | [
"BSD-3-Clause"
] | 30 | 2016-01-22T17:51:44.000Z | 2021-11-24T06:31:56.000Z | src/cmd_vel_subscribers.cpp | MNowickixBerry/yocs_cmd_vel_mux | a5a1b32285d5d836382fcf3756c86dbc11319e9f | [
"BSD-3-Clause"
] | 18 | 2015-01-12T19:17:18.000Z | 2020-03-15T14:08:32.000Z | src/cmd_vel_subscribers.cpp | MNowickixBerry/yocs_cmd_vel_mux | a5a1b32285d5d836382fcf3756c86dbc11319e9f | [
"BSD-3-Clause"
] | 26 | 2015-03-21T18:06:10.000Z | 2021-04-20T20:41:06.000Z | /**
* @file /src/cmd_vel_subscribers.cpp
*
* @brief Subscriber handlers for the yocs_cmd_vel_mux
*
* License: BSD
* https://raw.github.com/yujinrobot/yujin_ocs/hydro/yocs_cmd_vel_mux/LICENSE
**/
/*****************************************************************************
** Includes
*****************************************************************************/
#include <fstream>
#include "yocs_cmd_vel_mux/cmd_vel_subscribers.hpp"
#include "yocs_cmd_vel_mux/exceptions.hpp"
/*****************************************************************************
** Namespaces
*****************************************************************************/
namespace yocs_cmd_vel_mux {
/*****************************************************************************
** Implementation
*****************************************************************************/
void CmdVelSubscribers::CmdVelSubs::operator << (const YAML::Node& node)
{
// Fill attributes with a YAML node content
double new_timeout;
std::string new_topic;
node["name"] >> name;
node["topic"] >> new_topic;
node["timeout"] >> new_timeout;
node["priority"] >> priority;
#ifdef HAVE_NEW_YAMLCPP
if (node["short_desc"]) {
#else
if (node.FindValue("short_desc") != NULL) {
#endif
node["short_desc"] >> short_desc;
}
if (new_topic != topic)
{
// Shutdown the topic if the name has changed so it gets recreated on configuration reload
// In the case of new subscribers, topic is empty and shutdown has just no effect
topic = new_topic;
subs.shutdown();
}
if (new_timeout != timeout)
{
// Change timer period if the timeout changed
timeout = new_timeout;
timer.setPeriod(ros::Duration(timeout));
}
}
void CmdVelSubscribers::configure(const YAML::Node& node)
{
try
{
if (node.size() == 0)
{
throw EmptyCfgException("Configuration is empty");
}
std::vector<std::shared_ptr<CmdVelSubs>> new_list(node.size());
for (unsigned int i = 0; i < node.size(); i++)
{
// Parse entries on YAML
std::string new_subs_name = node[i]["name"].Scalar();
auto old_subs = std::find_if(list.begin(), list.end(),
[&new_subs_name](const std::shared_ptr<CmdVelSubs>& subs)
{return subs->name == new_subs_name;});
if (old_subs != list.end())
{
// For names already in the subscribers list, retain current object so we don't re-subscribe to the topic
new_list[i] = *old_subs;
}
else
{
new_list[i] = std::make_shared<CmdVelSubs>(i);
}
// update existing or new object with the new configuration
*new_list[i] << node[i];
}
list = new_list;
}
catch(EmptyCfgException& e) {
throw e;
}
catch(YAML::ParserException& e)
{
throw YamlException(e.what());
}
catch(YAML::RepresentationException& e)
{
throw YamlException(e.what());
}
}
} // namespace yocs_cmd_vel_mux
| 28.074074 | 113 | 0.530673 | [
"object",
"vector"
] |
40dab93318c5e65a9332ee0a93059b133398f615 | 11,712 | cpp | C++ | source/Lesson6_4/NormalMappingDemo.cpp | DakkyDaWolf/OpenGL | 628e9aed116022175cc0c59c88ace7688309628c | [
"MIT"
] | null | null | null | source/Lesson6_4/NormalMappingDemo.cpp | DakkyDaWolf/OpenGL | 628e9aed116022175cc0c59c88ace7688309628c | [
"MIT"
] | null | null | null | source/Lesson6_4/NormalMappingDemo.cpp | DakkyDaWolf/OpenGL | 628e9aed116022175cc0c59c88ace7688309628c | [
"MIT"
] | null | null | null | #include "pch.h"
#include "NormalMappingDemo.h"
#include "VertexDeclarations.h"
#include "VectorHelper.h"
#include "DirectionalLight.h"
#include "Camera.h"
#include "ProxyModel.h"
using namespace glm;
using namespace std;
using namespace Library;
namespace Rendering
{
RTTI_DEFINITIONS(NormalMappingDemo)
NormalMappingDemo::NormalMappingDemo(Game& game, shared_ptr<Camera> camera) :
DrawableGameComponent(game, move(camera))
{
}
NormalMappingDemo::~NormalMappingDemo()
{
mGame->RemoveKeyboardHandler(mKeyboardHandler);
glDeleteSamplers(1, &mTrilinearSampler);
glDeleteTextures(1, &mNormalMap);
glDeleteTextures(1, &mColorTexture);
glDeleteBuffers(1, &mIndexBuffer);
glDeleteBuffers(1, &mNormalMappingVertexBuffer);
glDeleteBuffers(1, &mFogVertexBuffer);
glDeleteVertexArrays(1, &mFogVAO);
glDeleteVertexArrays(1, &mNormalMappingVAO);
}
void NormalMappingDemo::Initialize()
{
// Build the shader programs
vector<ShaderDefinition> shaders;
shaders.push_back(ShaderDefinition(GL_VERTEX_SHADER, "Content/Effects/NormalMappingDemo.vert"));
shaders.push_back(ShaderDefinition(GL_FRAGMENT_SHADER, "Content/Effects/NormalMappingDemo.frag"));
mNormalMappingEffect.BuildProgram(shaders);
shaders.clear();
shaders.push_back(ShaderDefinition(GL_VERTEX_SHADER, "Content/Effects/FogDemo.vert"));
shaders.push_back(ShaderDefinition(GL_FRAGMENT_SHADER, "Content/Effects/FogDemo.frag"));
mFogEffect.BuildProgram(shaders);
// Load the color texture
mColorTexture = SOIL_load_OGL_texture("Content/Textures/Blocks_COLOR.tga", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT);
if (mColorTexture == 0)
{
throw runtime_error("SOIL_load_OGL_texture() failed.");
}
// Load the normal map
mNormalMap = SOIL_load_OGL_texture("Content/Textures/Blocks_NORM.tga", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT);
if (mNormalMap == 0)
{
throw runtime_error("SOIL_load_OGL_texture() failed.");
}
// Create the trilinear texture sampler
glGenSamplers(1, &mTrilinearSampler);
glSamplerParameteri(mTrilinearSampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glSamplerParameteri(mTrilinearSampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glSamplerParameteri(mTrilinearSampler, GL_TEXTURE_WRAP_S, GL_REPEAT);
glSamplerParameteri(mTrilinearSampler, GL_TEXTURE_WRAP_T, GL_REPEAT);
// Create the normal mapping vertex array object
glGenVertexArrays(1, &mNormalMappingVAO);
glBindVertexArray(mNormalMappingVAO);
// Create the normal mapping vertex buffer
const VertexPositionTextureNormalTangentBinormal normalMappingVertices[] =
{
VertexPositionTextureNormalTangentBinormal(vec4(-1.0f, 0.1f, 0.0f, 1.0f), vec2(0.0f, 1.0f), Vector3Helper::Backward, Vector3Helper::Down, Vector3Helper::Right),
VertexPositionTextureNormalTangentBinormal(vec4(-1.0f, 2.1f, 0.0f, 1.0f), vec2(0.0f, 0.0f), Vector3Helper::Backward, Vector3Helper::Down, Vector3Helper::Right),
VertexPositionTextureNormalTangentBinormal(vec4(1.0f, 2.1f, 0.0f, 1.0f), vec2(1.0f, 0.0f), Vector3Helper::Backward, Vector3Helper::Down, Vector3Helper::Right),
VertexPositionTextureNormalTangentBinormal(vec4(1.0f, 0.1f, 0.0f, 1.0f), vec2(1.0f, 1.0f), Vector3Helper::Backward, Vector3Helper::Down, Vector3Helper::Right)
};
VertexPositionTextureNormalTangentBinormal::CreateVertexBuffer(normalMappingVertices, mNormalMappingVertexBuffer);
mNormalMappingEffect.Initialize(mNormalMappingVAO);
// Create the fog vertex array object
glGenVertexArrays(1, &mFogVAO);
glBindVertexArray(mFogVAO);
// Create the fog vertex buffer
VertexPositionTextureNormal fogVertices[] =
{
VertexPositionTextureNormal(vec4(-1.0f, 0.1f, 0.0f, 1.0f), vec2(0.0f, 1.0f), Vector3Helper::Backward),
VertexPositionTextureNormal(vec4(-1.0f, 2.1f, 0.0f, 1.0f), vec2(0.0f, 0.0f), Vector3Helper::Backward),
VertexPositionTextureNormal(vec4(1.0f, 2.1f, 0.0f, 1.0f), vec2(1.0f, 0.0f), Vector3Helper::Backward),
VertexPositionTextureNormal(vec4(1.0f, 0.1f, 0.0f, 1.0f), vec2(1.0f, 1.0f), Vector3Helper::Backward)
};
VertexPositionTextureNormal::CreateVertexBuffer(fogVertices, mFogVertexBuffer);
mFogEffect.Initialize(mFogVAO);
glBindVertexArray(0);
// Create the index buffer
const uint32_t indices[] =
{
0, 2, 1,
0, 3, 2
};
mIndexCount = std::size(indices);
glGenBuffers(1, &mIndexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint32_t) * mIndexCount, indices, GL_STATIC_DRAW);
mAmbientLight = make_unique<Light>(*mGame);
mAmbientLight->SetColor(ColorHelper::Black);
mDirectionalLight = make_unique<DirectionalLight>(*mGame);
mProxyModel = make_unique<ProxyModel>(*mGame, mCamera, "Content/Models/DirectionalLightProxy.obj", 0.5f);
mProxyModel->Initialize();
mProxyModel->SetPosition(10.0f, 0.0, 0.0f);
mProxyModel->ApplyRotation(rotate(mat4(1), half_pi<float>(), Vector3Helper::Up));
mWorldMatrix = scale(mat4(1), vec3(5.0f));
// Attach the keyboard handler
using namespace std::placeholders;
mKeyboardHandler = bind(&NormalMappingDemo::OnKey, this, _1, _2, _3, _4);
mGame->AddKeyboardHandler(mKeyboardHandler);
}
void NormalMappingDemo::Update(const GameTime& gameTime)
{
UpdateAmbientLight(gameTime);
UpdateDirectionalLight(gameTime);
UpdateSpecularLight(gameTime);
mProxyModel->Update(gameTime);
}
void NormalMappingDemo::Draw(const GameTime& gameTime)
{
if (mShowNormalMapping)
{
glBindVertexArray(mNormalMappingVAO);
glBindBuffer(GL_ARRAY_BUFFER, mNormalMappingVertexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
mNormalMappingEffect.Use();
mat4 wvp = mCamera->ViewProjectionMatrix() * mWorldMatrix;
mNormalMappingEffect.WorldViewProjection() << wvp;
mNormalMappingEffect.World() << mWorldMatrix;
mNormalMappingEffect.AmbientColor() << mAmbientLight->Color();
mNormalMappingEffect.LightColor() << mDirectionalLight->Color();
mNormalMappingEffect.LightDirection() << mDirectionalLight->Direction();
mNormalMappingEffect.CameraPosition() << mCamera->Position();
mNormalMappingEffect.SpecularColor() << mSpecularColor;
mNormalMappingEffect.SpecularPower() << mSpecularPower;
mNormalMappingEffect.FogColor() << mFogColor;
mNormalMappingEffect.FogStart() << mFogStart;
mNormalMappingEffect.FogRange() << mFogRange;
glBindSampler(0, mTrilinearSampler);
glBindSampler(1, mTrilinearSampler);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mColorTexture);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, mNormalMap);
}
else
{
glBindVertexArray(mFogVAO);
glBindBuffer(GL_ARRAY_BUFFER, mFogVertexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
mFogEffect.Use();
mat4 wvp = mCamera->ViewProjectionMatrix() * mWorldMatrix;
mFogEffect.WorldViewProjection() << wvp;
mFogEffect.World() << mWorldMatrix;
mFogEffect.AmbientColor() << mAmbientLight->Color();
mFogEffect.LightColor() << mDirectionalLight->Color();
mFogEffect.LightDirection() << mDirectionalLight->Direction();
mFogEffect.CameraPosition() << mCamera->Position();
mFogEffect.SpecularColor() << mSpecularColor;
mFogEffect.SpecularPower() << mSpecularPower;
mFogEffect.FogColor() << mFogColor;
mFogEffect.FogStart() << mFogStart;
mFogEffect.FogRange() << mFogRange;
glBindSampler(0, mTrilinearSampler);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mColorTexture);
}
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(mIndexCount), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
mProxyModel->Draw(gameTime);
}
void NormalMappingDemo::UpdateAmbientLight(const GameTime& gameTime)
{
static float ambientIntensity = mAmbientLight->Color().r;
if (glfwGetKey(mGame->Window(), GLFW_KEY_PAGE_UP) && ambientIntensity < 1.0f)
{
ambientIntensity += gameTime.ElapsedGameTimeSeconds().count();
ambientIntensity = std::min(ambientIntensity, 1.0f);
mAmbientLight->SetColor(vec4((vec3)ambientIntensity, 1.0f));
}
if (glfwGetKey(mGame->Window(), GLFW_KEY_PAGE_DOWN) && ambientIntensity > 0.0f)
{
ambientIntensity -= gameTime.ElapsedGameTimeSeconds().count();
ambientIntensity = std::max(ambientIntensity, 0.0f);
mAmbientLight->SetColor(vec4((vec3)ambientIntensity, 1.0f));
}
}
void NormalMappingDemo::UpdateDirectionalLight(const GameTime& gameTime)
{
static float directionalIntensity = 1.0f;
float elapsedTime = gameTime.ElapsedGameTimeSeconds().count();
// Upddate directional light intensity
if (glfwGetKey(mGame->Window(), GLFW_KEY_HOME) && directionalIntensity < 1.0f)
{
directionalIntensity += elapsedTime;
directionalIntensity = std::min(directionalIntensity, 1.0f);
mDirectionalLight->SetColor(vec4((vec3)directionalIntensity, 1.0f));
}
if (glfwGetKey(mGame->Window(), GLFW_KEY_END) && directionalIntensity > 0.0f)
{
directionalIntensity -= elapsedTime;
directionalIntensity = std::max(directionalIntensity, 0.0f);
mDirectionalLight->SetColor(vec4((vec3)directionalIntensity, 1.0f));
}
// Rotate directional light
vec2 rotationAmount = Vector2Helper::Zero;
if (glfwGetKey(mGame->Window(), GLFW_KEY_LEFT))
{
rotationAmount.x += LightRotationRate.x * elapsedTime;
}
if (glfwGetKey(mGame->Window(), GLFW_KEY_RIGHT))
{
rotationAmount.x -= LightRotationRate.x * elapsedTime;
}
if (glfwGetKey(mGame->Window(), GLFW_KEY_UP))
{
rotationAmount.y += LightRotationRate.y * elapsedTime;
}
if (glfwGetKey(mGame->Window(), GLFW_KEY_DOWN))
{
rotationAmount.y -= LightRotationRate.y * elapsedTime;
}
mat4 lightRotationMatrix(1);
if (rotationAmount.x != 0)
{
lightRotationMatrix = rotate(mat4(1), rotationAmount.x, Vector3Helper::Up);
}
if (rotationAmount.y != 0)
{
lightRotationMatrix = rotate(lightRotationMatrix, rotationAmount.y, mDirectionalLight->Right());
}
if (rotationAmount.x != 0.0f || rotationAmount.y != 0.0f)
{
mDirectionalLight->ApplyRotation(lightRotationMatrix);
mProxyModel->ApplyRotation(lightRotationMatrix);
}
}
void NormalMappingDemo::UpdateSpecularLight(const GameTime& gameTime)
{
static float specularIntensity = 1.0f;
if (glfwGetKey(mGame->Window(), GLFW_KEY_INSERT) && specularIntensity < 1.0f)
{
specularIntensity += gameTime.ElapsedGameTimeSeconds().count();
specularIntensity = std::min(specularIntensity, 1.0f);
mSpecularColor = (vec4((vec3)specularIntensity, 1.0f));
}
if (glfwGetKey(mGame->Window(), GLFW_KEY_DELETE) && specularIntensity > 0.0f)
{
specularIntensity -= gameTime.ElapsedGameTimeSeconds().count();
specularIntensity = std::max(specularIntensity, 0.0f);
mSpecularColor = (vec4((vec3)specularIntensity, 1.0f));
}
static float specularPower = mSpecularPower;
if (glfwGetKey(mGame->Window(), GLFW_KEY_O) && specularPower < UCHAR_MAX)
{
specularPower += LightModulationRate * gameTime.ElapsedGameTimeSeconds().count();
specularPower = std::min(specularPower, static_cast<float>(UCHAR_MAX));
mSpecularPower = specularPower;
}
if (glfwGetKey(mGame->Window(), GLFW_KEY_P) && specularPower > 0.0f)
{
specularPower -= LightModulationRate * gameTime.ElapsedGameTimeSeconds().count();
specularPower = std::max(specularPower, 0.0f);
mSpecularPower = specularPower;
}
}
void NormalMappingDemo::OnKey(int key, int /*scancode*/, int action, int /*mods*/)
{
if (key == GLFW_KEY_SPACE && action == GLFW_PRESS)
{
mShowNormalMapping = !mShowNormalMapping;
}
}
} | 34.961194 | 186 | 0.752049 | [
"object",
"vector"
] |
40dad05c14581cc62d9fd2acd631b85634380d4d | 13,875 | cc | C++ | components/sync/test/model/fake_model_type_sync_bridge.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-10-18T02:33:40.000Z | 2020-10-18T02:33:40.000Z | components/sync/test/model/fake_model_type_sync_bridge.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2021-05-17T16:28:52.000Z | 2021-05-21T22:42:22.000Z | components/sync/test/model/fake_model_type_sync_bridge.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2015 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 "components/sync/test/model/fake_model_type_sync_bridge.h"
#include <set>
#include <utility>
#include "base/bind.h"
#include "base/containers/contains.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "components/sync/base/client_tag_hash.h"
#include "components/sync/model/conflict_resolution.h"
#include "components/sync/model/in_memory_metadata_change_list.h"
#include "components/sync/model/model_type_store.h"
#include "components/sync/model/mutable_data_batch.h"
#include "testing/gtest/include/gtest/gtest.h"
using sync_pb::EntityMetadata;
using sync_pb::EntitySpecifics;
using sync_pb::ModelTypeState;
namespace syncer {
namespace {
// MetadataChangeList implementaton that forwards writes metadata to a store.
class TestMetadataChangeList : public MetadataChangeList {
public:
explicit TestMetadataChangeList(FakeModelTypeSyncBridge::Store* db)
: db_(db) {}
~TestMetadataChangeList() override {}
// MetadataChangeList implementation.
void UpdateModelTypeState(
const sync_pb::ModelTypeState& model_type_state) override {
db_->set_model_type_state(model_type_state);
}
void ClearModelTypeState() override {
db_->set_model_type_state(ModelTypeState());
}
void UpdateMetadata(const std::string& storage_key,
const sync_pb::EntityMetadata& metadata) override {
DCHECK(!storage_key.empty());
db_->PutMetadata(storage_key, metadata);
}
void ClearMetadata(const std::string& storage_key) override {
DCHECK(!storage_key.empty());
db_->RemoveMetadata(storage_key);
}
private:
FakeModelTypeSyncBridge::Store* db_;
};
} // namespace
// static
std::string FakeModelTypeSyncBridge::ClientTagFromKey(const std::string& key) {
return "ClientTag_" + key;
}
// static
ClientTagHash FakeModelTypeSyncBridge::TagHashFromKey(const std::string& key) {
return ClientTagHash::FromUnhashed(
PREFERENCES, FakeModelTypeSyncBridge::ClientTagFromKey(key));
}
// static
EntitySpecifics FakeModelTypeSyncBridge::GenerateSpecifics(
const std::string& key,
const std::string& value) {
EntitySpecifics specifics;
specifics.mutable_preference()->set_name(key);
specifics.mutable_preference()->set_value(value);
return specifics;
}
// static
std::unique_ptr<EntityData> FakeModelTypeSyncBridge::GenerateEntityData(
const std::string& key,
const std::string& value) {
std::unique_ptr<EntityData> entity_data = std::make_unique<EntityData>();
entity_data->client_tag_hash = TagHashFromKey(key);
entity_data->specifics = GenerateSpecifics(key, value);
entity_data->name = key;
return entity_data;
}
FakeModelTypeSyncBridge::Store::Store() {}
FakeModelTypeSyncBridge::Store::~Store() {}
void FakeModelTypeSyncBridge::Store::PutData(const std::string& key,
const EntityData& data) {
data_change_count_++;
data_store_[key] = CopyEntityData(data);
}
void FakeModelTypeSyncBridge::Store::PutMetadata(
const std::string& key,
const EntityMetadata& metadata) {
metadata_change_count_++;
metadata_store_[key] = metadata;
}
void FakeModelTypeSyncBridge::Store::RemoveData(const std::string& key) {
data_change_count_++;
data_store_.erase(key);
}
void FakeModelTypeSyncBridge::Store::ClearAllData() {
data_change_count_++;
data_store_.clear();
}
void FakeModelTypeSyncBridge::Store::RemoveMetadata(const std::string& key) {
metadata_change_count_++;
metadata_store_.erase(key);
}
bool FakeModelTypeSyncBridge::Store::HasData(const std::string& key) const {
return data_store_.find(key) != data_store_.end();
}
bool FakeModelTypeSyncBridge::Store::HasMetadata(const std::string& key) const {
return metadata_store_.find(key) != metadata_store_.end();
}
const EntityData& FakeModelTypeSyncBridge::Store::GetData(
const std::string& key) const {
DCHECK(data_store_.count(key) != 0) << " for key " << key;
return *data_store_.find(key)->second;
}
const std::string& FakeModelTypeSyncBridge::Store::GetValue(
const std::string& key) const {
return GetData(key).specifics.preference().value();
}
const sync_pb::EntityMetadata& FakeModelTypeSyncBridge::Store::GetMetadata(
const std::string& key) const {
return metadata_store_.find(key)->second;
}
std::unique_ptr<MetadataBatch>
FakeModelTypeSyncBridge::Store::CreateMetadataBatch() const {
auto metadata_batch = std::make_unique<MetadataBatch>();
metadata_batch->SetModelTypeState(model_type_state_);
for (const auto& kv : metadata_store_) {
metadata_batch->AddMetadata(
kv.first, std::make_unique<sync_pb::EntityMetadata>(kv.second));
}
return metadata_batch;
}
void FakeModelTypeSyncBridge::Store::Reset() {
data_change_count_ = 0;
metadata_change_count_ = 0;
data_store_.clear();
metadata_store_.clear();
model_type_state_.Clear();
}
FakeModelTypeSyncBridge::FakeModelTypeSyncBridge(
std::unique_ptr<ModelTypeChangeProcessor> change_processor)
: ModelTypeSyncBridge(std::move(change_processor)),
db_(std::make_unique<Store>()) {}
FakeModelTypeSyncBridge::~FakeModelTypeSyncBridge() {
EXPECT_FALSE(error_next_);
}
EntitySpecifics FakeModelTypeSyncBridge::WriteItem(const std::string& key,
const std::string& value) {
std::unique_ptr<EntityData> entity_data = GenerateEntityData(key, value);
EntitySpecifics specifics_copy = entity_data->specifics;
WriteItem(key, std::move(entity_data));
return specifics_copy;
}
// Overloaded form to allow passing of custom entity data.
void FakeModelTypeSyncBridge::WriteItem(
const std::string& key,
std::unique_ptr<EntityData> entity_data) {
DCHECK(EntityHasClientTag(*entity_data));
db_->PutData(key, *entity_data);
if (change_processor()->IsTrackingMetadata()) {
auto change_list = CreateMetadataChangeList();
change_processor()->Put(key, std::move(entity_data), change_list.get());
ApplyMetadataChangeList(std::move(change_list));
}
}
void FakeModelTypeSyncBridge::DeleteItem(const std::string& key) {
db_->RemoveData(key);
if (change_processor()->IsTrackingMetadata()) {
auto change_list = CreateMetadataChangeList();
change_processor()->Delete(key, change_list.get());
ApplyMetadataChangeList(std::move(change_list));
}
}
void FakeModelTypeSyncBridge::MimicBugToLooseItemWithoutNotifyingProcessor(
const std::string& key) {
db_->RemoveData(key);
}
std::unique_ptr<MetadataChangeList>
FakeModelTypeSyncBridge::CreateMetadataChangeList() {
return std::make_unique<InMemoryMetadataChangeList>();
}
absl::optional<ModelError> FakeModelTypeSyncBridge::MergeSyncData(
std::unique_ptr<MetadataChangeList> metadata_change_list,
EntityChangeList entity_data) {
if (error_next_) {
error_next_ = false;
return ModelError(FROM_HERE, "boom");
}
std::set<std::string> remote_storage_keys;
// Store any new remote entities.
for (const auto& change : entity_data) {
EXPECT_FALSE(change->data().is_deleted());
EXPECT_EQ(EntityChange::ACTION_ADD, change->type());
std::string storage_key = change->storage_key();
EXPECT_NE(SupportsGetStorageKey(), storage_key.empty());
if (storage_key.empty()) {
if (base::Contains(values_to_ignore_,
change->data().specifics.preference().value())) {
change_processor()->UntrackEntityForClientTagHash(
change->data().client_tag_hash);
continue;
}
storage_key = GenerateStorageKey(change->data());
change_processor()->UpdateStorageKey(change->data(), storage_key,
metadata_change_list.get());
}
remote_storage_keys.insert(storage_key);
DCHECK(EntityHasClientTag(change->data()));
db_->PutData(storage_key, change->data());
}
// Commit any local entities that aren't being overwritten by the server.
for (const auto& kv : db_->all_data()) {
if (remote_storage_keys.find(kv.first) == remote_storage_keys.end()) {
change_processor()->Put(kv.first, CopyEntityData(*kv.second),
metadata_change_list.get());
}
}
ApplyMetadataChangeList(std::move(metadata_change_list));
return {};
}
absl::optional<ModelError> FakeModelTypeSyncBridge::ApplySyncChanges(
std::unique_ptr<MetadataChangeList> metadata_changes,
EntityChangeList entity_changes) {
if (error_next_) {
error_next_ = false;
return ModelError(FROM_HERE, "boom");
}
for (const std::unique_ptr<EntityChange>& change : entity_changes) {
switch (change->type()) {
case EntityChange::ACTION_ADD: {
std::string storage_key = change->storage_key();
EXPECT_NE(SupportsGetStorageKey(), storage_key.empty());
if (storage_key.empty()) {
storage_key = GenerateStorageKey(change->data());
change_processor()->UpdateStorageKey(change->data(), storage_key,
metadata_changes.get());
}
DCHECK(EntityHasClientTag(change->data()));
EXPECT_FALSE(db_->HasData(storage_key));
db_->PutData(storage_key, change->data());
break;
}
case EntityChange::ACTION_UPDATE:
DCHECK(EntityHasClientTag(change->data()));
EXPECT_TRUE(db_->HasData(change->storage_key()));
db_->PutData(change->storage_key(), change->data());
break;
case EntityChange::ACTION_DELETE:
EXPECT_TRUE(db_->HasData(change->storage_key()));
db_->RemoveData(change->storage_key());
break;
}
}
ApplyMetadataChangeList(std::move(metadata_changes));
return {};
}
void FakeModelTypeSyncBridge::ApplyMetadataChangeList(
std::unique_ptr<MetadataChangeList> mcl) {
InMemoryMetadataChangeList* in_memory_mcl =
static_cast<InMemoryMetadataChangeList*>(mcl.get());
// Use TestMetadataChangeList to commit all metadata changes to the store.
TestMetadataChangeList db_mcl(db_.get());
in_memory_mcl->TransferChangesTo(&db_mcl);
}
void FakeModelTypeSyncBridge::GetData(StorageKeyList keys,
DataCallback callback) {
if (error_next_) {
error_next_ = false;
change_processor()->ReportError({FROM_HERE, "boom"});
return;
}
auto batch = std::make_unique<MutableDataBatch>();
for (const std::string& key : keys) {
if (db_->HasData(key)) {
batch->Put(key, CopyEntityData(db_->GetData(key)));
} else {
DLOG(WARNING) << "No data for " << key;
}
}
std::move(callback).Run(std::move(batch));
}
void FakeModelTypeSyncBridge::GetAllDataForDebugging(DataCallback callback) {
if (error_next_) {
error_next_ = false;
change_processor()->ReportError({FROM_HERE, "boom"});
return;
}
auto batch = std::make_unique<MutableDataBatch>();
for (const auto& kv : db_->all_data()) {
batch->Put(kv.first, CopyEntityData(*kv.second));
}
std::move(callback).Run(std::move(batch));
}
std::string FakeModelTypeSyncBridge::GetClientTag(
const EntityData& entity_data) {
return ClientTagFromKey(entity_data.specifics.preference().name());
}
std::string FakeModelTypeSyncBridge::GetStorageKey(
const EntityData& entity_data) {
DCHECK(supports_get_storage_key_);
return GenerateStorageKey(entity_data);
}
std::string FakeModelTypeSyncBridge::GenerateStorageKey(
const EntityData& entity_data) {
if (supports_get_storage_key_) {
return entity_data.specifics.preference().name();
} else {
return base::NumberToString(++last_generated_storage_key_);
}
}
bool FakeModelTypeSyncBridge::SupportsGetClientTag() const {
return supports_get_client_tag_;
}
bool FakeModelTypeSyncBridge::SupportsGetStorageKey() const {
return supports_get_storage_key_;
}
ConflictResolution FakeModelTypeSyncBridge::ResolveConflict(
const std::string& storage_key,
const EntityData& remote_data) const {
return conflict_resolution_;
}
void FakeModelTypeSyncBridge::ApplyStopSyncChanges(
std::unique_ptr<MetadataChangeList> delete_metadata_change_list) {
ModelTypeSyncBridge::ApplyStopSyncChanges(
std::move(delete_metadata_change_list));
}
void FakeModelTypeSyncBridge::SetConflictResolution(
ConflictResolution resolution) {
conflict_resolution_ = resolution;
}
void FakeModelTypeSyncBridge::ErrorOnNextCall() {
EXPECT_FALSE(error_next_);
error_next_ = true;
}
std::unique_ptr<EntityData> FakeModelTypeSyncBridge::CopyEntityData(
const EntityData& old_data) {
auto new_data = std::make_unique<EntityData>();
new_data->id = old_data.id;
new_data->client_tag_hash = old_data.client_tag_hash;
new_data->name = old_data.name;
new_data->specifics = old_data.specifics;
new_data->creation_time = old_data.creation_time;
new_data->modification_time = old_data.modification_time;
return new_data;
}
void FakeModelTypeSyncBridge::SetSupportsGetClientTag(
bool supports_get_client_tag) {
supports_get_client_tag_ = supports_get_client_tag;
}
bool FakeModelTypeSyncBridge::EntityHasClientTag(const EntityData& entity) {
return supports_get_client_tag_ || !entity.client_tag_hash.value().empty();
}
void FakeModelTypeSyncBridge::SetSupportsGetStorageKey(
bool supports_get_storage_key) {
supports_get_storage_key_ = supports_get_storage_key;
}
std::string FakeModelTypeSyncBridge::GetLastGeneratedStorageKey() const {
// Verify that GenerateStorageKey() was called at least once.
EXPECT_NE(0, last_generated_storage_key_);
return base::NumberToString(last_generated_storage_key_);
}
void FakeModelTypeSyncBridge::AddValueToIgnore(const std::string& value) {
values_to_ignore_.insert(value);
}
} // namespace syncer
| 32.342657 | 80 | 0.727784 | [
"model"
] |
40db59eb306b5d968622492ec05169c9237cca96 | 1,821 | cpp | C++ | Sources/AGEngine/Engine/Components/ArchetypeComponent.cpp | Another-Game-Engine/AGE | d5d9e98235198fe580a43007914f515437635830 | [
"MIT"
] | 47 | 2015-03-29T09:44:25.000Z | 2020-11-30T10:05:56.000Z | Sources/AGEngine/Engine/Components/ArchetypeComponent.cpp | Another-Game-Engine/AGE | d5d9e98235198fe580a43007914f515437635830 | [
"MIT"
] | 313 | 2015-01-01T18:16:30.000Z | 2015-11-30T07:54:07.000Z | Sources/AGEngine/Engine/Components/ArchetypeComponent.cpp | Another-Game-Engine/AGE | d5d9e98235198fe580a43007914f515437635830 | [
"MIT"
] | 9 | 2015-06-07T13:21:54.000Z | 2020-08-25T09:50:07.000Z | #include "ArchetypeComponent.hpp"
#include <imgui/imgui.h>
#include "Entity\IArchetypeManager.hpp"
#include "Entity\Entity.hh"
#include "Core/AScene.hh"
#include "Entity/EntityData.hh"
namespace AGE
{
ArchetypeComponent::ArchetypeComponent()
{
}
#ifdef EDITOR_ENABLED
bool ArchetypeComponent::isExposedInEditor(){ return true; }
bool ArchetypeComponent::editorUpdate()
{
bool modified = false;
modified |= ImGui::Checkbox("Sync Position", &synchronizePosition);
modified |= ImGui::Checkbox("Sync Rotation", &synchronizeRotation);
modified |= ImGui::Checkbox("Sync Scale", &synchronizeScale);
if (modified)
{
entity->getScene()->getInstance<AGE::IArchetypeManager>()->updateArchetype(archetypeName);
}
return modified;
}
#endif
void ArchetypeComponent::init(const std::string &_archetypeName)
{
archetypeName = _archetypeName;
#ifdef EDITOR_ENABLED
synchronizePosition = false;
synchronizeRotation = true;
synchronizeScale = true;
deletableInEditor = false;
#endif
entity->getScene()->getInstance<AGE::IArchetypeManager>()->updateArchetype(archetypeName);
}
void ArchetypeComponent::postUnserialization()
{
}
void ArchetypeComponent::_copyFrom(const ComponentBase *model)
{
// on ne devrait pas passer par la mais par le manager
assert(false);
ArchetypeComponent *m = (ArchetypeComponent *)model;
archetypeName = m->archetypeName;
#ifdef EDITOR_ENABLED
synchronizePosition = m->synchronizePosition;
synchronizeRotation = m->synchronizeRotation;
synchronizeScale = m->synchronizeScale;
deletableInEditor = m->deletableInEditor;
#endif
//entity->getLink()->setPosition(m->entity->getLink().getPosition());
//entity->getLink()->setScale(m->entity->getLink().getScale());
//entity->getLink()->setOrientation(m->entity->getLink().getOrientation());
}
} | 28.904762 | 93 | 0.74849 | [
"model"
] |
40e0423a3aecbcb3e378f9c01c02c0892a54bd20 | 8,138 | hpp | C++ | sensing/preprocessor/pointcloud/pointcloud_preprocessor/include/pointcloud_preprocessor/ground_filter/ray_ground_filter_nodelet.hpp | sgk-000/roboken_autoware | 6e3beadd040135267221439cb16f84380ac8cb1d | [
"Apache-2.0"
] | 88 | 2021-01-16T20:05:40.000Z | 2022-03-21T05:40:35.000Z | sensing/preprocessor/pointcloud/pointcloud_preprocessor/include/pointcloud_preprocessor/ground_filter/ray_ground_filter_nodelet.hpp | sgk-000/roboken_autoware | 6e3beadd040135267221439cb16f84380ac8cb1d | [
"Apache-2.0"
] | 271 | 2021-01-13T16:54:09.000Z | 2022-02-25T16:26:07.000Z | sensing/preprocessor/pointcloud/pointcloud_preprocessor/include/pointcloud_preprocessor/ground_filter/ray_ground_filter_nodelet.hpp | sgk-000/roboken_autoware | 6e3beadd040135267221439cb16f84380ac8cb1d | [
"Apache-2.0"
] | 68 | 2021-01-14T09:16:40.000Z | 2022-03-29T02:15:36.000Z | // Copyright 2020 Tier IV, 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.
// Copyright 2020 Tier IV, 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.
/*
* Copyright 2017-2019 Autoware Foundation. 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.
********************
* v1.0: amc-nu (abrahammonrroy@yahoo.com)
*/
#ifndef POINTCLOUD_PREPROCESSOR__GROUND_FILTER__RAY_GROUND_FILTER_NODELET_HPP_
#define POINTCLOUD_PREPROCESSOR__GROUND_FILTER__RAY_GROUND_FILTER_NODELET_HPP_
#include <chrono>
#include <string>
#include <vector>
#include "sensor_msgs/msg/point_cloud2.hpp"
#include "tf2/transform_datatypes.h"
#include "tf2_eigen/tf2_eigen.h"
#include "tf2_ros/transform_listener.h"
#include "pcl/filters/extract_indices.h"
#include "pcl/filters/voxel_grid.h"
#include "pcl_conversions/pcl_conversions.h"
// #include "pcl_ros/point_cloud.h"
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "boost/geometry.hpp"
#include "boost/geometry/geometries/linestring.hpp"
#include "boost/geometry/geometries/point_xy.hpp"
#include "boost/optional.hpp"
#include "pointcloud_preprocessor/filter.hpp"
#include "pointcloud_preprocessor/ground_filter/gencolors.hpp"
namespace bg = boost::geometry;
using Point = bg::model::d2::point_xy<double>;
using Polygon = bg::model::polygon<Point>;
namespace pointcloud_preprocessor
{
class RayGroundFilterComponent : public pointcloud_preprocessor::Filter
{
typedef pcl::PointXYZ PointType_;
struct PointXYZRTColor
{
pcl::PointXYZ point;
size_t ring; // ring number if available
float radius; // cylindrical coords on XY Plane
float theta; // angle deg on XY plane
size_t radial_div; // index of the radial division to which this point belongs to
size_t red; // Red component [0-255]
size_t green; // Green Component[0-255]
size_t blue; // Blue component [0-255]
size_t original_index; // index of this point in the source pointcloud
};
typedef std::vector<PointXYZRTColor> PointCloudXYZRTColor;
protected:
void filter(
const PointCloud2ConstPtr & input, const IndicesPtr & indices, PointCloud2 & output) override;
private:
std::string base_frame_ = "base_link";
double general_max_slope_; // degrees
double local_max_slope_; // degrees
double initial_max_slope_; // degrees
double radial_divider_angle_; // distance in rads between dividers
double concentric_divider_distance_; // distance in meters between concentric divisions
double // minimum height threshold regardless the slope
min_height_threshold_; // useful for close points
double
reclass_distance_threshold_; // distance between points at which re classification will occur
size_t radial_dividers_num_;
size_t grid_width_;
size_t grid_height_;
double grid_precision_;
cv::Mat previous_occupancy_mat_;
cv::Mat accumulated_occupancy_mat_;
double min_x_;
double max_x_;
double min_y_;
double max_y_;
Polygon vehicle_footprint_;
bool use_vehicle_footprint_;
std::vector<cv::Scalar> colors_;
const size_t color_num_ = 10; // different number of color to generate
pcl::PointCloud<PointType_>::Ptr
previous_cloud_ptr_; // holds the previous groundless result of ground
// classification
/*!
* Output transformed PointCloud from in_cloud_ptr->header.frame_id to in_target_frame
* @param[in] in_target_frame Coordinate system to perform transform
* @param[in] in_cloud_ptr PointCloud to perform transform
* @param[out] out_cloud_ptr Resulting transformed PointCloud
* @retval true transform succeeded
* @retval false transform failed
*/
bool TransformPointCloud(
const std::string & in_target_frame, const PointCloud2ConstPtr & in_cloud_ptr,
const PointCloud2::SharedPtr & out_cloud_ptr);
/*!
*
* @param[in] in_cloud Input Point Cloud to be organized in radial segments
* @param[out] out_organized_points Custom Point Cloud filled with XYZRTZColor data
* @param[out] out_radial_divided_indices Indices of the points in the original cloud for each radial segment
* @param[out] out_radial_ordered_clouds Vector of Points Clouds, each element will contain the points ordered
*/
void ConvertXYZIToRTZColor(
const pcl::PointCloud<PointType_>::Ptr in_cloud, PointCloudXYZRTColor & out_organized_points,
std::vector<pcl::PointIndices> & out_radial_divided_indices,
std::vector<PointCloudXYZRTColor> & out_radial_ordered_clouds);
/*!
* Classifies Points in the PointCloud as Ground and Not Ground
* @param in_radial_ordered_clouds Vector of an Ordered PointsCloud ordered by radial distance from the origin
* @param out_ground_indices Returns the indices of the points classified as ground in the original PointCloud
* @param out_no_ground_indices Returns the indices of the points classified as not ground in the original PointCloud
*/
void ClassifyPointCloud(
std::vector<PointCloudXYZRTColor> & in_radial_ordered_clouds,
pcl::PointIndices & out_ground_indices, pcl::PointIndices & out_no_ground_indices);
/*!
* Returns the resulting complementary PointCloud, one with the points kept and the other removed as indicated
* in the indices
* @param in_cloud_ptr Input PointCloud to which the extraction will be performed
* @param in_indices Indices of the points to be both removed and kept
* @param out_only_indices_cloud_ptr Resulting PointCloud with the indices kept
* @param out_removed_indices_cloud_ptr Resulting PointCloud with the indices removed
*/
void ExtractPointsIndices(
const pcl::PointCloud<PointType_>::Ptr in_cloud_ptr, const pcl::PointIndices & in_indices,
pcl::PointCloud<PointType_>::Ptr out_only_indices_cloud_ptr,
pcl::PointCloud<PointType_>::Ptr out_removed_indices_cloud_ptr);
boost::optional<float> calcPointVehicleIntersection(const Point & point);
void setVehicleFootprint(
const double min_x, const double max_x, const double min_y, const double max_y);
/** \brief Parameter service callback result : needed to be hold */
OnSetParametersCallbackHandle::SharedPtr set_param_res_;
/** \brief Parameter service callback */
rcl_interfaces::msg::SetParametersResult paramCallback(const std::vector<rclcpp::Parameter> & p);
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
explicit RayGroundFilterComponent(const rclcpp::NodeOptions & options);
};
} // namespace pointcloud_preprocessor
#endif // POINTCLOUD_PREPROCESSOR__GROUND_FILTER__RAY_GROUND_FILTER_NODELET_HPP_
| 39.504854 | 119 | 0.757311 | [
"geometry",
"vector",
"model",
"transform"
] |
40e6b6cc239a915ea8b7f581ce1c357fc6980a80 | 99,011 | cc | C++ | services/image_annotation/annotator_unittest.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | services/image_annotation/annotator_unittest.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | services/image_annotation/annotator_unittest.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2019 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 "services/image_annotation/annotator.h"
#include <cstring>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/optional.h"
#include "base/strings/stringprintf.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "net/base/net_errors.h"
#include "net/http/http_status_code.h"
#include "services/data_decoder/public/cpp/data_decoder.h"
#include "services/data_decoder/public/cpp/test_support/in_process_data_decoder.h"
#include "services/data_decoder/public/mojom/json_parser.mojom.h"
#include "services/image_annotation/image_annotation_metrics.h"
#include "services/image_annotation/public/mojom/image_annotation.mojom.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader.mojom-shared.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace image_annotation {
namespace {
using base::Bucket;
using testing::ElementsAre;
using testing::Eq;
using testing::IsEmpty;
using testing::SizeIs;
using testing::UnorderedElementsAre;
MATCHER_P3(AnnotatorEq, type, score, text, "") {
return (arg.type == type && arg.score == score && arg.text == text);
}
constexpr char kTestServerUrl[] = "https://ia-pa.googleapis.com/v1/annotation";
constexpr char kLangsServerUrl[] = "https://ia-pa.googleapis.com/v1/langs";
// Example image URLs.
constexpr char kImage1Url[] = "https://www.example.com/image1.jpg";
constexpr char kImage2Url[] = "https://www.example.com/image2.jpg";
constexpr char kImage3Url[] = "https://www.example.com/image3.jpg";
// Example server requests / responses.
// Template for a request for a single image.
constexpr char kTemplateRequest[] = R"(
{
"imageRequests": [{
"imageId": "%s",
"imageBytes": "%s",
"engineParameters": [
{"ocrParameters": {}},
{"descriptionParameters": {}}
]
}]
}
)";
// Batch request for |kImage1Url|, |kImage2Url| and |kImage3Url|.
constexpr char kBatchRequest[] = R"(
{
"imageRequests": [
{
"imageId": "https://www.example.com/image3.jpg",
"imageBytes": "BwgJ",
"engineParameters": [
{"ocrParameters": {}},
{"descriptionParameters": {}}
]
},
{
"imageId": "https://www.example.com/image2.jpg",
"imageBytes": "BAUG",
"engineParameters": [
{"ocrParameters": {}},
{"descriptionParameters": {}}
]
},
{
"imageId": "https://www.example.com/image1.jpg",
"imageBytes": "AQID",
"engineParameters": [
{"ocrParameters": {}},
{"descriptionParameters": {}}
]
}
]
})";
// Successful OCR text extraction for |kImage1Url| with no descriptions.
constexpr char kOcrSuccessResponse[] = R"(
{
"results": [
{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [
{
"words": [
{
"detectedText": "Region",
"confidenceScore": 1.0
},
{
"detectedText": "1",
"confidenceScore": 1.0
}
]
},
{
"words": [
{
"detectedText": "Region",
"confidenceScore": 1.0
},
{
"detectedText": "2",
"confidenceScore": 1.0
}
]
}
]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {}
}
}
]
}
]
}
)";
// Batch response containing successful annotations for |kImage1Url| and
// |kImage2Url|, and a failure for |kImage3Url|.
//
// The results also appear "out of order" (i.e. image 2 comes before image 1).
constexpr char kBatchResponse[] = R"(
{
"results": [
{
"imageId": "https://www.example.com/image2.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "2",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {}
}
}
]
},
{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "1",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {}
}
}
]
},
{
"imageId": "https://www.example.com/image3.jpg",
"engineResults": [
{
"status": {
"code": 8,
"message": "Resource exhausted"
},
"ocrEngine": {}
},
{
"status": {
"code": 8,
"message": "Resource exhausted"
},
"descriptionEngine": {}
}
]
}
]
})";
constexpr base::TimeDelta kThrottle = base::TimeDelta::FromSeconds(1);
// The minimum dimension required for description annotation.
constexpr int32_t kDescDim = Annotator::kDescMinDimension;
// The description language to use in tests that don't exercise
// language-handling logic.
constexpr char kDescLang[] = "";
// An image processor that holds and exposes the callbacks it is passed.
class TestImageProcessor : public mojom::ImageProcessor {
public:
TestImageProcessor() = default;
mojo::PendingRemote<mojom::ImageProcessor> GetPendingRemote() {
mojo::PendingRemote<mojom::ImageProcessor> remote;
receivers_.Add(this, remote.InitWithNewPipeAndPassReceiver());
return remote;
}
void Reset() {
receivers_.Clear();
callbacks_.clear();
}
void GetJpgImageData(GetJpgImageDataCallback callback) override {
callbacks_.push_back(std::move(callback));
}
std::vector<GetJpgImageDataCallback>& callbacks() { return callbacks_; }
private:
std::vector<GetJpgImageDataCallback> callbacks_;
mojo::ReceiverSet<mojom::ImageProcessor> receivers_;
DISALLOW_COPY_AND_ASSIGN(TestImageProcessor);
};
// A class that supports test URL loading for the "server" use case: where
// all request URLs have the same prefix and differ only in suffix and body
// content.
class TestServerURLLoaderFactory {
public:
TestServerURLLoaderFactory(const std::string& server_url_prefix)
: server_url_prefix_(server_url_prefix),
shared_loader_factory_(
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&loader_factory_)) {}
const std::vector<network::TestURLLoaderFactory::PendingRequest>& requests() {
return *loader_factory_.pending_requests();
}
// Expects that the earliest received request has the given URL, headers and
// body, and replies with the given response.
//
// |expected_headers| is a map from header key string to either:
// a) a null optional, if the given header should not be present, or
// b) a non-null optional, if the given header should be present and match
// the optional value.
//
// Consumes the earliest received request (i.e. a subsequent call will apply
// to the second-earliest received request and so on).
void ExpectRequestAndSimulateResponse(
const std::string& expected_url_suffix,
const std::map<std::string, base::Optional<std::string>>&
expected_headers,
const std::string& expected_body,
const std::string& response,
const net::HttpStatusCode response_code) {
const std::string expected_url = server_url_prefix_ + expected_url_suffix;
const std::vector<network::TestURLLoaderFactory::PendingRequest>&
pending_requests = *loader_factory_.pending_requests();
CHECK(!pending_requests.empty());
const network::ResourceRequest& request = pending_requests.front().request;
// Assert that the earliest request is for the given URL.
CHECK_EQ(request.url, GURL(expected_url));
// Expect that specified headers are accurate.
for (const auto& kv : expected_headers) {
if (kv.second.has_value()) {
std::string actual_value;
EXPECT_THAT(request.headers.GetHeader(kv.first, &actual_value),
Eq(true));
EXPECT_THAT(actual_value, Eq(*kv.second));
} else {
EXPECT_THAT(request.headers.HasHeader(kv.first), Eq(false));
}
}
// Extract request body.
std::string actual_body;
if (request.request_body) {
const std::vector<network::DataElement>* const elements =
request.request_body->elements();
// We only support the simplest body structure.
if (elements && elements->size() == 1 &&
(*elements)[0].type() == network::mojom::DataElementType::kBytes) {
actual_body =
std::string((*elements)[0].bytes(), (*elements)[0].length());
}
}
EXPECT_THAT(actual_body, Eq(expected_body));
// Guaranteed to match the first request based on URL.
loader_factory_.SimulateResponseForPendingRequest(expected_url, response,
response_code);
}
scoped_refptr<network::SharedURLLoaderFactory> AsSharedURLLoaderFactory() {
return shared_loader_factory_;
}
private:
const std::string server_url_prefix_;
network::TestURLLoaderFactory loader_factory_;
scoped_refptr<network::SharedURLLoaderFactory> shared_loader_factory_;
DISALLOW_COPY_AND_ASSIGN(TestServerURLLoaderFactory);
};
// Returns a "canonically" formatted version of a JSON string by parsing and
// then rewriting it.
std::string ReformatJson(const std::string& in) {
const std::unique_ptr<base::Value> json =
base::JSONReader::ReadDeprecated(in);
CHECK(json);
std::string out;
base::JSONWriter::Write(*json, &out);
return out;
}
// Receives the result of an annotation request and writes the result data into
// the given variables.
void ReportResult(base::Optional<mojom::AnnotateImageError>* const error,
std::vector<mojom::Annotation>* const annotations,
mojom::AnnotateImageResultPtr result) {
if (result->which() == mojom::AnnotateImageResult::Tag::ERROR_CODE) {
*error = result->get_error_code();
} else {
// If annotations exists, then it is not empty.
ASSERT_THAT(result->get_annotations(), Not(IsEmpty()));
for (const auto& annotation_ptr : result->get_annotations()) {
annotations->push_back(*annotation_ptr);
}
}
}
class TestAnnotatorClient : public Annotator::Client {
public:
explicit TestAnnotatorClient() = default;
~TestAnnotatorClient() override = default;
// Set up tests.
void SetAcceptLanguages(const std::vector<std::string> accept_langs) {
accept_langs_ = accept_langs;
}
void SetTopLanguages(const std::vector<std::string> top_langs) {
top_langs_ = top_langs;
}
private:
// Annotator::Client implementation:
void BindJsonParser(mojo::PendingReceiver<data_decoder::mojom::JsonParser>
receiver) override {
decoder_.GetService()->BindJsonParser(std::move(receiver));
}
std::vector<std::string> GetAcceptLanguages() override {
return accept_langs_;
}
std::vector<std::string> GetTopLanguages() override { return top_langs_; }
void RecordLanguageMetrics(const std::string& page_language,
const std::string& requested_language) override {}
data_decoder::DataDecoder decoder_;
std::vector<std::string> accept_langs_ = {"en", "it", "fr"};
std::vector<std::string> top_langs_;
};
} // namespace
// Test that annotation works for one client, and that the cache is populated.
TEST(AnnotatorTest, OcrSuccessAndCache) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor;
// First call performs original image annotation.
{
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(
kImage1Url, kDescLang, processor.GetPendingRemote(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
test_task_env.RunUntilIdle();
// HTTP request should have been made.
const std::string request =
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID"));
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */, request, kOcrSuccessResponse,
net::HTTP_OK);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called.
ASSERT_THAT(error, Eq(base::nullopt));
EXPECT_THAT(annotations,
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr,
1.0, "Region 1\nRegion 2")));
// Metrics should have been logged for the major actions of the service.
histogram_tester.ExpectUniqueSample(metrics_internal::kCacheHit, false, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kPixelFetchSuccess,
true, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerRequestSize,
request.size() / 1024, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerNetError,
net::Error::OK, 1);
histogram_tester.ExpectUniqueSample(
metrics_internal::kServerHttpResponseCode, net::HTTP_OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerResponseSize,
std::strlen(kOcrSuccessResponse), 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kJsonParseSuccess,
true, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Ocr"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Desc"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence, "Ocr"), 100,
1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "Ocr"), false,
1);
}
// Second call uses cached results.
{
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(
kImage1Url, kDescLang, processor.GetPendingRemote(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Pixels shouldn't be requested.
ASSERT_THAT(processor.callbacks(), IsEmpty());
// Results should have been directly returned without any server call.
ASSERT_THAT(error, Eq(base::nullopt));
EXPECT_THAT(annotations,
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr,
1.0, "Region 1\nRegion 2")));
// Metrics should have been logged for a cache hit.
EXPECT_THAT(histogram_tester.GetAllSamples(metrics_internal::kCacheHit),
UnorderedElementsAre(Bucket(false, 1), Bucket(true, 1)));
}
}
// Test that description annotations are successfully returned.
TEST(AnnotatorTest, DescriptionSuccess) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPendingRemote(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
test_task_env.RunUntilIdle();
// HTTP request should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
R"({
"results": [{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {
"descriptions": [
{
"type": "CAPTION",
"text": "This is an example image.",
"score": 0.9
},
{
"type": "LABEL",
"text": "Example image",
"score": 1.0
}
]
}
}
}
]
}]
})",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called.
ASSERT_THAT(error, Eq(base::nullopt));
EXPECT_THAT(
annotations,
UnorderedElementsAre(
AnnotatorEq(mojom::AnnotationType::kOcr, 1.0, ""),
AnnotatorEq(mojom::AnnotationType::kCaption, 0.9,
"This is an example image."),
AnnotatorEq(mojom::AnnotationType::kLabel, 1.0, "Example image")));
// Metrics about the description results should have been logged.
histogram_tester.ExpectUniqueSample(
metrics_internal::kImageRequestIncludesDesc, true, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Ocr"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Desc"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence,
"DescCaption"),
90, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence, "DescLabel"),
100, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "DescCaption"),
false, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "DescLabel"),
false, 1);
}
// Test that the specialized OCR result takes precedence.
TEST(AnnotatorTest, DoubleOcrResult) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPendingRemote(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
test_task_env.RunUntilIdle();
// HTTP request should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
R"({
"results": [{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "Region 1",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {
"descriptions": [
{
"type": "CAPTION",
"text": "This is an example image.",
"score": 0.9
},
{
"type": "OCR",
"text": "R3gi0n I",
"score": 1.0
}
]
}
}
}
]
}]
})",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called.
ASSERT_THAT(error, Eq(base::nullopt));
EXPECT_THAT(annotations,
UnorderedElementsAre(
AnnotatorEq(mojom::AnnotationType::kOcr, 1.0, "Region 1"),
AnnotatorEq(mojom::AnnotationType::kCaption, 0.9,
"This is an example image.")));
// Metrics about the returned results should have been logged.
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Ocr"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Desc"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence, "Ocr"), 100,
1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence,
"DescCaption"),
90, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence, "DescOcr"),
100, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "Ocr"), false, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "DescCaption"),
false, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "DescOcr"), false,
1);
}
// Test that HTTP failure is gracefully handled.
TEST(AnnotatorTest, HttpError) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPendingRemote(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
"", net::HTTP_INTERNAL_SERVER_ERROR);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called.
EXPECT_THAT(error, Eq(mojom::AnnotateImageError::kFailure));
EXPECT_THAT(annotations, IsEmpty());
// Metrics about the HTTP request failure should have been logged.
histogram_tester.ExpectUniqueSample(
metrics_internal::kServerNetError,
net::Error::ERR_HTTP_RESPONSE_CODE_FAILURE, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerHttpResponseCode,
net::HTTP_INTERNAL_SERVER_ERROR, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kClientResult,
ClientResult::kFailed, 1);
}
// Test that backend failure is gracefully handled.
TEST(AnnotatorTest, BackendError) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPendingRemote(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
R"({
"results": [{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {
"code": 8,
"message": "Resource exhausted"
},
"ocrEngine": {}
},
{
"status": {
"code": 8,
"messages": "Resource exhausted"
},
"descriptionEngine": {}
}
]
}]
})",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called
// with an error status.
EXPECT_THAT(error, Eq(mojom::AnnotateImageError::kFailure));
EXPECT_THAT(annotations, IsEmpty());
// Metrics about the backend failure should have been logged.
histogram_tester.ExpectUniqueSample(metrics_internal::kServerNetError,
net::Error::OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerHttpResponseCode,
net::HTTP_OK, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Ocr"),
8 /* Failed RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Desc"),
8 /* Failed RPC status */, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kClientResult,
ClientResult::kFailed, 1);
}
// Test that partial results are returned if the OCR backend fails.
TEST(AnnotatorTest, OcrBackendError) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPendingRemote(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
R"({
"results": [{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {
"code": 8,
"message": "Resource exhausted"
},
"ocrEngine": {}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {
"descriptions": [{
"type": "CAPTION",
"text": "This is an example image.",
"score": 0.9
}]
}
}
}
]
}]
})",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called.
EXPECT_THAT(error, Eq(base::nullopt));
EXPECT_THAT(annotations, UnorderedElementsAre(
AnnotatorEq(mojom::AnnotationType::kCaption, 0.9,
"This is an example image.")));
// Metrics about the partial results should have been logged.
histogram_tester.ExpectUniqueSample(metrics_internal::kServerNetError,
net::Error::OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerHttpResponseCode,
net::HTTP_OK, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Ocr"),
8 /* Failed RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Desc"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence,
"DescCaption"),
90, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "DescCaption"),
false, 1);
}
// Test that partial results are returned if the description backend fails.
TEST(AnnotatorTest, DescriptionBackendError) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPendingRemote(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
R"({
"results": [{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "1",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {
"code": 8,
"message": "Resource exhausted"
},
"descriptionEngine": {}
}
]
}]
})",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called.
EXPECT_THAT(error, Eq(base::nullopt));
EXPECT_THAT(annotations, UnorderedElementsAre(AnnotatorEq(
mojom::AnnotationType::kOcr, 1.0, "1")));
// Metrics about the partial results should have been logged.
histogram_tester.ExpectUniqueSample(metrics_internal::kServerNetError,
net::Error::OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerHttpResponseCode,
net::HTTP_OK, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Ocr"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Desc"),
8 /* Failed RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence, "Ocr"), 100,
1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "Ocr"), false, 1);
}
// Test that server failure (i.e. nonsense response) is gracefully handled.
TEST(AnnotatorTest, ServerError) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPendingRemote(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request should have been made; respond with nonsense string.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
"Hello, world!", net::HTTP_OK);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called
// with an error status.
EXPECT_THAT(error, Eq(mojom::AnnotateImageError::kFailure));
EXPECT_THAT(annotations, IsEmpty());
// Metrics about the invalid response format should have been logged.
histogram_tester.ExpectUniqueSample(metrics_internal::kServerNetError,
net::Error::OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerHttpResponseCode,
net::HTTP_OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kJsonParseSuccess,
false, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kClientResult,
ClientResult::kFailed, 1);
}
// Test that adult content returns an error.
TEST(AnnotatorTest, AdultError) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPendingRemote(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
R"({
"results": [{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": []
}
},
{
"status": {},
"descriptionEngine": {
"failureReason": "ADULT"
}
}
]
}]
})",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called
// with an error status.
EXPECT_THAT(error, Eq(mojom::AnnotateImageError::kAdult));
EXPECT_THAT(annotations, IsEmpty());
// Metrics about the adult error should have been logged.
histogram_tester.ExpectUniqueSample(metrics_internal::kServerNetError,
net::Error::OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerHttpResponseCode,
net::HTTP_OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kDescFailure,
DescFailureReason::kAdult, 1);
}
// Test that work is reassigned if a processor fails.
TEST(AnnotatorTest, ProcessorFails) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor[3];
base::Optional<mojom::AnnotateImageError> error[3];
std::vector<mojom::Annotation> annotations[3];
for (int i = 0; i < 3; ++i) {
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[i].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[i], &annotations[i]));
}
test_task_env.RunUntilIdle();
// Annotator should have asked processor 1 for image 1's pixels.
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), IsEmpty());
ASSERT_THAT(processor[2].callbacks(), IsEmpty());
// Make processor 1 fail by returning empty bytes.
std::move(processor[0].callbacks()[0]).Run({}, 0, 0);
processor[0].callbacks().pop_back();
test_task_env.RunUntilIdle();
// Annotator should have asked processor 2 for image 1's pixels.
ASSERT_THAT(processor[0].callbacks(), IsEmpty());
ASSERT_THAT(processor[1].callbacks(), SizeIs(1));
ASSERT_THAT(processor[2].callbacks(), IsEmpty());
// Send back image data.
std::move(processor[1].callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor[1].callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request for image 1 should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
kOcrSuccessResponse, net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called all callbacks, but request 1 received an error
// when we returned empty bytes.
ASSERT_THAT(error, ElementsAre(mojom::AnnotateImageError::kFailure,
base::nullopt, base::nullopt));
EXPECT_THAT(annotations[0], IsEmpty());
EXPECT_THAT(annotations[1],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
EXPECT_THAT(annotations[2],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
// Metrics about the pixel fetch failure should have been logged.
EXPECT_THAT(
histogram_tester.GetAllSamples(metrics_internal::kPixelFetchSuccess),
UnorderedElementsAre(Bucket(false, 1), Bucket(true, 1)));
EXPECT_THAT(histogram_tester.GetAllSamples(metrics_internal::kClientResult),
UnorderedElementsAre(
Bucket(static_cast<int32_t>(ClientResult::kFailed), 1),
Bucket(static_cast<int32_t>(ClientResult::kSucceeded), 2)));
}
// Test a case that was previously buggy: when one client requests annotations,
// then fails local processing, then another client makes the same request.
TEST(AnnotatorTest, ProcessorFailedPreviously) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor[2];
base::Optional<mojom::AnnotateImageError> error[2];
std::vector<mojom::Annotation> annotations[2];
// Processor 1 makes a request for annotation of a given image.
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[0].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[0], &annotations[0]));
test_task_env.RunUntilIdle();
// Annotator should have asked processor 1 for the image's pixels.
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), IsEmpty());
// Make processor 1 fail by returning empty bytes.
std::move(processor[0].callbacks()[0]).Run({}, 0, 0);
processor[0].callbacks().pop_back();
test_task_env.RunUntilIdle();
// Processor 2 makes a request for annotation of the same image.
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[1].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[1], &annotations[1]));
test_task_env.RunUntilIdle();
// Annotator should have asked processor 2 for the image's pixels.
ASSERT_THAT(processor[1].callbacks(), SizeIs(1));
// Send back image data.
std::move(processor[1].callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor[1].callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request for image 1 should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
kOcrSuccessResponse, net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called all callbacks, but request 1 received an error
// when we returned empty bytes.
ASSERT_THAT(error,
ElementsAre(mojom::AnnotateImageError::kFailure, base::nullopt));
EXPECT_THAT(annotations[0], IsEmpty());
EXPECT_THAT(annotations[1],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
}
// Test that work is reassigned if processor dies.
TEST(AnnotatorTest, ProcessorDies) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor[3];
base::Optional<mojom::AnnotateImageError> error[3];
std::vector<mojom::Annotation> annotations[3];
for (int i = 0; i < 3; ++i) {
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[i].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[i], &annotations[i]));
}
test_task_env.RunUntilIdle();
// Annotator should have asked processor 1 for image 1's pixels.
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), IsEmpty());
ASSERT_THAT(processor[2].callbacks(), IsEmpty());
// Kill processor 1.
processor[0].Reset();
test_task_env.RunUntilIdle();
// Annotator should have asked processor 2 for image 1's pixels.
ASSERT_THAT(processor[0].callbacks(), IsEmpty());
ASSERT_THAT(processor[1].callbacks(), SizeIs(1));
ASSERT_THAT(processor[2].callbacks(), IsEmpty());
// Send back image data.
std::move(processor[1].callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor[1].callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request for image 1 should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
kOcrSuccessResponse, net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called all callbacks, but request 1 was canceled when
// we reset processor 1.
ASSERT_THAT(error, ElementsAre(mojom::AnnotateImageError::kCanceled,
base::nullopt, base::nullopt));
EXPECT_THAT(annotations[0], IsEmpty());
EXPECT_THAT(annotations[1],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
EXPECT_THAT(annotations[2],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
// Metrics about the client cancelation should have been logged.
EXPECT_THAT(histogram_tester.GetAllSamples(metrics_internal::kClientResult),
UnorderedElementsAre(
Bucket(static_cast<int32_t>(ClientResult::kCanceled), 1),
Bucket(static_cast<int32_t>(ClientResult::kSucceeded), 2)));
}
// Test that multiple concurrent requests are handled in the same batch.
TEST(AnnotatorTest, ConcurrentSameBatch) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
3 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor[3];
base::Optional<mojom::AnnotateImageError> error[3];
std::vector<mojom::Annotation> annotations[3];
// Request OCR for images 1, 2 and 3.
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[0].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[0], &annotations[0]));
annotator.AnnotateImage(
kImage2Url, kDescLang, processor[1].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[1], &annotations[1]));
annotator.AnnotateImage(
kImage3Url, kDescLang, processor[2].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[2], &annotations[2]));
test_task_env.RunUntilIdle();
// Annotator should have asked processor 1 for image 1's pixels, processor
// 2 for image 2's pixels and processor 3 for image 3's pixels.
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), SizeIs(1));
ASSERT_THAT(processor[2].callbacks(), SizeIs(1));
// Send back image data.
std::move(processor[0].callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor[0].callbacks().pop_back();
std::move(processor[1].callbacks()[0]).Run({4, 5, 6}, kDescDim, kDescDim);
processor[1].callbacks().pop_back();
std::move(processor[2].callbacks()[0]).Run({7, 8, 9}, kDescDim, kDescDim);
processor[2].callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// A single HTTP request for all images should have been sent.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */, ReformatJson(kBatchRequest),
kBatchResponse, net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called each callback with its corresponding text or
// failure.
ASSERT_THAT(error, ElementsAre(base::nullopt, base::nullopt,
mojom::AnnotateImageError::kFailure));
EXPECT_THAT(annotations[0], UnorderedElementsAre(AnnotatorEq(
mojom::AnnotationType::kOcr, 1.0, "1")));
EXPECT_THAT(annotations[1], UnorderedElementsAre(AnnotatorEq(
mojom::AnnotationType::kOcr, 1.0, "2")));
EXPECT_THAT(annotations[2], IsEmpty());
// Metrics should have been logged for a single server response with multiple
// results included.
histogram_tester.ExpectUniqueSample(metrics_internal::kServerNetError,
net::Error::OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerHttpResponseCode,
net::HTTP_OK, 1);
EXPECT_THAT(histogram_tester.GetAllSamples(base::StringPrintf(
metrics_internal::kAnnotationStatus, "Ocr")),
UnorderedElementsAre(Bucket(8 /* Failed RPC status */, 1),
Bucket(0 /* OK RPC status */, 2)));
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence, "Ocr"), 100,
2);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "Ocr"), false, 2);
EXPECT_THAT(histogram_tester.GetAllSamples(metrics_internal::kClientResult),
UnorderedElementsAre(
Bucket(static_cast<int32_t>(ClientResult::kFailed), 1),
Bucket(static_cast<int32_t>(ClientResult::kSucceeded), 2)));
}
// Test that multiple concurrent requests are handled in separate batches.
TEST(AnnotatorTest, ConcurrentSeparateBatches) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
3 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor[2];
base::Optional<mojom::AnnotateImageError> error[2];
std::vector<mojom::Annotation> annotations[2];
// Request OCR for image 1.
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[0].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[0], &annotations[0]));
test_task_env.RunUntilIdle();
// Annotator should have asked processor 1 for image 1's pixels.
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), IsEmpty());
// Send back image 1 data.
std::move(processor[0].callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor[0].callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// Request OCR for image 2.
annotator.AnnotateImage(
kImage2Url, kDescLang, processor[1].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[1], &annotations[1]));
test_task_env.RunUntilIdle();
// Annotator should have asked processor 2 for image 2's pixels.
ASSERT_THAT(processor[0].callbacks(), IsEmpty());
ASSERT_THAT(processor[1].callbacks(), SizeIs(1));
// Send back image 2 data.
std::move(processor[1].callbacks()[0]).Run({4, 5, 6}, kDescDim, kDescDim);
processor[1].callbacks().pop_back();
test_task_env.RunUntilIdle();
// Only the HTTP request for image 1 should have been made (the service is
// still waiting to make the batch that will include the request for image
// 2).
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
R"({
"results": [{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "1",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {}
}
}
]
}]
})",
net::HTTP_OK);
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// Now the HTTP request for image 2 should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage2Url, "BAUG")),
R"({
"results": [{
"imageId": "https://www.example.com/image2.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "2",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {}
}
}
]
}]
})",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called each callback with its corresponding text.
ASSERT_THAT(error, ElementsAre(base::nullopt, base::nullopt));
EXPECT_THAT(annotations[0], UnorderedElementsAre(AnnotatorEq(
mojom::AnnotationType::kOcr, 1.0, "1")));
EXPECT_THAT(annotations[1], UnorderedElementsAre(AnnotatorEq(
mojom::AnnotationType::kOcr, 1.0, "2")));
// Metrics should have been logged for two server responses.
histogram_tester.ExpectUniqueSample(metrics_internal::kServerNetError,
net::Error::OK, 2);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerHttpResponseCode,
net::HTTP_OK, 2);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Ocr"),
0 /* OK RPC status */, 2);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence, "Ocr"), 100,
2);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "Ocr"), false, 2);
histogram_tester.ExpectUniqueSample(metrics_internal::kClientResult,
ClientResult::kSucceeded, 2);
}
// Test that work is not duplicated if it is already ongoing.
TEST(AnnotatorTest, DuplicateWork) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor[4];
base::Optional<mojom::AnnotateImageError> error[4];
std::vector<mojom::Annotation> annotations[4];
// First request annotation of the image with processor 1.
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[0].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[0], &annotations[0]));
test_task_env.RunUntilIdle();
// Annotator should have asked processor 1 for the image's pixels.
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), IsEmpty());
ASSERT_THAT(processor[2].callbacks(), IsEmpty());
ASSERT_THAT(processor[3].callbacks(), IsEmpty());
// Now request annotation of the image with processor 2.
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[1].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[1], &annotations[1]));
test_task_env.RunUntilIdle();
// Annotator *should not* have asked processor 2 for the image's pixels (since
// processor 1 is already handling that).
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), IsEmpty());
ASSERT_THAT(processor[2].callbacks(), IsEmpty());
ASSERT_THAT(processor[3].callbacks(), IsEmpty());
// Get processor 1 to reply with bytes for the image.
std::move(processor[0].callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor[0].callbacks().pop_back();
test_task_env.RunUntilIdle();
// Now request annotation of the image with processor 3.
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[2].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[2], &annotations[2]));
test_task_env.RunUntilIdle();
// Annotator *should not* have asked processor 3 for the image's pixels (since
// it has already has the pixels in the HTTP request queue).
ASSERT_THAT(processor[0].callbacks(), IsEmpty());
ASSERT_THAT(processor[1].callbacks(), IsEmpty());
ASSERT_THAT(processor[2].callbacks(), IsEmpty());
ASSERT_THAT(processor[3].callbacks(), IsEmpty());
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
// Allow batch HTTP request to be sent off and then request annotation of the
// image with processor 4.
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
EXPECT_THAT(test_url_factory.requests(), SizeIs(1));
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[3].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[3], &annotations[3]));
test_task_env.RunUntilIdle();
// Annotator *should not* have asked processor 4 for the image's pixels (since
// an HTTP request for the image is already in process).
ASSERT_THAT(processor[0].callbacks(), IsEmpty());
ASSERT_THAT(processor[1].callbacks(), IsEmpty());
ASSERT_THAT(processor[2].callbacks(), IsEmpty());
ASSERT_THAT(processor[3].callbacks(), IsEmpty());
// HTTP request for the image should have been made (with bytes obtained from
// processor 1).
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
kOcrSuccessResponse, net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called all callbacks with annotation results.
ASSERT_THAT(error, ElementsAre(base::nullopt, base::nullopt, base::nullopt,
base::nullopt));
EXPECT_THAT(annotations[0],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
EXPECT_THAT(annotations[1],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
EXPECT_THAT(annotations[2],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
EXPECT_THAT(annotations[3],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
// Metrics should have been logged for a single pixel fetch.
histogram_tester.ExpectUniqueSample(metrics_internal::kPixelFetchSuccess,
true, 1);
}
// Test that the description engine is not requested for images that violate
// model policy (i.e. are too small or have too-high an aspect ratio).
TEST(AnnotatorTest, DescPolicy) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
3 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor[3];
base::Optional<mojom::AnnotateImageError> error[3];
std::vector<mojom::Annotation> annotations[3];
// Request annotation for images 1, 2 and 3.
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[0].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[0], &annotations[0]));
annotator.AnnotateImage(
kImage2Url, kDescLang, processor[1].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[1], &annotations[1]));
annotator.AnnotateImage(
kImage3Url, kDescLang, processor[2].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[2], &annotations[2]));
test_task_env.RunUntilIdle();
// Annotator should have asked processor 1 for image 1's pixels, processor
// 2 for image 2's pixels and processor 3 for image 3's pixels.
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), SizeIs(1));
ASSERT_THAT(processor[2].callbacks(), SizeIs(1));
// Send back image data.
//
// Image 1 is (just) within policy. Image 2 violates policy because it is too
// small. Image 3 is large enough, but violates policy because of its aspect
// ratio.
std::move(processor[0].callbacks()[0])
.Run({1, 2, 3}, Annotator::kDescMinDimension,
Annotator::kDescMinDimension);
processor[0].callbacks().pop_back();
std::move(processor[1].callbacks()[0])
.Run({4, 5, 6}, Annotator::kDescMinDimension,
Annotator::kDescMinDimension - 1);
processor[1].callbacks().pop_back();
std::move(processor[2].callbacks()[0])
.Run({7, 8, 9},
static_cast<int32_t>(Annotator::kDescMinDimension *
Annotator::kDescMaxAspectRatio) +
1,
Annotator::kDescMinDimension);
processor[2].callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// A single HTTP request for all images should have been sent.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
// Only image 1 includes a description request (as the other two violate
// one of the policies).
ReformatJson(R"(
{
"imageRequests": [
{
"imageId": "https://www.example.com/image3.jpg",
"imageBytes": "BwgJ",
"engineParameters": [
{"ocrParameters": {}}
]
},
{
"imageId": "https://www.example.com/image2.jpg",
"imageBytes": "BAUG",
"engineParameters": [
{"ocrParameters": {}}
]
},
{
"imageId": "https://www.example.com/image1.jpg",
"imageBytes": "AQID",
"engineParameters": [
{"ocrParameters": {}},
{"descriptionParameters": {}}
]
}
]
}
)"),
R"(
{
"results": [
{
"imageId": "https://www.example.com/image2.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "2",
"confidenceScore": 1.0
}]
}]
}
}
]
},
{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "1",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {
"descriptions": [{
"type": "CAPTION",
"text": "This is an example image.",
"score": 1.0
}]
}
}
}
]
},
{
"imageId": "https://www.example.com/image3.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "3",
"confidenceScore": 1.0
}]
}]
}
}
]
}
]
}
)",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called each callback with its corresponding results.
ASSERT_THAT(error, ElementsAre(base::nullopt, base::nullopt, base::nullopt));
EXPECT_THAT(
annotations[0],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0, "1"),
AnnotatorEq(mojom::AnnotationType::kCaption, 1.0,
"This is an example image.")));
EXPECT_THAT(annotations[1], UnorderedElementsAre(AnnotatorEq(
mojom::AnnotationType::kOcr, 1.0, "2")));
EXPECT_THAT(annotations[2], UnorderedElementsAre(AnnotatorEq(
mojom::AnnotationType::kOcr, 1.0, "3")));
// Metrics should have been logged for the 3 OCR results and 1 description
// result.
EXPECT_THAT(histogram_tester.GetAllSamples(
metrics_internal::kImageRequestIncludesDesc),
UnorderedElementsAre(Bucket(false, 2), Bucket(true, 1)));
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Ocr"),
0 /* OK RPC status */, 3);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Desc"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence, "Ocr"), 100,
3);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence,
"DescCaption"),
100, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "Ocr"), false, 3);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "DescCaption"),
false, 1);
}
// Test that description language preferences are sent to the server.
TEST(AnnotatorTest, DescLanguage) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
3 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
annotator.server_languages_ = {"en", "it", "fr"};
TestImageProcessor processor[3];
base::Optional<mojom::AnnotateImageError> error[3];
std::vector<mojom::Annotation> annotations[3];
// Request annotation for one image in two languages, and one other image in
// one language.
annotator.AnnotateImage(
kImage1Url, "fr", processor[0].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[0], &annotations[0]));
annotator.AnnotateImage(
kImage1Url, "it", processor[1].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[1], &annotations[1]));
annotator.AnnotateImage(
kImage2Url, "en", processor[2].GetPendingRemote(),
base::BindOnce(&ReportResult, &error[2], &annotations[2]));
test_task_env.RunUntilIdle();
// Annotator should have asked processor 1 and 2 for image 1's pixels and
// processor 3 for image 2's pixels.
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), SizeIs(1));
ASSERT_THAT(processor[2].callbacks(), SizeIs(1));
// Send back image data. Image 2 is out of policy.
std::move(processor[0].callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor[0].callbacks().pop_back();
std::move(processor[1].callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor[1].callbacks().pop_back();
std::move(processor[2].callbacks()[0])
.Run({4, 5, 6}, Annotator::kDescMinDimension - 1,
Annotator::kDescMinDimension);
processor[2].callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// A single HTTP request for all images should have been sent.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
// Image requests should include the preferred language in their image IDs
// and description parameters (except for image 2 which should not include
// description parameters).
ReformatJson(R"(
{
"imageRequests": [
{
"imageId": "https://www.example.com/image2.jpg en",
"imageBytes": "BAUG",
"engineParameters": [
{"ocrParameters": {}}
]
},
{
"imageId": "https://www.example.com/image1.jpg it",
"imageBytes": "AQID",
"engineParameters": [
{"ocrParameters": {}},
{
"descriptionParameters": {
"preferredLanguages": ["it"]
}
}
]
},
{
"imageId": "https://www.example.com/image1.jpg fr",
"imageBytes": "AQID",
"engineParameters": [
{"ocrParameters": {}},
{
"descriptionParameters": {
"preferredLanguages": ["fr"]
}
}
]
}
]
}
)"),
R"(
{
"results": [
{
"imageId": "https://www.example.com/image1.jpg it",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "1",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {
"descriptions": [{
"type": "CAPTION",
"text": "This is an example image.",
"score": 1.0
}]
}
}
}
]
},
{
"imageId": "https://www.example.com/image1.jpg fr",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "1",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {
"descriptions": [{
"type": "CAPTION",
"text": "Ceci est un exemple d'image.",
"score": 1.0
}]
}
}
}
]
},
{
"imageId": "https://www.example.com/image2.jpg en",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "2",
"confidenceScore": 1.0
}]
}]
}
}
]
}
]
}
)",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called each callback with its corresponding results.
ASSERT_THAT(error, ElementsAre(base::nullopt, base::nullopt, base::nullopt));
EXPECT_THAT(
annotations[0],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0, "1"),
AnnotatorEq(mojom::AnnotationType::kCaption, 1.0,
"Ceci est un exemple d'image.")));
EXPECT_THAT(
annotations[1],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0, "1"),
AnnotatorEq(mojom::AnnotationType::kCaption, 1.0,
"This is an example image.")));
EXPECT_THAT(annotations[2], UnorderedElementsAre(AnnotatorEq(
mojom::AnnotationType::kOcr, 1.0, "2")));
}
// Test that annotation works properly when we need to fall back on a
// different language because the page language isn't available.
TEST(AnnotatorTest, LanguageFallback) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
base::HistogramTester histogram_tester;
Annotator annotator(GURL(kTestServerUrl), GURL(""),
std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
annotator.server_languages_ = {"en", "it", "fr"};
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
// Send a request in an unsupported language.
annotator.AnnotateImage(kImage1Url, "hu", processor.GetPendingRemote(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// Fast-forward time so that server sends batch.
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// A single HTTP request for all images should have been sent.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */, ReformatJson(R"(
{
"imageRequests": [
{
"imageId": "https://www.example.com/image1.jpg en",
"imageBytes": "AQID",
"engineParameters": [
{"ocrParameters": {}},
{
"descriptionParameters": {
"preferredLanguages": ["en"]
}
}
]
}
]
}
)"),
R"(
{
"results": [
{
"imageId": "https://www.example.com/image1.jpg en",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "1",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {
"descriptions": [{
"type": "CAPTION",
"text": "Result in fallback language.",
"score": 1.0
}]
}
}
}
]
}
]
}
)",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called each callback with its corresponding results.
ASSERT_EQ(error, base::nullopt);
EXPECT_THAT(
annotations,
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0, "1"),
AnnotatorEq(mojom::AnnotationType::kCaption, 1.0,
"Result in fallback language.")));
}
// Test that the specified API key is sent, but only to Google-associated server
// domains.
TEST(AnnotatorTest, ApiKey) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
// A call to a secure Google-owner server URL should include the specified API
// key.
{
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
Annotator annotator(GURL(kTestServerUrl), GURL(""), "my_api_key", kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPendingRemote(),
base::DoNothing());
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
test_task_env.RunUntilIdle();
// HTTP request should have been made with the API key included.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {{Annotator::kGoogApiKeyHeader, "my_api_key"}},
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
kOcrSuccessResponse, net::HTTP_OK);
}
// A call to a Google-owned server URL should not include the API key if the
// requests are made insecurely.
{
// Note: not HTTPS.
TestServerURLLoaderFactory test_url_factory(
"http://ia-pa.googleapis.com/v1/");
Annotator annotator(GURL("http://ia-pa.googleapis.com/v1/annotation"),
GURL(""), "my_api_key", kThrottle, 1 /* batch_size */,
1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPendingRemote(),
base::DoNothing());
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
test_task_env.RunUntilIdle();
// HTTP request should have been made without the API key included.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {{Annotator::kGoogApiKeyHeader, base::nullopt}},
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
kOcrSuccessResponse, net::HTTP_OK);
}
// A call to a non-Google-owned URL should not include the API key.
{
TestServerURLLoaderFactory test_url_factory("https://datascraper.com/");
Annotator annotator(GURL("https://datascraper.com/annotation"), GURL(""),
"my_api_key", kThrottle, 1 /* batch_size */,
1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
TestImageProcessor processor;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPendingRemote(),
base::DoNothing());
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
test_task_env.RunUntilIdle();
// HTTP request should have been made without the API key included.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {{Annotator::kGoogApiKeyHeader, base::nullopt}},
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
kOcrSuccessResponse, net::HTTP_OK);
}
}
// Tests that the Annotator computes a reasonable preferred language
// based on the page language, top languages, accept languages, and
// server languages.
TEST(AnnotatorTest, ComputePreferredLanguage) {
TestAnnotatorClient* annotator_client = new TestAnnotatorClient();
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
Annotator annotator(GURL("https://datascraper.com/annotation"), GURL(""),
"my_api_key", kThrottle, 1 /* batch_size */,
1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
base::WrapUnique(annotator_client));
// Simplest case: the page language is in the list of top languages,
// accept languages, and server languages.
annotator.server_languages_ = {"fr", "ja"};
annotator_client->SetTopLanguages({"fr", "hu"});
annotator_client->SetAcceptLanguages({"fr", "es"});
EXPECT_EQ("fr", annotator.ComputePreferredLanguage("fr"));
// Case and locale are ignored (except for zh, see below).
annotator.server_languages_ = {"fR-FR", "ja"};
annotator_client->SetTopLanguages({"Fr-CA", "hu"});
annotator_client->SetAcceptLanguages({"fr-BE", "es"});
EXPECT_EQ("fr", annotator.ComputePreferredLanguage("FR-ch"));
// The page language is respected if it appears in the list of accept
// languages OR top languages, and it's also a supported server language.
annotator.server_languages_ = {"fr", "en", "de", "pt", "ja"};
annotator_client->SetTopLanguages({"fr", "de"});
annotator_client->SetAcceptLanguages({"en", "pt"});
EXPECT_EQ("pt", annotator.ComputePreferredLanguage("pt"));
EXPECT_EQ("de", annotator.ComputePreferredLanguage("de"));
EXPECT_EQ("en", annotator.ComputePreferredLanguage("en"));
EXPECT_EQ("fr", annotator.ComputePreferredLanguage("fr"));
// If the page language is not in the list of accept languages or top
// languages, the first choice should be an accept language that's
// also a top language and server language.
annotator.server_languages_ = {"en", "es"};
annotator_client->SetTopLanguages({"es"});
annotator_client->SetAcceptLanguages({"en", "es"});
EXPECT_EQ("es", annotator.ComputePreferredLanguage("hu"));
// If the page language is not in the list of accept languages or top
// languages, and no accept languages are top languages, return the
// first accept language that's a server language.
annotator.server_languages_ = {"en", "es"};
annotator_client->SetTopLanguages({});
annotator_client->SetAcceptLanguages({"en", "es"});
EXPECT_EQ("en", annotator.ComputePreferredLanguage("ja"));
// If the page language is not in the list of accept languages and none
// of the accept languages are server languages either, return the first
// top language that's a server language.
annotator.server_languages_ = {"en", "de", "pt"};
annotator_client->SetTopLanguages({"it", "hu", "de", "pt"});
annotator_client->SetAcceptLanguages({"es"});
EXPECT_EQ("de", annotator.ComputePreferredLanguage("ja"));
// If nothing matches, just return the first accept language. The server can
// still return OCR results, and it can log the request.
annotator.server_languages_ = {"en", "de", "pt"};
annotator_client->SetTopLanguages({"it", "hu"});
annotator_client->SetAcceptLanguages({"zh-TW"});
EXPECT_EQ("zh-TW", annotator.ComputePreferredLanguage("zh-CN"));
}
TEST(AnnotatorTest, FetchServerLanguages) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
Annotator annotator(GURL(kTestServerUrl), GURL(kLangsServerUrl),
std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
// Assert that initially server_languages_ doesn't contain the made-up
// language code zz.
EXPECT_FALSE(base::Contains(annotator.server_languages_, "zz"));
test_url_factory.ExpectRequestAndSimulateResponse(
"langs", {} /* expected headers */, "" /* body */,
R"({
"status": {},
"langs": [
"de",
"en",
"hu",
"zz"
]
})",
net::HTTP_OK);
test_task_env.RunUntilIdle();
EXPECT_TRUE(base::Contains(annotator.server_languages_, "zz"));
}
// If the server langs don't contain English, they're ignored.
TEST(AnnotatorTest, ServerLanguagesMustContainEnglish) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::test::InProcessDataDecoder in_process_data_decoder;
Annotator annotator(GURL(kTestServerUrl), GURL(kLangsServerUrl),
std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
std::make_unique<TestAnnotatorClient>());
// Assert that initially server_languages_ does contain "en" but
// doesn't contain the made-up language code zz.
EXPECT_FALSE(base::Contains(annotator.server_languages_, "zz"));
// The server response doesn't include "en", so we should ignore it.
test_url_factory.ExpectRequestAndSimulateResponse(
"langs", {} /* expected headers */, "" /* body */,
R"({
"status": {},
"langs": [
"de",
"zz"
]
})",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// We shouldn't have updated our languages because the response didn't
// include "en".
EXPECT_TRUE(base::Contains(annotator.server_languages_, "en"));
EXPECT_FALSE(base::Contains(annotator.server_languages_, "zz"));
}
} // namespace image_annotation
| 39.258921 | 82 | 0.615942 | [
"vector",
"model"
] |
40e77a7b317a1af03adafa687aaf186636a05c9f | 19,408 | cpp | C++ | main.cpp | chriamue/dressup | 1c091017f5a7a641e7b4b29b8022f8892db27ed0 | [
"Unlicense"
] | 1 | 2019-04-21T09:47:20.000Z | 2019-04-21T09:47:20.000Z | main.cpp | chriamue/dressup | 1c091017f5a7a641e7b4b29b8022f8892db27ed0 | [
"Unlicense"
] | null | null | null | main.cpp | chriamue/dressup | 1c091017f5a7a641e7b4b29b8022f8892db27ed0 | [
"Unlicense"
] | null | null | null | /*
* dressup - openpose example
* shows clothes on some skeleton parts
*
* based on https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/examples/tutorial_pose/2_extract_pose_or_heatmat_from_image.cpp
*
*
*/
#include <string>
// 3rdparty dependencies
#include <gflags/gflags.h> // DEFINE_bool, DEFINE_int32, DEFINE_int64, DEFINE_uint64, DEFINE_double, DEFINE_string
// OpenPose dependencies
#include <openpose/core/headers.hpp>
#include <openpose/filestream/headers.hpp>
#include <openpose/gui/headers.hpp>
#include <openpose/pose/headers.hpp>
#include <openpose/utilities/headers.hpp>
#include <opencv2/opencv.hpp>
// Debugging
DEFINE_int32(logging_level, 3, "The logging level. Integer in the range [0, 255]. 0 will output any log() message, while"
" 255 will not output any. Current OpenPose library messages are in the range 0-4: 1 for"
" low priority messages and 4 for important ones.");
// Producer
DEFINE_string(image_path, "examples/media/COCO_val2014_000000000192.jpg", "Process the desired image.");
// OpenPose
DEFINE_string(model_pose, "COCO", "Model to be used (e.g. COCO, MPI, MPI_4_layers).");
DEFINE_string(model_folder, "models/", "Folder path (absolute or relative) where the models (pose, face, ...) are located.");
DEFINE_string(net_resolution, "-1x368", "Multiples of 16. If it is increased, the accuracy potentially increases. If it is decreased,"
" the speed increases. For maximum speed-accuracy balance, it should keep the closest aspect"
" ratio possible to the images or videos to be processed. E.g. the default `656x368` is"
" optimal for 16:9 videos, e.g. full HD (1980x1080) and HD (1280x720) videos.");
DEFINE_string(output_resolution, "-1x-1", "The image resolution (display and output). Use \"-1x-1\" to force the program to use the"
" default images resolution.");
DEFINE_int32(num_gpu_start, 0, "GPU device start number.");
DEFINE_double(scale_gap, 0.3, "Scale gap between scales. No effect unless scale_number > 1. Initial scale is always 1."
" If you want to change the initial scale, you actually want to multiply the"
" `net_resolution` by your desired initial scale.");
DEFINE_int32(scale_number, 1, "Number of scales to average.");
// OpenPose Rendering
DEFINE_int32(part_to_show, 19, "Part to show from the start.");
DEFINE_bool(disable_blending, false, "If blending is enabled, it will merge the results with the original frame. If disabled, it"
" will only display the results.");
DEFINE_double(render_threshold, 0.05, "Only estimated keypoints whose score confidences are higher than this threshold will be"
" rendered. Generally, a high threshold (> 0.5) will only render very clear body parts;"
" while small thresholds (~0.1) will also output guessed and occluded keypoints, but also"
" more false positives (i.e. wrong detections).");
DEFINE_double(alpha_pose, 0.6, "Blending factor (range 0-1) for the body part rendering. 1 will show it completely, 0 will"
" hide it. Only valid for GPU rendering.");
DEFINE_double(alpha_heatmap, 0.7, "Blending factor (range 0-1) between heatmap and original frame. 1 will only show the"
" heatmap, 0 will only show the frame. Only valid for GPU rendering.");
cv::VideoCapture cap; // webcam capture
int Neck = 1; // index of neck
int RShoulder = 2; // index of right shoulder
int LShoulder = 5; // index of left shoulder
int RHip = 8; // index of right hip
int LHip = 11; // index of left hip
cv::Mat scarf; // picture of a scarf
cv::Mat skirt; // picture of a skirt
cv::Mat tshirt; // picture of a tshirt
/*
* source: http://jepsonsblog.blogspot.de/2012/10/overlay-transparent-image-in-opencv.html
*/
void overlayImage(const cv::Mat &background, const cv::Mat &foreground,
cv::Mat &output, cv::Point2i location)
{
background.copyTo(output);
// start at the row indicated by location, or at row 0 if location.y is negative.
for (int y = std::max(location.y, 0); y < background.rows; ++y)
{
int fY = y - location.y; // because of the translation
// we are done of we have processed all rows of the foreground image.
if (fY >= foreground.rows)
break;
// start at the column indicated by location,
// or at column 0 if location.x is negative.
for (int x = std::max(location.x, 0); x < background.cols; ++x)
{
int fX = x - location.x; // because of the translation.
// we are done with this row if the column is outside of the foreground image.
if (fX >= foreground.cols)
break;
// determine the opacity of the foregrond pixel, using its fourth (alpha) channel.
double opacity =
((double)foreground.data[fY * foreground.step + fX * foreground.channels() + 3])
/ 255.;
// and now combine the background and foreground pixel, using the opacity,
// but only if opacity > 0.
for (int c = 0; opacity > 0 && c < output.channels(); ++c)
{
unsigned char foregroundPx =
foreground.data[fY * foreground.step + fX * foreground.channels() + c];
unsigned char backgroundPx =
background.data[y * background.step + x * background.channels() + c];
output.data[y * output.step + output.channels() * x + c] =
backgroundPx * (1. - opacity) + foregroundPx * opacity;
}
}
}
}
/**
* @brief renderScarf
* renders scarf to the frame
* @param frame
* @param topleft
* position of topleft scarf corner on frame
* @param topright
* position of topright scarf corner on frame
*/
void renderScarf(cv::Mat frame, cv::Point2f topleft, cv::Point2f topright)
{
if (scarf.empty())
return;
cv::Point2f srcTri[3];
cv::Point2f dstTri[3];
srcTri[0] = cv::Point2f(0, 0);
srcTri[1] = cv::Point2f(scarf.cols - 1, 0);
srcTri[2] = cv::Point2f(0, scarf.rows - 1);
dstTri[0] = topleft;
dstTri[1] = topright;
dstTri[2] = cv::Point2f(topleft.x, topleft.y + (topright.x - topleft.x));
cv::Mat warp_mat(2, 3, CV_32FC1);
warp_mat = cv::getAffineTransform(srcTri, dstTri);
cv::Mat warpDest = cv::Mat(frame.cols, frame.rows, CV_8UC4, cv::Scalar(0, 0, 0, 0));
cv::warpAffine(scarf, warpDest, warp_mat, frame.size());
overlayImage(frame, warpDest, frame, cv::Point2i(0, 0));
}
/**
* @brief renderSkirt
* renders skirt to the frame
* @param frame
* @param topleft
* @param topright
*/
void renderSkirt(cv::Mat frame, cv::Point2f topleft, cv::Point2f topright)
{
if (scarf.empty())
return;
cv::Point2f srcTri[3];
cv::Point2f dstTri[3];
srcTri[0] = cv::Point2f(0, 0);
srcTri[1] = cv::Point2f(skirt.cols - 1, 0);
srcTri[2] = cv::Point2f(0, skirt.rows - 1);
dstTri[0] = topleft;
dstTri[1] = topright;
dstTri[2] = cv::Point2f(topleft.x, topleft.y + (topright.x - topleft.x));
cv::Mat warp_mat(2, 3, CV_32FC1);
warp_mat = cv::getAffineTransform(srcTri, dstTri);
cv::Mat warpDest = cv::Mat(frame.cols, frame.rows, CV_8UC4, cv::Scalar(0, 0, 0, 0));
cv::warpAffine(skirt, warpDest, warp_mat, frame.size());
overlayImage(frame, warpDest, frame, cv::Point2i(0, 0));
}
/**
* @brief renderTShirt
* renders tshirt to the frame
* @param frame
* @param topleft
* @param topright
* @param bottomleft
*/
void renderTShirt(cv::Mat frame, cv::Point2f topleft, cv::Point2f topright, cv::Point2f bottomleft)
{
if (scarf.empty())
return;
cv::Point2f srcTri[3];
cv::Point2f dstTri[3];
srcTri[0] = cv::Point2f(0, 0);
srcTri[1] = cv::Point2f(tshirt.cols - 1, 0);
srcTri[2] = cv::Point2f(0, tshirt.rows - 1);
dstTri[0] = topleft;
dstTri[1] = topright;
dstTri[2] = bottomleft;
cv::Mat warp_mat(2, 3, CV_32FC1);
warp_mat = cv::getAffineTransform(srcTri, dstTri);
cv::Mat warpDest = cv::Mat(frame.cols, frame.rows, CV_8UC4, cv::Scalar(0, 0, 0, 0));
cv::warpAffine(tshirt, warpDest, warp_mat, frame.size());
overlayImage(frame, warpDest, frame, cv::Point2i(0, 0));
}
/**
* @brief renderKeypoints
* renders keypoints to the frame and also clothes if enough keypoints are found
* @param frame
* the frame to render on
* @param keypoints
* found keypoints to render
* @param pairs
* @param colors
* @param thicknessCircleRatio
* @param thicknessLineRatioWRTCircle
* @param threshold
* @param scaleNetToFrame
*/
void renderKeypoints(cv::Mat frame, const op::Array<float> &keypoints, const std::vector<unsigned int> &pairs,
const std::vector<float> colors, const float thicknessCircleRatio, const float thicknessLineRatioWRTCircle,
const float threshold, float scaleNetToFrame)
{
try
{
if (!frame.empty())
{
// Get frame channels
const auto width = frame.size[2];
const auto height = frame.size[1];
const auto area = width * height;
cv::Mat frameB{height, width, CV_32FC1, &frame.data[0]};
cv::Mat frameG{height, width, CV_32FC1, &frame.data[area * sizeof(float) / sizeof(uchar)]};
cv::Mat frameR{height, width, CV_32FC1, &frame.data[2 * area * sizeof(float) / sizeof(uchar)]};
// Parameters
const auto lineType = 8;
const auto shift = 0;
const auto numberColors = colors.size();
const auto thresholdRectangle = 0.1f;
const auto numberKeypoints = keypoints.getSize(1);
// Keypoints
for (auto person = 0; person < keypoints.getSize(0); person++)
{
const auto personRectangle = getKeypointsRectangle(keypoints, person, numberKeypoints, thresholdRectangle);
if (personRectangle.area() > 0)
{
const auto ratioAreas = op::fastMin(1.f, op::fastMax(personRectangle.width / (float)width, personRectangle.height / (float)height));
// Size-dependent variables
const auto thicknessRatio = op::fastMax(op::intRound(std::sqrt(area) * thicknessCircleRatio * ratioAreas), 2);
// Negative thickness in cv::circle means that a filled circle is to be drawn.
const auto thicknessCircle = (ratioAreas > 0.05 ? thicknessRatio : -1);
const auto thicknessLine = op::intRound(thicknessRatio * thicknessLineRatioWRTCircle);
const auto radius = thicknessRatio / 2;
cv::Point2f lshoulder(-1, -1);
cv::Point2f rshoulder(-1, -1);
cv::Point2f lhip(-1, -1);
cv::Point2f rhip(-1, -1);
// Draw circles
for (auto part = 0; part < numberKeypoints; part++)
{
const auto faceIndex = (person * numberKeypoints + part) * keypoints.getSize(2);
if (keypoints[faceIndex + 2] > threshold)
{
const auto colorIndex = part * 3;
const cv::Scalar color{colors[colorIndex % numberColors],
colors[(colorIndex + 1) % numberColors],
colors[(colorIndex + 2) % numberColors]};
const cv::Point center{op::intRound(keypoints[faceIndex]), op::intRound(keypoints[faceIndex + 1])};
if (part == Neck || part == RShoulder || part == LShoulder || part == RHip || part == LHip)
cv::circle(frame, center /*scaleNetToFrame*/, 5, color, 3, lineType, shift);
if (part == LShoulder)
{
lshoulder = center;
}
if (part == RShoulder)
{
rshoulder = center;
}
if (part == LHip)
{
lhip = center;
lhip.x;
}
if (part == RHip)
{
rhip = center;
rhip.x;
}
}
}
if (rshoulder.x >= 0 && rshoulder.y >= 0 && lshoulder.x >= 0 && lshoulder.y >= 0 && rhip.x >= 0 && rhip.y >= 0)
{
renderTShirt(frame, rshoulder, lshoulder, rhip);
}
if (rshoulder.x >= 0 && rshoulder.y >= 0 && lshoulder.x >= 0 && lshoulder.y >= 0)
{
renderScarf(frame, rshoulder, lshoulder);
}
if (rhip.x >= 0 && rhip.y >= 0 && lhip.x >= 0 && lhip.y >= 0)
{
renderSkirt(frame, rhip, lhip);
}
}
}
}
}
catch (const std::exception &e)
{
}
}
/**
* @brief loadImages
* loads semitransparent images of clothes.
*/
void loadImages()
{
scarf = cv::imread("scarf.png", cv::IMREAD_UNCHANGED);
skirt = cv::imread("skirt.png", cv::IMREAD_UNCHANGED);
tshirt = cv::imread("tshirt.png", cv::IMREAD_UNCHANGED);
}
int dressup()
{
if (!cap.open(0))
return 1;
loadImages();
op::log("dressup - openpose example", op::Priority::High);
// ------------------------- INITIALIZATION -------------------------
// Step 1 - Set logging level
// - 0 will output all the logging messages
// - 255 will output nothing
op::check(0 <= FLAGS_logging_level && FLAGS_logging_level <= 255, "Wrong logging_level value.", __LINE__, __FUNCTION__, __FILE__);
op::ConfigureLog::setPriorityThreshold((op::Priority)FLAGS_logging_level);
op::log("", op::Priority::Low, __LINE__, __FUNCTION__, __FILE__);
// Step 2 - Read Google flags (user defined configuration)
// outputSize
const auto outputSize = op::flagsToPoint(FLAGS_output_resolution, "-1x-1");
// netInputSize
const auto netInputSize = op::flagsToPoint(FLAGS_net_resolution, "-1x368");
// poseModel
const auto poseModel = op::flagsToPoseModel(FLAGS_model_pose);
// Check no contradictory flags enabled
if (FLAGS_alpha_pose < 0. || FLAGS_alpha_pose > 1.)
op::error("Alpha value for blending must be in the range [0,1].", __LINE__, __FUNCTION__, __FILE__);
if (FLAGS_scale_gap <= 0. && FLAGS_scale_number > 1)
op::error("Incompatible flag configuration: scale_gap must be greater than 0 or scale_number = 1.", __LINE__, __FUNCTION__, __FILE__);
// Logging
op::log("", op::Priority::Low, __LINE__, __FUNCTION__, __FILE__);
// Step 3 - Initialize all required classes
op::ScaleAndSizeExtractor scaleAndSizeExtractor(netInputSize, outputSize, FLAGS_scale_number, FLAGS_scale_gap);
op::CvMatToOpInput cvMatToOpInput;
op::CvMatToOpOutput cvMatToOpOutput;
auto poseExtractorPtr = std::make_shared<op::PoseExtractorCaffe>(
poseModel, FLAGS_model_folder, FLAGS_num_gpu_start, std::vector<op::HeatMapType>{}, op::ScaleMode::ZeroToOne,
true);
op::PoseGpuRenderer poseRenderer{poseModel, poseExtractorPtr, (float)FLAGS_render_threshold,
!FLAGS_disable_blending, (float)FLAGS_alpha_pose, (float)FLAGS_alpha_heatmap};
poseRenderer.setElementToRender(FLAGS_part_to_show);
op::OpOutputToCvMat opOutputToCvMat;
const op::Point<int> windowedSize = outputSize;
op::FrameDisplayer frameDisplayer{"Dressup", outputSize};
// Step 4 - Initialize resources on desired thread (in this case single thread, i.e. we init resources here)
poseExtractorPtr->initializationOnThread();
poseRenderer.initializationOnThread();
// ------------------------- POSE ESTIMATION AND RENDERING -------------------------
// Step 1 - Read and load image, error if empty (possibly wrong path)
cv::Mat inputImage; // = op::loadImage(FLAGS_image_path, CV_LOAD_IMAGE_COLOR); // Alternative: cv::imread(FLAGS_image_path, CV_LOAD_IMAGE_COLOR);
cap >> inputImage;
if (inputImage.empty())
op::error("Could not open or find the image: " + FLAGS_image_path, __LINE__, __FUNCTION__, __FILE__);
const op::Point<int> imageSize{inputImage.cols, inputImage.rows};
// Step 2 - Get desired scale sizes
std::vector<double> scaleInputToNetInputs;
std::vector<op::Point<int>> netInputSizes;
double scaleInputToOutput = 1.f;
op::Point<int> outputResolution;
std::tie(scaleInputToNetInputs, netInputSizes, scaleInputToOutput, outputResolution) = scaleAndSizeExtractor.extract(imageSize);
char c = 'q';
do
{
cap >> inputImage;
// Step 3 - Format input image to OpenPose input and output formats
const auto netInputArray = cvMatToOpInput.createArray(inputImage, scaleInputToNetInputs, netInputSizes);
auto outputArray = cvMatToOpOutput.createArray(inputImage, scaleInputToOutput, outputResolution);
// Step 4 - Estimate poseKeypoints
poseExtractorPtr->forwardPass(netInputArray, imageSize, scaleInputToNetInputs);
const auto poseKeypoints = poseExtractorPtr->getPoseKeypoints();
const auto scaleNetToOutput = poseExtractorPtr->getScaleNetToOutput();
// Step 5 - Render pose
poseRenderer.renderPose(outputArray, poseKeypoints, scaleInputToOutput, scaleNetToOutput);
// Step 6 - OpenPose output format to cv::Mat
const auto thicknessCircleRatio = 1.f / 75.f;
const auto thicknessLineRatioWRTCircle = 0.75f;
const auto &pairs = op::POSE_BODY_PART_PAIRS_RENDER[(int)poseModel];
auto outputImage = opOutputToCvMat.formatToCvMat(outputArray);
renderKeypoints(outputImage, poseKeypoints, pairs, op::POSE_COLORS[(int)poseModel], thicknessCircleRatio,
thicknessLineRatioWRTCircle, (float)FLAGS_render_threshold, scaleNetToOutput);
// ------------------------- SHOWING RESULT AND CLOSING -------------------------
// Step 1 - Show results
//frameDisplayer.displayFrame(outputImage, 0); // Alternative: cv::imshow(outputImage) + cv::waitKey(0)
cv::imshow("dressup - openpose example", outputImage);
c = cv::waitKey(100);
} while (c != 'y' && c != 'n');
op::log("Example successfully finished.", op::Priority::High);
// Return successful message
return 0;
}
int main(int argc, char *argv[])
{
// Parsing command line flags
gflags::ParseCommandLineFlags(&argc, &argv, true);
return dressup();
}
| 44.209567 | 152 | 0.598155 | [
"render",
"vector",
"model"
] |
40e956e4de3ebee76672fe0e8ac8e63fefb501bd | 5,720 | cpp | C++ | source/tuning_runner/configuration_manager.cpp | jiri-filipovic/KTT | d70330d5a3fd02cfc2c2163ea8695b9eb1113c6d | [
"MIT"
] | null | null | null | source/tuning_runner/configuration_manager.cpp | jiri-filipovic/KTT | d70330d5a3fd02cfc2c2163ea8695b9eb1113c6d | [
"MIT"
] | null | null | null | source/tuning_runner/configuration_manager.cpp | jiri-filipovic/KTT | d70330d5a3fd02cfc2c2163ea8695b9eb1113c6d | [
"MIT"
] | null | null | null | #include <limits>
#include <stdexcept>
#include "configuration_manager.h"
#include "searcher/annealing_searcher.h"
#include "searcher/full_searcher.h"
#include "searcher/random_searcher.h"
#include "searcher/mcmc_searcher.h"
namespace ktt
{
ConfigurationManager::ConfigurationManager() :
searchMethod(SearchMethod::FullSearch)
{}
void ConfigurationManager::setKernelConfigurations(const KernelId id, const std::vector<KernelConfiguration>& configurations,
const std::vector<KernelParameter>& parameters)
{
clearData(id);
initializeSearcher(id, searchMethod, searchArguments, configurations, parameters);
}
void ConfigurationManager::setSearchMethod(const SearchMethod method, const std::vector<double>& arguments)
{
if (method == SearchMethod::Annealing && arguments.size() < 1)
{
throw std::runtime_error(std::string("Insufficient number of arguments given for specified search method: ")
+ getSearchMethodName(method));
}
this->searchArguments = arguments;
this->searchMethod = method;
}
bool ConfigurationManager::hasKernelConfigurations(const KernelId id) const
{
return searchers.find(id) != searchers.end();
}
void ConfigurationManager::clearData(const KernelId id)
{
clearSearcher(id);
if (bestConfigurations.find(id) != bestConfigurations.end())
{
bestConfigurations.erase(id);
}
}
void ConfigurationManager::clearSearcher(const KernelId id)
{
if (searchers.find(id) != searchers.end())
{
searchers.erase(id);
}
}
KernelConfiguration ConfigurationManager::getCurrentConfiguration(const KernelId id) const
{
auto searcherPair = searchers.find(id);
if (searcherPair == searchers.end())
{
throw std::runtime_error(std::string("Configuration for kernel with following id is not present: ") + std::to_string(id));
}
if (searcherPair->second->getUnexploredConfigurationCount() <= 0)
{
auto configurationPair = bestConfigurations.find(id);
if (configurationPair == bestConfigurations.end())
{
throw std::runtime_error(std::string("No configurations left to explore and no best configuration recorded for kernel with id: ")
+ std::to_string(id));
}
return std::get<0>(configurationPair->second);
}
return searcherPair->second->getCurrentConfiguration();
}
KernelConfiguration ConfigurationManager::getBestConfiguration(const KernelId id) const
{
auto configurationPair = bestConfigurations.find(id);
if (configurationPair == bestConfigurations.end())
{
return getCurrentConfiguration(id);
}
return std::get<0>(configurationPair->second);
}
ComputationResult ConfigurationManager::getBestComputationResult(const KernelId id) const
{
auto configurationPair = bestConfigurations.find(id);
if (configurationPair == bestConfigurations.end())
{
return ComputationResult("", std::vector<ParameterPair>{}, "Valid result does not exist");
}
return ComputationResult(std::get<1>(configurationPair->second), std::get<0>(configurationPair->second).getParameterPairs(),
std::get<2>(configurationPair->second));
}
void ConfigurationManager::calculateNextConfiguration(const KernelId id, const std::string& kernelName, const KernelConfiguration& previous,
const uint64_t previousDuration)
{
auto searcherPair = searchers.find(id);
if (searcherPair == searchers.end())
{
throw std::runtime_error(std::string("Configuration for kernel with following id is not present: ") + std::to_string(id));
}
auto configurationPair = bestConfigurations.find(id);
if (configurationPair == bestConfigurations.end())
{
bestConfigurations.insert(std::make_pair(id, std::make_tuple(previous, kernelName, previousDuration)));
}
else if (std::get<2>(configurationPair->second) > previousDuration)
{
bestConfigurations.erase(id);
bestConfigurations.insert(std::make_pair(id, std::make_tuple(previous, kernelName, previousDuration)));
}
searcherPair->second->calculateNextConfiguration(static_cast<double>(previousDuration));
}
void ConfigurationManager::initializeSearcher(const KernelId id, const SearchMethod method, const std::vector<double>& arguments,
const std::vector<KernelConfiguration>& configurations, const std::vector<KernelParameter>& parameters)
{
switch (method)
{
case SearchMethod::FullSearch:
searchers.insert(std::make_pair(id, std::make_unique<FullSearcher>(configurations)));
break;
case SearchMethod::RandomSearch:
searchers.insert(std::make_pair(id, std::make_unique<RandomSearcher>(configurations)));
break;
case SearchMethod::Annealing:
searchers.insert(std::make_pair(id, std::make_unique<AnnealingSearcher>(configurations, arguments.at(0))));
break;
case SearchMethod::MCMC:
searchers.insert(std::make_pair(id, std::make_unique<MCMCSearcher>(configurations, std::vector<double>(arguments.begin(),
arguments.end()))));
break;
default:
throw std::runtime_error("Specified searcher is not supported");
}
}
std::string ConfigurationManager::getSearchMethodName(const SearchMethod method)
{
switch (method)
{
case SearchMethod::FullSearch:
return std::string("FullSearch");
case SearchMethod::RandomSearch:
return std::string("RandomSearch");
case SearchMethod::Annealing:
return std::string("Annealing");
case SearchMethod::MCMC:
return std::string("Markov chain Monte Carlo");
default:
return std::string("Unknown search method");
}
}
} // namespace ktt
| 34.251497 | 141 | 0.711189 | [
"vector"
] |
40eadfd671e45f25bd553ab2a88622cdd29759a1 | 332 | cpp | C++ | all_domains/algorithms/bit_manipulation/sum_vs_xor.cpp | ejspeiro/HackerRank | 2e489588e8d7102acb676cc49fe07ee83e4f66e9 | [
"MIT"
] | null | null | null | all_domains/algorithms/bit_manipulation/sum_vs_xor.cpp | ejspeiro/HackerRank | 2e489588e8d7102acb676cc49fe07ee83e4f66e9 | [
"MIT"
] | null | null | null | all_domains/algorithms/bit_manipulation/sum_vs_xor.cpp | ejspeiro/HackerRank | 2e489588e8d7102acb676cc49fe07ee83e4f66e9 | [
"MIT"
] | null | null | null | // Copyright 2018 Eduardo Sanchez
#include <cmath>
#include <iostream>
#include <iomanip>
#include <vector>
int main() {
uint32_t nn{};
uint32_t count{};
std::cin >> nn;
uint32_t count = 0ul;
while (nn) {
count += nn%2ul? 0ul: 1ul;
nn/=2ul;
}
count = pow(2ul, count);
std::cout << count << std::endl;
}
| 14.434783 | 34 | 0.596386 | [
"vector"
] |
40ef889f0dade0acf7ed5e164a906d1639195922 | 6,646 | cc | C++ | smbprovider/iterator/directory_iterator.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | 5 | 2019-01-19T15:38:48.000Z | 2021-10-06T03:59:46.000Z | smbprovider/iterator/directory_iterator.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | null | null | null | smbprovider/iterator/directory_iterator.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | 1 | 2019-02-15T23:05:30.000Z | 2019-02-15T23:05:30.000Z | // Copyright 2018 The Chromium OS 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 "smbprovider/iterator/directory_iterator.h"
#include <utility>
#include <base/logging.h>
#include "smbprovider/constants.h"
#include "smbprovider/smbprovider_helper.h"
namespace smbprovider {
namespace {
constexpr int32_t kNoMoreEntriesError = -1;
} // namespace
BaseDirectoryIterator::BaseDirectoryIterator(const std::string& dir_path,
SambaInterface* samba_interface)
: BaseDirectoryIterator(dir_path,
samba_interface,
kDefaultMetadataBatchSize,
false /* include_metadata */) {}
BaseDirectoryIterator::BaseDirectoryIterator(const std::string& dir_path,
SambaInterface* samba_interface,
size_t batch_size)
: BaseDirectoryIterator(
dir_path, samba_interface, batch_size, false /* include_metadata */) {
}
BaseDirectoryIterator::BaseDirectoryIterator(const std::string& dir_path,
SambaInterface* samba_interface,
size_t batch_size,
bool include_metadata)
: dir_path_(dir_path),
batch_size_(batch_size),
include_metadata_(include_metadata),
samba_interface_(samba_interface) {}
BaseDirectoryIterator::BaseDirectoryIterator(BaseDirectoryIterator&& other)
: dir_path_(std::move(other.dir_path_)),
entries_(std::move(other.entries_)),
current_entry_index_(other.current_entry_index_),
batch_size_(other.batch_size_),
dir_id_(other.dir_id_),
is_done_(other.is_done_),
is_initialized_(other.is_initialized_),
include_metadata_(other.include_metadata_),
samba_interface_(other.samba_interface_) {
other.dir_id_ = -1;
other.is_initialized_ = false;
other.samba_interface_ = nullptr;
}
BaseDirectoryIterator::~BaseDirectoryIterator() {
if (dir_id_ != -1) {
CloseDirectory();
}
}
int32_t BaseDirectoryIterator::Init() {
DCHECK(!is_initialized_);
int32_t open_dir_error = OpenDirectory();
if (open_dir_error != 0) {
return open_dir_error;
}
is_initialized_ = true;
return Next();
}
int32_t BaseDirectoryIterator::Next() {
DCHECK(is_initialized_);
DCHECK(!is_done_);
++current_entry_index_;
if (current_entry_index_ >= entries_.size()) {
int32_t result = FillBuffer();
if (result != 0 && result != kNoMoreEntriesError) {
return result;
}
}
return 0;
}
const DirectoryEntry& BaseDirectoryIterator::Get() {
DCHECK(is_initialized_);
DCHECK(!is_done_);
DCHECK_LT(current_entry_index_, entries_.size());
return entries_[current_entry_index_];
}
bool BaseDirectoryIterator::IsDone() {
DCHECK(is_initialized_);
return is_done_;
}
int32_t BaseDirectoryIterator::OpenDirectory() {
DCHECK_EQ(-1, dir_id_);
return samba_interface_->OpenDirectory(dir_path_, &dir_id_);
}
void BaseDirectoryIterator::CloseDirectory() {
DCHECK_NE(-1, dir_id_);
int32_t result = samba_interface_->CloseDirectory(dir_id_);
if (result != 0) {
LOG(ERROR) << "BaseDirectoryIterator: CloseDirectory failed with error: "
<< GetErrorFromErrno(result);
}
dir_id_ = -1;
}
int32_t BaseDirectoryIterator::FillBuffer() {
int32_t fetch_error = include_metadata_ ? ReadEntriesWithMetadataToVector()
: ReadEntriesToVector();
if (fetch_error != 0) {
return fetch_error;
}
if (entries_.empty()) {
// Succeeded but nothing valid left to read.
is_done_ = true;
return kNoMoreEntriesError;
}
return 0;
}
int32_t BaseDirectoryIterator::ReadEntriesToVector() {
DCHECK(!include_metadata_);
DCHECK_GT(batch_size_, 0);
ClearVector();
for (size_t i = 0; i < batch_size_; i++) {
const struct smbc_dirent* dirent = nullptr;
int fetch_error = samba_interface_->GetDirectoryEntry(dir_id_, &dirent);
if (fetch_error) {
return fetch_error;
}
if (!dirent) {
// There are no more files, but this is not an error. The next call to
// refill the buffer will hit this case on the first iteration of the
// loop and will return an empty vector which will cause FillBuffer()
// to set |done_| and return |kNoMoreEntriesError|.
return 0;
}
AddEntryIfValid(*dirent);
}
// Completed the batch successfully.
return 0;
}
int32_t BaseDirectoryIterator::ReadEntriesWithMetadataToVector() {
DCHECK(include_metadata_);
DCHECK_GT(batch_size_, 0);
ClearVector();
for (size_t i = 0; i < batch_size_; i++) {
const struct libsmb_file_info* file_info = nullptr;
int fetch_error =
samba_interface_->GetDirectoryEntryWithMetadata(dir_id_, &file_info);
if (fetch_error) {
return fetch_error;
}
if (!file_info) {
// There are no more files, but this is not an error. The next call to
// refill the buffer will hit this case on the first iteration of the
// loop and will return an empty vector which will cause FillBuffer()
// to set |done_| and return |kNoMoreEntriesError|.
return 0;
}
AddEntryIfValid(*file_info);
}
// Completed the batch successfully.
return 0;
}
void BaseDirectoryIterator::ClearVector() {
entries_.clear();
current_entry_index_ = 0;
}
void BaseDirectoryIterator::AddEntryIfValid(const smbc_dirent& dirent) {
const std::string name(dirent.name);
// Ignore "." and ".." entries.
// TODO(allenvic): Handle SMBC_LINK
if (IsSelfOrParentDir(name) || !ShouldIncludeEntryType(dirent.smbc_type)) {
return;
}
bool is_directory =
dirent.smbc_type == SMBC_DIR || dirent.smbc_type == SMBC_FILE_SHARE;
entries_.emplace_back(is_directory, name, AppendPath(dir_path_, name));
}
void BaseDirectoryIterator::AddEntryIfValid(
const struct libsmb_file_info& file_info) {
const std::string name(file_info.name);
const uint16_t attrs(file_info.attrs);
// Ignore "." and ".." entries as well as symlinks.
// TODO(zentaro): Investigate how this API deals with directories that are
// file shares.
if (IsSelfOrParentDir(name) || IsSymlink(file_info.attrs)) {
return;
}
bool is_directory = attrs & kFileAttributeDirectory;
entries_.emplace_back(is_directory, name, AppendPath(dir_path_, name),
file_info.size, file_info.mtime_ts.tv_sec);
}
} // namespace smbprovider
| 29.277533 | 80 | 0.67424 | [
"vector"
] |
40f39de0bf5c799cf2b32fcfbb79baf096a8ec30 | 140,089 | cc | C++ | physicalrobots/player/server/drivers/mixed/p2os/p2os.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | physicalrobots/player/server/drivers/mixed/p2os/p2os.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | physicalrobots/player/server/drivers/mixed/p2os/p2os.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
* Player - One Hell of a Robot Server
* Copyright (C) 2000
* Brian Gerkey, Kasper Stoy, Richard Vaughan, & Andrew Howard
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*
* $Id: p2os.cc 8184 2009-08-07 08:48:58Z gbiggs $
*
* the P2OS device. it's the parent device for all the P2 'sub-devices',
* like gripper, position, sonar, etc. there's a thread here that
* actually interacts with P2OS via the serial line. the other
* "devices" communicate with this thread by putting into and getting
* data out of shared buffers.
*/
/** @ingroup drivers */
/** @{ */
/** @defgroup driver_p2os p2os
* @brief ActivMedia mobile robots
Many robots made by ActivMedia, such as the Pioneer series and the
AmigoBot, are controlled by a microcontroller that runs a special embedded
operating system called P2OS (aka AROS, PSOS). The host computer
talks to the P2OS microcontroller over a standard RS232 serial line.
This driver offer access to the various P2OS-mediated devices, logically
splitting up the devices' functionality.
@par Compile-time dependencies
- none
@par Provides
The p2os driver provides the following device interfaces, some of
them named:
- "odometry" @ref interface_position2d
- This interface returns odometry data, and accepts velocity commands.
- "compass" @ref interface_position2d
- This interface returns compass data (if equipped).
- "gyro" @ref interface_position2d
- This interface returns gyroscope data (if equipped).
- @ref interface_power
- Returns the current battery voltage (12 V when fully charged).
- @ref interface_sonar
- Returns data from sonar arrays (if equipped)
- @ref interface_aio
- Returns data from analog I/O ports (if equipped)
- @ref interface_dio
- Returns data from digital I/O ports (if equipped)
- "gripper" @ref interface_gripper
- Controls gripper (if equipped)
- "lift" @ref interface_actarray
- Controls a lift on the gripper (if gripper equipped)
- The lift is controlled by actuator 0. Position 1.0 is up and 0.0 is down.
- "arm" @ref interface_actarray
- Controls arm (if equipped)
- This driver does not support the player_actarray_speed_cmd and
player_actarray_brakes_config messages.
- @ref interface_limb
- Inverse kinematics interface to arm
- This driver does not support the player_limb_setposition_cmd,
player_limb_vecmove_cmd, player_limb_brakes_req and
player_limb_speed_req messages.
- The approach vector is forward along the gripper with the orientation
vector up from the gripper's centre.
- The limb takes pose commands in robot coordinates (offset from the robot's
centre, not the limb's base) and returns pose data in the same coordinate
space.
- The kinematics calculator is based on the analytical method by Gan et al. See:
J.Q. Gan, E. Oyama, E.M. Rosales, and H. Hu, "A complete analytical
solution to the inverse kinematics of the Pioneer 2 robotic arm,"
Robotica, vol.23, no.1, pp.123-129, 2005.
- "armgrip" @ref interface_gripper
- Controls the gripper on the end of the arm (if equipped)
- Good for using in conjunction with the @ref interface_limb
- @ref interface_bumper
- Returns data from bumper array (if equipped)
- @ref interface_blobfinder
- Controls a CMUCam2 connected to the AUX port on the P2OS board
(if equipped).
- @ref interface_ptz
- Controls a Canon VCC4 PTZ camera connected to the AUX2 port on
the P2OS board (if equipped).
- @ref interface_audio
- Controls the sound system of the AmigoBot, which can play back
recorded wav files.
@par Supported configuration requests
- "odometry" @ref interface_position2d :
- PLAYER_POSITION2D_REQ_SET_ODOM
- PLAYER_POSITION2D_REQ_MOTOR_POWER
- PLAYER_POSITION2D_REQ_RESET_ODOM
- PLAYER_POSITION2D_REQ_GET_GEOM
- PLAYER_POSITION2D_REQ_VELOCITY_MODE
- @ref interface_sonar :
- PLAYER_SONAR_REQ_POWER
- PLAYER_SONAR_REQ_GET_GEOM
- @ref interface_bumper :
- PLAYER_BUMPER_REQ_GET_GEOM
- @ref interface_blobfinder :
- PLAYER_BLOBFINDER_REQ_SET_COLOR
- PLAYER_BLOBFINDER_REQ_SET_IMAGER_PARAMS
@par Configuration file options
- port (string)
- Default: "/dev/ttyS0"
- use_tcp (boolean)
- Defaut: 0
- Set to 1 if a TCP connection should be used instead of serial port (e.g. Amigobot
with ethernet-serial bridge device attached)
- tcp_remote_host (string)
- Default: "localhost"
- Remote hostname or IP address to connect to if using TCP
- tcp_remote_port (integer)
- Default: 8101
- Remote port to connect to if using TCP
- Serial port used to communicate with the robot.
- radio (integer)
- Default: 0
- Nonzero if a radio modem is being used; zero for a direct serial link.
(a radio modem is different from and older than the newer ethernet-serial bridge used
on newer Pioneers and Amigos)
- bumpstall (integer)
- Default: -1
- Determine whether a bumper-equipped robot stalls when its bumpers are
pressed. Allowed values are:
- -1 : Don't change anything; the bumper-stall behavior will
be determined by the BumpStall value stored in the robot's
FLASH.
- 0 : Don't stall.
- 1 : Stall on front bumper contact.
- 2 : Stall on rear bumper contact.
- 3 : Stall on either bumper contact.
- pulse (float)
- Default: -1
- Specify a pulse for keeping the robot alive. Pioneer robots have a built-in watchdog in
the onboard controller. After a timeout period specified in the robot's FLASH, if no commands
have been received from the player server, the robot will stop. By specifying a positive value
here, the Player server will send a regular pulse command to the robot to let it know the client
is still alive. The value should be in seconds, with decimal places allowed (eg 0.5 = half a
second). Note that if this value is greater than the Pioneer's onboard value, it will still
time out.
- Specifying a value of -1 turns off the pulse, meaning that if you do not send regular commands
from your client program, the robot's onboard controller will time out and stop.
- WARNING: Overriding the onboard watchdog is dangerous! Specifying -1 and writing your client
appropriately is definitely the preffered option!
- joystick (integer)
- Default: 0
- Use direct joystick control
- direct_wheel_vel_control (integer)
- Default: 1
- Send direct wheel velocity commands to P2OS (as opposed to sending
translational and rotational velocities and letting P2OS smoothly
achieve them).
- max_xspeed (length)
- Default: 0.5 m/s
- Maximum translational velocity
- max_yawspeed (angle)
- Default: 100 deg/s
- Maximum rotational velocity
- max_xaccel (length)
- Default: 0
- Maximum translational acceleration, in length/sec/sec; nonnegative.
Zero means use the robot's default value.
- max_xdecel (length)
- Default: 0
- Maximum translational deceleration, in length/sec/sec; nonpositive.
Zero means use the robot's default value.
- max_yawaccel (angle)
- Default: 0
- Maximum rotational acceleration, in angle/sec/sec; nonnegative.
Zero means use the robot's default value.
- rot_kp (integer)
- Default: -1
- Rotational PID setting; proportional gain.
Negative means use the robot's default value.
- Requires P2OS1.M or above
- rot_kv (integer)
- Default: -1
- Rotational PID setting; derivative gain.
Negative means use the robot's default value.
- Requires P2OS1.M or above
- rot_ki (integer)
- Default: -1
- Rotational PID setting; integral gain.
Negative means use the robot's default value.
- Requires P2OS1.M or above
- trans_kp (integer)
- Default: -1
- Translational PID setting; proportional gain.
Negative means use the robot's default value.
- Requires P2OS1.M or above
- trans_kv (integer)
- Default: -1
- Translational PID setting; derivative gain.
Negative means use the robot's default value.
- Requires P2OS1.M or above
- trans_ki (integer)
- Default: -1
- Translational PID setting; integral gain.
Negative means use the robot's default value.
- Requires P2OS1.M or above
- max_yawdecel (angle)
- Default: 0
- Maximum rotational deceleration, in angle/sec/sec; nonpositive.
Zero means use the robot's default value.
- use_vel_band (integer)
- Default: 0
- Use velocity bands
- aa_basepos (3 floats)
- Default: (0.105, 0, 0.3185)
- Position of the base of the arm from the robot centre in metres.
- aa_baseorient (3 floats)
- Default: 0, 0, 0
- Orientation of the base of the arm from the robot centre in radians.
- aa_offsets (6 floats)
- Default: (0.06875, 0.16, 0, 0.13775, 0.11321, 0)
- Offsets for the actarray. Taken from current actuator to next actuator.
Each offset is a straight line, not measured per axis.
- aa_orients (3x6 floats)
- Default: all zero
- Orientation of each actuator when it is at 0. Measured by taking a line from
this actuator to the next and measuring its angles about the 3 axes of the
previous actuator's coordinate space.
- Each set of three values is a single orientation.
- aa_axes (3x6 floats)
- Default: ((0,0,-1), (0,-1,0), (0,-1,0), (1,0,0), (0,1,0), (0,0,1))
- The axis of rotation for each joint in the actarray.
- Each set of three values is a vector along the axis of rotation.
- limb_pos (3 floats)
- Default: (0.105, 0, 0.3185)
- Position of the base of the arm from the robot centre in metres.
- limb_links (5 floats)
- Default: (0.06875, 0.16, 0, 0.13775, 0.11321)
- Offset from previous joint to this joint in metres.
e.g. the offset from joint 0 to joint 1 is 0.06875m, and from joint 1 to joint 2 is 0.16m.
- The default is correct for the standard Pioneer arm at time of writing.
- limb_offsets (5 floats, metres)
- Default: (0, 0, 0, 0, 0)
- Angular offset of each joint from desired position to actual position (calibration data).
- Possibly taken by commanding joints to 0rad with actarray interface, then measuring
their actual angle.
- gripper_pose (6 floats - 3 in metres, 3 in rads)
- Default: (0, 0, 0, 0, 0, 0)
- 3D pose of the standard gripper
- gripper_outersize (3 floats, metres)
- Default: (0.315, 0.195, 0.035)
- Size of the outside of the standard gripper
- gripper_innersize (3 floats, metres)
- Default: (0.205, 0.095, 1.0)
- Size of the inside of the standard gripper's fingers when fully open,
i.e. the largest object it can pick up.
- armgrip_outersize (3 floats, metres)
- Default: (0.09, 0.09, 0.041)
- Size of the outside of the arm's gripper
- armgrip_innersize (3 floats, metres)
- Default: (0.054, 0.025, 1.0)
- Size of the inside of the arm's gripper (largest object it can hold)
- ignore_checksum (boolean)
- Default: False (no effect)
- If set to True, the checksum will be ignored
@par Example
@verbatim
driver
(
name "p2os"
provides ["odometry::position:0" "compass::position:1" "sonar:0" "power:0"]
)
@endverbatim
@author Brian Gerkey, Kasper Stoy, James McKenna
*/
/** @} */
#include "config.h"
#include "p2os.h"
#include <libplayerinterface/playerxdr.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <math.h>
#include <stdlib.h> /* for abs() */
#include <netinet/in.h>
#include <termios.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <netdb.h>
Driver*
P2OS_Init(ConfigFile* cf, int section)
{
return (Driver*)(new P2OS(cf,section));
}
void p2os_Register(DriverTable* table)
{
table->AddDriver("p2os", P2OS_Init);
}
P2OS::P2OS(ConfigFile* cf, int section)
: ThreadedDriver(cf,section,true,PLAYER_MSGQUEUE_DEFAULT_MAXLEN)
{
// zero ids, so that we'll know later which interfaces were requested
memset(&this->position_id, 0, sizeof(player_devaddr_t));
memset(&this->sonar_id, 0, sizeof(player_devaddr_t));
memset(&this->aio_id, 0, sizeof(player_devaddr_t));
memset(&this->dio_id, 0, sizeof(player_devaddr_t));
memset(&this->gripper_id, 0, sizeof(player_devaddr_t));
memset(&this->bumper_id, 0, sizeof(player_devaddr_t));
memset(&this->power_id, 0, sizeof(player_devaddr_t));
memset(&this->compass_id, 0, sizeof(player_devaddr_t));
memset(&this->gyro_id, 0, sizeof(player_devaddr_t));
memset(&this->blobfinder_id, 0, sizeof(player_devaddr_t));
memset(&this->audio_id, 0, sizeof(player_devaddr_t));
memset(&this->actarray_id, 0, sizeof(player_devaddr_t));
memset(&this->limb_id, 0, sizeof(player_devaddr_t));
memset(&this->ptz_id, 0, sizeof(player_devaddr_t));
this->position_subscriptions = this->sonar_subscriptions = this->actarray_subscriptions = 0;
this->pulse = -1;
// intialise members
sippacket = NULL;
// Do we create a robot position interface?
if(cf->ReadDeviceAddr(&(this->position_id), section, "provides",
PLAYER_POSITION2D_CODE, -1, NULL) == 0)
{
if(this->AddInterface(this->position_id) != 0)
{
this->SetError(-1);
return;
}
}
// Do we create a compass position interface?
if(cf->ReadDeviceAddr(&(this->compass_id), section, "provides",
PLAYER_POSITION2D_CODE, -1, "compass") == 0)
{
if(this->AddInterface(this->compass_id) != 0)
{
this->SetError(-1);
return;
}
}
// Do we create a gyro position interface?
if(cf->ReadDeviceAddr(&(this->gyro_id), section, "provides",
PLAYER_POSITION2D_CODE, -1, "gyro") == 0)
{
if(this->AddInterface(this->gyro_id) != 0)
{
this->SetError(-1);
return;
}
}
// Do we create a sonar interface?
if(cf->ReadDeviceAddr(&(this->sonar_id), section, "provides",
PLAYER_SONAR_CODE, -1, NULL) == 0)
{
if(this->AddInterface(this->sonar_id) != 0)
{
this->SetError(-1);
return;
}
}
// Do we create an aio interface?
if(cf->ReadDeviceAddr(&(this->aio_id), section, "provides",
PLAYER_AIO_CODE, -1, NULL) == 0)
{
if(this->AddInterface(this->aio_id) != 0)
{
this->SetError(-1);
return;
}
}
// Do we create a dio interface?
if(cf->ReadDeviceAddr(&(this->dio_id), section, "provides",
PLAYER_DIO_CODE, -1, NULL) == 0)
{
if(this->AddInterface(this->dio_id) != 0)
{
this->SetError(-1);
return;
}
}
// Do we create a gripper interface?
if(cf->ReadDeviceAddr(&(this->gripper_id), section, "provides",
PLAYER_GRIPPER_CODE, -1, "gripper") == 0)
{
if(this->AddInterface(this->gripper_id) != 0)
{
this->SetError(-1);
return;
}
}
// Do we create an actarray interface for the gripper lift?
if(cf->ReadDeviceAddr(&(this->lift_id), section, "provides",
PLAYER_ACTARRAY_CODE, -1, "lift") == 0)
{
if(this->AddInterface(this->lift_id) != 0)
{
this->SetError(-1);
return;
}
}
// Do we create a bumper interface?
if(cf->ReadDeviceAddr(&(this->bumper_id), section, "provides",
PLAYER_BUMPER_CODE, -1, NULL) == 0)
{
if(this->AddInterface(this->bumper_id) != 0)
{
this->SetError(-1);
return;
}
}
// Do we create a power interface?
if(cf->ReadDeviceAddr(&(this->power_id), section, "provides",
PLAYER_POWER_CODE, -1, NULL) == 0)
{
if(this->AddInterface(this->power_id) != 0)
{
this->SetError(-1);
return;
}
}
// Do we create a blobfinder interface?
if(cf->ReadDeviceAddr(&(this->blobfinder_id), section, "provides",
PLAYER_BLOBFINDER_CODE, -1, NULL) == 0)
{
if(this->AddInterface(this->blobfinder_id) != 0)
{
this->SetError(-1);
return;
}
}
// Do we create a audio interface?
if(cf->ReadDeviceAddr(&(this->audio_id), section, "provides",
PLAYER_AUDIO_CODE, -1, NULL) == 0)
{
if(this->AddInterface(this->audio_id) != 0)
{
this->SetError(-1);
return;
}
}
// Do We create the PTZ Interface
if(cf->ReadDeviceAddr(&(this->ptz_id), section, "provides",
PLAYER_PTZ_CODE, -1, NULL) == 0)
{
if(this->AddInterface(this->ptz_id) != 0)
{
this->SetError(-1);
return;
}
this->minfov = (int)rint(RTOD(cf->ReadTupleAngle(section, "fov", 0, DTOR(3))));
this->maxfov = (int)rint(RTOD(cf->ReadTupleAngle(section, "fov", 1, DTOR(30))));
}
// Do we create a limb interface?
if(cf->ReadDeviceAddr(&(this->limb_id), section, "provides", PLAYER_LIMB_CODE, -1, NULL) == 0)
{
if(this->AddInterface(this->limb_id) != 0)
{
this->SetError(-1);
return;
}
// If we do, we need a kinematics calculator
kineCalc = new KineCalc;
}
else
kineCalc = NULL;
// Do we create an arm gripper interface?
if(cf->ReadDeviceAddr(&(this->armgripper_id), section, "provides", PLAYER_GRIPPER_CODE, -1, "armgrip") == 0)
{
if(this->AddInterface(this->armgripper_id) != 0)
{
this->SetError(-1);
return;
}
}
// Do we create an actarray interface? Note that if we have a limb or arm gripper interface,
// this implies an actarray interface
if((cf->ReadDeviceAddr(&(this->actarray_id), section, "provides", PLAYER_ACTARRAY_CODE, -1, "arm") == 0) ||
this->limb_id.interf || this->armgripper_id.interf)
{
if(this->AddInterface(this->actarray_id) != 0)
{
this->SetError(-1);
return;
}
// Stop actarray messages in the queue from being overwritten
this->InQueue->AddReplaceRule (this->actarray_id, PLAYER_MSGTYPE_CMD, PLAYER_ACTARRAY_CMD_POS, false);
this->InQueue->AddReplaceRule (this->actarray_id, PLAYER_MSGTYPE_CMD, PLAYER_ACTARRAY_CMD_SPEED, false);
this->InQueue->AddReplaceRule (this->actarray_id, PLAYER_MSGTYPE_CMD, PLAYER_ACTARRAY_CMD_HOME, false);
}
// build the table of robot parameters.
::initialize_robot_params();
// Read config file options
this->ignore_checksum = cf->ReadBool(section, "ignore_checksum", false);
this->bumpstall = cf->ReadInt(section,"bumpstall",-1);
this->pulse = cf->ReadFloat(section,"pulse",-1);
this->rot_kp = cf->ReadInt(section, "rot_kp", -1);
this->rot_kv = cf->ReadInt(section, "rot_kv", -1);
this->rot_ki = cf->ReadInt(section, "rot_ki", -1);
this->trans_kp = cf->ReadInt(section, "trans_kp", -1);
this->trans_kv = cf->ReadInt(section, "trans_kv", -1);
this->trans_ki = cf->ReadInt(section, "trans_ki", -1);
this->psos_serial_port = cf->ReadString(section,"port",DEFAULT_P2OS_PORT);
//this->psos_use_tcp = cf->ReadBool(section, "use_tcp", false); // TODO after ReadBool added
this->psos_use_tcp = cf->ReadInt(section, "use_tcp", 0);
this->psos_tcp_host = cf->ReadString(section, "tcp_remote_host", DEFAULT_P2OS_TCP_REMOTE_HOST);
this->psos_tcp_port = cf->ReadInt(section, "tcp_remote_port", DEFAULT_P2OS_TCP_REMOTE_PORT);
this->radio_modemp = cf->ReadInt(section, "radio", 0);
this->joystickp = cf->ReadInt(section, "joystick", 0);
this->direct_wheel_vel_control =
cf->ReadInt(section, "direct_wheel_vel_control", 1);
this->motor_max_speed = (int)rint(1e3 * cf->ReadLength(section,
"max_xspeed",
MOTOR_DEF_MAX_SPEED));
this->motor_max_turnspeed = (int)rint(RTOD(cf->ReadAngle(section,
"max_yawspeed",
MOTOR_DEF_MAX_TURNSPEED)));
this->motor_max_trans_accel = (short)rint(1e3 *
cf->ReadLength(section,
"max_xaccel", 0));
this->motor_max_trans_decel = (short)rint(1e3 *
cf->ReadLength(section,
"max_xdecel", 0));
this->motor_max_rot_accel = (short)rint(RTOD(cf->ReadAngle(section,
"max_yawaccel",
0)));
this->motor_max_rot_decel = (short)rint(RTOD(cf->ReadAngle(section,
"max_yawdecel",
0)));
this->use_vel_band = cf->ReadInt(section, "use_vel_band", 0);
// Gripper configuration
gripperPose.px = cf->ReadTupleFloat(section, "gripper_pose", 0, 0.0f);
gripperPose.py = cf->ReadTupleFloat(section, "gripper_pose", 1, 0.0f);
gripperPose.pz = cf->ReadTupleFloat(section, "gripper_pose", 2, 0.0f);
gripperPose.proll = cf->ReadTupleFloat(section, "gripper_pose", 3, 0.0f);
gripperPose.ppitch = cf->ReadTupleFloat(section, "gripper_pose", 4, 0.0f);
gripperPose.pyaw = cf->ReadTupleFloat(section, "gripper_pose", 5, 0.0f);
gripperOuterSize.sw = cf->ReadTupleFloat(section, "gripper_outersize", 0, 0.315f);
gripperOuterSize.sl = cf->ReadTupleFloat(section, "gripper_outersize", 1, 0.195f);
gripperOuterSize.sh = cf->ReadTupleFloat(section, "gripper_outersize", 2, 0.035f);
gripperInnerSize.sw = cf->ReadTupleFloat(section, "gripper_innersize", 0, 0.205f);
gripperInnerSize.sl = cf->ReadTupleFloat(section, "gripper_innersize", 1, 0.095f);
gripperInnerSize.sh = cf->ReadTupleFloat(section, "gripper_innersize", 2, 0.035f);
// Arm gripper configuration
armGripperOuterSize.sw = cf->ReadTupleFloat(section, "armgrip_outersize", 0, 0.09f);
armGripperOuterSize.sl = cf->ReadTupleFloat(section, "armgrip_outersize", 1, 0.09f);
armGripperOuterSize.sh = cf->ReadTupleFloat(section, "armgrip_outersize", 2, 0.041f);
armGripperInnerSize.sw = cf->ReadTupleFloat(section, "armgrip_innersize", 0, 0.054f);
armGripperInnerSize.sl = cf->ReadTupleFloat(section, "armgrip_innersize", 1, 0.025f);
armGripperInnerSize.sh = cf->ReadTupleFloat(section, "armgrip_innersize", 2, 1.0f);
// Actarray configuration
// Offsets
aaLengths[0] = cf->ReadTupleFloat(section, "aa_offsets", 1, 0.06875f);
aaLengths[1] = cf->ReadTupleFloat(section, "aa_offsets", 2, 0.16f);
aaLengths[2] = cf->ReadTupleFloat(section, "aa_offsets", 3, 0.0925f);
aaLengths[3] = cf->ReadTupleFloat(section, "aa_offsets", 4, 0.05f);
aaLengths[4] = cf->ReadTupleFloat(section, "aa_offsets", 5, 0.085f);
aaLengths[5] = cf->ReadTupleFloat(section, "aa_offsets", 0, 0.0f);
// Orientations default: all zeros
for (int ii = 0; ii < 18; ii++)
{
aaOrients[ii] = cf->ReadTupleFloat(section, "aa_orients", ii, 0.0f);
}
// Joint 0 default: (0, 0, 1)
aaAxes[0] = cf->ReadTupleFloat(section, "aa_axes", 0, 0.0f);
aaAxes[1] = cf->ReadTupleFloat(section, "aa_axes", 1, 0.0f);
aaAxes[2] = cf->ReadTupleFloat(section, "aa_axes", 2, -1.0f);
// Joint 1 default: (0, 1, 0)
aaAxes[3] = cf->ReadTupleFloat(section, "aa_axes", 3, 0.0f);
aaAxes[4] = cf->ReadTupleFloat(section, "aa_axes", 4, -1.0f);
aaAxes[5] = cf->ReadTupleFloat(section, "aa_axes", 5, 0.0f);
// Joint 2 default: (0, 1, 0)
aaAxes[6] = cf->ReadTupleFloat(section, "aa_axes", 6, 0.0f);
aaAxes[7] = cf->ReadTupleFloat(section, "aa_axes", 7, -1.0f);
aaAxes[8] = cf->ReadTupleFloat(section, "aa_axes", 8, 0.0f);
// Joint 3 default: (1, 0, 0)
aaAxes[9] = cf->ReadTupleFloat(section, "aa_axes", 9, 1.0f);
aaAxes[10] = cf->ReadTupleFloat(section, "aa_axes", 10, 0.0f);
aaAxes[11] = cf->ReadTupleFloat(section, "aa_axes", 11, 0.0f);
// Joint 4 default: (0, 1, 0)
aaAxes[12] = cf->ReadTupleFloat(section, "aa_axes", 12, 0.0f);
aaAxes[13] = cf->ReadTupleFloat(section, "aa_axes", 13, 1.0f);
aaAxes[14] = cf->ReadTupleFloat(section, "aa_axes", 14, 0.0f);
// Joint 5 default: (0, 0, 1)
aaAxes[15] = cf->ReadTupleFloat(section, "aa_axes", 15, 0.0f);
aaAxes[16] = cf->ReadTupleFloat(section, "aa_axes", 16, 0.0f);
aaAxes[17] = cf->ReadTupleFloat(section, "aa_axes", 17, 1.0f);
// Joint base position, orientation
aaBasePos.px = cf->ReadTupleFloat(section, "aa_basepos", 0, 0.105f);
aaBasePos.py = cf->ReadTupleFloat(section, "aa_basepos", 1, 0.0f);
aaBasePos.pz = cf->ReadTupleFloat(section, "aa_basepos", 2, 0.3185f);
aaBaseOrient.proll = cf->ReadTupleFloat(section, "aa_baseorient", 0, 0.0f);
aaBaseOrient.ppitch = cf->ReadTupleFloat(section, "aa_baseorient", 1, 0.0f);
aaBaseOrient.pyaw = cf->ReadTupleFloat(section, "aa_baseorient", 2, 0.0f);
// Limb configuration
if(kineCalc)
{
limb_data.state = PLAYER_LIMB_STATE_IDLE;
armOffsetX = cf->ReadTupleFloat(section, "limb_pos", 0, 0.105f);
armOffsetY = cf->ReadTupleFloat(section, "limb_pos", 1, 0.0f);
armOffsetZ = cf->ReadTupleFloat(section, "limb_pos", 2, 0.3185f);
double temp1 = cf->ReadTupleFloat(section, "limb_links", 0, 0.06875f);
double temp2 = cf->ReadTupleFloat(section, "limb_links", 1, 0.16f);
double temp3 = cf->ReadTupleFloat(section, "limb_links", 2, 0.0f);
double temp4 = cf->ReadTupleFloat(section, "limb_links", 3, 0.13775f);
double temp5 = cf->ReadTupleFloat(section, "limb_links", 4, 0.11321f);
kineCalc->SetLinkLengths (temp1, temp2, temp3, temp4, temp5);
kineCalc->SetOffset (0, cf->ReadTupleFloat(section, "limb_offsets", 0, 0.0f));
kineCalc->SetOffset (0, cf->ReadTupleFloat(section, "limb_offsets", 1, 0.0f));
kineCalc->SetOffset (0, cf->ReadTupleFloat(section, "limb_offsets", 2, 0.0f));
kineCalc->SetOffset (0, cf->ReadTupleFloat(section, "limb_offsets", 3, 0.0f));
kineCalc->SetOffset (0, cf->ReadTupleFloat(section, "limb_offsets", 4, 0.0f));
}
this->psos_fd = -1;
sentGripperCmd = false;
sentArmGripperCmd = true;
lastGripperCmd = lastLiftCmd = lastArmGripperCmd = lastActArrayCmd = 255;
memset (&lastLiftPosCmd, 0, sizeof (player_actarray_position_cmd_t));
memset (&lastActArrayPosCmd, 0, sizeof (player_actarray_position_cmd_t));
}
int P2OS::MainSetup()
{
int i;
// this is the order in which we'll try the possible baud rates. we try 9600
// first because most robots use it, and because otherwise the radio modem
// connection code might not work (i think that the radio modems operate at
// 9600).
int bauds[] = {B9600, B38400, B19200, B115200, B57600};
int numbauds = sizeof bauds / sizeof(int);
int currbaud = 0;
struct termios term;
unsigned char command;
P2OSPacket packet, receivedpacket;
int flags=0;
bool sent_close = false;
enum
{
NO_SYNC,
AFTER_FIRST_SYNC,
AFTER_SECOND_SYNC,
READY
} psos_state;
psos_state = NO_SYNC;
char name[20], type[20], subtype[20];
int cnt;
if(this->psos_use_tcp)
{
// TCP socket:
printf("P2OS connecting to remote host (%s:%d)... ", this->psos_tcp_host, this->psos_tcp_port);
fflush(stdout);
if( (this->psos_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror("P2OS::Setup():socket():");
return(1);
}
//printf("created socket %d.\nLooking up hostname...\n", this->psos_fd);
struct sockaddr_in addr;
memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(this->psos_tcp_port);
#if HAVE_GETADDRINFO
struct addrinfo * addr_ptr = NULL;
if (getaddrinfo(this->psos_tcp_host, NULL, NULL, &addr_ptr))
{
PLAYER_ERROR("Error looking up hostname or address");
return 1;
}
assert(addr_ptr);
assert(addr_ptr->ai_addr);
assert((addr_ptr->ai_addr->sa_family) == AF_INET);
addr.sin_addr.s_addr = (reinterpret_cast<struct sockaddr_in *>(addr_ptr->ai_addr))->sin_addr.s_addr;
freeaddrinfo(addr_ptr);
addr_ptr = NULL;
#else
struct hostent* h = gethostbyname(this->psos_tcp_host);
if(!h)
{
perror("Error looking up hostname or address %s:");
return(1);
}
assert(static_cast<size_t> (h->h_length) <= sizeof(addr.sin_addr));
//printf("gethostbyname returned address %d length %d.\n", * h->h_addr, h->h_length);
memcpy(&(addr.sin_addr), h->h_addr, h->h_length);
//printf("copied address to addr.sin_addr.s_addr=%d\n", addr.sin_addr.s_addr);
#endif
PLAYER_WARN("Found host address, connecting...");
if(connect(this->psos_fd, reinterpret_cast<struct sockaddr*> (&addr), sizeof(addr)) < 0)
{
perror("Error Connecting to remote host (P2OS::Setup()::connect()):");
return(1);
}
fcntl(this->psos_fd, F_SETFL, O_SYNC | O_NONBLOCK);
if((flags = fcntl(this->psos_fd, F_GETFL)) < 0)
{
perror("P2OS::Setup():fcntl()");
close(this->psos_fd);
this->psos_fd = -1;
return(1);
}
assert(flags & O_NONBLOCK);
PLAYER_WARN("TCP socket connection is OK... ");
fflush(stdout);
}
else
{
// Serial port:
printf("P2OS connection opening serial port %s...",this->psos_serial_port);
fflush(stdout);
if((this->psos_fd = open(this->psos_serial_port,
#ifdef __QNXNTO__
O_RDWR | O_NONBLOCK, S_IRUSR | S_IWUSR )) < 0 )
#else
O_RDWR | O_SYNC | O_NONBLOCK, S_IRUSR | S_IWUSR )) < 0 )
#endif
{
perror("P2OS::Setup():open():");
return(1);
}
if(tcgetattr( this->psos_fd, &term ) < 0 )
{
perror("P2OS::Setup():tcgetattr():");
close(this->psos_fd);
this->psos_fd = -1;
return(1);
}
cfmakeraw( &term );
cfsetispeed(&term, bauds[currbaud]);
cfsetospeed(&term, bauds[currbaud]);
#if defined (__APPLE__)
/* CLOCAL: Local connection (no modem control) */
/* CREAD: Enable the receiver */
term.c_cflag |= (CLOCAL | CREAD);
/* PARENB: Use NO parity */
/* CSTOPB: Use 1 stop bit */
/* CSIZE: Next two constants: */
/* CS8: Use 8 data bits */
term.c_cflag &= ~PARENB;
term.c_cflag &= ~CSTOPB;
term.c_cflag &= ~CSIZE;
term.c_cflag |= CS8;
/* IGNPAR: Ignore bytes with parity errors */
/* ICRNL: Map CR to NL (otherwise a CR input on the other computer will not terminate input) */
term.c_iflag |= (IGNPAR | IGNBRK);
/* No flags at all for output control */
term.c_oflag = 0;
/* IXON: Disable software flow control (incoming) */
/* IXOFF: Disable software flow control (outgoing) */
/* IXANY: Disable software flow control (any character can start flow control */
term.c_iflag &= ~(IXON | IXOFF | IXANY);
/* NO FLAGS AT ALL FOR LFLAGS */
term.c_lflag = 0;
/* Clean the modem line and activate new port settings */
tcflush(this->psos_fd, TCIOFLUSH);
if (tcsetattr(this->psos_fd, TCSANOW, &term) < 0) {
perror("P2OS::Setup():tcsetattr()");
close(this->psos_fd);
this->psos_fd = -1;
return(1);
}
#else
if(tcsetattr(this->psos_fd, TCSAFLUSH, &term ) < 0)
{
perror("P2OS::Setup():tcsetattr():");
close(this->psos_fd);
this->psos_fd = -1;
return(1);
}
if(tcflush(this->psos_fd, TCIOFLUSH ) < 0)
{
perror("P2OS::Setup():tcflush():");
close(this->psos_fd);
this->psos_fd = -1;
return(1);
}
#endif
if((flags = fcntl(this->psos_fd, F_GETFL)) < 0)
{
perror("P2OS::Setup():fcntl()");
close(this->psos_fd);
this->psos_fd = -1;
return(1);
}
// radio modem initialization code, courtesy of Kim Jinsuck
// <jinsuckk@cs.tamu.edu>
if(this->radio_modemp)
{
puts("Initializing radio modem...");
int ret = write(this->psos_fd, "WMS2\r", 5);
if (ret < 5)
{
PLAYER_ERROR1("P2OS: Write failed to complete (%d)",ret);
return 1;
}
usleep(50000);
char modem_buf[50];
int buf_len = read(this->psos_fd, modem_buf, 5); // get "WMS2"
modem_buf[buf_len]='\0';
printf("wireless modem response = %s\n", modem_buf);
usleep(10000);
// get "\n\rConnecting..." --> \n\r is my guess
buf_len = read(this->psos_fd, modem_buf, 14);
modem_buf[buf_len]='\0';
printf("wireless modem response = %s\n", modem_buf);
// wait until get "Connected to address 2"
int modem_connect_try = 10;
while(strstr(modem_buf, "ected to addres") == NULL)
{
puts("Initializing radio modem...");
int ret = write(this->psos_fd, "WMS2\r", 5);
if (ret < 5)
{
PLAYER_ERROR1("P2OS: Failed to write full packet to modem (%d)", ret);
return 1;
}
usleep(50000);
char modem_buf[50];
int buf_len = read(this->psos_fd, modem_buf, 5); // get "WMS2"
modem_buf[buf_len]='\0';
printf("wireless modem response = %s\n", modem_buf);
// if "Partner busy!"
if(modem_buf[2] == 'P')
{
printf("Please reset partner modem and try again\n");
return(1);
}
// if "\n\rPartner not found!"
if(modem_buf[0] == 'P')
{
printf("Please check partner modem and try again\n");
return(1);
}
if(modem_connect_try-- == 0)
{
usleep(300000);
buf_len = read(this->psos_fd, modem_buf, 40);
modem_buf[buf_len]='\0';
printf("wireless modem response = %s\n", modem_buf);
// if "Partner busy!"
if(modem_buf[2] == 'P')
{
printf("Please reset partner modem and try again\n");
return(1);
}
// if "\n\rPartner not found!"
if(modem_buf[0] == 'P')
{
printf("Please check partner modem and try again\n");
return(1);
}
if(modem_connect_try-- == 0)
{
puts("Failed to connect radio modem, Trying direct connection...");
break;
}
}
}
}
printf("Connected to robot device, handshaking with P2OS...");
fflush(stdout);
}// end TCP socket or serial port.
// Sync:
int num_sync_attempts = 3;
while(psos_state != READY)
{
switch(psos_state)
{
case NO_SYNC:
command = SYNC0;
packet.Build(&command, 1);
packet.Send(this->psos_fd);
usleep(P2OS_CYCLETIME_USEC);
break;
case AFTER_FIRST_SYNC:
printf("turning off NONBLOCK mode...\n");
if(fcntl(this->psos_fd, F_SETFL, flags ^ O_NONBLOCK) < 0)
{
perror("P2OS::Setup():fcntl()");
close(this->psos_fd);
this->psos_fd = -1;
return(1);
}
command = SYNC1;
packet.Build(&command, 1);
packet.Send(this->psos_fd);
break;
case AFTER_SECOND_SYNC:
command = SYNC2;
packet.Build(&command, 1);
packet.Send(this->psos_fd);
break;
default:
puts("P2OS::Setup():shouldn't be here...");
break;
}
usleep(P2OS_CYCLETIME_USEC);
if(receivedpacket.Receive(this->psos_fd, this->ignore_checksum))
{
if((psos_state == NO_SYNC) && (num_sync_attempts >= 0))
{
num_sync_attempts--;
usleep(P2OS_CYCLETIME_USEC);
continue;
}
else
{
// couldn't connect; try different speed.
if(++currbaud < numbauds)
{
cfsetispeed(&term, bauds[currbaud]);
cfsetospeed(&term, bauds[currbaud]);
if( tcsetattr(this->psos_fd, TCSAFLUSH, &term ) < 0 )
{
perror("P2OS::Setup():tcsetattr():");
close(this->psos_fd);
this->psos_fd = -1;
return(1);
}
if(tcflush(this->psos_fd, TCIOFLUSH ) < 0 )
{
perror("P2OS::Setup():tcflush():");
close(this->psos_fd);
this->psos_fd = -1;
return(1);
}
num_sync_attempts = 3;
continue;
}
else
{
// tried all speeds; bail
break;
}
}
}
switch(receivedpacket.packet[3])
{
case SYNC0:
psos_state = AFTER_FIRST_SYNC;
break;
case SYNC1:
psos_state = AFTER_SECOND_SYNC;
break;
case SYNC2:
psos_state = READY;
break;
default:
// maybe P2OS is still running from last time. let's try to CLOSE
// and reconnect
if(!sent_close)
{
//puts("sending CLOSE");
command = CLOSE;
packet.Build( &command, 1);
packet.Send(this->psos_fd);
sent_close = true;
usleep(2*P2OS_CYCLETIME_USEC);
tcflush(this->psos_fd,TCIFLUSH);
psos_state = NO_SYNC;
}
break;
}
usleep(P2OS_CYCLETIME_USEC);
}
if(psos_state != READY)
{
printf("Couldn't synchronize with P2OS.\n"
" Most likely because the robot is not connected %s %s\n",
this->psos_use_tcp ? "to the ethernet-serial bridge device " : "to the serial port",
this->psos_use_tcp ? this->psos_tcp_host : this->psos_serial_port);
close(this->psos_fd);
this->psos_fd = -1;
return(1);
}
cnt = 4;
cnt += snprintf(name, sizeof(name), "%s", &receivedpacket.packet[cnt]);
cnt++;
cnt += snprintf(type, sizeof(type), "%s", &receivedpacket.packet[cnt]);
cnt++;
cnt += snprintf(subtype, sizeof(subtype), "%s", &receivedpacket.packet[cnt]);
cnt++;
command = OPEN;
packet.Build(&command, 1);
packet.Send(this->psos_fd);
usleep(P2OS_CYCLETIME_USEC);
command = PULSE;
packet.Build(&command, 1);
packet.Send(this->psos_fd);
usleep(P2OS_CYCLETIME_USEC);
printf("Done.\n Connected to %s, a %s %s\n", name, type, subtype);
// now, based on robot type, find the right set of parameters
for(i=0;i<PLAYER_NUM_ROBOT_TYPES;i++)
{
if(!strcasecmp(PlayerRobotParams[i].Class,type) &&
!strcasecmp(PlayerRobotParams[i].Subclass,subtype))
{
param_idx = i;
break;
}
}
if(i == PLAYER_NUM_ROBOT_TYPES)
{
fputs("P2OS: Warning: couldn't find parameters for this robot; "
"using defaults\n",stderr);
param_idx = 0;
}
// first, receive a packet so we know we're connected.
if(!this->sippacket)
this->sippacket = new SIP(param_idx);
this->sippacket->x_offset = 0;
this->sippacket->y_offset = 0;
this->sippacket->angle_offset = 0;
SendReceive((P2OSPacket*)NULL,false);
// turn off the sonars at first
this->ToggleSonarPower(0);
if(this->joystickp)
{
// enable joystick control
P2OSPacket js_packet;
unsigned char js_command[4];
js_command[0] = JOYDRIVE;
js_command[1] = ARGINT;
js_command[2] = 1;
js_command[3] = 0;
js_packet.Build(js_command, 4);
this->SendReceive(&js_packet,false);
}
if(this->blobfinder_id.interf)
CMUcamReset(false);
if(this->gyro_id.interf)
{
// request that gyro data be sent each cycle
P2OSPacket gyro_packet;
unsigned char gyro_command[4];
gyro_command[0] = GYRO;
gyro_command[1] = ARGINT;
gyro_command[2] = 1;
gyro_command[3] = 0;
gyro_packet.Build(gyro_command, 4);
this->SendReceive(&gyro_packet,false);
}
if (this->actarray_id.interf)
{
// Start a continuous stream of ARMpac packets
P2OSPacket aaPacket;
unsigned char aaCmd[4];
aaCmd[0] = ARM_STATUS;
aaCmd[1] = ARGINT;
aaCmd[2] = 2;
aaCmd[3] = 0;
aaPacket.Build (aaCmd, 4);
SendReceive (&aaPacket,false);
// Ask for an ARMINFOpac packet too
aaCmd[0] = ARM_INFO;
aaPacket.Build (aaCmd, 1);
SendReceive (&aaPacket,false);
}
// if requested, set max accel/decel limits
P2OSPacket accel_packet;
unsigned char accel_command[4];
if(this->motor_max_trans_accel > 0)
{
accel_command[0] = SETA;
accel_command[1] = ARGINT;
accel_command[2] = this->motor_max_trans_accel & 0x00FF;
accel_command[3] = (this->motor_max_trans_accel & 0xFF00) >> 8;
accel_packet.Build(accel_command, 4);
this->SendReceive(&accel_packet,false);
}
if(this->motor_max_trans_decel < 0)
{
accel_command[0] = SETA;
accel_command[1] = ARGNINT;
accel_command[2] = abs(this->motor_max_trans_decel) & 0x00FF;
accel_command[3] = (abs(this->motor_max_trans_decel) & 0xFF00) >> 8;
accel_packet.Build(accel_command, 4);
this->SendReceive(&accel_packet,false);
}
if(this->motor_max_rot_accel > 0)
{
accel_command[0] = SETRA;
accel_command[1] = ARGINT;
accel_command[2] = this->motor_max_rot_accel & 0x00FF;
accel_command[3] = (this->motor_max_rot_accel & 0xFF00) >> 8;
accel_packet.Build(accel_command, 4);
this->SendReceive(&accel_packet,false);
}
if(this->motor_max_rot_decel < 0)
{
accel_command[0] = SETRA;
accel_command[1] = ARGNINT;
accel_command[2] = abs(this->motor_max_rot_decel) & 0x00FF;
accel_command[3] = (abs(this->motor_max_rot_decel) & 0xFF00) >> 8;
accel_packet.Build(accel_command, 4);
this->SendReceive(&accel_packet,false);
}
// if requested, change PID settings
P2OSPacket pid_packet;
unsigned char pid_command[4];
if(this->rot_kp >= 0)
{
pid_command[0] = ROTKP;
pid_command[1] = ARGINT;
pid_command[2] = this->rot_kp & 0x00FF;
pid_command[3] = (this->rot_kp & 0xFF00) >> 8;
pid_packet.Build(pid_command, 4);
this->SendReceive(&pid_packet);
}
if(this->rot_kv >= 0)
{
pid_command[0] = ROTKV;
pid_command[1] = ARGINT;
pid_command[2] = this->rot_kv & 0x00FF;
pid_command[3] = (this->rot_kv & 0xFF00) >> 8;
pid_packet.Build(pid_command, 4);
this->SendReceive(&pid_packet);
}
if(this->rot_ki >= 0)
{
pid_command[0] = ROTKI;
pid_command[1] = ARGINT;
pid_command[2] = this->rot_ki & 0x00FF;
pid_command[3] = (this->rot_ki & 0xFF00) >> 8;
pid_packet.Build(pid_command, 4);
this->SendReceive(&pid_packet);
}
if(this->trans_kp >= 0)
{
pid_command[0] = TRANSKP;
pid_command[1] = ARGINT;
pid_command[2] = this->trans_kp & 0x00FF;
pid_command[3] = (this->trans_kp & 0xFF00) >> 8;
pid_packet.Build(pid_command, 4);
this->SendReceive(&pid_packet);
}
if(this->trans_kv >= 0)
{
pid_command[0] = TRANSKV;
pid_command[1] = ARGINT;
pid_command[2] = this->trans_kv & 0x00FF;
pid_command[3] = (this->trans_kv & 0xFF00) >> 8;
pid_packet.Build(pid_command, 4);
this->SendReceive(&pid_packet);
}
if(this->trans_ki >= 0)
{
pid_command[0] = TRANSKI;
pid_command[1] = ARGINT;
pid_command[2] = this->trans_ki & 0x00FF;
pid_command[3] = (this->trans_ki & 0xFF00) >> 8;
pid_packet.Build(pid_command, 4);
this->SendReceive(&pid_packet);
}
// if requested, change bumper-stall behavior
// 0 = don't stall
// 1 = stall on front bumper contact
// 2 = stall on rear bumper contact
// 3 = stall on either bumper contact
if(this->bumpstall >= 0)
{
if(this->bumpstall > 3)
PLAYER_ERROR1("ignoring bumpstall value %d; should be 0, 1, 2, or 3",
this->bumpstall);
else
{
PLAYER_MSG1(1, "setting bumpstall to %d", this->bumpstall);
P2OSPacket bumpstall_packet;;
unsigned char bumpstall_command[4];
bumpstall_command[0] = BUMP_STALL;
bumpstall_command[1] = ARGINT;
bumpstall_command[2] = (unsigned char)this->bumpstall;
bumpstall_command[3] = 0;
bumpstall_packet.Build(bumpstall_command, 4);
this->SendReceive(&bumpstall_packet,false);
}
}
// Set up the PTZ Camera
if(this->ptz_id.interf){
SetupPtz();
}
// TODO: figure out what the right behavior here is
#if 0
// zero position command buffer
player_position_cmd_t zero;
memset(&zero,0,sizeof(player_position_cmd_t));
this->PutCommand(this->position_id,(void*)&zero,
sizeof(player_position_cmd_t),NULL);
#endif
return(0);
}
void P2OS::MainQuit()
{
unsigned char command[20],buffer[20];
P2OSPacket packet;
memset(buffer,0,20);
if(this->psos_fd == -1)
return;
// Shut Down the PTZ camera
if(this->ptz_id.interf){
usleep(PTZ_SLEEP_TIME_USEC);
SendAbsPanTilt(0,0);
usleep(PTZ_SLEEP_TIME_USEC);
SendAbsZoom(0);
setPower(0);
puts("PTZ camera has been shutdown");
}
command[0] = STOP;
packet.Build(command, 1);
packet.Send(this->psos_fd);
usleep(P2OS_CYCLETIME_USEC);
command[0] = CLOSE;
packet.Build(command, 1);
packet.Send(this->psos_fd);
usleep(P2OS_CYCLETIME_USEC);
close(this->psos_fd);
this->psos_fd = -1;
puts("P2OS has been shutdown");
delete this->sippacket;
this->sippacket = NULL;
}
P2OS::~P2OS (void)
{
player_position2d_data_t_cleanup(&p2os_data.position);
player_sonar_data_t_cleanup (&p2os_data.sonar);
player_gripper_data_t_cleanup (&p2os_data.gripper);
player_gripper_data_t_cleanup (&p2os_data.armGripper);
player_power_data_t_cleanup (&p2os_data.power);
player_bumper_data_t_cleanup (&p2os_data.bumper);
player_dio_data_t_cleanup (&p2os_data.dio);
player_aio_data_t_cleanup (&p2os_data.aio);
player_blobfinder_data_t_cleanup (&p2os_data.blobfinder);
player_position2d_data_t_cleanup (&p2os_data.compass);
player_position2d_data_t_cleanup (&p2os_data.gyro);
player_actarray_data_t_cleanup (&p2os_data.lift);
player_actarray_data_t_cleanup (&p2os_data.actArray);
if (kineCalc)
{
delete kineCalc;
kineCalc = NULL;
}
}
int
P2OS::Subscribe(player_devaddr_t id)
{
int setupResult;
// do the subscription
if((setupResult = Driver::Subscribe(id)) == 0)
{
// also increment the appropriate subscription counter
if(Device::MatchDeviceAddress(id, this->position_id))
this->position_subscriptions++;
else if(Device::MatchDeviceAddress(id, this->sonar_id))
this->sonar_subscriptions++;
else if(Device::MatchDeviceAddress(id, this->actarray_id) ||
Device::MatchDeviceAddress(id, this->limb_id) ||
Device::MatchDeviceAddress(id, this->armgripper_id))
// We use the actarray subscriptions count for the limb and arm gripper
// interfaces too since they're the same physical hardware
this->actarray_subscriptions++;
}
return(setupResult);
}
int
P2OS::Unsubscribe(player_devaddr_t id)
{
int shutdownResult;
// do the unsubscription
if((shutdownResult = Driver::Unsubscribe(id)) == 0)
{
// also decrement the appropriate subscription counter
if(Device::MatchDeviceAddress(id, this->position_id))
{
this->position_subscriptions--;
assert(this->position_subscriptions >= 0);
}
else if(Device::MatchDeviceAddress(id, this->sonar_id))
{
this->sonar_subscriptions--;
assert(this->sonar_subscriptions >= 0);
}
else if(Device::MatchDeviceAddress(id, this->actarray_id) ||
Device::MatchDeviceAddress(id, this->limb_id) ||
Device::MatchDeviceAddress(id, this->armgripper_id))
{
// We use the actarray subscriptions count for the limb
// interface too since they're the same physical hardware
this->actarray_subscriptions--;
assert(this->actarray_subscriptions >= 0);
}
}
return(shutdownResult);
}
void
P2OS::StandardSIPPutData(double timestampStandardSIP)
{
// put odometry data
this->Publish(this->position_id,
PLAYER_MSGTYPE_DATA,
PLAYER_POSITION2D_DATA_STATE,
(void*)&(this->p2os_data.position),
sizeof(player_position2d_data_t),
×tampStandardSIP);
// put sonar data
this->Publish(this->sonar_id,
PLAYER_MSGTYPE_DATA,
PLAYER_SONAR_DATA_RANGES,
(void*)&(this->p2os_data.sonar),
sizeof(player_sonar_data_t),
×tampStandardSIP);
delete this->p2os_data.sonar.ranges;
// put aio data
this->Publish(this->aio_id,
PLAYER_MSGTYPE_DATA,
PLAYER_AIO_DATA_STATE,
(void*)&(this->p2os_data.aio),
sizeof(player_aio_data_t),
×tampStandardSIP);
// put dio data
this->Publish(this->dio_id,
PLAYER_MSGTYPE_DATA,
PLAYER_DIO_DATA_VALUES,
(void*)&(this->p2os_data.dio),
sizeof(player_dio_data_t),
×tampStandardSIP);
// put gripper data
this->Publish(this->gripper_id,
PLAYER_MSGTYPE_DATA,
PLAYER_GRIPPER_DATA_STATE,
(void*)&(this->p2os_data.gripper),
sizeof(player_gripper_data_t),
×tampStandardSIP);
// put lift data
this->Publish(this->lift_id,
PLAYER_MSGTYPE_DATA,
PLAYER_ACTARRAY_DATA_STATE,
(void*)&(this->p2os_data.lift),
sizeof(player_actarray_data_t),
×tampStandardSIP);
// put bumper data
this->Publish(this->bumper_id,
PLAYER_MSGTYPE_DATA,
PLAYER_BUMPER_DATA_STATE,
(void*)&(this->p2os_data.bumper),
sizeof(player_bumper_data_t),
×tampStandardSIP);
// put power data
this->Publish(this->power_id,
PLAYER_MSGTYPE_DATA,
PLAYER_POWER_DATA_STATE,
(void*)&(this->p2os_data.power),
sizeof(player_power_data_t),
×tampStandardSIP);
// put compass data
this->Publish(this->compass_id,
PLAYER_MSGTYPE_DATA,
PLAYER_POSITION2D_DATA_STATE,
(void*)&(this->p2os_data.compass),
sizeof(player_position2d_data_t),
×tampStandardSIP);
// put PTZ data
this->Publish(this->ptz_id,
PLAYER_MSGTYPE_DATA,
PLAYER_PTZ_DATA_STATE,
(void*)&(this->ptz_data));
}
void
P2OS::GyroPutData(double timestampGyro)
{
// put gyro data
this->Publish(this->gyro_id,
PLAYER_MSGTYPE_DATA,
PLAYER_POSITION2D_DATA_STATE,
(void*)&(this->p2os_data.gyro),
sizeof(player_position2d_data_t),
×tampGyro);
}
void
P2OS::BlobfinderPutData(double timestampSERAUX)
{
// put blobfinder data
this->Publish(this->blobfinder_id,
PLAYER_MSGTYPE_DATA,
PLAYER_BLOBFINDER_DATA_BLOBS,
(void*)&(this->p2os_data.blobfinder),
sizeof(player_blobfinder_data_t),
×tampSERAUX);
}
void
P2OS::ActarrayPutData(double timestampArm)
{
// put actarray data
this->Publish(this->actarray_id,
PLAYER_MSGTYPE_DATA,
PLAYER_ACTARRAY_DATA_STATE,
(void*)&(this->p2os_data.actArray),
sizeof(player_actarray_data_t),
×tampArm);
delete[] this->p2os_data.actArray.actuators;
// put limb data
this->Publish(this->limb_id,
PLAYER_MSGTYPE_DATA,
PLAYER_LIMB_DATA_STATE,
(void*)&(this->limb_data),
sizeof(player_limb_data_t),
×tampArm);
// put arm gripper data
this->Publish(this->armgripper_id,
PLAYER_MSGTYPE_DATA,
PLAYER_GRIPPER_DATA_STATE,
(void*)&(this->p2os_data.armGripper),
sizeof(player_gripper_data_t),
×tampArm);
}
void
P2OS::Main()
{
int last_sonar_subscrcount=0;
int last_position_subscrcount=0;
int last_actarray_subscrcount=0;
double currentTime;
struct timeval timeVal;
for(;;)
{
pthread_testcancel();
// we want to turn on the sonars if someone just subscribed, and turn
// them off if the last subscriber just unsubscribed.
if(!last_sonar_subscrcount && this->sonar_subscriptions)
this->ToggleSonarPower(1);
else if(last_sonar_subscrcount && !(this->sonar_subscriptions))
this->ToggleSonarPower(0);
last_sonar_subscrcount = this->sonar_subscriptions;
// Same for the actarray - this will also turn it on and off with limb subscriptions
if(!last_actarray_subscrcount && this->actarray_subscriptions)
this->ToggleActArrayPower(1, false);
else if(last_actarray_subscrcount && !(this->actarray_subscriptions))
this->ToggleActArrayPower(0, false);
last_actarray_subscrcount = this->actarray_subscriptions;
// we want to reset the odometry and enable the motors if the first
// client just subscribed to the position device, and we want to stop
// and disable the motors if the last client unsubscribed.
if(!last_position_subscrcount && this->position_subscriptions)
{
this->ToggleMotorPower(0);
this->ResetRawPositions();
}
else if(last_position_subscrcount && !(this->position_subscriptions))
{
// enable motor power
this->ToggleMotorPower(1);
}
last_position_subscrcount = this->position_subscriptions;
// The Amigo board seems to drop commands once in a while. This is
// a hack to restart the serial reads if that happens.
if(this->blobfinder_id.interf)
{
struct timeval now_tv;
GlobalTime->GetTime(&now_tv);
if (now_tv.tv_sec > lastblob_tv.tv_sec)
{
P2OSPacket cam_packet;
unsigned char cam_command[4];
cam_command[0] = GETAUX2;
cam_command[1] = ARGINT;
cam_command[2] = 0;
cam_command[3] = 0;
cam_packet.Build(cam_command, 4);
SendReceive(&cam_packet);
cam_command[0] = GETAUX2;
cam_command[1] = ARGINT;
cam_command[2] = CMUCAM_MESSAGE_LEN * 2 -1;
cam_command[3] = 0;
cam_packet.Build(cam_command, 4);
SendReceive(&cam_packet);
GlobalTime->GetTime(&lastblob_tv); // Reset last blob packet time
}
}
if(this->ptz_id.interf)
{
int pan,tilt;
int zoom;
//fprintf(stderr, "PTZ MAIN LOOP\n");
//fprintf(stderr, "Getting Pan/Tilt Data\n");
if(GetAbsPanTilt(&pan,&tilt) < 0)
{
fputs("canonvcc4:Main():GetAbsPanTilt() errored. bailing.\n",
stderr);
pthread_exit(NULL);
}
usleep(30000);
//fprintf(stderr, "Getting Zoom Data\n");
zoom = 0;
if(GetAbsZoom(&zoom) < 0)
{
fputs("canonvcc4:Main():GetAbsZoom() errored. bailing.\n", stderr);
pthread_exit(NULL);
}
// Do the necessary coordinate conversions. Camera's natural pan
// coordinates increase clockwise; we want them the other way, so
// we negate pan here. Zoom values are converted from arbitrary
// units to a field of view (in degrees).
pan = -pan;
//printf("before zoom = %i\n", zoom);
//zoom = this->maxfov + (zoom * (this->maxfov - this->minfov)) / maxzoom;
//printf("after zoom = %i\n", zoom);
ptz_data.pan = DTOR((unsigned short)pan);
ptz_data.tilt = DTOR((unsigned short)tilt);
//double m = (double)(this->minfov - this->maxfov) / (double)this->maxzoom;
ptz_data.zoom = DTOR(this->maxfov+(zoom * (double)(this->minfov - this->maxfov) / (double)this->maxzoom));
}
// handle pending messages
if(!this->InQueue->Empty())
{
ProcessMessages();
}
// Check if need to send a pulse to the robot
if (this->pulse != -1)
{
gettimeofday (&timeVal, NULL);
currentTime = static_cast<double> (timeVal.tv_sec) + (static_cast<double> (timeVal.tv_usec) / 1e6);
if ((currentTime - lastPulseTime) > this->pulse)
{
SendPulse ();
// Update the time of last pulse/command
lastPulseTime = currentTime;
}
}
// Hack fix to get around the fact that if no commands are sent to the robot via SendReceive,
// the driver will never read SIP packets and so never send data back to clients.
// We need a better way of doing regular checks of the serial port - peek in sendreceive, maybe?
// Because if there is no data waiting this will sit around waiting until one comes
SendReceive (NULL, true);
}
}
/* send the packet, then receive and parse an SIP */
int
P2OS::SendReceive(P2OSPacket* pkt, bool publish_data)
{
P2OSPacket packet;
// zero the combined data buffer. it will be filled with the latest data
// by corresponding SIP::Fill*()
memset(&(this->p2os_data),0,sizeof(player_p2os_data_t));
if((this->psos_fd >= 0) && this->sippacket)
{
if(pkt)
pkt->Send(this->psos_fd);
/* receive a packet */
pthread_testcancel();
if(packet.Receive(this->psos_fd, this->ignore_checksum))
{
puts("RunPsosThread(): Receive errored");
pthread_exit(NULL);
}
if(packet.packet[0] == 0xFA && packet.packet[1] == 0xFB &&
(packet.packet[3] == 0x30 || packet.packet[3] == 0x31 ||
packet.packet[3] == 0x32 || packet.packet[3] == 0x33 ||
packet.packet[3] == 0x34))
{
/* It is a server packet, so process it */
this->sippacket->ParseStandard( &packet.packet[3] );
this->sippacket->FillStandard(&(this->p2os_data));
if(publish_data)
this->StandardSIPPutData(packet.timestamp);
}
else if(packet.packet[0] == 0xFA && packet.packet[1] == 0xFB &&
packet.packet[3] == SERAUX)
{
// This is an AUX serial packet
if(ptz_id.interf)
{
/* It is an extended SIP (ptz) packet, so process it */
/* Be sure to pass data size too (packet[2])! */
//fprintf(stderr,"Got a PTZ packet\n");
int len;
//printf("Got ptz packet\n");
len = packet.packet[2] - 3;
//packet.PrintHex();
//fprintf(stderr, "Got PTZ Packet of length %i\n",len);
if ( cb.gotPacket() ){
fprintf(stderr, "ptz_error: got a message, but we already have the complete packet.\n");
}
else {
for ( int i = 4; i < 4+len ; i++ )
{
cb.putOnBuf(packet.packet[i]);
}
}
}
}
else if(packet.packet[0] == 0xFA && packet.packet[1] == 0xFB &&
packet.packet[3] == SERAUX2)
{
// This is an AUX2 serial packet
if(blobfinder_id.interf)
{
/* It is an extended SIP (blobfinder) packet, so process it */
/* Be sure to pass data size too (packet[2])! */
this->sippacket->ParseSERAUX( &packet.packet[2] );
this->sippacket->FillSERAUX(&(this->p2os_data));
if(publish_data)
this->BlobfinderPutData(packet.timestamp);
P2OSPacket cam_packet;
unsigned char cam_command[4];
/* We cant get the entire contents of the buffer,
** and we cant just have P2OS send us the buffer on a regular basis.
** My solution is to flush the buffer and then request exactly
** CMUCAM_MESSAGE_LEN * 2 -1 bytes of data. This ensures that
** we will get exactly one full message, and it will be "current"
** within the last 2 messages. Downside is that we end up pitching
** every other CMUCAM message. Tradeoffs... */
// Flush
cam_command[0] = GETAUX2;
cam_command[1] = ARGINT;
cam_command[2] = 0;
cam_command[3] = 0;
cam_packet.Build(cam_command, 4);
this->SendReceive(&cam_packet,publish_data);
// Reqest next packet
cam_command[0] = GETAUX2;
cam_command[1] = ARGINT;
// Guarantee exactly 1 full message
cam_command[2] = CMUCAM_MESSAGE_LEN * 2 -1;
cam_command[3] = 0;
cam_packet.Build(cam_command, 4);
this->SendReceive(&cam_packet,publish_data);
GlobalTime->GetTime(&lastblob_tv); // Reset last blob packet time
}
}
else if(packet.packet[0] == 0xFA && packet.packet[1] == 0xFB &&
(packet.packet[3] == 0x50 || packet.packet[3] == 0x80 ||
// packet.packet[3] == 0xB0 || packet.packet[3] == 0xC0 ||
packet.packet[3] == 0xC0 ||
packet.packet[3] == 0xD0 || packet.packet[3] == 0xE0))
{
/* It is a vision packet from the old Cognachrome system*/
/* we don't understand these yet, so ignore */
}
else if(packet.packet[0] == 0xFA && packet.packet[1] == 0xFB &&
packet.packet[3] == GYROPAC)
{
if(this->gyro_id.interf)
{
/* It's a set of gyro measurements */
this->sippacket->ParseGyro(&packet.packet[2]);
this->sippacket->FillGyro(&(this->p2os_data));
if(publish_data)
this->GyroPutData(packet.timestamp);
/* Now, the manual says that we get one gyro packet each cycle,
* right before the standard SIP. So, we'll call SendReceive()
* again (with no packet to send) to get the standard SIP. There's
* a definite danger of infinite recursion here if the manual
* is wrong.
*/
this->SendReceive(NULL,publish_data);
}
}
else if(packet.packet[0] == 0xFA && packet.packet[1] == 0xFB &&
(packet.packet[3] == 0x20))
{
//printf("got a CONFIGpac:%d\n",packet.size);
}
else if (packet.packet[0] == 0xFA && packet.packet[1] == 0xFB && packet.packet[3] == ARMPAC)
{
if (actarray_id.interf)
{
// ARMpac - current arm status
double joints[6];
sippacket->ParseArm (&packet.packet[2]);
for (int ii = 0; ii < 6; ii++)
{
sippacket->armJointPosRads[ii] = TicksToRadians (ii, sippacket->armJointPos[ii]);
joints[ii] = sippacket->armJointPosRads[ii];
}
sippacket->FillArm(&p2os_data);
if(kineCalc)
{
kineCalc->CalculateFK (joints);
limb_data.position.px = kineCalc->GetP ().x + armOffsetX;
limb_data.position.py = kineCalc->GetP ().y + armOffsetY;
limb_data.position.pz = kineCalc->GetP ().z + armOffsetZ;
limb_data.approach.px = kineCalc->GetA ().x;
limb_data.approach.py = kineCalc->GetA ().y;
limb_data.approach.pz = kineCalc->GetA ().z;
limb_data.orientation.px = kineCalc->GetO ().x;
limb_data.orientation.py = kineCalc->GetO ().y;
limb_data.orientation.pz = kineCalc->GetO ().z;
if (limb_data.state != PLAYER_LIMB_STATE_OOR && limb_data.state != PLAYER_LIMB_STATE_COLL)
{
if (sippacket->armJointMoving[0] || sippacket->armJointMoving[1] || sippacket->armJointMoving[2] ||
sippacket->armJointMoving[3] || sippacket->armJointMoving[4])
{
limb_data.state = PLAYER_LIMB_STATE_MOVING;
}
else
limb_data.state = PLAYER_LIMB_STATE_IDLE;
}
}
if(publish_data)
this->ActarrayPutData(packet.timestamp);
}
// Go for another SIP - there had better be one or things will probably go boom
SendReceive(NULL,publish_data);
}
else if (packet.packet[0] == 0xFA && packet.packet[1] == 0xFB && packet.packet[3] == ARMINFOPAC)
{
// ARMINFOpac - arm configuration stuff
if (actarray_id.interf)
{
sippacket->ParseArmInfo (&packet.packet[2]);
// Update the KineCalc with the new info for joints - one would assume this doesn't change, though...
if (kineCalc)
{
for (int ii = 0; ii < 5; ii++)
kineCalc->SetJointRange (ii, TicksToRadians (ii, sippacket->armJoints[ii].min), TicksToRadians (ii, sippacket->armJoints[ii].max));
// Go for another SIP - there had better be one or things will probably go boom
}
SendReceive(NULL,publish_data);
}
}
else
{
packet.PrintHex();
}
}
return(0);
}
void
P2OS::ResetRawPositions()
{
P2OSPacket pkt;
unsigned char p2oscommand[4];
if(this->sippacket)
{
this->sippacket->rawxpos = 0;
this->sippacket->rawypos = 0;
this->sippacket->xpos = 0;
this->sippacket->ypos = 0;
p2oscommand[0] = SETO;
p2oscommand[1] = ARGINT;
pkt.Build(p2oscommand, 2);
this->SendReceive(&pkt,false);
}
}
/****************************************************************
** Reset the CMUcam. This includes flushing the buffer and
** setting interface output mode to raw. It also restarts
** tracking output (current mode)
****************************************************************/
void P2OS::CMUcamReset(bool doLock)
{
CMUcamStopTracking(doLock); // Stop the current tracking.
P2OSPacket cam_packet;
unsigned char cam_command[10];
printf("Resetting the CMUcam...\n");
cam_command[0] = TTY3;
cam_command[1] = ARGSTR;
strncpy((char*)&cam_command[3], "RS\r",4);
cam_command[2] = strlen((char *)&cam_command[3]);
cam_packet.Build(cam_command, (int)cam_command[2]+3);
this->SendReceive(&cam_packet,doLock);
// Set for raw output + no ACK/NACK
printf("Setting raw mode...\n");
cam_command[0] = TTY3;
cam_command[1] = ARGSTR;
strncpy((char*)&cam_command[3], "RM 3\r",6);
cam_command[2] = strlen((char *)&cam_command[3]);
cam_packet.Build(cam_command, (int)cam_command[2]+3);
this->SendReceive(&cam_packet,doLock);
usleep(100000);
printf("Flushing serial buffer...\n");
cam_command[0] = GETAUX2;
cam_command[1] = ARGINT;
cam_command[2] = 0;
cam_command[3] = 0;
cam_packet.Build(cam_command, 4);
this->SendReceive(&cam_packet,doLock);
sleep(1);
// (Re)start tracking
this->CMUcamStartTracking(false);
}
/****************************************************************
** Start CMUcam blob tracking. This method can be called 3 ways:
** 1) with a set of 6 color arguments (RGB min and max)
** 2) with auto tracking (-1 argument)
** 3) with current values (0 or no arguments)
****************************************************************/
void P2OS::CMUcamTrack(int rmin, int rmax,
int gmin, int gmax,
int bmin, int bmax)
{
this->CMUcamStopTracking(); // Stop the current tracking.
P2OSPacket cam_packet;
unsigned char cam_command[50];
if (!rmin && !rmax && !gmin && !gmax && !bmin && !bmax)
{
CMUcamStartTracking();
}
else if (rmin<0 || rmax<0 || gmin<0 || gmax<0 || bmin<0 || bmax<0)
{
printf("Activating CMUcam color tracking (AUTO-mode)...\n");
cam_command[0] = TTY3;
cam_command[1] = ARGSTR;
strncpy((char*)&cam_command[3], "TW\r",4);
cam_command[2] = strlen((char *)&cam_command[3]);
cam_packet.Build(cam_command, (int)cam_command[2]+3);
this->SendReceive(&cam_packet);
}
else
{
printf("Activating CMUcam color tracking (MANUAL-mode)...\n");
//printf(" RED: %d %d GREEN: %d %d BLUE: %d %d\n",
// rmin, rmax, gmin, gmax, bmin, bmax);
cam_command[0] = TTY3;
cam_command[1] = ARGSTR;
snprintf((char*)&cam_command[3], sizeof(cam_command) - 3, "TC %d %d %d %d %d %d\r",
rmin, rmax, gmin, gmax, bmin, bmax);
cam_command[2] = strlen((char *)&cam_command[3]);
cam_packet.Build(cam_command, (int)cam_command[2]+3);
this->SendReceive(&cam_packet);
}
cam_command[0] = GETAUX2;
cam_command[1] = ARGINT;
cam_command[2] = CMUCAM_MESSAGE_LEN * 2 -1; // Guarantee 1 full message
cam_command[3] = 0;
cam_packet.Build(cam_command, 4);
this->SendReceive(&cam_packet);
}
/****************************************************************
** Start Tracking - with last config
****************************************************************/
void P2OS::CMUcamStartTracking(bool doLock)
{
P2OSPacket cam_packet;
unsigned char cam_command[50];
// Then start it up with current values.
cam_command[0] = TTY3;
cam_command[1] = ARGSTR;
strncpy((char*)&cam_command[3], "TC\r", 4);
cam_command[2] = strlen((char *)&cam_command[3]);
cam_packet.Build(cam_command, (int)cam_command[2]+3);
this->SendReceive(&cam_packet,false);
}
/****************************************************************
** Stop Tracking - This should be done before any new command
** are issued to the CMUcam.
****************************************************************/
void P2OS::CMUcamStopTracking(bool doLock)
{
P2OSPacket cam_packet;
unsigned char cam_command[50];
// First we must STOP tracking. Just send a return.
cam_command[0] = TTY3;
cam_command[1] = ARGSTR;
strncpy((char*)&cam_command[3], "\r", 2);
cam_command[2] = strlen((char *)&cam_command[3]);
cam_packet.Build(cam_command, (int)cam_command[2]+3);
this->SendReceive(&cam_packet,doLock);
}
/* toggle sonars on/off, according to val */
void
P2OS::ToggleSonarPower(unsigned char val)
{
unsigned char command[4];
P2OSPacket packet;
command[0] = SONAR;
command[1] = ARGINT;
command[2] = val;
command[3] = 0;
packet.Build(command, 4);
SendReceive(&packet,false);
}
/* toggle motors on/off, according to val */
void
P2OS::ToggleMotorPower(unsigned char val)
{
unsigned char command[4];
P2OSPacket packet;
command[0] = ENABLE;
command[1] = ARGINT;
command[2] = val;
command[3] = 0;
packet.Build(command, 4);
SendReceive(&packet,false);
}
/////////////////////////////////////////////////////
// Actarray stuff
/////////////////////////////////////////////////////
// Ticks to degrees from the ARIA software
inline double P2OS::TicksToDegrees (int joint, unsigned char ticks)
{
if ((joint < 0) || (joint >= sippacket->armNumJoints))
return 0;
double result;
int pos = ticks - sippacket->armJoints[joint].centre;
result = 90.0 / static_cast<double> (sippacket->armJoints[joint].ticksPer90);
result = result * pos;
if ((joint >= 0) && (joint <= 2))
result = -result;
return result;
}
// Degrees to ticks from the ARIA software
inline unsigned char P2OS::DegreesToTicks (int joint, double degrees)
{
double val;
if ((joint < 0) || (joint >= sippacket->armNumJoints))
return 0;
val = static_cast<double> (sippacket->armJoints[joint].ticksPer90) * degrees / 90.0;
val = round (val);
if ((joint >= 0) && (joint <= 2))
val = -val;
val += sippacket->armJoints[joint].centre;
if (val < sippacket->armJoints[joint].min)
return sippacket->armJoints[joint].min;
else if (val > sippacket->armJoints[joint].max)
return sippacket->armJoints[joint].max;
else
return static_cast<int> (round (val));
}
inline double P2OS::TicksToRadians (int joint, unsigned char ticks)
{
double result = DTOR (TicksToDegrees (joint, ticks));
return result;
}
inline unsigned char P2OS::RadiansToTicks (int joint, double rads)
{
unsigned char result = static_cast<unsigned char> (DegreesToTicks (joint, RTOD (rads)));
return result;
}
inline double P2OS::RadsPerSectoSecsPerTick (int joint, double speed)
{
double degs = RTOD (speed);
double ticksPerDeg = static_cast<double> (sippacket->armJoints[joint].ticksPer90) / 90.0f;
double ticksPerSec = degs * ticksPerDeg;
double secsPerTick = 1000.0f / ticksPerSec;
if (secsPerTick > 127)
return 127;
else if (secsPerTick < 1)
return 1;
return secsPerTick;
}
inline double P2OS::SecsPerTicktoRadsPerSec (int joint, double msecs)
{
double ticksPerSec = 1.0 / (static_cast<double> (msecs) / 1000.0);
double ticksPerDeg = static_cast<double> (sippacket->armJoints[joint].ticksPer90) / 90.0f;
double degs = ticksPerSec / ticksPerDeg;
double rads = DTOR (degs);
return rads;
}
void P2OS::ToggleActArrayPower (unsigned char value, bool lock)
{
unsigned char command[4];
P2OSPacket packet;
command[0] = ARM_POWER;
command[1] = ARGINT;
command[2] = value;
command[3] = 0;
packet.Build (command, 4);
SendReceive (&packet, lock);
}
void P2OS::SetActArrayJointSpeed (int joint, double speed)
{
unsigned char command[4];
P2OSPacket packet;
command[0] = ARM_SPEED;
command[1] = ARGINT;
command[2] = static_cast<int> (round (speed));
command[3] = joint;
packet.Build (command, 4);
SendReceive (&packet);
}
/////////////////////////////////////////////////////
// End actarray stuff
/////////////////////////////////////////////////////
int
P2OS::ProcessMessage(QueuePointer & resp_queue,
player_msghdr * hdr,
void * data)
{
// Check for capabilities requests first
HANDLE_CAPABILITY_REQUEST (position_id, resp_queue, hdr, data, PLAYER_MSGTYPE_REQ, PLAYER_CAPABILTIES_REQ);
HANDLE_CAPABILITY_REQUEST (actarray_id, resp_queue, hdr, data, PLAYER_MSGTYPE_REQ, PLAYER_CAPABILTIES_REQ);
HANDLE_CAPABILITY_REQUEST (lift_id, resp_queue, hdr, data, PLAYER_MSGTYPE_REQ, PLAYER_CAPABILTIES_REQ);
HANDLE_CAPABILITY_REQUEST (limb_id, resp_queue, hdr, data, PLAYER_MSGTYPE_REQ, PLAYER_CAPABILTIES_REQ);
HANDLE_CAPABILITY_REQUEST (gripper_id, resp_queue, hdr, data, PLAYER_MSGTYPE_REQ, PLAYER_CAPABILTIES_REQ);
HANDLE_CAPABILITY_REQUEST (armgripper_id, resp_queue, hdr, data, PLAYER_MSGTYPE_REQ, PLAYER_CAPABILTIES_REQ);
// Position2d caps
HANDLE_CAPABILITY_REQUEST (position_id, resp_queue, hdr, data, PLAYER_MSGTYPE_CMD, PLAYER_POSITION2D_CMD_VEL);
// Act array caps
HANDLE_CAPABILITY_REQUEST (actarray_id, resp_queue, hdr, data, PLAYER_MSGTYPE_CMD, PLAYER_ACTARRAY_CMD_POS);
HANDLE_CAPABILITY_REQUEST (actarray_id, resp_queue, hdr, data, PLAYER_MSGTYPE_CMD, PLAYER_ACTARRAY_CMD_MULTI_POS);
HANDLE_CAPABILITY_REQUEST (actarray_id, resp_queue, hdr, data, PLAYER_MSGTYPE_CMD, PLAYER_ACTARRAY_CMD_HOME);
HANDLE_CAPABILITY_REQUEST (actarray_id, resp_queue, hdr, data, PLAYER_MSGTYPE_REQ, PLAYER_ACTARRAY_REQ_POWER);
HANDLE_CAPABILITY_REQUEST (actarray_id, resp_queue, hdr, data, PLAYER_MSGTYPE_REQ, PLAYER_ACTARRAY_REQ_GET_GEOM);
HANDLE_CAPABILITY_REQUEST (actarray_id, resp_queue, hdr, data, PLAYER_MSGTYPE_REQ, PLAYER_ACTARRAY_REQ_SPEED);
// Lift caps
HANDLE_CAPABILITY_REQUEST (lift_id, resp_queue, hdr, data, PLAYER_MSGTYPE_CMD, PLAYER_ACTARRAY_CMD_POS);
HANDLE_CAPABILITY_REQUEST (lift_id, resp_queue, hdr, data, PLAYER_MSGTYPE_CMD, PLAYER_ACTARRAY_CMD_HOME);
HANDLE_CAPABILITY_REQUEST (lift_id, resp_queue, hdr, data, PLAYER_MSGTYPE_REQ, PLAYER_ACTARRAY_REQ_GET_GEOM);
// Limb caps
HANDLE_CAPABILITY_REQUEST (limb_id, resp_queue, hdr, data, PLAYER_MSGTYPE_CMD, PLAYER_LIMB_CMD_HOME);
HANDLE_CAPABILITY_REQUEST (limb_id, resp_queue, hdr, data, PLAYER_MSGTYPE_CMD, PLAYER_LIMB_CMD_STOP);
HANDLE_CAPABILITY_REQUEST (limb_id, resp_queue, hdr, data, PLAYER_MSGTYPE_CMD, PLAYER_LIMB_CMD_SETPOSE);
HANDLE_CAPABILITY_REQUEST (limb_id, resp_queue, hdr, data, PLAYER_MSGTYPE_REQ, PLAYER_LIMB_REQ_POWER);
HANDLE_CAPABILITY_REQUEST (limb_id, resp_queue, hdr, data, PLAYER_MSGTYPE_REQ, PLAYER_LIMB_REQ_GEOM);
// Gripper caps
HANDLE_CAPABILITY_REQUEST (gripper_id, resp_queue, hdr, data, PLAYER_MSGTYPE_CMD, PLAYER_GRIPPER_CMD_OPEN);
HANDLE_CAPABILITY_REQUEST (gripper_id, resp_queue, hdr, data, PLAYER_MSGTYPE_CMD, PLAYER_GRIPPER_CMD_CLOSE);
HANDLE_CAPABILITY_REQUEST (gripper_id, resp_queue, hdr, data, PLAYER_MSGTYPE_CMD, PLAYER_GRIPPER_CMD_STOP);
// Arm gripper caps
HANDLE_CAPABILITY_REQUEST (armgripper_id, resp_queue, hdr, data, PLAYER_MSGTYPE_CMD, PLAYER_GRIPPER_CMD_OPEN);
HANDLE_CAPABILITY_REQUEST (armgripper_id, resp_queue, hdr, data, PLAYER_MSGTYPE_CMD, PLAYER_GRIPPER_CMD_CLOSE);
HANDLE_CAPABILITY_REQUEST (armgripper_id, resp_queue, hdr, data, PLAYER_MSGTYPE_CMD, PLAYER_GRIPPER_CMD_STOP);
// Process other messages
if(hdr->type == PLAYER_MSGTYPE_REQ)
return(this->HandleConfig(resp_queue,hdr,data));
else if(hdr->type == PLAYER_MSGTYPE_CMD)
return(this->HandleCommand(hdr,data));
else
return(-1);
}
int
P2OS::HandleConfig(QueuePointer & resp_queue,
player_msghdr * hdr,
void * data)
{
int joint = 0;
double newSpeed = 0.0f;
// check for position config requests
if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,
PLAYER_POSITION2D_REQ_SET_ODOM,
this->position_id))
{
if(hdr->size != sizeof(player_position2d_set_odom_req_t))
{
PLAYER_WARN("Arg to odometry set requests wrong size; ignoring");
return(-1);
}
player_position2d_set_odom_req_t* set_odom_req =
(player_position2d_set_odom_req_t*)data;
this->sippacket->x_offset = ((int)rint(set_odom_req->pose.px*1e3)) -
this->sippacket->xpos;
this->sippacket->y_offset = ((int)rint(set_odom_req->pose.py*1e3)) -
this->sippacket->ypos;
this->sippacket->angle_offset = ((int)rint(RTOD(set_odom_req->pose.pa))) -
this->sippacket->angle;
this->Publish(this->position_id, resp_queue,
PLAYER_MSGTYPE_RESP_ACK, PLAYER_POSITION2D_REQ_SET_ODOM);
return(0);
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,
PLAYER_POSITION2D_REQ_MOTOR_POWER,
this->position_id))
{
/* motor state change request
* 1 = enable motors
* 0 = disable motors (default)
*/
if(hdr->size != sizeof(player_position2d_power_config_t))
{
PLAYER_WARN("Arg to motor state change request wrong size; ignoring");
return(-1);
}
player_position2d_power_config_t* power_config =
(player_position2d_power_config_t*)data;
this->ToggleMotorPower(power_config->state);
this->Publish(this->position_id, resp_queue,
PLAYER_MSGTYPE_RESP_ACK, PLAYER_POSITION2D_REQ_MOTOR_POWER);
return(0);
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,
PLAYER_POSITION2D_REQ_RESET_ODOM,
this->position_id))
{
/* reset position to 0,0,0: no args */
if(hdr->size != 0)
{
PLAYER_WARN("Arg to reset position request is wrong size; ignoring");
return(-1);
}
ResetRawPositions();
this->Publish(this->position_id, resp_queue,
PLAYER_MSGTYPE_RESP_ACK, PLAYER_POSITION2D_REQ_RESET_ODOM);
return(0);
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,
PLAYER_POSITION2D_REQ_GET_GEOM,
this->position_id))
{
/* Return the robot geometry. */
if(hdr->size != 0)
{
PLAYER_WARN("Arg get robot geom is wrong size; ignoring");
return(-1);
}
player_position2d_geom_t geom;
// TODO: Figure out this rotation offset somehow; it's not
// given in the Saphira parameters. For now, -0.1 is
// about right for a Pioneer 2DX.
geom.pose.px = -0.1;
geom.pose.py = 0.0;
geom.pose.pyaw = 0.0;
// get dimensions from the parameter table
geom.size.sl = PlayerRobotParams[param_idx].RobotLength / 1e3;
geom.size.sw = PlayerRobotParams[param_idx].RobotWidth / 1e3;
this->Publish(this->position_id, resp_queue,
PLAYER_MSGTYPE_RESP_ACK,
PLAYER_POSITION2D_REQ_GET_GEOM,
(void*)&geom, sizeof(geom), NULL);
return(0);
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,
PLAYER_POSITION2D_REQ_VELOCITY_MODE,
this->position_id))
{
/* velocity control mode:
* 0 = direct wheel velocity control (default)
* 1 = separate translational and rotational control
*/
if(hdr->size != sizeof(player_position2d_velocity_mode_config_t))
{
PLAYER_WARN("Arg to velocity control mode change request is wrong "
"size; ignoring");
return(-1);
}
player_position2d_velocity_mode_config_t* velmode_config =
(player_position2d_velocity_mode_config_t*)data;
if(velmode_config->value)
direct_wheel_vel_control = false;
else
direct_wheel_vel_control = true;
this->Publish(this->position_id, resp_queue,
PLAYER_MSGTYPE_RESP_ACK, PLAYER_POSITION2D_REQ_VELOCITY_MODE);
return(0);
}
// check for sonar config requests
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,
PLAYER_SONAR_REQ_POWER,
this->sonar_id))
{
/*
* 1 = enable sonars
* 0 = disable sonar
*/
if(hdr->size != sizeof(player_sonar_power_config_t))
{
PLAYER_WARN("Arg to sonar state change request wrong size; ignoring");
return(-1);
}
player_sonar_power_config_t* sonar_config =
(player_sonar_power_config_t*)data;
this->ToggleSonarPower(sonar_config->state);
this->Publish(this->sonar_id, resp_queue,
PLAYER_MSGTYPE_RESP_ACK, PLAYER_SONAR_REQ_POWER);
return(0);
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,
PLAYER_SONAR_REQ_GET_GEOM,
this->sonar_id))
{
/* Return the sonar geometry. */
if(hdr->size != 0)
{
PLAYER_WARN("Arg get sonar geom is wrong size; ignoring");
return(-1);
}
player_sonar_geom_t geom;
geom.poses_count = PlayerRobotParams[param_idx].SonarNum;
geom.poses = new player_pose3d_t[geom.poses_count];
for(int i = 0; i < PlayerRobotParams[param_idx].SonarNum; i++)
{
sonar_pose_t pose = PlayerRobotParams[param_idx].sonar_pose[i];
geom.poses[i].px = pose.x / 1e3;
geom.poses[i].py = pose.y / 1e3;
geom.poses[i].pyaw = DTOR(pose.th);
}
this->Publish(this->sonar_id, resp_queue,
PLAYER_MSGTYPE_RESP_ACK, PLAYER_SONAR_REQ_GET_GEOM,
(void*)&geom);
delete [] geom.poses;
return(0);
}
// check for blobfinder requests
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,
PLAYER_BLOBFINDER_REQ_SET_COLOR,
this->blobfinder_id))
{
// Set the tracking color (RGB max/min values)
if(hdr->size != sizeof(player_blobfinder_color_config_t))
{
puts("Arg to blobfinder color request wrong size; ignoring");
return(-1);
}
player_blobfinder_color_config_t* color_config =
(player_blobfinder_color_config_t*)data;
CMUcamTrack(color_config->rmin,
color_config->rmax,
color_config->gmin,
color_config->gmax,
color_config->bmin,
color_config->bmax);
this->Publish(this->blobfinder_id, resp_queue,
PLAYER_MSGTYPE_RESP_ACK, PLAYER_BLOBFINDER_REQ_SET_COLOR);
return(0);
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,
PLAYER_BLOBFINDER_REQ_SET_IMAGER_PARAMS,
this->blobfinder_id))
{
// Set the imager control params
if(hdr->size != sizeof(player_blobfinder_imager_config_t))
{
puts("Arg to blobfinder imager request wrong size; ignoring");
return(-1);
}
player_blobfinder_imager_config_t* imager_config =
(player_blobfinder_imager_config_t*)data;
P2OSPacket cam_packet;
unsigned char cam_command[50];
int np;
np=3;
CMUcamStopTracking(); // Stop the current tracking.
cam_command[0] = TTY3;
cam_command[1] = ARGSTR;
np += snprintf((char*)&cam_command[np], sizeof(cam_command) - np, "CR ");
if (imager_config->brightness >= 0)
np += snprintf((char*)&cam_command[np],sizeof(cam_command) - np, " 6 %d",
imager_config->brightness);
if (imager_config->contrast >= 0)
np += snprintf((char*)&cam_command[np],sizeof(cam_command) - np, " 5 %d",
imager_config->contrast);
if (imager_config->autogain >= 0)
{
if (imager_config->autogain == 0)
np += snprintf((char*)&cam_command[np],sizeof(cam_command) - np, " 19 32");
else
np += snprintf((char*)&cam_command[np], sizeof(cam_command) - np," 19 33");
}
if (imager_config->colormode >= 0)
{
if (imager_config->colormode == 3)
np += snprintf((char*)&cam_command[np],sizeof(cam_command) - np, " 18 36");
else if (imager_config->colormode == 2)
np += snprintf((char*)&cam_command[np],sizeof(cam_command) - np, " 18 32");
else if (imager_config->colormode == 1)
np += snprintf((char*)&cam_command[np],sizeof(cam_command) - np, " 18 44");
else
np += snprintf((char*)&cam_command[np],sizeof(cam_command) - np, " 18 40");
}
if (np > 6)
{
snprintf((char*)&cam_command[np],sizeof(cam_command) - np, "\r");
cam_command[2] = strlen((char *)&cam_command[3]);
cam_packet.Build(cam_command, (int)cam_command[2]+3);
SendReceive(&cam_packet);
printf("Blobfinder imager parameters updated.\n");
printf(" %s\n", &cam_command[3]);
} else
printf("Blobfinder imager parameters NOT updated.\n");
CMUcamTrack(); // Restart tracking
this->Publish(this->blobfinder_id, resp_queue,
PLAYER_MSGTYPE_RESP_ACK,
PLAYER_BLOBFINDER_REQ_SET_IMAGER_PARAMS);
return(0);
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,PLAYER_ACTARRAY_REQ_POWER,this->actarray_id))
{
ToggleActArrayPower (((player_actarray_power_config_t*) data)->value);
this->Publish(this->actarray_id, resp_queue, PLAYER_MSGTYPE_RESP_ACK, PLAYER_ACTARRAY_REQ_POWER);
return 0;
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,PLAYER_ACTARRAY_REQ_GET_GEOM,this->actarray_id))
{
// First ask for an ARMINFOpac (because we need to get any updates to speed settings)
P2OSPacket aaPacket;
unsigned char aaCmd = ARM_INFO;
aaPacket.Build (&aaCmd, 1);
SendReceive (&aaPacket);
player_actarray_geom_t aaGeom;
player_actarray_actuatorgeom_t *actuators;
aaGeom.actuators_count = sippacket->armNumJoints;
actuators = new player_actarray_actuatorgeom_t[sippacket->armNumJoints];
if (actuators == NULL)
{
PLAYER_ERROR ("Failed to allocate memory for actuator data");
return -1;
}
aaGeom.actuators = actuators;
for (int ii = 0; ii < sippacket->armNumJoints; ii++)
{
aaGeom.actuators[ii].type = PLAYER_ACTARRAY_TYPE_ROTARY;
aaGeom.actuators[ii].length = aaLengths[ii];
aaGeom.actuators[ii].orientation.proll = aaOrients[ii * 3];
aaGeom.actuators[ii].orientation.ppitch = aaOrients[ii * 3 + 1];
aaGeom.actuators[ii].orientation.pyaw = aaOrients[ii * 3 + 2];
aaGeom.actuators[ii].axis.px = aaAxes[ii * 3];
aaGeom.actuators[ii].axis.py = aaAxes[ii * 3 + 1];
aaGeom.actuators[ii].axis.pz = aaAxes[ii * 3 + 2];
aaGeom.actuators[ii].min = static_cast<float> (TicksToRadians (ii, sippacket->armJoints[ii].min));
aaGeom.actuators[ii].centre = static_cast<float> (TicksToRadians (ii, sippacket->armJoints[ii].centre));
aaGeom.actuators[ii].max = static_cast<float> (TicksToRadians (ii, sippacket->armJoints[ii].max));
aaGeom.actuators[ii].home = static_cast<float> (TicksToRadians (ii, sippacket->armJoints[ii].home));
aaGeom.actuators[ii].config_speed = static_cast<float> (SecsPerTicktoRadsPerSec (ii, sippacket->armJoints[ii].speed));
aaGeom.actuators[ii].hasbrakes = 0;
}
aaGeom.base_pos.px = aaBasePos.px;
aaGeom.base_pos.py = aaBasePos.py;
aaGeom.base_pos.pz = aaBasePos.pz;
aaGeom.base_orientation.proll = aaBaseOrient.proll;
aaGeom.base_orientation.ppitch = aaBaseOrient.ppitch;
aaGeom.base_orientation.pyaw = aaBaseOrient.pyaw;
this->Publish(this->actarray_id, resp_queue, PLAYER_MSGTYPE_RESP_ACK, PLAYER_ACTARRAY_REQ_GET_GEOM, &aaGeom, sizeof (aaGeom), NULL);
delete[] actuators;
return 0;
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,PLAYER_ACTARRAY_REQ_SPEED,this->actarray_id))
{
joint = ((player_actarray_speed_config_t*) data)->joint + 1;
newSpeed = RadsPerSectoSecsPerTick (joint, ((player_actarray_speed_config_t*) data)->speed);
SetActArrayJointSpeed (joint, newSpeed);
this->Publish(this->actarray_id, resp_queue, PLAYER_MSGTYPE_RESP_ACK, PLAYER_ACTARRAY_REQ_SPEED);
return 0;
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,PLAYER_LIMB_REQ_POWER,this->limb_id))
{
ToggleActArrayPower (((player_actarray_power_config_t*) data)->value);
this->Publish(this->actarray_id, resp_queue, PLAYER_MSGTYPE_RESP_ACK, PLAYER_LIMB_REQ_POWER);
return 0;
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,PLAYER_LIMB_REQ_BRAKES,this->limb_id))
{
// We don't have any brakes
return 0;
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,PLAYER_LIMB_REQ_GEOM,this->limb_id))
{
player_limb_geom_req_t limbGeom;
limbGeom.basePos.px = armOffsetX;
limbGeom.basePos.py = armOffsetY;
limbGeom.basePos.pz = armOffsetZ;
this->Publish(this->limb_id, resp_queue, PLAYER_MSGTYPE_RESP_ACK, PLAYER_LIMB_REQ_GEOM, &limbGeom, sizeof (limbGeom), NULL);
return 0;
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,PLAYER_LIMB_REQ_SPEED,this->limb_id))
{
// FIXME - need to figure out what sort of speed support we should provide through the IK interface
// Would need some form of motion control
// For now, just set all joint speeds - take the value as being rad/s instead of m/s
float speed = ((player_limb_speed_req_t*) data)->speed;
for (int ii = 1; ii < 6; ii++)
{
newSpeed = RadsPerSectoSecsPerTick (ii, speed);
SetActArrayJointSpeed (ii, newSpeed);
}
this->Publish(this->limb_id, resp_queue, PLAYER_MSGTYPE_RESP_ACK, PLAYER_LIMB_REQ_SPEED);
return 0;
}
else if (Message::MatchMessage (hdr, PLAYER_MSGTYPE_REQ, PLAYER_BUMPER_REQ_GET_GEOM, this->bumper_id))
{
/* Return the bumper geometry. */
if(hdr->size != 0)
{
PLAYER_WARN("Arg get bumper geom is wrong size; ignoring");
return(-1);
}
player_bumper_geom_t geom;
geom.bumper_def_count = PlayerRobotParams[param_idx].NumFrontBumpers + PlayerRobotParams[param_idx].NumRearBumpers;
geom.bumper_def = new player_bumper_define_t[geom.bumper_def_count];
for(unsigned int ii = 0; ii < geom.bumper_def_count; ii++)
{
bumper_def_t def = PlayerRobotParams[param_idx].bumper_geom[ii];
geom.bumper_def[ii].pose.px = def.x;
geom.bumper_def[ii].pose.py = def.y;
geom.bumper_def[ii].pose.pyaw = DTOR(def.th);
geom.bumper_def[ii].length = def.length;
geom.bumper_def[ii].radius = def.radius;
}
this->Publish(this->bumper_id, resp_queue,
PLAYER_MSGTYPE_RESP_ACK, PLAYER_BUMPER_REQ_GET_GEOM,
(void*)&geom);
delete [] geom.bumper_def;
return(0);
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,PLAYER_ACTARRAY_REQ_GET_GEOM,this->lift_id))
{
player_actarray_geom_t aaGeom;
player_actarray_actuatorgeom_t actuator;
aaGeom.actuators = &actuator;
aaGeom.actuators_count = 1;
memset (aaGeom.actuators, 0, sizeof (player_actarray_actuator_t));
aaGeom.actuators[0].type = PLAYER_ACTARRAY_TYPE_LINEAR;
aaGeom.actuators[0].min = 0.0f;
aaGeom.actuators[0].centre = 0.5f;
aaGeom.actuators[0].max = 1.0f;
aaGeom.actuators[0].home = 1.0f;
aaGeom.actuators[0].config_speed = 0.02f; // 2cm/s, according to the manual
aaGeom.actuators[0].hasbrakes = 0;
this->Publish(this->lift_id, resp_queue, PLAYER_MSGTYPE_RESP_ACK, PLAYER_ACTARRAY_REQ_GET_GEOM, &aaGeom, sizeof (aaGeom), NULL);
return 0;
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,PLAYER_GRIPPER_REQ_GET_GEOM,this->gripper_id))
{
player_gripper_geom_t geom;
memset (&geom, 0, sizeof (player_gripper_geom_t));
geom.pose = gripperPose;
geom.outer_size = gripperOuterSize;
geom.inner_size = gripperInnerSize;
geom.num_beams = 2;
geom.capacity = 0;
this->Publish(this->gripper_id, resp_queue, PLAYER_MSGTYPE_RESP_ACK, PLAYER_GRIPPER_REQ_GET_GEOM, &geom, sizeof (geom), NULL);
return 0;
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,PLAYER_GRIPPER_REQ_GET_GEOM,this->armgripper_id))
{
player_gripper_geom_t geom;
memset (&geom, 0, sizeof (player_gripper_geom_t));
memset (&(geom.pose), 0, sizeof (player_pose3d_t)); // Hard to know since it's on the end of the arm
geom.outer_size = armGripperOuterSize;
geom.inner_size = armGripperInnerSize;
geom.num_beams = 0;
geom.capacity = 0;
this->Publish(this->armgripper_id, resp_queue, PLAYER_MSGTYPE_RESP_ACK, PLAYER_GRIPPER_REQ_GET_GEOM, &geom, sizeof (geom), NULL);
return 0;
}
// PTZ Stuff now.
else if (Message::MatchMessage(hdr,
PLAYER_MSGTYPE_REQ,
PLAYER_PTZ_REQ_GENERIC, device_addr))
{
assert(hdr->size == sizeof(player_ptz_req_generic_t));
player_ptz_req_generic_t *cfg = (player_ptz_req_generic_t *)data;
// check whether command or inquiry...
if (cfg->config[0] == 0x01)
{
if (SendCommand((uint8_t *)cfg->config, cfg->config_count) < 0)
Publish(device_addr, resp_queue, PLAYER_MSGTYPE_RESP_NACK, hdr->subtype);
else
Publish(device_addr, resp_queue, PLAYER_MSGTYPE_RESP_ACK, hdr->subtype);
return 0;
}
else
{
// this is an inquiry, so we have to send data back
cfg->config_count = SendRequest((uint8_t*)cfg->config,
cfg->config_count,
(uint8_t*)cfg->config);
Publish(device_addr, resp_queue, PLAYER_MSGTYPE_RESP_ACK, hdr->subtype);
}
return 0;
}
else
{
PLAYER_WARN("unknown config request to p2os driver");
return(-1);
}
return 0;
}
void P2OS::SendPulse (void)
{
unsigned char command;
P2OSPacket packet;
command = PULSE;
packet.Build(&command, 1);
SendReceive(&packet);
}
///////////////////////////////////////////////////////////////////////////////
// Command handling
///////////////////////////////////////////////////////////////////////////////
void
P2OS::HandlePositionCommand(player_position2d_cmd_vel_t position_cmd)
{
int speedDemand, turnRateDemand;
double leftvel, rightvel;
double rotational_term;
unsigned short absspeedDemand, absturnRateDemand;
unsigned char motorcommand[4];
P2OSPacket motorpacket;
speedDemand = (int)rint(position_cmd.vel.px * 1e3);
turnRateDemand = (int)rint(RTOD(position_cmd.vel.pa));
if(this->direct_wheel_vel_control)
{
// convert xspeed and yawspeed into wheelspeeds
rotational_term = (M_PI/180.0) * turnRateDemand /
PlayerRobotParams[param_idx].DiffConvFactor;
leftvel = (speedDemand - rotational_term);
rightvel = (speedDemand + rotational_term);
// Apply wheel speed bounds
if(fabs(leftvel) > this->motor_max_speed)
{
if(leftvel > 0)
{
rightvel *= this->motor_max_speed/leftvel;
leftvel = this->motor_max_speed;
puts("Left wheel velocity threshholded!");
}
else
{
rightvel *= -this->motor_max_speed/leftvel;
leftvel = -this->motor_max_speed;
}
}
if(fabs(rightvel) > this->motor_max_speed)
{
if(rightvel > 0)
{
leftvel *= this->motor_max_speed/rightvel;
rightvel = this->motor_max_speed;
puts("Right wheel velocity threshholded!");
}
else
{
leftvel *= -this->motor_max_speed/rightvel;
rightvel = -this->motor_max_speed;
}
}
// Apply control band bounds
if(this->use_vel_band)
{
// This band prevents the wheels from turning in opposite
// directions
if (leftvel * rightvel < 0)
{
if (leftvel + rightvel >= 0)
{
if (leftvel < 0)
leftvel = 0;
if (rightvel < 0)
rightvel = 0;
}
else
{
if (leftvel > 0)
leftvel = 0;
if (rightvel > 0)
rightvel = 0;
}
}
}
// Apply byte range bounds
if (leftvel / PlayerRobotParams[param_idx].Vel2Divisor > 126)
leftvel = 126 * PlayerRobotParams[param_idx].Vel2Divisor;
if (leftvel / PlayerRobotParams[param_idx].Vel2Divisor < -126)
leftvel = -126 * PlayerRobotParams[param_idx].Vel2Divisor;
if (rightvel / PlayerRobotParams[param_idx].Vel2Divisor > 126)
rightvel = 126 * PlayerRobotParams[param_idx].Vel2Divisor;
if (rightvel / PlayerRobotParams[param_idx].Vel2Divisor < -126)
rightvel = -126 * PlayerRobotParams[param_idx].Vel2Divisor;
// send the speed command
motorcommand[0] = VEL2;
motorcommand[1] = ARGINT;
motorcommand[2] = (char)(rightvel /
PlayerRobotParams[param_idx].Vel2Divisor);
motorcommand[3] = (char)(leftvel /
PlayerRobotParams[param_idx].Vel2Divisor);
motorpacket.Build(motorcommand, 4);
this->SendReceive(&motorpacket);
}
else
{
// do separate trans and rot vels
motorcommand[0] = VEL;
if(speedDemand >= 0)
motorcommand[1] = ARGINT;
else
motorcommand[1] = ARGNINT;
absspeedDemand = (unsigned short)abs(speedDemand);
if(absspeedDemand < this->motor_max_speed)
{
motorcommand[2] = absspeedDemand & 0x00FF;
motorcommand[3] = (absspeedDemand & 0xFF00) >> 8;
}
else
{
puts("Speed demand threshholded!");
motorcommand[2] = this->motor_max_speed & 0x00FF;
motorcommand[3] = (this->motor_max_speed & 0xFF00) >> 8;
}
motorpacket.Build(motorcommand, 4);
this->SendReceive(&motorpacket);
motorcommand[0] = RVEL;
if(turnRateDemand >= 0)
motorcommand[1] = ARGINT;
else
motorcommand[1] = ARGNINT;
absturnRateDemand = (unsigned short)abs(turnRateDemand);
if(absturnRateDemand < this->motor_max_turnspeed)
{
motorcommand[2] = absturnRateDemand & 0x00FF;
motorcommand[3] = (absturnRateDemand & 0xFF00) >> 8;
}
else
{
puts("Turn rate demand threshholded!");
motorcommand[2] = this->motor_max_turnspeed & 0x00FF;
motorcommand[3] = (this->motor_max_turnspeed & 0xFF00) >> 8;
}
motorpacket.Build(motorcommand, 4);
this->SendReceive(&motorpacket);
}
}
void
P2OS::HandleAudioCommand(player_audio_sample_item_t audio_cmd)
{
unsigned char soundcommand[4];
P2OSPacket soundpacket;
unsigned short soundindex;
soundindex = audio_cmd.index;
if(!this->sent_audio_cmd || (soundindex != this->last_audio_cmd.index))
{
soundcommand[0] = SOUND;
soundcommand[1] = ARGINT;
soundcommand[2] = soundindex & 0x00FF;
soundcommand[3] = (soundindex & 0xFF00) >> 8;
soundpacket.Build(soundcommand,4);
SendReceive(&soundpacket);
fflush(stdout);
this->last_audio_cmd.index = soundindex;
}
}
///////////////////////////////////////////////////////////////////////////////
// Arm actuator array commands
void P2OS::HandleActArrayPosCmd (player_actarray_position_cmd_t cmd)
{
unsigned char command[4];
P2OSPacket packet;
if (!(lastActArrayCmd == PLAYER_ACTARRAY_CMD_POS) || ((lastActArrayCmd == PLAYER_ACTARRAY_CMD_POS) &&
(cmd.joint != lastActArrayPosCmd.joint || cmd.position != lastActArrayPosCmd.position)))
{
command[0] = ARM_POS;
command[1] = ARGINT;
command[2] = RadiansToTicks (cmd.joint, cmd.position);
command[3] = static_cast<unsigned char> (cmd.joint) + 1;
packet.Build(command, 4);
SendReceive(&packet);
sippacket->armJointTargetPos[static_cast<unsigned char> (cmd.joint)] = command[2];
}
}
void P2OS::HandleActArrayHomeCmd (player_actarray_home_cmd_t cmd)
{
unsigned char command[4];
P2OSPacket packet;
if ((lastActArrayCmd == PLAYER_ACTARRAY_CMD_POS) || (!(lastActArrayCmd == PLAYER_ACTARRAY_CMD_POS) &&
(cmd.joint != lastActArrayHomeCmd.joint)))
{
command[0] = ARM_HOME;
command[1] = ARGINT;
command[2] = (cmd.joint == -1) ? 7 : (static_cast<unsigned char> (cmd.joint) + 1);
command[3] = 0;
packet.Build(command, 4);
SendReceive(&packet);
}
}
int P2OS::HandleActArrayCommand (player_msghdr * hdr, void * data)
{
if (Message::MatchMessage (hdr, PLAYER_MSGTYPE_CMD, PLAYER_ACTARRAY_CMD_POS, this->actarray_id))
{
player_actarray_position_cmd_t cmd;
cmd = *(player_actarray_position_cmd_t*) data;
this->HandleActArrayPosCmd (cmd);
lastActArrayCmd = PLAYER_ACTARRAY_CMD_POS;
return 0;
}
else if (Message::MatchMessage (hdr, PLAYER_MSGTYPE_CMD, PLAYER_ACTARRAY_CMD_HOME, this->actarray_id))
{
player_actarray_home_cmd_t cmd;
cmd = *(player_actarray_home_cmd_t*) data;
this->HandleActArrayHomeCmd (cmd);
lastActArrayCmd = PLAYER_ACTARRAY_CMD_HOME;
return 0;
}
else if (Message::MatchMessage (hdr, PLAYER_MSGTYPE_CMD, PLAYER_ACTARRAY_CMD_MULTI_POS, this->actarray_id))
{
player_actarray_multi_position_cmd_t cmd = *(player_actarray_multi_position_cmd_t*) data;
player_actarray_position_cmd_t singleCmd;
for (unsigned int ii = 0; ii < cmd.positions_count && ii < 6; ii++)
{
singleCmd.joint = ii;
singleCmd.position = cmd.positions[ii];
this->HandleActArrayPosCmd (singleCmd);
}
lastActArrayCmd = PLAYER_ACTARRAY_CMD_MULTI_POS;
}
return -1;
}
///////////////////////////////////////////////////////////////////////////////
// Limb commands
void P2OS::HandleLimbHomeCmd (void)
{
unsigned char command[4];
P2OSPacket packet;
command[0] = ARM_HOME;
command[1] = ARGINT;
command[2] = 7;
command[3] = 0;
packet.Build(command, 4);
SendReceive(&packet);
}
void P2OS::HandleLimbStopCmd (void)
{
unsigned char command[4];
P2OSPacket packet;
command[0] = ARM_STOP;
command[1] = ARGINT;
for (int ii = 1; ii < 5; ii++)
{
command[2] = ii;
command[3] = 0;
packet.Build (command, 4);
SendReceive (&packet);
}
}
void P2OS::HandleLimbSetPoseCmd (player_limb_setpose_cmd_t cmd)
{
unsigned char command[4];
P2OSPacket packet;
EndEffector pose;
// printf ("Moving limb to pose (%f, %f, %f), (%f, %f, %f), (%f, %f, %f)\n", cmd.position.px, cmd.position.py, cmd.position.pz, cmd.approach.px, cmd.approach.py, cmd.approach.pz, cmd.orientation.px, cmd.orientation.py, cmd.orientation.pz);
pose.p.x = cmd.position.px - armOffsetX;
pose.p.y = cmd.position.py - armOffsetY;
pose.p.z = cmd.position.pz - armOffsetZ;
pose.a.x = cmd.approach.px; pose.a.y = cmd.approach.py; pose.a.z = cmd.approach.pz;
pose.o.x = cmd.orientation.px; pose.o.y = cmd.orientation.py; pose.o.z = cmd.orientation.pz;
pose.a = kineCalc->Normalise (pose.a);
pose.o = kineCalc->Normalise (pose.o);
pose.n = kineCalc->CalculateN (pose);
// printf ("Pose = %f, %f, %f\t", pose.p.x, pose.p.y, pose.p.z);
// printf ("Approach = %f, %f, %f\n", pose.a.x, pose.a.y, pose.a.z);
// printf ("Orientation = %f, %f, %f\t", pose.o.x, pose.o.y, pose.o.z);
// printf ("Normal = %f, %f, %f\n", pose.n.x, pose.n.y, pose.n.z);
if (!kineCalc->CalculateIK (pose))
{
limb_data.state = PLAYER_LIMB_STATE_OOR;
return;
}
command[0] = ARM_POS;
command[1] = ARGINT;
for (int ii = 0; ii < 5; ii++)
{
command[2] = RadiansToTicks (ii, kineCalc->GetTheta (ii));
command[3] = ii + 1;
packet.Build (command, 4);
SendReceive (&packet);
// printf ("Sent joint %d to %f (%d)\n", ii, kineCalc->GetTheta (ii), command[2]);
}
limb_data.state = PLAYER_LIMB_STATE_MOVING;
}
// NOTE: Not functional
void P2OS::HandleLimbSetPositionCmd (player_limb_setposition_cmd_t cmd)
{
EndEffector pose;
unsigned char command[4];
P2OSPacket packet;
pose.p.x = cmd.position.px - armOffsetX;
pose.p.y = -(cmd.position.py - armOffsetY);
pose.p.z = cmd.position.pz - armOffsetZ;
// Use the pose info from the last reported arm position (cause the IK calculator doesn't
// calculate without full pose data)
pose.o = kineCalc->GetO ();
pose.a = kineCalc->GetA ();
pose.n = kineCalc->GetN ();
if (!kineCalc->CalculateIK (pose))
{
limb_data.state = PLAYER_LIMB_STATE_OOR;
return;
}
command[0] = ARM_POS;
command[1] = ARGINT;
for (int ii = 0; ii < 5; ii++)
{
command[2] = RadiansToTicks (ii, kineCalc->GetTheta (ii));
command[3] = ii + 1;
packet.Build (command, 4);
SendReceive (&packet);
}
limb_data.state = PLAYER_LIMB_STATE_MOVING;
}
// NOTE: Not functional
void P2OS::HandleLimbVecMoveCmd (player_limb_vecmove_cmd_t cmd)
{
EndEffector pose;
unsigned char command[4];
P2OSPacket packet;
// To do a vector move, calculate a new position that is offset from the current
// by the length of the desired move in the direction of the desired vector.
// Since we lack constant motion control, but are moving over a small range, this
// should hopefully give an accurate representation of a vector move.
// UPDATE: Turns out it doesn't work. Hopefully I'll have time to rewrite
// this driver in the future so that it can support proper constant motion
// control without being an unmaintainable mess.
// As such, this vector move isn't actually a vector move as it is intended in
// the interface. I'll leave it in because it could be useful as an "offset"
// command, but this should be noted in the docs for the driver.
pose.p = kineCalc->GetP ();
pose.o = kineCalc->GetO ();
pose.a = kineCalc->GetA ();
pose.n = kineCalc->GetN ();
KineVector offset;
offset.x = cmd.direction.px; offset.y = -cmd.direction.py; offset.z = cmd.direction.pz;
offset = kineCalc->Normalise (offset);
offset.x *= cmd.length;
offset.y *= cmd.length;
offset.z *= cmd.length;
pose.p.x += offset.x;
pose.p.y += offset.y;
pose.p.z += offset.z;
if (!kineCalc->CalculateIK (pose))
{
limb_data.state = PLAYER_LIMB_STATE_OOR;
return;
}
command[0] = ARM_POS;
command[1] = ARGINT;
for (int ii = 0; ii < 5; ii++)
{
command[2] = RadiansToTicks (ii, kineCalc->GetTheta (ii));
command[3] = ii + 1;
packet.Build (command, 4);
SendReceive (&packet);
}
limb_data.state = PLAYER_LIMB_STATE_MOVING;
}
int P2OS::HandleLimbCommand (player_msghdr *hdr, void *data)
{
if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_CMD,PLAYER_LIMB_CMD_HOME,this->limb_id))
{
this->HandleLimbHomeCmd ();
return 0;
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_CMD,PLAYER_LIMB_CMD_STOP,this->limb_id))
{
this->HandleLimbStopCmd ();
return 0;
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_CMD,PLAYER_LIMB_CMD_SETPOSE,this->limb_id))
{
player_limb_setpose_cmd_t cmd;
cmd = *(player_limb_setpose_cmd_t*) data;
this->HandleLimbSetPoseCmd (cmd);
return 0;
}
return -1;
}
///////////////////////////////////////////////////////////////////////////////
// Lift commands
int P2OS::HandleLiftCommand (player_msghdr *hdr, void *data)
{
unsigned char command[4];
P2OSPacket packet;
if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_CMD,PLAYER_ACTARRAY_CMD_POS,this->lift_id))
{
player_actarray_position_cmd_t cmd;
cmd = *(player_actarray_position_cmd_t*) data;
// If not the first joint, return error
if (cmd.joint > 0)
return -1;
if (lastLiftCmd == PLAYER_ACTARRAY_CMD_POS && lastLiftPosCmd.position == cmd.position)
return 0;
command[0] = GRIPPER;
command[1] = ARGINT;
// If the position is 1 or 0, then it's easy: just use LIFTup or LIFTdown
if (cmd.position <= 0.0)
{
command[2] = LIFTdown;
command[3] = 0;
packet.Build (command, 4);
SendReceive (&packet);
}
else if (cmd.position >= 1.0)
{
command[3] = LIFTup;
command[3] = 0;
packet.Build (command, 4);
SendReceive (&packet);
}
else
{
// Lift position is a range from 0 to 1. 0 corresponds to down, 1 corresponds to up.
// Setting positions in between is done using the carry time.
// According to the manual, the lift can move 7cm at a rate of 2cm/s (in ideal conditions).
// So to figure out the lift time for a given position, we consider an AA position of 1 to
// correspond to a lift position of 7cm and 0 to 0cm. Given a speed of 2cm/s, this means
// the lift takes 3.5s to move over its full range. So an AA position is converted to a
// time by 3.5 * cmd.pos. For example, 0.5 is 3.5 * 0.5 = 1.75s travel time.
// We then use the LIFTcarry command to set this travel time. LIFTcarry is specified as
// an integer, with each step equal to 20ms of travel time. So the LIFTcarry value
// becomes travel time / 0.02.
// It is important to remember that the LIFTcarry is (if my reading of the manul is correct)
// an offset command, not absolute position command. So we have to track the last commanded
// position of the lift and work from that to get the correct travel time (and direction).
double offset = cmd.position - lastLiftPosCmd.position;
double travelTime = offset * 3.5f;
short liftCarryVal = static_cast<short> (travelTime / 0.02f);
// Send the LIFTcarry command
command[2] = LIFTcarry;
command[3] = 0;
packet.Build (command, 4);
SendReceive (&packet);
// Followed by the carry time
command[0] = GRIPPERVAL;
command[2] = liftCarryVal & 0x00FF;
command[3] = (liftCarryVal & 0xFF00) >> 8;
packet.Build (command, 4);
SendReceive (&packet);
}
lastLiftCmd = PLAYER_ACTARRAY_CMD_POS;
lastLiftPosCmd = cmd;
sippacket->lastLiftPos = cmd.position;
return 0;
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_CMD,PLAYER_ACTARRAY_CMD_HOME,this->lift_id))
{
if (lastLiftCmd == PLAYER_ACTARRAY_CMD_HOME)
return 0;
// For home, just send the lift to up position
command[0] = GRIPPER;
command[1] = ARGINT;
command[2] = LIFTup;
command[3] = 0;
packet.Build (command, 4);
SendReceive (&packet);
lastLiftCmd = PLAYER_ACTARRAY_CMD_HOME;
lastLiftPosCmd.position = 1.0f;
return 0;
}
return -1;
}
///////////////////////////////////////////////////////////////////////////////
// Gripper commands
void P2OS::OpenGripper (void)
{
unsigned char cmd[4];
P2OSPacket packet;
/*
if (sentGripperCmd && lastGripperCmd == PLAYER_GRIPPER_CMD_OPEN)
return;
*/
cmd[0] = GRIPPER;
cmd[1] = ARGINT;
cmd[2] = GRIPopen; // low bits of unsigned 16bit int
cmd[3] = 0; // high bits of unsigned 16bit int
packet.Build (cmd, 4);
SendReceive (&packet);
sentGripperCmd = true;
lastGripperCmd = PLAYER_GRIPPER_CMD_OPEN;
}
void P2OS::CloseGripper (void)
{
unsigned char cmd[4];
P2OSPacket packet;
/*
if (sentGripperCmd && lastGripperCmd == PLAYER_GRIPPER_CMD_CLOSE)
return;
*/
cmd[0] = GRIPPER;
cmd[1] = ARGINT;
cmd[2] = GRIPclose; // low bits of unsigned 16 bit int
cmd[3] = 0; // high bits of unsigned 16bit int
packet.Build (cmd, 4);
SendReceive (&packet);
sentGripperCmd = true;
lastGripperCmd = PLAYER_GRIPPER_CMD_CLOSE;
}
void P2OS::StopGripper (void)
{
unsigned char cmd[4];
P2OSPacket packet;
if (sentGripperCmd && lastGripperCmd == PLAYER_GRIPPER_CMD_STOP)
return;
cmd[0] = GRIPPER;
cmd[1] = ARGINT;
cmd[2] = GRIPstop;
cmd[3] = 0;
packet.Build (cmd, 4);
SendReceive (&packet);
sentGripperCmd = true;
lastGripperCmd = PLAYER_GRIPPER_CMD_STOP;
}
int P2OS::HandleGripperCommand (player_msghdr * hdr, void * data)
{
if (Message::MatchMessage (hdr, PLAYER_MSGTYPE_CMD, PLAYER_GRIPPER_CMD_OPEN, this->gripper_id))
{
OpenGripper ();
return 0;
}
else if (Message::MatchMessage (hdr, PLAYER_MSGTYPE_CMD, PLAYER_GRIPPER_CMD_CLOSE, this->gripper_id))
{
CloseGripper ();
return 0;
}
else if (Message::MatchMessage (hdr, PLAYER_MSGTYPE_CMD, PLAYER_GRIPPER_CMD_STOP, this->gripper_id))
{
StopGripper ();
return 0;
}
return -1;
}
///////////////////////////////////////////////////////////////////////////////
// Arm gripper commands
void P2OS::OpenArmGripper (void)
{
unsigned char command[4];
P2OSPacket packet;
if (sentArmGripperCmd && lastArmGripperCmd == PLAYER_GRIPPER_CMD_OPEN)
return;
command[0] = ARM_POS;
command[1] = ARGINT;
command[2] = sippacket->armJoints[5].max;
command[3] = 6;
packet.Build(command, 4);
SendReceive(&packet);
sippacket->armJointTargetPos[5] = command[2];
sentArmGripperCmd = true;
lastArmGripperCmd = PLAYER_GRIPPER_CMD_OPEN;
}
void P2OS::CloseArmGripper (void)
{
unsigned char command[4];
P2OSPacket packet;
if (sentArmGripperCmd && lastArmGripperCmd == PLAYER_GRIPPER_CMD_CLOSE)
return;
command[0] = ARM_POS;
command[1] = ARGINT;
command[2] = sippacket->armJoints[5].min;
command[3] = 6;
packet.Build(command, 4);
SendReceive(&packet);
sippacket->armJointTargetPos[5] = command[2];
sentArmGripperCmd = true;
lastArmGripperCmd = PLAYER_GRIPPER_CMD_CLOSE;
}
void P2OS::StopArmGripper (void)
{
unsigned char command[4];
P2OSPacket packet;
if (sentArmGripperCmd && lastArmGripperCmd == PLAYER_GRIPPER_CMD_STOP)
return;
command[0] = ARM_STOP;
command[1] = ARGINT;
command[2] = 6;
command[3] = 0;
packet.Build(command, 4);
SendReceive(&packet);
sentArmGripperCmd = true;
lastArmGripperCmd = PLAYER_GRIPPER_CMD_STOP;
}
int P2OS::HandleArmGripperCommand (player_msghdr *hdr, void *data)
{
if (Message::MatchMessage (hdr, PLAYER_MSGTYPE_CMD, PLAYER_GRIPPER_CMD_OPEN, this->armgripper_id))
{
OpenArmGripper ();
return 0;
}
else if (Message::MatchMessage (hdr, PLAYER_MSGTYPE_CMD, PLAYER_GRIPPER_CMD_CLOSE, this->armgripper_id))
{
CloseArmGripper ();
return 0;
}
else if (Message::MatchMessage (hdr, PLAYER_MSGTYPE_CMD, PLAYER_GRIPPER_CMD_STOP, this->armgripper_id))
{
StopArmGripper ();
return 0;
}
return -1;
}
///////////////////////////////////////////////////////////////////////////////
int
P2OS::HandleCommand(player_msghdr * hdr, void* data)
{
int retVal = -1;
struct timeval timeVal;
if(Message::MatchMessage(hdr,
PLAYER_MSGTYPE_CMD,
PLAYER_POSITION2D_CMD_VEL,
this->position_id))
{
// get and send the latest motor command
player_position2d_cmd_vel_t position_cmd;
position_cmd = *(player_position2d_cmd_vel_t*)data;
this->HandlePositionCommand(position_cmd);
retVal = 0;
}
else if(Message::MatchMessage(hdr, PLAYER_MSGTYPE_CMD, PLAYER_AUDIO_CMD_SAMPLE_PLAY, this->audio_id))
{
// get and send the latest audio command, if it's new
player_audio_sample_item_t audio_cmd;
audio_cmd = *(player_audio_sample_item_t*)data;
this->HandleAudioCommand(audio_cmd);
retVal = 0;
}
else if (Message::MatchMessage (hdr, PLAYER_MSGTYPE_CMD, -1, actarray_id))
{
retVal = HandleActArrayCommand (hdr, data);
}
else if (Message::MatchMessage (hdr, PLAYER_MSGTYPE_CMD, -1, limb_id))
{
retVal = HandleLimbCommand (hdr, data);
}
else if (Message::MatchMessage (hdr, PLAYER_MSGTYPE_CMD, -1, lift_id))
{
retVal = HandleLiftCommand (hdr, data);
}
else if (Message::MatchMessage (hdr, PLAYER_MSGTYPE_CMD, -1, gripper_id))
{
retVal = HandleGripperCommand (hdr, data);
}
else if(Message::MatchMessage(hdr, PLAYER_MSGTYPE_CMD, -1, gripper_id))
{
retVal = HandleGripperCommand(hdr, data);
}
else if (Message::MatchMessage (hdr, PLAYER_MSGTYPE_CMD, -1, armgripper_id))
{
retVal = HandleArmGripperCommand (hdr, data);
}
// Update the time of last pulse/command on successful handling of commands
if (retVal == 0 && pulse != -1)
{
gettimeofday (&timeVal, NULL);
lastPulseTime = static_cast<double> (timeVal.tv_sec) + (static_cast<double> (timeVal.tv_usec) / 1e6);
}
return retVal;
}
// I'm going to put my PTZ stuff down here for now.
/************************************************************************/
int
P2OS::SetupPtz()
{
int err;
int error_code;
int pan, tilt;
fprintf(stderr, "Setting up the Canon PTZ Camera.\n");
//err = setPower(0);
do {
//fprintf(stderr, "\nPowering off/on the camera!!!!!!!!!!!!!!\n");
fprintf(stderr, "\nPowering On the Camera.\n");
err = setPower(1);
while (error_code == CAM_ERROR_BUSY)
{
fprintf(stdout, "power on busy: %x\n", error_code);
err = setPower(1);
}
if ((err != 0) &&
(error_code != CAM_ERROR_NONE) && (error_code != CAM_ERROR_MODE))
{
printf("Could not set power on: %x\n", error_code);
setPower(0);
//close(ptz_fd);
return -1;
}
/* Set Host Mode Control */
fprintf(stderr, "\nSeting Host Control mode.\n");
err = setControlMode();
while (error_code == CAM_ERROR_BUSY)
{
printf("control mode busy: %x\n", error_code);
err = setControlMode();
}
if (err)
{
printf("Could not set control mode\n");
setPower(0);
//close(ptz_fd);
return -1;
}
/* Send Init Command */
fprintf(stderr, "\nSendInit()\n");
err = sendInit();
while (error_code == CAM_ERROR_BUSY)
{
fprintf(stdout, "sendInit busy: %x\n", error_code);
err = sendInit();
}
if ((err != 0) && (error_code != CAM_ERROR_NONE) && (error_code != CAM_ERROR_MODE))
{
printf("Could not sendInit off: %x\n", error_code);
setPower(0);
return -1;
}
}while (error_code == CAM_ERROR_MODE);
/* Turn on Notify Command */
/*
fprintf(stderr, "Setting Notify Command on\n");
err = setNotifyCommand();
while (error_code == CAM_ERROR_BUSY)
{
printf("notify command busy: %x\n", error_code);
err = setNotifyCommand();
}
if (err)
{
printf("Could not set notify command\n");
setPower(0);
//close(ptz_fd);
return -1;
}
*/
/* Now Turn Power on. */
/*
fprintf(stderr, "Powering On the Camera.\n");
err = setPower(1);
while (error_code == CAM_ERROR_BUSY)
{
fprintf(stdout, "power on busy: %x\n", error_code);
err = setPower(1);
}
if ((err != 0) &&
(error_code != CAM_ERROR_NONE) && (error_code != CAM_ERROR_MODE))
{
printf("Could not set power on: %x\n", error_code);
setPower(0);
return -1;
}
*/
fprintf(stderr, "\nSetting the default tilt range.\n");
err = setDefaultTiltRange();
while (error_code == CAM_ERROR_BUSY)
{
printf("control mode busy: %x\n", error_code);
err = setDefaultTiltRange();
}
if (err)
{
printf("Could not set default tilt range\n");
setPower(0);
//close(ptz_fd);
return -1;
}
/* try to get current state, just to make sure we actually have a camera */
fprintf(stderr, "\nGetting the Abs Pan Tilt\n");
err = GetAbsPanTilt(&pan,&tilt);
if (err)
{
printf("Couldn't connect to PTZ device most likely because the camera\n"
"is not connected or is connected not to AUX1: %x\n",
error_code);
setPower(0);
//close(ptz_fd);
//ptz_fd = -1;
return(-1);
}
fprintf(stderr, "getAbsPantilt: %d %d\n", pan, tilt);
// Get the Zoom Range. 0 to what
fprintf(stderr, "Getting Max Zoom Range.\n");
err = GetMaxZoom(&maxzoom);
if (err)
{
fprintf(stderr, "Couldn't get max zoom range.\n");
setPower(0);
//close(ptz_fd);
//ptz_fd = -1;
return(-1);
}
fprintf(stderr, "maxzoom value = %i \n", maxzoom);
fprintf(stderr, "Done Initializing the PTZ Camera.\n");
return 0;
}
int
P2OS::SendCommand(unsigned char *str, int len)
{
int err = 0;
P2OSPacket ptz_packet;
P2OSPacket request_pkt;
unsigned char request[4];
// Zero out the Receive Buffer
request[0] = GETAUX;
request[1] = ARGINT;
request[2] = 0;
request[3] = 0;
request_pkt.Build(request,4);
SendReceive(&request_pkt,false);
if(len > MAX_PTZ_COMMAND_LENGTH)
{
fprintf(stderr,
"CANNONvcc4::SendCommand(): message is too large (%d bytes)\n",
len);
return(-1);
}
//err = write(ptz_fd, str, len);
// Since I'm hardcoding this to AUX1, basically we gotta stick the AUX1DATA
// header on this and then give it to the p2os send command.
unsigned char mybuf[MAX_PTZ_COMMAND_LENGTH];
mybuf[0] = TTY2;
mybuf[1] = ARGSTR;
mybuf[2] = len;
// Copy the command
memcpy(&mybuf[3], str, len);
//for (int i = 0; i < len+3; i ++)
// fprintf(stderr, "0x%x ", mybuf[i]);
//fprintf(stderr,"\n");
ptz_packet.Build(mybuf, len+3);
/*
printf("ptz_command packet = ");
ptz_packet.PrintHex();
*/
// Send the packet
this->SendReceive(&ptz_packet, false);
if (err != 0)
{
perror("canonvcc4::Send():write():");
return(-1);
}
return(0);
}
/************************************************************************/
//int
//canonvcc4::SendRequest(unsigned char* str, int len)
int P2OS::SendRequest(unsigned char* str, int len, unsigned char* reply, uint8_t camera)
{
return this->SendCommand(str,len);
}
/************************************************************************/
void
P2OS::PrintPacket(char* str, unsigned char* cmd, int len)
{
for(int i=0;i<len;i++)
printf(" %.2x", cmd[i]);
puts("");
}
/************************************************************************/
int
P2OS::SendAbsPanTilt(int pan, int tilt)
{
unsigned char command[MAX_PTZ_COMMAND_LENGTH];
int convpan, convtilt;
unsigned char buf[5];
int ppan, ttilt;
ppan = pan; ttilt = tilt;
if (abs(pan) > PTZ_PAN_MAX)
{
if(pan < -PTZ_PAN_MAX)
ppan = (int)-PTZ_PAN_MAX;
else
if(pan > PTZ_PAN_MAX)
ppan = (int)PTZ_PAN_MAX;
//puts("Camera pan angle thresholded");
}
if (tilt > PTZ_TILT_MAX)
ttilt = (int)PTZ_TILT_MAX;
else
if(tilt < PTZ_TILT_MIN)
ttilt = (int)PTZ_TILT_MIN;
//puts("Camera pan angle thresholded");
//puts("Camera tilt angle thresholded");
convpan = (int)floor(ppan/.1125) + 0x8000;
convtilt = (int)floor(ttilt/.1125) + 0x8000;
// fprintf(stdout, "ppan: %d ttilt: %d conpan: %d contilt: %d\n",
// ppan,ttilt,convpan,convtilt);
command[0] = 0xFF;
command[1] = 0x30;
command[2] = 0x30;
command[3] = 0x00;
command[4] = 0x62;
// pan position
sprintf((char *)buf, "%X", convpan);
command[5] = buf[0];
command[6] = buf[1];
command[7] = buf[2];
command[8] = buf[3];
// tilt position
sprintf((char *)buf, "%X", convtilt);
command[9] = buf[0];
command[10] = buf[1];
command[11] = buf[2];
command[12] = buf[3];
command[13] = (unsigned char) 0xEF;
SendCommand(command, 14);
// PrintPacket( "sendabspantilt: ", command, 14);
return(ReceiveCommandAnswer(6));
}
/************************************************************************/
int
P2OS::setDefaultTiltRange()
{
unsigned char command[MAX_PTZ_COMMAND_LENGTH];
unsigned char buf[8];
int maxtilt, mintilt;
command[0] = 0xFF;
command[1] = 0x30;
command[2] = 0x30;
command[3] = 0x00;
command[4] = 0x64;
command[5] = 0x31;
mintilt = (int)(floor(PTZ_TILT_MIN/.1125) + 0x8000);
sprintf((char *)buf, "%X", mintilt);
command[6] = buf[0];
command[7] = buf[1];
command[8] = buf[2];
command[9] = buf[3];
// tilt position
maxtilt = (int)(floor(PTZ_TILT_MAX/.1125) + 0x8000);
sprintf((char *)buf, "%X", maxtilt);
command[10] = buf[0];
command[11] = buf[1];
command[12] = buf[2];
command[13] = buf[3];
command[14] = (unsigned char) 0xEF;
SendCommand(command, 15);
// PrintPacket( "setDefaultRange: ", command, 15);
return(ReceiveCommandAnswer(6));
}
/************************************************************************/
int
P2OS::GetAbsPanTilt(int* pan, int* tilt)
{
unsigned char command[MAX_PTZ_COMMAND_LENGTH];
unsigned char reply[MAX_PTZ_REQUEST_LENGTH];
int reply_len;
unsigned char buf[4];
char byte;
unsigned int u_val;
int val;
int i;
command[0] = 0xFF;
command[1] = 0x30;
command[2] = 0x30;
command[3] = 0x00;
command[4] = 0x63;
command[5] = 0xEF;
if (SendRequest(command, 6, reply))
return(-1);
// PrintPacket("getabspantilt: ", command, 6);
//reply_len = ReceiveRequestAnswer(reply,6,14);
reply_len = ReceiveRequestAnswer(reply,14,0);
if ( reply_len != 14 ) {
fprintf(stderr, "Reply Len = %i\n", reply_len);
return -1;
}
// remove the ascii encoding, and put into 4-byte array
for (i = 0; i < 4; i++)
{
byte = reply[i+5];
if (byte < 0x40)
byte = byte - 0x30;
else
byte = byte - 'A' + 10;
buf[i] = byte;
}
// convert the 4-bytes into a number
u_val = buf[0] * 0x1000 + buf[1] * 0x100 + buf[2] * 0x10 + buf[3];
// convert the number to a value that's meaningful, based on camera specs
val = (int)(((int)u_val - (int)0x8000) * 0.1125);
// now set myPan to the response received for where the camera thinks it is
*pan = val;
// repeat the steps for the tilt value
for (i = 0; i < 4; i++)
{
byte = reply[i+9];
if (byte < 0x40)
byte = byte - 0x30;
else
byte = byte - 'A' + 10;
buf[i] = byte;
}
u_val = buf[0] * 0x1000 + buf[1] * 0x100 + buf[2] * 0x10 + buf[3];
val =(int)(((int)u_val - (int)0x8000) * 0.1125);
*tilt = val;
return(0);
}
/************************************************************************/
int
P2OS::GetAbsZoom(int* zoom)
{
unsigned char command[MAX_PTZ_COMMAND_LENGTH];
unsigned char reply[MAX_PTZ_REQUEST_LENGTH];
int reply_len;
char byte;
unsigned char buf[4];
unsigned int u_zoom;
int i;
command[0] = 0xFF;
command[1] = 0x30;
command[2] = 0x30;
command[3] = 0x00;
command[4] = 0xB4;
command[5] = 0x30;
command[6] = 0xEF;
if (SendRequest(command, 7, reply))
return(-1);
// PrintPacket( "getabszoom: ", command, 6);
reply_len = ReceiveRequestAnswer(reply,10,0);
if (reply_len == 6)
return -1;
// remove the ascii encoding, and put into 2 bytes
for (i = 0; i < 4; i++)
{
byte = reply[i + 5];
if (byte < 0x40)
byte = byte - 0x30;
else
byte = byte - 'A' + 10;
buf[i] = byte;
}
// convert the 2 bytes into a number
u_zoom = 0;
for (i = 0; i < 4; i++)
u_zoom += buf[i] * (unsigned int) pow(16.0, (double)(3 - i));
*zoom = u_zoom;
return(0);
}
/************************************************************************/
int
P2OS::SendAbsZoom(int zoom)
{
unsigned char command[MAX_PTZ_COMMAND_LENGTH];
unsigned char buf[5];
int i;
if(zoom < 0)
zoom = 0;
//puts("Camera zoom thresholded");
else
if(zoom > maxzoom){
zoom = maxzoom;
//printf("putting zoom at MAX_ZOOM\n");
}
command[0] = 0xFF;
command[1] = 0x30;
command[2] = 0x30;
command[3] = 0x00;
command[4] = 0xB3;
sprintf((char *)buf, "%4X", zoom);
for (i=0;i<3;i++)
if (buf[i] == ' ')
buf[i] = '0';
// zoom position
command[5] = buf[0];
command[6] = buf[1];
command[7] = buf[2];
command[8] = buf[3];
command[9] = 0xEF;
if (SendCommand(command, 10))
return -1;
//PrintPacket( "setabszoom: ", command, 10);
return (ReceiveCommandAnswer(6));
}
void P2OS::get_ptz_packet(int s1, int s2)
{
//printf("get_ptz_packet()\n");
static const int TIMEOUT = 100;
int packetCount = 0;
unsigned char request[4];
P2OSPacket request_pkt;
bool secondSent = false;
request[0] = GETAUX;
request[1] = ARGINT;
request[2] = s1;
request[3] = 0;
// Reset our receiving buffer.
cb.reset();
//sleep(1);
//Request the request-size back
request_pkt.Build(request,4);
SendReceive(&request_pkt,false);
while ( !cb.gotPacket() )
{
if ( packetCount++ > TIMEOUT ) {
// Give Up We're not getting it.
fprintf(stderr, "Waiting for packet timed out.\n");
return;
}
if ( cb.size() == s1 && !secondSent)
{
if ( s2 > s1 )
{
// We got the first packet size, but we don't have a full packet.
int newsize = s2 - s1;
fprintf(stderr, "Requesting Second Packet of size %i\n", newsize);
request[2] = newsize;
request_pkt.Build(request,4);
secondSent = true;
//cb.printBuf();
SendReceive(&request_pkt,false);
}
else
{
// We got the first packet but don't have a full packet, this is an error.
fprintf(stderr, "Error: Got reply from AUX1 But don't have a full packet.\n");
break;
}
}
// Keep reading data until we get a response from the camera.
//fprintf(stderr, "foo\n");
SendReceive(NULL,false);
}
//fprintf(stderr, "Got ptz_packet: ");
//cb.printBuf();
}
/************************************************************************/
int
P2OS::ReceiveCommandAnswer(int asize)
{
int num;
unsigned char reply[MAX_PTZ_REQUEST_LENGTH];
int len = 0;
unsigned char byte;
int t;
int error_code;
// puts("Receivecommandanswer begin\n");
memset(reply, 0, COMMAND_RESPONSE_BYTES);
get_ptz_packet(asize);
//fprintf(stderr, "Recieved Packet: ");
//cb.printBuf();
for (num = 0; num <= COMMAND_RESPONSE_BYTES + 1; num++)
{
// if we don't get any bytes, or if we've just exceeded the limit
// then return null
//err = read_ptz(&byte, 1);
t = cb.getFromBuf();
if ( t < 0 ) { // Buf Error!
printf("circbuf error!\n");
}
else {
byte = (unsigned char)t;
}
if (byte == (unsigned char)0xFE)
{
reply[0] = byte;
len ++;
break;
}
}
if (len == 0)
return -1;
// we got the header character so keep reading bytes for MAX_RESPONSE_BYTES more
for(num = 1; num <= MAX_PTZ_REQUEST_LENGTH; num++)
{
t = cb.getFromBuf();
if (t < 0)
{
// there are no more bytes, so check the last byte for the footer
if (reply[len - 1] != (unsigned char)0xEF)
{
fputs("canonvcc4::receiveCommandAnswer: Discarding bad packet.",
stderr);
return -1;
}
else
break;
}
else
{
// add the byte to the array
reply[len] = (unsigned char)t;
len ++;
}
}
// Check the response
if (len != 6)
{
fputs("canonvcc4::receiveCommandAnswer:Incorrect number of bytes in response packet.",
stderr);
return -1;
}
// check the header and footer
if (reply[0] != (unsigned char)0xFE || reply[5] != (unsigned char)0xEF)
{
fputs("canonvcc4::receiveCommandAnswer: Bad header or footer character in response packet.", stderr);
return -1;
}
// so far so good. Set myError to the error byte
error_code = reply[3];
//PrintPacket("receivecommandasnwer: ", reply, 6);
if (error_code == CAM_ERROR_NONE)
return 0;
else {
switch(error_code){
case CAM_ERROR_BUSY:
fputs("Error: CAM_ERROR_BUSY\n", stderr);
break;
case CAM_ERROR_PARAM:
fputs("Error: CAM_ERROR_PARAM\n", stderr);
break;
case CAM_ERROR_MODE:
fputs("Error: CAM_ERROR_MODE\n", stderr);
break;
default:
fputs("Error: Unknown error response from camera.\n",stderr);
break;
}
}
return -1;
}
/************************************************************************/
/* These commands often have variable packet lengths, if there is an error,
* there is a smaller packet size. If we request the larger packet size first,
* then we will never get a response back. Because of this, we have to first
* request the smaller size, check if its a full packet, if it's not, request
* the rest of the packet. Also according to the source code for ARIA, we can
* not do more than 2 requests for a single packet, therefor, we can't just
* request 1 byte over and over again.
*
* So here, s1 is the size of the smaller packet.
* And s2 is the size of the larger packet.
*/
int
P2OS::ReceiveRequestAnswer(unsigned char *data, int s1, int s2)
{
int num;
unsigned char reply[MAX_PTZ_REQUEST_LENGTH];
int len = 0;
unsigned char byte;
int t;
int error_code;
memset(reply, 0, MAX_PTZ_REQUEST_LENGTH);
get_ptz_packet(s1, s2);
//cb.printBuf();
for (num = 0; num <= COMMAND_RESPONSE_BYTES + 1; num++)
{
// if we don't get any bytes, or if we've just exceeded the limit
// then return null
t = cb.getFromBuf();
if ( t < 0 ) { // Buf Error!
printf("circbuf error!\n");
}
else {
byte = (unsigned char)t;
}
if (byte == (unsigned char)0xFE)
{
reply[0] = byte;
len ++;
break;
}
}
if (len == 0)
return -1;
// we got the header character so keep reading bytes for MAX_RESPONSE_BYTES more
for(num = 1; num <= MAX_PTZ_REQUEST_LENGTH; num++)
{
t = cb.getFromBuf();
if (t < 0)
{
// there are no more bytes, so check the last byte for the footer
if (reply[len - 1] != (unsigned char)0xEF)
{
fputs("canonvcc4::receiveRequest: Discarding bad packet.",
stderr);
return -1;
}
else
break;
}
else
{
// add the byte to the array
reply[len] = (unsigned char)t;
len ++;
}
}
// Check the response length: pt: 14; zoom: 10
if (len != 6 && len != 8 && len != 10 && len != 14)
{
fputs("Arvcc4::packetHandler: Incorrect number of bytes in response packet.", stderr);
return -1;
}
if (reply[0] != (unsigned char)0xFE ||
reply[len - 1] != (unsigned char)0xEF)
{
fputs("canonvcc4::receiveRequestArvcc4: Bad header or footer character in response packet.", stderr);
return -1;
}
// so far so good. Set myError to the error byte
error_code = reply[3];
// PrintPacket("receiverequestasnwer: ", reply, len);
if (error_code == CAM_ERROR_NONE)
{
memcpy(data, reply, len);
return len;
}
return -1;
}
/************************************************************************/
int
P2OS::setControlMode()
{
unsigned char command[MAX_PTZ_COMMAND_LENGTH];
command[0] = 0xFF;
command[1] = 0x30;
command[2] = 0x30;
command[3] = 0x00;
command[4] = 0x90;
command[5] = 0x30;
command[6] = 0xEF;
if (SendCommand(command, 7))
return -1;
// usleep(5000000);
return (ReceiveCommandAnswer(6));
}
/************************************************************************/
int
P2OS::setNotifyCommand()
{
unsigned char command[MAX_PTZ_COMMAND_LENGTH];
command[0] = 0xFF;
command[1] = 0x30;
command[2] = 0x30;
command[3] = 0x00;
command[4] = 0x94;
command[5] = 0x31;
command[6] = 0xEF;
if (SendCommand(command, 7))
return -1;
// usleep(5000000);
return (ReceiveCommandAnswer(6));
}
/************************************************************************/
int
P2OS::setPower(int on)
{
unsigned char command[MAX_PTZ_COMMAND_LENGTH];
command[0] = 0xFF;
command[1] = 0x30;
command[2] = 0x30;
command[3] = 0x00;
command[4] = 0xA0;
if (on)
command[5] = 0x31;
else
command[5] = 0x30;
command[6] = 0xEF;
if (SendCommand(command, 7))
return -1;
// usleep(5000000);
return (ReceiveCommandAnswer(6));
}
/************************************************************************/
int
P2OS::setOnScreenOff()
{
unsigned char command[MAX_PTZ_COMMAND_LENGTH];
command[0] = 0xFF;
command[1] = 0x30;
command[2] = 0x30;
command[3] = 0x00;
command[4] = 0x91;
command[5] = 0x30;
command[6] = 0x30;
command[7] = 0xEF;
if (SendCommand(command, 8))
return -1;
// usleep(5000000);
return (ReceiveCommandAnswer(6));
}
int P2OS::sendInit()
{
unsigned char command[MAX_PTZ_COMMAND_LENGTH];
command[0] = 0xFF;
command[1] = 0x30;
command[2] = 0x30;
command[3] = 0x00;
command[4] = 0x58;
command[5] = 0x30;
command[6] = 0xEF;
if (SendCommand(command, 7))
return -1;
// usleep(5000000);
return (ReceiveCommandAnswer(6));
}
int P2OS::GetMaxZoom(int * maxzoom){
unsigned char command[MAX_PTZ_COMMAND_LENGTH];
unsigned char reply[MAX_PTZ_REQUEST_LENGTH];
int reply_len;
char byte;
unsigned char buf[4];
unsigned int u_zoom;
int i;
command[0] = 0xFF;
command[1] = 0x30;
command[2] = 0x30;
command[3] = 0x00;
command[4] = 0xB4;
command[5] = 0x33;
command[6] = 0xEF;
if (SendCommand(command, 7))
return -1;
// usleep(5000000);
reply_len = ReceiveRequestAnswer(reply,10,0);
if ( reply_len == 6 ){
return -1;
}
// remove the ascii encoding, and put into 2 bytes
for (i = 0; i < 4; i++)
{
byte = reply[i + 5];
if (byte < 0x40)
byte = byte - 0x30;
else
byte = byte - 'A' + 10;
buf[i] = byte;
}
// convert the 2 bytes into a number
u_zoom = 0;
for (i = 0; i < 4; i++)
u_zoom += buf[i] * (unsigned int) pow(16.0, (double)(3 - i));
*maxzoom = u_zoom;
return 0;
}
/* Circular Buffer To deal with getting data back from AUX */
circbuf::circbuf(int size)
{
this->buf = new unsigned char[size];
this->mysize = size;
this->start = this->end = 0;
}
void circbuf::printBuf(){
int i = start;
printf("circbuf: ");
while ( i != end ){
printf("0x%x ", buf[i]);
i = (i+1)%mysize;
}
printf("\n");
}
void circbuf::putOnBuf(unsigned char c)
{
buf[end] = c;
end = (end+1)%mysize;
if ( end == start )
{
// We're overwriting old data.
start = (start + 1)%mysize;
}
// Check to see if we have the whole packet now. (ends with 0xEF)
if ( c == 0xEF )
{
gotPack = true;
}
}
bool circbuf::haveData()
{
return !(this->start == this->end);
}
int circbuf::getFromBuf()
{
if ( start != end ){
unsigned char ret = buf[start];
start = (start+1)%mysize;
return (int)ret;
}
else
{
return -1;
}
}
int circbuf::size()
{
if ( end > start )
{
return end-start;
}
else if ( start > end )
{
return mysize - start - end - 1;
}
else
{
return 0;
}
}
bool circbuf::gotPacket()
{
return gotPack;
}
void circbuf::reset()
{
memset(buf, 0, mysize);
gotPack = false;
start = end = 0;
}
| 31.339821 | 241 | 0.62097 | [
"geometry",
"object",
"vector",
"3d"
] |
40f5480c9f8446e1184eb4408ab78174ea05eba2 | 1,460 | cpp | C++ | Plugins/UnrealJS/Source/JavascriptUMG/JavascriptListView.cpp | webhacking/Unreal.js | fdbb34464a7a40fb16d1e8510f54e0487aecfa05 | [
"Apache-2.0"
] | null | null | null | Plugins/UnrealJS/Source/JavascriptUMG/JavascriptListView.cpp | webhacking/Unreal.js | fdbb34464a7a40fb16d1e8510f54e0487aecfa05 | [
"Apache-2.0"
] | null | null | null | Plugins/UnrealJS/Source/JavascriptUMG/JavascriptListView.cpp | webhacking/Unreal.js | fdbb34464a7a40fb16d1e8510f54e0487aecfa05 | [
"Apache-2.0"
] | null | null | null | #include "JavascriptUMG.h"
#include "JavascriptListView.h"
#include "JavascriptContext.h"
UJavascriptListView::UJavascriptListView(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
TSharedRef<SWidget> UJavascriptListView::RebuildWidget()
{
MyListView = SNew(SListView< UObject* >)
.SelectionMode(SelectionMode)
.ListItemsSource(&Items)
.ItemHeight(ItemHeight)
.OnGenerateRow(BIND_UOBJECT_DELEGATE(SListView< UObject* >::FOnGenerateRow, HandleOnGenerateRow))
.OnSelectionChanged_Lambda([this](UObject* Object, ESelectInfo::Type SelectInfo){
OnSelectionChanged(Object, SelectInfo);
})
.OnMouseButtonClick_Lambda([this](UObject* Object){
OnClick(Object);
})
.OnMouseButtonDoubleClick_Lambda([this](UObject* Object){
OnDoubleClick(Object);
})
//.OnContextMenuOpening(this, &SSocketManager::OnContextMenuOpening)
//.OnItemScrolledIntoView(this, &SSocketManager::OnItemScrolledIntoView)
// .HeaderRow
// (
// SNew(SHeaderRow)
// .Visibility(EVisibility::Collapsed)
// + SHeaderRow::Column(TEXT("Socket"))
// );
;
return BuildDesignTimeWidget(MyListView.ToSharedRef());
}
void UJavascriptListView::ProcessEvent(UFunction* Function, void* Parms)
{
if (JavascriptContext && JavascriptContext->CallProxyFunction(this, this, Function, Parms))
{
return;
}
Super::ProcessEvent(Function, Parms);
}
void UJavascriptListView::RequestListRefresh()
{
MyListView->RequestListRefresh();
} | 28.076923 | 99 | 0.760274 | [
"object"
] |
40f689f34184e30a50a152933457e991fbaa64c7 | 2,999 | cpp | C++ | stxxl/tests/mng/test_block_manager.cpp | ernstki/kASA | f1d5722442ddce47bdb60406fd7e0636a22499b9 | [
"BSL-1.0"
] | 406 | 2015-01-31T01:37:16.000Z | 2022-03-14T00:58:18.000Z | tests/mng/test_block_manager.cpp | bensuperpc/stxxl | b9e44f0ecba7d7111fbb33f3330c3e53f2b75236 | [
"BSL-1.0"
] | 82 | 2015-01-06T14:06:19.000Z | 2021-05-02T13:30:32.000Z | tests/mng/test_block_manager.cpp | bensuperpc/stxxl | b9e44f0ecba7d7111fbb33f3330c3e53f2b75236 | [
"BSL-1.0"
] | 89 | 2015-02-11T20:01:16.000Z | 2022-03-28T18:20:18.000Z | /***************************************************************************
* tests/mng/test_block_manager.cpp
*
* Part of the STXXL. See http://stxxl.sourceforge.net
*
* Copyright (C) 2002 Roman Dementiev <dementiev@mpi-sb.mpg.de>
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
**************************************************************************/
//! \example mng/test_mng.cpp
//! This is an example of use of completion handlers, \c stxxl::block_manager, and
//! \c stxxl::typed_block
#include <iostream>
#include <stxxl/request>
#include <stxxl/mng>
#include <stxxl/bits/verbose.h>
#define BLOCK_SIZE (1024 * 512)
struct MyType
{
int integer;
//char chars[4];
~MyType() { }
};
struct my_handler
{
void operator () (stxxl::request* req)
{
STXXL_MSG(req << " done, type=" << req->io_type());
}
};
typedef stxxl::typed_block<BLOCK_SIZE, MyType> block_type;
int main()
{
STXXL_MSG(sizeof(MyType) << " " << (BLOCK_SIZE % sizeof(MyType)));
STXXL_MSG(sizeof(block_type) << " " << BLOCK_SIZE);
const unsigned nblocks = 2;
stxxl::BIDArray<BLOCK_SIZE> bids(nblocks);
std::vector<int> disks(nblocks, 2);
stxxl::request_ptr* reqs = new stxxl::request_ptr[nblocks];
stxxl::block_manager* bm = stxxl::block_manager::get_instance();
bm->new_blocks(stxxl::striping(), bids.begin(), bids.end());
block_type* block = new block_type[2];
STXXL_MSG(std::hex);
STXXL_MSG("Allocated block address : " << (stxxl::unsigned_type)(block));
STXXL_MSG("Allocated block address + 1: " << (stxxl::unsigned_type)(block + 1));
STXXL_MSG(std::dec);
unsigned i = 0;
for (i = 0; i < block_type::size; ++i)
{
block->elem[i].integer = i;
//memcpy (block->elem[i].chars, "STXXL", 4);
}
for (i = 0; i < nblocks; ++i)
reqs[i] = block->write(bids[i], my_handler());
std::cout << "Waiting " << std::endl;
stxxl::wait_all(reqs, nblocks);
for (i = 0; i < nblocks; ++i)
{
reqs[i] = block->read(bids[i], my_handler());
reqs[i]->wait();
for (int j = 0; j < block_type::size; ++j)
{
STXXL_CHECK2(j == block->elem[j].integer,
"Error in block " << std::hex << i << " pos: " << j
<< " value read: " << block->elem[j].integer);
}
}
bm->delete_blocks(bids.begin(), bids.end());
delete[] reqs;
delete[] block;
#if 0
// variable-size blocks, not supported currently
BIDArray<0> vbids(nblocks);
for (i = 0; i < nblocks; i++)
vbids[i].size = 1024 + i;
bm->new_blocks(striping(), vbids.begin(), vbids.end());
for (i = 0; i < nblocks; i++)
STXXL_MSG("Allocated block: offset=" << vbids[i].offset << ", size=" << vbids[i].size);
bm->delete_blocks(vbids.begin(), vbids.end());
#endif
}
| 29.693069 | 95 | 0.556185 | [
"vector"
] |
40f798fb7e139e94ba6098fb90ece47ce98e45c7 | 3,698 | cpp | C++ | Scr/lab_hash/src/logfile_parser.cpp | bo-rc/data_structures | d568b240aff9ceaf5c220684358e32643b8b1864 | [
"MIT"
] | null | null | null | Scr/lab_hash/src/logfile_parser.cpp | bo-rc/data_structures | d568b240aff9ceaf5c220684358e32643b8b1864 | [
"MIT"
] | null | null | null | Scr/lab_hash/src/logfile_parser.cpp | bo-rc/data_structures | d568b240aff9ceaf5c220684358e32643b8b1864 | [
"MIT"
] | null | null | null | /**
* @file logfile_parser.cpp
* Implementation of the LogfileParser class.
*
* @author Chase Geigle
* @date Spring 2011
* @date Summer 2012
*/
#include "logfile_parser.h"
#include <iostream>
#include <ctime>
using namespace cs225;
using std::string;
using std::vector;
using std::ifstream;
using std::istringstream;
/**
* Constructs a LogLine from a string (actual physical line in the
* logfile).
*
* @param line The line in the file to extract info from.
*/
LogfileParser::LogLine::LogLine(const string& line)
{
istringstream iss(line);
iss >> customer;
customer = customer.substr(1, customer.length() - 3);
iss >> url;
string dte = "";
string dline;
do
{
iss >> dline;
dte += dline;
} while (iss);
date = time(NULL);
tm* tme = localtime(&date);
strptime(dte.c_str(), "%c", tme);
// force correct DST
tme->tm_isdst = 1;
date = mktime(tme);
}
/**
* Constructs a new LogfileParser from the name of a log file.
*
* @param fname The name of the log file to open.
*/
LogfileParser::LogfileParser(const string& fname) : whenVisitedTable(256)
{
sc_hash_table<string, bool> pageVisitedTable(256);
ifstream infile(fname.c_str());
string line;
while (infile.good())
{
getline(infile, line);
// if the line length is 0, move on to the next loop iteration
if (line.length() == 0)
continue;
// otherwise parse the line and update the hash tables and vector
LogLine ll(line);
/**
* @todo Finish implementing this function.
*
* Given the LogLine above, you should be able to update the member
* variable hash table and any other hash tables necessary to solve
* this problem. This should also build the uniqueURLs member
* vector as well.
*/
pageVisitedTable[ll.url] = true;
auto customer_and_url = ll.customer + ll.url;
if (std::difftime(ll.date, whenVisitedTable[customer_and_url]) > 0)
whenVisitedTable[customer_and_url] = ll.date;
}
for (auto it = pageVisitedTable.begin(); it != pageVisitedTable.end(); ++it)
{
if (it->second)
uniqueURLs.push_back(it->first);
}
}
/**
* Determines if a given customer has ever visited the given url.
*
* @param customer The customer name.
* @param url The url.
* @return A boolean value indicating whether the customer visited the url.
*/
bool LogfileParser::hasVisited(const string& customer, const string& url) const
{
/**
* @todo Implement this function.
*/
auto customer_and_url = customer + url;
return whenVisitedTable.contains(customer_and_url);
}
/**
* Determines *when* a customer last visited a given url. If the customer
* has not visited the given url, the output of this function should be the
* default time_t.
*
* @param customer The customer name.
* @param url The url.
* @return A time_t representing when the customer last visited the given
* url.
*/
time_t LogfileParser::dateVisited(const string& customer,
const string& url) const
{
/**
* @todo Implement this function.
*/
auto customer_and_url = customer + url;
if (whenVisitedTable.contains(customer_and_url))
{
return whenVisitedTable.at(customer_and_url);
}
else
return time_t();
}
/**
* Gets all of the unique urls that have been visited.
*
* @return A vector of urls that were visited in the logfile. Note
* that **there should be no duplicates in this vector**.
*/
vector<string> LogfileParser::uniquePages() const
{
return uniqueURLs;
}
| 25.328767 | 80 | 0.642509 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.