text
stringlengths 5
1.04M
|
|---|
#include "../lua/impl.hpp"
#include "../input/input.hpp"
DEF_LUAIMPLEMENT_PTR_NOCTOR(
rev::Input, Input,
LUAIMPLEMENT_BASE,
NOTHING,
NOTHING,
(name)(getButton)(getAxis)(getHat)(numButtons)(numAxes)(numHats)
(setDeadZone)(setMouseMode)(getMouseMode)(getPointer)
)
DEF_LUAIMPLEMENT_PTR_NOCTOR(
rev::Action, Action,
LUAIMPLEMENT_BASE,
NOTHING,
NOTHING,
(isKeyPressed)(isKeyReleased)(isKeyPressing)(addLink)(remLink)(getState)(getValue)
(getKeyValueSimplified)(linkButtonAsAxis)
)
DEF_LUAIMPLEMENT_PTR_NOCTOR(
rev::Keyboard, Keyboard,
"Input",
(OpenKeyboard),
NOTHING,
NOTHING
)
DEF_LUAIMPLEMENT_PTR_NOCTOR(
rev::Mouse, Mouse,
"Input",
(OpenMouse)(NumMouse),
NOTHING,
NOTHING
)
DEF_LUAIMPLEMENT_PTR_NOCTOR(
rev::Joypad, Joypad,
"Input",
(OpenJoypad)(NumJoypad),
NOTHING,
NOTHING
)
DEF_LUAIMPLEMENT_PTR_NOCTOR(
TPos2D, TPos2D,
LUAIMPLEMENT_BASE,
NOTHING,
(absPos)(relPos)(pressure),
(setNewAbs)(setNewRel)
)
DEF_LUAIMPLEMENT_PTR_NOCTOR(
rev::InputMgr, InputMgr,
LUAIMPLEMENT_BASE,
(LinkButtonAsAxis),
NOTHING,
(makeAction)
)
namespace rev {
void LuaImport::RegisterInputClass(LuaState& lsc) {
RegisterClass<Input>(lsc);
RegisterClass<Action>(lsc);
RegisterClass<Keyboard>(lsc);
RegisterClass<Mouse>(lsc);
RegisterClass<Joypad>(lsc);
RegisterClass<TPos2D>(lsc);
ImportClass(lsc, "System", "input", &mgr_input);
}
}
|
#include "Application.hpp"
#include "States/DummyState.hpp"
#include "States/GameState.hpp"
#include <SFML/Graphics/Text.hpp>
#include <SFML/Window/Event.hpp>
#include <chrono>
typedef std::chrono::high_resolution_clock chrono_clock;
typedef chrono_clock::duration duration;
typedef chrono_clock::time_point time_point;
typedef std::chrono::duration<float> dt_seconds;
Application* Application::s_singleton = nullptr;
Application::Application()
{
if (s_singleton)
throw std::runtime_error("Multiple Application instances");
s_singleton = this;
setCurState(new Game::States::GameState());
}
Application::~Application()
{
if (s_singleton == this)
s_singleton = nullptr;
}
Application& Application::getApplication()
{
return *s_singleton;
}
sf::Font& Application::getDefaultFont() const
{
static sf::Font s_defaultFont;
std::string fonts[] = {
#ifdef SFML_SYSTEM_LINUX
"/usr/share/fonts/corefonts/andalemo.ttf",
"/usr/share/fonts/dejavu/DejaVuSansMono.ttf",
"/usr/share/fonts/liberation-fonts/LiberationMono-Regular.ttf"
#elif defined(SFML_SYSTEM_WINDOWS)
"C:\\Windows\\Fonts\\consola.ttf",
"C:\\Windows\\Fonts\\segoeui.ttf",
"C:\\Windows\\Fonts\\cour.ttf"
#endif
};
if (s_defaultFont.getInfo().family.empty())
for (auto& path : fonts)
if (s_defaultFont.loadFromFile(path))
break;
return s_defaultFont;
}
IState& Application::getCurState()
{
return *m_curState;
}
const IState& Application::getCurState() const
{
return *m_curState;
}
void Application::setCurState(IState* aState)
{
aState->m_app = this;
m_curState.reset(aState);
}
CollisionManager& Application::getCollisionManager()
{
return m_collision;
}
ParticleManager& Application::getParticleManager()
{
return m_particles;
}
ProjectileManager& Application::getProjectileManager()
{
return m_projectiles;
}
sf::RenderWindow& Application::getRenderWindow()
{
return m_window;
}
void Application::run()
{
time_point start = chrono_clock::now(),
end = chrono_clock::now(),
lastFPS = chrono_clock::now();
duration dt;
sf::Event ev;
int realFPS = 0, frames = 0;
m_window.create(sf::VideoMode(800, 600), "LD44", sf::Style::Default, sf::ContextSettings(0, 0, 2));
m_window.setFramerateLimit(150);
m_uiView = m_window.getDefaultView();
while (m_window.isOpen())
{
dt = end - start;
start = chrono_clock::now();
++frames;
if (start - lastFPS > std::chrono::seconds(1))
{
lastFPS = start;
realFPS = frames;
frames = 0;
}
while (m_window.pollEvent(ev))
{
m_curState->handleEvent(ev);
switch (ev.type)
{
case sf::Event::Closed:
m_window.close(); break;
case sf::Event::Resized:
m_uiView.setSize(sf::Vector2f(m_window.getSize()));
m_uiView.setCenter(m_uiView.getSize() / 2.f);
break;
default: break;
}
}
// Pre draw runs before updates, to allow the correct view to be in use
m_curState->preDraw(m_window);
float f_dt = std::chrono::duration_cast<dt_seconds>(dt).count();
m_projectiles.update(f_dt);
m_collision.update(f_dt);
m_curState->update(f_dt);
m_particles.update(f_dt);
m_particles.drawBelow(m_window);
m_curState->draw(m_window);
m_projectiles.draw(m_window);
m_particles.drawAbove(m_window);
m_window.setView(m_uiView);
m_curState->postDraw(m_window);
char fpsCount[32];
snprintf(fpsCount, 32, "FPS: %d", realFPS);
sf::Text stats(fpsCount, getDefaultFont(), 12u);
stats.setFillColor(sf::Color::White);
stats.setOutlineColor(sf::Color::Black);
stats.setOutlineThickness(1.5f);
stats.move(5, 2);
m_window.draw(stats);
m_window.display();
end = chrono_clock::now();
}
m_collision.clear();
}
|
/*
* Copyright 2018, Magazino GmbH, Sebastian Pütz, Jorge Santos Simón
*
* 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.
*
* planner_action.cpp
*
* authors:
* Sebastian Pütz <spuetz@uni-osnabrueck.de>
* Jorge Santos Simón <santos@magazino.eu>
*
*/
#include <sstream>
#include "mbf_abstract_nav/planner_action.h"
namespace mbf_abstract_nav
{
PlannerAction::PlannerAction(
const std::string &name,
const mbf_utility::RobotInformation &robot_info)
: AbstractActionBase(name, robot_info, boost::bind(&mbf_abstract_nav::PlannerAction::run, this, _1, _2)), path_seq_count_(0)
{
ros::NodeHandle private_nh("~");
// informative topics: current navigation goal
current_goal_pub_ = private_nh.advertise<geometry_msgs::PoseStamped>("current_goal", 1);
}
void PlannerAction::run(GoalHandle &goal_handle, AbstractPlannerExecution &execution)
{
const mbf_msgs::GetPathGoal& goal = *(goal_handle.getGoal().get());
mbf_msgs::GetPathResult result;
geometry_msgs::PoseStamped start_pose;
result.path.header.seq = path_seq_count_++;
result.path.header.frame_id = robot_info_.getGlobalFrame();
double tolerance = goal.tolerance;
bool use_start_pose = goal.use_start_pose;
current_goal_pub_.publish(goal.target_pose);
bool planner_active = true;
if(use_start_pose)
{
start_pose = goal.start_pose;
const geometry_msgs::Point& p = start_pose.pose.position;
ROS_DEBUG_STREAM_NAMED(name_, "Use the given start pose (" << p.x << ", " << p.y << ", " << p.z << ").");
}
else
{
// get the current robot pose
if (!robot_info_.getRobotPose(start_pose))
{
result.outcome = mbf_msgs::GetPathResult::TF_ERROR;
result.message = "Could not get the current robot pose!";
goal_handle.setAborted(result, result.message);
ROS_ERROR_STREAM_NAMED(name_, result.message << " Canceling the action call.");
return;
}
else
{
const geometry_msgs::Point& p = start_pose.pose.position;
ROS_DEBUG_STREAM_NAMED(name_, "Got the current robot pose at ("
<< p.x << ", " << p.y << ", " << p.z << ").");
}
}
AbstractPlannerExecution::PlanningState state_planning_input;
std::vector<geometry_msgs::PoseStamped> plan, global_plan;
while (planner_active && ros::ok())
{
// get the current state of the planning thread
state_planning_input = execution.getState();
switch (state_planning_input)
{
case AbstractPlannerExecution::INITIALIZED:
ROS_DEBUG_STREAM_NAMED(name_, "planner state: initialized");
if (!execution.start(start_pose, goal.target_pose, tolerance))
{
result.outcome = mbf_msgs::GetPathResult::INTERNAL_ERROR;
result.message = "Another thread is still planning!";
goal_handle.setAborted(result, result.message);
ROS_ERROR_STREAM_NAMED(name_, result.message << " Canceling the action call.");
planner_active = false;
}
break;
case AbstractPlannerExecution::STARTED:
ROS_DEBUG_STREAM_NAMED(name_, "planner state: started");
break;
case AbstractPlannerExecution::STOPPED:
ROS_DEBUG_STREAM_NAMED(name_, "planner state: stopped");
ROS_WARN_STREAM_NAMED(name_, "Planning has been stopped rigorously!");
result.outcome = mbf_msgs::GetPathResult::STOPPED;
result.message = "Global planner has been stopped!";
goal_handle.setAborted(result, result.message);
planner_active = false;
break;
case AbstractPlannerExecution::CANCELED:
ROS_DEBUG_STREAM_NAMED(name_, "planner state: canceled");
ROS_DEBUG_STREAM_NAMED(name_, "Global planner has been canceled successfully");
result.path.header.stamp = ros::Time::now();
result.outcome = mbf_msgs::GetPathResult::CANCELED;
result.message = "Global planner has been canceled!";
goal_handle.setCanceled(result, result.message);
planner_active = false;
break;
// in progress
case AbstractPlannerExecution::PLANNING:
if (execution.isPatienceExceeded())
{
ROS_INFO_STREAM_NAMED(name_, "Global planner patience has been exceeded! Cancel planning...");
execution.cancel();
}
else
{
ROS_DEBUG_THROTTLE_NAMED(2.0, name_, "planner state: planning");
}
break;
// found a new plan
case AbstractPlannerExecution::FOUND_PLAN:
// set time stamp to now
result.path.header.stamp = ros::Time::now();
plan = execution.getPlan();
ROS_DEBUG_STREAM_NAMED(name_, "planner state: found plan with cost: " << execution.getCost());
if (!transformPlanToGlobalFrame(plan, global_plan))
{
result.outcome = mbf_msgs::GetPathResult::TF_ERROR;
result.message = "Could not transform the plan to the global frame!";
ROS_ERROR_STREAM_NAMED(name_, result.message << " Canceling the action call.");
goal_handle.setAborted(result, result.message);
planner_active = false;
break;
}
if (global_plan.empty())
{
result.outcome = mbf_msgs::GetPathResult::EMPTY_PATH;
result.message = "Global planner returned an empty path!";
ROS_ERROR_STREAM_NAMED(name_, result.message);
goal_handle.setAborted(result, result.message);
planner_active = false;
break;
}
result.path.poses = global_plan;
result.cost = execution.getCost();
result.outcome = execution.getOutcome();
result.message = execution.getMessage();
goal_handle.setSucceeded(result, result.message);
planner_active = false;
break;
// no plan found
case AbstractPlannerExecution::NO_PLAN_FOUND:
ROS_DEBUG_STREAM_NAMED(name_, "planner state: no plan found");
result.outcome = execution.getOutcome();
result.message = execution.getMessage();
goal_handle.setAborted(result, result.message);
planner_active = false;
break;
case AbstractPlannerExecution::MAX_RETRIES:
ROS_DEBUG_STREAM_NAMED(name_, "Global planner reached the maximum number of retries");
result.outcome = execution.getOutcome();
result.message = execution.getMessage();
goal_handle.setAborted(result, result.message);
planner_active = false;
break;
case AbstractPlannerExecution::PAT_EXCEEDED:
ROS_DEBUG_STREAM_NAMED(name_, "Global planner exceeded the patience time");
result.outcome = mbf_msgs::GetPathResult::PAT_EXCEEDED;
result.message = "Global planner exceeded the patience time";
goal_handle.setAborted(result, result.message);
planner_active = false;
break;
case AbstractPlannerExecution::INTERNAL_ERROR:
ROS_FATAL_STREAM_NAMED(name_, "Internal error: Unknown error thrown by the plugin!"); // TODO getMessage from planning
planner_active = false;
result.outcome = mbf_msgs::GetPathResult::INTERNAL_ERROR;
result.message = "Internal error: Unknown error thrown by the plugin!";
goal_handle.setAborted(result, result.message);
break;
default:
result.outcome = mbf_msgs::GetPathResult::INTERNAL_ERROR;
std::ostringstream ss;
ss << "Internal error: Unknown state in a move base flex planner execution with the number: "
<< static_cast<int>(state_planning_input);
result.message = ss.str();
ROS_FATAL_STREAM_NAMED(name_, result.message);
goal_handle.setAborted(result, result.message);
planner_active = false;
}
if (planner_active)
{
// try to sleep a bit
// normally this thread should be woken up from the planner execution thread
// in order to transfer the results to the controller.
boost::mutex mutex;
boost::unique_lock<boost::mutex> lock(mutex);
execution.waitForStateUpdate(boost::chrono::milliseconds(500));
}
} // while (planner_active && ros::ok())
if (!planner_active)
{
ROS_DEBUG_STREAM_NAMED(name_, "\"" << name_ << "\" action ended properly.");
}
else
{
ROS_ERROR_STREAM_NAMED(name_, "\"" << name_ << "\" action has been stopped!");
}
}
bool PlannerAction::transformPlanToGlobalFrame(
std::vector<geometry_msgs::PoseStamped> &plan, std::vector<geometry_msgs::PoseStamped> &global_plan)
{
global_plan.clear();
std::vector<geometry_msgs::PoseStamped>::iterator iter;
bool tf_success = false;
for (iter = plan.begin(); iter != plan.end(); ++iter)
{
geometry_msgs::PoseStamped global_pose;
tf_success = mbf_utility::transformPose(robot_info_.getTransformListener(), robot_info_.getGlobalFrame(), iter->header.stamp,
robot_info_.getTfTimeout(), *iter, robot_info_.getGlobalFrame(), global_pose);
if (!tf_success)
{
ROS_ERROR_STREAM("Can not transform pose from the \"" << iter->header.frame_id << "\" frame into the \""
<< robot_info_.getGlobalFrame() << "\" frame !");
return false;
}
global_plan.push_back(global_pose);
}
return true;
}
} /* namespace mbf_abstract_nav */
|
//
// DepthwiseConvInt8Execution.hpp
// MNN
//
// Created by MNN on 2019/6/19.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef DepthwiseConvInt8Execution_hpp
#define DepthwiseConvInt8Execution_hpp
#include "CommonExecution.hpp"
#include <MNN_generated.h>
#include "Execution.hpp"
#include "core/OpenCLBackend.hpp"
namespace MNN {
namespace OpenCL {
class DepthwiseConvInt8Execution : public Execution {
public:
DepthwiseConvInt8Execution(Backend *backend, const MNN::Op *param);
virtual ~DepthwiseConvInt8Execution();
virtual ErrorCode onExecute(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override;
virtual ErrorCode onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override;
private:
std::vector<int> mStrides{1, 1};
std::vector<int> mPaddings{0, 0};
std::vector<int> mDilations{1, 1};
std::shared_ptr<cl::Buffer> mScaleBuffer;
std::shared_ptr<cl::Buffer> mFilterBuffer;
std::shared_ptr<cl::Buffer> mBiasBuffer;
OpenCLBackend *mOpenCLBackend;
cl::Kernel mKernel;
uint32_t mMaxWorkGroupSize;
const Convolution2DCommon *mConv2dCommonParams;
std::vector<uint32_t> mGlobalWorkSize{1, 1, 1};
std::vector<uint32_t> mLocalWorkSize{1, 1, 1, 1};
};
}
} // namespace MNN
#endif /* DepthwiseConvInt8Execution_hpp */
|
/* NOCHKSRC */
#line 2 "l_filter.c"
#line 4 "l_filter.c"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
#define yy_create_buffer filter_create_buffer
#define yy_delete_buffer filter_delete_buffer
#define yy_flex_debug filter_flex_debug
#define yy_init_buffer filter_init_buffer
#define yy_flush_buffer filter_flush_buffer
#define yy_load_buffer_state filter_load_buffer_state
#define yy_switch_to_buffer filter_switch_to_buffer
#define yyin filterin
#define yyleng filterleng
#define yylex filterlex
#define yylineno filterlineno
#define yyout filterout
#define yyrestart filterrestart
#define yytext filtertext
#define yywrap filterwrap
#define yyalloc filteralloc
#define yyrealloc filterrealloc
#define yyfree filterfree
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 35
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* end standard C headers. */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
#endif /* ! C99 */
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#endif /* ! FLEXINT_H */
#ifdef __cplusplus
/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST
#else /* ! __cplusplus */
/* C99 requires __STDC__ to be defined as 1. */
#if defined (__STDC__)
#define YY_USE_CONST
#endif /* defined (__STDC__) */
#endif /* ! __cplusplus */
#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif
/* Returned upon end-of-file. */
#define YY_NULL 0
/* Promotes a possibly negative, possibly signed char to an unsigned
* integer for use as an array index. If the signed char is negative,
* we want to instead treat it as an 8-bit unsigned char, hence the
* double cast.
*/
#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN (yy_start) = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START (((yy_start) - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE filterrestart(filterin )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#define YY_BUF_SIZE 16384
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
extern int filterleng;
extern FILE *filterin, *filterout;
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
#define YY_LESS_LINENO(n)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up filtertext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
*yy_cp = (yy_hold_char); \
YY_RESTORE_YY_MORE_OFFSET \
(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up filtertext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, (yytext_ptr) )
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
FILE *yy_input_file;
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
yy_size_t yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
int yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via filterrestart()), so that the user can continue scanning by
* just pointing filterin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* Stack of input buffers. */
static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
? (yy_buffer_stack)[(yy_buffer_stack_top)] \
: NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
/* yy_hold_char holds the character lost when filtertext is formed. */
static char yy_hold_char;
static int yy_n_chars; /* number of characters read into yy_ch_buf */
int filterleng;
/* Points to current character in buffer. */
static char *yy_c_buf_p = (char *) 0;
static int yy_init = 0; /* whether we need to initialize */
static int yy_start = 0; /* start state number */
/* Flag which is used to allow filterwrap()'s to do buffer switches
* instead of setting up a fresh filterin. A bit of a hack ...
*/
static int yy_did_buffer_switch_on_eof;
void filterrestart (FILE *input_file );
void filter_switch_to_buffer (YY_BUFFER_STATE new_buffer );
YY_BUFFER_STATE filter_create_buffer (FILE *file,int size );
void filter_delete_buffer (YY_BUFFER_STATE b );
void filter_flush_buffer (YY_BUFFER_STATE b );
void filterpush_buffer_state (YY_BUFFER_STATE new_buffer );
void filterpop_buffer_state (void );
static void filterensure_buffer_stack (void );
static void filter_load_buffer_state (void );
static void filter_init_buffer (YY_BUFFER_STATE b,FILE *file );
#define YY_FLUSH_BUFFER filter_flush_buffer(YY_CURRENT_BUFFER )
YY_BUFFER_STATE filter_scan_buffer (char *base,yy_size_t size );
YY_BUFFER_STATE filter_scan_string (yyconst char *yy_str );
YY_BUFFER_STATE filter_scan_bytes (yyconst char *bytes,int len );
void *filteralloc (yy_size_t );
void *filterrealloc (void *,yy_size_t );
void filterfree (void * );
#define yy_new_buffer filter_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
filterensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
filter_create_buffer(filterin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
filterensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
filter_create_buffer(filterin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
#define filterwrap(n) 1
#define YY_SKIP_YYWRAP
typedef unsigned char YY_CHAR;
FILE *filterin = (FILE *) 0, *filterout = (FILE *) 0;
typedef int yy_state_type;
extern int filterlineno;
int filterlineno = 1;
extern char *filtertext;
#define yytext_ptr filtertext
static yy_state_type yy_get_previous_state (void );
static yy_state_type yy_try_NUL_trans (yy_state_type current_state );
static int yy_get_next_buffer (void );
static void yy_fatal_error (yyconst char msg[] );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up filtertext.
*/
#define YY_DO_BEFORE_ACTION \
(yytext_ptr) = yy_bp; \
filterleng = (size_t) (yy_cp - yy_bp); \
(yy_hold_char) = *yy_cp; \
*yy_cp = '\0'; \
(yy_c_buf_p) = yy_cp;
#define YY_NUM_RULES 21
#define YY_END_OF_BUFFER 22
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info
{
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static yyconst flex_int16_t yy_accept[47] =
{ 0,
3, 3, 0, 0, 22, 20, 3, 8, 1, 6,
4, 5, 20, 16, 16, 21, 9, 21, 20, 20,
7, 21, 2, 21, 20, 3, 14, 14, 16, 20,
11, 12, 10, 20, 20, 13, 2, 20, 17, 20,
20, 15, 20, 18, 19, 0
} ;
static yyconst flex_int32_t yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 2, 4, 5, 1, 1, 1, 6, 1, 7,
8, 9, 10, 1, 10, 1, 1, 11, 12, 12,
12, 12, 12, 12, 12, 12, 12, 1, 1, 13,
14, 15, 1, 1, 16, 17, 17, 17, 18, 19,
1, 1, 1, 1, 1, 20, 1, 1, 1, 1,
1, 21, 22, 23, 24, 1, 1, 25, 1, 1,
1, 1, 1, 1, 1, 1, 16, 17, 17, 17,
18, 19, 1, 1, 1, 1, 1, 20, 1, 1,
1, 1, 1, 21, 22, 23, 24, 1, 1, 25,
1, 1, 1, 26, 1, 27, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1
} ;
static yyconst flex_int32_t yy_meta[28] =
{ 0,
1, 2, 3, 4, 1, 4, 4, 4, 1, 1,
1, 1, 4, 4, 4, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 4, 4
} ;
static yyconst flex_int16_t yy_base[50] =
{ 0,
0, 0, 25, 50, 73, 0, 70, 105, 0, 105,
105, 105, 23, 25, 30, 57, 61, 55, 52, 46,
105, 52, 0, 105, 0, 60, 34, 32, 36, 67,
105, 105, 105, 41, 36, 105, 0, 76, 0, 33,
31, 0, 12, 0, 0, 105, 95, 99, 102
} ;
static yyconst flex_int16_t yy_def[50] =
{ 0,
46, 1, 47, 47, 46, 48, 46, 46, 48, 46,
46, 46, 48, 48, 48, 46, 46, 46, 48, 48,
46, 46, 49, 46, 48, 46, 48, 48, 48, 48,
46, 46, 46, 48, 48, 46, 49, 48, 30, 48,
48, 38, 48, 48, 48, 0, 46, 46, 46
} ;
static yyconst flex_int16_t yy_nxt[133] =
{ 0,
6, 7, 6, 8, 9, 10, 11, 12, 6, 13,
14, 15, 16, 17, 18, 6, 6, 6, 19, 6,
6, 6, 20, 6, 6, 21, 22, 24, 24, 45,
24, 24, 24, 27, 28, 29, 29, 24, 24, 24,
29, 29, 28, 28, 28, 28, 29, 29, 44, 30,
24, 24, 24, 24, 43, 24, 24, 24, 38, 41,
40, 26, 24, 24, 24, 36, 35, 34, 33, 32,
31, 26, 46, 46, 46, 24, 24, 39, 39, 46,
46, 46, 39, 39, 39, 39, 42, 42, 46, 46,
46, 42, 42, 42, 42, 23, 23, 23, 23, 25,
46, 25, 37, 37, 5, 46, 46, 46, 46, 46,
46, 46, 46, 46, 46, 46, 46, 46, 46, 46,
46, 46, 46, 46, 46, 46, 46, 46, 46, 46,
46, 46
} ;
static yyconst flex_int16_t yy_chk[133] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 3, 3, 43,
3, 3, 3, 13, 13, 14, 14, 3, 3, 3,
15, 15, 28, 28, 27, 27, 29, 29, 41, 14,
3, 3, 4, 4, 40, 4, 4, 4, 27, 35,
34, 26, 4, 4, 4, 22, 20, 19, 18, 17,
16, 7, 5, 0, 0, 4, 4, 30, 30, 0,
0, 0, 30, 30, 30, 30, 38, 38, 0, 0,
0, 38, 38, 38, 38, 47, 47, 47, 47, 48,
0, 48, 49, 49, 46, 46, 46, 46, 46, 46,
46, 46, 46, 46, 46, 46, 46, 46, 46, 46,
46, 46, 46, 46, 46, 46, 46, 46, 46, 46,
46, 46
} ;
static yy_state_type yy_last_accepting_state;
static char *yy_last_accepting_cpos;
extern int filter_flex_debug;
int filter_flex_debug = 0;
/* The intent behind this definition is that it'll catch
* any uses of REJECT which flex missed.
*/
#define REJECT reject_used_but_not_detected
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
char *filtertext;
#line 1 "filter.l"
/*
//%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
*/
/*****************************************************************************
* Description: encode/decode/eval LDAP Filters
*
* Originated: April 04, 2002
* Original Author: Mike Day md@soft-hackle.net
* mdd@us.ibm.com
*
* Copyright (c) 2001 - 2003 IBM
* Copyright (c) 2000 - 2003 Michael Day
*
* 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.
*
*****************************************************************************/
#line 66 "filter.l"
#undef YYLMAX
#define YYLMAX 2048
#define YY_NEVER_INTERACTIVE 1
#undef YY_INPUT
#define YY_INPUT(b, r, m) abort()
#define exit(i) abort()
#include "slp_client.h"
#include "y_filter.h"
#include <stdarg.h>
#define filterless yyless
void filtererror(const char *, ...);
/*
extern char *lslp_logPath;
#define yyerror(s) _lslpMsgOut(lslp_logPath, lslpPrintSem, LSLP_LOG_ERRORS, \
NULL, 0, (s), __FILE__, __LINE__);
*/
static int16 heapIndex;
static char *heap;
static char *buf;
static char *_lslp_strdup(const char *s);
void filter_close_lexer(size_t handle);
size_t filter_init_lexer(const char *s);
/* regex macros for the lexer */
/* special lexer states */
/* table size directives */
#define YY_NO_INPUT 1
#line 609 "l_filter.c"
#define INITIAL 0
#define QUOTED_STRING 1
#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
* down here because we want the user's section 1 to have been scanned first.
* The user has a chance to override it with an option.
*/
#include <unistd.h>
#endif
#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif
static int yy_init_globals (void );
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int filterlex_destroy (void );
int filterget_debug (void );
void filterset_debug (int debug_flag );
YY_EXTRA_TYPE filterget_extra (void );
void filterset_extra (YY_EXTRA_TYPE user_defined );
FILE *filterget_in (void );
void filterset_in (FILE * in_str );
FILE *filterget_out (void );
void filterset_out (FILE * out_str );
int filterget_leng (void );
char *filterget_text (void );
int filterget_lineno (void );
void filterset_lineno (int line_number );
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int filterwrap (void );
#else
extern int filterwrap (void );
#endif
#endif
#ifndef yytext_ptr
static void yy_flex_strncpy (char *,yyconst char *,int );
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * );
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void );
#else
static int input (void );
#endif
#endif
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#define YY_READ_BUF_SIZE 8192
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO do { if (fwrite( filtertext, filterleng, 1, filterout )) {} } while (0)
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
unsigned n; \
for ( n = 0; n < max_size && \
(c = getc( filterin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( filterin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = fread(buf, 1, max_size, filterin))==0 && ferror(filterin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(filterin); \
} \
}\
\
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
#endif
/* end tables serialization structures and prototypes */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int filterlex (void);
#define YY_DECL int filterlex (void)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after filtertext and filterleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK break;
#endif
#define YY_RULE_SETUP \
YY_USER_ACTION
/** The main scanner function which does all the work.
*/
YY_DECL
{
register yy_state_type yy_current_state;
register char *yy_cp, *yy_bp;
register int yy_act;
#line 111 "filter.l"
#line 793 "l_filter.c"
if ( !(yy_init) )
{
(yy_init) = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
if ( ! (yy_start) )
(yy_start) = 1; /* first start state */
if ( ! filterin )
filterin = stdin;
if ( ! filterout )
filterout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
filterensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
filter_create_buffer(filterin,YY_BUF_SIZE );
}
filter_load_buffer_state( );
}
while ( 1 ) /* loops until end-of-file is reached */
{
yy_cp = (yy_c_buf_p);
/* Support of filtertext. */
*yy_cp = (yy_hold_char);
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
yy_current_state = (yy_start);
yy_match:
do
{
register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 47 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
++yy_cp;
}
while ( yy_base[yy_current_state] != 105 );
yy_find_action:
yy_act = yy_accept[yy_current_state];
if ( yy_act == 0 )
{ /* have to back up */
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
yy_act = yy_accept[yy_current_state];
}
YY_DO_BEFORE_ACTION;
do_action: /* This label is used only to access EOF actions. */
switch ( yy_act )
{ /* beginning of action switch */
case 0: /* must back up */
/* undo the effects of YY_DO_BEFORE_ACTION */
*yy_cp = (yy_hold_char);
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
goto yy_find_action;
case 1:
YY_RULE_SETUP
#line 113 "filter.l"
{ BEGIN QUOTED_STRING; filterless(0); }
YY_BREAK
case 2:
YY_RULE_SETUP
#line 114 "filter.l"
{
BEGIN INITIAL;
if (NULL != (filterlval.filter_string =
_lslp_strdup(filtertext)))
return OPERAND;
else
return 0L;
}
YY_BREAK
case 3:
YY_RULE_SETUP
#line 124 "filter.l"
{ ; }
YY_BREAK
case 4:
YY_RULE_SETUP
#line 125 "filter.l"
{ filterlval.filter_int = L_PAREN; return L_PAREN ; }
YY_BREAK
case 5:
YY_RULE_SETUP
#line 126 "filter.l"
{ filterlval.filter_int = R_PAREN; return R_PAREN ; }
YY_BREAK
case 6:
YY_RULE_SETUP
#line 127 "filter.l"
{ filterlval.filter_int = OP_AND; return OP_AND ; }
YY_BREAK
case 7:
YY_RULE_SETUP
#line 128 "filter.l"
{ filterlval.filter_int = OP_OR; return OP_OR ; }
YY_BREAK
case 8:
YY_RULE_SETUP
#line 129 "filter.l"
{ filterlval.filter_int = OP_NOT; return OP_NOT ; }
YY_BREAK
case 9:
YY_RULE_SETUP
#line 130 "filter.l"
{ filterlval.filter_int = OP_EQU; return OP_EQU ; }
YY_BREAK
case 10:
YY_RULE_SETUP
#line 131 "filter.l"
{ filterlval.filter_int = OP_GT; return OP_GT ; }
YY_BREAK
case 11:
YY_RULE_SETUP
#line 132 "filter.l"
{ filterlval.filter_int = OP_LT; return OP_LT ; }
YY_BREAK
case 12:
YY_RULE_SETUP
#line 133 "filter.l"
{ filterlval.filter_int = OP_PRESENT; return OP_PRESENT ; }
YY_BREAK
case 13:
YY_RULE_SETUP
#line 134 "filter.l"
{ filterlval.filter_int = OP_APPROX; return OP_APPROX ; }
YY_BREAK
case 14:
#line 138 "filter.l"
case 15:
YY_RULE_SETUP
#line 138 "filter.l"
{
filterlval.filter_int =
strtol(filtertext, (char **) 0, 0) ;
return VAL_INT;
}
YY_BREAK
case 16:
#line 145 "filter.l"
case 17:
YY_RULE_SETUP
#line 145 "filter.l"
{
filterlval.filter_int =
strtoul(filtertext, (char **) 0, 0);
return VAL_INT;
}
YY_BREAK
case 18:
YY_RULE_SETUP
#line 151 "filter.l"
{
filterlval.filter_int = 1; return VAL_BOOL;
}
YY_BREAK
case 19:
YY_RULE_SETUP
#line 156 "filter.l"
{
filterlval.filter_int = 0; return VAL_BOOL;
}
YY_BREAK
case 20:
/* rule 20 can match eol */
YY_RULE_SETUP
#line 161 "filter.l"
{
if (NULL != (filterlval.filter_string =
_lslp_strdup(filtertext)))
return(OPERAND) ;
else
return(0L) ;
}
YY_BREAK
case 21:
YY_RULE_SETUP
#line 171 "filter.l"
ECHO;
YY_BREAK
#line 1001 "l_filter.c"
case YY_STATE_EOF(INITIAL):
case YY_STATE_EOF(QUOTED_STRING):
yyterminate();
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = (yy_hold_char);
YY_RESTORE_YY_MORE_OFFSET
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed filterin at a new source and called
* filterlex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
YY_CURRENT_BUFFER_LVALUE->yy_input_file = filterin;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
(yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state );
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++(yy_c_buf_p);
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
yy_cp = (yy_c_buf_p);
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_END_OF_FILE:
{
(yy_did_buffer_switch_on_eof) = 0;
if ( filterwrap( ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* filtertext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
(yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) =
(yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
(yy_c_buf_p) =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of filterlex */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
static int yy_get_next_buffer (void)
{
register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
register char *source = (yytext_ptr);
register int number_to_move, i;
int ret_val;
if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1;
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
else
{
int num_to_read =
YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
/* just a shorter name for the current buffer */
YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
int yy_c_buf_p_offset =
(int) ((yy_c_buf_p) - b->yy_ch_buf);
if ( b->yy_is_our_buffer )
{
int new_size = b->yy_buf_size * 2;
if ( new_size <= 0 )
b->yy_buf_size += b->yy_buf_size / 8;
else
b->yy_buf_size *= 2;
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
filterrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 );
}
else
/* Can't grow it, we don't own it. */
b->yy_ch_buf = 0;
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR(
"fatal error - scanner input buffer overflow" );
(yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];
num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
number_to_move - 1;
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
(yy_n_chars), (size_t) num_to_read );
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
if ( (yy_n_chars) == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
filterrestart(filterin );
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) filterrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
}
(yy_n_chars) += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
(yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
static yy_state_type yy_get_previous_state (void)
{
register yy_state_type yy_current_state;
register char *yy_cp;
yy_current_state = (yy_start);
for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
{
register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 47 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state )
{
register int yy_is_jam;
register char *yy_cp = (yy_c_buf_p);
register YY_CHAR yy_c = 1;
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 47 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
yy_is_jam = (yy_current_state == 46);
return yy_is_jam ? 0 : yy_current_state;
}
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void)
#else
static int input (void)
#endif
{
int c;
*(yy_c_buf_p) = (yy_hold_char);
if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
/* This was really a NUL. */
*(yy_c_buf_p) = '\0';
else
{ /* need more input */
int offset = (yy_c_buf_p) - (yytext_ptr);
++(yy_c_buf_p);
switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
filterrestart(filterin );
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
if ( filterwrap( ) )
return EOF;
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput();
#else
return input();
#endif
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) = (yytext_ptr) + offset;
break;
}
}
}
c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */
*(yy_c_buf_p) = '\0'; /* preserve filtertext */
(yy_hold_char) = *++(yy_c_buf_p);
return c;
}
#endif /* ifndef YY_NO_INPUT */
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
*
* @note This function does not reset the start condition to @c INITIAL .
*/
void filterrestart (FILE * input_file )
{
if ( ! YY_CURRENT_BUFFER ){
filterensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
filter_create_buffer(filterin,YY_BUF_SIZE );
}
filter_init_buffer(YY_CURRENT_BUFFER,input_file );
filter_load_buffer_state( );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
*
*/
void filter_switch_to_buffer (YY_BUFFER_STATE new_buffer )
{
/* TODO. We should be able to replace this entire function body
* with
* filterpop_buffer_state();
* filterpush_buffer_state(new_buffer);
*/
filterensure_buffer_stack ();
if ( YY_CURRENT_BUFFER == new_buffer )
return;
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
filter_load_buffer_state( );
/* We don't actually know whether we did this switch during
* EOF (filterwrap()) processing, but the only time this flag
* is looked at is after filterwrap() is called, so it's safe
* to go ahead and always set it.
*/
(yy_did_buffer_switch_on_eof) = 1;
}
static void filter_load_buffer_state (void)
{
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
(yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
filterin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
(yy_hold_char) = *(yy_c_buf_p);
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
*
* @return the allocated buffer state.
*/
YY_BUFFER_STATE filter_create_buffer (FILE * file, int size )
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) filteralloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in filter_create_buffer()" );
b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) filteralloc(b->yy_buf_size + 2 );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in filter_create_buffer()" );
b->yy_is_our_buffer = 1;
filter_init_buffer(b,file );
return b;
}
/** Destroy the buffer.
* @param b a buffer created with filter_create_buffer()
*
*/
void filter_delete_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
filterfree((void *) b->yy_ch_buf );
filterfree((void *) b );
}
#ifndef __cplusplus
extern int isatty (int );
#endif /* __cplusplus */
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a filterrestart() or at EOF.
*/
static void filter_init_buffer (YY_BUFFER_STATE b, FILE * file )
{
int oerrno = errno;
filter_flush_buffer(b );
b->yy_input_file = file;
b->yy_fill_buffer = 1;
/* If b is the current buffer, then filter_init_buffer was _probably_
* called from filterrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
*
*/
void filter_flush_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
filter_load_buffer_state( );
}
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
*
*/
void filterpush_buffer_state (YY_BUFFER_STATE new_buffer )
{
if (new_buffer == NULL)
return;
filterensure_buffer_stack();
/* This block is copied from filter_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER)
(yy_buffer_stack_top)++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from filter_switch_to_buffer. */
filter_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
*
*/
void filterpop_buffer_state (void)
{
if (!YY_CURRENT_BUFFER)
return;
filter_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
if ((yy_buffer_stack_top) > 0)
--(yy_buffer_stack_top);
if (YY_CURRENT_BUFFER) {
filter_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
}
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
static void filterensure_buffer_stack (void)
{
int num_to_alloc;
if (!(yy_buffer_stack)) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1;
(yy_buffer_stack) = (struct yy_buffer_state**)filteralloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in filterensure_buffer_stack()" );
memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
(yy_buffer_stack_top) = 0;
return;
}
if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
/* Increase the buffer to prepare for a possible push. */
int grow_size = 8 /* arbitrary grow size */;
num_to_alloc = (yy_buffer_stack_max) + grow_size;
(yy_buffer_stack) = (struct yy_buffer_state**)filterrealloc
((yy_buffer_stack),
num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in filterensure_buffer_stack()" );
/* zero only the new slots.*/
memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
}
}
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE filter_scan_buffer (char * base, yy_size_t size )
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return 0;
b = (YY_BUFFER_STATE) filteralloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in filter_scan_buffer()" );
b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = 0;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
filter_switch_to_buffer(b );
return b;
}
/** Setup the input buffer state to scan a string. The next call to filterlex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
*
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* filter_scan_bytes() instead.
*/
YY_BUFFER_STATE filter_scan_string (yyconst char * yystr )
{
return filter_scan_bytes(yystr,strlen(yystr) );
}
/** Setup the input buffer state to scan the given bytes. The next call to filterlex() will
* scan from a @e copy of @a bytes.
* @param bytes the byte buffer to scan
* @param len the number of bytes in the buffer pointed to by @a bytes.
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE filter_scan_bytes (yyconst char * yybytes, int _yybytes_len )
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
int i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = _yybytes_len + 2;
buf = (char *) filteralloc(n );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in filter_scan_bytes()" );
for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
b = filter_scan_buffer(buf,n );
if ( ! b )
YY_FATAL_ERROR( "bad buffer in filter_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
static void yy_fatal_error (yyconst char* msg )
{
(void) fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up filtertext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
filtertext[filterleng] = (yy_hold_char); \
(yy_c_buf_p) = filtertext + yyless_macro_arg; \
(yy_hold_char) = *(yy_c_buf_p); \
*(yy_c_buf_p) = '\0'; \
filterleng = yyless_macro_arg; \
} \
while ( 0 )
/* Accessor methods (get/set functions) to struct members. */
/** Get the current line number.
*
*/
int filterget_lineno (void)
{
return filterlineno;
}
/** Get the input stream.
*
*/
FILE *filterget_in (void)
{
return filterin;
}
/** Get the output stream.
*
*/
FILE *filterget_out (void)
{
return filterout;
}
/** Get the length of the current token.
*
*/
int filterget_leng (void)
{
return filterleng;
}
/** Get the current token.
*
*/
char *filterget_text (void)
{
return filtertext;
}
/** Set the current line number.
* @param line_number
*
*/
void filterset_lineno (int line_number )
{
filterlineno = line_number;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param in_str A readable stream.
*
* @see filter_switch_to_buffer
*/
void filterset_in (FILE * in_str )
{
filterin = in_str ;
}
void filterset_out (FILE * out_str )
{
filterout = out_str ;
}
int filterget_debug (void)
{
return filter_flex_debug;
}
void filterset_debug (int bdebug )
{
filter_flex_debug = bdebug ;
}
static int yy_init_globals (void)
{
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from filterlex_destroy(), so don't allocate here.
*/
(yy_buffer_stack) = 0;
(yy_buffer_stack_top) = 0;
(yy_buffer_stack_max) = 0;
(yy_c_buf_p) = (char *) 0;
(yy_init) = 0;
(yy_start) = 0;
/* Defined in main.c */
#ifdef YY_STDINIT
filterin = stdin;
filterout = stdout;
#else
filterin = (FILE *) 0;
filterout = (FILE *) 0;
#endif
/* For future reference: Set errno on error, since we are called by
* filterlex_init()
*/
return 0;
}
/* filterlex_destroy is for both reentrant and non-reentrant scanners. */
int filterlex_destroy (void)
{
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
filter_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
filterpop_buffer_state();
}
/* Destroy the stack itself. */
filterfree((yy_buffer_stack) );
(yy_buffer_stack) = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* filterlex() is called, initialization will occur. */
yy_init_globals( );
return 0;
}
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, yyconst char * s2, int n )
{
register int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * s )
{
register int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
void *filteralloc (yy_size_t size )
{
return (void *) malloc( size );
}
void *filterrealloc (void * ptr, yy_size_t size )
{
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return (void *) realloc( (char *) ptr, size );
}
void filterfree (void * ptr )
{
free( (char *) ptr ); /* see filterrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
#line 171 "filter.l"
static char *_lslp_strdup(const char *s)
{
char *p = &heap[heapIndex];
while ((heap[heapIndex++] = *s++))
;
return p;
}
void filter_close_lexer(size_t handle)
{
PEGASUS_ASSERT(handle);
PEGASUS_ASSERT(buf);
PEGASUS_ASSERT(heap);
filter_delete_buffer((YY_BUFFER_STATE)handle);
free(buf);
free(heap);
buf = heap = 0;
}
size_t filter_init_lexer(const char *s)
{
size_t len = strlen(s) + 2;
if (!(heap = (char*)malloc(len)))
{
return 0;
}
if (!(buf = (char*)malloc(len)))
{
free (heap);
return 0;
}
heapIndex = 0;
strcpy(buf, s);
buf[len - 1] = 0;
return ((size_t) filter_scan_buffer(buf, len));
}
/*****
static char *_lslp_strdup_strip_quotes(char *s)
{
char *p = &heap[heapIndex];
do
{
if(*s != '"') heap[heapIndex++] = *s;
}
while ((*s != 0x00) && (heapIndex < 2049) && (++s));
return(p);
}
******/
void filtererror(const char *s, ...)
{
return;
}
/*
int main(int argc, char *argv[])
{
}
*/
|
/*
* Copyright 2018 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 Yukihiro Saito
*/
#include "multi_object_tracker/node.hpp"
#include <string>
#include "multi_object_tracker/data_association/data_association.hpp"
#include "multi_object_tracker/tracker/tracker.hpp"
#define EIGEN_MPL2_ONLY
#include <Eigen/Core>
#include <Eigen/Geometry>
MultiObjectTrackerNode::MultiObjectTrackerNode() : nh_(""), pnh_("~"), tf_listener_(tf_buffer_)
{
sub_ = pnh_.subscribe("input", 1, &MultiObjectTrackerNode::measurementCallback, this);
pub_ = pnh_.advertise<autoware_perception_msgs::DynamicObjectArray>("output", 1, true);
double publish_rate;
pnh_.param<double>("publish_rate", publish_rate, double(30.0));
publish_timer_ = nh_.createTimer(
ros::Duration(1.0 / publish_rate), &MultiObjectTrackerNode::publishTimerCallback, this);
pnh_.param<std::string>("world_frame_id", world_frame_id_, std::string("world"));
}
void MultiObjectTrackerNode::measurementCallback(
const autoware_perception_msgs::DynamicObjectWithFeatureArray::ConstPtr & input_objects_msg)
{
autoware_perception_msgs::DynamicObjectWithFeatureArray input_transformed_objects =
*input_objects_msg;
/* transform to world coordinate */
if (input_objects_msg->header.frame_id != world_frame_id_) {
tf2::Transform tf_world2objets_world;
tf2::Transform tf_world2objets;
tf2::Transform tf_objets_world2objects;
try {
geometry_msgs::TransformStamped ros_world2objets_world;
ros_world2objets_world = tf_buffer_.lookupTransform(
/*target*/ world_frame_id_, /*src*/ input_transformed_objects.header.frame_id,
input_transformed_objects.header.stamp, ros::Duration(0.5));
tf2::fromMsg(ros_world2objets_world.transform, tf_world2objets_world);
} catch (tf2::TransformException & ex) {
ROS_WARN("%s", ex.what());
return;
}
for (size_t i = 0; i < input_transformed_objects.feature_objects.size(); ++i) {
tf2::fromMsg(
input_transformed_objects.feature_objects.at(i).object.state.pose_covariance.pose,
tf_objets_world2objects);
tf_world2objets = tf_world2objets_world * tf_objets_world2objects;
tf2::toMsg(
tf_world2objets,
input_transformed_objects.feature_objects.at(i).object.state.pose_covariance.pose);
}
}
/* tracker prediction */
ros::Time measuremet_time = input_objects_msg->header.stamp;
for (auto itr = list_tracker_.begin(); itr != list_tracker_.end(); ++itr) {
(*itr)->predict(measuremet_time);
}
/* life cycle check */
// TODO
/* global nearest neighboor */
std::unordered_map<int, int> direct_assignment;
std::unordered_map<int, int> reverse_assignment;
Eigen::MatrixXd score_matrix = data_association_.calcScoreMatrix(
input_transformed_objects, list_tracker_); // row : tracker, col : measurement
data_association_.assign(score_matrix, direct_assignment, reverse_assignment);
/* tracker measurement update */
int tracker_idx = 0;
for (auto tracker_itr = list_tracker_.begin(); tracker_itr != list_tracker_.end();
++tracker_itr, ++tracker_idx) {
if (direct_assignment.find(tracker_idx) != direct_assignment.end()) // found
{
(*(tracker_itr))
->updateWithMeasurement(
input_transformed_objects.feature_objects.at(direct_assignment.find(tracker_idx)->second)
.object,
measuremet_time);
} else // not found
{
(*(tracker_itr))->updateWithoutMeasurement();
}
}
/* new tracker */
for (size_t i = 0; i < input_transformed_objects.feature_objects.size(); ++i) {
if (reverse_assignment.find(i) != reverse_assignment.end()) // found
continue;
if (
input_transformed_objects.feature_objects.at(i).object.semantic.type ==
autoware_perception_msgs::Semantic::CAR ||
input_transformed_objects.feature_objects.at(i).object.semantic.type ==
autoware_perception_msgs::Semantic::TRUCK ||
input_transformed_objects.feature_objects.at(i).object.semantic.type ==
autoware_perception_msgs::Semantic::BUS) {
list_tracker_.push_back(std::make_shared<VehicleTracker>(
measuremet_time, input_transformed_objects.feature_objects.at(i).object));
} else if (
input_transformed_objects.feature_objects.at(i).object.semantic.type ==
autoware_perception_msgs::Semantic::PEDESTRIAN) {
list_tracker_.push_back(std::make_shared<PedestrianTracker>(
measuremet_time, input_transformed_objects.feature_objects.at(i).object));
} else if (
input_transformed_objects.feature_objects.at(i).object.semantic.type ==
autoware_perception_msgs::Semantic::BICYCLE ||
input_transformed_objects.feature_objects.at(i).object.semantic.type ==
autoware_perception_msgs::Semantic::MOTORBIKE) {
list_tracker_.push_back(std::make_shared<BicycleTracker>(
measuremet_time, input_transformed_objects.feature_objects.at(i).object));
} else {
// list_tracker_.push_back(std::make_shared<PedestrianTracker>(input_transformed_objects.feature_objects.at(i).object));
}
}
}
void MultiObjectTrackerNode::publishTimerCallback(const ros::TimerEvent & e)
{
// Guard
if (pub_.getNumSubscribers() < 1) return;
/* life cycle check */
for (auto itr = list_tracker_.begin(); itr != list_tracker_.end(); ++itr) {
if (1.0 < (*itr)->getElapsedTimeFromLastUpdate()) {
auto erase_itr = itr;
--itr;
list_tracker_.erase(erase_itr);
}
}
// Create output msg
ros::Time current_time = ros::Time::now();
autoware_perception_msgs::DynamicObjectArray output_msg;
output_msg.header.frame_id = world_frame_id_;
output_msg.header.stamp = current_time;
for (auto itr = list_tracker_.begin(); itr != list_tracker_.end(); ++itr) {
if ((*itr)->getTotalMeasurementCount() < 3) continue;
autoware_perception_msgs::DynamicObject object;
(*itr)->getEstimatedDynamicObject(current_time, object);
output_msg.objects.push_back(object);
}
// Publish
pub_.publish(output_msg);
return;
}
|
/* Copyright (c) 2017, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
*
* All rights reserved.
*
* The Astrobee platform is 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 <ff_util/ff_names.h>
#include <localization_analysis/imu_bias_tester_adder.h>
#include <localization_analysis/utilities.h>
#include <imu_bias_tester/imu_bias_tester_wrapper.h>
namespace localization_analysis {
ImuBiasTesterAdder::ImuBiasTesterAdder(const std::string& input_bag_name, const std::string& output_bag_name)
: input_bag_(input_bag_name, rosbag::bagmode::Read), output_bag_(output_bag_name, rosbag::bagmode::Write) {}
void ImuBiasTesterAdder::AddPredictions() {
rosbag::View view(input_bag_);
for (const rosbag::MessageInstance msg : view) {
if (string_ends_with(msg.getTopic(), TOPIC_GRAPH_LOC_STATE)) {
const ff_msgs::GraphState::ConstPtr localization_msg = msg.instantiate<ff_msgs::GraphState>();
const auto imu_bias_tester_predicted_states =
imu_bias_tester_wrapper_.LocalizationStateCallback(*localization_msg);
SaveImuBiasTesterPredictedStates(imu_bias_tester_predicted_states, output_bag_);
} else if (string_ends_with(msg.getTopic(), TOPIC_HARDWARE_IMU)) {
sensor_msgs::ImuConstPtr imu_msg = msg.instantiate<sensor_msgs::Imu>();
imu_bias_tester_wrapper_.ImuCallback(*imu_msg);
}
output_bag_.write(msg.getTopic(), msg.getTime(), msg);
}
}
} // namespace localization_analysis
|
/*
* Copyright (C) 2020 StreetDrone Limited - All rights reserved
*
* Author: Fionán O'Sullivan
*
* Based on original work of: Efimia Panagiotaki
* 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 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 OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "sd_control.h"
namespace speedcontroller{
uint8_t steer_map[YAW_YAXIS][V_XAXIS] =
{//0m/s <1m/s <2m/s <3m/s <4m/s <5m/s <6m/s <7m/s <8m/s <9m/s
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // 0 deg/s
{40, 30, 20, 18, 11, 10, 7, 7, 6, 3}, // <5 deg/s
{60, 50, 37, 30, 21, 13, 14, 12, 11, 7}, // <10 deg/s
{95, 65, 49, 43, 34, 28, 21, 16, 14, 12}, // <15 deg/s
{100, 97, 90, 77, 50, 35, 28, 23, 21, 17}, // <20 deg/s
{100, 100, 100, 90, 55, 39, 35, 28, 25, 17}, // <25 deg/s
{100, 100, 100, 100, 60, 50, 40, 30, 28, 17}, // <30 deg/s
{100, 100, 100, 100, 65, 60, 45, 35, 32, 17}, // <35 deg/s
{100, 100, 100, 100, 90, 70, 58, 42, 38, 17}, // <40 deg/s
{100, 100, 100, 100, 95, 85, 65, 48, 33, 17}, // <45 deg/s
{100, 100, 100, 100, 100, 90, 70, 55, 45, 17}, // <50 deg/s
{100, 100, 100, 100, 100, 95, 80, 60, 50, 19}, // <55 deg/s
{100, 100, 100, 100, 100, 100, 90, 65, 53, 20}, // <60 deg/s
{100, 100, 100, 100, 100, 100, 100, 70, 55, 45}, // >60 deg/s //Map should be extended if tighter turns needed above 6m/s
};
//FeedForward Calibration
//Map is used to provide feedforward torque (% from 0-100) for a given speed. An additional axis should be considered for gradient
//Note, the FF gain at exactly 0 will be BRAKE_HOLD_TORQUE
int8_t feedforward_torque_map_twizy[V_XAXIS] =
//>0m/s <1m/s <2m/s <3m/s <4m/s <5m/s <6m/s <7m/s <8m/s <9m/s
{33, 33, 33, 34, 35, 38, 39, 40, 41, 42};
int8_t feedforward_torque_map_env200[V_XAXIS] =
//>0m/s <1m/s <2m/s <3m/s <4m/s <5m/s <6m/s <7m/s <8m/s <9m/s
{-5, 0, 2, 6, 7, 8, 10, 12, 13, 15};
//This function calculates the steer angle that will achieve a given angular velocity at a given speed
int8_t CalculateSteerRequest(double TargetAngularVelocity_Dps, double CurrentTwistLinear_Mps){
//For velocitys inbetween match points e.g 1.5 m/s, both the steer angles from the 1m/s and 2m/s
//column are calculated, the final steer linearly interpolated between them.
double SteeringAngleTable_Pc_Speed_1;
double SteeringAngleTable_Pc_Speed_2;
int CalculatedSteeringAngle_Pc; //Final Output steer
//Yaw index and remainder used to interpolate between different yaw values of the steer table
int yaw_index = floor(abs((TargetAngularVelocity_Dps)/YAW_STEPS));
double yaw_index_remainder=abs((TargetAngularVelocity_Dps)/YAW_STEPS) - yaw_index;
//Speed index and remainder used to interpolate between different speed values of the steer table
int speed_index = floor(CurrentTwistLinear_Mps);
double speed_index_remainder=abs(CurrentTwistLinear_Mps) - speed_index;
//handles inputs outside calibrated map size (high speeds and high yaw request)
if(speed_index > V_XAXIS -2){
speed_index = V_XAXIS -2;
}
if(yaw_index > YAW_YAXIS -2){
yaw_index = YAW_YAXIS -2;
}
//yaw interpolation handled below
SteeringAngleTable_Pc_Speed_1 = (1-yaw_index_remainder)*steer_map[yaw_index][speed_index] + yaw_index_remainder*steer_map[yaw_index+1][speed_index];
SteeringAngleTable_Pc_Speed_2 = (1-yaw_index_remainder)*steer_map[yaw_index][speed_index+1] + yaw_index_remainder*steer_map[yaw_index+1][speed_index+1];
//Interpolate for speed
CalculatedSteeringAngle_Pc = (1-speed_index_remainder)*SteeringAngleTable_Pc_Speed_1 + speed_index_remainder*(SteeringAngleTable_Pc_Speed_2);
//Flip sign convention (Positive Yaw request achieved by negative steering Angle in StreetDrone protocol)
if(TargetAngularVelocity_Dps <= 0){
CalculatedSteeringAngle_Pc = CalculatedSteeringAngle_Pc*-1;
}
//If there is not angular velocity request, steering angle is set to 0
if (0 == TargetAngularVelocity_Dps){
CalculatedSteeringAngle_Pc = 0;
//If there is no linear velocity request, steering angle is set to 0
} else if (CurrentTwistLinear_Mps <= 0){
CalculatedSteeringAngle_Pc = 0;
}
//Saturate to Min/Max value
if (CalculatedSteeringAngle_Pc > MAX_STEER_ANG){
CalculatedSteeringAngle_Pc = MAX_STEER_ANG;
} else if(CalculatedSteeringAngle_Pc < MIN_STEER_ANG){
CalculatedSteeringAngle_Pc = MIN_STEER_ANG;
}
return CalculatedSteeringAngle_Pc;
}
int8_t CalculateTorqueRequestTwizy(double TargetLinearVelocity_Mps, double CurrentLinearVelocity_Mps, int& P_Contribution_Pc, int& I_Contribution_Pc, int& D_Contribution_Pc, int& FF_Contribution_Pc){
//Calculate PID Errors
static double LinearVelocityError_Mps;
static double LinearVelocityIntegratedError;
static double LinearVelocityDerivativeError;
int FinalDBWTorqueRequest_Pc; //Variable for final torque value
//Speed index and remainder used to interpolate between different speed values of the steer table
int speed_index = floor(TargetLinearVelocity_Mps);
double speed_index_remainder=abs(TargetLinearVelocity_Mps) - speed_index;
if(speed_index > V_XAXIS -2){
speed_index = V_XAXIS -2;
}
//Reverse currently not suppported. If a negative speed request is received, we clamp it to 0 (standstill)
if (TargetLinearVelocity_Mps <= 0) {
TargetLinearVelocity_Mps = 0;
FF_Contribution_Pc = 0;
}else{
//Calculate Feedforward contribution
FF_Contribution_Pc = (1-speed_index_remainder)*feedforward_torque_map_twizy[speed_index] + speed_index_remainder*feedforward_torque_map_twizy[speed_index+1];
}
LinearVelocityError_Mps = TargetLinearVelocity_Mps - CurrentLinearVelocity_Mps; //The error between current speed and target speed
LinearVelocityDerivativeError = LinearVelocityError_Mps - PreviousLinearVelocityError_Mps; //The difference between current error and error on last cycle
LinearVelocityIntegratedError = LinearVelocityIntegratedError + LinearVelocityError_Mps; //The accumulated error over time
if ((TargetLinearVelocity_Mps == 0 && CurrentLinearVelocity_Mps == 0)){
P_Contribution_Pc = 0;
I_Contribution_Pc = 0;
D_Contribution_Pc =0;
FF_Contribution_Pc = BRAKE_HOLD_TORQUE_TWIZY; //If we currently have a speed target of 0 (standstill), and are not moving, lightly hold the vehicle still by gently braking
} else if (abs(LinearVelocityError_Mps) < ANTI_FUSSINESS_TWIZY){
//PID remain the same. I gain = 0. This resets the I gain so we don't have to "unwind"
LinearVelocityIntegratedError = 0;
I_Contribution_Pc = 0;
//P, D and FF fails maintain last value
} else if ((TargetLinearVelocity_Mps == 0 && CurrentLinearVelocity_Mps > 0)){ //Use braking gains if we wish to slow down to a standstill (Emergency stop or final stop).
P_Contribution_Pc = LinearVelocityError_Mps * Kp_Speed_FullStop_Braking_Twizy;
I_Contribution_Pc = LinearVelocityIntegratedError * Ki_Speed_FullStop_Braking_Twizy;
D_Contribution_Pc = LinearVelocityDerivativeError * Kd_Speed_FullStop_Braking_Twizy;
}else if (LinearVelocityError_Mps < - ANTI_FUSSINESS_TWIZY){ //When we are going too fast, we reduce speed with a different set of gains. (this allows us to account for vehicle overrun/coasting)
P_Contribution_Pc = LinearVelocityError_Mps * Kp_Speed_Retd_Twizy;
I_Contribution_Pc = LinearVelocityIntegratedError * Ki_Speed_Retd_Twizy;
D_Contribution_Pc = LinearVelocityDerivativeError * Kd_Speed_Retd_Twizy;
} else { //else use the calculated errors
P_Contribution_Pc = LinearVelocityError_Mps * Kp_Speed_Twizy;
I_Contribution_Pc = LinearVelocityIntegratedError * Ki_Speed_Twizy;
D_Contribution_Pc = LinearVelocityDerivativeError * Kd_Speed_Twizy;
}
//I gain Anti windup Strategy
if (I_Contribution_Pc > MAX_ABS_I_CONTRIBUTION_TWIZY){ //I Gain saturation
I_Contribution_Pc = MAX_ABS_I_CONTRIBUTION_TWIZY;
} else if (I_Contribution_Pc < -MAX_ABS_I_CONTRIBUTION_TWIZY){
I_Contribution_Pc = - MAX_ABS_I_CONTRIBUTION_TWIZY;
}
if(CurrentLinearVelocity_Mps < ANTI_FUSSINESS_TWIZY){ //Prevents I gain winding up when sitting still with handbrake on
I_Contribution_Pc = 0;
}
if(abs(LinearVelocityError_Mps) > I_GAIN_ERROR_BAND_TWIZY){ //I Gain should only influence the system in a band about the setpoint.
LinearVelocityIntegratedError = 0;
I_Contribution_Pc = 0;
}
FinalDBWTorqueRequest_Pc = P_Contribution_Pc + I_Contribution_Pc + D_Contribution_Pc + FF_Contribution_Pc;
//Impose limits on the torque if greater than or less than maximum and minimum values
if (FinalDBWTorqueRequest_Pc > MAX_TORQUE_TWIZY){
FinalDBWTorqueRequest_Pc = MAX_TORQUE_TWIZY;
} else if(FinalDBWTorqueRequest_Pc < MIN_TORQUE_TWIZY){
FinalDBWTorqueRequest_Pc = MIN_TORQUE_TWIZY;
}
//Remember previous variables for next cycle
PreviousLinearVelocityError_Mps = LinearVelocityError_Mps;
return (int8_t)FinalDBWTorqueRequest_Pc;
}
int8_t CalculateTorqueRequestEnv200(double TargetLinearVelocity_Mps, double CurrentLinearVelocity_Mps, int& P_Contribution_Pc, int& I_Contribution_Pc, int& D_Contribution_Pc, int& FF_Contribution_Pc){
//Calculate PID Errors
static double LinearVelocityError_Mps;
static double LinearVelocityIntegratedError;
static double LinearVelocityDerivativeError;
int FinalDBWTorqueRequest_Pc; //Variable for final torque value
//Speed index and remainder used to interpolate between different speed values of the steer table
int speed_index = floor(TargetLinearVelocity_Mps);
double speed_index_remainder=abs(TargetLinearVelocity_Mps) - speed_index;
if(speed_index > V_XAXIS -2){
speed_index = V_XAXIS -2;
}
//Reverse currently not suppported. If a negative speed request is received, we clamp it to 0 (standstill)
if (TargetLinearVelocity_Mps <= 0) {
TargetLinearVelocity_Mps = 0;
FF_Contribution_Pc = 0;
}else{
//Calculate Feedforward contribution
FF_Contribution_Pc = (1-speed_index_remainder)*feedforward_torque_map_env200[speed_index] + speed_index_remainder*feedforward_torque_map_env200[speed_index+1];
}
LinearVelocityError_Mps = TargetLinearVelocity_Mps - CurrentLinearVelocity_Mps; //The error between current speed and target speed
LinearVelocityDerivativeError = LinearVelocityError_Mps - PreviousLinearVelocityError_Mps; //The difference between current error and error on last cycle
LinearVelocityIntegratedError = LinearVelocityIntegratedError + LinearVelocityError_Mps; //The accumulated error over time
if ((TargetLinearVelocity_Mps == 0 && CurrentLinearVelocity_Mps == 0)){
P_Contribution_Pc = 0;
I_Contribution_Pc = 0;
D_Contribution_Pc =0;
FF_Contribution_Pc = BRAKE_HOLD_TORQUE_ENV200; //If we currently have a speed target of 0 (standstill), and are not moving, lightly hold the vehicle still by gently braking
} else if (abs(LinearVelocityError_Mps) < ANTI_FUSSINESS_ENV200){
//PID remain the same. I gain = 0. This resets the I gain so we don't have to "unwind"
LinearVelocityIntegratedError = 0;
I_Contribution_Pc = 0;
//P, D and FF fails maintain last value
} else if ((TargetLinearVelocity_Mps == 0 && CurrentLinearVelocity_Mps > 0)){ //Use braking gains if we wish to slow down to a standstill (Emergency stop or final stop).
P_Contribution_Pc = LinearVelocityError_Mps * Kp_Speed_FullStop_Braking_Env200;
I_Contribution_Pc = LinearVelocityIntegratedError * Ki_Speed_FullStop_Braking_Env200;
D_Contribution_Pc = LinearVelocityDerivativeError * Kd_Speed_FullStop_Braking_Env200;
}else if (LinearVelocityError_Mps < - ANTI_FUSSINESS_ENV200){ //When we are going too fast, we reduce speed with a different set of gains. (this allows us to account for vehicle overrun/coasting)
P_Contribution_Pc = LinearVelocityError_Mps * Kp_Speed_Retd_Env200;
I_Contribution_Pc = LinearVelocityIntegratedError * Ki_Speed_Retd_Env200;
D_Contribution_Pc = LinearVelocityDerivativeError * Kd_Speed_Retd_Env200;
} else { //else use the calculated errors
P_Contribution_Pc = LinearVelocityError_Mps * Kp_Speed_Env200;
I_Contribution_Pc = LinearVelocityIntegratedError * Ki_Speed_Env200;
D_Contribution_Pc = LinearVelocityDerivativeError * Kd_Speed_Env200;
}
//I gain Anti windup Strategy
if (I_Contribution_Pc > MAX_ABS_I_CONTRIBUTION_ENV200){ //I Gain saturation
I_Contribution_Pc = MAX_ABS_I_CONTRIBUTION_ENV200;
} else if (I_Contribution_Pc < -MAX_ABS_I_CONTRIBUTION_ENV200){
I_Contribution_Pc = - MAX_ABS_I_CONTRIBUTION_ENV200;
}
if(CurrentLinearVelocity_Mps < ANTI_FUSSINESS_ENV200){ //Prevents I gain winding up when sitting still with handbrake on
I_Contribution_Pc = 0;
}
if(abs(LinearVelocityError_Mps) > I_GAIN_ERROR_BAND_ENV200){ //I Gain should only influence the system in a band about the setpoint.
LinearVelocityIntegratedError = 0;
I_Contribution_Pc = 0;
}
FinalDBWTorqueRequest_Pc = P_Contribution_Pc + I_Contribution_Pc + D_Contribution_Pc + FF_Contribution_Pc;
//Impose limits on the torque if greater than or less than maximum and minimum values
if (FinalDBWTorqueRequest_Pc > MAX_TORQUE_ENV200){
FinalDBWTorqueRequest_Pc = MAX_TORQUE_ENV200;
} else if(FinalDBWTorqueRequest_Pc < MIN_TORQUE_ENV200){
FinalDBWTorqueRequest_Pc = MIN_TORQUE_ENV200;
}
//Remember previous variables for next cycle
PreviousLinearVelocityError_Mps = LinearVelocityError_Mps;
return (int8_t)FinalDBWTorqueRequest_Pc;
}
}
|
/**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* 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 Server Side 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.
*/
#include "mongo/platform/basic.h"
#include "mongo/base/data_view.h"
#include "mongo/bson/bson_depth.h"
#include "mongo/bson/bson_validate.h"
#include "mongo/db/jsobj.h"
#include "mongo/logv2/log.h"
#include "mongo/platform/random.h"
#include "mongo/unittest/unittest.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kTest
namespace {
using namespace mongo;
using std::endl;
using std::unique_ptr;
void appendInvalidStringElement(const char* fieldName, BufBuilder* bb) {
// like a BSONObj string, but without a NUL terminator.
bb->appendChar(String);
bb->appendStr(fieldName, /*withNUL*/ true);
bb->appendNum(4);
bb->appendStr("asdf", /*withNUL*/ false);
}
TEST(BSONValidate, Basic) {
BSONObj x;
ASSERT_TRUE(x.valid());
x = BSON("x" << 1);
ASSERT_TRUE(x.valid());
}
TEST(BSONValidate, RandomData) {
PseudoRandom r(17);
int numValid = 0;
int numToRun = 1000;
long long jsonSize = 0;
for (int i = 0; i < numToRun; i++) {
int size = 1234;
char* x = new char[size];
DataView(x).write(tagLittleEndian(size));
for (int i = 4; i < size; i++) {
x[i] = r.nextInt32(255);
}
x[size - 1] = 0;
BSONObj o(x);
ASSERT_EQUALS(size, o.objsize());
if (o.valid()) {
numValid++;
jsonSize += o.jsonString().size();
ASSERT_OK(validateBSON(o.objdata(), o.objsize()));
} else {
ASSERT_NOT_OK(validateBSON(o.objdata(), o.objsize()));
}
delete[] x;
}
LOGV2(20104,
"RandomData: didn't crash valid/total: {numValid}/{numToRun} (want few valid ones) "
"jsonSize: {jsonSize}",
"numValid"_attr = numValid,
"numToRun"_attr = numToRun,
"jsonSize"_attr = jsonSize);
}
TEST(BSONValidate, MuckingData1) {
BSONObj theObject;
{
BSONObjBuilder b;
b.append("name", "eliot was here");
b.append("yippee", "asd");
BSONArrayBuilder a(b.subarrayStart("arr"));
for (int i = 0; i < 100; i++) {
a.append(BSON("x" << i << "who"
<< "me"
<< "asd"
<< "asd"));
}
a.done();
b.done();
theObject = b.obj();
}
int numValid = 0;
int numToRun = 1000;
long long jsonSize = 0;
for (int i = 4; i < theObject.objsize() - 1; i++) {
BSONObj mine = theObject.copy();
char* data = const_cast<char*>(mine.objdata());
data[i] = 0xc8U;
numToRun++;
if (mine.valid()) {
numValid++;
jsonSize += mine.jsonString().size();
ASSERT_OK(validateBSON(mine.objdata(), mine.objsize()));
} else {
ASSERT_NOT_OK(validateBSON(mine.objdata(), mine.objsize()));
}
}
LOGV2(20105,
"MuckingData1: didn't crash valid/total: {numValid}/{numToRun} (want few valid ones) "
"jsonSize: {jsonSize}",
"numValid"_attr = numValid,
"numToRun"_attr = numToRun,
"jsonSize"_attr = jsonSize);
}
TEST(BSONValidate, Fuzz) {
int64_t seed = time(nullptr);
LOGV2(20106, "BSONValidate Fuzz random seed: {seed}", "seed"_attr = seed);
PseudoRandom randomSource(seed);
BSONObj original =
BSON("one" << 3 << "two" << 5 << "three" << BSONObj() << "four"
<< BSON("five" << BSON("six" << 11)) << "seven"
<< BSON_ARRAY("a"
<< "bb"
<< "ccc" << 5)
<< "eight" << BSONDBRef("rrr", OID("01234567890123456789aaaa")) << "_id"
<< OID("deadbeefdeadbeefdeadbeef") << "nine"
<< BSONBinData("\x69\xb7", 2, BinDataGeneral) << "ten"
<< Date_t::fromMillisSinceEpoch(44) << "eleven" << BSONRegEx("foooooo", "i"));
int32_t fuzzFrequencies[] = {2, 10, 20, 100, 1000};
for (size_t i = 0; i < sizeof(fuzzFrequencies) / sizeof(int32_t); ++i) {
int32_t fuzzFrequency = fuzzFrequencies[i];
// Copy the 'original' BSONObj to 'buffer'.
unique_ptr<char[]> buffer(new char[original.objsize()]);
memcpy(buffer.get(), original.objdata(), original.objsize());
// Randomly flip bits in 'buffer', with probability determined by 'fuzzFrequency'. The
// first four bytes, representing the size of the object, are excluded from bit
// flipping.
for (int32_t byteIdx = 4; byteIdx < original.objsize(); ++byteIdx) {
for (int32_t bitIdx = 0; bitIdx < 8; ++bitIdx) {
if (randomSource.nextInt32(fuzzFrequency) == 0) {
reinterpret_cast<unsigned char&>(buffer[byteIdx]) ^= (1U << bitIdx);
}
}
}
BSONObj fuzzed(buffer.get());
// There is no assert here because there is no other BSON validator oracle
// to compare outputs against (BSONObj::valid() is a wrapper for validateBSON()).
// Thus, the reason for this test is to ensure that validateBSON() doesn't trip
// any ASAN or UBSAN check when fed fuzzed input.
validateBSON(fuzzed.objdata(), fuzzed.objsize()).isOK();
}
}
TEST(BSONValidateFast, Empty) {
BSONObj x;
ASSERT_OK(validateBSON(x.objdata(), x.objsize()));
}
TEST(BSONValidateFast, RegEx) {
BSONObjBuilder b;
b.appendRegex("foo", "i");
BSONObj x = b.obj();
ASSERT_OK(validateBSON(x.objdata(), x.objsize()));
}
TEST(BSONValidateFast, Simple0) {
BSONObj x;
ASSERT_OK(validateBSON(x.objdata(), x.objsize()));
x = BSON("foo" << 17 << "bar"
<< "eliot");
ASSERT_OK(validateBSON(x.objdata(), x.objsize()));
}
TEST(BSONValidateFast, Simple2) {
char buf[64];
for (int i = 1; i <= JSTypeMax; i++) {
BSONObjBuilder b;
sprintf(buf, "foo%d", i);
b.appendMinForType(buf, i);
sprintf(buf, "bar%d", i);
b.appendMaxForType(buf, i);
BSONObj x = b.obj();
ASSERT_OK(validateBSON(x.objdata(), x.objsize()));
}
}
TEST(BSONValidateFast, Simple3) {
BSONObjBuilder b;
char buf[64];
for (int i = 1; i <= JSTypeMax; i++) {
sprintf(buf, "foo%d", i);
b.appendMinForType(buf, i);
sprintf(buf, "bar%d", i);
b.appendMaxForType(buf, i);
}
BSONObj x = b.obj();
ASSERT_OK(validateBSON(x.objdata(), x.objsize()));
}
TEST(BSONValidateFast, NestedObject) {
BSONObj x = BSON("a" << 1 << "b"
<< BSON("c" << 2 << "d" << BSONArrayBuilder().obj() << "e"
<< BSON_ARRAY("1" << 2 << 3)));
ASSERT_OK(validateBSON(x.objdata(), x.objsize()));
ASSERT_NOT_OK(validateBSON(x.objdata(), x.objsize() / 2));
}
TEST(BSONValidateFast, AllTypesSimple) {
BSONObj x = BSON(
"1float" << 1.5 // 64-bit binary floating point
<< "2string"
<< "Hello" // UTF-8 string
<< "3document" << BSON("a" << 1) // Embedded document
<< "4array" << BSON_ARRAY(1 << 2) // Array
<< "5bindata" << BSONBinData("", 0, BinDataGeneral) // Binary data
<< "6undefined" << BSONUndefined // Undefined (value) -- Deprecated
<< "7objectid" << OID("deadbeefdeadbeefdeadbeef") // ObjectId
<< "8boolean" << true // Boolean
<< "9datetime" << DATENOW // UTC datetime
<< "10null" << BSONNULL // Null value
<< "11regex" << BSONRegEx("reg.ex") // Regular Expression
<< "12dbref"
<< BSONDBRef("db", OID("dbdbdbdbdbdbdbdbdbdbdbdb")) // DBPointer -- Deprecated
<< "13code" << BSONCode("(function(){})();") // JavaScript code
<< "14symbol" << BSONSymbol("symbol") // Symbol. Deprecated
<< "15code_w_s"
<< BSONCodeWScope("(function(){})();", BSON("a" << 1)) // JavaScript code w/ scope
<< "16int" << 42 // 32-bit integer
<< "17timestamp" << Timestamp(1, 2) // Timestamp
<< "18long" << 0x0123456789abcdefll // 64-bit integer
<< "19decimal" << Decimal128("0.30") // 128-bit decimal floating point
);
ASSERT_OK(validateBSON(x.objdata(), x.objsize()));
}
TEST(BSONValidateFast, ErrorWithId) {
BufBuilder bb;
BSONObjBuilder ob(bb);
ob.append("_id", 1);
appendInvalidStringElement("not_id", &bb);
const BSONObj x = ob.done();
const Status status = validateBSON(x.objdata(), x.objsize());
ASSERT_NOT_OK(status);
ASSERT_EQUALS(
status.reason(),
"Not null terminated string in element with field name 'not_id' in object with _id: 1");
}
TEST(BSONValidateFast, ErrorBeforeId) {
BufBuilder bb;
BSONObjBuilder ob(bb);
appendInvalidStringElement("not_id", &bb);
ob.append("_id", 1);
const BSONObj x = ob.done();
const Status status = validateBSON(x.objdata(), x.objsize());
ASSERT_NOT_OK(status);
ASSERT_EQUALS(status.reason(),
"Not null terminated string in element with field name 'not_id' in object with "
"unknown _id");
}
TEST(BSONValidateFast, ErrorNoId) {
BufBuilder bb;
BSONObjBuilder ob(bb);
appendInvalidStringElement("not_id", &bb);
const BSONObj x = ob.done();
const Status status = validateBSON(x.objdata(), x.objsize());
ASSERT_NOT_OK(status);
ASSERT_EQUALS(status.reason(),
"Not null terminated string in element with field name 'not_id' in object with "
"unknown _id");
}
TEST(BSONValidateFast, ErrorIsInId) {
BufBuilder bb;
BSONObjBuilder ob(bb);
appendInvalidStringElement("_id", &bb);
const BSONObj x = ob.done();
const Status status = validateBSON(x.objdata(), x.objsize());
ASSERT_NOT_OK(status);
ASSERT_EQUALS(
status.reason(),
"Not null terminated string in element with field name '_id' in object with unknown _id");
}
TEST(BSONValidateFast, NonTopLevelId) {
BufBuilder bb;
BSONObjBuilder ob(bb);
ob.append("not_id1",
BSON("_id"
<< "not the real _id"));
appendInvalidStringElement("not_id2", &bb);
const BSONObj x = ob.done();
const Status status = validateBSON(x.objdata(), x.objsize());
ASSERT_NOT_OK(status);
ASSERT_EQUALS(status.reason(),
"Not null terminated string in element with field name 'not_id2' in object with "
"unknown _id");
}
TEST(BSONValidateFast, ErrorInNestedObjectWithId) {
BufBuilder bb;
BSONObjBuilder ob(bb);
ob.append("x", 2.0);
appendInvalidStringElement("invalid", &bb);
const BSONObj nestedInvalid = ob.done();
const BSONObj x = BSON("_id" << 1 << "nested"
<< BSON_ARRAY("a"
<< "b" << nestedInvalid));
const Status status = validateBSON(x.objdata(), x.objsize());
ASSERT_NOT_OK(status);
ASSERT_EQUALS(status.reason(),
"Not null terminated string in element with field name 'nested.2.invalid' "
"in object with _id: 1");
}
TEST(BSONValidateFast, StringHasSomething) {
BufBuilder bb;
BSONObjBuilder ob(bb);
bb.appendChar(String);
bb.appendStr("x", /*withNUL*/ true);
bb.appendNum(0);
const BSONObj x = ob.done();
ASSERT_EQUALS(5 // overhead
+ 1 // type
+ 2 // name
+ 4 // size
,
x.objsize());
ASSERT_NOT_OK(validateBSON(x.objdata(), x.objsize()));
}
TEST(BSONValidateFast, BoolValuesAreValidated) {
BSONObjBuilder bob;
bob.append("x", false);
const BSONObj obj = bob.done();
ASSERT_OK(validateBSON(obj.objdata(), obj.objsize()));
const BSONElement x = obj["x"];
// Legal, because we know that the BufBuilder gave
// us back some heap memory, which isn't oringinally const.
auto writable = const_cast<char*>(x.value());
for (int val = std::numeric_limits<char>::min();
val != (int(std::numeric_limits<char>::max()) + 1);
++val) {
*writable = static_cast<char>(val);
if ((val == 0) || (val == 1)) {
ASSERT_OK(validateBSON(obj.objdata(), obj.objsize()));
} else {
ASSERT_NOT_OK(validateBSON(obj.objdata(), obj.objsize()));
}
}
}
TEST(BSONValidateFast, InvalidType) {
// Encode an invalid BSON Object with an invalid type, x90.
const char* buffer = "\x0c\x00\x00\x00\x90\x41\x00\x10\x00\x00\x00\x00";
// Constructing the object is fine, but validating should fail.
BSONObj obj(buffer);
// Validate fails.
ASSERT_NOT_OK(validateBSON(obj.objdata(), obj.objsize()));
// Make sure the binary buffer above indeed has the invalid type.
ASSERT_THROWS_CODE(obj.woCompare(BSON("A" << 1)), DBException, 10320);
}
TEST(BSONValidateFast, ValidCodeWScope) {
BSONObj obj = BSON("a" << BSONCodeWScope("code", BSON("c" << BSONObj())));
ASSERT_OK(validateBSON(obj.objdata(), obj.objsize()));
obj = BSON("a" << BSONCodeWScope("code", BSON("c" << BSONArray() << "d" << BSONArray())));
ASSERT_OK(validateBSON(obj.objdata(), obj.objsize()));
}
BSONObj nest(int nesting) {
return nesting < 1 ? BSON("i" << nesting) : BSON("i" << nesting << "o" << nest(nesting - 1));
}
TEST(BSONValidateFast, MaxNestingDepth) {
BSONObj maxNesting = nest(BSONDepth::getMaxAllowableDepth());
ASSERT_OK(validateBSON(maxNesting.objdata(), maxNesting.objsize()));
BSONObj tooDeepNesting = nest(BSONDepth::getMaxAllowableDepth() + 1);
Status status = validateBSON(tooDeepNesting.objdata(), tooDeepNesting.objsize());
ASSERT_EQ(status.code(), ErrorCodes::Overflow);
}
} // namespace
|
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "T3D/missionMarker.h"
#include "console/consoleTypes.h"
#include "core/color.h"
#include "console/engineAPI.h"
extern bool gEditingMission;
IMPLEMENT_CO_DATABLOCK_V1(MissionMarkerData);
ConsoleDocClass( MissionMarkerData,
"@brief A very basic class containing information used by MissionMarker objects for rendering\n\n"
"MissionMarkerData, is an extremely barebones class derived from ShapeBaseData. It is solely used by "
"MissionMarker classes (such as SpawnSphere), so that you can see the object while editing a level.\n\n"
"@tsexample\n"
"datablock MissionMarkerData(SpawnSphereMarker)\n"
"{\n"
" category = \"Misc\";\n"
" shapeFile = \"core/art/shapes/octahedron.dts\";\n"
"};\n"
"@endtsexample\n\n"
"@see MissionMarker\n\n"
"@see SpawnSphere\n\n"
"@see WayPoint\n\n"
"@ingroup enviroMisc\n"
);
//------------------------------------------------------------------------------
// Class: MissionMarker
//------------------------------------------------------------------------------
IMPLEMENT_CO_NETOBJECT_V1(MissionMarker);
ConsoleDocClass( MissionMarker,
"@brief This is a base class for all \"marker\" related objets. It is a 3D representation of a point in the level.\n\n"
"The main use of a MissionMarker is to represent a point in 3D space with a mesh and basic ShapeBase information. "
"If you simply need to mark a spot in your level, with no overhead from additional fields, this is a useful object.\n\n"
"@tsexample\n"
"new MissionMarker()\n"
"{\n"
" dataBlock = \"WayPointMarker\";\n"
" position = \"295.699 -171.817 280.124\";\n"
" rotation = \"0 0 -1 13.8204\";\n"
" scale = \"1 1 1\";\n"
" isRenderEnabled = \"true\";\n"
" canSaveDynamicFields = \"1\";\n"
" enabled = \"1\";\n"
"};\n"
"@endtsexample\n\n"
"@note MissionMarkers will not add themselves to the scene except when in the editor.\n\n"
"@see MissionMarkerData\n\n"
"@see SpawnSphere\n\n"
"@see WayPoint\n\n"
"@ingroup enviroMisc\n"
);
MissionMarker::MissionMarker()
{
mTypeMask |= StaticObjectType;
mDataBlock = 0;
mAddedToScene = false;
mNetFlags.set(Ghostable | ScopeAlways);
}
bool MissionMarker::onAdd()
{
if(!Parent::onAdd() || !mDataBlock)
return(false);
if(gEditingMission)
{
addToScene();
mAddedToScene = true;
}
return(true);
}
void MissionMarker::onRemove()
{
if( mAddedToScene )
{
removeFromScene();
mAddedToScene = false;
}
Parent::onRemove();
}
void MissionMarker::inspectPostApply()
{
Parent::inspectPostApply();
setMaskBits(PositionMask);
}
void MissionMarker::onEditorEnable()
{
if(!mAddedToScene)
{
addToScene();
mAddedToScene = true;
}
}
void MissionMarker::onEditorDisable()
{
if(mAddedToScene)
{
removeFromScene();
mAddedToScene = false;
}
}
bool MissionMarker::onNewDataBlock( GameBaseData *dptr, bool reload )
{
mDataBlock = dynamic_cast<MissionMarkerData*>( dptr );
if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) )
return(false);
scriptOnNewDataBlock();
return(true);
}
void MissionMarker::setTransform(const MatrixF& mat)
{
Parent::setTransform(mat);
setMaskBits(PositionMask);
}
U32 MissionMarker::packUpdate(NetConnection * con, U32 mask, BitStream * stream)
{
U32 retMask = Parent::packUpdate(con, mask, stream);
if(stream->writeFlag(mask & PositionMask))
{
stream->writeAffineTransform(mObjToWorld);
mathWrite(*stream, mObjScale);
}
return(retMask);
}
void MissionMarker::unpackUpdate(NetConnection * con, BitStream * stream)
{
Parent::unpackUpdate(con, stream);
if(stream->readFlag())
{
MatrixF mat;
stream->readAffineTransform(&mat);
Parent::setTransform(mat);
Point3F scale;
mathRead(*stream, &scale);
setScale(scale);
}
}
void MissionMarker::initPersistFields() {
Parent::initPersistFields();
}
//------------------------------------------------------------------------------
// Class: WayPoint
//------------------------------------------------------------------------------
IMPLEMENT_CO_NETOBJECT_V1(WayPoint);
ConsoleDocClass( WayPoint,
"@brief Special type of marker, distinguished by a name and team ID number\n\n"
"The original Torque engines were built from a multi-player game called Tribes. "
"The Tribes series featured various team based game modes, such as capture the flag. "
"The WayPoint class survived the conversion from game (Tribes) to game engine (Torque).\n\n"
"Essentially, this is a MissionMarker with the addition of two variables: markerName and team. "
"Whenever a WayPoint is created, it is added to a unique global list called WayPointSet. "
"You can iterate through this set, seeking out specific markers determined by their markerName and team ID. "
"This avoids the overhead of constantly calling commandToClient and commandToServer to determine "
"a WayPoint object's name, unique ID, etc.\n\n"
"@note The <i>markerName<i> field was previously called <i>name</i>, but was changed "
"because this conflicted with the SimObject name field. Existing scripts that relied "
"on the WayPoint <i>name</i> field will need to be updated.\n\n"
"@tsexample\n"
"new WayPoint()\n"
"{\n"
" team = \"1\";\n"
" dataBlock = \"WayPointMarker\";\n"
" position = \"-0.0224786 1.53471 2.93219\";\n"
" rotation = \"1 0 0 0\";\n"
" scale = \"1 1 1\";\n"
" canSave = \"1\";\n"
" canSaveDynamicFields = \"1\";\n"
"};\n"
"@endtsexample\n\n"
"@see MissionMarker\n\n"
"@see MissionMarkerData\n\n"
"@ingroup enviroMisc\n"
);
WayPointTeam::WayPointTeam()
{
mTeamId = 0;
mWayPoint = 0;
}
WayPoint::WayPoint()
{
mName = StringTable->insert("");
}
void WayPoint::setHidden(bool hidden)
{
// Skip ShapeBase::setHidden (only ever added to scene if in the editor)
ShapeBase::Parent::setHidden( hidden );
if(isServerObject())
setMaskBits(UpdateHiddenMask);
}
bool WayPoint::onAdd()
{
if(!Parent::onAdd())
return(false);
//
if(isClientObject())
Sim::getWayPointSet()->addObject(this);
else
{
mTeam.mWayPoint = this;
setMaskBits(UpdateNameMask|UpdateTeamMask);
}
return(true);
}
void WayPoint::inspectPostApply()
{
Parent::inspectPostApply();
if(!mName || !mName[0])
mName = StringTable->insert("");
setMaskBits(UpdateNameMask|UpdateTeamMask);
}
U32 WayPoint::packUpdate(NetConnection * con, U32 mask, BitStream * stream)
{
U32 retMask = Parent::packUpdate(con, mask, stream);
if(stream->writeFlag(mask & UpdateNameMask))
stream->writeString(mName);
if(stream->writeFlag(mask & UpdateTeamMask))
stream->write(mTeam.mTeamId);
if(stream->writeFlag(mask & UpdateHiddenMask))
stream->writeFlag(isHidden());
return(retMask);
}
void WayPoint::unpackUpdate(NetConnection * con, BitStream * stream)
{
Parent::unpackUpdate(con, stream);
if(stream->readFlag())
mName = stream->readSTString(true);
if(stream->readFlag())
stream->read(&mTeam.mTeamId);
if(stream->readFlag())
setHidden(stream->readFlag());
}
//-----------------------------------------------------------------------------
// TypeWayPointTeam
//-----------------------------------------------------------------------------
IMPLEMENT_STRUCT( WayPointTeam, WayPointTeam,,
"" )
END_IMPLEMENT_STRUCT;
//FIXME: this should work but does not; need to check the stripping down to base types within TYPE
//ConsoleType( WayPointTeam, TypeWayPointTeam, WayPointTeam* )
ConsoleType( WayPointTeam, TypeWayPointTeam, WayPointTeam )
ConsoleGetType( TypeWayPointTeam )
{
static const U32 bufSize = 32;
char * buf = Con::getReturnBuffer(bufSize);
dSprintf(buf, bufSize, "%d", ((WayPointTeam*)dptr)->mTeamId);
return(buf);
}
ConsoleSetType( TypeWayPointTeam )
{
WayPointTeam * pTeam = (WayPointTeam*)dptr;
pTeam->mTeamId = dAtoi(argv[0]);
if(pTeam->mWayPoint && pTeam->mWayPoint->isServerObject())
pTeam->mWayPoint->setMaskBits(WayPoint::UpdateTeamMask);
}
void WayPoint::initPersistFields()
{
addGroup("Misc");
addField("markerName", TypeCaseString, Offset(mName, WayPoint), "Unique name representing this waypoint");
addField("team", TypeWayPointTeam, Offset(mTeam, WayPoint), "Unique numerical ID assigned to this waypoint, or set of waypoints");
endGroup("Misc");
Parent::initPersistFields();
}
//------------------------------------------------------------------------------
// Class: SpawnSphere
//------------------------------------------------------------------------------
IMPLEMENT_CO_NETOBJECT_V1(SpawnSphere);
ConsoleDocClass( SpawnSphere,
"@brief This class is used for creating any type of game object, assigning it a class, datablock, and other "
"properties when it is spawned.\n\n"
"Torque 3D uses a simple spawn system, which can be easily modified to spawn any kind of object (of any class). "
"Each new level already contains at least one SpawnSphere, which is represented by a green octahedron in stock Torque 3D. "
"The spawnClass field determines the object type, such as Player, AIPlayer, etc. The spawnDataBlock field applies the "
"pre-defined datablock to each spawned object instance. The really powerful feature of this class is provided by "
"the spawnScript field which allows you to define a simple script (multiple lines) that will be executed once the "
"object has been spawned.\n\n"
"@tsexample\n"
"// Define an SpawnSphere that essentially performs the following each time an object is spawned\n"
"//$SpawnObject = new Player()\n"
"//{\n"
"// dataBlock = \"DefaultPlayerData\";\n"
"// name = \"Bob\";\n"
"// lifeTotal = 3;\n"
"//};\n"
"//echo(\"Spawned a Player: \" @ $SpawnObject);\n\n"
"new SpawnSphere(DefaultSpawnSphere)\n"
"{\n"
" spawnClass = \"Player\";\n"
" spawnDatablock = \"DefaultPlayerData\";\n"
" spawnScript = \"echo(\\\"Spawned a Player: \\\" @ $SpawnObject);\"; // embedded quotes must be escaped with \\ \n"
" spawnProperties = \"name = \\\"Bob\\\";lifeTotal = 3;\"; // embedded quotes must be escaped with \\ \n"
" autoSpawn = \"1\";\n"
" dataBlock = \"SpawnSphereMarker\";\n"
" position = \"-0.77266 -19.882 17.8153\";\n"
" rotation = \"1 0 0 0\";\n"
" scale = \"1 1 1\";\n"
" canSave = \"1\";\n"
" canSaveDynamicFields = \"1\";\n"
"};\n\n"
"// Because autoSpawn is set to true in the above example, the following lines\n"
"// of code will execute AFTER the Player object has been spawned.\n"
"echo(\"Object Spawned\");\n"
"echo(\"Hello World\");\n\n"
"@endtsexample\n\n"
"@see MissionMarker\n\n"
"@see MissionMarkerData\n\n"
"@ingroup gameObjects\n"
"@ingroup enviroMisc\n"
);
SpawnSphere::SpawnSphere()
{
mAutoSpawn = false;
mSpawnTransform = false;
mRadius = 100.f;
mSphereWeight = 100.f;
mIndoorWeight = 100.f;
mOutdoorWeight = 100.f;
}
IMPLEMENT_CALLBACK( SpawnSphere, onAdd, void, ( U32 objectId ), ( objectId ),
"Called when the SpawnSphere is being created.\n"
"@param objectId The unique SimObjectId generated when SpawnSphere is created (%%this in script)\n" );
bool SpawnSphere::onAdd()
{
if(!Parent::onAdd())
return(false);
if(!isClientObject())
setMaskBits(UpdateSphereMask);
if (!isGhost())
{
onAdd_callback( getId());
if (mAutoSpawn)
spawnObject();
}
return true;
}
SimObject* SpawnSphere::spawnObject(String additionalProps)
{
SimObject* spawnObject = Sim::spawnObject(mSpawnClass, mSpawnDataBlock, mSpawnName,
mSpawnProperties + " " + additionalProps, mSpawnScript);
// If we have a spawnObject add it to the MissionCleanup group
if (spawnObject)
{
if (mSpawnTransform)
{
if(SceneObject *s = dynamic_cast<SceneObject*>(spawnObject))
s->setTransform(getTransform());
}
SimObject* cleanup = Sim::findObject("MissionCleanup");
if (cleanup)
{
SimGroup* missionCleanup = dynamic_cast<SimGroup*>(cleanup);
missionCleanup->addObject(spawnObject);
}
}
return spawnObject;
}
void SpawnSphere::inspectPostApply()
{
Parent::inspectPostApply();
setMaskBits(UpdateSphereMask);
}
U32 SpawnSphere::packUpdate(NetConnection * con, U32 mask, BitStream * stream)
{
U32 retMask = Parent::packUpdate(con, mask, stream);
//
if(stream->writeFlag(mask & UpdateSphereMask))
{
stream->writeFlag(mAutoSpawn);
stream->writeFlag(mSpawnTransform);
stream->write(mSpawnClass);
stream->write(mSpawnDataBlock);
stream->write(mSpawnName);
stream->write(mSpawnProperties);
stream->write(mSpawnScript);
}
return(retMask);
}
void SpawnSphere::unpackUpdate(NetConnection * con, BitStream * stream)
{
Parent::unpackUpdate(con, stream);
if(stream->readFlag())
{
mAutoSpawn = stream->readFlag();
mSpawnTransform = stream->readFlag();
stream->read(&mSpawnClass);
stream->read(&mSpawnDataBlock);
stream->read(&mSpawnName);
stream->read(&mSpawnProperties);
stream->read(&mSpawnScript);
}
}
void SpawnSphere::processTick( const Move *move )
{
if ( isServerObject() && isMounted() )
{
MatrixF mat( true );
mMount.object->getRenderMountTransform( 0.f, mMount.node, mMount.xfm, &mat );
setTransform( mat );
}
}
void SpawnSphere::advanceTime( F32 timeDelta )
{
if ( isMounted() )
{
MatrixF mat( true );
mMount.object->getRenderMountTransform( 0.f, mMount.node, mMount.xfm, &mat );
setTransform( mat );
}
}
void SpawnSphere::initPersistFields()
{
addGroup( "Spawn" );
addField( "spawnClass", TypeRealString, Offset(mSpawnClass, SpawnSphere),
"Object class to create (eg. Player, AIPlayer, Debris etc)" );
addField( "spawnDatablock", TypeRealString, Offset(mSpawnDataBlock, SpawnSphere),
"Predefined datablock assigned to the object when created" );
addField( "spawnProperties", TypeRealString, Offset(mSpawnProperties, SpawnSphere),
"String containing semicolon (;) delimited properties to set when the object is created." );
addField( "spawnScript", TypeCommand, Offset(mSpawnScript, SpawnSphere),
"Command to execute immediately after spawning an object. New object id is stored in $SpawnObject. Max 255 characters." );
addField( "autoSpawn", TypeBool, Offset(mAutoSpawn, SpawnSphere),
"Flag to spawn object as soon as SpawnSphere is created, true to enable or false to disable." );
addField( "spawnTransform", TypeBool, Offset(mSpawnTransform, SpawnSphere),
"Flag to set the spawned object's transform to the SpawnSphere's transform." );
endGroup( "Spawn" );
addGroup( "Dimensions" );
addField( "radius", TypeF32, Offset(mRadius, SpawnSphere), "Deprecated" );
endGroup( "Dimensions" );
addGroup( "Weight" );
addField( "sphereWeight", TypeF32, Offset(mSphereWeight, SpawnSphere), "Deprecated" );
addField( "indoorWeight", TypeF32, Offset(mIndoorWeight, SpawnSphere), "Deprecated" );
addField( "outdoorWeight", TypeF32, Offset(mOutdoorWeight, SpawnSphere), "Deprecated" );
endGroup( "Weight" );
Parent::initPersistFields();
}
ConsoleDocFragment _SpawnSpherespawnObject1(
"@brief Dynamically create a new game object with a specified class, datablock, and optional properties.\n\n"
"This is called on the actual SpawnSphere, not to be confused with the Sim::spawnObject() "
"global function\n\n"
"@param additionalProps Optional set of semiconlon delimited parameters applied to the spawn object during creation.\n\n"
"@tsexample\n"
"// Use the SpawnSphere::spawnObject function to create a game object\n"
"// No additional properties assigned\n"
"%player = DefaultSpawnSphere.spawnObject();\n\n"
"@endtsexample\n\n",
"SpawnSphere",
"bool spawnObject(string additionalProps);"
);
ConsoleMethod(SpawnSphere, spawnObject, S32, 2, 3,
"([string additionalProps]) Spawns the object based on the SpawnSphere's "
"class, datablock, properties, and script settings. Allows you to pass in "
"extra properties."
"@hide" )
{
String additionalProps;
if (argc == 3)
additionalProps = String(argv[2]);
SimObject* obj = object->spawnObject(additionalProps);
if (obj)
return obj->getId();
return -1;
}
//------------------------------------------------------------------------------
// Class: CameraBookmark
//------------------------------------------------------------------------------
IMPLEMENT_CO_NETOBJECT_V1(CameraBookmark);
ConsoleDocClass( CameraBookmark,
"@brief Special type of mission marker which allows a level editor's camera to jump to specific points.\n\n"
"For Torque 3D editors only, not for actual game development\n\n"
"@internal"
);
CameraBookmark::CameraBookmark()
{
mName = StringTable->insert("");
}
bool CameraBookmark::onAdd()
{
if(!Parent::onAdd())
return(false);
//
if(!isClientObject())
{
setMaskBits(UpdateNameMask);
}
if( isServerObject() && isMethod("onAdd") )
Con::executef( this, "onAdd" );
return(true);
}
void CameraBookmark::onRemove()
{
if( isServerObject() && isMethod("onRemove") )
Con::executef( this, "onRemove" );
Parent::onRemove();
}
void CameraBookmark::onGroupAdd()
{
if( isServerObject() && isMethod("onGroupAdd") )
Con::executef( this, "onGroupAdd" );
}
void CameraBookmark::onGroupRemove()
{
if( isServerObject() && isMethod("onGroupRemove") )
Con::executef( this, "onGroupRemove" );
}
void CameraBookmark::inspectPostApply()
{
Parent::inspectPostApply();
if(!mName || !mName[0])
mName = StringTable->insert("");
setMaskBits(UpdateNameMask);
if( isMethod("onInspectPostApply") )
Con::executef( this, "onInspectPostApply" );
}
U32 CameraBookmark::packUpdate(NetConnection * con, U32 mask, BitStream * stream)
{
U32 retMask = Parent::packUpdate(con, mask, stream);
if(stream->writeFlag(mask & UpdateNameMask))
stream->writeString(mName);
return(retMask);
}
void CameraBookmark::unpackUpdate(NetConnection * con, BitStream * stream)
{
Parent::unpackUpdate(con, stream);
if(stream->readFlag())
mName = stream->readSTString(true);
}
void CameraBookmark::initPersistFields()
{
//addGroup("Misc");
//addField("name", TypeCaseString, Offset(mName, CameraBookmark));
//endGroup("Misc");
Parent::initPersistFields();
removeField("nameTag"); // From GameBase
}
|
class Solution {
public:
int XXX(vector<int>& nums, int target) {
if(nums.size() == 0 || nums[0] > target) return 0;
if(nums.back() < target) return nums.size();
int l = 0, r = nums.size() - 1;
while(l <= r){
int mid = l + (r-l)/2;
if(nums[mid] == target){
return mid;
}else if(nums[mid] < target){
if(mid == nums.size() - 1 || nums[mid + 1] > target){
return mid + 1;
}
l = mid + 1;
}else{
if(mid == 0 || nums[mid - 1] < target){
return mid;
}
r = mid - 1;
}
}
if(nums[r] < target) return r+1;
else if(nums[r] == target) return r;
else return r-1;
}
};
|
/* _________________________________________________________________________
*
* Acro: A Common Repository for Optimizers
* Copyright (c) 2008 Sandia Corporation.
* This software is distributed under the BSD License.
* Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
* the U.S. Government retains certain rights in this software.
* For more information, see the README.txt file in the top Acro directory.
* _________________________________________________________________________
*/
//
// workerInHeap.cpp
//
// A little class used by the hub code in PEBBL. Had to be moved to its
// own header file because it's used in a template.
//
// Jonathan Eckstein
//
#include <pebbl_config.h>
#include <pebbl/pbb/parBranching.h>
#ifdef ACRO_HAVE_MPI
using namespace std;
namespace pebbl {
int workerInHeap::compare(const workerInHeap& other) const
{
return global->lowerLoadWorker(w,other.w);
}
int workerInQHeap::compare(const workerInHeap& other) const
{
return global->worseQualityWorker(w,other.w);
}
} // namespace pebbl
#endif
|
/*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 2019, by the GROMACS development team, led by
* Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
* and including many others, as listed in the AUTHORS file in the
* top-level source directory and at http://www.gromacs.org.
*
* GROMACS is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* GROMACS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
/*! \internal \file
* \brief
* Implements the Nbnxm class
*
* \author Berk Hess <hess@kth.se>
* \ingroup module_nbnxm
*/
#include "gmxpre.h"
#include "nbnxm.h"
#include "gromacs/domdec/domdec_struct.h"
#include "gromacs/nbnxm/atomdata.h"
#include "gromacs/timing/wallcycle.h"
#include "pairlistsets.h"
#include "pairsearch.h"
/*! \cond INTERNAL */
void nbnxn_put_on_grid(nonbonded_verlet_t *nb_verlet,
const matrix box,
int ddZone,
const rvec lowerCorner,
const rvec upperCorner,
const gmx::UpdateGroupsCog *updateGroupsCog,
int atomStart,
int atomEnd,
real atomDensity,
gmx::ArrayRef<const int> atomInfo,
gmx::ArrayRef<const gmx::RVec> x,
int numAtomsMoved,
const int *move)
{
nb_verlet->pairSearch_->putOnGrid(box, ddZone, lowerCorner, upperCorner,
updateGroupsCog, atomStart, atomEnd, atomDensity,
atomInfo, x, numAtomsMoved, move,
nb_verlet->nbat.get());
}
/* Calls nbnxn_put_on_grid for all non-local domains */
void nbnxn_put_on_grid_nonlocal(nonbonded_verlet_t *nbv,
const struct gmx_domdec_zones_t *zones,
gmx::ArrayRef<const int> atomInfo,
gmx::ArrayRef<const gmx::RVec> x)
{
for (int zone = 1; zone < zones->n; zone++)
{
rvec c0, c1;
for (int d = 0; d < DIM; d++)
{
c0[d] = zones->size[zone].bb_x0[d];
c1[d] = zones->size[zone].bb_x1[d];
}
nbnxn_put_on_grid(nbv, nullptr,
zone, c0, c1,
nullptr,
zones->cg_range[zone],
zones->cg_range[zone+1],
-1,
atomInfo,
x,
0, nullptr);
}
}
bool nonbonded_verlet_t::isDynamicPruningStepCpu(int64_t step) const
{
return pairlistSets_->isDynamicPruningStepCpu(step);
}
bool nonbonded_verlet_t::isDynamicPruningStepGpu(int64_t step) const
{
return pairlistSets_->isDynamicPruningStepGpu(step);
}
gmx::ArrayRef<const int> nonbonded_verlet_t::getLocalAtomOrder() const
{
/* Return the atom order for the home cell (index 0) */
const Nbnxm::Grid &grid = pairSearch_->gridSet().grids()[0];
const int numIndices = grid.atomIndexEnd() - grid.firstAtomInColumn(0);
return gmx::constArrayRefFromArray(pairSearch_->gridSet().atomIndices().data(), numIndices);
}
void nonbonded_verlet_t::setLocalAtomOrder()
{
pairSearch_->setLocalAtomOrder();
}
void nonbonded_verlet_t::setAtomProperties(const t_mdatoms &mdatoms,
gmx::ArrayRef<const int> atomInfo)
{
nbnxn_atomdata_set(nbat.get(), pairSearch_->gridSet(), &mdatoms, atomInfo.data());
}
void nonbonded_verlet_t::setCoordinates(const Nbnxm::AtomLocality locality,
const bool fillLocal,
gmx::ArrayRef<const gmx::RVec> x,
BufferOpsUseGpu useGpu,
void *xPmeDevicePtr,
gmx_wallcycle *wcycle)
{
wallcycle_start(wcycle, ewcNB_XF_BUF_OPS);
wallcycle_sub_start(wcycle, ewcsNB_X_BUF_OPS);
auto fnPtr = (useGpu == BufferOpsUseGpu::True) ?
nbnxn_atomdata_copy_x_to_nbat_x<true> :
nbnxn_atomdata_copy_x_to_nbat_x<false>;
fnPtr(pairSearch_->gridSet(), locality, fillLocal,
as_rvec_array(x.data()),
nbat.get(), gpu_nbv, xPmeDevicePtr);
wallcycle_sub_stop(wcycle, ewcsNB_X_BUF_OPS);
wallcycle_stop(wcycle, ewcNB_XF_BUF_OPS);
}
gmx::ArrayRef<const int> nonbonded_verlet_t::getGridIndices() const
{
return pairSearch_->gridSet().cells();
}
void
nonbonded_verlet_t::atomdata_add_nbat_f_to_f(const Nbnxm::AtomLocality locality,
rvec *f,
BufferOpsUseGpu useGpu,
GpuBufferOpsAccumulateForce accumulateForce,
gmx_wallcycle *wcycle)
{
GMX_ASSERT(!((useGpu == BufferOpsUseGpu::False) &&
(accumulateForce == GpuBufferOpsAccumulateForce::True)),
"Accumulatation of force is only valid when GPU buffer ops are active");
/* Skip the reduction if there was no short-range GPU work to do
* (either NB or both NB and bonded work). */
if (!pairlistIsSimple() && !haveGpuShortRangeWork(locality))
{
return;
}
wallcycle_start(wcycle, ewcNB_XF_BUF_OPS);
wallcycle_sub_start(wcycle, ewcsNB_F_BUF_OPS);
auto fn = useGpu == BufferOpsUseGpu::True ? reduceForces<true> : reduceForces<false>;
fn(nbat.get(), locality, pairSearch_->gridSet(), f, gpu_nbv, accumulateForce);
wallcycle_sub_stop(wcycle, ewcsNB_F_BUF_OPS);
wallcycle_stop(wcycle, ewcNB_XF_BUF_OPS);
}
void
nonbonded_verlet_t::atomdata_init_add_nbat_f_to_f_gpu(gmx_wallcycle *wcycle)
{
wallcycle_start(wcycle, ewcNB_XF_BUF_OPS);
wallcycle_sub_start(wcycle, ewcsNB_F_BUF_OPS);
const Nbnxm::GridSet &gridSet = pairSearch_->gridSet();
Nbnxm::nbnxn_gpu_init_add_nbat_f_to_f(gridSet.cells().data(),
gpu_nbv,
gridSet.numRealAtomsTotal());
wallcycle_sub_stop(wcycle, ewcsNB_F_BUF_OPS);
wallcycle_stop(wcycle, ewcNB_XF_BUF_OPS);
}
real nonbonded_verlet_t::pairlistInnerRadius() const
{
return pairlistSets_->params().rlistInner;
}
real nonbonded_verlet_t::pairlistOuterRadius() const
{
return pairlistSets_->params().rlistOuter;
}
void nonbonded_verlet_t::changePairlistRadii(real rlistOuter,
real rlistInner)
{
pairlistSets_->changePairlistRadii(rlistOuter, rlistInner);
}
void
nonbonded_verlet_t::atomdata_init_copy_x_to_nbat_x_gpu()
{
Nbnxm::nbnxn_gpu_init_x_to_nbat_x(pairSearch_->gridSet(), gpu_nbv);
}
void nonbonded_verlet_t::insertNonlocalGpuDependency(const Nbnxm::InteractionLocality interactionLocality)
{
Nbnxm::nbnxnInsertNonlocalGpuDependency(gpu_nbv, interactionLocality);
}
void nonbonded_verlet_t::launch_copy_f_to_gpu(rvec *f, const Nbnxm::AtomLocality locality)
{
nbnxn_launch_copy_f_to_gpu(locality,
pairSearch_->gridSet(),
gpu_nbv,
f);
}
void nonbonded_verlet_t::launch_copy_f_from_gpu(rvec *f, const Nbnxm::AtomLocality locality)
{
nbnxn_launch_copy_f_from_gpu(locality,
pairSearch_->gridSet(),
gpu_nbv,
f);
}
void nonbonded_verlet_t::wait_stream_gpu(const Nbnxm::AtomLocality locality)
{
nbnxn_wait_stream_gpu(locality, gpu_nbv);
}
/*! \endcond */
|
///
/// @file PrimeGenerator.hpp
/// Generates the primes inside [start, stop] and stores them
/// in a vector. After the primes have been stored in the
/// vector primesieve::iterator iterates over the vector and
/// returns the primes. When there are no more primes left in
/// the vector PrimeGenerator generates new primes.
///
/// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PRIMEGENERATOR_HPP
#define PRIMEGENERATOR_HPP
#include "Erat.hpp"
#include "PreSieve.hpp"
#include "SievingPrimes.hpp"
#include <stdint.h>
#include <vector>
namespace primesieve {
class PrimeGenerator : public Erat
{
public:
PrimeGenerator(uint64_t start, uint64_t stop);
void fillPrevPrimes(std::vector<uint64_t>& primes, std::size_t* size);
void fillNextPrimes(std::vector<uint64_t>& primes, std::size_t* size);
static uint64_t maxCachedPrime();
private:
uint64_t low_ = 0;
uint64_t sieveIdx_ = ~0ull;
uint64_t prime_ = 0;
PreSieve preSieve_;
SievingPrimes sievingPrimes_;
bool isInit_ = false;
std::size_t getStartIdx() const;
std::size_t getStopIdx() const;
void initErat();
void initPrevPrimes(std::vector<uint64_t>&, std::size_t*);
void initNextPrimes(std::vector<uint64_t>&, std::size_t*);
bool sievePrevPrimes(std::vector<uint64_t>&, std::size_t*);
bool sieveNextPrimes(std::vector<uint64_t>&, std::size_t*);
void sieveSegment();
};
} // namespace
#endif
|
/*
* Copyright (c) 2018 GYB, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <gyb/chain/protocol/buyback.hpp>
namespace gyb { namespace chain {
class database;
void evaluate_buyback_account_options( const database& db, const buyback_account_options& auth );
} } // gyb::chain
|
\*
Author: allannozomu
Runtime: 20 ms
Memory: 11.4 MB*\
class Solution {
public:
bool isBipartite(vector<vector<int>>& graph) {
vector<int> colors = vector<int>(graph.size());
for(int node = 0; node < graph.size(); ++node){
if (colors[node]) {
continue;
}
queue<pair<int, int>> nodes_queue;
colors[node] = 1;
nodes_queue.push({node, 1});
while(!nodes_queue.empty()){
pair<int, int> curr_node = nodes_queue.front();
nodes_queue.pop();
for (int neigh : graph[curr_node.first]){
if (colors[neigh] == 0){
colors[neigh] = -curr_node.second;
nodes_queue.push({neigh, -curr_node.second});
} else if (colors[neigh] != -curr_node.second){
return false;
}
}
}
}
return true;
}
};
|
//===- InstCombineAndOrXor.cpp --------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the visitAnd, visitOr, and visitXor functions.
//
//===----------------------------------------------------------------------===//
#include "InstCombineInternal.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Transforms/Utils/CmpInstAnalysis.h"
using namespace llvm;
using namespace PatternMatch;
#define DEBUG_TYPE "instcombine"
static inline Value *dyn_castNotVal(Value *V) {
// If this is not(not(x)) don't return that this is a not: we want the two
// not's to be folded first.
if (BinaryOperator::isNot(V)) {
Value *Operand = BinaryOperator::getNotArgument(V);
if (!IsFreeToInvert(Operand, Operand->hasOneUse()))
return Operand;
}
// Constants can be considered to be not'ed values...
if (ConstantInt *C = dyn_cast<ConstantInt>(V))
return ConstantInt::get(C->getType(), ~C->getValue());
return nullptr;
}
/// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
/// a three bit mask. It also returns whether it is an ordered predicate by
/// reference.
static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
isOrdered = false;
switch (CC) {
case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
case FCmpInst::FCMP_UNO: return 0; // 000
case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
case FCmpInst::FCMP_UGT: return 1; // 001
case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
case FCmpInst::FCMP_UEQ: return 2; // 010
case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
case FCmpInst::FCMP_UGE: return 3; // 011
case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
case FCmpInst::FCMP_ULT: return 4; // 100
case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
case FCmpInst::FCMP_UNE: return 5; // 101
case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
case FCmpInst::FCMP_ULE: return 6; // 110
// True -> 7
default:
// Not expecting FCMP_FALSE and FCMP_TRUE;
llvm_unreachable("Unexpected FCmp predicate!");
}
}
/// This is the complement of getICmpCode, which turns an opcode and two
/// operands into either a constant true or false, or a brand new ICmp
/// instruction. The sign is passed in to determine which kind of predicate to
/// use in the new icmp instruction.
static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
InstCombiner::BuilderTy *Builder) {
ICmpInst::Predicate NewPred;
if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
return NewConstant;
return Builder->CreateICmp(NewPred, LHS, RHS);
}
/// This is the complement of getFCmpCode, which turns an opcode and two
/// operands into either a FCmp instruction. isordered is passed in to determine
/// which kind of predicate to use in the new fcmp instruction.
static Value *getFCmpValue(bool isordered, unsigned code,
Value *LHS, Value *RHS,
InstCombiner::BuilderTy *Builder) {
CmpInst::Predicate Pred;
switch (code) {
default: llvm_unreachable("Illegal FCmp code!");
case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
case 7:
if (!isordered)
return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Pred = FCmpInst::FCMP_ORD; break;
}
return Builder->CreateFCmp(Pred, LHS, RHS);
}
/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
/// \param I Binary operator to transform.
/// \return Pointer to node that must replace the original binary operator, or
/// null pointer if no transformation was made.
Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
// Can't do vectors.
if (I.getType()->isVectorTy()) return nullptr;
// Can only do bitwise ops.
unsigned Op = I.getOpcode();
if (Op != Instruction::And && Op != Instruction::Or &&
Op != Instruction::Xor)
return nullptr;
Value *OldLHS = I.getOperand(0);
Value *OldRHS = I.getOperand(1);
ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
if (!IsBswapLHS && !IsBswapRHS)
return nullptr;
if (!IsBswapLHS && !ConstLHS)
return nullptr;
if (!IsBswapRHS && !ConstRHS)
return nullptr;
/// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
/// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
Builder->getInt(ConstLHS->getValue().byteSwap());
Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
Builder->getInt(ConstRHS->getValue().byteSwap());
Value *BinOp = nullptr;
if (Op == Instruction::And)
BinOp = Builder->CreateAnd(NewLHS, NewRHS);
else if (Op == Instruction::Or)
BinOp = Builder->CreateOr(NewLHS, NewRHS);
else //if (Op == Instruction::Xor)
BinOp = Builder->CreateXor(NewLHS, NewRHS);
Module *M = I.getParent()->getParent()->getParent();
Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
return Builder->CreateCall(F, BinOp);
}
/// This handles expressions of the form ((val OP C1) & C2). Where
/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
/// guaranteed to be a binary operator.
Instruction *InstCombiner::OptAndOp(Instruction *Op,
ConstantInt *OpRHS,
ConstantInt *AndRHS,
BinaryOperator &TheAnd) {
Value *X = Op->getOperand(0);
Constant *Together = nullptr;
if (!Op->isShift())
Together = ConstantExpr::getAnd(AndRHS, OpRHS);
switch (Op->getOpcode()) {
case Instruction::Xor:
if (Op->hasOneUse()) {
// (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Value *And = Builder->CreateAnd(X, AndRHS);
And->takeName(Op);
return BinaryOperator::CreateXor(And, Together);
}
break;
case Instruction::Or:
if (Op->hasOneUse()){
if (Together != OpRHS) {
// (X | C1) & C2 --> (X | (C1&C2)) & C2
Value *Or = Builder->CreateOr(X, Together);
Or->takeName(Op);
return BinaryOperator::CreateAnd(Or, AndRHS);
}
ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
if (TogetherCI && !TogetherCI->isZero()){
// (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
// NOTE: This reduces the number of bits set in the & mask, which
// can expose opportunities for store narrowing.
Together = ConstantExpr::getXor(AndRHS, Together);
Value *And = Builder->CreateAnd(X, Together);
And->takeName(Op);
return BinaryOperator::CreateOr(And, OpRHS);
}
}
break;
case Instruction::Add:
if (Op->hasOneUse()) {
// Adding a one to a single bit bit-field should be turned into an XOR
// of the bit. First thing to check is to see if this AND is with a
// single bit constant.
const APInt &AndRHSV = AndRHS->getValue();
// If there is only one bit set.
if (AndRHSV.isPowerOf2()) {
// Ok, at this point, we know that we are masking the result of the
// ADD down to exactly one bit. If the constant we are adding has
// no bits set below this bit, then we can eliminate the ADD.
const APInt& AddRHS = OpRHS->getValue();
// Check to see if any bits below the one bit set in AndRHSV are set.
if ((AddRHS & (AndRHSV-1)) == 0) {
// If not, the only thing that can effect the output of the AND is
// the bit specified by AndRHSV. If that bit is set, the effect of
// the XOR is to toggle the bit. If it is clear, then the ADD has
// no effect.
if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
TheAnd.setOperand(0, X);
return &TheAnd;
} else {
// Pull the XOR out of the AND.
Value *NewAnd = Builder->CreateAnd(X, AndRHS);
NewAnd->takeName(Op);
return BinaryOperator::CreateXor(NewAnd, AndRHS);
}
}
}
}
break;
case Instruction::Shl: {
// We know that the AND will not produce any of the bits shifted in, so if
// the anded constant includes them, clear them now!
//
uint32_t BitWidth = AndRHS->getType()->getBitWidth();
uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
if (CI->getValue() == ShlMask)
// Masking out bits that the shift already masks.
return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
if (CI != AndRHS) { // Reducing bits set in and.
TheAnd.setOperand(1, CI);
return &TheAnd;
}
break;
}
case Instruction::LShr: {
// We know that the AND will not produce any of the bits shifted in, so if
// the anded constant includes them, clear them now! This only applies to
// unsigned shifts, because a signed shr may bring in set bits!
//
uint32_t BitWidth = AndRHS->getType()->getBitWidth();
uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
if (CI->getValue() == ShrMask)
// Masking out bits that the shift already masks.
return ReplaceInstUsesWith(TheAnd, Op);
if (CI != AndRHS) {
TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
return &TheAnd;
}
break;
}
case Instruction::AShr:
// Signed shr.
// See if this is shifting in some sign extension, then masking it out
// with an and.
if (Op->hasOneUse()) {
uint32_t BitWidth = AndRHS->getType()->getBitWidth();
uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
if (C == AndRHS) { // Masking out bits shifted in.
// (Val ashr C1) & C2 -> (Val lshr C1) & C2
// Make the argument unsigned.
Value *ShVal = Op->getOperand(0);
ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
}
}
break;
}
return nullptr;
}
/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
/// (V < Lo || V >= Hi). In practice, we emit the more efficient
/// (V-Lo) \<u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
/// whether to treat the V, Lo and HI as signed or not. IB is the location to
/// insert new instructions.
Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
bool isSigned, bool Inside) {
assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
"Lo is not <= Hi in range emission code!");
if (Inside) {
if (Lo == Hi) // Trivially false.
return Builder->getFalse();
// V >= Min && V < Hi --> V < Hi
if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
ICmpInst::Predicate pred = (isSigned ?
ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
return Builder->CreateICmp(pred, V, Hi);
}
// Emit V-Lo <u Hi-Lo
Constant *NegLo = ConstantExpr::getNeg(Lo);
Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
return Builder->CreateICmpULT(Add, UpperBound);
}
if (Lo == Hi) // Trivially true.
return Builder->getTrue();
// V < Min || V >= Hi -> V > Hi-1
Hi = SubOne(cast<ConstantInt>(Hi));
if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
ICmpInst::Predicate pred = (isSigned ?
ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
return Builder->CreateICmp(pred, V, Hi);
}
// Emit V-Lo >u Hi-1-Lo
// Note that Hi has already had one subtracted from it, above.
ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
return Builder->CreateICmpUGT(Add, LowerBound);
}
/// Returns true iff Val consists of one contiguous run of 1s with any number
/// of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
/// so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
/// not, since all 1s are not contiguous.
static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
const APInt& V = Val->getValue();
uint32_t BitWidth = Val->getType()->getBitWidth();
if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
// look for the first zero bit after the run of ones
MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
// look for the first non-zero bit
ME = V.getActiveBits();
return true;
}
/// This is part of an expression (LHS +/- RHS) & Mask, where isSub determines
/// whether the operator is a sub. If we can fold one of the following xforms:
///
/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
///
/// return (A +/- B).
///
Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
ConstantInt *Mask, bool isSub,
Instruction &I) {
Instruction *LHSI = dyn_cast<Instruction>(LHS);
if (!LHSI || LHSI->getNumOperands() != 2 ||
!isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
switch (LHSI->getOpcode()) {
default: return nullptr;
case Instruction::And:
if (ConstantExpr::getAnd(N, Mask) == Mask) {
// If the AndRHS is a power of two minus one (0+1+), this is simple.
if ((Mask->getValue().countLeadingZeros() +
Mask->getValue().countPopulation()) ==
Mask->getValue().getBitWidth())
break;
// Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
// part, we don't need any explicit masks to take them out of A. If that
// is all N is, ignore it.
uint32_t MB = 0, ME = 0;
if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
if (MaskedValueIsZero(RHS, Mask, 0, &I))
break;
}
}
return nullptr;
case Instruction::Or:
case Instruction::Xor:
// If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
if ((Mask->getValue().countLeadingZeros() +
Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
&& ConstantExpr::getAnd(N, Mask)->isNullValue())
break;
return nullptr;
}
if (isSub)
return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
}
/// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
/// One of A and B is considered the mask, the other the value. This is
/// described as the "AMask" or "BMask" part of the enum. If the enum
/// contains only "Mask", then both A and B can be considered masks.
/// If A is the mask, then it was proven, that (A & C) == C. This
/// is trivial if C == A, or C == 0. If both A and C are constants, this
/// proof is also easy.
/// For the following explanations we assume that A is the mask.
/// The part "AllOnes" declares, that the comparison is true only
/// if (A & B) == A, or all bits of A are set in B.
/// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
/// The part "AllZeroes" declares, that the comparison is true only
/// if (A & B) == 0, or all bits of A are cleared in B.
/// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
/// The part "Mixed" declares, that (A & B) == C and C might or might not
/// contain any number of one bits and zero bits.
/// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
/// The Part "Not" means, that in above descriptions "==" should be replaced
/// by "!=".
/// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
/// If the mask A contains a single bit, then the following is equivalent:
/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
enum MaskedICmpType {
FoldMskICmp_AMask_AllOnes = 1,
FoldMskICmp_AMask_NotAllOnes = 2,
FoldMskICmp_BMask_AllOnes = 4,
FoldMskICmp_BMask_NotAllOnes = 8,
FoldMskICmp_Mask_AllZeroes = 16,
FoldMskICmp_Mask_NotAllZeroes = 32,
FoldMskICmp_AMask_Mixed = 64,
FoldMskICmp_AMask_NotMixed = 128,
FoldMskICmp_BMask_Mixed = 256,
FoldMskICmp_BMask_NotMixed = 512
};
/// Return the set of pattern classes (from MaskedICmpType)
/// that (icmp SCC (A & B), C) satisfies.
static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
ICmpInst::Predicate SCC)
{
ConstantInt *ACst = dyn_cast<ConstantInt>(A);
ConstantInt *BCst = dyn_cast<ConstantInt>(B);
ConstantInt *CCst = dyn_cast<ConstantInt>(C);
bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
bool icmp_abit = (ACst && !ACst->isZero() &&
ACst->getValue().isPowerOf2());
bool icmp_bbit = (BCst && !BCst->isZero() &&
BCst->getValue().isPowerOf2());
unsigned result = 0;
if (CCst && CCst->isZero()) {
// if C is zero, then both A and B qualify as mask
result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
FoldMskICmp_Mask_AllZeroes |
FoldMskICmp_AMask_Mixed |
FoldMskICmp_BMask_Mixed)
: (FoldMskICmp_Mask_NotAllZeroes |
FoldMskICmp_Mask_NotAllZeroes |
FoldMskICmp_AMask_NotMixed |
FoldMskICmp_BMask_NotMixed));
if (icmp_abit)
result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
FoldMskICmp_AMask_NotMixed)
: (FoldMskICmp_AMask_AllOnes |
FoldMskICmp_AMask_Mixed));
if (icmp_bbit)
result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
FoldMskICmp_BMask_NotMixed)
: (FoldMskICmp_BMask_AllOnes |
FoldMskICmp_BMask_Mixed));
return result;
}
if (A == C) {
result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
FoldMskICmp_AMask_Mixed)
: (FoldMskICmp_AMask_NotAllOnes |
FoldMskICmp_AMask_NotMixed));
if (icmp_abit)
result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
FoldMskICmp_AMask_NotMixed)
: (FoldMskICmp_Mask_AllZeroes |
FoldMskICmp_AMask_Mixed));
} else if (ACst && CCst &&
ConstantExpr::getAnd(ACst, CCst) == CCst) {
result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
: FoldMskICmp_AMask_NotMixed);
}
if (B == C) {
result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
FoldMskICmp_BMask_Mixed)
: (FoldMskICmp_BMask_NotAllOnes |
FoldMskICmp_BMask_NotMixed));
if (icmp_bbit)
result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
FoldMskICmp_BMask_NotMixed)
: (FoldMskICmp_Mask_AllZeroes |
FoldMskICmp_BMask_Mixed));
} else if (BCst && CCst &&
ConstantExpr::getAnd(BCst, CCst) == CCst) {
result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
: FoldMskICmp_BMask_NotMixed);
}
return result;
}
/// Convert an analysis of a masked ICmp into its equivalent if all boolean
/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
/// is adjacent to the corresponding normal flag (recording ==), this just
/// involves swapping those bits over.
static unsigned conjugateICmpMask(unsigned Mask) {
unsigned NewMask;
NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
FoldMskICmp_BMask_Mixed))
<< 1;
NewMask |=
(Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
FoldMskICmp_BMask_NotMixed))
>> 1;
return NewMask;
}
/// Decompose an icmp into the form ((X & Y) pred Z) if possible.
/// The returned predicate is either == or !=. Returns false if
/// decomposition fails.
static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
Value *&X, Value *&Y, Value *&Z) {
ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
if (!C)
return false;
switch (I->getPredicate()) {
default:
return false;
case ICmpInst::ICMP_SLT:
// X < 0 is equivalent to (X & SignBit) != 0.
if (!C->isZero())
return false;
Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
Pred = ICmpInst::ICMP_NE;
break;
case ICmpInst::ICMP_SGT:
// X > -1 is equivalent to (X & SignBit) == 0.
if (!C->isAllOnesValue())
return false;
Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
Pred = ICmpInst::ICMP_EQ;
break;
case ICmpInst::ICMP_ULT:
// X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
if (!C->getValue().isPowerOf2())
return false;
Y = ConstantInt::get(I->getContext(), -C->getValue());
Pred = ICmpInst::ICMP_EQ;
break;
case ICmpInst::ICMP_UGT:
// X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
if (!(C->getValue() + 1).isPowerOf2())
return false;
Y = ConstantInt::get(I->getContext(), ~C->getValue());
Pred = ICmpInst::ICMP_NE;
break;
}
X = I->getOperand(0);
Z = ConstantInt::getNullValue(C->getType());
return true;
}
/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
/// Return the set of pattern classes (from MaskedICmpType)
/// that both LHS and RHS satisfy.
static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
Value*& B, Value*& C,
Value*& D, Value*& E,
ICmpInst *LHS, ICmpInst *RHS,
ICmpInst::Predicate &LHSCC,
ICmpInst::Predicate &RHSCC) {
if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
// vectors are not (yet?) supported
if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
// Here comes the tricky part:
// LHS might be of the form L11 & L12 == X, X == L21 & L22,
// and L11 & L12 == L21 & L22. The same goes for RHS.
// Now we must find those components L** and R**, that are equal, so
// that we can extract the parameters A, B, C, D, and E for the canonical
// above.
Value *L1 = LHS->getOperand(0);
Value *L2 = LHS->getOperand(1);
Value *L11,*L12,*L21,*L22;
// Check whether the icmp can be decomposed into a bit test.
if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
L21 = L22 = L1 = nullptr;
} else {
// Look for ANDs in the LHS icmp.
if (!L1->getType()->isIntegerTy()) {
// You can icmp pointers, for example. They really aren't masks.
L11 = L12 = nullptr;
} else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
// Any icmp can be viewed as being trivially masked; if it allows us to
// remove one, it's worth it.
L11 = L1;
L12 = Constant::getAllOnesValue(L1->getType());
}
if (!L2->getType()->isIntegerTy()) {
// You can icmp pointers, for example. They really aren't masks.
L21 = L22 = nullptr;
} else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
L21 = L2;
L22 = Constant::getAllOnesValue(L2->getType());
}
}
// Bail if LHS was a icmp that can't be decomposed into an equality.
if (!ICmpInst::isEquality(LHSCC))
return 0;
Value *R1 = RHS->getOperand(0);
Value *R2 = RHS->getOperand(1);
Value *R11,*R12;
bool ok = false;
if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
A = R11; D = R12;
} else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
A = R12; D = R11;
} else {
return 0;
}
E = R2; R1 = nullptr; ok = true;
} else if (R1->getType()->isIntegerTy()) {
if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
// As before, model no mask as a trivial mask if it'll let us do an
// optimization.
R11 = R1;
R12 = Constant::getAllOnesValue(R1->getType());
}
if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
A = R11; D = R12; E = R2; ok = true;
} else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
A = R12; D = R11; E = R2; ok = true;
}
}
// Bail if RHS was a icmp that can't be decomposed into an equality.
if (!ICmpInst::isEquality(RHSCC))
return 0;
// Look for ANDs in on the right side of the RHS icmp.
if (!ok && R2->getType()->isIntegerTy()) {
if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
R11 = R2;
R12 = Constant::getAllOnesValue(R2->getType());
}
if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
A = R11; D = R12; E = R1; ok = true;
} else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
A = R12; D = R11; E = R1; ok = true;
} else {
return 0;
}
}
if (!ok)
return 0;
if (L11 == A) {
B = L12; C = L2;
} else if (L12 == A) {
B = L11; C = L2;
} else if (L21 == A) {
B = L22; C = L1;
} else if (L22 == A) {
B = L21; C = L1;
}
unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
return left_type & right_type;
}
/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
/// into a single (icmp(A & X) ==/!= Y).
static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
llvm::InstCombiner::BuilderTy *Builder) {
Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
LHSCC, RHSCC);
if (mask == 0) return nullptr;
assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
"foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
// In full generality:
// (icmp (A & B) Op C) | (icmp (A & D) Op E)
// == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
//
// If the latter can be converted into (icmp (A & X) Op Y) then the former is
// equivalent to (icmp (A & X) !Op Y).
//
// Therefore, we can pretend for the rest of this function that we're dealing
// with the conjunction, provided we flip the sense of any comparisons (both
// input and output).
// In most cases we're going to produce an EQ for the "&&" case.
ICmpInst::Predicate NEWCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
if (!IsAnd) {
// Convert the masking analysis into its equivalent with negated
// comparisons.
mask = conjugateICmpMask(mask);
}
if (mask & FoldMskICmp_Mask_AllZeroes) {
// (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
// -> (icmp eq (A & (B|D)), 0)
Value *newOr = Builder->CreateOr(B, D);
Value *newAnd = Builder->CreateAnd(A, newOr);
// we can't use C as zero, because we might actually handle
// (icmp ne (A & B), B) & (icmp ne (A & D), D)
// with B and D, having a single bit set
Value *zero = Constant::getNullValue(A->getType());
return Builder->CreateICmp(NEWCC, newAnd, zero);
}
if (mask & FoldMskICmp_BMask_AllOnes) {
// (icmp eq (A & B), B) & (icmp eq (A & D), D)
// -> (icmp eq (A & (B|D)), (B|D))
Value *newOr = Builder->CreateOr(B, D);
Value *newAnd = Builder->CreateAnd(A, newOr);
return Builder->CreateICmp(NEWCC, newAnd, newOr);
}
if (mask & FoldMskICmp_AMask_AllOnes) {
// (icmp eq (A & B), A) & (icmp eq (A & D), A)
// -> (icmp eq (A & (B&D)), A)
Value *newAnd1 = Builder->CreateAnd(B, D);
Value *newAnd = Builder->CreateAnd(A, newAnd1);
return Builder->CreateICmp(NEWCC, newAnd, A);
}
// Remaining cases assume at least that B and D are constant, and depend on
// their actual values. This isn't strictly, necessary, just a "handle the
// easy cases for now" decision.
ConstantInt *BCst = dyn_cast<ConstantInt>(B);
if (!BCst) return nullptr;
ConstantInt *DCst = dyn_cast<ConstantInt>(D);
if (!DCst) return nullptr;
if (mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
// (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
// (icmp ne (A & B), B) & (icmp ne (A & D), D)
// -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
// Only valid if one of the masks is a superset of the other (check "B&D" is
// the same as either B or D).
APInt NewMask = BCst->getValue() & DCst->getValue();
if (NewMask == BCst->getValue())
return LHS;
else if (NewMask == DCst->getValue())
return RHS;
}
if (mask & FoldMskICmp_AMask_NotAllOnes) {
// (icmp ne (A & B), B) & (icmp ne (A & D), D)
// -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
// Only valid if one of the masks is a superset of the other (check "B|D" is
// the same as either B or D).
APInt NewMask = BCst->getValue() | DCst->getValue();
if (NewMask == BCst->getValue())
return LHS;
else if (NewMask == DCst->getValue())
return RHS;
}
if (mask & FoldMskICmp_BMask_Mixed) {
// (icmp eq (A & B), C) & (icmp eq (A & D), E)
// We already know that B & C == C && D & E == E.
// If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
// C and E, which are shared by both the mask B and the mask D, don't
// contradict, then we can transform to
// -> (icmp eq (A & (B|D)), (C|E))
// Currently, we only handle the case of B, C, D, and E being constant.
// we can't simply use C and E, because we might actually handle
// (icmp ne (A & B), B) & (icmp eq (A & D), D)
// with B and D, having a single bit set
ConstantInt *CCst = dyn_cast<ConstantInt>(C);
if (!CCst) return nullptr;
ConstantInt *ECst = dyn_cast<ConstantInt>(E);
if (!ECst) return nullptr;
if (LHSCC != NEWCC)
CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
if (RHSCC != NEWCC)
ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
// if there is a conflict we should actually return a false for the
// whole construct
if (((BCst->getValue() & DCst->getValue()) &
(CCst->getValue() ^ ECst->getValue())) != 0)
return ConstantInt::get(LHS->getType(), !IsAnd);
Value *newOr1 = Builder->CreateOr(B, D);
Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
Value *newAnd = Builder->CreateAnd(A, newOr1);
return Builder->CreateICmp(NEWCC, newAnd, newOr2);
}
return nullptr;
}
/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
/// If \p Inverted is true then the check is for the inverted range, e.g.
/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
bool Inverted) {
// Check the lower range comparison, e.g. x >= 0
// InstCombine already ensured that if there is a constant it's on the RHS.
ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
if (!RangeStart)
return nullptr;
ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
Cmp0->getPredicate());
// Accept x > -1 or x >= 0 (after potentially inverting the predicate).
if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
(Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
return nullptr;
ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
Cmp1->getPredicate());
Value *Input = Cmp0->getOperand(0);
Value *RangeEnd;
if (Cmp1->getOperand(0) == Input) {
// For the upper range compare we have: icmp x, n
RangeEnd = Cmp1->getOperand(1);
} else if (Cmp1->getOperand(1) == Input) {
// For the upper range compare we have: icmp n, x
RangeEnd = Cmp1->getOperand(0);
Pred1 = ICmpInst::getSwappedPredicate(Pred1);
} else {
return nullptr;
}
// Check the upper range comparison, e.g. x < n
ICmpInst::Predicate NewPred;
switch (Pred1) {
case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
default: return nullptr;
}
// This simplification is only valid if the upper range is not negative.
bool IsNegative, IsNotNegative;
ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1);
if (!IsNotNegative)
return nullptr;
if (Inverted)
NewPred = ICmpInst::getInversePredicate(NewPred);
return Builder->CreateICmp(NewPred, Input, RangeEnd);
}
/// Fold (icmp)&(icmp) if possible.
Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
// (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
if (PredicatesFoldable(LHSCC, RHSCC)) {
if (LHS->getOperand(0) == RHS->getOperand(1) &&
LHS->getOperand(1) == RHS->getOperand(0))
LHS->swapOperands();
if (LHS->getOperand(0) == RHS->getOperand(0) &&
LHS->getOperand(1) == RHS->getOperand(1)) {
Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
bool isSigned = LHS->isSigned() || RHS->isSigned();
return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
}
}
// handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
return V;
// E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
return V;
// E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
return V;
// This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
if (!LHSCst || !RHSCst) return nullptr;
if (LHSCst == RHSCst && LHSCC == RHSCC) {
// (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
// where C is a power of 2
if (LHSCC == ICmpInst::ICMP_ULT &&
LHSCst->getValue().isPowerOf2()) {
Value *NewOr = Builder->CreateOr(Val, Val2);
return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
}
// (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
Value *NewOr = Builder->CreateOr(Val, Val2);
return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
}
}
// (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
// where CMAX is the all ones value for the truncated type,
// iff the lower bits of C2 and CA are zero.
if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
LHS->hasOneUse() && RHS->hasOneUse()) {
Value *V;
ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
// (trunc x) == C1 & (and x, CA) == C2
// (and x, CA) == C2 & (trunc x) == C1
if (match(Val2, m_Trunc(m_Value(V))) &&
match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
SmallCst = RHSCst;
BigCst = LHSCst;
} else if (match(Val, m_Trunc(m_Value(V))) &&
match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
SmallCst = LHSCst;
BigCst = RHSCst;
}
if (SmallCst && BigCst) {
unsigned BigBitSize = BigCst->getType()->getBitWidth();
unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
// Check that the low bits are zero.
APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
}
}
}
// From here on, we only handle:
// (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
if (Val != Val2) return nullptr;
// ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
return nullptr;
// Make a constant range that's the intersection of the two icmp ranges.
// If the intersection is empty, we know that the result is false.
ConstantRange LHSRange =
ConstantRange::makeAllowedICmpRegion(LHSCC, LHSCst->getValue());
ConstantRange RHSRange =
ConstantRange::makeAllowedICmpRegion(RHSCC, RHSCst->getValue());
if (LHSRange.intersectWith(RHSRange).isEmptySet())
return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
// We can't fold (ugt x, C) & (sgt x, C2).
if (!PredicatesFoldable(LHSCC, RHSCC))
return nullptr;
// Ensure that the larger constant is on the RHS.
bool ShouldSwap;
if (CmpInst::isSigned(LHSCC) ||
(ICmpInst::isEquality(LHSCC) &&
CmpInst::isSigned(RHSCC)))
ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
else
ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
if (ShouldSwap) {
std::swap(LHS, RHS);
std::swap(LHSCst, RHSCst);
std::swap(LHSCC, RHSCC);
}
// At this point, we know we have two icmp instructions
// comparing a value against two constants and and'ing the result
// together. Because of the above check, we know that we only have
// icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
// (from the icmp folding check above), that the two constants
// are not equal and that the larger constant is on the RHS
assert(LHSCst != RHSCst && "Compares not folded above?");
switch (LHSCC) {
default: llvm_unreachable("Unknown integer condition code!");
case ICmpInst::ICMP_EQ:
switch (RHSCC) {
default: llvm_unreachable("Unknown integer condition code!");
case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
return LHS;
}
case ICmpInst::ICMP_NE:
switch (RHSCC) {
default: llvm_unreachable("Unknown integer condition code!");
case ICmpInst::ICMP_ULT:
if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
return Builder->CreateICmpULT(Val, LHSCst);
if (LHSCst->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
break; // (X != 13 & X u< 15) -> no change
case ICmpInst::ICMP_SLT:
if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
return Builder->CreateICmpSLT(Val, LHSCst);
break; // (X != 13 & X s< 15) -> no change
case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
return RHS;
case ICmpInst::ICMP_NE:
// Special case to get the ordering right when the values wrap around
// zero.
if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
std::swap(LHSCst, RHSCst);
if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
Val->getName()+".cmp");
}
break; // (X != 13 & X != 15) -> no change
}
break;
case ICmpInst::ICMP_ULT:
switch (RHSCC) {
default: llvm_unreachable("Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
break;
case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
return LHS;
case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
break;
}
break;
case ICmpInst::ICMP_SLT:
switch (RHSCC) {
default: llvm_unreachable("Unknown integer condition code!");
case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
break;
case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
return LHS;
case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
break;
}
break;
case ICmpInst::ICMP_UGT:
switch (RHSCC) {
default: llvm_unreachable("Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
return RHS;
case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
break;
case ICmpInst::ICMP_NE:
if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
return Builder->CreateICmp(LHSCC, Val, RHSCst);
break; // (X u> 13 & X != 15) -> no change
case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
break;
}
break;
case ICmpInst::ICMP_SGT:
switch (RHSCC) {
default: llvm_unreachable("Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
return RHS;
case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
break;
case ICmpInst::ICMP_NE:
if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
return Builder->CreateICmp(LHSCC, Val, RHSCst);
break; // (X s> 13 & X != 15) -> no change
case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
break;
}
break;
}
return nullptr;
}
/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
/// a Value which should already be inserted into the function.
Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
RHS->getPredicate() == FCmpInst::FCMP_ORD) {
if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
return nullptr;
// (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
// If either of the constants are nans, then the whole thing returns
// false.
if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
return Builder->getFalse();
return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
}
// Handle vector zeros. This occurs because the canonical form of
// "fcmp ord x,x" is "fcmp ord x, 0".
if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
isa<ConstantAggregateZero>(RHS->getOperand(1)))
return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
return nullptr;
}
Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
// Swap RHS operands to match LHS.
Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
std::swap(Op1LHS, Op1RHS);
}
if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
// Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
if (Op0CC == Op1CC)
return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
if (Op0CC == FCmpInst::FCMP_TRUE)
return RHS;
if (Op1CC == FCmpInst::FCMP_TRUE)
return LHS;
bool Op0Ordered;
bool Op1Ordered;
unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
// uno && ord -> false
if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
if (Op1Pred == 0) {
std::swap(LHS, RHS);
std::swap(Op0Pred, Op1Pred);
std::swap(Op0Ordered, Op1Ordered);
}
if (Op0Pred == 0) {
// uno && ueq -> uno && (uno || eq) -> uno
// ord && olt -> ord && (ord && lt) -> olt
if (!Op0Ordered && (Op0Ordered == Op1Ordered))
return LHS;
if (Op0Ordered && (Op0Ordered == Op1Ordered))
return RHS;
// uno && oeq -> uno && (ord && eq) -> false
if (!Op0Ordered)
return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
// ord && ueq -> ord && (uno || eq) -> oeq
return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
}
}
return nullptr;
}
/// Match De Morgan's Laws:
/// (~A & ~B) == (~(A | B))
/// (~A | ~B) == (~(A & B))
static Instruction *matchDeMorgansLaws(BinaryOperator &I,
InstCombiner::BuilderTy *Builder) {
auto Opcode = I.getOpcode();
assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
"Trying to match De Morgan's Laws with something other than and/or");
// Flip the logic operation.
if (Opcode == Instruction::And)
Opcode = Instruction::Or;
else
Opcode = Instruction::And;
Value *Op0 = I.getOperand(0);
Value *Op1 = I.getOperand(1);
// TODO: Use pattern matchers instead of dyn_cast.
if (Value *Op0NotVal = dyn_castNotVal(Op0))
if (Value *Op1NotVal = dyn_castNotVal(Op1))
if (Op0->hasOneUse() && Op1->hasOneUse()) {
Value *LogicOp = Builder->CreateBinOp(Opcode, Op0NotVal, Op1NotVal,
I.getName() + ".demorgan");
return BinaryOperator::CreateNot(LogicOp);
}
// De Morgan's Law in disguise:
// (zext(bool A) ^ 1) & (zext(bool B) ^ 1) -> zext(~(A | B))
// (zext(bool A) ^ 1) | (zext(bool B) ^ 1) -> zext(~(A & B))
Value *A = nullptr;
Value *B = nullptr;
ConstantInt *C1 = nullptr;
if (match(Op0, m_OneUse(m_Xor(m_ZExt(m_Value(A)), m_ConstantInt(C1)))) &&
match(Op1, m_OneUse(m_Xor(m_ZExt(m_Value(B)), m_Specific(C1))))) {
// TODO: This check could be loosened to handle different type sizes.
// Alternatively, we could fix the definition of m_Not to recognize a not
// operation hidden by a zext?
if (A->getType()->isIntegerTy(1) && B->getType()->isIntegerTy(1) &&
C1->isOne()) {
Value *LogicOp = Builder->CreateBinOp(Opcode, A, B,
I.getName() + ".demorgan");
Value *Not = Builder->CreateNot(LogicOp);
return CastInst::CreateZExtOrBitCast(Not, I.getType());
}
}
return nullptr;
}
Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
bool Changed = SimplifyAssociativeOrCommutative(I);
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
if (Value *V = SimplifyVectorOp(I))
return ReplaceInstUsesWith(I, V);
if (Value *V = SimplifyAndInst(Op0, Op1, DL, TLI, DT, AC))
return ReplaceInstUsesWith(I, V);
// (A|B)&(A|C) -> A|(B&C) etc
if (Value *V = SimplifyUsingDistributiveLaws(I))
return ReplaceInstUsesWith(I, V);
// See if we can simplify any instructions used by the instruction whose sole
// purpose is to compute bits we don't care about.
if (SimplifyDemandedInstructionBits(I))
return &I;
if (Value *V = SimplifyBSwap(I))
return ReplaceInstUsesWith(I, V);
if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
const APInt &AndRHSMask = AndRHS->getValue();
// Optimize a variety of ((val OP C1) & C2) combinations...
if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Value *Op0LHS = Op0I->getOperand(0);
Value *Op0RHS = Op0I->getOperand(1);
switch (Op0I->getOpcode()) {
default: break;
case Instruction::Xor:
case Instruction::Or: {
// If the mask is only needed on one incoming arm, push it up.
if (!Op0I->hasOneUse()) break;
APInt NotAndRHS(~AndRHSMask);
if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
// Not masking anything out for the LHS, move to RHS.
Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
Op0RHS->getName()+".masked");
return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
}
if (!isa<Constant>(Op0RHS) &&
MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
// Not masking anything out for the RHS, move to LHS.
Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
Op0LHS->getName()+".masked");
return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
}
break;
}
case Instruction::Add:
// ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
// ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
// ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
return BinaryOperator::CreateAnd(V, AndRHS);
if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
break;
case Instruction::Sub:
// ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
// ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
// ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
return BinaryOperator::CreateAnd(V, AndRHS);
// -x & 1 -> x & 1
if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
// (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
// has 1's for all bits that the subtraction with A might affect.
if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
uint32_t BitWidth = AndRHSMask.getBitWidth();
uint32_t Zeros = AndRHSMask.countLeadingZeros();
APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
if (MaskedValueIsZero(Op0LHS, Mask, 0, &I)) {
Value *NewNeg = Builder->CreateNeg(Op0RHS);
return BinaryOperator::CreateAnd(NewNeg, AndRHS);
}
}
break;
case Instruction::Shl:
case Instruction::LShr:
// (1 << x) & 1 --> zext(x == 0)
// (1 >> x) & 1 --> zext(x == 0)
if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Value *NewICmp =
Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
return new ZExtInst(NewICmp, I.getType());
}
break;
}
if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
return Res;
}
// If this is an integer truncation, and if the source is an 'and' with
// immediate, transform it. This frequently occurs for bitfield accesses.
{
Value *X = nullptr; ConstantInt *YC = nullptr;
if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
// Change: and (trunc (and X, YC) to T), C2
// into : and (trunc X to T), trunc(YC) & C2
// This will fold the two constants together, which may allow
// other simplifications.
Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
C3 = ConstantExpr::getAnd(C3, AndRHS);
return BinaryOperator::CreateAnd(NewCast, C3);
}
}
// Try to fold constant and into select arguments.
if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
if (Instruction *R = FoldOpIntoSelect(I, SI))
return R;
if (isa<PHINode>(Op0))
if (Instruction *NV = FoldOpIntoPhi(I))
return NV;
}
if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
return DeMorgan;
{
Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
// (A|B) & ~(A&B) -> A^B
if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
((A == C && B == D) || (A == D && B == C)))
return BinaryOperator::CreateXor(A, B);
// ~(A&B) & (A|B) -> A^B
if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
((A == C && B == D) || (A == D && B == C)))
return BinaryOperator::CreateXor(A, B);
// A&(A^B) => A & ~B
{
Value *tmpOp0 = Op0;
Value *tmpOp1 = Op1;
if (Op0->hasOneUse() &&
match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
if (A == Op1 || B == Op1 ) {
tmpOp1 = Op0;
tmpOp0 = Op1;
// Simplify below
}
}
if (tmpOp1->hasOneUse() &&
match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
if (B == tmpOp0) {
std::swap(A, B);
}
// Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
// A is originally -1 (or a vector of -1 and undefs), then we enter
// an endless loop. By checking that A is non-constant we ensure that
// we will never get to the loop.
if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
}
}
// (A&((~A)|B)) -> A&B
if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
return BinaryOperator::CreateAnd(A, Op1);
if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
return BinaryOperator::CreateAnd(A, Op0);
// (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
// ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
// (A | B) & ((~A) ^ B) -> (A & B)
if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
return BinaryOperator::CreateAnd(A, B);
// ((~A) ^ B) & (A | B) -> (A & B)
if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
match(Op1, m_Or(m_Specific(A), m_Specific(B))))
return BinaryOperator::CreateAnd(A, B);
}
{
ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
if (LHS && RHS)
if (Value *Res = FoldAndOfICmps(LHS, RHS))
return ReplaceInstUsesWith(I, Res);
// TODO: Make this recursive; it's a little tricky because an arbitrary
// number of 'and' instructions might have to be created.
Value *X, *Y;
if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
if (auto *Cmp = dyn_cast<ICmpInst>(X))
if (Value *Res = FoldAndOfICmps(LHS, Cmp))
return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
if (auto *Cmp = dyn_cast<ICmpInst>(Y))
if (Value *Res = FoldAndOfICmps(LHS, Cmp))
return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
}
if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
if (auto *Cmp = dyn_cast<ICmpInst>(X))
if (Value *Res = FoldAndOfICmps(Cmp, RHS))
return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
if (auto *Cmp = dyn_cast<ICmpInst>(Y))
if (Value *Res = FoldAndOfICmps(Cmp, RHS))
return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
}
}
// If and'ing two fcmp, try combine them into one.
if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
if (Value *Res = FoldAndOfFCmps(LHS, RHS))
return ReplaceInstUsesWith(I, Res);
if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Value *Op0COp = Op0C->getOperand(0);
Type *SrcTy = Op0COp->getType();
// fold (and (cast A), (cast B)) -> (cast (and A, B))
if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
SrcTy == Op1C->getOperand(0)->getType() &&
SrcTy->isIntOrIntVectorTy()) {
Value *Op1COp = Op1C->getOperand(0);
// Only do this if the casts both really cause code to be generated.
if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
}
// If this is and(cast(icmp), cast(icmp)), try to fold this even if the
// cast is otherwise not optimizable. This happens for vector sexts.
if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
if (Value *Res = FoldAndOfICmps(LHS, RHS))
return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
// If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
// cast is otherwise not optimizable. This happens for vector sexts.
if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
if (Value *Res = FoldAndOfFCmps(LHS, RHS))
return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
}
}
// If we are masking off the sign bit of a floating-point value, convert
// this to the canonical fabs intrinsic call and cast back to integer.
// The backend should know how to optimize fabs().
// TODO: This transform should also apply to vectors.
ConstantInt *CI;
if (isa<BitCastInst>(Op0C) && SrcTy->isFloatingPointTy() &&
match(Op1, m_ConstantInt(CI)) && CI->isMaxValue(true)) {
Module *M = I.getParent()->getParent()->getParent();
Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, SrcTy);
Value *Call = Builder->CreateCall(Fabs, Op0COp, "fabs");
return CastInst::CreateBitOrPointerCast(Call, I.getType());
}
}
{
Value *X = nullptr;
bool OpsSwapped = false;
// Canonicalize SExt or Not to the LHS
if (match(Op1, m_SExt(m_Value())) ||
match(Op1, m_Not(m_Value()))) {
std::swap(Op0, Op1);
OpsSwapped = true;
}
// Fold (and (sext bool to A), B) --> (select bool, B, 0)
if (match(Op0, m_SExt(m_Value(X))) &&
X->getType()->getScalarType()->isIntegerTy(1)) {
Value *Zero = Constant::getNullValue(Op1->getType());
return SelectInst::Create(X, Op1, Zero);
}
// Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
X->getType()->getScalarType()->isIntegerTy(1)) {
Value *Zero = Constant::getNullValue(Op0->getType());
return SelectInst::Create(X, Zero, Op1);
}
if (OpsSwapped)
std::swap(Op0, Op1);
}
return Changed ? &I : nullptr;
}
/// Analyze the specified subexpression and see if it is capable of providing
/// pieces of a bswap. The subexpression provides pieces of a bswap if it is
/// proven that each of the non-zero bytes in the output of the expression came
/// from the corresponding "byte swapped" byte in some other value.
/// For example, if the current subexpression is "(shl i32 %X, 24)" then
/// we know that the expression deposits the low byte of %X into the high byte
/// of the bswap result and that all other bytes are zero. This expression is
/// accepted, the high byte of ByteValues is set to X to indicate a correct
/// match.
///
/// This function returns true if the match was unsuccessful and false if so.
/// On entry to the function the "OverallLeftShift" is a signed integer value
/// indicating the number of bytes that the subexpression is later shifted. For
/// example, if the expression is later right shifted by 16 bits, the
/// OverallLeftShift value would be -2 on entry. This is used to specify which
/// byte of ByteValues is actually being set.
///
/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
/// byte is masked to zero by a user. For example, in (X & 255), X will be
/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
/// this function to working on up to 32-byte (256 bit) values. ByteMask is
/// always in the local (OverallLeftShift) coordinate space.
///
static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
SmallVectorImpl<Value *> &ByteValues) {
if (Instruction *I = dyn_cast<Instruction>(V)) {
// If this is an or instruction, it may be an inner node of the bswap.
if (I->getOpcode() == Instruction::Or) {
return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
ByteValues) ||
CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
ByteValues);
}
// If this is a logical shift by a constant multiple of 8, recurse with
// OverallLeftShift and ByteMask adjusted.
if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
unsigned ShAmt =
cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
// Ensure the shift amount is defined and of a byte value.
if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
return true;
unsigned ByteShift = ShAmt >> 3;
if (I->getOpcode() == Instruction::Shl) {
// X << 2 -> collect(X, +2)
OverallLeftShift += ByteShift;
ByteMask >>= ByteShift;
} else {
// X >>u 2 -> collect(X, -2)
OverallLeftShift -= ByteShift;
ByteMask <<= ByteShift;
ByteMask &= (~0U >> (32-ByteValues.size()));
}
if (OverallLeftShift >= (int)ByteValues.size()) return true;
if (OverallLeftShift <= -(int)ByteValues.size()) return true;
return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
ByteValues);
}
// If this is a logical 'and' with a mask that clears bytes, clear the
// corresponding bytes in ByteMask.
if (I->getOpcode() == Instruction::And &&
isa<ConstantInt>(I->getOperand(1))) {
// Scan every byte of the and mask, seeing if the byte is either 0 or 255.
unsigned NumBytes = ByteValues.size();
APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
// If this byte is masked out by a later operation, we don't care what
// the and mask is.
if ((ByteMask & (1 << i)) == 0)
continue;
// If the AndMask is all zeros for this byte, clear the bit.
APInt MaskB = AndMask & Byte;
if (MaskB == 0) {
ByteMask &= ~(1U << i);
continue;
}
// If the AndMask is not all ones for this byte, it's not a bytezap.
if (MaskB != Byte)
return true;
// Otherwise, this byte is kept.
}
return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
ByteValues);
}
}
// Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
// the input value to the bswap. Some observations: 1) if more than one byte
// is demanded from this input, then it could not be successfully assembled
// into a byteswap. At least one of the two bytes would not be aligned with
// their ultimate destination.
if (!isPowerOf2_32(ByteMask)) return true;
unsigned InputByteNo = countTrailingZeros(ByteMask);
// 2) The input and ultimate destinations must line up: if byte 3 of an i32
// is demanded, it needs to go into byte 0 of the result. This means that the
// byte needs to be shifted until it lands in the right byte bucket. The
// shift amount depends on the position: if the byte is coming from the high
// part of the value (e.g. byte 3) then it must be shifted right. If from the
// low part, it must be shifted left.
unsigned DestByteNo = InputByteNo + OverallLeftShift;
if (ByteValues.size()-1-DestByteNo != InputByteNo)
return true;
// If the destination byte value is already defined, the values are or'd
// together, which isn't a bswap (unless it's an or of the same bits).
if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
return true;
ByteValues[DestByteNo] = V;
return false;
}
/// Given an OR instruction, check to see if this is a bswap idiom.
/// If so, insert the new bswap intrinsic and return it.
Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
if (!ITy || ITy->getBitWidth() % 16 ||
// ByteMask only allows up to 32-byte values.
ITy->getBitWidth() > 32*8)
return nullptr; // Can only bswap pairs of bytes. Can't do vectors.
/// ByteValues - For each byte of the result, we keep track of which value
/// defines each byte.
SmallVector<Value*, 8> ByteValues;
ByteValues.resize(ITy->getBitWidth()/8);
// Try to find all the pieces corresponding to the bswap.
uint32_t ByteMask = ~0U >> (32-ByteValues.size());
if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
return nullptr;
// Check to see if all of the bytes come from the same value.
Value *V = ByteValues[0];
if (!V) return nullptr; // Didn't find a byte? Must be zero.
// Check to make sure that all of the bytes come from the same value.
for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
if (ByteValues[i] != V)
return nullptr;
Module *M = I.getParent()->getParent()->getParent();
Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
return CallInst::Create(F, V);
}
/// We have an expression of the form (A&C)|(B&D). Check if A is (cond?-1:0)
/// and either B or D is ~(cond?-1,0) or (cond?0,-1), then we can simplify this
/// expression to "cond ? C : D or B".
static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Value *C, Value *D) {
// If A is not a select of -1/0, this cannot match.
Value *Cond = nullptr;
if (!match(A, m_SExt(m_Value(Cond))) ||
!Cond->getType()->isIntegerTy(1))
return nullptr;
// ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
return SelectInst::Create(Cond, C, B);
if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
return SelectInst::Create(Cond, C, B);
// ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
return SelectInst::Create(Cond, C, D);
if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
return SelectInst::Create(Cond, C, D);
return nullptr;
}
/// Fold (icmp)|(icmp) if possible.
Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
Instruction *CxtI) {
ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
// Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
// if K1 and K2 are a one-bit mask.
ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
LAnd->getOpcode() == Instruction::And &&
RAnd->getOpcode() == Instruction::And) {
Value *Mask = nullptr;
Value *Masked = nullptr;
if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, AC, CxtI,
DT) &&
isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, AC, CxtI,
DT)) {
Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
} else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, AC,
CxtI, DT) &&
isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, AC,
CxtI, DT)) {
Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
}
if (Masked)
return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
}
}
// Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
// --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
// The original condition actually refers to the following two ranges:
// [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
// We can fold these two ranges if:
// 1) C1 and C2 is unsigned greater than C3.
// 2) The two ranges are separated.
// 3) C1 ^ C2 is one-bit mask.
// 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
// This implies all values in the two ranges differ by exactly one bit.
if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
LHSCst->getValue() == (RHSCst->getValue())) {
Value *LAdd = LHS->getOperand(0);
Value *RAdd = RHS->getOperand(0);
Value *LAddOpnd, *RAddOpnd;
ConstantInt *LAddCst, *RAddCst;
if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
LAddCst->getValue().ugt(LHSCst->getValue()) &&
RAddCst->getValue().ugt(LHSCst->getValue())) {
APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
ConstantInt *MaxAddCst = nullptr;
if (LAddCst->getValue().ult(RAddCst->getValue()))
MaxAddCst = RAddCst;
else
MaxAddCst = LAddCst;
APInt RRangeLow = -RAddCst->getValue();
APInt RRangeHigh = RRangeLow + LHSCst->getValue();
APInt LRangeLow = -LAddCst->getValue();
APInt LRangeHigh = LRangeLow + LHSCst->getValue();
APInt LowRangeDiff = RRangeLow ^ LRangeLow;
APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
: RRangeLow - LRangeLow;
if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
RangeDiff.ugt(LHSCst->getValue())) {
Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
}
}
}
}
// (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
if (PredicatesFoldable(LHSCC, RHSCC)) {
if (LHS->getOperand(0) == RHS->getOperand(1) &&
LHS->getOperand(1) == RHS->getOperand(0))
LHS->swapOperands();
if (LHS->getOperand(0) == RHS->getOperand(0) &&
LHS->getOperand(1) == RHS->getOperand(1)) {
Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
bool isSigned = LHS->isSigned() || RHS->isSigned();
return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
}
}
// handle (roughly):
// (icmp ne (A & B), C) | (icmp ne (A & D), E)
if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
return V;
Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
if (LHS->hasOneUse() || RHS->hasOneUse()) {
// (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
// (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Value *A = nullptr, *B = nullptr;
if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
B = Val;
if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
A = Val2;
else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
A = RHS->getOperand(1);
}
// (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
// (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
B = Val2;
if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
A = Val;
else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
A = LHS->getOperand(1);
}
if (A && B)
return Builder->CreateICmp(
ICmpInst::ICMP_UGE,
Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
}
// E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
return V;
// E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
return V;
// This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
if (!LHSCst || !RHSCst) return nullptr;
if (LHSCst == RHSCst && LHSCC == RHSCC) {
// (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
Value *NewOr = Builder->CreateOr(Val, Val2);
return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
}
}
// (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
// iff C2 + CA == C1.
if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
ConstantInt *AddCst;
if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
return Builder->CreateICmpULE(Val, LHSCst);
}
// From here on, we only handle:
// (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
if (Val != Val2) return nullptr;
// ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
return nullptr;
// We can't fold (ugt x, C) | (sgt x, C2).
if (!PredicatesFoldable(LHSCC, RHSCC))
return nullptr;
// Ensure that the larger constant is on the RHS.
bool ShouldSwap;
if (CmpInst::isSigned(LHSCC) ||
(ICmpInst::isEquality(LHSCC) &&
CmpInst::isSigned(RHSCC)))
ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
else
ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
if (ShouldSwap) {
std::swap(LHS, RHS);
std::swap(LHSCst, RHSCst);
std::swap(LHSCC, RHSCC);
}
// At this point, we know we have two icmp instructions
// comparing a value against two constants and or'ing the result
// together. Because of the above check, we know that we only have
// ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
// icmp folding check above), that the two constants are not
// equal.
assert(LHSCst != RHSCst && "Compares not folded above?");
switch (LHSCC) {
default: llvm_unreachable("Unknown integer condition code!");
case ICmpInst::ICMP_EQ:
switch (RHSCC) {
default: llvm_unreachable("Unknown integer condition code!");
case ICmpInst::ICMP_EQ:
if (LHS->getOperand(0) == RHS->getOperand(0)) {
// if LHSCst and RHSCst differ only by one bit:
// (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
assert(LHSCst->getValue().ule(LHSCst->getValue()));
APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
if (Xor.isPowerOf2()) {
Value *NegCst = Builder->getInt(~Xor);
Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
}
}
if (LHSCst == SubOne(RHSCst)) {
// (X == 13 | X == 14) -> X-13 <u 2
Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
return Builder->CreateICmpULT(Add, AddCST);
}
break; // (X == 13 | X == 15) -> no change
case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
break;
case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
return RHS;
}
break;
case ICmpInst::ICMP_NE:
switch (RHSCC) {
default: llvm_unreachable("Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
return LHS;
case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
return Builder->getTrue();
}
case ICmpInst::ICMP_ULT:
switch (RHSCC) {
default: llvm_unreachable("Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
break;
case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
// If RHSCst is [us]MAXINT, it is always false. Not handling
// this can cause overflow.
if (RHSCst->isMaxValue(false))
return LHS;
return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
break;
case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
return RHS;
case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
break;
}
break;
case ICmpInst::ICMP_SLT:
switch (RHSCC) {
default: llvm_unreachable("Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
break;
case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
// If RHSCst is [us]MAXINT, it is always false. Not handling
// this can cause overflow.
if (RHSCst->isMaxValue(true))
return LHS;
return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
break;
case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
return RHS;
case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
break;
}
break;
case ICmpInst::ICMP_UGT:
switch (RHSCC) {
default: llvm_unreachable("Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
return LHS;
case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
break;
case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
return Builder->getTrue();
case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
break;
}
break;
case ICmpInst::ICMP_SGT:
switch (RHSCC) {
default: llvm_unreachable("Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
return LHS;
case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
break;
case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
return Builder->getTrue();
case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
break;
}
break;
}
return nullptr;
}
/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
/// a Value which should already be inserted into the function.
Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
RHS->getPredicate() == FCmpInst::FCMP_UNO &&
LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
// If either of the constants are nans, then the whole thing returns
// true.
if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
return Builder->getTrue();
// Otherwise, no need to compare the two constants, compare the
// rest.
return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
}
// Handle vector zeros. This occurs because the canonical form of
// "fcmp uno x,x" is "fcmp uno x, 0".
if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
isa<ConstantAggregateZero>(RHS->getOperand(1)))
return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
return nullptr;
}
Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
// Swap RHS operands to match LHS.
Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
std::swap(Op1LHS, Op1RHS);
}
if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
// Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
if (Op0CC == Op1CC)
return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
if (Op0CC == FCmpInst::FCMP_FALSE)
return RHS;
if (Op1CC == FCmpInst::FCMP_FALSE)
return LHS;
bool Op0Ordered;
bool Op1Ordered;
unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
if (Op0Ordered == Op1Ordered) {
// If both are ordered or unordered, return a new fcmp with
// or'ed predicates.
return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
}
}
return nullptr;
}
/// This helper function folds:
///
/// ((A | B) & C1) | (B & C2)
///
/// into:
///
/// (A & C1) | B
///
/// when the XOR of the two constants is "all ones" (-1).
Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Value *A, Value *B, Value *C) {
ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
if (!CI1) return nullptr;
Value *V1 = nullptr;
ConstantInt *CI2 = nullptr;
if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
APInt Xor = CI1->getValue() ^ CI2->getValue();
if (!Xor.isAllOnesValue()) return nullptr;
if (V1 == A || V1 == B) {
Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
return BinaryOperator::CreateOr(NewOp, V1);
}
return nullptr;
}
/// \brief This helper function folds:
///
/// ((A | B) & C1) ^ (B & C2)
///
/// into:
///
/// (A & C1) ^ B
///
/// when the XOR of the two constants is "all ones" (-1).
Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
Value *A, Value *B, Value *C) {
ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
if (!CI1)
return nullptr;
Value *V1 = nullptr;
ConstantInt *CI2 = nullptr;
if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
return nullptr;
APInt Xor = CI1->getValue() ^ CI2->getValue();
if (!Xor.isAllOnesValue())
return nullptr;
if (V1 == A || V1 == B) {
Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
return BinaryOperator::CreateXor(NewOp, V1);
}
return nullptr;
}
Instruction *InstCombiner::visitOr(BinaryOperator &I) {
bool Changed = SimplifyAssociativeOrCommutative(I);
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
if (Value *V = SimplifyVectorOp(I))
return ReplaceInstUsesWith(I, V);
if (Value *V = SimplifyOrInst(Op0, Op1, DL, TLI, DT, AC))
return ReplaceInstUsesWith(I, V);
// (A&B)|(A&C) -> A&(B|C) etc
if (Value *V = SimplifyUsingDistributiveLaws(I))
return ReplaceInstUsesWith(I, V);
// See if we can simplify any instructions used by the instruction whose sole
// purpose is to compute bits we don't care about.
if (SimplifyDemandedInstructionBits(I))
return &I;
if (Value *V = SimplifyBSwap(I))
return ReplaceInstUsesWith(I, V);
if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
ConstantInt *C1 = nullptr; Value *X = nullptr;
// (X & C1) | C2 --> (X | C2) & (C1|C2)
// iff (C1 & C2) == 0.
if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
(RHS->getValue() & C1->getValue()) != 0 &&
Op0->hasOneUse()) {
Value *Or = Builder->CreateOr(X, RHS);
Or->takeName(Op0);
return BinaryOperator::CreateAnd(Or,
Builder->getInt(RHS->getValue() | C1->getValue()));
}
// (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Op0->hasOneUse()) {
Value *Or = Builder->CreateOr(X, RHS);
Or->takeName(Op0);
return BinaryOperator::CreateXor(Or,
Builder->getInt(C1->getValue() & ~RHS->getValue()));
}
// Try to fold constant and into select arguments.
if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
if (Instruction *R = FoldOpIntoSelect(I, SI))
return R;
if (isa<PHINode>(Op0))
if (Instruction *NV = FoldOpIntoPhi(I))
return NV;
}
Value *A = nullptr, *B = nullptr;
ConstantInt *C1 = nullptr, *C2 = nullptr;
// (A | B) | C and A | (B | C) -> bswap if possible.
bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
match(Op1, m_Or(m_Value(), m_Value()));
// (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
match(Op1, m_LogicalShift(m_Value(), m_Value()));
// (A & B) | (C & D) -> bswap if possible.
bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
match(Op1, m_And(m_Value(), m_Value()));
if (OrOfOrs || OrOfShifts || OrOfAnds)
if (Instruction *BSwap = MatchBSwap(I))
return BSwap;
// (X^C)|Y -> (X|Y)^C iff Y&C == 0
if (Op0->hasOneUse() &&
match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
Value *NOr = Builder->CreateOr(A, Op1);
NOr->takeName(Op0);
return BinaryOperator::CreateXor(NOr, C1);
}
// Y|(X^C) -> (X|Y)^C iff Y&C == 0
if (Op1->hasOneUse() &&
match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
Value *NOr = Builder->CreateOr(A, Op0);
NOr->takeName(Op0);
return BinaryOperator::CreateXor(NOr, C1);
}
// ((~A & B) | A) -> (A | B)
if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
match(Op1, m_Specific(A)))
return BinaryOperator::CreateOr(A, B);
// ((A & B) | ~A) -> (~A | B)
if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
match(Op1, m_Not(m_Specific(A))))
return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
// (A & (~B)) | (A ^ B) -> (A ^ B)
if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
return BinaryOperator::CreateXor(A, B);
// (A ^ B) | ( A & (~B)) -> (A ^ B)
if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))
return BinaryOperator::CreateXor(A, B);
// (A & C)|(B & D)
Value *C = nullptr, *D = nullptr;
if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
match(Op1, m_And(m_Value(B), m_Value(D)))) {
Value *V1 = nullptr, *V2 = nullptr;
C1 = dyn_cast<ConstantInt>(C);
C2 = dyn_cast<ConstantInt>(D);
if (C1 && C2) { // (A & C1)|(B & C2)
if ((C1->getValue() & C2->getValue()) == 0) {
// ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
// iff (C1&C2) == 0 and (N&~C1) == 0
if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
((V1 == B &&
MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
(V2 == B &&
MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
return BinaryOperator::CreateAnd(A,
Builder->getInt(C1->getValue()|C2->getValue()));
// Or commutes, try both ways.
if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
((V1 == A &&
MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
(V2 == A &&
MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
return BinaryOperator::CreateAnd(B,
Builder->getInt(C1->getValue()|C2->getValue()));
// ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
// iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
ConstantInt *C3 = nullptr, *C4 = nullptr;
if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
(C3->getValue() & ~C1->getValue()) == 0 &&
match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
(C4->getValue() & ~C2->getValue()) == 0) {
V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
return BinaryOperator::CreateAnd(V2,
Builder->getInt(C1->getValue()|C2->getValue()));
}
}
}
// (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
// Don't do this for vector select idioms, the code generator doesn't handle
// them well yet.
if (!I.getType()->isVectorTy()) {
if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
return Match;
if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
return Match;
if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
return Match;
if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
return Match;
}
// ((A&~B)|(~A&B)) -> A^B
if ((match(C, m_Not(m_Specific(D))) &&
match(B, m_Not(m_Specific(A)))))
return BinaryOperator::CreateXor(A, D);
// ((~B&A)|(~A&B)) -> A^B
if ((match(A, m_Not(m_Specific(D))) &&
match(B, m_Not(m_Specific(C)))))
return BinaryOperator::CreateXor(C, D);
// ((A&~B)|(B&~A)) -> A^B
if ((match(C, m_Not(m_Specific(B))) &&
match(D, m_Not(m_Specific(A)))))
return BinaryOperator::CreateXor(A, B);
// ((~B&A)|(B&~A)) -> A^B
if ((match(A, m_Not(m_Specific(B))) &&
match(D, m_Not(m_Specific(C)))))
return BinaryOperator::CreateXor(C, B);
// ((A|B)&1)|(B&-2) -> (A&1) | B
if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
match(A, m_Or(m_Specific(B), m_Value(V1)))) {
Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
if (Ret) return Ret;
}
// (B&-2)|((A|B)&1) -> (A&1) | B
if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
match(B, m_Or(m_Value(V1), m_Specific(A)))) {
Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
if (Ret) return Ret;
}
// ((A^B)&1)|(B&-2) -> (A&1) ^ B
if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
if (Ret) return Ret;
}
// (B&-2)|((A^B)&1) -> (A&1) ^ B
if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
if (Ret) return Ret;
}
}
// (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
return BinaryOperator::CreateOr(Op0, C);
// ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
return BinaryOperator::CreateOr(Op1, C);
// ((B | C) & A) | B -> B | (A & C)
if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
return DeMorgan;
// Canonicalize xor to the RHS.
bool SwappedForXor = false;
if (match(Op0, m_Xor(m_Value(), m_Value()))) {
std::swap(Op0, Op1);
SwappedForXor = true;
}
// A | ( A ^ B) -> A | B
// A | (~A ^ B) -> A | ~B
// (A & B) | (A ^ B)
if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
if (Op0 == A || Op0 == B)
return BinaryOperator::CreateOr(A, B);
if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
match(Op0, m_And(m_Specific(B), m_Specific(A))))
return BinaryOperator::CreateOr(A, B);
if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
Value *Not = Builder->CreateNot(B, B->getName()+".not");
return BinaryOperator::CreateOr(Not, Op0);
}
if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
Value *Not = Builder->CreateNot(A, A->getName()+".not");
return BinaryOperator::CreateOr(Not, Op0);
}
}
// A | ~(A | B) -> A | ~B
// A | ~(A ^ B) -> A | ~B
if (match(Op1, m_Not(m_Value(A))))
if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
B->getOpcode() == Instruction::Xor)) {
Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
B->getOperand(0);
Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
return BinaryOperator::CreateOr(Not, Op0);
}
// (A & B) | ((~A) ^ B) -> (~A ^ B)
if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
// ((~A) ^ B) | (A & B) -> (~A ^ B)
if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
match(Op1, m_And(m_Specific(A), m_Specific(B))))
return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
if (SwappedForXor)
std::swap(Op0, Op1);
{
ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
if (LHS && RHS)
if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
return ReplaceInstUsesWith(I, Res);
// TODO: Make this recursive; it's a little tricky because an arbitrary
// number of 'or' instructions might have to be created.
Value *X, *Y;
if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
if (auto *Cmp = dyn_cast<ICmpInst>(X))
if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
if (auto *Cmp = dyn_cast<ICmpInst>(Y))
if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
}
if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
if (auto *Cmp = dyn_cast<ICmpInst>(X))
if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
if (auto *Cmp = dyn_cast<ICmpInst>(Y))
if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
}
}
// (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
if (Value *Res = FoldOrOfFCmps(LHS, RHS))
return ReplaceInstUsesWith(I, Res);
// fold (or (cast A), (cast B)) -> (cast (or A, B))
if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
CastInst *Op1C = dyn_cast<CastInst>(Op1);
if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Type *SrcTy = Op0C->getOperand(0)->getType();
if (SrcTy == Op1C->getOperand(0)->getType() &&
SrcTy->isIntOrIntVectorTy()) {
Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
// Only do this if the casts both really cause code to be
// generated.
ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
}
// If this is or(cast(icmp), cast(icmp)), try to fold this even if the
// cast is otherwise not optimizable. This happens for vector sexts.
if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
// If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
// cast is otherwise not optimizable. This happens for vector sexts.
if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
if (Value *Res = FoldOrOfFCmps(LHS, RHS))
return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
}
}
}
// or(sext(A), B) -> A ? -1 : B where A is an i1
// or(A, sext(B)) -> B ? -1 : A where B is an i1
if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
// Note: If we've gotten to the point of visiting the outer OR, then the
// inner one couldn't be simplified. If it was a constant, then it won't
// be simplified by a later pass either, so we try swapping the inner/outer
// ORs in the hopes that we'll be able to simplify it this way.
// (X|C) | V --> (X|V) | C
if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
Value *Inner = Builder->CreateOr(A, Op1);
Inner->takeName(Op0);
return BinaryOperator::CreateOr(Inner, C1);
}
// Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
// Since this OR statement hasn't been optimized further yet, we hope
// that this transformation will allow the new ORs to be optimized.
{
Value *X = nullptr, *Y = nullptr;
if (Op0->hasOneUse() && Op1->hasOneUse() &&
match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
Value *orTrue = Builder->CreateOr(A, C);
Value *orFalse = Builder->CreateOr(B, D);
return SelectInst::Create(X, orTrue, orFalse);
}
}
return Changed ? &I : nullptr;
}
Instruction *InstCombiner::visitXor(BinaryOperator &I) {
bool Changed = SimplifyAssociativeOrCommutative(I);
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
if (Value *V = SimplifyVectorOp(I))
return ReplaceInstUsesWith(I, V);
if (Value *V = SimplifyXorInst(Op0, Op1, DL, TLI, DT, AC))
return ReplaceInstUsesWith(I, V);
// (A&B)^(A&C) -> A&(B^C) etc
if (Value *V = SimplifyUsingDistributiveLaws(I))
return ReplaceInstUsesWith(I, V);
// See if we can simplify any instructions used by the instruction whose sole
// purpose is to compute bits we don't care about.
if (SimplifyDemandedInstructionBits(I))
return &I;
if (Value *V = SimplifyBSwap(I))
return ReplaceInstUsesWith(I, V);
// Is this a ~ operation?
if (Value *NotOp = dyn_castNotVal(&I)) {
if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
if (Op0I->getOpcode() == Instruction::And ||
Op0I->getOpcode() == Instruction::Or) {
// ~(~X & Y) --> (X | ~Y) - De Morgan's Law
// ~(~X | Y) === (X & ~Y) - De Morgan's Law
if (dyn_castNotVal(Op0I->getOperand(1)))
Op0I->swapOperands();
if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Value *NotY =
Builder->CreateNot(Op0I->getOperand(1),
Op0I->getOperand(1)->getName()+".not");
if (Op0I->getOpcode() == Instruction::And)
return BinaryOperator::CreateOr(Op0NotVal, NotY);
return BinaryOperator::CreateAnd(Op0NotVal, NotY);
}
// ~(X & Y) --> (~X | ~Y) - De Morgan's Law
// ~(X | Y) === (~X & ~Y) - De Morgan's Law
if (IsFreeToInvert(Op0I->getOperand(0),
Op0I->getOperand(0)->hasOneUse()) &&
IsFreeToInvert(Op0I->getOperand(1),
Op0I->getOperand(1)->hasOneUse())) {
Value *NotX =
Builder->CreateNot(Op0I->getOperand(0), "notlhs");
Value *NotY =
Builder->CreateNot(Op0I->getOperand(1), "notrhs");
if (Op0I->getOpcode() == Instruction::And)
return BinaryOperator::CreateOr(NotX, NotY);
return BinaryOperator::CreateAnd(NotX, NotY);
}
} else if (Op0I->getOpcode() == Instruction::AShr) {
// ~(~X >>s Y) --> (X >>s Y)
if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
}
}
}
if (Constant *RHS = dyn_cast<Constant>(Op1)) {
if (RHS->isAllOnesValue() && Op0->hasOneUse())
// xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
return CmpInst::Create(CI->getOpcode(),
CI->getInversePredicate(),
CI->getOperand(0), CI->getOperand(1));
}
if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
// fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
if (CI->hasOneUse() && Op0C->hasOneUse()) {
Instruction::CastOps Opcode = Op0C->getOpcode();
if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
(RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Op0C->getDestTy()))) {
CI->setPredicate(CI->getInversePredicate());
return CastInst::Create(Opcode, CI, Op0C->getType());
}
}
}
}
if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
// ~(c-X) == X-c-1 == X+(-c-1)
if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
ConstantInt::get(I.getType(), 1));
return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
}
if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
if (Op0I->getOpcode() == Instruction::Add) {
// ~(X-c) --> (-c-1)-X
if (RHS->isAllOnesValue()) {
Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
return BinaryOperator::CreateSub(
ConstantExpr::getSub(NegOp0CI,
ConstantInt::get(I.getType(), 1)),
Op0I->getOperand(0));
} else if (RHS->getValue().isSignBit()) {
// (X + C) ^ signbit -> (X + C + signbit)
Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
}
} else if (Op0I->getOpcode() == Instruction::Or) {
// (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
0, &I)) {
Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
// Anything in both C1 and C2 is known to be zero, remove it from
// NewRHS.
Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
NewRHS = ConstantExpr::getAnd(NewRHS,
ConstantExpr::getNot(CommonBits));
Worklist.Add(Op0I);
I.setOperand(0, Op0I->getOperand(0));
I.setOperand(1, NewRHS);
return &I;
}
} else if (Op0I->getOpcode() == Instruction::LShr) {
// ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
// E1 = "X ^ C1"
BinaryOperator *E1;
ConstantInt *C1;
if (Op0I->hasOneUse() &&
(E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
E1->getOpcode() == Instruction::Xor &&
(C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
// fold (C1 >> C2) ^ C3
ConstantInt *C2 = Op0CI, *C3 = RHS;
APInt FoldConst = C1->getValue().lshr(C2->getValue());
FoldConst ^= C3->getValue();
// Prepare the two operands.
Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
Opnd0->takeName(Op0I);
cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
return BinaryOperator::CreateXor(Opnd0, FoldVal);
}
}
}
}
// Try to fold constant and into select arguments.
if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
if (Instruction *R = FoldOpIntoSelect(I, SI))
return R;
if (isa<PHINode>(Op0))
if (Instruction *NV = FoldOpIntoPhi(I))
return NV;
}
BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
if (Op1I) {
Value *A, *B;
if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
if (A == Op0) { // B^(B|A) == (A|B)^B
Op1I->swapOperands();
I.swapOperands();
std::swap(Op0, Op1);
} else if (B == Op0) { // B^(A|B) == (A|B)^B
I.swapOperands(); // Simplified below.
std::swap(Op0, Op1);
}
} else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Op1I->hasOneUse()){
if (A == Op0) { // A^(A&B) -> A^(B&A)
Op1I->swapOperands();
std::swap(A, B);
}
if (B == Op0) { // A^(B&A) -> (B&A)^A
I.swapOperands(); // Simplified below.
std::swap(Op0, Op1);
}
}
}
BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
if (Op0I) {
Value *A, *B;
if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Op0I->hasOneUse()) {
if (A == Op1) // (B|A)^B == (A|B)^B
std::swap(A, B);
if (B == Op1) // (A|B)^B == A & ~B
return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
} else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Op0I->hasOneUse()){
if (A == Op1) // (A&B)^A -> (B&A)^A
std::swap(A, B);
if (B == Op1 && // (B&A)^A == ~B & A
!isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
}
}
}
if (Op0I && Op1I) {
Value *A, *B, *C, *D;
// (A & B)^(A | B) -> A ^ B
if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
if ((A == C && B == D) || (A == D && B == C))
return BinaryOperator::CreateXor(A, B);
}
// (A | B)^(A & B) -> A ^ B
if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
match(Op1I, m_And(m_Value(C), m_Value(D)))) {
if ((A == C && B == D) || (A == D && B == C))
return BinaryOperator::CreateXor(A, B);
}
// (A | ~B) ^ (~A | B) -> A ^ B
if (match(Op0I, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) {
return BinaryOperator::CreateXor(A, B);
}
// (~A | B) ^ (A | ~B) -> A ^ B
if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
return BinaryOperator::CreateXor(A, B);
}
// (A & ~B) ^ (~A & B) -> A ^ B
if (match(Op0I, m_And(m_Value(A), m_Not(m_Value(B)))) &&
match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B)))) {
return BinaryOperator::CreateXor(A, B);
}
// (~A & B) ^ (A & ~B) -> A ^ B
if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
return BinaryOperator::CreateXor(A, B);
}
// (A ^ C)^(A | B) -> ((~A) & B) ^ C
if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
if (D == A)
return BinaryOperator::CreateXor(
Builder->CreateAnd(Builder->CreateNot(A), B), C);
if (D == B)
return BinaryOperator::CreateXor(
Builder->CreateAnd(Builder->CreateNot(B), A), C);
}
// (A | B)^(A ^ C) -> ((~A) & B) ^ C
if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
if (D == A)
return BinaryOperator::CreateXor(
Builder->CreateAnd(Builder->CreateNot(A), B), C);
if (D == B)
return BinaryOperator::CreateXor(
Builder->CreateAnd(Builder->CreateNot(B), A), C);
}
// (A & B) ^ (A ^ B) -> (A | B)
if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
return BinaryOperator::CreateOr(A, B);
// (A ^ B) ^ (A & B) -> (A | B)
if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
match(Op1I, m_And(m_Specific(A), m_Specific(B))))
return BinaryOperator::CreateOr(A, B);
}
Value *A = nullptr, *B = nullptr;
// (A & ~B) ^ (~A) -> ~(A & B)
if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
match(Op1, m_Not(m_Specific(A))))
return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
// (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
if (LHS->getOperand(0) == RHS->getOperand(1) &&
LHS->getOperand(1) == RHS->getOperand(0))
LHS->swapOperands();
if (LHS->getOperand(0) == RHS->getOperand(0) &&
LHS->getOperand(1) == RHS->getOperand(1)) {
Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
bool isSigned = LHS->isSigned() || RHS->isSigned();
return ReplaceInstUsesWith(I,
getNewICmpValue(isSigned, Code, Op0, Op1,
Builder));
}
}
// fold (xor (cast A), (cast B)) -> (cast (xor A, B))
if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
Type *SrcTy = Op0C->getOperand(0)->getType();
if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
// Only do this if the casts both really cause code to be generated.
ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
I.getType()) &&
ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
I.getType())) {
Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
Op1C->getOperand(0), I.getName());
return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
}
}
}
return Changed ? &I : nullptr;
}
|
/*This file is part of the FEBio Studio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio-Studio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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 "stdafx.h"
#include "GPLCObject.h"
#include "FETetGenMesher.h"
#include <GeomLib/geom.h>
#include "GSketch.h"
#include <MeshLib/triangulate.h>
#include <MeshLib/FEMesh.h>
//-----------------------------------------------------------------------------
GPLCObject::GPLCObject() : GObject(GPLC_OBJECT)
{
SetFEMesher(new FETetGenMesher(this));
}
//-----------------------------------------------------------------------------
FEMeshBase* GPLCObject::GetEditableMesh()
{
return GetFEMesh();
}
//-----------------------------------------------------------------------------
FEMesh* GPLCObject::BuildMesh()
{
SetFEMesh(GetFEMesher()->BuildMesh());
return GetFEMesh();
}
inline double Measure(vec2d& a, vec2d& b)
{
double cw = 0.5*(1.0 - a*b);
vec2d c(0,0);
if (IsLeft(c, a, b) == false) cw = -cw;
return cw;
}
//-----------------------------------------------------------------------------
// Create a PLC Object from a sketch
void GPLCObject::Create(GSketch &s)
{
int i;
const double eps = 0.0001;
// add all the nodes
int NP = s.Points();
for (i=0; i<NP; ++i)
{
GSketch::POINT& p = s.Point(i);
AddNode(p.r);
}
// add all the edges
int NE = s.Edges();
for (i=0; i<NE; ++i)
{
GSketch::EDGE& e = s.Edge(i);
switch (e.ntype)
{
case GSketch::LINE:
AddLine(e.n[0], e.n[1]);
break;
case GSketch::ARC:
AddCircularArc(e.nc, e.n[0], e.n[1]);
break;
default:
assert(false);
}
}
// Find all the faces
for (i=0; i<NE; ++i) Edge(i)->m_ntag = 0;
GEdge* pe = 0;
do
{
// The nodal tags store the number of edges
// that reference them
for (i=0; i<NP; ++i) Node(i)->m_ntag = 0;
for (i=0; i<NE; ++i)
{
GEdge& e = *Edge(i);
if (e.m_ntag == 0)
{
Node(e.m_node[0])->m_ntag += 1;
Node(e.m_node[1])->m_ntag += 1;
}
}
// Find the lowest point. If multiple lowest points
// exist, we pick the most left one.
int imin = -1;
vec3d rmin;
for (i=0; i<NP; ++i)
{
GNode& node = *Node(i);
if (node.m_ntag > 0)
{
if (imin == -1)
{
imin = i;
rmin = node.LocalPosition();
}
else
{
vec3d r = node.LocalPosition();
if ((r.y < rmin.y) || ((r.y == rmin.y)&&(r.x < rmin.x)))
{
imin = i;
rmin = r;
}
}
}
}
// Make sure we found a point
if (imin == -1) break;
// find the lowest unprocessed edge that starts from this node
// If the edge ends at this node, we know that we have to flip it
int ew = 0;
pe = 0;
vec2d te;
for (i=0; i<NE; ++i)
{
GEdge& e = *Edge(i);
if ((e.m_ntag == 0)&&(e.HasNode(imin)))
{
if (pe == 0)
{
pe = Edge(i);
if (e.m_node[0] == imin) ew = 1; else ew = -1;
te = (ew==1?pe->Tangent(eps):-pe->Tangent(1.0-eps));
}
else
{
vec2d t1 = (e.m_node[0]==imin?e.Tangent(eps):-e.Tangent(1.0-eps));
double w = Measure(te, t1);
if (w < 0)
{
ew = (e.m_node[0] == imin? 1 : -1);
pe = Edge(i);
te = t1;
}
}
}
}
// Make sure we found an edge
assert(pe);
if (pe==0) break;
// construct a face by finding a closed loop
vector<int> node;
vector<pair<int,int> > edge;
node.clear();
edge.clear();
while (pe)
{
// en0 and en1 define the start and end-node for the current edge.
// for a normal edge they will be 0 and 1, but for an inverted
// edge they will 1 and 0
int en0, en1;
if (ew == 1) { en0 = 0; en1 = 1; } else { en0 = 1; en1 = 0; }
int nn0 = pe->m_node[en0];
int nn1 = pe->m_node[en1];
if ((Node(nn0)->m_ntag == 2) || (Node(nn1)->m_ntag == 2)) pe->m_ntag = 1;
// add the edge and start node
node.push_back(pe->m_node[en0]);
edge.push_back(pair<int, int>(pe->GetLocalID(), ew));
// see if we reached the end of the loop
if (pe->m_node[en1] == node[0]) break;
// get the end-tangent
vec2d te;
if (ew == 1) te = pe->Tangent(1.0);
else te = -pe->Tangent(0.0);
// find the edge that attaches to pe
GEdge* pe1 = 0;
int ew1 = 0;
vec2d t1;
for (int j=0; j<NE; ++j)
{
GEdge* pe2 = Edge(j);
if ((pe2 != pe) && (pe2->HasNode(nn1)))
{
if (pe1 == 0)
{
pe1 = pe2;
ew1 = (pe2->m_node[0] == nn1? 1 : -1);
// get the start tangent (at a slight offset)
t1 = (ew1==1?pe2->Tangent(eps):-pe2->Tangent(1.0-eps));
}
else
{
int ew2 = (pe2->m_node[0] == nn1? 1 : -1);
vec2d t2 = (ew2==1?pe2->Tangent(eps):-pe2->Tangent(1.0-eps));
double w1 = Measure(te, t1);
double w2 = Measure(te, t2);
if (w2 > w1)
{
pe1 = pe2;
t1 = t2;
ew1 = ew2;
}
}
}
}
pe = pe1;
ew = ew1;
}
// build the face
AddFacet(node, edge, FACE_POLYGON);
}
while (1);
// we only add one part for now
AddPart();
// Build the GMesh
BuildGMesh();
// find all vertices
UpdateNodeTypes();
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: OVR.OpenVR.IVRTrackedCamera
#include "OVR/OpenVR/IVRTrackedCamera.hpp"
// Including type: System.MulticastDelegate
#include "System/MulticastDelegate.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: OVR::OpenVR
namespace OVR::OpenVR {
// Forward declaring type: EVRTrackedCameraError
struct EVRTrackedCameraError;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: IAsyncResult
class IAsyncResult;
// Forward declaring type: AsyncCallback
class AsyncCallback;
}
// Completed forward declares
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::OVR::OpenVR::IVRTrackedCamera::_AcquireVideoStreamingService);
DEFINE_IL2CPP_ARG_TYPE(::OVR::OpenVR::IVRTrackedCamera::_AcquireVideoStreamingService*, "OVR.OpenVR", "IVRTrackedCamera/_AcquireVideoStreamingService");
// Type namespace: OVR.OpenVR
namespace OVR::OpenVR {
// Size: 0x70
#pragma pack(push, 1)
// Autogenerated type: OVR.OpenVR.IVRTrackedCamera/OVR.OpenVR._AcquireVideoStreamingService
// [TokenAttribute] Offset: FFFFFFFF
// [UnmanagedFunctionPointerAttribute] Offset: 695148
class IVRTrackedCamera::_AcquireVideoStreamingService : public ::System::MulticastDelegate {
public:
// public System.Void .ctor(System.Object object, System.IntPtr method)
// Offset: 0x847BA4
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static IVRTrackedCamera::_AcquireVideoStreamingService* New_ctor(::Il2CppObject* object, ::System::IntPtr method) {
static auto ___internal__logger = ::Logger::get().WithContext("::OVR::OpenVR::IVRTrackedCamera::_AcquireVideoStreamingService::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<IVRTrackedCamera::_AcquireVideoStreamingService*, creationType>(object, method)));
}
// public OVR.OpenVR.EVRTrackedCameraError Invoke(System.UInt32 nDeviceIndex, ref System.UInt64 pHandle)
// Offset: 0x847BB4
::OVR::OpenVR::EVRTrackedCameraError Invoke(uint nDeviceIndex, ByRef<uint64_t> pHandle);
// public System.IAsyncResult BeginInvoke(System.UInt32 nDeviceIndex, ref System.UInt64 pHandle, System.AsyncCallback callback, System.Object object)
// Offset: 0x847DFC
::System::IAsyncResult* BeginInvoke(uint nDeviceIndex, ByRef<uint64_t> pHandle, ::System::AsyncCallback* callback, ::Il2CppObject* object);
// public OVR.OpenVR.EVRTrackedCameraError EndInvoke(ref System.UInt64 pHandle, System.IAsyncResult result)
// Offset: 0x847EB8
::OVR::OpenVR::EVRTrackedCameraError EndInvoke(ByRef<uint64_t> pHandle, ::System::IAsyncResult* result);
}; // OVR.OpenVR.IVRTrackedCamera/OVR.OpenVR._AcquireVideoStreamingService
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: OVR::OpenVR::IVRTrackedCamera::_AcquireVideoStreamingService::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: OVR::OpenVR::IVRTrackedCamera::_AcquireVideoStreamingService::Invoke
// Il2CppName: Invoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::OVR::OpenVR::EVRTrackedCameraError (OVR::OpenVR::IVRTrackedCamera::_AcquireVideoStreamingService::*)(uint, ByRef<uint64_t>)>(&OVR::OpenVR::IVRTrackedCamera::_AcquireVideoStreamingService::Invoke)> {
static const MethodInfo* get() {
static auto* nDeviceIndex = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg;
static auto* pHandle = &::il2cpp_utils::GetClassFromName("System", "UInt64")->this_arg;
return ::il2cpp_utils::FindMethod(classof(OVR::OpenVR::IVRTrackedCamera::_AcquireVideoStreamingService*), "Invoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{nDeviceIndex, pHandle});
}
};
// Writing MetadataGetter for method: OVR::OpenVR::IVRTrackedCamera::_AcquireVideoStreamingService::BeginInvoke
// Il2CppName: BeginInvoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::IAsyncResult* (OVR::OpenVR::IVRTrackedCamera::_AcquireVideoStreamingService::*)(uint, ByRef<uint64_t>, ::System::AsyncCallback*, ::Il2CppObject*)>(&OVR::OpenVR::IVRTrackedCamera::_AcquireVideoStreamingService::BeginInvoke)> {
static const MethodInfo* get() {
static auto* nDeviceIndex = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg;
static auto* pHandle = &::il2cpp_utils::GetClassFromName("System", "UInt64")->this_arg;
static auto* callback = &::il2cpp_utils::GetClassFromName("System", "AsyncCallback")->byval_arg;
static auto* object = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(OVR::OpenVR::IVRTrackedCamera::_AcquireVideoStreamingService*), "BeginInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{nDeviceIndex, pHandle, callback, object});
}
};
// Writing MetadataGetter for method: OVR::OpenVR::IVRTrackedCamera::_AcquireVideoStreamingService::EndInvoke
// Il2CppName: EndInvoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::OVR::OpenVR::EVRTrackedCameraError (OVR::OpenVR::IVRTrackedCamera::_AcquireVideoStreamingService::*)(ByRef<uint64_t>, ::System::IAsyncResult*)>(&OVR::OpenVR::IVRTrackedCamera::_AcquireVideoStreamingService::EndInvoke)> {
static const MethodInfo* get() {
static auto* pHandle = &::il2cpp_utils::GetClassFromName("System", "UInt64")->this_arg;
static auto* result = &::il2cpp_utils::GetClassFromName("System", "IAsyncResult")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(OVR::OpenVR::IVRTrackedCamera::_AcquireVideoStreamingService*), "EndInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pHandle, result});
}
};
|
#include "pch.h"
#include "factory.h"
void bullet_body_create_generic(lua_State* L, btCollisionShape* shape, FLOAT mass, const btTransform& tr,
btVector3 inertia = btVector3(0, 0, 0))
{
auto* motion = new btDefaultMotionState(tr);
const btRigidBody::btRigidBodyConstructionInfo ci(mass, motion, shape, inertia);
auto* body = new btRigidBody(ci);
const auto index = bodyIndex++;
shape->setUserIndex(static_cast<int>(index));
body->setUserIndex(static_cast<int>(index));
bodies[index] = body;
world->addRigidBody(body);
lua_pushinteger(L, index);
}
auto bullet_body_create_generic_wrapper(lua_State* L, const D3DXMATRIX& mat, btCollisionShape* shape, float mass=0.0f) -> INT
{
btTransform tr;
tr.setIdentity();
tr.setFromOpenGLMatrix(&mat[0]);
btVector3 localInertia;
if (mass > 0.0f)
{
shape->calculateLocalInertia(mass, localInertia);
}
bullet_body_create_generic(L, shape, mass, tr, localInertia);
return 1;
}
auto bullet_body_create_plane(lua_State* L) -> INT
{
const auto mat = *static_cast<D3DXMATRIX*>(luaL_checkudata(L, 1, L_VECTOR));
const auto plane = *static_cast<D3DXVECTOR4*>(luaL_checkudata(L, 2, L_VECTOR));
btTransform tr;
tr.setIdentity();
tr.setOrigin(btVector3(mat._31, mat._32, mat._33));
btCollisionShape* shape = new btStaticPlaneShape(btVector3(plane.x, plane.y, plane.z), plane.w);
bullet_body_create_generic(L, shape, 0.0F, tr);
return 1;
}
static void bullet_populate_mesh_from_part(btTriangleIndexVertexArray* mesh, CFaceGroup* fg)
{
auto* meshData = new btTriangleMesh(false, false);
for (UINT i = 0; i < fg->GetNumVertices(); i += 3)
{
auto v0 = *(fg->GetVertices() + i);
auto v1 = *(fg->GetVertices() + i + 1);
auto v2 = *(fg->GetVertices() + i + 2);
auto p0 = btVector3(v0.x, v0.y, v0.z);
auto p1 = btVector3(v1.x, v1.y, v1.z);
auto p2 = btVector3(v2.x, v2.y, v2.z);
meshData->addTriangle(p0, p1, p2);
}
for (UINT i = 0; i < fg->GetNumIndices(); i += 3)
{
auto i0 = *(fg->GetIndices() + i);
auto i1 = *(fg->GetIndices() + i + 1);
auto i2 = *(fg->GetIndices() + i + 2);
meshData->addTriangleIndices(i0, i1, i2);
}
mesh->addIndexedMesh(meshData->getIndexedMeshArray().at(0), PHY_SHORT);
}
static void bullet_body_create_static_cols_generic(lua_State* L, btTriangleIndexVertexArray* mesh,
const D3DXMATRIX& mat)
{
btCollisionShape* shape = new btBvhTriangleMeshShape(mesh, true);
bullet_body_create_generic_wrapper(L, mat, shape, 0.0F);
}
auto bullet_body_create_static_cols(lua_State* L) -> INT
{
const auto mat = *static_cast<D3DXMATRIX*>(luaL_checkudata(L, 1, L_MATRIX));
auto* const fg = *static_cast<CFaceGroup**>(luaL_checkudata(L, 2, L_FACEGROUP));
auto* mesh = new btTriangleIndexVertexArray();
bullet_populate_mesh_from_part(mesh, fg);
bullet_body_create_static_cols_generic(L, mesh, mat);
return 1;
}
auto bullet_body_create_static_cols_mesh(lua_State* L) -> INT
{
const auto mat = *static_cast<D3DXMATRIX*>(luaL_checkudata(L, 1, L_MATRIX));
auto* const m = *static_cast<CMesh**>(luaL_checkudata(L, 2, L_MESH));
auto* mesh = new btTriangleIndexVertexArray();
for (UINT i = 0; i < m->GetNumFGroups(); i++)
{
auto* const fg = m->GetFGroupData()[i];
bullet_populate_mesh_from_part(mesh, fg);
}
bullet_body_create_static_cols_generic(L, mesh, mat);
return 1;
}
auto bullet_body_create_sphere(lua_State* L) -> INT
{
auto mat = *static_cast<D3DXMATRIX*>(luaL_checkudata(L, 1, L_MATRIX));
const auto radius = static_cast<FLOAT>(luaL_checknumber(L, 2));
const auto mass = static_cast<FLOAT>(luaL_checknumber(L, 3));
bullet_body_create_generic_wrapper(L, mat, new btSphereShape(radius), mass);
return 1;
}
auto bullet_body_create_box(lua_State* L) -> INT
{
auto mat = *static_cast<D3DXMATRIX*>(luaL_checkudata(L, 1, L_MATRIX));
const auto halfExtents = *static_cast<D3DXVECTOR4*>(luaL_checkudata(L, 2, L_VECTOR));
const auto mass = static_cast<FLOAT>(luaL_checknumber(L, 3));
bullet_body_create_generic_wrapper(L, mat, new btBoxShape(btVector3(halfExtents.x, halfExtents.y, halfExtents.z)), mass);
return 1;
}
auto bullet_body_create_capsule(lua_State* L) -> INT
{
auto mat = *static_cast<D3DXMATRIX*>(luaL_checkudata(L, 1, L_MATRIX));
const auto radius = static_cast<FLOAT>(luaL_checknumber(L, 2));
const auto height = static_cast<FLOAT>(luaL_checknumber(L, 3));
const auto mass = static_cast<FLOAT>(luaL_checknumber(L, 4));
bullet_body_create_generic_wrapper(L, mat, new btCapsuleShape(radius, height), mass);
return 1;
}
|
//
// Copyright (c) 2019 Loïc HAMOT
//
// 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 "rah.hpp"
#ifdef MSVC
#pragma warning(push, 0)
#endif
#include <iostream>
#include <vector>
#include <map>
#include <list>
#include <forward_list>
#include <ciso646>
#include <sstream>
#include <random>
#include <atomic>
#include <set>
#ifdef MSVC
#pragma warning(pop)
#endif
template<typename A, typename B, typename C, typename D>
bool operator == (std::tuple<A, B> a, std::pair<D, C> b)
{
return std::get<0>(a) == std::get<0>(b) && std::get<1>(a) == std::get<1>(b);
}
template<typename A, typename B, typename C, typename D>
bool operator == (std::pair<A, B> a, std::tuple<D, C> b)
{
return std::get<0>(a) == std::get<0>(b) && std::get<1>(a) == std::get<1>(b);
}
auto PairEqual = [](auto ab) {return std::get<0>(ab) == std::get<1>(ab); };
#undef assert
#define assert(CONDITION) \
{ \
std::cout << __LINE__ << " assert : " << #CONDITION << std::endl; \
if (CONDITION) \
std::cout << "OK" << std::endl; \
else \
{std::cout << "NOT OK" << std::endl; abort(); } \
}
#define EQUAL_RANGE(RANGE, IL) \
{ \
std::cout << "assert : " << #RANGE << " == " << #IL << std::endl; \
if (rah::view::zip(RANGE, IL) | rah::all_of(PairEqual)) \
std::cout << "OK" << std::endl; \
else \
{std::cout << "NOT OK" << std::endl; abort(); } \
}
template<typename T>
using il = std::initializer_list<T>;
auto print_elt = [](auto&& elt)
{
(std::cout << std::forward<decltype(elt)>(elt)) << " ";
};
template<typename... Args>
std::ostream& operator << (std::ostream& os, std::tuple<Args...> tup)
{
::rah::view::details::for_each(tup, print_elt);
return os;
}
namespace test
{
template< class T >
constexpr bool is_reference_v = std::is_reference<T>::value;
template< class T >
constexpr bool is_rvalue_reference_v = std::is_rvalue_reference<T>::value;
}
template<typename T>
struct WhatIsIt;
/// [make_pipeable create]
auto test_count(int i)
{
return rah::make_pipeable([=](auto&& range) { return std::count(begin(range), end(range), i); });
}
/// [make_pipeable create]
template<typename R, typename = std::enable_if_t<rah::is_range<R>::value>>
void toto(R&&) {}
template<typename V>
auto toto(std::initializer_list<V> il)
{
return toto(rah::make_iterator_range(begin(il), end(il)));
}
bool is_odd(int val)
{
return val % 2 == 0;
}
template<typename T>
struct WhatIs;
// Test creation of a custom iterator
struct CustomGenerator : rah::iterator_facade<CustomGenerator, int, RAH_STD::forward_iterator_tag>
{
int y = 1;
void increment()
{
y *= 2;
}
auto dereference() const
{
return y;
}
bool equal(CustomGenerator) const { return y > 10; }
};
auto customGenerate()
{
return rah::iterator_range<CustomGenerator>{};
}
int main()
{
{
std::vector<int> vec{ 0, 1, 2, 2, 3 };
toto(vec);
toto({ 0, 1, 2, 2, 3 });
}
{
/// [make_pipeable use]
std::vector<int> vec{ 0, 1, 2, 2, 3 };
assert((vec | test_count(2)) == 2);
/// [make_pipeable use]
}
// *********************************** views **************************************************
{
std::vector<int> result;
int value = 20;
for (int i : rah::view::single(value))
result.push_back(i);
assert(result == std::vector<int>({ 20 }));
}
{
/// [single]
std::vector<int> result;
for (int i : rah::view::single(20))
result.push_back(i);
assert(result == std::vector<int>({ 20 }));
/// [single]
}
{
/// [ints]
std::vector<int> result;
for (int i : rah::view::ints(10, 15))
result.push_back(i);
assert(result == std::vector<int>({ 10, 11, 12, 13, 14 }));
/// [ints]
}
{
/// [closed_ints]
std::vector<int> result;
for (int i : rah::view::closed_ints(10, 14))
result.push_back(i);
assert(result == std::vector<int>({ 10, 11, 12, 13, 14 }));
/// [closed_ints]
}
{
std::vector<int> result;
for (int i : rah::view::ints(10) | rah::view::slice(2, 5))
result.push_back(i);
assert(result == std::vector<int>({ 12, 13, 14 }));
}
{
std::vector<size_t> result;
for (size_t i : rah::view::ints() | rah::view::slice(2, 5))
result.push_back(i);
assert(result == std::vector<size_t>({ 2, 3, 4 }));
}
{
/// [iota]
std::vector<int> result;
for (int i : rah::view::iota(10, 19, 2))
result.push_back(i);
assert(result == std::vector<int>({ 10, 12, 14, 16, 18 }));
/// [iota]
}
{
std::vector<int> result;
for (int i : rah::view::iota(-5, 5, 2))
result.push_back(i);
assert(result == std::vector<int>({ -5, -3, -1, 1, 3 }));
}
{
std::vector<int> result;
for (int i : rah::view::iota(-15, -6, 2))
result.push_back(i);
assert(result == std::vector<int>({ -15, -13, -11, -9, -7 }));
}
{
/// [join]
std::vector<std::vector<int>> in = {
{ },
{0, 1},
{ },
{2, 3, 4},
{ 5},
{},
};
auto range = rah::view::join(in);
std::vector<int> result;
std::copy(begin(range), end(range), std::back_inserter(result));
assert(result == std::vector<int>({ 0, 1, 2, 3, 4, 5 }));
/// [join]
}
//{
// // Test join on a range of rvalue
// auto range = rah::view::iota(0, 6)
// | rah::view::transform([](int i) {return std::vector<int>(1, i); })
// | rah::view::join();
// std::vector<int> result;
// std::copy(begin(range), end(range), std::back_inserter(result));
// assert(result == std::vector<int>({ 0, 1, 2, 3, 4, 5 }));
//}
{
/// [join_pipeable]
std::vector<std::vector<int>> in = {
{0, 1},
{ },
{2, 3, 4},
{ 5},
{},
};
auto range = in | rah::view::join();
std::vector<int> result;
std::copy(begin(range), end(range), std::back_inserter(result));
assert(result == std::vector<int>({ 0, 1, 2, 3, 4, 5 }));
/// [join_pipeable]
}
{
/// [for_each]
auto createRange = [](int i)
{
return rah::view::repeat(char('a' + i)) | rah::view::counted(i);
};
auto range = rah::view::for_each(rah::view::iota(0, 5), createRange);
std::string result;
std::copy(begin(range), end(range), std::back_inserter(result));
assert(result == "bccdddeeee");
/// [for_each]
}
{
/// [for_each_pipeable]
auto range = rah::view::ints(0, 3) | rah::view::for_each([&](int z)
{
return rah::view::ints(3, 6) | rah::view::for_each([&, z](int y)
{
return rah::view::ints(6, 9) | rah::view::for_each([&, y, z](int x)
{
return rah::view::single(x + y * 3 + z * 9);
});
});
});
assert(equal(range, rah::view::ints(15, 42)));
/// [for_each_pipeable]
}
{
size_t count = 0;
size_t count2 = 0;
size_t count3 = 0;
auto range = rah::view::ints(0, 3) | rah::view::for_each([&](int z)
{
++count;
return rah::view::ints(3, 6) | rah::view::for_each([&, z](int y)
{
++count2;
return rah::view::ints(6, 9) | rah::view::for_each([&, y, z](int x)
{
++count3;
return rah::view::single(x + y * 3 + z * 9);
});
});
});
assert(equal(range, rah::view::ints(15, 42)));
assert(count == 3);
assert(count2 == 9);
assert(count3 == 27);
}
{
size_t xSize = 2;
size_t ySize = 3;
auto xyIndexes = [=](size_t y)
{
return rah::view::zip(
rah::view::repeat(y),
rah::view::iota<size_t>(0, xSize)
);
};
auto range = rah::view::iota<size_t>(0, ySize) | rah::view::for_each(xyIndexes);
std::vector<std::tuple<size_t, size_t>> result;
std::copy(begin(range), end(range), std::back_inserter(result));
assert(result == (std::vector<std::tuple<size_t, size_t>>{
{ 0, 0 }, { 0, 1 },
{ 1, 0 }, { 1, 1 },
{ 2, 0 }, { 2, 1 }
}));
size_t zSize = 4;
auto xyzIndexes = [=](size_t z)
{
return rah::view::zip(
rah::view::repeat(z),
rah::view::iota<size_t>(0, ySize) | rah::view::for_each(xyIndexes)
);
};
auto flattenTuple = [](auto&& z_yx)
{
using namespace std;
return std::make_tuple(
get<0>(z_yx),
get<0>(get<1>(z_yx)),
get<1>(get<1>(z_yx))
);
};
auto rangeZYX = rah::view::iota<size_t>(0, zSize)
| rah::view::for_each(xyzIndexes)
| rah::view::transform(flattenTuple);
std::vector<std::tuple<size_t, size_t, size_t>> resultZYX;
std::copy(begin(rangeZYX), end(rangeZYX), std::back_inserter(resultZYX));
assert(resultZYX == (std::vector<std::tuple<size_t, size_t, size_t>>{
{ 0, 0, 0 }, { 0, 0, 1 },
{ 0, 1, 0 }, { 0, 1, 1 },
{ 0, 2, 0 }, { 0, 2, 1 },
{ 1, 0, 0 }, { 1, 0, 1 },
{ 1, 1, 0 }, { 1, 1, 1 },
{ 1, 2, 0 }, { 1, 2, 1 },
{ 2, 0, 0 }, { 2, 0, 1 },
{ 2, 1, 0 }, { 2, 1, 1 },
{ 2, 2, 0 }, { 2, 2, 1 },
{ 3, 0, 0 }, { 3, 0, 1 },
{ 3, 1, 0 }, { 3, 1, 1 },
{ 3, 2, 0 }, { 3, 2, 1 }
}));
}
{
/// [generate]
int y = 1;
auto gen = rah::view::generate([&y]() mutable { auto prev = y; y *= 2; return prev; });
std::vector<int> gen_copy;
std::copy_n(begin(gen), 4, std::back_inserter(gen_copy));
assert(gen_copy == std::vector<int>({ 1, 2, 4, 8 }));
/// [generate]
}
{
/// [generate_n]
std::vector<int> result;
int y = 1;
for (int i : rah::view::generate_n(4, [&y]() mutable { auto prev = y; y *= 2; return prev; }))
result.push_back(i);
assert(result == std::vector<int>({ 1, 2, 4, 8 }));
/// [generate_n]
}
{
/// [cycle]
std::vector<int> in{ 0, 1, 2 };
auto cy = rah::view::cycle(in);
std::vector<int> out;
std::copy_n(begin(cy), 8, std::back_inserter(out));
assert(out == std::vector<int>({ 0, 1, 2, 0, 1, 2, 0, 1 }));
/// [cycle]
}
{
std::vector<int> in{ 0, 1, 2 };
auto cy = rah::view::cycle(in) | rah::view::reverse();
std::vector<int> out;
std::copy_n(begin(cy), 8, std::back_inserter(out));
assert(out == std::vector<int>({ 2, 1, 0, 2, 1, 0, 2, 1 }));
}
{
/// [cycle_pipeable]
std::vector<int> in{ 0, 1, 2 };
auto cy = in | rah::view::cycle();
std::vector<int> out;
std::copy_n(begin(cy), 8, std::back_inserter(out));
assert(out == std::vector<int>({ 0, 1, 2, 0, 1, 2, 0, 1 }));
/// [cycle_pipeable]
}
{
std::vector<int> in{ 0, 1, 2 };
auto cy = rah::view::cycle(in) | rah::view::counted(8);
std::vector<int> out;
std::copy(begin(cy), end(cy), std::back_inserter(out));
assert(out == std::vector<int>({ 0, 1, 2, 0, 1, 2, 0, 1 }));
}
{
/// [repeat]
std::vector<int> out;
auto range = rah::view::repeat(42);
std::copy_n(begin(range), 5, std::back_inserter(out));
assert(out == std::vector<int>({ 42, 42, 42, 42, 42 }));
/// [repeat]
}
{
/// [take]
std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto range = rah::view::take(in, 5);
std::vector<int> out;
std::copy(begin(range), end(range), std::back_inserter(out));
assert(out == std::vector<int>({ 0, 1, 2, 3, 4 }));
auto range2 = rah::view::take(in, 1000);
std::vector<int> out2;
std::copy(begin(range2), end(range2), std::back_inserter(out2));
assert(out2 == std::vector<int>({ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }));
/// [take]
}
{
/// [take_pipeable]
std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto range = in | rah::view::take(5);
std::vector<int> out;
std::copy(begin(range), end(range), std::back_inserter(out));
assert(out == std::vector<int>({ 0, 1, 2, 3, 4 }));
auto range2 = in | rah::view::take(1000);
std::vector<int> out2;
std::copy(begin(range2), end(range2), std::back_inserter(out2));
assert(out2 == std::vector<int>({ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }));
/// [take_pipeable]
}
{
/// [drop]
std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto range = rah::view::drop(in, 6);
std::vector<int> out;
std::copy(begin(range), end(range), std::back_inserter(out));
assert(out == std::vector<int>({ 6, 7, 8, 9 }));
/// [drop]
}
{
/// [drop_pipeable]
std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto range = in | rah::view::drop(6);
std::vector<int> out;
std::copy(begin(range), end(range), std::back_inserter(out));
assert(out == std::vector<int>({ 6, 7, 8, 9 }));
/// [drop_pipeable]
}
{
std::vector<int> in{ 0, 1, 2 };
auto range = rah::view::drop(in, 6);
std::vector<int> out;
std::copy(begin(range), end(range), std::back_inserter(out));
assert(out.empty());
}
{
/// [drop_exactly]
std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto range = rah::view::drop_exactly(in, 6);
std::vector<int> out;
std::copy(begin(range), end(range), std::back_inserter(out));
assert(out == std::vector<int>({ 6, 7, 8, 9 }));
/// [drop_exactly]
}
{
/// [drop_exactly_pipeable]
std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto range = in | rah::view::drop_exactly(6);
std::vector<int> out;
std::copy(begin(range), end(range), std::back_inserter(out));
assert(out == std::vector<int>({ 6, 7, 8, 9 }));
/// [drop_exactly_pipeable]
}
{
/// [sliding]
std::vector<int> in{ 0, 1, 2, 3, 4, 5 };
std::vector<std::vector<int>> out;
for (auto subRange : rah::view::sliding(in, 3))
{
out.emplace_back();
std::copy(begin(subRange), end(subRange), std::back_inserter(out.back()));
}
assert(out == (std::vector<std::vector<int>>{
{ 0, 1, 2 },
{ 1, 2, 3 },
{ 2, 3, 4 },
{ 3, 4, 5 } }));
/// [sliding]
}
{
std::vector<int> in{ 0, 1, 2, 3, 4, 5 };
std::vector<std::vector<int>> out;
for (auto subRange :
in
| rah::view::cycle()
| rah::view::sliding(3)
| rah::view::take(in.size())
)
{
out.emplace_back();
std::copy(begin(subRange), end(subRange), std::back_inserter(out.back()));
}
assert(out == (std::vector<std::vector<int>>{
{ 0, 1, 2 },
{ 1, 2, 3 },
{ 2, 3, 4 },
{ 3, 4, 5 },
{ 4, 5, 0 },
{ 5, 0, 1 },
}));
}
{
/// [sliding_pipeable]
std::vector<int> in{ 0, 1, 2, 3, 4, 5 };
std::vector<std::vector<int>> out;
for (auto subRange : in | rah::view::sliding(3))
{
out.emplace_back();
std::copy(begin(subRange), end(subRange), std::back_inserter(out.back()));
}
assert(out == (std::vector<std::vector<int>>{
{ 0, 1, 2 },
{ 1, 2, 3 },
{ 2, 3, 4 },
{ 3, 4, 5 } }));
/// [sliding_pipeable]
}
{
std::vector<int> in{ 0, 1, 2, 3 };
std::vector<std::vector<int>> out;
for (auto subRange : rah::view::sliding(in, 4))
{
out.emplace_back();
std::copy(begin(subRange), end(subRange), std::back_inserter(out.back()));
}
assert(out == (std::vector<std::vector<int>>{ {0, 1, 2, 3}}));
}
{
std::vector<int> in{ 0, 1 };
std::vector<std::vector<int>> out;
for (auto subRange : rah::view::sliding(in, 4))
{
out.emplace_back();
std::copy(begin(subRange), end(subRange), std::back_inserter(out.back()));
}
assert(out == (std::vector<std::vector<int>>{}));
}
{
std::vector<int> in{ 0, 1, 2, 3 };
std::vector<std::vector<int>> out;
for (auto subRange : rah::view::sliding(in, 0))
{
out.emplace_back();
std::copy(begin(subRange), end(subRange), std::back_inserter(out.back()));
}
assert(out == (std::vector<std::vector<int>>{}));
}
{
std::vector<int> in{ 0, 1, 2, 3 };
std::vector<std::vector<int>> out;
for (auto subRange : in | rah::view::sliding(1))
{
out.emplace_back();
std::copy(begin(subRange), end(subRange), std::back_inserter(out.back()));
}
assert(out == (std::vector<std::vector<int>>{ {0}, { 1 }, { 2 }, { 3 }, }));
}
{
/// [counted]
std::vector<int> in{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
auto range = rah::view::counted(in.begin(), 5);
std::vector<int> out;
std::copy(begin(range), end(range), std::back_inserter(out));
assert(out == std::vector<int>({ 0, 1, 2, 3, 4 }));
/// [counted]
}
{
/// [unbounded]
std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto range = rah::view::unbounded(in.begin());
std::vector<int> out;
std::copy_n(begin(range), 5, std::back_inserter(out));
assert(out == std::vector<int>({ 0, 1, 2, 3, 4 }));
/// [unbounded]
}
{
std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto range = rah::view::unbounded(in.begin()) | rah::view::slice(0, 5);
std::vector<int> out;
std::copy(begin(range), end(range), std::back_inserter(out));
assert(out == std::vector<int>({ 0, 1, 2, 3, 4 }));
}
{
int in[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto range = rah::view::unbounded((int const*const)std::begin(in)) | rah::view::slice(0, 5);
std::vector<int> out;
std::copy(begin(range), end(range), std::back_inserter(out));
assert(out == std::vector<int>({ 0, 1, 2, 3, 4 }));
}
{
/// [counted_pipeable]
std::vector<int> in{ 0, 1, 2, 3, 4, 5 };
auto range = in | rah::view::counted(9);
std::vector<int> out;
auto a = begin(range);
auto b = end(range);
volatile auto dist = std::distance(a, b);
(void)dist;
std::copy(begin(range), end(range), std::back_inserter(out));
assert(out == std::vector<int>({ 0, 1, 2, 3, 4, 5 }));
/// [counted_pipeable]
}
{
/// [counted_iterator]
std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto range = rah::view::counted(in.begin(), 5);
std::vector<int> out;
std::copy(begin(range), end(range), std::back_inserter(out));
assert(out == std::vector<int>({ 0, 1, 2, 3, 4 }));
/// [counted_iterator]
}
// Test all
EQUAL_RANGE((il<int>{0, 1, 2, 3} | rah::view::all()), (il<int>{ 0, 1, 2, 3 }));
int intTab[] = { 0, 1, 2, 3 };
EQUAL_RANGE((intTab | rah::view::all()), (il<int>{ 0, 1, 2, 3 }));
// Test transform
{
/// [rah::view::transform]
std::vector<int> vec{ 0, 1, 2, 3 };
std::vector<int> result;
for (int i : rah::view::transform(vec, [](auto a) {return a * 2; }))
result.push_back(i);
assert(result == std::vector<int>({ 0, 2, 4, 6 }));
/// [rah::view::transform]
}
{
std::vector<int> vec{ 0, 1, 2, 3 };
std::vector<int> result;
auto valueSelector = [](auto a) {return a * 2; };
auto selectedValuesRange = rah::view::transform(vec, valueSelector);
auto bounds = std::minmax_element(begin(selectedValuesRange), end(selectedValuesRange));
auto min = *bounds.first;
assert(min == 0);
auto max = *bounds.second;
assert(max == 6); // 3 * 2
}
{
/// [rah::view::transform_pipeable]
std::vector<int> vec{ 0, 1, 2, 3 };
std::vector<int> result;
for (int i : vec | rah::view::transform([](auto a) {return a * 2; }))
result.push_back(i);
assert(result == std::vector<int>({ 0, 2, 4, 6 }));
/// [rah::view::transform_pipeable]
}
{
/// [slice]
std::vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 };
std::vector<int> result;
for (int i : rah::view::slice(vec, 2, 6))
result.push_back(i);
assert(result == std::vector<int>({ 2, 3, 4, 5 }));
std::vector<int> result2;
for (int i : rah::view::slice(vec, rah::End - 6, rah::End - 2))
result2.push_back(i);
assert(result2 == std::vector<int>({ 2, 3, 4, 5 }));
/// [slice]
}
{
/// [slice_pipeable]
std::vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 };
std::vector<int> result;
for (int i : vec | rah::view::slice(2, 6))
result.push_back(i);
assert(result == std::vector<int>({ 2, 3, 4, 5 }));
/// [slice_pipeable]
}
{
/// [stride]
std::vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 };
std::vector<int> result;
for (int i : rah::view::stride(vec, 2))
result.push_back(i);
assert(result == std::vector<int>({ 0, 2, 4, 6 }));
/// [stride]
}
{
/// [stride_pipeable]
std::vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 };
std::vector<int> result;
for (int i : vec | rah::view::stride(2))
result.push_back(i);
assert(result == std::vector<int>({ 0, 2, 4, 6 }));
/// [stride_pipeable]
}
{
/// [reverse]
std::vector<int> vec{ 0, 1, 2, 3 };
std::vector<int> result;
for (int i : rah::view::reverse(vec))
result.push_back(i);
assert(result == std::vector<int>({ 3, 2, 1, 0 }));
/// [reverse]
}
{
/// [reverse_pipeable]
std::vector<int> vec{ 0, 1, 2, 3 };
std::vector<int> result;
for (int i : vec | rah::view::reverse())
result.push_back(i);
assert(result == std::vector<int>({ 3, 2, 1, 0 }));
/// [reverse_pipeable]
}
{
/// [zip]
std::vector<int> inputA{ 1, 2, 3, 4 };
std::vector<double> inputB{ 2.5, 4.5, 6.5, 8.5 };
std::vector<char> inputC{ 'a', 'b', 'c', 'd', 'e', 'f', 'g' };
std::vector<std::tuple<int, double, char>> result;
for (auto a_b_c : rah::view::zip(inputA, inputB, inputC))
result.emplace_back(a_b_c);
assert(result == (std::vector<std::tuple<int, double, char>>{
{ 1, 2.5, 'a' },
{ 2, 4.5, 'b' },
{ 3, 6.5, 'c' },
{ 4, 8.5, 'd' }
}));
/// [zip]
}
{
std::vector<int> inputA{ 1, 2, 3, 4 };
std::vector<bool> inputB{ false, true, true, false };
auto range =
rah::view::zip(inputA, inputB)
| rah::view::filter([](auto a_b) {return std::get<1>(a_b); });
assert(rah::equal(range, std::vector<std::tuple<int, bool>>({ {2, true}, { 3, true } })));
}
{
/// [chunk]
std::vector<int> vec_01234{ 0, 1, 2, 3, 4 };
std::vector<std::vector<int>> result;
for (auto elts : rah::view::chunk(vec_01234, 2))
result.emplace_back(begin(elts), end(elts));
assert(result == std::vector<std::vector<int>>({ {0, 1}, { 2, 3 }, { 4 } }));
/// [chunk]
}
{
/// [chunk_pipeable]
std::vector<int> vec_01234{ 0, 1, 2, 3, 4 };
std::vector<std::vector<int>> result;
for (auto elts : vec_01234 | rah::view::chunk(2))
result.emplace_back(begin(elts), end(elts));
assert(result == std::vector<std::vector<int>>({ {0, 1}, { 2, 3 }, { 4 } }));
/// [chunk_pipeable]
}
{
/// [filter]
std::vector<int> vec_01234{ 0, 1, 2, 3, 4 };
std::vector<int> result;
for (int i : rah::view::filter(vec_01234, [](auto a) {return a % 2 == 0; }))
result.push_back(i);
assert(result == std::vector<int>({ 0, 2, 4 }));
/// [filter]
}
{
std::vector<int> vec_01234{ 0, 1, 2, 3, 4 };
std::vector<int> result;
for (int i : rah::view::filter(vec_01234, &is_odd))
result.push_back(i);
assert(result == std::vector<int>({ 0, 2, 4 }));
}
{
enum class Tutu { a, b, c, d, e };
std::vector<Tutu> vec_01234{ Tutu::a, Tutu::b, Tutu::c, Tutu::d, Tutu::e };
std::vector<Tutu> result;
for (Tutu i : rah::view::filter(vec_01234, [](Tutu a) {return a != Tutu::c; }))
result.push_back(i);
assert(result == std::vector<Tutu>({ Tutu::a, Tutu::b, Tutu::d, Tutu::e }));
}
{
int vec_01234[] = { 0, 1, 2, 3, 4 };
std::vector<int> result;
for (int i : rah::view::filter(vec_01234, [](auto a) {return a % 2 == 0; }))
result.push_back(i);
assert(result == std::vector<int>({ 0, 2, 4 }));
}
{
std::vector<std::vector<int>> vec_01234 =
{
{0},
{1},
{2},
{3},
{4},
};
std::vector<bool> vec_bool =
{
true,
true,
true,
true,
true,
};
std::vector<std::vector<int>> result;
for (auto&& i : rah::view::zip(vec_01234, vec_bool) | rah::view::filter([](auto&& a) {return std::get<0>(a).front() % 2 == 0; }))
result.push_back(std::get<0>(i));
assert(result == (std::vector<std::vector<int>>{ { 0 }, { 2 }, { 4 } }));
assert(vec_01234 == (std::vector<std::vector<int>>{ { 0 }, { 1 }, { 2 }, { 3 }, { 4 }}));
}
{
/// [filter_pipeable]
std::vector<int> vec_01234{ 0, 1, 2, 3, 4 };
std::vector<int> result;
for (int i : vec_01234 | rah::view::filter([](auto a) {return a % 2 == 0; }))
result.push_back(i);
assert(result == std::vector<int>({ 0, 2, 4 }));
/// [filter_pipeable]
}
{
// test filter with the first elements filtered
auto range1 = rah::view::ints(1, 10) | rah::view::filter([](auto&& val) {return val % 2 == 0; });
assert(rah::none_of(range1, [](auto v) { return (v % 2) == 1; }));
// test generate + filter
auto range2 = rah::view::generate_n(100, []() {return rand(); })
| rah::view::filter([](auto&& val) { return val % 2 == 0; });
assert(rah::none_of(range2, [](auto v) { return (v % 2) == 1; }));
// Can create some compilation issue about lambda copy
auto range3 = rah::view::ints(0, 5) | rah::view::for_each([](auto)
{
return rah::view::generate_n(5, []() {return rand(); })
| rah::view::filter([](auto&& val) {return val % 2 == 0; });
});
assert(rah::none_of(range3, [](auto v) { return (v % 2) == 1; }));
}
{
/// [concat]
std::vector<int> inputA{ 0, 1, 2, 3 };
std::vector<int> inputB{ 4, 5, 6 };
std::vector<int> inputC{ 7, 8, 9, 10, 11 };
{
std::vector<int> result;
for (int i : rah::view::concat(inputA))
result.push_back(i);
assert(result == std::vector<int>({ 0, 1, 2, 3 }));
}
{
std::vector<int> result;
for (int i : rah::view::concat(inputA, inputB))
result.push_back(i);
assert(result == std::vector<int>({ 0, 1, 2, 3, 4, 5, 6 }));
}
{
std::vector<int> result;
for (int i : rah::view::concat(inputA, inputB, inputC))
result.push_back(i);
assert(result == std::vector<int>({ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }));
}
/// [concat]
}
{
std::vector<int> inputA{ };
std::vector<int> inputB{ 1, 2, 3, 4};
{
std::vector<int> result;
for (int i : rah::view::concat(inputA, inputB))
result.push_back(i);
assert(result == std::vector<int>({ 1, 2, 3, 4 }));
}
{
std::vector<int> result;
for (int i : rah::view::concat(inputA, inputB))
result.push_back(i);
assert(result == std::vector<int>({ 1, 2, 3, 4 }));
}
{
std::vector<int> result;
for (int i : rah::view::concat(inputA, inputA))
result.push_back(i);
assert(result == std::vector<int>({ }));
}
}
{
/// [enumerate]
std::vector<int> input{ 4, 5, 6, 7 };
std::vector<std::tuple<size_t, int>> result;
for (auto i_value : rah::view::enumerate(input))
result.emplace_back(i_value);
assert(result == (std::vector<std::tuple<size_t, int>>{ { 0, 4 }, { 1, 5 }, { 2, 6 }, { 3, 7 } }));
/// [enumerate]
}
{
/// [enumerate_pipeable]
std::vector<int> input{ 4, 5, 6, 7 };
std::vector<std::tuple<size_t, int>> result;
for (auto i_value : input | rah::view::enumerate())
result.emplace_back(i_value);
assert(result == (std::vector<std::tuple<size_t, int>>{ { 0, 4 }, { 1, 5 }, { 2, 6 }, { 3, 7 } }));
/// [enumerate_pipeable]
}
{
/// [map_value]
std::map<int, double> input{ {1, 1.5}, { 2, 2.5 }, { 3, 3.5 }, { 4, 4.5 } };
std::vector<double> result;
for (double value : rah::view::map_value(input))
result.push_back(value);
assert(result == (std::vector<double>{ 1.5, 2.5, 3.5, 4.5 }));
/// [map_value]
}
/*{
// This can't work since enumerate return an rvalue pairs since map_key want an lvalue
bool bools[] = { false, true, true, false, false, true };
auto range = bools
| rah::view::enumerate()
| rah::view::filter([](auto&& index_bool) {return std::get<1>(index_bool); })
| rah::view::map_key();
std::vector<size_t> ref;
std::copy(begin(range), end(range), std::back_inserter(ref));
assert(ref == (std::vector<size_t>{1, 2, 5}));
}*/
{
/// [map_value_pipeable]
std::map<int, double> input{ {1, 1.5}, { 2, 2.5 }, { 3, 3.5 }, { 4, 4.5 } };
std::vector<double> result;
for (double value : input | rah::view::map_value())
result.push_back(value);
assert(result == (std::vector<double>{ 1.5, 2.5, 3.5, 4.5 }));
/// [map_value_pipeable]
}
{
/// [map_key]
std::map<int, double> input{ {1, 1.5}, { 2, 2.5 }, { 3, 3.5 }, { 4, 4.5 } };
std::vector<int> result;
for (int key : rah::view::map_key(input))
result.push_back(key);
assert(result == (std::vector<int>{ 1, 2, 3, 4 }));
/// [map_key]
}
{
/// [map_key_pipeable]
std::map<int, double> input{ {1, 1.5}, { 2, 2.5 }, { 3, 3.5 }, { 4, 4.5 } };
std::vector<int> result;
for (int key : input | rah::view::map_key())
result.push_back(key);
assert(result == (std::vector<int>{ 1, 2, 3, 4 }));
/// [map_key_pipeable]
}
{
/// [view::set_difference]
std::vector<int> in1 = {1, 2, 3, 4, 5, 6};
std::vector<int> in2 = { 2, 4, 6, 7, 8, 9, 10 };
std::vector<int> out;
for (int val : rah::view::set_difference(in1, in2))
out.push_back(val);
assert(out == std::vector<int>({1, 3, 5}));
/// [view::set_difference]
}
{
/// view::set_difference
auto test_set_difference = [](std::vector<int> const& in1, std::vector<int> const& in2, std::vector<int> const& expected)
{
std::vector<int> out;
for (int val : rah::view::set_difference(in1, in2))
out.push_back(val);
assert(out == expected);
};
test_set_difference({}, { 2, 4, 6, 7, 8, 9, 10 }, {});
test_set_difference({ 1, 2, 3, 4, 5, 6 }, { }, { 1, 2, 3, 4, 5, 6 });
test_set_difference({ 1, 2, 3, 4, 5, 6, 7 }, {2, 4, 6}, { 1, 3, 5, 7 });
test_set_difference({ 1, 2, 4, 6 }, {3, 5, 7}, { 1, 2, 4, 6 });
test_set_difference({ 1, 2, 4, 6 }, { 1, 2, 4, 6 }, {});
test_set_difference({ 1, 2, 4, 6, 7, 8, 9 }, { 1, 2, 4, 6 }, {7, 8, 9});
for (int x = 0; x < 100; ++x)
{
std::vector<int> in1;
std::vector<int> in2;
size_t const size1 = rand() % 100;
size_t const size2 = rand() % 100;
for (size_t i = 0; i < size1; ++i)
in1.push_back(rand() % 100);
for (size_t i = 0; i < size2; ++i)
in2.push_back(rand() % 100);
rah::sort(in1);
rah::sort(in2);
std::vector<int> outRef;
std::set_difference(begin(in1), end(in1), begin(in2), end(in2), std::back_inserter(outRef));
std::vector<int> out;
for (int val : in1 | rah::view::set_difference(in2))
out.push_back(val);
assert(out == outRef);
}
}
// *********************************** algos **************************************************
{
/// [rah::equal_range]
std::vector<int> vecIn1{ 1, 2, 2, 3, 4 };
{
std::vector<int> out;
for (int i : rah::equal_range(vecIn1, 0))
out.push_back(i);
assert(out == std::vector<int>({ }));
}
{
std::vector<int> out;
for (int i : rah::equal_range(vecIn1, 1))
out.push_back(i);
assert(out == std::vector<int>({ 1 }));
}
{
std::vector<int> out;
for (int i : rah::equal_range(vecIn1, 2))
out.push_back(i);
assert(out == std::vector<int>({ 2, 2 }));
}
/// [rah::equal_range]
}
{
/// [rah::equal_range_pipeable]
std::vector<int> vecIn1{ 1, 2, 2, 3, 4 };
{
std::vector<int> out;
for (int i : vecIn1 | rah::equal_range(0))
out.push_back(i);
assert(out == std::vector<int>({ }));
}
{
std::vector<int> out;
for (int i : vecIn1 | rah::equal_range(1))
out.push_back(i);
assert(out == std::vector<int>({ 1 }));
}
{
std::vector<int> out;
for (int i : vecIn1 | rah::equal_range(2))
out.push_back(i);
assert(out == std::vector<int>({ 2, 2 }));
}
/// [rah::equal_range_pipeable]
}
{
/// [rah::equal_range_pred_0]
struct S
{
int value;
char test;
bool operator==(S rhs) const
{
return value == rhs.value && test == rhs.test;
}
};
struct FindS
{
bool operator()(S s, int val) const { return s.value < val; }
bool operator()(int val, S s) const { return val < s.value; }
};
/// [rah::equal_range_pred_0]
{
/// [rah::equal_range_pred]
std::vector<S> vecIn1{ {1, 'a'}, {2, 'b'}, {2, 'c'}, {3, 'd'}, {4, 'e'} };
{
std::vector<S> out;
for (S i : rah::equal_range(vecIn1, 0, FindS{}))
out.push_back(i);
assert(out == std::vector<S>({ }));
}
{
std::vector<S> out;
for (S i : rah::equal_range(vecIn1, 1, FindS{}))
out.push_back(i);
assert(out == std::vector<S>({ {1, 'a'} }));
}
{
std::vector<S> out;
for (S i : rah::equal_range(vecIn1, 2, FindS{}))
out.push_back(i);
assert(out == std::vector<S>({ {2, 'b'}, {2, 'c'} }));
}
/// [rah::equal_range_pred]
}
{
/// [rah::equal_range_pred_pipeable]
std::vector<S> vecIn1{ {1, 'a'}, {2, 'b'}, {2, 'c'}, {3, 'd'}, {4, 'e'} };
{
std::vector<S> out;
for (S i : vecIn1 | rah::equal_range(0, FindS{}))
out.push_back(i);
assert(out == std::vector<S>({ }));
}
{
std::vector<S> out;
for (S i : vecIn1 | rah::equal_range(1, FindS{}))
out.push_back(i);
assert(out == std::vector<S>({ {1, 'a'} }));
}
{
std::vector<S> out;
for (S i : vecIn1 | rah::equal_range(2, FindS{}))
out.push_back(i);
assert(out == std::vector<S>({ {2, 'b'}, {2, 'c'} }));
}
/// [rah::equal_range_pred_pipeable]
}
}
{
/// [rah::binary_search]
std::vector<int> vecIn1{ 1, 2, 2, 3, 4 };
assert(not rah::binary_search(vecIn1, 0));
assert(rah::binary_search(vecIn1, 1));
assert(rah::binary_search(vecIn1, 2));
/// [rah::binary_search]
}
{
/// [rah::binary_search_pipeable]
std::vector<int> vecIn1{ 1, 2, 2, 3, 4 };
assert(not (vecIn1 | rah::binary_search(0)));
assert(vecIn1 | rah::binary_search(1));
assert(vecIn1 | rah::binary_search(2));
/// [rah::binary_search_pipeable]
}
{
std::vector<int> vecIn1{ 0, 1, 2, 3 };
std::vector<int> vecOut{ 0, 0, 0, 0 };
rah::transform(vecIn1, vecOut, [](int a) {return a + 1; });
assert(vecOut == std::vector<int>({ 1, 2, 3, 4 }));
}
{
/// [rah::transform3]
std::vector<int> vecIn1{ 0, 1, 2, 3 };
std::vector<int> vecOut;
rah::transform(vecIn1, rah::back_inserter(vecOut), [](int a) {return a + 1; });
assert(vecOut == std::vector<int>({ 1, 2, 3, 4 }));
/// [rah::transform3]
}
{
/// [rah::transform4]
std::vector<int> vecIn1{ 0, 1, 2, 3 };
std::vector<int> vecIn2{ 4, 3, 2, 1 };
std::vector<int> vecOut;
rah::transform(vecIn1, vecIn2, rah::back_inserter(vecOut), [](int a, int b) {return a + b; });
assert(vecOut == std::vector<int>({ 4, 4, 4, 4 }));
/// [rah::transform4]
}
assert((rah::view::iota(0, 0) | rah::reduce(0, [](auto a, auto b) {return a + b; })) == 0);
{
/// [rah::reduce]
std::vector<int> vecIn1{ 1, 2, 3, 4 };
assert(rah::reduce(vecIn1, 0, [](auto a, auto b) {return a + b; }) == 10);
/// [rah::reduce]
}
{
/// [rah::reduce_pipeable]
std::vector<int> vecIn1{ 1, 2, 3, 4 };
assert((vecIn1 | rah::reduce(0, [](auto a, auto b) {return a + b; })) == 10);
/// [rah::reduce_pipeable]
}
/// [rah::any_of]
assert(rah::any_of(
std::initializer_list<int>{ 3, 0, 1, 3, 4, 6 },
[](auto a) {return a == 3; })
);
/// [rah::any_of]
/// [rah::any_of_pipeable]
assert((
std::initializer_list<int>{0, 1, 2, 3, 4, 6}
| rah::any_of([](auto a) {return a == 3; })
));
/// [rah::any_of_pipeable]
assert((std::initializer_list<int>{3, 0, 1, 3, 4, 6} | rah::any_of([](auto a) {return a == 3; })));
assert((std::initializer_list<int>{2, 0, 1, 2, 4, 6} | rah::any_of([](auto a) {return a == 3; })) == false);
/// [rah::all_of]
assert(rah::all_of(
std::initializer_list<int>{ 4, 4, 4, 4 },
[](auto a) {return a == 4; })
);
/// [rah::all_of]
assert(rah::all_of(std::initializer_list<int>{ 4, 4, 3, 4 }, [](auto a) {return a == 4; }) == false);
assert((std::initializer_list<int>{ 4, 4, 4, 4 } | rah::all_of([](auto a) {return a == 4; })));
/// [rah::all_of_pipeable]
assert((
std::initializer_list<int>{ 4, 4, 3, 4 }
| rah::all_of([](auto a) {return a == 4; })
) == false);
/// [rah::all_of_pipeable]
/// [rah::none_of]
assert((rah::none_of(
std::initializer_list<int>{7, 8, 9, 10},
[](auto a) {return a == 11; })
));
/// [rah::none_of]
assert((std::initializer_list<int>{7, 8, 9, 10} | rah::none_of([](auto a) {return a == 11; })));
/// [rah::none_of_pipeable]
assert((
std::initializer_list<int>{7, 8, 9, 10, 11}
| rah::none_of([](auto a) {return a == 11; })
) == false);
/// [rah::none_of_pipeable]
/// [rah::count]
assert(rah::count(std::initializer_list<int>{ 4, 4, 4, 3 }, 3) == 1);
/// [rah::count]
/// [rah::count_pipeable]
assert((std::initializer_list<int>{ 4, 4, 4, 3 } | rah::count(4)) == 3);
/// [rah::count_pipeable]
/// [rah::count_if]
assert(rah::count_if(std::initializer_list<int>{ 4, 4, 4, 3 }, [](auto a) {return a == 4; }) == 3);
/// [rah::count_if]
/// [rah::count_if_pipeable]
assert((std::initializer_list<int>{ 4, 4, 4, 3 } | rah::count_if([](auto a) {return a == 3; })) == 1);
/// [rah::count_if_pipeable]
{
/// [rah::for_each]
std::vector<int> testFE{ 4, 4, 4, 4 };
rah::for_each(testFE, [](auto& value) {return ++value; });
EQUAL_RANGE(testFE, std::initializer_list<int>({ 5, 5, 5, 5 }));
/// [rah::for_each]
}
{
/// [rah::for_each_pipeable]
std::vector<int> testFE{ 4, 4, 4, 4 };
testFE | rah::for_each([](auto& value) {return ++value; });
EQUAL_RANGE(testFE, std::initializer_list<int>({ 5, 5, 5, 5 }));
/// [rah::for_each_pipeable]
}
{
/// [rah::to_container_pipeable]
std::vector<std::pair<int, char>> in1{ {4, 'a'}, { 5, 'b' }, { 6, 'c' }, { 7, 'd' } };
std::map<int, char> map_4a_5b_6c_7d = in1 | rah::to_container<std::map<int, char>>();
assert(
map_4a_5b_6c_7d == (std::map<int, char>{ {4, 'a'}, { 5, 'b' }, { 6, 'c' }, { 7, 'd' } })
);
std::list<int> in2{ 4, 5, 6, 7 };
std::vector<int> out = in2 | rah::to_container<std::vector<int>>();
assert(out == (std::vector<int>{ 4, 5, 6, 7 }));
/// [rah::to_container_pipeable]
}
{
/// [rah::to_container]
std::vector<std::pair<int, char>> in1{ {4, 'a'}, { 5, 'b' }, { 6, 'c' }, { 7, 'd' } };
std::map<int, char> map_4a_5b_6c_7d = rah::to_container<std::map<int, char>>(in1);
assert(
map_4a_5b_6c_7d == (std::map<int, char>{ {4, 'a'}, { 5, 'b' }, { 6, 'c' }, { 7, 'd' } })
);
std::list<int> in2{ 4, 5, 6, 7 };
std::vector<int> out = rah::to_container<std::vector<int>>(in2);
assert(out == (std::vector<int>{ 4, 5, 6, 7 }));
/// [rah::to_container]
}
{
/// [rah::mismatch]
std::vector<int> in1 = { 1, 2, 3, 4 };
std::vector<int> in2 = { 1, 2, 42, 42 };
auto r1_r2 = rah::mismatch(in1, in2);
std::vector<int> out1;
std::vector<int> out2;
std::copy(std::get<0>(r1_r2), end(in1), std::back_inserter(out1));
std::copy(std::get<1>(r1_r2), end(in2), std::back_inserter(out2));
assert(out1 == std::vector<int>({ 3, 4 }));
assert(out2 == std::vector<int>({ 42, 42 }));
/// [rah::mismatch]
}
{
/// [rah::find]
std::vector<int> in{ 1, 2, 3, 4 };
auto iter = rah::find(in, 3);
assert(
(rah::make_iterator_range(iter, end(in)) | rah::equal(std::initializer_list<int>({ 3, 4 })))
);
/// [rah::find]
}
{
/// [rah::find_pipeable]
std::vector<int> in{ 1, 2, 3, 4 };
auto iter = in | rah::find(3);
assert(
(rah::make_iterator_range(iter, end(in)) | rah::equal(std::initializer_list<int>({ 3, 4 })))
);
/// [rah::find_pipeable]
}
{
/// [rah::find_if]
std::vector<int> in{ 1, 2, 3, 4 };
auto iter = rah::find_if(in, [](int i) {return i == 3; });
assert(
(rah::make_iterator_range(iter, end(in)) | rah::equal(std::initializer_list<int>({ 3, 4 })))
);
/// [rah::find_if]
}
{
/// [rah::find_if_pipeable]
std::vector<int> in{ 1, 2, 3, 4 };
auto iter = in | rah::find_if([](int i) {return i == 3; });
assert(
(rah::make_iterator_range(iter, end(in)) | rah::equal(std::initializer_list<int>({ 3, 4 })))
);
/// [rah::find_if_pipeable]
}
{
/// [rah::find_if_not]
std::vector<int> in{ 1, 2, 3, 4 };
auto iter = rah::find_if_not(in, [](int i) {return i < 3; });
assert((rah::make_iterator_range(iter, end(in)) | rah::equal(std::initializer_list<int>({ 3, 4 }))));
/// [rah::find_if_not]
}
{
/// [rah::find_if_not_pipeable]
std::vector<int> in{ 1, 2, 3, 4 };
auto iter = in | rah::find_if_not([](int i) {return i < 3; });
assert((rah::make_iterator_range(iter, end(in)) | rah::equal(std::initializer_list<int>({ 3, 4 }))));
/// [rah::find_if_not_pipeable]
}
{
/// [rah::max_element]
std::vector<int> in{ 1, 5, 3, 4 };
auto iter = rah::max_element(in);
assert(*iter == 5);
/// [rah::max_element]
}
{
/// [rah::max_element_pipeable]
std::vector<int> in{ 1, 5, 3, 4 };
auto iter = in | rah::max_element();
assert(*iter == 5);
/// [rah::max_element_pipeable]
}
{
/// [rah::max_element_pred]
std::vector<std::pair<int, int>> in{ {100, 3}, {0, 5}, {0, 1}, {0, 4} };
auto iter = rah::max_element(in, [](auto&& a, auto& b) {return a.second < b.second; });
assert(*iter == (std::pair<int, int>{0, 5}));
/// [rah::max_element_pred]
}
{
/// [rah::max_element_pred_pipeable]
std::vector<std::pair<int, int>> in{ {100, 3}, {0, 5}, {0, 1}, {0, 4} };
auto iter = in | rah::max_element([](auto&& a, auto& b) {return a.second < b.second; });
assert(*iter == (std::pair<int, int>{0, 5}));
/// [rah::max_element_pred_pipeable]
}
{
/// [rah::min_element]
std::vector<int> in{ 1, -5, 3, 4 };
auto iter = rah::min_element(in);
assert(*iter == -5);
/// [rah::min_element]
}
{
/// [rah::min_element_pipeable]
std::vector<int> in{ 1, -5, 3, 4 };
auto iter = in | rah::min_element();
assert(*iter == -5);
/// [rah::min_element_pipeable]
}
{
/// [rah::min_element_pred]
std::vector<std::pair<int, int>> in{ {-100, 3}, {0, -5}, {0, 1}, {0, 4} };
auto iter = rah::min_element(in, [](auto&& a, auto& b) {return a.second < b.second; });
assert(*iter == (std::pair<int, int>{0, -5}));
/// [rah::min_element_pred]
}
{
/// [rah::min_element_pred_pipeable]
std::vector<std::pair<int, int>> in{ {-100, 3}, {0, -5}, {0, 1}, {0, 4} };
auto iter = in | rah::min_element([](auto&& a, auto& b) {return a.second < b.second; });
assert(*iter == (std::pair<int, int>{0, -5}));
/// [rah::min_element_pred_pipeable]
}
{
/// [rah::size]
std::vector<int> vec3{ 1, 2, 3 };
assert(rah::size(vec3) == 3);
/// [rah::size]
}
{
/// [rah::size_pipeable]
std::vector<int> vec3{ 1, 2, 3 };
assert((vec3 | rah::size()) == 3);
/// [rah::size_pipeable]
}
{
/// [rah::equal]
std::vector<int> in1{ 1, 2, 3 };
std::vector<int> in2{ 1, 2, 3 };
std::vector<int> in3{ 11, 12, 13 };
assert(rah::equal(in1, in2));
assert(rah::equal(in1, in3) == false);
/// [rah::equal]
}
{
/// [rah::equal_pipeable]
std::vector<int> in1{ 1, 2, 3 };
std::vector<int> in2{ 1, 2, 3 };
std::vector<int> in3{ 11, 12, 13 };
assert(in1 | rah::equal(in2));
assert(not (in1 | rah::equal(in3)));
/// [rah::equal_pipeable]
}
/// [rah::empty]
assert(not (rah::empty(std::vector<int>{ 1, 2, 3 })));
assert(rah::empty(std::vector<int>()));
/// [rah::empty]
/// [rah::empty_pipeable]
assert(not (std::vector<int>{ 1, 2, 3 } | rah::empty()));
assert(std::vector<int>() | rah::empty());
/// [rah::empty_pipeable]
{
/// [rah::copy]
std::vector<int> in{ 1, 2, 3 };
std::vector<int> out{ 0, 0, 0, 4, 5 };
// std::vector<int> out{ 0, 0 }; // Trigger an assert
assert(rah::make_iterator_range(rah::copy(in, out), end(out)) | rah::equal(std::initializer_list<int>({ 4, 5 })));
assert(out == (std::vector<int>{ 1, 2, 3, 4, 5 }));
/// [rah::copy]
}
{
/// [rah::copy_pipeable]
std::vector<int> in{ 1, 2, 3 };
std::vector<int> out{ 0, 0, 0, 4, 5 };
auto iter = in | rah::copy(out);
assert((rah::make_iterator_range(iter, end(out)) | rah::equal(std::initializer_list<int>{ 4, 5 })));
assert(out == (std::vector<int>{ 1, 2, 3, 4, 5 }));
/// [rah::copy_pipeable]
}
{
/// [rah::copy_if]
std::vector<int> in{ 1, 2, 3, 4 };
std::vector<int> out{ 0, 0, 5, 6 };
assert(rah::make_iterator_range(rah::copy_if(in, out, [](int i) {return i % 2 == 0; }), end(out)) | rah::equal(std::initializer_list<int>({ 5, 6 })));
assert(out == (std::vector<int>{ 2, 4, 5, 6 }));
/// [rah::copy_if]
}
{
/// [rah::copy_if_pipeable]
std::vector<int> in{ 1, 2, 3, 4 };
std::vector<int> out{ 0, 0, 5, 6 };
assert(rah::make_iterator_range(in | rah::copy_if(out, [](int i) {return i % 2 == 0; }), end(out)) | rah::equal(std::initializer_list<int>({ 5, 6 })));
assert(out == (std::vector<int>{ 2, 4, 5, 6 }));
/// [rah::copy_if_pipeable]
}
{
/// [rah::fill]
std::vector<int> out{ 0, 0, 0, 4, 5 };
rah::fill(out, 42);
assert(out == (std::vector<int>{ 42, 42, 42, 42, 42 }));
/// [rah::fill]
}
{
/// [rah::fill_pipeable]
std::vector<int> out{ 0, 0, 0, 4, 5 };
out | rah::fill(42);
assert(out == (std::vector<int>{ 42, 42, 42, 42, 42 }));
/// [rah::fill_pipeable]
}
{
std::vector<int> out{ 0, 0, 0, 4, 5 };
out | rah::view::counted(3) | rah::fill(42);
assert(out == (std::vector<int>{ 42, 42, 42, 4, 5 }));
}
{
/// [rah::back_inserter]
std::vector<int> in{ 1, 2, 3 };
std::vector<int> out;
rah::copy(in, rah::back_inserter(out));
assert(out == std::vector<int>({ 1, 2, 3 }));
/// [rah::back_inserter]
}
{
/// [rah::back_insert]
std::vector<int> in{ 1, 2, 3 };
std::vector<int> out{ 10 };
rah::back_insert(in, out);
assert(out == (std::vector<int>{ 10, 1, 2, 3 }));
/// [rah::back_insert]
}
{
/// [rah::back_insert_pipeable]
std::vector<int> in{ 1, 2, 3 };
std::vector<int> out{ 10 };
in | rah::back_insert(out);
assert(out == (std::vector<int>{ 10, 1, 2, 3 }));
/// [rah::back_insert_pipeable]
}
{
std::vector<int> in{ 1, 2, 3 };
std::vector<int> out;
in | rah::copy(rah::back_inserter(out));
assert(out == (std::vector<int>{ 1, 2, 3 }));
}
{
// Test rah::inserter
std::vector<int> in{ 1, 3, 5 };
std::set<int> out{ 2, 4 };
in | rah::copy(rah::inserter(out, end(out)));
assert(out == (std::set<int>{ 1, 2, 3, 4, 5 }));
}
{
/// [rah::stream_inserter]
std::string in("Test");
std::stringstream out;
in | rah::copy(rah::stream_inserter(out));
assert(out.str() == in);
/// [rah::stream_inserter]
}
{
/// [rah::remove_if]
std::vector<int> in{ 1, 2, 3, 4, 5 };
auto range_to_erase_begin = rah::remove_if(in, [](auto a) {return a < 4; });
in.erase(range_to_erase_begin, end(in));
std::sort(in.begin(), in.end());
assert(in == std::vector<int>({4, 5}));
/// [rah::remove_if]
}
{
/// [rah::remove_if_pipeable]
std::vector<int> in{ 1, 2, 3, 4, 5 };
auto range_to_erase_begin = in | rah::remove_if([](int a) {return a < 4; });
in.erase(range_to_erase_begin, end(in));
std::sort(in.begin(), in.end());
assert(in == std::vector<int>({ 4, 5 }));
/// [rah::remove_if_pipeable]
}
{
/// [rah::remove]
std::vector<int> in{ 1, 2, 1, 3, 1 };
auto range_to_erase_begin = rah::remove(in, 1);
in.erase(range_to_erase_begin, end(in));
std::sort(in.begin(), in.end());
assert(in == std::vector<int>({ 2, 3 }));
/// [rah::remove]
}
{
/// [rah::remove_pipeable]
std::vector<int> in{ 1, 2, 1, 3, 1 };
auto range_to_erase_begin = in | rah::remove(1);
in.erase(range_to_erase_begin, end(in));
std::sort(in.begin(), in.end());
assert(in == std::vector<int>({ 2, 3 }));
/// [rah::remove_pipeable]
}
{
/// [rah::partition]
std::vector<int> in{ 1, 2, 3, 4, 5 };
auto boundary = rah::partition(in, [](auto a) {return a >= 4; });
assert(boundary == in.begin() + 2);
std::sort(in.begin(), boundary);
std::sort(boundary, in.end());
assert(in == std::vector<int>({ 4, 5, 1, 2, 3 }));
/// [rah::partition]
}
{
/// [rah::partition_pipeable]
std::vector<int> in{ 1, 2, 3, 4, 5 };
auto boundary = in | rah::partition([](auto a) {return a >= 4; });
assert(boundary == in.begin() + 2);
std::sort(in.begin(), boundary);
std::sort(boundary, in.end());
assert(in == std::vector<int>({ 4, 5, 1, 2, 3 }));
/// [rah::partition_pipeable]
}
{
/// [rah::stable_partition]
std::vector<int> in{ 1, 2, 3, 4, 5 };
auto boundary = rah::stable_partition(in, [](auto a) {return a >= 4; });
assert(boundary == in.begin() + 2);
assert(in == std::vector<int>({ 4, 5, 1, 2, 3 }));
/// [rah::stable_partition]
}
{
/// [rah::stable_partition_pipeable]
std::vector<int> in{ 1, 2, 3, 4, 5 };
auto boundary = in | rah::stable_partition([](auto a) {return a >= 4; });
assert(boundary == in.begin() + 2);
assert(in == std::vector<int>({ 4, 5, 1, 2, 3 }));
/// [rah::stable_partition_pipeable]
}
{
/// [rah::erase]
std::vector<int> in{ 1, 2, 3, 4, 5 };
rah::erase(in, rah::make_iterator_range(begin(in), begin(in) + 3));
assert(in == std::vector<int>({ 4, 5 }));
/// [rah::erase]
}
{
/// [rah::erase_pipeable]
std::vector<int> in{ 1, 2, 3, 4, 5 };
in | rah::erase(rah::make_iterator_range(begin(in), begin(in) + 3));
assert(in == std::vector<int>({ 4, 5 }));
/// [rah::erase_pipeable]
}
{
/// [rah::erase_remove_if]
std::vector<int> in{ 1, 2, 3, 4, 5 };
in | rah::erase(rah::make_iterator_range(in | rah::remove_if([](int a) {return a < 4; }), end(in)));
assert(in == std::vector<int>({ 4, 5 }));
/// [rah::erase_remove_if]
}
{
/// [rah::sort]
std::vector<int> in{ 2, 1, 5, 3, 4 };
rah::sort(in);
assert(in == std::vector<int>({ 1, 2, 3, 4, 5 }));
/// [rah::sort]
}
{
/// [rah::sort_pipeable]
std::vector<int> in{ 2, 1, 5, 3, 4 };
in | rah::sort();
assert(in == std::vector<int>({ 1, 2, 3, 4, 5 }));
/// [rah::sort_pipeable]
}
{
/// [rah::sort_pred]
std::vector<int> in{ 2, 1, 5, 3, 4 };
rah::sort(in, [](auto a, auto b) {return a < b; });
assert(in == std::vector<int>({ 1, 2, 3, 4, 5 }));
/// [rah::sort_pred]
}
{
/// [rah::sort_pred_pipeable]
std::vector<int> in{ 2, 1, 5, 3, 4 };
in | rah::sort([](auto a, auto b) {return a < b; });
assert(in == std::vector<int>({ 1, 2, 3, 4, 5 }));
/// [rah::sort_pred_pipeable]
}
/// [rah::stable_sort]
struct CmpA
{
int a;
int b;
bool operator<(CmpA rhs) const
{
return a < rhs.a;
}
bool operator==(CmpA rhs) const
{
return a == rhs.a && b == rhs.b;
}
};
{
std::vector<CmpA> in{ { 4, 1 }, { 2, 1 }, { 4, 2 }, { 1, 1 }, { 4, 3 }, { 2, 2 }, { 4, 4 } };
rah::stable_sort(in);
assert(in == std::vector<CmpA>({ { 1, 1 }, { 2, 1 }, { 2, 2 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 } }));
}
/// [rah::stable_sort]
{
std::vector<CmpA> in{ { 4, 1 }, { 2, 1 }, { 4, 2 }, { 1, 1 }, { 4, 3 }, { 2, 2 }, { 4, 4 } };
/// [rah::stable_sort_pipeable]
in | rah::stable_sort();
assert(in == std::vector<CmpA>({ { 1, 1 }, { 2, 1 }, { 2, 2 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 } }));
/// [rah::stable_sort_pipeable]
}
{
/// [rah::stable_sort_pred]
std::vector<CmpA> in{ { 4, 1 }, { 2, 1 }, { 4, 2 }, { 1, 1 }, { 4, 3 }, { 2, 2 }, { 4, 4 } };
rah::stable_sort(in, [](CmpA l, CmpA r) { return l.b < r.b; });
assert(in == std::vector<CmpA>({ { 4, 1 }, { 2, 1 }, { 1, 1 }, { 4, 2 }, { 2, 2 }, { 4, 3 }, { 4, 4 } }));
/// [rah::stable_sort_pred]
}
{
/// [rah::stable_sort_pred_pipeable]
std::vector<CmpA> in{ { 4, 1 }, { 2, 1 }, { 4, 2 }, { 1, 1 }, { 4, 3 }, { 2, 2 }, { 4, 4 } };
in | rah::stable_sort([](CmpA l, CmpA r) { return l.b < r.b; });
assert(in == std::vector<CmpA>({ { 4, 1 }, { 2, 1 }, { 1, 1 }, { 4, 2 }, { 2, 2 }, { 4, 3 }, { 4, 4 } }));
/// [rah::stable_sort_pred_pipeable]
}
{
/// [rah::shuffle]
std::random_device rd;
std::mt19937 g(rd());
std::vector<int> in{ 1, 2, 3, 4, 5, 6 };
rah::shuffle(in, g);
/// [rah::shuffle]
}
{
/// [rah::shuffle_pipeable]
std::random_device rd;
std::mt19937 g(rd());
std::vector<int> in{ 1, 2, 3, 4, 5, 6 };
in | rah::shuffle(g);
/// [rah::shuffle_pipeable]
}
{
/// [rah::unique]
std::vector<int> in{ 2, 1, 1, 1, 5, 3, 3, 4 };
in.erase(rah::unique(in), end(in));
assert(in == std::vector<int>({ 2, 1, 5, 3, 4 }));
/// [rah::unique]
}
{
/// [rah::unique_pipeable]
std::vector<int> in{ 2, 1, 1, 1, 5, 3, 3, 4 };
in.erase(in | rah::unique(), end(in));
assert(in == std::vector<int>({ 2, 1, 5, 3, 4 }));
/// [rah::unique_pipeable]
}
{
/// [rah::unique_pred]
std::vector<int> in{ 2, 1, 1, 1, 5, 3, 3, 4 };
in.erase(rah::unique(in, [](auto a, auto b) {return a == b; }), end(in));
assert(in == std::vector<int>({ 2, 1, 5, 3, 4 }));
/// [rah::unique_pred]
}
{
/// [rah::unique_pred_pipeable]
std::vector<int> in{ 2, 1, 1, 1, 5, 3, 3, 4 };
in.erase(in | rah::unique([](auto a, auto b) {return a == b; }), end(in));
assert(in == std::vector<int>({ 2, 1, 5, 3, 4 }));
/// [rah::unique_pred_pipeable]
}
{
/// [rah::set_difference]
std::vector<int> in1{ 1, 3, 4 };
std::vector<int> in2{ 1, 2, 3 };
std::vector<int> out{ 0, 0, 0, 0 };
rah::set_difference(in1, in2, out);
assert(out == std::vector<int>({4, 0, 0, 0}));
/// [rah::set_difference]
}
{
/// [rah::set_intersection]
std::vector<int> in1{ 1, 3, 4 };
std::vector<int> in2{ 1, 2, 3 };
std::vector<int> out{ 0, 0, 0, 0 };
rah::set_intersection(in1, in2, out);
assert(out == std::vector<int>({ 1, 3, 0, 0 }));
/// [rah::set_intersection]
}
{
/// [rah::action::unique]
std::vector<int> in{ 2, 1, 1, 1, 5, 3, 3, 4 };
auto&& result = rah::action::unique(in);
assert(&result == &in);
assert(in == std::vector<int>({ 2, 1, 5, 3, 4 }));
/// [rah::action::unique]
}
{
/// [rah::action::unique_pipeable]
std::vector<int> in{ 2, 1, 1, 1, 5, 3, 3, 4 };
auto&& result = in | rah::action::unique();
assert(&result == &in);
assert(in == std::vector<int>({ 2, 1, 5, 3, 4 }));
/// [rah::action::unique_pipeable]
}
{
/// [rah::action::unique_pred]
std::vector<int> in{ 2, 1, 1, 1, 5, 3, 3, 4 };
auto&& result = rah::action::unique(in, [](auto a, auto b) {return a == b; });
assert(&result == &in);
assert(in == std::vector<int>({ 2, 1, 5, 3, 4 }));
/// [rah::action::unique_pred]
}
{
/// [rah::action::unique_pred_pipeable]
std::vector<int> in{ 2, 1, 1, 1, 5, 3, 3, 4 };
auto&& result = in | rah::action::unique([](auto a, auto b) {return a == b; });
assert(&result == &in);
assert(in == std::vector<int>({ 2, 1, 5, 3, 4 }));
/// [rah::action::unique_pred_pipeable]
}
{
/// [rah::action::remove_if]
std::vector<int> in{ 1, 2, 3, 4, 5 };
auto&& result = rah::action::remove_if(in, [](auto a) {return a < 4; });
assert(&result == &in);
assert(in == std::vector<int>({ 4, 5 }));
/// [rah::action::remove_if]
}
{
/// [rah::action::remove_if_pipeable]
std::vector<int> in{ 1, 2, 3, 4, 5 };
auto&& result = in | rah::action::remove_if([](int a) {return a < 4; });
assert(&result == &in);
assert(in == std::vector<int>({ 4, 5 }));
/// [rah::action::remove_if_pipeable]
}
{
/// [rah::action::remove]
std::vector<int> in{ 1, 2, 1, 3, 1 };
auto&& result = rah::action::remove(in, 1);
assert(&result == &in);
assert(in == std::vector<int>({ 2, 3 }));
/// [rah::action::remove]
}
{
/// [rah::action::remove_pipeable]
std::vector<int> in{ 1, 2, 1, 3, 1 };
auto&& result = in | rah::action::remove(1);
assert(&result == &in);
assert(in == std::vector<int>({ 2, 3 }));
/// [rah::action::remove_pipeable]
}
{
/// [rah::action::sort]
std::vector<int> in{ 2, 1, 5, 3, 4 };
auto&& result = rah::action::sort(in);
assert(&result == &in);
assert(in == std::vector<int>({ 1, 2, 3, 4, 5 }));
/// [rah::action::sort]
}
{
/// [rah::action::sort_pipeable]
std::vector<int> in{ 2, 1, 5, 3, 4 };
auto&& result = in | rah::action::sort();
assert(&result == &in);
assert(in == std::vector<int>({ 1, 2, 3, 4, 5 }));
/// [rah::action::sort_pipeable]
}
{
/// [rah::action::sort_pred]
std::vector<int> in{ 2, 1, 5, 3, 4 };
auto&& result = rah::action::sort(in, [](auto a, auto b) {return a < b; });
assert(&result == &in);
assert(in == std::vector<int>({ 1, 2, 3, 4, 5 }));
/// [rah::action::sort_pred]
}
{
/// [rah::action::sort_pred_pipeable]
std::vector<int> in{ 2, 1, 5, 3, 4 };
auto&& result = in | rah::action::sort([](auto a, auto b) {return a < b; });
assert(&result == &in);
assert(in == std::vector<int>({ 1, 2, 3, 4, 5 }));
/// [rah::action::sort_pred_pipeable]
}
{
/// [rah::action::shuffle]
std::random_device rd;
std::mt19937 g(rd());
std::vector<int> in{ 1, 2, 3, 4, 5, 6 };
assert(&rah::action::shuffle(in, g) == &in);
/// [rah::action::shuffle]
}
{
/// [rah::action::shuffle_pipeable]
std::random_device rd;
std::mt19937 g(rd());
std::vector<int> in{ 1, 2, 3, 4, 5, 6 };
assert(&(in | rah::action::shuffle(g)) == &in);
/// [rah::action::shuffle_pipeable]
}
{
/// [rah::view::sort]
std::vector<int> in{ 2, 1, 5, 3, 4 };
auto&& result = rah::view::sort(in);
assert(in == std::vector<int>({ 2, 1, 5, 3, 4 }));
assert(result == std::vector<int>({ 1, 2, 3, 4, 5 }));
/// [rah::view::sort]
}
{
std::vector<int> in{ 2, 1, 5, 3, 4 };
auto&& result = in | rah::view::transform([](int& i) ->const int& {return i; }) | rah::view::sort() | rah::to_container<std::vector<int>>();
assert(in == std::vector<int>({ 2, 1, 5, 3, 4 }));
assert(result == std::vector<int>({ 1, 2, 3, 4, 5 }));
}
{
/// [rah::view::sort_pipeable]
std::vector<int> in{ 2, 1, 5, 3, 4 };
auto&& result = in | rah::view::sort();
assert(in == std::vector<int>({ 2, 1, 5, 3, 4 }));
assert(result == std::vector<int>({ 1, 2, 3, 4, 5 }));
/// [rah::view::sort_pipeable]
}
{
/// [rah::view::sort_pred]
std::vector<int> in{ 2, 1, 5, 3, 4 };
auto&& result = rah::view::sort(in, [](auto a, auto b) {return a < b; });
assert(in == std::vector<int>({ 2, 1, 5, 3, 4 }));
assert(result == std::vector<int>({ 1, 2, 3, 4, 5 }));
/// [rah::view::sort_pred]
}
{
/// [rah::view::sort_pred_pipeable]
std::vector<int> in{ 2, 1, 5, 3, 4 };
auto&& result = in | rah::view::sort([](auto a, auto b) {return a < b; });
assert(in == std::vector<int>({ 2, 1, 5, 3, 4 }));
assert(result == std::vector<int>({ 1, 2, 3, 4, 5 }));
/// [rah::view::sort_pred_pipeable]
}
{
auto&& sorted = rah::view::iota(0, 10, 2)
| rah::view::sort([](auto a, auto b) {return b < a; });
auto&& result = sorted
| rah::view::transform([](auto v) {return v - 10; })
| rah::to_container<std::vector<int>>();
assert(result == std::vector<int>({ -2, -4, -6, -8, -10 }));
}
{
/// [rah::actions::fill]
std::vector<int> out{ 0, 0, 0, 4, 5 };
assert(rah::action::fill(out, 42) == (std::vector<int>{ 42, 42, 42, 42, 42 }));
/// [rah::actions::fill]
}
// ********************************* test return ref and non-ref ******************************
using namespace rah;
using namespace rah::view;
using namespace std;
struct Elt
{
int member;
bool operator==(Elt elt) const
{
return member == elt.member;
}
};
// Test return reference
{
std::vector<Elt> vec = { {0}, { 1 }, { 2 }, { 3 }, { 4 } };
auto& r = vec;
for (auto iter = begin(r), end_iter = end(r); iter != end_iter; ++iter)
{
iter->member = 42; // Check for mutability
}
EQUAL_RANGE(r, (il<Elt>({ {42}, { 42 }, { 42 }, { 42 }, { 42 } })));
for (auto&& elt : r)
{
static_assert(test::is_reference_v<decltype(elt)>, "elt is expected to be a reference");
elt.member = 78; // Check for mutability
}
EQUAL_RANGE(r, (il<Elt>({ {78}, { 78 }, { 78 }, { 78 }, { 78 } })));
}
{
std::vector<int> vec(5);
for (int& i : vec | rah::view::transform([](int& i) ->int& {return i;}))
i = 42; // Check for mutability
EQUAL_RANGE(vec, (il<int>({ 42, 42, 42, 42, 42 })));
}
// Test return non-reference
{
std::vector<int> constVect{ 0, 1, 2, 3 };
EQUAL_RANGE(
constVect | transform([](auto a) {return a * 2; }),
il<int>({ 0, 2, 4, 6 })
);
std::vector<Elt> vec = { {1} };
auto r_copy = vec | transform([](auto a) {return Elt{ a.member + 1 }; });
for (auto iter = begin(r_copy), end_iter = end(r_copy); iter != end_iter; ++iter)
{
assert(iter->member == 2); // Check for mutability
assert((*iter).member == 2); // Check for mutability
static_assert(test::is_rvalue_reference_v<decltype(*iter)> ||
(not test::is_reference_v<decltype(*iter)>),
"*iter is not expected to be a reference");
}
for (auto&& elt : r_copy)
{
assert(elt.member == 2); // Check for mutability
static_assert(test::is_rvalue_reference_v<decltype(elt)> ||
(not test::is_reference_v<decltype(elt)>),
"elt is not expected to be a reference");
}
auto r_ref = vec | transform([](auto a) {return a.member; });
for (auto iter = begin(r_ref), end_iter = end(r_ref); iter != end_iter; ++iter)
{
assert(*iter == 1); // Check for mutability
static_assert(test::is_rvalue_reference_v<decltype(*iter)> ||
(not test::is_reference_v<decltype(*iter)>),
"*iter is not expected to be a reference");
}
for (auto&& elt : r_ref)
{
assert(elt == 1); // Check for mutability
static_assert(test::is_rvalue_reference_v<decltype(elt)> ||
(not test::is_reference_v<decltype(elt)>),
"elt is not expected to be a reference");
}
}
// **************************** divers compination test ***************************************
{
auto genRange = [](size_t i) {return rah::view::zip(rah::view::repeat(i), rah::view::iota<size_t>(0, 3)); };
auto globalRange =
rah::view::iota<size_t>(0, 4)
| rah::view::transform(genRange)
| rah::view::join();
EQUAL_RANGE(globalRange, (il<std::pair<size_t, size_t>>{
{0, 0}, { 0, 1 }, { 0, 2 },
{1, 0}, { 1, 1 }, { 1, 2 },
{2, 0}, { 2, 1 }, { 2, 2 },
{3, 0}, { 3, 1 }, { 3, 2 }
}));
}
EQUAL_RANGE(
(iota(0, 3) | transform([](auto i) {return i * 2; }) | enumerate()),
(il<std::pair<size_t, int>>{ {0, 0}, { 1, 2 }, { 2, 4 } })
);
std::vector<char> vec_abcd{ 'a', 'b', 'c', 'd' };
EQUAL_RANGE(
(vec_abcd | transform([](char i) {return i + 1; }) | enumerate()),
(il<std::pair<size_t, char>>{ {0, 'b'}, { 1, 'c' }, { 2, 'd' }, { 3, 'e' } })
);
EQUAL_RANGE(
(iota(0, 3000, 3) | transform([](auto i) {return i * 2; }) | enumerate() | slice(10, 13)),
(il<std::pair<size_t, int>>{ {10, 60}, { 11, 66 }, { 12, 72 } })
);
EQUAL_RANGE(
(zip(vec_abcd, iota(0, 4))),
(il<std::tuple<char, int>>{ {'a', 0}, { 'b', 1 }, { 'c', 2 }, { 'd', 3 } })
);
EQUAL_RANGE(
(iota(0, 100) | slice(0, 20) | stride(3)),
(il<int>{0, 3, 6, 9, 12, 15, 18})
);
EQUAL_RANGE(
(iota(10, 15) | reverse()),
(il<int>{14, 13, 12, 11, 10})
);
EQUAL_RANGE(
(iota(0, 100) | slice(10, 15) | reverse()),
(il<int>{14, 13, 12, 11, 10})
);
EQUAL_RANGE(
(iota(10, 15) | enumerate() | reverse()),
(il<std::tuple<size_t, int>>{ {4, 14}, { 3, 13 }, { 2, 12 }, { 1, 11 }, { 0, 10 }})
);
EQUAL_RANGE(
(iota(0, 100) | enumerate() | slice(10, 15)),
(il<std::tuple<size_t, int>>{ {10, 10}, { 11, 11 }, { 12, 12 }, { 13, 13 }, { 14, 14 } })
);
EQUAL_RANGE(
(iota(0, 100) | enumerate() | slice(10, 15) | reverse()),
(il<std::tuple<size_t, int>>{ {14, 14}, { 13, 13 }, { 12, 12 }, { 11, 11 }, { 10, 10 } })
);
EQUAL_RANGE( // test slice in bidirectional iterator
(iota(0, 10) | filter([](int i) {return i % 2 == 0; }) | slice(1, End - 1)),
(il<int>{ 2, 4, 6 })
);
{
// Can't compile because generate_n create a forward iterator range
// int y = 1;
// EQUAL_RANGE( // test slice in forward iterator
// (rah::view::generate_n(4, [&y]() mutable { auto prev = y; y *= 2; return prev; }) | slice(1, End - 1)),
// (il<int>{ 2, 4 })
// );
}
{
// Test creation of a custom iterator
auto gen = customGenerate();
std::vector<int> gen_copy;
std::copy(begin(gen), end(gen), std::back_inserter(gen_copy));
EQUAL_RANGE(gen_copy, il<int>({ 1, 2, 4, 8 }));
}
{
using namespace rah;
using namespace rah::view;
int const width = 5;
int const height = 6;
int const start = 8;
int startX = start % width;
int startY = start / width;
int const end = 22;
int endX = end % width;
int endY = end / width;
auto getRangeX = [=](int y)
{
if (y == startY)
return std::make_tuple(y, ints(startX, width));
else if (y == endY)
return std::make_tuple(y, ints(0, endX));
else
return std::make_tuple(y, ints(0, width));
};
std::vector<std::atomic<int>> test(width * height);
auto updateRaw = [&](auto&& y_xRange)
{
auto y = std::get<0>(y_xRange);
auto xRange = std::get<1>(y_xRange);
for (int x : xRange)
++test[x + y * width];
};
for (int ySelector : ints(0, 3))
{
auto range = iota(startY + ySelector, endY + 1, 3) | transform(getRangeX);
rah::for_each(range, updateRaw);
}
assert(all_of(test | slice(0, start), [](auto&& val) {return val == 0; }));
assert(all_of(test | slice(start, end), [](auto&& val) {return val == 1; }));
assert(all_of(test | slice(end, rah::End), [](auto&& val) {return val == 0; }));
}
std::cout << "ALL TEST OK" << std::endl;
return 0;
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: OVRPlugin
#include "GlobalNamespace/OVRPlugin.hpp"
// Including type: OVRPlugin/Media
#include "GlobalNamespace/OVRPlugin_Media.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Version
class Version;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: OVRP_1_57_0
class OVRP_1_57_0;
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(GlobalNamespace::OVRPlugin::OVRP_1_57_0);
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::OVRPlugin::OVRP_1_57_0*, "", "OVRPlugin/OVRP_1_57_0");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: OVRPlugin/OVRP_1_57_0
// [TokenAttribute] Offset: FFFFFFFF
class OVRPlugin::OVRP_1_57_0 : public ::Il2CppObject {
public:
// Get static field: static public readonly System.Version version
static System::Version* _get_version();
// Set static field: static public readonly System.Version version
static void _set_version(System::Version* value);
// static private System.Void .cctor()
// Offset: 0x17EAFA4
static void _cctor();
// static public OVRPlugin/Result ovrp_Media_GetPlatformCameraMode(out OVRPlugin/Media/PlatformCameraMode platformCameraMode)
// Offset: 0x17E19F4
static GlobalNamespace::OVRPlugin::Result ovrp_Media_GetPlatformCameraMode(ByRef<GlobalNamespace::OVRPlugin::Media::PlatformCameraMode> platformCameraMode);
// static public OVRPlugin/Result ovrp_Media_SetPlatformCameraMode(OVRPlugin/Media/PlatformCameraMode platformCameraMode)
// Offset: 0x17E1B7C
static GlobalNamespace::OVRPlugin::Result ovrp_Media_SetPlatformCameraMode(GlobalNamespace::OVRPlugin::Media::PlatformCameraMode platformCameraMode);
// static public OVRPlugin/Result ovrp_SetEyeFovPremultipliedAlphaMode(OVRPlugin/Bool enabled)
// Offset: 0x17EAE14
static GlobalNamespace::OVRPlugin::Result ovrp_SetEyeFovPremultipliedAlphaMode(GlobalNamespace::OVRPlugin::Bool enabled);
// static public OVRPlugin/Result ovrp_GetEyeFovPremultipliedAlphaMode(ref OVRPlugin/Bool enabled)
// Offset: 0x17EAE94
static GlobalNamespace::OVRPlugin::Result ovrp_GetEyeFovPremultipliedAlphaMode(ByRef<GlobalNamespace::OVRPlugin::Bool> enabled);
// static public OVRPlugin/Result ovrp_SetKeyboardOverlayUV(OVRPlugin/Vector2f uv)
// Offset: 0x17EAF14
static GlobalNamespace::OVRPlugin::Result ovrp_SetKeyboardOverlayUV(GlobalNamespace::OVRPlugin::Vector2f uv);
}; // OVRPlugin/OVRP_1_57_0
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_57_0::_cctor
// Il2CppName: .cctor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&GlobalNamespace::OVRPlugin::OVRP_1_57_0::_cctor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_57_0*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_57_0::ovrp_Media_GetPlatformCameraMode
// Il2CppName: ovrp_Media_GetPlatformCameraMode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::OVRPlugin::Result (*)(ByRef<GlobalNamespace::OVRPlugin::Media::PlatformCameraMode>)>(&GlobalNamespace::OVRPlugin::OVRP_1_57_0::ovrp_Media_GetPlatformCameraMode)> {
static const MethodInfo* get() {
static auto* platformCameraMode = &::il2cpp_utils::GetClassFromName("", "OVRPlugin/Media/PlatformCameraMode")->this_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_57_0*), "ovrp_Media_GetPlatformCameraMode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{platformCameraMode});
}
};
// Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_57_0::ovrp_Media_SetPlatformCameraMode
// Il2CppName: ovrp_Media_SetPlatformCameraMode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::OVRPlugin::Result (*)(GlobalNamespace::OVRPlugin::Media::PlatformCameraMode)>(&GlobalNamespace::OVRPlugin::OVRP_1_57_0::ovrp_Media_SetPlatformCameraMode)> {
static const MethodInfo* get() {
static auto* platformCameraMode = &::il2cpp_utils::GetClassFromName("", "OVRPlugin/Media/PlatformCameraMode")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_57_0*), "ovrp_Media_SetPlatformCameraMode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{platformCameraMode});
}
};
// Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_57_0::ovrp_SetEyeFovPremultipliedAlphaMode
// Il2CppName: ovrp_SetEyeFovPremultipliedAlphaMode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::OVRPlugin::Result (*)(GlobalNamespace::OVRPlugin::Bool)>(&GlobalNamespace::OVRPlugin::OVRP_1_57_0::ovrp_SetEyeFovPremultipliedAlphaMode)> {
static const MethodInfo* get() {
static auto* enabled = &::il2cpp_utils::GetClassFromName("", "OVRPlugin/Bool")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_57_0*), "ovrp_SetEyeFovPremultipliedAlphaMode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{enabled});
}
};
// Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_57_0::ovrp_GetEyeFovPremultipliedAlphaMode
// Il2CppName: ovrp_GetEyeFovPremultipliedAlphaMode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::OVRPlugin::Result (*)(ByRef<GlobalNamespace::OVRPlugin::Bool>)>(&GlobalNamespace::OVRPlugin::OVRP_1_57_0::ovrp_GetEyeFovPremultipliedAlphaMode)> {
static const MethodInfo* get() {
static auto* enabled = &::il2cpp_utils::GetClassFromName("", "OVRPlugin/Bool")->this_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_57_0*), "ovrp_GetEyeFovPremultipliedAlphaMode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{enabled});
}
};
// Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_57_0::ovrp_SetKeyboardOverlayUV
// Il2CppName: ovrp_SetKeyboardOverlayUV
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::OVRPlugin::Result (*)(GlobalNamespace::OVRPlugin::Vector2f)>(&GlobalNamespace::OVRPlugin::OVRP_1_57_0::ovrp_SetKeyboardOverlayUV)> {
static const MethodInfo* get() {
static auto* uv = &::il2cpp_utils::GetClassFromName("", "OVRPlugin/Vector2f")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_57_0*), "ovrp_SetKeyboardOverlayUV", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{uv});
}
};
|
#include "crypto.h"
#include <openssl/evp.h>
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
#include <opensslpp/base64.h>
#include <opensslpp/aes_cbc.h>
void base64_encode(const void* in_data, int in_length, char** out_data, int& out_length)
{
const auto pl = 4 * ((in_length + 2) / 3);
*out_data = reinterpret_cast<char*>(calloc(pl + 1, 1)); //+1 for the terminating null that EVP_EncodeBlock adds on
out_length = EVP_EncodeBlock(reinterpret_cast<unsigned char*>(*out_data), reinterpret_cast<const unsigned char*>(in_data), in_length);
}
void base64_decode(const void* in_data, int in_length, unsigned char** out_data, int& out_length)
{
const auto pl = 3 * in_length / 4;
*out_data = reinterpret_cast<unsigned char*>(calloc(pl + 1, 1));
out_length = EVP_DecodeBlock(*out_data, reinterpret_cast<const unsigned char*>(in_data), in_length);
}
bool base64_encode_text_file(const char* in_filename, const char* out_filename)
{
try
{
std::ifstream in_file(in_filename, std::ifstream::in);
std::stringstream in_buffer;
in_buffer << in_file.rdbuf();
std::vector<uint8_t> decoded_str;
std::copy(std::istream_iterator<uint8_t>(in_buffer), std::istream_iterator<uint8_t>(), std::back_inserter(decoded_str));
const std::string encoded = opensslpp::Base64::encode(decoded_str);
std::ofstream out_file(out_filename, std::ifstream::out);
out_file << encoded;
return true;
}
catch (const std::exception& e)
{
std::cout << "Error: Could not encode " << in_filename << std::endl;
return false;
}
}
bool base64_decode_text_file(const char* in_filename, const char* out_filename)
{
try
{
std::ifstream in_file(in_filename, std::ifstream::in);
std::stringstream in_buffer;
in_buffer << in_file.rdbuf();
const std::vector<uint8_t> decoded = opensslpp::Base64::decode(in_buffer.str());
std::string decoded_str(decoded.begin(), decoded.end());
std::ofstream out_file(out_filename, std::ifstream::out);
out_file << decoded_str;
}
catch (const std::exception& e)
{
std::cout << "Error: Could not decode " << in_filename << std::endl;
return false;
}
}
bool aes_cbc_create_key(const char* out_filename)
{
try
{
auto newAes = opensslpp::Aes256Cbc::createNewKey();
if (newAes == nullptr) throw;
std::ofstream out_file(out_filename, std::ifstream::out | std::ios::binary);
out_file.write(reinterpret_cast<const char*>(newAes->key().data()), newAes->key().size());
out_file.close();
return true;
}
catch (const std::exception& e)
{
std::cout << "Error: Could not generate key "<< std::endl;
return false;
}
}
bool aes_cbc_encode_to_file(
const char* in_filename_data,
const char* in_filename_key,
const char* out_filename_data)
{
try
{
std::vector<uint8_t> in_data;
{
std::ifstream in_file_data(in_filename_data, std::ifstream::in | std::ifstream::binary);
in_file_data.seekg (0, in_file_data.end);
int length = in_file_data.tellg();
in_file_data.seekg (0, in_file_data.beg);
in_data.resize(length);
in_file_data.read(reinterpret_cast<char*>(&in_data[0]), length);
in_file_data.close();
}
opensslpp::Aes256Cbc::Key key;
{
std::ifstream in_file_key(in_filename_key, std::ifstream::in | std::ifstream::binary);
in_file_key.seekg (0, in_file_key.end);
int length = in_file_key.tellg();
in_file_key.seekg (0, in_file_key.beg);
char* buffer = new char[length];
in_file_key.read(buffer, length);
in_file_key.close();
std::memcpy(key.data(), buffer, length);
delete[] buffer;
}
auto aes = opensslpp::Aes256Cbc::createWithKey(key);
std::vector<uint8_t> cipher;
if (!aes->encrypt(in_data.data(), in_data.size(), cipher)) throw;
std::ofstream out_file_data(out_filename_data, std::ios::out | std::ios::binary);
out_file_data.write(reinterpret_cast<const char*>(cipher.data()), cipher.size());
return true;
}
catch (const std::exception& e)
{
std::cout << "Error: Could not encode " << in_filename_data << std::endl;
return false;
}
}
bool aes_cbc_decode_to_file(
const char* in_filename_data,
const char* in_filename_key,
const char* out_filename_data)
{
try
{
std::vector<uint8_t> cipher;
{
std::ifstream in_file_data(in_filename_data, std::ios::in | std::ios::binary | std::ios::ate);
auto fsize = in_file_data.tellg();
in_file_data.seekg(0, std::ios::beg);
cipher.resize(fsize);
in_file_data.read(reinterpret_cast<char*>(&cipher[0]), fsize);
}
opensslpp::Aes256Cbc::Key key;
std::ifstream in_file_key(in_filename_key, std::ifstream::in | std::ifstream::binary);
in_file_key.seekg (0, in_file_key.end);
int length = in_file_key.tellg();
in_file_key.seekg (0, in_file_key.beg);
char* buffer = new char[length];
in_file_key.read(buffer, length);
in_file_key.close();
std::memcpy(key.data(), buffer, length);
auto aes = opensslpp::Aes256Cbc::createWithKey(key);
delete[] buffer;
std::vector<uint8_t> decoded;
if (!aes->decrypt(cipher, decoded)) throw("Exception: Failed decrypting");
std::ofstream out_file_data(out_filename_data, std::ios::out | std::ios::binary);
out_file_data.write(reinterpret_cast<const char*>(decoded.data()), decoded.size());
}
catch (const std::exception& e)
{
std::cout
<< "Error: Could not decode " << in_filename_data << std::endl
<< e.what() << std::endl;
return false;
}
}
int aes_cbc_decode_to_str(
const char* in_filename_data,
const char* in_filename_key,
char* out_decoded_data)
{
try
{
std::vector<uint8_t> cipher;
{
std::ifstream in_file_data(in_filename_data, std::ios::in | std::ios::binary | std::ios::ate);
auto fsize = in_file_data.tellg();
in_file_data.seekg(0, std::ios::beg);
cipher.resize(fsize);
in_file_data.read(reinterpret_cast<char*>(&cipher[0]), fsize);
}
opensslpp::Aes256Cbc::Key key;
std::ifstream in_file_key(in_filename_key, std::ifstream::in | std::ifstream::binary);
in_file_key.seekg (0, in_file_key.end);
int length = in_file_key.tellg();
in_file_key.seekg (0, in_file_key.beg);
char* buffer = new char[length];
in_file_key.read(buffer, length);
in_file_key.close();
std::memcpy(key.data(), buffer, length);
auto aes = opensslpp::Aes256Cbc::createWithKey(key);
delete[] buffer;
std::vector<uint8_t> decoded;
if (!aes->decrypt(cipher, decoded)) throw("Exception: Failed decrypting");
decoded.push_back('\0');
memcpy(out_decoded_data, decoded.data(), decoded.size());
return decoded.size();
}
catch (const std::exception& e)
{
std::cout
<< "Error: Could not decode " << in_filename_data << std::endl
<< e.what() << std::endl;
return 0;
}
}
|
// Filename: maxEggImport.cxx
// Created by: jyelon (15Jul05)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
//
// This is the wrapper code for the max importer plugin.
// It includes:
//
// - user interface dialogs and popups
// - plugin initialization/registration
//
// It does not include the actual code to traverse the EggData.
//
////////////////////////////////////////////////////////////////////
// Include this before everything
#include "pandatoolbase.h"
// MAX includes
#include "maxEggLoader.h"
#include "Max.h"
#include "maxImportRes.h"
#include "istdplug.h"
// panda includes.
#include "notifyCategoryProxy.h"
#include <iostream>
#include <sstream>
class MaxEggImporter : public SceneImport
{
public:
// GUI-related methods
MaxEggImporter();
~MaxEggImporter();
int ExtCount(); // Number of extensions supported
const TCHAR * Ext(int n); // Extension #n (i.e. "EGG")
const TCHAR * LongDesc(); // Long ASCII description (i.e. "Egg Importer")
const TCHAR * ShortDesc(); // Short ASCII description (i.e. "Egg")
const TCHAR * AuthorName(); // ASCII Author name
const TCHAR * CopyrightMessage();// ASCII Copyright message
const TCHAR * OtherMessage1(); // Other message #1
const TCHAR * OtherMessage2(); // Other message #2
unsigned int Version(); // Version number * 100 (i.e. v3.01 = 301)
void ShowAbout(HWND hWnd); // Show DLL's "About..." box
int DoImport(const TCHAR *name,ImpInterface *ei,Interface *i, BOOL suppressPrompts);
public:
// GUI-related fields
static BOOL _merge;
static BOOL _importmodel;
static BOOL _importanim;
};
BOOL MaxEggImporter::_merge = TRUE;
BOOL MaxEggImporter::_importmodel = TRUE;
BOOL MaxEggImporter::_importanim = FALSE;
MaxEggImporter::MaxEggImporter()
{
}
MaxEggImporter::~MaxEggImporter()
{
}
int MaxEggImporter::ExtCount()
{
// Number of different extensions handled by this importer.
return 1;
}
const TCHAR * MaxEggImporter::Ext(int n)
{
// Fetch the extensions handled by this importer.
switch(n) {
case 0: return _T("egg");
default: return _T("");
}
}
const TCHAR * MaxEggImporter::LongDesc()
{
return _T("Panda3D Egg Importer");
}
const TCHAR * MaxEggImporter::ShortDesc()
{
return _T("Panda3D Egg");
}
const TCHAR * MaxEggImporter::AuthorName()
{
return _T("Joshua Yelon");
}
const TCHAR * MaxEggImporter::CopyrightMessage()
{
return _T("Copyight (c) 2005 Josh Yelon");
}
const TCHAR * MaxEggImporter::OtherMessage1()
{
return _T("");
}
const TCHAR * MaxEggImporter::OtherMessage2()
{
return _T("");
}
unsigned int MaxEggImporter::Version()
{
return 100;
}
static INT_PTR CALLBACK AboutBoxDlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case WM_INITDIALOG:
CenterWindow(hWnd, GetParent(hWnd));
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
EndDialog(hWnd, 1);
break;
}
break;
default:
return FALSE;
}
return TRUE;
}
void MaxEggImporter::ShowAbout(HWND hWnd)
{
DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_ABOUTBOX),
hWnd, AboutBoxDlgProc, 0);
}
static INT_PTR CALLBACK ImportDlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
MaxEggImporter *imp = (MaxEggImporter*) GetWindowLongPtr(hWnd, GWLP_USERDATA);
switch (msg) {
case WM_INITDIALOG:
imp = (MaxEggImporter*)lParam;
SetWindowLongPtr(hWnd, GWLP_USERDATA, lParam);
CenterWindow(hWnd, GetParent(hWnd));
CheckDlgButton(hWnd, IDC_MERGE, imp->_merge);
CheckDlgButton(hWnd, IDC_IMPORTMODEL, imp->_importmodel);
CheckDlgButton(hWnd, IDC_IMPORTANIM, imp->_importanim);
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
imp->_merge = IsDlgButtonChecked(hWnd, IDC_MERGE);
imp->_importmodel = IsDlgButtonChecked(hWnd, IDC_IMPORTMODEL);
imp->_importanim = IsDlgButtonChecked(hWnd, IDC_IMPORTANIM);
EndDialog(hWnd, 1);
break;
case IDCANCEL:
EndDialog(hWnd, 0);
break;
}
break;
default:
return FALSE;
}
return TRUE;
}
int MaxEggImporter::DoImport(const TCHAR *name,ImpInterface *ii,Interface *i, BOOL suppressPrompts) {
// Prompt the user with our dialogbox.
if (!DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_IMPORT_DLG),
i->GetMAXHWnd(), ImportDlgProc, (LPARAM)this)) {
return 1;
}
std::ostringstream log;
Notify::ptr()->set_ostream_ptr(&log, false);
bool ok = MaxLoadEggFile(name, _merge ? true:false, _importmodel ? true:false, _importanim ? true:false);
string txt = log.str();
if (txt != "") {
MessageBox(NULL, txt.c_str(), "Panda3D Importer", MB_OK);
} else {
if (!ok) MessageBox(NULL, "Import Failed, unknown reason\n", "Panda3D Importer", MB_OK);
}
Notify::ptr()->set_ostream_ptr(NULL, false);
return 1;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Plugin Initialization
//
// The following code enables Max to load this DLL, get a list
// of the classes defined in this DLL, and provides a means for
// Max to create instances of those classes.
//
////////////////////////////////////////////////////////////////////////////////////////////////////
HINSTANCE hInstance;
BOOL WINAPI DllMain(HINSTANCE hinstDLL,ULONG fdwReason,LPVOID lpvReserved) {
static int controlsInit = FALSE;
hInstance = hinstDLL;
if (!controlsInit) {
controlsInit = TRUE;
// It appears that InitCustomControls is deprecated in 2012.
// I'm not sure if we can just remove it like this, but
// I've heard that it seems to work, so let's do it like this.
#if MAX_VERSION_MAJOR < 14
InitCustomControls(hInstance);
#endif
InitCommonControls();
}
return (TRUE);
}
#define PANDAEGGIMP_CLASS_ID1 0x377193ab
#define PANDAEGGIMP_CLASS_ID2 0x897afe12
class MaxEggImporterClassDesc: public ClassDesc {
public:
int IsPublic() {return 1;}
void *Create(BOOL loading = FALSE) {return new MaxEggImporter;}
const TCHAR *ClassName() {return _T("MaxEggImporter");}
SClass_ID SuperClassID() {return SCENE_IMPORT_CLASS_ID;}
Class_ID ClassID() {return Class_ID(PANDAEGGIMP_CLASS_ID1,PANDAEGGIMP_CLASS_ID2);}
const TCHAR *Category() {return _T("Chrutilities");}
};
static MaxEggImporterClassDesc MaxEggImporterDesc;
__declspec( dllexport ) const TCHAR* LibDescription()
{
return _T("Panda3D Egg Importer");
}
__declspec( dllexport ) int LibNumberClasses()
{
return 1;
}
__declspec( dllexport ) ClassDesc* LibClassDesc(int i)
{
switch(i) {
case 0: return &MaxEggImporterDesc;
default: return 0;
}
}
__declspec( dllexport ) ULONG LibVersion()
{
return VERSION_3DSMAX;
}
|
#include <AComponent/function.h>
#include <iostream>
namespace a
{
void function()
{
std::cout << "Run APackage function()"
<< "\n";
}
}
|
#include <fstream>
#include <iostream>
using namespace std;
int main() {
int n, ans;
long long sum = 0;
cin >> n;
for(int h = 1 ; ; ++ h) {
sum = sum + h;
if(n >= sum) {
ans = h;
n -= sum;
}
else {
cout << h - 1 << '\n';
break;
}
}
}
|
/*
**==============================================================================
**
** Copyright (c) 2003, 2004, 2005, 2006, Michael Brasher, Karl Schopmeyer
**
** 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 <cstdio>
#include <cstring>
#include "libgen.h"
POSIX_NAMESPACE_BEGIN
char* dirname(char* path)
{
if (!path || *path == '\0')
return ".";
// Seek zero terminator.
char* end = path;
while (*end)
end++;
// Remove trailing slashes.
while (--end != path && *end == '/')
*end = '\0';
// Find last slash.
char* slash = strrchr(path, '/');
// If no slash...
if (!slash)
return ".";
// If found slash that was first character.
if (path == slash)
return "/";
*slash = '\0';
return path;
}
POSIX_NAMESPACE_END
|
#include "nonce_num_set.h"
NonceNumRange NonceNumSet::CutPieceAtBeginning( uint64_t preferredSplitSize )
{
EXCEPTION_ASSERT( !AreAnyNoncesOverlapping() );
EXCEPTION_ASSERT( !ranges_.empty() );
NonceNumRange firstRange = *ranges_.cbegin();
ranges_.erase( ranges_.cbegin() );
auto splitResult = firstRange.Split( preferredSplitSize );
if ( splitResult.second )
{
ranges_.insert( *splitResult.second );
}
return splitResult.first;
}
bool NonceNumSet::AreAnyNoncesOverlapping() const
{
// TODO resembles part in OverlapChecker::CheckForNonceOverlaps(), but with differences.
// No idea if they can be reworked to a single piece of code
bool result = false;
Utils::ExecutePairWise( ranges_.begin(), ranges_.end(), [&result]
( const NonceNumRange& lhs, const NonceNumRange& rhs )
{
boost::optional<NonceNumRange> possibleOverlap = lhs.CalcIntersectionWith( rhs );
result = result || possibleOverlap;
}
);
return result;
}
|
#pragma once
#include <stdafx.h>
#include <Utils.h>
|
/*!
@file
Defines `boost::hana::iterate`.
@copyright Louis Dionne 2013-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_FUNCTIONAL_ITERATE_HPP
#define BOOST_HANA_FUNCTIONAL_ITERATE_HPP
#include <boost/hana/config.hpp>
#include <boost/hana/core/when.hpp>
#include <boost/hana/functional/partial.hpp>
#include <cstddef>
namespace boost { namespace hana {
//! @ingroup group-functional
//! Applies another function `n` times to its argument.
//!
//! Given a function `f` and an argument `x`, `iterate<n>(f, x)` returns
//! the result of applying `f` `n` times to its argument. In other words,
//! @code
//! iterate<n>(f, x) == f(f( ... f(x)))
//! ^^^^^^^^^^ n times total
//! @endcode
//!
//! If `n == 0`, `iterate<n>(f, x)` returns the `x` argument unchanged
//! and `f` is never applied. It is important to note that the function
//! passed to `iterate<n>` must be a unary function. Indeed, since `f`
//! will be called with the result of the previous `f` application, it
//! may only take a single argument.
//!
//! In addition to what's documented above, `iterate` can also be
//! partially applied to the function argument out-of-the-box. In
//! other words, `iterate<n>(f)` is a function object applying `f`
//! `n` times to the argument it is called with, which means that
//! @code
//! iterate<n>(f)(x) == iterate<n>(f, x)
//! @endcode
//!
//! This is provided for convenience, and it turns out to be especially
//! useful in conjunction with higher-order algorithms.
//!
//!
//! Signature
//! ---------
//! Given a function \f$ f : T \to T \f$ and `x` and argument of data
//! type `T`, the signature is
//! \f$
//! \mathtt{iterate_n} : (T \to T) \times T \to T
//! \f$
//!
//! @tparam n
//! An unsigned integer representing the number of times that `f`
//! should be applied to its argument.
//!
//! @param f
//! A function to apply `n` times to its argument.
//!
//! @param x
//! The initial value to call `f` with.
//!
//!
//! Example
//! -------
//! @include example/functional/iterate.cpp
#ifdef BOOST_HANA_DOXYGEN_INVOKED
template <std::size_t n>
constexpr auto iterate = [](auto&& f) {
return [perfect-capture](auto&& x) -> decltype(auto) {
return f(f( ... f(forwarded(x))));
};
};
#else
template <std::size_t n, typename = when<true>>
struct iterate_t;
template <>
struct iterate_t<0> {
template <typename F, typename X>
constexpr X operator()(F&&, X&& x) const
{ return static_cast<X&&>(x); }
};
template <>
struct iterate_t<1> {
template <typename F, typename X>
constexpr decltype(auto) operator()(F&& f, X&& x) const {
return f(static_cast<X&&>(x));
}
};
template <>
struct iterate_t<2> {
template <typename F, typename X>
constexpr decltype(auto) operator()(F&& f, X&& x) const {
return f(f(static_cast<X&&>(x)));
}
};
template <>
struct iterate_t<3> {
template <typename F, typename X>
constexpr decltype(auto) operator()(F&& f, X&& x) const {
return f(f(f(static_cast<X&&>(x))));
}
};
template <>
struct iterate_t<4> {
template <typename F, typename X>
constexpr decltype(auto) operator()(F&& f, X&& x) const {
return f(f(f(f(static_cast<X&&>(x)))));
}
};
template <>
struct iterate_t<5> {
template <typename F, typename X>
constexpr decltype(auto) operator()(F&& f, X&& x) const {
return f(f(f(f(f(static_cast<X&&>(x))))));
}
};
template <std::size_t n>
struct iterate_t<n, when<(n >= 6) && (n < 12)>> {
template <typename F, typename X>
constexpr decltype(auto) operator()(F&& f, X&& x) const {
return iterate_t<n - 6>{}(f,
f(f(f(f(f(f(static_cast<X&&>(x)))))))
);
}
};
template <std::size_t n>
struct iterate_t<n, when<(n >= 12) && (n < 24)>> {
template <typename F, typename X>
constexpr decltype(auto) operator()(F&& f, X&& x) const {
return iterate_t<n - 12>{}(f,
f(f(f(f(f(f(f(f(f(f(f(f(
static_cast<X&&>(x)
))))))))))))
);
}
};
template <std::size_t n>
struct iterate_t<n, when<(n >= 24) && (n < 48)>> {
template <typename F, typename X>
constexpr decltype(auto) operator()(F&& f, X&& x) const {
return iterate_t<n - 24>{}(f,
f(f(f(f(f(f(f(f(f(f(f(f(
f(f(f(f(f(f(f(f(f(f(f(f(
static_cast<X&&>(x)
))))))))))))
))))))))))))
);
}
};
template <std::size_t n>
struct iterate_t<n, when<(n >= 48)>> {
template <typename F, typename X>
constexpr decltype(auto) operator()(F&& f, X&& x) const {
return iterate_t<n - 48>{}(f,
f(f(f(f(f(f(f(f(f(f(f(f(
f(f(f(f(f(f(f(f(f(f(f(f(
f(f(f(f(f(f(f(f(f(f(f(f(
f(f(f(f(f(f(f(f(f(f(f(f(
static_cast<X&&>(x)
))))))))))))
))))))))))))
))))))))))))
))))))))))))
);
}
};
template <std::size_t n>
struct make_iterate_t {
template <typename F>
constexpr decltype(auto) operator()(F&& f) const
{ return hana::partial(iterate_t<n>{}, static_cast<F&&>(f)); }
template <typename F, typename X>
constexpr decltype(auto) operator()(F&& f, X&& x) const {
return iterate_t<n>{}(static_cast<F&&>(f),
static_cast<X&&>(x));
}
};
template <std::size_t n>
BOOST_HANA_INLINE_VARIABLE constexpr make_iterate_t<n> iterate{};
#endif
}} // end namespace boost::hana
#endif // !BOOST_HANA_FUNCTIONAL_ITERATE_HPP
|
/******************************************************************************
* $Id: ogrwalkdriver.cpp
*
* Project: OpenGIS Simple Features Reference Implementation
* Purpose: Implements OGRWalkDriver class.
* Author: Xian Chen, chenxian at walkinfo.com.cn
*
******************************************************************************
* Copyright (c) 2013, ZJU Walkinfo Technology Corp., Ltd.
* Copyright (c) 2013, Even Rouault <even dot rouault at mines-paris dot org>
*
* 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 "ogrwalk.h"
/************************************************************************/
/* ~OGRWalkDriver() */
/************************************************************************/
OGRWalkDriver::~OGRWalkDriver()
{
}
/************************************************************************/
/* GetName() */
/************************************************************************/
const char *OGRWalkDriver::GetName()
{
return "Walk";
}
/************************************************************************/
/* Open() */
/************************************************************************/
OGRDataSource *OGRWalkDriver::Open( const char * pszFilename, int bUpdate )
{
if( STARTS_WITH_CI(pszFilename, "PGEO:") )
return NULL;
if( STARTS_WITH_CI(pszFilename, "GEOMEDIA:") )
return NULL;
if( !STARTS_WITH_CI(pszFilename, "WALK:")
&& !EQUAL(CPLGetExtension(pszFilename), "MDB") )
return NULL;
#ifndef WIN32
// Try to register MDB Tools driver
//
// ODBCINST.INI NOTE:
// This operation requires write access to odbcinst.ini file
// located in directory pointed by ODBCINISYS variable.
// Usually, it points to /etc, so non-root users can overwrite this
// setting ODBCINISYS with location they have write access to, e.g.:
// $ export ODBCINISYS=$HOME/etc
// $ touch $ODBCINISYS/odbcinst.ini
//
// See: http://www.unixodbc.org/internals.html
//
if ( !InstallMdbDriver() )
{
CPLError( CE_Warning, CPLE_AppDefined,
"Unable to install MDB driver for ODBC, MDB access may not supported.\n" );
}
else
CPLDebug( "Walk", "MDB Tools driver installed successfully!");
#endif /* ndef WIN32 */
OGRWalkDataSource *poDS = new OGRWalkDataSource();
if( !poDS->Open( pszFilename, bUpdate ) )
{
delete poDS;
return NULL;
}
else
return poDS;
}
/************************************************************************/
/* CreateDataSource() */
/************************************************************************/
OGRDataSource *OGRWalkDriver::CreateDataSource( const char * pszName,
CPL_UNUSED char **papszOptions )
{
//if( !EQUAL(CPLGetExtension(pszName), "MDB") )
// return NULL;
OGRWalkDataSource *poDS = new OGRWalkDataSource();
if( !poDS->Open( pszName, TRUE ) )
{
delete poDS;
CPLError( CE_Failure, CPLE_AppDefined,
"Walk driver doesn't currently support database creation.\n"
"Please create database with the `createdb' command." );
return NULL;
}
else
return poDS;
}
/************************************************************************/
/* TestCapability() */
/************************************************************************/
int OGRWalkDriver::TestCapability( CPL_UNUSED const char * pszCap )
{
return FALSE;
}
/************************************************************************/
/* RegisterOGRWalk() */
/************************************************************************/
void RegisterOGRWalk()
{
OGRSFDriverRegistrar::GetRegistrar()->RegisterDriver( new OGRWalkDriver );
}
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/disk_cache/simple/simple_test_util.h"
#include "base/files/file.h"
#include "net/disk_cache/simple/simple_util.h"
namespace disk_cache {
namespace simple_util {
bool CreateCorruptFileForTests(const std::string& key,
const base::FilePath& cache_path) {
base::FilePath entry_file_path = cache_path.AppendASCII(
disk_cache::simple_util::GetFilenameFromKeyAndFileIndex(key, 0));
int flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE;
base::File entry_file(entry_file_path, flags);
if (!entry_file.IsValid())
return false;
return entry_file.Write(0, "dummy", 1) == 1;
}
} // namespace simple_util
} // namespace disk_cache
|
#include<iostream>
using namespace std;
void checkPrimeNumber(int);
int main()
{
int num;
cout<<"Enter a Number: ";
cin>>num;
checkPrimeNumber(num);
cout<<endl;
return 0;
}
void checkPrimeNumber(int num)
{
int i, chk=0;
for(i=2; i<num; i++)
{
if(num%i==0)
{
chk++;
break;
}
}
if(chk==0)
cout<<"\nIt is a Prime Number";
else
cout<<"\nIt is not a Prime Number";
}
|
// Copyright (c) YugaByte, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations
// under the License.
//
#include "yb/master/yql_aggregates_vtable.h"
namespace yb {
namespace master {
YQLAggregatesVTable::YQLAggregatesVTable(const TableName& table_name,
const NamespaceName& namespace_name,
Master* const master)
: YQLEmptyVTable(table_name, namespace_name, master, CreateSchema()) {
}
Schema YQLAggregatesVTable::CreateSchema() const {
SchemaBuilder builder;
CHECK_OK(builder.AddHashKeyColumn("keyspace_name", DataType::STRING));
CHECK_OK(builder.AddKeyColumn("aggregate_name", DataType::STRING));
// TODO: argument_types should be part of the primary key, but since we don't support the CQL
// 'frozen' type, we can't have collections in our primary key.
CHECK_OK(builder.AddColumn("argument_types", QLType::CreateTypeList(DataType::STRING)));
CHECK_OK(builder.AddColumn("final_func", QLType::Create(DataType::STRING)));
CHECK_OK(builder.AddColumn("initcond", QLType::Create(DataType::STRING)));
CHECK_OK(builder.AddColumn("state_func", QLType::Create(DataType::STRING)));
CHECK_OK(builder.AddColumn("state_type", QLType::Create(DataType::STRING)));
return builder.Build();
}
} // namespace master
} // namespace yb
|
#include "Janela.hpp"
#include "Jogador.hpp"
Janela::Janela (int resolucao_x, int resolucao_y, std::string nome, int largura, int altura, int fps_maximo)
: janela(sf::VideoMode(largura, altura), nome, sf::Style::Titlebar | sf::Style::Resize)
, camera(sf::Vector2f(0.0f,0.0f), sf::Vector2f(largura, altura))
, _jogador_principal(NULL)
, _altura (altura)
, _largura (largura)
{
janela.setPosition(sf::Vector2i(0,0));
janela.setSize(sf::Vector2u(resolucao_x, resolucao_y));
janela.setFramerateLimit(fps_maximo);
}
Janela::~Janela() {
if (janela.isOpen()) {
janela.close();
}
}
bool Janela::estaAberta() {
return janela.isOpen();
}
void Janela::atualizar () {
while (janela.pollEvent(evento)) {
// Caso foi clicado no 'X' da janela
if (evento.type == sf::Event::Closed) {
janela.close();
}
}
}
void Janela::close() {
janela.close();
}
void Janela::clear() {
// "Limpa a tela" de branco
janela.clear(sf::Color::Transparent);
}
void Janela::setJogadorPrincipal(Jogador* p_ent) {
if(p_ent != NULL) {
_jogador_principal = p_ent;
}
else {
std::cerr << "Janela::setJogadorPrincipal: ponteiro para jogador invalido" << std::endl;
}
}
void Janela::removerJogadorPrincipal() {
resetarCamera();
_jogador_principal = NULL;
}
void Janela::resetarCamera() {
camera.setCenter(sf::Vector2f(_largura / 2, _altura/2));
janela.setView(camera);
}
void Janela::atualizarCamera(sf::Vector2f limites) {
if (_jogador_principal != NULL) {
int delta_direita = _largura / 10;
int delta_esquerda = _largura / 3;
if (_jogador_principal->getPosicao().x > limites.x + _largura * 0.26 - delta_direita &&
_jogador_principal->getPosicao().x < limites.y - _largura * 0.735 + delta_esquerda) {
if (_jogador_principal->getPosicao().x - delta_direita > camera.getCenter().x ) {
camera.setCenter(_jogador_principal->getPosicao().x - delta_direita, _altura/2);
}
else if (_jogador_principal->getPosicao().x + delta_esquerda < camera.getCenter().x ) {
camera.setCenter(_jogador_principal->getPosicao().x + delta_esquerda , _altura/2);
}
janela.setView(camera);
}
}
}
void Janela::atualizarCamera() {
if (_jogador_principal != NULL) {
if (_jogador_principal->getPosicao().x - 40 > camera.getCenter().x ) {
camera.setCenter(_jogador_principal->getPosicao().x - 40, _altura/2);
}
else if (_jogador_principal->getPosicao().x + 100 < camera.getCenter().x ) {
camera.setCenter(_jogador_principal->getPosicao().x + 100, _altura/2);
}
janela.setView(camera);
}
}
void Janela::desenhar(sf::Drawable& desenho) {
janela.draw(desenho);
}
void Janela::renderiza() {
janela.display();
}
sf::Vector2f Janela::getCameraPos() {
return camera.getCenter();
}
std::string& Janela::getString (std::string& str, bool receber_dados) {
while (janela.pollEvent(evento)) {
// Permite fechar a janela enquanto recebe a string
if (evento.type == sf::Event::Closed) {
janela.close();
}
if (evento.type == sf::Event::TextEntered) {
if (evento.text.unicode < 128 && receber_dados) {
char c = static_cast<char>(evento.text.unicode);
if (c == '\b' && str.size() > 0) {
str.pop_back();
}
else if (c != 13 && c != '\b') {
str += c;
}
}
}
}
return str;
}
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
int totalTilt = 0;
int getSum(TreeNode* root) {
if (!root) return 0;
int leftSum = getSum(root->left);
int rightSum = getSum(root->right);
totalTilt += abs(leftSum - rightSum);
return leftSum + root->val + rightSum;
}
public:
int findTilt(TreeNode* root) {
getSum(root);
return totalTilt;
}
};
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <cstring>
#include <gna_plugin_log.hpp>
#include <limits>
#include "backend/gna_types.h"
#include "quantization.h"
#include <algorithm>
#ifdef DEBUG
#define QUANTWARNING(...) (fprintf(stderr, __VA_ARGS__))
#else
#define QUANTWARNING(...)
#endif
template<>
void QuantizationCallback<int16_t, int32_t>::runFakeQuantize() const {
if (quantizedWeights) {
THROW_GNA_EXCEPTION << "Quantized weights are not yet supported in int16 quantization mode";
}
uint32_t num_saturate = 0;
auto input_low = 0.0f;
auto input_high = 0.0f;
auto output_low = 0.0f;
auto output_high = 0.0f;
auto levels = 1;
if (fq_num_stats > 0) {
input_low = *fq_ptr_input_low;
input_high = *fq_ptr_input_high;
output_low = *fq_ptr_output_low;
output_high = *fq_ptr_output_high;
levels = fq_levels;
}
for (uint32_t row = 0; row < num_rows; row++) {
for (uint32_t col = 0; col < num_columns; col++) {
float rounding_value = (ptr_float_weights[row * num_columns + col] > 0) ? 0.5f : -0.5f;
float value = ptr_float_weights[row * num_columns + col];
if (fq_num_stats > 0) {
auto x = value;
if (x <= std::min(input_low, input_high)) {
value = output_low;
} else if (x > std::max(input_low, input_high)) {
value = output_high;
} else {
value = nearbyint((x - input_low) / (input_high - input_low) * (levels - 1)) /
(levels - 1) * (output_high - output_low) + output_low;
}
}
value = value * *ptr_weight_scale_factor + rounding_value;
int16_t* ptr_weight_16 = ptr_int_weights + (row * num_columns_padded + col);
if (value > std::numeric_limits<int16_t>::max()) {
*ptr_weight_16 = std::numeric_limits<int16_t>::max();
num_saturate++;
} else if (value < std::numeric_limits<int16_t>::min()) {
*ptr_weight_16 = std::numeric_limits<int16_t>::min();
num_saturate++;
} else {
*ptr_weight_16 = (int16_t)value;
}
}
for (uint32_t col = num_columns; col < num_columns_padded; col++) {
int16_t* ptr_weight_16 = ptr_int_weights + (row * num_columns_padded + col);
*ptr_weight_16 = 0;
}
}
for (uint32_t row = num_rows; row < num_rows_padded; row++) {
for (uint32_t col = 0; col < num_columns_padded; col++) {
int16_t* ptr_weight_16 = ptr_int_weights + (row * num_columns_padded + col);
*ptr_weight_16 = 0;
}
}
// case for element wise layer
if (ptr_float_biases != nullptr && ptr_int_biases != nullptr) {
for (uint32_t j = 0; j < num_rows; j++) {
float rounding_value = (ptr_float_biases[j] > 0) ? 0.5f : -0.5f;
float value = ptr_float_biases[j] * *ptr_output_scale_factor + rounding_value;
if (value > 2147483647.0) {
ptr_int_biases[j] = 2147483647L;
num_saturate++;
} else if (value < -2147483648.0) {
ptr_int_biases[j] = -2147483648LL;
num_saturate++;
} else {
ptr_int_biases[j] = (int32_t)value;
}
}
for (uint32_t j = num_rows; j < num_rows_padded; j++) {
ptr_int_biases[j] = 0;
}
}
if (num_saturate > 0) {
QUANTWARNING("Warning: %d / %d saturations in QuantizeAffine16()\n",
num_saturate,
num_rows * num_columns + num_rows);
}
}
template<>
void QuantizationCallback<int16_t, int32_t>::runQuantize() const {
uint32_t num_saturate = 0;
for (uint32_t row = 0; row < num_rows; row++) {
for (uint32_t col = 0; col < num_columns; col++) {
float rounding_value = (ptr_float_weights[row * num_columns + col] > 0) ? 0.5f : -0.5f;
float value = ptr_float_weights[row * num_columns + col] * *ptr_weight_scale_factor + rounding_value;
int16_t *ptr_weight_16 = ptr_int_weights + (row * num_columns_padded + col);
if (value > 32767.0) {
*ptr_weight_16 = 32767;
num_saturate++;
} else if (value < -32768.0) {
*ptr_weight_16 = -32768;
num_saturate++;
} else {
*ptr_weight_16 = (int16_t) value;
}
}
for (uint32_t col = num_columns; col < num_columns_padded; col++) {
int16_t *ptr_weight_16 = ptr_int_weights + (row * num_columns_padded + col);
*ptr_weight_16 = 0;
}
}
for (uint32_t row = num_rows; row < num_rows_padded; row++) {
for (uint32_t col = 0; col < num_columns_padded; col++) {
int16_t *ptr_weight_16 = ptr_int_weights + (row * num_columns_padded + col);
*ptr_weight_16 = 0;
}
}
// case for element wise layer
if (ptr_float_biases != nullptr && ptr_int_biases != nullptr) {
for (uint32_t j = 0; j < num_rows; j++) {
float rounding_value = (ptr_float_biases[j] > 0) ? 0.5f : -0.5f;
float value = ptr_float_biases[j] * *ptr_output_scale_factor + rounding_value;
if (value > 2147483647.0) {
ptr_int_biases[j] = 2147483647L;
num_saturate++;
} else if (value < -2147483648.0) {
ptr_int_biases[j] = -2147483648LL;
num_saturate++;
} else {
ptr_int_biases[j] = (int32_t) value;
}
}
for (uint32_t j = num_rows; j < num_rows_padded; j++) {
ptr_int_biases[j] = 0;
}
}
if (num_saturate > 0) {
QUANTWARNING("Warning: %d / %d saturations in QuantizeAffine16()\n",
num_saturate,
num_rows * num_columns + num_rows);
}
}
std::pair<float, float> FindMinMaxValues(void* ptr_float_memory, size_t num_elements) {
float* ptr_float_feat = reinterpret_cast<float*>(ptr_float_memory);
float min = num_elements ? ptr_float_feat[0] : 0.0;
float max = num_elements ? ptr_float_feat[0] : 0.0;
for (size_t i = 1; i < num_elements; i++) {
if (fabs(ptr_float_feat[i]) > max) {
max = fabs(ptr_float_feat[i]);
}
if (fabs(ptr_float_feat[i]) < min) {
min = fabs(ptr_float_feat[i]);
}
}
return { min, max };
}
float ScaleFactorForQuantization(void *ptr_float_memory, float target_max, size_t num_elements) {
float *ptr_float_feat = reinterpret_cast<float *>(ptr_float_memory);
float max = 0.0;
float scale_factor;
for (size_t i = 0; i < num_elements; i++) {
if (fabs(ptr_float_feat[i]) > max) {
max = fabs(ptr_float_feat[i]);
}
}
if (max == 0) {
scale_factor = -1.0f; // need to handle all zeros as a special case
} else {
scale_factor = target_max / max;
}
return (scale_factor);
}
void QuantizeVector16(float *ptr_float_memory, int16_t *ptr_int_memory, uint32_t num_elements, float scale_factor) {
float *ptr_float_feat = reinterpret_cast<float *>(ptr_float_memory);
uint32_t num_saturate = 0;
int16_t *ptr_int_feat = reinterpret_cast<int16_t *>(ptr_int_memory);
for (uint32_t i = 0; i < num_elements; i++) {
float rounding_value = (ptr_float_feat[i] > 0) ? 0.5f : -0.5f;
float value = ptr_float_feat[i] * scale_factor + rounding_value;
if (value > 32767.0) {
ptr_int_feat[i] = 32767;
num_saturate++;
} else if (value < -32768.0) {
ptr_int_feat[i] = -32768;
num_saturate++;
} else {
ptr_int_feat[i] = (int16_t) value;
}
}
if (num_saturate > 0) {
QUANTWARNING("Warning: %d / %d saturations during QuantizeVector16()\n", num_saturate, num_elements);
}
}
template<>
void QuantizationCallback<int8_t, gna_compound_bias_t>::runFakeQuantize() const {
uint32_t num_saturate = 0;
auto input_low = 0.0f;
auto input_high = 0.0f;
auto output_low = 0.0f;
auto output_high = 0.0f;
auto levels = 1;
float valueAcc = 0.0;
for (uint32_t i = 0; i < num_rows; i++) {
uint32_t channel_multiplier = 1;
if (fq_num_stats > 0) {
auto idx = fq_num_stats == 1 ? 0 : i;
input_low = fq_ptr_input_low[idx];
input_high = fq_ptr_input_high[idx];
output_low = fq_ptr_output_low[idx];
output_high = fq_ptr_output_high[idx];
levels = fq_levels;
channel_multiplier = ((input_high - input_low) * *ptr_weight_scale_factor) / (levels - 1);
} else {
float scaled_row_max = 0;
for (uint32_t col = 0; col < num_columns; col++) {
float value = ptr_float_weights[i * num_columns + col] * *ptr_weight_scale_factor;
valueAcc += value;
if (fabs(value) > scaled_row_max) {
scaled_row_max = fabs(value);
}
}
channel_multiplier = scaled_row_max / static_cast<float>(MAX_VAL_1B_WEIGHT);
}
// channel multiplier shouldn't be 0
channel_multiplier = channel_multiplier == 0 ? 1 : channel_multiplier;
ptr_int_biases[i].multiplier = static_cast<uint8_t> (channel_multiplier + 0.5f);
if (channel_multiplier > MAX_OUT_MULTIPLIER) {
THROW_GNA_EXCEPTION << "invalid channel multiplier: " << channel_multiplier;
}
for (uint32_t j = 0; j < num_columns; j++) {
auto offset = i * num_columns + j;
auto rounding_value = (ptr_float_weights[i * num_columns + j] > 0) ? 0.5f : -0.5f;
float value = ptr_float_weights[offset];
if (!quantizedWeights) {
if (fq_num_stats > 0) {
auto x = value;
if (x <= std::min(input_low, input_high)) {
value = output_low;
} else if (x > std::max(input_low, input_high)) {
value = output_high;
} else {
value = nearbyint((x - input_low) / (input_high - input_low) * (levels - 1)) /
(levels - 1) * (output_high - output_low) + output_low;
}
}
value = value * (*ptr_weight_scale_factor / ptr_int_biases[i].multiplier) + rounding_value;
} else {
value -= MAX_VAL_1B_WEIGHT;
}
auto normalizedWeight = static_cast<int32_t>(value);
if (value > std::numeric_limits<int8_t>::max()) {
normalizedWeight = std::numeric_limits<int8_t>::max();
num_saturate++;
} else if (value < std::numeric_limits<int8_t>::min()) {
normalizedWeight = std::numeric_limits<int8_t>::min();
num_saturate++;
} else {
normalizedWeight = (int8_t)value;
}
// range checking
ptr_int_weights[offset] = static_cast<int8_t>(normalizedWeight);
}
for (uint32_t j = num_columns; j < num_columns_padded; j++) {
ptr_int_weights[i * num_columns + j] = 0;
}
}
for (uint32_t i = num_rows; i < num_rows_padded; i++) {
for (uint32_t j = 0; j < num_columns_padded; j++) {
ptr_int_weights[i * num_columns + j] = 0;
}
ptr_int_biases[i].multiplier = 0;
}
if (ptr_float_biases != nullptr) {
for (uint32_t j = 0; j < num_rows; j++) {
float rounding_value = (ptr_float_biases[j] > 0) ? 0.5f : -0.5f;
float value = ptr_float_biases[j] * *ptr_output_scale_factor + rounding_value;
if (value > 2147483647.0) {
ptr_int_biases[j].bias = 2147483647L;
num_saturate++;
} else if (value < -2147483648.0) {
ptr_int_biases[j].bias = -2147483648LL;
num_saturate++;
} else {
ptr_int_biases[j].bias = (int32_t) value;
}
}
}
if (num_saturate > 0) {
QUANTWARNING("Warning: %d / %d saturations in QuantizeAffine8()\n", num_saturate, num_rows * num_columns + num_rows);
}
}
template<>
void QuantizationCallback<int8_t, gna_compound_bias_t>::runQuantize() const {
if (ptr_int_biases == nullptr) {
IE_THROW() << "Int biases are empty";
}
uint32_t num_saturate = 0;
float valueAcc = 0.0;
for (uint32_t row = 0; row < num_rows; row++) {
float scaled_row_max = 0;
float rounding_value, value;
for (uint32_t col = 0; col < num_columns; col++) {
value = ptr_float_weights[row*num_columns + col] * *ptr_weight_scale_factor;
valueAcc += value;
if (fabs(value) > scaled_row_max) {
scaled_row_max = fabs(value);
}
}
value = scaled_row_max / static_cast<float>(MAX_VAL_1B_WEIGHT);
ptr_int_biases[row].multiplier = (uint8_t) (value + 0.5);
for (uint32_t col = 0; col < num_columns; col++) {
int8_t *ptr_weight_8 = ptr_int_weights + (row * num_columns_padded + col);
rounding_value = (ptr_float_weights[row * num_columns + col] > 0) ? 0.5f : -0.5f;
value = ptr_float_weights[row * num_columns + col] * (*ptr_weight_scale_factor / ptr_int_biases[row].multiplier) + rounding_value;
if (value > 127.0) {
*ptr_weight_8 = 127;
num_saturate++;
} else if (value < -128.0) {
*ptr_weight_8 = -128;
num_saturate++;
} else {
*ptr_weight_8 = (int8_t) value;
}
}
for (uint32_t col = num_columns; col < num_columns_padded; col++) {
int8_t *ptr_weight_8 = ptr_int_weights + (row * num_columns_padded + col);
*ptr_weight_8 = 0;
}
}
for (uint32_t row = num_rows; row < num_rows_padded; row++) {
for (uint32_t col = 0; col < num_columns_padded; col++) {
int8_t *ptr_weight_8 = ptr_int_weights + (row*num_columns_padded + col);
*ptr_weight_8 = 0;
}
ptr_int_biases[row].multiplier = 0;
}
// bias value of the bas will be only used when input bias provided
if (ptr_float_biases != nullptr) {
for (uint32_t j = 0; j < num_rows; j++) {
float rounding_value = (ptr_float_biases[j] > 0) ? 0.5f : -0.5f;
float value = ptr_float_biases[j] * *ptr_output_scale_factor + rounding_value;
if (value > 2147483647.0) {
ptr_int_biases[j].bias = 2147483647L;
num_saturate++;
} else if (value < -2147483648.0) {
ptr_int_biases[j].bias = -2147483648LL;
num_saturate++;
} else {
ptr_int_biases[j].bias = (int32_t) value;
}
}
}
if (num_saturate > 0) {
QUANTWARNING("Warning: %d / %d saturations in QuantizeAffine8()\n", num_saturate, num_rows * num_columns + num_rows);
}
}
template<>
void QuantizationCallback<int8_t, int8_t>::runQuantize() const {
uint32_t num_saturate = 0;
for (uint32_t row = 0; row < num_rows; row++) {
for (uint32_t col = 0; col < num_columns; col++) {
float rounding_value = (ptr_float_weights[row * num_columns + col] > 0) ? 0.5f : -0.5f;
float value = ptr_float_weights[row * num_columns + col] * *ptr_weight_scale_factor + rounding_value;
int8_t* ptr_weight_8 = ptr_int_weights + (row * num_columns_padded + col);
if (value > 127.0) {
*ptr_weight_8 = 127;
num_saturate++;
} else if (value < -128.0) {
*ptr_weight_8 = -128;
num_saturate++;
} else {
*ptr_weight_8 = (int8_t)value;
}
}
for (uint32_t col = num_columns; col < num_columns_padded; col++) {
int8_t* ptr_weight_8 = ptr_int_weights + (row * num_columns_padded + col);
*ptr_weight_8 = 0;
}
}
for (uint32_t row = num_rows; row < num_rows_padded; row++) {
for (uint32_t col = 0; col < num_columns_padded; col++) {
int8_t* ptr_weight_8 = ptr_int_weights + (row * num_columns_padded + col);
*ptr_weight_8 = 0;
}
}
if (ptr_float_biases != nullptr && ptr_int_biases != nullptr) {
for (uint32_t j = 0; j < num_rows; j++) {
float rounding_value = (ptr_float_biases[j] > 0) ? 0.5f : -0.5f;
float value = ptr_float_biases[j] * *ptr_output_scale_factor + rounding_value;
if (value > 127.0) {
ptr_int_biases[j] = 127;
num_saturate++;
} else if (value < -128.0) {
ptr_int_biases[j] = -128;
num_saturate++;
} else {
ptr_int_biases[j] = (int8_t)value;
}
}
for (uint32_t j = num_rows; j < num_rows_padded; j++) {
ptr_int_biases[j] = 0;
}
}
if (num_saturate > 0) {
QUANTWARNING("Warning: %d / %d saturations in QuantizeAffine8_8()\n", num_saturate, num_rows * num_columns + num_rows);
}
}
|
//#include <eve/function/is_not_real.hpp>
#include <eve/module/ieee.hpp>
#include <eve/wide.hpp>
#include <iostream>
using wide_ft = eve::wide<float, eve::fixed<4>>;
int main()
{
wide_ft pf = {0.0f, 1.0f, -0.0f, -2.0f};
std::cout << "---- simd" << '\n'
<< "<- pf = " << pf << '\n'
<< "-> is_not_real(pf) = " << eve::is_not_real(pf) << '\n';
float xf = 1.0f;
std::cout << "---- scalar" << '\n'
<< "<- xf = " << xf << '\n'
<< "-> is_not_real(xf) = " << eve::is_not_real(xf) << '\n';
return 0;
}
|
#ifndef HPP_035_PKT_NPC_ForceDead_HPP
#define HPP_035_PKT_NPC_ForceDead_HPP
#include "base.hpp"
#pragma pack(push, 1)
struct PKT_NPC_ForceDead_s : DefaultPacket<PKT_NPC_ForceDead>
{
};
#pragma pack(pop)
#endif
|
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Christian Schulte <schulte@gecode.org>
*
* Contributing authors:
* Samuel Gagnon <samuel.gagnon92@gmail.com>
*
* Copyright:
* Christian Schulte, 2002
* Samuel Gagnon, 2018
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* 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.
*
*/
namespace Gecode { namespace Int {
/*
* Constructors and initialization
*
*/
forceinline
BoolView::BoolView(void) {}
forceinline
BoolView::BoolView(const BoolVar& y)
: VarImpView<BoolVar>(y.varimp()) {}
forceinline
BoolView::BoolView(BoolVarImp* y)
: VarImpView<BoolVar>(y) {}
/*
* Value access
*
*/
forceinline BoolStatus
BoolView::status(void) const {
return x->status();
}
forceinline int
BoolView::min(void) const {
return x->min();
}
forceinline int
BoolView::max(void) const {
return x->max();
}
forceinline int
BoolView::med(void) const {
return x->med();
}
forceinline int
BoolView::val(void) const {
return x->val();
}
#ifdef GECODE_HAS_CBS
forceinline int
BoolView::baseval(int val) const {
return val;
}
#endif
forceinline unsigned int
BoolView::size(void) const {
return x->size();
}
forceinline unsigned int
BoolView::width(void) const {
return x->width();
}
forceinline unsigned int
BoolView::regret_min(void) const {
return x->regret_min();
}
forceinline unsigned int
BoolView::regret_max(void) const {
return x->regret_max();
}
/*
* Domain tests
*
*/
forceinline bool
BoolView::range(void) const {
return x->range();
}
forceinline bool
BoolView::in(int n) const {
return x->in(n);
}
forceinline bool
BoolView::in(long long int n) const {
return x->in(n);
}
/*
* Domain update by value
*
*/
forceinline ModEvent
BoolView::lq(Space& home, int n) {
return x->lq(home,n);
}
forceinline ModEvent
BoolView::lq(Space& home, long long int n) {
return x->lq(home,n);
}
forceinline ModEvent
BoolView::le(Space& home, int n) {
return x->lq(home,n-1);
}
forceinline ModEvent
BoolView::le(Space& home, long long int n) {
return x->lq(home,n-1);
}
forceinline ModEvent
BoolView::gq(Space& home, int n) {
return x->gq(home,n);
}
forceinline ModEvent
BoolView::gq(Space& home, long long int n) {
return x->gq(home,n);
}
forceinline ModEvent
BoolView::gr(Space& home, int n) {
return x->gq(home,n+1);
}
forceinline ModEvent
BoolView::gr(Space& home, long long int n) {
return x->gq(home,n+1);
}
forceinline ModEvent
BoolView::nq(Space& home, int n) {
return x->nq(home,n);
}
forceinline ModEvent
BoolView::nq(Space& home, long long int n) {
return x->nq(home,n);
}
forceinline ModEvent
BoolView::eq(Space& home, int n) {
return x->eq(home,n);
}
forceinline ModEvent
BoolView::eq(Space& home, long long int n) {
return x->eq(home,n);
}
/*
* Iterator-based domain update
*
*/
template<class I>
forceinline ModEvent
BoolView::narrow_r(Space& home, I& i, bool depend) {
return x->narrow_r(home,i,depend);
}
template<class I>
forceinline ModEvent
BoolView::inter_r(Space& home, I& i, bool depend) {
return x->inter_r(home,i,depend);
}
template<class I>
forceinline ModEvent
BoolView::minus_r(Space& home, I& i, bool depend) {
return x->minus_r(home,i,depend);
}
template<class I>
forceinline ModEvent
BoolView::narrow_v(Space& home, I& i, bool depend) {
return x->narrow_v(home,i,depend);
}
template<class I>
forceinline ModEvent
BoolView::inter_v(Space& home, I& i, bool depend) {
return x->inter_v(home,i,depend);
}
template<class I>
forceinline ModEvent
BoolView::minus_v(Space& home, I& i, bool depend) {
return x->minus_v(home,i,depend);
}
/*
* Boolean domain tests
*
*/
forceinline bool
BoolView::zero(void) const {
return x->zero();
}
forceinline bool
BoolView::one(void) const {
return x->one();
}
forceinline bool
BoolView::none(void) const {
return x->none();
}
/*
* Boolean assignment operations
*
*/
forceinline ModEvent
BoolView::zero_none(Space& home) {
return x->zero_none(home);
}
forceinline ModEvent
BoolView::one_none(Space& home) {
return x->one_none(home);
}
forceinline ModEvent
BoolView::zero(Space& home) {
return x->zero(home);
}
forceinline ModEvent
BoolView::one(Space& home) {
return x->one(home);
}
/*
* Delta information for advisors
*
*/
forceinline int
BoolView::min(const Delta& d) const {
return BoolVarImp::min(d);
}
forceinline int
BoolView::max(const Delta& d) const {
return BoolVarImp::max(d);
}
forceinline unsigned int
BoolView::width(const Delta& d) const {
return BoolVarImp::width(d);
}
forceinline bool
BoolView::any(const Delta& d) const {
return BoolVarImp::any(d);
}
forceinline bool
BoolView::zero(const Delta& d) {
return BoolVarImp::zero(d);
}
forceinline bool
BoolView::one(const Delta& d) {
return BoolVarImp::one(d);
}
forceinline ModEventDelta
BoolView::med(ModEvent me) {
return VarImpView<BoolVar>::med(me);
}
/**
* \brief %Range iterator for Boolean variable views
* \ingroup TaskActorIntView
*/
template<>
class ViewRanges<BoolView> : public Iter::Ranges::Singleton {
public:
/// \name Constructors and initialization
//@{
/// Default constructor
ViewRanges(void);
/// Initialize with ranges for view \a x
ViewRanges(const BoolView& x);
/// Initialize with ranges for view \a x
void init(const BoolView& x);
//@}
};
forceinline
ViewRanges<BoolView>::ViewRanges(void) {}
forceinline
ViewRanges<BoolView>::ViewRanges(const BoolView& x)
: Iter::Ranges::Singleton(x.min(),x.max()) {}
forceinline void
ViewRanges<BoolView>::init(const BoolView& x) {
Iter::Ranges::Singleton::init(x.min(),x.max());
}
}}
// STATISTICS: int-var
|
/*
* 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) 2015 by Contributors
* \file fully_connected.cc
* \brief fully connect operator
*/
#include "./fully_connected-inl.h"
#include "./mkldnn/mkldnn_ops-inl.h"
#include "./mkldnn/mkldnn_base-inl.h"
#if MXNET_USE_NNPACK == 1
#include "../nnpack/nnpack_fully_connected-inl.h"
#endif // MXNET_USE_NNPACK
namespace mxnet {
namespace op {
static bool FullyConnectedShape(const nnvm::NodeAttrs& attrs,
std::vector<TShape> *in_shape,
std::vector<TShape> *out_shape) {
const FullyConnectedParam& param = nnvm::get<FullyConnectedParam>(attrs.parsed);
using namespace mshadow;
if (!param.no_bias) {
CHECK_EQ(in_shape->size(), 3U) << "Input:[data, weight, bias]";
} else {
CHECK_EQ(in_shape->size(), 2U) << "Input:[data, weight]";
}
CHECK_EQ(out_shape->size(), 1U);
TShape dshape = (*in_shape)[fullc::kData];
TShape oshape = (*out_shape)[0];
// require data to be known
if (dshape.ndim() == 0) return false;
index_t num_input;
if (!param.flatten) {
num_input = dshape[dshape.ndim()-1];
} else {
num_input = dshape.ProdShape(1, dshape.ndim());
}
SHAPE_ASSIGN_CHECK(*in_shape, fullc::kWeight, Shape2(param.num_hidden, num_input));
if (!param.no_bias) {
if (!shape_assign(&(*in_shape)[fullc::kBias], Shape1(param.num_hidden)) &&
!shape_assign(&(*in_shape)[fullc::kBias], Shape2(param.num_hidden, 1))) {
LOG(FATAL) << "Unexpected shape for bias " << (*in_shape)[fullc::kBias];
}
}
if (!param.flatten) {
TShape result_shape(dshape);
result_shape[dshape.ndim()-1] = param.num_hidden;
SHAPE_ASSIGN_CHECK(*out_shape, 0, result_shape);
} else {
SHAPE_ASSIGN_CHECK(*out_shape, 0, Shape2(dshape[0], param.num_hidden));
}
if (oshape.ndim() != 0) {
dshape[0] = oshape[0];
SHAPE_ASSIGN_CHECK(*in_shape, fullc::kData, dshape);
}
return true;
}
void FullyConnectedComputeExCPU(const nnvm::NodeAttrs& attrs,
const OpContext &ctx,
const std::vector<NDArray> &inputs,
const std::vector<OpReqType> &req,
const std::vector<NDArray> &outputs) {
const FullyConnectedParam& param = nnvm::get<FullyConnectedParam>(attrs.parsed);
const bool valid_data = inputs[0].storage_type() == kDefaultStorage;
const bool valid_weight = inputs[1].storage_type() == kDefaultStorage ||
inputs[1].storage_type() == kRowSparseStorage;
const bool valid_out = outputs[0].storage_type() == kDefaultStorage;
bool valid_bias = true;
if (!param.no_bias) {
valid_bias = inputs[2].storage_type() == kDefaultStorage ||
inputs[2].storage_type() == kRowSparseStorage;
}
#if MXNET_USE_MKLDNN == 1
if (common::ContainsOnlyStorage(inputs, kDefaultStorage) &&
common::ContainsOnlyStorage(outputs, kDefaultStorage)) {
if (SupportMKLDNN(inputs[0])) {
MKLDNN_OPCHECK_INIT(false, outputs.size(), inputs, outputs);
MKLDNNFCForward(attrs, ctx, inputs, req, outputs);
MKLDNN_OPCHECK_RUN(FullyConnectedCompute<cpu>, attrs, ctx, inputs, req,
outputs);
} else {
FallBackCompute(FullyConnectedCompute<cpu>, attrs, ctx, inputs, req, outputs);
}
return;
} else if (valid_data && valid_weight && valid_bias && valid_out) {
// inputs
std::vector<NDArray> temp_ndarrays;
std::vector<TBlob> in_blobs;
for (const NDArray& in : inputs) {
// if ndarray is in default storage and MKLDNN is available,
// need to make sure cpu layout data is used, instead of MKL layout
if (in.storage_type() == kDefaultStorage) {
temp_ndarrays.push_back(in.Reorder2Default());
in_blobs.emplace_back(temp_ndarrays.back().data());
} else {
in_blobs.emplace_back(in.data());
}
}
// output
FullyConnectedCompute<cpu>(attrs, ctx, in_blobs, req, {outputs[0].data()});
} else {
LogUnimplementedOp(attrs, ctx, inputs, req, outputs);
}
#else
if (valid_data && valid_weight && valid_bias && valid_out) {
std::vector<TBlob> in_blobs(inputs.size());
for (size_t i = 0; i < in_blobs.size(); i++) in_blobs[i] = inputs[i].data();
std::vector<TBlob> out_blobs(outputs.size());
for (size_t i = 0; i < out_blobs.size(); i++) out_blobs[i] = outputs[i].data();
FullyConnectedCompute<cpu>(attrs, ctx, in_blobs, req, out_blobs);
} else {
LogUnimplementedOp(attrs, ctx, inputs, req, outputs);
}
#endif
}
#if MXNET_USE_MKLDNN == 1
void FullyConnectedGradComputeExCPU(const nnvm::NodeAttrs& attrs,
const OpContext &ctx,
const std::vector<NDArray> &inputs,
const std::vector<OpReqType> &req,
const std::vector<NDArray> &outputs) {
if (SupportMKLDNN(inputs[0])) {
MKLDNN_OPCHECK_INIT(true, outputs.size(), inputs, outputs);
MKLDNNFCBackward(attrs, ctx, inputs, req, outputs);
MKLDNN_OPCHECK_RUN(FullyConnectedGradCompute<cpu>, attrs, ctx, inputs, req,
outputs);
return;
}
FallBackCompute(FullyConnectedGradCompute<cpu>, attrs, ctx, inputs, req, outputs);
}
#endif
static bool FullyConnectedType(const nnvm::NodeAttrs& attrs,
std::vector<int> *in_type, std::vector<int> *out_type) {
CHECK_GE(in_type->size(), 1U);
return ElemwiseAttr<int, type_is_none, type_assign, true, type_string>(
attrs, in_type, out_type, -1);
}
struct FullyConnectedGrad {
const char *op_name;
std::vector<nnvm::NodeEntry> operator()(const nnvm::NodePtr& n,
const std::vector<nnvm::NodeEntry>& ograds) const {
std::vector<nnvm::NodeEntry> heads(ograds.begin(), ograds.end());
heads.push_back(n->inputs[fullc::kData]);
heads.push_back(n->inputs[fullc::kWeight]);
return MakeGradNode(op_name, n, heads, n->attrs.dict);
}
};
inline static bool FCStorageType(const nnvm::NodeAttrs& attrs,
const int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
const FullyConnectedParam& param = nnvm::get<FullyConnectedParam>(attrs.parsed);
const bool valid_data = in_attrs->at(0) == kDefaultStorage;
const bool valid_weight = in_attrs->at(1) == kDefaultStorage ||
in_attrs->at(1) == kRowSparseStorage;
bool valid_bias = true;
uint32_t in_expected = 2;
if (!param.no_bias) {
in_expected = 3;
valid_bias = in_attrs->at(2) == kDefaultStorage || in_attrs->at(2) == kRowSparseStorage;
}
CHECK_EQ(in_attrs->size(), in_expected);
CHECK_EQ(out_attrs->size(), 1);
// dispatch to kFComputeEx is fine even if all inputs are dense and no MKL is present
bool dispatched = false;
if (!dispatched && valid_data && valid_weight && valid_bias) {
dispatched = storage_type_assign(out_attrs, mxnet::kDefaultStorage,
dispatch_mode, DispatchMode::kFComputeEx);
}
if (!dispatched) {
dispatched = dispatch_fallback(out_attrs, dispatch_mode);
}
return dispatched;
}
inline static bool BackwardFCStorageType(const nnvm::NodeAttrs& attrs,
const int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
const FullyConnectedParam& param = nnvm::get<FullyConnectedParam>(attrs.parsed);
uint32_t out_expected = param.no_bias ? 2 : 3;
CHECK_EQ(in_attrs->size(), 3U);
CHECK_EQ(out_attrs->size(), out_expected);
bool dispatched = false;
// TODO(zhengda) let's disable MKLDNN for FullyConnected for now.
// It seems there is a bug.
if (!dispatched && common::ContainsOnlyStorage(*in_attrs, mxnet::kDefaultStorage)) {
dispatched = storage_type_assign(out_attrs, mxnet::kDefaultStorage,
dispatch_mode, DispatchMode::kFCompute);
}
if (!dispatched && common::ContainsStorageType(*in_attrs, mxnet::kRowSparseStorage)) {
dispatched = dispatch_fallback(out_attrs, dispatch_mode);
}
if (!dispatched) {
dispatched = storage_type_assign(out_attrs, mxnet::kDefaultStorage,
dispatch_mode, DispatchMode::kFCompute);
}
return dispatched;
}
DMLC_REGISTER_PARAMETER(FullyConnectedParam);
NNVM_REGISTER_OP(FullyConnected)
MXNET_ADD_SPARSE_OP_ALIAS(FullyConnected)
.describe(R"code(Applies a linear transformation: :math:`Y = XW^T + b`.
If ``flatten`` is set to be true, then the shapes are:
- **data**: `(batch_size, x1, x2, ..., xn)`
- **weight**: `(num_hidden, x1 * x2 * ... * xn)`
- **bias**: `(num_hidden,)`
- **out**: `(batch_size, num_hidden)`
If ``flatten`` is set to be false, then the shapes are:
- **data**: `(x1, x2, ..., xn, input_dim)`
- **weight**: `(num_hidden, input_dim)`
- **bias**: `(num_hidden,)`
- **out**: `(x1, x2, ..., xn, num_hidden)`
The learnable parameters include both ``weight`` and ``bias``.
If ``no_bias`` is set to be true, then the ``bias`` term is ignored.
.. Note::
The sparse support for FullyConnected is limited to forward evaluation with `row_sparse`
weight and bias, where the length of `weight.indices` and `bias.indices` must be equal
to `num_hidden`. This could be useful for model inference with `row_sparse` weights
trained with importance sampling or noise contrastive estimation.
To compute linear transformation with 'csr' sparse data, sparse.dot is recommended instead
of sparse.FullyConnected.
)code" ADD_FILELINE)
.set_num_inputs([](const NodeAttrs& attrs) {
const FullyConnectedParam& params = nnvm::get<FullyConnectedParam>(attrs.parsed);
return params.no_bias ? 2 : 3;
})
.set_num_outputs(1)
.set_attr_parser(ParamParser<FullyConnectedParam>)
.set_attr<FInferStorageType>("FInferStorageType", FCStorageType)
.set_attr<nnvm::FListInputNames>("FListInputNames", [](const NodeAttrs& attrs) {
const FullyConnectedParam& params = nnvm::get<FullyConnectedParam>(attrs.parsed);
if (!params.no_bias) {
return std::vector<std::string>{"data", "weight", "bias"};
} else {
return std::vector<std::string>{"data", "weight"};
}
})
.set_attr<nnvm::FListOutputNames>("FListOutputNames",
[](const NodeAttrs& attrs) {
return std::vector<std::string>{"output"};
})
#if MXNET_USE_MKLDNN == 1
.set_attr<FResourceRequest>("FResourceRequest", [](const NodeAttrs& n) {
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
})
#endif
.set_attr<nnvm::FInferShape>("FInferShape", FullyConnectedShape)
.set_attr<nnvm::FInferType>("FInferType", FullyConnectedType)
.set_attr<FCompute>("FCompute<cpu>", FullyConnectedCompute<cpu>)
.set_attr<FComputeEx>("FComputeEx<cpu>", FullyConnectedComputeExCPU)
.set_attr<nnvm::FGradient>("FGradient", FullyConnectedGrad{"_backward_FullyConnected"})
.add_argument("data", "NDArray-or-Symbol", "Input data.")
.add_argument("weight", "NDArray-or-Symbol", "Weight matrix.")
.add_argument("bias", "NDArray-or-Symbol", "Bias parameter.")
.add_arguments(FullyConnectedParam::__FIELDS__());
NNVM_REGISTER_OP(_backward_FullyConnected)
.set_num_inputs(3)
.set_num_outputs([](const NodeAttrs& attrs) {
const FullyConnectedParam& params = nnvm::get<FullyConnectedParam>(attrs.parsed);
return params.no_bias ? 2 : 3;
})
#if MXNET_USE_MKLDNN == 1
.set_attr<FResourceRequest>("FResourceRequest", [](const NodeAttrs& n) {
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
})
#endif
.set_attr<nnvm::TIsBackward>("TIsBackward", true)
.set_attr<nnvm::FInplaceOption>("FInplaceOption", [](const NodeAttrs& attrs){
return std::vector<std::pair<int, int> >{{1, 0}};
})
.set_attr<FInferStorageType>("FInferStorageType", BackwardFCStorageType)
.set_attr_parser(ParamParser<FullyConnectedParam>)
#if MXNET_USE_MKLDNN == 1
.set_attr<FComputeEx>("FComputeEx<cpu>", FullyConnectedGradComputeExCPU)
#endif
.set_attr<FCompute>("FCompute<cpu>", FullyConnectedGradCompute<cpu>);
} // namespace op
} // namespace mxnet
|
#include <nano/lib/asio.hpp>
nano::shared_const_buffer::shared_const_buffer (const std::vector<uint8_t> & data) :
m_data (std::make_shared<std::vector<uint8_t>> (data)),
m_buffer (boost::asio::buffer (*m_data))
{
}
nano::shared_const_buffer::shared_const_buffer (std::vector<uint8_t> && data) :
m_data (std::make_shared<std::vector<uint8_t>> (std::move (data))),
m_buffer (boost::asio::buffer (*m_data))
{
}
nano::shared_const_buffer::shared_const_buffer (uint8_t data) :
shared_const_buffer (std::vector<uint8_t>{ data })
{
}
nano::shared_const_buffer::shared_const_buffer (std::string const & data) :
m_data (std::make_shared<std::vector<uint8_t>> (data.begin (), data.end ())),
m_buffer (boost::asio::buffer (*m_data))
{
}
nano::shared_const_buffer::shared_const_buffer (std::shared_ptr<std::vector<uint8_t>> const & data) :
m_data (data),
m_buffer (boost::asio::buffer (*m_data))
{
}
const boost::asio::const_buffer * nano::shared_const_buffer::begin () const
{
return &m_buffer;
}
const boost::asio::const_buffer * nano::shared_const_buffer::end () const
{
return &m_buffer + 1;
}
size_t nano::shared_const_buffer::size () const
{
return m_buffer.size ();
}
|
/*
* Copyright (c) 2017-2018 Shehryar Khurshid <shryr.kd@gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 "unicycle.h"
#include <math.h>
#include <ekf.h>
#include <ukf.h>
#include <cdkf.h>
#include <sqrt_ukf.h>
#include <sqrt_cdkf.h>
using namespace spkf;
using std::cout;
int main() {
/* time step and no of itertions */
const double del_k = 0.01; /* time step: d_k = 10ms */
const int iter_n = 10000; /* no. of iterations */
/* state vector: x_k = [x_k, y_k, theta_k, v_k, w_k]^T */
StateT<double> state;
state[0] = 0.0; /* x_k = 0.0 meters */
state[1] = -10.0; /* y_k = -10.0 meters */
state[2] = 0.0; /* theta_k = 0.0 rads */
state[3] = spkf::pi<double>(); /* v_k = pi meters/second^2 */
state[4] = spkf::pi<double>()/10; /* w_k = pi/10 rads/second^2 */
/* constants */
const auto covar = 20.0 * CovarT<double>::Identity(); /* state covariance: Px = 20.0*I */
const auto proc_covar = 5.0 * CovarT<double>::Identity(); /* process noise covariance: Q = 5.0*I */
const auto obs_covar = 3.0 * ObsCovarT<double>::Identity(); /* observation noise covariance: R = 3.0*I */
/* variables */
StateT<double> gt_state = state; /* ground truth state */
StateT<double> proc_noise = StateT<double>::Zero(); /* process noise mean = [0]^T */
ObsT<double> obs_noise = ObsT<double>::Zero(); /* observation noise mean = [0]^T */
ObsT<double> gt_obs; /* ground truth observation */
ObsT<double> prt_obs; /* perturbed measurement */
ControlT<double> control; /* control vector u_k = [a_k, w_t]^T */
/* models */
process_t<double> f; /* process model f() */
observe_t<double> h; /* observation model */
/* normal distribution */
std::random_device rd;
std::mt19937 twister(rd());
std::normal_distribution<double> proc_dist(0.0, 1.0); /* process normal rand u=0.0, s=1.0 */
std::normal_distribution<double> obs_dist(0.0, 0.8); /* observation normal rand u=0.0, s=0.8 */
std::normal_distribution<double> control_dist(0.0, 2.0); /* control normal rand u=0.0, s=2.0 */
std::normal_distribution<double> prt_dist(0.0, 0.8); /* control normal rand u=0.0, s=0.8 */
/* initialize filters */
/* EKF: extended Kalman filter */
EKF<process_t<double>, observe_t<double>>
ekf(state, covar, proc_covar, obs_covar);
/* UKF: unscented Kalman filter */
UKF<process_t<double>, observe_t<double>>
ukf(state, covar, proc_covar, obs_covar);
/* CDKF: central difference Kalman filter */
CDKF<process_t<double>, observe_t<double>>
cdkf(state, covar, proc_covar, obs_covar);
/* SqrtUKF: square-root, unscented Kalman filter */
SqrtUKF<process_t<double>, observe_t<double>>
sqrt_ukf(state, covar, proc_covar, obs_covar);
/* SqrtCDKF: square-root, central difference Kalman filter */
SqrtCDKF<process_t<double>, observe_t<double>>
sqrt_cdkf(state, covar, proc_covar, obs_covar);
/* iterate for iter_n time steps */
for (auto i = 0; i < iter_n; ++i) {
/* generate control commands */
control[0] = control_dist(twister); /* a_k m/s^2 */
control[1] = control_dist(twister); /* w_k rads/s^2 */
/* generate process noise */
for (auto j = 0; j < proc_noise.rows(); ++j) {
proc_noise[j] = proc_dist(twister);
}
/* generate observation noise */
for (auto j = 0; j < obs_noise.rows(); ++j) {
obs_noise[j] = obs_dist(twister);
}
/* prediction step */
ekf.predict(control, del_k, proc_noise);
ukf.predict(control, del_k, proc_noise);
cdkf.predict(control, del_k, proc_noise);
sqrt_ukf.predict(control, del_k, proc_noise);
sqrt_cdkf.predict(control, del_k, proc_noise);
/* get ground truth state */
f(gt_state, control, proc_noise, del_k);
/* propagate it through h() to get ground truth observation */
h(gt_state, gt_obs, obs_noise);
/* perturb ground truth measurement */
for(auto j = 0; j < prt_obs.rows(); ++j) {
prt_obs[j] = gt_obs[j] + prt_dist(twister);
}
/* innovation step with perturbed observation */
ekf.innovate(prt_obs, obs_noise);
ukf.innovate(prt_obs, obs_noise);
cdkf.innovate(prt_obs, obs_noise);
sqrt_ukf.innovate(prt_obs, obs_noise);
sqrt_cdkf.innovate(prt_obs, obs_noise);
/* update step */
ekf.update();
ukf.update();
cdkf.update();
sqrt_ukf.update();
sqrt_cdkf.update();
}
/* errors */
const auto& ekf_error = (ekf.state() - gt_state).norm();
const auto& ukf_error = (ukf.state() - gt_state).norm();
const auto& cdkf_error = (cdkf.state() - gt_state).norm();
const auto& sqrt_ukf_error = (sqrt_ukf.state() - gt_state).norm();
const auto& sqrt_cdkf_error = (sqrt_cdkf.state() - gt_state).norm();
/* print state estimates */
cout << "------------- state estimates --------------" << "\n\n";
cout << "G.T. state: " << "\n" << gt_state << "\n\n";
cout << "EKF state: " << "\n" << ekf.state() << "\n\n";
cout << "UKF state: " << "\n" << ukf.state() << "\n\n";
cout << "CDKF state: " << "\n" << cdkf.state() << "\n\n";
cout << "SR-UKF state: " << "\n" << sqrt_ukf.state() << "\n\n";
cout << "SR-CDKF state: " << "\n" << sqrt_cdkf.state() << "\n\n";
/* print covariances */
cout << "---------- covariance estimates ------------" << "\n\n";
cout << "EKF covar: " << "\n" << ekf.covar() << "\n\n";
cout << "UKF covar: " << "\n" << ukf.covar() << "\n\n";
cout << "CDKF covar: " << "\n" << cdkf.covar() << "\n\n";
cout << "SR-UKF covar: " << "\n" << sqrt_ukf.covar() << "\n\n";
cout << "SR-CDKF covar: " << "\n" << sqrt_cdkf.covar() << "\n\n";
/* print state errors */
cout << "--------------- state errors ---------------" << "\n\n";
cout << "EKF error: " << "\n" << ekf_error << "\n\n";
cout << "UKF state: " << "\n" << ukf_error << "\n\n";
cout << "CDKF state: " << "\n" << cdkf_error << "\n\n";
cout << "SR-UKF state: " << "\n" << sqrt_ukf_error << "\n\n";
cout << "SR-CDKF state: " << "\n" << sqrt_cdkf_error << "\n\n";
/* fin */
return 0;
}
|
/*
* Copyright (c) 2015 - 2021, Intel Corporation
*
* 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "MSRFieldControl.hpp"
#include "MSRIO.hpp"
#include "MSR.hpp"
#include "Exception.hpp"
#include "geopm_debug.hpp"
namespace geopm
{
MSRFieldControl::MSRFieldControl(std::shared_ptr<MSRIO> msrio,
int cpu,
uint64_t offset,
int begin_bit,
int end_bit,
int function,
double scalar)
: m_msrio(msrio)
, m_cpu(cpu)
, m_offset(offset)
, m_shift(begin_bit)
, m_num_bit(end_bit - begin_bit + 1)
, m_mask(((1ULL << m_num_bit) - 1) << begin_bit)
, m_function(function)
, m_inverse(1.0 / scalar)
, m_is_batch_ready(false)
, m_adjust_idx(-1)
, m_saved_msr_value(0)
{
if (m_msrio == nullptr) {
throw Exception("MSRFieldControl: cannot construct with null MSRIO",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
if (m_function < 0 || m_function >= MSR::M_FUNCTION_OVERFLOW) {
throw Exception("MSRFieldControl: unsupported encode function.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
if (begin_bit > end_bit) {
throw Exception("MSRFieldControl: begin bit must be <= end bit",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
}
void MSRFieldControl::setup_batch(void)
{
GEOPM_DEBUG_ASSERT(m_msrio != nullptr, "null MSRIO");
if (!m_is_batch_ready) {
m_adjust_idx = m_msrio->add_write(m_cpu, m_offset);
m_is_batch_ready = true;
}
}
uint64_t MSRFieldControl::encode(double value) const
{
uint64_t result = 0;
double value_inferred = 0.0;
uint64_t float_y, float_z;
switch (m_function) {
case MSR::M_FUNCTION_SCALE:
result = (uint64_t)(m_inverse * value);
break;
case MSR::M_FUNCTION_LOG_HALF:
// F = S * 2.0 ^ -X =>
// X = log2(S / F)
result = (uint64_t)(-1.0 * std::log2(m_inverse * value));
break;
case MSR::M_FUNCTION_7_BIT_FLOAT:
// F = S * 2 ^ Y * (1.0 + Z / 4.0)
// Y in bits [0:5) and Z in bits [5:7)
if (value > 0) {
value *= m_inverse;
float_y = (uint64_t)std::log2(value);
float_z = (uint64_t)(4.0 * (value / (1 << float_y) - 1.0));
if ((float_y && (float_y >> 5) != 0) ||
(float_z && (float_z >> 2) != 0)) {
throw Exception("MSR::encode(): integer overflow in M_FUNCTION_7_BIT_FLOAT datatype encoding",
EOVERFLOW, __FILE__, __LINE__);
}
value_inferred = (1 << float_y) * (1.0 + (float_z / 4.0));
if ((value - value_inferred) > (value * 0.25)) {
throw Exception("MSR::encode(): inferred value from encoded value is inaccurate",
GEOPM_ERROR_LOGIC, __FILE__, __LINE__);
}
result = float_y | (float_z << 5);
}
else {
throw Exception("MSRFieldControl::encode(): input value <= 0 for M_FUNCTION_7_BIT_FLOAT",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
break;
default:
GEOPM_DEBUG_ASSERT(false, "unsupported encode function");
break;
}
result = (result << m_shift) & m_mask;
return result;
}
void MSRFieldControl::adjust(double value)
{
GEOPM_DEBUG_ASSERT(m_msrio != nullptr, "null MSRIO");
if (!m_is_batch_ready) {
throw Exception("MSRFieldControl::adjust(): cannot call adjust() before setup_batch()",
GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
m_msrio->adjust(m_adjust_idx, encode(value), m_mask);
}
void MSRFieldControl::write(double value)
{
GEOPM_DEBUG_ASSERT(m_msrio != nullptr, "null MSRIO");
m_msrio->write_msr(m_cpu, m_offset, encode(value), m_mask);
}
void MSRFieldControl::save(void)
{
m_saved_msr_value = m_msrio->read_msr(m_cpu, m_offset);
m_saved_msr_value &= m_mask;
}
void MSRFieldControl::restore(void)
{
m_msrio->write_msr(m_cpu, m_offset, m_saved_msr_value, m_mask);
}
}
|
#include "quitest.h"
QuiTest::QuiTest(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
}
|
/******************************************************************************
* $Id$
*
* Project: OpenGIS Simple Features Reference Implementation
* Purpose: Implements OGRMySQLDriver class.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 2004, Frank Warmerdam <warmerdam@pobox.com>
*
* 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 "ogr_mysql.h"
#include "cpl_conv.h"
#include "cpl_multiproc.h"
CPL_CVSID("$Id$");
static void* hMutex = NULL;
static int bInitialized = FALSE;
/************************************************************************/
/* OGRMySQLDriverUnload() */
/************************************************************************/
static void OGRMySQLDriverUnload( CPL_UNUSED GDALDriver* poDriver )
{
if( bInitialized )
{
mysql_library_end();
bInitialized = FALSE;
}
if( hMutex != NULL )
{
CPLDestroyMutex(hMutex);
hMutex = NULL;
}
}
/************************************************************************/
/* Open() */
/************************************************************************/
static GDALDataset *OGRMySQLDriverOpen( GDALOpenInfo* poOpenInfo )
{
OGRMySQLDataSource *poDS;
if( !EQUALN(poOpenInfo->pszFilename,"MYSQL:",6) )
return NULL;
{
CPLMutexHolderD(&hMutex);
if( !bInitialized )
{
if ( mysql_library_init( 0, NULL, NULL ) )
{
CPLError( CE_Failure, CPLE_AppDefined, "Could not initialize MySQL library" );
return NULL;
}
bInitialized = TRUE;
}
}
poDS = new OGRMySQLDataSource();
if( !poDS->Open( poOpenInfo->pszFilename, poOpenInfo->eAccess == GA_Update ) )
{
delete poDS;
return NULL;
}
else
return poDS;
}
/************************************************************************/
/* Create() */
/************************************************************************/
static GDALDataset *OGRMySQLDriverCreate( const char * pszName,
CPL_UNUSED int nBands,
CPL_UNUSED int nXSize,
CPL_UNUSED int nYSize,
CPL_UNUSED GDALDataType eDT,
CPL_UNUSED char **papszOptions )
{
OGRMySQLDataSource *poDS;
poDS = new OGRMySQLDataSource();
if( !poDS->Open( pszName, TRUE ) )
{
delete poDS;
CPLError( CE_Failure, CPLE_AppDefined,
"MySQL driver doesn't currently support database creation.\n"
"Please create database before using." );
return NULL;
}
return poDS;
}
/************************************************************************/
/* RegisterOGRMySQL() */
/************************************************************************/
void RegisterOGRMySQL()
{
if (! GDAL_CHECK_VERSION("MySQL driver"))
return;
GDALDriver *poDriver;
if( GDALGetDriverByName( "MySQL" ) == NULL )
{
poDriver = new GDALDriver();
poDriver->SetDescription( "MySQL" );
poDriver->SetMetadataItem( GDAL_DCAP_VECTOR, "YES" );
poDriver->SetMetadataItem( GDAL_DMD_LONGNAME,
"MySQL" );
poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC,
"drv_mysqls.html" );
poDriver->pfnOpen = OGRMySQLDriverOpen;
poDriver->pfnCreate = OGRMySQLDriverCreate;
poDriver->pfnUnloadDriver = OGRMySQLDriverUnload;
GetGDALDriverManager()->RegisterDriver( poDriver );
}
}
|
#include "PCFG.h"
#include "debug.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(int argc, char* argv[]) {
DebugStream::threashold_ = DebugStream::I;
srand((unsigned)time(0));
cerr << "reading cnf grammar..." << endl;
PCFG aPCFG;
cin >> aPCFG;
cout << aPCFG.generateSamples(10);
}
|
#include "RandDoter.hpp"
#include "digit_numbers.h"
#include "DXUT.h"
#include "Geometry/vertex.h"
//#define __DEBUG__ 1
using namespace EyeStereo;
RandomDot::RandomDot(int maxbound):pd3dDevice(0), iVertexNum(-1), dotDist(0.005), maxPointNum(maxbound) {}
RandomDot::~RandomDot() {
SAFE_DELETE( vertices[0] );
SAFE_DELETE( vertices[1] );
SAFE_DELETE( pointStat );
SAFE_DELETE( velocity );
SAFE_DELETE( binGeometry );
SAFE_RELEASE( vBuffer[0] );
SAFE_RELEASE( vBuffer[1] );
SAFE_RELEASE( pd3dDevice );
}
bool RandomDot::inGeometry(Vertex &p, Geometry *g) {
return inGeometry(p.pos.x, p.pos.y, 0, g);
}
bool RandomDot::inGeometry(float x, float y, float z, Geometry *g) {
/*
Vector3 P(x, y, z);
//printf("check\n");
for (int i = 0; i < g->cnt; i++) {
Vector3 A(g->point[i*3].x, g->point[i*3].y, g->point[i*3].z);
Vector3 B(g->point[i*3+1].x, g->point[i*3+1].y, g->point[i*3+2].z);
Vector3 C(g->point[i*3+2].x, g->point[i*3+2].y, g->point[i*3+2].z);
Vector3 v0 = C - A ;
Vector3 v1 = B - A ;
Vector3 v2 = P - A ;
float dot00 = v0.Dot(v0) ;
float dot01 = v0.Dot(v1) ;
float dot02 = v0.Dot(v2) ;
float dot11 = v1.Dot(v1) ;
float dot12 = v1.Dot(v2) ;
float inverDeno = 1 / (dot00 * dot11 - dot01 * dot01) ;
float u = (dot11 * dot02 - dot01 * dot12) * inverDeno ;
if (u < 0 || u > 1) // if u out of range, return directly
{
continue ;
}
float v = (dot00 * dot12 - dot01 * dot02) * inverDeno ;
if (v < 0 || v > 1) // if v out of range, return directly
{
continue;
}
if ( u + v <= 1 ) {
return true;
}
}
return false;
*/
return false;
}
// do create Dot then shift these.
void RandomDot::makeRandomDot(Vertex** vertices, float x, float y) {
srand(1);
for (int i = 0; i < maxPointNum; ++i) {
vertices[0][i] = Vertex(RandF(0, x), RandF(0, y), 0, WHITE);
vertices[1][i] = vertices[0][i];
vertices[1][i].color = WHITE;
binGeometry[i] = false;
}
}
void RandomDot::makeRandomDotTest(Vertex** vertices, float x, float y) {
srand(1);
for (int i = 0; i < maxPointNum; ++i) {
vertices[0][i] = Vertex(RandF(0, x), RandF(0, y), 0, WHITE);
while (!inGeometry(vertices[0][i], pGeo)) {
vertices[0][i] = Vertex(RandF(0, x), RandF(0, y), 0, WHITE);
}
vertices[1][i] = vertices[0][i];
vertices[1][i].color = WHITE;
}
}
void RandomDot::dotShiftNumber(Vertex** vertices)
{
for (UINT i = 0; i < maxPointNum; ++i) {
if (pGeo->distanceShiftDot(vertices[1][i].pos.x, vertices[1][i].pos.y) > Elapse) {
#ifdef __DEBUG__
vertices[1][i].color = YELLOW;
#else
vertices[1][i].pos.x += dotDist;
#endif
}
}
}
bool RandomDot::init(ID3D10Device *pDevice, float x, float y, const int cnt, Geometry* gout) {
//UnknownType vbd;
pd3dDevice = pDevice;
pd3dDevice->AddRef();
//Vertex* vertices[2];
vertices[0] = new Vertex[maxPointNum];
vertices[1] = new Vertex[maxPointNum];
binGeometry = new bool[maxPointNum];
velocity = new Vector3f[maxPointNum];
ZeroMemory(velocity, sizeof(Vector3f)*maxPointNum);
velocityL = new Vector3f(0, 0, 0);
iVertexNum = cnt;
pGeo = gout;
vBuffer[0] = vBuffer[1] = NULL;
boundX = x, boundY = y;
makeRandomDot(vertices, x, y);
dotShiftNumber(vertices);
updateBuffer();
pointStat = new Vector3f[maxPointNum];
ZeroMemory(pointStat, sizeof(Vector3f)*maxPointNum);
return true;
}
bool RandomDot::outBound(Vector3f p, Vector3f &v, int flg) {
if (p.x > boundX && v.x > 0) {
v.x = -v.x;
return true;
}
if (p.x < 0 && v.x < 0) {
v.x = -v.x;
return true;
}
if (p.y <0 && v.y < 0) {
v.y = -v.y;
return true;
}
if (p.y > boundY && v.y > 0) {
v.y = -v.y;
return true;
}
return false;
}
bool RandomDot::updateVertex(float ftime) {
for (int i = 0; i < maxPointNum; ++i) {
Vector3f b = Vector3f(RandF(-1,1), RandF(-1,1), 0);
velocity[i] += b*ftime;
/// Data changed in the procedure
if (outBound(vertices[1][i].pos, velocity[i], 0)) {
//velocity[i] = -velocity[i];
}
vertices[0][i].pos += velocity[i]*(ftime/2);
vertices[1][i].pos = vertices[0][i].pos;
vertices[1][i].color = WHITE;
}
dotShiftNumber(vertices);
updateBuffer();
return true;
}
bool RandomDot::updateBuffer() {
if (vBuffer[0] != NULL) {
vBuffer[0]->Release();
vBuffer[1]->Release();
}
HRESULT hr;
D3D10_BUFFER_DESC bd;
bd.Usage = D3D10_USAGE_DEFAULT;
bd.ByteWidth = sizeof( Vertex ) * iVertexNum;
bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
bd.MiscFlags = 0;
D3D10_SUBRESOURCE_DATA InitData;
InitData.pSysMem = vertices[0];
hr = pd3dDevice->CreateBuffer( &bd, &InitData, &vBuffer[0] );
if( FAILED( hr ) )
return hr;
InitData.pSysMem = vertices[1];
hr = pd3dDevice->CreateBuffer( &bd, &InitData, &vBuffer[1] );
return hr;
}
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/Types/generated/ent/IComponent.hpp>
namespace RED4ext
{
namespace game {
struct TargetingActivatorComponent : ent::IComponent
{
static constexpr const char* NAME = "gameTargetingActivatorComponent";
static constexpr const char* ALIAS = NAME;
};
RED4EXT_ASSERT_SIZE(TargetingActivatorComponent, 0x90);
} // namespace game
} // namespace RED4ext
|
#ifndef EHDG_SWE_DATA_HPP
#define EHDG_SWE_DATA_HPP
#include "ehdg_swe_data_state.hpp"
#include "ehdg_swe_data_internal.hpp"
#include "ehdg_swe_data_boundary.hpp"
#include "ehdg_swe_data_source.hpp"
#include "ehdg_swe_data_wet_dry.hpp"
#include "ehdg_swe_data_slope_limit.hpp"
namespace SWE {
namespace EHDG {
struct Data {
AlignedVector<State> state;
Internal internal;
AlignedVector<Boundary> boundary;
Source source;
WetDry wet_dry_state;
SlopeLimit slope_limit_state;
void initialize() {
this->state.emplace_back(this->ndof);
this->internal = Internal(this->ngp_internal);
for (uint bound_id = 0; bound_id < this->nbound; ++bound_id) {
this->boundary.push_back(Boundary(this->ngp_boundary[bound_id]));
}
this->source = Source(this->nnode);
this->wet_dry_state = WetDry(this->nvrtx);
this->slope_limit_state = SlopeLimit(this->nvrtx, this->nbound);
}
void resize(const uint nstate) {
if (this->state.size() < nstate) {
this->state.insert(this->state.end(), nstate - this->state.size(), State(ndof));
} else if (this->state.size() > nstate) {
this->state.erase(this->state.end() - (this->state.size() - nstate), this->state.end());
}
}
uint get_nnode() { return this->nnode; }
uint get_nvrtx() { return this->nvrtx; }
uint get_nbound() { return this->nbound; }
uint get_ndof() { return this->ndof; }
uint get_ngp_internal() { return this->ngp_internal; }
uint get_ngp_boundary(uint nbound) { return this->ngp_boundary[nbound]; }
void set_nnode(const uint nnode) { this->nnode = nnode; }
void set_nvrtx(const uint nvrtx) { this->nvrtx = nvrtx; }
void set_nbound(const uint nbound) {
this->nbound = nbound;
this->ngp_boundary = std::vector<uint>(this->nbound, 0);
}
void set_ndof(const uint ndof) { this->ndof = ndof; }
void set_ngp_internal(const uint ngp) { this->ngp_internal = ngp; }
void set_ngp_boundary(const uint bound_id, const uint ngp) { this->ngp_boundary[bound_id] = ngp; }
private:
uint nnode;
uint nvrtx;
uint nbound;
uint ndof;
uint ngp_internal;
std::vector<uint> ngp_boundary;
};
}
}
#endif
|
/*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "web/WebInputEventConversion.h"
#include "core/dom/Touch.h"
#include "core/dom/TouchList.h"
#include "core/events/GestureEvent.h"
#include "core/events/KeyboardEvent.h"
#include "core/events/MouseEvent.h"
#include "core/events/TouchEvent.h"
#include "core/events/WheelEvent.h"
#include "core/frame/FrameHost.h"
#include "core/frame/FrameView.h"
#include "core/frame/VisualViewport.h"
#include "core/layout/api/LayoutItem.h"
#include "core/page/ChromeClient.h"
#include "core/page/Page.h"
#include "platform/KeyboardCodes.h"
#include "platform/Widget.h"
#include "public/platform/Platform.h"
namespace blink {
namespace {
float frameScale(const Widget* widget) {
float scale = 1;
if (widget) {
FrameView* rootView = toFrameView(widget->root());
if (rootView)
scale = rootView->inputEventsScaleFactor();
}
return scale;
}
FloatPoint frameTranslation(const Widget* widget) {
float scale = 1;
FloatSize offset;
IntPoint visualViewport;
FloatSize overscrollOffset;
if (widget) {
FrameView* rootView = toFrameView(widget->root());
if (rootView) {
scale = rootView->inputEventsScaleFactor();
offset = FloatSize(rootView->inputEventsOffsetForEmulation());
visualViewport = flooredIntPoint(rootView->page()
->frameHost()
.visualViewport()
.visibleRect()
.location());
overscrollOffset =
rootView->page()->frameHost().chromeClient().elasticOverscroll();
}
}
return FloatPoint(
-offset.width() / scale + visualViewport.x() + overscrollOffset.width(),
-offset.height() / scale + visualViewport.y() +
overscrollOffset.height());
}
float scaleDeltaToWindow(const Widget* widget, float delta) {
return delta / frameScale(widget);
}
FloatSize scaleSizeToWindow(const Widget* widget, FloatSize size) {
return FloatSize(scaleDeltaToWindow(widget, size.width()),
scaleDeltaToWindow(widget, size.height()));
}
// This method converts from the renderer's coordinate space into Blink's root
// frame coordinate space. It's somewhat unique in that it takes into account
// DevTools emulation, which applies a scale and offset in the root layer (see
// updateRootLayerTransform in WebViewImpl) as well as the overscroll effect on
// OSX. This is in addition to the visual viewport "pinch-zoom" transformation
// and is one of the few cases where the visual viewport is not equal to the
// renderer's coordinate-space.
FloatPoint convertHitPointToRootFrame(const Widget* widget,
FloatPoint pointInRendererViewport) {
float scale = 1;
IntSize offset;
IntPoint visualViewport;
FloatSize overscrollOffset;
if (widget) {
FrameView* rootView = toFrameView(widget->root());
if (rootView) {
scale = rootView->inputEventsScaleFactor();
offset = rootView->inputEventsOffsetForEmulation();
visualViewport = flooredIntPoint(rootView->page()
->frameHost()
.visualViewport()
.visibleRect()
.location());
overscrollOffset =
rootView->page()->frameHost().chromeClient().elasticOverscroll();
}
}
return FloatPoint((pointInRendererViewport.x() - offset.width()) / scale +
visualViewport.x() + overscrollOffset.width(),
(pointInRendererViewport.y() - offset.height()) / scale +
visualViewport.y() + overscrollOffset.height());
}
PlatformEvent::DispatchType toPlatformDispatchType(
WebInputEvent::DispatchType type) {
static_assert(PlatformEvent::DispatchType::Blocking ==
static_cast<PlatformEvent::DispatchType>(
WebInputEvent::DispatchType::Blocking),
"Dispatch Types not equal");
static_assert(PlatformEvent::DispatchType::EventNonBlocking ==
static_cast<PlatformEvent::DispatchType>(
WebInputEvent::DispatchType::EventNonBlocking),
"Dispatch Types not equal");
static_assert(
PlatformEvent::DispatchType::ListenersNonBlockingPassive ==
static_cast<PlatformEvent::DispatchType>(
WebInputEvent::DispatchType::ListenersNonBlockingPassive),
"Dispatch Types not equal");
static_assert(
PlatformEvent::DispatchType::ListenersForcedNonBlockingDueToFling ==
static_cast<PlatformEvent::DispatchType>(
WebInputEvent::DispatchType::
ListenersForcedNonBlockingDueToFling),
"Dispatch Types not equal");
return static_cast<PlatformEvent::DispatchType>(type);
}
unsigned toPlatformModifierFrom(WebMouseEvent::Button button) {
if (button == WebMouseEvent::Button::NoButton)
return 0;
unsigned webMouseButtonToPlatformModifier[] = {
PlatformEvent::LeftButtonDown, PlatformEvent::MiddleButtonDown,
PlatformEvent::RightButtonDown};
return webMouseButtonToPlatformModifier[static_cast<int>(button)];
}
} // namespace
// MakePlatformMouseEvent -----------------------------------------------------
// TODO(mustaq): Add tests for this.
PlatformMouseEventBuilder::PlatformMouseEventBuilder(Widget* widget,
const WebMouseEvent& e) {
// FIXME: Widget is always toplevel, unless it's a popup. We may be able
// to get rid of this once we abstract popups into a WebKit API.
m_position = widget->convertFromRootFrame(
flooredIntPoint(convertHitPointToRootFrame(widget, IntPoint(e.x, e.y))));
m_globalPosition = IntPoint(e.globalX, e.globalY);
m_movementDelta = IntPoint(scaleDeltaToWindow(widget, e.movementX),
scaleDeltaToWindow(widget, e.movementY));
m_modifiers = e.modifiers();
m_timestamp = TimeTicks::FromSeconds(e.timeStampSeconds());
m_clickCount = e.clickCount;
m_pointerProperties = static_cast<WebPointerProperties>(e);
switch (e.type()) {
case WebInputEvent::MouseMove:
case WebInputEvent::MouseEnter: // synthesize a move event
case WebInputEvent::MouseLeave: // synthesize a move event
m_type = PlatformEvent::MouseMoved;
break;
case WebInputEvent::MouseDown:
m_type = PlatformEvent::MousePressed;
break;
case WebInputEvent::MouseUp:
m_type = PlatformEvent::MouseReleased;
// The MouseEvent spec requires that buttons indicates the state
// immediately after the event takes place. To ensure consistency
// between platforms here, we explicitly clear the button that is
// in the process of being released.
m_modifiers &= ~toPlatformModifierFrom(e.button);
break;
default:
NOTREACHED();
}
}
WebMouseWheelEvent TransformWebMouseWheelEvent(
Widget* widget,
const WebMouseWheelEvent& event) {
WebMouseWheelEvent result = event;
result.setFrameScale(frameScale(widget));
result.setFrameTranslate(frameTranslation(widget));
return result;
}
WebGestureEvent TransformWebGestureEvent(Widget* widget,
const WebGestureEvent& event) {
WebGestureEvent result = event;
result.setFrameScale(frameScale(widget));
result.setFrameTranslate(frameTranslation(widget));
return result;
}
inline PlatformEvent::EventType toPlatformTouchEventType(
const WebInputEvent::Type type) {
switch (type) {
case WebInputEvent::TouchStart:
return PlatformEvent::TouchStart;
case WebInputEvent::TouchMove:
return PlatformEvent::TouchMove;
case WebInputEvent::TouchEnd:
return PlatformEvent::TouchEnd;
case WebInputEvent::TouchCancel:
return PlatformEvent::TouchCancel;
case WebInputEvent::TouchScrollStarted:
return PlatformEvent::TouchScrollStarted;
default:
NOTREACHED();
}
return PlatformEvent::TouchStart;
}
inline PlatformTouchPoint::TouchState toPlatformTouchPointState(
const WebTouchPoint::State state) {
switch (state) {
case WebTouchPoint::StateReleased:
return PlatformTouchPoint::TouchReleased;
case WebTouchPoint::StatePressed:
return PlatformTouchPoint::TouchPressed;
case WebTouchPoint::StateMoved:
return PlatformTouchPoint::TouchMoved;
case WebTouchPoint::StateStationary:
return PlatformTouchPoint::TouchStationary;
case WebTouchPoint::StateCancelled:
return PlatformTouchPoint::TouchCancelled;
case WebTouchPoint::StateUndefined:
NOTREACHED();
}
return PlatformTouchPoint::TouchReleased;
}
inline WebTouchPoint::State toWebTouchPointState(const AtomicString& type) {
if (type == EventTypeNames::touchend)
return WebTouchPoint::StateReleased;
if (type == EventTypeNames::touchcancel)
return WebTouchPoint::StateCancelled;
if (type == EventTypeNames::touchstart)
return WebTouchPoint::StatePressed;
if (type == EventTypeNames::touchmove)
return WebTouchPoint::StateMoved;
return WebTouchPoint::StateUndefined;
}
// TODO(mustaq): Add tests for this.
PlatformTouchPointBuilder::PlatformTouchPointBuilder(
Widget* widget,
const WebTouchPoint& point) {
m_pointerProperties = point;
m_state = toPlatformTouchPointState(point.state);
FloatPoint floatPos = convertHitPointToRootFrame(widget, point.position);
IntPoint flooredPoint = flooredIntPoint(floatPos);
m_pos =
widget->convertFromRootFrame(flooredPoint) + (floatPos - flooredPoint);
m_screenPos = FloatPoint(point.screenPosition.x, point.screenPosition.y);
m_radius = scaleSizeToWindow(widget, FloatSize(point.radiusX, point.radiusY));
m_rotationAngle = point.rotationAngle;
}
PlatformTouchEventBuilder::PlatformTouchEventBuilder(
Widget* widget,
const WebTouchEvent& event) {
m_type = toPlatformTouchEventType(event.type());
m_modifiers = event.modifiers();
m_timestamp = TimeTicks::FromSeconds(event.timeStampSeconds());
m_causesScrollingIfUncanceled = event.movedBeyondSlopRegion;
m_touchStartOrFirstTouchMove = event.touchStartOrFirstTouchMove;
for (unsigned i = 0; i < event.touchesLength; ++i)
m_touchPoints.push_back(
PlatformTouchPointBuilder(widget, event.touches[i]));
m_dispatchType = toPlatformDispatchType(event.dispatchType);
m_uniqueTouchEventId = event.uniqueTouchEventId;
}
static FloatPoint convertAbsoluteLocationForLayoutObjectFloat(
const DoublePoint& location,
const LayoutItem layoutItem) {
return layoutItem.absoluteToLocal(FloatPoint(location), UseTransforms);
}
static IntPoint convertAbsoluteLocationForLayoutObjectInt(
const DoublePoint& location,
const LayoutItem layoutItem) {
return roundedIntPoint(
convertAbsoluteLocationForLayoutObjectFloat(location, layoutItem));
}
// FIXME: Change |widget| to const Widget& after RemoteFrames get
// RemoteFrameViews.
static void updateWebMouseEventFromCoreMouseEvent(const MouseEvent& event,
const Widget* widget,
const LayoutItem layoutItem,
WebMouseEvent& webEvent) {
webEvent.setTimeStampSeconds(event.platformTimeStamp().InSeconds());
webEvent.setModifiers(event.modifiers());
FrameView* view = widget ? toFrameView(widget->parent()) : 0;
// TODO(bokan): If view == nullptr, pointInRootFrame will really be
// pointInRootContent.
IntPoint pointInRootFrame(event.absoluteLocation().x(),
event.absoluteLocation().y());
if (view)
pointInRootFrame = view->contentsToRootFrame(pointInRootFrame);
webEvent.globalX = event.screenX();
webEvent.globalY = event.screenY();
webEvent.windowX = pointInRootFrame.x();
webEvent.windowY = pointInRootFrame.y();
IntPoint localPoint = convertAbsoluteLocationForLayoutObjectInt(
event.absoluteLocation(), layoutItem);
webEvent.x = localPoint.x();
webEvent.y = localPoint.y();
}
WebMouseEventBuilder::WebMouseEventBuilder(const Widget* widget,
const LayoutItem layoutItem,
const MouseEvent& event) {
if (event.type() == EventTypeNames::mousemove)
m_type = WebInputEvent::MouseMove;
else if (event.type() == EventTypeNames::mouseout)
m_type = WebInputEvent::MouseLeave;
else if (event.type() == EventTypeNames::mouseover)
m_type = WebInputEvent::MouseEnter;
else if (event.type() == EventTypeNames::mousedown)
m_type = WebInputEvent::MouseDown;
else if (event.type() == EventTypeNames::mouseup)
m_type = WebInputEvent::MouseUp;
else if (event.type() == EventTypeNames::contextmenu)
m_type = WebInputEvent::ContextMenu;
else
return; // Skip all other mouse events.
m_timeStampSeconds = event.platformTimeStamp().InSeconds();
m_modifiers = event.modifiers();
updateWebMouseEventFromCoreMouseEvent(event, widget, layoutItem, *this);
switch (event.button()) {
case short(WebPointerProperties::Button::Left):
button = WebMouseEvent::Button::Left;
break;
case short(WebPointerProperties::Button::Middle):
button = WebMouseEvent::Button::Middle;
break;
case short(WebPointerProperties::Button::Right):
button = WebMouseEvent::Button::Right;
break;
}
if (event.buttonDown()) {
switch (event.button()) {
case short(WebPointerProperties::Button::Left):
m_modifiers |= WebInputEvent::LeftButtonDown;
break;
case short(WebPointerProperties::Button::Middle):
m_modifiers |= WebInputEvent::MiddleButtonDown;
break;
case short(WebPointerProperties::Button::Right):
m_modifiers |= WebInputEvent::RightButtonDown;
break;
}
} else {
button = WebMouseEvent::Button::NoButton;
}
movementX = event.movementX();
movementY = event.movementY();
clickCount = event.detail();
pointerType = WebPointerProperties::PointerType::Mouse;
if (event.mouseEvent())
pointerType = event.mouseEvent()->pointerProperties().pointerType;
}
// Generate a synthetic WebMouseEvent given a TouchEvent (eg. for emulating a
// mouse with touch input for plugins that don't support touch input).
WebMouseEventBuilder::WebMouseEventBuilder(const Widget* widget,
const LayoutItem layoutItem,
const TouchEvent& event) {
if (!event.touches())
return;
if (event.touches()->length() != 1) {
if (event.touches()->length() || event.type() != EventTypeNames::touchend ||
!event.changedTouches() || event.changedTouches()->length() != 1)
return;
}
const Touch* touch = event.touches()->length() == 1
? event.touches()->item(0)
: event.changedTouches()->item(0);
if (touch->identifier())
return;
if (event.type() == EventTypeNames::touchstart)
m_type = MouseDown;
else if (event.type() == EventTypeNames::touchmove)
m_type = MouseMove;
else if (event.type() == EventTypeNames::touchend)
m_type = MouseUp;
else
return;
m_timeStampSeconds = event.platformTimeStamp().InSeconds();
m_modifiers = event.modifiers();
// The mouse event co-ordinates should be generated from the co-ordinates of
// the touch point.
FrameView* view = toFrameView(widget->parent());
// FIXME: if view == nullptr, pointInRootFrame will really be
// pointInRootContent.
IntPoint pointInRootFrame = roundedIntPoint(touch->absoluteLocation());
if (view)
pointInRootFrame = view->contentsToRootFrame(pointInRootFrame);
IntPoint screenPoint = roundedIntPoint(touch->screenLocation());
globalX = screenPoint.x();
globalY = screenPoint.y();
windowX = pointInRootFrame.x();
windowY = pointInRootFrame.y();
button = WebMouseEvent::Button::Left;
m_modifiers |= WebInputEvent::LeftButtonDown;
clickCount = (m_type == MouseDown || m_type == MouseUp);
IntPoint localPoint = convertAbsoluteLocationForLayoutObjectInt(
DoublePoint(touch->absoluteLocation()), layoutItem);
x = localPoint.x();
y = localPoint.y();
pointerType = WebPointerProperties::PointerType::Touch;
}
WebKeyboardEventBuilder::WebKeyboardEventBuilder(const KeyboardEvent& event) {
if (const WebKeyboardEvent* webEvent = event.keyEvent()) {
*static_cast<WebKeyboardEvent*>(this) = *webEvent;
// TODO(dtapuska): DOM KeyboardEvents converted back to WebInputEvents
// drop the Raw behaviour. Figure out if this is actually really needed.
if (m_type == RawKeyDown)
m_type = KeyDown;
return;
}
if (event.type() == EventTypeNames::keydown)
m_type = KeyDown;
else if (event.type() == EventTypeNames::keyup)
m_type = WebInputEvent::KeyUp;
else if (event.type() == EventTypeNames::keypress)
m_type = WebInputEvent::Char;
else
return; // Skip all other keyboard events.
m_modifiers = event.modifiers();
m_timeStampSeconds = event.platformTimeStamp().InSeconds();
windowsKeyCode = event.keyCode();
}
static WebTouchPoint toWebTouchPoint(const Touch* touch,
const LayoutItem layoutItem,
WebTouchPoint::State state,
WebPointerProperties::PointerType type) {
WebTouchPoint point;
point.pointerType = type;
point.id = touch->identifier();
point.screenPosition = touch->screenLocation();
point.position = convertAbsoluteLocationForLayoutObjectFloat(
DoublePoint(touch->absoluteLocation()), layoutItem);
point.radiusX = touch->radiusX();
point.radiusY = touch->radiusY();
point.rotationAngle = touch->rotationAngle();
point.force = touch->force();
point.state = state;
return point;
}
static unsigned indexOfTouchPointWithId(const WebTouchPoint* touchPoints,
unsigned touchPointsLength,
unsigned id) {
for (unsigned i = 0; i < touchPointsLength; ++i) {
if (touchPoints[i].id == static_cast<int>(id))
return i;
}
return std::numeric_limits<unsigned>::max();
}
static void addTouchPointsUpdateStateIfNecessary(
WebTouchPoint::State state,
TouchList* touches,
WebTouchPoint* touchPoints,
unsigned* touchPointsLength,
const LayoutItem layoutItem,
WebPointerProperties::PointerType pointerType) {
unsigned initialTouchPointsLength = *touchPointsLength;
for (unsigned i = 0; i < touches->length(); ++i) {
const unsigned pointIndex = *touchPointsLength;
if (pointIndex >= static_cast<unsigned>(WebTouchEvent::kTouchesLengthCap))
return;
const Touch* touch = touches->item(i);
unsigned existingPointIndex = indexOfTouchPointWithId(
touchPoints, initialTouchPointsLength, touch->identifier());
if (existingPointIndex != std::numeric_limits<unsigned>::max()) {
touchPoints[existingPointIndex].state = state;
} else {
touchPoints[pointIndex] =
toWebTouchPoint(touch, layoutItem, state, pointerType);
++(*touchPointsLength);
}
}
}
WebTouchEventBuilder::WebTouchEventBuilder(const LayoutItem layoutItem,
const TouchEvent& event) {
if (event.type() == EventTypeNames::touchstart)
m_type = TouchStart;
else if (event.type() == EventTypeNames::touchmove)
m_type = TouchMove;
else if (event.type() == EventTypeNames::touchend)
m_type = TouchEnd;
else if (event.type() == EventTypeNames::touchcancel)
m_type = TouchCancel;
else {
NOTREACHED();
m_type = Undefined;
return;
}
m_timeStampSeconds = event.platformTimeStamp().InSeconds();
m_modifiers = event.modifiers();
dispatchType = event.cancelable() ? WebInputEvent::Blocking
: WebInputEvent::EventNonBlocking;
movedBeyondSlopRegion = event.causesScrollingIfUncanceled();
// Currently touches[] is empty, add stationary points as-is.
for (unsigned i = 0;
i < event.touches()->length() &&
i < static_cast<unsigned>(WebTouchEvent::kTouchesLengthCap);
++i) {
touches[i] =
toWebTouchPoint(event.touches()->item(i), layoutItem,
WebTouchPoint::StateStationary, event.pointerType());
++touchesLength;
}
// If any existing points are also in the change list, we should update
// their state, otherwise just add the new points.
addTouchPointsUpdateStateIfNecessary(
toWebTouchPointState(event.type()), event.changedTouches(), touches,
&touchesLength, layoutItem, event.pointerType());
}
Vector<PlatformMouseEvent> createPlatformMouseEventVector(
Widget* widget,
const std::vector<const WebInputEvent*>& coalescedEvents) {
Vector<PlatformMouseEvent> result;
for (const auto& event : coalescedEvents) {
DCHECK(WebInputEvent::isMouseEventType(event->type()));
result.push_back(PlatformMouseEventBuilder(
widget, static_cast<const WebMouseEvent&>(*event)));
}
return result;
}
Vector<PlatformTouchEvent> createPlatformTouchEventVector(
Widget* widget,
const std::vector<const WebInputEvent*>& coalescedEvents) {
Vector<PlatformTouchEvent> result;
for (const auto& event : coalescedEvents) {
DCHECK(WebInputEvent::isTouchEventType(event->type()));
result.push_back(PlatformTouchEventBuilder(
widget, static_cast<const WebTouchEvent&>(*event)));
}
return result;
}
} // namespace blink
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "android_webview/browser/find_helper.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/stop_find_action.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
using content::WebContents;
namespace android_webview {
FindHelper::FindHelper(WebContents* web_contents)
: WebContentsObserver(web_contents),
listener_(nullptr),
async_find_started_(false),
find_request_id_counter_(0),
current_request_id_(0),
current_session_id_(0),
last_match_count_(-1),
last_active_ordinal_(-1) {
}
FindHelper::~FindHelper() {
}
void FindHelper::SetListener(Listener* listener) {
listener_ = listener;
}
void FindHelper::FindAllAsync(const base::string16& search_string) {
// Stop any ongoing asynchronous request.
web_contents()->StopFinding(content::STOP_FIND_ACTION_KEEP_SELECTION);
async_find_started_ = true;
StartNewSession(search_string);
if (MaybeHandleEmptySearch(search_string))
return;
auto options = blink::mojom::FindOptions::New();
options->forward = true;
options->match_case = false;
options->new_session = true;
web_contents()->Find(current_request_id_, search_string, std::move(options));
}
void FindHelper::HandleFindReply(int request_id,
int match_count,
int active_ordinal,
bool finished) {
if (!async_find_started_ || request_id < current_session_id_)
return;
NotifyResults(active_ordinal, match_count, finished);
}
void FindHelper::FindNext(bool forward) {
if (!async_find_started_)
return;
current_request_id_ = find_request_id_counter_++;
if (MaybeHandleEmptySearch(last_search_string_))
return;
auto options = blink::mojom::FindOptions::New();
options->forward = forward;
options->match_case = false;
options->new_session = false;
web_contents()->Find(current_request_id_, last_search_string_,
std::move(options));
}
void FindHelper::ClearMatches() {
web_contents()->StopFinding(content::STOP_FIND_ACTION_CLEAR_SELECTION);
async_find_started_ = false;
last_search_string_.clear();
last_match_count_ = -1;
last_active_ordinal_ = -1;
}
bool FindHelper::MaybeHandleEmptySearch(const base::string16& search_string) {
if (!search_string.empty())
return false;
web_contents()->StopFinding(content::STOP_FIND_ACTION_CLEAR_SELECTION);
NotifyResults(0, 0, true);
return true;
}
void FindHelper::StartNewSession(const base::string16& search_string) {
current_request_id_ = find_request_id_counter_++;
current_session_id_ = current_request_id_;
last_search_string_ = search_string;
last_match_count_ = -1;
last_active_ordinal_ = -1;
}
void FindHelper::NotifyResults(int active_ordinal,
int match_count,
bool finished) {
// Match count or ordinal values set to -1 refer to received replies.
if (match_count == -1)
match_count = last_match_count_;
else
last_match_count_ = match_count;
if (active_ordinal == -1)
active_ordinal = last_active_ordinal_;
else
last_active_ordinal_ = active_ordinal;
// Skip the update if we don't still have a valid ordinal.
// The next update, final or not, should have this information.
if (!finished && active_ordinal == -1)
return;
// Safeguard in case of errors to prevent reporting -1 to the API listeners.
if (match_count == -1) {
NOTREACHED();
match_count = 0;
}
if (active_ordinal == -1) {
NOTREACHED();
active_ordinal = 0;
}
// WebView.FindListener active match ordinals are 0-based while WebKit sends
// 1-based ordinals. Still we can receive 0 ordinal in case of no results.
active_ordinal = std::max(active_ordinal - 1, 0);
if (listener_)
listener_->OnFindResultReceived(active_ordinal, match_count, finished);
}
} // namespace android_webview
|
#ifndef GREGORIAN_FACET_HPP___
#define GREGORIAN_FACET_HPP___
/* Copyright (c) 2002,2003 CrystalClear Software, Inc.
* Use, modification and distribution is subject to the
* Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
* Author: Jeff Garland, Bart Garst
* $Date$
*/
#include <boost/date_time/compiler_config.hpp>
#include <boost/date_time/gregorian/gregorian_types.hpp>
#include <boost/date_time/date_formatting_locales.hpp> // sets BOOST_DATE_TIME_NO_LOCALE
#include <boost/date_time/gregorian/parsers.hpp>
//This file is basically commented out if locales are not supported
#ifndef BOOST_DATE_TIME_NO_LOCALE
#include <string>
#include <memory>
#include <locale>
#include <iostream>
#include <exception>
namespace boost {
namespace gregorian {
//! Configuration of the output facet template
struct BOOST_SYMBOL_VISIBLE greg_facet_config
{
typedef boost::gregorian::greg_month month_type;
typedef boost::date_time::special_values special_value_enum;
typedef boost::gregorian::months_of_year month_enum;
typedef boost::date_time::weekdays weekday_enum;
};
#if defined(USE_DATE_TIME_PRE_1_33_FACET_IO)
//! Create the base facet type for gregorian::date
typedef boost::date_time::date_names_put<greg_facet_config> greg_base_facet;
//! ostream operator for gregorian::date
/*! Uses the date facet to determine various output parameters including:
* - string values for the month (eg: Jan, Feb, Mar) (default: English)
* - string values for special values (eg: not-a-date-time) (default: English)
* - selection of long, short strings, or numerical month representation (default: short string)
* - month day year order (default yyyy-mmm-dd)
*/
template <class charT, class traits>
inline
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const date& d)
{
typedef boost::date_time::date_names_put<greg_facet_config, charT> facet_def;
typedef boost::date_time::ostream_date_formatter<date, facet_def, charT> greg_ostream_formatter;
greg_ostream_formatter::date_put(d, os);
return os;
}
//! operator<< for gregorian::greg_month typically streaming: Jan, Feb, Mar...
/*! Uses the date facet to determine output string as well as selection of long or short strings.
* Default if no facet is installed is to output a 2 wide numeric value for the month
* eg: 01 == Jan, 02 == Feb, ... 12 == Dec.
*/
template <class charT, class traits>
inline
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const greg_month& m)
{
typedef boost::date_time::date_names_put<greg_facet_config, charT> facet_def;
typedef boost::date_time::ostream_month_formatter<facet_def, charT> greg_month_formatter;
std::locale locale = os.getloc();
if (std::has_facet<facet_def>(locale)) {
const facet_def& f = std::use_facet<facet_def>(locale);
greg_month_formatter::format_month(m, os, f);
}
else { //default to numeric
charT fill_char = '0';
os << std::setw(2) << std::setfill(fill_char) << m.as_number();
}
return os;
}
//! operator<< for gregorian::greg_weekday typically streaming: Sun, Mon, Tue, ...
/*! Uses the date facet to determine output string as well as selection of long or short string.
* Default if no facet is installed is to output a 3 char english string for the
* day of the week.
*/
template <class charT, class traits>
inline
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const greg_weekday& wd)
{
typedef boost::date_time::date_names_put<greg_facet_config, charT> facet_def;
typedef boost::date_time::ostream_weekday_formatter<greg_weekday, facet_def, charT> greg_weekday_formatter;
std::locale locale = os.getloc();
if (std::has_facet<facet_def>(locale)) {
const facet_def& f = std::use_facet<facet_def>(locale);
greg_weekday_formatter::format_weekday(wd, os, f, true);
}
else { //default to short English string eg: Sun, Mon, Tue, Wed...
os << wd.as_short_string();
}
return os;
}
//! operator<< for gregorian::date_period typical output: [2002-Jan-01/2002-Jan-31]
/*! Uses the date facet to determine output string as well as selection of long
* or short string fr dates.
* Default if no facet is installed is to output a 3 char english string for the
* day of the week.
*/
template <class charT, class traits>
inline
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const date_period& dp)
{
os << '['; //TODO: facet or manipulator for periods?
os << dp.begin();
os << '/'; //TODO: facet or manipulator for periods?
os << dp.last();
os << ']';
return os;
}
template <class charT, class traits>
inline
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const date_duration& dd)
{
//os << dd.days();
os << dd.get_rep();
return os;
}
//! operator<< for gregorian::partial_date. Output: "Jan 1"
template <class charT, class traits>
inline
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const partial_date& pd)
{
os << std::setw(2) << std::setfill('0') << pd.day() << ' '
<< pd.month().as_short_string() ;
return os;
}
//! operator<< for gregorian::nth_kday_of_month. Output: "first Mon of Jun"
template <class charT, class traits>
inline
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os,
const nth_kday_of_month& nkd)
{
os << nkd.nth_week_as_str() << ' '
<< nkd.day_of_week() << " of "
<< nkd.month().as_short_string() ;
return os;
}
//! operator<< for gregorian::first_kday_of_month. Output: "first Mon of Jun"
template <class charT, class traits>
inline
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os,
const first_kday_of_month& fkd)
{
os << "first " << fkd.day_of_week() << " of "
<< fkd.month().as_short_string() ;
return os;
}
//! operator<< for gregorian::last_kday_of_month. Output: "last Mon of Jun"
template <class charT, class traits>
inline
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os,
const last_kday_of_month& lkd)
{
os << "last " << lkd.day_of_week() << " of "
<< lkd.month().as_short_string() ;
return os;
}
//! operator<< for gregorian::first_kday_after. Output: "first Mon after"
template <class charT, class traits>
inline
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os,
const first_kday_after& fka)
{
os << fka.day_of_week() << " after";
return os;
}
//! operator<< for gregorian::first_kday_before. Output: "first Mon before"
template <class charT, class traits>
inline
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os,
const first_kday_before& fkb)
{
os << fkb.day_of_week() << " before";
return os;
}
#endif // USE_DATE_TIME_PRE_1_33_FACET_IO
/**************** Input Streaming ******************/
#if !defined(BOOST_NO_STD_ITERATOR_TRAITS)
//! operator>> for gregorian::date
template<class charT>
inline
std::basic_istream<charT>& operator>>(std::basic_istream<charT>& is, date& d)
{
std::istream_iterator<std::basic_string<charT>, charT> beg(is), eos;
d = from_stream(beg, eos);
return is;
}
#endif // BOOST_NO_STD_ITERATOR_TRAITS
//! operator>> for gregorian::date_duration
template<class charT>
inline
std::basic_istream<charT>& operator>>(std::basic_istream<charT>& is,
date_duration& dd)
{
long v;
is >> v;
dd = date_duration(v);
return is;
}
//! operator>> for gregorian::date_period
template<class charT>
inline
std::basic_istream<charT>& operator>>(std::basic_istream<charT>& is,
date_period& dp)
{
std::basic_string<charT> s;
is >> s;
dp = date_time::from_simple_string_type<date>(s);
return is;
}
//! generates a locale with the set of gregorian name-strings of type char*
BOOST_DATE_TIME_DECL std::locale generate_locale(std::locale& loc, char type);
//! Returns a pointer to a facet with a default set of names (English)
/* Necessary in the event an exception is thrown from op>> for
* weekday or month. See comments in those functions for more info */
BOOST_DATE_TIME_DECL boost::date_time::all_date_names_put<greg_facet_config, char>* create_facet_def(char type);
#ifndef BOOST_NO_STD_WSTRING
//! generates a locale with the set of gregorian name-strings of type wchar_t*
BOOST_DATE_TIME_DECL std::locale generate_locale(std::locale& loc, wchar_t type);
//! Returns a pointer to a facet with a default set of names (English)
/* Necessary in the event an exception is thrown from op>> for
* weekday or month. See comments in those functions for more info */
BOOST_DATE_TIME_DECL boost::date_time::all_date_names_put<greg_facet_config, wchar_t>* create_facet_def(wchar_t type);
#endif // BOOST_NO_STD_WSTRING
//! operator>> for gregorian::greg_month - throws exception if invalid month given
template<class charT>
inline
std::basic_istream<charT>& operator>>(std::basic_istream<charT>& is,greg_month& m)
{
typedef boost::date_time::all_date_names_put<greg_facet_config, charT> facet_def;
std::basic_string<charT> s;
is >> s;
if(!std::has_facet<facet_def>(is.getloc())) {
std::locale loc = is.getloc();
charT a = '\0';
is.imbue(generate_locale(loc, a));
}
short num = 0;
try{
const facet_def& f = std::use_facet<facet_def>(is.getloc());
num = date_time::find_match(f.get_short_month_names(),
f.get_long_month_names(),
(greg_month::max)(), s); // greg_month spans 1..12, so max returns the array size,
// which is needed by find_match
}
/* bad_cast will be thrown if the desired facet is not accessible
* so we can generate the facet. This has the drawback of using english
* names as a default. */
catch(std::bad_cast&){
charT a = '\0';
#if defined(BOOST_NO_CXX11_SMART_PTR)
std::auto_ptr< const facet_def > f(create_facet_def(a));
#else
std::unique_ptr< const facet_def > f(create_facet_def(a));
#endif
num = date_time::find_match(f->get_short_month_names(),
f->get_long_month_names(),
(greg_month::max)(), s); // greg_month spans 1..12, so max returns the array size,
// which is needed by find_match
}
++num; // months numbered 1-12
m = greg_month(num);
return is;
}
//! operator>> for gregorian::greg_weekday - throws exception if invalid weekday given
template<class charT>
inline
std::basic_istream<charT>& operator>>(std::basic_istream<charT>& is,greg_weekday& wd)
{
typedef boost::date_time::all_date_names_put<greg_facet_config, charT> facet_def;
std::basic_string<charT> s;
is >> s;
if(!std::has_facet<facet_def>(is.getloc())) {
std::locale loc = is.getloc();
charT a = '\0';
is.imbue(generate_locale(loc, a));
}
short num = 0;
try{
const facet_def& f = std::use_facet<facet_def>(is.getloc());
num = date_time::find_match(f.get_short_weekday_names(),
f.get_long_weekday_names(),
(greg_weekday::max)() + 1, s); // greg_weekday spans 0..6, so increment is needed
// to form the array size which is needed by find_match
}
/* bad_cast will be thrown if the desired facet is not accessible
* so we can generate the facet. This has the drawback of using english
* names as a default. */
catch(std::bad_cast&){
charT a = '\0';
#if defined(BOOST_NO_CXX11_SMART_PTR)
std::auto_ptr< const facet_def > f(create_facet_def(a));
#else
std::unique_ptr< const facet_def > f(create_facet_def(a));
#endif
num = date_time::find_match(f->get_short_weekday_names(),
f->get_long_weekday_names(),
(greg_weekday::max)() + 1, s); // greg_weekday spans 0..6, so increment is needed
// to form the array size which is needed by find_match
}
wd = greg_weekday(num); // weekdays numbered 0-6
return is;
}
} } //namespace gregorian
#endif
#endif
|
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/route53domains/model/OperationSummary.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Route53Domains
{
namespace Model
{
OperationSummary::OperationSummary() :
m_operationIdHasBeenSet(false),
m_statusHasBeenSet(false),
m_typeHasBeenSet(false),
m_submittedDateHasBeenSet(false)
{
}
OperationSummary::OperationSummary(const JsonValue& jsonValue) :
m_operationIdHasBeenSet(false),
m_statusHasBeenSet(false),
m_typeHasBeenSet(false),
m_submittedDateHasBeenSet(false)
{
*this = jsonValue;
}
OperationSummary& OperationSummary::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("OperationId"))
{
m_operationId = jsonValue.GetString("OperationId");
m_operationIdHasBeenSet = true;
}
if(jsonValue.ValueExists("Status"))
{
m_status = OperationStatusMapper::GetOperationStatusForName(jsonValue.GetString("Status"));
m_statusHasBeenSet = true;
}
if(jsonValue.ValueExists("Type"))
{
m_type = OperationTypeMapper::GetOperationTypeForName(jsonValue.GetString("Type"));
m_typeHasBeenSet = true;
}
if(jsonValue.ValueExists("SubmittedDate"))
{
m_submittedDate = jsonValue.GetDouble("SubmittedDate");
m_submittedDateHasBeenSet = true;
}
return *this;
}
JsonValue OperationSummary::Jsonize() const
{
JsonValue payload;
if(m_operationIdHasBeenSet)
{
payload.WithString("OperationId", m_operationId);
}
if(m_statusHasBeenSet)
{
payload.WithString("Status", OperationStatusMapper::GetNameForOperationStatus(m_status));
}
if(m_typeHasBeenSet)
{
payload.WithString("Type", OperationTypeMapper::GetNameForOperationType(m_type));
}
if(m_submittedDateHasBeenSet)
{
payload.WithDouble("SubmittedDate", m_submittedDate.SecondsWithMSPrecision());
}
return payload;
}
} // namespace Model
} // namespace Route53Domains
} // namespace Aws
|
#include <catch.hpp>
#include <internal/facts/resolvers/operating_system_resolver.hpp>
#include <facter/facts/collection.hpp>
#include <facter/facts/fact.hpp>
#include <facter/facts/scalar_value.hpp>
#include <facter/facts/map_value.hpp>
using namespace std;
using namespace facter::facts;
using namespace facter::facts::resolvers;
struct empty_os_resolver : operating_system_resolver
{
protected:
virtual data collect_data(collection& facts) override
{
return {};
}
};
struct test_os_resolver : operating_system_resolver
{
protected:
virtual data collect_data(collection& facts) override
{
data result;
result.name = "Archlinux";
result.family = "Archlinux";
result.release = "1.2.3";
result.major = "1";
result.minor = "2";
result.specification_version = "1.4";
result.distro.id = "Arch";
result.distro.release = "1.2.3";
result.distro.codename = "awesomesauce";
result.distro.description = "best distro ever";
result.osx.product = "Mac OS X";
result.osx.build = "14A388b";
result.osx.version = "10.10";
result.win.system32 = "C:\\WINDOWS\\sysnative";
result.architecture = "amd64";
result.hardware = "x86-64";
result.selinux.supported = true;
result.selinux.enabled = true;
result.selinux.enforced = true;
result.selinux.current_mode = "current mode";
result.selinux.config_mode = "config mode";
result.selinux.config_policy = "config policy";
result.selinux.policy_version = "policy version";
return result;
}
};
SCENARIO("using the operating system resolver") {
collection facts;
WHEN("data is not present") {
facts.add(make_shared<empty_os_resolver>());
THEN("facts should not be added") {
REQUIRE(facts.size() == 0u);
}
}
WHEN("data is present") {
facts.add(make_shared<test_os_resolver>());
REQUIRE(facts.size() == 26u);
THEN("a structured fact is added") {
auto os = facts.get<map_value>(fact::os);
REQUIRE(os);
REQUIRE(os->size() == 9u);
auto distro = os->get<map_value>("distro");
REQUIRE(distro);
REQUIRE(distro->size() == 5u);
auto codename = distro->get<string_value>("codename");
REQUIRE(codename);
REQUIRE(codename->value() == "awesomesauce");
auto description = distro->get<string_value>("description");
REQUIRE(description);
REQUIRE(description->value() == "best distro ever");
auto id = distro->get<string_value>("id");
REQUIRE(description);
REQUIRE(id->value() == "Arch");
auto lsbrelease = distro->get<string_value>("specification");
REQUIRE(lsbrelease);
REQUIRE(lsbrelease->value() == "1.4");
auto release_attribute = distro->get<map_value>("release");
REQUIRE(release_attribute);
REQUIRE(release_attribute->size() == 3u);
auto release = release_attribute->get<string_value>("full");
REQUIRE(release);
REQUIRE(release->value() == "1.2.3");
auto major = release_attribute->get<string_value>("major");
REQUIRE(major);
REQUIRE(major->value() == "1");
auto minor = release_attribute->get<string_value>("minor");
REQUIRE(minor);
REQUIRE(minor->value() == "2");
auto family = os->get<string_value>("family");
REQUIRE(family);
REQUIRE(family->value() == "Archlinux");
auto name = os->get<string_value>("name");
REQUIRE(name);
REQUIRE(name->value() == "Archlinux");
auto architecture = os->get<string_value>("architecture");
REQUIRE(architecture);
REQUIRE(architecture->value() == "amd64");
auto hardware = os->get<string_value>("hardware");
REQUIRE(hardware);
REQUIRE(hardware->value() == "x86-64");
release_attribute = os->get<map_value>("release");
REQUIRE(release_attribute);
REQUIRE(release_attribute->size() == 3u);
release = release_attribute->get<string_value>("full");
REQUIRE(release);
REQUIRE(release->value() == "1.2.3");
major = release_attribute->get<string_value>("major");
REQUIRE(major);
REQUIRE(major->value() == "1");
minor = release_attribute->get<string_value>("minor");
REQUIRE(minor);
REQUIRE(minor->value() == "2");
auto macosx = os->get<map_value>("macosx");
REQUIRE(macosx);
REQUIRE(macosx->size() == 3u);
auto product = macosx->get<string_value>("product");
REQUIRE(product);
REQUIRE(product->value() == "Mac OS X");
auto build = macosx->get<string_value>("build");
REQUIRE(build);
REQUIRE(build->value() == "14A388b");
release_attribute = macosx->get<map_value>("version");
REQUIRE(release_attribute);
REQUIRE(release_attribute->size() == 3u);
release = release_attribute->get<string_value>("full");
REQUIRE(release);
REQUIRE(release->value() == "10.10");
major = release_attribute->get<string_value>("major");
REQUIRE(major);
REQUIRE(major->value() == "10.10");
minor = release_attribute->get<string_value>("minor");
REQUIRE(minor);
REQUIRE(minor->value() == "0");
auto windows = os->get<map_value>("windows");
REQUIRE(windows);
REQUIRE(windows->size() == 1u);
auto system32 = windows->get<string_value>("system32");
REQUIRE(system32);
REQUIRE(system32->value() == "C:\\WINDOWS\\sysnative");
auto selinux = os->get<map_value>("selinux");
REQUIRE(selinux);
REQUIRE(selinux->size() == 6u);
auto bval = selinux->get<boolean_value>("enabled");
REQUIRE(bval);
REQUIRE(bval->value());
bval = selinux->get<boolean_value>("enforced");
REQUIRE(bval);
REQUIRE(bval->value());
auto sval = selinux->get<string_value>("policy_version");
REQUIRE(sval);
REQUIRE(sval->value() == "policy version");
sval = selinux->get<string_value>("current_mode");
REQUIRE(sval);
REQUIRE(sval->value() == "current mode");
sval = selinux->get<string_value>("config_mode");
REQUIRE(sval);
REQUIRE(sval->value() == "config mode");
sval = selinux->get<string_value>("config_policy");
REQUIRE(sval);
REQUIRE(sval->value() == "config policy");
}
THEN("flat facts are added") {
auto name = facts.get<string_value>(fact::operating_system);
REQUIRE(name);
REQUIRE(name->value() == "Archlinux");
auto architecture = facts.get<string_value>(fact::architecture);
REQUIRE(architecture);
REQUIRE(architecture->value() == "amd64");
auto hardware = facts.get<string_value>(fact::hardware_model);
REQUIRE(hardware);
REQUIRE(hardware->value() == "x86-64");
auto release = facts.get<string_value>(fact::operating_system_release);
REQUIRE(release);
REQUIRE(release->value() == "1.2.3");
auto major = facts.get<string_value>(fact::operating_system_major_release);
REQUIRE(major);
REQUIRE(major->value() == "1");
auto family = facts.get<string_value>(fact::os_family);
REQUIRE(family);
REQUIRE(family->value() == "Archlinux");
auto codename = facts.get<string_value>(fact::lsb_dist_codename);
REQUIRE(codename);
REQUIRE(codename->value() == "awesomesauce");
auto description = facts.get<string_value>(fact::lsb_dist_description);
REQUIRE(description);
REQUIRE(description->value() == "best distro ever");
auto id = facts.get<string_value>(fact::lsb_dist_id);
REQUIRE(id);
REQUIRE(id->value() == "Arch");
release = facts.get<string_value>(fact::lsb_dist_release);
REQUIRE(release);
REQUIRE(release->value() == "1.2.3");
major = facts.get<string_value>(fact::lsb_dist_major_release);
REQUIRE(major);
REQUIRE(major->value() == "1");
auto minor = facts.get<string_value>(fact::lsb_dist_minor_release);
REQUIRE(minor);
REQUIRE(minor->value() == "2");
auto lsbrelease = facts.get<string_value>(fact::lsb_release);
REQUIRE(lsbrelease);
REQUIRE(lsbrelease->value() == "1.4");
auto build = facts.get<string_value>(fact::macosx_buildversion);
REQUIRE(build);
REQUIRE(build->value() == "14A388b");
auto product = facts.get<string_value>(fact::macosx_productname);
REQUIRE(product);
REQUIRE(product->value() == "Mac OS X");
release = facts.get<string_value>(fact::macosx_productversion);
REQUIRE(release);
REQUIRE(release->value() == "10.10");
major = facts.get<string_value>(fact::macosx_productversion_major);
REQUIRE(major);
REQUIRE(major->value() == "10.10");
minor = facts.get<string_value>(fact::macosx_productversion_minor);
REQUIRE(minor);
REQUIRE(minor->value() == "0");
auto system32 = facts.get<string_value>(fact::windows_system32);
REQUIRE(system32);
REQUIRE(system32->value() == "C:\\WINDOWS\\sysnative");
auto bval = facts.get<boolean_value>(fact::selinux);
REQUIRE(bval);
REQUIRE(bval->value());
bval = facts.get<boolean_value>(fact::selinux_enforced);
REQUIRE(bval);
REQUIRE(bval->value());
auto sval = facts.get<string_value>(fact::selinux_policyversion);
REQUIRE(sval);
REQUIRE(sval->value() == "policy version");
sval = facts.get<string_value>(fact::selinux_current_mode);
REQUIRE(sval);
REQUIRE(sval->value() == "current mode");
sval = facts.get<string_value>(fact::selinux_config_mode);
REQUIRE(sval);
REQUIRE(sval->value() == "config mode");
sval = facts.get<string_value>(fact::selinux_config_policy);
REQUIRE(sval);
REQUIRE(sval->value() == "config policy");
}
}
}
|
/***********************************************************************************
* Copyright (C) 2008 by Filip Rooms *
* *
* Terms and conditions for using this software in any form are provided in the *
* file COPYING, which can be found in the root directory of this project. *
* *
* Contact data: filip.rooms@gmail.com *
* http://www.filiprooms.be/ *
* *
***********************************************************************************/
#include <QMessageBox>
#include "ProcessManager.h"
#include "MainWindow.h"
#include "../../stira/imagetools/tools/ImageTools.h"
#include "../dialogs/SimulateNoiseDialog.h"
#include "../dialogs/SimpleImageFilterDialog.h"
#include "../dialogs/LogGaborFilterDialog.h"
#include "../dialogs/AnisotropicDiffusionDialog.h"
#include "../dialogs/WatershedDialog.h"
#include "../dialogs/HoughTransformDialog.h"
#include "../dialogs/WienerDeconvolveDialog.h"
#include "../dialogs/RichardsonLucyDeconvolveDialog.h"
#include "../dialogs/GNCDeconvolveDialog.h"
#include "../dialogs/CannyDialog.h"
#include "../dialogs/ContrastEnhanceDialog.h"
#include "../dialogs/SplitBregmanDenoiseDialog.h"
#include "../dialogs/SteerableDenoisingDialog.h"
#include "../dialogs/SplitColorChannelsDialog.h"
#include "../curveplotter/ShowHistogramDialog.h"
#include "../curveplotter/ShowRadiallyAveragedFourierSpectrumDialog.h"
#include "../../stira/common/common/Point.h"
#include "../../stira/common/common/RectangularROI.h"
#include "../../stira/imagedata/simpletools/GridStatistics.h"
#include "../../stira/imagedata/datastructures/Image.h"
#include "../../stira/imagetools/tools/NumberGridTools.h"
#include "../../stira/imagetools/colortools/ColorBalancer.h"
#include "../../stira/fouriertools/fouriertools/FFT.h"
#include "../../stira/contrastenhance/contrastenhance/HistogramTools.h"
#include "../../stira/steerable/freemanadelson/ComputeSteerableFilteredImages.h"
#include "../../stira/imageanalysis/imageanalysis/HOG.h"
using namespace std;
using namespace stira::common;
using namespace stira::imagetools;
using namespace stira::imagedata;
using namespace stira::imageanalysis;
using namespace stira::steerable;
//==========================================================
ProcessManager::ProcessManager( stira::imagedata::Image* pImage )
{
mpImage = pImage;
CreateActions();
CreateMenus( );
}
//==========================================================
ProcessManager::~ProcessManager()
{
}
//==========================================================
void ProcessManager::SetImage( stira::imagedata::Image* pImage )
{
mpImage = pImage;
}
//==========================================================
std::vector<QMenu*> ProcessManager::GetMenus()
{
return mvSubMenus;
}
//==========================================================
void ProcessManager::CreateMenus( )
{
// FILTER
/////////////
mpSubMenuNoiseFilterProcess = new QMenu( tr ( "&Noise / Filter" ), 0);
mpSubMenuNoiseFilterProcess->addAction ( mpSimulateNoiseAction );
mpSubMenuNoiseFilterProcess->addAction ( mpLogGaborFilterAction );
mpSubMenuNoiseFilterProcess->addAction ( mpSimpleFilterAction );
mpSubMenuNoiseFilterProcess->addAction ( mpDiffusionAction );
mpSubMenuNoiseFilterProcess->addAction ( mpSplitBregmanDenoiseAction );
mpSubMenuNoiseFilterProcess->addAction ( mpWienerDeconvolveAction );
mpSubMenuNoiseFilterProcess->addAction ( mpRichardsonLucyDeconvolveAction );
mpSubMenuNoiseFilterProcess->addAction ( mpGNCDeconvolveAction );
mpSubMenuNoiseFilterProcess->addAction ( mpSteerableDenoiseAction );
mvSubMenus.push_back( mpSubMenuNoiseFilterProcess );
// COLOR
/////////////
mpSubMenuColor = new QMenu( tr ( "&Color / Contrast" ), 0 );
mpSubMenuColor->addAction ( mpContrastEnhanceAction );
mpSubMenuColor->addAction ( mpSplitChannelsAction );
mpSubMenuColor->addAction ( mpApplyJetColorMapAction );
mpSubMenuColor->addAction ( mpConvertToGrayAction );
mpSubMenuColor->addAction ( mpConvertToSepiaAction );
mpSubMenuColor->addAction ( mpColorBalanceAction );
mvSubMenus.push_back( mpSubMenuColor );
// PROPERTIES / ANALYSIS
////////////////////////
mpSubMenuProperties = new QMenu( tr ( "&Analysis / Properties" ), 0 );
mpSubMenuProperties->addAction ( mpShowHistogramAction );
mpSubMenuProperties->addAction ( mpFourierSpectrumAction );
mpSubMenuProperties->addAction ( mpRadiallyAveragedFourierSpectrumAction );
mpSubMenuProperties->addAction ( mpShowImagePropertiesAction );
mpSubMenuProperties->addAction ( mpWatershedAction );
mpSubMenuProperties->addAction ( mpHoughTransformAction );
mpSubMenuProperties->addAction ( mpCannyAction );
mpSubMenuProperties->addAction ( mpOrientationAnalysisAction );
mpSubMenuProperties->addAction ( mpHistogramOrientedGradientsAction );
mvSubMenus.push_back( mpSubMenuProperties );
}
//==========================================================
void ProcessManager::CreateActions()
{
// FILTER
///////////
mpSimulateNoiseAction = new QAction ( tr ( "&Simulate Noise" ), this );
mpSimulateNoiseAction->setShortcut ( tr ( "Ctrl+D" ) );
mpSimulateNoiseAction->setEnabled ( true );
connect ( mpSimulateNoiseAction, SIGNAL ( triggered() ), this, SLOT ( SlotSelectSimulateNoise() ) );
mpLogGaborFilterAction = new QAction ( tr ( "&Log Gabor Filter" ), this );
mpLogGaborFilterAction->setShortcut ( tr ( "Ctrl+L" ) );
mpLogGaborFilterAction->setEnabled ( true );
connect ( mpLogGaborFilterAction, SIGNAL ( triggered() ), this, SLOT ( SlotSelectLogGaborFilter() ) );
mpSimpleFilterAction = new QAction ( tr ( "&Simple Filter" ), this );
mpSimpleFilterAction->setShortcut ( tr ( "Ctrl+S" ) );
mpSimpleFilterAction->setEnabled ( true );
connect ( mpSimpleFilterAction, SIGNAL ( triggered() ), this, SLOT ( SlotSelectSimpleFilter() ) );
mpDiffusionAction = new QAction ( tr ( "&Anisotropic Diffusion" ), this );
mpDiffusionAction->setShortcut ( tr ( "Ctrl+A" ) );
mpDiffusionAction->setEnabled ( true );
connect ( mpDiffusionAction, SIGNAL ( triggered() ), this, SLOT ( SlotSelectAnisotropicDiffusion() ) );
mpSplitBregmanDenoiseAction = new QAction ( tr ( "&Split-Bregman TV Denoise" ), this );
mpSplitBregmanDenoiseAction->setShortcut ( tr ( "Ctrl+A" ) );
mpSplitBregmanDenoiseAction->setEnabled ( true );
connect ( mpSplitBregmanDenoiseAction, SIGNAL ( triggered() ), this, SLOT ( SlotSelectSplitBregmanDenoise() ) );
mpWienerDeconvolveAction = new QAction ( tr ( "&Wiener Deconvolution" ), this );
mpWienerDeconvolveAction->setShortcut ( tr ( "Ctrl+W" ) );
mpWienerDeconvolveAction->setEnabled ( true );
connect ( mpWienerDeconvolveAction, SIGNAL ( triggered() ), this, SLOT ( SlotSelectWienerDeconvolve() ) );
mpRichardsonLucyDeconvolveAction = new QAction ( tr ( "&Richardson-Lucy Deconvolution" ), this );
mpRichardsonLucyDeconvolveAction->setShortcut ( tr ( "Ctrl+R" ) );
mpRichardsonLucyDeconvolveAction->setEnabled ( true );
connect ( mpRichardsonLucyDeconvolveAction, SIGNAL ( triggered() ), this, SLOT ( SlotSelectRichardsonLucyDeconvolve() ) );
mpGNCDeconvolveAction = new QAction ( tr ( "&GNC-based Deconvolution" ), this );
mpGNCDeconvolveAction->setShortcut ( tr ( "Ctrl+G" ) );
mpGNCDeconvolveAction->setEnabled ( true );
connect ( mpGNCDeconvolveAction, SIGNAL ( triggered() ), this, SLOT ( SlotSelectGNCDeconvolve() ) );
mpSteerableDenoiseAction = new QAction ( tr ( "&Steerable Denoising" ), this );
mpSteerableDenoiseAction->setShortcut ( tr ( "Ctrl+D" ) );
mpSteerableDenoiseAction->setEnabled ( true );
connect ( mpSteerableDenoiseAction, SIGNAL ( triggered() ), this, SLOT ( SlotSelectSteerableDenoise() ) );
// COLOR
///////////
mpApplyJetColorMapAction = new QAction ( tr ( "Apply Jet Colormap" ), this );
mpApplyJetColorMapAction->setShortcut ( tr ( "Ctrl+J") );
mpApplyJetColorMapAction->setEnabled ( true );
connect ( mpApplyJetColorMapAction, SIGNAL ( triggered() ), this, SLOT ( SlotApplyJetColorMap() ) );
mpSplitChannelsAction = new QAction ( tr ( "Split Color Channels"), this );
mpSplitChannelsAction->setShortcut ( tr ( "Ctrl+A") );
connect ( mpSplitChannelsAction, SIGNAL ( triggered() ), this, SLOT ( SlotSplitChannels() ) );
mpConvertToGrayAction = new QAction ( tr ( "&Convert To Gray" ), this );
mpConvertToGrayAction->setEnabled ( true );
connect ( mpConvertToGrayAction, SIGNAL ( triggered() ), this, SLOT ( SlotConvertToGray() ) );
mpConvertToSepiaAction = new QAction ( tr ( "&Convert To Sepia" ), this );
mpConvertToSepiaAction->setEnabled ( true );
connect ( mpConvertToSepiaAction, SIGNAL ( triggered() ), this, SLOT ( SlotConvertToSepia() ) );
mpColorBalanceAction = new QAction ( tr ( "&Balance Colors" ), this );
mpColorBalanceAction->setEnabled ( true );
connect ( mpColorBalanceAction, SIGNAL ( triggered() ), this, SLOT ( SlotColorBalance() ) );
// CONTRAST
/////////////
mpContrastEnhanceAction = new QAction ( tr ( "Contrast &Enhance" ), this );
mpContrastEnhanceAction->setShortcut ( tr ( "Ctrl+E" ) );
mpContrastEnhanceAction->setEnabled ( true );
connect ( mpContrastEnhanceAction, SIGNAL ( triggered() ), this, SLOT ( SlotSelectContrastEnhance() ));
// PROPERTIES / ANALYSIS
/////////////////////////
mpShowHistogramAction = new QAction ( tr ( "&Plot Histogram" ), this );
mpShowHistogramAction->setShortcut ( tr ( "Ctrl+H" ) );
mpShowHistogramAction->setEnabled ( true );
connect ( mpShowHistogramAction, SIGNAL ( triggered() ), this, SLOT ( SlotShowHistogram() ) );
mpFourierSpectrumAction = new QAction ( tr ( "&Fourier Spectrum" ), this );
mpFourierSpectrumAction->setShortcut ( tr ( "Ctrl+F" ) );
mpFourierSpectrumAction->setEnabled ( true );
connect ( mpFourierSpectrumAction, SIGNAL ( triggered() ), this, SLOT ( SlotSelectCreateFourierSpectrum() ) );
mpRadiallyAveragedFourierSpectrumAction = new QAction ( tr ( "&Radially Averaged Fourier Spectrum" ), this );
mpRadiallyAveragedFourierSpectrumAction->setShortcut ( tr ( "Ctrl+R" ) );
mpRadiallyAveragedFourierSpectrumAction->setEnabled ( true );
connect ( mpRadiallyAveragedFourierSpectrumAction, SIGNAL ( triggered() ), this, SLOT ( SlotRadiallyAveragedFourierSpectrum() ) );
mpShowImagePropertiesAction = new QAction ( tr ( "&Show Image Properties" ), this );
mpShowImagePropertiesAction->setEnabled ( true );
connect ( mpShowImagePropertiesAction, SIGNAL ( triggered() ), this, SLOT ( SlotImageProperties() ) );
mpWatershedAction = new QAction ( tr ( "&Watershed" ), this );
mpWatershedAction->setShortcut ( tr ( "Ctrl+W" ) );
mpWatershedAction->setEnabled ( true );
connect ( mpWatershedAction, SIGNAL ( triggered() ), this, SLOT ( SlotSelectWatershedMeyer() ) );
mpHoughTransformAction = new QAction ( tr ( "&HoughTransform" ), this );
mpHoughTransformAction->setShortcut ( tr ( "Ctrl+H" ) );
mpHoughTransformAction->setEnabled ( true );
connect ( mpHoughTransformAction, SIGNAL ( triggered() ), this, SLOT ( SlotSelectHoughTransform() ) );
mpCannyAction = new QAction ( tr ( "&Canny Edge Detect" ), this );
mpCannyAction->setShortcut ( tr ( "Ctrl+C" ) );
mpCannyAction->setEnabled ( true );
connect ( mpCannyAction, SIGNAL ( triggered() ), this, SLOT ( SlotSelectCannyEdgeDetect() ) );
mpOrientationAnalysisAction = new QAction ( tr ( "&Analyse Orientations" ), this );
mpOrientationAnalysisAction->setEnabled ( true );
connect ( mpOrientationAnalysisAction, SIGNAL ( triggered() ), this, SLOT ( SlotAnalyseOrientations() ) );
mpHistogramOrientedGradientsAction = new QAction ( tr ( "&Histogram of Oriented Gradients" ), this );
mpHistogramOrientedGradientsAction->setEnabled ( true );
connect ( mpHistogramOrientedGradientsAction, SIGNAL ( triggered() ), this, SLOT ( SlotHistogramOrientedGradients() ) );
}
//------------------------------------------------------------------
void ProcessManager::SlotSelectAnisotropicDiffusion()
{
mpAnisotropicDiffusionDialog = new AnisotropicDiffusionDialog( mpImage );
}
//------------------------------------------------------------------
void ProcessManager::SlotSelectSplitBregmanDenoise()
{
mpSplitBregmanDenoiseDialog = new SplitBregmanDenoiseDialog( mpImage );
}
//------------------------------------------------------------------
void ProcessManager::SlotSelectWatershedMeyer()
{
mpWatershedDialog = new WatershedDialog ( mpImage );
mpWatershedDialog->show();
}
//------------------------------------------------------------------
void ProcessManager::SlotSelectHoughTransform()
{
mpHoughTransformDialog = new HoughTransformDialog ( mpImage );
mpHoughTransformDialog->show();
}
//------------------------------------------------------------------
void ProcessManager::SlotSelectCreateFourierSpectrum()
{
stira::fouriertools::FFT myFft;
int nrBands = mpImage->GetNumberOfBands();
int width = mpImage->GetWidth();
int height = mpImage->GetWidth();
Image* pImageOut = new Image( width, height );
for (int i = 0; i < nrBands; i++)
{
ArrayGrid<double>* pSpectrumGrid = myFft.ComputeLogPowerSpectrum ( mpImage->GetBands() [i] );
pImageOut->AddBand( pSpectrumGrid );
}
std::string outName = mpImage->GetImageName() + std::string("-FourierSpectrum");
pImageOut->SetImageName(outName);
ImageDataList::GetInstance()->AddImage( pImageOut );
}
//------------------------------------------------------------------
void ProcessManager::SlotApplyJetColorMap()
{
if ( mpImage->GetNumberOfBands() == 1 )
{
Image* pImageOut = ImageTools::ApplyJetColorMap( mpImage );
ImageDataList::GetInstance()->AddImage( pImageOut );
}
else
{
QMessageBox::information ( 0, tr ( "Error" ), tr ( "Jet Color map is only applicable to images with 1 band!!" ) );
}
}
//------------------------------------------------------------------
void ProcessManager::SlotSelectContrastEnhance()
{
mpContrastEnhanceDialog = new ContrastEnhanceDialog( mpImage );
}
//------------------------------------------------------------------
void ProcessManager::SlotSelectWienerDeconvolve()
{
mpWienerDeconvolveDialog = new WienerDeconvolveDialog ( mpImage );
mpWienerDeconvolveDialog->show();
}
//------------------------------------------------------------------
void ProcessManager::SlotSelectRichardsonLucyDeconvolve()
{
mpRichardsonLucyDeconvolveDialog = new RichardsonLucyDeconvolveDialog ( mpImage );
mpRichardsonLucyDeconvolveDialog->show();
}
//------------------------------------------------------------------
void ProcessManager::SlotSelectCannyEdgeDetect()
{
mpCannyDialog = new CannyDialog( mpImage );
mpCannyDialog->show();
}
//------------------------------------------------------------------
void ProcessManager::SlotSelectSteerableDenoise()
{
mpSteerableDenoisingDialog = new SteerableDenoisingDialog( mpImage );
mpSteerableDenoisingDialog->show();
}
//------------------------------------------------------------------
void ProcessManager::SlotSelectSimpleFilter()
{
mpSimpleImageFilterDialog = new SimpleImageFilterDialog( mpImage );
mpSimpleImageFilterDialog->show();
}
//------------------------------------------------------------------
void ProcessManager::SlotSelectSimulateNoise()
{
mpSimulateNoiseDialog = new SimulateNoiseDialog( mpImage );
mpSimulateNoiseDialog->show();
}
//------------------------------------------------------------------
void ProcessManager::SlotShowHistogram()
{
mpShowHistogramDialog = new ShowHistogramDialog( mpImage );
mpShowHistogramDialog->show();
}
//------------------------------------------------------------------
void ProcessManager::SlotRadiallyAveragedFourierSpectrum()
{
mpShowRadiallyAveragedFourierSpectrumDialog = new ShowRadiallyAveragedFourierSpectrumDialog( mpImage );
mpShowRadiallyAveragedFourierSpectrumDialog->show();
}
//------------------------------------------------------------------
void ProcessManager::SlotConvertToGray()
{
Image* pImageOut = ImageTools::ConvertToGrayImage( mpImage );
ImageDataList::GetInstance()->AddImage( pImageOut );
}
//------------------------------------------------------------------
void ProcessManager::SlotImageProperties()
{
QDialog* pDialog = new QDialog( 0, Qt::WindowStaysOnTopHint );
QVBoxLayout* pLayout = new QVBoxLayout( pDialog );
QLabel* pTitleLabel = new QLabel( QString("<B>Image properties</B> "), 0 );
std::string imageName = mpImage->GetImageName();
QLabel* pNameLabel = new QLabel( QString("Name: %1 " ).arg( imageName.c_str() ), 0 );
QLabel* pDimensionsLabel = new QLabel( QString("width: %1 \t height: %2" ).arg( mpImage->GetWidth() ).arg( mpImage->GetHeight() ), 0 );
int nrBands = mpImage->GetNumberOfBands();
QLabel* pNrBandsLabel = new QLabel( QString("Nr. bands: %1 " ).arg( nrBands ), 0 );
pLayout->addWidget( pTitleLabel );
pLayout->addWidget( pNameLabel );
pLayout->addWidget( pDimensionsLabel );
pLayout->addWidget( pNrBandsLabel );
for (int i = 0; i < nrBands; i++)
{
double mmin, mmax;
ArrayGrid<double>* pGrid = mpImage->GetBands()[i];
GridStatistics<double>::GetMinMax( pGrid, mmin, mmax);
double mean = GridStatistics<double>::GetGridMean( pGrid );
double var = GridStatistics<double>::GetGridVariance( pGrid, mean);
QLabel* pMinMaxLabel = new QLabel( QString("\t Band nr.: %1 \t min = %2 \t max = %3 \t mean = %4 \t variance = %5" ).arg( i ).arg( mmin ).arg( mmax ).arg( mean ).arg( var ), 0 );
pLayout->addWidget( pMinMaxLabel );
}
pDialog->show();
}
//------------------------------------------------------------------
void ProcessManager::SlotColorBalance()
{
if ( mpImage->GetNumberOfBands() == 3)
{
Image* pImageOut = ColorBalancer::RunBalance( mpImage );
Image* pImageOutScaled = stira::contrastenhance::HistogramTools::RobustLinearRescale( pImageOut, 0.03, 0.99 );
delete pImageOut;
ImageDataList::GetInstance()->AddImage( pImageOutScaled );
}
else
{
QMessageBox::information ( 0, tr ( "Error" ), tr ( "Need image with three bands for color balancing!!" ) );
}
}
//------------------------------------------------------------------
void ProcessManager::SlotSelectLogGaborFilter()
{
mpLogGaborFilterDialog = new LogGaborFilterDialog( mpImage );
mpLogGaborFilterDialog->show();
}
//------------------------------------------------------------------
void ProcessManager::SlotSelectGNCDeconvolve()
{
mpGNCDeconvolveDialog = new GNCDeconvolveDialog( mpImage );
mpGNCDeconvolveDialog->show();
}
//------------------------------------------------------------------
void ProcessManager::SlotConvertToSepia()
{
Image* pImageOut = ImageTools::ConvertToSepiaImage( mpImage );
ImageDataList::GetInstance()->AddImage( pImageOut );
}
//------------------------------------------------------------------
void ProcessManager::SlotSplitChannels()
{
mpSplitColorChannelsDialog = new SplitColorChannelsDialog( mpImage );
mpSplitColorChannelsDialog->show();
}
//------------------------------------------------------------------
void ProcessManager::SlotAnalyseOrientations()
{
ComputeSteerableFilteredImages csfi( mpImage->GetBands()[0] );
csfi.Run();
OrientationGrid* pGrid = csfi.GetOrientationGrid( ); // csfi is respon
ImageDataList::GetInstance()->AddImage( pGrid->VisualizeOrientationImage( 5 ) ); // ownership of this image is transfered through GetImage() to ImageDataList
ImageDataList::GetInstance()->AddImage( pGrid->VisualizeMagnitudeImage( ) ); // ownership of this image is transfered through GetImage() to ImageDataList
delete pGrid;
}
//------------------------------------------------------------------
void ProcessManager::SlotHistogramOrientedGradients()
{
int nrBins = 9;
int cellWidth = 8;
int cellHeight = 8;
double viz_factor = 3;
double scaleFactor = 1.0;
std::vector<double> descriptorValues;
RectangularROI<int> myRoi( 0, 0, mpImage->GetWidth() - 1, mpImage->GetHeight() - 1 );
HOG myHOG( mpImage, myRoi, cellWidth, cellHeight, nrBins);
myHOG.ComputeHogDescriptor( descriptorValues );
Image* pVisual = myHOG.VisualizeHogDescriptor( descriptorValues,
mpImage->GetWidth(), mpImage->GetHeight(),
scaleFactor, viz_factor);
ImageDataList::GetInstance()->AddImage( pVisual ); // ownership of this image is transfered through GetImage() to ImageDataList
}
//------------------------------------------------------------------
|
#include "C:\!!BITBUCKET\11l-lang\_11l_to_cpp\11l.hpp"
auto MAX_DIST = 1999999999.0;
auto PI_SOBRE_180 = 0.017453292;
auto PEQUENO = 0.000000001;
template <typename T1> auto colorToString(const T1 &c)
{
return u"#. #. #."_S.format(to_int(max(0.0, min(c.r * 255.0, 255.0))), to_int(max(0.0, min(c.g * 255.0, 255.0))), to_int(max(0.0, min(c.b * 255.0, 255.0))));
}
class Luz
{
public:
dvec3 posicion;
dvec3 color;
String tipo;
template <typename T1, typename T2, typename T3> Luz(const T1 &posicion, const T2 &color, const T3 &tipo) :
posicion(posicion),
color(color),
tipo(tipo)
{
}
};
class Material
{
public:
dvec3 color;
double cDifuso;
double cEspecular;
double dEspecular;
double cReflexion;
double cTransmitividad;
double iRefraccion;
template <typename T1, typename T2 = decltype(0.0), typename T3 = decltype(0.0), typename T4 = decltype(0.0), typename T5 = decltype(0.0), typename T6 = decltype(0.0), typename T7 = decltype(0.0)> Material(const T1 &color, const T2 &cDifuso = 0.0, const T3 &cEspecular = 0.0, const T4 &dEspecular = 0.0, const T5 &cReflexion = 0.0, const T6 &cTransmitividad = 0.0, const T7 &iRefraccion = 0.0) :
color(color),
cDifuso(cDifuso),
cEspecular(cEspecular),
dEspecular(dEspecular),
cReflexion(cReflexion),
cTransmitividad(cTransmitividad),
iRefraccion(iRefraccion)
{
}
};
class Cuerpo;
class Rayo
{
public:
dvec3 origen;
dvec3 direccion;
double disInter;
Cuerpo *objInter;
template <typename T1, typename T2> Rayo(const T1 &origen, const T2 &direccion) :
origen(origen),
direccion(direccion)
{
disInter = ::MAX_DIST;
objInter = nullptr;
}
};
class Cuerpo
{
public:
String tipo;
int material;
template <typename T1, typename T2> auto init(const T1 &tipo, const T2 &material)
{
this->tipo = tipo;
this->material = material;
}
virtual bool intersecta(Rayo &r) = 0;
virtual dvec3 getNormal(const dvec3 &punto) = 0;
};
class Esfera : public Cuerpo
{
public:
dvec3 posicion;
double radio;
template <typename T1, typename T2, typename T3> Esfera(const T1 &material, const T2 &posicion, const T3 &radio) :
posicion(posicion),
radio(radio)
{
init(u"esfera"_S, material);
}
virtual bool intersecta(Rayo &r) override
{
auto esfera_rayo = posicion - r.origen;
auto v = dot(esfera_rayo, r.direccion);
if (v - radio > r.disInter)
return false;
auto distChoque = radio * radio + v * v - esfera_rayo.x * esfera_rayo.x - esfera_rayo.y * esfera_rayo.y - esfera_rayo.z * esfera_rayo.z;
if (distChoque < 0.0)
return false;
distChoque = v - sqrt(distChoque);
if (distChoque > r.disInter || distChoque < 0.0)
return false;
r.disInter = distChoque;
r.objInter = &*this;
return true;
}
virtual dvec3 getNormal(const dvec3 &punto) override
{
auto normal = punto - posicion;
return normalize(normal);
}
};
class Plano : public Cuerpo
{
public:
dvec3 normal;
double distancia;
template <typename T1, typename T2, typename T3> Plano(const T1 &material, const T2 &normal, const T3 &distancia) :
distancia(distancia)
{
init(u"plano"_S, material);
this->normal = normalize(normal);
}
virtual bool intersecta(Rayo &r) override
{
auto v = dot(normal, r.direccion);
if (v == 0.0)
return false;
auto distChoque = -(dot(normal, r.origen) + distancia) / v;
if (distChoque < 0.0)
return false;
if (distChoque > r.disInter)
return false;
r.disInter = distChoque;
r.objInter = &*this;
return true;
}
virtual dvec3 getNormal(const dvec3 &punto) override
{
return normal;
}
};
class Scene
{
public:
int endline;
dvec3 posCamara;
dvec3 lookCamara;
dvec3 upCamara;
int anchoGrid;
int altoGrid;
dvec3 look;
dvec3 Vhor;
dvec3 Vver;
dvec3 Vp;
Array<std::unique_ptr<Cuerpo>> lObjetos;
Array<Luz> lLuces;
Array<Material> lMateriales;
decltype(320) imgAncho = 320;
decltype(200) imgAlto = 200;
decltype(3) profTrazado = 3;
decltype(1) oversampling = 1;
decltype(60.0) campoVision = 60.0;
decltype(0) startline = 0;
template <typename T1> Scene(const T1 &scene_filename)
{
auto lines = File(scene_filename).read_lines(true).filter([](const auto &l){return l.trim(make_tuple(u" "_S, u"\t"_S, u"\r"_S, u"\n"_S)) != u"" && _get<0>(l.trim(make_tuple(u" "_S, u"\t"_S, u"\r"_S, u"\n"_S))) != u'#';}).map([](const auto &l){return l.split_py();});
endline = imgAlto - 1;
for (auto &&line : lines) {
auto word = _get<0>(line);
line = line[range_ei(1)];
if (word == u"size") {
imgAncho = to_int(_get<0>(line));
imgAlto = to_int(_get<1>(line));
endline = imgAlto - 1;
}
else if (word == u"nbounces")
profTrazado = to_int(_get<0>(line));
else if (word == u"oversampling")
oversampling = to_int(_get<0>(line));
else if (word == u"vision")
campoVision = to_float(_get<0>(line));
else if (word == u"renderslice") {
startline = max(0, to_int(_get<0>(line)));
endline = min(imgAlto - 1, to_int(_get<1>(line)));
}
else if (word == u"posCamara")
posCamara = parse_vector(line);
else if (word == u"lookCamara")
lookCamara = parse_vector(line);
else if (word == u"upCamara")
upCamara = parse_vector(line);
else if (word == u"sphere") {
auto sph = std::make_unique<Esfera>(to_int(_get<0>(line)), parse_vector(line[range_el(1, 4)]), to_float(line.last()));
lObjetos.append(std::move(sph));
}
else if (word == u"plano") {
auto pl = std::make_unique<Plano>(to_int(_get<0>(line)), parse_vector(line[range_el(1, 4)]), to_float(line.last()));
lObjetos.append(std::move(pl));
}
else if (word == u"light") {
auto light = Luz(parse_vector(line[range_el(0, 3)]), parse_color(line[range_el(3, 6)]), line.last());
lLuces.append(light);
}
else if (word == u"material") {
auto mat = parse_material(line);
lMateriales.append(mat);
}
}
anchoGrid = imgAncho * oversampling;
altoGrid = imgAlto * oversampling;
look = lookCamara - posCamara;
Vhor = normalize(cross(upCamara, look));
Vver = normalize(cross(Vhor, look));
auto fl = anchoGrid / (2 * tan((0.5 * campoVision) * ::PI_SOBRE_180));
auto Vp = normalize(look);
Vp.x = Vp.x * fl - 0.5 * (anchoGrid * Vhor.x + altoGrid * Vver.x);
Vp.y = Vp.y * fl - 0.5 * (anchoGrid * Vhor.y + altoGrid * Vver.y);
Vp.z = Vp.z * fl - 0.5 * (anchoGrid * Vhor.z + altoGrid * Vver.z);
this->Vp = Vp;
}
template <typename T1> auto parse_vector(const T1 &line)
{
return make_tuple(to_float(_get<0>(line)), to_float(_get<1>(line)), to_float(_get<2>(line)));
}
template <typename T1> auto parse_color(const T1 &line)
{
return make_tuple(to_float(_get<0>(line)), to_float(_get<1>(line)), to_float(_get<2>(line)));
}
template <typename T1> auto parse_material(const T1 &line)
{
auto f = line[range_ei(3)].map([](const auto &x){return to_float(x);});
return Material(parse_color(line[range_el(0, 3)]), _get<0>(f), _get<1>(f), _get<2>(f), _get<3>(f), _get<4>(f), _get<5>(f));
}
};
auto scene_namefile = u"testdata/scene.txt"_S;
auto scene = Scene(scene_namefile);
template <typename T2> auto calculaSombra(Rayo &r, const T2 &objChoque)
{
auto sombra = 1.0;
for (auto &&obj : ::scene.lObjetos) {
r.objInter = nullptr;
r.disInter = ::MAX_DIST;
if (obj->intersecta(r) && &*obj != objChoque)
sombra *= ::scene.lMateriales[obj->material].cTransmitividad;
}
return sombra;
}
template <typename T2> dvec3 trazar(Rayo &r, const T2 &prof)
{
auto c = make_tuple(0.0, 0.0, 0.0);
for (auto &&obj : ::scene.lObjetos)
obj->intersecta(r);
if (r.objInter != nullptr) {
auto matIndex = r.objInter->material;
auto pInterseccion = r.origen + r.direccion * r.disInter;
auto vIncidente = pInterseccion - r.origen;
auto vVueltaOrigen = normalize(r.direccion * -1.0);
auto vNormal = r.objInter->getNormal(pInterseccion);
for (auto &&luz : ::scene.lLuces)
if (luz.tipo == u"ambiental")
c += luz.color;
else if (luz.tipo == u"puntual") {
auto dirLuz = normalize(luz.posicion - pInterseccion);
auto rayoLuz = Rayo(pInterseccion, dirLuz);
auto sombra = calculaSombra(rayoLuz, r.objInter);
auto NL = dot(vNormal, dirLuz);
if (NL > 0.0) {
if (::scene.lMateriales[matIndex].cDifuso > 0.0) {
auto colorDifuso = luz.color * ::scene.lMateriales[matIndex].cDifuso * NL;
colorDifuso.r *= ::scene.lMateriales[matIndex].color.r * sombra;
colorDifuso.g *= ::scene.lMateriales[matIndex].color.g * sombra;
colorDifuso.b *= ::scene.lMateriales[matIndex].color.b * sombra;
c += colorDifuso;
}
if (::scene.lMateriales[matIndex].cEspecular > 0.0) {
auto rr = (vNormal * 2 * NL) - dirLuz;
auto espec = dot(vVueltaOrigen, rr);
if (espec > 0.0) {
espec = ::scene.lMateriales[matIndex].cEspecular * pow(espec, ::scene.lMateriales[matIndex].dEspecular);
auto colorEspecular = luz.color * espec * sombra;
c += colorEspecular;
}
}
}
}
if (prof < ::scene.profTrazado) {
if (::scene.lMateriales[matIndex].cReflexion > 0.0) {
auto t = dot(vVueltaOrigen, vNormal);
if (t > 0.0) {
auto vDirRef = (vNormal * 2 * t) - vVueltaOrigen;
auto vOffsetInter = pInterseccion + vDirRef * ::PEQUENO;
auto rayoRef = Rayo(vOffsetInter, vDirRef);
c += trazar(rayoRef, prof + 1.0) * ::scene.lMateriales[matIndex].cReflexion;
}
}
if (::scene.lMateriales[matIndex].cTransmitividad > 0.0) {
auto RN = dot(vNormal, vIncidente * -1.0);
double n1;
double n2;
vIncidente = normalize(vIncidente);
if (dot(vNormal, vIncidente) > 0.0) {
vNormal = vNormal * -1.0;
RN = -RN;
n1 = ::scene.lMateriales[matIndex].iRefraccion;
n2 = 1.0;
}
else {
n2 = ::scene.lMateriales[matIndex].iRefraccion;
n1 = 1.0;
}
if (n1 != 0.0 && n2 != 0.0) {
auto par_sqrt = sqrt(1 - (n1 * n1 / n2 * n2) * (1 - RN * RN));
auto vDirRefrac = vIncidente + (vNormal * RN) * (n1 / n2) - (vNormal * par_sqrt);
auto vOffsetInter = pInterseccion + vDirRefrac * ::PEQUENO;
auto rayoRefrac = Rayo(vOffsetInter, vDirRefrac);
c += trazar(rayoRefrac, prof + 1.0) * ::scene.lMateriales[matIndex].cTransmitividad;
}
}
}
}
return c;
}
template <typename T1, typename T2> auto renderPixel(T1 x, T2 y)
{
auto c = make_tuple(0.0, 0.0, 0.0);
x *= ::scene.oversampling;
y *= ::scene.oversampling;
for (auto i : range_el(0, ::scene.oversampling)) {
for (auto j : range_el(0, ::scene.oversampling)) {
dvec3 direc;
direc.x = x * ::scene.Vhor.x + y * ::scene.Vver.x + ::scene.Vp.x;
direc.y = x * ::scene.Vhor.y + y * ::scene.Vver.y + ::scene.Vp.y;
direc.z = x * ::scene.Vhor.z + y * ::scene.Vver.z + ::scene.Vp.z;
auto r = Rayo(::scene.posCamara, normalize(direc));
c += trazar(r, 1.0);
y++;
}
x++;
}
auto srq_oversampling = ::scene.oversampling * ::scene.oversampling;
c.r /= srq_oversampling;
c.g /= srq_oversampling;
c.b /= srq_oversampling;
return c;
}
int main()
{
print(u"Rendering: "_S & scene_namefile);
auto fileout = File(scene_namefile & u".ppm"_S, u"w"_S);
fileout.write(u"P3\n"_S);
fileout.write(String(scene.imgAncho) & u" "_S & String(scene.endline - scene.startline + 1) & u"\n"_S);
fileout.write(u"255\n"_S);
print(u"Line (from #.0 to #.0):"_S.format(scene.startline, scene.endline), u" "_S);
for (auto y : range_el(scene.startline, scene.endline + 1)) {
for (auto x : range_el(0, scene.imgAncho))
fileout.write(colorToString(renderPixel(x, y)) & u" "_S);
fileout.write(u"\n"_S);
print(y, u" "_S);
_stdout.flush();
}
}
|
#include "InitState.h"
void InitState::entry(void) {
std::cout
<< "==================================" << endl
<< " WELCOME TO THE TEST STATE MACHINE" << endl
<< "==================================" << endl
<< endl
<< "========================" << endl
<< " PRESS S to start program" << endl
<< "========================" << endl;
}
void InitState::during(void) {
}
void InitState::exit(void) {
robot->initPositionControl();
std::cout << "Initialise State Exited" << endl;
}
|
/*
* Copyright (c) 2014 The WebM project authors. All Rights Reserved.
*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "WebMFileWriter.h"
#include <string>
#include "mkvmuxer/mkvmuxerutil.h"
namespace mozilla {
WebMFileWriter::WebMFileWriter(FILE* file, vpx_codec_enc_cfg_t* cfg)
: m_cfg(cfg)
, m_writer(new mkvmuxer::MkvWriter(file))
, m_segment(new mkvmuxer::Segment()) {
m_segment->Init(m_writer.get());
m_segment->set_mode(mkvmuxer::Segment::kFile);
m_segment->OutputCues(true);
mkvmuxer::SegmentInfo* info = m_segment->GetSegmentInfo();
std::string version = "Playwright " + std::string(vpx_codec_version_str());
info->set_writing_app(version.c_str());
// Add vp8 track.
m_videoTrackId = m_segment->AddVideoTrack(
static_cast<int>(m_cfg->g_w), static_cast<int>(m_cfg->g_h), 0);
if (!m_videoTrackId) {
fprintf(stderr, "Failed to add video track\n");
}
}
WebMFileWriter::~WebMFileWriter() {}
void WebMFileWriter::writeFrame(const vpx_codec_cx_pkt_t* pkt) {
int64_t pts_ns = pkt->data.frame.pts * 1000000000ll * m_cfg->g_timebase.num /
m_cfg->g_timebase.den;
m_segment->AddFrame(static_cast<uint8_t*>(pkt->data.frame.buf),
pkt->data.frame.sz, m_videoTrackId, pts_ns,
pkt->data.frame.flags & VPX_FRAME_IS_KEY);
}
void WebMFileWriter::finish() {
m_segment->Finalize();
}
} // namespace mozilla
|
#include <fstream>
using namespace std;
ifstream f("ec.in");
ofstream g("ec.out");
int a,b,x;
int main()
{
f>>a>>b;
if(a)
{
x=-b/a;
g<<x<<endl;
}
else if(a==0&&b==0) g<<"Infinitate solutii"<<endl;
else g<<"Nu are solutii"<<endl;
f.close();
g.close();
return 0;
}
|
//-----------------------------------------------------------------------------
// Software that is described herein is for illustrative purposes only
// which provides customers with programming information regarding the
// products. This software is supplied "AS IS" without any warranties.
// NXP Semiconductors assumes no responsibility or liability for the
// use of the software, conveys no license or title under any patent,
// copyright, or mask work right to the product. NXP Semiconductors
// reserves the right to make changes in the software without
// notification. NXP Semiconductors also make no representation or
// warranty that such application will be suitable for the specified
// use without further testing or modification.
//-----------------------------------------------------------------------------
#include <tinyhal.h>
#include "..\LPC22XX.h"
///////////////////////////////////////////////////////////////////////////////
#if defined(ADS_LINKER_BUG__NOT_ALL_UNUSED_VARIABLES_ARE_REMOVED)
#pragma arm section zidata = "g_LPC22XX_I2C_Driver"
#endif
LPC22XX_I2C_Driver g_LPC22XX_I2C_Driver;
#if defined(ADS_LINKER_BUG__NOT_ALL_UNUSED_VARIABLES_ARE_REMOVED)
#pragma arm section zidata
#endif
//--//
BOOL I2C_Internal_Initialize()
{
return LPC22XX_I2C_Driver::Initialize();
}
BOOL I2C_Internal_Uninitialize()
{
return LPC22XX_I2C_Driver::Uninitialize();
}
void I2C_Internal_XActionStart( I2C_HAL_XACTION* xAction, bool repeatedStart )
{
LPC22XX_I2C_Driver::MasterXAction_Start( xAction, repeatedStart );
}
void I2C_Internal_XActionStop()
{
LPC22XX_I2C_Driver::MasterXAction_Stop();
}
void I2C_Internal_GetClockRate( UINT32 rateKhz, UINT8& clockRate, UINT8& clockRate2)
{
clockRate = LPC22XX_I2C_Driver::GetClockRate( rateKhz );
//clockrate2 not use.
clockRate2 = 0;
}
void I2C_Internal_GetPins(GPIO_PIN& scl, GPIO_PIN& sda)
{
return LPC22XX_I2C_Driver::GetPins( scl, sda);
}
//--//
BOOL LPC22XX_I2C_Driver::Initialize()
{
LPC22XX_I2C& I2C = LPC22XX::I2C();
if(g_LPC22XX_I2C_Driver.m_initialized == FALSE)
{
g_LPC22XX_I2C_Driver.m_currentXAction = NULL;
g_LPC22XX_I2C_Driver.m_currentXActionUnit = NULL;
CPU_INTC_ActivateInterrupt( LPC22XX_VIC::c_IRQ_INDEX_I2C, &LPC22XX_I2C_Driver::ISR, NULL );
// enable the I2c module
I2C.I2CONSET = LPC22XX_I2C::I2EN;
// set the Subordinate address
I2C.I2ADR = 0x7E;
g_LPC22XX_I2C_Driver.m_initialized = TRUE;
}
// even if the driver is initialized already we should still change the pins
// to their i2c function, in case they have been stolen by another peripheral
CPU_GPIO_DisablePin( LPC22XX_I2C::c_I2C_SDA, RESISTOR_DISABLED, 0, GPIO_ALT_MODE_1 );
CPU_GPIO_DisablePin( LPC22XX_I2C::c_I2C_SCL, RESISTOR_DISABLED, 0, GPIO_ALT_MODE_1 );
return TRUE;
}
BOOL LPC22XX_I2C_Driver::Uninitialize()
{
LPC22XX_I2C& I2C = LPC22XX::I2C();
if(g_LPC22XX_I2C_Driver.m_initialized == TRUE)
{
CPU_INTC_DeactivateInterrupt( LPC22XX_VIC::c_IRQ_INDEX_I2C );
I2C.I2CONCLR = ( LPC22XX_I2C::AA | LPC22XX_I2C::SI | LPC22XX_I2C::STO | LPC22XX_I2C::STA | LPC22XX_I2C::I2EN );
g_LPC22XX_I2C_Driver.m_initialized = FALSE;
}
return TRUE;
}
void LPC22XX_I2C_Driver::MasterXAction_Start( I2C_HAL_XACTION* xAction, bool repeatedStart )
{
LPC22XX_I2C& I2C = LPC22XX::I2C();
g_LPC22XX_I2C_Driver.m_currentXAction = xAction;
g_LPC22XX_I2C_Driver.m_currentXActionUnit = xAction->m_xActionUnits[ xAction->m_current ]; ++xAction->m_current;
if(!repeatedStart)
{
/////////////////////////////////
// Start sequence
I2C.I2SCLH = xAction->m_clockRate ;
I2C.I2SCLL = xAction->m_clockRate ;
I2C.I2CONSET = LPC22XX_I2C::STA;
// Start sequence
/////////////////////////////////
}
else
{
/////////////////////////////////
// Repeated start sequence
I2C.I2CONSET = LPC22XX_I2C::STA;
// Repeated start sequence
/////////////////////////////////
}
}
void LPC22XX_I2C_Driver::MasterXAction_Stop()
{
LPC22XX_I2C& I2C = LPC22XX::I2C();
// unset all flags that depend on the xaction flow
I2C.I2CONSET = LPC22XX_I2C::STO;
I2C.I2CONCLR = LPC22XX_I2C::AA | LPC22XX_I2C::SI | LPC22XX_I2C::STA;
g_LPC22XX_I2C_Driver.m_currentXAction = NULL;
g_LPC22XX_I2C_Driver.m_currentXActionUnit = NULL;
}
UINT8 LPC22XX_I2C_Driver::GetClockRate( UINT32 rateKhz )
{
UINT32 divider = LPC22XX_I2C::c_I2C_Clk_KHz / ( 2 * rateKhz );
return (UINT8) divider;
}
void LPC22XX_I2C_Driver::WriteToSubordinate( I2C_HAL_XACTION_UNIT* unit )
{
UINT8* queueData;
LPC22XX_I2C& I2C = LPC22XX::I2C();
queueData = unit->m_dataQueue.Pop();
I2C.I2DAT = *queueData;
++unit->m_bytesTransferred;
--unit->m_bytesToTransfer;
}
void LPC22XX_I2C_Driver::ReadFromSubordinate( I2C_HAL_XACTION_UNIT* unit )
{
UINT8* queueData;
LPC22XX_I2C& I2C = LPC22XX::I2C();
queueData = unit->m_dataQueue.Push();
ASSERT(queueData);
UINT8 data = I2C.I2DAT;
*queueData = data;
++unit->m_bytesTransferred;
--unit->m_bytesToTransfer;
}
void LPC22XX_I2C_Driver::ISR( void* arg )
{
UINT8 address;
LPC22XX_I2C& I2C = LPC22XX::I2C();
// read status
volatile UINT32 status;
status = (I2C.I2STAT & 0xFF);
I2C_HAL_XACTION* xAction = g_LPC22XX_I2C_Driver.m_currentXAction;
I2C_HAL_XACTION_UNIT* unit = g_LPC22XX_I2C_Driver.m_currentXActionUnit;
ASSERT(xAction);
ASSERT(unit);
switch(status)
{
case 0x08: // Start Condition transmitted
case 0x10: // Repeated Start Condition transmitted
// Write Subordinate address and Data direction
address = 0xFE & (xAction->m_address << 1);
address |= unit->IsReadXActionUnit() ? LPC22XX_I2C_Driver::c_DirectionRead : LPC22XX_I2C_Driver::c_DirectionWrite;
I2C.I2DAT = address;
// Clear STA bit
I2C.I2CONCLR = LPC22XX_I2C::STA;
break;
case 0x18: // Subordinate Address + W transmitted, Ack received
case 0x28: // Data transmitted, Ack received
// Write data
// transaction completed
if(unit->m_bytesToTransfer == 0)
{
if(xAction->ProcessingLastUnit())
{
xAction->Signal( I2C_HAL_XACTION::c_Status_Completed );
}
else
{
MasterXAction_Start( xAction, true );
}
}
else
{
WriteToSubordinate( unit );
}
break;
case 0x20: // Write Address not acknowledged by Subordinate
case 0x30: // Data not acknowledged by Subordinate
case 0x48: // Read Address not acknowledged by Subordinate
xAction->Signal( I2C_HAL_XACTION::c_Status_Aborted );
break;
case 0x38: // Arbitration lost
xAction->Signal( I2C_HAL_XACTION::c_Status_Aborted );
break;
case 0x40: // Subordinate Address + R transmitted, Ack received
// if the transaction is one byte only to read, then we must send NAK immediately
if(unit->m_bytesToTransfer == 1)
{
I2C.I2CONCLR = LPC22XX_I2C::AA;
}
else
{
I2C.I2CONSET = LPC22XX_I2C::AA;
}
break;
case 0x50: // Data received, Ack Sent
case 0x58: // Data received, NO Ack sent
// read next byte
ReadFromSubordinate( unit );
if(unit->m_bytesToTransfer == 1)
{
I2C.I2CONCLR = LPC22XX_I2C::AA;
}
if(unit->m_bytesToTransfer == 0)
{
if(xAction->ProcessingLastUnit())
{
// send transaction stop
xAction->Signal( I2C_HAL_XACTION::c_Status_Completed );
}
else
{
// start next
MasterXAction_Start( xAction, true );
}
}
break;
case 0x00: // Bus Error
// Clear Bus error
I2C.I2CONSET = LPC22XX_I2C::STO;
xAction->Signal( I2C_HAL_XACTION::c_Status_Aborted );
break;
default:
xAction->Signal( I2C_HAL_XACTION::c_Status_Aborted );
break;
} // switch(status)
// clear the interrupt flag to start the next I2C transfer
I2C.I2CONCLR = LPC22XX_I2C::SI;
}
void LPC22XX_I2C_Driver::GetPins(GPIO_PIN& scl, GPIO_PIN& sda)
{
scl = LPC22XX_I2C::c_I2C_SCL;
sda = LPC22XX_I2C::c_I2C_SDA;
}
|
// Boost string_algo library collection_traits.hpp header file -------------//
// Copyright Pavol Droba 2002-2003. 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)
// (C) Copyright Thorsten Ottosen 2002-2003. 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)
// (C) Copyright Jeremy Siek 2001. 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)
// Original idea of container traits was proposed by Jeremy Siek and
// Thorsten Ottosen. This implementation is lightweighted version
// of container_traits adapter for usage with string_algo library
#ifndef BOOST_RANGE_STRING_COLLECTION_TRAITS_HPP
#define BOOST_RANGE_STRING_COLLECTION_TRAITS_HPP
#include <boost/type_traits/is_array.hpp>
#include <boost/type_traits/is_pointer.hpp>
#include <boost/mpl/eval_if.hpp>
// Implementation
#include <boost/range/detail/collection_traits_detail.hpp>
/*! \file
Defines collection_traits class and related free-standing functions.
This facility is used to unify the access to different types of collections.
It allows the algorithms in the library to work with STL collections, c-style
array, null-terminated c-strings (and more) using the same interface.
*/
namespace boost {
namespace algorithm {
// collection_traits template class -----------------------------------------//
//! collection_traits class
/*!
Collection traits provide uniform access to different types of
collections. This functionality allows to write generic algorithms
which work with several different kinds of collections.
Currently following collection types are supported:
- containers with STL compatible container interface ( see ContainerConcept )
( i.e. \c std::vector<>, \c std::list<>, \c std::string<> ... )
- c-style array
( \c char[10], \c int[15] ... )
- null-terminated c-strings
( \c char*, \c wchar_T* )
- std::pair of iterators
( i.e \c std::pair<vector<int>::iterator,vector<int>::iterator> )
Collection traits provide an external collection interface operations.
All are accessible using free-standing functions.
The following operations are supported:
- \c size()
- \c empty()
- \c begin()
- \c end()
Container traits have somewhat limited functionality on compilers not
supporting partial template specialization and partial template ordering.
*/
template< typename T >
struct collection_traits
{
private:
typedef typename ::boost::mpl::eval_if<
::boost::algorithm::detail::is_pair<T>,
detail::pair_container_traits_selector<T>,
typename ::boost::mpl::eval_if<
::boost::is_array<T>,
detail::array_container_traits_selector<T>,
typename ::boost::mpl::eval_if<
::boost::is_pointer<T>,
detail::pointer_container_traits_selector<T>,
detail::default_container_traits_selector<T>
>
>
>::type container_helper_type;
public:
//! Function type
typedef container_helper_type function_type;
//! Value type
typedef typename
container_helper_type::value_type value_type;
//! Size type
typedef typename
container_helper_type::size_type size_type;
//! Iterator type
typedef typename
container_helper_type::iterator iterator;
//! Const iterator type
typedef typename
container_helper_type::const_iterator const_iterator;
//! Result iterator type ( iterator of const_iterator, depending on the constness of the container )
typedef typename
container_helper_type::result_iterator result_iterator;
//! Difference type
typedef typename
container_helper_type::difference_type difference_type;
}; // 'collection_traits'
// collection_traits metafunctions -----------------------------------------//
//! Container value_type trait
/*!
Extract the type of elements contained in a container
*/
template< typename C >
struct value_type_of
{
typedef typename collection_traits<C>::value_type type;
};
//! Container difference trait
/*!
Extract the container's difference type
*/
template< typename C >
struct difference_type_of
{
typedef typename collection_traits<C>::difference_type type;
};
//! Container iterator trait
/*!
Extract the container's iterator type
*/
template< typename C >
struct iterator_of
{
typedef typename collection_traits<C>::iterator type;
};
//! Container const_iterator trait
/*!
Extract the container's const_iterator type
*/
template< typename C >
struct const_iterator_of
{
typedef typename collection_traits<C>::const_iterator type;
};
//! Container result_iterator
/*!
Extract the container's result_iterator type. This type maps to \c C::iterator
for mutable container and \c C::const_iterator for const containers.
*/
template< typename C >
struct result_iterator_of
{
typedef typename collection_traits<C>::result_iterator type;
};
// collection_traits related functions -----------------------------------------//
//! Free-standing size() function
/*!
Get the size of the container. Uses collection_traits.
*/
template< typename C >
inline typename collection_traits<C>::size_type
size( const C& c )
{
return collection_traits<C>::function_type::size( c );
}
//! Free-standing empty() function
/*!
Check whether the container is empty. Uses container traits.
*/
template< typename C >
inline bool empty( const C& c )
{
return collection_traits<C>::function_type::empty( c );
}
#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
//! Free-standing begin() function
/*!
Get the begin iterator of the container. Uses collection_traits.
*/
template< typename C >
inline typename collection_traits<C>::iterator
begin( C& c )
{
return collection_traits<C>::function_type::begin( c );
}
//! Free-standing begin() function
/*!
\overload
*/
template< typename C >
inline typename collection_traits<C>::const_iterator
begin( const C& c )
{
return collection_traits<C>::function_type::begin( c );
}
//! Free-standing end() function
/*!
Get the begin iterator of the container. Uses collection_traits.
*/
template< typename C >
inline typename collection_traits<C>::iterator
end( C& c )
{
return collection_traits<C>::function_type::end( c );
}
//! Free-standing end() function
/*!
\overload
*/
template< typename C >
inline typename collection_traits<C>::const_iterator
end( const C& c )
{
return collection_traits<C>::function_type::end( c );
}
#else // BOOST_NO_FUNCTION_TEMPLATE_ORDERING
//! Free-standing begin() function
/*!
\overload
*/
template< typename C >
inline typename collection_traits<C>::result_iterator
begin( C& c )
{
return collection_traits<C>::function_type::begin( c );
}
//! Free-standing end() function
/*!
\overload
*/
template< typename C >
inline typename collection_traits<C>::result_iterator
end( C& c )
{
return collection_traits<C>::function_type::end( c );
}
#endif // BOOST_NO_FUNCTION_TEMPLATE_ORDERING
} // namespace algorithm
} // namespace boost
#endif // BOOST_STRING_COLLECTION_TRAITS_HPP
|
/*
*************************************************************************
*
* PCX_COMM.C - PCX_LIB Library Common Functions
*
* Version: 1.00B
*
* History: 91/02/14 - Created
* 91/04/01 - Release 1.00A
* 91/04/03 - fixed "segread" call.
* 91/04/07 - Release 1.00B
*
* Compiler: Microsoft C V6.0
*
* Author: Ian Ashdown, P.Eng.
* byHeart Software
* 620 Ballantree Road
* West Vancouver, B.C.
* Canada V7S 1W3
* Tel. (604) 922-6148
* Fax. (604) 987-7621
*
* Copyright: Public Domain
*
*************************************************************************
*/
/*
*************************************************************************
*
* PORTABILITY NOTES
*
* 1. While this program is written in ANSI C, it uses a number of
* function calls that are specific to the Microsoft C V6.0 library.
* These are documented as follows for the purposes of porting this
* program to other compilers and/or processors:
*
* int86x - execute 80x86 interrupt routine (far data)
* segread - get current 80x86 segment register values
*
*************************************************************************
*/
/* INCLUDE FILES */
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include "pcx_int.h"
/* FORWARD REFERENCES */
/* GLOBALS */
/* PUBLIC FUNCTIONS */
/*
*************************************************************************
*
* PCX_OPEN - Open PCX Workblock
*
* Purpose: To allocate and initialize a PCX image file workblock.
*
* Setup: PCX_WORKBLK *pcx_open
* (
* char *fname,
* BOOL wrt_flag
* )
*
* Where: fname is a PCX image file name.
* wrt_flag is a Boolean flag which if TRUE indicates that
* the PCX image file is to be opened for writing;
* otherwise it is opened for reading.
*
* Return: A pointer to a PCX image file workblock if successful;
* otherwise NULL.
*
*************************************************************************
*/
PCX_WORKBLK *pcx_open
(
char *fname,
BOOL wrt_flag
)
{
PCX_WORKBLK *wbp; /* PCX image file workblock pointer */
/* Allocate a workblock */
if ((wbp = (PCX_WORKBLK *) malloc(sizeof(PCX_WORKBLK))) == NULL)
return (NULL);
/* Open the PCX image file in binary mode */
if (wrt_flag == FALSE)
wbp->fp = fopen(fname, "rb"); /* Open for reading */
else
wbp->fp = fopen(fname, "wb"); /* Open for writing */
if (wbp->fp == NULL) /* Check for successful file opening */
{
free(wbp); /* Free the workblock memory */
return (NULL);
}
return (wbp); /* Return the workblock pointer */
}
/*
*************************************************************************
*
* PCX_CLOSE - Close PCX Workblock
*
* Purpose: To close a PCX image file and release its workblock
* memory.
*
* Setup: BOOL pcx_close
* (
* PCX_WORKBLK *wbp
* )
*
* Where: wbp is a PCX image file workblock pointer.
*
* Return: TRUE if successful; otherwise FALSE.
*
*************************************************************************
*/
BOOL pcx_close
(
PCX_WORKBLK *wbp
)
{
free(wbp->palettep); /* Free the extended palette (if it exists) */
free(wbp); /* Free the PCX image file workblock */
if (fclose(wbp->fp) == EOF) /* Close the PCX image file */
return (FALSE);
return (TRUE);
}
/*
*************************************************************************
*
* PCX_ISVGA - Check For VGA Display Adapter
*
* Purpose: To determine whether a display adapter supports VGA BIOS
* service routines.
*
* Setup: BOOL pcx_isvga(void)
*
* Return: TRUE if display adapter is VGA-compatible; otherwise
* FALSE.
*
*************************************************************************
*/
BOOL pcx_isvga(void)
{
unsigned char *vinfop; /* VGA information buffer pointer */
union REGS regs; /* 80x86 register values */
struct SREGS sregs; /* 80x86 segment register values */
/* Allocate a VGA functionality/state information buffer */
if ((vinfop = (unsigned char *) malloc(sizeof(unsigned char) * 64)) ==
NULL)
return (FALSE);
/* Attempt to read the VGA information */
regs.h.ah = 0x1b; /* Select "Return VGA Info" BIOS routine */
regs.x.bx = 0; /* Implementation type */
/* Get the VGA information buffer offset value */
regs.x.di = (unsigned int) vinfop;
segread(&sregs); /* Get the current DS segment register value */
sregs.es = sregs.ds;
int86x(0x10, ®s, ®s, &sregs); /* Call BIOS video service */
free(vinfop); /* Free the VGA information buffer */
/* The value 0x1b is returned in register AL only if a VGA display */
/* adapter is present */
if (regs.h.al == 0x1b)
return (TRUE);
else
return (FALSE);
}
|
/*
* SPDX-License-Identifier: Apache-2.0
*/
#include "sandstone_context_dump.h"
#include "sandstone.h"
#include "amx_common.h"
#include "cpu_features.h"
#include "fp_vectors/Floats.h"
#include <algorithm>
#include <limits>
#ifdef __unix__
# include <dlfcn.h>
#endif
#include <immintrin.h>
#include <inttypes.h>
#include <string.h>
#include <x86intrin.h>
#ifndef signature_INTEL_ebx
# include <cpuid.h>
#endif
union xmmreg
{
__m128 f;
__m128d d;
__m128i i;
__uint128_t u;
};
union ymmreg
{
__m256 f;
__m256d d;
__m256i i;
xmmreg xmm[2];
};
union zmmreg
{
__m512 f;
__m512d d;
__m512i i;
xmmreg xmm[4];
ymmreg ymm[2];
};
struct Fxsave
{
static constexpr ptrdiff_t size = FXSAVE_SIZE;
uint16_t fcw; // FPU control word
uint16_t fsw; // FPU status word
uint16_t ftw; // FPU tag word
uint16_t fop;
uint64_t fip; // FPU RIP
uint64_t fdp; // FPU data pointer
uint32_t mxcsr;
uint32_t mcxsr_mask;
static_assert(sizeof(Float80) == 16);
Float80 st[8];
static_assert(sizeof(xmmreg) == 16);
xmmreg xmm[16];
uint8_t padding[size - 416];
};
static_assert(sizeof(Fxsave) == Fxsave::size);
using char4 = char[4];
static constexpr char4 eflags[] = {
"CF", // bit 0 - carry flag
"", // bit 1 - fixed
"PF", // bit 2 - parity flag
"", // bit 3
"AF", // bit 4 - auxiliary flag
"", // bit 5
"ZF", // bit 6 - zero flag
"SF", // bit 7 - sign flag
"TF", // bit 8 - trap flag
"IF", // bit 9 - interrupt flag
"DF", // bit 10 - direction flag
"OF", // bit 11 - overflow flag
"", // bit 12 - IOPL bit
"", // bit 13 - IOPL bit
"NT", // bit 14 - nested task flag
"", // bit 15
"RF", // bit 16 - resume flag
"VM", // bit 17 - virtual mode flag
"AC", // bit 18 - alignment check flag
"VIF", // bit 19 - virtual interrupt flag
"VIP", // bit 20 - virtual interrupt pending
// "ID", // bit 21 - CPUID available (we don't print it)
};
static constexpr char4 fsw[] = {
"IE", // bit 0 - invalid exception
"DE", // bit 1 - denormal exception
"ZE", // bit 2 - division by zero exception
"OE", // bit 3 - overflow exception
"UE", // bit 4 - underflow exception
"PE", // bit 5 - inexact/precision exception
"SF", // bit 6 - stack fault
"ES", // bit 7 - exception summary
"C0", // bit 8 - code C0
"C1", // bit 9 - code C1
"C2", // bit 10 - code C2
"", // bit 11 - top of stack bit
"", // bit 12 - top of stack bit
"", // bit 13 - top of stack bit
"C3", // bit 14 - code C3
// "B", // bit 15 - FPU busy
};
static constexpr char4 mxcsr[] = {
"IE", // bit 0 - invalid exception
"DE", // bit 1 - denormal exception
"ZE", // bit 2 - division by zero exception
"OE", // bit 3 - overflow exception
"UE", // bit 4 - underflow exception
"PE", // bit 5 - inexact/precision exception
"DAZ", // bit 6 - denormals are zero
"IM", // bit 7 - invalid exceptions masked
"DM", // bit 8 - denormal exceptions masked
"ZM", // bit 9 - division by zero exceptions masked
"OM", // bit 10 - overflow exceptions masked
"UM", // bit 11 - underflow exceptions masked
"PM", // bit 12 - inexact/precision exceptions masked
"", // bit 13 - round control
"", // bit 14 - round control
"FTZ", // bit 15 - flush to zero
};
static constexpr char rounding_modes[][9] = {
"nearest", "down", "up", "truncate"
};
static ptrdiff_t xsave_offset(XSaveBits bit)
{
int n = __bsfd(bit);
uint32_t eax, ebx, ecx, edx;
__cpuid_count(0xd, n, eax, ebx, ecx, edx);
return ebx;
};
template <int N, typename T>
static void print_flag_description(FILE *f, uint64_t value, T (&array)[N])
{
for (size_t i = 0; i < std::size(array); ++i) {
uint64_t bit = UINT64_C(1) << i;
const char *name = array[i];
if ((value & bit) && *name)
fprintf(f, "%s ", name);
}
}
static void print_gpr(FILE *f, const char *name, int64_t value)
{
fprintf(f, " %-5s = 0x%016" PRIx64, name, value);
if (value <= 4096 && value >= -4096)
fprintf(f, " (%d)", int(value));
fputc('\n', f);
}
static void print_rip(FILE *f, uintptr_t rip)
{
fprintf(f, " %-5s = 0x%016tx", "rip", rip);
#ifdef __unix__
uint8_t *ptr = reinterpret_cast<uint8_t *>(rip);
Dl_info dli;
if (dladdr(ptr, &dli) && dli.dli_sname)
fprintf(f, " <%s+%#tx>", dli.dli_sname, ptr - static_cast<uint8_t *>(dli.dli_saddr));
#endif
fputc('\n', f);
}
static void print_eflags(FILE *f, uint64_t value)
{
fprintf(f, " flags = 0x%08" PRIx64 " [ ", value);
print_flag_description(f, value, eflags);
fputs("]\n", f);
}
static void print_segment(FILE *f, const char *name, uint16_t value)
{
fprintf(f, " %-5s = 0x%x\n", name, value);
}
#if defined(__linux__)
void dump_gprs(FILE *f, const mcontext_t *mc)
{
static constexpr struct {
char name[4];
int idx;
} registers[] = {
{ "rax", REG_RAX },
{ "rbx", REG_RBX },
{ "rcx", REG_RCX },
{ "rdx", REG_RDX },
{ "rsi", REG_RSI },
{ "rdi", REG_RDI },
{ "rbp", REG_RBP },
{ "rsp", REG_RSP },
{ "r8", REG_R8 },
{ "r9", REG_R9 },
{ "r10", REG_R10 },
{ "r11", REG_R11 },
{ "r12", REG_R12 },
{ "r13", REG_R13 },
{ "r14", REG_R14 },
{ "r15", REG_R15 },
};
for (auto reg : registers)
print_gpr(f, reg.name, mc->gregs[reg.idx]);
print_rip(f, mc->gregs[REG_RIP]);
print_eflags(f, mc->gregs[REG_EFL]);
// Linux always writes 0 to these fields, so this is useless. Don't waste
// log space.
if (false) {
print_segment(f, "fs", mc->gregs[REG_CSGSFS] >> 16);
print_segment(f, "gs", mc->gregs[REG_CSGSFS] >> 8);
}
}
#elif defined(__FreeBSD__)
void dump_gprs(FILE *f, const mcontext_t *mc)
{
using register_t = decltype(mc->mc_rax);
static constexpr struct {
char name[4];
register_t mcontext_t:: *ptr;
} registers[] = {
{ "rax", &mcontext_t::mc_rax },
{ "rbx", &mcontext_t::mc_rbx },
{ "rcx", &mcontext_t::mc_rcx },
{ "rdx", &mcontext_t::mc_rdx },
{ "rsi", &mcontext_t::mc_rsi },
{ "rdi", &mcontext_t::mc_rdi },
{ "rbp", &mcontext_t::mc_rbp },
{ "rsp", &mcontext_t::mc_rsp },
{ "r8", &mcontext_t::mc_r8 },
{ "r9", &mcontext_t::mc_r9 },
{ "r10", &mcontext_t::mc_r10 },
{ "r11", &mcontext_t::mc_r11 },
{ "r12", &mcontext_t::mc_r12 },
{ "r13", &mcontext_t::mc_r13 },
{ "r14", &mcontext_t::mc_r14 },
{ "r15", &mcontext_t::mc_r15 },
};
for (auto reg : registers)
print_gpr(f, reg.name, mc->*(reg.ptr));
print_rip(f, mc->mc_rip);
print_eflags(f, mc->mc_rflags);
print_segment(f, "fs", mc->mc_fs);
print_segment(f, "gs", mc->mc_gs);
}
#elif defined(__APPLE__) || defined(__MACH__)
void dump_gprs(FILE *f, const mcontext_t mc)
{
auto *state = &mc->__ss;
using ThreadState = std::decay_t<decltype(*state)>;
using register_t = decltype(state->__rax);
static constexpr struct {
char name[4];
register_t ThreadState:: *ptr;
} registers[] = {
{ "rax", &ThreadState::__rax },
{ "rbx", &ThreadState::__rbx },
{ "rcx", &ThreadState::__rcx },
{ "rdx", &ThreadState::__rdx },
{ "rsi", &ThreadState::__rsi },
{ "rdi", &ThreadState::__rdi },
{ "rbp", &ThreadState::__rbp },
{ "rsp", &ThreadState::__rsp },
{ "r8", &ThreadState::__r8 },
{ "r9", &ThreadState::__r9 },
{ "r10", &ThreadState::__r10 },
{ "r11", &ThreadState::__r11 },
{ "r12", &ThreadState::__r12 },
{ "r13", &ThreadState::__r13 },
{ "r14", &ThreadState::__r14 },
{ "r15", &ThreadState::__r15 },
};
for (auto reg : registers)
print_gpr(f, reg.name, state->*(reg.ptr));
print_rip(f, state->__rip);
print_eflags(f, state->__rflags);
print_segment(f, "fs", state->__fs);
print_segment(f, "gs", state->__gs);
}
#endif
static void print_x87mmx_registers(FILE *f, const Fxsave *state)
{
int fptop = (state->fsw >> 11) & 7;
fprintf(f, " fcw = %#x\n fsw = %#x [ ", state->fcw, state->fsw);
print_flag_description(f, state->fsw, fsw);
fprintf(f, "top=%d ]\n ftw = %#x\n", fptop, state->ftw);
if (state->ftw == 0)
return; // no tags, nothing to display, so save space
// put them back in order according to the FP top
for (size_t i = 0; i < std::size(state->st); ++i) {
int effective = (i + fptop) % std::size(state->st); // ### is this right?
effective = i;
auto st = state->st + effective;
fprintf(f, " st(%zu) = %04x%016" PRIx64 " (%La)\n",
i, st->as_hex.high16, st->as_hex.low64, st->as_float);
}
}
static void print_xmm_register(FILE *f, const xmmreg &ptr)
{
uint64_t low = uint64_t(ptr.u);
uint64_t high = uint64_t(ptr.u >> 8 * sizeof(low));
fprintf(f, "%016" PRIx64 ":%016" PRIx64 " ", high, low);
}
static void print_avx_registers(FILE *f, const Fxsave *state, XSaveBits mask)
{
// start with the MXCSR
fprintf(f, " mxcsr = 0x%08u [ ", state->mxcsr);
print_flag_description(f, state->mxcsr, mxcsr);
fprintf(f, "RC=%s ]\n", rounding_modes[(state->mxcsr & _MM_ROUND_MASK) / _MM_ROUND_DOWN]);
char nameprefix = 'x';
auto base = reinterpret_cast<const uint8_t *>(state);
const xmmreg *ymmhstate = nullptr;
const ymmreg *zmmhstate = nullptr;
const zmmreg *hizmmstate = nullptr;
const __mmask64 *opmaskstate = nullptr;
if (mask & XSave_Ymm_Hi128) {
nameprefix = 'y';
if (int offset = xsave_offset(XSave_Ymm_Hi128); offset > Fxsave::size)
ymmhstate = reinterpret_cast<const xmmreg *>(base + offset);
}
if (mask & XSave_Zmm_Hi256) {
nameprefix = 'z';
if (int offset = xsave_offset(XSave_Zmm_Hi256); offset > Fxsave::size)
zmmhstate = reinterpret_cast<const ymmreg *>(base + offset);
}
if (mask & XSave_Hi16_Zmm) {
if (int offset = xsave_offset(XSave_Zmm_Hi256); offset > Fxsave::size)
hizmmstate = reinterpret_cast<const zmmreg *>(base + offset);
}
if (mask & XSave_OpMask) {
if (int offset = xsave_offset(XSave_Zmm_Hi256); offset > Fxsave::size)
opmaskstate = reinterpret_cast<const __mmask64 *>(base + offset);
}
for (int i = 0; i < int(std::size(state->xmm)); ++i) {
fprintf(f, " %cmm%-2d = ", nameprefix, i);
if (zmmhstate) {
print_xmm_register(f, zmmhstate[i].xmm[1]);
print_xmm_register(f, zmmhstate[i].xmm[0]);
}
if (ymmhstate)
print_xmm_register(f, ymmhstate[i]);
print_xmm_register(f, state->xmm[i]);
fputc('\n', f);
}
for (int i = 0; hizmmstate && i < 16; ++i) {
fprintf(f, " %cmm%-2d = ", nameprefix, i + 16);
for (int j = std::size(hizmmstate->xmm) - 1; j >= 0; --j)
print_xmm_register(f, hizmmstate[i].xmm[j]);
fputc('\n', f);
}
for (int i = 0; opmaskstate && i < 8; ++i)
fprintf(f, " k%d = 0x%016" PRIx64 "\n", i, uint64_t(opmaskstate[i]));
}
static void print_amx_tiles_palette1(FILE *f, const Fxsave *state, const amx_tileconfig *tileconfig)
{
// should we even print the 8 kB of tile data?
//auto info = amx_palette1_info();
constexpr struct amx_palette1_info info = {
.total_tile_bytes = 8192,
.bytes_per_tile = 1024,
.bytes_per_row = 64,
.max_names = 8,
.max_rows = 16
};
int offset = xsave_offset(XSave_Xtiledata);
if (offset + info.total_tile_bytes <= Fxsave::size)
return;
auto base = reinterpret_cast<const uint8_t *>(state) + offset;
for (int reg = 0; reg < info.max_names; ++reg) {
fprintf(f, " tmm%-2d =", reg);
if (tileconfig->rows[reg] == 0) {
fprintf(f, " <0 rows>\n");
continue;
}
const uint8_t *tiledata = base + reg * info.bytes_per_tile;
for (int row = 0; row < tileconfig->rows[reg]; ++row) {
const uint8_t *rowdata = tiledata + row * info.bytes_per_row;
fprintf(f, " %d: {", row);
for (int i = 0; i < tileconfig->colsb[reg]; ++i)
fprintf(f, " %02x", rowdata[i]);
fprintf(f, " }\n");
}
}
}
static void print_amx_state(FILE *f, const Fxsave *state, XSaveBits mask)
{
int offset = xsave_offset(XSave_Xtilecfg);
if (offset + sizeof(amx_tileconfig) <= Fxsave::size)
return;
auto base = reinterpret_cast<const uint8_t *>(state);
auto tileconfig = reinterpret_cast<const amx_tileconfig *>(base + offset);
fprintf(f, " xtilecfg = palette: %u, start_row: %u\n", tileconfig->palette, tileconfig->start_row);
for (size_t i = 0; i < std::size(tileconfig->colsb); ++i)
fprintf(f, " tile%-2zu { colsb: %u, rows: %u }\n",
i, tileconfig->colsb[i], tileconfig->rows[i]);
if (mask & XSave_Xtiledata) {
if (tileconfig->palette == 1)
return print_amx_tiles_palette1(f, state, tileconfig);
}
}
static inline uint64_t __attribute__((target("xsave"))) do_xgetbv()
{
return _xgetbv(0);
}
void dump_xsave(FILE *f, const void *xsave_area, size_t xsave_size, int xsave_dump_mask)
{
// sanity check the state
XSaveBits mask = XSaveBits(xsave_dump_mask);
if (xsave_size < Fxsave::size)
return; // too small to be FXSAVE state
auto state = static_cast<const Fxsave *>(xsave_area);
if (xsave_size > Fxsave::size) {
if (xsave_size < Fxsave::size + 64)
return; // XSAVE extended header missing
// get the bit vector of saved features
uint64_t xsave_bv;
memcpy(&xsave_bv, state + 1, sizeof(xsave_bv));
mask = XSaveBits(mask & xsave_bv);
// sanity check it
uint64_t xgetbv0 = XSave_X87 | XSave_SseState;
// some Atoms have XSAVE but not AVX, but until there's interesting
// state in them, the check for AVX suffices
if (cpu_has_feature(cpu_feature_avx))
xgetbv0 = do_xgetbv();
if (xsave_bv & ~xgetbv0)
return; // bit vector contains invalid bits
}
if (mask & XSave_X87)
print_x87mmx_registers(f, state);
if (mask & XSave_Avx512State)
print_avx_registers(f, state, mask);
if (mask & XSave_AmxState)
print_amx_state(f, state, mask);
}
|
//..............................
// UI Lab Inc. Arthur Amshukov .
//..............................
#ifndef __ARCTURUS_TYPE_H__
#define __ARCTURUS_TYPE_H__
#pragma once
BEGIN_NAMESPACE(arcturus)
USING_NAMESPACE(core)
USING_NAMESPACE(frontend)
struct arcturus_type_traits
{
DECLARE_ENUM
(
kind,
std::size_t,
unknown_type = 0,
byte_type = 100,
integer_type = 101,
real_type = 102,
string_type = 103,
boolean_type = 104,
pointer_type = 105, // ref/ptr
array_type = 150,
structure_type = 200,
enumeration_type = 201,
function_type = 300,
procedure_type = 301,
namespace_type = 500,
package_type = 501,
module_type = 502,
// attributes
constant = 1024, // const
readonly = 1025, // let
variable = 1026, // var
// the following one (1) entry MUST be the last entry in the enum
size
)
};
class arcturus_type : public abstract_type<arcturus_type_traits>
{
public:
arcturus_type(kind_type kind);
arcturus_type(const arcturus_type& other) = default;
arcturus_type(arcturus_type&& other) = default;
~arcturus_type();
arcturus_type& operator = (const arcturus_type& other) = default;
arcturus_type& operator = (arcturus_type&& other) = default;
};
END_NAMESPACE
#endif // __ARCTURUS_TYPE_H__
|
#ifndef BOOST_MPL_LIST_AUX_TAG_HPP_INCLUDED
#define BOOST_MPL_LIST_AUX_TAG_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: tag.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-11 02:19:02 -0400 (Sat, 11 Oct 2008) $
// $Revision: 49267 $
namespace riakboost{} namespace boost = riakboost; namespace riakboost{ namespace mpl { namespace aux {
struct list_tag;
struct l_iter_tag;
}}}
#endif // BOOST_MPL_LIST_AUX_TAG_HPP_INCLUDED
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <numeric>
// template <InputIterator Iter1, InputIterator Iter2, MoveConstructible T,
// class BinaryOperation1,
// Callable<auto, Iter1::reference, Iter2::reference> BinaryOperation2>
// requires Callable<BinaryOperation1, const T&, BinaryOperation2::result_type>
// && HasAssign<T, BinaryOperation1::result_type>
// && CopyConstructible<BinaryOperation1>
// && CopyConstructible<BinaryOperation2>
// T
// inner_product(Iter1 first1, Iter1 last1, Iter2 first2,
// T init, BinaryOperation1 binary_op1, BinaryOperation2 binary_op2);
#include <numeric>
#include <functional>
#include <cassert>
#include "../iterators.h"
template <class Iter1, class Iter2, class T>
void
test(Iter1 first1, Iter1 last1, Iter2 first2, T init, T x)
{
assert(std::inner_product(first1, last1, first2, init,
std::multiplies<int>(), std::plus<int>()) == x);
}
template <class Iter1, class Iter2>
void
test()
{
int a[] = {1, 2, 3, 4, 5, 6};
int b[] = {6, 5, 4, 3, 2, 1};
unsigned sa = sizeof(a) / sizeof(a[0]);
test(Iter1(a), Iter1(a), Iter2(b), 1, 1);
test(Iter1(a), Iter1(a), Iter2(b), 10, 10);
test(Iter1(a), Iter1(a+1), Iter2(b), 1, 7);
test(Iter1(a), Iter1(a+1), Iter2(b), 10, 70);
test(Iter1(a), Iter1(a+2), Iter2(b), 1, 49);
test(Iter1(a), Iter1(a+2), Iter2(b), 10, 490);
test(Iter1(a), Iter1(a+sa), Iter2(b), 1, 117649);
test(Iter1(a), Iter1(a+sa), Iter2(b), 10, 1176490);
}
int main()
{
test<input_iterator<const int*>, input_iterator<const int*> >();
test<input_iterator<const int*>, forward_iterator<const int*> >();
test<input_iterator<const int*>, bidirectional_iterator<const int*> >();
test<input_iterator<const int*>, random_access_iterator<const int*> >();
test<input_iterator<const int*>, const int*>();
test<forward_iterator<const int*>, input_iterator<const int*> >();
test<forward_iterator<const int*>, forward_iterator<const int*> >();
test<forward_iterator<const int*>, bidirectional_iterator<const int*> >();
test<forward_iterator<const int*>, random_access_iterator<const int*> >();
test<forward_iterator<const int*>, const int*>();
test<bidirectional_iterator<const int*>, input_iterator<const int*> >();
test<bidirectional_iterator<const int*>, forward_iterator<const int*> >();
test<bidirectional_iterator<const int*>, bidirectional_iterator<const int*> >();
test<bidirectional_iterator<const int*>, random_access_iterator<const int*> >();
test<bidirectional_iterator<const int*>, const int*>();
test<random_access_iterator<const int*>, input_iterator<const int*> >();
test<random_access_iterator<const int*>, forward_iterator<const int*> >();
test<random_access_iterator<const int*>, bidirectional_iterator<const int*> >();
test<random_access_iterator<const int*>, random_access_iterator<const int*> >();
test<random_access_iterator<const int*>, const int*>();
test<const int*, input_iterator<const int*> >();
test<const int*, forward_iterator<const int*> >();
test<const int*, bidirectional_iterator<const int*> >();
test<const int*, random_access_iterator<const int*> >();
test<const int*, const int*>();
}
|
#include "EngineSrc/Technique/MaterialPool.h"
#include "EngineSrc/Rendering/Renderer.h"
#include "../../Scene/SceneMgr.h"
#include "EngineSrc/3D/Vegetation/Tree.h"
#include "3D/Model/Model.h"
#include "Mesh/InstancedMesh.h"
namespace tzw {
VegetationBatInfo::VegetationBatInfo()
{
}
VegetationBatInfo::VegetationBatInfo(VegetationType theType, std::string filePath, vec2 size)
{
m_type = theType;
file_path = filePath;
m_size = size;
}
VegetationBatch::VegetationBatch(const VegetationBatInfo * info)
{
m_type = info->m_type;
auto filePath = info->file_path;
m_info = (*info);
switch (m_type)
{
case VegetationType::QUAD_TRI:
{
auto theMesh = new Mesh();
float halfWidth = m_info.m_size.x / 2.f;
float halfHeight = m_info.m_size.y / 2.f;
VertexData vertices[] = {
//#1
VertexData(vec3(-1.0f *halfWidth, -1.0f * halfHeight, -0.5f), vec2(0.0f, 0.0f)),
VertexData(vec3( 1.0f *halfWidth, -1.0f * halfHeight, -0.5f), vec2(1.0f, 0.0f)),
VertexData(vec3(1.0f *halfWidth, 1.0f * halfHeight, -0.5f), vec2(1.0f, 1.0f)),
VertexData(vec3( -1.0f *halfWidth, 1.0f * halfHeight, -0.5f), vec2(0.0f, 1.0f)),
//#2
VertexData(vec3(-0.707f *halfWidth - 0.353, -1.0f * halfHeight, -0.707f *halfWidth + 0.353), vec2(0.0f, 0.0f)),
VertexData(vec3(0.707f *halfWidth - 0.353, 1.0f * halfHeight, 0.707f * halfWidth + 0.353), vec2(1.0f, 1.0f)),
VertexData(vec3(-0.707f *halfWidth - 0.353, 1.0f * halfHeight, -0.707f * halfWidth + 0.353), vec2(0.0f, 1.0f)),
VertexData(vec3(0.707f *halfWidth - 0.353, -1.0f * halfHeight, 0.707f * halfWidth + 0.353), vec2(1.0f, 0.0f)),
//#3
VertexData(vec3(-0.707f *halfWidth + 0.353, -1.0f * halfHeight, 0.707f *halfWidth + 0.353), vec2(0.0f, 0.0f)),
VertexData(vec3(0.707f *halfWidth + 0.353, 1.0f * halfHeight, -0.707f * halfWidth + 0.353), vec2(1.0f, 1.0f)),
VertexData(vec3(-0.707f *halfWidth + 0.353, 1.0f * halfHeight, 0.707f * halfWidth + 0.353), vec2(0.0f, 1.0f)),
VertexData(vec3(0.707f *halfWidth + 0.353, -1.0f * halfHeight, -0.707f * halfWidth + 0.353), vec2(1.0f, 0.0f)),
};
unsigned short indices[] = {
0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 7, 5, 8, 9, 10, 8, 11, 9,
};
theMesh->addVertices(vertices,sizeof(vertices)/sizeof(VertexData));
theMesh->addIndices(indices,sizeof(indices)/sizeof(unsigned short));
theMesh->finish();
m_quadMesh = theMesh;
m_quadMat = Material::createFromTemplate("Grass");
auto tex = TextureMgr::shared()->getByPath(filePath);
tex->genMipMap();
tex->setWarp(RenderFlag::WarpAddress::ClampToEdge);
m_quadMat->setTex("DiffuseMap", tex);
auto instancedMesh = new InstancedMesh();
instancedMesh->setMesh(theMesh);
m_instancedMeshList.push_back(instancedMesh);
}
break;
case VegetationType::QUAD:
{
auto theMesh = new Mesh();
float halfWidth = m_info.m_size.x / 2.f;
float halfHeight = m_info.m_size.y / 2.f;
VertexData vertices[] = {
//#1
VertexData(vec3(-1.0f *halfWidth, 0, -0.5f), vec2(0.0f, 0.0f)),
VertexData(vec3( 1.0f *halfWidth, 0, -0.5f), vec2(1.0f, 0.0f)),
VertexData(vec3(1.0f *halfWidth, 2.0f * halfHeight, -0.5f), vec2(1.0f, 1.0f)),
VertexData(vec3( -1.0f *halfWidth, 2.0f * halfHeight, -0.5f), vec2(0.0f, 1.0f)),
};
unsigned short indices[] = {
0, 1, 2, 0, 2, 3,
};
theMesh->addVertices(vertices,sizeof(vertices)/sizeof(VertexData));
theMesh->addIndices(indices,sizeof(indices)/sizeof(unsigned short));
theMesh->finish();
m_quadMesh = theMesh;
m_quadMat = Material::createFromTemplate("BillBoardInstance");
auto tex = TextureMgr::shared()->getByPath(filePath);
tex->genMipMap();
tex->setWarp(RenderFlag::WarpAddress::ClampToEdge);
m_quadMat->setTex("DiffuseMap", tex);
auto instancedMesh = new InstancedMesh();
instancedMesh->setMesh(theMesh);
m_instancedMeshList.push_back(instancedMesh);
}
break;
case VegetationType::ModelType:
{
auto treeModel = Model::create(filePath, false);
m_model = treeModel;
for(auto i = 0; i < treeModel->getMatCount(); i ++)
{
auto mat = treeModel->getMat(i);
mat->setIsEnableInstanced(true);
mat->reload();
}
for(auto i = 0; i < m_model->getMeshCount(); i++)
{
auto theMesh = m_model->getMesh(i);
auto instancedMesh = new InstancedMesh();
instancedMesh->setMesh(theMesh);
m_instancedMeshList.push_back(instancedMesh);
}
}
break;
default: ;
}
}
void VegetationBatch::insertInstanceData(InstanceData inst)
{
switch (m_type)
{
case VegetationType::QUAD_TRI:
{
m_instancedMeshList[0]->pushInstance(inst);
}
break;
case VegetationType::QUAD:
{
m_instancedMeshList[0]->pushInstance(inst);
}
break;
case VegetationType::ModelType:
{
for(auto i = 0; i < m_model->getMeshCount(); i++)
{
m_instancedMeshList[i]->pushInstance(inst);
//m_model->getMesh(i)->pushInstance(inst);
}
}
break;
default: ;
}
m_totalCount += 1;
}
void VegetationBatch::clear()
{
switch (m_type)
{
case VegetationType::QUAD_TRI:
{
m_instancedMeshList[0]->clearInstances();
}
break;
case VegetationType::QUAD:
{
m_instancedMeshList[0]->clearInstances();
}
break;
case VegetationType::ModelType:
{
for(auto i = 0; i < m_model->getMeshCount(); i++)
{
m_instancedMeshList[i]->clearInstances();
}
}
break;
default: ;
}
m_totalCount = 0;
}
void VegetationBatch::setUpTransFormation(TransformationInfo& info)
{
auto currCam = g_GetCurrScene()->defaultCamera();
info.m_projectMatrix = currCam->projection();
info.m_viewMatrix = currCam->getViewMatrix();
Matrix44 mat;
mat.setToIdentity();
info.m_worldMatrix = mat;
}
void VegetationBatch::commitRenderCmd(RenderFlag::RenderStageType stageType, RenderQueues * queues, int requirementArg)
{
switch (m_type)
{
case VegetationType::QUAD_TRI:
{
auto theMesh = m_quadMesh;
auto mat = m_quadMat;
m_instancedMeshList[0]->submitInstanced();
RenderCommand command(theMesh, mat, this, stageType, RenderCommand::PrimitiveType::TRIANGLES, RenderCommand::RenderBatchType::Instanced);
command.setInstancedMesh(m_instancedMeshList[0]);
command.setPrimitiveType(RenderCommand::PrimitiveType::TRIANGLES);
setUpTransFormation(command.m_transInfo);
queues->addRenderCommand(command, requirementArg);
setUpTransFormation(command.m_transInfo);
}
break;
case VegetationType::QUAD:
{
auto theMesh = m_quadMesh;
auto mat = m_quadMat;
m_instancedMeshList[0]->submitInstanced();
RenderCommand command(theMesh, mat, this, stageType, RenderCommand::PrimitiveType::TRIANGLES, RenderCommand::RenderBatchType::Instanced);
command.setInstancedMesh(m_instancedMeshList[0]);
command.setPrimitiveType(RenderCommand::PrimitiveType::TRIANGLES);
setUpTransFormation(command.m_transInfo);
queues->addRenderCommand(command, requirementArg);
setUpTransFormation(command.m_transInfo);
}
break;
case VegetationType::ModelType:
{
for(auto i = 0; i < m_model->getMeshCount(); i++)
{
auto theMesh = m_model->getMesh(i);
auto mat = m_model->getMat(theMesh->getMatIndex());
m_instancedMeshList[i]->submitInstanced();
RenderCommand command(theMesh, mat, this, stageType,RenderCommand::PrimitiveType::TRIANGLES, RenderCommand::RenderBatchType::Instanced);
command.setInstancedMesh(m_instancedMeshList[i]);
command.setPrimitiveType(RenderCommand::PrimitiveType::TRIANGLES);
setUpTransFormation(command.m_transInfo);
queues->addRenderCommand(command, requirementArg);
setUpTransFormation(command.m_transInfo);
}
}
break;
default: ;
}
}
void VegetationBatch::commitShadowRenderCmd(RenderQueues * queues, int level)
{
switch (m_type)
{
case VegetationType::QUAD_TRI:
{
}
break;
case VegetationType::ModelType:
{
for(auto i = 0; i < m_model->getMeshCount(); i++)
{
auto theMesh = m_model->getMesh(i);
auto mat = m_model->getMat(theMesh->getMatIndex());
m_instancedMeshList[i]->submitInstanced();
RenderCommand command(theMesh, mat, this, RenderFlag::RenderStageType::SHADOW, RenderCommand::PrimitiveType::TRIANGLES, RenderCommand::RenderBatchType::Instanced);
command.setInstancedMesh(m_instancedMeshList[i]);
command.setPrimitiveType(RenderCommand::PrimitiveType::TRIANGLES);
setUpTransFormation(command.m_transInfo);
queues->addRenderCommand(command,level);
setUpTransFormation(command.m_transInfo);
}
}
break;
default: ;
}
}
VegetationInfo::VegetationInfo()
{
}
void VegetationInfo::init(const VegetationBatInfo * lod0, const VegetationBatInfo * lod1, const VegetationBatInfo * lod2)
{
m_lodBatch[0] = new VegetationBatch(lod0);
if(lod1)
{
m_lodBatch[1] = new VegetationBatch(lod1);
} else
{
m_lodBatch[1] = nullptr;
}
if(lod2)
{
m_lodBatch[2] = new VegetationBatch(lod2);
} else
{
m_lodBatch[2] = nullptr;
}
}
void VegetationInfo::clear()
{
for(int i = 0; i < 3; i++)
{
if(m_lodBatch[i])
{
m_lodBatch[i]->clear();
}
}
}
void VegetationInfo::commitRenderCmd(RenderFlag::RenderStageType stageType, RenderQueues * queues, int requirementArg)
{
for(int i = 0; i < 3; i++)
{
if(m_lodBatch[i] && m_lodBatch[i]->m_totalCount)
{
m_lodBatch[i]->commitRenderCmd(stageType, queues, requirementArg);
}
}
}
void VegetationInfo::insert(InstanceData inst)
{
auto cam = g_GetCurrScene()->defaultCamera();
auto dist = cam->getWorldPos().distance(inst.transform.getTranslation());
if(dist > 200.0f) return;//just ignore
if(dist < 35.f)
{
m_lodBatch[0]->insertInstanceData(inst);
}
else if(dist < 100.f)
{
if(m_lodBatch[1])
{
m_lodBatch[1]->insertInstanceData(inst);
}else
{
m_lodBatch[0]->insertInstanceData(inst);
}
}
else
{
if(m_lodBatch[2])
{
m_lodBatch[2]->insertInstanceData(inst);
} else
{
if(m_lodBatch[1])
{
m_lodBatch[1]->insertInstanceData(inst);
}else
{
m_lodBatch[0]->insertInstanceData(inst);
}
}
}
}
bool VegetationInfo::anyHas()
{
for(int i = 0; i < 3; i++)
{
if(m_lodBatch[i])
{
if(m_lodBatch[i]->m_totalCount) return true;
}
}
return false;
}
void VegetationInfo::submitShadowDraw(RenderQueues * queues, int level)
{
if(m_lodBatch[0] && m_lodBatch[0]->m_totalCount) m_lodBatch[0]->commitShadowRenderCmd(queues, level);
if(m_lodBatch[1] && m_lodBatch[1]->m_totalCount) m_lodBatch[1]->commitShadowRenderCmd(queues, level);
}
TreeGroup::TreeGroup(int treeClass)
{
m_treeClass = treeClass;
}
Tree::Tree()
{
m_isFinish = false;
std::string materialName = "Tree";
m_barkMat = Material::createFromTemplate("ModelInstance");
auto tex = TextureMgr::shared()->getByPath("Models/tree/bark.jpg");
tex->genMipMap();
m_barkMat->setTex("DiffuseMap", tex);
m_leafMat = Material::createFromTemplate("Tree");
auto leafTex = TextureMgr::shared()->getByPath("Models/tree/twig.png", true);
m_leafMat->setTex("DiffuseMap", leafTex);
setIsAccpectOcTtree(false);
setCamera(g_GetCurrScene()->defaultCamera());
initMesh();
}
int Tree::regVegetation(const VegetationBatInfo * lod0, const VegetationBatInfo * lod1, const VegetationBatInfo * lod2)
{
auto info = new VegetationInfo();
// info->m_type = type;
info->init(lod0, lod1, lod2);
m_infoList.push_back(info);
return m_infoList.size() -1;
}
void Tree::addTreeGroup(TreeGroup* treeGroup)
{
m_tree[treeGroup->m_treeClass].insert(treeGroup);
}
void Tree::clearTreeGroup()
{
for(auto p : m_tree)
{
p.second.clear();
}
for(auto info :m_infoList)
{
info->clear();
}
}
void Tree::setUpTransFormation(TransformationInfo &info)
{
auto currCam = g_GetCurrScene()->defaultCamera();
info.m_projectMatrix = currCam->projection();
info.m_viewMatrix = currCam->getViewMatrix();
Matrix44 mat;
mat.setToIdentity();
info.m_worldMatrix = mat;
}
void Tree::submitShadowDraw(RenderQueues * queues, int level)
{
for(auto info :m_infoList)
{
if(info->anyHas())
{
info->submitShadowDraw(queues, level);
}
}
}
unsigned int Tree::getTypeId()
{
return 2333;
}
void Tree::pushCommand(RenderFlag::RenderStageType requirementType, RenderQueues * queues, int requirementArg)
{
//regroup
for(auto iter : m_tree)
{
// std::copy(iter->m_instance.begin(), iter->m_instance.end(), m_mesh->m_instanceOffset.begin());
auto info = m_infoList[iter.first];
auto &tg = iter;
auto theSet = tg.second;
for(auto group : theSet)
{
for(auto inst :group->m_instance)
{
info->insert(inst);
}
// info->m_totalCount += group->m_instance.size();
}
}
if (! m_isFinish)
{
finish();
}else
{
for(auto info :m_infoList)
{
if(info->anyHas())
{
info->commitRenderCmd(requirementType, queues, requirementArg);
}
}
// auto targetAmount = m_mesh->m_instanceOffset.size();
// if (targetAmount > 0)
// {
// // if(targetAmount > m_mesh->getInstanceBuf()->getAmount())
// // {
// // m_mesh->submitInstanced(targetAmount);
// // }else
// // {
// // m_mesh->reSubmitInstanced();
// // }
// m_mesh->submitInstanced();
// m_leafMesh->submitInstanced();
// // m_mesh->getInstanceBuf()->use();
// // m_mesh->getInstanceBuf()->allocate(&m_mesh->m_instanceOffset[0], m_mesh->m_instanceOffset.size() * sizeof(InstanceData), RenderFlag::BufferStorageType::DYNAMIC_DRAW);
// }
// // m_mesh->reSubmitInstanced();
}
// if(m_mesh->m_instanceOffset.size() > 0)
// {
// RenderCommand command(m_mesh, m_barkMat, RenderCommand::RenderType::Instanced);
// command.setPrimitiveType(RenderCommand::PrimitiveType::TRIANGLES);
// setUpTransFormation(command.m_transInfo);
// Renderer::shared()->addRenderCommand(command);
// setUpTransFormation(command.m_transInfo);
//
// RenderCommand commandLeaf(m_leafMesh, m_leafMat, RenderCommand::RenderType::Instanced);
// commandLeaf.setPrimitiveType(RenderCommand::PrimitiveType::TRIANGLES);
// setUpTransFormation(commandLeaf.m_transInfo);
// Renderer::shared()->addRenderCommand(commandLeaf);
// setUpTransFormation(commandLeaf.m_transInfo);
// }
}
void Tree::finish()
{
// m_mesh->finish();
// m_leafMesh->finish();
// // tlog("instance size %d", m_mesh->getInstanceSize());
// // m_mesh->reSubmitInstanced();
m_isFinish = true;
}
void Tree::submitDrawCmd(RenderFlag::RenderStageType requirementType, RenderQueues * queues, int requirementArg)
{
RenderCommand command(m_mesh, m_material,this, requirementType);
setUpTransFormation(command.m_transInfo);
queues->addRenderCommand(command, requirementArg);
}
void Tree::initMesh()
{
// auto treeModel = Model::create("Models/tree/tree.tzw", false);
//
//
// m_barkMat = treeModel->getMat(0);
// m_barkMat->setIsEnableInstanced(true);
//
// m_barkMat->setTex("DiffuseMap",TextureMgr::shared()->getByPath("Models/tree/bark.jpg", true));
// m_barkMat->reload();
//
//
// m_leafMat = treeModel->getMat(1);
// m_leafMat->setIsEnableInstanced(true);
// m_barkMat->setIsCullFace(false);
// m_leafMat->reload();
// m_leafMat->setTex("DiffuseMap",TextureMgr::shared()->getByPath("Models/tree/twig.png", true));
//
// m_mesh = treeModel->getMesh(0);
// m_leafMesh = treeModel->getMesh(1);
}
} // namespace tzw
|
/*=============================================================================
NifTK: A software platform for medical image computing.
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
=============================================================================*/
#include "niftkFastPointSetVtkMapper3D.h"
#include <mitkColorProperty.h>
#include <mitkDataNode.h>
#include <mitkPointSet.h>
#include <mitkProperties.h>
#include <mitkVector.h>
#include <mitkVtkPropRenderer.h>
#include <vtkActor.h>
#include <vtkCellArray.h>
#include <vtkFloatArray.h>
#include <vtkIdTypeArray.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
namespace niftk
{
//-----------------------------------------------------------------------------
FastPointSetVtkMapper3D::FastPointSetVtkMapper3D()
{
}
//-----------------------------------------------------------------------------
FastPointSetVtkMapper3D::~FastPointSetVtkMapper3D()
{
}
//-----------------------------------------------------------------------------
FastPointSetVtkMapper3D::LocalStorage::LocalStorage()
: m_Indicies(NULL)
, m_Array(NULL)
, m_Points(NULL)
, m_CellArray(NULL)
, m_PolyData(NULL)
, m_PolyDataMapper(NULL)
, m_Actor(NULL)
, m_NumberOfPoints(0)
{
m_Indicies = vtkIdTypeArray::New();
m_Array = vtkFloatArray::New();
m_Points = vtkPoints::New();
m_CellArray = vtkCellArray::New();
m_PolyData = vtkPolyData::New();
m_PolyDataMapper = vtkPolyDataMapper::New();
m_Actor = vtkActor::New();
}
//-----------------------------------------------------------------------------
FastPointSetVtkMapper3D::LocalStorage::~LocalStorage()
{
}
//-----------------------------------------------------------------------------
const mitk::PointSet* FastPointSetVtkMapper3D::GetInput()
{
return static_cast<const mitk::PointSet * > ( GetDataNode()->GetData() );
}
//-----------------------------------------------------------------------------
vtkProp* FastPointSetVtkMapper3D::GetVtkProp(mitk::BaseRenderer *renderer)
{
LocalStorage *ls = m_LocalStorage.GetLocalStorage(renderer);
return ls->m_Actor;
}
//-----------------------------------------------------------------------------
void FastPointSetVtkMapper3D::ResetMapper(mitk::BaseRenderer* renderer)
{
LocalStorage *ls = m_LocalStorage.GetLocalStorage(renderer);
ls->m_Actor->VisibilityOff();
}
//-----------------------------------------------------------------------------
void FastPointSetVtkMapper3D::GenerateDataForRenderer(mitk::BaseRenderer* renderer)
{
LocalStorage *ls = m_LocalStorage.GetLocalStorage(renderer);
mitk::DataNode* dataNode = this->GetDataNode();
assert(dataNode);
bool visible = true;
bool gotVisibility = dataNode->GetVisibility(visible, renderer);
if (!gotVisibility)
{
dataNode->SetVisibility(visible, renderer);
}
if(!visible)
{
ls->m_Actor->VisibilityOff();
return;
}
else
{
ls->m_Actor->VisibilityOn();
}
float opacity = 1;
bool gotOpacity = dataNode->GetOpacity(opacity, renderer);
if (!gotOpacity)
{
dataNode->SetBoolProperty("opacity", opacity, renderer);
}
ls->m_Actor->GetProperty()->SetOpacity(opacity);
int pointSize = 1;
bool gotPointSize = dataNode->GetIntProperty("pointsize", pointSize);
if (!gotPointSize)
{
dataNode->SetIntProperty("pointsize", pointSize, renderer);
}
ls->m_Actor->GetProperty()->SetPointSize(pointSize);
if (dynamic_cast<mitk::ColorProperty*>(dataNode->GetPropertyList(renderer)->GetProperty("color")) == NULL)
{
float unselectedColor[3] = {1.0f, 1.0f, 0.0f};
dataNode->SetColor(unselectedColor, renderer, "color");
}
if (dynamic_cast<mitk::ColorProperty*>(dataNode->GetPropertyList(renderer)->GetProperty("selectedcolor")) == NULL)
{
float selectedColor[3] = {1.0f, 0.0f, 0.0f};
dataNode->SetColor(selectedColor, renderer, "selectedcolor");
}
mitk::Color colour;
double colourVtk[4]={1.0f, 1.0f, 1.0f,1.0f};
bool isSelected = false;
bool gotSelected = dataNode->GetBoolProperty("selected", isSelected);
if (!gotSelected)
{
dataNode->SetBoolProperty("selected", isSelected, renderer);
}
if (isSelected)
{
colour = dynamic_cast<mitk::ColorProperty *>(this->GetDataNode()->GetPropertyList(renderer)->GetProperty("selectedcolor"))->GetValue();
}
else
{
colour = dynamic_cast<mitk::ColorProperty *>(this->GetDataNode()->GetPropertyList(renderer)->GetProperty("color"))->GetValue();
}
colourVtk[0] = colour[0];
colourVtk[1] = colour[1];
colourVtk[2] = colour[2];
ls->m_Actor->GetProperty()->SetColor(colourVtk);
mitk::PointSet::PointType point;
const mitk::PointSet* pointSet = this->GetInput();
mitk::PointSet::DataType* itkPointSet = pointSet->GetPointSet( 0 );
mitk::PointSet::PointsContainer* points = itkPointSet->GetPoints();
if (pointSet != NULL && pointSet->GetSize() > 0)
{
unsigned long int numberOfPoints = pointSet->GetSize();
// Only allocate new if the number of points have changed.
if (ls->m_NumberOfPoints != numberOfPoints)
{
ls->m_Indicies->SetNumberOfComponents(1);
ls->m_Indicies->SetNumberOfValues(numberOfPoints*2);
ls->m_Array->SetNumberOfComponents(3);
ls->m_Array->SetNumberOfValues(numberOfPoints*3);
ls->m_Points->SetData(ls->m_Array);
ls->m_CellArray->SetCells(numberOfPoints, ls->m_Indicies);
ls->m_PolyData->SetPoints(ls->m_Points);
ls->m_PolyData->SetVerts(ls->m_CellArray);
ls->m_PolyDataMapper->SetInputDataObject(0, ls->m_PolyData);
ls->m_Actor->SetMapper(ls->m_PolyDataMapper);
ls->m_NumberOfPoints = numberOfPoints;
}
unsigned long int pointCounter = 0;
unsigned long int arrayCounter = 0;
unsigned long int indexCounter = 0;
mitk::PointSet::PointsIterator pIt;
// Processing each point one at a time.
for (pIt = points->Begin(); pIt != points->End(); ++pIt) // for each point in the pointset
{
point = pIt->Value();
arrayCounter = pointCounter*3;
indexCounter = pointCounter*2;
// Copy x,y,z in sequence for each point.
ls->m_Array->SetValue(arrayCounter, point[0]);
ls->m_Array->SetValue(arrayCounter+1, point[1]);
ls->m_Array->SetValue(arrayCounter+2, point[2]);
// Copy a list of cells, where the first number is
// the number of points in the cell (always 1), and
// the second number is the point ID.
ls->m_Indicies->SetValue(indexCounter, 1);
ls->m_Indicies->SetValue(indexCounter+1, pointCounter);
pointCounter += 1;
}
}
}
}
|
/*
* David Salac
*/
#ifndef MIRROR_HPP
#define MIRROR_HPP
#include <string>
#include <tuple>
#include "MirrorIntersectionParameters.h"
/**
* Represents one mirror in 2D space
*/
class Mirror {
private:
const double m_x_start;
const double m_x_end;
const double m_y_start;
const double m_y_end;
double m_x_start_temp;
double m_x_end_temp;
double m_y_start_temp;
double m_y_end_temp;
double m_intersection_dist_x;
public:
/**
* Init instance
* @param x_start Horizontal position of start point
* @param x_end Horizontal position of end point
* @param y_start Vertical position of start point
* @param y_end Vertical position of end point
*/
Mirror(const double & x_start, const double & x_end, const double & y_start, const double & y_end) :
m_x_start(x_start), m_x_end(x_end), m_y_start(y_start), m_y_end(y_end),
m_x_start_temp(x_start), m_x_end_temp(x_end), m_y_start_temp(y_start), m_y_end_temp(y_end)
{}
/**
* Set temporary coordinates (for the purposes of rotation)
* @param x_start Horizontal position of start point
* @param x_end Horizontal position of end point
* @param y_start Vertical position of start point
* @param y_end Vertical position of end point
*/
void setTempCoordinates(const double & x_start, const double & x_end, const double & y_start, const double & y_end);
/**
* @return Horizontal position of start point
*/
double getXStart();
/**
* @return Vertical position of start point
*/
double getYStart();
/**
* @return Horizontal position of end point
*/
double getXEnd();
/**
* @return Vertical position of end point
*/
double getYEnd();
//Get coordinates after rotation
/**
* @return Horizontal position of start point after rotation
*/
double getXStartTemp();
/**
* @return Vertical position of start point after rotation
*/
double getYStartTemp();
/**
* @return Horizontal position of end point after rotation
*/
double getXEndTemp();
/**
* @return Vertical position of end point after rotation
*/
double getYEndTemp();
/**
* Compute the distance of the intersection point from beginning (after rotation)
* @param exists return whether intersection with any mirror exists
* @return distance of intersection point from beginning
*/
double computeXAxisIntersection(bool & exists);
/**
* Compute parameters of intersection point
* @return Parameters of intersection
*/
MirrorIntersectionParameters getIntersectionParameters();
/**
* Nice output
* @return String that represents mirror parameters
*/
std::string toString();
};
#endif /* MIRROR_HPP */
|
// Copyright (C) 2016 Vicente J. Botet Escriba
//
// 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)
// <experimental/functor.hpp>
// <experimental/utility.hpp> pair
#include <experimental/utility.hpp>
#include <experimental/n_functor.hpp>
#include <experimental/product_type.hpp>
#include <boost/detail/lightweight_test.hpp>
int twice(int i) {
return 2*i;
}
int main()
{
#if __cplusplus >= 201402L
namespace stde = std::experimental;
using T = std::pair<int, int>;
static_assert(stde::is_product_type_v<T>, "ERROR");
static_assert(stde::is_type_constructible_v<T>, "ERROR");
static_assert(std::is_base_of<stde::n_functor::tag, stde::n_functor::traits<std::pair<stde::_t, stde::_t>>> ::value, "ERROR");
static_assert(stde::is_n_functor<std::pair<stde::_t, stde::_t>>::value, "ERROR");
{
int v=1;
T x = std::make_pair(v,v);
BOOST_TEST(x.first == 1);
BOOST_TEST(x.second == 1);
auto call = std::make_tuple(twice,twice);
T y = stde::n_functor::transform(x, call);
BOOST_TEST(y.first == 2);
BOOST_TEST(y.second == 2);
}
#endif
return ::boost::report_errors();
}
|
// Copyright 2014 the V8 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.
#include "src/compiler/machine-operator-reducer.h"
#include <cmath>
#include "src/base/bits.h"
#include "src/base/division-by-constant.h"
#include "src/base/ieee754.h"
#include "src/base/overflowing-math.h"
#include "src/compiler/diamond.h"
#include "src/compiler/graph.h"
#include "src/compiler/machine-graph.h"
#include "src/compiler/node-matchers.h"
#include "src/compiler/node-properties.h"
#include "src/numbers/conversions-inl.h"
namespace v8 {
namespace internal {
namespace compiler {
MachineOperatorReducer::MachineOperatorReducer(Editor* editor,
MachineGraph* mcgraph,
bool allow_signalling_nan)
: AdvancedReducer(editor),
mcgraph_(mcgraph),
allow_signalling_nan_(allow_signalling_nan) {}
MachineOperatorReducer::~MachineOperatorReducer() = default;
Node* MachineOperatorReducer::Float32Constant(volatile float value) {
return graph()->NewNode(common()->Float32Constant(value));
}
Node* MachineOperatorReducer::Float64Constant(volatile double value) {
return mcgraph()->Float64Constant(value);
}
Node* MachineOperatorReducer::Int32Constant(int32_t value) {
return mcgraph()->Int32Constant(value);
}
Node* MachineOperatorReducer::Int64Constant(int64_t value) {
return graph()->NewNode(common()->Int64Constant(value));
}
Node* MachineOperatorReducer::Float64Mul(Node* lhs, Node* rhs) {
return graph()->NewNode(machine()->Float64Mul(), lhs, rhs);
}
Node* MachineOperatorReducer::Float64PowHalf(Node* value) {
value =
graph()->NewNode(machine()->Float64Add(), Float64Constant(0.0), value);
Diamond d(graph(), common(),
graph()->NewNode(machine()->Float64LessThanOrEqual(), value,
Float64Constant(-V8_INFINITY)),
BranchHint::kFalse);
return d.Phi(MachineRepresentation::kFloat64, Float64Constant(V8_INFINITY),
graph()->NewNode(machine()->Float64Sqrt(), value));
}
Node* MachineOperatorReducer::Word32And(Node* lhs, Node* rhs) {
Node* const node = graph()->NewNode(machine()->Word32And(), lhs, rhs);
Reduction const reduction = ReduceWord32And(node);
return reduction.Changed() ? reduction.replacement() : node;
}
Node* MachineOperatorReducer::Word32Sar(Node* lhs, uint32_t rhs) {
if (rhs == 0) return lhs;
return graph()->NewNode(machine()->Word32Sar(), lhs, Uint32Constant(rhs));
}
Node* MachineOperatorReducer::Word32Shr(Node* lhs, uint32_t rhs) {
if (rhs == 0) return lhs;
return graph()->NewNode(machine()->Word32Shr(), lhs, Uint32Constant(rhs));
}
Node* MachineOperatorReducer::Word32Equal(Node* lhs, Node* rhs) {
return graph()->NewNode(machine()->Word32Equal(), lhs, rhs);
}
Node* MachineOperatorReducer::Int32Add(Node* lhs, Node* rhs) {
Node* const node = graph()->NewNode(machine()->Int32Add(), lhs, rhs);
Reduction const reduction = ReduceInt32Add(node);
return reduction.Changed() ? reduction.replacement() : node;
}
Node* MachineOperatorReducer::Int32Sub(Node* lhs, Node* rhs) {
Node* const node = graph()->NewNode(machine()->Int32Sub(), lhs, rhs);
Reduction const reduction = ReduceInt32Sub(node);
return reduction.Changed() ? reduction.replacement() : node;
}
Node* MachineOperatorReducer::Int32Mul(Node* lhs, Node* rhs) {
return graph()->NewNode(machine()->Int32Mul(), lhs, rhs);
}
Node* MachineOperatorReducer::Int32Div(Node* dividend, int32_t divisor) {
DCHECK_NE(0, divisor);
DCHECK_NE(std::numeric_limits<int32_t>::min(), divisor);
base::MagicNumbersForDivision<uint32_t> const mag =
base::SignedDivisionByConstant(bit_cast<uint32_t>(divisor));
Node* quotient = graph()->NewNode(machine()->Int32MulHigh(), dividend,
Uint32Constant(mag.multiplier));
if (divisor > 0 && bit_cast<int32_t>(mag.multiplier) < 0) {
quotient = Int32Add(quotient, dividend);
} else if (divisor < 0 && bit_cast<int32_t>(mag.multiplier) > 0) {
quotient = Int32Sub(quotient, dividend);
}
return Int32Add(Word32Sar(quotient, mag.shift), Word32Shr(dividend, 31));
}
Node* MachineOperatorReducer::Uint32Div(Node* dividend, uint32_t divisor) {
DCHECK_LT(0u, divisor);
// If the divisor is even, we can avoid using the expensive fixup by shifting
// the dividend upfront.
unsigned const shift = base::bits::CountTrailingZeros(divisor);
dividend = Word32Shr(dividend, shift);
divisor >>= shift;
// Compute the magic number for the (shifted) divisor.
base::MagicNumbersForDivision<uint32_t> const mag =
base::UnsignedDivisionByConstant(divisor, shift);
Node* quotient = graph()->NewNode(machine()->Uint32MulHigh(), dividend,
Uint32Constant(mag.multiplier));
if (mag.add) {
DCHECK_LE(1u, mag.shift);
quotient = Word32Shr(
Int32Add(Word32Shr(Int32Sub(dividend, quotient), 1), quotient),
mag.shift - 1);
} else {
quotient = Word32Shr(quotient, mag.shift);
}
return quotient;
}
// Perform constant folding and strength reduction on machine operators.
Reduction MachineOperatorReducer::Reduce(Node* node) {
switch (node->opcode()) {
case IrOpcode::kProjection:
return ReduceProjection(ProjectionIndexOf(node->op()), node->InputAt(0));
case IrOpcode::kWord32And:
return ReduceWord32And(node);
case IrOpcode::kWord32Or:
return ReduceWord32Or(node);
case IrOpcode::kWord32Xor:
return ReduceWord32Xor(node);
case IrOpcode::kWord32Shl:
return ReduceWord32Shl(node);
case IrOpcode::kWord64Shl:
return ReduceWord64Shl(node);
case IrOpcode::kWord32Shr:
return ReduceWord32Shr(node);
case IrOpcode::kWord64Shr:
return ReduceWord64Shr(node);
case IrOpcode::kWord32Sar:
return ReduceWord32Sar(node);
case IrOpcode::kWord64Sar:
return ReduceWord64Sar(node);
case IrOpcode::kWord32Ror: {
Int32BinopMatcher m(node);
if (m.right().Is(0)) return Replace(m.left().node()); // x ror 0 => x
if (m.IsFoldable()) { // K ror K => K
return ReplaceInt32(base::bits::RotateRight32(m.left().Value(),
m.right().Value() & 31));
}
break;
}
case IrOpcode::kWord32Equal: {
Int32BinopMatcher m(node);
if (m.IsFoldable()) { // K == K => K
return ReplaceBool(m.left().Value() == m.right().Value());
}
if (m.left().IsInt32Sub() && m.right().Is(0)) { // x - y == 0 => x == y
Int32BinopMatcher msub(m.left().node());
node->ReplaceInput(0, msub.left().node());
node->ReplaceInput(1, msub.right().node());
return Changed(node);
}
// TODO(turbofan): fold HeapConstant, ExternalReference, pointer compares
if (m.LeftEqualsRight()) return ReplaceBool(true); // x == x => true
break;
}
case IrOpcode::kWord64Equal: {
Int64BinopMatcher m(node);
if (m.IsFoldable()) { // K == K => K
return ReplaceBool(m.left().Value() == m.right().Value());
}
if (m.left().IsInt64Sub() && m.right().Is(0)) { // x - y == 0 => x == y
Int64BinopMatcher msub(m.left().node());
node->ReplaceInput(0, msub.left().node());
node->ReplaceInput(1, msub.right().node());
return Changed(node);
}
// TODO(turbofan): fold HeapConstant, ExternalReference, pointer compares
if (m.LeftEqualsRight()) return ReplaceBool(true); // x == x => true
break;
}
case IrOpcode::kInt32Add:
return ReduceInt32Add(node);
case IrOpcode::kInt64Add:
return ReduceInt64Add(node);
case IrOpcode::kInt32Sub:
return ReduceInt32Sub(node);
case IrOpcode::kInt64Sub:
return ReduceInt64Sub(node);
case IrOpcode::kInt32Mul: {
Int32BinopMatcher m(node);
if (m.right().Is(0)) return Replace(m.right().node()); // x * 0 => 0
if (m.right().Is(1)) return Replace(m.left().node()); // x * 1 => x
if (m.IsFoldable()) { // K * K => K
return ReplaceInt32(
base::MulWithWraparound(m.left().Value(), m.right().Value()));
}
if (m.right().Is(-1)) { // x * -1 => 0 - x
node->ReplaceInput(0, Int32Constant(0));
node->ReplaceInput(1, m.left().node());
NodeProperties::ChangeOp(node, machine()->Int32Sub());
return Changed(node);
}
if (m.right().IsPowerOf2()) { // x * 2^n => x << n
node->ReplaceInput(1, Int32Constant(WhichPowerOf2(m.right().Value())));
NodeProperties::ChangeOp(node, machine()->Word32Shl());
Reduction reduction = ReduceWord32Shl(node);
return reduction.Changed() ? reduction : Changed(node);
}
break;
}
case IrOpcode::kInt32MulWithOverflow: {
Int32BinopMatcher m(node);
if (m.right().Is(2)) {
node->ReplaceInput(1, m.left().node());
NodeProperties::ChangeOp(node, machine()->Int32AddWithOverflow());
return Changed(node);
}
if (m.right().Is(-1)) {
node->ReplaceInput(0, Int32Constant(0));
node->ReplaceInput(1, m.left().node());
NodeProperties::ChangeOp(node, machine()->Int32SubWithOverflow());
return Changed(node);
}
break;
}
case IrOpcode::kInt32Div:
return ReduceInt32Div(node);
case IrOpcode::kUint32Div:
return ReduceUint32Div(node);
case IrOpcode::kInt32Mod:
return ReduceInt32Mod(node);
case IrOpcode::kUint32Mod:
return ReduceUint32Mod(node);
case IrOpcode::kInt32LessThan: {
Int32BinopMatcher m(node);
if (m.IsFoldable()) { // K < K => K
return ReplaceBool(m.left().Value() < m.right().Value());
}
if (m.LeftEqualsRight()) return ReplaceBool(false); // x < x => false
if (m.left().IsWord32Or() && m.right().Is(0)) {
// (x | K) < 0 => true or (K | x) < 0 => true iff K < 0
Int32BinopMatcher mleftmatcher(m.left().node());
if (mleftmatcher.left().IsNegative() ||
mleftmatcher.right().IsNegative()) {
return ReplaceBool(true);
}
}
break;
}
case IrOpcode::kInt32LessThanOrEqual: {
Int32BinopMatcher m(node);
if (m.IsFoldable()) { // K <= K => K
return ReplaceBool(m.left().Value() <= m.right().Value());
}
if (m.LeftEqualsRight()) return ReplaceBool(true); // x <= x => true
break;
}
case IrOpcode::kUint32LessThan: {
Uint32BinopMatcher m(node);
if (m.left().Is(kMaxUInt32)) return ReplaceBool(false); // M < x => false
if (m.right().Is(0)) return ReplaceBool(false); // x < 0 => false
if (m.IsFoldable()) { // K < K => K
return ReplaceBool(m.left().Value() < m.right().Value());
}
if (m.LeftEqualsRight()) return ReplaceBool(false); // x < x => false
if (m.left().IsWord32Sar() && m.right().HasValue()) {
Int32BinopMatcher mleft(m.left().node());
if (mleft.right().HasValue()) {
// (x >> K) < C => x < (C << K)
// when C < (M >> K)
const uint32_t c = m.right().Value();
const uint32_t k = mleft.right().Value() & 0x1F;
if (c < static_cast<uint32_t>(kMaxInt >> k)) {
node->ReplaceInput(0, mleft.left().node());
node->ReplaceInput(1, Uint32Constant(c << k));
return Changed(node);
}
// TODO(turbofan): else the comparison is always true.
}
}
break;
}
case IrOpcode::kUint32LessThanOrEqual: {
Uint32BinopMatcher m(node);
if (m.left().Is(0)) return ReplaceBool(true); // 0 <= x => true
if (m.right().Is(kMaxUInt32)) return ReplaceBool(true); // x <= M => true
if (m.IsFoldable()) { // K <= K => K
return ReplaceBool(m.left().Value() <= m.right().Value());
}
if (m.LeftEqualsRight()) return ReplaceBool(true); // x <= x => true
break;
}
case IrOpcode::kFloat32Sub: {
Float32BinopMatcher m(node);
if (allow_signalling_nan_ && m.right().Is(0) &&
(std::copysign(1.0, m.right().Value()) > 0)) {
return Replace(m.left().node()); // x - 0 => x
}
if (m.right().IsNaN()) { // x - NaN => NaN
// Do some calculation to make a signalling NaN quiet.
return ReplaceFloat32(m.right().Value() - m.right().Value());
}
if (m.left().IsNaN()) { // NaN - x => NaN
// Do some calculation to make a signalling NaN quiet.
return ReplaceFloat32(m.left().Value() - m.left().Value());
}
if (m.IsFoldable()) { // L - R => (L - R)
return ReplaceFloat32(m.left().Value() - m.right().Value());
}
if (allow_signalling_nan_ && m.left().IsMinusZero()) {
// -0.0 - round_down(-0.0 - R) => round_up(R)
if (machine()->Float32RoundUp().IsSupported() &&
m.right().IsFloat32RoundDown()) {
if (m.right().InputAt(0)->opcode() == IrOpcode::kFloat32Sub) {
Float32BinopMatcher mright0(m.right().InputAt(0));
if (mright0.left().IsMinusZero()) {
return Replace(graph()->NewNode(machine()->Float32RoundUp().op(),
mright0.right().node()));
}
}
}
// -0.0 - R => -R
node->RemoveInput(0);
NodeProperties::ChangeOp(node, machine()->Float32Neg());
return Changed(node);
}
break;
}
case IrOpcode::kFloat64Add: {
Float64BinopMatcher m(node);
if (m.IsFoldable()) { // K + K => K
return ReplaceFloat64(m.left().Value() + m.right().Value());
}
break;
}
case IrOpcode::kFloat64Sub: {
Float64BinopMatcher m(node);
if (allow_signalling_nan_ && m.right().Is(0) &&
(Double(m.right().Value()).Sign() > 0)) {
return Replace(m.left().node()); // x - 0 => x
}
if (m.right().IsNaN()) { // x - NaN => NaN
// Do some calculation to make a signalling NaN quiet.
return ReplaceFloat64(m.right().Value() - m.right().Value());
}
if (m.left().IsNaN()) { // NaN - x => NaN
// Do some calculation to make a signalling NaN quiet.
return ReplaceFloat64(m.left().Value() - m.left().Value());
}
if (m.IsFoldable()) { // L - R => (L - R)
return ReplaceFloat64(m.left().Value() - m.right().Value());
}
if (allow_signalling_nan_ && m.left().IsMinusZero()) {
// -0.0 - round_down(-0.0 - R) => round_up(R)
if (machine()->Float64RoundUp().IsSupported() &&
m.right().IsFloat64RoundDown()) {
if (m.right().InputAt(0)->opcode() == IrOpcode::kFloat64Sub) {
Float64BinopMatcher mright0(m.right().InputAt(0));
if (mright0.left().IsMinusZero()) {
return Replace(graph()->NewNode(machine()->Float64RoundUp().op(),
mright0.right().node()));
}
}
}
// -0.0 - R => -R
node->RemoveInput(0);
NodeProperties::ChangeOp(node, machine()->Float64Neg());
return Changed(node);
}
break;
}
case IrOpcode::kFloat64Mul: {
Float64BinopMatcher m(node);
if (allow_signalling_nan_ && m.right().Is(1))
return Replace(m.left().node()); // x * 1.0 => x
if (m.right().Is(-1)) { // x * -1.0 => -0.0 - x
node->ReplaceInput(0, Float64Constant(-0.0));
node->ReplaceInput(1, m.left().node());
NodeProperties::ChangeOp(node, machine()->Float64Sub());
return Changed(node);
}
if (m.right().IsNaN()) { // x * NaN => NaN
// Do some calculation to make a signalling NaN quiet.
return ReplaceFloat64(m.right().Value() - m.right().Value());
}
if (m.IsFoldable()) { // K * K => K
return ReplaceFloat64(m.left().Value() * m.right().Value());
}
if (m.right().Is(2)) { // x * 2.0 => x + x
node->ReplaceInput(1, m.left().node());
NodeProperties::ChangeOp(node, machine()->Float64Add());
return Changed(node);
}
break;
}
case IrOpcode::kFloat64Div: {
Float64BinopMatcher m(node);
if (allow_signalling_nan_ && m.right().Is(1))
return Replace(m.left().node()); // x / 1.0 => x
// TODO(ahaas): We could do x / 1.0 = x if we knew that x is not an sNaN.
if (m.right().IsNaN()) { // x / NaN => NaN
// Do some calculation to make a signalling NaN quiet.
return ReplaceFloat64(m.right().Value() - m.right().Value());
}
if (m.left().IsNaN()) { // NaN / x => NaN
// Do some calculation to make a signalling NaN quiet.
return ReplaceFloat64(m.left().Value() - m.left().Value());
}
if (m.IsFoldable()) { // K / K => K
return ReplaceFloat64(
base::Divide(m.left().Value(), m.right().Value()));
}
if (allow_signalling_nan_ && m.right().Is(-1)) { // x / -1.0 => -x
node->RemoveInput(1);
NodeProperties::ChangeOp(node, machine()->Float64Neg());
return Changed(node);
}
if (m.right().IsNormal() && m.right().IsPositiveOrNegativePowerOf2()) {
// All reciprocals of non-denormal powers of two can be represented
// exactly, so division by power of two can be reduced to
// multiplication by reciprocal, with the same result.
node->ReplaceInput(1, Float64Constant(1.0 / m.right().Value()));
NodeProperties::ChangeOp(node, machine()->Float64Mul());
return Changed(node);
}
break;
}
case IrOpcode::kFloat64Mod: {
Float64BinopMatcher m(node);
if (m.right().Is(0)) { // x % 0 => NaN
return ReplaceFloat64(std::numeric_limits<double>::quiet_NaN());
}
if (m.right().IsNaN()) { // x % NaN => NaN
return Replace(m.right().node());
}
if (m.left().IsNaN()) { // NaN % x => NaN
return Replace(m.left().node());
}
if (m.IsFoldable()) { // K % K => K
return ReplaceFloat64(Modulo(m.left().Value(), m.right().Value()));
}
break;
}
case IrOpcode::kFloat64Acos: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::acos(m.Value()));
break;
}
case IrOpcode::kFloat64Acosh: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::acosh(m.Value()));
break;
}
case IrOpcode::kFloat64Asin: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::asin(m.Value()));
break;
}
case IrOpcode::kFloat64Asinh: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::asinh(m.Value()));
break;
}
case IrOpcode::kFloat64Atan: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::atan(m.Value()));
break;
}
case IrOpcode::kFloat64Atanh: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::atanh(m.Value()));
break;
}
case IrOpcode::kFloat64Atan2: {
Float64BinopMatcher m(node);
if (m.right().IsNaN()) {
return Replace(m.right().node());
}
if (m.left().IsNaN()) {
return Replace(m.left().node());
}
if (m.IsFoldable()) {
return ReplaceFloat64(
base::ieee754::atan2(m.left().Value(), m.right().Value()));
}
break;
}
case IrOpcode::kFloat64Cbrt: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::cbrt(m.Value()));
break;
}
case IrOpcode::kFloat64Cos: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::cos(m.Value()));
break;
}
case IrOpcode::kFloat64Cosh: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::cosh(m.Value()));
break;
}
case IrOpcode::kFloat64Exp: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::exp(m.Value()));
break;
}
case IrOpcode::kFloat64Expm1: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::expm1(m.Value()));
break;
}
case IrOpcode::kFloat64Log: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::log(m.Value()));
break;
}
case IrOpcode::kFloat64Log1p: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::log1p(m.Value()));
break;
}
case IrOpcode::kFloat64Log10: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::log10(m.Value()));
break;
}
case IrOpcode::kFloat64Log2: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::log2(m.Value()));
break;
}
case IrOpcode::kFloat64Pow: {
Float64BinopMatcher m(node);
if (m.IsFoldable()) {
return ReplaceFloat64(
base::ieee754::pow(m.left().Value(), m.right().Value()));
} else if (m.right().Is(0.0)) { // x ** +-0.0 => 1.0
return ReplaceFloat64(1.0);
} else if (m.right().Is(-2.0)) { // x ** -2.0 => 1 / (x * x)
node->ReplaceInput(0, Float64Constant(1.0));
node->ReplaceInput(1, Float64Mul(m.left().node(), m.left().node()));
NodeProperties::ChangeOp(node, machine()->Float64Div());
return Changed(node);
} else if (m.right().Is(2.0)) { // x ** 2.0 => x * x
node->ReplaceInput(1, m.left().node());
NodeProperties::ChangeOp(node, machine()->Float64Mul());
return Changed(node);
} else if (m.right().Is(-0.5)) {
// x ** 0.5 => 1 / (if x <= -Infinity then Infinity else sqrt(0.0 + x))
node->ReplaceInput(0, Float64Constant(1.0));
node->ReplaceInput(1, Float64PowHalf(m.left().node()));
NodeProperties::ChangeOp(node, machine()->Float64Div());
return Changed(node);
} else if (m.right().Is(0.5)) {
// x ** 0.5 => if x <= -Infinity then Infinity else sqrt(0.0 + x)
return Replace(Float64PowHalf(m.left().node()));
}
break;
}
case IrOpcode::kFloat64Sin: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::sin(m.Value()));
break;
}
case IrOpcode::kFloat64Sinh: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::sinh(m.Value()));
break;
}
case IrOpcode::kFloat64Tan: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::tan(m.Value()));
break;
}
case IrOpcode::kFloat64Tanh: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(base::ieee754::tanh(m.Value()));
break;
}
case IrOpcode::kChangeFloat32ToFloat64: {
Float32Matcher m(node->InputAt(0));
if (m.HasValue()) {
if (!allow_signalling_nan_ && std::isnan(m.Value())) {
// Do some calculation to make guarantee the value is a quiet NaN.
return ReplaceFloat64(m.Value() + m.Value());
}
return ReplaceFloat64(m.Value());
}
break;
}
case IrOpcode::kChangeFloat64ToInt32: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceInt32(FastD2IChecked(m.Value()));
if (m.IsChangeInt32ToFloat64()) return Replace(m.node()->InputAt(0));
break;
}
case IrOpcode::kChangeFloat64ToInt64: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceInt64(static_cast<int64_t>(m.Value()));
if (m.IsChangeInt64ToFloat64()) return Replace(m.node()->InputAt(0));
break;
}
case IrOpcode::kChangeFloat64ToUint32: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceInt32(FastD2UI(m.Value()));
if (m.IsChangeUint32ToFloat64()) return Replace(m.node()->InputAt(0));
break;
}
case IrOpcode::kChangeInt32ToFloat64: {
Int32Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(FastI2D(m.Value()));
break;
}
case IrOpcode::kChangeInt32ToInt64: {
Int32Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceInt64(m.Value());
break;
}
case IrOpcode::kChangeInt64ToFloat64: {
Int64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(static_cast<double>(m.Value()));
if (m.IsChangeFloat64ToInt64()) return Replace(m.node()->InputAt(0));
break;
}
case IrOpcode::kChangeUint32ToFloat64: {
Uint32Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceFloat64(FastUI2D(m.Value()));
break;
}
case IrOpcode::kChangeUint32ToUint64: {
Uint32Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceInt64(static_cast<uint64_t>(m.Value()));
break;
}
case IrOpcode::kTruncateFloat64ToWord32: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceInt32(DoubleToInt32(m.Value()));
if (m.IsChangeInt32ToFloat64()) return Replace(m.node()->InputAt(0));
return NoChange();
}
case IrOpcode::kTruncateInt64ToInt32: {
Int64Matcher m(node->InputAt(0));
if (m.HasValue()) return ReplaceInt32(static_cast<int32_t>(m.Value()));
if (m.IsChangeInt32ToInt64()) return Replace(m.node()->InputAt(0));
break;
}
case IrOpcode::kTruncateFloat64ToFloat32: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) {
if (!allow_signalling_nan_ && std::isnan(m.Value())) {
// Do some calculation to make guarantee the value is a quiet NaN.
return ReplaceFloat32(DoubleToFloat32(m.Value() + m.Value()));
}
return ReplaceFloat32(DoubleToFloat32(m.Value()));
}
if (allow_signalling_nan_ && m.IsChangeFloat32ToFloat64())
return Replace(m.node()->InputAt(0));
break;
}
case IrOpcode::kRoundFloat64ToInt32: {
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) {
return ReplaceInt32(DoubleToInt32(m.Value()));
}
if (m.IsChangeInt32ToFloat64()) return Replace(m.node()->InputAt(0));
break;
}
case IrOpcode::kFloat64InsertLowWord32:
return ReduceFloat64InsertLowWord32(node);
case IrOpcode::kFloat64InsertHighWord32:
return ReduceFloat64InsertHighWord32(node);
case IrOpcode::kStore:
case IrOpcode::kUnalignedStore:
return ReduceStore(node);
case IrOpcode::kFloat64Equal:
case IrOpcode::kFloat64LessThan:
case IrOpcode::kFloat64LessThanOrEqual:
return ReduceFloat64Compare(node);
case IrOpcode::kFloat64RoundDown:
return ReduceFloat64RoundDown(node);
case IrOpcode::kBitcastTaggedToWord:
case IrOpcode::kBitcastTaggedSignedToWord: {
NodeMatcher m(node->InputAt(0));
if (m.IsBitcastWordToTaggedSigned()) {
RelaxEffectsAndControls(node);
return Replace(m.InputAt(0));
}
break;
}
default:
break;
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceInt32Add(Node* node) {
DCHECK_EQ(IrOpcode::kInt32Add, node->opcode());
Int32BinopMatcher m(node);
if (m.right().Is(0)) return Replace(m.left().node()); // x + 0 => x
if (m.IsFoldable()) { // K + K => K
return ReplaceInt32(
base::AddWithWraparound(m.left().Value(), m.right().Value()));
}
if (m.left().IsInt32Sub()) {
Int32BinopMatcher mleft(m.left().node());
if (mleft.left().Is(0)) { // (0 - x) + y => y - x
node->ReplaceInput(0, m.right().node());
node->ReplaceInput(1, mleft.right().node());
NodeProperties::ChangeOp(node, machine()->Int32Sub());
Reduction const reduction = ReduceInt32Sub(node);
return reduction.Changed() ? reduction : Changed(node);
}
}
if (m.right().IsInt32Sub()) {
Int32BinopMatcher mright(m.right().node());
if (mright.left().Is(0)) { // y + (0 - x) => y - x
node->ReplaceInput(1, mright.right().node());
NodeProperties::ChangeOp(node, machine()->Int32Sub());
Reduction const reduction = ReduceInt32Sub(node);
return reduction.Changed() ? reduction : Changed(node);
}
}
// (x + Int32Constant(a)) + Int32Constant(b)) => x + Int32Constant(a + b)
if (m.right().HasValue() && m.left().IsInt32Add()) {
Int32BinopMatcher n(m.left().node());
if (n.right().HasValue() && m.OwnsInput(m.left().node())) {
node->ReplaceInput(1, Int32Constant(base::AddWithWraparound(
m.right().Value(), n.right().Value())));
node->ReplaceInput(0, n.left().node());
return Changed(node);
}
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceInt64Add(Node* node) {
DCHECK_EQ(IrOpcode::kInt64Add, node->opcode());
Int64BinopMatcher m(node);
if (m.right().Is(0)) return Replace(m.left().node()); // x + 0 => 0
if (m.IsFoldable()) {
return ReplaceInt64(
base::AddWithWraparound(m.left().Value(), m.right().Value()));
}
// (x + Int64Constant(a)) + Int64Constant(b)) => x + Int64Constant(a + b)
if (m.right().HasValue() && m.left().IsInt64Add()) {
Int64BinopMatcher n(m.left().node());
if (n.right().HasValue() && m.OwnsInput(m.left().node())) {
node->ReplaceInput(1, Int64Constant(base::AddWithWraparound(
m.right().Value(), n.right().Value())));
node->ReplaceInput(0, n.left().node());
return Changed(node);
}
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceInt32Sub(Node* node) {
DCHECK_EQ(IrOpcode::kInt32Sub, node->opcode());
Int32BinopMatcher m(node);
if (m.right().Is(0)) return Replace(m.left().node()); // x - 0 => x
if (m.IsFoldable()) { // K - K => K
return ReplaceInt32(
base::SubWithWraparound(m.left().Value(), m.right().Value()));
}
if (m.LeftEqualsRight()) return ReplaceInt32(0); // x - x => 0
if (m.right().HasValue()) { // x - K => x + -K
node->ReplaceInput(
1, Int32Constant(base::NegateWithWraparound(m.right().Value())));
NodeProperties::ChangeOp(node, machine()->Int32Add());
Reduction const reduction = ReduceInt32Add(node);
return reduction.Changed() ? reduction : Changed(node);
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceInt64Sub(Node* node) {
DCHECK_EQ(IrOpcode::kInt64Sub, node->opcode());
Int64BinopMatcher m(node);
if (m.right().Is(0)) return Replace(m.left().node()); // x - 0 => x
if (m.IsFoldable()) { // K - K => K
return ReplaceInt64(
base::SubWithWraparound(m.left().Value(), m.right().Value()));
}
if (m.LeftEqualsRight()) return Replace(Int64Constant(0)); // x - x => 0
if (m.right().HasValue()) { // x - K => x + -K
node->ReplaceInput(
1, Int64Constant(base::NegateWithWraparound(m.right().Value())));
NodeProperties::ChangeOp(node, machine()->Int64Add());
Reduction const reduction = ReduceInt64Add(node);
return reduction.Changed() ? reduction : Changed(node);
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceInt32Div(Node* node) {
Int32BinopMatcher m(node);
if (m.left().Is(0)) return Replace(m.left().node()); // 0 / x => 0
if (m.right().Is(0)) return Replace(m.right().node()); // x / 0 => 0
if (m.right().Is(1)) return Replace(m.left().node()); // x / 1 => x
if (m.IsFoldable()) { // K / K => K
return ReplaceInt32(
base::bits::SignedDiv32(m.left().Value(), m.right().Value()));
}
if (m.LeftEqualsRight()) { // x / x => x != 0
Node* const zero = Int32Constant(0);
return Replace(Word32Equal(Word32Equal(m.left().node(), zero), zero));
}
if (m.right().Is(-1)) { // x / -1 => 0 - x
node->ReplaceInput(0, Int32Constant(0));
node->ReplaceInput(1, m.left().node());
node->TrimInputCount(2);
NodeProperties::ChangeOp(node, machine()->Int32Sub());
return Changed(node);
}
if (m.right().HasValue()) {
int32_t const divisor = m.right().Value();
Node* const dividend = m.left().node();
Node* quotient = dividend;
if (base::bits::IsPowerOfTwo(Abs(divisor))) {
uint32_t const shift = WhichPowerOf2(Abs(divisor));
DCHECK_NE(0u, shift);
if (shift > 1) {
quotient = Word32Sar(quotient, 31);
}
quotient = Int32Add(Word32Shr(quotient, 32u - shift), dividend);
quotient = Word32Sar(quotient, shift);
} else {
quotient = Int32Div(quotient, Abs(divisor));
}
if (divisor < 0) {
node->ReplaceInput(0, Int32Constant(0));
node->ReplaceInput(1, quotient);
node->TrimInputCount(2);
NodeProperties::ChangeOp(node, machine()->Int32Sub());
return Changed(node);
}
return Replace(quotient);
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceUint32Div(Node* node) {
Uint32BinopMatcher m(node);
if (m.left().Is(0)) return Replace(m.left().node()); // 0 / x => 0
if (m.right().Is(0)) return Replace(m.right().node()); // x / 0 => 0
if (m.right().Is(1)) return Replace(m.left().node()); // x / 1 => x
if (m.IsFoldable()) { // K / K => K
return ReplaceUint32(
base::bits::UnsignedDiv32(m.left().Value(), m.right().Value()));
}
if (m.LeftEqualsRight()) { // x / x => x != 0
Node* const zero = Int32Constant(0);
return Replace(Word32Equal(Word32Equal(m.left().node(), zero), zero));
}
if (m.right().HasValue()) {
Node* const dividend = m.left().node();
uint32_t const divisor = m.right().Value();
if (base::bits::IsPowerOfTwo(divisor)) { // x / 2^n => x >> n
node->ReplaceInput(1, Uint32Constant(WhichPowerOf2(m.right().Value())));
node->TrimInputCount(2);
NodeProperties::ChangeOp(node, machine()->Word32Shr());
return Changed(node);
} else {
return Replace(Uint32Div(dividend, divisor));
}
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceInt32Mod(Node* node) {
Int32BinopMatcher m(node);
if (m.left().Is(0)) return Replace(m.left().node()); // 0 % x => 0
if (m.right().Is(0)) return Replace(m.right().node()); // x % 0 => 0
if (m.right().Is(1)) return ReplaceInt32(0); // x % 1 => 0
if (m.right().Is(-1)) return ReplaceInt32(0); // x % -1 => 0
if (m.LeftEqualsRight()) return ReplaceInt32(0); // x % x => 0
if (m.IsFoldable()) { // K % K => K
return ReplaceInt32(
base::bits::SignedMod32(m.left().Value(), m.right().Value()));
}
if (m.right().HasValue()) {
Node* const dividend = m.left().node();
uint32_t const divisor = Abs(m.right().Value());
if (base::bits::IsPowerOfTwo(divisor)) {
uint32_t const mask = divisor - 1;
Node* const zero = Int32Constant(0);
Diamond d(graph(), common(),
graph()->NewNode(machine()->Int32LessThan(), dividend, zero),
BranchHint::kFalse);
return Replace(
d.Phi(MachineRepresentation::kWord32,
Int32Sub(zero, Word32And(Int32Sub(zero, dividend), mask)),
Word32And(dividend, mask)));
} else {
Node* quotient = Int32Div(dividend, divisor);
DCHECK_EQ(dividend, node->InputAt(0));
node->ReplaceInput(1, Int32Mul(quotient, Int32Constant(divisor)));
node->TrimInputCount(2);
NodeProperties::ChangeOp(node, machine()->Int32Sub());
}
return Changed(node);
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceUint32Mod(Node* node) {
Uint32BinopMatcher m(node);
if (m.left().Is(0)) return Replace(m.left().node()); // 0 % x => 0
if (m.right().Is(0)) return Replace(m.right().node()); // x % 0 => 0
if (m.right().Is(1)) return ReplaceUint32(0); // x % 1 => 0
if (m.LeftEqualsRight()) return ReplaceInt32(0); // x % x => 0
if (m.IsFoldable()) { // K % K => K
return ReplaceUint32(
base::bits::UnsignedMod32(m.left().Value(), m.right().Value()));
}
if (m.right().HasValue()) {
Node* const dividend = m.left().node();
uint32_t const divisor = m.right().Value();
if (base::bits::IsPowerOfTwo(divisor)) { // x % 2^n => x & 2^n-1
node->ReplaceInput(1, Uint32Constant(m.right().Value() - 1));
node->TrimInputCount(2);
NodeProperties::ChangeOp(node, machine()->Word32And());
} else {
Node* quotient = Uint32Div(dividend, divisor);
DCHECK_EQ(dividend, node->InputAt(0));
node->ReplaceInput(1, Int32Mul(quotient, Uint32Constant(divisor)));
node->TrimInputCount(2);
NodeProperties::ChangeOp(node, machine()->Int32Sub());
}
return Changed(node);
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceStore(Node* node) {
NodeMatcher nm(node);
MachineRepresentation rep;
int value_input;
if (nm.IsStore()) {
rep = StoreRepresentationOf(node->op()).representation();
value_input = 2;
} else {
DCHECK(nm.IsUnalignedStore());
rep = UnalignedStoreRepresentationOf(node->op());
value_input = 2;
}
Node* const value = node->InputAt(value_input);
switch (value->opcode()) {
case IrOpcode::kWord32And: {
Uint32BinopMatcher m(value);
if (m.right().HasValue() && ((rep == MachineRepresentation::kWord8 &&
(m.right().Value() & 0xFF) == 0xFF) ||
(rep == MachineRepresentation::kWord16 &&
(m.right().Value() & 0xFFFF) == 0xFFFF))) {
node->ReplaceInput(value_input, m.left().node());
return Changed(node);
}
break;
}
case IrOpcode::kWord32Sar: {
Int32BinopMatcher m(value);
if (m.left().IsWord32Shl() && ((rep == MachineRepresentation::kWord8 &&
m.right().IsInRange(1, 24)) ||
(rep == MachineRepresentation::kWord16 &&
m.right().IsInRange(1, 16)))) {
Int32BinopMatcher mleft(m.left().node());
if (mleft.right().Is(m.right().Value())) {
node->ReplaceInput(value_input, mleft.left().node());
return Changed(node);
}
}
break;
}
default:
break;
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceProjection(size_t index, Node* node) {
switch (node->opcode()) {
case IrOpcode::kInt32AddWithOverflow: {
DCHECK(index == 0 || index == 1);
Int32BinopMatcher m(node);
if (m.IsFoldable()) {
int32_t val;
bool ovf = base::bits::SignedAddOverflow32(m.left().Value(),
m.right().Value(), &val);
return ReplaceInt32(index == 0 ? val : ovf);
}
if (m.right().Is(0)) {
return Replace(index == 0 ? m.left().node() : m.right().node());
}
break;
}
case IrOpcode::kInt32SubWithOverflow: {
DCHECK(index == 0 || index == 1);
Int32BinopMatcher m(node);
if (m.IsFoldable()) {
int32_t val;
bool ovf = base::bits::SignedSubOverflow32(m.left().Value(),
m.right().Value(), &val);
return ReplaceInt32(index == 0 ? val : ovf);
}
if (m.right().Is(0)) {
return Replace(index == 0 ? m.left().node() : m.right().node());
}
break;
}
case IrOpcode::kInt32MulWithOverflow: {
DCHECK(index == 0 || index == 1);
Int32BinopMatcher m(node);
if (m.IsFoldable()) {
int32_t val;
bool ovf = base::bits::SignedMulOverflow32(m.left().Value(),
m.right().Value(), &val);
return ReplaceInt32(index == 0 ? val : ovf);
}
if (m.right().Is(0)) {
return Replace(m.right().node());
}
if (m.right().Is(1)) {
return index == 0 ? Replace(m.left().node()) : ReplaceInt32(0);
}
break;
}
default:
break;
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceWord32Shifts(Node* node) {
DCHECK((node->opcode() == IrOpcode::kWord32Shl) ||
(node->opcode() == IrOpcode::kWord32Shr) ||
(node->opcode() == IrOpcode::kWord32Sar));
if (machine()->Word32ShiftIsSafe()) {
// Remove the explicit 'and' with 0x1F if the shift provided by the machine
// instruction matches that required by JavaScript.
Int32BinopMatcher m(node);
if (m.right().IsWord32And()) {
Int32BinopMatcher mright(m.right().node());
if (mright.right().Is(0x1F)) {
node->ReplaceInput(1, mright.left().node());
return Changed(node);
}
}
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceWord32Shl(Node* node) {
DCHECK_EQ(IrOpcode::kWord32Shl, node->opcode());
Int32BinopMatcher m(node);
if (m.right().Is(0)) return Replace(m.left().node()); // x << 0 => x
if (m.IsFoldable()) { // K << K => K
return ReplaceInt32(
base::ShlWithWraparound(m.left().Value(), m.right().Value()));
}
if (m.right().IsInRange(1, 31)) {
// (x >>> K) << K => x & ~(2^K - 1)
// (x >> K) << K => x & ~(2^K - 1)
if (m.left().IsWord32Sar() || m.left().IsWord32Shr()) {
Int32BinopMatcher mleft(m.left().node());
if (mleft.right().Is(m.right().Value())) {
node->ReplaceInput(0, mleft.left().node());
node->ReplaceInput(1,
Uint32Constant(~((1U << m.right().Value()) - 1U)));
NodeProperties::ChangeOp(node, machine()->Word32And());
Reduction reduction = ReduceWord32And(node);
return reduction.Changed() ? reduction : Changed(node);
}
}
}
return ReduceWord32Shifts(node);
}
Reduction MachineOperatorReducer::ReduceWord64Shl(Node* node) {
DCHECK_EQ(IrOpcode::kWord64Shl, node->opcode());
Int64BinopMatcher m(node);
if (m.right().Is(0)) return Replace(m.left().node()); // x << 0 => x
if (m.IsFoldable()) { // K << K => K
return ReplaceInt64(
base::ShlWithWraparound(m.left().Value(), m.right().Value()));
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceWord32Shr(Node* node) {
Uint32BinopMatcher m(node);
if (m.right().Is(0)) return Replace(m.left().node()); // x >>> 0 => x
if (m.IsFoldable()) { // K >>> K => K
return ReplaceInt32(m.left().Value() >> (m.right().Value() & 31));
}
if (m.left().IsWord32And() && m.right().HasValue()) {
Uint32BinopMatcher mleft(m.left().node());
if (mleft.right().HasValue()) {
uint32_t shift = m.right().Value() & 31;
uint32_t mask = mleft.right().Value();
if ((mask >> shift) == 0) {
// (m >>> s) == 0 implies ((x & m) >>> s) == 0
return ReplaceInt32(0);
}
}
}
return ReduceWord32Shifts(node);
}
Reduction MachineOperatorReducer::ReduceWord64Shr(Node* node) {
DCHECK_EQ(IrOpcode::kWord64Shr, node->opcode());
Uint64BinopMatcher m(node);
if (m.right().Is(0)) return Replace(m.left().node()); // x >>> 0 => x
if (m.IsFoldable()) { // K >> K => K
return ReplaceInt64(m.left().Value() >> (m.right().Value() & 63));
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceWord32Sar(Node* node) {
Int32BinopMatcher m(node);
if (m.right().Is(0)) return Replace(m.left().node()); // x >> 0 => x
if (m.IsFoldable()) { // K >> K => K
return ReplaceInt32(m.left().Value() >> (m.right().Value() & 31));
}
if (m.left().IsWord32Shl()) {
Int32BinopMatcher mleft(m.left().node());
if (mleft.left().IsComparison()) {
if (m.right().Is(31) && mleft.right().Is(31)) {
// Comparison << 31 >> 31 => 0 - Comparison
node->ReplaceInput(0, Int32Constant(0));
node->ReplaceInput(1, mleft.left().node());
NodeProperties::ChangeOp(node, machine()->Int32Sub());
Reduction const reduction = ReduceInt32Sub(node);
return reduction.Changed() ? reduction : Changed(node);
}
} else if (mleft.left().IsLoad()) {
LoadRepresentation const rep =
LoadRepresentationOf(mleft.left().node()->op());
if (m.right().Is(24) && mleft.right().Is(24) &&
rep == MachineType::Int8()) {
// Load[kMachInt8] << 24 >> 24 => Load[kMachInt8]
return Replace(mleft.left().node());
}
if (m.right().Is(16) && mleft.right().Is(16) &&
rep == MachineType::Int16()) {
// Load[kMachInt16] << 16 >> 16 => Load[kMachInt8]
return Replace(mleft.left().node());
}
}
}
return ReduceWord32Shifts(node);
}
Reduction MachineOperatorReducer::ReduceWord64Sar(Node* node) {
Int64BinopMatcher m(node);
if (m.right().Is(0)) return Replace(m.left().node()); // x >> 0 => x
if (m.IsFoldable()) {
return ReplaceInt64(m.left().Value() >> (m.right().Value() & 63));
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceWord32And(Node* node) {
DCHECK_EQ(IrOpcode::kWord32And, node->opcode());
Int32BinopMatcher m(node);
if (m.right().Is(0)) return Replace(m.right().node()); // x & 0 => 0
if (m.right().Is(-1)) return Replace(m.left().node()); // x & -1 => x
if (m.left().IsComparison() && m.right().Is(1)) { // CMP & 1 => CMP
return Replace(m.left().node());
}
if (m.IsFoldable()) { // K & K => K
return ReplaceInt32(m.left().Value() & m.right().Value());
}
if (m.LeftEqualsRight()) return Replace(m.left().node()); // x & x => x
if (m.left().IsWord32And() && m.right().HasValue()) {
Int32BinopMatcher mleft(m.left().node());
if (mleft.right().HasValue()) { // (x & K) & K => x & K
node->ReplaceInput(0, mleft.left().node());
node->ReplaceInput(
1, Int32Constant(m.right().Value() & mleft.right().Value()));
Reduction const reduction = ReduceWord32And(node);
return reduction.Changed() ? reduction : Changed(node);
}
}
if (m.right().IsNegativePowerOf2()) {
int32_t const mask = m.right().Value();
int32_t const neg_mask = base::NegateWithWraparound(mask);
if (m.left().IsWord32Shl()) {
Uint32BinopMatcher mleft(m.left().node());
if (mleft.right().HasValue() &&
(mleft.right().Value() & 0x1F) >=
base::bits::CountTrailingZeros(mask)) {
// (x << L) & (-1 << K) => x << L iff L >= K
return Replace(mleft.node());
}
} else if (m.left().IsInt32Add()) {
Int32BinopMatcher mleft(m.left().node());
if (mleft.right().HasValue() &&
(mleft.right().Value() & mask) == mleft.right().Value()) {
// (x + (K << L)) & (-1 << L) => (x & (-1 << L)) + (K << L)
node->ReplaceInput(0, Word32And(mleft.left().node(), m.right().node()));
node->ReplaceInput(1, mleft.right().node());
NodeProperties::ChangeOp(node, machine()->Int32Add());
Reduction const reduction = ReduceInt32Add(node);
return reduction.Changed() ? reduction : Changed(node);
}
if (mleft.left().IsInt32Mul()) {
Int32BinopMatcher mleftleft(mleft.left().node());
if (mleftleft.right().IsMultipleOf(neg_mask)) {
// (y * (K << L) + x) & (-1 << L) => (x & (-1 << L)) + y * (K << L)
node->ReplaceInput(0,
Word32And(mleft.right().node(), m.right().node()));
node->ReplaceInput(1, mleftleft.node());
NodeProperties::ChangeOp(node, machine()->Int32Add());
Reduction const reduction = ReduceInt32Add(node);
return reduction.Changed() ? reduction : Changed(node);
}
}
if (mleft.right().IsInt32Mul()) {
Int32BinopMatcher mleftright(mleft.right().node());
if (mleftright.right().IsMultipleOf(neg_mask)) {
// (x + y * (K << L)) & (-1 << L) => (x & (-1 << L)) + y * (K << L)
node->ReplaceInput(0,
Word32And(mleft.left().node(), m.right().node()));
node->ReplaceInput(1, mleftright.node());
NodeProperties::ChangeOp(node, machine()->Int32Add());
Reduction const reduction = ReduceInt32Add(node);
return reduction.Changed() ? reduction : Changed(node);
}
}
if (mleft.left().IsWord32Shl()) {
Int32BinopMatcher mleftleft(mleft.left().node());
if (mleftleft.right().Is(base::bits::CountTrailingZeros(mask))) {
// (y << L + x) & (-1 << L) => (x & (-1 << L)) + y << L
node->ReplaceInput(0,
Word32And(mleft.right().node(), m.right().node()));
node->ReplaceInput(1, mleftleft.node());
NodeProperties::ChangeOp(node, machine()->Int32Add());
Reduction const reduction = ReduceInt32Add(node);
return reduction.Changed() ? reduction : Changed(node);
}
}
if (mleft.right().IsWord32Shl()) {
Int32BinopMatcher mleftright(mleft.right().node());
if (mleftright.right().Is(base::bits::CountTrailingZeros(mask))) {
// (x + y << L) & (-1 << L) => (x & (-1 << L)) + y << L
node->ReplaceInput(0,
Word32And(mleft.left().node(), m.right().node()));
node->ReplaceInput(1, mleftright.node());
NodeProperties::ChangeOp(node, machine()->Int32Add());
Reduction const reduction = ReduceInt32Add(node);
return reduction.Changed() ? reduction : Changed(node);
}
}
} else if (m.left().IsInt32Mul()) {
Int32BinopMatcher mleft(m.left().node());
if (mleft.right().IsMultipleOf(neg_mask)) {
// (x * (K << L)) & (-1 << L) => x * (K << L)
return Replace(mleft.node());
}
}
}
return NoChange();
}
Reduction MachineOperatorReducer::TryMatchWord32Ror(Node* node) {
DCHECK(IrOpcode::kWord32Or == node->opcode() ||
IrOpcode::kWord32Xor == node->opcode());
Int32BinopMatcher m(node);
Node* shl = nullptr;
Node* shr = nullptr;
// Recognize rotation, we are matching:
// * x << y | x >>> (32 - y) => x ror (32 - y), i.e x rol y
// * x << (32 - y) | x >>> y => x ror y
// * x << y ^ x >>> (32 - y) => x ror (32 - y), i.e. x rol y
// * x << (32 - y) ^ x >>> y => x ror y
// as well as their commuted form.
if (m.left().IsWord32Shl() && m.right().IsWord32Shr()) {
shl = m.left().node();
shr = m.right().node();
} else if (m.left().IsWord32Shr() && m.right().IsWord32Shl()) {
shl = m.right().node();
shr = m.left().node();
} else {
return NoChange();
}
Int32BinopMatcher mshl(shl);
Int32BinopMatcher mshr(shr);
if (mshl.left().node() != mshr.left().node()) return NoChange();
if (mshl.right().HasValue() && mshr.right().HasValue()) {
// Case where y is a constant.
if (mshl.right().Value() + mshr.right().Value() != 32) return NoChange();
} else {
Node* sub = nullptr;
Node* y = nullptr;
if (mshl.right().IsInt32Sub()) {
sub = mshl.right().node();
y = mshr.right().node();
} else if (mshr.right().IsInt32Sub()) {
sub = mshr.right().node();
y = mshl.right().node();
} else {
return NoChange();
}
Int32BinopMatcher msub(sub);
if (!msub.left().Is(32) || msub.right().node() != y) return NoChange();
}
node->ReplaceInput(0, mshl.left().node());
node->ReplaceInput(1, mshr.right().node());
NodeProperties::ChangeOp(node, machine()->Word32Ror());
return Changed(node);
}
Reduction MachineOperatorReducer::ReduceWord32Or(Node* node) {
DCHECK_EQ(IrOpcode::kWord32Or, node->opcode());
Int32BinopMatcher m(node);
if (m.right().Is(0)) return Replace(m.left().node()); // x | 0 => x
if (m.right().Is(-1)) return Replace(m.right().node()); // x | -1 => -1
if (m.IsFoldable()) { // K | K => K
return ReplaceInt32(m.left().Value() | m.right().Value());
}
if (m.LeftEqualsRight()) return Replace(m.left().node()); // x | x => x
return TryMatchWord32Ror(node);
}
Reduction MachineOperatorReducer::ReduceWord32Xor(Node* node) {
DCHECK_EQ(IrOpcode::kWord32Xor, node->opcode());
Int32BinopMatcher m(node);
if (m.right().Is(0)) return Replace(m.left().node()); // x ^ 0 => x
if (m.IsFoldable()) { // K ^ K => K
return ReplaceInt32(m.left().Value() ^ m.right().Value());
}
if (m.LeftEqualsRight()) return ReplaceInt32(0); // x ^ x => 0
if (m.left().IsWord32Xor() && m.right().Is(-1)) {
Int32BinopMatcher mleft(m.left().node());
if (mleft.right().Is(-1)) { // (x ^ -1) ^ -1 => x
return Replace(mleft.left().node());
}
}
return TryMatchWord32Ror(node);
}
Reduction MachineOperatorReducer::ReduceFloat64InsertLowWord32(Node* node) {
DCHECK_EQ(IrOpcode::kFloat64InsertLowWord32, node->opcode());
Float64Matcher mlhs(node->InputAt(0));
Uint32Matcher mrhs(node->InputAt(1));
if (mlhs.HasValue() && mrhs.HasValue()) {
return ReplaceFloat64(bit_cast<double>(
(bit_cast<uint64_t>(mlhs.Value()) & uint64_t{0xFFFFFFFF00000000}) |
mrhs.Value()));
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceFloat64InsertHighWord32(Node* node) {
DCHECK_EQ(IrOpcode::kFloat64InsertHighWord32, node->opcode());
Float64Matcher mlhs(node->InputAt(0));
Uint32Matcher mrhs(node->InputAt(1));
if (mlhs.HasValue() && mrhs.HasValue()) {
return ReplaceFloat64(bit_cast<double>(
(bit_cast<uint64_t>(mlhs.Value()) & uint64_t{0xFFFFFFFF}) |
(static_cast<uint64_t>(mrhs.Value()) << 32)));
}
return NoChange();
}
namespace {
bool IsFloat64RepresentableAsFloat32(const Float64Matcher& m) {
if (m.HasValue()) {
double v = m.Value();
return DoubleToFloat32(v) == v;
}
return false;
}
} // namespace
Reduction MachineOperatorReducer::ReduceFloat64Compare(Node* node) {
DCHECK(IrOpcode::kFloat64Equal == node->opcode() ||
IrOpcode::kFloat64LessThan == node->opcode() ||
IrOpcode::kFloat64LessThanOrEqual == node->opcode());
Float64BinopMatcher m(node);
if (m.IsFoldable()) {
switch (node->opcode()) {
case IrOpcode::kFloat64Equal:
return ReplaceBool(m.left().Value() == m.right().Value());
case IrOpcode::kFloat64LessThan:
return ReplaceBool(m.left().Value() < m.right().Value());
case IrOpcode::kFloat64LessThanOrEqual:
return ReplaceBool(m.left().Value() <= m.right().Value());
default:
UNREACHABLE();
}
} else if ((m.left().IsChangeFloat32ToFloat64() &&
m.right().IsChangeFloat32ToFloat64()) ||
(m.left().IsChangeFloat32ToFloat64() &&
IsFloat64RepresentableAsFloat32(m.right())) ||
(IsFloat64RepresentableAsFloat32(m.left()) &&
m.right().IsChangeFloat32ToFloat64())) {
// As all Float32 values have an exact representation in Float64, comparing
// two Float64 values both converted from Float32 is equivalent to comparing
// the original Float32s, so we can ignore the conversions. We can also
// reduce comparisons of converted Float64 values against constants that
// can be represented exactly as Float32.
switch (node->opcode()) {
case IrOpcode::kFloat64Equal:
NodeProperties::ChangeOp(node, machine()->Float32Equal());
break;
case IrOpcode::kFloat64LessThan:
NodeProperties::ChangeOp(node, machine()->Float32LessThan());
break;
case IrOpcode::kFloat64LessThanOrEqual:
NodeProperties::ChangeOp(node, machine()->Float32LessThanOrEqual());
break;
default:
UNREACHABLE();
}
node->ReplaceInput(
0, m.left().HasValue()
? Float32Constant(static_cast<float>(m.left().Value()))
: m.left().InputAt(0));
node->ReplaceInput(
1, m.right().HasValue()
? Float32Constant(static_cast<float>(m.right().Value()))
: m.right().InputAt(0));
return Changed(node);
}
return NoChange();
}
Reduction MachineOperatorReducer::ReduceFloat64RoundDown(Node* node) {
DCHECK_EQ(IrOpcode::kFloat64RoundDown, node->opcode());
Float64Matcher m(node->InputAt(0));
if (m.HasValue()) {
return ReplaceFloat64(std::floor(m.Value()));
}
return NoChange();
}
CommonOperatorBuilder* MachineOperatorReducer::common() const {
return mcgraph()->common();
}
MachineOperatorBuilder* MachineOperatorReducer::machine() const {
return mcgraph()->machine();
}
Graph* MachineOperatorReducer::graph() const { return mcgraph()->graph(); }
} // namespace compiler
} // namespace internal
} // namespace v8
|
/**
* @file camoto/gamemusic/music.hpp
* @brief Declaration of top-level Music class, for in-memory representation
* of all music formats.
*
* Copyright (C) 2010-2015 Adam Nielsen <malvineous@shikadi.net>
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#ifndef _CAMOTO_GAMEMUSIC_MUSIC_HPP_
#define _CAMOTO_GAMEMUSIC_MUSIC_HPP_
#include <math.h>
#include <boost/shared_ptr.hpp>
#include <camoto/metadata.hpp>
#include <camoto/gamemusic/tempo.hpp>
namespace camoto {
namespace gamemusic {
struct Music;
/// Shared pointer to a Music instance.
typedef boost::shared_ptr<Music> MusicPtr;
/// Shared pointer to an unmodifiable Music instance.
typedef boost::shared_ptr<const Music> ConstMusicPtr;
} // namespace gamemusic
} // namespace camoto
#include <camoto/gamemusic/patchbank.hpp>
#include <camoto/gamemusic/events.hpp>
namespace camoto {
namespace gamemusic {
/// Information about a track, shared across all patterns.
/**
* This controls which channel a track's events are played on.
*/
struct DLL_EXPORT TrackInfo
{
/// Channel type
enum ChannelType {
UnusedChannel,
AnyChannel,
OPLChannel,
OPLPercChannel,
MIDIChannel,
PCMChannel,
};
/// What type of channel this track will be played through.
ChannelType channelType;
/// Channel index.
/**
* When type is:
*
* - AnyChannel: this value is 0-255. The value
* is not so important, but only one note can be played on each channel
* at a time, across all tracks. It is not valid to write any tracks
* with this channel type set. All AnyChannel tracks must be mapped to
* other values before a song is passed to a format writer. This is to
* prevent every format writer from having to map channels itself.
* @todo: Make a utility function to do this.
*
* - OPLChannel: this value is 0 to 8 for normal OPL channels on
* chip 1, and 9 to 17 for chip 2. Some events are global and will affect
* the whole chip regardless of what track they are played on.
*
* - OPLPercChannel: this value is 4 for bass drum, 3 for snare, 2 for tomtom,
* 1 for top cymbal, 0 for hi-hat. Other values are invalid.
*
* - MIDIChannel: this value is 0 to 15, with 9 being percussion.
*
* - PCMChannel: this value is the channel index starting at 0. For some
* formats like .mod, this affects the panning of the channel.
*
* Note that OPL percussion mode uses channels 6, 7 and 8, so it is not
* valid for a song to have OPLChannel events on these channels while
* OPLPercChannel events are present. This may happen temporarily during a
* format conversion, but this state must be resolved by the time the
* data is written out to a file.
*/
unsigned int channelIndex;
};
/// Vector of trackinfo (a channel map)
typedef std::vector<TrackInfo> TrackInfoVector;
/// In-memory representation of a single song.
/**
* This class represents a single song in an arbitrary file format. The
* instruments (patches) can be read and modified, as can the events making up
* the melody and percussion. Care must be taken when writing a Music object
* back to a file, as most file formats only support differing subsets of the
* capabilities presented here.
*/
struct Music
{
/// PatchBank holding all instruments in the song.
PatchBankPtr patches;
/// List of all tracks in the song and their channel allocations.
/**
* A pattern always has the same number of tracks as there are entries in
* this vector, and the allocation specified in this vector holds true for
* all tracks in all patterns.
*/
TrackInfoVector trackInfo;
/// List of events in the song (note on, note off, etc.)
/**
* Each entry in the vector is one pattern, referred to by index into the
* vector. Patterns are played one after the other, in the order given by
* \ref patternOrder.
*/
std::vector<PatternPtr> patterns;
/// Which order the above patterns play in.
/**
* A value of 1 refers to the second entry in \ref patterns.
*/
std::vector<unsigned int> patternOrder;
/// Loop destination.
/**
* -1 means no loop, otherwise this value is the index into
* \ref patternOrder where playback will jump to once the last entry in
* \ref patternOrder has been played.
*
* Note that an effect can also cause a loop independently of this value.
*/
int loopDest;
/// Total number of ticks in each track.
/**
* This is the same for all tracks in all patterns in the song.
*/
unsigned int ticksPerTrack;
/// List of metadata elements set. Remove from map to unset.
Metadata::TypeMap metadata;
/// Initial song tempo, time signature, etc.
/**
* This is the value the song starts with. The actual tempo can be changed
* during playback, but this value always contains the song's starting tempo.
*/
Tempo initialTempo;
};
} // namespace gamemusic
} // namespace camoto
#endif // _CAMOTO_GAMEMUSIC_MUSIC_HPP_
|
//======================================================================================================================
// jumpdir - A smart directory navigation command
//
// Copyright 2017 Steve Hollasch. All rights reserved.
//======================================================================================================================
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <windows.h>
#include <direct.h>
#include <assert.h>
#include <PathMatcher.h>
#include <fileSystemProxyWindows.h>
using namespace PMatcher;
using namespace FSProxy;
// Program Parameters and Constants
bool fDebug = false;
// Version and Usage Information
static const char* usage[] = {
"",
"jumpdir v0.0.10 / (c) 2017 Steve Hollasch",
"",
"jumpdir: Adaptive directory navigation for the command line",
"Usage: jumpdir <directory>",
"",
" This command changes the directory as specified.",
0
};
//======================================================================================================================
// Utility Functions
//======================================================================================================================
void PrintUsage () {
// Prints out usage information for this tool.
//----------------------------------------------------------------------------------------------
int i;
for (i=0; usage[i]; ++i) {
if (usage[i][0] == 0)
puts ("echo.");
else
printf ("echo %s\n", usage[i]);
}
}
//--------------------------------------------------------------------------------------------------
void DPrint (const char* format, ...) {
// Prints one line of debug information. The formatted string does not need a carriage return.
//
// 'format' - a printf-style format string
// ... - the remainder of the printf-style arguments
//----------------------------------------------------------------------------------------------
if (!fDebug) return;
va_list vl;
va_start (vl, format);
fputs ("# ", stderr);
vfprintf_s (stderr, format, vl);
fputc ('\n', stderr);
va_end (vl);
}
//--------------------------------------------------------------------------------------------------
void ErrorPrint (const char* format, ...) {
// Prints a printf-style message plus arguments to the error output stream, followed by a
// carriage return.
//----------------------------------------------------------------------------------------------
va_list vl;
va_start (vl, format);
fputs ("jumpdir: ", stderr);
vfprintf_s (stderr, format, vl);
fputc ('\n', stderr);
va_end (vl);
}
//--------------------------------------------------------------------------------------------------
inline bool streqic (const char *str1, const char *str2) {
// Returns true if the two strings are non-null and equal, ignoring case. Either string
// argument may be null.
//----------------------------------------------------------------------------------------------
return (str1 != 0) && (str2 != 0) && (0 == _stricmp(str1,str2));
}
//--------------------------------------------------------------------------------------------------
void SlashForward (char* str) {
// Given a string pointer, converts all back slashes to forward slashes.
//----------------------------------------------------------------------------------------------
char* ptr;
for (ptr=str; *ptr; ++ptr) {
if (*ptr == '\\')
*ptr = '/';
}
}
//--------------------------------------------------------------------------------------------------
void SlashBackward (char* str) {
// Given a string pointer, converts all forward slashes to back slashes.
//----------------------------------------------------------------------------------------------
char* ptr;
for (ptr=str; *ptr; ++ptr) {
if (*ptr == '/') *ptr = '\\';
}
}
//--------------------------------------------------------------------------------------------------
static bool isWildStr (const char* str) {
// Returns true if the given string begins with a wildcard character sequence.
// This includes '?', '*', '**', or '...'.
//----------------------------------------------------------------------------------------------
return (*str == '?')
|| (*str == '*')
|| ((str[0] == '.') && (str[1] == '.') && (str[2] == '.'));
}
//======================================================================================================================
// Struct DirEntry
//======================================================================================================================
struct DirEntry {
unsigned int m_dvol_name; // Offset of Volume Name
unsigned int m_dvol_label; // Offset of Volume Label
unsigned int m_dpath; // Offset of Path
time_t m_lastverified; // Date Last Verified
DWORD m_serialnum; // Volume Serial Number
bool m_valid; // Entry Valid
DirEntry *m_next; // Next Directory Entry
};
//======================================================================================================================
// Class JDMemPool
//======================================================================================================================
class JDMemPool {
public:
JDMemPool () : m_size{0}, m_heap{0} { }
void Attach (void* block, unsigned int size);
private:
unsigned int m_size;
void *m_heap;
};
//--------------------------------------------------------------------------------------------------
void JDMemPool::Attach (void *block, unsigned int size) {
// This method sets the block and size for the memory pool, as read from the data file. This
// memory pool can be effectively detached by calling it with (0,0) as the arguments.
//
// Ensure that the block is non-null if the size is non-zero.
//----------------------------------------------------------------------------------------------
assert ((size == 0) == (block == NULL));
m_heap = block;
m_size = size;
}
//======================================================================================================================
// Class JDFileHeader
//======================================================================================================================
class JDFileHeader {
public:
JDFileHeader ()
: maxHistSize {-1},
dirEcho {false},
verbose {false},
netSearch {true},
automap {true},
numHistEntries {0}
{
}
// Data Fields
int maxHistSize; // Max Number of History Entries
bool dirEcho; // Echo new directories?
bool verbose; // Echo resultant shell commands?
bool netSearch; // Search network paths?
bool automap; // Automatically map network drives?
unsigned int numHistEntries; // Current count of path history entries
};
//======================================================================================================================
// Class JumpData
//======================================================================================================================
class JumpData {
public:
JumpData() : m_rawData{nullptr} {};
~JumpData();
bool Load (const string& filename);
bool Store (const string& filename) const;
private:
JDFileHeader *m_header;
DirEntry *m_dirEntries; // Directory Entry List
char* m_strpool;
private:
void *m_rawData; // Raw Data File Contents
};
//--------------------------------------------------------------------------------------------------
JumpData::~JumpData () {
if (m_rawData) {
delete [] m_rawData;
}
}
//--------------------------------------------------------------------------------------------------
bool JumpData::Load (const string& filename) {
DPrint ("Reading jumpdata from \"%s\".", filename.c_str());
m_header = new JDFileHeader;
// If the data file does not exist, then silently assume that we're starting
// from scratch.
// ifstream dbStream {filename.c_str()};
if (0 != _access(filename.c_str(), 0))
return true;
// Read in the entire contents of the jump data file into the data buffer.
// Below open in "rb" mode to get an accurate (untranslated) size of the
// entire data file, so we can slurp the entire thing into memory at once.
// If the file is opened in text mode, the size won't be accurate since
// carriage-return/linefeeds may be logically collapsed into a single
// entity.
FILE* dataFile;
if (0 != fopen_s (&dataFile, filename.c_str(), "r,ccs=UTF-8")) {
ErrorPrint ("Couldn't open data file \"%s\".", filename);
return false;
}
// Seek to the end to determine the size of the entire data file.
if (0 != fseek (dataFile, 0, SEEK_END)) {
ErrorPrint ("Couldn't seek in data file \"%s\".", filename);
return false;
}
auto dataCount = ftell (dataFile);
rewind (dataFile);
// Allocate the buffer for the data file contents.
m_rawData = new char [dataCount + 100]; // !!! TEMPORARY !!! buffer for experimentation
if (m_rawData == nullptr) {
ErrorPrint ("Couldn't allocate %ld bytes for jumpdir data.\n", dataCount);
return false;
}
// Read the data file into the data block and close the file.
size_t nItemsRead = fread_s (m_rawData, dataCount, 1, dataCount, dataFile);
if (nItemsRead != dataCount) {
ErrorPrint ("Read failed on data file \"%s\".", filename);
return false;
}
fclose (dataFile);
return true;
}
//--------------------------------------------------------------------------------------------------
bool JumpData::Store (const string& filename) const {
// !!! TEMPORARY !!!
DPrint ("Skipping DB store for development.");
return true;
#if 0
FILE *datafile;
if (0 != _wfopen_s (&datafile, filename, L"wb")) {
ErrorPrint (L"Couldn't create data file \"%s\".", filename);
return false;
}
if (1 != fwrite (m_header, sizeof(JDFileHeader), 1, datafile)) {
ErrorPrint (L"Error while writing data file.");
return false;
}
#endif
#if 0
for (int i=0; i <= 0xff; ++i) {
unsigned char c = static_cast<unsigned char> (i);
if (1 != fwrite (&c, sizeof(unsigned char), 1, datafile)) {
ErrorPrint (L"Error while writing data file.");
return false;
}
}
unsigned int x = 0x11223344;
if (1 != fwrite (&x, sizeof(unsigned int), 1, datafile)) {
ErrorPrint (L"Error while writing data file.");
return false;
}
if (0 > fputws (L"[# Hello world!\n]", datafile)) {
ErrorPrint (L"Error while writing data file.");
return false;
}
#endif
#if 0
fclose (datafile);
#endif
return true;
}
//======================================================================================================================
// Class JDContext
//======================================================================================================================
class JDContext {
//--------------------------------------------------------------------------
// The main data context structure for the jumpdir program.
//--------------------------------------------------------------------------
public:
static const int c_numDrives = 26;
JDContext (FileSysProxy&);
~JDContext() {};
bool ParseArgs (int argc, const char* const argv[]);
bool ScanEnvironment ();
bool ScanDrives ();
bool Load ();
bool Store ();
void EnumerateNetMaps ();
bool HandleTrivialChange();
bool Jump ();
private:
FileSysProxy& m_fsProxy; // File System Proxy
bool AppendDest (const char*); // Appends Path to Destination
string m_dbFilename; // Jumpdir Data File Name
JumpData m_jumpData; // Jump Directory Data
PathMatcher m_pathMatcher; // Wildcard Path Matcher
char m_cwd[MAX_PATH+1]; // Current Working Directory
char* m_driveMaps[c_numDrives]; // Drive Network Mappings
char m_dest[MAX_PATH+1]; // Specified Destination
int m_destlen; // Dest String Length
bool m_destwild; // Destination Contains Wildcards
};
//--------------------------------------------------------------------------------------------------
JDContext::JDContext (FileSysProxy& fsProxy)
: m_fsProxy{fsProxy}, m_pathMatcher{fsProxy} {
int drive;
for (drive=0; drive < c_numDrives; ++drive)
m_driveMaps[drive] = 0;
m_dest[0] = 0;
m_destlen = 0;
m_destwild = false;
}
//--------------------------------------------------------------------------------------------------
bool JDContext::ParseArgs (int argc, const char* const argv[]) {
// Parses the command-line arguments before executing commands. This
// function is also responsible for reading in the data file.
//
// Parameter 'context' is the jumpdir context object. 'argc' and 'argv' are
// the standard command line arguments.
//
// Returns true if the parse succeeded, otherwise false.
//----------------------------------------------------------------------------------------------
int argi; // Argument Index
for (argi=1; argi < argc; ++argi) {
if ( streqic (argv[argi], "-?")
|| streqic (argv[argi], "/?")
|| streqic (argv[argi], "-h")
|| streqic (argv[argi], "/h")
|| streqic (argv[argi], "--help")
)
{
PrintUsage();
continue;
}
if (argv[argi][0] == '-') {
switch (argv[argi][1]) {
case 'd': case 'D': {
fDebug = 1;
break;
}
default: {
ErrorPrint ("Unrecognized command option (%s).", argv[argi]);
exit (1);
break;
}
}
} else {
if (!AppendDest (argv[argi]))
return false;
}
}
DPrint ("Debug flag on");
DPrint ("Destination \"%s\"", m_dest);
DPrint ("Destination is %swild.", m_destwild ? "" : "not ");
// Return true to indicate success.
return true;
}
//--------------------------------------------------------------------------------------------------
bool JDContext::ScanEnvironment () {
// Scans the current environment and initializes the context object
// accordingly. This includes the current working directory, the current
// drive mappings, the data file, and so forth.
//
// Returns true if the scan/initialization succeeded, otherwise false.
//--------------------------------------------------------------------------
// Load the current working directory.
if (!_getcwd (m_cwd, static_cast<int>(std::size(m_cwd))))
return false;
SlashForward (m_cwd);
if (!ScanDrives()) return false;
if (!Load()) return false;
return true;
}
//--------------------------------------------------------------------------------------------------
bool JDContext::ScanDrives () {
// Scan the currently mapped drives for type and other info. Returns True if
// the scan was successful, otherwise false.
//----------------------------------------------------------------------------------------------
return true;
}
//--------------------------------------------------------------------------------------------------
bool JDContext::Load () {
// Loads the jumpdir data file and initializes the related fields in the JDContext object.
//
// Returns True if the scan was successful, otherwise false.
//----------------------------------------------------------------------------------------------
DPrint ("Loading jump data.");
size_t jumpDataStrLength;
getenv_s (&jumpDataStrLength, NULL, 0, "JUMPDATA");
if (jumpDataStrLength) {
auto dbFilename = new char [jumpDataStrLength];
if (0 != getenv_s (&jumpDataStrLength, dbFilename, jumpDataStrLength, "JUMPDATA"))
return false;
m_dbFilename = dbFilename;
DPrint ("Using %%JUMPDATA%%=\"%s\"", m_dbFilename);
} else {
DPrint ("JUMPDATA is not defined.");
size_t userProfileStrLength;
getenv_s (&userProfileStrLength, NULL, 0, "USERPROFILE");
if (!userProfileStrLength) {
DPrint ("USERPROFILE is not defined. Hmmm, didn't expect THAT.");
ErrorPrint ("Couldn't find jumpdir.dat file. Neither JUMPDATA nor\nUSERPROFILE is defined.");
exit (1);
}
auto userProfilePath = new char [userProfileStrLength];
if (0 != getenv_s (&userProfileStrLength, userProfilePath, userProfileStrLength, "USERPROFILE"))
return false;
m_dbFilename = userProfilePath;
m_dbFilename += "\\jumpdir.dat";
DPrint ("Using \"%s\"", m_dbFilename);
}
return m_jumpData.Load(m_dbFilename);
}
//--------------------------------------------------------------------------------------------------
bool JDContext::Store () {
return m_jumpData.Store(m_dbFilename);
}
//--------------------------------------------------------------------------------------------------
void JDContext::EnumerateNetMaps () {
DPrint ("Enumerating network drive mappings.");
// char driveStr[] = "X:";
// char netName [MAX_PATH + 1];
int driveNum;
for (driveNum=0; driveNum < c_numDrives; ++driveNum) {
}
}
//--------------------------------------------------------------------------------------------------
bool JDContext::HandleTrivialChange () {
// This routine handles trivial target directories. This includes null directories, and
// non-wildcard directories that begin with '.' or '..'. This routine assumes that the
// m_destwild member variable has already been set properly.
//----------------------------------------------------------------------------------------------
DPrint ("Trivial change?");
// Bail out if the destination path contains wildcard characters.
if (m_destwild) {
DPrint ("Not trivial; destination path contains wildcards.");
return false;
}
// If no directory was specified, and if no other commands were supplied,
// then echo the current directory.
if (m_dest[0] == 0) {
DPrint ("Null directory; echo current.");
printf ("echo %s\n", m_cwd);
return true;
}
// If this is not a dot directory; then handle elsewhere.
if (m_dest[0] != '.') {
DPrint ("Not trivial (not null and not dot directory).");
return false;
}
// If the directory is literally ".", we're already there, so return true.
if (0 == strcmp(m_dest, ".")) {
DPrint ("Literally '.'; no action.");
return true;
}
// If this is a path that begins with a single dot directory, then use that
// path directly.
if (m_dest[1] == '/') {
SlashBackward (m_dest);
printf ("cd \"%s\"\n", m_dest);
return true;
}
if (m_dest[1] != '.') // Something else that begins with a dot.
return false;
// If the first subdirectory is "..", then use that path directly.
if ((m_dest[2] == 0) || (m_dest[2] == '/')) {
SlashBackward (m_dest);
printf ("cd \"%s\"\n", m_dest);
return true;
}
return false; // For all other paths, handle elsewhere.
}
//--------------------------------------------------------------------------------------------------
bool JDContext::Jump () {
// Jumps to the destination directory.
//
// Returns true if a match was found, and the function successfully changed to that matching
// directory.
//----------------------------------------------------------------------------------------------
if (HandleTrivialChange()) return true;
DPrint ("Seeing if new target matches current directory.");
if (0 == _stricmp(m_cwd, m_dest)) {
DPrint ("Tried to change to same directory as current.");
return false;
}
DPrint ("Attempting to change to \"%s\".", m_dest);
if (0 == _chdir(m_dest)) {
DPrint ("Successfully changed to \"%s\".", m_dest);
printf ("cd /d %s\n", m_dest);
return true;
}
DPrint ("Attempt failed.");
return false;
}
//--------------------------------------------------------------------------------------------------
bool JDContext::AppendDest (const char* path) {
size_t roomleft = sizeof(m_dest) - m_destlen - 1;
if (m_destlen > 0) roomleft -= 1;
if (strlen(path) > roomleft) return false;
if (m_destlen > 0)
m_dest[m_destlen++] = ' ';
for (; *path != 0; ++path, ++m_destlen) {
if (!m_destwild && isWildStr(path))
m_destwild = true;
if (*path == '\\')
m_dest[m_destlen] = '/';
else
m_dest[m_destlen] = *path;
}
m_dest[m_destlen] = 0;
return true;
}
//======================================================================================================================
// Main Program
//======================================================================================================================
// int wmain (int argc, const wchar_t* const argv[]) {
int main (int argc, const char* const argv[]) {
// The main entry point for the jumpdir program. Returns the return code for the entire program.
assert ((sizeof(DirEntry) & 0x7) == 0);
FileSysProxyWindows fsProxy;
JDContext context {fsProxy};
if (!context.ParseArgs(argc, argv)) return 1;
if (!context.ScanEnvironment()) return 1;
if (!context.Jump()) return 1;
if (!context.Store()) return 1;
return 0;
}
|
/*
* This file corresponds to SimControlPanel.ui and sets everything about
* the simulator control panel.
* The default mode and robot have been set to Simulator and Milab robot,
* users can click the start button directly to start the simulation.
*/
#include "SimControlPanel.h"
#include <ControlParameters/ControlParameters.h>
#include <QFileDialog>
#include <QMessageBox>
#include <ParamHandler.hpp>
#include <leg_control_command_lcmt.hpp>
#include "ui_SimControlPanel.h"
#include "JoystickTest.h"
// Todo: the Milab robot default joint angles for go-home button (883)
/*!
* Display an error messagebox with the given text
*/
static void createErrorMessage(const std::string& text) {
QMessageBox mb;
mb.setText(QString(text.c_str()));
mb.exec();
}
/*!
* Display control parameters in a qtable.
*/
static void updateQtableWithParameters(ControlParameters& params,
QTableWidget& table) {
table.setRowCount((s32)params.collection._map.size());
table.setColumnCount(2);
s32 i = 0;
for (auto& kv : params.collection._map) {
(void)kv;
for (s32 col = 0; col < 2; col++) {
QTableWidgetItem* cell = table.item(i, col);
if (!cell) {
cell = new QTableWidgetItem;
table.setItem(i, col, cell);
}
}
table.item(i, 0)->setText(QString(kv.first.c_str()));
table.item(i, 1)->setText(QString(kv.second->toString().c_str()));
i++;
}
}
/*
* load User Control Parameters
*/
std::string SimControlPanel::getDefaultUserParameterFileName() {
std::string path = getConfigDirectoryPath() + DEFAULT_USER_FILE;
ParamHandler paramHandler(path);
if(!paramHandler.fileOpenedSuccessfully()) {
throw std::runtime_error("Could not open yaml file for default user parameter file: " + path);
}
std::string collectionName;
if(!paramHandler.getString("__collection-name__", collectionName)) {
throw std::runtime_error("Could not find __collection-name__ parameter in default user parameter file");
}
if(collectionName != "user-parameter-file") {
throw std::runtime_error("default user parameter file has the wrong collection name, should be user-parameter-file");
}
std::string fileName;
if(!paramHandler.getString("file_name", fileName)) {
throw std::runtime_error("default user parameter file does not have a parameter named file_name");
}
return fileName;
}
/*!
* Init sim window
*/
SimControlPanel::SimControlPanel(QWidget* parent)
: QMainWindow(parent),
ui(new Ui::SimControlPanel),
_userParameters("user-parameters"),
_terrainFileName(getConfigDirectoryPath() + DEFAULT_TERRAIN_FILE),//get default terrain file name
_heightmapLCM(getLcmUrl(255)),
_pointsLCM(getLcmUrl(255)),
_indexmapLCM(getLcmUrl(255)),
_ctrlVisionLCM(getLcmUrl(255)),
_miniCheetahDebugLCM(getLcmUrl(255))
{
ui->setupUi(this); // QT setup
updateUiEnable(); // enable/disable buttons as needed.
updateTerrainLabel(); // display name of loaded terrain file
_loadedUserSettings = true;
// attempt to load User Control Parameters.
try {
_userParameters.defineAndInitializeFromYamlFile(getConfigDirectoryPath() + getDefaultUserParameterFileName());
} catch (std::runtime_error& ex) {
_loadedUserSettings = false;
}
if(!_loadedUserSettings) {
printf("[SimControlPanel] Failed to load default user settings!\n");
throw std::runtime_error("Failed to load default user settings!");
} else {
// display user settings in qtable if we loaded successfully
loadUserParameters(_userParameters);
}
// load Simulator Control Parameters
printf("[SimControlPanel] Init simulator parameters...\n");
_parameters.initializeFromYamlFile(getConfigDirectoryPath() +
SIMULATOR_DEFAULT_PARAMETERS);
if (!_parameters.isFullyInitialized()) {
printf(
"[ERROR] Simulator parameters are not fully initialized. You forgot: "
"\n%s\n",
_parameters.generateUnitializedList().c_str());
throw std::runtime_error("simulator not initialized");
} else {
printf("\tsim parameters are all good\n");
}
loadSimulationParameters(_parameters);
_pointsLCM.subscribe("cf_pointcloud", &SimControlPanel::handlePointsLCM, this);
_pointsLCMThread = std::thread(&SimControlPanel::pointsLCMThread, this);
_heightmapLCM.subscribe("local_heightmap", &SimControlPanel::handleHeightmapLCM, this);
_heightmapLCMThread = std::thread(&SimControlPanel::heightmapLCMThread, this);
_indexmapLCM.subscribe("traversability", &SimControlPanel::handleIndexmapLCM, this);
_indexmapLCMThread = std::thread(&SimControlPanel::indexmapLCMThread, this);
_ctrlVisionLCM.subscribe("velocity_cmd", &SimControlPanel::handleVelocityCMDLCM, this);
_ctrlVisionLCM.subscribe("obstacle_visual", &SimControlPanel::handleObstacleLCM, this);
_ctrlVisionLCMThread = std::thread(&SimControlPanel::ctrlVisionLCMThread, this);
// subscribe mc debug
_miniCheetahDebugLCM.subscribe("leg_control_data", &SimControlPanel::handleSpiDebug, this);
_miniCheetahDebugLCMThread = std::thread([&](){
for(;;)
_miniCheetahDebugLCM.handle();
});
}
void SimControlPanel::handleVelocityCMDLCM(const lcm::ReceiveBuffer* rbuf,
const std::string & chan,
const velocity_visual_t* msg){
(void)rbuf;
(void)chan;
if(_graphicsWindow){
for(size_t i(0); i<3; ++i){
_graphicsWindow->_vel_cmd_dir[i] = msg->vel_cmd[i];
_graphicsWindow->_vel_cmd_pos[i] = msg->base_position[i];
}
_graphicsWindow->_vel_cmd_update = true;
}
}
void SimControlPanel::handleObstacleLCM(const lcm::ReceiveBuffer* rbuf,
const std::string & chan,
const obstacle_visual_t* msg){
(void)rbuf;
(void)chan;
if(_graphicsWindow){
_graphicsWindow->_obs_list.clear();
Vec3<double> obs_loc;
for(int i(0); i<msg->num_obs; ++i){
obs_loc[0] = msg->location[i][0];
obs_loc[1] = msg->location[i][1];
obs_loc[2] = msg->location[i][2];
_graphicsWindow->_obs_list.push_back(obs_loc);
}
_graphicsWindow->_obs_sigma = msg->sigma;
_graphicsWindow->_obs_height = msg->height;
_graphicsWindow->_obstacle_update = true;
//printf("%f, %f\n", _graphicsWindow->_obs_list[0][0], _graphicsWindow->_obs_list[0][1]);
}
}
void SimControlPanel::handlePointsLCM(const lcm::ReceiveBuffer *rbuf,
const std::string &chan,
const rs_pointcloud_t*msg) {
(void)rbuf;
(void)chan;
if(_graphicsWindow){
for(size_t i(0); i<_graphicsWindow->_num_points; ++i){
for(size_t j(0); j<3; ++j){
_graphicsWindow->_points[i][j] = msg->pointlist[i][j];
}
}
_graphicsWindow->_pointcloud_data_update = true;
}
}
void SimControlPanel::handleIndexmapLCM(const lcm::ReceiveBuffer *rbuf,
const std::string &chan,
const traversability_map_t *msg) {
(void)rbuf;
(void)chan;
if(_graphicsWindow){
for(size_t i(0); i<_graphicsWindow->x_size; ++i){
for(size_t j(0); j<_graphicsWindow->y_size; ++j){
_graphicsWindow->_idx_map(i,j) = msg->map[i][j];
}
}
_graphicsWindow->_indexmap_data_update = true;
}
}
void SimControlPanel::handleHeightmapLCM(const lcm::ReceiveBuffer *rbuf,
const std::string &chan,
const heightmap_t *msg) {
(void)rbuf;
(void)chan;
if(_graphicsWindow){
for(size_t i(0); i<_graphicsWindow->x_size; ++i){
for(size_t j(0); j<_graphicsWindow->y_size; ++j){
_graphicsWindow->_map(i,j) = msg->map[i][j];
}
}
_graphicsWindow->_pos[0] = msg->robot_loc[0];
_graphicsWindow->_pos[1] = msg->robot_loc[1];
_graphicsWindow->_pos[2] = msg->robot_loc[2];
_graphicsWindow->_heightmap_data_update = true;
}
}
void SimControlPanel::handleSpiDebug(const lcm::ReceiveBuffer *rbuf, const std::string &chan,
const leg_control_data_lcmt *msg) {
(void)rbuf;
(void)chan;
MiniCheetahDebugData ddata;
u32 idx = 0;
for(u32 leg = 0; leg < 4; leg++) {
for(u32 joint = 0; joint < 3; joint++) {
ddata.p[leg][joint] = msg->q[idx];
ddata.v[leg][joint] = msg->qd[idx];
idx++;
}
}
if(_mcDebugWindow.setDebugData(ddata)) {
MiniCheetahDebugCommand cmd;
_mcDebugWindow.getDebugCommand(cmd);
leg_control_command_lcmt lcm_cmd;
memset(&lcm_cmd, 0, sizeof(leg_control_command_lcmt));
idx = 0;
for(u32 leg = 0; leg < 4; leg++) {
for(u32 joint = 0; joint < 3; joint++) {
if(cmd.enable[leg][joint]) {
lcm_cmd.q_des[idx] = cmd.qd[leg][joint];
lcm_cmd.kp_joint[idx] = cmd.kp[leg][joint];
lcm_cmd.kd_joint[idx] = cmd.kd[leg][joint];
}
idx++;
}
}
_miniCheetahDebugLCM.publish("spi_debug_cmd", &lcm_cmd);
}
}
SimControlPanel::~SimControlPanel() {
delete _simulation;
delete _interfaceTaskManager;
delete _robotInterface;
delete _graphicsWindow;
delete ui;
}
/*!
* External notification of UI update needed
*/
void SimControlPanel::update_ui() {
updateUiEnable();
}
/*!
* Enable/disable buttons as needed based on what is running
*/
void SimControlPanel::updateUiEnable() {
ui->startButton->setEnabled(!(isRunning() || isError()));
ui->stopButton->setEnabled(isRunning() || isError());
ui->joystickButton->setEnabled(isRunning() || isError());
ui->robotTable->setEnabled(isRunning() || isError());
ui->goHomeButton->setEnabled(isRunning() || isError());
switch(_state) {
case SimulationWindowState::STOPPED:
ui->simulatorStateLabel->setText("Simulator State: Stopped");
ui->stopButton->setText("Stop");
break;
case SimulationWindowState::RUNNING:
ui->simulatorStateLabel->setText("Simulator State: Running");
ui->stopButton->setText("Stop");
break;
case SimulationWindowState::ERROR:
ui->simulatorStateLabel->setText("Simulator State: Error");
ui->stopButton->setText("Reset Error");
break;
}
if((isRunning() || isError()) && _simulation) {
if(_simulation->isRobotConnected()) {
ui->simulatorConnectedLabel->setText("Sim Connection: Yes");
} else {
ui->simulatorConnectedLabel->setText("Sim Connection: No");
}
} else {
ui->simulatorConnectedLabel->setText("Sim Connection: N/A");
}
}
/*!
* Update the name of the loaded terrain file label
*/
void SimControlPanel::updateTerrainLabel() {
ui->terrainFileLabel->setText(QString(_terrainFileName.c_str()));
}
/*!
* Simulation error
*/
void SimControlPanel::errorCallback(std::string errorMessage) {
_state = SimulationWindowState::ERROR; // go to error state
updateUiEnable(); // update UI
createErrorMessage("Simulation Error\n" + errorMessage); // display error dialog
}
/*!
* Start a simulation/robot run
*/
void SimControlPanel::on_startButton_clicked() {
// get robot type
RobotType robotType;
// default set to Milab
if (ui->cheetah3Button->isChecked()) {
robotType = RobotType::CHEETAH_3;
} else if (ui->miniCheetahButton->isChecked()) {
robotType = RobotType::MINI_CHEETAH;
} else if (ui->MilabButton->isChecked()) {
robotType = RobotType::MILAB;
} else {
createErrorMessage("Error: you must select a robot");
return;
}
// get run type
if (!ui->simulatorButton->isChecked() && !ui->robotButton->isChecked()) {
createErrorMessage(
"Error: you must select either robot or simulation mode");
return;
}
//default set to simulator
_simulationMode = ui->simulatorButton->isChecked();
// graphics
printf("[SimControlPanel] Initialize Graphics...\n");
_graphicsWindow = new Graphics3D();
_graphicsWindow->show();
_graphicsWindow->resize(1000, 800);
if (_simulationMode) {
// run a simulation
try {
printf("[SimControlPanel] Initialize simulator...\n");
_simulation = new Simulation(robotType, _graphicsWindow, _parameters, _userParameters,
// this will allow the simulation thread to poke us when there's a state change
[this](){
QMetaObject::invokeMethod(this,"update_ui");
});
loadSimulationParameters(_simulation->getSimParams());
loadRobotParameters(_simulation->getRobotParams());
// terrain
printf("[SimControlParameter] Load terrain...\n");
_simulation->loadTerrainFile(_terrainFileName);
} catch (std::exception& e) {
createErrorMessage("FATAL: Exception thrown during simulator setup\n" + std::string(e.what()));
throw e;
}
// start sim
_simThread = std::thread(
// simulation function
[this]() {
// error callback function
std::function<void(std::string)> error_function = [this](std::string str) {
// Qt will take care of doing the call in the UI event loop
QMetaObject::invokeMethod(this, [=]() {
this->errorCallback(str);
});
};
try {
// pass error callback to simulator
_simulation->runAtSpeed(error_function);
} catch (std::exception &e) {
// also catch exceptions
error_function("Exception thrown in simulation thread: " + std::string(e.what()));
}
});
// graphics start
_graphicsWindow->setAnimating(true);
} else {
printf("[SimControlPanel] Init Robot Interface...\n");
_interfaceTaskManager = new PeriodicTaskManager;
_robotInterface =
new RobotInterface(robotType, _graphicsWindow, _interfaceTaskManager, _userParameters);
loadRobotParameters(_robotInterface->getParams());
_robotInterface->startInterface();
_graphicsWindow->setAnimating(true);
}
_state = SimulationWindowState::RUNNING;
updateUiEnable();
}
/*!
* Stop the currently running simulation or robot connection
*/
void SimControlPanel::on_stopButton_clicked() {
if (_simulation) {
_simulation->stop();
_simThread.join();
} else {
_robotInterface->stopInterface();
}
if (_graphicsWindow) {
_graphicsWindow->setAnimating(false);
_graphicsWindow->hide();
}
delete _interfaceTaskManager;
delete _robotInterface;
delete _simulation;
delete _graphicsWindow;
_simulation = nullptr;
_graphicsWindow = nullptr;
_robotInterface = nullptr;
_interfaceTaskManager = nullptr;
_state = SimulationWindowState::STOPPED;
updateUiEnable();
}
/*!
* Populate the simulator qtable parameters
*/
void SimControlPanel::loadSimulationParameters(
SimulatorControlParameters& params) {
_ignoreTableCallbacks = true;
updateQtableWithParameters(params, *ui->simulatorTable);
_ignoreTableCallbacks = false;
}
/*!
* Populate the robot qtable parameters
*/
void SimControlPanel::loadRobotParameters(RobotControlParameters& params) {
_ignoreTableCallbacks = true;
updateQtableWithParameters(params, *ui->robotTable);
_ignoreTableCallbacks = false;
}
/*!
* Populate the robot qtable parameters
*/
void SimControlPanel::loadUserParameters(ControlParameters& params) {
_ignoreTableCallbacks = true;
updateQtableWithParameters(params, *ui->userControlTable);
_ignoreTableCallbacks = false;
}
/*!
* Attempt to reset the joystick if a new one is connected
*/
void SimControlPanel::on_joystickButton_clicked() {
if(isRunning()) {
_graphicsWindow->resetGameController();
JoystickTestWindow* window = new JoystickTestWindow(_graphicsWindow->getGameController());
window->exec();
delete window;
}
}
/*
* display mini cheeath debug panel
*/
void SimControlPanel::on_driverButton_clicked() {
_mcDebugWindow.show();
}
/*!
* Respond to a change in the simulator table.
*/
void SimControlPanel::on_simulatorTable_cellChanged(int row, int column) {
if (_ignoreTableCallbacks) return;
// we only allow values to change, which are in column 1
if (column != 1) {
return;
}
// get the name of the parameter....
auto cell = ui->simulatorTable->item(row, 0);
std::string cellName = cell->text().toStdString();
if (cellName == "") {
return;
}
// get the parameters
auto& parameter = _parameters.collection.lookup(cellName);
ControlParameterValueKind kind = parameter._kind;
ControlParameterValue oldValue = parameter.get(kind);
bool success = true;
// attempt to set, based on string.
try {
parameter.setFromString(
ui->simulatorTable->item(row, 1)->text().toStdString());
} catch (std::exception& e) {
success = false;
}
// if it fails (bad user input string), restore to the old value
if (!success) {
printf("[ERROR] invalid data, restoring old data!\n");
// set parameter value
parameter.set(oldValue, kind);
assert(!_ignoreTableCallbacks);
// manually fix the table
_ignoreTableCallbacks = true;
ui->simulatorTable->item(row, 1)->setText(
QString(_parameters.collection.lookup(cellName).toString().c_str()));
_ignoreTableCallbacks = false;
} else {
// this update "rewrites" the value in the table. If it's an integer, it kills any
// decimal. If it's a float, it puts in scientific notation if needed.
_ignoreTableCallbacks = true;
ui->simulatorTable->item(row, 1)->setText(
QString(parameter.toString().c_str()));
_ignoreTableCallbacks = false;
}
}
/*!
* Save simulation config to file
*/
void SimControlPanel::on_saveSimulatorButton_clicked() {
QString fileName = QFileDialog::getSaveFileName(
nullptr, ("Save Simulator Table Values"), "../config", "All Files (*)");
if (fileName == nullptr || fileName == "") {
createErrorMessage("File name is invalid");
return;
}
_parameters.lockMutex();
_parameters.writeToYamlFile(fileName.toStdString());
_parameters.unlockMutex();
}
/*!
* Load simulation config from file
*/
void SimControlPanel::on_loadSimulatorButton_clicked() {
QString fileName = QFileDialog::getOpenFileName(
nullptr, ("Load Simulator Table Values"), "../config", "All Files (*)");
if (fileName == nullptr || fileName == "") {
createErrorMessage("File name is invalid");
return;
};
_parameters.collection.clearAllSet();
_parameters.initializeFromYamlFile(fileName.toStdString());
if (!_parameters.collection.checkIfAllSet()) {
printf(
"new settings file %s doesn't contain the following simulator "
"parameters:\n%s\n",
fileName.toStdString().c_str(),
_parameters.generateUnitializedList().c_str());
throw std::runtime_error("bad new settings file");
}
loadSimulationParameters(_parameters);
_parameters.unlockMutex();
}
/*
* Change simulator and robot parameters in panel
*/
void SimControlPanel::on_robotTable_cellChanged(int row, int column) {
if (_ignoreTableCallbacks) return;
if (column != 1) {
return;
}
auto cell = ui->robotTable->item(row, 0);
std::string cellName = cell->text().toStdString();
if (cellName == "") {
return;
}
auto& parameter = (_simulationMode ? _simulation->getRobotParams()
: _robotInterface->getParams())
.collection.lookup(cellName);
ControlParameterValueKind kind = parameter._kind;
ControlParameterValue oldValue = parameter.get(kind);
bool success = true;
try {
parameter.setFromString(ui->robotTable->item(row, 1)->text().toStdString());
} catch (std::exception& e) {
success = false;
}
if (!success) {
printf("[ERROR] invalid data, restoring old data!\n");
parameter.set(oldValue, kind);
assert(!_ignoreTableCallbacks);
_ignoreTableCallbacks = true;
ui->robotTable->item(row, 1)->setText(
QString(parameter
.toString()
.c_str()));
_ignoreTableCallbacks = false;
} else {
if (_simulationMode) {
if (_simulation->isRobotConnected()) {
_simulation->sendControlParameter(
cellName, parameter.get(parameter._kind), parameter._kind, false);
}
_ignoreTableCallbacks = true;
ui->robotTable->item(row, 1)->setText(
QString(parameter.toString().c_str()));
_ignoreTableCallbacks = false;
} else {
_robotInterface->sendControlParameter(
cellName, parameter.get(parameter._kind), parameter._kind, false);
}
}
}
/*!
* Save robot config to file
*/
void SimControlPanel::on_saveRobotButton_clicked() {
QString fileName = QFileDialog::getSaveFileName(
nullptr, ("Save Robot Table Values"), "../config", "All Files (*)");
if (fileName == nullptr || fileName == "") {
createErrorMessage("File name is invalid");
return;
}
_simulation->getRobotParams().writeToYamlFile(fileName.toStdString());
}
/*!
* Load robot config from file
*/
void SimControlPanel::on_loadRobotButton_clicked() {
QString fileName = QFileDialog::getOpenFileName(
nullptr, ("Load Quadruped Table Values"), "../config", "All Files (*)");
if (fileName == nullptr || fileName == "") {
createErrorMessage("File name is invalid");
return;
}
if (_simulationMode) {
_simulation->getRobotParams().lockMutex();
_simulation->getRobotParams().collection.clearAllSet();
_simulation->getRobotParams().initializeFromYamlFile(
fileName.toStdString());
if (!_simulation->getRobotParams().collection.checkIfAllSet()) {
printf(
"new settings file %s doesn't contain the following robot "
"parameters:\n%s\n",
fileName.toStdString().c_str(),
_simulation->getRobotParams().generateUnitializedList().c_str());
throw std::runtime_error("bad new settings file");
}
loadRobotParameters(_simulation->getRobotParams());
if (_simulation->isRobotConnected()) {
for (auto& kv : _simulation->getRobotParams().collection._map) {
_simulation->sendControlParameter(
kv.first, kv.second->get(kv.second->_kind), kv.second->_kind, false);
}
}
_simulation->getRobotParams().unlockMutex();
} else {
_robotInterface->getParams().lockMutex();
_robotInterface->getParams().collection.clearAllSet();
_robotInterface->getParams().initializeFromYamlFile(fileName.toStdString());
if (!_robotInterface->getParams().collection.checkIfAllSet()) {
printf(
"new settings file %s doesn't contain the following robot "
"parameters:\n%s\n",
fileName.toStdString().c_str(),
_robotInterface->getParams().generateUnitializedList().c_str());
throw std::runtime_error("bad new settings file");
}
loadRobotParameters(_robotInterface->getParams());
for (auto& kv : _robotInterface->getParams().collection._map) {
_robotInterface->sendControlParameter(
kv.first, kv.second->get(kv.second->_kind), kv.second->_kind, false);
}
_robotInterface->getParams().unlockMutex();
}
}
/*!
* Load terrain from file
*/
void SimControlPanel::on_setTerrainButton_clicked() {
QString fileName = QFileDialog::getOpenFileName(
nullptr, ("Load Terrain Definition"), "../config", "All Files (*)");
if (fileName == nullptr || fileName == "") {
createErrorMessage("File name is invalid");
return;
}
_terrainFileName = fileName.toStdString();
updateTerrainLabel();
}
/*
* Change user control parameters in panel
*/
void SimControlPanel::on_userControlTable_cellChanged(int row, int column) {
if (_ignoreTableCallbacks) return;
if (column != 1) {
return;
}
auto cell = ui->userControlTable->item(row, 0);
std::string cellName = cell->text().toStdString();
if (cellName == "") {
return;
}
auto& parameter = _userParameters.collection.lookup(cellName);
// auto& parameter = (_simulationMode ? _simulation->getRobotParams()
// : _robotInterface->getParams())
// .collection.lookup(cellName);
ControlParameterValueKind kind = parameter._kind;
ControlParameterValue oldValue = parameter.get(kind);
bool success = true;
try {
parameter.setFromString(ui->userControlTable->item(row, 1)->text().toStdString());
} catch (std::exception& e) {
success = false;
}
if (!success) {
printf("[ERROR] invalid data, restoring old data!\n");
parameter.set(oldValue, kind);
assert(!_ignoreTableCallbacks);
_ignoreTableCallbacks = true;
ui->userControlTable->item(row, 1)->setText(
QString(_userParameters
.collection.lookup(cellName)
.toString()
.c_str()));
_ignoreTableCallbacks = false;
} else {
if(isRunning() || isError()) {
if (_simulationMode) {
if (_simulation && _simulation->isRobotConnected()) {
_simulation->sendControlParameter(
cellName, parameter.get(parameter._kind), parameter._kind, true);
}
_ignoreTableCallbacks = true;
ui->userControlTable->item(row, 1)->setText(
QString(parameter.toString().c_str()));
_ignoreTableCallbacks = false;
} else {
_robotInterface->sendControlParameter(
cellName, parameter.get(parameter._kind), parameter._kind, true);
}
}
}
}
/*!
* Load user config from file
*/
void SimControlPanel::on_loadUserButton_clicked() {
QString fileName = QFileDialog::getOpenFileName(
nullptr, ("Load User Table Values"), "../config", "All Files (*)");
if (fileName == nullptr || fileName == "") {
createErrorMessage("File name is invalid");
return;
}
_userParameters.lockMutex();
_userParameters.collection.deleteAll();
_userParameters.defineAndInitializeFromYamlFile(
fileName.toStdString());
loadUserParameters(_userParameters);
_userParameters.unlockMutex();
_loadedUserSettings = true;
if(isRunning() || isError()) {
if (_simulationMode) {
if (_simulation && _simulation->isRobotConnected()) {
for (auto& kv : _userParameters.collection._map) {
_simulation->sendControlParameter(
kv.first, kv.second->get(kv.second->_kind), kv.second->_kind, true);
}
}
} else {
for (auto& kv : _userParameters.collection._map) {
_robotInterface->sendControlParameter(
kv.first, kv.second->get(kv.second->_kind), kv.second->_kind, true);
}
}
}
}
/*!
* Save user config to file
*/
void SimControlPanel::on_saveUserButton_clicked() {
QString fileName = QFileDialog::getSaveFileName(
nullptr, ("Save User Table Values"), "../config", "All Files (*)");
if (fileName == nullptr || fileName == "") {
createErrorMessage("File name is invalid");
return;
}
_userParameters.writeToYamlFile(fileName.toStdString());
}
/*!
* Reset robot state to default joint angles
*/
void SimControlPanel::on_goHomeButton_clicked() {
FBModelState<double> homeState;
homeState.bodyOrientation << 1, 0, 0, 0;
homeState.bodyPosition = Vec3<double>(0, 0, 0.5);
homeState.bodyVelocity = SVec<double>::Zero();
homeState.q = DVec<double>(12);
if(_simulation->_robot == RobotType::MILAB){
printf("[Simulation] MILAB ROBOT ");
homeState.q << -0., -0.96, 1.6, 0., -0.96, 1.6, -0., -0.96, 1.6, 0., -0.96, 1.6;
}else{
printf("[Simulation] MIT CHEETAH ");
homeState.q << -0.05, -0.8, 1.7, 0.05, -0.8, 1.7, -0.05, -0.8, 1.7, 0.05, -0.8, 1.7;
}
homeState.qd = homeState.q;
printf("Go Home\n");
_simulation->setRobotState(homeState);
}
/*!
* Simulate external force work on the robot body
*/
void SimControlPanel::on_kickButton_clicked() {
// velocity of the floating base:
SVec<double> kickVelocity;
kickVelocity << ui->kickAngularX->text().toDouble(),
ui->kickAngularY->text().toDouble(), ui->kickAngularZ->text().toDouble(),
ui->kickLinearX->text().toDouble(), ui->kickLinearY->text().toDouble(),
ui->kickLinearZ->text().toDouble();
FBModelState<double> state = _simulation->getRobotState();
state.bodyVelocity += kickVelocity;
_simulation->setRobotState(state);
}
|
#include "ast.hpp"
AST::AST(QObject *parent)
: QAbstractItemModel(parent)
{
}
QVariant AST::headerData(int section, Qt::Orientation orientation, int role) const
{
// FIXME: Implement me!
}
QModelIndex AST::index(int row, int column, const QModelIndex &parent) const
{
// FIXME: Implement me!
}
QModelIndex AST::parent(const QModelIndex &index) const
{
// FIXME: Implement me!
}
int AST::rowCount(const QModelIndex &parent) const
{
if (!parent.isValid())
return 0;
// FIXME: Implement me!
}
int AST::columnCount(const QModelIndex &parent) const
{
if (!parent.isValid())
return 0;
// FIXME: Implement me!
}
QVariant AST::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
// FIXME: Implement me!
return QVariant();
}
|
/**
******************************************************************************
* This file is part of the TouchGFX 4.10.0 distribution.
*
* <h2><center>© Copyright (c) 2018 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#ifndef PAINTERVERTICALALPHA_HPP
#define PAINTERVERTICALALPHA_HPP
#include <touchgfx/hal/Types.hpp>
#include <stdint.h>
#if !defined(USE_BPP) || USE_BPP==16
#include <touchgfx/widgets/canvas/AbstractPainterRGB565.hpp>
#elif USE_BPP==24
#include <touchgfx/widgets/canvas/AbstractPainterRGB888.hpp>
#elif USE_BPP==4
#include <touchgfx/widgets/canvas/AbstractPainterGRAY4.hpp>
#include <platform/driver/lcd/LCD4bpp.hpp>
#elif USE_BPP==2
#include <touchgfx/widgets/canvas/AbstractPainterGRAY2.hpp>
#include <platform/driver/lcd/LCD2bpp.hpp>
#else
#error Unknown USE_BPP
#endif
using namespace touchgfx;
/**
* @class PainterVerticalAlpha PainterVerticalAlpha.hpp gui/common/PainterVerticalAlpha.hpp
*
* @brief A Painter that will paint using a fading color.
*
* PainterVerticalAlpha will paint using the given color at y coordinate 0 fading
* the color to invisible at the given y coordinate.
*
* @see AbstractPainter
*/
class PainterVerticalAlpha :
#if !defined(USE_BPP) || USE_BPP==16
public AbstractPainterRGB565
#elif USE_BPP==24
public AbstractPainterRGB888
#elif USE_BPP==4
public AbstractPainterGRAY4
#elif USE_BPP==2
public AbstractPainterGRAY2
#else
#error Unknown USE_BPP
#endif
{
public:
/**
* @fn PainterVerticalAlpha::PainterVerticalAlpha(colortype color = 0, int alpha0atY = 100);
*
* @brief Constructor.
*
* Constructor.
*
* @param color The color.
* @param alpha0atY The y coordinate where alpha has faded to 0.
*/
PainterVerticalAlpha(colortype color = 0, int alpha0atY = 100);
/**
* @fn void PainterVerticalAlpha::setColor(colortype color, int alphaZeroAt);
*
* @brief Sets color and alpha to use when drawing the CanvasWidget.
*
* Sets color and alpha to use when drawing the CanvasWidget.
*
* @param color The color.
* @param alphaZeroAt The y coordinate where alpha has faded to 0.
*/
void setColor(colortype color, int alphaZeroAt);
virtual void render(uint8_t* ptr, int x, int xAdjust, int y, unsigned count, const uint8_t* covers);
protected:
/**
* @fn virtual bool PainterVerticalAlpha::renderInit();
*
* @brief Get ready to render (part of) a scanline.
*
* Get ready to render (part of) a scanline. Since the scanline will have the same y
* coordinate, the alpha for the scanline can be calculated here and used for all
* pixels in the scanline.
*
* @return true if it succeeds, false if it fails.
*/
virtual bool renderInit();
#if !defined(USE_BPP) || USE_BPP==16 || USE_BPP==24
virtual bool renderNext(uint8_t& pixelRed, uint8_t& pixelGreen, uint8_t& pixelBlue, uint8_t& pixelAlpha);
uint8_t painterRed; ///< The red part of the color
uint8_t painterGreen; ///< The green part of the color
uint8_t painterBlue; ///< The blue part of the color
#elif USE_BPP==4 || USE_BPP==2
virtual bool renderNext(uint8_t& gray, uint8_t& alpha);
uint8_t painterGray; ///< The gray color
#else
#error Unknown USE_BPP
#endif
uint8_t painterAlpha; ///< Current alpha for the scan line
int alpha0atY; ///< The Y coordinate where alpha has faded to 0
private:
}; // class PainterVerticalAlpha
#endif /* PAINTERVERTICALALPHA_HPP */
|
#include "game.h"
#include "tetris.h"
int main(int argc, char *argv[]) {
Tetris *t = new Tetris();
Game *g = new Game(t);
printf("Aqui\n");
g->run_loop();
return 0;
}
|
/*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "bindings/v8/ScriptEventListener.h"
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/ScriptState.h"
#include "bindings/v8/V8AbstractEventListener.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8WindowShell.h"
#include "core/dom/Document.h"
#include "core/dom/DocumentParser.h"
#include "core/events/EventListener.h"
#include "core/frame/LocalFrame.h"
#include <v8.h>
namespace WebCore {
PassRefPtr<V8LazyEventListener> createAttributeEventListener(Node* node, const QualifiedName& name, const AtomicString& value, const AtomicString& eventParameterName)
{
ASSERT(node);
if (value.isNull())
return nullptr;
// FIXME: Very strange: we initialize zero-based number with '1'.
TextPosition position(OrdinalNumber::fromZeroBasedInt(1), OrdinalNumber::first());
String sourceURL;
v8::Isolate* isolate;
if (LocalFrame* frame = node->document().frame()) {
isolate = toIsolate(frame);
ScriptController& scriptController = frame->script();
if (!scriptController.canExecuteScripts(AboutToExecuteScript))
return nullptr;
position = scriptController.eventHandlerPosition();
sourceURL = node->document().url().string();
} else {
isolate = v8::Isolate::GetCurrent();
}
return V8LazyEventListener::create(name.localName(), eventParameterName, value, sourceURL, position, node, isolate);
}
PassRefPtr<V8LazyEventListener> createAttributeEventListener(LocalFrame* frame, const QualifiedName& name, const AtomicString& value, const AtomicString& eventParameterName)
{
if (!frame)
return nullptr;
if (value.isNull())
return nullptr;
ScriptController& scriptController = frame->script();
if (!scriptController.canExecuteScripts(AboutToExecuteScript))
return nullptr;
TextPosition position = scriptController.eventHandlerPosition();
String sourceURL = frame->document()->url().string();
return V8LazyEventListener::create(name.localName(), eventParameterName, value, sourceURL, position, 0, toIsolate(frame));
}
static v8::Handle<v8::Function> eventListenerEffectiveFunction(v8::Isolate* isolate, v8::Handle<v8::Object> listenerObject)
{
v8::Handle<v8::Function> function;
if (listenerObject->IsFunction()) {
function = v8::Handle<v8::Function>::Cast(listenerObject);
} else if (listenerObject->IsObject()) {
// Try the "handleEvent" method (EventListener interface).
v8::Handle<v8::Value> property = listenerObject->Get(v8AtomicString(isolate, "handleEvent"));
if (property.IsEmpty() || !property->IsFunction()) {
// Fall back to the "constructor" property.
property = listenerObject->Get(v8AtomicString(isolate, "constructor"));
}
if (!property.IsEmpty() && property->IsFunction())
function = v8::Handle<v8::Function>::Cast(property);
}
return function;
}
String eventListenerHandlerBody(Document* document, EventListener* listener)
{
if (listener->type() != EventListener::JSEventListenerType)
return "";
v8::HandleScope scope(toIsolate(document));
V8AbstractEventListener* v8Listener = static_cast<V8AbstractEventListener*>(listener);
v8::Handle<v8::Context> context = toV8Context(document, v8Listener->world());
v8::Context::Scope contextScope(context);
v8::Handle<v8::Object> object = v8Listener->getListenerObject(document);
if (object.IsEmpty())
return "";
v8::Handle<v8::Function> function = eventListenerEffectiveFunction(scope.GetIsolate(), object);
if (function.IsEmpty())
return "";
TOSTRING_DEFAULT(V8StringResource<WithNullCheck>, functionString, function, "");
return functionString;
}
ScriptValue eventListenerHandler(Document* document, EventListener* listener)
{
if (listener->type() != EventListener::JSEventListenerType)
return ScriptValue();
v8::Isolate* isolate = toIsolate(document);
v8::HandleScope scope(isolate);
V8AbstractEventListener* v8Listener = static_cast<V8AbstractEventListener*>(listener);
v8::Handle<v8::Context> context = toV8Context(document, v8Listener->world());
v8::Context::Scope contextScope(context);
v8::Handle<v8::Object> function = v8Listener->getListenerObject(document);
if (function.IsEmpty())
return ScriptValue();
return ScriptValue(ScriptState::from(context), function);
}
ScriptState* eventListenerHandlerScriptState(LocalFrame* frame, EventListener* listener)
{
if (listener->type() != EventListener::JSEventListenerType)
return 0;
V8AbstractEventListener* v8Listener = static_cast<V8AbstractEventListener*>(listener);
v8::HandleScope scope(toIsolate(frame));
v8::Handle<v8::Context> v8Context = frame->script().windowShell(v8Listener->world())->context();
return ScriptState::from(v8Context);
}
bool eventListenerHandlerLocation(Document* document, EventListener* listener, String& sourceName, String& scriptId, int& lineNumber)
{
if (listener->type() != EventListener::JSEventListenerType)
return false;
v8::HandleScope scope(toIsolate(document));
V8AbstractEventListener* v8Listener = static_cast<V8AbstractEventListener*>(listener);
v8::Handle<v8::Context> context = toV8Context(document, v8Listener->world());
v8::Context::Scope contextScope(context);
v8::Local<v8::Object> object = v8Listener->getListenerObject(document);
if (object.IsEmpty())
return false;
v8::Handle<v8::Function> function = eventListenerEffectiveFunction(scope.GetIsolate(), object);
if (function.IsEmpty())
return false;
v8::Handle<v8::Function> originalFunction = getBoundFunction(function);
int scriptIdValue = originalFunction->ScriptId();
scriptId = String::number(scriptIdValue);
v8::ScriptOrigin origin = originalFunction->GetScriptOrigin();
if (!origin.ResourceName().IsEmpty() && origin.ResourceName()->IsString())
sourceName = toCoreString(origin.ResourceName().As<v8::String>());
else
sourceName = "";
lineNumber = originalFunction->GetScriptLineNumber();
return true;
}
} // namespace WebCore
|
class Solution {
public:
string XXX(string s, int numRows) {
int l=s.size();
int t=0;
if(numRows==1){
return s;
}
int sum;
if(l<(2*numRows-2)){
sum=1+(l%numRows);
}else{
sum=(l/(2*numRows-2))*(numRows-1);
if((l-(l/(2*numRows-2))*(numRows-1))<=numRows){
sum++;
}else{
sum=sum+((l-(l/(2*numRows-2))*(numRows-1))-numRows)+1;
}
}
vector<vector<char>>ans(numRows,vector<char>(sum));
vector<vector<int>>visited(numRows,vector<int>(sum,0));
int i=0,j=0;
int fx=0;
int a[2][2]={{1,0},{-1,1}};
for(int k=0;k<l;k++){
ans[i][j]=s[k];
visited[i][j]=1;
int xi=i+a[fx][0];
int xj=j+a[fx][1];
if(xi<0||xj<0||xi>=numRows||xj>=sum||visited[xi][xj]==1){
fx=(fx+1)%2;
i+=a[fx][0];
j+=a[fx][1];
continue;
}
i=xi;j=xj;
}
string res="";
for(int m=0;m<numRows;m++){
for(int n=0;n<sum;n++){
if(visited[m][n]==1){
res+=ans[m][n];
}
}
}
return res;
}
};
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2022 Ryo Suzuki
// Copyright (c) 2016-2022 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/EngineLog.hpp>
# include <Siv3D/Unicode.hpp>
# include <Siv3D/Window/IWindow.hpp>
# include <Siv3D/Common/Siv3DEngine.hpp>
# include "CClipboard.hpp"
namespace s3d
{
namespace detail
{
__attribute__((import_name("siv3dSetClipboardText")))
extern void siv3dSetClipboardText(const char* text);
__attribute__((import_name("siv3dGetClipboardText")))
extern char* siv3dGetClipboardText();
using siv3dGetClipboardTextAsyncCallBack = void(*)(char* text, void* promise);
__attribute__((import_name("siv3dGetClipboardTextAsync")))
extern void siv3dGetClipboardTextAsync(siv3dGetClipboardTextAsyncCallBack, void*);
}
CClipboard::CClipboard() {}
CClipboard::~CClipboard()
{
LOG_SCOPED_TRACE(U"CClipboard::~CClipboard()");
}
void CClipboard::init()
{
LOG_SCOPED_TRACE(U"CClipboard::init()");
}
bool CClipboard::hasChanged()
{
// [Siv3D ToDo]
return false;
}
bool CClipboard::getText(String& text)
{
text.clear();
if (auto rawClipBoardText = detail::siv3dGetClipboardText(); rawClipBoardText != nullptr)
{
text = Unicode::FromUTF8(rawClipBoardText);
delete rawClipBoardText;
}
return (not text.isEmpty());
}
bool CClipboard::getImage(Image& image)
{
image.clear();
// [Siv3D ToDo]
return (not image.isEmpty());
}
bool CClipboard::getFilePaths(Array<FilePath>& paths)
{
paths.clear();
// [Siv3D ToDo]
return (not paths.isEmpty());
}
void CClipboard::setText(const String& text)
{
detail::siv3dSetClipboardText(text.narrow().c_str());
}
void CClipboard::setImage(const Image& image)
{
// [Siv3D ToDo]
}
void CClipboard::clear()
{
setText(U"");
}
void CClipboard::OnGetClipboardText(char* text, void* userData)
{
auto& clipboard = *static_cast<CClipboard*>(userData);
if (text)
{
clipboard.m_clibboardTexts << Unicode::FromUTF8(text);
}
}
namespace Platform::Web::Clipboard
{
namespace detail
{
void OnGetClipboardText(char* text, void* userData)
{
auto promise = static_cast<std::promise<s3d::String>*>(userData);
if (text)
{
promise->set_value(Unicode::Widen(text));
}
else
{
promise->set_value(U"");
}
}
}
std::future<String> GetText()
{
auto p = new std::promise<s3d::String>();
auto result_future = p->get_future();
s3d::detail::siv3dGetClipboardTextAsync(&detail::OnGetClipboardText, p);
return result_future;
}
}
}
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sendcoinsdialog.h"
#include "ui_sendcoinsdialog.h"
#include "addresstablemodel.h"
#include "askpassphrasedialog.h"
#include "bitcoinunits.h"
#include "clientmodel.h"
#include "coincontroldialog.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "sendcoinsentry.h"
#include "walletmodel.h"
#include "base58.h"
#include "coincontrol.h"
#include "ui_interface.h"
#include "utilmoneystr.h"
#include "wallet.h"
#include <QMessageBox>
#include <QScrollBar>
#include <QSettings>
#include <QTextDocument>
SendCoinsDialog::SendCoinsDialog(QWidget* parent) : QDialog(parent),
ui(new Ui::SendCoinsDialog),
clientModel(0),
model(0),
fNewRecipientAllowed(true),
fFeeMinimized(true)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
GUIUtil::setupAddressWidget(ui->lineEditCoinControlChange, this);
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// Coin Control
connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked()));
connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int)));
connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString&)), this, SLOT(coinControlChangeEdited(const QString&)));
// UTXO Splitter
connect(ui->splitBlockCheckBox, SIGNAL(stateChanged(int)), this, SLOT(splitBlockChecked(int)));
connect(ui->splitBlockLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(splitBlockLineEditChanged(const QString&)));
// NodeCircle specific
QSettings settings;
if (!settings.contains("bUseObfuScation"))
settings.setValue("bUseObfuScation", false);
if (!settings.contains("bUseSwiftTX"))
settings.setValue("bUseSwiftTX", false);
bool useSwiftTX = settings.value("bUseSwiftTX").toBool();
if (fLiteMode) {
ui->checkSwiftTX->setVisible(false);
CoinControlDialog::coinControl->useObfuScation = false;
CoinControlDialog::coinControl->useSwiftTX = false;
} else {
ui->checkSwiftTX->setChecked(useSwiftTX);
CoinControlDialog::coinControl->useSwiftTX = useSwiftTX;
}
connect(ui->checkSwiftTX, SIGNAL(stateChanged(int)), this, SLOT(updateSwiftTX()));
// Coin Control: clipboard actions
QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this);
QAction* clipboardFeeAction = new QAction(tr("Copy fee"), this);
QAction* clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
QAction* clipboardBytesAction = new QAction(tr("Copy bytes"), this);
QAction* clipboardPriorityAction = new QAction(tr("Copy priority"), this);
QAction* clipboardLowOutputAction = new QAction(tr("Copy dust"), this);
QAction* clipboardChangeAction = new QAction(tr("Copy change"), this);
connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity()));
connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount()));
connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee()));
connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee()));
connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes()));
connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority()));
connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput()));
connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange()));
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
ui->labelCoinControlFee->addAction(clipboardFeeAction);
ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
ui->labelCoinControlBytes->addAction(clipboardBytesAction);
ui->labelCoinControlPriority->addAction(clipboardPriorityAction);
ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
ui->labelCoinControlChange->addAction(clipboardChangeAction);
// init transaction fee section
if (!settings.contains("fFeeSectionMinimized"))
settings.setValue("fFeeSectionMinimized", true);
if (!settings.contains("nFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility
settings.setValue("nFeeRadio", 1); // custom
if (!settings.contains("nFeeRadio"))
settings.setValue("nFeeRadio", 0); // recommended
if (!settings.contains("nCustomFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility
settings.setValue("nCustomFeeRadio", 1); // total at least
if (!settings.contains("nCustomFeeRadio"))
settings.setValue("nCustomFeeRadio", 0); // per kilobyte
if (!settings.contains("nSmartFeeSliderPosition"))
settings.setValue("nSmartFeeSliderPosition", 0);
if (!settings.contains("nTransactionFee"))
settings.setValue("nTransactionFee", (qint64)DEFAULT_TRANSACTION_FEE);
if (!settings.contains("fPayOnlyMinFee"))
settings.setValue("fPayOnlyMinFee", false);
if (!settings.contains("fSendFreeTransactions"))
settings.setValue("fSendFreeTransactions", false);
ui->groupFee->setId(ui->radioSmartFee, 0);
ui->groupFee->setId(ui->radioCustomFee, 1);
ui->groupFee->button((int)std::max(0, std::min(1, settings.value("nFeeRadio").toInt())))->setChecked(true);
ui->groupCustomFee->setId(ui->radioCustomPerKilobyte, 0);
ui->groupCustomFee->setId(ui->radioCustomAtLeast, 1);
ui->groupCustomFee->button((int)std::max(0, std::min(1, settings.value("nCustomFeeRadio").toInt())))->setChecked(true);
ui->sliderSmartFee->setValue(settings.value("nSmartFeeSliderPosition").toInt());
ui->customFee->setValue(settings.value("nTransactionFee").toLongLong());
ui->checkBoxMinimumFee->setChecked(settings.value("fPayOnlyMinFee").toBool());
ui->checkBoxFreeTx->setChecked(settings.value("fSendFreeTransactions").toBool());
ui->checkzNCX->hide();
minimizeFeeSection(settings.value("fFeeSectionMinimized").toBool());
}
void SendCoinsDialog::setClientModel(ClientModel* clientModel)
{
this->clientModel = clientModel;
if (clientModel) {
connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(updateSmartFeeLabel()));
}
}
void SendCoinsDialog::setModel(WalletModel* model)
{
this->model = model;
if (model && model->getOptionsModel()) {
for (int i = 0; i < ui->entries->count(); ++i) {
SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if (entry) {
entry->setModel(model);
}
}
setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(),
model->getZerocoinBalance (), model->getUnconfirmedZerocoinBalance (), model->getImmatureZerocoinBalance (),
model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance());
connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this,
SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
updateDisplayUnit();
// Coin Control
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels()));
connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool)));
ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures());
coinControlUpdateLabels();
// fee section
connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(updateSmartFeeLabel()));
connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(updateGlobalFeeVariables()));
connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(coinControlUpdateLabels()));
connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(updateFeeSectionControls()));
connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(updateGlobalFeeVariables()));
connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(coinControlUpdateLabels()));
connect(ui->groupCustomFee, SIGNAL(buttonClicked(int)), this, SLOT(updateGlobalFeeVariables()));
connect(ui->groupCustomFee, SIGNAL(buttonClicked(int)), this, SLOT(coinControlUpdateLabels()));
connect(ui->customFee, SIGNAL(valueChanged()), this, SLOT(updateGlobalFeeVariables()));
connect(ui->customFee, SIGNAL(valueChanged()), this, SLOT(coinControlUpdateLabels()));
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(setMinimumFee()));
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(updateFeeSectionControls()));
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(updateGlobalFeeVariables()));
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels()));
connect(ui->checkBoxFreeTx, SIGNAL(stateChanged(int)), this, SLOT(updateGlobalFeeVariables()));
connect(ui->checkBoxFreeTx, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels()));
ui->customFee->setSingleStep(CWallet::minTxFee.GetFeePerK());
updateFeeSectionControls();
updateMinFeeLabel();
updateSmartFeeLabel();
updateGlobalFeeVariables();
}
}
SendCoinsDialog::~SendCoinsDialog()
{
QSettings settings;
settings.setValue("fFeeSectionMinimized", fFeeMinimized);
settings.setValue("nFeeRadio", ui->groupFee->checkedId());
settings.setValue("nCustomFeeRadio", ui->groupCustomFee->checkedId());
settings.setValue("nSmartFeeSliderPosition", ui->sliderSmartFee->value());
settings.setValue("nTransactionFee", (qint64)ui->customFee->value());
settings.setValue("fPayOnlyMinFee", ui->checkBoxMinimumFee->isChecked());
settings.setValue("fSendFreeTransactions", ui->checkBoxFreeTx->isChecked());
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
if (!model || !model->getOptionsModel())
return;
QList<SendCoinsRecipient> recipients;
bool valid = true;
for (int i = 0; i < ui->entries->count(); ++i) {
SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
//UTXO splitter - address should be our own
CBitcoinAddress address = entry->getValue().address.toStdString();
if (!model->isMine(address) && ui->splitBlockCheckBox->checkState() == Qt::Checked) {
CoinControlDialog::coinControl->fSplitBlock = false;
ui->splitBlockCheckBox->setCheckState(Qt::Unchecked);
QMessageBox::warning(this, tr("Send Coins"),
tr("The split block tool does not work when sending to outside addresses. Try again."),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
if (entry) {
if (entry->validate()) {
recipients.append(entry->getValue());
} else {
valid = false;
}
}
}
if (!valid || recipients.isEmpty()) {
return;
}
//set split block in model
CoinControlDialog::coinControl->fSplitBlock = ui->splitBlockCheckBox->checkState() == Qt::Checked;
if (ui->entries->count() > 1 && ui->splitBlockCheckBox->checkState() == Qt::Checked) {
CoinControlDialog::coinControl->fSplitBlock = false;
ui->splitBlockCheckBox->setCheckState(Qt::Unchecked);
QMessageBox::warning(this, tr("Send Coins"),
tr("The split block tool does not work with multiple addresses. Try again."),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
if (CoinControlDialog::coinControl->fSplitBlock)
CoinControlDialog::coinControl->nSplitBlock = int(ui->splitBlockLineEdit->text().toInt());
QString strFunds = "";
QString strFee = "";
recipients[0].inputType = ALL_COINS;
if (ui->checkSwiftTX->isChecked()) {
recipients[0].useSwiftTX = true;
strFunds += " ";
strFunds += tr("using SwiftX");
} else {
recipients[0].useSwiftTX = false;
}
// Format confirmation message
QStringList formatted;
foreach (const SendCoinsRecipient& rcp, recipients) {
// generate bold amount string
QString amount = "<b>" + BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount);
amount.append("</b> ").append(strFunds);
// generate monospace address string
QString address = "<span style='font-family: monospace;'>" + rcp.address;
address.append("</span>");
QString recipientElement;
if (!rcp.paymentRequest.IsInitialized()) // normal payment
{
if (rcp.label.length() > 0) // label with address
{
recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.label));
recipientElement.append(QString(" (%1)").arg(address));
} else // just address
{
recipientElement = tr("%1 to %2").arg(amount, address);
}
} else if (!rcp.authenticatedMerchant.isEmpty()) // secure payment request
{
recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.authenticatedMerchant));
} else // insecure payment request
{
recipientElement = tr("%1 to %2").arg(amount, address);
}
if (CoinControlDialog::coinControl->fSplitBlock) {
recipientElement.append(tr(" split into %1 outputs using the UTXO splitter.").arg(CoinControlDialog::coinControl->nSplitBlock));
}
formatted.append(recipientElement);
}
fNewRecipientAllowed = false;
// request unlock only if was locked or unlocked for mixing:
// this way we let users unlock by walletpassphrase or by menu
// and make many transactions while unlocking through this dialog
// will call relock
WalletModel::EncryptionStatus encStatus = model->getEncryptionStatus();
if (encStatus == model->Locked || encStatus == model->UnlockedForAnonymizationOnly) {
WalletModel::UnlockContext ctx(model->requestUnlock(true));
if (!ctx.isValid()) {
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
send(recipients, strFee, formatted);
return;
}
// already unlocked or not encrypted at all
send(recipients, strFee, formatted);
}
void SendCoinsDialog::send(QList<SendCoinsRecipient> recipients, QString strFee, QStringList formatted)
{
// prepare transaction for getting txFee earlier
WalletModelTransaction currentTransaction(recipients);
WalletModel::SendCoinsReturn prepareStatus;
if (model->getOptionsModel()->getCoinControlFeatures()) // coin control enabled
prepareStatus = model->prepareTransaction(currentTransaction, CoinControlDialog::coinControl);
else
prepareStatus = model->prepareTransaction(currentTransaction);
// process prepareStatus and on error generate message shown to user
processSendCoinsReturn(prepareStatus,
BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), currentTransaction.getTransactionFee()), true);
if (prepareStatus.status != WalletModel::OK) {
fNewRecipientAllowed = true;
return;
}
CAmount txFee = currentTransaction.getTransactionFee();
QString questionString = tr("Are you sure you want to send?");
questionString.append("<br /><br />%1");
if (txFee > 0) {
// append fee string if a fee is required
questionString.append("<hr /><span style='color:#aa0000;'>");
questionString.append(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), txFee));
questionString.append("</span> ");
questionString.append(tr("are added as transaction fee"));
questionString.append(" ");
questionString.append(strFee);
// append transaction size
questionString.append(" (" + QString::number((double)currentTransaction.getTransactionSize() / 1000) + " kB)");
}
// add total amount in all subdivision units
questionString.append("<hr />");
CAmount totalAmount = currentTransaction.getTotalTransactionAmount() + txFee;
QStringList alternativeUnits;
foreach (BitcoinUnits::Unit u, BitcoinUnits::availableUnits()) {
if (u != model->getOptionsModel()->getDisplayUnit())
alternativeUnits.append(BitcoinUnits::formatHtmlWithUnit(u, totalAmount));
}
// Show total amount + all alternative units
questionString.append(tr("Total Amount = <b>%1</b><br />= %2")
.arg(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), totalAmount))
.arg(alternativeUnits.join("<br />= ")));
// Limit number of displayed entries
int messageEntries = formatted.size();
int displayedEntries = 0;
for (int i = 0; i < formatted.size(); i++) {
if (i >= MAX_SEND_POPUP_ENTRIES) {
formatted.removeLast();
i--;
} else {
displayedEntries = i + 1;
}
}
questionString.append("<hr />");
questionString.append(tr("<b>(%1 of %2 entries displayed)</b>").arg(displayedEntries).arg(messageEntries));
// Display message box
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
questionString.arg(formatted.join("<br />")),
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel);
if (retval != QMessageBox::Yes) {
fNewRecipientAllowed = true;
return;
}
// now send the prepared transaction
WalletModel::SendCoinsReturn sendStatus = model->sendCoins(currentTransaction);
// process sendStatus and on error generate message shown to user
processSendCoinsReturn(sendStatus);
if (sendStatus.status == WalletModel::OK) {
accept();
CoinControlDialog::coinControl->UnSelectAll();
coinControlUpdateLabels();
}
fNewRecipientAllowed = true;
}
void SendCoinsDialog::clear()
{
// Remove entries until only one left
while (ui->entries->count()) {
ui->entries->takeAt(0)->widget()->deleteLater();
}
addEntry();
updateTabsAndLabels();
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
SendCoinsEntry* SendCoinsDialog::addEntry()
{
SendCoinsEntry* entry = new SendCoinsEntry(this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels()));
updateTabsAndLabels();
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
qApp->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if (bar)
bar->setSliderPosition(bar->maximum());
return entry;
}
void SendCoinsDialog::updateTabsAndLabels()
{
setupTabChain(0);
coinControlUpdateLabels();
}
void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
{
entry->hide();
// If the last entry is about to be removed add an empty one
if (ui->entries->count() == 1)
addEntry();
entry->deleteLater();
updateTabsAndLabels();
}
QWidget* SendCoinsDialog::setupTabChain(QWidget* prev)
{
for (int i = 0; i < ui->entries->count(); ++i) {
SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if (entry) {
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->sendButton);
QWidget::setTabOrder(ui->sendButton, ui->clearButton);
QWidget::setTabOrder(ui->clearButton, ui->addButton);
return ui->addButton;
}
void SendCoinsDialog::setAddress(const QString& address)
{
SendCoinsEntry* entry = 0;
// Replace the first entry if it is still unused
if (ui->entries->count() == 1) {
SendCoinsEntry* first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if (first->isClear()) {
entry = first;
}
}
if (!entry) {
entry = addEntry();
}
entry->setAddress(address);
}
void SendCoinsDialog::pasteEntry(const SendCoinsRecipient& rv)
{
if (!fNewRecipientAllowed)
return;
SendCoinsEntry* entry = 0;
// Replace the first entry if it is still unused
if (ui->entries->count() == 1) {
SendCoinsEntry* first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if (first->isClear()) {
entry = first;
}
}
if (!entry) {
entry = addEntry();
}
entry->setValue(rv);
updateTabsAndLabels();
}
bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient& rv)
{
// Just paste the entry, all pre-checks
// are done in paymentserver.cpp.
pasteEntry(rv);
return true;
}
void SendCoinsDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance,
const CAmount& zerocoinBalance, const CAmount& unconfirmedZerocoinBalance, const CAmount& immatureZerocoinBalance,
const CAmount& watchBalance, const CAmount& watchUnconfirmedBalance, const CAmount& watchImmatureBalance)
{
Q_UNUSED(unconfirmedBalance);
Q_UNUSED(immatureBalance);
Q_UNUSED(zerocoinBalance);
Q_UNUSED(unconfirmedZerocoinBalance);
Q_UNUSED(immatureZerocoinBalance);
Q_UNUSED(watchBalance);
Q_UNUSED(watchUnconfirmedBalance);
Q_UNUSED(watchImmatureBalance);
if (model && model->getOptionsModel()) {
uint64_t bal = 0;
bal = balance;
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), bal));
}
}
void SendCoinsDialog::updateDisplayUnit()
{
TRY_LOCK(cs_main, lockMain);
if (!lockMain) return;
setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(),
model->getZerocoinBalance (), model->getUnconfirmedZerocoinBalance (), model->getImmatureZerocoinBalance (),
model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance());
coinControlUpdateLabels();
ui->customFee->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
updateMinFeeLabel();
updateSmartFeeLabel();
}
void SendCoinsDialog::updateSwiftTX()
{
QSettings settings;
settings.setValue("bUseSwiftTX", ui->checkSwiftTX->isChecked());
CoinControlDialog::coinControl->useSwiftTX = ui->checkSwiftTX->isChecked();
coinControlUpdateLabels();
}
void SendCoinsDialog::processSendCoinsReturn(const WalletModel::SendCoinsReturn& sendCoinsReturn, const QString& msgArg, bool fPrepare)
{
bool fAskForUnlock = false;
QPair<QString, CClientUIInterface::MessageBoxFlags> msgParams;
// Default to a warning message, override if error message is needed
msgParams.second = CClientUIInterface::MSG_WARNING;
// This comment is specific to SendCoinsDialog usage of WalletModel::SendCoinsReturn.
// WalletModel::TransactionCommitFailed is used only in WalletModel::sendCoins()
// all others are used only in WalletModel::prepareTransaction()
switch (sendCoinsReturn.status) {
case WalletModel::InvalidAddress:
msgParams.first = tr("The recipient address is not valid, please recheck.");
break;
case WalletModel::InvalidAmount:
msgParams.first = tr("The amount to pay must be larger than 0.");
break;
case WalletModel::AmountExceedsBalance:
msgParams.first = tr("The amount exceeds your balance.");
break;
case WalletModel::AmountWithFeeExceedsBalance:
msgParams.first = tr("The total exceeds your balance when the %1 transaction fee is included.").arg(msgArg);
break;
case WalletModel::DuplicateAddress:
msgParams.first = tr("Duplicate address found, can only send to each address once per send operation.");
break;
case WalletModel::TransactionCreationFailed:
msgParams.first = tr("Transaction creation failed!");
msgParams.second = CClientUIInterface::MSG_ERROR;
break;
case WalletModel::TransactionCommitFailed:
msgParams.first = tr("The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
msgParams.second = CClientUIInterface::MSG_ERROR;
break;
case WalletModel::AnonymizeOnlyUnlocked:
// Unlock is only need when the coins are send
if(!fPrepare)
fAskForUnlock = true;
else
msgParams.first = tr("Error: The wallet was unlocked only to anonymize coins.");
break;
case WalletModel::InsaneFee:
msgParams.first = tr("A fee %1 times higher than %2 per kB is considered an insanely high fee.").arg(10000).arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), ::minRelayTxFee.GetFeePerK()));
break;
// included to prevent a compiler warning.
case WalletModel::OK:
default:
return;
}
// Unlock wallet if it wasn't fully unlocked already
if(fAskForUnlock) {
model->requestUnlock(false);
if(model->getEncryptionStatus () != WalletModel::Unlocked) {
msgParams.first = tr("Error: The wallet was unlocked only to anonymize coins. Unlock canceled.");
}
else {
// Wallet unlocked
return;
}
}
emit message(tr("Send Coins"), msgParams.first, msgParams.second);
}
void SendCoinsDialog::minimizeFeeSection(bool fMinimize)
{
ui->labelFeeMinimized->setVisible(fMinimize);
ui->buttonChooseFee->setVisible(fMinimize);
ui->buttonMinimizeFee->setVisible(!fMinimize);
ui->frameFeeSelection->setVisible(!fMinimize);
ui->horizontalLayoutSmartFee->setContentsMargins(0, (fMinimize ? 0 : 6), 0, 0);
fFeeMinimized = fMinimize;
}
void SendCoinsDialog::on_buttonChooseFee_clicked()
{
minimizeFeeSection(false);
}
void SendCoinsDialog::on_buttonMinimizeFee_clicked()
{
updateFeeMinimizedLabel();
minimizeFeeSection(true);
}
void SendCoinsDialog::setMinimumFee()
{
ui->radioCustomPerKilobyte->setChecked(true);
ui->customFee->setValue(CWallet::minTxFee.GetFeePerK());
}
void SendCoinsDialog::updateFeeSectionControls()
{
ui->sliderSmartFee->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFee->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFee2->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFee3->setEnabled(ui->radioSmartFee->isChecked());
ui->labelFeeEstimation->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFeeNormal->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFeeFast->setEnabled(ui->radioSmartFee->isChecked());
ui->checkBoxMinimumFee->setEnabled(ui->radioCustomFee->isChecked());
ui->labelMinFeeWarning->setEnabled(ui->radioCustomFee->isChecked());
ui->radioCustomPerKilobyte->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked());
ui->radioCustomAtLeast->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked());
ui->customFee->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked());
}
void SendCoinsDialog::updateGlobalFeeVariables()
{
if (ui->radioSmartFee->isChecked()) {
nTxConfirmTarget = (int)25 - (int)std::max(0, std::min(24, ui->sliderSmartFee->value()));
payTxFee = CFeeRate(0);
} else {
nTxConfirmTarget = 25;
payTxFee = CFeeRate(ui->customFee->value());
fPayAtLeastCustomFee = ui->radioCustomAtLeast->isChecked();
}
fSendFreeTransactions = ui->checkBoxFreeTx->isChecked();
}
void SendCoinsDialog::updateFeeMinimizedLabel()
{
if (!model || !model->getOptionsModel())
return;
if (ui->radioSmartFee->isChecked())
ui->labelFeeMinimized->setText(ui->labelSmartFee->text());
else {
ui->labelFeeMinimized->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), ui->customFee->value()) +
((ui->radioCustomPerKilobyte->isChecked()) ? "/kB" : ""));
}
}
void SendCoinsDialog::updateMinFeeLabel()
{
if (model && model->getOptionsModel())
ui->checkBoxMinimumFee->setText(tr("Pay only the minimum fee of %1").arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), CWallet::minTxFee.GetFeePerK()) + "/kB"));
}
void SendCoinsDialog::updateSmartFeeLabel()
{
if (!model || !model->getOptionsModel())
return;
int nBlocksToConfirm = (int)25 - (int)std::max(0, std::min(24, ui->sliderSmartFee->value()));
CFeeRate feeRate = mempool.estimateFee(nBlocksToConfirm);
if (feeRate <= CFeeRate(0)) // not enough data => minfee
{
ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), CWallet::minTxFee.GetFeePerK()) + "/kB");
ui->labelSmartFee2->show(); // (Smart fee not initialized yet. This usually takes a few blocks...)
ui->labelFeeEstimation->setText("");
} else {
ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()) + "/kB");
ui->labelSmartFee2->hide();
ui->labelFeeEstimation->setText(tr("Estimated to begin confirmation within %n block(s).", "", nBlocksToConfirm));
}
updateFeeMinimizedLabel();
}
// UTXO splitter
void SendCoinsDialog::splitBlockChecked(int state)
{
if (model) {
CoinControlDialog::coinControl->fSplitBlock = (state == Qt::Checked);
fSplitBlock = (state == Qt::Checked);
ui->splitBlockLineEdit->setEnabled((state == Qt::Checked));
ui->labelBlockSizeText->setEnabled((state == Qt::Checked));
ui->labelBlockSize->setEnabled((state == Qt::Checked));
coinControlUpdateLabels();
}
}
//UTXO splitter
void SendCoinsDialog::splitBlockLineEditChanged(const QString& text)
{
//grab the amount in Coin Control AFter Fee field
QString qAfterFee = ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace("~", "").simplified().replace(" ", "");
//convert to CAmount
CAmount nAfterFee;
ParseMoney(qAfterFee.toStdString().c_str(), nAfterFee);
//if greater than 0 then divide after fee by the amount of blocks
CAmount nSize = nAfterFee;
int nBlocks = text.toInt();
if (nAfterFee && nBlocks)
nSize = nAfterFee / nBlocks;
//assign to split block dummy, which is used to recalculate the fee amount more outputs
CoinControlDialog::nSplitBlockDummy = nBlocks;
//update labels
ui->labelBlockSize->setText(QString::fromStdString(FormatMoney(nSize)));
coinControlUpdateLabels();
}
// Coin Control: copy label "Quantity" to clipboard
void SendCoinsDialog::coinControlClipboardQuantity()
{
GUIUtil::setClipboard(ui->labelCoinControlQuantity->text());
}
// Coin Control: copy label "Amount" to clipboard
void SendCoinsDialog::coinControlClipboardAmount()
{
GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// Coin Control: copy label "Fee" to clipboard
void SendCoinsDialog::coinControlClipboardFee()
{
GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace("~", ""));
}
// Coin Control: copy label "After fee" to clipboard
void SendCoinsDialog::coinControlClipboardAfterFee()
{
GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace("~", ""));
}
// Coin Control: copy label "Bytes" to clipboard
void SendCoinsDialog::coinControlClipboardBytes()
{
GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace("~", ""));
}
// Coin Control: copy label "Priority" to clipboard
void SendCoinsDialog::coinControlClipboardPriority()
{
GUIUtil::setClipboard(ui->labelCoinControlPriority->text());
}
// Coin Control: copy label "Dust" to clipboard
void SendCoinsDialog::coinControlClipboardLowOutput()
{
GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text());
}
// Coin Control: copy label "Change" to clipboard
void SendCoinsDialog::coinControlClipboardChange()
{
GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace("~", ""));
}
// Coin Control: settings menu - coin control enabled/disabled by user
void SendCoinsDialog::coinControlFeatureChanged(bool checked)
{
ui->frameCoinControl->setVisible(checked);
if (!checked && model) // coin control features disabled
CoinControlDialog::coinControl->SetNull();
if (checked)
coinControlUpdateLabels();
}
// Coin Control: button inputs -> show actual coin control dialog
void SendCoinsDialog::coinControlButtonClicked()
{
CoinControlDialog dlg;
dlg.setModel(model);
dlg.exec();
coinControlUpdateLabels();
}
// Coin Control: checkbox custom change address
void SendCoinsDialog::coinControlChangeChecked(int state)
{
if (state == Qt::Unchecked) {
CoinControlDialog::coinControl->destChange = CNoDestination();
ui->labelCoinControlChangeLabel->clear();
} else
// use this to re-validate an already entered address
coinControlChangeEdited(ui->lineEditCoinControlChange->text());
ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked));
}
// Coin Control: custom change address changed
void SendCoinsDialog::coinControlChangeEdited(const QString& text)
{
if (model && model->getAddressTableModel()) {
// Default to no change address until verified
CoinControlDialog::coinControl->destChange = CNoDestination();
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}");
CBitcoinAddress addr = CBitcoinAddress(text.toStdString());
if (text.isEmpty()) // Nothing entered
{
ui->labelCoinControlChangeLabel->setText("");
} else if (!addr.IsValid()) // Invalid address
{
ui->labelCoinControlChangeLabel->setText(tr("Warning: Invalid NodeCircle address"));
} else // Valid address
{
CPubKey pubkey;
CKeyID keyid;
addr.GetKeyID(keyid);
if (!model->getPubKey(keyid, pubkey)) // Unknown change address
{
ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address"));
} else // Known change address
{
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}");
// Query label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(text);
if (!associatedLabel.isEmpty())
ui->labelCoinControlChangeLabel->setText(associatedLabel);
else
ui->labelCoinControlChangeLabel->setText(tr("(no label)"));
CoinControlDialog::coinControl->destChange = addr.Get();
}
}
}
}
// Coin Control: update labels
void SendCoinsDialog::coinControlUpdateLabels()
{
if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures())
return;
// set pay amounts
CoinControlDialog::payAmounts.clear();
for (int i = 0; i < ui->entries->count(); ++i) {
SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if (entry)
CoinControlDialog::payAmounts.append(entry->getValue().amount);
}
if (CoinControlDialog::coinControl->HasSelected()) {
// actual coin control calculation
CoinControlDialog::updateLabels(model, this);
// show coin control stats
ui->labelCoinControlAutomaticallySelected->hide();
ui->widgetCoinControl->show();
} else {
// hide coin control stats
ui->labelCoinControlAutomaticallySelected->show();
ui->widgetCoinControl->hide();
ui->labelCoinControlInsuffFunds->hide();
}
}
|
#ifndef TEXT_MANAGER_HPP
#define TEXT_MANAGER_HPP
#include <ft2build.h>
#include FT_FREETYPE_H
#include "Texture.hpp"
#include "Sprite.hpp"
#include "FontId.hpp"
class GlyphTexture : public Texture {
public:
GlyphTexture();
~GlyphTexture();
bool init(const FT_GlyphSlot &glyph);
};
class GlyphSprite : public Sprite {
public:
GlyphSprite();
~GlyphSprite();
bool init(const FT_GlyphSlot &glyph);
void deinit();
GLuint getVAO();
void draw();
protected:
GLuint vao;
GLuint vbo;
GLuint tvbo;
GlyphTexture texture; // Should convert this sometime to handle a texture atlas
};
struct Glyph { // Rasterized glyph
GlyphSprite sprite;
// Width and height data already captured in texture
GLuint left; // distance between left of glyph and x=0
GLuint top; // distance between top of glyph and y=0
GLfloat advance; // x-distance between the origin points of this glyph and the next
};
#define TEXT_NUM_OF_SUPPORTED_CHARS 128 // first 128 ASCII chars
struct Font { // Rasterized, i.e. already has a fixed size
// Note: for a greater alphabet in the future, this can be changed to std::map, the access will still have the same syntax
Glyph glyphs[TEXT_NUM_OF_SUPPORTED_CHARS];
GLfloat height; // Distance between one baseline and the next
};
class TextManager {
public:
TextManager();
~TextManager();
bool init();
void deinit();
// Getters of useful params
// Versions with missing ID params means the function will return the value for the current active font
GLfloat getCharLength(FontId fontId, FontsizeId fontsizeId, char c) const;
GLfloat getCharLength(char c) const;
GLfloat getTextLength(FontId fontId, FontsizeId fontsizeId, const char* text) const;
GLfloat getTextLength(const char* text) const;
GLfloat getFontHeight(FontId fontId, FontsizeId fontsizeId) const;
GLfloat getFontHeight() const;
void setActiveFont(FontId fontId, FontsizeId fontsizeId);
// Later: load font texture atlas into GPU
// Truncate the given text to be within the given maxWidth
// (Rewrite: Should return an array of strings, which is the given string split into several substrings all within the given maxWidth, to be drawn consecutively)
//const char* getTruncatedText(FontId fontId, const char* text, GLuint maxWidth);
// Returns the amount to advance (in the +x direction) to the next position to print the next char
GLfloat drawChar(char c);
// Higher UiManager responsible for positioning each char, setting colour etc. (since the uniforms (particularly translations) are handled over there)
protected:
Font fonts[FONT_ID_COUNT][FONTSIZE_ID_COUNT];
FT_UInt fontsizes[FONTSIZE_ID_COUNT]; // Might possibly become different value sets for different fonts
FontId activeFontId;
FontsizeId activeFontsizeId;
bool initFont(FT_Library ftlib, FontId fontId, const char *filepath);
};
#endif // TEXT_MANAGER_HPP
|
#include "fileWatcher.hh"
#ifdef __linux__
#include "fileWatcher_linux.cpp"
#elif __APPLE__
#include "fileWatcher_osx.cpp"
#endif
|
#include <cstdio>
#include <csignal>
#include <unistd.h>
#include "CmdOptions.h"
#include "NetServer.h"
#include "ServerApp.h"
ServerApp *G_pApp = nullptr;
bool G_RUNNING = true;
void SignalHandler(int signum)
{
G_RUNNING = false;
if (G_pApp)
{
G_pApp->Stop();
}
}
int main(int argc, char *argv[])
{
signal(SIGINT, SignalHandler);
ParseCmdOptions(argc, argv);
// 将程序运行在后台
if (G_AppOptions.bBackground)
{
if (daemon(0, 1) == -1)
{
printf("daemon error\n");
}
}
NetServer &pNetServer = NetServer::getInstance();
G_pApp = new ServerApp;
pNetServer.StartServer(1024, 1024);
G_pApp->SendMessage();
while (G_RUNNING)
{
sleep(1);
}
return 0;
}
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (C) 2008-2016 Ryo Suzuki
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include "Fwd.hpp"
# include "Optional.hpp"
# include "PointVector.hpp"
# include "Quaternion.hpp"
# include "Mat4x4.hpp"
namespace s3d
{
struct Disc
{
Quaternion rotation = Quaternion::Identity();
#pragma warning(disable:4201)
union
{
struct { double x, y, z, r; };
struct { Vec3 center; double r; };
};
#pragma warning(default:4201)
Disc() = default;
explicit Disc(double _r, const Quaternion& _rotation = Quaternion::Identity())
: rotation(_rotation)
, x(0.0)
, y(0.0)
, z(0.0)
, r(_r) {}
Disc(double _x, double _y, double _z, double _r, const Quaternion& _rotation = Quaternion::Identity())
: rotation(_rotation)
, x(_x)
, y(_y)
, z(_z)
, r(_r) {}
Disc(const Vec3& pos, double _r, const Quaternion& _rotation = Quaternion::Identity())
: rotation(_rotation)
, x(pos.x)
, y(pos.y)
, z(pos.z)
, r(_r) {}
Disc& setPos(double _x, double _y, double _z) { return setPos({ _x, _y, _z }); }
Disc& setPos(const Vec3& _pos) { center.set(_pos); return *this; }
Disc& setSize(double _r) { r = _r; return *this; }
Disc& moveBy(double _x, double _y, double _z) { return moveBy({ _x, _y, _z }); }
Disc& moveBy(const Vec3& v) { center.moveBy(v); return *this; }
Disc movedBy(double _x, double _y, double _z) const { return movedBy({ _x, _y, _z }); }
Disc movedBy(const Vec3& v) const { return{ center.movedBy(v), r, rotation }; }
Disc stretched(double s) const { return{ center, r + s, rotation }; }
Disc scaled(double s) const { return{ center, r * s, rotation }; }
Disc rollPitchYaw(double roll, double pitch, double yaw) const { return{ center, r, rotation.rollPitchYaw(roll, pitch, yaw) }; }
Disc rollPitchYaw(const Quaternion& _rotation) const { return{ center, r, rotation * _rotation }; }
Mat4x4 XM_CALLCONV getMatrix() const { return Mat4x4::AffineTransform({ r, 1.0, r }, rotation, center); }
TransformedMesh asMesh() const;
template <class Primitive>
bool intersects(const Primitive& primitive) const
{
return Geometry3D::Intersect(*this, primitive);
}
void draw(const ColorF& color = Palette::White) const;
void draw(const Texture& texture, const ColorF& color = Palette::White) const;
void drawForward(const ColorF& color = Palette::White) const;
void drawForward(const Texture& texture, const ColorF& color = Palette::White) const;
};
}
|
#ifndef GeometryService_src_DetectorSystemMaker_hh
#define GeometryService_src_DetectorSystemMaker_hh
//
// Construct a DetectorSystem object.
//
// $Id: DetectorSystemMaker.hh,v 1.6 2013/03/15 15:52:04 kutschke Exp $
// $Author: kutschke $
// $Date: 2013/03/15 15:52:04 $
//
// Original author Rob Kutschke
//
// C++ includes
#include <memory>
// Mu2e includes.
#include "Mu2eInterfaces/inc/Detector.hh"
#include "GeometryService/inc/DetectorSystem.hh"
namespace mu2e {
// Forward references
class SimpleConfig;
class DetectorSystemMaker: virtual public Detector{
public:
static std::unique_ptr<DetectorSystem> make(const SimpleConfig&);
};
} //namespace mu2e
#endif /* GeometryService_src_DetectorSystemMaker_hh */
|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define rep(i, s, t) for(int i = s;i <= t;i++)
#define rap(i, s, t) for(int i = s;i >= t;i--)
using namespace std;
int C[1005], D[1005];
int N, b;
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &N, &b);
rep(i, 1, N)
scanf("%d", &C[i]);
rep(i, 1, N - 1)
scanf("%d", &D[i]);
int support = 0;
int flag = 1;
rep(i, 1, N - 1)
{
support += C[i];
support -= D[i] * b;
if(support < 0)
{
flag = 0;
break;
}
}
if(flag == 1)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}
|
/******************************************************************************
Copyright (c) 2020, Farbod Farshidian. 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 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 "ocs2_core/integration/SensitivityIntegratorImpl.h"
namespace ocs2 {
/******************************************************************************************************/
/******************************************************************************************************/
/******************************************************************************************************/
vector_t eulerDiscretization(SystemDynamicsBase& system, scalar_t t, const vector_t& x, const vector_t& u, scalar_t dt) {
vector_t tmp = system.computeFlowMap(t, x, u);
tmp = x + dt * tmp;
return tmp;
}
/******************************************************************************************************/
/******************************************************************************************************/
/******************************************************************************************************/
VectorFunctionLinearApproximation eulerSensitivityDiscretization(SystemDynamicsBase& system, scalar_t t, const vector_t& x,
const vector_t& u, scalar_t dt) {
// x_{k+1} = A_{k} * dx_{k} + B_{k} * du_{k} + b_{k}
// A_{k} = Id + dt * dfdx
// B_{k} = dt * dfdu
// b_{k} = x_{n} + dt * f(x_{n},u_{n})
auto continuousApproximation = system.linearApproximation(t, x, u);
continuousApproximation.dfdx *= dt;
continuousApproximation.dfdx.diagonal().array() += 1.0; // plus Identity()
continuousApproximation.dfdu *= dt;
continuousApproximation.f = x + dt * continuousApproximation.f;
return continuousApproximation;
}
/******************************************************************************************************/
/******************************************************************************************************/
/******************************************************************************************************/
vector_t rk2Discretization(SystemDynamicsBase& system, scalar_t t, const vector_t& x, const vector_t& u, scalar_t dt) {
const scalar_t dt_halve = dt / 2.0;
// System evaluations
const vector_t k1 = system.computeFlowMap(t, x, u);
vector_t tmp = x + dt * k1;
const vector_t k2 = system.computeFlowMap(t + dt, tmp, u);
tmp = x + dt_halve * k1 + dt_halve * k2;
return tmp;
}
/******************************************************************************************************/
/******************************************************************************************************/
/******************************************************************************************************/
VectorFunctionLinearApproximation rk2SensitivityDiscretization(SystemDynamicsBase& system, scalar_t t, const vector_t& x, const vector_t& u,
scalar_t dt) {
const scalar_t dt_halve = dt / 2.0;
// System evaluations
VectorFunctionLinearApproximation k1 = system.linearApproximation(t, x, u);
VectorFunctionLinearApproximation k2 = system.linearApproximation(t + dt, x + dt * k1.f, u);
// Input sensitivity \dot{Su} = dfdx(t) Su + dfdu(t), with Su(0) = Zero()
// Re-use memory from k.dfdu as dkduk
// dk1duk = k1.dfdu
k2.dfdu.noalias() += dt * k2.dfdx * k1.dfdu;
// State sensitivity \dot{Sx} = dfdx(t) Sx, with Sx(0) = Identity()
// Re-use memory from k.dfdx as dkdxk
// dk1dxk = k1.dfdx;
k2.dfdx += dt * k2.dfdx * k1.dfdx; // need one temporary to avoid alias
// Assemble discrete approximation
// Re-use k1 to collect the result
k1.dfdx = dt_halve * k1.dfdx + dt_halve * k2.dfdx;
k1.dfdx.diagonal().array() += 1.0; // plus Identity()
k1.dfdu = dt_halve * k1.dfdu + dt_halve * k2.dfdu;
k1.f = x + dt_halve * k1.f + dt_halve * k2.f;
return k1;
}
/******************************************************************************************************/
/******************************************************************************************************/
/******************************************************************************************************/
vector_t rk4Discretization(SystemDynamicsBase& system, scalar_t t, const vector_t& x, const vector_t& u, scalar_t dt) {
const scalar_t dt_halve = dt / 2.0;
const scalar_t dt_sixth = dt / 6.0;
const scalar_t dt_third = dt / 3.0;
// System evaluations
const vector_t k1 = system.computeFlowMap(t, x, u);
vector_t tmp = x + dt_halve * k1;
const vector_t k2 = system.computeFlowMap(t + dt_halve, tmp, u);
tmp = x + dt_halve * k2;
const vector_t k3 = system.computeFlowMap(t + dt_halve, tmp, u);
tmp = x + dt * k3;
const vector_t k4 = system.computeFlowMap(t + dt, tmp, u);
tmp = x + dt_sixth * k1 + dt_third * k2 + dt_third * k3 + dt_sixth * k4;
return tmp;
}
/******************************************************************************************************/
/******************************************************************************************************/
/******************************************************************************************************/
VectorFunctionLinearApproximation rk4SensitivityDiscretization(SystemDynamicsBase& system, scalar_t t, const vector_t& x, const vector_t& u,
scalar_t dt) {
const scalar_t dt_halve = dt / 2.0;
const scalar_t dt_sixth = dt / 6.0;
const scalar_t dt_third = dt / 3.0;
// System evaluations
VectorFunctionLinearApproximation k1 = system.linearApproximation(t, x, u);
vector_t tmpV = x + dt_halve * k1.f;
VectorFunctionLinearApproximation k2 = system.linearApproximation(t + dt_halve, tmpV, u);
tmpV = x + dt_halve * k2.f;
VectorFunctionLinearApproximation k3 = system.linearApproximation(t + dt_halve, tmpV, u);
tmpV = x + dt * k3.f;
VectorFunctionLinearApproximation k4 = system.linearApproximation(t + dt, tmpV, u);
// Input sensitivity \dot{Su} = dfdx(t) Su + dfdu(t), with Su(0) = Zero()
// Re-use memory from k.dfdu as dkduk
// dk1duk = k1.dfdu
k2.dfdu.noalias() += dt_halve * k2.dfdx * k1.dfdu;
k3.dfdu.noalias() += dt_halve * k3.dfdx * k2.dfdu;
k4.dfdu.noalias() += dt * k4.dfdx * k3.dfdu;
// State sensitivity \dot{Sx} = dfdx(t) Sx, with Sx(0) = Identity()
// Re-use memory from k.dfdx as dkdxk
// dk1dxk = k1.dfdx;
matrix_t tmp = dt_halve * k2.dfdx * k1.dfdx; // need one temporary to avoid alias
k2.dfdx += tmp;
tmp.noalias() = dt_halve * k3.dfdx * k2.dfdx;
k3.dfdx += tmp;
tmp.noalias() = dt * k4.dfdx * k3.dfdx;
k4.dfdx += tmp;
// Assemble discrete approximation
// Re-use k1 to collect the result
k1.dfdx = dt_sixth * k1.dfdx + dt_third * k2.dfdx + dt_third * k3.dfdx + dt_sixth * k4.dfdx;
k1.dfdx.diagonal().array() += 1.0; // plus Identity()
k1.dfdu = dt_sixth * k1.dfdu + dt_third * k2.dfdu + dt_third * k3.dfdu + dt_sixth * k4.dfdu;
k1.f = x + dt_sixth * k1.f + dt_third * k2.f + dt_third * k3.f + dt_sixth * k4.f;
return k1;
}
} // namespace ocs2
|
#include "sphere.hpp"
#include <glm/vec3.hpp>
#include <cmath>
Sphere::Sphere() :
Shape{"none"},
center_{0.0, 0.0, 0.0},
radius_{1.0} {}
Sphere::Sphere(glm::vec3 const& center, double radius) :
Shape{"sphere_radius"},
center_{center},
radius_{radius} {}
Sphere::Sphere(Sphere const& x) :
Shape{"sphere_copy"},
center_{x.center_},
radius_{x.radius_} {}
double Sphere::getradius()
{
return radius_;
}
glm::vec3 Sphere::getcenter()
{
return center_;
}
double Sphere::area() const
{
double a = 4*M_PI*radius_*radius_;
return a;
}
double Sphere::volume() const
{
double v = (4.0/3.0)*M_PI*radius_*radius_*radius_;
return v;
}
/*std::string const& Sphere::name() const
{
return name_;
}
Color const& Sphere::color() const
{
return color_;
}*/
std::ostream& Sphere::print(std::ostream& os) const
{
os << "Sphere";
Shape::print(os);
os << radius_;
return os;
}
bool Sphere::intersect(Ray const& r) const
{
auto v = glm::normalize(r.direction);
float distance = 0;
return glm::intersectRaySphere(r.origin, v, center_,radius_, distance);
}
|
#include "main.h"
#include <natus/ntd/string.hpp>
#include <natus/log/global.h>
#include <natus/ntd/vector.hpp>
#include <natus/math/vector/vector2.hpp>
#include <cstdlib>
#include <chrono>
#include <limits>
#include <thread>
#include <functional>
#include <mmdeviceapi.h>
#include <audioclient.h>
#include <windows.h>
// Testing audio capture of system output/mix using wasapi
// https://docs.microsoft.com/en-us/windows/win32/coreaudio/loopback-recording
// https://docs.microsoft.com/en-us/windows/win32/coreaudio/capturing-a-stream
const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
const IID IID_IAudioClient = __uuidof(IAudioClient);
const IID IID_IAudioCaptureClient = __uuidof(IAudioCaptureClient);
#define REFTIMES_PER_SEC 10000000
#define REFTIMES_PER_MILLISEC 10000
using namespace natus::core::types ;
#if 0
struct loopback_device
{
natus_this_typedefs( loopback_device ) ;
public:
loopback_device( void_t ) {}
loopback_device( this_cref_t ) = delete ;
loopback_device( this_rref_t rhv )
{
natus_move_member_ptr( def_device_ptr, rhv ) ;
natus_move_member_ptr( audio_client_ptr, rhv ) ;
natus_move_member_ptr( wav_format_ptr, rhv ) ;
natus_move_member_ptr( capture_client_ptr, rhv ) ;
}
~loopback_device( void_t ) {}
public:
IMMDevice * def_device_ptr = NULL ;
IAudioClient *audio_client_ptr = NULL;
IAudioCaptureClient * capture_client_ptr = NULL ;
// format see: mmreg.h
WAVEFORMATEX * wav_format_ptr = NULL ;
};
#endif
//
// - test audio capture with wasapi loopback device
//
int main( int argc, char ** argv )
{
IMMDeviceEnumerator *pEnumerator = NULL ;
IMMDevice *pDevice = NULL ;
// format see: mmreg.h
WAVEFORMATEX *pwfx = NULL ;
IAudioClient *pAudioClient = NULL;
UINT32 bufferFrameCount;
REFERENCE_TIME hnsRequestedDuration = REFTIMES_PER_SEC;
REFERENCE_TIME hnsActualDuration;
IAudioCaptureClient *pCaptureClient = NULL;
WAVEFORMATEXTENSIBLE * fmt_ext = NULL ;
bool_t is_float = false ;
//so_audio::ipcm_buffer_ptr_t the_buffer = nullptr ;
{
auto const res = CoInitializeEx( NULL, COINIT_MULTITHREADED ) ;
if( res != S_OK )
{
natus::log::global::error( "[wasapi_engine::initialize] : CoInitializeEx" ) ;
return 1 ;
}
}
{
HRESULT const hr = CoCreateInstance(
CLSID_MMDeviceEnumerator, NULL,
CLSCTX_ALL, IID_IMMDeviceEnumerator,
(void**)&pEnumerator ) ;
if( hr != S_OK )
{
natus::log::global::error( "[wasapi_engine::initialize] : CoCreateInstance" ) ;
return 1 ;
}
}
{
auto const res = pEnumerator->GetDefaultAudioEndpoint(
eRender, eConsole, &pDevice ) ;
if( res != S_OK )
{
natus::log::global::error( "[wasapi_engine::initialize] : GetDefaultAudioEndpoint" ) ;
return 1 ;
}
}
{
auto const res = pDevice->Activate( IID_IAudioClient, CLSCTX_ALL,
NULL, (void**)&pAudioClient );
if( res != S_OK )
{
natus::log::global::error( "[wasapi_engine::initialize] : Device Activate" ) ;
return 1 ;
}
}
std::function< void_t ( BYTE const * buffer, UINT32 const num_frames, natus::ntd::vector< float_t > & ) > copy_funk =
[=]( BYTE const * buffer, UINT32 const num_frames, natus::ntd::vector< float_t > & ){} ;
{
auto const res = pAudioClient->GetMixFormat( &pwfx ) ;
if( res != S_OK )
{
natus::log::global::error( "[wasapi_engine::initialize] : GetMixFormat" ) ;
return 1 ;
}
if( pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE )
{
fmt_ext = (WAVEFORMATEXTENSIBLE*)pwfx ;
if( fmt_ext->SubFormat == KSDATAFORMAT_SUBTYPE_PCM )
{
int const bp = 0 ;
// create integral type buffer
if( pwfx->wBitsPerSample == 8 )
{
copy_funk = [=]( BYTE const * buffer, UINT32 const num_frames, natus::ntd::vector< float_t > & samples )
{
samples.resize( num_frames ) ;
for( size_t i=0; i<num_frames; ++i )
{
samples[i] = float_t(double_t(int8_cptr_t(buffer)[i])/125.0) ;
}
} ;
}
else if( pwfx->wBitsPerSample == 16 )
{
copy_funk = [=]( BYTE const * buffer, UINT32 const num_frames, natus::ntd::vector< float_t > & samples )
{
samples.resize( num_frames ) ;
for( size_t i=0; i<num_frames; ++i )
{
samples[i] = float_t(double_t(int16_cptr_t(buffer)[i])/32768.0) ;
}
} ;
}
else if( pwfx->wBitsPerSample == 32 )
{
copy_funk = [=]( BYTE const * buffer, UINT32 const num_frames, natus::ntd::vector< float_t > & samples )
{
samples.resize( num_frames ) ;
for( size_t i=0; i<num_frames; ++i )
{
samples[i] = float_t(double_t(int32_cptr_t(buffer)[i])/2147483648.0) ;
}
} ;
}
}
else if( fmt_ext->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT )
{
copy_funk = [=]( BYTE const * buffer, UINT32 const num_frames, natus::ntd::vector< float_t > & samples )
{
samples.resize( num_frames ) ;
for( size_t i=0; i<num_frames; ++i )
{
samples[i] = float_cptr_t(buffer)[i] ;
}
} ;
}
}
}
{
auto const res = pAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_STREAMFLAGS_LOOPBACK, hnsRequestedDuration,
0, pwfx, NULL ) ;
if( res != S_OK )
{
natus::log::global::error( "[wasapi_engine::initialize] : AudioClient Initialize" ) ;
return 1 ;
}
}
{
auto const res = pAudioClient->GetBufferSize( &bufferFrameCount ) ;
if( res != S_OK )
{
natus::log::global::error( "[wasapi_engine::initialize] : GetBufferSize" ) ;
return 1 ;
}
}
{
auto const res = pAudioClient->GetService( IID_IAudioCaptureClient, (void**)&pCaptureClient ) ;
if( res != S_OK )
{
natus::log::global::error( "[wasapi_engine::initialize] : AudioClient GetService" ) ;
return 1 ;
}
}
{
auto const res = pAudioClient->Start() ;
if( res != S_OK )
{
natus::log::global::error( "[wasapi_engine::initialize] : AudioClient GetService" ) ;
return 1 ;
}
}
size_t const num_bits_per_sample = pwfx->wBitsPerSample ;
{
natus::ntd::vector< float_t > samples ;
typedef std::chrono::high_resolution_clock clock_t ;
clock_t::time_point tp = clock_t::now() ;
while( std::chrono::duration_cast<std::chrono::seconds>( clock_t::now() - tp ) < std::chrono::seconds( 10 ) )
{
UINT32 packetLength = 0 ;
// read available data
{
auto const res = pCaptureClient->GetNextPacketSize( &packetLength ) ;
if( res != S_OK )
{
natus::log::global::error( "[wasapi_engine] : GetNextPacketSize" ) ;
break ;
}
}
while( packetLength != 0 )
{
// get loopback data
BYTE *data_ptr ;
UINT32 num_frames_available ;
DWORD flags ;
{
auto const res = pCaptureClient->GetBuffer( &data_ptr,
&num_frames_available, &flags, NULL, NULL ) ;
if( res != S_OK )
{
natus::log::global::error( "[wasapi_engine] : unable to get audio buffer."
"Will cancel thread." ) ;
break ;
}
}
copy_funk( data_ptr, num_frames_available, samples ) ;
// release wasapi buffer
{
auto const res = pCaptureClient->ReleaseBuffer( num_frames_available ) ;
if( res != S_OK )
{
natus::log::global::error( "[wasapi_engine] : ReleaseBuffer" ) ;
break ;
}
}
// print data
{
float_t accum = 0.0f ;
for( auto const s : samples ) accum += s ;
natus::log::global_t::status( std::to_string(accum / float_t(samples.size())) ) ;
}
// read available data
{
auto const res = pCaptureClient->GetNextPacketSize( &packetLength ) ;
if( res != S_OK )
{
natus::log::global::error( "[wasapi_engine] : GetNextPacketSize" ) ;
break ;
}
}
}
}
}
return 0 ;
}
|
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/sfm/pipelines/sequential/sequential_SfM.hpp"
#include "openMVG/geometry/pose3.hpp"
#include "openMVG/multiview/triangulation.hpp"
#include "openMVG/sfm/pipelines/sfm_features_provider.hpp"
#include "openMVG/sfm/pipelines/sfm_matches_provider.hpp"
#include "openMVG/sfm/pipelines/localization/SfM_Localizer.hpp"
#include "openMVG/sfm/pipelines/sfm_robust_model_estimation.hpp"
#include "openMVG/sfm/sfm_data.hpp"
#include "openMVG/sfm/sfm_data_BA.hpp"
#include "openMVG/sfm/sfm_data_BA_ceres.hpp"
#include "openMVG/sfm/sfm_data_filters.hpp"
#include "openMVG/sfm/sfm_data_io.hpp"
#include "openMVG/stl/stl.hpp"
#include "third_party/histogram/histogram.hpp"
#include "third_party/htmlDoc/htmlDoc.hpp"
#include "third_party/progress/progress.hpp"
#include <ceres/types.h>
#include <functional>
#include <iostream>
#include <utility>
#ifdef _MSC_VER
#pragma warning( once : 4267 ) //warning C4267: 'argument' : conversion from 'size_t' to 'const int', possible loss of data
#endif
namespace openMVG {
namespace sfm {
using namespace openMVG::cameras;
using namespace openMVG::geometry;
using namespace openMVG::matching;
SequentialSfMReconstructionEngine::SequentialSfMReconstructionEngine(
const SfM_Data & sfm_data,
const std::string & soutDirectory,
const std::string & sloggingFile)
: ReconstructionEngine(sfm_data, soutDirectory),
sLogging_file_(sloggingFile),
initial_pair_(0,0),
cam_type_(EINTRINSIC(PINHOLE_CAMERA_RADIAL3))
{
if (!sLogging_file_.empty())
{
// setup HTML logger
html_doc_stream_ = std::make_shared<htmlDocument::htmlDocumentStream>("SequentialReconstructionEngine SFM report.");
html_doc_stream_->pushInfo(
htmlDocument::htmlMarkup("h1", std::string("SequentialSfMReconstructionEngine")));
html_doc_stream_->pushInfo("<hr>");
html_doc_stream_->pushInfo( "Dataset info:");
html_doc_stream_->pushInfo( "Views count: " +
htmlDocument::toString( sfm_data.GetViews().size()) + "<br>");
}
// Init remaining image list
for (Views::const_iterator itV = sfm_data.GetViews().begin();
itV != sfm_data.GetViews().end(); ++itV)
{
set_remaining_view_id_.insert(itV->second->id_view);
}
}
SequentialSfMReconstructionEngine::~SequentialSfMReconstructionEngine()
{
if (!sLogging_file_.empty())
{
// Save the reconstruction Log
std::ofstream htmlFileStream(sLogging_file_.c_str());
htmlFileStream << html_doc_stream_->getDoc();
}
}
void SequentialSfMReconstructionEngine::SetFeaturesProvider(Features_Provider * provider)
{
features_provider_ = provider;
}
void SequentialSfMReconstructionEngine::SetMatchesProvider(Matches_Provider * provider)
{
matches_provider_ = provider;
}
bool SequentialSfMReconstructionEngine::Process() {
//-------------------
//-- Incremental reconstruction
//-------------------
if (!InitLandmarkTracks())
return false;
// Initial pair choice
if (initial_pair_ == Pair(0,0))
{
if (!AutomaticInitialPairChoice(initial_pair_))
{
// Cannot find a valid initial pair, try to set it by hand?
if (!ChooseInitialPair(initial_pair_))
{
return false;
}
}
}
// Else a starting pair was already initialized before
// Initial pair Essential Matrix and [R|t] estimation.
if (!MakeInitialPair3D(initial_pair_))
return false;
// Compute robust Resection of remaining images
// - group of images will be selected and resection + scene completion will be tried
size_t resectionGroupIndex = 0;
std::vector<uint32_t> vec_possible_resection_indexes;
while (FindImagesWithPossibleResection(vec_possible_resection_indexes))
{
bool bImageAdded = false;
// Add images to the 3D reconstruction
for (const auto & iter : vec_possible_resection_indexes)
{
bImageAdded |= Resection(iter);
set_remaining_view_id_.erase(iter);
}
if (bImageAdded)
{
// Scene logging as ply for visual debug
std::ostringstream os;
os << std::setw(8) << std::setfill('0') << resectionGroupIndex << "_Resection";
Save(sfm_data_, stlplus::create_filespec(sOut_directory_, os.str(), ".ply"), ESfM_Data(ALL));
// Perform BA until all point are under the given precision
do
{
BundleAdjustment();
}
while (badTrackRejector(4.0, 50));
eraseUnstablePosesAndObservations(sfm_data_);
}
++resectionGroupIndex;
}
// Ensure there is no remaining outliers
if (badTrackRejector(4.0, 0))
{
eraseUnstablePosesAndObservations(sfm_data_);
}
//-- Reconstruction done.
//-- Display some statistics
std::cout << "\n\n-------------------------------" << "\n"
<< "-- Structure from Motion (statistics):\n"
<< "-- #Camera calibrated: " << sfm_data_.GetPoses().size()
<< " from " << sfm_data_.GetViews().size() << " input images.\n"
<< "-- #Tracks, #3D points: " << sfm_data_.GetLandmarks().size() << "\n"
<< "-------------------------------" << "\n";
Histogram<double> h;
ComputeResidualsHistogram(&h);
std::cout << "\nHistogram of residuals:\n" << h.ToString() << std::endl;
if (!sLogging_file_.empty())
{
using namespace htmlDocument;
std::ostringstream os;
os << "Structure from Motion process finished.";
html_doc_stream_->pushInfo("<hr>");
html_doc_stream_->pushInfo(htmlMarkup("h1",os.str()));
os.str("");
os << "-------------------------------" << "<br>"
<< "-- Structure from Motion (statistics):<br>"
<< "-- #Camera calibrated: " << sfm_data_.GetPoses().size()
<< " from " <<sfm_data_.GetViews().size() << " input images.<br>"
<< "-- #Tracks, #3D points: " << sfm_data_.GetLandmarks().size() << "<br>"
<< "-------------------------------" << "<br>";
html_doc_stream_->pushInfo(os.str());
html_doc_stream_->pushInfo(htmlMarkup("h2","Histogram of reprojection-residuals"));
const std::vector<double> xBin = h.GetXbinsValue();
const auto range = autoJSXGraphViewport<double>(xBin, h.GetHist());
htmlDocument::JSXGraphWrapper jsxGraph;
jsxGraph.init("3DtoImageResiduals",600,300);
jsxGraph.addXYChart(xBin, h.GetHist(), "line,point");
jsxGraph.UnsuspendUpdate();
jsxGraph.setViewport(range);
jsxGraph.close();
html_doc_stream_->pushInfo(jsxGraph.toStr());
}
return true;
}
/// Select a candidate initial pair
bool SequentialSfMReconstructionEngine::ChooseInitialPair(Pair & initialPairIndex) const
{
if (initial_pair_ != Pair(0,0))
{
// Internal initial pair is already initialized (so return it)
initialPairIndex = initial_pair_;
}
else
{
// List Views that supports valid intrinsic
std::set<IndexT> valid_views;
for (const auto & view : sfm_data_.GetViews())
{
const View * v = view.second.get();
if (sfm_data_.GetIntrinsics().find(v->id_intrinsic) != sfm_data_.GetIntrinsics().end())
valid_views.insert(v->id_view);
}
if (sfm_data_.GetIntrinsics().empty() || valid_views.empty())
{
std::cerr
<< "There is no defined intrinsic data in order to compute an essential matrix for the initial pair."
<< std::endl;
return false;
}
std::cout << std::endl
<< "----------------------------------------------------\n"
<< "SequentialSfMReconstructionEngine::ChooseInitialPair\n"
<< "----------------------------------------------------\n"
<< " Pairs that have valid intrinsic and high support of points are displayed:\n"
<< " Choose one pair manually by typing the two integer indexes\n"
<< "----------------------------------------------------\n"
<< std::endl;
// Try to list the 10 top pairs that have:
// - valid intrinsics,
// - valid estimated Fundamental matrix.
std::vector<uint32_t > vec_NbMatchesPerPair;
std::vector<openMVG::matching::PairWiseMatches::const_iterator> vec_MatchesIterator;
const openMVG::matching::PairWiseMatches & map_Matches = matches_provider_->pairWise_matches_;
for (openMVG::matching::PairWiseMatches::const_iterator
iter = map_Matches.begin();
iter != map_Matches.end(); ++iter)
{
const Pair current_pair = iter->first;
if (valid_views.count(current_pair.first) &&
valid_views.count(current_pair.second) )
{
vec_NbMatchesPerPair.push_back(iter->second.size());
vec_MatchesIterator.push_back(iter);
}
}
// sort the Pairs in descending order according their correspondences count
using namespace stl::indexed_sort;
std::vector<sort_index_packet_descend<uint32_t, uint32_t>> packet_vec(vec_NbMatchesPerPair.size());
sort_index_helper(packet_vec, &vec_NbMatchesPerPair[0], std::min((size_t)10, vec_NbMatchesPerPair.size()));
for (size_t i = 0; i < std::min((size_t)10, vec_NbMatchesPerPair.size()); ++i) {
const uint32_t index = packet_vec[i].index;
openMVG::matching::PairWiseMatches::const_iterator iter = vec_MatchesIterator[index];
std::cout << "(" << iter->first.first << "," << iter->first.second <<")\t\t"
<< iter->second.size() << " matches" << std::endl;
}
// Ask the user to choose an initial pair (by set some view ids)
std::cout << std::endl << " type INITIAL pair ids: X enter Y enter\n";
int val, val2;
if ( std::cin >> val && std::cin >> val2) {
initialPairIndex.first = val;
initialPairIndex.second = val2;
}
}
std::cout << "\nPutative starting pair is: (" << initialPairIndex.first
<< "," << initialPairIndex.second << ")" << std::endl;
// Check validity of the initial pair indices:
if (features_provider_->feats_per_view.find(initialPairIndex.first) == features_provider_->feats_per_view.end() ||
features_provider_->feats_per_view.find(initialPairIndex.second) == features_provider_->feats_per_view.end())
{
std::cerr << "At least one of the initial pair indices is invalid."
<< std::endl;
return false;
}
return true;
}
bool SequentialSfMReconstructionEngine::InitLandmarkTracks()
{
// Compute tracks from matches
tracks::TracksBuilder tracksBuilder;
{
// List of features matches for each couple of images
const openMVG::matching::PairWiseMatches & map_Matches = matches_provider_->pairWise_matches_;
std::cout << "\n" << "Track building" << std::endl;
tracksBuilder.Build(map_Matches);
std::cout << "\n" << "Track filtering" << std::endl;
tracksBuilder.Filter();
std::cout << "\n" << "Track export to internal struct" << std::endl;
//-- Build tracks with STL compliant type :
tracksBuilder.ExportToSTL(map_tracks_);
std::cout << "\n" << "Track stats" << std::endl;
{
std::ostringstream osTrack;
//-- Display stats :
// - number of images
// - number of tracks
std::set<uint32_t> set_imagesId;
tracks::TracksUtilsMap::ImageIdInTracks(map_tracks_, set_imagesId);
osTrack << "------------------" << "\n"
<< "-- Tracks Stats --" << "\n"
<< " Tracks number: " << tracksBuilder.NbTracks() << "\n"
<< " Images Id: " << "\n";
std::copy(set_imagesId.begin(),
set_imagesId.end(),
std::ostream_iterator<uint32_t>(osTrack, ", "));
osTrack << "\n------------------" << "\n";
std::map<uint32_t, uint32_t> map_Occurence_TrackLength;
tracks::TracksUtilsMap::TracksLength(map_tracks_, map_Occurence_TrackLength);
osTrack << "TrackLength, Occurrence" << "\n";
for (const auto & it : map_Occurence_TrackLength) {
osTrack << "\t" << it.first << "\t" << it.second << "\n";
}
osTrack << "\n";
std::cout << osTrack.str();
}
}
// Initialize the shared track visibility helper
shared_track_visibility_helper_.reset(new openMVG::tracks::SharedTrackVisibilityHelper(map_tracks_));
return map_tracks_.size() > 0;
}
bool SequentialSfMReconstructionEngine::AutomaticInitialPairChoice(Pair & initial_pair) const
{
// select a pair that have the largest baseline (mean angle between its bearing vectors).
const unsigned iMin_inliers_count = 100;
const float fRequired_min_angle = 3.0f;
const float fLimit_max_angle = 60.0f; // More than 60 degree, we cannot rely on matches for initial pair seeding
// List Views that support valid intrinsic (view that could be used for Essential matrix computation)
std::set<IndexT> valid_views;
for (Views::const_iterator it = sfm_data_.GetViews().begin();
it != sfm_data_.GetViews().end(); ++it)
{
const View * v = it->second.get();
if (sfm_data_.GetIntrinsics().count(v->id_intrinsic))
valid_views.insert(v->id_view);
}
if (valid_views.size() < 2)
{
return false; // There is not view that support valid intrinsic data
}
std::vector<std::pair<double, Pair>> scoring_per_pair;
// Compute the relative pose & the 'baseline score'
C_Progress_display my_progress_bar( matches_provider_->pairWise_matches_.size(),
std::cout,
"Automatic selection of an initial pair:\n" );
#ifdef OPENMVG_USE_OPENMP
#pragma omp parallel
#endif
for (const std::pair<Pair, IndMatches> & match_pair : matches_provider_->pairWise_matches_)
{
#ifdef OPENMVG_USE_OPENMP
#pragma omp single nowait
#endif
{
++my_progress_bar;
const Pair current_pair = match_pair.first;
const uint32_t I = std::min(current_pair.first, current_pair.second);
const uint32_t J = std::max(current_pair.first, current_pair.second);
if (valid_views.count(I) && valid_views.count(J))
{
const View
* view_I = sfm_data_.GetViews().at(I).get(),
* view_J = sfm_data_.GetViews().at(J).get();
const Intrinsics::const_iterator
iterIntrinsic_I = sfm_data_.GetIntrinsics().find(view_I->id_intrinsic),
iterIntrinsic_J = sfm_data_.GetIntrinsics().find(view_J->id_intrinsic);
const auto
cam_I = iterIntrinsic_I->second.get(),
cam_J = iterIntrinsic_J->second.get();
if (cam_I && cam_J)
{
openMVG::tracks::STLMAPTracks map_tracksCommon;
shared_track_visibility_helper_->GetTracksInImages({I, J}, map_tracksCommon);
// Copy points correspondences to arrays for relative pose estimation
const size_t n = map_tracksCommon.size();
Mat xI(2,n), xJ(2,n);
size_t cptIndex = 0;
for (const auto & track_iter : map_tracksCommon)
{
auto iter = track_iter.second.cbegin();
const uint32_t i = iter->second;
const uint32_t j = (++iter)->second;
Vec2 feat = features_provider_->feats_per_view[I][i].coords().cast<double>();
xI.col(cptIndex) = cam_I->get_ud_pixel(feat);
feat = features_provider_->feats_per_view[J][j].coords().cast<double>();
xJ.col(cptIndex) = cam_J->get_ud_pixel(feat);
++cptIndex;
}
// Robust estimation of the relative pose
RelativePose_Info relativePose_info;
relativePose_info.initial_residual_tolerance = Square(4.0);
if (robustRelativePose(
cam_I, cam_J,
xI, xJ, relativePose_info,
{cam_I->w(), cam_I->h()}, {cam_J->w(), cam_J->h()},
256)
&& relativePose_info.vec_inliers.size() > iMin_inliers_count)
{
// Triangulate inliers & compute angle between bearing vectors
std::vector<float> vec_angles;
vec_angles.reserve(relativePose_info.vec_inliers.size());
const Pose3 pose_I = Pose3(Mat3::Identity(), Vec3::Zero());
const Pose3 pose_J = relativePose_info.relativePose;
for (const uint32_t & inlier_idx : relativePose_info.vec_inliers)
{
openMVG::tracks::STLMAPTracks::const_iterator iterT = map_tracksCommon.begin();
std::advance(iterT, inlier_idx);
tracks::submapTrack::const_iterator iter = iterT->second.begin();
const Vec2 featI = features_provider_->feats_per_view[I][iter->second].coords().cast<double>();
const Vec2 featJ = features_provider_->feats_per_view[J][(++iter)->second].coords().cast<double>();
vec_angles.push_back(AngleBetweenRay(pose_I, cam_I, pose_J, cam_J,
cam_I->get_ud_pixel(featI), cam_J->get_ud_pixel(featJ)));
}
// Compute the median triangulation angle
const unsigned median_index = vec_angles.size() / 2;
std::nth_element(
vec_angles.begin(),
vec_angles.begin() + median_index,
vec_angles.end());
const float scoring_angle = vec_angles[median_index];
// Store the pair iff the pair is in the asked angle range [fRequired_min_angle;fLimit_max_angle]
if (scoring_angle > fRequired_min_angle &&
scoring_angle < fLimit_max_angle)
{
#ifdef OPENMVG_USE_OPENMP
#pragma omp critical
#endif
scoring_per_pair.emplace_back(scoring_angle, current_pair);
}
}
}
}
} // omp section
}
std::sort(scoring_per_pair.begin(), scoring_per_pair.end());
// Since scoring is ordered in increasing order, reverse the order
std::reverse(scoring_per_pair.begin(), scoring_per_pair.end());
if (!scoring_per_pair.empty())
{
initial_pair = scoring_per_pair.begin()->second;
return true;
}
return false;
}
/// Compute the initial 3D seed (First camera t=0; R=Id, second estimated by 5 point algorithm)
bool SequentialSfMReconstructionEngine::MakeInitialPair3D(const Pair & current_pair)
{
// Compute robust Essential matrix for ImageId [I,J]
// use min max to have I < J
const uint32_t
I = std::min(current_pair.first, current_pair.second),
J = std::max(current_pair.first, current_pair.second);
if (sfm_data_.GetViews().count(I) == 0 ||
sfm_data_.GetViews().count(J) == 0)
{
return false;
}
// a. Assert we have valid cameras
const View
* view_I = sfm_data_.GetViews().at(I).get(),
* view_J = sfm_data_.GetViews().at(J).get();
const Intrinsics::const_iterator
iterIntrinsic_I = sfm_data_.GetIntrinsics().find(view_I->id_intrinsic),
iterIntrinsic_J = sfm_data_.GetIntrinsics().find(view_J->id_intrinsic);
if (iterIntrinsic_I == sfm_data_.GetIntrinsics().end() ||
iterIntrinsic_J == sfm_data_.GetIntrinsics().end() )
{
return false;
}
const auto
* cam_I = iterIntrinsic_I->second.get(),
* cam_J = iterIntrinsic_J->second.get();
if (!cam_I || !cam_J)
{
return false;
}
// b. Get common features between the two view
// use the track to have a more dense match correspondence set
openMVG::tracks::STLMAPTracks map_tracksCommon;
shared_track_visibility_helper_->GetTracksInImages({I, J}, map_tracksCommon);
//-- Copy point to arrays
const size_t n = map_tracksCommon.size();
Mat xI(2,n), xJ(2,n);
uint32_t cptIndex = 0;
for (const auto & track_iter : map_tracksCommon)
{
auto iter = track_iter.second.cbegin();
const uint32_t
i = iter->second,
j = (++iter)->second;
Vec2 feat = features_provider_->feats_per_view[I][i].coords().cast<double>();
xI.col(cptIndex) = cam_I->get_ud_pixel(feat);
feat = features_provider_->feats_per_view[J][j].coords().cast<double>();
xJ.col(cptIndex) = cam_J->get_ud_pixel(feat);
++cptIndex;
}
// c. Robust estimation of the relative pose
RelativePose_Info relativePose_info;
const std::pair<size_t, size_t>
imageSize_I(cam_I->w(), cam_I->h()),
imageSize_J(cam_J->w(), cam_J->h());
if (!robustRelativePose(
cam_I, cam_J, xI, xJ, relativePose_info, imageSize_I, imageSize_J, 4096))
{
std::cerr << " /!\\ Robust estimation failed to compute E for this pair"
<< std::endl;
return false;
}
std::cout << "A-Contrario initial pair residual: "
<< relativePose_info.found_residual_precision << std::endl;
// Bound min precision at 1 pix.
relativePose_info.found_residual_precision = std::max(relativePose_info.found_residual_precision, 1.0);
const bool bRefine_using_BA = true;
if (bRefine_using_BA)
{
// Refine the defined scene
SfM_Data tiny_scene;
tiny_scene.views.insert(*sfm_data_.GetViews().find(view_I->id_view));
tiny_scene.views.insert(*sfm_data_.GetViews().find(view_J->id_view));
tiny_scene.intrinsics.insert(*sfm_data_.GetIntrinsics().find(view_I->id_intrinsic));
tiny_scene.intrinsics.insert(*sfm_data_.GetIntrinsics().find(view_J->id_intrinsic));
// Init poses
const Pose3 & Pose_I = tiny_scene.poses[view_I->id_pose] = Pose3(Mat3::Identity(), Vec3::Zero());
const Pose3 & Pose_J = tiny_scene.poses[view_J->id_pose] = relativePose_info.relativePose;
// Init structure
Landmarks & landmarks = tiny_scene.structure;
for (const auto & track_iterator : map_tracksCommon)
{
// Get corresponding points
auto iter = track_iterator.second.cbegin();
const uint32_t
i = iter->second,
j = (++iter)->second;
const Vec2
x1 = features_provider_->feats_per_view[I][i].coords().cast<double>(),
x2 = features_provider_->feats_per_view[J][j].coords().cast<double>();
Vec3 X;
TriangulateDLT(Pose_I.asMatrix(), (*cam_I)(cam_I->get_ud_pixel(x1)),
Pose_J.asMatrix(), (*cam_J)(cam_J->get_ud_pixel(x2)), &X);
Observations obs;
obs[view_I->id_view] = Observation(x1, i);
obs[view_J->id_view] = Observation(x2, j);
landmarks[track_iterator.first].obs = std::move(obs);
landmarks[track_iterator.first].X = X;
}
Save(tiny_scene, stlplus::create_filespec(sOut_directory_, "initialPair.ply"), ESfM_Data(ALL));
// - refine only Structure and Rotations & translations (keep intrinsic constant)
Bundle_Adjustment_Ceres::BA_Ceres_options options(true, true);
options.linear_solver_type_ = ceres::DENSE_SCHUR;
Bundle_Adjustment_Ceres bundle_adjustment_obj(options);
if (!bundle_adjustment_obj.Adjust(tiny_scene,
Optimize_Options
(
Intrinsic_Parameter_Type::NONE, // Keep intrinsic constant
Extrinsic_Parameter_Type::ADJUST_ALL, // Adjust camera motion
Structure_Parameter_Type::ADJUST_ALL) // Adjust structure
)
)
{
return false;
}
// Save computed data
const Pose3 pose_I = sfm_data_.poses[view_I->id_pose] = tiny_scene.poses[view_I->id_pose];
const Pose3 pose_J = sfm_data_.poses[view_J->id_pose] = tiny_scene.poses[view_J->id_pose];
map_ACThreshold_.insert({I, relativePose_info.found_residual_precision});
map_ACThreshold_.insert({J, relativePose_info.found_residual_precision});
set_remaining_view_id_.erase(view_I->id_view);
set_remaining_view_id_.erase(view_J->id_view);
// List inliers and save them
for (const auto & landmark_entry : tiny_scene.GetLandmarks())
{
const IndexT trackId = landmark_entry.first;
const Landmark & landmark = landmark_entry.second;
const Observations & obs = landmark.obs;
Observations::const_iterator
iterObs_xI = obs.find(view_I->id_view),
iterObs_xJ = obs.find(view_J->id_view);
const Observation & ob_xI = iterObs_xI->second;
const Observation & ob_xJ = iterObs_xJ->second;
const Vec2
ob_xI_ud = cam_I->get_ud_pixel(ob_xI.x),
ob_xJ_ud = cam_J->get_ud_pixel(ob_xJ.x);
const double angle = AngleBetweenRay(
pose_I, cam_I, pose_J, cam_J, ob_xI_ud, ob_xJ_ud);
const Vec2 residual_I = cam_I->residual(pose_I(landmark.X), ob_xI.x);
const Vec2 residual_J = cam_J->residual(pose_J(landmark.X), ob_xJ.x);
if (angle > 2.0 &&
CheiralityTest((*cam_I)(ob_xI_ud), pose_I,
(*cam_J)(ob_xJ_ud), pose_J,
landmark.X) &&
residual_I.norm() < relativePose_info.found_residual_precision &&
residual_J.norm() < relativePose_info.found_residual_precision)
{
sfm_data_.structure[trackId] = landmarks[trackId];
}
}
// Save outlier residual information
Histogram<double> histoResiduals;
std::cout << "\n"
<< "=========================\n"
<< " MSE Residual InitialPair Inlier:\n";
ComputeResidualsHistogram(&histoResiduals);
std::cout << "=========================" << std::endl;
if (!sLogging_file_.empty())
{
using namespace htmlDocument;
html_doc_stream_->pushInfo(htmlMarkup("h1","Essential Matrix."));
std::ostringstream os;
os << std::endl
<< "-------------------------------" << "<br>"
<< "-- Robust Essential matrix: <" << I << "," <<J << "> images: "
<< view_I->s_Img_path << ","
<< view_J->s_Img_path << "<br>"
<< "-- Threshold: " << relativePose_info.found_residual_precision << "<br>"
<< "-- Resection status: " << "OK" << "<br>"
<< "-- Nb points used for robust Essential matrix estimation: "
<< xI.cols() << "<br>"
<< "-- Nb points validated by robust estimation: "
<< sfm_data_.structure.size() << "<br>"
<< "-- % points validated: "
<< sfm_data_.structure.size()/static_cast<float>(xI.cols())
<< "<br>"
<< "-------------------------------" << "<br>";
html_doc_stream_->pushInfo(os.str());
html_doc_stream_->pushInfo(htmlMarkup("h2",
"Residual of the robust estimation (Initial triangulation). Thresholded at: "
+ toString(relativePose_info.found_residual_precision)));
html_doc_stream_->pushInfo(htmlMarkup("h2","Histogram of residuals"));
const std::vector<double> xBin = histoResiduals.GetXbinsValue();
const auto range = autoJSXGraphViewport<double>(xBin, histoResiduals.GetHist());
htmlDocument::JSXGraphWrapper jsxGraph;
jsxGraph.init("InitialPairTriangulationKeptInfo",600,300);
jsxGraph.addXYChart(xBin, histoResiduals.GetHist(), "line,point");
jsxGraph.addLine(relativePose_info.found_residual_precision, 0,
relativePose_info.found_residual_precision, histoResiduals.GetHist().front());
jsxGraph.UnsuspendUpdate();
jsxGraph.setViewport(range);
jsxGraph.close();
html_doc_stream_->pushInfo(jsxGraph.toStr());
html_doc_stream_->pushInfo("<hr>");
std::ofstream htmlFileStream( std::string(stlplus::folder_append_separator(sOut_directory_) +
"Reconstruction_Report.html").c_str());
htmlFileStream << html_doc_stream_->getDoc();
}
}
return !sfm_data_.structure.empty();
}
double SequentialSfMReconstructionEngine::ComputeResidualsHistogram(Histogram<double> * histo)
{
// Collect residuals for each observation
std::vector<float> vec_residuals;
vec_residuals.reserve(sfm_data_.structure.size());
for (const auto & landmark_entry : sfm_data_.GetLandmarks())
{
const Observations & obs = landmark_entry.second.obs;
for (const auto & observation : obs)
{
const View * view = sfm_data_.GetViews().find(observation.first)->second.get();
const Pose3 pose = sfm_data_.GetPoseOrDie(view);
const auto intrinsic = sfm_data_.GetIntrinsics().find(view->id_intrinsic)->second;
const Vec2 residual = intrinsic->residual(pose(landmark_entry.second.X), observation.second.x);
vec_residuals.emplace_back( std::abs(residual(0)) );
vec_residuals.emplace_back( std::abs(residual(1)) );
}
}
// Display statistics
if (vec_residuals.size() > 1)
{
float dMin, dMax, dMean, dMedian;
minMaxMeanMedian<float>(vec_residuals.cbegin(), vec_residuals.cend(),
dMin, dMax, dMean, dMedian);
if (histo) {
*histo = Histogram<double>(dMin, dMax, 10);
histo->Add(vec_residuals.cbegin(), vec_residuals.cend());
}
std::cout << std::endl << std::endl;
std::cout << std::endl
<< "SequentialSfMReconstructionEngine::ComputeResidualsMSE." << "\n"
<< "\t-- #Tracks:\t" << sfm_data_.GetLandmarks().size() << std::endl
<< "\t-- Residual min:\t" << dMin << std::endl
<< "\t-- Residual median:\t" << dMedian << std::endl
<< "\t-- Residual max:\t " << dMax << std::endl
<< "\t-- Residual mean:\t " << dMean << std::endl;
return dMean;
}
return -1.0;
}
/// Functor to sort a vector of pair given the pair's second value
template<class T1, class T2, class Pred = std::less<T2>>
struct sort_pair_second {
bool operator()(const std::pair<T1,T2>&left,
const std::pair<T1,T2>&right)
{
Pred p;
return p(left.second, right.second);
}
};
/**
* @brief Estimate images on which we can compute the resectioning safely.
*
* @param[out] vec_possible_indexes: list of indexes we can use for resectioning.
* @return False if there is no possible resection.
*
* Sort the images by the number of features id shared with the reconstruction.
* Select the image I that share the most of correspondences.
* Then keep all the images that have at least:
* 0.75 * #correspondences(I) common correspondences to the reconstruction.
*/
bool SequentialSfMReconstructionEngine::FindImagesWithPossibleResection(
std::vector<uint32_t> & vec_possible_indexes)
{
// Threshold used to select the best images
static const float dThresholdGroup = 0.75f;
vec_possible_indexes.clear();
if (set_remaining_view_id_.empty() || sfm_data_.GetLandmarks().empty())
return false;
// Collect tracksIds
std::set<uint32_t> reconstructed_trackId;
std::transform(sfm_data_.GetLandmarks().cbegin(), sfm_data_.GetLandmarks().cend(),
std::inserter(reconstructed_trackId, reconstructed_trackId.begin()),
stl::RetrieveKey());
Pair_Vec vec_putative; // ImageId, NbPutativeCommonPoint
#ifdef OPENMVG_USE_OPENMP
#pragma omp parallel
#endif
for (std::set<uint32_t>::const_iterator iter = set_remaining_view_id_.begin();
iter != set_remaining_view_id_.end(); ++iter)
{
#ifdef OPENMVG_USE_OPENMP
#pragma omp single nowait
#endif
{
const uint32_t viewId = *iter;
// Compute 2D - 3D possible content
openMVG::tracks::STLMAPTracks map_tracksCommon;
shared_track_visibility_helper_->GetTracksInImages({viewId}, map_tracksCommon);
if (!map_tracksCommon.empty())
{
std::set<uint32_t> set_tracksIds;
tracks::TracksUtilsMap::GetTracksIdVector(map_tracksCommon, &set_tracksIds);
// Count the common possible putative point
// with the already 3D reconstructed trackId
std::vector<uint32_t> vec_trackIdForResection;
std::set_intersection(set_tracksIds.cbegin(), set_tracksIds.cend(),
reconstructed_trackId.cbegin(), reconstructed_trackId.cend(),
std::back_inserter(vec_trackIdForResection));
#ifdef OPENMVG_USE_OPENMP
#pragma omp critical
#endif
{
vec_putative.emplace_back(viewId, vec_trackIdForResection.size());
}
}
}
}
// Sort by the number of matches to the 3D scene.
std::sort(vec_putative.begin(), vec_putative.end(), sort_pair_second<uint32_t, uint32_t, std::greater<uint32_t>>());
// If the list is empty or if the list contains images with no correspdences
// -> (no resection will be possible)
if (vec_putative.empty() || vec_putative[0].second == 0)
{
// All remaining images cannot be used for pose estimation
set_remaining_view_id_.clear();
return false;
}
// Add the image view index that share the most of 2D-3D correspondences
vec_possible_indexes.push_back(vec_putative[0].first);
// Then, add all the image view indexes that have at least N% of the number of the matches of the best image.
const IndexT M = vec_putative[0].second; // Number of 2D-3D correspondences
const size_t threshold = static_cast<uint32_t>(dThresholdGroup * M);
for (size_t i = 1; i < vec_putative.size() &&
vec_putative[i].second > threshold; ++i)
{
vec_possible_indexes.push_back(vec_putative[i].first);
}
return true;
}
/**
* @brief Add one image to the 3D reconstruction. To the resectioning of
* the camera and triangulate all the new possible tracks.
* @param[in] viewIndex: image index to add to the reconstruction.
*
* A. Compute 2D/3D matches
* B. Look if intrinsic data is known or not
* C. Do the resectioning: compute the camera pose.
* D. Refine the pose of the found camera
* E. Update the global scene with the new camera
* F. Update the observations into the global scene structure
* G. Triangulate new possible 2D tracks
*/
bool SequentialSfMReconstructionEngine::Resection(const uint32_t viewIndex)
{
using namespace tracks;
// A. Compute 2D/3D matches
// A1. list tracks ids used by the view
openMVG::tracks::STLMAPTracks map_tracksCommon;
shared_track_visibility_helper_->GetTracksInImages({viewIndex}, map_tracksCommon);
std::set<uint32_t> set_tracksIds;
TracksUtilsMap::GetTracksIdVector(map_tracksCommon, &set_tracksIds);
// A2. intersects the track list with the reconstructed
std::set<uint32_t> reconstructed_trackId;
std::transform(sfm_data_.GetLandmarks().cbegin(), sfm_data_.GetLandmarks().cend(),
std::inserter(reconstructed_trackId, reconstructed_trackId.begin()),
stl::RetrieveKey());
// Get the ids of the already reconstructed tracks
std::set<uint32_t> set_trackIdForResection;
std::set_intersection(set_tracksIds.cbegin(), set_tracksIds.cend(),
reconstructed_trackId.cbegin(), reconstructed_trackId.cend(),
std::inserter(set_trackIdForResection, set_trackIdForResection.begin()));
if (set_trackIdForResection.empty())
{
// No match. The image has no connection with already reconstructed points.
std::cout << std::endl
<< "-------------------------------" << "\n"
<< "-- Resection of camera index: " << viewIndex << "\n"
<< "-- Resection status: " << "FAILED" << "\n"
<< "-------------------------------" << std::endl;
return false;
}
// Get back featId associated to a tracksID already reconstructed.
// These 2D/3D associations will be used for the resection.
std::vector<uint32_t> vec_featIdForResection;
TracksUtilsMap::GetFeatIndexPerViewAndTrackId(map_tracksCommon,
set_trackIdForResection,
viewIndex,
&vec_featIdForResection);
// Localize the image inside the SfM reconstruction
Image_Localizer_Match_Data resection_data;
resection_data.pt2D.resize(2, set_trackIdForResection.size());
resection_data.pt3D.resize(3, set_trackIdForResection.size());
// B. Look if the intrinsic data is known or not
const View * view_I = sfm_data_.GetViews().at(viewIndex).get();
std::shared_ptr<cameras::IntrinsicBase> optional_intrinsic;
if (sfm_data_.GetIntrinsics().count(view_I->id_intrinsic))
{
optional_intrinsic = sfm_data_.GetIntrinsics().at(view_I->id_intrinsic);
}
// Setup the track 2d observation for this new view
Mat2X pt2D_original(2, set_trackIdForResection.size());
std::set<uint32_t>::const_iterator iterTrackId = set_trackIdForResection.begin();
std::vector<uint32_t>::const_iterator iterfeatId = vec_featIdForResection.begin();
for (size_t cpt = 0; cpt < vec_featIdForResection.size(); ++cpt, ++iterTrackId, ++iterfeatId)
{
resection_data.pt3D.col(cpt) = sfm_data_.GetLandmarks().at(*iterTrackId).X;
resection_data.pt2D.col(cpt) = pt2D_original.col(cpt) =
features_provider_->feats_per_view.at(viewIndex)[*iterfeatId].coords().cast<double>();
// Handle image distortion if intrinsic is known (to ease the resection)
if (optional_intrinsic && optional_intrinsic->have_disto())
{
resection_data.pt2D.col(cpt) = optional_intrinsic->get_ud_pixel(resection_data.pt2D.col(cpt));
}
}
// C. Do the resectioning: compute the camera pose
std::cout << std::endl
<< "-------------------------------" << std::endl
<< "-- Robust Resection of view: " << viewIndex << std::endl;
geometry::Pose3 pose;
const bool bResection = sfm::SfM_Localizer::Localize
(
optional_intrinsic ? resection::SolverType::P3P_NORDBERG_ECCV18 : resection::SolverType::DLT_6POINTS,
{view_I->ui_width, view_I->ui_height},
optional_intrinsic.get(),
resection_data,
pose
);
resection_data.pt2D = std::move(pt2D_original); // restore original image domain points
if (!sLogging_file_.empty())
{
using namespace htmlDocument;
std::ostringstream os;
os << "Resection of Image index: <" << viewIndex << "> image: "
<< view_I->s_Img_path <<"<br> \n";
html_doc_stream_->pushInfo(htmlMarkup("h1",os.str()));
os.str("");
os << std::endl
<< "-------------------------------" << "<br>"
<< "-- Robust Resection of camera index: <" << viewIndex << "> image: "
<< view_I->s_Img_path <<"<br>"
<< "-- Threshold: " << resection_data.error_max << "<br>"
<< "-- Resection status: " << (bResection ? "OK" : "FAILED") << "<br>"
<< "-- Nb points used for Resection: " << vec_featIdForResection.size() << "<br>"
<< "-- Nb points validated by robust estimation: " << resection_data.vec_inliers.size() << "<br>"
<< "-- % points validated: "
<< resection_data.vec_inliers.size()/static_cast<float>(vec_featIdForResection.size()) << "<br>"
<< "-------------------------------" << "<br>";
html_doc_stream_->pushInfo(os.str());
}
if (!bResection)
return false;
// D. Refine the pose of the found camera.
// We use a local scene with only the 3D points and the new camera.
{
const bool b_new_intrinsic = (optional_intrinsic == nullptr);
// A valid pose has been found (try to refine it):
// If no valid intrinsic as input:
// init a new one from the projection matrix decomposition
// Else use the existing one and consider it as constant.
if (b_new_intrinsic)
{
// setup a default camera model from the found projection matrix
Mat3 K, R;
Vec3 t;
KRt_From_P(resection_data.projection_matrix, &K, &R, &t);
const double focal = (K(0,0) + K(1,1))/2.0;
const Vec2 principal_point(K(0,2), K(1,2));
// Create the new camera intrinsic group
switch (cam_type_)
{
case PINHOLE_CAMERA:
optional_intrinsic =
std::make_shared<Pinhole_Intrinsic>
(view_I->ui_width, view_I->ui_height, focal, principal_point(0), principal_point(1));
break;
case PINHOLE_CAMERA_RADIAL1:
optional_intrinsic =
std::make_shared<Pinhole_Intrinsic_Radial_K1>
(view_I->ui_width, view_I->ui_height, focal, principal_point(0), principal_point(1));
break;
case PINHOLE_CAMERA_RADIAL3:
optional_intrinsic =
std::make_shared<Pinhole_Intrinsic_Radial_K3>
(view_I->ui_width, view_I->ui_height, focal, principal_point(0), principal_point(1));
break;
case PINHOLE_CAMERA_BROWN:
optional_intrinsic =
std::make_shared<Pinhole_Intrinsic_Brown_T2>
(view_I->ui_width, view_I->ui_height, focal, principal_point(0), principal_point(1));
break;
case PINHOLE_CAMERA_FISHEYE:
optional_intrinsic =
std::make_shared<Pinhole_Intrinsic_Fisheye>
(view_I->ui_width, view_I->ui_height, focal, principal_point(0), principal_point(1));
break;
default:
std::cerr << "Try to create an unknown camera type." << std::endl;
return false;
}
}
const bool b_refine_pose = true;
const bool b_refine_intrinsics = false;
if (!sfm::SfM_Localizer::RefinePose(
optional_intrinsic.get(), pose,
resection_data, b_refine_pose, b_refine_intrinsics))
{
return false;
}
// E. Update the global scene with:
// - the new found camera pose
sfm_data_.poses[view_I->id_pose] = pose;
// - track the view's AContrario robust estimation found threshold
map_ACThreshold_.insert({viewIndex, resection_data.error_max});
// - intrinsic parameters (if the view has no intrinsic group add a new one)
if (b_new_intrinsic)
{
// Since the view have not yet an intrinsic group before, create a new one
IndexT new_intrinsic_id = 0;
if (!sfm_data_.GetIntrinsics().empty())
{
// Since some intrinsic Id already exists,
// we have to create a new unique identifier following the existing one
std::set<IndexT> existing_intrinsicId;
std::transform(sfm_data_.GetIntrinsics().cbegin(), sfm_data_.GetIntrinsics().cend(),
std::inserter(existing_intrinsicId, existing_intrinsicId.begin()),
stl::RetrieveKey());
new_intrinsic_id = (*existing_intrinsicId.rbegin())+1;
}
sfm_data_.views.at(viewIndex)->id_intrinsic = new_intrinsic_id;
sfm_data_.intrinsics[new_intrinsic_id] = optional_intrinsic;
}
}
// F. List tracks that share content with this view and add observations and new 3D track if required.
// - If the track already exists (look if the new view tracks observation are valid)
// - If the track does not exists, try robust triangulation & add the new valid view track observation
{
// Get information of new view
const IndexT I = viewIndex;
const View * view_I = sfm_data_.GetViews().at(I).get();
const IntrinsicBase * cam_I = sfm_data_.GetIntrinsics().at(view_I->id_intrinsic).get();
const Pose3 pose_I = sfm_data_.GetPoseOrDie(view_I);
// Vector of all already reconstructed views
const std::set<IndexT> valid_views = Get_Valid_Views(sfm_data_);
// Go through each track and look if we must add new view observations or new 3D points
for (const std::pair<uint32_t, tracks::submapTrack>& trackIt : map_tracksCommon)
{
const uint32_t trackId = trackIt.first;
const tracks::submapTrack & track = trackIt.second;
// List the potential view observations of the track
const tracks::submapTrack & allViews_of_track = map_tracks_[trackId];
// List to save the new view observations that must be added to the track
std::set<IndexT> new_track_observations_valid_views;
// If the track was already reconstructed
if (sfm_data_.structure.count(trackId) != 0)
{
// Since the 3D point was triangulated before we add the new the Inth view observation
new_track_observations_valid_views.insert(I);
}
else
{
// Go through the views that observe this track & look if a successful triangulation can be done
for (const std::pair<IndexT, IndexT>& trackViewIt : allViews_of_track)
{
const IndexT & J = trackViewIt.first;
// If view is valid try triangulation
if (J != I && valid_views.count(J) != 0)
{
// If successfuly triangulated add the observation from J view
if (sfm_data_.structure.count(trackId) != 0)
{
new_track_observations_valid_views.insert(J);
}
else
{
const View * view_J = sfm_data_.GetViews().at(J).get();
const IntrinsicBase * cam_J = sfm_data_.GetIntrinsics().at(view_J->id_intrinsic).get();
const Pose3 pose_J = sfm_data_.GetPoseOrDie(view_J);
const Vec2 xJ = features_provider_->feats_per_view.at(J)[allViews_of_track.at(J)].coords().cast<double>();
// Position of the point in view I
const Vec2 xI = features_provider_->feats_per_view.at(I)[track.at(I)].coords().cast<double>();
// Try to triangulate a 3D point from J view
// A new 3D point must be added
// Triangulate it
const Vec2
xI_ud = cam_I->get_ud_pixel(xI),
xJ_ud = cam_J->get_ud_pixel(xJ);
Vec3 X = Vec3::Zero();
TriangulateDLT(pose_I.asMatrix(), (*cam_I)(xI_ud),
pose_J.asMatrix(), (*cam_J)(xJ_ud),
&X);
// Check triangulation result
const double angle = AngleBetweenRay(
pose_I, cam_I, pose_J, cam_J, xI_ud, xJ_ud);
const Vec2 residual_I = cam_I->residual(pose_I(X), xI);
const Vec2 residual_J = cam_J->residual(pose_J(X), xJ);
if (
// - Check angle (small angle leads to imprecise triangulation)
angle > 2.0 &&
// - Check positive depth
CheiralityTest((*cam_I)(xI_ud), pose_I,
(*cam_J)(xJ_ud), pose_J,
X) &&
// - Check residual values (must be inferior to the found view's AContrario threshold)
residual_I.norm() < std::max(4.0, map_ACThreshold_.at(I)) &&
residual_J.norm() < std::max(4.0, map_ACThreshold_.at(J))
)
{
// Add a new track
Landmark & landmark = sfm_data_.structure[trackId];
landmark.X = X;
new_track_observations_valid_views.insert(I);
new_track_observations_valid_views.insert(J);
} // 3D point is valid
else
{
// We mark the view to add the observations once the point is triangulated
new_track_observations_valid_views.insert(J);
} // 3D point is invalid
}
}
}// Go through all the views
}// If new point
// If successfuly triangulated, add the valid view observations
if (sfm_data_.structure.count(trackId) != 0 &&
!new_track_observations_valid_views.empty())
{
Landmark & landmark = sfm_data_.structure[trackId];
// Check if view feature point observations of the track are valid (residual, depth) or not
for (const IndexT & J: new_track_observations_valid_views)
{
const View * view_J = sfm_data_.GetViews().at(J).get();
const IntrinsicBase * cam_J = sfm_data_.GetIntrinsics().at(view_J->id_intrinsic).get();
const Pose3 pose_J = sfm_data_.GetPoseOrDie(view_J);
const Vec2 xJ = features_provider_->feats_per_view.at(J)[allViews_of_track.at(J)].coords().cast<double>();
const Vec2 xJ_ud = cam_J->get_ud_pixel(xJ);
const Vec2 residual = cam_J->residual(pose_J(landmark.X), xJ);
if (CheiralityTest((*cam_J)(xJ_ud), pose_J, landmark.X)
&& residual.norm() < std::max(4.0, map_ACThreshold_.at(J))
)
{
landmark.obs[J] = Observation(xJ, allViews_of_track.at(J));
}
}
}
}// All the tracks in the view
}
return true;
}
/// Bundle adjustment to refine Structure; Motion and Intrinsics
bool SequentialSfMReconstructionEngine::BundleAdjustment()
{
Bundle_Adjustment_Ceres::BA_Ceres_options options;
if ( sfm_data_.GetPoses().size() > 100 &&
(ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::SUITE_SPARSE) ||
ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::CX_SPARSE) ||
ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::EIGEN_SPARSE))
)
// Enable sparse BA only if a sparse lib is available and if there more than 100 poses
{
options.preconditioner_type_ = ceres::JACOBI;
options.linear_solver_type_ = ceres::SPARSE_SCHUR;
}
else
{
options.linear_solver_type_ = ceres::DENSE_SCHUR;
}
Bundle_Adjustment_Ceres bundle_adjustment_obj(options);
const Optimize_Options ba_refine_options
( ReconstructionEngine::intrinsic_refinement_options_,
Extrinsic_Parameter_Type::ADJUST_ALL, // Adjust camera motion
Structure_Parameter_Type::ADJUST_ALL, // Adjust scene structure
Control_Point_Parameter(),
this->b_use_motion_prior_
);
return bundle_adjustment_obj.Adjust(sfm_data_, ba_refine_options);
}
/**
* @brief Discard tracks with too large residual error
*
* Remove observation/tracks that have:
* - too large residual error
* - too small angular value
*
* @return True if more than 'count' outliers have been removed.
*/
bool SequentialSfMReconstructionEngine::badTrackRejector(double dPrecision, size_t count)
{
const size_t nbOutliers_residualErr = RemoveOutliers_PixelResidualError(sfm_data_, dPrecision, 2);
const size_t nbOutliers_angleErr = RemoveOutliers_AngleError(sfm_data_, 2.0);
return (nbOutliers_residualErr + nbOutliers_angleErr) > count;
}
} // namespace sfm
} // namespace openMVG
|
// Copyright 2020 The Tint Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/tint/ast/call_statement.h"
#include "src/tint/ast/variable_decl_statement.h"
#include "src/tint/writer/hlsl/test_helper.h"
namespace tint::writer::hlsl {
namespace {
using HlslGeneratorImplTest_Binary = TestHelper;
struct BinaryData {
const char* result;
ast::BinaryOp op;
enum Types { All = 0b11, Integer = 0b10, Float = 0b01 };
Types valid_for = Types::All;
};
inline std::ostream& operator<<(std::ostream& out, BinaryData data) {
out << data.op;
return out;
}
using HlslBinaryTest = TestParamHelper<BinaryData>;
TEST_P(HlslBinaryTest, Emit_f32) {
auto params = GetParam();
if ((params.valid_for & BinaryData::Types::Float) == 0) {
return;
}
// Skip ops that are illegal for this type
if (params.op == ast::BinaryOp::kAnd || params.op == ast::BinaryOp::kOr ||
params.op == ast::BinaryOp::kXor ||
params.op == ast::BinaryOp::kShiftLeft ||
params.op == ast::BinaryOp::kShiftRight) {
return;
}
Global("left", ty.f32(), ast::StorageClass::kPrivate);
Global("right", ty.f32(), ast::StorageClass::kPrivate);
auto* left = Expr("left");
auto* right = Expr("right");
auto* expr = create<ast::BinaryExpression>(params.op, left, right);
WrapInFunction(expr);
GeneratorImpl& gen = Build();
std::stringstream out;
ASSERT_TRUE(gen.EmitExpression(out, expr)) << gen.error();
EXPECT_EQ(out.str(), params.result);
}
TEST_P(HlslBinaryTest, Emit_u32) {
auto params = GetParam();
if ((params.valid_for & BinaryData::Types::Integer) == 0) {
return;
}
Global("left", ty.u32(), ast::StorageClass::kPrivate);
Global("right", ty.u32(), ast::StorageClass::kPrivate);
auto* left = Expr("left");
auto* right = Expr("right");
auto* expr = create<ast::BinaryExpression>(params.op, left, right);
WrapInFunction(expr);
GeneratorImpl& gen = Build();
std::stringstream out;
ASSERT_TRUE(gen.EmitExpression(out, expr)) << gen.error();
EXPECT_EQ(out.str(), params.result);
}
TEST_P(HlslBinaryTest, Emit_i32) {
auto params = GetParam();
if ((params.valid_for & BinaryData::Types::Integer) == 0) {
return;
}
// Skip ops that are illegal for this type
if (params.op == ast::BinaryOp::kShiftLeft ||
params.op == ast::BinaryOp::kShiftRight) {
return;
}
Global("left", ty.i32(), ast::StorageClass::kPrivate);
Global("right", ty.i32(), ast::StorageClass::kPrivate);
auto* left = Expr("left");
auto* right = Expr("right");
auto* expr = create<ast::BinaryExpression>(params.op, left, right);
WrapInFunction(expr);
GeneratorImpl& gen = Build();
std::stringstream out;
ASSERT_TRUE(gen.EmitExpression(out, expr)) << gen.error();
EXPECT_EQ(out.str(), params.result);
}
INSTANTIATE_TEST_SUITE_P(
HlslGeneratorImplTest,
HlslBinaryTest,
testing::Values(
BinaryData{"(left & right)", ast::BinaryOp::kAnd},
BinaryData{"(left | right)", ast::BinaryOp::kOr},
BinaryData{"(left ^ right)", ast::BinaryOp::kXor},
BinaryData{"(left == right)", ast::BinaryOp::kEqual},
BinaryData{"(left != right)", ast::BinaryOp::kNotEqual},
BinaryData{"(left < right)", ast::BinaryOp::kLessThan},
BinaryData{"(left > right)", ast::BinaryOp::kGreaterThan},
BinaryData{"(left <= right)", ast::BinaryOp::kLessThanEqual},
BinaryData{"(left >= right)", ast::BinaryOp::kGreaterThanEqual},
BinaryData{"(left << right)", ast::BinaryOp::kShiftLeft},
BinaryData{"(left >> right)", ast::BinaryOp::kShiftRight},
BinaryData{"(left + right)", ast::BinaryOp::kAdd},
BinaryData{"(left - right)", ast::BinaryOp::kSubtract},
BinaryData{"(left * right)", ast::BinaryOp::kMultiply},
// NOTE: Integer divide covered by DivOrModBy* tests below
BinaryData{"(left / right)", ast::BinaryOp::kDivide,
BinaryData::Types::Float},
// NOTE: Integer modulo covered by DivOrModBy* tests below
BinaryData{"(left % right)", ast::BinaryOp::kModulo,
BinaryData::Types::Float}));
TEST_F(HlslGeneratorImplTest_Binary, Multiply_VectorScalar) {
auto* lhs = vec3<f32>(1.f, 1.f, 1.f);
auto* rhs = Expr(1.f);
auto* expr =
create<ast::BinaryExpression>(ast::BinaryOp::kMultiply, lhs, rhs);
WrapInFunction(expr);
GeneratorImpl& gen = Build();
std::stringstream out;
EXPECT_TRUE(gen.EmitExpression(out, expr)) << gen.error();
EXPECT_EQ(out.str(),
"(float3(1.0f, 1.0f, 1.0f) * "
"1.0f)");
}
TEST_F(HlslGeneratorImplTest_Binary, Multiply_ScalarVector) {
auto* lhs = Expr(1.f);
auto* rhs = vec3<f32>(1.f, 1.f, 1.f);
auto* expr =
create<ast::BinaryExpression>(ast::BinaryOp::kMultiply, lhs, rhs);
WrapInFunction(expr);
GeneratorImpl& gen = Build();
std::stringstream out;
EXPECT_TRUE(gen.EmitExpression(out, expr)) << gen.error();
EXPECT_EQ(out.str(),
"(1.0f * float3(1.0f, 1.0f, "
"1.0f))");
}
TEST_F(HlslGeneratorImplTest_Binary, Multiply_MatrixScalar) {
Global("mat", ty.mat3x3<f32>(), ast::StorageClass::kPrivate);
auto* lhs = Expr("mat");
auto* rhs = Expr(1.f);
auto* expr =
create<ast::BinaryExpression>(ast::BinaryOp::kMultiply, lhs, rhs);
WrapInFunction(expr);
GeneratorImpl& gen = Build();
std::stringstream out;
EXPECT_TRUE(gen.EmitExpression(out, expr)) << gen.error();
EXPECT_EQ(out.str(), "(mat * 1.0f)");
}
TEST_F(HlslGeneratorImplTest_Binary, Multiply_ScalarMatrix) {
Global("mat", ty.mat3x3<f32>(), ast::StorageClass::kPrivate);
auto* lhs = Expr(1.f);
auto* rhs = Expr("mat");
auto* expr =
create<ast::BinaryExpression>(ast::BinaryOp::kMultiply, lhs, rhs);
WrapInFunction(expr);
GeneratorImpl& gen = Build();
std::stringstream out;
EXPECT_TRUE(gen.EmitExpression(out, expr)) << gen.error();
EXPECT_EQ(out.str(), "(1.0f * mat)");
}
TEST_F(HlslGeneratorImplTest_Binary, Multiply_MatrixVector) {
Global("mat", ty.mat3x3<f32>(), ast::StorageClass::kPrivate);
auto* lhs = Expr("mat");
auto* rhs = vec3<f32>(1.f, 1.f, 1.f);
auto* expr =
create<ast::BinaryExpression>(ast::BinaryOp::kMultiply, lhs, rhs);
WrapInFunction(expr);
GeneratorImpl& gen = Build();
std::stringstream out;
EXPECT_TRUE(gen.EmitExpression(out, expr)) << gen.error();
EXPECT_EQ(out.str(), "mul(float3(1.0f, 1.0f, 1.0f), mat)");
}
TEST_F(HlslGeneratorImplTest_Binary, Multiply_VectorMatrix) {
Global("mat", ty.mat3x3<f32>(), ast::StorageClass::kPrivate);
auto* lhs = vec3<f32>(1.f, 1.f, 1.f);
auto* rhs = Expr("mat");
auto* expr =
create<ast::BinaryExpression>(ast::BinaryOp::kMultiply, lhs, rhs);
WrapInFunction(expr);
GeneratorImpl& gen = Build();
std::stringstream out;
EXPECT_TRUE(gen.EmitExpression(out, expr)) << gen.error();
EXPECT_EQ(out.str(), "mul(mat, float3(1.0f, 1.0f, 1.0f))");
}
TEST_F(HlslGeneratorImplTest_Binary, Multiply_MatrixMatrix) {
Global("lhs", ty.mat3x3<f32>(), ast::StorageClass::kPrivate);
Global("rhs", ty.mat3x3<f32>(), ast::StorageClass::kPrivate);
auto* expr = create<ast::BinaryExpression>(ast::BinaryOp::kMultiply,
Expr("lhs"), Expr("rhs"));
WrapInFunction(expr);
GeneratorImpl& gen = Build();
std::stringstream out;
EXPECT_TRUE(gen.EmitExpression(out, expr)) << gen.error();
EXPECT_EQ(out.str(), "mul(rhs, lhs)");
}
TEST_F(HlslGeneratorImplTest_Binary, Logical_And) {
Global("a", ty.bool_(), ast::StorageClass::kPrivate);
Global("b", ty.bool_(), ast::StorageClass::kPrivate);
auto* expr = create<ast::BinaryExpression>(ast::BinaryOp::kLogicalAnd,
Expr("a"), Expr("b"));
WrapInFunction(expr);
GeneratorImpl& gen = Build();
std::stringstream out;
ASSERT_TRUE(gen.EmitExpression(out, expr)) << gen.error();
EXPECT_EQ(out.str(), "(tint_tmp)");
EXPECT_EQ(gen.result(), R"(bool tint_tmp = a;
if (tint_tmp) {
tint_tmp = b;
}
)");
}
TEST_F(HlslGeneratorImplTest_Binary, Logical_Multi) {
// (a && b) || (c || d)
Global("a", ty.bool_(), ast::StorageClass::kPrivate);
Global("b", ty.bool_(), ast::StorageClass::kPrivate);
Global("c", ty.bool_(), ast::StorageClass::kPrivate);
Global("d", ty.bool_(), ast::StorageClass::kPrivate);
auto* expr = create<ast::BinaryExpression>(
ast::BinaryOp::kLogicalOr,
create<ast::BinaryExpression>(ast::BinaryOp::kLogicalAnd, Expr("a"),
Expr("b")),
create<ast::BinaryExpression>(ast::BinaryOp::kLogicalOr, Expr("c"),
Expr("d")));
WrapInFunction(expr);
GeneratorImpl& gen = Build();
std::stringstream out;
ASSERT_TRUE(gen.EmitExpression(out, expr)) << gen.error();
EXPECT_EQ(out.str(), "(tint_tmp)");
EXPECT_EQ(gen.result(), R"(bool tint_tmp_1 = a;
if (tint_tmp_1) {
tint_tmp_1 = b;
}
bool tint_tmp = (tint_tmp_1);
if (!tint_tmp) {
bool tint_tmp_2 = c;
if (!tint_tmp_2) {
tint_tmp_2 = d;
}
tint_tmp = (tint_tmp_2);
}
)");
}
TEST_F(HlslGeneratorImplTest_Binary, Logical_Or) {
Global("a", ty.bool_(), ast::StorageClass::kPrivate);
Global("b", ty.bool_(), ast::StorageClass::kPrivate);
auto* expr = create<ast::BinaryExpression>(ast::BinaryOp::kLogicalOr,
Expr("a"), Expr("b"));
WrapInFunction(expr);
GeneratorImpl& gen = Build();
std::stringstream out;
ASSERT_TRUE(gen.EmitExpression(out, expr)) << gen.error();
EXPECT_EQ(out.str(), "(tint_tmp)");
EXPECT_EQ(gen.result(), R"(bool tint_tmp = a;
if (!tint_tmp) {
tint_tmp = b;
}
)");
}
TEST_F(HlslGeneratorImplTest_Binary, If_WithLogical) {
// if (a && b) {
// return 1;
// } else if (b || c) {
// return 2;
// } else {
// return 3;
// }
Global("a", ty.bool_(), ast::StorageClass::kPrivate);
Global("b", ty.bool_(), ast::StorageClass::kPrivate);
Global("c", ty.bool_(), ast::StorageClass::kPrivate);
auto* expr = If(create<ast::BinaryExpression>(ast::BinaryOp::kLogicalAnd,
Expr("a"), Expr("b")),
Block(Return(1)),
Else(create<ast::BinaryExpression>(ast::BinaryOp::kLogicalOr,
Expr("b"), Expr("c")),
Block(Return(2))),
Else(Block(Return(3))));
Func("func", {}, ty.i32(), {WrapInStatement(expr)});
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.EmitStatement(expr)) << gen.error();
EXPECT_EQ(gen.result(), R"(bool tint_tmp = a;
if (tint_tmp) {
tint_tmp = b;
}
if ((tint_tmp)) {
return 1;
} else {
bool tint_tmp_1 = b;
if (!tint_tmp_1) {
tint_tmp_1 = c;
}
if ((tint_tmp_1)) {
return 2;
} else {
return 3;
}
}
)");
}
TEST_F(HlslGeneratorImplTest_Binary, Return_WithLogical) {
// return (a && b) || c;
Global("a", ty.bool_(), ast::StorageClass::kPrivate);
Global("b", ty.bool_(), ast::StorageClass::kPrivate);
Global("c", ty.bool_(), ast::StorageClass::kPrivate);
auto* expr = Return(create<ast::BinaryExpression>(
ast::BinaryOp::kLogicalOr,
create<ast::BinaryExpression>(ast::BinaryOp::kLogicalAnd, Expr("a"),
Expr("b")),
Expr("c")));
Func("func", {}, ty.bool_(), {WrapInStatement(expr)});
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.EmitStatement(expr)) << gen.error();
EXPECT_EQ(gen.result(), R"(bool tint_tmp_1 = a;
if (tint_tmp_1) {
tint_tmp_1 = b;
}
bool tint_tmp = (tint_tmp_1);
if (!tint_tmp) {
tint_tmp = c;
}
return (tint_tmp);
)");
}
TEST_F(HlslGeneratorImplTest_Binary, Assign_WithLogical) {
// a = (b || c) && d;
Global("a", ty.bool_(), ast::StorageClass::kPrivate);
Global("b", ty.bool_(), ast::StorageClass::kPrivate);
Global("c", ty.bool_(), ast::StorageClass::kPrivate);
Global("d", ty.bool_(), ast::StorageClass::kPrivate);
auto* expr = Assign(
Expr("a"), create<ast::BinaryExpression>(
ast::BinaryOp::kLogicalAnd,
create<ast::BinaryExpression>(ast::BinaryOp::kLogicalOr,
Expr("b"), Expr("c")),
Expr("d")));
WrapInFunction(expr);
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.EmitStatement(expr)) << gen.error();
EXPECT_EQ(gen.result(), R"(bool tint_tmp_1 = b;
if (!tint_tmp_1) {
tint_tmp_1 = c;
}
bool tint_tmp = (tint_tmp_1);
if (tint_tmp) {
tint_tmp = d;
}
a = (tint_tmp);
)");
}
TEST_F(HlslGeneratorImplTest_Binary, Decl_WithLogical) {
// var a : bool = (b && c) || d;
Global("b", ty.bool_(), ast::StorageClass::kPrivate);
Global("c", ty.bool_(), ast::StorageClass::kPrivate);
Global("d", ty.bool_(), ast::StorageClass::kPrivate);
auto* var = Var("a", ty.bool_(), ast::StorageClass::kNone,
create<ast::BinaryExpression>(
ast::BinaryOp::kLogicalOr,
create<ast::BinaryExpression>(ast::BinaryOp::kLogicalAnd,
Expr("b"), Expr("c")),
Expr("d")));
auto* decl = Decl(var);
WrapInFunction(decl);
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.EmitStatement(decl)) << gen.error();
EXPECT_EQ(gen.result(), R"(bool tint_tmp_1 = b;
if (tint_tmp_1) {
tint_tmp_1 = c;
}
bool tint_tmp = (tint_tmp_1);
if (!tint_tmp) {
tint_tmp = d;
}
bool a = (tint_tmp);
)");
}
TEST_F(HlslGeneratorImplTest_Binary, Call_WithLogical) {
// foo(a && b, c || d, (a || c) && (b || d))
Func("foo",
{
Param(Sym(), ty.bool_()),
Param(Sym(), ty.bool_()),
Param(Sym(), ty.bool_()),
},
ty.void_(), ast::StatementList{}, ast::AttributeList{});
Global("a", ty.bool_(), ast::StorageClass::kPrivate);
Global("b", ty.bool_(), ast::StorageClass::kPrivate);
Global("c", ty.bool_(), ast::StorageClass::kPrivate);
Global("d", ty.bool_(), ast::StorageClass::kPrivate);
ast::ExpressionList params;
params.push_back(create<ast::BinaryExpression>(ast::BinaryOp::kLogicalAnd,
Expr("a"), Expr("b")));
params.push_back(create<ast::BinaryExpression>(ast::BinaryOp::kLogicalOr,
Expr("c"), Expr("d")));
params.push_back(create<ast::BinaryExpression>(
ast::BinaryOp::kLogicalAnd,
create<ast::BinaryExpression>(ast::BinaryOp::kLogicalOr, Expr("a"),
Expr("c")),
create<ast::BinaryExpression>(ast::BinaryOp::kLogicalOr, Expr("b"),
Expr("d"))));
auto* expr = CallStmt(Call("foo", params));
WrapInFunction(expr);
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.EmitStatement(expr)) << gen.error();
EXPECT_EQ(gen.result(), R"(bool tint_tmp = a;
if (tint_tmp) {
tint_tmp = b;
}
bool tint_tmp_1 = c;
if (!tint_tmp_1) {
tint_tmp_1 = d;
}
bool tint_tmp_3 = a;
if (!tint_tmp_3) {
tint_tmp_3 = c;
}
bool tint_tmp_2 = (tint_tmp_3);
if (tint_tmp_2) {
bool tint_tmp_4 = b;
if (!tint_tmp_4) {
tint_tmp_4 = d;
}
tint_tmp_2 = (tint_tmp_4);
}
foo((tint_tmp), (tint_tmp_1), (tint_tmp_2));
)");
}
namespace HlslGeneratorDivMod {
struct Params {
enum class Type { Div, Mod };
Type type;
};
struct HlslGeneratorDivModTest : TestParamHelper<Params> {
std::string Token() {
return GetParam().type == Params::Type::Div ? "/" : "%";
}
template <typename... Args>
auto Op(Args... args) {
return GetParam().type == Params::Type::Div
? Div(std::forward<Args>(args)...)
: Mod(std::forward<Args>(args)...);
}
};
INSTANTIATE_TEST_SUITE_P(HlslGeneratorImplTest,
HlslGeneratorDivModTest,
testing::Values(Params{Params::Type::Div},
Params{Params::Type::Mod}));
TEST_P(HlslGeneratorDivModTest, DivOrModByLiteralZero_i32) {
Func("fn", {}, ty.void_(),
{
Decl(Var("a", ty.i32())),
Decl(Const("r", nullptr, Op("a", 0))),
});
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.Generate());
EXPECT_EQ(gen.result(), R"(void fn() {
int a = 0;
const int r = (a )" + Token() +
R"( 1);
}
)");
}
TEST_P(HlslGeneratorDivModTest, DivOrModByLiteralZero_u32) {
Func("fn", {}, ty.void_(),
{
Decl(Var("a", ty.u32())),
Decl(Const("r", nullptr, Op("a", 0u))),
});
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.Generate());
EXPECT_EQ(gen.result(), R"(void fn() {
uint a = 0u;
const uint r = (a )" + Token() +
R"( 1u);
}
)");
} // namespace HlslGeneratorDivMod
TEST_P(HlslGeneratorDivModTest, DivOrModByLiteralZero_vec_by_vec_i32) {
Func("fn", {}, ty.void_(),
{
Decl(Var("a", nullptr, vec4<i32>(100, 100, 100, 100))),
Decl(Const("r", nullptr, Op("a", vec4<i32>(50, 0, 25, 0)))),
});
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.Generate());
EXPECT_EQ(gen.result(), R"(void fn() {
int4 a = int4(100, 100, 100, 100);
const int4 r = (a )" + Token() +
R"( int4(50, 1, 25, 1));
}
)");
} // namespace
TEST_P(HlslGeneratorDivModTest, DivOrModByLiteralZero_vec_by_scalar_i32) {
Func("fn", {}, ty.void_(),
{
Decl(Var("a", nullptr, vec4<i32>(100, 100, 100, 100))),
Decl(Const("r", nullptr, Op("a", 0))),
});
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.Generate());
EXPECT_EQ(gen.result(), R"(void fn() {
int4 a = int4(100, 100, 100, 100);
const int4 r = (a )" + Token() +
R"( 1);
}
)");
} // namespace hlsl
TEST_P(HlslGeneratorDivModTest, DivOrModByIdentifier_i32) {
Func("fn", {Param("b", ty.i32())}, ty.void_(),
{
Decl(Var("a", ty.i32())),
Decl(Const("r", nullptr, Op("a", "b"))),
});
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.Generate());
EXPECT_EQ(gen.result(), R"(void fn(int b) {
int a = 0;
const int r = (a )" + Token() +
R"( (b == 0 ? 1 : b));
}
)");
} // namespace writer
TEST_P(HlslGeneratorDivModTest, DivOrModByIdentifier_u32) {
Func("fn", {Param("b", ty.u32())}, ty.void_(),
{
Decl(Var("a", ty.u32())),
Decl(Const("r", nullptr, Op("a", "b"))),
});
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.Generate());
EXPECT_EQ(gen.result(), R"(void fn(uint b) {
uint a = 0u;
const uint r = (a )" + Token() +
R"( (b == 0u ? 1u : b));
}
)");
} // namespace tint
TEST_P(HlslGeneratorDivModTest, DivOrModByIdentifier_vec_by_vec_i32) {
Func("fn", {Param("b", ty.vec3<i32>())}, ty.void_(),
{
Decl(Var("a", ty.vec3<i32>())),
Decl(Const("r", nullptr, Op("a", "b"))),
});
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.Generate());
EXPECT_EQ(gen.result(), R"(void fn(int3 b) {
int3 a = int3(0, 0, 0);
const int3 r = (a )" + Token() +
R"( (b == int3(0, 0, 0) ? int3(1, 1, 1) : b));
}
)");
}
TEST_P(HlslGeneratorDivModTest, DivOrModByIdentifier_vec_by_scalar_i32) {
Func("fn", {Param("b", ty.i32())}, ty.void_(),
{
Decl(Var("a", ty.vec3<i32>())),
Decl(Const("r", nullptr, Op("a", "b"))),
});
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.Generate());
EXPECT_EQ(gen.result(), R"(void fn(int b) {
int3 a = int3(0, 0, 0);
const int3 r = (a )" + Token() +
R"( (b == 0 ? 1 : b));
}
)");
}
TEST_P(HlslGeneratorDivModTest, DivOrModByExpression_i32) {
Func("zero", {}, ty.i32(),
{
Return(Expr(0)),
});
Func("fn", {}, ty.void_(),
{
Decl(Var("a", ty.i32())),
Decl(Const("r", nullptr, Op("a", Call("zero")))),
});
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.Generate());
EXPECT_EQ(gen.result(), R"(int value_or_one_if_zero_int(int value) {
return value == 0 ? 1 : value;
}
int zero() {
return 0;
}
void fn() {
int a = 0;
const int r = (a )" + Token() +
R"( value_or_one_if_zero_int(zero()));
}
)");
}
TEST_P(HlslGeneratorDivModTest, DivOrModByExpression_u32) {
Func("zero", {}, ty.u32(),
{
Return(Expr(0u)),
});
Func("fn", {}, ty.void_(),
{
Decl(Var("a", ty.u32())),
Decl(Const("r", nullptr, Op("a", Call("zero")))),
});
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.Generate());
EXPECT_EQ(gen.result(), R"(uint value_or_one_if_zero_uint(uint value) {
return value == 0u ? 1u : value;
}
uint zero() {
return 0u;
}
void fn() {
uint a = 0u;
const uint r = (a )" + Token() +
R"( value_or_one_if_zero_uint(zero()));
}
)");
}
TEST_P(HlslGeneratorDivModTest, DivOrModByExpression_vec_by_vec_i32) {
Func("zero", {}, ty.vec3<i32>(),
{
Return(vec3<i32>(0, 0, 0)),
});
Func("fn", {}, ty.void_(),
{
Decl(Var("a", ty.vec3<i32>())),
Decl(Const("r", nullptr, Op("a", Call("zero")))),
});
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.Generate());
EXPECT_EQ(gen.result(), R"(int3 value_or_one_if_zero_int3(int3 value) {
return value == int3(0, 0, 0) ? int3(1, 1, 1) : value;
}
int3 zero() {
return int3(0, 0, 0);
}
void fn() {
int3 a = int3(0, 0, 0);
const int3 r = (a )" + Token() +
R"( value_or_one_if_zero_int3(zero()));
}
)");
}
TEST_P(HlslGeneratorDivModTest, DivOrModByExpression_vec_by_scalar_i32) {
Func("zero", {}, ty.i32(),
{
Return(0),
});
Func("fn", {}, ty.void_(),
{
Decl(Var("a", ty.vec3<i32>())),
Decl(Const("r", nullptr, Op("a", Call("zero")))),
});
GeneratorImpl& gen = Build();
ASSERT_TRUE(gen.Generate());
EXPECT_EQ(gen.result(), R"(int value_or_one_if_zero_int(int value) {
return value == 0 ? 1 : value;
}
int zero() {
return 0;
}
void fn() {
int3 a = int3(0, 0, 0);
const int3 r = (a )" + Token() +
R"( value_or_one_if_zero_int(zero()));
}
)");
}
} // namespace HlslGeneratorDivMod
} // namespace
} // namespace tint::writer::hlsl
|
#include "stdafx.h"
#include "PlayerScenePart.h"
#include "PlayerObject.h"
PlayerScenePart::PlayerScenePart() : ScenePart()
{
AddObject(PlayerObject());
}
|
/************************************************************
*
* OPEN TRANSACTIONS
*
* Financial Cryptography and Digital Cash
* Library, Protocol, API, Server, CLI, GUI
*
* -- Anonymous Numbered Accounts.
* -- Untraceable Digital Cash.
* -- Triple-Signed Receipts.
* -- Cheques, Vouchers, Transfers, Inboxes.
* -- Basket Currencies, Markets, Payment Plans.
* -- Signed, XML, Ricardian-style Contracts.
* -- Scripted smart contracts.
*
* EMAIL:
* fellowtraveler@opentransactions.org
*
* WEBSITE:
* http://www.opentransactions.org/
*
* -----------------------------------------------------
*
* LICENSE:
* This Source Code Form is subject to the terms of the
* Mozilla Public License, v. 2.0. If a copy of the MPL
* was not distributed with this file, You can obtain one
* at http://mozilla.org/MPL/2.0/.
*
* DISCLAIMER:
* 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 Mozilla Public License
* for more details.
*
************************************************************/
#include "ot_utility_ot.hpp"
#include <opentxs/client/ot_otapi_ot.hpp>
#include <opentxs/core/Log.hpp>
#include <locale>
namespace opentxs
{
using namespace std;
OT_UTILITY_OT bool VerifyExists(const string& theObjectNameAsStr,
bool bDisplayError)
{
if (OT_ME::FindVariable2(theObjectNameAsStr) == nullptr) {
if (bDisplayError) {
otOut << "Missing parameter: --";
locale loc;
for (auto elem : theObjectNameAsStr) {
otOut << tolower(elem, loc);
}
otOut << "\n";
}
return false;
}
return true;
}
//// ---------------------------------------
// OT_UTILITY_OT bool VerifyOTIntegerRef(nValue) // used for OTInteger
//{
// if (nValue.is_var_null() || nValue.is_var_undef() ||
// !nValue.is_type("OTInteger"))
// {
// return false;
// }
// else { return true; }
//}
//
//// ---------------------------------------
// OT_UTILITY_OT bool VerifyOTBoolRef(bValue) // used for OTBool class
//{
// if (bValue.is_var_null() || bValue.is_var_undef() ||
// !bValue.is_type("OTBool"))
// {
// return false;
// }
// else { return true; }
//}
//// ---------------------------------------
OT_UTILITY_OT bool VerifyMessage(const string& strMessage)
{
if (10 > strMessage.length()) {
otWarn << "VerifyMessage: Error strMessage is: Too Short:" << strMessage
<< "\n";
return false;
}
return true;
}
OT_UTILITY_OT int32_t VerifyMessageSuccess(const string& strMessage)
{
if (!VerifyMessage(strMessage)) {
return -1;
}
int32_t nStatus = OTAPI_Wrap::Message_GetSuccess(strMessage);
switch (nStatus) {
case -1:
otOut << "VerifyMessageSuccess: Error calling "
"OT_API_Message_GetSuccess, for message:\n\n" << strMessage
<< "\n";
break;
case 0:
otWarn << "VerifyMessageSuccess: Reply received: success == FALSE. "
"Reply message:\n\n" << strMessage << "\n";
break;
case 1:
otWarn << "VerifyMessageSuccess: Reply received: success == TRUE.\n";
break;
default:
otOut << "VerifyMessageSuccess: Error. (This should never happen!) "
"nStatus: " << nStatus << ", Input: " << strMessage << "\n";
nStatus = -1;
break;
}
return nStatus;
}
OT_UTILITY_OT int32_t VerifyMsgBalanceAgrmntSuccess(
const string& NOTARY_ID, const string& NYM_ID, const string& ACCOUNT_ID,
const string& strMessage) // For when an OTMessage is the input.
{
if (!VerifyMessage(strMessage)) {
return -1;
}
int32_t nSuccess = OTAPI_Wrap::Message_GetBalanceAgreementSuccess(
NOTARY_ID, NYM_ID, ACCOUNT_ID, strMessage);
switch (nSuccess) {
case -1:
otOut << "VerifyMsgBalanceAgrmntSuccess: Error calling "
"OT_API_Msg_GetBlnceAgrmntSuccess, for message:\n\n"
<< strMessage << "\n";
break;
case 0:
otWarn << "VerifyMsgBalanceAgrmntSuccess: Reply received: success == "
"FALSE. Reply message:\n\n" << strMessage << "\n";
break;
case 1:
otWarn << "VerifyMsgBalanceAgrmntSuccess: Reply received: success == "
"TRUE.\n";
break;
default:
otOut << "VerifyMsgBalanceAgrmntSuccess: Error. (This should never "
"happen!) Input: " << strMessage << "\n";
nSuccess = -1;
break;
}
return nSuccess;
}
OT_UTILITY_OT int32_t
VerifyMsgTrnxSuccess(const string& NOTARY_ID, const string& NYM_ID,
const string& ACCOUNT_ID, const string& strMessage)
{
if (!VerifyMessage(strMessage)) {
return -1;
}
int32_t nSuccess = OTAPI_Wrap::Message_GetTransactionSuccess(
NOTARY_ID, NYM_ID, ACCOUNT_ID, strMessage);
switch (nSuccess) {
case -1:
otOut << "VerifyMsgTrnxSuccess: Error calling "
"OT_API_Message_GetSuccess, for message:\n\n" << strMessage
<< "\n";
break;
case 0:
otWarn << "VerifyMsgTrnxSuccess: Reply received: success == FALSE. "
"Reply message:\n\n" << strMessage << "\n";
break;
case 1:
otWarn << "VerifyMsgTrnxSuccess: Reply received: success == TRUE.\n";
break;
default:
otOut << "VerifyMsgTrnxSuccess: Error. (This should never happen!) "
"Input: " << strMessage << "\n";
nSuccess = -1;
break;
}
return nSuccess;
}
//
// This code was repeating a lot, so I just added a function for it.
//
OT_UTILITY_OT int32_t InterpretTransactionMsgReply(const string& NOTARY_ID,
const string& NYM_ID,
const string& ACCOUNT_ID,
const string& strAttempt,
const string& strResponse)
{
int32_t nMessageSuccess = VerifyMessageSuccess(strResponse);
if (-1 == nMessageSuccess) {
otOut << "Message error: " << strAttempt << ".\n";
return -1;
}
if (0 == nMessageSuccess) {
otOut << "Server reply (" << strAttempt << "): Message failure.\n";
return 0;
}
int32_t nBalanceSuccess = VerifyMsgBalanceAgrmntSuccess(
NOTARY_ID, NYM_ID, ACCOUNT_ID, strResponse);
if (-1 == nBalanceSuccess) {
otOut << "Balance agreement error: " << strAttempt << ".\n";
return -1;
}
if (0 == nBalanceSuccess) {
otOut << "Server reply (" << strAttempt
<< "): Balance agreement failure.\n";
return 0;
}
int32_t nTransSuccess =
VerifyMsgTrnxSuccess(NOTARY_ID, NYM_ID, ACCOUNT_ID, strResponse);
if (-1 == nTransSuccess) {
otOut << "Transaction error: " << strAttempt << ".\n";
return -1;
}
if (0 == nTransSuccess) {
otOut << "Server reply (" << strAttempt << "): Transaction failure.\n";
return 0;
}
return 1;
}
//// Provides the functionality of the ? : operator.
//// NOTE: the chai team have since added ? :, so this is deprecated now.
//
// OT_UTILITY_OT int32_t ifB(the_expression, X, Y)
//{
// var theReturnValue
//
// if (the_expression)
// {
// theReturnValue = X;
// }
// else
// {
// theReturnValue = Y;
// }
//
// // Returning...
// //
//
// return theReturnValue;
//
//}
////
///********************************************************************************
//
// attr OTBool::value
// attr OTBool::value2
//
//// ----------------------------
// OT_UTILITY_OT int32_t OTBool::OTBool()
//{
// value = false;
// value2 = false;
//}
//// ----------------------------
// OT_UTILITY_OT int32_t OTBool::OTBool(param_value)
//{
// value = param_value;
// value2 = false;
//}
//// ----------------------------
// OT_UTILITY_OT int32_t OTBool::getBooleanValue()
//{
//
// return value;
//
//}
//// ----------------------------
// OT_UTILITY_OT int32_t OTBool::setBooleanValue(param_value)
//{
// value = param_value;
//}
//// ----------------------------
// OT_UTILITY_OT int32_t OTBool::getSecondValue()
//{
//
// return value2;
//
//}
//// ----------------------------
// OT_UTILITY_OT int32_t OTBool::setSecondValue(param_value)
//{
// value2 = param_value;
//}
//
////
///********************************************************************************
//
// attr OTInteger::value
//
//// ----------------------------
// OT_UTILITY_OT int32_t OTInteger::OTInteger()
//{
// value = 0;
//}
//// ----------------------------
// OT_UTILITY_OT int32_t OTInteger::OTInteger(param_value)
//{
// value = param_value;
//}
//// ----------------------------
// OT_UTILITY_OT int32_t OTInteger::getIntegerValue()
//{
// // Returning...
// //
//
// return value;
//
//}
//// ----------------------------
// OT_UTILITY_OT int32_t OTInteger::setIntegerValue(param_value)
//{
// value = param_value;
//}
////
///********************************************************************************
Utility::Utility()
{
strLastReplyReceived = "";
delay_ms = 50;
max_trans_dl = 10; // Number of transactions I download when I'm low. (Also,
// when I'm low is when I'm below this number.)
}
Utility::~Utility()
{
}
OT_UTILITY_OT void Utility::delay() const
{
OTAPI_Wrap::Sleep(delay_ms);
}
OT_UTILITY_OT void Utility::longDelay() const
{
OTAPI_Wrap::Sleep(delay_ms + 200);
}
OT_UTILITY_OT int32_t Utility::getNbrTransactionCount() const
{
return max_trans_dl;
}
OT_UTILITY_OT void Utility::setNbrTransactionCount(int32_t new_trans_dl)
{
max_trans_dl = new_trans_dl;
}
OT_UTILITY_OT string Utility::getLastReplyReceived() const
{
return strLastReplyReceived;
}
OT_UTILITY_OT void Utility::setLastReplyReceived(const string& strReply)
{
strLastReplyReceived = strReply;
}
OT_UTILITY_OT int32_t
Utility::getNymboxLowLevel(const string& notaryID, const string& nymID)
{
bool bWasSent = false;
return getNymboxLowLevel(notaryID, nymID, bWasSent);
}
// This returns -1 if error, or a positive request number if it was sent.
// (It cannot return 0;
// Called by getAndProcessNymbox.
//
OT_UTILITY_OT int32_t Utility::getNymboxLowLevel(const string& notaryID,
const string& nymID,
bool& bWasSent)
{
string strLocation = "Utility::getNymboxLowLevel";
OTAPI_Wrap::FlushMessageBuffer();
bWasSent = false;
int32_t nRequestNum = OTAPI_Wrap::getNymbox(
notaryID, nymID); // <===== ATTEMPT TO SEND THE MESSAGE HERE...;
if (-1 == nRequestNum) {
otOut << strLocation
<< ": Failed to send getNymbox message due to error.\n";
return -1;
}
if (0 == nRequestNum) {
otOut << strLocation << ": Unexpectedly returned 0. Didn't send "
"getNymbox message, but NO error occurred, "
"either. (In this case, SHOULD NEVER HAPPEN. "
"Treating as Error.)\n";
return -1; // Even though '0' MEANS "didn't send, but no error" by
// convention in many places, it is actually an impossible
// return value;
}
if (nRequestNum < 0) {
otOut << strLocation << ": Unexpected request number: " << nRequestNum
<< "\n";
return -1;
}
bWasSent = true;
//
int32_t nResult =
receiveReplySuccessLowLevel(notaryID, nymID, nRequestNum, strLocation);
// otOut << strLocation << ": receiveReplySuccessLowLevel:
// " << nResult << "\n";
// BY this point, we definitely have the request number in nResult, which
// means
// the message was actually SENT. (At least.) This also means we can use
// nResult
// later to query for a copy of that sent message.
// Let's go ahead, in this case, and remove that now:
//
// THE REMOVE SENT MESSAGE BELOW FAILS, LIKE IT'S ALREADY GONE.
//
// THIS MUST BE DUE TO THE PROCESS SERVER REPLY THAT OCCURS **IMMEDIATELY**
// after the message was originally sent!
// (The reply came in and was sent to OT's "ProcessServerReply", INSIDE the
// call to getNymbox.)
// Our subsequent "receive" (above) is nothing of the sort, but actually
// pops the incoming message buffer where
// the server's reply was ALREADY SITTING, since it was put there in OT's
// "ProcessServerReply", WHICH REMOVED THE
// SENT MESSAGE ALREADY (that's why the below call to RemoveSentMessage
// fails.)
//
// RETHINK any logic that doesn't take this into account,.
// Either we REMOVE this call wherever this happens, OR... we call Get first
// and make sure whether it's
// there, THEN remove it. But we can't be lumping "Failure because it's
// gone" versus "Error state" by mixing
// 0 and -1 here. We need to differentiate.
//
// Bottom line: if the reply WAS received, then the original sent message
// has ALREADY been removed
// from the sent buffer. Whereas if the reply was NOT received, then the
// sent message is still there,
// but in that case, we do NOT want to remove it -- we want it to STAY in
// the sent buffer, so that
// when we get the Nymbox later and we DO have the reply from that, THEN we
// can remove the sent msg from
// the sent buffer. Until then, we don't want OT to think it's already been
// processed (which it will, if
// it's already been removed from the sent buffer. So we leave it there for
// now.)
//
// int32_t nRemovedSentMsg =
// OTAPI_Wrap::RemoveSentMessage(to_string(nRequestNum), notaryID, nymID);
//
// if (nRemovedSentMsg < 1)
// {
// otOut << strLocation << ": ERROR:
// OT_API_RemoveSentMessage returned: " << nRemovedSentMsg << "\n";
// }
if (1 == nResult) {
return nRequestNum;
}
return nResult;
}
OT_UTILITY_OT int32_t
Utility::getNymbox(const string& notaryID, const string& nymID)
{
bool bForceDownload = false;
return getNymbox(notaryID, nymID, bForceDownload);
}
OT_UTILITY_OT int32_t Utility::getNymbox(const string& notaryID,
const string& nymID,
bool bForceDownload)
{
string strLocation = "Utility::getNymbox";
string strRecentHash = OTAPI_Wrap::GetNym_RecentHash(notaryID, nymID);
bool bRecentHash = VerifyStringVal(strRecentHash);
if (!bRecentHash) {
otOut << strLocation << ": Warning: Unable to retrieve recent cached "
"copy of server-side NymboxHash from "
"client-side nym (perhaps he's never "
"downloaded it before?)\n\n";
}
string strLocalHash = OTAPI_Wrap::GetNym_NymboxHash(notaryID, nymID);
bool bLocalHash = VerifyStringVal(strLocalHash);
if (!bLocalHash) {
otOut << strLocation << ": Warning: Unable to retrieve client-side "
"NymboxHash for:\n notaryID: " << notaryID
<< "\n nymID: " << nymID << "\n";
}
if (!bForceDownload) {
if (bLocalHash && bRecentHash &&
(strRecentHash == strLocalHash)) // the hashes match -- no need to
// download anything.
{
otWarn
<< strLocation
<< ": The hashes already match (skipping Nymbox download.)\n";
return 1;
}
}
// -- SECTION 1: "GET NYMBOX"
//
bool bWasMsgSent = false;
int32_t nGetNymbox = getNymboxLowLevel(
notaryID, nymID, bWasMsgSent); // bWasMsgSent is output from this call.;
if (bWasMsgSent) {
otWarn << strLocation
<< ": FYI: we just sent a getNymboxLowLevel msg. RequestNum: "
<< nGetNymbox << "\n";
}
if (!(bWasMsgSent) || ((nGetNymbox <= 0) && (-1 != nGetNymbox))) {
otOut << strLocation
<< ": Failure: this.getNymboxLowLevel returned unexpected value: "
<< nGetNymbox << "\n";
return -1;
} // NOTE: for getNymbox, there is no '0' return value;
if (-1 ==
nGetNymbox) // we'll try re-syncing the request number, then try again.
{
otOut << strLocation
<< ": FYI: this.getNymboxLowLevel returned -1. (Re-trying...)\n";
int32_t nGetRequestNumber = getRequestNumber(notaryID, nymID);
if (1 != nGetRequestNumber) {
otOut << strLocation << ": Failure: this.getNymboxLowLevel failed, "
"then I tried to resync with "
"this.getRequestNumber and then that "
"failed too. (I give up.)\n";
return -1;
}
// todo: should the member variable strLastReplyReceived be set to this
// one?
// before, the member var was shadowed (string strLastReplyReceived =
// getLastReplyReceived();).
string lastReplyReceived = getLastReplyReceived();
// I had to do this bit because getRequestNumber doesn't return the
// reply itself. But in this case, I needed it.
if (!VerifyStringVal(lastReplyReceived)) // THIS SHOULD NEVER HAPPEN.
{
otOut << strLocation << ": ERROR in getLastReplyReceived(): why "
"was this string not set, when "
"this.getRequestNumber was otherwise an "
"apparent success?\n";
return -1; // (SHOULD NEVER HAPPEN. This string is set in the
// getRequestNumber function.)
}
// BY THIS POINT, we have received a server reply:
// getRequestNumberResponse
// (Unless it is malformed.) It's definitely not null, nor empty.
// Grab the NymboxHash on the getRequestNumberResponse reply, and also
// the one
// I
// already had on my client-side Nym... (So we can compare them.)
//
// If the hashes do NOT match, then I DO need to download nymbox
// and box receipts.
/*
* ===> If the NymboxHash is changed from what I expected, then I
*need to re-download the
* nymbox (and any box receipts I don't already have.)
*
* Then I need to process the Nymbox. But first, see if my missing
*server reply is in there.
* If it is, then I have the server reply! (As if we had succeeded
*in the first place!!)
* Next, process the Nymbox (which processes that reply) and then
*return strReply;
*
* (Clearly this is just going to be a normal part of the
*getRequestNumber
*syncronization.)
*
* By the time that much is done, I will KNOW the request number,
*the nymbox, the box receipts,
* etc are ALL syncronized properly, and that I THEN processed the
*Nymbox successfully.
*
*
* NOTICE: In this example I do NOT want to pull out my sent message
*from the outbuffer (using
* the request number) and try to harvest all the transaction
*numbers. Why not? Because possibly the
* server DID reply! And if I processed that reply properly, it
*would sync my transaction numbers
* properly just from that! ===>
*
* ===> Therefore, I need to see FIRST if the old message has a
*reply WAITING in the Nymbox. THEN
* I need to process the Nymbox. ONLY if the reply wasn't there, can
*I THEN pull out the message
* from my outbuffer and harvest it. (Which I am reticent to do,
*until I am SURE the server
* really never saw that message in the first place.)
*
* However, as long as my NymboxHash hasn't changed, then I'm safe!
*But if it HAS changed,
* then I HAVE to A. download it B. SEE if the reply is there for
*the request number, then
* C. process it. ... If the reply wasn't there, THEN Harvest the
*transaction #s (for transaction
* messages) and then re-try.
*/
// Grabbing again in case it's changed.
string strServerHash =
OTAPI_Wrap::Message_GetNymboxHash(lastReplyReceived);
bool bServerHash = VerifyStringVal(strServerHash);
if (!bServerHash) {
otOut << strLocation
<< ": Warning: Unable to retrieve server-side NymboxHash "
"from server getRequestNumberResponse reply:\n\n"
<< lastReplyReceived << "\n";
}
strLocalHash = OTAPI_Wrap::GetNym_NymboxHash(notaryID, nymID);
bLocalHash = VerifyStringVal(strLocalHash);
if (!bLocalHash) {
otOut << strLocation
<< ": Warning(2): Unable to retrieve client-side NymboxHash "
"for:\n notaryID: " << notaryID << "\n nymID: " << nymID
<< "\n";
}
// The hashes don't match -- so let's definitely re-try to download the
// latest nymbox.
if (bForceDownload || !bLocalHash || !bServerHash ||
(bServerHash && bLocalHash && !(strServerHash == strLocalHash))) {
// the getRequestNumber worked, and the server hashes don't match,
// so let's try the call again...
nGetNymbox = getNymboxLowLevel(notaryID, nymID, bWasMsgSent);
if (!(bWasMsgSent) || ((nGetNymbox <= 0) && (-1 != nGetNymbox))) {
otOut << strLocation
<< ": Failure(2): this.getNymboxLowLevel returned "
"unexpected value: " << nGetNymbox << "\n";
return -1;
}
if (-1 == nGetNymbox) // we'll try re-syncing the request number,
// then try again.
{
otOut << strLocation << ": Failure: this.getNymboxLowLevel "
"returned -1, even after syncing the "
"request number successfully. (Giving "
"up.)\n";
return -1;
}
}
}
// By this point, we DEFINITELY know that the Nymbox was retrieved
// successfully.
// (With request number nGetNymbox.) This is because the getNymboxLowLevel()
// call
// also tries to receive the reply, so we already know by now whether the
// reply
// was successfully received.
//
return nGetNymbox;
}
// NEW ONES:
// public static int32_t getAndProcessNymbox(String notaryID, String nymID,
// OTBool bWasMsgSent, boolean bForceDownload,
// var nRequestNumber, // nRequestNumber
// refers to a PREVIOUS msg (like a cash withdrawal) that had an error and then
// called this while trying to resync. (The caller will want to know whether it
// was found in the Nymbox.)
// OTBool bFoundNymboxItem, //
// bFoundNymboxItem is OUTPUT bool, telling caller whether it was found.
// boolean bHarvestingForRetry, //
// bHarvestingForRetry is INPUT, in the case nRequestNumber needs to be
// harvested before a flush occurs.
// boolean bMsgReplySuccess, //
// bMsgReplySuccess is INPUT, and is in case nRequestNumber needs to be
// HARVESTED before a FLUSH happens.
// boolean bMsgReplyFailure, //
// bMsgReplyFailure is INPUT, and is in case nRequestNumber needs to be
// HARVESTED before a FLUSH happens.
// boolean bMsgTransSuccess, //
// bMsgTransSuccess is INPUT, and is in case nRequestNumber needs to be
// HARVESTED before a FLUSH happens.
// boolean bMsgTransFailure) //
// bMsgTransFailure is INPUT, and is in case nRequestNumber needs to be
// HARVESTED before a FLUSH happens.
// def Utility::getAndProcessNymbox_8(notaryID, nymID, bWasMsgSent, //
// bWasMsgSent is OUTPUT.
// bForceDownload, // INPUT
// nRequestNumber, // nRequestNumber
// refers to a PREVIOUS msg (like a cash withdrawal) that had an error and then
// called this while trying to resync. (The caller will want to know whether it
// was found in the Nymbox.)
// bFoundNymboxItem, // bFoundNymboxItem
// is OUTPUT bool, telling caller whether it was found.
// bHarvestingForRetry, //
// bHarvestingForRetry is INPUT, in the case nRequestNumber needs to be
// harvested before a flush occurs.
// bMsgFoursome) // OTfourbool class, used to
// reduce the number of parameters here, which I am suspicious that ChaiScript
// cannot handle.
// Returns:
// -1 ERROR.
// 0 Nymbox was empty -- nothing done. (bWasMsgSent = false)
// 0 Transactionstatus = = server reply received (bWasMsgSent = true), but;
// the server reply hasstatus = = FAILED. (All harvesting was subsequently
// successful for processNymbox).;
// 1 If the ProcessNymbox Transaction status (from the server reply) is
// SUCCESS,
// then this function returns 1.
// >1 If the ProcessNymbox Transaction status (from the server reply) is >1,
// then this function returns the
// REQUEST NUMBER from when it was originally sent. (Harvesting was NOT
// performed, which is why the request
// number is being returned, so the caller can choose what to do next.)
// def Utility::getAndProcessNymbox_8(notaryID, nymID, bWasMsgSent,
// bForceDownload, nRequestNumber, bFoundNymboxItem, bHarvestingForRetry,
// bMsgFoursome)
//{
// cout << "Here's the dead version!\n";
//}
// var nGetAndProcessNymbox = getAndProcessNymbox_8(notaryID, nymID,
// bWasMsgSent, bForceDownload, nRequestNumber, bFoundNymboxItem,
// bHarvestingForRetry, the_foursome);
OT_UTILITY_OT int32_t Utility::getAndProcessNymbox_8(
const string& notaryID, const string& nymID, bool& bWasMsgSent,
bool bForceDownload, int32_t nRequestNumber, bool& bFoundNymboxItem,
bool bHarvestingForRetry, const OTfourbool& bMsgFoursome)
{
string strLocation = "Utility::getAndProcessNymbox";
bool bMsgReplySuccess = bMsgFoursome[0];
bool bMsgReplyFailure = bMsgFoursome[1];
bool bMsgTransSuccess = bMsgFoursome[2];
bool bMsgTransFailure = bMsgFoursome[3];
if (0 > nRequestNumber) {
otOut << "\n\n\n\n Failed verifying nRequestNumber as an integer. "
"\n\n\n\n\n";
return -1;
}
if (1 == nRequestNumber) {
otOut << strLocation
<< ": WARNING: Request Num of '1' was just passed in here.\n";
}
bWasMsgSent = false;
// what is nRequestNumber?
//
// Let's say a message, say for a cash withdrawal with request number 5, has
// FAILED.
// Since the message failed, perhaps the request number was out of sync, or
// Nymbox hash
// was old? So, let's say that it then sent a getRequestNumber message, in
// order
// to resync,
// and discovered that the Nymbox hash has changed. Therefore the Nymbox is
// now being
// re-downloaded and processed, so that the cash withdrawal can be attempted
// again.
//
// HOWEVER, before we PROCESS the Nymbox, we need to see if the withdrawal
// reply is already
// sitting in it. Why, you ask, if the withdrawal failed, would I expect a
// reply to be in
// the Nymbox? In case 1, the message was dropped, so I don't know if the
// reply is there
// until I check the Nymbox. In case 2, the message may have failed OR
// SUCCEEDED, with the
// successful message containing a FAILED TRANSACTION.
// Thus, we just want to check the Nymbox for nRequestNumber, and make sure
// whether it's
// there or not, before we PROCESS the nymbox, because once we do THAT, it
// will be empty.
//
// We will return a;
// was already in the Nymbox. We can also harvest the transaction numbers
// from the reply
// message, if it's a transaction, so that everything is set for the re-try.
// (Possibly pass
// a bool parameter dictating whether the harvesting is being done for a
// re-try or not.)
//
// -- SECTION 1: "GET NYMBOX"
//
// This call is sufficiently high-level enough that it already has re-tries
// built into it. That's why you don't see me re-trying the getNymbox if it
// fails.
//
int32_t nGetNymbox = getNymbox(notaryID, nymID, bForceDownload);
if (nGetNymbox < 1) {
otOut << strLocation
<< ": Failure: this.getNymbox returned: " << nGetNymbox << "\n";
return -1;
}
// By this point, we DEFINITELY know that the Nymbox was retrieved
// successfully.
// (With request number nGetNymbox.) This is because the getNymboxLowLevel()
// call
// also tries to receive the reply, so we already know by now whether the
// reply
// was successfully received.
//
/*
* FYI: nRequestNumber is the request number, if >0, for whatever command
* is causing this getAndProcessNymbox to occur (like a cash withdrawal, or
* a cheque deposit, etc.) We pass it in here so we can verify whether it's
*on
* the Nymbox, before we process it out (so the caller knows whether to
*clawback.)
*
* FYI: nGetNymbox is the request number from getNymboxLowLevel() (above.) We
* know for a FACT, by this point, this number is >0.
*
* FYI: nProcess (just below) is the request number for the PROCESS NYMBOX
*message.
* Below the switch block just down there, we know for a fact this number is
*>0.
*/
// -- SECTION 2: "SEND PROCESS NYMBOX"
//
// Next, we have to make sure we have all the BOX RECEIPTS downloaded
// for this Nymbox.
// If the caller wanted to know whether a certain reply (by request number)
// was in the Nymbox, then bFoundNymboxItem
// will be set true in this call, if it was there. That way he can Harvest
// his own msg if he needs to. (Just like I
// harvest my own processNymbox call below, if necessary.)
//
// nBoxType = 0 aka nymbox;
//
int32_t nBoxType = 0;
bool bInsured = insureHaveAllBoxReceipts(
notaryID, nymID, nymID, nBoxType, nRequestNumber,
bFoundNymboxItem); // ***************************;
if (bInsured) {
// If the caller was on about a specific request number...
//
if (nRequestNumber > 0) {
// ...And if we DID NOT find that request number in the Nymbox
// (along with the server's reply), then harvest it!!
// (If we HAD found it, then we'd know it didn't NEED harvesting,
// since the server clearly REPLIED to it already.)
// FOUND it in the nymbox! Therefore we can remove without
// harvesting.
// (Server definitely processed it, so nothing to harvest.)
//
if (bFoundNymboxItem) {
// Notice, if the above call to insureHaveAllBoxReceipts had any
// network hiccups, then
// it may have had to get and processNymbox, meaning the below
// Remove would fail, since
// the sent message was already removed. Therefore, might want
// to update this to call getSent
// FIRST, before trying to remove.
// (Might want different messages in either case.)
//
bool nRemovedMsg = OTAPI_Wrap::RemoveSentMessage(
int64_t(nRequestNumber), notaryID, nymID);
otInfo << strLocation
<< ": OT_API_RemoveSentMessage: (Found server reply in "
"Nymbox. Removing local sent msg.) Request number: "
<< nRemovedMsg << "\n";
}
else // We DIDN'T find it in the nymbox, so we can harvest it:
{
// NOTE: This may always fail,
otLog3 << strLocation
<< ": FYI: Calling OT_API_GetSentMessage...\n";
string strSentMsg = OTAPI_Wrap::GetSentMessage(
int64_t(nRequestNumber), notaryID, nymID);
if (!VerifyStringVal(strSentMsg)) {
otInfo << strLocation
<< ": (1) OT_API_GetSentMessage returned nullptr "
"for clawback. (Must have already been cleared. "
"OT uses deliberate redundancy, though optimizes "
"this wherever possible.) Request number: "
<< nRequestNumber << "\n";
}
else // OTAPI_Wrap::GetSentMessage success.
{
otOut << strLocation << ": FYI: Harvesting transaction "
"numbers from failed Msg "
"attempt...\n";
bool nHarvested = OTAPI_Wrap::Msg_HarvestTransactionNumbers(
strSentMsg, nymID,
bHarvestingForRetry, // bHarvestingForRetry.
bMsgReplySuccess, // bReplyWasSuccess, // RECEIVED
// server reply: explicit success.
bMsgReplyFailure, // bReplyWasFailure, // RECEIVED
// server reply: explicit failure.
bMsgTransSuccess, // bTransactionWasSuccess, // MESSAGE
// success, Transaction success.
// (Explicit.)
bMsgTransFailure); // bTransactionWasFailure // MESSAGE
// success, Transaction failure.
// (Explicit.)
otOut << strLocation
<< ": OT_API_Msg_HarvestTransactionNumbers: "
<< nHarvested << "\n";
bool nRemovedMsg = OTAPI_Wrap::RemoveSentMessage(
int64_t(nRequestNumber), notaryID, nymID);
otInfo << strLocation
<< ": OT_API_RemoveSentMessage: " << nRemovedMsg
<< "\n";
} // strSentMsg NOT null!
}
}
// (flush): LOOP THROUGH ALL "SENT" messages, and see if ANY of them has
// a reply
// sitting in my Nymbox. If so, REMOVE IT from "Sent" queue, (since
// clearly the server
// DID respond already.) And if it's NOT in my nymbox, that means I
// DEFINITELY need to
// harvest it back since the server definitely rejected it or never
// received it.
//
// The Nym actually SAVES the sent messages PER SERVER, so that this
// will continue to work in every possible case!!
// NOTE: Also now storing, on the client nym, a copy of the server's
// latest nymbox hash
// for that nym, in addition to the nym's copy (which only updates when
// he gets his Nymbox.)
// That way the Nym, even before syncing the nymboxes, and even before
// sending a new message
// to find out if they are out of sync, ALREADY KNOWS if they're in sync
// or not. (That's why
// all those other server messages send a copy of that hash back, not
// just the getNymbox msg.)
//
//
// void OTAPI_Wrap::FlushSentMessages( int32_t //
// bHarvestingForRetry, // bHarvestingForRetry is actually OT_BOOL
// const char * NOTARY_ID,
// const char * NYM_ID,
// const char * THE_NYMBOX);
// NoVerify means don't load up all the box receipts.
// Especially in this case--we only care about whether a box receipt is
// THERE, not
// what it contains. FlushSentMessages will work just fine WITHOUT
// loading those
// box receipts (because the Nymbox contains enough of an abbreviated
// record already
// for each one, that we will have the info we need already.)
//
string strNymbox = OTAPI_Wrap::LoadNymboxNoVerify(
notaryID, nymID); // FLUSH SENT MESSAGES!!!! (AND HARVEST.);
if (VerifyStringVal(strNymbox)) {
OTAPI_Wrap::FlushSentMessages(
false, // harvesting for retry = = OT_FALSE. None of the things
// are being re-tried by the time they are being flushed.
// They were already old news.;
notaryID, nymID, strNymbox);
}
// Flushing removes all the messages from the "sent messages" queue,
// and harvests any transaction numbers to be had. How do I know for
// sure
// that I can get away with this? How do I know whether the server has
// processed those messages or not? How can I harvest them as though
// they
// were dropped on the network somewhere? The answer is because I JUST
// called GetNymbox and downloaded the latest one. I can SEE which
// replies
// are in there -- and which ones aren't. I pass that Nymbox into the
// flush
// call, so that flush can be careful to remove all sent messages that
// have
// nymbox replies, and only harvest the others.
else {
otOut << strLocation
<< ": Error while trying to flush sent messages: Failed "
"loading Nymbox for nym: " << nymID << "\n";
}
int32_t nMsgSentRequestNumOut = -1;
int32_t nReplySuccessOut = -1;
int32_t nBalanceSuccessOut = -1;
int32_t nTransSuccessOut = -1;
// PROCESS NYMBOX
//
// Returns:
// -1 Error.
// 0 Nymbox was empty -- nothing done. (bWasMsgSent = false)
// 0 Transactionstatus = = server reply received (bWasMsgSent = true),;
// but the server reply saysstatus = =failed.;
// >0 If the Transaction status (from the server reply) is SUCCESS, then
// this function
// returns the REQUEST NUMBER from when it was originally sent.
int32_t nProcess = processNymbox(
notaryID, nymID, bWasMsgSent, nMsgSentRequestNumOut,
nReplySuccessOut, nBalanceSuccessOut, nTransSuccessOut);
if (-1 == nProcess) {
// Todo: might want to remove the sent message here, IF bMsgWasSent
// is true.
// (Just like case 0.)
//
otOut << strLocation << ": Failure: processNymbox: error (-1). (It "
"couldn't send. I give up.)\n";
return -1; // (It didn't even send.)
}
else if (0 == nProcess) {
// Nymbox was empty. (So we didn't send any process message because
// there was nothing to process.)
if (!bWasMsgSent) {
return 0; // success. done. (box was empty already.)
}
// else: the message WAS sent, (the Nymbox was NOT empty)
// and then the server replied "success==FALSE"
// in its REPLY to that message! Thus we continue and DROP
// THROUGH...
}
else if (nProcess < 0) {
otOut << strLocation
<< ": Failure: processNymbox: unexpected: " << nProcess
<< ". (I give up.)\n";
return -1;
}
// bWasMsgSent = true; // unnecessary -- set already by processNymbox
// call above.
// By this point, we definitely have a >0 request number from the
// sendProcessNymbox()
// call, stored in nProcess (meaning the message WAS sent.) (Except in
// case of 0, see next line which fixes this:)
//
nProcess = nMsgSentRequestNumOut; // Sometimes this could be 0 still, so
// we fix it here.;
int32_t nReplySuccess = nReplySuccessOut;
int32_t nTransSuccess = nTransSuccessOut;
int32_t nBalanceSuccess = nBalanceSuccessOut;
/*
return const;
char * OTAPI_Wrap::GetSentMessage(const char* REQUEST_NUMBER)
OT_BOOL OTAPI_Wrap::RemoveSentMessage(const char* REQUEST_NUMBER)
*/
// All of these booleans (except "error") represent RECEIVED ANSWERS
// from the server.
// In other words, "false" does not mean "failed to find message."
// Rather, it means "DEFINITELY got a reply, and that reply sayssuccess
// = =false.";
// SHOULD NEVER HAPPEN (processNymbox call just above was successful,
// therefore the sent message SHOULD be here in my cache.)
//
string strReplyProcess = getLastReplyReceived();
// I had to do this bit because getRequestNumber doesn't return the;
// reply itself. But in this case, I needed it.
if (!VerifyStringVal(strReplyProcess)) // THIS SHOULD NEVER HAPPEN.
{
otOut << strLocation << ": ERROR in getLastReplyReceived(): why "
"was this string not set, when "
"getRequestNumber was otherwise an "
"apparent success?\n";
return -1; // (SHOULD NEVER HAPPEN. This string is set in the
// getRequestNumber function.)
}
bool bProcessNymboxReplyError =
(!VerifyStringVal(strReplyProcess) || (nReplySuccess < 0));
bool bProcessNymboxBalanceError =
(!VerifyStringVal(strReplyProcess) || (nBalanceSuccess < 0));
bool bProcessNymboxTransError =
(!VerifyStringVal(strReplyProcess) || (nTransSuccess < 0));
bool bProcessNymboxReplySuccess =
(!bProcessNymboxReplyError && (nReplySuccess > 0));
bool bProcessNymboxReplyFailure =
(!bProcessNymboxReplyError && (nReplySuccess == 0));
bool bProcessNymboxBalanceSuccess =
(!bProcessNymboxReplyError && !bProcessNymboxBalanceError &&
(nBalanceSuccess > 0));
bool bProcessNymboxBalanceFailure =
(!bProcessNymboxReplyError && !bProcessNymboxBalanceError &&
(nBalanceSuccess == 0));
bool bProcessNymboxTransSuccess =
(!bProcessNymboxReplyError && !bProcessNymboxBalanceError &&
!bProcessNymboxTransError && (nTransSuccess > 0));
bool bProcessNymboxTransFailure =
(!bProcessNymboxReplyError && !bProcessNymboxBalanceError &&
!bProcessNymboxTransError && (nTransSuccess == 0));
bool bProcessAnyError =
(bProcessNymboxReplyError || bProcessNymboxBalanceError ||
bProcessNymboxTransError);
bool bProcessAnyFailure =
(bProcessNymboxReplyFailure || bProcessNymboxBalanceFailure ||
bProcessNymboxTransFailure);
bool bProcessAllSuccess =
(bProcessNymboxReplySuccess && bProcessNymboxBalanceSuccess &&
bProcessNymboxTransSuccess);
// Note: we LEAVE the sent message in the "sent queue" until we are
// certain that it processed.
// If we are NOT certain that it processed, then we try to download the
// Nymbox and see if there's
// a reply there (for the sent message.) If we are able to confirm THAT,
// AFTER SUCCESSFULLY downloading
// the Nymbox, then then we don't have to do anything because we know
// for sure it was processed.
// Similarly, if we DEFINITELY download the Nymbox and do NOT find the
// reply, then we know the server
// DEFINITELY did not receive (or at least process) that message, which
// is what allows us to HARVEST
// the transaction numbers back from the sent message, and remove the
// sent message from the sent queue.
//
// However, if we are NOT able to Verify any of these things, NOR are we
// able to download the Nymbox to
// see, then we DO leave the message in the sent queue. This is
// deliberate, since it gives us the opportunity
// in the future to clear those sent messages NEXT time we successfully
// DO download the Nymbox, and in the
// meantime, it allows us to store a record of EXACTLY which messages
// were MISSED.
//
int32_t nHarvested = -1;
if (bProcessAllSuccess) {
// the processNymbox was a complete success, including the message
// AND the transaction AND the transaction statement.
// Therefore, there's DEFINITELY nothing to clawback.
//
// (Thus I RemoveSentMessage for the processNymbox message, since
// I'm totally done with it now.)
//
// int32_t nRemoved =
// OTAPI_Wrap::RemoveSentMessage(Integer.toString(nProcess),
// notaryID, nymID);
// NOTE: The above call is unnecessary, since a successful process
// means
// we already received the successful server reply, and OT's
// "ProcessServerReply"
// already removed the sent message from the sent buffer (so no need
// to do that here.)
//
}
else if (bProcessAnyError ||
bProcessAnyFailure) // let's resync, and clawback whatever
// transaction numbers we might have used
// on the processNymbox request...
{
nGetNymbox = getNymbox(notaryID, nymID,
true); // bForceDownload=true - NOTE: could
// maybe change this to false and have
// it still work.;
if (nGetNymbox < 1) {
otOut << strLocation
<< ": Failure: this.getNymbox returned: " << nGetNymbox
<< "\n";
return -1;
}
bool bWasFound = false;
nBoxType =
0; // I think it was already zero, but since i'm using it here;
// PURELY to be a '0', I feel safer setting it again. (Nymbox is 0.)
// bool bInsured = insureHaveAllBoxReceipts(notaryID, nymID,
// nymID, nBoxType, nRequestNumber, bFoundNymboxItem); //
// ***************************;
if (insureHaveAllBoxReceipts(notaryID, nymID, nymID, nBoxType,
nProcess, bWasFound)) // This will tell
// us whether the
// processNymbox
// reply was
// found in the
// Nymbox
{
// we FOUND the processNymbox reply in the Nymbox!
//
if (bWasFound) {
// Thus, no need to clawback any transaction numbers,
// since the server clearly already processed this
// processNymbox
// transaction, since I have a reply to it already sitting
// in my Nymbox.
//
// int32_t nRemoved =
// OTAPI_Wrap::RemoveSentMessage(Integer.toString(nProcess),
// notaryID, nymID);
//
// NOTE: The above call is unnecessary, since a successful
// process means
// we already received the successful server reply, and OT's
// "ProcessServerReply"
// already removed the sent message from the sent buffer (so
// no need to do that here.)
otOut << strLocation << ": FYI: I *did* find the "
"processNymboxResponse reply in my "
"Nymbox, so NO NEED to clawback "
"any transaction numbers.\n";
}
else // was NOT found... we need to clawback.
{
// This means the server's reply was definitely NOT found in
// the
// Nymbox, even after successfully DOWNLOADING that Nymbox.
// Which
// means the server never got it in the first place, or
// rejected it
// at the message level before the transaction portion had a
// chance
// to run. Either way, we need to claw back any relevant
// transaction
// numbers...
// HARVEST the processNymbox message from outgoing messages.
otLog3 << strLocation
<< ": FYI: Calling OT_API_GetSentMessage...\n";
string strSentProcessNymboxMsg = OTAPI_Wrap::GetSentMessage(
int64_t(nProcess), notaryID, nymID);
if (!VerifyStringVal(strSentProcessNymboxMsg)) {
otInfo << strLocation
<< ": (2) OT_API_GetSentMessage returned "
"nullptr for clawback. (Must have already "
"been cleared. OT uses deliberate "
"redundancy, though optimizes this wherever "
"possible.) Request number: " << nProcess
<< "\n";
}
else // strSentProcessNymboxMsg NOT null!
{
otOut << strLocation << ": FYI: Harvesting transaction "
"numbers from failed "
"processNymbox attempt...\n";
nHarvested = OTAPI_Wrap::Msg_HarvestTransactionNumbers(
strSentProcessNymboxMsg, nymID,
false, // bHarvestingForRetry = = false;
bProcessNymboxReplySuccess, // bReplyWasSuccess,
// // RECEIVED server
// reply: explicit
// success.
bProcessNymboxReplyFailure, // bReplyWasFailure,
// // RECEIVED server
// reply: explicit
// failure.
bProcessNymboxTransSuccess, // bTransactionWasSuccess,
// // MESSAGE success,
// Transaction success.
// (Explicit.)
bProcessNymboxTransFailure); // bTransactionWasFailure
// // MESSAGE success,
// Transaction failure.
// (Explicit.)
otOut << strLocation
<< ": OT_API_Msg_HarvestTransactionNumbers: "
<< nHarvested << "\n";
bool nRemovedProcessNymboxMsg =
OTAPI_Wrap::RemoveSentMessage(int64_t(nProcess),
notaryID, nymID);
otInfo << strLocation << ": OT_API_RemoveSentMessage: "
<< nRemovedProcessNymboxMsg << "\n";
} // strSentProcessNymboxMsg NOT null!
} // a specific receipt was not found in the nymbox (need to
// clawback the transaction numbers on that receipt.)
strNymbox = OTAPI_Wrap::LoadNymboxNoVerify(
notaryID,
nymID); // FLUSH SENT MESSAGES!!!! (AND HARVEST.);
if (VerifyStringVal(strNymbox)) {
OTAPI_Wrap::FlushSentMessages(
false, // harvesting for retry = = OT_FALSE
notaryID, nymID, strNymbox);
}
// Flushing removes all the messages from the "sent messages"
// queue,
// and harvests any transaction numbers to be had. How do I know
// for sure
// that I can get away with this? How do I know whether the
// server has
// processed those messages or not? How can I harvest them as
// though they
// were dropped on the network somewhere? The answer is because
// I JUST
// called getNymbox and downloaded the latest one. I can SEE
// which replies
// are in there -- and which ones aren't. I pass that Nymbox
// into the flush
// call, so that flush can be careful to remove all sent
// messages that have
// nymbox replies, and only harvest the others.
else {
otOut << strLocation << ": Error while trying to flush "
"sent messages: Failed loading "
"Nymbox for nym: " << nymID << "\n";
}
} // if insureHaveAllBoxReceipts()
else // we do NOT have all the box receipts.
{
otOut << strLocation << ": Error: insureHaveAllBoxReceipts "
"failed. (I give up.)\n";
return -1;
}
} // else if (bProcessAnyError || bProcessAnyFailure)
// Return the request number, if potentially needed by caller.
// If explicit success, the request number is returned as a positive
// number (though already removed from sent queue.) Whereas if explicit
// failure (replystatus = failed) then we harvest the numbers;
//
if (bProcessAllSuccess)
// return getNymbox(notaryID, nymID, true);
// //bForceDownload = true. Since we DID process it successfully,
// then we grab it again.
{
return 1;
} // We don't need the sent message after this, and we've already
// removed it from sent queue.
if (bProcessAnyFailure || bProcessAnyError) {
if (nHarvested < 1) // If the message failed, and the harvesting
// failed, then we return the
{
return nProcess;
} // number for the process nymbox, so the caller has a choice of
// what to do next.
if (bProcessAnyFailure) {
return 0;
} // by this point, we've definitely harvested, AND removed sent
// message from sent queue. So we just return 0;
}
return -1; // must've been an error.
} // if insureAllBoxReceipts()
else {
otOut << strLocation
<< ": insureHaveAllBoxReceipts failed. (I give up.)\n";
}
return -1;
}
// def Utility::getAndProcessNymbox(String notaryID, String nymID, OTBool
// bWasMsgSent, boolean bForceDownload)
//
OT_UTILITY_OT int32_t
Utility::getAndProcessNymbox_4(const string& notaryID, const string& nymID,
bool& bWasMsgSent, bool bForceDownload)
{
string strLocation = "Utility::getAndProcessNymbox_4";
if (!VerifyStringVal(notaryID) || !VerifyStringVal(nymID)) {
otOut << strLocation << ": SHOULD NEVER HAPPEN!!! ASSERT!! ERROR!! "
"FAILURE!!! PROBLEM!!!!!\n";
return -1;
}
// bool bMsgReplySuccess5 = false;
// bool bMsgReplyFailure5 = false;
// bool bMsgTransSuccess5 = false;
// bool bMsgTransFailure5 = false;
int32_t nRequestNumber = 0;
bool bHarvestingForRetry = false;
OTfourbool the_foursome = {false, false, false, false};
bool bFoundNymboxItem = false; // bFoundNymboxItem is output bool, telling
// caller whether it was found.;
return getAndProcessNymbox_8(notaryID, nymID, bWasMsgSent, bForceDownload,
nRequestNumber, bFoundNymboxItem,
bHarvestingForRetry, the_foursome);
}
// public static int32_t getNymboxLowLevel(String notaryID, String nymID)
// public static int32_t receiveNymboxLowLevel(String notaryID, String nymID,
// var nRequestNum)
// public static int32_t processNymboxLowLevel(String notaryID, String nymID) {
// def Utility::getAndProcessNymbox(String notaryID, String nymID, OTBool
// bWasMsgSent)
OT_UTILITY_OT int32_t Utility::getAndProcessNymbox_3(const string& notaryID,
const string& nymID,
bool& bWasMsgSent)
{
bool bForceDownload = false;
return getAndProcessNymbox_4(notaryID, nymID, bWasMsgSent, bForceDownload);
}
// NEW VERSION:
// PROCESS NYMBOX
//
// Returns:
// -1 Error.
// 0 Nymbox was empty -- nothing done. (bWasMsgSent = false)
// 0 server reply received, but it sayssuccess = =false on that msg.
// (bWasMsgSent = true);
// >0 If the Transaction status (from the server reply) is SUCCESS, then this
// function
// returns the REQUEST NUMBER from when it was originally sent.
//
// public static int32_t processNymbox(String notaryID, String nymID,
// OTBool bWasMsgSent,
//
// OTInteger nMsgSentRequestNumOut,
// OTInteger nReplySuccessOut,
// OTInteger nBalanceSuccessOut,
// OTInteger nTransSuccessOut)
OT_UTILITY_OT int32_t
Utility::processNymbox(const string& notaryID, const string& nymID,
bool& bWasMsgSent, int32_t& nMsgSentRequestNumOut,
int32_t& nReplySuccessOut,
int32_t& nBalanceSuccessOut,
int32_t& nTransSuccessOut)
{
bWasMsgSent = false;
string strLocation = "Utility::processNymbox";
// if (!VerifyOTBoolRef(bWasMsgSent) ||
// !VerifyOTIntegerRef(nReplySuccessOut) ||
// !VerifyOTIntegerRef(nBalanceSuccessOut) ||
// !VerifyOTIntegerRef(nTransSuccessOut))
//{
// otOut << strLocation << ": SHOULD NEVER HAPPEN: has null
// values passed in...\n";
// exit(-1)
//}
nMsgSentRequestNumOut = -1;
nReplySuccessOut = -1;
nBalanceSuccessOut = -1;
nTransSuccessOut = -1;
// -- SECTION 2: "SEND PROCESS NYMBOX"
// Next, we have to make sure we have all the BOX RECEIPTS downloaded
// for this Nymbox.
int32_t nProcess = sendProcessNymboxLowLevel(
notaryID, nymID); // <===================== SEND PROCESS NYMBOX!!;
if (-1 == nProcess) {
otOut << strLocation << "(2): error (-1), when calling "
"sendProcessNymboxLowLevel. (It couldn't send. "
"I give up.)\n";
return -1; // (It didn't even send.)
}
// Nymbox was empty. (So we didn't send any process message because there
// was nothing to process.)
if (0 == nProcess) {
return 0; // success. done.
}
if (nProcess < 0) {
otOut << strLocation << ": unexpected: " << nProcess
<< ", when calling sendProcessNymboxLowLevel. (I give up.)\n";
return -1;
}
bWasMsgSent = true;
nMsgSentRequestNumOut = nProcess;
// By this point, we definitely have a >0 request number from the
// sendProcessNymbox()
// call, stored in ** nProcess ** (meaning the message WAS sent.)
//
// But was it received?
//
string strReplyProcess =
ReceiveReplyLowLevel(notaryID, nymID, nProcess,
"processNymbox / sendProcessNymboxLowLevel / "
"ReceiveReplyLowLevel"); // <=============== Here
// we RECEIVE the REPLY...
// getLastReplyReceived() will also contain the same as strReplyProcess.
// So if the CALLER of this function (that we're in, receiveNymboxLowLevel)
// wants to see the contents, he can.
// ReceiveReplyLowLevel returns null unless there was a string returned.
// So we can directly check it for success...
int32_t nReplySuccess =
VerifyMessageSuccess(strReplyProcess); // sendProcessNymboxLowLevel;
int32_t nTransSuccess = -1;
int32_t nBalanceSuccess = -1;
;
if (nReplySuccess > 0) // If message was success, then let's see if the
// transaction was, too.
{
nBalanceSuccess = OTAPI_Wrap::Message_GetBalanceAgreementSuccess(
notaryID, nymID, nymID,
strReplyProcess); // the processNymbox transaction.;
if (nBalanceSuccess > 0) {
nTransSuccess = OTAPI_Wrap::Message_GetTransactionSuccess(
notaryID, nymID, nymID,
strReplyProcess); // the processNymbox transaction.;
}
}
nReplySuccessOut = nReplySuccess;
nBalanceSuccessOut = nBalanceSuccess;
nTransSuccessOut = nTransSuccess;
// NOTE: The caller MUST have a call to OTAPI_Wrap::RemoveSentMessage
// to correspond to THIS function's call of sendProcessNymboxLowLevel().
//
if (nTransSuccess > 0) {
return nProcess; // <=========================
}
return nTransSuccess;
}
// No need to deal with getRequestNumber here when failure, since the calling
// function already goes through that crap before we get here.
// Returns: the request number for the process Nymbox request.
// OR returns 0 if the Nymbox was empty (and no message was sent.)
// OR returns -1 if there was an error.
//
// DONE
OT_UTILITY_OT int32_t Utility::sendProcessNymboxLowLevel(
const string& notaryID, const string& nymID) const // bWasSent is an output
// param allowing to
// return whether;
{
string strLocation = "Utility::sendProcessNymboxLowLevel";
// Send message..
OTAPI_Wrap::FlushMessageBuffer();
int32_t nRequestNum = OTAPI_Wrap::processNymbox(notaryID, nymID);
if (-1 == nRequestNum) {
otOut << strLocation
<< ": Failure sending. OT_API_processNymbox() returned -1. \n";
return -1; // no need to check for any reply.
}
if (nRequestNum < 0) {
otOut << strLocation
<< ": Failure: OT_API_processNymbox() returned unexpected value: "
<< nRequestNum << "\n";
return -1; // no need to check for any reply.
}
if (0 == nRequestNum) {
otOut << strLocation << ": Nymbox was empty; no need to process it. \n";
return 0; // Nymbox is empty, thus no need to process it.
}
// Note: I do NOT call RemoveSentMessage for processNymbox, at least, not
// here.
// Instead, the place that CALLS this function, will actually use that
// because
// it has to be able to harvest the transaction numbers in certain failure
// cases.
return nRequestNum;
}
// returns:
// -1 for error,
// 0 for server reply of failure,
// 1 for server reply of success
//
OT_UTILITY_OT int32_t
Utility::receiveReplySuccessLowLevel(const string& notaryID18,
const string& nymID,
int32_t nRequestNumber7,
const string& IN_FUNCTION)
{
string strReply = ReceiveReplyLowLevel(
notaryID18, nymID, nRequestNumber7,
"receiveReplySuccessLowLevel: " +
IN_FUNCTION); // <=============== Here we RECEIVE the REPLY...
// getLastReplyReceived() will also contain the same as strReply.
// So if the CALLER of this function (that we're in, receiveNymboxLowLevel)
// wants to see the contents, he can.
// ReceiveReplyLowLevel returns null unless there was a string returned.
// So we can directly check it for success...
return VerifyMessageSuccess(strReply);
}
// Tries to receive a server reply
// (for a message that you presumably just sent.)
// If successful, returns the server reply. Otherwise returns null.
// (Successful meaning, a valid-formed message was received. Whether that is a
// "success=true" or "success=false" message, the caller will have to figure
// that out for himself.)
//
OT_UTILITY_OT string Utility::ReceiveReplyLowLevel(const string& notaryID17,
const string& nymID,
int32_t nRequestNumber8,
const string& IN_FUNCTION)
{
setLastReplyReceived("");
if (0 > nRequestNumber8) {
otOut << "ReceiveReplyLowLevel (" << IN_FUNCTION
<< "): nRequestNumber isn't a valid number.\n";
return "";
}
string strResponseMessage = OTAPI_Wrap::PopMessageBuffer(
int64_t(nRequestNumber8), notaryID17, nymID);
if (!VerifyStringVal(strResponseMessage)) {
otOut << "ReceiveReplyLowLevel (" << IN_FUNCTION
<< "): null server reply!\n";
return "";
}
setLastReplyReceived(strResponseMessage);
return strResponseMessage;
}
OT_UTILITY_OT int32_t
Utility::getRequestNumber(const string& notaryID, const string& nymID)
{
bool bWasSent = false;
return getRequestNumber(notaryID, nymID, bWasSent);
}
// -1 == error (couldn't send, or couldn't receive)
// 0 = = success false (received reply from server);
// 1 = = success true (received reply from server);
//
// To distinguish between error where message wasn't sent,
// and error where message WAS sent, but reply never received,
// bWasSent will be set to TRUE once this function is sure that
// it was sent out. (which you only care about if -1 was the
// return value;
// server reply, AND its status.
// DONE
OT_UTILITY_OT int32_t
Utility::getRequestNumber(const string& notaryID, const string& nymID,
bool& bWasSent) // bWasSent is an output param
// allowing to return whether;
{
string strLocation = "Utility::getRequestNumber";
OTAPI_Wrap::FlushMessageBuffer();
int32_t nResult = OTAPI_Wrap::getRequestNumber(notaryID, nymID);
if (-1 == nResult) // if error -1, that means it DIDN'T SEND (error)
{
otOut << strLocation
<< ": Failed to send getRequestNumber message due to error.\n";
return -1;
}
if (0 == nResult) // if 0 is returned, that also means it DIDN'T SEND (but
// there was NO error...)
{ // I don't know if this case can actually even HAPPEN... but if it does,
// I'll log it.
otOut << strLocation
<< ": Didn't send this getRequestNumber message, but NO "
"error occurred, either. (Should never "
"happen.)\n";
return -1; // Since the 0 case should never happen, I'm returning it as
// an ERROR (-1).
// Note: I could never return 0;
// and that the server's reply said "success == 0". But that's not what
// happened here. Here,
// we couldn't even SEND our request, which is an error
}
//
// else it's >0 == successfully sent! (I BELIEVE this is 1, in this case,
// every time, since you don't NEED a request number to CALL
// getRequestNumberNum
// since you are only calling it in the first place because it must have
// gotten out of sync.)
//
bWasSent = true;
//
int32_t nReturn =
receiveReplySuccessLowLevel(notaryID, nymID, nResult, strLocation);
// otOut << "IN getRequestNumber " <<
// getLastReplyReceived());
// BY this point, we definitely have the request number in nResult, which
// means
// the message was actually SENT. (At least.) This also means we can use
// nResult
// later to query for a copy of that sent message.
// Let's go ahead, in this case, and remove that now:
//
// var nRemovedGetRequestNumber =
// OTAPI_Wrap::RemoveSentMessage(Integer.toString(nResult), notaryID,
// nymID);
// NOTE: The above call is unnecessary, since a successful reply means
// we already received the successful server reply, and OT's
// "ProcessServerReply"
// already removed the sent message from the sent buffer (so no need to do
// that here.)
// if (nRemovedGetRequestNumber < 1)
// {
// otOut << "getRequestNumber: ERROR:
// OT_API_RemoveSentMessage returned: " << nRemovedGetRequestNumber);
// }
return nReturn;
}
// called by getBoxReceiptWithErrorCorrection DONE
OT_UTILITY_OT bool Utility::getBoxReceiptLowLevel(
const string& notaryID, const string& nymID, const string& accountID,
int32_t nBoxType, int64_t strTransactionNum,
bool& bWasSent) // bWasSent is OTBool
{
string strLocation = "Utility::getBoxReceiptLowLevel";
bWasSent = false;
OTAPI_Wrap::FlushMessageBuffer();
int32_t nRequestNum = OTAPI_Wrap::getBoxReceipt(
notaryID, nymID, accountID, nBoxType,
strTransactionNum); // <===== ATTEMPT TO SEND THE MESSAGE HERE...;
if (-1 == nRequestNum) {
otOut << strLocation
<< ": Failed to send getNymbox message due to error.\n";
return false;
}
if (0 == nRequestNum) {
otOut << strLocation << ": Didn't send getNymbox message, but NO error "
"occurred, either. (In this case, SHOULD NEVER "
"HAPPEN. Treating as Error.)\n";
return false; // Even though '0' MEANS "didn't send, but no error" by
// convention in many places, it is actually an impossible
// return value;
}
if (nRequestNum < 0) {
otOut << strLocation << ": Unexpected request number: " << nRequestNum
<< "\n";
return false;
}
bWasSent = true;
// BY this point, we definitely have the request number, which means the
// message was actually SENT. (At least.) This also means we can use
// nRequestNum
// later to query for a copy of that sent message.
//
//
int32_t nReturn =
receiveReplySuccessLowLevel(notaryID, nymID, nRequestNum, strLocation);
otWarn << strLocation << ": nRequestNum: " << nRequestNum
<< " / nReturn: " << nReturn << "\n";
// int32_t nRemovedGetBoxReceipt =
// OTAPI_Wrap::RemoveSentMessage(Integer.toString(nRequestNum), notaryID,
// nymID);
//
// // NOTE: The above call is unnecessary, since a successful reply
// means
// // we already received the successful server reply, and OT's
// "ProcessServerReply"
// // already removed the sent message from the sent buffer (so no need
// to do that here.)
//
// if (nRemovedGetBoxReceipt < 1)
// {
// otOut << "getBoxReceiptLowLevel: ERROR:
// OT_API_RemoveSentMessage returned: " << nRemovedGetBoxReceipt);
// }
if (nReturn > 0) {
return true;
}
otOut << strLocation << ": Failure: Response from server:\n"
<< getLastReplyReceived() << "\n";
return false;
}
// called by insureHaveAllBoxReceipts DONE
OT_UTILITY_OT bool Utility::getBoxReceiptWithErrorCorrection(
const string& notaryID, const string& nymID, const string& accountID,
int32_t nBoxType, int64_t strTransactionNum) // nBoxType is int32_t
{
string strLocation = "Utility::getBoxReceiptWithErrorCorrection";
bool bWasSent = false;
bool bWasRequestSent = false;
if (getBoxReceiptLowLevel(notaryID, nymID, accountID, nBoxType,
strTransactionNum, bWasSent)) {
return true;
}
if (bWasSent && (1 == getRequestNumber(notaryID, nymID,
bWasRequestSent))) // this might be
// out of sync, if
// it failed...
// we'll re-sync,
// and re-try.
{
if (bWasRequestSent &&
getBoxReceiptLowLevel(notaryID, nymID, accountID, nBoxType,
strTransactionNum, bWasSent)) {
return true;
}
otOut << strLocation << ": getBoxReceiptLowLevel failed, then "
"getRequestNumber succeeded, then "
"getBoxReceiptLowLevel failed again. (I give "
"up.)\n";
}
else {
otOut << strLocation
<< ": getBoxReceiptLowLevel failed, then "
"getRequestNumber failed. (I give up.) Was "
"getRequestNumber message sent: " << bWasRequestSent << "\n";
}
return false;
}
// This function assumes you just downloaded the latest version of the box
// (inbox, outbox, or nymbox)
// and its job is to make sure all the related box receipts are downloaded as
// well and available, though
// not necessarily loaded into memory. (Yet.)
// NOTE: If nBoxType is 0 (nymbox) then pass nymID as the accountID as well!
//
OT_UTILITY_OT bool Utility::insureHaveAllBoxReceipts(
const string& notaryID, const string& nymID, const string& accountID,
int32_t nBoxType) // nBoxType is int32_t
{
bool bFoundIt = false;
int32_t nRequestSeeking = 0;
return insureHaveAllBoxReceipts(notaryID, nymID, accountID, nBoxType,
nRequestSeeking, bFoundIt);
}
OT_UTILITY_OT bool Utility::insureHaveAllBoxReceipts(
const string& notaryID, const string& nymID, const string& accountID,
int32_t nBoxType, int32_t nRequestSeeking, bool& bFoundIt)
{
string strLocation = "Utility::insureHaveAllBoxReceipts";
string ledger = "";
if (0 == nBoxType) {
ledger = OTAPI_Wrap::LoadNymboxNoVerify(notaryID, nymID);
}
else if (1 == nBoxType) {
ledger = OTAPI_Wrap::LoadInboxNoVerify(notaryID, nymID, accountID);
}
else if (2 == nBoxType) {
ledger = OTAPI_Wrap::LoadOutboxNoVerify(notaryID, nymID, accountID);
}
else {
otOut << strLocation << ": Error. Expected nBoxType of 0,1,2 (nymbox, "
"inbox, or outbox.)\n";
return false;
}
// Unable to load or verify inbox/outbox/nymbox
// Notice I don't call VerifyAccount() here (not that the API even exposes
// that method) but why not? Because that method tries to load up all the
// box receipts, in addition to verifying the signature. Therefore I call
// "Load XXXX NoVerify()", avoiding all that, then I verify the Signature
// itself. That's because this function's whole point is to find out what
// the box receipts are, and download them from the server. No point trying
// to load them before that time, when I know it will fail.
//
if (!VerifyStringVal(ledger) ||
(!OTAPI_Wrap::VerifySignature(nymID, ledger))) {
otOut << strLocation << ": Unable to load or verify signature on "
"ledger. (Failure.) Contents:\n" << ledger
<< "\n";
return false;
}
// At this point, the box is definitely loaded.
// Next we'll iterate the receipts
// within, and for each, verify that the Box Receipt already exists. If not,
// then we'll download it using getBoxReceiptLowLevel(). If any download
// fails,
// then we break out of the loop (without continuing on to try the rest.)
//
bool bReturnValue = true; // Assuming an empty box, we return success;
int32_t nReceiptCount =
OTAPI_Wrap::Ledger_GetCount(notaryID, nymID, accountID, ledger);
if (nReceiptCount > 0) {
for (int32_t i_loop = 0; i_loop < nReceiptCount; ++i_loop) {
int64_t lTransactionNum =
OTAPI_Wrap::Ledger_GetTransactionIDByIndex(
notaryID, nymID, accountID, ledger, i_loop);
if (lTransactionNum != -1) {
if (lTransactionNum > 0) {
string strTransaction =
OTAPI_Wrap::Ledger_GetTransactionByID(notaryID, nymID,
accountID, ledger,
lTransactionNum);
// Note: OTAPI_Wrap::Ledger_GetTransactionByID tries to get
// the full transaction from the ledger and
// return it;
// and pass the full version back to us. Failing that
// (perhaps the box receipt hasn't been downloaded
// yet) then it will try to re-sign / re-save the
// abbreviated version and pass it back. So if, by this
// point, it STILL has failed, that means it couldn't even
// give us the abbreviated version either!
//
if (!VerifyStringVal(strTransaction)) {
otOut << strLocation
<< ": Error: Null transaction somehow returned, "
"(not even an abbreviated one!) even though I "
"had a good ID " << lTransactionNum
<< " which came originally as lTransactionNum: "
<< lTransactionNum << " for index: " << i_loop
<< " with the contents:\n\n" << strTransaction
<< "\n\n";
return false;
}
// This block might have a full version, OR an abbreviated
// version of the box receipt in
// question, in the strTransaction variable. It will attempt
// to download the full box
// receipt, if we don't already have it here on the client
// side.
{
string strTransType = OTAPI_Wrap::Transaction_GetType(
notaryID, nymID, accountID, strTransaction);
bool bIsReplyNotice = (VerifyStringVal(strTransType) &&
(strTransType == "replyNotice"));
int64_t lRequestNum = 0;
if (bIsReplyNotice) {
lRequestNum = OTAPI_Wrap::ReplyNotice_GetRequestNum(
notaryID, nymID, strTransaction);
}
bool bShouldDownload =
(!bIsReplyNotice ||
(bIsReplyNotice && (0 < lRequestNum) &&
!OTAPI_Wrap::HaveAlreadySeenReply(notaryID, nymID,
lRequestNum)));
if (bShouldDownload) // This block executes if we should
// download it (assuming we haven't
// already, which it also checks
// for.)
{
bool bHaveBoxReceipt =
OTAPI_Wrap::DoesBoxReceiptExist(
notaryID, nymID, accountID, nBoxType,
lTransactionNum);
if (!bHaveBoxReceipt) {
otWarn << strLocation << ": Downloading box "
"receipt to add to my "
"collection...\n";
bool bDownloaded =
getBoxReceiptWithErrorCorrection(
notaryID, nymID, accountID, nBoxType,
lTransactionNum);
if (!bDownloaded) {
otOut
<< strLocation
<< ": Failed downloading box receipt. "
"(Skipping any others.) Transaction "
"number: " << lTransactionNum
<< "\n";
bReturnValue = false;
break;
// No point continuing to loop and fail 500
// times, when
// getBoxReceiptWithErrorCorrection()
// already failed
// even doing the getRequestNumber() trick
// and
// everything, and whatever retries are
// inside OT, before it finally
// gave up.
}
// else (Download success.)
} // if (!bHaveBoxReceipt)
}
// else we already have the box receipt, no need to
// download again.
}
} // if (lTransactionNum > 0)
else {
otOut
<< strLocation
<< ": Error: TransactionNum less-than-or-equal-to 0.\n";
}
}
else {
otOut << strLocation << ": Error: TransactionNum was null, "
"when trying to read it based on the "
"index (within bounds, too!)\n";
}
} // ************* FOR LOOP ******************
} // if (nReceiptCount > 0)
//
// if nRequestSeeking is >0, that means the caller wants to know if there is
// a receipt present for that request number.
// (which is only a valid option ifnBoxType = = 0 for Nymbox.);
// IF the receipt is found, then bFoundIt is set to true.
//
if ((nRequestSeeking > 0) && (0 == nBoxType)) {
// NOTE: the below call to OTAPI_Wrap::Nymbox_GetReplyNotice will
// succeed even if
// only the abbreviated receipt is available, because the caller mainly
// just
// wants to know if it is there.
// Technically the full receipt SHOULD always be there, with the above
// loop,
// but since the above loop can break in case of error, it's still
// possible that
// box receipts haven't been downloaded by the time you reach this code.
// Nevertheless, we will see if the reply is there for the appropriate
// request
// number, whether abbreviated or not.
//
// UPDATE: I am now adding specific cases where the replyNotice is NOT
// downloaded.
// You still use it, through its abbreviated version -- and the actual
// version
// IS still available for download through the server's API. But with a
// replyNotice,
// just knowing that it exists is usually enough for the client, who
// probably still
// has a cached copy of the original sent message anyway. Only in cases
// where he
// doesn't, would he need to download it. (Why? So he can process the
// server's reply.)
// Therefore the cached sent message is useless, since it doesn't
// contain the server's
// reply! Hmm. So I need that reply BUT ONLY IN CASES where I didn't
// already receive it
// as a normal part of processing (and that is MOST of the time, meaning
// most cases can
// thus entirely eliminate the download.)
//
// PROTOCOL FOR NOT DOWNLOADING MOST OF THE BOX RECEIPTS
//
// Solution: User messages should contain a list of the last X number of
// request numbers
// that they have DEFINITELY seen the response to. The server,
// meanwhile, since the user
// has DEFINITELY seen the response, can now safely remove the
// replyNotice from the Nymbox.
// The only reason it was there in the first place was to make sure the
// user got the reply.
// Since the user is straight-up acknowledging that he received it, the
// server no longer
// needs to "make sure" and thus it can remove that reply from the
// Nymbox, and mark the
// box receipt for deletion. This will be MOST REPLIES! We'll eliminate
// the step of having
// to download the box receipt.
// The above call to getBoxReceiptWithErrorCorrection should also be
// smart enough not to
// bother downloading any replyNotice Box Receipts if their request
// number appears on that
// list. Again: the list means I DEFINITELY already responded to it--if
// the request # is on
// that list, then NO NEED downloading the Box Receipt -- I DEFINITELY
// already got that reply!
//
// Therefore, Something like OTAPI_Wrap::HaveAlreadySeenReply(notaryID,
// nymID, requestNum);
//
// Perhaps also, on the server side, send a list of request numbers for
// that Nym that the
// server KNOWS the Nym saw the reply to. This way, the Nym can remove
// the number from his
// list, and thus won't be continually causing the server to load up the
// Nymbox and try
// to remove the replyNotice (since it's already been removed.)
//
// The Nym doesn't have to keep a list of ALL request numbers he's seen
// the reply to.
// Rather, just the past X number of them, and with the number
// explicitly removed once
// he sees the server acknowledgment. (ServerAckOfAlreadyGotReply.)
//
// The server, meanwhile, is free to remove the ACK for any request #
// once he sees that
// the client has as well. Server also only needs to store a list of the
// past X request #s.
// Also: since both sides REMOVE the number, there need not necessarily
// be a limit on the
// size of the list, since it grows and shrinks as needed.
//
// Whenever Wallet processes a server reply, just see if it's on that
// "replied to already"
// list already on client side. If so, discard the reply.
// OTClient::ProcessServerReply probably
// best place to do (We replied to it already, so discard it.)
// Also, for any server reply, look at the list of numbers on it. The
// server is acknowledging
// to us that it KNOWS we got those replies, and that it ALREADY has
// removed them from the
// Nymbox as a result. Therefore we can remove ALL of those numbers from
// our own list
// as well. No need for an API call to do this, since it will happen
// internally to OT.
//
// On the server side, any numbers on its own list were only there to
// acknowledge numbers
// that had been on the client side list. Therefore, when those numbers
// disappear from the
// client side list, the server simply removes them. Again: ANY NUMBERS
// on the server list,
// which do NOT appear on the client list, are REMOVED From the server
// list. After all, the
// client has clearly now removed them, so the server doesn't have to
// keep them around either.
//
// These are useful for synchronization but also there's a int64_t term
// benefit, if we include
// them in the signed receipt (which they will be already, if the
// receipt contains the entire
// message and not just the transaction.) That benefit is that we can
// prove receipt of notice.
// At least, notice of server replies. But for other notice types, such
// as notice of upcoming
// meeting. Or notice of upcoming election. Or notice of election
// outcome. Or notice of petition
// to put X issue on the next ballot, or to nominate Y Nym for some
// corporate role. Sometimes
// you want to be able to PROVE that notice was received. Does this
// prove that?
// Hmm, not necessarily. Currently I'm using this as an optimization
// scheme, which is useful
// even if not provable. How to make it provable?
//
// Back from tangent: Wait a sec! If I notice the server that I saw the
// reply, the server will
// remove that reply from my Nymbox -- but it's still in my Nymbox on
// the client side! Until
// I download the latest Nymbox. Thus if I try to PROCESS MY NYMBOX, I
// will be attempting to
// accept a receipt that's already gone! (And the processNymbox will
// therefore FAIL!)
// Solution: be smart enough, when processing Nymbox, to IGNORE any
// replyNotices when the request
// Number appears on the client's list! As the wallet processes the
// Nymbox it should already
// know to skip the ones that were already replied-to.
// Meanwhile the server side will deliberately NOT update the Nymbox
// hash just because the receipt
// was removed. Otherwise it could trigger an unnecessary download of
// the Nymbox, when the whole
// point of this exercise was to prevent unnecessary downloads. It only
// updates the Nymbox hash
// when it WANTS me to download the Nymbox, and that certainly does NOT
// apply to cases where the
// only change involved the removal of some old receipt I already
// acknowledged. (No need to force
// any downloads based on THAT case, after all.)
//
string strReplyNotice = OTAPI_Wrap::Nymbox_GetReplyNotice(
notaryID, nymID, int64_t(nRequestSeeking));
if (VerifyStringVal(strReplyNotice)) {
bFoundIt = true;
}
}
return bReturnValue;
}
/*
static void getBoxReceipt( string NOTARY_ID, string NYM_ID, string ACCT_ID, //
If for Nymbox (vs inbox/outbox) then pass NYM_ID
in this field also.
int32_t nBoxType, // 0/nymbox, 1/inbox, 2/outbox
const string TRANSACTION_NUMBER);
static bool DoesBoxReceiptExist( string NOTARY_ID, string NYM_ID, string
ACCT_ID, // If for Nymbox (vs inbox/outbox) then pass NYM_ID
in this field also.
int32_t nBoxType, // 0/nymbox, 1/inbox, 2/outbox
const string TRANSACTION_NUMBER);
*/
// If the transaction number requests fail, this function will try to resync
// the request number. But you still have to call getRequestNumber() yourself if
// you have a failure in your own function, since you might already have
// enough transaction numbers, and thus this function will never get called,
// even if your request number IS out of sync. Sorry :-)
//
OT_UTILITY_OT int32_t
Utility::getTransactionNumLowLevel(const string& notaryID,
const string& nymID,
bool& bWasSent) // bWasSent is OTBool
{
string strLocation = "Utility::getTransactionNumLowLevel";
OTAPI_Wrap::FlushMessageBuffer();
bWasSent = false;
int32_t nRequestNum = OTAPI_Wrap::getTransactionNumbers(
notaryID, nymID); // <===== ATTEMPT TO SEND THE MESSAGE HERE...;
if (-1 == nRequestNum) {
otOut << strLocation
<< ": Failed to send getNymbox message due to error.\n";
return -1;
}
if (0 == nRequestNum) {
otOut << strLocation << ": Unexpectedly returned 0. Didn't send "
"getTransactionNumbers message, but NO error "
"occurred, either. (In this case, SHOULD NEVER "
"HAPPEN. Treating as Error.)\n";
return -1; // Even though '0' MEANS "didn't send, but no error" by
// convention in many places, it is actually an impossible
// return value;
}
if (nRequestNum < 0) {
otOut << strLocation << ": Unexpected request number: " << nRequestNum
<< "\n";
return -1;
}
bWasSent = true;
//
int32_t nReturn = receiveReplySuccessLowLevel(notaryID, nymID, nRequestNum,
"getTransactionNumbers");
// otOut << "IN getTransactionNumbers " <<
// getLastReplyReceived());
// BY this point, we definitely have the request number in nResult, which
// means
// the message was actually SENT. (At least.) This also means we can use
// nResult
// later to query for a copy of that sent message.
// Let's go ahead, in this case, and remove that now:
//
// THE REMOVE SENT MESSAGE BELOW FAILS, LIKE IT'S ALREADY GONE.
//
// THIS MUST BE DUE TO THE PROCESS SERVER REPLY THAT OCCURS **IMMEDIATELY**
// after the message was originally sent!
// (The reply came in and was sent to OT's "ProcessServerReply", INSIDE the
// call to OTAPI_Wrap::getTransactionNumber.)
// Our subsequent "receive" (above) is nothing of the sort, but actually
// pops the incoming message buffer where
// the server's reply was ALREADY SITTING, since it was put there in OT's
// "ProcessServerReply", WHICH REMOVED THE
// SENT MESSAGE ALREADY (that's why the below call to RemoveSentMessage
// fails.)
//
// RETHINK any logic that doesn't take this into account,.
// Either we REMOVE this call wherever this happens, OR... we call Get first
// and make sure whether it's
// there, THEN remove it. But we can't be lumping "Failure because it's
// gone" versus "Error state" by mixing
// 0 and -1 here. We need to differentiate.
//
// Bottom line: if the reply WAS received, then the original sent message
// has ALREADY been removed
// from the sent buffer. Whereas if the reply was NOT received, then the
// sent message is still there,
// but in that case, we do NOT want to remove it -- we want it to STAY in
// the sent buffer, so that
// when we get the Nymbox later and we DO have the reply from that, THEN we
// can remove the sent msg from
// the sent buffer. Until then, we don't want OT to think it's already been
// processed (which it will, if
// it's already been removed from the sent buffer. So we leave it there for
// now.)
//
//
//
// int32_t nRemovedSentMsg =
// OTAPI_Wrap::RemoveSentMessage(Integer.toString(nRequestNum), notaryID,
// nymID);
//
// if (nRemovedSentMsg < 1)
// {
// otOut << "getTransactionNumbers: ERROR:
// OT_API_RemoveSentMessage returned: " << nRemovedSentMsg);
// }
if (1 == nReturn) {
return nRequestNum;
}
return nReturn;
}
// DONE
OT_UTILITY_OT bool Utility::getTransactionNumbers(const string& notaryID,
const string& nymID)
{
return getTransactionNumbers(notaryID, nymID, true); // bForceFirstCall = =
// true (by default)
// but in special cases
// you can override it
// and set it to false.
}
OT_UTILITY_OT bool Utility::getTransactionNumbers(
const string& notaryID, const string& nymID,
bool bForceFirstCall) // boolean bForceFirstCall defaults to true.
{
string strLocation = "Utility::getTransactionNumbers";
bool bWasSent = false;
int32_t nGetNumbers = -1;
if (bForceFirstCall) {
nGetNumbers = getTransactionNumLowLevel(
notaryID, nymID, bWasSent); // <============ FIRST TRY;
}
// if the first call didn't happen, due to bForceFirstCall being false, that
// means the caller wants the rest of this to happen as though it did.
//
if (!bForceFirstCall || (bWasSent && (nGetNumbers >= 1)) ||
(!bWasSent && (nGetNumbers == 0))) {
// Because it was successful, we have to now SIGN FOR those numbers we
// requested.
//
bool bForceDownload = true;
int32_t nProcess = getAndProcessNymbox_4(
notaryID, nymID, bWasSent, bForceDownload); // bForceDownload=true;
if ((bWasSent && (1 == nProcess)) || (!bWasSent && (0 == nProcess))) {
return true;
}
}
// If value is LESS THAN -1 (which is an unexpected value)
// or if the getTransactionNumbers message WASN'T EVEN SENT, then return.
//
else if ((nGetNumbers < -1) || !bWasSent) {
otOut << strLocation << ": Failure: getTransactionNumLowLevel returned "
"unexpected value: " << nGetNumbers << "\n";
return false;
}
// Below this point, the message WAS sent. -1 is error, 0 is failure, >0 is
// success.
// Now it's just about whether a reply was successful, or was even received.
//
// else if ((-1 == nGetNumbers) || // Message sent, but then error
// receiving or loading the reply.
// (( 0) == nGetNumbers)) // Received a reply, butstatus =
// = failure on that reply.;
else if ((-1 == nGetNumbers) || (0 == nGetNumbers)) {
if (-1 == nGetNumbers) {
otOut << strLocation << ": FYI: getTransactionNumLowLevel did "
"send, but returned error (-1). "
"(Re-trying...)\n";
}
else if (0 == nGetNumbers) {
otOut << strLocation << ": FYI: getTransactionNumLowLevel did "
"send, but returned failure (0). "
"(Re-trying...)\n";
}
int32_t nGetRequestNumber = getRequestNumber(notaryID, nymID);
if (1 != nGetRequestNumber) {
otOut << strLocation << ": Failure: getTransactionNumLowLevel "
"failed, then I tried to resync with "
"getRequestNumber and then that failed "
"too. (I give up.)\n";
return false;
}
bool bWasProcessSent = false;
int32_t nProcessNymbox =
getAndProcessNymbox_4(notaryID, nymID, bWasProcessSent, true);
// if ( (!bWasProcessSent && ((nProcessNymbox < 0) ||
// (nProcessNymbox > 1))) ||
// ( bWasProcessSent && (nProcessNymbox != 1)) ) // -1
// error, 0 failed (harvesting success), 1 success, >1 failed
// (harvesting NOT done) RequestNum is returned.
if ((!bWasProcessSent &&
((nProcessNymbox < 0) || (nProcessNymbox > 1))) ||
(bWasProcessSent && (nProcessNymbox != 1))) {
// todo: if request num is returned probably don't have to do
// anything with it.
// Why not? Because future processNymbox will iterate Nymbox and
// search for all found
// items in the sent message buffer, and REMOVE them from it (as
// clearly they will be
// processed already.)
// The ones left over in the sent buffer, after this? Must be
// harvested!
// Hmm, solution: Use the "Flush Sent Messages" function, which is
// already
// there. Have it be smart enough to harvest all sent messages
// before flushing,
//
//
if (bWasProcessSent && (nProcessNymbox > 1)) {
string strNymbox = OTAPI_Wrap::LoadNymboxNoVerify(
notaryID,
nymID); // FLUSH SENT MESSAGES!!!! (AND HARVEST.);
if (VerifyStringVal(strNymbox)) {
OTAPI_Wrap::FlushSentMessages(
false, // harvesting for retry = = OT_FALSE
notaryID, nymID, strNymbox);
}
}
otOut << strLocation
<< ": Failure: getAndProcessNymbox. Returned value: "
<< nProcessNymbox << "\n";
return false;
}
nGetNumbers = getTransactionNumLowLevel(
notaryID, nymID, bWasSent); // <================= SECOND TRY;
// if ( ( bWasSent && (nGetNumbers >= 1)) || // if message was
// sent, and was a success.
// (!bWasSent && (nGetNumbers == 0)) ) // Or if message
// wasn't sent due to "you already signed out too many numbers--you need
// to process your Nymbox..."
if ((bWasSent && (nGetNumbers >= 1)) ||
(!bWasSent && (nGetNumbers == 0))) {
int32_t nProcess =
getAndProcessNymbox_4(notaryID, nymID, bWasSent, true);
// if ( ( bWasSent && (1 == nProcess)) ||
// (!bWasSent && (0 == nProcess)) )
if ((bWasSent && (1 == nProcess)) ||
(!bWasSent && (0 == nProcess))) {
return true;
}
}
// else if (( nGetNumbers < -1) ||
// (!bWasSent && nGetNumbers != 0))
else if ((nGetNumbers < -1) || (!bWasSent && nGetNumbers != 0)) {
otOut << strLocation << ": Failure: getTransactionNumLowLevel "
"returned unexpected value: " << nGetNumbers
<< "\n";
return false;
}
else if ((-1 == nGetNumbers) || (0 == nGetNumbers)) {
if (-1 == nGetNumbers) {
otOut << strLocation << ": Failure: getTransactionNumLowLevel "
"did send, but returned error (-1), "
"even after syncing the request number "
"successfully. (Giving up.)\n";
}
else if (0 == nGetNumbers) {
otOut << strLocation << ": Failure: getTransactionNumLowLevel "
"did send, but returned failure (0), "
"even after syncing the request number "
"successfully. (Giving up.)\n";
}
bool forceDownload = true;
int32_t nLast = getAndProcessNymbox_4(
notaryID, nymID, bWasProcessSent, forceDownload);
// if (
// ((!bWasProcessSent) && ((nLast < 0) || (nLast
// > 1))) ||
// ((true == bWasProcessSent) && (nLast != 1))
// ) // -1 error, 0 failed (harvesting success), 1
// success, >1 failed (harvesting NOT done) RequestNum is returned.
if (((!bWasProcessSent) && ((nLast < 0) || (nLast > 1))) ||
((true == bWasProcessSent) &&
(nLast != 1))) // -1 error, 0 failed (harvesting success), 1
// success, >1 failed (harvesting NOT done)
// RequestNum is returned.
{
if (bWasProcessSent && (nLast > 1)) {
string strNymbox = OTAPI_Wrap::LoadNymboxNoVerify(
notaryID,
nymID); // FLUSH SENT MESSAGES!!!! (AND HARVEST.);
if (VerifyStringVal(strNymbox)) {
OTAPI_Wrap::FlushSentMessages(
false, // harvesting for retry = = OT_FALSE
notaryID, nymID, strNymbox);
}
}
otOut << strLocation
<< ": Failure: getAndProcessNymbox. Returned value: "
<< nLast << "\n";
return false;
}
nGetNumbers = getTransactionNumLowLevel(
notaryID, nymID, bWasSent); // <============ FIRST TRY;
// if ( (bWasSent && (nGetNumbers >= 1) )
// ||
// ((!bWasSent && (nGetNumbers == 0) ) )
// )
if ((bWasSent && (nGetNumbers >= 1)) ||
((!bWasSent && (nGetNumbers == 0)))) {
int32_t nProcess =
getAndProcessNymbox_4(notaryID, nymID, bWasSent, true);
// if ( ( bWasSent && (1 == nProcess)) ||
// (!bWasSent && (0 == nProcess)) )
if ((bWasSent && (1 == nProcess)) ||
(!bWasSent && (0 == nProcess))) {
return true;
}
}
// if ((nGetNumbers < -1) || // If value is
// LESS THAN -1 (which is an unexpected value)
// !bWasSent) // or if the getTransactionNumbers
// message WASN'T EVEN SENT, then return.
if ((nGetNumbers < -1) || !bWasSent) {
otOut << strLocation
<< ": Failure: getTransactionNumLowLevel returned "
"unexpected value: " << nGetNumbers << "\n";
return false;
}
}
}
// BY THIS POINT, we have SUCCESSFULLY sent the getTransactionNumLowLevel
// message,
// and nGetNumbers contains its request number.
// No need to read the result, as getTransactionNumLowLevel() already read
// it,
// and and it's available anytime via getLastReplyReceived()
// todo: should the member variable strLastReplyReceived be set to this
// one?
// before, the member var was shadowed (string strLastReplyReceived =
// getLastReplyReceived();).
string lastReplyReceived = getLastReplyReceived();
if (!VerifyStringVal(lastReplyReceived)) {
otOut << strLocation << ": ERROR in getLastReplyReceived(): why was "
"this string not set, when getRequestNumber "
"was otherwise an apparent success?\n";
return false; // (SHOULD NEVER HAPPEN. This string is set in the
// getRequestNumber function.);
}
// BY THIS POINT, we have received a server reply: getTransactionNumResponse
// (Unless it is malformed.) It's definitely not null, nor empty.
// Grab the NymboxHash on the getTransactionNumResponse reply, and also the
// one I
// already had on my client-side Nym... (So we can compare them.)
//
string strServerHash = OTAPI_Wrap::Message_GetNymboxHash(lastReplyReceived);
bool bServerhash = VerifyStringVal(strServerHash);
if (!bServerhash) {
otOut << strLocation
<< ": Warning: Unable to retrieve server-side NymboxHash from "
"OT, from server getTransactionNumResponse reply:\n\n"
<< strLastReplyReceived << "\n";
// return false;
}
string strLocalHash = OTAPI_Wrap::GetNym_NymboxHash(notaryID, nymID);
bool bLocalhash = VerifyStringVal(strLocalHash);
if (!bLocalhash) {
otOut << strLocation
<< ": Warning: Unable to retrieve client-side NymboxHash from "
"OT, for:\n notaryID: " << notaryID << "\n nymID: " << nymID
<< "\n";
// return false;
}
// the hashes don't match -- so let's definitely re-try to download the
// latest nymbox.
//
if (!bServerhash || !bLocalhash ||
(bServerhash && bLocalhash && !(strServerHash == strLocalHash))) {
// the getRequestNumber worked, and the server hashes don't match,
// so let's get and process the Nymbox...
//
bool bWasProcessSent = false;
int32_t nGetNymbox =
getAndProcessNymbox_4(notaryID, nymID, bWasProcessSent, true);
// if ( ((!bWasProcessSent) && ((nGetNymbox < 0) ||
// (nGetNymbox > 1))) ||
// ((true == bWasProcessSent) && (nGetNymbox != 1)) ) //
// -1 error, 0 failed (harvesting success), 1 success, >1 failed
// (harvesting NOT done) RequestNum is returned.
if (((!bWasProcessSent) && ((nGetNymbox < 0) || (nGetNymbox > 1))) ||
((true == bWasProcessSent) && (nGetNymbox != 1))) {
if (nGetNymbox > 1) {
string strNymbox = OTAPI_Wrap::LoadNymboxNoVerify(
notaryID,
nymID); // FLUSH SENT MESSAGES!!!! (AND HARVEST.);
if (VerifyStringVal(strNymbox)) {
OTAPI_Wrap::FlushSentMessages(
false, // harvesting for retry = = OT_FALSE
notaryID, nymID, strNymbox);
}
}
otOut
<< strLocation
<< ": Failure: getAndProcessNymbox returned unexpected value: "
<< nGetNymbox << "\n";
return false;
}
if (-1 == nGetNymbox) // we'll try re-syncing the request number, then
// try again.
{
otOut << strLocation << ": Failure: getAndProcessNymbox returned "
"-1, even after syncing the request number "
"successfully. (Giving up.)\n";
return false;
}
}
return true;
}
OT_UTILITY_OT bool Utility::getIntermediaryFiles(const string& notaryID,
const string& nymID,
const string& accountID)
{
bool bForceDownload = false;
return getIntermediaryFiles(notaryID, nymID, accountID, bForceDownload);
}
// NOTE: This is a new version, that uses getInboxAccount new version, which
// uses getAccountData instead of getAccount, getInbox, and getOutbox.
OT_UTILITY_OT bool Utility::getIntermediaryFiles(
const string& notaryID, const string& nymID, const string& accountID,
bool bForceDownload) // booleanbForceDownload = false;
{
string strLocation = "Utility::getIntermediaryFiles";
if (!VerifyStringVal(notaryID) || notaryID.size() < 10) {
otOut << strLocation << ": nullptr or invalid notaryID.\n";
return false;
}
if (!VerifyStringVal(nymID) || nymID.size() < 10) {
otOut << strLocation << ": nullptr or invalid nymID.\n";
return false;
}
if (!VerifyStringVal(accountID) || accountID.size() < 10) {
otOut << strLocation << ": nullptr or invalid accountID.\n";
return false;
}
bool bWasSentInbox = false;
bool bWasSentAccount = false;
// This is a new version of getInboxAccount that downloads ALL
// THREE files (account/inbox/outbox) in a single server message.
//
int32_t nGetInboxAcct =
getInboxAccount(notaryID, nymID, accountID, bWasSentInbox,
bWasSentAccount, bForceDownload);
// if we received an error state, and the "getAccountData" message wasn't
// even sent,
// then no point doing a bunch of retries -- it failed.
//
if (-1 == nGetInboxAcct) {
if (!bWasSentAccount) {
otOut << strLocation << ": this.getInboxAccount failed, without "
"even sending getAccountData. (Returning "
"false.)\n";
return false;
}
}
// If it wasn't sent, and 0 was returned, that means
// no error: we already have the latest inbox. (Nothing done.)
//
else if (!bWasSentInbox && (0 == nGetInboxAcct)) {
// we don't return true;
}
else if (1 != nGetInboxAcct) {
otOut << strLocation
<< ": getInboxAccount failed. (Trying one more time...)\n";
int32_t nGetRequestNumber = getRequestNumber(notaryID, nymID);
if (1 != nGetRequestNumber) {
otOut << strLocation << ": Failure: getInboxAccount failed, then I "
"tried to resync with getRequestNumber and "
"then that failed too. (I give up.)\n";
return false;
}
///////////////////////// WARNING: DEAD CODE
///?????????????????????????????????
// We sync'd the request number, so now we try the function again...
//
int32_t nSecondtry =
getInboxAccount(notaryID, nymID, accountID, bWasSentInbox,
bWasSentAccount, bForceDownload);
if ((-1 == nSecondtry) && !bWasSentAccount) {
// if we received an error state, and the "getAccountData" message
// wasn't even sent,
// then no point doing a bunch of retries -- it failed.
//
otOut << strLocation << ": getInboxAccount failed a second time, "
"without even sending getAccountData. "
"(Returning false.)\n";
return false;
}
// If it wasn't sent, and 0 was returned, that means
// no error: we already have the latest inbox. (Nothing done.)
//
if (!bWasSentInbox && (0 == nSecondtry)) {
// we don't return true;
}
else if (1 != nSecondtry) {
otOut << strLocation
<< ": getInboxAccount re-try failed. (That's twice "
"now--Returning false.) Value: " << nSecondtry << "\n";
return false;
}
otOut << strLocation
<< ": getInboxAccount second call succeeded. (Continuing...)\n";
}
return true;
}
// NOTE: This is a new version that uses the new server message, getAccountData
// (Which combines getAccount, getInbox, and getOutbox into a single message.)
OT_UTILITY_OT int32_t
Utility::getInboxAccount(const string& notaryID, const string& nymID,
const string& accountID, bool& bWasSentInbox,
bool& bWasSentAccount, const bool)
{
string strLocation = "Utility::getInboxAccount";
bWasSentAccount = false;
bWasSentInbox = false;
//
// (Success means both were downloaded, if necessary.)
//
// FIRST WE DO THE ACCOUNT...
//
// GET ACCOUNT
//
OTAPI_Wrap::FlushMessageBuffer();
int32_t nRequestNum = OTAPI_Wrap::getAccountData(
notaryID, nymID, accountID); // <===== ATTEMPT TO SEND MESSAGE;
if (-1 == nRequestNum) {
otOut << strLocation
<< ": Failed to send getAccountData message due to error.\n";
return -1;
}
if (0 == nRequestNum) {
otOut << strLocation << ": Didn't send getAccountData message, but NO "
"error occurred, either. (In this case, SHOULD "
"NEVER HAPPEN. Treating as Error.)\n";
return -1;
}
if (nRequestNum < 0) {
otOut << strLocation
<< ": Unexpected failure sending getAccountData. Request number: "
<< nRequestNum << "\n";
return -1;
}
bWasSentAccount = true;
bWasSentInbox = true;
// -1 for error
// 0 for reply: failure
// 1 for reply: success
//
int32_t nReturn = receiveReplySuccessLowLevel(
notaryID, nymID, nRequestNum,
"getInboxAccount"); // <============ RETURN VALUE;
if (nReturn < 0) // error
{
otOut << strLocation << ": Error in getAccountData: " << nReturn
<< ". (I give up.)\n";
return -1;
}
// otOut << "IN getInboxAccount " <<
// getLastReplyReceived());
// BY this point, we definitely have the request number, which means the
// message was actually SENT. (At least.) This also means we can use
// nRequestNum
// later to query for a copy of that sent message.
// Let's go ahead, in this case, and remove that now:
//
// int32_t nRemovedSentMsg =
// OTAPI_Wrap::RemoveSentMessage(Integer.toString(nRequestNum), notaryID,
// nymID);
//
// // NOTE: The above call is unnecessary, since a successful process
// means
// // we already received the successful server reply, and OT's
// "ProcessServerReply"
// // already removed the sent message from the sent buffer (so no need
// to do that here.)
//
// if (nRemovedSentMsg < 1) // (not success.)
// {
// otOut << "getInboxAccount: ERROR:
// OT_API_RemoveSentMessage returned: " << nRemovedSentMsg);
// }
if (1 != nReturn) {
otOut << strLocation
<< ": getAccountData failed, returning: " << nReturn << "\n";
return nReturn;
}
// DOWNLOAD THE BOX RECEIPTS.
if (!insureHaveAllBoxReceipts(notaryID, nymID, accountID,
1)) // <===== nBoxType = 1 aka INBOX;
{
otOut << strLocation << ": getAccountData succeeded, but then "
"insureHaveAllBoxReceipts failed on the inbox. "
"(I give up.)\n";
return -1;
}
if (!insureHaveAllBoxReceipts(notaryID, nymID, accountID,
2)) // <===== nBoxType = 2 aka OUTBOX;
{
otOut << strLocation << ": getAccountData succeeded, but then "
"insureHaveAllBoxReceipts failed on the "
"outbox. (I give up.)\n";
return -1;
}
return 1;
}
// Same as the above function, except you only have to pass the accountID.
// (instead of 3 IDs...)
//
OT_UTILITY_OT bool Utility::getInboxOutboxAccount(const string& accountID)
{
bool bForceDownload = false;
return getInboxOutboxAccount(accountID, bForceDownload);
}
OT_UTILITY_OT bool Utility::getInboxOutboxAccount(
const string& accountID,
bool bForceDownload) // booleanbForceDownload = false;
{
string strLocation = "Utility::getInboxOutboxAccount";
if (!VerifyStringVal(accountID) || accountID.size() < 10) {
otOut << strLocation << ": invalid accountID: " << accountID << "\n";
return false;
}
string notaryID = OTAPI_Wrap::GetAccountWallet_NotaryID(accountID);
string nymID = OTAPI_Wrap::GetAccountWallet_NymID(accountID);
if (!getIntermediaryFiles(notaryID, nymID, accountID, bForceDownload)) {
otOut << strLocation << ": getIntermediaryFiles failed. (Returning.)\n";
return false;
}
return true;
}
// getInboxAccount()
// Grabs the "Account", which is the intermediary file containing the current
// balance, verified against
// last signed receipt. Server must have your signature on the last balance
// agreement plus, if applicable,
// any inbox receipts (box receipts), also with your signature, in order to
// justify the current balance.
// Any inbox receipts, further, are only valid if they each contain a
// transaction number that was previously
// already signed out to you.
// (As you can see, the "account" is not a list of transactions, as per the
// classical understanding in
// double-entry accounting, but instead it's just a signed balance agreement,
// plus any as-yet-unclosed
// transactions that have cleared since that balance was last signed, and are
// still waiting in the inbox
// for the next balance agreement to be signed when they can be removed.)
// In addition to the "Account" there is also the Inbox itself, as well as all
// of its box receipts.
// The box receipts are stored in abbreviated form in the Inbox itself, with the
// actual full
// versions in separate files. These are retrieved individually from the server
// after the inbox itself
// is, and then each is verified against a hash kept inside its abbreviated
// version.)
// DONE
OT_UTILITY_OT int32_t
Utility::getInboxAccount(const string& notaryID, const string& nymID,
const string& accountID, bool& bWasSentInbox,
bool& bWasSentAccount)
{
bool bForceDownload = false;
return getInboxAccount(notaryID, nymID, accountID, bWasSentInbox,
bWasSentAccount, bForceDownload);
}
} // namespace opentxs
|
#include "pch.h"
#include "PrimitiveUtils.h"
#include "Renderer/Gizmo.h"
namespace sixengine {
std::vector<GizmoVertex> PrimitiveUtils::generateBoxVertices(float x, float y, float z)
{
x = x / 2.0f;
y = y / 2.0f;
z = z / 2.0f;
std::vector<GizmoVertex> vertices{
// top face
GizmoVertex{ glm::vec3{-x, y, -z}/*, glm::vec3{ 0.0f, 1.0f, 0.0f}, glm::vec2{ 0.0f, 0.0f}*/ }, // bottom left
GizmoVertex{ glm::vec3{ x, y, -z}/*, glm::vec3{ 0.0f, 1.0f, 0.0f}, glm::vec2{ 1.0f, 0.0f}*/ }, // bottom right
GizmoVertex{ glm::vec3{-x, y, z}/*, glm::vec3{ 0.0f, 1.0f, 0.0f}, glm::vec2{ 0.0f, 1.0f}*/ }, // top left
GizmoVertex{ glm::vec3{ x, y, z}/*, glm::vec3{ 0.0f, 1.0f, 0.0f}, glm::vec2{ 1.0f, 1.0f}*/ }, // top right
// bottom face
GizmoVertex{ glm::vec3{ x, -y, -z}/*, glm::vec3{ 0.0f, -1.0f, 0.0f}, glm::vec2{ 0.0f, 0.0f}*/ }, // bottom left
GizmoVertex{ glm::vec3{-x, -y, -z}/*, glm::vec3{ 0.0f, -1.0f, 0.0f}, glm::vec2{ 1.0f, 0.0f}*/ }, // bottom right
GizmoVertex{ glm::vec3{ x, -y, z}/*, glm::vec3{ 0.0f, -1.0f, 0.0f}, glm::vec2{ 0.0f, 1.0f}*/ }, // top left
GizmoVertex{ glm::vec3{-x, -y, z}/*, glm::vec3{ 0.0f, -1.0f, 0.0f}, glm::vec2{ 1.0f, 1.0f}*/ }, // top right
// front face
GizmoVertex{ glm::vec3{ x, -y, z}/*, glm::vec3{ 0.0f, 0.0f, 1.0f}, glm::vec2{ 0.0f, 0.0f}*/ }, // bottom left
GizmoVertex{ glm::vec3{-x, -y, z}/*, glm::vec3{ 0.0f, 0.0f, 1.0f}, glm::vec2{ 1.0f, 0.0f}*/ }, // bottom right
GizmoVertex{ glm::vec3{ x, y, z}/*, glm::vec3{ 0.0f, 0.0f, 1.0f}, glm::vec2{ 0.0f, 1.0f}*/ }, // top left
GizmoVertex{ glm::vec3{-x, y, z}/*, glm::vec3{ 0.0f, 0.0f, 1.0f}, glm::vec2{ 1.0f, 1.0f}*/ }, // top right
// back face
GizmoVertex{ glm::vec3{-x, -y, -z}/*, glm::vec3{ 0.0f, 0.0f, -1.0f}, glm::vec2{ 0.0f, 0.0f}*/ }, // bottom left
GizmoVertex{ glm::vec3{ x, -y, -z}/*, glm::vec3{ 0.0f, 0.0f, -1.0f}, glm::vec2{ 1.0f, 0.0f}*/ }, // bottom right
GizmoVertex{ glm::vec3{-x, y, -z}/*, glm::vec3{ 0.0f, 0.0f, -1.0f}, glm::vec2{ 0.0f, 1.0f}*/ }, // top left
GizmoVertex{ glm::vec3{ x, y, -z}/*, glm::vec3{ 0.0f, 0.0f, -1.0f}, glm::vec2{ 1.0f, 1.0f}*/ }, // top right
// right face
GizmoVertex{ glm::vec3{ x, -y, -z}/*, glm::vec3{ 1.0f, 0.0f, 0.0f}, glm::vec2{ 0.0f, 0.0f}*/ }, // bottom left
GizmoVertex{ glm::vec3{ x, -y, z}/*, glm::vec3{ 1.0f, 0.0f, 0.0f}, glm::vec2{ 1.0f, 0.0f}*/ }, // bottom right
GizmoVertex{ glm::vec3{ x, y, -z}/*, glm::vec3{ 1.0f, 0.0f, 0.0f}, glm::vec2{ 0.0f, 1.0f}*/ }, // top left
GizmoVertex{ glm::vec3{ x, y, z}/*, glm::vec3{ 1.0f, 0.0f, 0.0f}, glm::vec2{ 1.0f, 1.0f}*/ }, // top right
// left face
GizmoVertex{ glm::vec3{-x, -y, z}/*, glm::vec3{-1.0f, 0.0f, 0.0f}, glm::vec2{ 0.0f, 0.0f}*/ }, // bottom left
GizmoVertex{ glm::vec3{-x, -y, -z}/*, glm::vec3{-1.0f, 0.0f, 0.0f}, glm::vec2{ 1.0f, 0.0f}*/ }, // bottom right
GizmoVertex{ glm::vec3{-x, y, z}/*, glm::vec3{-1.0f, 0.0f, 0.0f}, glm::vec2{ 0.0f, 1.0f}*/ }, // top left
GizmoVertex{ glm::vec3{-x, y, -z}/*, glm::vec3{-1.0f, 0.0f, 0.0f}, glm::vec2{ 1.0f, 1.0f}*/ }, // top right
};
return vertices;
}
std::vector<unsigned int> PrimitiveUtils::generateBoxIndices()
{
std::vector <unsigned int> indices{
0, 1, 2,
1, 3, 2,
4, 6, 5,
5, 6, 7,
8, 9, 10,
9, 11, 10,
12, 14, 13,
13, 14, 15,
16, 17, 18,
17, 19, 18,
20, 22, 21,
21, 22, 23
};
return indices;
}
std::vector<GizmoVertex> PrimitiveUtils::generateSphereVertices(int sectorCount, int stackCount, float radius)
{
std::vector<GizmoVertex> vertices;
float x, y, z, xz; // GizmoVertex position
//float nx, ny, nz, lengthInv = 1.0f / radius; // GizmoVertex normal
//float s, t; // GizmoVertex texCoord
float sectorStep = 2 * glm::pi<float>() / sectorCount;
float stackStep = glm::pi<float>() / stackCount;
float sectorAngle, stackAngle;
for (int i = 0; i <= stackCount; ++i)
{
stackAngle = glm::pi<float>() / 2 - i * stackStep; // starting from pi/2 to -pi/2
xz = radius * glm::cos(stackAngle); // r * cos(u)
y = radius * glm::sin(stackAngle); // r * sin(u)
// add (sectorCount+1) vertices per stack
// the first and last vertices have same position and normal, but different tex coords
for (int j = 0; j <= sectorCount; ++j)
{
//LOG_CORE_INFO(j);
sectorAngle = j * sectorStep; // starting from 0 to 2pi
// GizmoVertex position (x, y, z)
x = xz * glm::cos(sectorAngle); // r * cos(u) * cos(v)
z = xz * glm::sin(sectorAngle); // r * cos(u) * sin(v)
vertices.push_back(GizmoVertex{ glm::vec3{ x, y, z } });
// normalized GizmoVertex normal (nx, ny, nz)
//nx = x * lengthInv;
//ny = y * lengthInv;
//nz = z * lengthInv;
//normals.push_back(nx);
//normals.push_back(ny);
//normals.push_back(nz);
// GizmoVertex tex coord (s, t) range between [0, 1]
//s = (float)j / sectorCount;
//t = (float)i / stackCount;
//texCoords.push_back(s);
//texCoords.push_back(t);
}
}
return vertices;
}
std::vector<unsigned int> PrimitiveUtils::generateSphereIndices(int sectorCount, int stackCount)
{
std::vector<unsigned int> indices;
int k1, k2;
for (int i = 0; i < stackCount; ++i)
{
k1 = i * (sectorCount + 1); // beginning of current stack
k2 = k1 + sectorCount + 1; // beginning of next stack
for (int j = 0; j < sectorCount; ++j, ++k1, ++k2)
{
// 2 triangles per sector excluding first and last stacks
// k1 => k2 => k1+1
if (i != 0)
{
indices.push_back(k1);
indices.push_back(k2);
indices.push_back(k1 + 1);
}
// k1+1 => k2 => k2+1
if (i != (stackCount - 1))
{
indices.push_back(k1 + 1);
indices.push_back(k2);
indices.push_back(k2 + 1);
}
}
}
return indices;
}
std::vector<GizmoVertex> PrimitiveUtils::generateConeVertices(int sectorCount, float radius, float height)
{
std::vector<GizmoVertex> vertices;
float sectorStep = 2 * glm::pi<float>() / sectorCount;
__debugbreak(); //TODO: implement
return vertices;
}
std::vector<unsigned int> PrimitiveUtils::generateConeIndices(int sectorCount)
{
std::vector<unsigned int> indices;
__debugbreak(); //TODO: implemnet
return indices;
}
std::vector<GizmoVertex> PrimitiveUtils::generateCapsuleVertices(int sectorCount, int stackCount, float radius, float height)
{
std::vector<GizmoVertex> vertices;
float x, y, z, xz; // GizmoVertex position
//float nx, ny, nz, lengthInv = 1.0f / radius; // GizmoVertex normal
//float s, t; // GizmoVertex texCoord
float sectorStep = 2 * glm::pi<float>() / sectorCount;
float stackStep = glm::pi<float>() / stackCount;
float sectorAngle, stackAngle;
for (int i = 0; i <= stackCount; ++i)
{
stackAngle = glm::pi<float>() / 2 - i * stackStep; // starting from pi/2 to -pi/2
xz = radius * glm::cos(stackAngle); // r * cos(u)
y = radius * glm::sin(stackAngle); // r * sin(u)
if (stackAngle > 0)
{
y += height / 2.0f;
}
else if(stackAngle < 0)
{
y -= height / 2.0f;
}
// add (sectorCount+1) vertices per stack
// the first and last vertices have same position and normal, but different tex coords
for (int j = 0; j <= sectorCount; ++j)
{
//LOG_CORE_INFO(j);
sectorAngle = j * sectorStep; // starting from 0 to 2pi
// GizmoVertex position (x, y, z)
x = xz * glm::cos(sectorAngle); // r * cos(u) * cos(v)
z = xz * glm::sin(sectorAngle); // r * cos(u) * sin(v)
vertices.push_back(GizmoVertex{ glm::vec3{ x, y , z } });
// normalized GizmoVertex normal (nx, ny, nz)
//nx = x * lengthInv;
//ny = y * lengthInv;
//nz = z * lengthInv;
//normals.push_back(nx);
//normals.push_back(ny);
//normals.push_back(nz);
// GizmoVertex tex coord (s, t) range between [0, 1]
//s = (float)j / sectorCount;
//t = (float)i / stackCount;
//texCoords.push_back(s);
//texCoords.push_back(t);
}
}
return vertices;
}
std::vector<unsigned int> PrimitiveUtils::generateCapsuleIndices(int sectorCount, int stackCount)
{
std::vector<unsigned int> indices;
int k1, k2;
for (int i = 0; i < stackCount; ++i)
{
k1 = i * (sectorCount + 1); // beginning of current stack
k2 = k1 + sectorCount + 1; // beginning of next stack
for (int j = 0; j < sectorCount; ++j, ++k1, ++k2)
{
// 2 triangles per sector excluding first and last stacks
// k1 => k2 => k1+1
if (i != 0)
{
indices.push_back(k1);
indices.push_back(k2);
indices.push_back(k1 + 1);
}
// k1+1 => k2 => k2+1
if (i != (stackCount - 1))
{
indices.push_back(k1 + 1);
indices.push_back(k2);
indices.push_back(k2 + 1);
}
}
}
return indices;
}
std::vector<GizmoVertex> PrimitiveUtils::generateQuadVertices()
{
std::vector<GizmoVertex> vertices{
GizmoVertex{ glm::vec3{ 0.5f, -0.5f, 0.0f}/*, glm::vec3{ 0.0f, 0.0f, 1.0f}, glm::vec2{ 0.0f, 0.0f} */}, // bottom left
GizmoVertex{ glm::vec3{-0.5f, -0.5f, 0.0f}/*, glm::vec3{ 0.0f, 0.0f, 1.0f}, glm::vec2{ 1.0f, 0.0f} */}, // bottom right
GizmoVertex{ glm::vec3{ 0.5f, 0.5f, 0.0f}/*, glm::vec3{ 0.0f, 0.0f, 1.0f}, glm::vec2{ 0.0f, 1.0f} */}, // top left
GizmoVertex{ glm::vec3{-0.5f, 0.5f, 0.0f}/*, glm::vec3{ 0.0f, 0.0f, 1.0f}, glm::vec2{ 1.0f, 1.0f} */}, // top right
};
return vertices;
}
std::vector<unsigned int> PrimitiveUtils::generateQuadIndices()
{
std::vector <unsigned int> indices{
0, 1, 2,
1, 3, 2
};
return indices;
}
void PrimitiveUtils::GenerateQuad(std::vector<GizmoVertex>& vertices, std::vector<unsigned int>& indices)
{
vertices = PrimitiveUtils::generateQuadVertices();
indices = PrimitiveUtils::generateQuadIndices();
}
void PrimitiveUtils::GenerateBox(std::vector<GizmoVertex>& vertices, std::vector<unsigned int>& indices, float x, float y, float z)
{
vertices = PrimitiveUtils::generateBoxVertices(x, y, z);
indices = PrimitiveUtils::generateBoxIndices();
}
void PrimitiveUtils::GenerateSphere(std::vector<GizmoVertex>& vertices, std::vector<unsigned int>& indices, float radius, int sectorCount, int stackCount)
{
vertices = PrimitiveUtils::generateSphereVertices(sectorCount, stackCount, radius);
indices = PrimitiveUtils::generateSphereIndices(sectorCount, stackCount);
}
void PrimitiveUtils::GenerateCone(std::vector<GizmoVertex>& vertices, std::vector<unsigned int>& indices, float radius, float height, int sectorCount)
{
vertices = PrimitiveUtils::generateConeVertices(sectorCount, radius, height);
indices = PrimitiveUtils::generateConeIndices(sectorCount);
}
void PrimitiveUtils::GenerateCapsule(std::vector<GizmoVertex>& vertices, std::vector<unsigned int>& indices, float radius, float height, int sectorCount, int stackCount)
{
vertices = PrimitiveUtils::generateCapsuleVertices(sectorCount, stackCount, radius, height);
indices = PrimitiveUtils::generateCapsuleIndices(sectorCount, stackCount);
}
}
|
#include <functional>
#include "common/event/dispatcher_impl.h"
#include "test/mocks/common.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace Envoy {
using testing::InSequence;
namespace Event {
class TestDeferredDeletable : public DeferredDeletable {
public:
TestDeferredDeletable(std::function<void()> on_destroy) : on_destroy_(on_destroy) {}
~TestDeferredDeletable() { on_destroy_(); }
private:
std::function<void()> on_destroy_;
};
TEST(DispatcherImplTest, DeferredDelete) {
InSequence s;
DispatcherImpl dispatcher;
ReadyWatcher watcher1;
dispatcher.deferredDelete(
DeferredDeletablePtr{new TestDeferredDeletable([&]() -> void { watcher1.ready(); })});
// The first one will get deleted inline.
EXPECT_CALL(watcher1, ready());
dispatcher.clearDeferredDeleteList();
// This one does a nested deferred delete. We should need two clear calls to actually get
// rid of it with the vector swapping. We also test that inline clear() call does nothing.
ReadyWatcher watcher2;
ReadyWatcher watcher3;
dispatcher.deferredDelete(DeferredDeletablePtr{new TestDeferredDeletable([&]() -> void {
watcher2.ready();
dispatcher.deferredDelete(
DeferredDeletablePtr{new TestDeferredDeletable([&]() -> void { watcher3.ready(); })});
dispatcher.clearDeferredDeleteList();
})});
EXPECT_CALL(watcher2, ready());
dispatcher.clearDeferredDeleteList();
EXPECT_CALL(watcher3, ready());
dispatcher.clearDeferredDeleteList();
}
} // Event
} // Envoy
|
#include "N64.hpp"
#include "PIFrom.hpp"
using namespace ultra64;
void N64::load_pif_rom(std::string filepath)
{
ultra64::PIFrom pifrom(filepath);
uint32_t count = 0;
uint32_t *p = (uint32_t *)pifrom.get_pointer();
ultra64::map_memory(this->mmu, "pif_rom", 0x1FC00000, 0x7C0, 0x7C0, new std::byte[0x7C0], nullptr, nullptr);
while(count < 0x7C0)
{
this->mmu->write_word_raw(0x1FC00000 + count, *p++);
count += 4;
}
std::cout << "Loaded " << filepath << std::endl;
}
|
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote
* products derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative
* works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without
* specific prior written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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, THE UNITED STATES GOVERNMENT, OR ANY 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.
**********************************************************************************************************************/
#ifndef UTILITIES_IDD_IDDOBJECTPROPERTIES_HPP
#define UTILITIES_IDD_IDDOBJECTPROPERTIES_HPP
#include "../UtilitiesAPI.hpp"
#include "../core/Optional.hpp"
#include <string>
namespace openstudio{
/** IddObjectProperties describes the properties of an IddObject, as specified by
* object-level IDD markup. */
struct UTILITIES_API IddObjectProperties{
public:
/** Default constructor. */
IddObjectProperties();
/** Returns true if all of the underlying data is exactly equal. */
bool operator==(const IddObjectProperties& other) const;
/** Negation of operator==. */
bool operator!=(const IddObjectProperties& other) const;
/** Returns the memo associated with this object. */
std::string memo;
/** Returns true if this object must be unique within an individual IdfFile. */
bool unique;
/** Returns true if this object is required for an IdfFile to be valid. */
bool required;
/** Returns true if this object is obsolete. */
bool obsolete;
/** Returns true if this object contains an IddField of type url. */
bool hasURL;
/** Returns true if this object is extensible. */
bool extensible;
/** Returns the number of fields in this object's extensible group (zero if !extensible). */
unsigned numExtensible;
/** Returns the minimum number of extensible groups an IdfObject following this schema must
* have to be valid. */
unsigned numExtensibleGroupsRequired;
/** Formatting markup for this object. Often empty. Contains suggestions for printing certain
* types of IdfObjects. For instance, many geometric objects have \\format vertices. */
std::string format;
/** Minimum number of fields required for an IdfObject to be valid according to this schema. */
unsigned minFields;
/** Maximum number of fields allowed in IdfObjects following this schema. Limits the number of
* allowable extensible groups. */
boost::optional<unsigned> maxFields;
/** Print object-level IDD flags to os. Includes indentation for IDD file readability. */
std::ostream& print(std::ostream& os) const;
};
} // openstudio
#endif // UTILITIES_IDD_IDDOBJECTPROPERTIES_HPP
|
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This file is auto-generated by rute_gen. DO NOT EDIT
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "../rute_base.h"
#include "../rute_manual.h"
#include <QObject>
#include "object_ffi.h"
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static const char* object_object_name(struct RUBase* self_c) {
WRObject* qt_value = (WRObject*)self_c;
auto ret_value = qt_value->objectName();
return q_string_to_const_char(ret_value);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void object_set_object_name(struct RUBase* self_c, const char* name) {
WRObject* qt_value = (WRObject*)self_c;
qt_value->setObjectName(QString::fromUtf8(name));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static bool object_is_widget_type(struct RUBase* self_c) {
WRObject* qt_value = (WRObject*)self_c;
auto ret_value = qt_value->isWidgetType();
return ret_value;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static bool object_is_window_type(struct RUBase* self_c) {
WRObject* qt_value = (WRObject*)self_c;
auto ret_value = qt_value->isWindowType();
return ret_value;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static bool object_signals_blocked(struct RUBase* self_c) {
WRObject* qt_value = (WRObject*)self_c;
auto ret_value = qt_value->signalsBlocked();
return ret_value;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static bool object_block_signals(struct RUBase* self_c, bool b) {
WRObject* qt_value = (WRObject*)self_c;
auto ret_value = qt_value->blockSignals(b);
return ret_value;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int object_start_timer(struct RUBase* self_c, int interval, uint32_t timer_type) {
WRObject* qt_value = (WRObject*)self_c;
auto ret_value = qt_value->startTimer(interval, (Qt::TimerType)timer_type);
return ret_value;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int object_start_timer_2(struct RUBase* self_c, uint32_t time, uint32_t timer_type) {
WRObject* qt_value = (WRObject*)self_c;
auto ret_value = qt_value->startTimer(time, (Qt::TimerType)timer_type);
return ret_value;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void object_kill_timer(struct RUBase* self_c, int id) {
WRObject* qt_value = (WRObject*)self_c;
qt_value->killTimer(id);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void object_set_parent(struct RUBase* self_c, struct RUBase* parent) {
WRObject* qt_value = (WRObject*)self_c;
qt_value->setParent((WRObject*)parent);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void object_install_event_filter(struct RUBase* self_c, struct RUBase* filter_obj) {
WRObject* qt_value = (WRObject*)self_c;
qt_value->installEventFilter((WRObject*)filter_obj);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void object_dump_object_tree(struct RUBase* self_c) {
WRObject* qt_value = (WRObject*)self_c;
qt_value->dumpObjectTree();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void object_dump_object_info(struct RUBase* self_c) {
WRObject* qt_value = (WRObject*)self_c;
qt_value->dumpObjectInfo();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void object_dump_object_tree_2(struct RUBase* self_c) {
WRObject* qt_value = (WRObject*)self_c;
qt_value->dumpObjectTree();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void object_dump_object_info_2(struct RUBase* self_c) {
WRObject* qt_value = (WRObject*)self_c;
qt_value->dumpObjectInfo();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static struct RUObject object_parent(struct RUBase* self_c) {
WRObject* qt_value = (WRObject*)self_c;
auto ret_value = qt_value->parent();
struct RUObject ctl;
ctl.qt_data = (struct RUBase*)ret_value;
ctl.host_data = (struct RUBase*)s_host_data_lookup[(void*)ret_value];
ctl.all_funcs = &s_object_all_funcs;
return ctl;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void object_delete_later(struct RUBase* self_c) {
WRObject* qt_value = (WRObject*)self_c;
qt_value->deleteLater();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void set_object_custom_event(void* object, void* user_data, void* wrapped_func, void (*trampoline_func)(void*, void* self_c, struct RUBase* event)) {
WRObject* qt_object = (WRObject*)object;
qt_object->m_custom_event = trampoline_func;
qt_object->m_custom_event_user_data = user_data;
qt_object->m_custom_event_wrapped_func = wrapped_func;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void remove_object_custom_event(void* object) {
WRObject* qt_object = (WRObject*)object;
qt_object->m_custom_event = nullptr;
qt_object->m_custom_event_user_data = nullptr;
qt_object->m_custom_event_wrapped_func = nullptr;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static struct RUObject create_object(
struct RUBase* priv_data,
RUDeleteCallback delete_callback,
void* private_user_data)
{
auto ctl = generic_create_func_with_delete<struct RUObject, WRObject>(priv_data, delete_callback, private_user_data);
ctl.all_funcs = &s_object_all_funcs;
return ctl;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void destroy_object(struct RUBase* priv_data) {
destroy_generic<WRObject>(priv_data);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct RUObjectFuncs s_object_funcs = {
destroy_object,
object_object_name,
object_set_object_name,
object_is_widget_type,
object_is_window_type,
object_signals_blocked,
object_block_signals,
object_start_timer,
object_start_timer_2,
object_kill_timer,
object_set_parent,
object_install_event_filter,
object_dump_object_tree,
object_dump_object_info,
object_dump_object_tree_2,
object_dump_object_info_2,
object_parent,
object_delete_later,
set_object_custom_event,
remove_object_custom_event,
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct RUObjectAllFuncs s_object_all_funcs = {
&s_object_funcs,
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.